diff options
author | The Android Open Source Project <initial-contribution@android.com> | 2008-12-17 18:05:15 -0800 |
---|---|---|
committer | The Android Open Source Project <initial-contribution@android.com> | 2008-12-17 18:05:15 -0800 |
commit | 1cbdecfa9fc428ac2d8aca0fa91c9580b3d57353 (patch) | |
tree | 4457a7306ea5acb43fe05bfe0973b1f7faf97ba2 /WebCore/bindings | |
parent | 9364f22aed35e1a1e9d07c121510f80be3ab0502 (diff) | |
download | external_webkit-1cbdecfa9fc428ac2d8aca0fa91c9580b3d57353.zip external_webkit-1cbdecfa9fc428ac2d8aca0fa91c9580b3d57353.tar.gz external_webkit-1cbdecfa9fc428ac2d8aca0fa91c9580b3d57353.tar.bz2 |
Code drop from //branches/cupcake/...@124589
Diffstat (limited to 'WebCore/bindings')
215 files changed, 13047 insertions, 9818 deletions
diff --git a/WebCore/bindings/js/GCController.cpp b/WebCore/bindings/js/GCController.cpp index 94c48a1..fc8a778 100644 --- a/WebCore/bindings/js/GCController.cpp +++ b/WebCore/bindings/js/GCController.cpp @@ -26,14 +26,16 @@ #include "config.h" #include "GCController.h" -#include <kjs/JSLock.h> +#include "JSDOMWindow.h" +#include <runtime/JSGlobalData.h> +#include <runtime/JSLock.h> #include <kjs/collector.h> #if USE(PTHREADS) #include <pthread.h> #endif -using namespace KJS; +using namespace JSC; namespace WebCore { @@ -41,8 +43,8 @@ namespace WebCore { static void* collect(void*) { - JSLock lock; - Collector::collect(); + JSLock lock(false); + JSDOMWindow::commonJSGlobalData()->heap.collect(); return 0; } @@ -67,14 +69,14 @@ void GCController::garbageCollectSoon() void GCController::gcTimerFired(Timer<GCController>*) { - JSLock lock; - Collector::collect(); + JSLock lock(false); + JSDOMWindow::commonJSGlobalData()->heap.collect(); } void GCController::garbageCollectNow() { - JSLock lock; - Collector::collect(); + JSLock lock(false); + JSDOMWindow::commonJSGlobalData()->heap.collect(); } void GCController::garbageCollectOnAlternateThreadForDebugging(bool waitUntilDone) @@ -83,10 +85,8 @@ void GCController::garbageCollectOnAlternateThreadForDebugging(bool waitUntilDon pthread_t thread; pthread_create(&thread, NULL, collect, NULL); - if (waitUntilDone) { - JSLock::DropAllLocks dropLocks; // Otherwise our lock would deadlock the collect thread we're joining + if (waitUntilDone) pthread_join(thread, NULL); - } #endif } diff --git a/WebCore/bindings/js/JSAttrCustom.cpp b/WebCore/bindings/js/JSAttrCustom.cpp index b2c9044..0cf5705 100644 --- a/WebCore/bindings/js/JSAttrCustom.cpp +++ b/WebCore/bindings/js/JSAttrCustom.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2007 Apple Inc. All rights reserved. + * Copyright (C) 2007, 2008 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -29,35 +29,25 @@ #include "config.h" #include "JSAttr.h" -#include "Attr.h" -#include "Document.h" -#include "ExceptionCode.h" #include "CSSHelper.h" +#include "Document.h" #include "HTMLFrameElementBase.h" #include "HTMLNames.h" -#include "PlatformString.h" -#include "kjs_binding.h" -#include "kjs_dom.h" -#ifdef ANDROID_JAVASCRIPT_SECURITY -#include "KURL.h" -#endif + +using namespace JSC; namespace WebCore { using namespace HTMLNames; -void JSAttr::setValue(KJS::ExecState* exec, KJS::JSValue* value) +void JSAttr::setValue(ExecState* exec, JSValue* value) { Attr* imp = static_cast<Attr*>(impl()); String attrValue = valueToStringWithNullCheck(exec, value); Element* ownerElement = imp->ownerElement(); if (ownerElement && (ownerElement->hasTagName(iframeTag) || ownerElement->hasTagName(frameTag))) { -#ifdef ANDROID_JAVASCRIPT_SECURITY if (equalIgnoringCase(imp->name(), "src") && protocolIs(parseURL(attrValue), "javascript")) { -#else - if (equalIgnoringCase(imp->name(), "src") && parseURL(attrValue).startsWith("javascript:", false)) { -#endif if (!checkNodeSecurity(exec, static_cast<HTMLFrameElementBase*>(ownerElement)->contentDocument())) return; } @@ -65,7 +55,7 @@ void JSAttr::setValue(KJS::ExecState* exec, KJS::JSValue* value) ExceptionCode ec = 0; imp->setValue(attrValue, ec); - KJS::setDOMException(exec, ec); + setDOMException(exec, ec); } } // namespace WebCore diff --git a/WebCore/bindings/js/JSAudioConstructor.cpp b/WebCore/bindings/js/JSAudioConstructor.cpp index 1efb0d8..f342cea 100644 --- a/WebCore/bindings/js/JSAudioConstructor.cpp +++ b/WebCore/bindings/js/JSAudioConstructor.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2007 Apple Inc. All rights reserved. + * Copyright (C) 2007, 2008 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -26,46 +26,54 @@ #include "config.h" #if ENABLE(VIDEO) + #include "JSAudioConstructor.h" -#include "Document.h" #include "HTMLAudioElement.h" #include "JSHTMLAudioElement.h" +#include "ScriptExecutionContext.h" #include "Text.h" -using namespace KJS; +using namespace JSC; namespace WebCore { -JSAudioConstructor::JSAudioConstructor(ExecState* exec, Document* d) - : DOMObject(exec->lexicalGlobalObject()->objectPrototype()) - , m_doc(d) -{ - putDirect(exec->propertyNames().length, jsNumber(1), ReadOnly|DontDelete|DontEnum); -} +const ClassInfo JSAudioConstructor::s_info = { "AudioConstructor", 0, 0, 0 }; -bool JSAudioConstructor::implementsConstruct() const +JSAudioConstructor::JSAudioConstructor(ExecState* exec, ScriptExecutionContext* context) + : DOMObject(JSAudioConstructor::createStructureID(exec->lexicalGlobalObject()->objectPrototype())) { - return true; + ASSERT(context->isDocument()); + m_document = static_cast<JSDocument*>(asObject(toJS(exec, static_cast<Document*>(context)))); + + putDirect(exec->propertyNames().length, jsNumber(exec, 1), ReadOnly|DontDelete|DontEnum); } -JSObject* JSAudioConstructor::construct(ExecState* exec, const List& args) +static JSObject* constructAudio(ExecState* exec, JSObject* constructor, const ArgList& args) { - int exception = 0; - RefPtr<Element> el(m_doc->createElement("audio", exception)); - HTMLAudioElement* audio = 0; - if (el && !exception) { - audio = static_cast<HTMLAudioElement*>(el.get()); - int sz = args.size(); - if (sz > 0) { - audio->setSrc(args[0]->toString(exec)); - audio->scheduleLoad(); - } + // FIXME: Why doesn't this need the call toJS on the document like JSImageConstructor? + + RefPtr<HTMLAudioElement> audio = new HTMLAudioElement(static_cast<JSAudioConstructor*>(constructor)->document()); + if (args.size() > 0) { + audio->setSrc(args.at(exec, 0)->toString(exec)); + audio->scheduleLoad(); } + return asObject(toJS(exec, audio.release())); +} - setDOMException(exec, exception); - return static_cast<JSObject*>(toJS(exec, audio)); +ConstructType JSAudioConstructor::getConstructData(ConstructData& constructData) +{ + constructData.native.function = constructAudio; + return ConstructTypeHost; } +void JSAudioConstructor::mark() +{ + DOMObject::mark(); + if (!m_document->marked()) + m_document->mark(); } -#endif + +} // namespace WebCore + +#endif // ENABLE(VIDEO) diff --git a/WebCore/bindings/js/JSAudioConstructor.h b/WebCore/bindings/js/JSAudioConstructor.h index 558b7fe..cdff10f 100644 --- a/WebCore/bindings/js/JSAudioConstructor.h +++ b/WebCore/bindings/js/JSAudioConstructor.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2007 Apple Inc. All rights reserved. + * Copyright (C) 2007, 2008 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -28,21 +28,31 @@ #if ENABLE(VIDEO) -#include "kjs_binding.h" +#include "JSDOMBinding.h" +#include "JSDocument.h" #include <wtf/RefPtr.h> namespace WebCore { - class JSAudioConstructor : public KJS::DOMObject { + class JSAudioConstructor : public DOMObject { public: - JSAudioConstructor(KJS::ExecState*, Document*); - virtual bool implementsConstruct() const; - virtual KJS::JSObject *construct(KJS::ExecState*, const KJS::List& args); + JSAudioConstructor(JSC::ExecState*, ScriptExecutionContext*); + + Document* document() const { return m_document->impl(); } + + static const JSC::ClassInfo s_info; + + virtual void mark(); private: - RefPtr<Document> m_doc; + virtual JSC::ConstructType getConstructData(JSC::ConstructData&); + + virtual const JSC::ClassInfo* classInfo() const { return &s_info; } + + JSDocument* m_document; }; -} +} // namespace WebCore + +#endif // ENABLE(VIDEO) -#endif -#endif +#endif // JSAudioConstructor_h diff --git a/WebCore/bindings/js/JSCSSRuleCustom.cpp b/WebCore/bindings/js/JSCSSRuleCustom.cpp index 00f7063..1e0fac3 100644 --- a/WebCore/bindings/js/JSCSSRuleCustom.cpp +++ b/WebCore/bindings/js/JSCSSRuleCustom.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2007 Apple Inc. All rights reserved. + * Copyright (C) 2007, 2008 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -31,54 +31,67 @@ #include "CSSImportRule.h" #include "CSSMediaRule.h" #include "CSSPageRule.h" -#include "CSSRule.h" #include "CSSStyleRule.h" +#include "CSSVariablesRule.h" #include "JSCSSCharsetRule.h" #include "JSCSSFontFaceRule.h" #include "JSCSSImportRule.h" #include "JSCSSMediaRule.h" #include "JSCSSPageRule.h" #include "JSCSSStyleRule.h" -#include "kjs_binding.h" +#include "JSCSSVariablesRule.h" +#include "JSWebKitCSSKeyframeRule.h" +#include "JSWebKitCSSKeyframesRule.h" +#include "WebKitCSSKeyframeRule.h" +#include "WebKitCSSKeyframesRule.h" + +using namespace JSC; namespace WebCore { -KJS::JSValue* toJS(KJS::ExecState* exec, CSSRule* rule) +JSValue* toJS(ExecState* exec, CSSRule* rule) { if (!rule) - return KJS::jsNull(); + return jsNull(); - KJS::DOMObject* ret = KJS::ScriptInterpreter::getDOMObject(rule); + DOMObject* wrapper = getCachedDOMObjectWrapper(exec->globalData(), rule); - if (ret) - return ret; + if (wrapper) + return wrapper; switch (rule->type()) { case CSSRule::STYLE_RULE: - ret = new JSCSSStyleRule(JSCSSRulePrototype::self(exec), static_cast<CSSStyleRule*>(rule)); + wrapper = CREATE_DOM_OBJECT_WRAPPER(exec, CSSStyleRule, rule); break; case CSSRule::MEDIA_RULE: - ret = new JSCSSMediaRule(JSCSSMediaRulePrototype::self(exec), static_cast<CSSMediaRule*>(rule)); + wrapper = CREATE_DOM_OBJECT_WRAPPER(exec, CSSMediaRule, rule); break; case CSSRule::FONT_FACE_RULE: - ret = new JSCSSFontFaceRule(JSCSSFontFaceRulePrototype::self(exec), static_cast<CSSFontFaceRule*>(rule)); + wrapper = CREATE_DOM_OBJECT_WRAPPER(exec, CSSFontFaceRule, rule); break; case CSSRule::PAGE_RULE: - ret = new JSCSSPageRule(JSCSSPageRulePrototype::self(exec), static_cast<CSSPageRule*>(rule)); + wrapper = CREATE_DOM_OBJECT_WRAPPER(exec, CSSPageRule, rule); break; case CSSRule::IMPORT_RULE: - ret = new JSCSSImportRule(JSCSSImportRulePrototype::self(exec), static_cast<CSSImportRule*>(rule)); + wrapper = CREATE_DOM_OBJECT_WRAPPER(exec, CSSImportRule, rule); break; case CSSRule::CHARSET_RULE: - ret = new JSCSSCharsetRule(JSCSSCharsetRulePrototype::self(exec), static_cast<CSSCharsetRule*>(rule)); + wrapper = CREATE_DOM_OBJECT_WRAPPER(exec, CSSCharsetRule, rule); break; - default: - ret = new JSCSSRule(JSCSSRulePrototype::self(exec), rule); + case CSSRule::VARIABLES_RULE: + wrapper = CREATE_DOM_OBJECT_WRAPPER(exec, CSSVariablesRule, rule); + break; + case CSSRule::WEBKIT_KEYFRAME_RULE: + wrapper = CREATE_DOM_OBJECT_WRAPPER(exec, WebKitCSSKeyframeRule, rule); break; + case CSSRule::WEBKIT_KEYFRAMES_RULE: + wrapper = CREATE_DOM_OBJECT_WRAPPER(exec, WebKitCSSKeyframesRule, rule); + break; + default: + wrapper = CREATE_DOM_OBJECT_WRAPPER(exec, CSSRule, rule); } - KJS::ScriptInterpreter::putDOMObject(rule, ret); - return ret; + return wrapper; } } // namespace WebCore diff --git a/WebCore/bindings/js/JSCSSStyleDeclarationCustom.cpp b/WebCore/bindings/js/JSCSSStyleDeclarationCustom.cpp index 3e68ce0..13b6379 100644 --- a/WebCore/bindings/js/JSCSSStyleDeclarationCustom.cpp +++ b/WebCore/bindings/js/JSCSSStyleDeclarationCustom.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2007 Apple Inc. All rights reserved. + * Copyright (C) 2007, 2008 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -24,54 +24,95 @@ */ #include "config.h" -#include "JSCSSStyleDeclaration.h" +#include "JSCSSStyleDeclarationCustom.h" #include "AtomicString.h" #include "CSSPrimitiveValue.h" #include "CSSStyleDeclaration.h" #include "CSSValue.h" -#include "DeprecatedString.h" #include "PlatformString.h" -#include <kjs/string_object.h> +#include <runtime/StringObjectThatMasqueradesAsUndefined.h> +#include <runtime/StringPrototype.h> +#include <wtf/ASCIICType.h> -namespace WebCore { +using namespace JSC; +using namespace WTF; -using namespace KJS; +namespace WebCore { -static String cssPropertyName(const Identifier& propertyName, bool* hadPixelOrPosPrefix = 0) +// Check for a CSS prefix. +// Passed prefix is all lowercase. +// First character of the prefix within the property name may be upper or lowercase. +// Other characters in the prefix within the property name must be lowercase. +// The prefix within the property name must be followed by a capital letter. +static bool hasCSSPropertyNamePrefix(const Identifier& propertyName, const char* prefix) { - DeprecatedString prop = propertyName; - - int i = prop.length(); - - if (!i) - return prop; +#ifndef NDEBUG + ASSERT(*prefix); + for (const char* p = prefix; *p; ++p) + ASSERT(isASCIILower(*p)); + ASSERT(propertyName.size()); +#endif + + if (toASCIILower(propertyName.data()[0]) != prefix[0]) + return false; - while (--i) { - ::UChar c = prop[i].unicode(); - if (c >= 'A' && c <= 'Z') - prop.insert(i, '-'); + unsigned length = propertyName.size(); + for (unsigned i = 1; i < length; ++i) { + if (!prefix[i]) + return isASCIIUpper(propertyName.data()[i]); + if (propertyName.data()[i] != prefix[i]) + return false; } + return false; +} - prop = prop.lower(); - +static String cssPropertyName(const Identifier& propertyName, bool* hadPixelOrPosPrefix = 0) +{ if (hadPixelOrPosPrefix) *hadPixelOrPosPrefix = false; - if (prop.startsWith("css-")) - prop = prop.mid(4); - else if (prop.startsWith("pixel-")) { - prop = prop.mid(6); + unsigned length = propertyName.size(); + if (!length) + return String(); + + Vector<UChar> name; + name.reserveCapacity(length); + + unsigned i = 0; + + if (hasCSSPropertyNamePrefix(propertyName, "css")) + i += 3; + else if (hasCSSPropertyNamePrefix(propertyName, "pixel")) { + i += 5; if (hadPixelOrPosPrefix) *hadPixelOrPosPrefix = true; - } else if (prop.startsWith("pos-")) { - prop = prop.mid(4); + } else if (hasCSSPropertyNamePrefix(propertyName, "pos")) { + i += 3; if (hadPixelOrPosPrefix) *hadPixelOrPosPrefix = true; - } else if (prop.startsWith("khtml-") || prop.startsWith("apple-") || prop.startsWith("webkit-")) - prop.insert(0, '-'); + } else if (hasCSSPropertyNamePrefix(propertyName, "webkit") + || hasCSSPropertyNamePrefix(propertyName, "khtml") + || hasCSSPropertyNamePrefix(propertyName, "apple")) + name.append('-'); + else { + if (isASCIIUpper(propertyName.data()[0])) + return String(); + } + + name.append(toASCIILower(propertyName.data()[i++])); + + for (; i < length; ++i) { + UChar c = propertyName.data()[i]; + if (!isASCIIUpper(c)) + name.append(c); + else { + name.append('-'); + name.append(toASCIILower(c)); + } + } - return prop; + return String::adopt(name); } static bool isCSSPropertyName(const Identifier& propertyName) @@ -84,9 +125,11 @@ bool JSCSSStyleDeclaration::canGetItemsForName(ExecState*, CSSStyleDeclaration*, return isCSSPropertyName(propertyName); } -JSValue* JSCSSStyleDeclaration::nameGetter(ExecState* exec, JSObject* originalObject, const Identifier& propertyName, const PropertySlot& slot) +// FIXME: You can get these properties, and set them (see customPut below), +// but you should also be able to enumerate them. +JSValue* JSCSSStyleDeclaration::nameGetter(ExecState* exec, const Identifier& propertyName, const PropertySlot& slot) { - JSCSSStyleDeclaration* thisObj = static_cast<JSCSSStyleDeclaration*>(slot.slotBase()); + JSCSSStyleDeclaration* thisObj = static_cast<JSCSSStyleDeclaration*>(asObject(slot.slotBase())); // Set up pixelOrPos boolean to handle the fact that // pixelTop returns "CSS Top" as number value in unit pixels @@ -98,8 +141,8 @@ JSValue* JSCSSStyleDeclaration::nameGetter(ExecState* exec, JSObject* originalOb RefPtr<CSSValue> v = thisObj->impl()->getPropertyCSSValue(prop); if (v) { if (pixelOrPos && v->cssValueType() == CSSValue::CSS_PRIMITIVE_VALUE) - return jsNumber(static_pointer_cast<CSSPrimitiveValue>(v)->getFloatValue(CSSPrimitiveValue::CSS_PX)); - return jsStringOrNull(v->cssText()); + return jsNumber(exec, static_pointer_cast<CSSPrimitiveValue>(v)->getFloatValue(CSSPrimitiveValue::CSS_PX)); + return jsStringOrNull(exec, v->cssText()); } // If the property is a shorthand property (such as "padding"), @@ -107,24 +150,25 @@ JSValue* JSCSSStyleDeclaration::nameGetter(ExecState* exec, JSObject* originalOb // Make the SVG 'filter' attribute undetectable, to avoid confusion with the IE 'filter' attribute. if (propertyName == "filter") - return new StringInstanceThatMasqueradesAsUndefined(exec->lexicalGlobalObject()->stringPrototype(), thisObj->impl()->getPropertyValue(prop)); + return StringObjectThatMasqueradesAsUndefined::create(exec, thisObj->impl()->getPropertyValue(prop)); - return jsString(thisObj->impl()->getPropertyValue(prop)); + return jsString(exec, thisObj->impl()->getPropertyValue(prop)); } -bool JSCSSStyleDeclaration::customPut(ExecState* exec, const Identifier& propertyName, JSValue* value, int /*attr*/) +bool JSCSSStyleDeclaration::customPut(ExecState* exec, const Identifier& propertyName, JSValue* value, PutPropertySlot&) { if (!isCSSPropertyName(propertyName)) return false; - DOMExceptionTranslator exception(exec); bool pixelOrPos; String prop = cssPropertyName(propertyName, &pixelOrPos); String propValue = valueToStringWithNullCheck(exec, value); if (pixelOrPos) propValue += "px"; - impl()->setProperty(prop, propValue, exception); + ExceptionCode ec = 0; + impl()->setProperty(prop, propValue, ec); + setDOMException(exec, ec); return true; } diff --git a/WebCore/bindings/js/JSCSSStyleDeclarationCustom.h b/WebCore/bindings/js/JSCSSStyleDeclarationCustom.h new file mode 100644 index 0000000..32ecbe0 --- /dev/null +++ b/WebCore/bindings/js/JSCSSStyleDeclarationCustom.h @@ -0,0 +1,31 @@ +/* + * Copyright (C) 2008 Apple Inc. All Rights Reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef JSCSSStyleDeclarationCustom_h +#define JSCSSStyleDeclarationCustom_h + +#include "JSCSSStyleDeclaration.h" + +#endif // JSCSSStyleDeclarationCustom_h diff --git a/WebCore/bindings/js/JSCSSValueCustom.cpp b/WebCore/bindings/js/JSCSSValueCustom.cpp index f544849..85868c3 100644 --- a/WebCore/bindings/js/JSCSSValueCustom.cpp +++ b/WebCore/bindings/js/JSCSSValueCustom.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2007 Apple Inc. All rights reserved. + * Copyright (C) 2007, 2008 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -27,11 +27,11 @@ #include "JSCSSValue.h" #include "CSSPrimitiveValue.h" -#include "CSSValue.h" #include "CSSValueList.h" #include "JSCSSPrimitiveValue.h" #include "JSCSSValueList.h" -#include "kjs_binding.h" +#include "JSWebKitCSSTransformValue.h" +#include "WebKitCSSTransformValue.h" #if ENABLE(SVG) #include "JSSVGColor.h" @@ -40,33 +40,36 @@ #include "SVGPaint.h" #endif +using namespace JSC; + namespace WebCore { -KJS::JSValue* toJS(KJS::ExecState* exec, CSSValue* value) +JSValue* toJS(ExecState* exec, CSSValue* value) { if (!value) - return KJS::jsNull(); + return jsNull(); - KJS::DOMObject* ret = KJS::ScriptInterpreter::getDOMObject(value); + DOMObject* wrapper = getCachedDOMObjectWrapper(exec->globalData(), value); - if (ret) - return ret; + if (wrapper) + return wrapper; - if (value->isValueList()) - ret = new JSCSSValueList(JSCSSValueListPrototype::self(exec), static_cast<CSSValueList*>(value)); + if (value->isWebKitCSSTransformValue()) + wrapper = CREATE_DOM_OBJECT_WRAPPER(exec, WebKitCSSTransformValue, value); + else if (value->isValueList()) + wrapper = CREATE_DOM_OBJECT_WRAPPER(exec, CSSValueList, value); #if ENABLE(SVG) else if (value->isSVGPaint()) - ret = new JSSVGPaint(JSSVGPaintPrototype::self(exec), static_cast<SVGPaint*>(value)); + wrapper = CREATE_DOM_OBJECT_WRAPPER(exec, SVGPaint, value); else if (value->isSVGColor()) - ret = new JSSVGColor(JSSVGColorPrototype::self(exec), static_cast<SVGColor*>(value)); + wrapper = CREATE_DOM_OBJECT_WRAPPER(exec, SVGColor, value); #endif else if (value->isPrimitiveValue()) - ret = new JSCSSPrimitiveValue(JSCSSPrimitiveValuePrototype::self(exec), static_cast<CSSPrimitiveValue*>(value)); + wrapper = CREATE_DOM_OBJECT_WRAPPER(exec, CSSPrimitiveValue, value); else - ret = new JSCSSValue(JSCSSValuePrototype::self(exec), value); + wrapper = CREATE_DOM_OBJECT_WRAPPER(exec, CSSValue, value); - KJS::ScriptInterpreter::putDOMObject(value, ret); - return ret; + return wrapper; } } // namespace WebCore diff --git a/WebCore/bindings/js/JSCanvasPixelArrayCustom.h b/WebCore/bindings/js/JSCanvasPixelArrayCustom.h new file mode 100644 index 0000000..9bdcccd --- /dev/null +++ b/WebCore/bindings/js/JSCanvasPixelArrayCustom.h @@ -0,0 +1,50 @@ +/* + * Copyright (C) 2008 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "JSCanvasPixelArray.h" + +#include "CanvasPixelArray.h" + +using namespace JSC; + +namespace WebCore { + + inline JSValue* JSCanvasPixelArray::getByIndex(ExecState* exec, unsigned index) + { + unsigned char result; + if (!impl()->get(index, result)) + return jsUndefined(); + return JSImmediate::from(result); + } + + inline void JSCanvasPixelArray::indexSetter(ExecState* exec, unsigned index, JSValue* value) + { + double pixelValue = value->toNumber(exec); + if (exec->hadException()) + return; + m_impl->set(index, pixelValue); + } + +} // namespace WebCore diff --git a/WebCore/bindings/js/JSCanvasRenderingContext2DCustom.cpp b/WebCore/bindings/js/JSCanvasRenderingContext2DCustom.cpp index 68328f4..a2f4f65 100644 --- a/WebCore/bindings/js/JSCanvasRenderingContext2DCustom.cpp +++ b/WebCore/bindings/js/JSCanvasRenderingContext2DCustom.cpp @@ -28,36 +28,38 @@ #include "FloatRect.h" #include "HTMLCanvasElement.h" #include "HTMLImageElement.h" +#include "ImageData.h" #include "JSCanvasGradient.h" #include "JSCanvasPattern.h" #include "JSHTMLCanvasElement.h" #include "JSHTMLImageElement.h" -#include "kjs_html.h" +#include "JSImageData.h" +#include <runtime/Error.h> -using namespace KJS; +using namespace JSC; namespace WebCore { static JSValue* toJS(ExecState* exec, CanvasStyle* style) { - if (style->gradient()) - return toJS(exec, style->gradient()); - if (style->pattern()) - return toJS(exec, style->pattern()); - return jsString(style->color()); + if (style->canvasGradient()) + return toJS(exec, style->canvasGradient()); + if (style->canvasPattern()) + return toJS(exec, style->canvasPattern()); + return jsString(exec, style->color()); } static PassRefPtr<CanvasStyle> toHTMLCanvasStyle(ExecState* exec, JSValue* value) { if (value->isString()) - return new CanvasStyle(value->toString(exec)); + return CanvasStyle::create(asString(value)->value()); if (!value->isObject()) return 0; - JSObject* object = static_cast<JSObject*>(value); - if (object->inherits(&JSCanvasGradient::info)) - return new CanvasStyle(static_cast<JSCanvasGradient*>(object)->impl()); - if (object->inherits(&JSCanvasPattern::info)) - return new CanvasStyle(static_cast<JSCanvasPattern*>(object)->impl()); + JSObject* object = asObject(value); + if (object->inherits(&JSCanvasGradient::s_info)) + return CanvasStyle::create(static_cast<JSCanvasGradient*>(object)->impl()); + if (object->inherits(&JSCanvasPattern::s_info)) + return CanvasStyle::create(static_cast<JSCanvasPattern*>(object)->impl()); return 0; } @@ -81,7 +83,7 @@ void JSCanvasRenderingContext2D::setFillStyle(ExecState* exec, JSValue* value) impl()->setFillStyle(toHTMLCanvasStyle(exec, value)); } -JSValue* JSCanvasRenderingContext2D::setFillColor(ExecState* exec, const List& args) +JSValue* JSCanvasRenderingContext2D::setFillColor(ExecState* exec, const ArgList& args) { CanvasRenderingContext2D* context = impl(); @@ -93,24 +95,24 @@ JSValue* JSCanvasRenderingContext2D::setFillColor(ExecState* exec, const List& a // 5 args = c, m, y, k, a switch (args.size()) { case 1: - if (args[0]->isString()) - context->setFillColor(args[0]->toString(exec)); + if (args.at(exec, 0)->isString()) + context->setFillColor(asString(args.at(exec, 0))->value()); else - context->setFillColor(args[0]->toFloat(exec)); + context->setFillColor(args.at(exec, 0)->toFloat(exec)); break; case 2: - if (args[0]->isString()) - context->setFillColor(args[0]->toString(exec), args[1]->toFloat(exec)); + if (args.at(exec, 0)->isString()) + context->setFillColor(asString(args.at(exec, 0))->value(), args.at(exec, 1)->toFloat(exec)); else - context->setFillColor(args[0]->toFloat(exec), args[1]->toFloat(exec)); + context->setFillColor(args.at(exec, 0)->toFloat(exec), args.at(exec, 1)->toFloat(exec)); break; case 4: - context->setFillColor(args[0]->toFloat(exec), args[1]->toFloat(exec), - args[2]->toFloat(exec), args[3]->toFloat(exec)); + context->setFillColor(args.at(exec, 0)->toFloat(exec), args.at(exec, 1)->toFloat(exec), + args.at(exec, 2)->toFloat(exec), args.at(exec, 3)->toFloat(exec)); break; case 5: - context->setFillColor(args[0]->toFloat(exec), args[1]->toFloat(exec), - args[2]->toFloat(exec), args[3]->toFloat(exec), args[4]->toFloat(exec)); + context->setFillColor(args.at(exec, 0)->toFloat(exec), args.at(exec, 1)->toFloat(exec), + args.at(exec, 2)->toFloat(exec), args.at(exec, 3)->toFloat(exec), args.at(exec, 4)->toFloat(exec)); break; default: return throwError(exec, SyntaxError); @@ -118,7 +120,7 @@ JSValue* JSCanvasRenderingContext2D::setFillColor(ExecState* exec, const List& a return jsUndefined(); } -JSValue* JSCanvasRenderingContext2D::setStrokeColor(ExecState* exec, const List& args) +JSValue* JSCanvasRenderingContext2D::setStrokeColor(ExecState* exec, const ArgList& args) { CanvasRenderingContext2D* context = impl(); @@ -130,24 +132,24 @@ JSValue* JSCanvasRenderingContext2D::setStrokeColor(ExecState* exec, const List& // 5 args = c, m, y, k, a switch (args.size()) { case 1: - if (args[0]->isString()) - context->setStrokeColor(args[0]->toString(exec)); + if (args.at(exec, 0)->isString()) + context->setStrokeColor(asString(args.at(exec, 0))->value()); else - context->setStrokeColor(args[0]->toFloat(exec)); + context->setStrokeColor(args.at(exec, 0)->toFloat(exec)); break; case 2: - if (args[0]->isString()) - context->setStrokeColor(args[0]->toString(exec), args[1]->toFloat(exec)); + if (args.at(exec, 0)->isString()) + context->setStrokeColor(asString(args.at(exec, 0))->value(), args.at(exec, 1)->toFloat(exec)); else - context->setStrokeColor(args[0]->toFloat(exec), args[1]->toFloat(exec)); + context->setStrokeColor(args.at(exec, 0)->toFloat(exec), args.at(exec, 1)->toFloat(exec)); break; case 4: - context->setStrokeColor(args[0]->toFloat(exec), args[1]->toFloat(exec), - args[2]->toFloat(exec), args[3]->toFloat(exec)); + context->setStrokeColor(args.at(exec, 0)->toFloat(exec), args.at(exec, 1)->toFloat(exec), + args.at(exec, 2)->toFloat(exec), args.at(exec, 3)->toFloat(exec)); break; case 5: - context->setStrokeColor(args[0]->toFloat(exec), args[1]->toFloat(exec), - args[2]->toFloat(exec), args[3]->toFloat(exec), args[4]->toFloat(exec)); + context->setStrokeColor(args.at(exec, 0)->toFloat(exec), args.at(exec, 1)->toFloat(exec), + args.at(exec, 2)->toFloat(exec), args.at(exec, 3)->toFloat(exec), args.at(exec, 4)->toFloat(exec)); break; default: return throwError(exec, SyntaxError); @@ -156,23 +158,21 @@ JSValue* JSCanvasRenderingContext2D::setStrokeColor(ExecState* exec, const List& return jsUndefined(); } -JSValue* JSCanvasRenderingContext2D::strokeRect(ExecState* exec, const List& args) +JSValue* JSCanvasRenderingContext2D::strokeRect(ExecState* exec, const ArgList& args) { - CanvasRenderingContext2D* context = impl(); - ExceptionCode ec; + CanvasRenderingContext2D* context = impl(); if (args.size() <= 4) - context->strokeRect(args[0]->toFloat(exec), args[1]->toFloat(exec), - args[2]->toFloat(exec), args[3]->toFloat(exec), ec); + context->strokeRect(args.at(exec, 0)->toFloat(exec), args.at(exec, 1)->toFloat(exec), + args.at(exec, 2)->toFloat(exec), args.at(exec, 3)->toFloat(exec)); else - context->strokeRect(args[0]->toFloat(exec), args[1]->toFloat(exec), - args[2]->toFloat(exec), args[3]->toFloat(exec), args[4]->toFloat(exec), ec); - setDOMException(exec, ec); - + context->strokeRect(args.at(exec, 0)->toFloat(exec), args.at(exec, 1)->toFloat(exec), + args.at(exec, 2)->toFloat(exec), args.at(exec, 3)->toFloat(exec), args.at(exec, 4)->toFloat(exec)); + return jsUndefined(); } -JSValue* JSCanvasRenderingContext2D::drawImage(ExecState* exec, const List& args) +JSValue* JSCanvasRenderingContext2D::drawImage(ExecState* exec, const ArgList& args) { CanvasRenderingContext2D* context = impl(); @@ -182,49 +182,49 @@ JSValue* JSCanvasRenderingContext2D::drawImage(ExecState* exec, const List& args // drawImage(img, sx, sy, sw, sh, dx, dy, dw, dh) // Composite operation is specified with globalCompositeOperation. // The img parameter can be a <img> or <canvas> element. - JSValue* value = args[0]; + JSValue* value = args.at(exec, 0); if (!value->isObject()) return throwError(exec, TypeError); - JSObject* o = static_cast<JSObject*>(value); + JSObject* o = asObject(value); ExceptionCode ec = 0; - if (o->inherits(&JSHTMLImageElement::info)) { - HTMLImageElement* imgElt = static_cast<HTMLImageElement*>(static_cast<JSHTMLElement*>(args[0])->impl()); + if (o->inherits(&JSHTMLImageElement::s_info)) { + HTMLImageElement* imgElt = static_cast<HTMLImageElement*>(static_cast<JSHTMLElement*>(o)->impl()); switch (args.size()) { case 3: - context->drawImage(imgElt, args[1]->toFloat(exec), args[2]->toFloat(exec)); + context->drawImage(imgElt, args.at(exec, 1)->toFloat(exec), args.at(exec, 2)->toFloat(exec)); break; case 5: - context->drawImage(imgElt, args[1]->toFloat(exec), args[2]->toFloat(exec), - args[3]->toFloat(exec), args[4]->toFloat(exec), ec); + context->drawImage(imgElt, args.at(exec, 1)->toFloat(exec), args.at(exec, 2)->toFloat(exec), + args.at(exec, 3)->toFloat(exec), args.at(exec, 4)->toFloat(exec), ec); setDOMException(exec, ec); break; case 9: - context->drawImage(imgElt, FloatRect(args[1]->toFloat(exec), args[2]->toFloat(exec), - args[3]->toFloat(exec), args[4]->toFloat(exec)), - FloatRect(args[5]->toFloat(exec), args[6]->toFloat(exec), - args[7]->toFloat(exec), args[8]->toFloat(exec)), ec); + context->drawImage(imgElt, FloatRect(args.at(exec, 1)->toFloat(exec), args.at(exec, 2)->toFloat(exec), + args.at(exec, 3)->toFloat(exec), args.at(exec, 4)->toFloat(exec)), + FloatRect(args.at(exec, 5)->toFloat(exec), args.at(exec, 6)->toFloat(exec), + args.at(exec, 7)->toFloat(exec), args.at(exec, 8)->toFloat(exec)), ec); setDOMException(exec, ec); break; default: return throwError(exec, SyntaxError); } - } else if (o->inherits(&JSHTMLCanvasElement::info)) { - HTMLCanvasElement* canvas = static_cast<HTMLCanvasElement*>(static_cast<JSHTMLElement*>(args[0])->impl()); + } else if (o->inherits(&JSHTMLCanvasElement::s_info)) { + HTMLCanvasElement* canvas = static_cast<HTMLCanvasElement*>(static_cast<JSHTMLElement*>(o)->impl()); switch (args.size()) { case 3: - context->drawImage(canvas, args[1]->toFloat(exec), args[2]->toFloat(exec)); + context->drawImage(canvas, args.at(exec, 1)->toFloat(exec), args.at(exec, 2)->toFloat(exec)); break; case 5: - context->drawImage(canvas, args[1]->toFloat(exec), args[2]->toFloat(exec), - args[3]->toFloat(exec), args[4]->toFloat(exec), ec); + context->drawImage(canvas, args.at(exec, 1)->toFloat(exec), args.at(exec, 2)->toFloat(exec), + args.at(exec, 3)->toFloat(exec), args.at(exec, 4)->toFloat(exec), ec); setDOMException(exec, ec); break; case 9: - context->drawImage(canvas, FloatRect(args[1]->toFloat(exec), args[2]->toFloat(exec), - args[3]->toFloat(exec), args[4]->toFloat(exec)), - FloatRect(args[5]->toFloat(exec), args[6]->toFloat(exec), - args[7]->toFloat(exec), args[8]->toFloat(exec)), ec); + context->drawImage(canvas, FloatRect(args.at(exec, 1)->toFloat(exec), args.at(exec, 2)->toFloat(exec), + args.at(exec, 3)->toFloat(exec), args.at(exec, 4)->toFloat(exec)), + FloatRect(args.at(exec, 5)->toFloat(exec), args.at(exec, 6)->toFloat(exec), + args.at(exec, 7)->toFloat(exec), args.at(exec, 8)->toFloat(exec)), ec); setDOMException(exec, ec); break; default: @@ -232,70 +232,69 @@ JSValue* JSCanvasRenderingContext2D::drawImage(ExecState* exec, const List& args } } else { setDOMException(exec, TYPE_MISMATCH_ERR); - return 0; } return jsUndefined(); } -JSValue* JSCanvasRenderingContext2D::drawImageFromRect(ExecState* exec, const List& args) +JSValue* JSCanvasRenderingContext2D::drawImageFromRect(ExecState* exec, const ArgList& args) { CanvasRenderingContext2D* context = impl(); - JSValue* value = args[0]; + JSValue* value = args.at(exec, 0); if (!value->isObject()) return throwError(exec, TypeError); - JSObject* o = static_cast<JSObject*>(value); + JSObject* o = asObject(value); - if (!o->inherits(&JSHTMLImageElement::info)) + if (!o->inherits(&JSHTMLImageElement::s_info)) return throwError(exec, TypeError); - context->drawImageFromRect(static_cast<HTMLImageElement*>(static_cast<JSHTMLElement*>(args[0])->impl()), - args[1]->toFloat(exec), args[2]->toFloat(exec), - args[3]->toFloat(exec), args[4]->toFloat(exec), - args[5]->toFloat(exec), args[6]->toFloat(exec), - args[7]->toFloat(exec), args[8]->toFloat(exec), - args[9]->toString(exec)); + context->drawImageFromRect(static_cast<HTMLImageElement*>(static_cast<JSHTMLElement*>(o)->impl()), + args.at(exec, 1)->toFloat(exec), args.at(exec, 2)->toFloat(exec), + args.at(exec, 3)->toFloat(exec), args.at(exec, 4)->toFloat(exec), + args.at(exec, 5)->toFloat(exec), args.at(exec, 6)->toFloat(exec), + args.at(exec, 7)->toFloat(exec), args.at(exec, 8)->toFloat(exec), + args.at(exec, 9)->toString(exec)); return jsUndefined(); } -JSValue* JSCanvasRenderingContext2D::setShadow(ExecState* exec, const List& args) +JSValue* JSCanvasRenderingContext2D::setShadow(ExecState* exec, const ArgList& args) { CanvasRenderingContext2D* context = impl(); switch (args.size()) { case 3: - context->setShadow(args[0]->toFloat(exec), args[1]->toFloat(exec), - args[2]->toFloat(exec)); + context->setShadow(args.at(exec, 0)->toFloat(exec), args.at(exec, 1)->toFloat(exec), + args.at(exec, 2)->toFloat(exec)); break; case 4: - if (args[3]->isString()) - context->setShadow(args[0]->toFloat(exec), args[1]->toFloat(exec), - args[2]->toFloat(exec), args[3]->toString(exec)); + if (args.at(exec, 3)->isString()) + context->setShadow(args.at(exec, 0)->toFloat(exec), args.at(exec, 1)->toFloat(exec), + args.at(exec, 2)->toFloat(exec), asString(args.at(exec, 3))->value()); else - context->setShadow(args[0]->toFloat(exec), args[1]->toFloat(exec), - args[2]->toFloat(exec), args[3]->toFloat(exec)); + context->setShadow(args.at(exec, 0)->toFloat(exec), args.at(exec, 1)->toFloat(exec), + args.at(exec, 2)->toFloat(exec), args.at(exec, 3)->toFloat(exec)); break; case 5: - if (args[3]->isString()) - context->setShadow(args[0]->toFloat(exec), args[1]->toFloat(exec), - args[2]->toFloat(exec), args[3]->toString(exec), - args[4]->toFloat(exec)); + if (args.at(exec, 3)->isString()) + context->setShadow(args.at(exec, 0)->toFloat(exec), args.at(exec, 1)->toFloat(exec), + args.at(exec, 2)->toFloat(exec), asString(args.at(exec, 3))->value(), + args.at(exec, 4)->toFloat(exec)); else - context->setShadow(args[0]->toFloat(exec), args[1]->toFloat(exec), - args[2]->toFloat(exec), args[3]->toFloat(exec), - args[4]->toFloat(exec)); + context->setShadow(args.at(exec, 0)->toFloat(exec), args.at(exec, 1)->toFloat(exec), + args.at(exec, 2)->toFloat(exec), args.at(exec, 3)->toFloat(exec), + args.at(exec, 4)->toFloat(exec)); break; case 7: - context->setShadow(args[0]->toFloat(exec), args[1]->toFloat(exec), - args[2]->toFloat(exec), args[3]->toFloat(exec), - args[4]->toFloat(exec), args[5]->toFloat(exec), - args[6]->toFloat(exec)); + context->setShadow(args.at(exec, 0)->toFloat(exec), args.at(exec, 1)->toFloat(exec), + args.at(exec, 2)->toFloat(exec), args.at(exec, 3)->toFloat(exec), + args.at(exec, 4)->toFloat(exec), args.at(exec, 5)->toFloat(exec), + args.at(exec, 6)->toFloat(exec)); break; case 8: - context->setShadow(args[0]->toFloat(exec), args[1]->toFloat(exec), - args[2]->toFloat(exec), args[3]->toFloat(exec), - args[4]->toFloat(exec), args[5]->toFloat(exec), - args[6]->toFloat(exec), args[7]->toFloat(exec)); + context->setShadow(args.at(exec, 0)->toFloat(exec), args.at(exec, 1)->toFloat(exec), + args.at(exec, 2)->toFloat(exec), args.at(exec, 3)->toFloat(exec), + args.at(exec, 4)->toFloat(exec), args.at(exec, 5)->toFloat(exec), + args.at(exec, 6)->toFloat(exec), args.at(exec, 7)->toFloat(exec)); break; default: return throwError(exec, SyntaxError); @@ -304,33 +303,87 @@ JSValue* JSCanvasRenderingContext2D::setShadow(ExecState* exec, const List& args return jsUndefined(); } -JSValue* JSCanvasRenderingContext2D::createPattern(ExecState* exec, const List& args) +JSValue* JSCanvasRenderingContext2D::createPattern(ExecState* exec, const ArgList& args) { CanvasRenderingContext2D* context = impl(); - JSValue* value = args[0]; + JSValue* value = args.at(exec, 0); if (!value->isObject()) return throwError(exec, TypeError); - JSObject* o = static_cast<JSObject*>(value); - - if (o->inherits(&JSHTMLImageElement::info)) { + JSObject* o = asObject(value); + + if (o->inherits(&JSHTMLImageElement::s_info)) { ExceptionCode ec; JSValue* pattern = toJS(exec, - context->createPattern(static_cast<HTMLImageElement*>(static_cast<JSHTMLElement*>(args[0])->impl()), - args[1]->toString(exec), ec).get()); + context->createPattern(static_cast<HTMLImageElement*>(static_cast<JSHTMLElement*>(o)->impl()), + valueToStringWithNullCheck(exec, args.at(exec, 1)), ec).get()); setDOMException(exec, ec); return pattern; } - if (o->inherits(&JSHTMLCanvasElement::info)) { + if (o->inherits(&JSHTMLCanvasElement::s_info)) { ExceptionCode ec; JSValue* pattern = toJS(exec, - context->createPattern(static_cast<HTMLCanvasElement*>(static_cast<JSHTMLElement*>(args[0])->impl()), - args[1]->toString(exec), ec).get()); + context->createPattern(static_cast<HTMLCanvasElement*>(static_cast<JSHTMLElement*>(o)->impl()), + valueToStringWithNullCheck(exec, args.at(exec, 1)), ec).get()); setDOMException(exec, ec); return pattern; } setDOMException(exec, TYPE_MISMATCH_ERR); - return 0; + return jsUndefined(); +} + +JSValue* JSCanvasRenderingContext2D::putImageData(ExecState* exec, const ArgList& args) +{ + // putImageData has two variants + // putImageData(ImageData, x, y) + // putImageData(ImageData, x, y, dirtyX, dirtyY, dirtyWidth, dirtyHeight) + CanvasRenderingContext2D* context = impl(); + + ExceptionCode ec = 0; + if (args.size() >= 7) + context->putImageData(toImageData(args.at(exec, 0)), args.at(exec, 1)->toFloat(exec), args.at(exec, 2)->toFloat(exec), + args.at(exec, 3)->toFloat(exec), args.at(exec, 4)->toFloat(exec), args.at(exec, 5)->toFloat(exec), args.at(exec, 6)->toFloat(exec), ec); + else + context->putImageData(toImageData(args.at(exec, 0)), args.at(exec, 1)->toFloat(exec), args.at(exec, 2)->toFloat(exec), ec); + + setDOMException(exec, ec); + return jsUndefined(); +} + +JSValue* JSCanvasRenderingContext2D::fillText(ExecState* exec, const ArgList& args) +{ + CanvasRenderingContext2D* context = impl(); + + // string arg = text to draw + // number arg = x + // number arg = y + // optional number arg = maxWidth + if (args.size() < 3 || args.size() > 4) + return throwError(exec, SyntaxError); + + if (args.size() == 4) + context->fillText(args.at(exec, 0)->toString(exec), args.at(exec, 1)->toFloat(exec), args.at(exec, 2)->toFloat(exec), args.at(exec, 3)->toFloat(exec)); + else + context->fillText(args.at(exec, 0)->toString(exec), args.at(exec, 1)->toFloat(exec), args.at(exec, 2)->toFloat(exec)); + return jsUndefined(); +} + +JSValue* JSCanvasRenderingContext2D::strokeText(ExecState* exec, const ArgList& args) +{ + CanvasRenderingContext2D* context = impl(); + + // string arg = text to draw + // number arg = x + // number arg = y + // optional number arg = maxWidth + if (args.size() < 3 || args.size() > 4) + return throwError(exec, SyntaxError); + + if (args.size() == 4) + context->strokeText(args.at(exec, 0)->toString(exec), args.at(exec, 1)->toFloat(exec), args.at(exec, 2)->toFloat(exec), args.at(exec, 3)->toFloat(exec)); + else + context->strokeText(args.at(exec, 0)->toString(exec), args.at(exec, 1)->toFloat(exec), args.at(exec, 2)->toFloat(exec)); + return jsUndefined(); } } // namespace WebCore diff --git a/WebCore/bindings/js/JSClipboardCustom.cpp b/WebCore/bindings/js/JSClipboardCustom.cpp new file mode 100644 index 0000000..bdcb074 --- /dev/null +++ b/WebCore/bindings/js/JSClipboardCustom.cpp @@ -0,0 +1,142 @@ +/* + * Copyright (C) 2008 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of + * its contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "JSClipboard.h" + +#include "Clipboard.h" +#include "Element.h" +#include "HTMLImageElement.h" +#include "HTMLNames.h" +#include "IntPoint.h" +#include "JSNode.h" +#include "Node.h" +#include "PlatformString.h" +#include "StringHash.h" +#include <runtime/ArrayPrototype.h> +#include <runtime/Error.h> +#include <wtf/HashSet.h> + +using namespace JSC; + +namespace WebCore { + +using namespace HTMLNames; + +JSValue* JSClipboard::types(ExecState* exec) const +{ + Clipboard* clipboard = impl(); + + HashSet<String> types = clipboard->types(); + if (types.isEmpty()) + return jsNull(); + + ArgList list; + HashSet<String>::const_iterator end = types.end(); + for (HashSet<String>::const_iterator it = types.begin(); it != end; ++it) + list.append(jsString(exec, UString(*it))); + return constructArray(exec, list); +} + +JSValue* JSClipboard::clearData(ExecState* exec, const ArgList& args) +{ + Clipboard* clipboard = impl(); + + if (args.size() == 0) { + clipboard->clearAllData(); + return jsUndefined(); + } + + if (args.size() == 1) { + clipboard->clearData(args.at(exec, 0)->toString(exec)); + return jsUndefined(); + } + + // FIXME: It does not match the rest of the JS bindings to throw on invalid number of arguments. + return throwError(exec, SyntaxError, "clearData: Invalid number of arguments"); +} + +JSValue* JSClipboard::getData(ExecState* exec, const ArgList& args) +{ + // FIXME: It does not match the rest of the JS bindings to throw on invalid number of arguments. + if (args.size() != 1) + return throwError(exec, SyntaxError, "getData: Invalid number of arguments"); + + Clipboard* clipboard = impl(); + + bool success; + String result = clipboard->getData(args.at(exec, 0)->toString(exec), success); + if (!success) + return jsUndefined(); + + return jsString(exec, result); +} + +JSValue* JSClipboard::setData(ExecState* exec, const ArgList& args) +{ + Clipboard* clipboard = impl(); + + // FIXME: It does not match the rest of the JS bindings to throw on invalid number of arguments. + if (args.size() != 2) + return throwError(exec, SyntaxError, "setData: Invalid number of arguments"); + + return jsBoolean(clipboard->setData(args.at(exec, 0)->toString(exec), args.at(exec, 1)->toString(exec))); +} + +JSValue* JSClipboard::setDragImage(ExecState* exec, const ArgList& args) +{ + Clipboard* clipboard = impl(); + + if (!clipboard->isForDragging()) + return jsUndefined(); + + // FIXME: It does not match the rest of the JS bindings to throw on invalid number of arguments. + if (args.size() != 3) + return throwError(exec, SyntaxError, "setDragImage: Invalid number of arguments"); + + int x = args.at(exec, 1)->toInt32(exec); + int y = args.at(exec, 2)->toInt32(exec); + + // See if they passed us a node + Node* node = toNode(args.at(exec, 0)); + if (!node) + return throwError(exec, TypeError); + + // FIXME: This should probably be a TypeError. + if (!node->isElementNode()) + return throwError(exec, SyntaxError, "setDragImageFromElement: Invalid first argument"); + + if (static_cast<Element*>(node)->hasLocalName(imgTag) && !node->inDocument()) + clipboard->setDragImage(static_cast<HTMLImageElement*>(node)->cachedImage(), IntPoint(x, y)); + else + clipboard->setDragImageElement(node, IntPoint(x, y)); + + return jsUndefined(); +} + +} // namespace WebCore diff --git a/WebCore/bindings/js/JSConsoleCustom.cpp b/WebCore/bindings/js/JSConsoleCustom.cpp new file mode 100644 index 0000000..6131cb6 --- /dev/null +++ b/WebCore/bindings/js/JSConsoleCustom.cpp @@ -0,0 +1,138 @@ +/* + * Copyright (C) 2008 Apple Inc. All Rights Reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "JSConsole.h" +#include "JavaScriptProfile.h" +#include <runtime/JSArray.h> + +#include "Console.h" + +using namespace JSC; + +namespace WebCore { + +typedef Vector<RefPtr<JSC::Profile> > ProfilesArray; + +JSValue* JSConsole::profiles(ExecState* exec) const +{ + const ProfilesArray& profiles = impl()->profiles(); + ArgList list; + + ProfilesArray::const_iterator end = profiles.end(); + for (ProfilesArray::const_iterator iter = profiles.begin(); iter != end; ++iter) + list.append(toJS(exec, iter->get())); + + return constructArray(exec, list); +} + +JSValue* JSConsole::debug(ExecState* exec, const ArgList& arguments) +{ + impl()->debug(exec, arguments); + return jsUndefined(); +} + +JSValue* JSConsole::error(ExecState* exec, const ArgList& arguments) +{ + impl()->error(exec, arguments); + return jsUndefined(); +} + +JSValue* JSConsole::info(ExecState* exec, const ArgList& arguments) +{ + impl()->info(exec, arguments); + return jsUndefined(); +} + +JSValue* JSConsole::log(ExecState* exec, const ArgList& arguments) +{ + impl()->log(exec, arguments); + return jsUndefined(); +} + +JSValue* JSConsole::warn(ExecState* exec, const ArgList& arguments) +{ + impl()->warn(exec, arguments); + return jsUndefined(); +} + +JSValue* JSConsole::dir(ExecState* exec, const ArgList& arguments) +{ + impl()->dir(exec, arguments); + return jsUndefined(); +} + +JSValue* JSConsole::dirxml(ExecState* exec, const ArgList& arguments) +{ + impl()->dirxml(exec, arguments); + return jsUndefined(); +} + +JSValue* JSConsole::trace(ExecState* exec, const ArgList&) +{ + impl()->trace(exec); + return jsUndefined(); +} + +JSValue* JSConsole::assertCondition(ExecState* exec, const ArgList& arguments) +{ + ArgList messageParameters; + arguments.getSlice(1, messageParameters); + + impl()->assertCondition(arguments.at(exec, 0)->toBoolean(exec), exec, messageParameters); + return jsUndefined(); +} + +JSValue* JSConsole::count(ExecState* exec, const ArgList& arguments) +{ + impl()->count(exec, arguments); + return jsUndefined(); +} + +JSValue* JSConsole::timeEnd(ExecState* exec, const ArgList& arguments) +{ + impl()->timeEnd(exec, arguments); + return jsUndefined(); +} + +JSValue* JSConsole::profile(ExecState* exec, const ArgList& arguments) +{ + impl()->profile(exec, arguments); + return jsUndefined(); +} + +JSValue* JSConsole::profileEnd(ExecState* exec, const ArgList& arguments) +{ + impl()->profileEnd(exec, arguments); + return jsUndefined(); +} + +JSValue* JSConsole::group(ExecState* exec, const ArgList& arguments) +{ + impl()->group(exec, arguments); + return jsUndefined(); +} + +} // namespace WebCore diff --git a/WebCore/bindings/js/JSCustomPositionCallback.cpp b/WebCore/bindings/js/JSCustomPositionCallback.cpp new file mode 100644 index 0000000..5a5e6b0 --- /dev/null +++ b/WebCore/bindings/js/JSCustomPositionCallback.cpp @@ -0,0 +1,87 @@ +/* + * Copyright (C) 2008 Apple Inc. All Rights Reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "JSCustomPositionCallback.h" + +#include "Console.h" +#include "CString.h" +#include "Frame.h" +#include "JSGeoposition.h" +#include "Page.h" +#include "ScriptController.h" +#include <runtime/JSLock.h> + +namespace WebCore { + +using namespace JSC; + +JSCustomPositionCallback::JSCustomPositionCallback(JSObject* callback, Frame* frame) + : m_callback(callback) + , m_frame(frame) +{ +} + +void JSCustomPositionCallback::handleEvent(Geoposition* geoposition, bool& raisedException) +{ + ASSERT(m_callback); + ASSERT(m_frame); + + if (!m_frame->script()->isEnabled()) + return; + + JSGlobalObject* globalObject = m_frame->script()->globalObject(); + ExecState* exec = globalObject->globalExec(); + + JSC::JSLock lock(false); + + JSValue* function = m_callback->get(exec, Identifier(exec, "handleEvent")); + CallData callData; + CallType callType = function->getCallData(callData); + if (callType == CallTypeNone) { + callType = m_callback->getCallData(callData); + if (callType == CallTypeNone) { + // FIXME: Should an exception be thrown here? + return; + } + function = m_callback; + } + + RefPtr<JSCustomPositionCallback> protect(this); + + ArgList args; + args.append(toJS(exec, geoposition)); + + globalObject->startTimeoutCheck(); + call(exec, function, callType, callData, m_callback, args); + globalObject->stopTimeoutCheck(); + + if (exec->hadException()) { + m_frame->domWindow()->console()->reportCurrentException(exec); + raisedException = true; + } +} + +} // namespace WebCore diff --git a/WebCore/bindings/js/JSCustomPositionCallback.h b/WebCore/bindings/js/JSCustomPositionCallback.h new file mode 100644 index 0000000..96e6177 --- /dev/null +++ b/WebCore/bindings/js/JSCustomPositionCallback.h @@ -0,0 +1,58 @@ +/* + * Copyright (C) 2008 Apple Inc. All Rights Reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef JSCustomPositionCallback_h +#define JSCustomPositionCallback_h + +#include "PositionCallback.h" +#include <runtime/JSObject.h> +#include <kjs/protect.h> +#include <wtf/Forward.h> + +namespace JSC { + class JSObject; +} + +namespace WebCore { + +class Frame; +class Geoposition; + +class JSCustomPositionCallback : public PositionCallback { +public: + static PassRefPtr<JSCustomPositionCallback> create(JSC::JSObject* callback, Frame* frame) { return adoptRef(new JSCustomPositionCallback(callback, frame)); } + + virtual void handleEvent(Geoposition*, bool& raisedException); + +private: + JSCustomPositionCallback(JSC::JSObject* callback, Frame*); + + JSC::ProtectedPtr<JSC::JSObject> m_callback; + RefPtr<Frame> m_frame; +}; + +} // namespace WebCore + +#endif // JSCustomPositionCallback_h diff --git a/WebCore/bindings/js/JSCustomPositionErrorCallback.cpp b/WebCore/bindings/js/JSCustomPositionErrorCallback.cpp new file mode 100644 index 0000000..2cd41d7 --- /dev/null +++ b/WebCore/bindings/js/JSCustomPositionErrorCallback.cpp @@ -0,0 +1,85 @@ +/* + * Copyright (C) 2008 Apple Inc. All Rights Reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "JSCustomPositionErrorCallback.h" + +#include "Console.h" +#include "CString.h" +#include "Frame.h" +#include "JSPositionError.h" +#include "Page.h" +#include "ScriptController.h" +#include <runtime/JSLock.h> + +namespace WebCore { + +using namespace JSC; + +JSCustomPositionErrorCallback::JSCustomPositionErrorCallback(JSObject* callback, Frame* frame) + : m_callback(callback) + , m_frame(frame) +{ +} + +void JSCustomPositionErrorCallback::handleEvent(PositionError* positionError) +{ + ASSERT(m_callback); + ASSERT(m_frame); + + if (!m_frame->script()->isEnabled()) + return; + + JSGlobalObject* globalObject = m_frame->script()->globalObject(); + ExecState* exec = globalObject->globalExec(); + + JSC::JSLock lock(false); + + JSValue* function = m_callback->get(exec, Identifier(exec, "handleEvent")); + CallData callData; + CallType callType = function->getCallData(callData); + if (callType == CallTypeNone) { + callType = m_callback->getCallData(callData); + if (callType == CallTypeNone) { + // FIXME: Should an exception be thrown here? + return; + } + function = m_callback; + } + + RefPtr<JSCustomPositionErrorCallback> protect(this); + + ArgList args; + args.append(toJS(exec, positionError)); + + globalObject->startTimeoutCheck(); + call(exec, function, callType, callData, m_callback, args); + globalObject->stopTimeoutCheck(); + + if (exec->hadException()) + m_frame->domWindow()->console()->reportCurrentException(exec); +} + +} // namespace WebCore diff --git a/WebCore/bindings/js/JSCustomPositionErrorCallback.h b/WebCore/bindings/js/JSCustomPositionErrorCallback.h new file mode 100644 index 0000000..190e5a4 --- /dev/null +++ b/WebCore/bindings/js/JSCustomPositionErrorCallback.h @@ -0,0 +1,58 @@ +/* + * Copyright (C) 2008 Apple Inc. All Rights Reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef JSCustomPositionErrorCallback_h +#define JSCustomPositionErrorCallback_h + +#include "PositionErrorCallback.h" +#include <runtime/JSObject.h> +#include <kjs/protect.h> +#include <wtf/Forward.h> + +namespace JSC { + class JSObject; +} + +namespace WebCore { + +class Frame; +class PositionError; + +class JSCustomPositionErrorCallback : public PositionErrorCallback { +public: + static PassRefPtr<JSCustomPositionErrorCallback> create(JSC::JSObject* callback, Frame* frame) { return adoptRef(new JSCustomPositionErrorCallback(callback, frame)); } + + virtual void handleEvent(PositionError*); + +private: + JSCustomPositionErrorCallback(JSC::JSObject* callback, Frame*); + + JSC::ProtectedPtr<JSC::JSObject> m_callback; + RefPtr<Frame> m_frame; +}; + +} // namespace WebCore + +#endif // JSCustomPositionErrorCallback_h diff --git a/WebCore/bindings/js/JSCustomSQLStatementCallback.cpp b/WebCore/bindings/js/JSCustomSQLStatementCallback.cpp index 7adab5f..4787440 100644 --- a/WebCore/bindings/js/JSCustomSQLStatementCallback.cpp +++ b/WebCore/bindings/js/JSCustomSQLStatementCallback.cpp @@ -30,15 +30,17 @@ #include "JSCustomSQLStatementCallback.h" #include "CString.h" +#include "Console.h" +#include "DOMWindow.h" #include "Frame.h" -#include "kjs_proxy.h" +#include "ScriptController.h" #include "JSSQLResultSet.h" #include "JSSQLTransaction.h" -#include "Page.h" +#include <runtime/JSLock.h> namespace WebCore { -using namespace KJS; +using namespace JSC; JSCustomSQLStatementCallback::JSCustomSQLStatementCallback(JSObject* callback, Frame* frame) : m_callback(callback) @@ -51,53 +53,40 @@ void JSCustomSQLStatementCallback::handleEvent(SQLTransaction* transaction, SQLR ASSERT(m_callback); ASSERT(m_frame); - if (!m_frame->scriptProxy()->isEnabled()) + if (!m_frame->script()->isEnabled()) return; - JSGlobalObject* globalObject = m_frame->scriptProxy()->globalObject(); + JSGlobalObject* globalObject = m_frame->script()->globalObject(); ExecState* exec = globalObject->globalExec(); - KJS::JSLock lock; + JSC::JSLock lock(false); - JSValue* handleEventFuncValue = m_callback->get(exec, "handleEvent"); - JSObject* handleEventFunc = 0; - if (handleEventFuncValue->isObject()) { - handleEventFunc = static_cast<JSObject*>(handleEventFuncValue); - if (!handleEventFunc->implementsCall()) - handleEventFunc = 0; - } - - if (!handleEventFunc && !m_callback->implementsCall()) { - // FIXME: Should an exception be thrown here? - return; + JSValue* function = m_callback->get(exec, Identifier(exec, "handleEvent")); + CallData callData; + CallType callType = function->getCallData(callData); + if (callType == CallTypeNone) { + callType = m_callback->getCallData(callData); + if (callType == CallTypeNone) { + // FIXME: Should an exception be thrown here? + return; + } + function = m_callback; } RefPtr<JSCustomSQLStatementCallback> protect(this); - List args; + ArgList args; args.append(toJS(exec, transaction)); args.append(toJS(exec, resultSet)); globalObject->startTimeoutCheck(); - if (handleEventFunc) - handleEventFunc->call(exec, m_callback, args); - else - m_callback->call(exec, m_callback, args); + call(exec, function, callType, callData, m_callback, args); globalObject->stopTimeoutCheck(); if (exec->hadException()) { - JSObject* exception = exec->exception()->toObject(exec); - String message = exception->get(exec, exec->propertyNames().message)->toString(exec); - int lineNumber = exception->get(exec, "line")->toInt32(exec); - String sourceURL = exception->get(exec, "sourceURL")->toString(exec); - if (Interpreter::shouldPrintExceptions()) - printf("SQLStatementCallback: %s\n", message.utf8().data()); - if (Page* page = m_frame->page()) - page->chrome()->addMessageToConsole(JSMessageSource, ErrorMessageLevel, message, lineNumber, sourceURL); + m_frame->domWindow()->console()->reportCurrentException(exec); raisedException = true; - - exec->clearException(); } Document::updateDocumentsRendering(); diff --git a/WebCore/bindings/js/JSCustomSQLStatementCallback.h b/WebCore/bindings/js/JSCustomSQLStatementCallback.h index 27bca7b..d4fd6ec 100644 --- a/WebCore/bindings/js/JSCustomSQLStatementCallback.h +++ b/WebCore/bindings/js/JSCustomSQLStatementCallback.h @@ -31,11 +31,11 @@ #include "SQLStatementCallback.h" -#include <kjs/object.h> +#include <runtime/JSObject.h> #include <kjs/protect.h> #include <wtf/Forward.h> -namespace KJS { +namespace JSC { class JSObject; } @@ -46,11 +46,14 @@ class SQLResultSet; class JSCustomSQLStatementCallback : public SQLStatementCallback { public: - JSCustomSQLStatementCallback(KJS::JSObject* callback, Frame*); - + static PassRefPtr<JSCustomSQLStatementCallback> create(JSC::JSObject* callback, Frame* frame) { return adoptRef(new JSCustomSQLStatementCallback(callback, frame)); } + virtual void handleEvent(SQLTransaction*, SQLResultSet*, bool& raisedException); + private: - KJS::ProtectedPtr<KJS::JSObject> m_callback; + JSCustomSQLStatementCallback(JSC::JSObject* callback, Frame*); + + JSC::ProtectedPtr<JSC::JSObject> m_callback; RefPtr<Frame> m_frame; }; diff --git a/WebCore/bindings/js/JSCustomSQLStatementErrorCallback.cpp b/WebCore/bindings/js/JSCustomSQLStatementErrorCallback.cpp index 615082d..f301704 100644 --- a/WebCore/bindings/js/JSCustomSQLStatementErrorCallback.cpp +++ b/WebCore/bindings/js/JSCustomSQLStatementErrorCallback.cpp @@ -30,15 +30,17 @@ #include "JSCustomSQLStatementErrorCallback.h" #include "CString.h" +#include "Console.h" +#include "DOMWindow.h" #include "Frame.h" -#include "kjs_proxy.h" +#include "ScriptController.h" #include "JSSQLError.h" #include "JSSQLTransaction.h" -#include "Page.h" +#include <runtime/JSLock.h> namespace WebCore { -using namespace KJS; +using namespace JSC; JSCustomSQLStatementErrorCallback::JSCustomSQLStatementErrorCallback(JSObject* callback, Frame* frame) : m_callback(callback) @@ -51,51 +53,44 @@ bool JSCustomSQLStatementErrorCallback::handleEvent(SQLTransaction* transaction, ASSERT(m_callback); ASSERT(m_frame); - if (!m_frame->scriptProxy()->isEnabled()) + if (!m_frame->script()->isEnabled()) return true; - JSGlobalObject* globalObject = m_frame->scriptProxy()->globalObject(); + JSGlobalObject* globalObject = m_frame->script()->globalObject(); ExecState* exec = globalObject->globalExec(); - KJS::JSLock lock; + JSC::JSLock lock(false); - JSValue* handleEventFuncValue = m_callback->get(exec, "handleEvent"); - JSObject* handleEventFunc = 0; - if (handleEventFuncValue->isObject()) { - handleEventFunc = static_cast<JSObject*>(handleEventFuncValue); - if (!handleEventFunc->implementsCall()) - handleEventFunc = 0; - } - - if (!handleEventFunc && !m_callback->implementsCall()) { - // FIXME: Should an exception be thrown here? - return true; + JSValue* handleEventFunction = m_callback->get(exec, Identifier(exec, "handleEvent")); + CallData handleEventCallData; + CallType handleEventCallType = handleEventFunction->getCallData(handleEventCallData); + CallData callbackCallData; + CallType callbackCallType = CallTypeNone; + + if (handleEventCallType == CallTypeNone) { + callbackCallType = m_callback->getCallData(callbackCallData); + if (callbackCallType == CallTypeNone) { + // FIXME: Should an exception be thrown here? + return true; + } } RefPtr<JSCustomSQLStatementErrorCallback> protect(this); - List args; + ArgList args; args.append(toJS(exec, transaction)); args.append(toJS(exec, error)); - JSValue *result; + JSValue* result; globalObject->startTimeoutCheck(); - if (handleEventFunc) - result = handleEventFunc->call(exec, m_callback, args); + if (handleEventCallType != CallTypeNone) + result = call(exec, handleEventFunction, handleEventCallType, handleEventCallData, m_callback, args); else - result = m_callback->call(exec, m_callback, args); + result = call(exec, m_callback, callbackCallType, callbackCallData, m_callback, args); globalObject->stopTimeoutCheck(); if (exec->hadException()) { - JSObject* exception = exec->exception()->toObject(exec); - String message = exception->get(exec, exec->propertyNames().message)->toString(exec); - int lineNumber = exception->get(exec, "line")->toInt32(exec); - String sourceURL = exception->get(exec, "sourceURL")->toString(exec); - if (Interpreter::shouldPrintExceptions()) - printf("SQLStatementErrorCallback: %s\n", message.utf8().data()); - if (Page* page = m_frame->page()) - page->chrome()->addMessageToConsole(JSMessageSource, ErrorMessageLevel, message, lineNumber, sourceURL); - exec->clearException(); + m_frame->domWindow()->console()->reportCurrentException(exec); // The spec says: // "If the error callback returns false, then move on to the next statement..." diff --git a/WebCore/bindings/js/JSCustomSQLStatementErrorCallback.h b/WebCore/bindings/js/JSCustomSQLStatementErrorCallback.h index 7bc40c6..e235f23 100644 --- a/WebCore/bindings/js/JSCustomSQLStatementErrorCallback.h +++ b/WebCore/bindings/js/JSCustomSQLStatementErrorCallback.h @@ -31,11 +31,11 @@ #include "SQLStatementErrorCallback.h" -#include <kjs/object.h> +#include <runtime/JSObject.h> #include <kjs/protect.h> #include <wtf/Forward.h> -namespace KJS { +namespace JSC { class JSObject; } @@ -46,11 +46,14 @@ class SQLError; class JSCustomSQLStatementErrorCallback : public SQLStatementErrorCallback { public: - JSCustomSQLStatementErrorCallback(KJS::JSObject* callback, Frame*); + static PassRefPtr<JSCustomSQLStatementErrorCallback> create(JSC::JSObject* callback, Frame* frame) { return adoptRef(new JSCustomSQLStatementErrorCallback(callback, frame)); } virtual bool handleEvent(SQLTransaction*, SQLError*); + private: - KJS::ProtectedPtr<KJS::JSObject> m_callback; + JSCustomSQLStatementErrorCallback(JSC::JSObject* callback, Frame*); + + JSC::ProtectedPtr<JSC::JSObject> m_callback; RefPtr<Frame> m_frame; }; diff --git a/WebCore/bindings/js/JSCustomSQLTransactionCallback.cpp b/WebCore/bindings/js/JSCustomSQLTransactionCallback.cpp index b63144c..3e3bcce 100644 --- a/WebCore/bindings/js/JSCustomSQLTransactionCallback.cpp +++ b/WebCore/bindings/js/JSCustomSQLTransactionCallback.cpp @@ -30,32 +30,23 @@ #include "JSCustomSQLTransactionCallback.h" #include "CString.h" +#include "Console.h" +#include "DOMWindow.h" #include "Frame.h" #include "Logging.h" -#include "kjs_proxy.h" +#include "ScriptController.h" #include "JSSQLTransaction.h" #include "Page.h" +#include <runtime/JSLock.h> +#include <wtf/MainThread.h> +#include <wtf/RefCountedLeakCounter.h> namespace WebCore { -using namespace KJS; +using namespace JSC; #ifndef NDEBUG - -WTFLogChannel LogWebCoreSQLLeaks = { 0x00000000, "", WTFLogChannelOn }; - -struct JSCustomSQLTransactionCallbackCounter { - static int count; - ~JSCustomSQLTransactionCallbackCounter() - { - if (count) - LOG(WebCoreSQLLeaks, "LEAK: %d JSCustomSQLTransactionCallback\n", count); - } -}; - -int JSCustomSQLTransactionCallbackCounter::count = 0; -static JSCustomSQLTransactionCallbackCounter counter; - +static WTF::RefCountedLeakCounter counter("JSCustomSQLTransactionCallback"); #endif // We have to clean up the data on the main thread for two reasons: @@ -79,7 +70,7 @@ JSCustomSQLTransactionCallback::JSCustomSQLTransactionCallback(JSObject* callbac : m_data(new Data(callback, frame)) { #ifndef NDEBUG - ++JSCustomSQLTransactionCallbackCounter::count; + counter.increment(); #endif } @@ -93,7 +84,7 @@ JSCustomSQLTransactionCallback::~JSCustomSQLTransactionCallback() callOnMainThread(deleteData, m_data); #ifndef NDEBUG m_data = 0; - --JSCustomSQLTransactionCallbackCounter::count; + counter.decrement(); #endif } @@ -103,49 +94,42 @@ void JSCustomSQLTransactionCallback::handleEvent(SQLTransaction* transaction, bo ASSERT(m_data->callback()); ASSERT(m_data->frame()); - if (!m_data->frame()->scriptProxy()->isEnabled()) + if (!m_data->frame()->script()->isEnabled()) return; - JSGlobalObject* globalObject = m_data->frame()->scriptProxy()->globalObject(); + JSGlobalObject* globalObject = m_data->frame()->script()->globalObject(); ExecState* exec = globalObject->globalExec(); - KJS::JSLock lock; - - JSValue* handleEventFuncValue = m_data->callback()->get(exec, "handleEvent"); - JSObject* handleEventFunc = 0; - if (handleEventFuncValue->isObject()) { - handleEventFunc = static_cast<JSObject*>(handleEventFuncValue); - if (!handleEventFunc->implementsCall()) - handleEventFunc = 0; - } + JSC::JSLock lock(false); - if (!handleEventFunc && !m_data->callback()->implementsCall()) { - // FIXME: Should an exception be thrown here? - return; + JSValue* handleEventFunction = m_data->callback()->get(exec, Identifier(exec, "handleEvent")); + CallData handleEventCallData; + CallType handleEventCallType = handleEventFunction->getCallData(handleEventCallData); + CallData callbackCallData; + CallType callbackCallType = CallTypeNone; + + if (handleEventCallType == CallTypeNone) { + callbackCallType = m_data->callback()->getCallData(callbackCallData); + if (callbackCallType == CallTypeNone) { + // FIXME: Should an exception be thrown here? + return; + } } RefPtr<JSCustomSQLTransactionCallback> protect(this); - List args; + ArgList args; args.append(toJS(exec, transaction)); globalObject->startTimeoutCheck(); - if (handleEventFunc) - handleEventFunc->call(exec, m_data->callback(), args); + if (handleEventCallType != CallTypeNone) + call(exec, handleEventFunction, handleEventCallType, handleEventCallData, m_data->callback(), args); else - m_data->callback()->call(exec, m_data->callback(), args); + call(exec, m_data->callback(), callbackCallType, callbackCallData, m_data->callback(), args); globalObject->stopTimeoutCheck(); if (exec->hadException()) { - JSObject* exception = exec->exception()->toObject(exec); - String message = exception->get(exec, exec->propertyNames().message)->toString(exec); - int lineNumber = exception->get(exec, "line")->toInt32(exec); - String sourceURL = exception->get(exec, "sourceURL")->toString(exec); - if (Interpreter::shouldPrintExceptions()) - printf("SQLTransactionCallback: %s\n", message.utf8().data()); - if (Page* page = m_data->frame()->page()) - page->chrome()->addMessageToConsole(JSMessageSource, ErrorMessageLevel, message, lineNumber, sourceURL); - exec->clearException(); + m_data->frame()->domWindow()->console()->reportCurrentException(exec); raisedException = true; } diff --git a/WebCore/bindings/js/JSCustomSQLTransactionCallback.h b/WebCore/bindings/js/JSCustomSQLTransactionCallback.h index aa31d50..0a21c1a 100644 --- a/WebCore/bindings/js/JSCustomSQLTransactionCallback.h +++ b/WebCore/bindings/js/JSCustomSQLTransactionCallback.h @@ -31,7 +31,9 @@ #include "SQLTransactionCallback.h" -namespace KJS { +#include <wtf/PassRefPtr.h> + +namespace JSC { class JSObject; } @@ -41,12 +43,15 @@ class Frame; class JSCustomSQLTransactionCallback : public SQLTransactionCallback { public: - JSCustomSQLTransactionCallback(KJS::JSObject* callback, Frame*); + static PassRefPtr<JSCustomSQLTransactionCallback> create(JSC::JSObject* callback, Frame* frame) { return adoptRef(new JSCustomSQLTransactionCallback(callback, frame)); } + virtual ~JSCustomSQLTransactionCallback(); virtual void handleEvent(SQLTransaction*, bool& raisedException); private: + JSCustomSQLTransactionCallback(JSC::JSObject* callback, Frame*); + static void deleteData(void*); class Data; diff --git a/WebCore/bindings/js/JSCustomSQLTransactionErrorCallback.cpp b/WebCore/bindings/js/JSCustomSQLTransactionErrorCallback.cpp index ff4d1c1..097f809 100644 --- a/WebCore/bindings/js/JSCustomSQLTransactionErrorCallback.cpp +++ b/WebCore/bindings/js/JSCustomSQLTransactionErrorCallback.cpp @@ -30,14 +30,16 @@ #include "JSCustomSQLTransactionErrorCallback.h" #include "CString.h" +#include "Console.h" +#include "DOMWindow.h" #include "Frame.h" -#include "kjs_proxy.h" +#include "ScriptController.h" #include "JSSQLError.h" -#include "Page.h" +#include <runtime/JSLock.h> namespace WebCore { -using namespace KJS; +using namespace JSC; JSCustomSQLTransactionErrorCallback::JSCustomSQLTransactionErrorCallback(JSObject* callback, Frame* frame) : m_callback(callback) @@ -50,51 +52,38 @@ bool JSCustomSQLTransactionErrorCallback::handleEvent(SQLError* error) ASSERT(m_callback); ASSERT(m_frame); - if (!m_frame->scriptProxy()->isEnabled()) + if (!m_frame->script()->isEnabled()) return true; - JSGlobalObject* globalObject = m_frame->scriptProxy()->globalObject(); + JSGlobalObject* globalObject = m_frame->script()->globalObject(); ExecState* exec = globalObject->globalExec(); - KJS::JSLock lock; + JSC::JSLock lock(false); - JSValue* handleEventFuncValue = m_callback->get(exec, "handleEvent"); - JSObject* handleEventFunc = 0; - if (handleEventFuncValue->isObject()) { - handleEventFunc = static_cast<JSObject*>(handleEventFuncValue); - if (!handleEventFunc->implementsCall()) - handleEventFunc = 0; + JSValue* function = m_callback->get(exec, Identifier(exec, "handleEvent")); + CallData callData; + CallType callType = function->getCallData(callData); + if (callType == CallTypeNone) { + callType = m_callback->getCallData(callData); + if (callType == CallTypeNone) { + // FIXME: Should an exception be thrown here? + return true; + } + function = m_callback; } - - if (!handleEventFunc && !m_callback->implementsCall()) { - // FIXME: Should an exception be thrown here? - return true; - } - + RefPtr<JSCustomSQLTransactionErrorCallback> protect(this); - List args; + ArgList args; args.append(toJS(exec, error)); - JSValue *result; + JSValue* result; globalObject->startTimeoutCheck(); - if (handleEventFunc) - result = handleEventFunc->call(exec, m_callback, args); - else - result = m_callback->call(exec, m_callback, args); + result = call(exec, function, callType, callData, m_callback, args); globalObject->stopTimeoutCheck(); - if (exec->hadException()) { - JSObject* exception = exec->exception()->toObject(exec); - String message = exception->get(exec, exec->propertyNames().message)->toString(exec); - int lineNumber = exception->get(exec, "line")->toInt32(exec); - String sourceURL = exception->get(exec, "sourceURL")->toString(exec); - if (Interpreter::shouldPrintExceptions()) - printf("SQLTransactionErrorCallback: %s\n", message.utf8().data()); - if (Page* page = m_frame->page()) - page->chrome()->addMessageToConsole(JSMessageSource, ErrorMessageLevel, message, lineNumber, sourceURL); - exec->clearException(); - } + if (exec->hadException()) + m_frame->domWindow()->console()->reportCurrentException(exec); Document::updateDocumentsRendering(); diff --git a/WebCore/bindings/js/JSCustomSQLTransactionErrorCallback.h b/WebCore/bindings/js/JSCustomSQLTransactionErrorCallback.h index 6b079c4..bfbb1e2 100644 --- a/WebCore/bindings/js/JSCustomSQLTransactionErrorCallback.h +++ b/WebCore/bindings/js/JSCustomSQLTransactionErrorCallback.h @@ -31,11 +31,11 @@ #include "SQLTransactionErrorCallback.h" -#include <kjs/object.h> +#include <runtime/JSObject.h> #include <kjs/protect.h> #include <wtf/Forward.h> -namespace KJS { +namespace JSC { class JSObject; } @@ -46,11 +46,14 @@ class SQLError; class JSCustomSQLTransactionErrorCallback : public SQLTransactionErrorCallback { public: - JSCustomSQLTransactionErrorCallback(KJS::JSObject* callback, Frame*); + static PassRefPtr<JSCustomSQLTransactionErrorCallback> create(JSC::JSObject* callback, Frame* frame) { return adoptRef(new JSCustomSQLTransactionErrorCallback(callback, frame)); } virtual bool handleEvent(SQLError*); + private: - KJS::ProtectedPtr<KJS::JSObject> m_callback; + JSCustomSQLTransactionErrorCallback(JSC::JSObject* callback, Frame*); + + JSC::ProtectedPtr<JSC::JSObject> m_callback; RefPtr<Frame> m_frame; }; diff --git a/WebCore/bindings/js/JSCustomVoidCallback.cpp b/WebCore/bindings/js/JSCustomVoidCallback.cpp index 7964e59..a838e95 100644 --- a/WebCore/bindings/js/JSCustomVoidCallback.cpp +++ b/WebCore/bindings/js/JSCustomVoidCallback.cpp @@ -30,16 +30,17 @@ #include "JSCustomVoidCallback.h" #include "CString.h" +#include "Console.h" #include "DOMWindow.h" #include "Frame.h" -#include "kjs_binding.h" -#include "kjs_proxy.h" -#include "kjs_window.h" -#include "Page.h" +#include "JSDOMWindowCustom.h" +#include "JSDOMBinding.h" +#include "ScriptController.h" +#include <runtime/JSLock.h> namespace WebCore { -using namespace KJS; +using namespace JSC; JSCustomVoidCallback::JSCustomVoidCallback(JSObject* callback, Frame* frame) : m_callback(callback) @@ -52,67 +53,51 @@ void JSCustomVoidCallback::handleEvent() ASSERT(m_callback); ASSERT(m_frame); - if (!m_frame->scriptProxy()->isEnabled()) + if (!m_frame->script()->isEnabled()) return; - JSGlobalObject* globalObject = m_frame->scriptProxy()->globalObject(); + JSGlobalObject* globalObject = m_frame->script()->globalObject(); ExecState* exec = globalObject->globalExec(); - KJS::JSLock lock; + JSC::JSLock lock(false); - JSValue* handleEventFuncValue = m_callback->get(exec, "handleEvent"); - JSObject* handleEventFunc = 0; - if (handleEventFuncValue->isObject()) { - handleEventFunc = static_cast<JSObject*>(handleEventFuncValue); - if (!handleEventFunc->implementsCall()) - handleEventFunc = 0; - } - - if (!handleEventFunc && !m_callback->implementsCall()) { - // FIXME: Should an exception be thrown here? - return; + JSValue* function = m_callback->get(exec, Identifier(exec, "handleEvent")); + CallData callData; + CallType callType = function->getCallData(callData); + if (callType == CallTypeNone) { + callType = m_callback->getCallData(callData); + if (callType == CallTypeNone) { + // FIXME: Should an exception be thrown here? + return; + } + function = m_callback; } RefPtr<JSCustomVoidCallback> protect(this); - List args; + ArgList args; globalObject->startTimeoutCheck(); - if (handleEventFunc) - handleEventFunc->call(exec, m_callback, args); - else - m_callback->call(exec, m_callback, args); + call(exec, function, callType, callData, m_callback, args); globalObject->stopTimeoutCheck(); - if (exec->hadException()) { - JSObject* exception = exec->exception()->toObject(exec); - String message = exception->get(exec, exec->propertyNames().message)->toString(exec); - int lineNumber = exception->get(exec, "line")->toInt32(exec); - String sourceURL = exception->get(exec, "sourceURL")->toString(exec); - if (Interpreter::shouldPrintExceptions()) - printf("VoidCallback: %s\n", message.utf8().data()); - if (Page* page = m_frame->page()) - page->chrome()->addMessageToConsole(JSMessageSource, ErrorMessageLevel, message, lineNumber, sourceURL); - exec->clearException(); - } + if (exec->hadException()) + m_frame->domWindow()->console()->reportCurrentException(exec); Document::updateDocumentsRendering(); } -VoidCallback* toVoidCallback(ExecState* exec, JSValue* value, bool& ok) +PassRefPtr<VoidCallback> toVoidCallback(ExecState* exec, JSValue* value) { - ok = false; - JSObject* object = value->getObject(); if (!object) return 0; - Frame* frame = Window::retrieveActive(exec)->impl()->frame(); + Frame* frame = asJSDOMWindow(exec->dynamicGlobalObject())->impl()->frame(); if (!frame) return 0; - ok = true; - return new JSCustomVoidCallback(object, frame); + return JSCustomVoidCallback::create(object, frame); } } diff --git a/WebCore/bindings/js/JSCustomVoidCallback.h b/WebCore/bindings/js/JSCustomVoidCallback.h index 1f97f39..9931631 100644 --- a/WebCore/bindings/js/JSCustomVoidCallback.h +++ b/WebCore/bindings/js/JSCustomVoidCallback.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2007 Apple Inc. All rights reserved. + * Copyright (C) 2007, 2008 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -31,30 +31,32 @@ #include "VoidCallback.h" -#include <kjs/object.h> +#include <runtime/JSObject.h> #include <kjs/protect.h> #include <wtf/Forward.h> -namespace KJS { - class JSObject; -} - namespace WebCore { class Frame; - class SQLError; class JSCustomVoidCallback : public VoidCallback { - public: - JSCustomVoidCallback(KJS::JSObject* callback, Frame*); + public: + static PassRefPtr<JSCustomVoidCallback> create(JSC::JSObject* callback, Frame* frame) + { + return adoptRef(new JSCustomVoidCallback(callback, frame)); + } virtual void handleEvent(); + private: - KJS::ProtectedPtr<KJS::JSObject> m_callback; + JSCustomVoidCallback(JSC::JSObject* callback, Frame*); + + JSC::ProtectedPtr<JSC::JSObject> m_callback; RefPtr<Frame> m_frame; }; - - VoidCallback* toVoidCallback(KJS::ExecState*, KJS::JSValue*, bool& ok); -} + + PassRefPtr<VoidCallback> toVoidCallback(JSC::ExecState*, JSC::JSValue*); + +} // namespace WebCore #endif // JSCustomVoidCallback_h diff --git a/WebCore/bindings/js/JSCustomXPathNSResolver.cpp b/WebCore/bindings/js/JSCustomXPathNSResolver.cpp index a8c4788..45c2c18 100644 --- a/WebCore/bindings/js/JSCustomXPathNSResolver.cpp +++ b/WebCore/bindings/js/JSCustomXPathNSResolver.cpp @@ -29,21 +29,21 @@ #if ENABLE(XPATH) #include "CString.h" +#include "Console.h" #include "DOMWindow.h" #include "Document.h" #include "ExceptionCode.h" #include "Frame.h" -#include "Page.h" - -#include "kjs_binding.h" -#include "kjs_proxy.h" -#include "kjs_window.h" +#include "JSDOMWindowCustom.h" +#include "JSDOMBinding.h" +#include "ScriptController.h" +#include <runtime/JSLock.h> namespace WebCore { -using namespace KJS; +using namespace JSC; -PassRefPtr<JSCustomXPathNSResolver> JSCustomXPathNSResolver::create(KJS::ExecState* exec, KJS::JSValue* value) +PassRefPtr<JSCustomXPathNSResolver> JSCustomXPathNSResolver::create(JSC::ExecState* exec, JSC::JSValue* value) { if (value->isUndefinedOrNull()) return 0; @@ -54,7 +54,7 @@ PassRefPtr<JSCustomXPathNSResolver> JSCustomXPathNSResolver::create(KJS::ExecSta return 0; } - return new JSCustomXPathNSResolver(resolverObject, KJS::Window::retrieveActive(exec)->impl()->frame()); + return adoptRef(new JSCustomXPathNSResolver(resolverObject, asJSDOMWindow(exec->dynamicGlobalObject())->impl()->frame())); } JSCustomXPathNSResolver::JSCustomXPathNSResolver(JSObject* customResolver, Frame* frame) @@ -73,54 +73,40 @@ String JSCustomXPathNSResolver::lookupNamespaceURI(const String& prefix) if (!m_frame) return String(); - if (!m_frame->scriptProxy()->isEnabled()) + if (!m_frame->script()->isEnabled()) return String(); - JSLock lock; + JSLock lock(false); - JSGlobalObject* globalObject = m_frame->scriptProxy()->globalObject(); + JSGlobalObject* globalObject = m_frame->script()->globalObject(); ExecState* exec = globalObject->globalExec(); - JSValue* lookupNamespaceURIFuncValue = m_customResolver->get(exec, "lookupNamespaceURI"); - JSObject* lookupNamespaceURIFunc = 0; - if (lookupNamespaceURIFuncValue->isObject()) { - lookupNamespaceURIFunc = static_cast<JSObject*>(lookupNamespaceURIFuncValue); - if (!lookupNamespaceURIFunc->implementsCall()) - lookupNamespaceURIFunc = 0; - } - - if (!lookupNamespaceURIFunc && !m_customResolver->implementsCall()) { - // FIXME: pass actual line number and source URL. - if (Page* page = m_frame->page()) - page->chrome()->addMessageToConsole(JSMessageSource, ErrorMessageLevel, "XPathNSResolver does not have a lookupNamespaceURI method.", 0, String()); - return String(); + JSValue* function = m_customResolver->get(exec, Identifier(exec, "lookupNamespaceURI")); + CallData callData; + CallType callType = function->getCallData(callData); + if (callType == CallTypeNone) { + callType = m_customResolver->getCallData(callData); + if (callType == CallTypeNone) { + // FIXME: Pass actual line number and source URL. + m_frame->domWindow()->console()->addMessage(JSMessageSource, ErrorMessageLevel, "XPathNSResolver does not have a lookupNamespaceURI method.", 0, String()); + return String(); + } + function = m_customResolver; } RefPtr<JSCustomXPathNSResolver> selfProtector(this); - List args; - args.append(jsString(prefix)); + ArgList args; + args.append(jsString(exec, prefix)); - String result; - JSValue* retval; globalObject->startTimeoutCheck(); - if (lookupNamespaceURIFunc) - retval = lookupNamespaceURIFunc->call(exec, m_customResolver, args); - else - retval = m_customResolver->call(exec, m_customResolver, args); + JSValue* retval = call(exec, function, callType, callData, m_customResolver, args); globalObject->stopTimeoutCheck(); - if (exec->hadException()) { - JSObject* exception = exec->exception()->toObject(exec); - String message = exception->get(exec, exec->propertyNames().message)->toString(exec); - int lineNumber = exception->get(exec, "line")->toInt32(exec); - String sourceURL = exception->get(exec, "sourceURL")->toString(exec); - if (Interpreter::shouldPrintExceptions()) - printf("XPathNSResolver: %s\n", message.utf8().data()); - if (Page* page = m_frame->page()) - page->chrome()->addMessageToConsole(JSMessageSource, ErrorMessageLevel, message, lineNumber, sourceURL); - exec->clearException(); - } else { + String result; + if (exec->hadException()) + m_frame->domWindow()->console()->reportCurrentException(exec); + else { if (!retval->isUndefinedOrNull()) result = retval->toString(exec); } diff --git a/WebCore/bindings/js/JSCustomXPathNSResolver.h b/WebCore/bindings/js/JSCustomXPathNSResolver.h index 023e893..bb8aed8 100644 --- a/WebCore/bindings/js/JSCustomXPathNSResolver.h +++ b/WebCore/bindings/js/JSCustomXPathNSResolver.h @@ -29,13 +29,13 @@ #if ENABLE(XPATH) #include "XPathNSResolver.h" +#include <runtime/JSValue.h> #include <wtf/Forward.h> #include <wtf/RefPtr.h> -namespace KJS { +namespace JSC { class ExecState; class JSObject; - class JSValue; } namespace WebCore { @@ -44,17 +44,17 @@ namespace WebCore { class JSCustomXPathNSResolver : public XPathNSResolver { public: + static PassRefPtr<JSCustomXPathNSResolver> create(JSC::ExecState*, JSC::JSValue*); - static PassRefPtr<JSCustomXPathNSResolver> create(KJS::ExecState*, KJS::JSValue*); - - JSCustomXPathNSResolver(KJS::JSObject*, Frame*); virtual ~JSCustomXPathNSResolver(); virtual String lookupNamespaceURI(const String& prefix); private: - KJS::JSObject* m_customResolver; // JSCustomXPathNSResolvers are always temporary, thus no need to GC protect the object. - RefPtr<Frame> m_frame; + JSCustomXPathNSResolver(JSC::JSObject*, Frame*); + + JSC::JSObject* m_customResolver; // JSCustomXPathNSResolvers are always temporary, thus no need to GC protect the object. + RefPtr<Frame> m_frame; }; } // namespace WebCore diff --git a/WebCore/bindings/js/JSDOMApplicationCacheCustom.cpp b/WebCore/bindings/js/JSDOMApplicationCacheCustom.cpp new file mode 100644 index 0000000..c79b0d9 --- /dev/null +++ b/WebCore/bindings/js/JSDOMApplicationCacheCustom.cpp @@ -0,0 +1,133 @@ +/* + * Copyright (C) 2008 Apple Inc. All Rights Reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "JSDOMApplicationCache.h" + +#if ENABLE(OFFLINE_WEB_APPLICATIONS) + +#include "AtomicString.h" +#include "DOMApplicationCache.h" +#include "DOMWindow.h" +#include "Event.h" +#include "Frame.h" +#include "FrameLoader.h" +#include "JSDOMWindowCustom.h" +#include "JSEvent.h" +#include "JSEventListener.h" + +using namespace JSC; + +namespace WebCore { + +void JSDOMApplicationCache::mark() +{ + DOMObject::mark(); + + if (JSUnprotectedEventListener* listener = static_cast<JSUnprotectedEventListener*>(m_impl->onchecking())) + listener->mark(); + + if (JSUnprotectedEventListener* listener = static_cast<JSUnprotectedEventListener*>(m_impl->onerror())) + listener->mark(); + + if (JSUnprotectedEventListener* listener = static_cast<JSUnprotectedEventListener*>(m_impl->onnoupdate())) + listener->mark(); + + if (JSUnprotectedEventListener* listener = static_cast<JSUnprotectedEventListener*>(m_impl->ondownloading())) + listener->mark(); + + if (JSUnprotectedEventListener* listener = static_cast<JSUnprotectedEventListener*>(m_impl->onprogress())) + listener->mark(); + + if (JSUnprotectedEventListener* listener = static_cast<JSUnprotectedEventListener*>(m_impl->onupdateready())) + listener->mark(); + + if (JSUnprotectedEventListener* listener = static_cast<JSUnprotectedEventListener*>(m_impl->oncached())) + listener->mark(); + + typedef DOMApplicationCache::EventListenersMap EventListenersMap; + typedef DOMApplicationCache::ListenerVector ListenerVector; + EventListenersMap& eventListeners = m_impl->eventListeners(); + for (EventListenersMap::iterator mapIter = eventListeners.begin(); mapIter != eventListeners.end(); ++mapIter) { + for (ListenerVector::iterator vecIter = mapIter->second.begin(); vecIter != mapIter->second.end(); ++vecIter) { + JSUnprotectedEventListener* listener = static_cast<JSUnprotectedEventListener*>(vecIter->get()); + listener->mark(); + } + } +} + +JSValue* JSDOMApplicationCache::add(ExecState* exec, const ArgList& args) +{ + Frame* frame = asJSDOMWindow(exec->dynamicGlobalObject())->impl()->frame(); + if (!frame) + return jsUndefined(); + const KURL& url = frame->loader()->completeURL(args.at(exec, 0)->toString(exec)); + + ExceptionCode ec = 0; + impl()->add(url, ec); + setDOMException(exec, ec); + return jsUndefined(); +} + +JSValue* JSDOMApplicationCache::remove(ExecState* exec, const ArgList& args) +{ + Frame* frame = asJSDOMWindow(exec->dynamicGlobalObject())->impl()->frame(); + if (!frame) + return jsUndefined(); + const KURL& url = frame->loader()->completeURL(args.at(exec, 0)->toString(exec)); + + ExceptionCode ec = 0; + impl()->remove(url, ec); + setDOMException(exec, ec); + return jsUndefined(); +} + +JSValue* JSDOMApplicationCache::addEventListener(ExecState* exec, const ArgList& args) +{ + JSDOMGlobalObject* globalObject = toJSDOMGlobalObject(impl()->scriptExecutionContext()); + if (!globalObject) + return jsUndefined(); + RefPtr<JSUnprotectedEventListener> listener = globalObject->findOrCreateJSUnprotectedEventListener(exec, args.at(exec, 1)); + if (!listener) + return jsUndefined(); + impl()->addEventListener(args.at(exec, 0)->toString(exec), listener.release(), args.at(exec, 2)->toBoolean(exec)); + return jsUndefined(); +} + +JSValue* JSDOMApplicationCache::removeEventListener(ExecState* exec, const ArgList& args) +{ + JSDOMGlobalObject* globalObject = toJSDOMGlobalObject(impl()->scriptExecutionContext()); + if (!globalObject) + return jsUndefined(); + JSUnprotectedEventListener* listener = globalObject->findJSUnprotectedEventListener(exec, args.at(exec, 1)); + if (!listener) + return jsUndefined(); + impl()->removeEventListener(args.at(exec, 0)->toString(exec), listener, args.at(exec, 2)->toBoolean(exec)); + return jsUndefined(); +} + +} // namespace WebCore + +#endif // ENABLE(OFFLINE_WEB_APPLICATIONS) diff --git a/WebCore/bindings/js/JSDOMBinding.cpp b/WebCore/bindings/js/JSDOMBinding.cpp new file mode 100644 index 0000000..8676146 --- /dev/null +++ b/WebCore/bindings/js/JSDOMBinding.cpp @@ -0,0 +1,548 @@ +/* + * Copyright (C) 1999-2001 Harri Porten (porten@kde.org) + * Copyright (C) 2004, 2005, 2006, 2007, 2008 Apple Inc. All rights reserved. + * Copyright (C) 2007 Samuel Weinig <sam@webkit.org> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +// gcc 3.x can't handle including the HashMap pointer specialization in this file +#if defined __GNUC__ && !defined __GLIBCXX__ // less than gcc 3.4 +#define HASH_MAP_PTR_SPEC_WORKAROUND 1 +#endif + +#include "config.h" +#include "JSDOMBinding.h" + +#include "ActiveDOMObject.h" +#include "DOMCoreException.h" +#include "Document.h" +#include "EventException.h" +#include "ExceptionCode.h" +#include "Frame.h" +#include "HTMLImageElement.h" +#include "HTMLNames.h" +#include "JSDOMCoreException.h" +#include "JSDOMWindowCustom.h" +#include "JSEventException.h" +#include "JSNode.h" +#include "JSRangeException.h" +#include "JSXMLHttpRequestException.h" +#include "KURL.h" +#include "MessagePort.h" +#include "RangeException.h" +#include "ScriptController.h" +#include "XMLHttpRequestException.h" +#include <runtime/PrototypeFunction.h> + +#if ENABLE(SVG) +#include "JSSVGException.h" +#include "SVGException.h" +#endif + +#if ENABLE(XPATH) +#include "JSXPathException.h" +#include "XPathException.h" +#endif + +#if ENABLE(WORKERS) +#include <wtf/ThreadSpecific.h> +using namespace WTF; +#endif + +using namespace JSC; + +namespace WebCore { + +using namespace HTMLNames; + +typedef Document::JSWrapperCache JSWrapperCache; + +// For debugging, keep a set of wrappers currently registered, and check that +// all are unregistered before they are destroyed. This has helped us fix at +// least one bug. + +static void addWrapper(DOMObject* wrapper); +static void removeWrapper(DOMObject* wrapper); +static void removeWrappers(const JSWrapperCache& wrappers); + +#ifdef NDEBUG + +static inline void addWrapper(DOMObject*) +{ +} + +static inline void removeWrapper(DOMObject*) +{ +} + +static inline void removeWrappers(const JSWrapperCache&) +{ +} + +#else + +static HashSet<DOMObject*>& wrapperSet() +{ +#if ENABLE(WORKERS) + static ThreadSpecific<HashSet<DOMObject*> > staticWrapperSet; + return *staticWrapperSet; +#else + static HashSet<DOMObject*> staticWrapperSet; + return staticWrapperSet; +#endif +} + +static void addWrapper(DOMObject* wrapper) +{ + ASSERT(!wrapperSet().contains(wrapper)); + wrapperSet().add(wrapper); +} + +static void removeWrapper(DOMObject* wrapper) +{ + if (!wrapper) + return; + ASSERT(wrapperSet().contains(wrapper)); + wrapperSet().remove(wrapper); +} + +static void removeWrappers(const JSWrapperCache& wrappers) +{ + for (JSWrapperCache::const_iterator it = wrappers.begin(); it != wrappers.end(); ++it) + removeWrapper(it->second); +} + +DOMObject::~DOMObject() +{ + ASSERT(!wrapperSet().contains(this)); +} + +#endif + +class DOMObjectWrapperMap { +public: + static DOMObjectWrapperMap& mapFor(JSGlobalData&); + + DOMObject* get(void* objectHandle) + { + return m_map.get(objectHandle); + } + + void set(void* objectHandle, DOMObject* wrapper) + { + addWrapper(wrapper); + m_map.set(objectHandle, wrapper); + } + + void remove(void* objectHandle) + { + removeWrapper(m_map.take(objectHandle)); + } + +private: + HashMap<void*, DOMObject*> m_map; +}; + +// Map from static HashTable instances to per-GlobalData ones. +class DOMObjectHashTableMap { +public: + static DOMObjectHashTableMap& mapFor(JSGlobalData&); + + ~DOMObjectHashTableMap() + { + HashMap<const JSC::HashTable*, JSC::HashTable>::iterator mapEnd = m_map.end(); + for (HashMap<const JSC::HashTable*, JSC::HashTable>::iterator iter = m_map.begin(); iter != m_map.end(); ++iter) + iter->second.deleteTable(); + } + + const JSC::HashTable* get(const JSC::HashTable* staticTable) + { + HashMap<const JSC::HashTable*, JSC::HashTable>::iterator iter = m_map.find(staticTable); + if (iter != m_map.end()) + return &iter->second; + return &m_map.set(staticTable, JSC::HashTable(*staticTable)).first->second; + } + +private: + HashMap<const JSC::HashTable*, JSC::HashTable> m_map; +}; + +class WebCoreJSClientData : public JSGlobalData::ClientData { +public: + DOMObjectHashTableMap hashTableMap; + DOMObjectWrapperMap wrapperMap; +}; + +DOMObjectHashTableMap& DOMObjectHashTableMap::mapFor(JSGlobalData& globalData) +{ + JSGlobalData::ClientData* clientData = globalData.clientData; + if (!clientData) { + clientData = new WebCoreJSClientData; + globalData.clientData = clientData; + } + return static_cast<WebCoreJSClientData*>(clientData)->hashTableMap; +} + +const JSC::HashTable* getHashTableForGlobalData(JSGlobalData& globalData, const JSC::HashTable* staticTable) +{ + return DOMObjectHashTableMap::mapFor(globalData).get(staticTable); +} + +inline DOMObjectWrapperMap& DOMObjectWrapperMap::mapFor(JSGlobalData& globalData) +{ + JSGlobalData::ClientData* clientData = globalData.clientData; + if (!clientData) { + clientData = new WebCoreJSClientData; + globalData.clientData = clientData; + } + return static_cast<WebCoreJSClientData*>(clientData)->wrapperMap; +} + +DOMObject* getCachedDOMObjectWrapper(JSGlobalData& globalData, void* objectHandle) +{ + return DOMObjectWrapperMap::mapFor(globalData).get(objectHandle); +} + +void cacheDOMObjectWrapper(JSGlobalData& globalData, void* objectHandle, DOMObject* wrapper) +{ + DOMObjectWrapperMap::mapFor(globalData).set(objectHandle, wrapper); +} + +void forgetDOMObject(JSGlobalData& globalData, void* objectHandle) +{ + DOMObjectWrapperMap::mapFor(globalData).remove(objectHandle); +} + +JSNode* getCachedDOMNodeWrapper(Document* document, Node* node) +{ + if (!document) + return static_cast<JSNode*>(DOMObjectWrapperMap::mapFor(*JSDOMWindow::commonJSGlobalData()).get(node)); + return document->wrapperCache().get(node); +} + +void forgetDOMNode(Document* document, Node* node) +{ + if (!document) { + DOMObjectWrapperMap::mapFor(*JSDOMWindow::commonJSGlobalData()).remove(node); + return; + } + removeWrapper(document->wrapperCache().take(node)); +} + +void cacheDOMNodeWrapper(Document* document, Node* node, JSNode* wrapper) +{ + if (!document) { + DOMObjectWrapperMap::mapFor(*JSDOMWindow::commonJSGlobalData()).set(node, wrapper); + return; + } + addWrapper(wrapper); + document->wrapperCache().set(node, wrapper); +} + +void forgetAllDOMNodesForDocument(Document* document) +{ + ASSERT(document); + removeWrappers(document->wrapperCache()); +} + +void markDOMNodesForDocument(Document* doc) +{ + // If a node's JS wrapper holds custom properties, those properties must + // persist every time the node is fetched from the DOM. So, we keep JS + // wrappers like that from being garbage collected. + + JSWrapperCache& nodeDict = doc->wrapperCache(); + JSWrapperCache::iterator nodeEnd = nodeDict.end(); + for (JSWrapperCache::iterator nodeIt = nodeDict.begin(); nodeIt != nodeEnd; ++nodeIt) { + JSNode* jsNode = nodeIt->second; + Node* node = jsNode->impl(); + + if (jsNode->marked()) + continue; + + // No need to preserve a wrapper that has no custom properties or is no + // longer fetchable through the DOM. + if (!jsNode->hasCustomProperties() || !node->inDocument()) { + //... unless the wrapper wraps a loading image, since the "new Image" + // syntax allows an orphan image wrapper to be the last reference + // to a loading image, whose load event might have important side-effects. + if (!node->hasTagName(imgTag) || static_cast<HTMLImageElement*>(node)->haveFiredLoadEvent()) + continue; + } + + jsNode->mark(); + } +} + +void markActiveObjectsForContext(JSGlobalData& globalData, ScriptExecutionContext* scriptExecutionContext) +{ + // If an element has pending activity that may result in listeners being called + // (e.g. an XMLHttpRequest), we need to keep all JS wrappers alive. + + const HashMap<ActiveDOMObject*, void*>& activeObjects = scriptExecutionContext->activeDOMObjects(); + HashMap<ActiveDOMObject*, void*>::const_iterator activeObjectsEnd = activeObjects.end(); + for (HashMap<ActiveDOMObject*, void*>::const_iterator iter = activeObjects.begin(); iter != activeObjectsEnd; ++iter) { + if (iter->first->hasPendingActivity()) { + DOMObject* wrapper = getCachedDOMObjectWrapper(globalData, iter->second); + // An object with pending activity must have a wrapper to mark its listeners, so no null check. + if (!wrapper->marked()) + wrapper->mark(); + } + } + + const HashSet<MessagePort*>& messagePorts = scriptExecutionContext->messagePorts(); + HashSet<MessagePort*>::const_iterator portsEnd = messagePorts.end(); + for (HashSet<MessagePort*>::const_iterator iter = messagePorts.begin(); iter != portsEnd; ++iter) { + if ((*iter)->hasPendingActivity()) { + DOMObject* wrapper = getCachedDOMObjectWrapper(globalData, *iter); + // An object with pending activity must have a wrapper to mark its listeners, so no null check. + if (!wrapper->marked()) + wrapper->mark(); + } + } +} + +void markCrossHeapDependentObjectsForContext(JSGlobalData& globalData, ScriptExecutionContext* scriptExecutionContext) +{ + const HashSet<MessagePort*>& messagePorts = scriptExecutionContext->messagePorts(); + HashSet<MessagePort*>::const_iterator portsEnd = messagePorts.end(); + for (HashSet<MessagePort*>::const_iterator iter = messagePorts.begin(); iter != portsEnd; ++iter) { + MessagePort* port = *iter; + RefPtr<MessagePort> entangledPort = port->entangledPort(); + if (entangledPort) { + // No wrapper, or wrapper is already marked - no need to examine cross-heap dependencies. + DOMObject* wrapper = getCachedDOMObjectWrapper(globalData, port); + if (!wrapper || wrapper->marked()) + continue; + + // Don't use cross-heap model of marking on same-heap pairs. Otherwise, they will never be destroyed, because a port will mark its entangled one, + // and it will never get a chance to be marked as inaccessible. So, the port will keep getting marked in this function. + if ((port->scriptExecutionContext() == entangledPort->scriptExecutionContext()) || (port->scriptExecutionContext()->isDocument() && entangledPort->scriptExecutionContext()->isDocument())) + continue; + + // If the wrapper hasn't been marked during the mark phase of GC, then the port shouldn't protect its entangled one. + // It's important not to call this when there is no wrapper. E.g., if GC is triggered after a MessageChannel is created, but before its ports are used from JS, + // irreversibly telling the object that its (not yet existing) wrapper is inaccessible would be wrong. Similarly, ports posted via postMessage() may not + // have wrappers until delivered. + port->setJSWrapperIsInaccessible(); + + // If the port is protected by its entangled one, mark it. + // This is an atomic read of a boolean value, no synchronization between threads is required (at least on platforms that guarantee cache coherency). + if (!entangledPort->jsWrapperIsInaccessible()) + wrapper->mark(); + } + } +} + +void updateDOMNodeDocument(Node* node, Document* oldDocument, Document* newDocument) +{ + ASSERT(oldDocument != newDocument); + JSNode* wrapper = getCachedDOMNodeWrapper(oldDocument, node); + if (!wrapper) + return; + removeWrapper(wrapper); + cacheDOMNodeWrapper(newDocument, node, wrapper); + forgetDOMNode(oldDocument, node); + addWrapper(wrapper); +} + +void markDOMObjectWrapper(JSGlobalData& globalData, void* object) +{ + if (!object) + return; + DOMObject* wrapper = getCachedDOMObjectWrapper(globalData, object); + if (!wrapper || wrapper->marked()) + return; + wrapper->mark(); +} + +JSValue* jsStringOrNull(ExecState* exec, const String& s) +{ + if (s.isNull()) + return jsNull(); + return jsString(exec, s); +} + +JSValue* jsOwnedStringOrNull(ExecState* exec, const UString& s) +{ + if (s.isNull()) + return jsNull(); + return jsOwnedString(exec, s); +} + +JSValue* jsStringOrUndefined(ExecState* exec, const String& s) +{ + if (s.isNull()) + return jsUndefined(); + return jsString(exec, s); +} + +JSValue* jsStringOrFalse(ExecState* exec, const String& s) +{ + if (s.isNull()) + return jsBoolean(false); + return jsString(exec, s); +} + +JSValue* jsStringOrNull(ExecState* exec, const KURL& url) +{ + if (url.isNull()) + return jsNull(); + return jsString(exec, url.string()); +} + +JSValue* jsStringOrUndefined(ExecState* exec, const KURL& url) +{ + if (url.isNull()) + return jsUndefined(); + return jsString(exec, url.string()); +} + +JSValue* jsStringOrFalse(ExecState* exec, const KURL& url) +{ + if (url.isNull()) + return jsBoolean(false); + return jsString(exec, url.string()); +} + +UString valueToStringWithNullCheck(ExecState* exec, JSValue* value) +{ + if (value->isNull()) + return UString(); + return value->toString(exec); +} + +UString valueToStringWithUndefinedOrNullCheck(ExecState* exec, JSValue* value) +{ + if (value->isUndefinedOrNull()) + return UString(); + return value->toString(exec); +} + +void setDOMException(ExecState* exec, ExceptionCode ec) +{ + if (!ec || exec->hadException()) + return; + + ExceptionCodeDescription description; + getExceptionCodeDescription(ec, description); + + JSValue* errorObject = noValue(); + switch (description.type) { + case DOMExceptionType: + errorObject = toJS(exec, DOMCoreException::create(description)); + break; + case RangeExceptionType: + errorObject = toJS(exec, RangeException::create(description)); + break; + case EventExceptionType: + errorObject = toJS(exec, EventException::create(description)); + break; + case XMLHttpRequestExceptionType: + errorObject = toJS(exec, XMLHttpRequestException::create(description)); + break; +#if ENABLE(SVG) + case SVGExceptionType: + errorObject = toJS(exec, SVGException::create(description).get(), 0); + break; +#endif +#if ENABLE(XPATH) + case XPathExceptionType: + errorObject = toJS(exec, XPathException::create(description)); + break; +#endif + } + + ASSERT(errorObject); + exec->setException(errorObject); +} + +bool checkNodeSecurity(ExecState* exec, Node* node) +{ + return node && allowsAccessFromFrame(exec, node->document()->frame()); +} + +bool allowsAccessFromFrame(ExecState* exec, Frame* frame) +{ + if (!frame) + return false; + JSDOMWindow* window = toJSDOMWindow(frame); + return window && window->allowsAccessFrom(exec); +} + +bool allowsAccessFromFrame(ExecState* exec, Frame* frame, String& message) +{ + if (!frame) + return false; + JSDOMWindow* window = toJSDOMWindow(frame); + return window && window->allowsAccessFrom(exec, message); +} + +void printErrorMessageForFrame(Frame* frame, const String& message) +{ + if (!frame) + return; + if (JSDOMWindow* window = toJSDOMWindow(frame)) + window->printErrorMessage(message); +} + +JSValue* objectToStringFunctionGetter(ExecState* exec, const Identifier& propertyName, const PropertySlot&) +{ + return new (exec) PrototypeFunction(exec, 0, propertyName, objectProtoFuncToString); +} + +ExecState* execStateFromNode(Node* node) +{ + if (!node) + return 0; + Document* document = node->document(); + if (!document) + return 0; + Frame* frame = document->frame(); + if (!frame) + return 0; + if (!frame->script()->isEnabled()) + return 0; + return frame->script()->globalObject()->globalExec(); +} + +StructureID* getCachedDOMStructure(ExecState* exec, const ClassInfo* classInfo) +{ + JSDOMStructureMap& structures = static_cast<JSDOMGlobalObject*>(exec->lexicalGlobalObject())->structures(); + return structures.get(classInfo).get(); +} + +StructureID* cacheDOMStructure(ExecState* exec, PassRefPtr<StructureID> structureID, const ClassInfo* classInfo) +{ + JSDOMStructureMap& structures = static_cast<JSDOMGlobalObject*>(exec->lexicalGlobalObject())->structures(); + ASSERT(!structures.contains(classInfo)); + return structures.set(classInfo, structureID).first->second.get(); +} + +JSObject* getCachedDOMConstructor(ExecState* exec, const ClassInfo* classInfo) +{ + JSDOMConstructorMap& constructors = static_cast<JSDOMGlobalObject*>(exec->lexicalGlobalObject())->constructors(); + return constructors.get(classInfo); +} + +void cacheDOMConstructor(ExecState* exec, const ClassInfo* classInfo, JSObject* constructor) +{ + JSDOMConstructorMap& constructors = static_cast<JSDOMGlobalObject*>(exec->lexicalGlobalObject())->constructors(); + ASSERT(!constructors.contains(classInfo)); + constructors.set(classInfo, constructor); +} + +} // namespace WebCore diff --git a/WebCore/bindings/js/JSDOMBinding.h b/WebCore/bindings/js/JSDOMBinding.h new file mode 100644 index 0000000..e8040f2 --- /dev/null +++ b/WebCore/bindings/js/JSDOMBinding.h @@ -0,0 +1,185 @@ +/* + * Copyright (C) 1999-2001 Harri Porten (porten@kde.org) + * Copyright (C) 2003, 2004, 2005, 2006, 2008 Apple Inc. All rights reserved. + * Copyright (C) 2007 Samuel Weinig <sam@webkit.org> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#ifndef JSDOMBinding_h +#define JSDOMBinding_h + +#include "JSDOMGlobalObject.h" +#include <kjs/interpreter.h> +#include <kjs/lookup.h> +#include <runtime/JSFunction.h> +#include <wtf/Noncopyable.h> + +namespace JSC { + class JSGlobalData; +} + +namespace WebCore { + + class Document; + class Frame; + class KURL; + class Node; + class String; + class JSNode; + + typedef int ExceptionCode; + +#if ENABLE(SVG) + class SVGElement; +#endif + + // Base class for all objects in this binding except Window. + class DOMObject : public JSC::JSObject { + protected: + explicit DOMObject(PassRefPtr<JSC::StructureID> structureID) + : JSObject(structureID) + { + } + +#ifndef NDEBUG + virtual ~DOMObject(); +#endif + }; + + DOMObject* getCachedDOMObjectWrapper(JSC::JSGlobalData&, void* objectHandle); + void cacheDOMObjectWrapper(JSC::JSGlobalData&, void* objectHandle, DOMObject* wrapper); + void forgetDOMObject(JSC::JSGlobalData&, void* objectHandle); + + JSNode* getCachedDOMNodeWrapper(Document*, Node*); + void cacheDOMNodeWrapper(Document*, Node*, JSNode* wrapper); + void forgetDOMNode(Document*, Node*); + void forgetAllDOMNodesForDocument(Document*); + void updateDOMNodeDocument(Node*, Document* oldDocument, Document* newDocument); + void markDOMNodesForDocument(Document*); + void markActiveObjectsForContext(JSC::JSGlobalData&, ScriptExecutionContext*); + void markDOMObjectWrapper(JSC::JSGlobalData& globalData, void* object); + void markCrossHeapDependentObjectsForContext(JSC::JSGlobalData&, ScriptExecutionContext*); + + JSC::StructureID* getCachedDOMStructure(JSC::ExecState*, const JSC::ClassInfo*); + JSC::StructureID* cacheDOMStructure(JSC::ExecState*, PassRefPtr<JSC::StructureID>, const JSC::ClassInfo*); + + JSC::JSObject* getCachedDOMConstructor(JSC::ExecState*, const JSC::ClassInfo*); + void cacheDOMConstructor(JSC::ExecState*, const JSC::ClassInfo*, JSC::JSObject* constructor); + + template<class WrapperClass> inline JSC::StructureID* getDOMStructure(JSC::ExecState* exec) + { + if (JSC::StructureID* structure = getCachedDOMStructure(exec, &WrapperClass::s_info)) + return structure; + return cacheDOMStructure(exec, WrapperClass::createStructureID(WrapperClass::createPrototype(exec)), &WrapperClass::s_info); + } + template<class WrapperClass> inline JSC::JSObject* getDOMPrototype(JSC::ExecState* exec) + { + return static_cast<JSC::JSObject*>(asObject(getDOMStructure<WrapperClass>(exec)->storedPrototype())); + } + #define CREATE_DOM_OBJECT_WRAPPER(exec, className, object) createDOMObjectWrapper<JS##className>(exec, static_cast<className*>(object)) + template<class WrapperClass, class DOMClass> inline DOMObject* createDOMObjectWrapper(JSC::ExecState* exec, DOMClass* object) + { + ASSERT(object); + ASSERT(!getCachedDOMObjectWrapper(exec->globalData(), object)); + WrapperClass* wrapper = new (exec) WrapperClass(getDOMStructure<WrapperClass>(exec), object); + cacheDOMObjectWrapper(exec->globalData(), object, wrapper); + return wrapper; + } + template<class WrapperClass, class DOMClass> inline JSC::JSValue* getDOMObjectWrapper(JSC::ExecState* exec, DOMClass* object) + { + if (!object) + return JSC::jsNull(); + if (DOMObject* wrapper = getCachedDOMObjectWrapper(exec->globalData(), object)) + return wrapper; + return createDOMObjectWrapper<WrapperClass>(exec, object); + } + +#if ENABLE(SVG) + #define CREATE_SVG_OBJECT_WRAPPER(exec, className, object, context) createDOMObjectWrapper<JS##className>(exec, static_cast<className*>(object), context) + template<class WrapperClass, class DOMClass> inline DOMObject* createDOMObjectWrapper(JSC::ExecState* exec, DOMClass* object, SVGElement* context) + { + ASSERT(object); + ASSERT(!getCachedDOMObjectWrapper(exec->globalData(), object)); + WrapperClass* wrapper = new (exec) WrapperClass(getDOMStructure<WrapperClass>(exec), object, context); + cacheDOMObjectWrapper(exec->globalData(), object, wrapper); + return wrapper; + } + template<class WrapperClass, class DOMClass> inline JSC::JSValue* getDOMObjectWrapper(JSC::ExecState* exec, DOMClass* object, SVGElement* context) + { + if (!object) + return JSC::jsNull(); + if (DOMObject* wrapper = getCachedDOMObjectWrapper(exec->globalData(), object)) + return wrapper; + return createDOMObjectWrapper<WrapperClass>(exec, object, context); + } +#endif + + #define CREATE_DOM_NODE_WRAPPER(exec, className, object) createDOMNodeWrapper<JS##className>(exec, static_cast<className*>(object)) + template<class WrapperClass, class DOMClass> inline JSNode* createDOMNodeWrapper(JSC::ExecState* exec, DOMClass* node) + { + ASSERT(node); + ASSERT(!getCachedDOMNodeWrapper(node->document(), node)); + WrapperClass* wrapper = new (exec) WrapperClass(getDOMStructure<WrapperClass>(exec), node); + cacheDOMNodeWrapper(node->document(), node, wrapper); + return wrapper; + } + template<class WrapperClass, class DOMClass> inline JSC::JSValue* getDOMNodeWrapper(JSC::ExecState* exec, DOMClass* node) + { + if (!node) + return JSC::jsNull(); + if (JSNode* wrapper = getCachedDOMNodeWrapper(node->document(), node)) + return wrapper; + return createDOMNodeWrapper<WrapperClass>(exec, node); + } + + const JSC::HashTable* getHashTableForGlobalData(JSC::JSGlobalData&, const JSC::HashTable* staticTable); + + // Convert a DOM implementation exception code into a JavaScript exception in the execution state. + void setDOMException(JSC::ExecState*, ExceptionCode); + + JSC::JSValue* jsStringOrNull(JSC::ExecState*, const String&); // null if the string is null + JSC::JSValue* jsStringOrNull(JSC::ExecState*, const KURL&); // null if the URL is null + + JSC::JSValue* jsStringOrUndefined(JSC::ExecState*, const String&); // undefined if the string is null + JSC::JSValue* jsStringOrUndefined(JSC::ExecState*, const KURL&); // undefined if the URL is null + + JSC::JSValue* jsStringOrFalse(JSC::ExecState*, const String&); // boolean false if the string is null + JSC::JSValue* jsStringOrFalse(JSC::ExecState*, const KURL&); // boolean false if the URL is null + + // See JavaScriptCore for explanation: Should be used for any UString that is already owned by another + // object, to let the engine know that collecting the JSString wrapper is unlikely to save memory. + JSC::JSValue* jsOwnedStringOrNull(JSC::ExecState*, const JSC::UString&); + + JSC::UString valueToStringWithNullCheck(JSC::ExecState*, JSC::JSValue*); // null if the value is null + JSC::UString valueToStringWithUndefinedOrNullCheck(JSC::ExecState*, JSC::JSValue*); // null if the value is null or undefined + + template <typename T> inline JSC::JSValue* toJS(JSC::ExecState* exec, PassRefPtr<T> ptr) { return toJS(exec, ptr.get()); } + + bool checkNodeSecurity(JSC::ExecState*, Node*); + + // Helpers for Window, History, and Location classes to implement cross-domain policy. + // Besides the cross-domain check, they need non-caching versions of staticFunctionGetter for + // because we do not want current property values involved at all. + bool allowsAccessFromFrame(JSC::ExecState*, Frame*); + bool allowsAccessFromFrame(JSC::ExecState*, Frame*, String& message); + void printErrorMessageForFrame(Frame*, const String& message); + JSC::JSValue* objectToStringFunctionGetter(JSC::ExecState*, const JSC::Identifier& propertyName, const JSC::PropertySlot&); + + JSC::ExecState* execStateFromNode(Node*); + +} // namespace WebCore + +#endif // JSDOMBinding_h diff --git a/WebCore/bindings/js/JSDOMGlobalObject.cpp b/WebCore/bindings/js/JSDOMGlobalObject.cpp new file mode 100644 index 0000000..d9dae37 --- /dev/null +++ b/WebCore/bindings/js/JSDOMGlobalObject.cpp @@ -0,0 +1,168 @@ +/* + * Copyright (C) 2008 Apple Inc. All Rights Reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +#include "config.h" +#include "JSDOMGlobalObject.h" + +#include "Document.h" +#include "JSDOMWindow.h" +#include "JSEventListener.h" + +using namespace JSC; + +namespace WebCore { + +JSDOMGlobalObject::JSDOMGlobalObjectData::JSDOMGlobalObjectData() + : evt(0) +{ +} + +JSDOMGlobalObject::JSDOMGlobalObject(PassRefPtr<StructureID> structure, JSDOMGlobalObject::JSDOMGlobalObjectData* data, JSObject* thisValue) + : JSGlobalObject(structure, data, thisValue) +{ +} + +JSDOMGlobalObject::~JSDOMGlobalObject() +{ + // Clear any backpointers to the window + ListenersMap::iterator i1 = d()->jsEventListeners.begin(); + ListenersMap::iterator e1 = d()->jsEventListeners.end(); + for (; i1 != e1; ++i1) + i1->second->clearGlobalObject(); + + i1 = d()->jsInlineEventListeners.begin(); + e1 = d()->jsInlineEventListeners.end(); + for (; i1 != e1; ++i1) + i1->second->clearGlobalObject(); + + UnprotectedListenersMap::iterator i2 = d()->jsUnprotectedEventListeners.begin(); + UnprotectedListenersMap::iterator e2 = d()->jsUnprotectedEventListeners.end(); + for (; i2 != e2; ++i2) + i2->second->clearGlobalObject(); + + i2 = d()->jsUnprotectedInlineEventListeners.begin(); + e2 = d()->jsUnprotectedInlineEventListeners.end(); + for (; i2 != e2; ++i2) + i2->second->clearGlobalObject(); +} + +void JSDOMGlobalObject::mark() +{ + Base::mark(); + + JSDOMStructureMap::iterator end = structures().end(); + for (JSDOMStructureMap::iterator it = structures().begin(); it != end; ++it) + it->second->mark(); + + JSDOMConstructorMap::iterator end2 = constructors().end(); + for (JSDOMConstructorMap::iterator it2 = constructors().begin(); it2 != end2; ++it2) { + if (!it2->second->marked()) + it2->second->mark(); + } +} + +JSEventListener* JSDOMGlobalObject::findJSEventListener(JSValue* val, bool isInline) +{ + if (!val->isObject()) + return 0; + JSObject* object = asObject(val); + ListenersMap& listeners = isInline ? d()->jsInlineEventListeners : d()->jsEventListeners; + return listeners.get(object); +} + +PassRefPtr<JSEventListener> JSDOMGlobalObject::findOrCreateJSEventListener(ExecState* exec, JSValue* val, bool isInline) +{ + if (JSEventListener* listener = findJSEventListener(val, isInline)) + return listener; + + if (!val->isObject()) + return 0; + + // The JSEventListener constructor adds it to our jsEventListeners map. + return JSEventListener::create(asObject(val), this, isInline).get(); +} + +JSUnprotectedEventListener* JSDOMGlobalObject::findJSUnprotectedEventListener(ExecState* exec, JSValue* val, bool isInline) +{ + if (!val->isObject()) + return 0; + + UnprotectedListenersMap& listeners = isInline ? d()->jsUnprotectedInlineEventListeners : d()->jsUnprotectedEventListeners; + return listeners.get(asObject(val)); +} + +PassRefPtr<JSUnprotectedEventListener> JSDOMGlobalObject::findOrCreateJSUnprotectedEventListener(ExecState* exec, JSValue* val, bool isInline) +{ + if (JSUnprotectedEventListener* listener = findJSUnprotectedEventListener(exec, val, isInline)) + return listener; + + if (!val->isObject()) + return 0; + + // The JSUnprotectedEventListener constructor adds it to our jsUnprotectedEventListeners map. + return JSUnprotectedEventListener::create(asObject(val), this, isInline).get(); +} + +JSDOMGlobalObject::ListenersMap& JSDOMGlobalObject::jsEventListeners() +{ + return d()->jsEventListeners; +} + +JSDOMGlobalObject::ListenersMap& JSDOMGlobalObject::jsInlineEventListeners() +{ + return d()->jsInlineEventListeners; +} + +JSDOMGlobalObject::UnprotectedListenersMap& JSDOMGlobalObject::jsUnprotectedEventListeners() +{ + return d()->jsUnprotectedEventListeners; +} + +JSDOMGlobalObject::UnprotectedListenersMap& JSDOMGlobalObject::jsUnprotectedInlineEventListeners() +{ + return d()->jsUnprotectedInlineEventListeners; +} + +void JSDOMGlobalObject::setCurrentEvent(Event* evt) +{ + d()->evt = evt; +} + +Event* JSDOMGlobalObject::currentEvent() +{ + return d()->evt; +} + +JSDOMGlobalObject* toJSDOMGlobalObject(ScriptExecutionContext* scriptExecutionContext) +{ + if (scriptExecutionContext->isDocument()) + return toJSDOMWindow(static_cast<Document*>(scriptExecutionContext)->frame()); + + // Not implemented yet. + return 0; +} + +} // namespace WebCore diff --git a/WebCore/bindings/js/JSDOMGlobalObject.h b/WebCore/bindings/js/JSDOMGlobalObject.h new file mode 100644 index 0000000..3c210bb --- /dev/null +++ b/WebCore/bindings/js/JSDOMGlobalObject.h @@ -0,0 +1,125 @@ +/* + * Copyright (C) 2008 Apple Inc. All Rights Reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +#ifndef JSDOMGlobalObject_h +#define JSDOMGlobalObject_h + +#include <runtime/JSGlobalObject.h> + +namespace WebCore { + + class Event; + class JSEventListener; + class JSUnprotectedEventListener; + class ScriptExecutionContext; + + typedef HashMap<const JSC::ClassInfo*, RefPtr<JSC::StructureID> > JSDOMStructureMap; + typedef HashMap<const JSC::ClassInfo*, JSC::JSObject*> JSDOMConstructorMap; + + class JSDOMGlobalObject : public JSC::JSGlobalObject { + typedef JSC::JSGlobalObject Base; + protected: + struct JSDOMGlobalObjectData; + + JSDOMGlobalObject(PassRefPtr<JSC::StructureID>, JSDOMGlobalObjectData*, JSC::JSObject* thisValue); + virtual ~JSDOMGlobalObject(); + + public: + JSDOMStructureMap& structures() { return d()->structures; } + JSDOMConstructorMap& constructors() const { return d()->constructors; } + + virtual ScriptExecutionContext* scriptExecutionContext() const = 0; + + // Finds a wrapper of a JS EventListener, returns 0 if no existing one. + JSEventListener* findJSEventListener(JSC::JSValue*, bool isInline = false); + + // Finds or creates a wrapper of a JS EventListener. JS EventListener object is GC-protected. + PassRefPtr<JSEventListener> findOrCreateJSEventListener(JSC::ExecState*, JSC::JSValue*, bool isInline = false); + + // Finds a wrapper of a GC-unprotected JS EventListener, returns 0 if no existing one. + JSUnprotectedEventListener* findJSUnprotectedEventListener(JSC::ExecState*, JSC::JSValue*, bool isInline = false); + + // Finds or creates a wrapper of a JS EventListener. JS EventListener object is *NOT* GC-protected. + PassRefPtr<JSUnprotectedEventListener> findOrCreateJSUnprotectedEventListener(JSC::ExecState*, JSC::JSValue*, bool isInline = false); + + typedef HashMap<JSC::JSObject*, JSEventListener*> ListenersMap; + typedef HashMap<JSC::JSObject*, JSUnprotectedEventListener*> UnprotectedListenersMap; + + ListenersMap& jsEventListeners(); + ListenersMap& jsInlineEventListeners(); + UnprotectedListenersMap& jsUnprotectedEventListeners(); + UnprotectedListenersMap& jsUnprotectedInlineEventListeners(); + + void setCurrentEvent(Event*); + Event* currentEvent(); + + virtual void mark(); + + protected: + struct JSDOMGlobalObjectData : public JSC::JSGlobalObject::JSGlobalObjectData { + JSDOMGlobalObjectData(); + + JSDOMStructureMap structures; + JSDOMConstructorMap constructors; + + JSDOMGlobalObject::ListenersMap jsEventListeners; + JSDOMGlobalObject::ListenersMap jsInlineEventListeners; + JSDOMGlobalObject::UnprotectedListenersMap jsUnprotectedEventListeners; + JSDOMGlobalObject::UnprotectedListenersMap jsUnprotectedInlineEventListeners; + + Event* evt; + }; + + private: + JSDOMGlobalObjectData* d() const { return static_cast<JSDOMGlobalObjectData*>(JSC::JSVariableObject::d); } + }; + + template<class ConstructorClass> + inline JSC::JSObject* getDOMConstructor(JSC::ExecState* exec) + { + if (JSC::JSObject* constructor = getCachedDOMConstructor(exec, &ConstructorClass::s_info)) + return constructor; + JSC::JSObject* constructor = new (exec) ConstructorClass(exec); + cacheDOMConstructor(exec, &ConstructorClass::s_info, constructor); + return constructor; + } + + template<class ConstructorClass> + inline JSC::JSObject* getDOMConstructor(JSC::ExecState* exec, JSDOMGlobalObject* globalObject) + { + if (JSC::JSObject* constructor = globalObject->constructors().get(&ConstructorClass::s_info)) + return constructor; + JSC::JSObject* constructor = new (exec) ConstructorClass(exec, globalObject->scriptExecutionContext()); + ASSERT(!globalObject->constructors().contains(&ConstructorClass::s_info)); + globalObject->constructors().set(&ConstructorClass::s_info, constructor); + return constructor; + } + + JSDOMGlobalObject* toJSDOMGlobalObject(ScriptExecutionContext*); + +} // namespace WebCore + +#endif // JSDOMGlobalObject_h diff --git a/WebCore/bindings/js/JSDOMWindowBase.cpp b/WebCore/bindings/js/JSDOMWindowBase.cpp new file mode 100644 index 0000000..4ec39cd --- /dev/null +++ b/WebCore/bindings/js/JSDOMWindowBase.cpp @@ -0,0 +1,1039 @@ +/* + * Copyright (C) 2000 Harri Porten (porten@kde.org) + * Copyright (C) 2006 Jon Shier (jshier@iastate.edu) + * Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008 Apple Inc. All rights reseved. + * Copyright (C) 2006 Alexey Proskuryakov (ap@webkit.org) + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 + * USA + */ + +#include "config.h" +#include "JSDOMWindowBase.h" + +#include "CString.h" +#include "Console.h" +#include "DOMWindow.h" +#include "Element.h" +#include "EventListener.h" +#include "ExceptionCode.h" +#include "FloatRect.h" +#include "Frame.h" +#include "FrameLoadRequest.h" +#include "FrameLoader.h" +#include "FrameTree.h" +#include "GCController.h" +#include "HTMLDocument.h" +#include "InspectorController.h" +#include "JSAudioConstructor.h" +#include "JSDedicatedWorkerConstructor.h" +#include "JSDOMWindowCustom.h" +#include "JSEvent.h" +#include "JSEventListener.h" +#include "JSHTMLCollection.h" +#include "JSImageConstructor.h" +#include "JSMessageChannelConstructor.h" +#include "JSNode.h" +#include "JSOptionConstructor.h" +#include "JSXMLHttpRequestConstructor.h" +#include "JSXSLTProcessorConstructor.h" +#include "Logging.h" +#include "MediaPlayer.h" +#include "Page.h" +#include "PausedTimeouts.h" +#include "PlatformScreen.h" +#include "PluginInfoStore.h" +#include "RenderView.h" +#include "ScheduledAction.h" +#include "ScriptController.h" +#include "SecurityOrigin.h" +#include "Settings.h" +#include "WindowFeatures.h" +#include "htmlediting.h" +#include <runtime/Error.h> +#include <runtime/JSLock.h> +#include <wtf/AlwaysInline.h> +#include <wtf/MathExtras.h> + +using namespace JSC; + +static JSValue* windowProtoFuncOpen(ExecState*, JSObject*, JSValue*, const ArgList&); +static JSValue* windowProtoFuncShowModalDialog(ExecState*, JSObject*, JSValue*, const ArgList&); +static JSValue* windowProtoFuncNotImplemented(ExecState*, JSObject*, JSValue*, const ArgList&); + +static JSValue* jsDOMWindowBaseCrypto(ExecState*, const Identifier&, const PropertySlot&); +static JSValue* jsDOMWindowBaseEvent(ExecState*, const Identifier&, const PropertySlot&); +static void setJSDOMWindowBaseEvent(ExecState*, JSObject*, JSValue*); + +// Constructors +static JSValue* jsDOMWindowBaseAudio(ExecState*, const Identifier&, const PropertySlot&); +static void setJSDOMWindowBaseAudio(ExecState*, JSObject*, JSValue*); +static JSValue* jsDOMWindowBaseImage(ExecState*, const Identifier&, const PropertySlot&); +static void setJSDOMWindowBaseImage(ExecState*, JSObject*, JSValue*); +static JSValue* jsDOMWindowBaseMessageChannel(ExecState*, const Identifier&, const PropertySlot&); +static void setJSDOMWindowBaseMessageChannel(ExecState*, JSObject*, JSValue*); +static JSValue* jsDOMWindowBaseWorker(ExecState*, const Identifier&, const PropertySlot&); +static void setJSDOMWindowBaseWorker(ExecState*, JSObject*, JSValue*); +static JSValue* jsDOMWindowBaseOption(ExecState*, const Identifier&, const PropertySlot&); +static void setJSDOMWindowBaseOption(ExecState*, JSObject*, JSValue*); +static JSValue* jsDOMWindowBaseXMLHttpRequest(ExecState*, const Identifier&, const PropertySlot&); +static void setJSDOMWindowBaseXMLHttpRequest(ExecState*, JSObject*, JSValue*); +static JSValue* jsDOMWindowBaseXSLTProcessor(ExecState*, const Identifier&, const PropertySlot&); +static void setJSDOMWindowBaseXSLTProcessor(ExecState*, JSObject*, JSValue*); + +#include "JSDOMWindowBase.lut.h" + +namespace WebCore { + +static int lastUsedTimeoutId; + +static int timerNestingLevel = 0; +const int cMaxTimerNestingLevel = 5; +const double cMinimumTimerInterval = 0.010; + +class DOMWindowTimer : public TimerBase { +public: + DOMWindowTimer(int timeoutId, int nestingLevel, JSDOMWindowBase* object, ScheduledAction* action) + : m_timeoutId(timeoutId) + , m_nestingLevel(nestingLevel) + , m_object(object) + , m_action(action) + { + } + + virtual ~DOMWindowTimer() + { + JSLock lock(false); + delete m_action; + } + + int timeoutId() const { return m_timeoutId; } + + int nestingLevel() const { return m_nestingLevel; } + void setNestingLevel(int n) { m_nestingLevel = n; } + + ScheduledAction* action() const { return m_action; } + ScheduledAction* takeAction() { ScheduledAction* a = m_action; m_action = 0; return a; } + +private: + virtual void fired(); + + int m_timeoutId; + int m_nestingLevel; + JSDOMWindowBase* m_object; + ScheduledAction* m_action; +}; + +////////////////////// JSDOMWindowBase Object //////////////////////// + +const ClassInfo JSDOMWindowBase::s_info = { "Window", 0, &JSDOMWindowBaseTable, 0 }; + +/* +@begin JSDOMWindowBaseTable +# -- Functions -- + open windowProtoFuncOpen DontDelete|Function 3 + showModalDialog windowProtoFuncShowModalDialog DontDelete|Function 1 +# Not implemented + captureEvents windowProtoFuncNotImplemented DontDelete|Function 0 + releaseEvents windowProtoFuncNotImplemented DontDelete|Function 0 +# -- Attributes -- + crypto jsDOMWindowBaseCrypto DontDelete|ReadOnly + event jsDOMWindowBaseEvent DontDelete +# -- Constructors -- + Audio jsDOMWindowBaseAudio DontDelete + Image jsDOMWindowBaseImage DontDelete + MessageChannel jsDOMWindowBaseMessageChannel DontDelete + Option jsDOMWindowBaseOption DontDelete + Worker jsDOMWindowBaseWorker DontDelete + XMLHttpRequest jsDOMWindowBaseXMLHttpRequest DontDelete + XSLTProcessor jsDOMWindowBaseXSLTProcessor DontDelete +@end +*/ + +JSDOMWindowBase::JSDOMWindowBaseData::JSDOMWindowBaseData(PassRefPtr<DOMWindow> window, JSDOMWindowShell* shell) + : impl(window) + , returnValueSlot(0) + , shell(shell) +{ +} + +JSDOMWindowBase::JSDOMWindowBase(PassRefPtr<StructureID> structure, PassRefPtr<DOMWindow> window, JSDOMWindowShell* shell) + : JSDOMGlobalObject(structure, new JSDOMWindowBaseData(window, shell), shell) +{ + // Time in milliseconds before the script timeout handler kicks in. + setTimeoutTime(10000); + + GlobalPropertyInfo staticGlobals[] = { + GlobalPropertyInfo(Identifier(globalExec(), "document"), jsNull(), DontDelete | ReadOnly), + GlobalPropertyInfo(Identifier(globalExec(), "window"), d()->shell, DontDelete | ReadOnly) + }; + + addStaticGlobals(staticGlobals, sizeof(staticGlobals) / sizeof(GlobalPropertyInfo)); +} + +void JSDOMWindowBase::updateDocument() +{ + ASSERT(d()->impl->document()); + ExecState* exec = globalExec(); + symbolTablePutWithAttributes(Identifier(exec, "document"), toJS(exec, d()->impl->document()), DontDelete | ReadOnly); +} + +JSDOMWindowBase::~JSDOMWindowBase() +{ + if (d()->impl->frame()) + d()->impl->frame()->script()->clearFormerWindow(asJSDOMWindow(this)); + + clearAllTimeouts(); +} + +ScriptExecutionContext* JSDOMWindowBase::scriptExecutionContext() const +{ + return d()->impl->document(); +} + +static bool allowPopUp(ExecState* exec) +{ + Frame* frame = asJSDOMWindow(exec->dynamicGlobalObject())->impl()->frame(); + + ASSERT(frame); + if (frame->script()->processingUserGesture()) + return true; + Settings* settings = frame->settings(); + return settings && settings->JavaScriptCanOpenWindowsAutomatically(); +} + +static HashMap<String, String> parseModalDialogFeatures(const String& featuresArg) +{ + HashMap<String, String> map; + + Vector<String> features; + featuresArg.split(';', features); + Vector<String>::const_iterator end = features.end(); + for (Vector<String>::const_iterator it = features.begin(); it != end; ++it) { + String s = *it; + int pos = s.find('='); + int colonPos = s.find(':'); + if (pos >= 0 && colonPos >= 0) + continue; // ignore any strings that have both = and : + if (pos < 0) + pos = colonPos; + if (pos < 0) { + // null string for value means key without value + map.set(s.stripWhiteSpace().lower(), String()); + } else { + String key = s.left(pos).stripWhiteSpace().lower(); + String val = s.substring(pos + 1).stripWhiteSpace().lower(); + int spacePos = val.find(' '); + if (spacePos != -1) + val = val.left(spacePos); + map.set(key, val); + } + } + + return map; +} + +static Frame* createWindow(ExecState* exec, Frame* openerFrame, const String& url, + const String& frameName, const WindowFeatures& windowFeatures, JSValue* dialogArgs) +{ + Frame* activeFrame = asJSDOMWindow(exec->dynamicGlobalObject())->impl()->frame(); + ASSERT(activeFrame); + + ResourceRequest request; + + request.setHTTPReferrer(activeFrame->loader()->outgoingReferrer()); + FrameLoader::addHTTPOriginIfNeeded(request, activeFrame->loader()->outgoingOrigin()); + FrameLoadRequest frameRequest(request, frameName); + + // FIXME: It's much better for client API if a new window starts with a URL, here where we + // know what URL we are going to open. Unfortunately, this code passes the empty string + // for the URL, but there's a reason for that. Before loading we have to set up the opener, + // openedByDOM, and dialogArguments values. Also, to decide whether to use the URL we currently + // do an allowsAccessFrom call using the window we create, which can't be done before creating it. + // We'd have to resolve all those issues to pass the URL instead of "". + + bool created; + // We pass in the opener frame here so it can be used for looking up the frame name, in case the active frame + // is different from the opener frame, and the name references a frame relative to the opener frame, for example + // "_self" or "_parent". + Frame* newFrame = activeFrame->loader()->createWindow(openerFrame->loader(), frameRequest, windowFeatures, created); + if (!newFrame) + return 0; + + newFrame->loader()->setOpener(openerFrame); + newFrame->loader()->setOpenedByDOM(); + + JSDOMWindow* newWindow = toJSDOMWindow(newFrame); + + if (dialogArgs) + newWindow->putDirect(Identifier(exec, "dialogArguments"), dialogArgs); + + if (!protocolIs(url, "javascript") || newWindow->allowsAccessFrom(exec)) { + KURL completedURL = url.isEmpty() ? KURL("") : activeFrame->document()->completeURL(url); + bool userGesture = activeFrame->script()->processingUserGesture(); + + if (created) + newFrame->loader()->changeLocation(completedURL, activeFrame->loader()->outgoingReferrer(), false, userGesture); + else if (!url.isEmpty()) + newFrame->loader()->scheduleLocationChange(completedURL.string(), activeFrame->loader()->outgoingReferrer(), false, userGesture); + } + + return newFrame; +} + +static bool canShowModalDialog(const Frame* frame) +{ + if (!frame) + return false; + +#ifdef ANDROID_FIX + // Note for integration: this fix came from Webkit + Page* page = frame->page(); + if (!page) + return false; + + return page->chrome()->canRunModal(); +#else + return frame->page()->chrome()->canRunModal(); +#endif +} + +static bool canShowModalDialogNow(const Frame* frame) +{ + if (!frame) + return false; + +#ifdef ANDROID_FIX + // Note for integration: this fix came from Webkit + Page* page = frame->page(); + if (!page) + return false; + + return page->chrome()->canRunModalNow(); +#else + return frame->page()->chrome()->canRunModalNow(); +#endif +} + +static JSValue* showModalDialog(ExecState* exec, Frame* frame, const String& url, JSValue* dialogArgs, const String& featureArgs) +{ + if (!canShowModalDialogNow(frame) || !allowPopUp(exec)) + return jsUndefined(); + + const HashMap<String, String> features = parseModalDialogFeatures(featureArgs); + + const bool trusted = false; + + // The following features from Microsoft's documentation are not implemented: + // - default font settings + // - width, height, left, and top specified in units other than "px" + // - edge (sunken or raised, default is raised) + // - dialogHide: trusted && boolFeature(features, "dialoghide"), makes dialog hide when you print + // - help: boolFeature(features, "help", true), makes help icon appear in dialog (what does it do on Windows?) + // - unadorned: trusted && boolFeature(features, "unadorned"); + + if (!frame) + return jsUndefined(); + + FloatRect screenRect = screenAvailableRect(frame->view()); + + WindowFeatures wargs; + wargs.width = WindowFeatures::floatFeature(features, "dialogwidth", 100, screenRect.width(), 620); // default here came from frame size of dialog in MacIE + wargs.widthSet = true; + wargs.height = WindowFeatures::floatFeature(features, "dialogheight", 100, screenRect.height(), 450); // default here came from frame size of dialog in MacIE + wargs.heightSet = true; + + wargs.x = WindowFeatures::floatFeature(features, "dialogleft", screenRect.x(), screenRect.right() - wargs.width, -1); + wargs.xSet = wargs.x > 0; + wargs.y = WindowFeatures::floatFeature(features, "dialogtop", screenRect.y(), screenRect.bottom() - wargs.height, -1); + wargs.ySet = wargs.y > 0; + + if (WindowFeatures::boolFeature(features, "center", true)) { + if (!wargs.xSet) { + wargs.x = screenRect.x() + (screenRect.width() - wargs.width) / 2; + wargs.xSet = true; + } + if (!wargs.ySet) { + wargs.y = screenRect.y() + (screenRect.height() - wargs.height) / 2; + wargs.ySet = true; + } + } + + wargs.dialog = true; + wargs.resizable = WindowFeatures::boolFeature(features, "resizable"); + wargs.scrollbarsVisible = WindowFeatures::boolFeature(features, "scroll", true); + wargs.statusBarVisible = WindowFeatures::boolFeature(features, "status", !trusted); + wargs.menuBarVisible = false; + wargs.toolBarVisible = false; + wargs.locationBarVisible = false; + wargs.fullscreen = false; + + Frame* dialogFrame = createWindow(exec, frame, url, "", wargs, dialogArgs); + if (!dialogFrame) + return jsUndefined(); + + JSDOMWindow* dialogWindow = toJSDOMWindow(dialogFrame); + + // Get the return value either just before clearing the dialog window's + // properties (in JSDOMWindowBase::clear), or when on return from runModal. + JSValue* returnValue = noValue(); + dialogWindow->setReturnValueSlot(&returnValue); + dialogFrame->page()->chrome()->runModal(); + dialogWindow->setReturnValueSlot(0); + + // If we don't have a return value, get it now. + // Either JSDOMWindowBase::clear was not called yet, or there was no return value, + // and in that case, there's no harm in trying again (no benefit either). + if (!returnValue) + returnValue = dialogWindow->getDirect(Identifier(exec, "returnValue")); + + return returnValue ? returnValue : jsUndefined(); +} + +} // namespace WebCore + +using namespace WebCore; + +JSValue* jsDOMWindowBaseCrypto(ExecState*, const Identifier&, const PropertySlot&) +{ + return jsUndefined(); // FIXME: implement this +} + +JSValue* jsDOMWindowBaseEvent(ExecState* exec, const Identifier&, const PropertySlot& slot) +{ + if (!static_cast<JSDOMWindowBase*>(asObject(slot.slotBase()))->allowsAccessFrom(exec)) + return jsUndefined(); + if (!static_cast<JSDOMWindowBase*>(asObject(slot.slotBase()))->currentEvent()) + return jsUndefined(); + return toJS(exec, static_cast<JSDOMWindowBase*>(asObject(slot.slotBase()))->currentEvent()); +} + +JSValue* jsDOMWindowBaseImage(ExecState* exec, const Identifier&, const PropertySlot& slot) +{ + if (!static_cast<JSDOMWindowBase*>(asObject(slot.slotBase()))->allowsAccessFrom(exec)) + return jsUndefined(); + return getDOMConstructor<JSImageConstructor>(exec, static_cast<JSDOMWindowBase*>(asObject(slot.slotBase()))); +} + +JSValue* jsDOMWindowBaseMessageChannel(ExecState* exec, const Identifier&, const PropertySlot& slot) +{ + if (!static_cast<JSDOMWindowBase*>(asObject(slot.slotBase()))->allowsAccessFrom(exec)) + return jsUndefined(); + return getDOMConstructor<JSMessageChannelConstructor>(exec, static_cast<JSDOMWindowBase*>(asObject(slot.slotBase()))); +} + +JSValue* jsDOMWindowBaseOption(ExecState* exec, const Identifier&, const PropertySlot& slot) +{ + if (!static_cast<JSDOMWindowBase*>(asObject(slot.slotBase()))->allowsAccessFrom(exec)) + return jsUndefined(); + return getDOMConstructor<JSOptionConstructor>(exec, static_cast<JSDOMWindowBase*>(asObject(slot.slotBase()))); +} + +JSValue* jsDOMWindowBaseXMLHttpRequest(ExecState* exec, const Identifier&, const PropertySlot& slot) +{ + if (!static_cast<JSDOMWindowBase*>(asObject(slot.slotBase()))->allowsAccessFrom(exec)) + return jsUndefined(); + return getDOMConstructor<JSXMLHttpRequestConstructor>(exec, static_cast<JSDOMWindowBase*>(asObject(slot.slotBase()))); +} + +JSValue* jsDOMWindowBaseAudio(ExecState* exec, const Identifier&, const PropertySlot& slot) +{ +#if ENABLE(VIDEO) + if (!static_cast<JSDOMWindowBase*>(asObject(slot.slotBase()))->allowsAccessFrom(exec)) + return jsUndefined(); + if (!MediaPlayer::isAvailable()) + return jsUndefined(); + return getDOMConstructor<JSAudioConstructor>(exec, static_cast<JSDOMWindowBase*>(asObject(slot.slotBase()))); +#else + return jsUndefined(); +#endif +} + +JSValue* jsDOMWindowBaseWorker(ExecState* exec, const Identifier&, const PropertySlot& slot) +{ +#if ENABLE(WORKERS) + if (!static_cast<JSDOMWindowBase*>(asObject(slot.slotBase()))->allowsAccessFrom(exec)) + return jsUndefined(); + return getDOMConstructor<JSDedicatedWorkerConstructor>(exec); +#else + return jsUndefined(); +#endif +} + +JSValue* jsDOMWindowBaseXSLTProcessor(ExecState* exec, const Identifier&, const PropertySlot& slot) +{ +#if ENABLE(XSLT) + if (!static_cast<JSDOMWindowBase*>(asObject(slot.slotBase()))->allowsAccessFrom(exec)) + return jsUndefined(); + return getDOMConstructor<JSXSLTProcessorConstructor>(exec); +#else + return jsUndefined(); +#endif +} + +namespace WebCore { + +JSValue* JSDOMWindowBase::childFrameGetter(ExecState* exec, const Identifier& propertyName, const PropertySlot& slot) +{ + return toJS(exec, static_cast<JSDOMWindowBase*>(asObject(slot.slotBase()))->impl()->frame()->tree()->child(AtomicString(propertyName))->domWindow()); +} + +JSValue* JSDOMWindowBase::indexGetter(ExecState* exec, const Identifier&, const PropertySlot& slot) +{ + return toJS(exec, static_cast<JSDOMWindowBase*>(asObject(slot.slotBase()))->impl()->frame()->tree()->child(slot.index())->domWindow()); +} + +JSValue* JSDOMWindowBase::namedItemGetter(ExecState* exec, const Identifier& propertyName, const PropertySlot& slot) +{ + JSDOMWindowBase* thisObj = static_cast<JSDOMWindowBase*>(asObject(slot.slotBase())); + Document* doc = thisObj->impl()->frame()->document(); + ASSERT(thisObj->allowsAccessFrom(exec)); + ASSERT(doc); + ASSERT(doc->isHTMLDocument()); + + RefPtr<HTMLCollection> collection = doc->windowNamedItems(propertyName); + if (collection->length() == 1) + return toJS(exec, collection->firstItem()); + return toJS(exec, collection.get()); +} + +void JSDOMWindowBase::markCrossHeapDependentObjects() +{ + Document* document = impl()->document(); + if (!document) + return; + + markCrossHeapDependentObjectsForContext(*globalData(), document); +} + +bool JSDOMWindowBase::getOwnPropertySlot(ExecState* exec, const Identifier& propertyName, PropertySlot& slot) +{ + // Check for child frames by name before built-in properties to + // match Mozilla. This does not match IE, but some sites end up + // naming frames things that conflict with window properties that + // are in Moz but not IE. Since we have some of these, we have to do + // it the Moz way. + if (impl()->frame()->tree()->child(propertyName)) { + slot.setCustom(this, childFrameGetter); + return true; + } + + const HashEntry* entry = JSDOMWindowBaseTable.entry(exec, propertyName); + if (entry) { + if (entry->attributes() & Function) { + if (entry->function() == windowProtoFuncShowModalDialog) { + if (!canShowModalDialog(impl()->frame())) + return false; + } + if (allowsAccessFrom(exec)) + setUpStaticFunctionSlot(exec, entry, this, propertyName, slot); + else + slot.setUndefined(); + } else + slot.setCustom(this, entry->propertyGetter()); + return true; + } + + // Do prototype lookup early so that functions and attributes in the prototype can have + // precedence over the index and name getters. + JSValue* proto = prototype(); + if (proto->isObject()) { + if (asObject(proto)->getPropertySlot(exec, propertyName, slot)) { + if (!allowsAccessFrom(exec)) + slot.setUndefined(); + return true; + } + } + + // FIXME: Search the whole frame hierachy somewhere around here. + // We need to test the correct priority order. + + // allow window[1] or parent[1] etc. (#56983) + bool ok; + unsigned i = propertyName.toArrayIndex(&ok); + if (ok && i < impl()->frame()->tree()->childCount()) { + slot.setCustomIndex(this, i, indexGetter); + return true; + } + + if (!allowsAccessFrom(exec)) { + slot.setUndefined(); + return true; + } + + // Allow shortcuts like 'Image1' instead of document.images.Image1 + Document* document = impl()->frame()->document(); + if (document && document->isHTMLDocument()) { + AtomicStringImpl* atomicPropertyName = AtomicString::find(propertyName); + if (atomicPropertyName && (static_cast<HTMLDocument*>(document)->hasNamedItem(atomicPropertyName) || document->hasElementWithId(atomicPropertyName))) { + slot.setCustom(this, namedItemGetter); + return true; + } + } + + return Base::getOwnPropertySlot(exec, propertyName, slot); +} + +void JSDOMWindowBase::put(ExecState* exec, const Identifier& propertyName, JSValue* value, PutPropertySlot& slot) +{ + const HashEntry* entry = JSDOMWindowBaseTable.entry(exec, propertyName); + if (entry) { + if (entry->attributes() & Function) { + if (allowsAccessFrom(exec)) + Base::put(exec, propertyName, value, slot); + return; + } + if (entry->attributes() & ReadOnly) + return; + + // Don't call the put function for replacable properties. + if (!(entry->propertyPutter() == setJSDOMWindowBaseEvent + || entry->propertyPutter() == setJSDOMWindowBaseAudio + || entry->propertyPutter() == setJSDOMWindowBaseImage + || entry->propertyPutter() == setJSDOMWindowBaseOption + || entry->propertyPutter() == setJSDOMWindowBaseMessageChannel + || entry->propertyPutter() == setJSDOMWindowBaseWorker + || entry->propertyPutter() == setJSDOMWindowBaseXMLHttpRequest + || entry->propertyPutter() == setJSDOMWindowBaseXSLTProcessor)) { + entry->propertyPutter()(exec, this, value); + return; + } + } + + if (allowsAccessFrom(exec)) + Base::put(exec, propertyName, value, slot); +} + +} // namespace WebCore + +void setJSDOMWindowBaseEvent(ExecState*, JSObject*, JSValue*) +{ + ASSERT_NOT_REACHED(); +} + +void setJSDOMWindowBaseAudio(ExecState*, JSObject*, JSValue*) +{ + ASSERT_NOT_REACHED(); +} + +void setJSDOMWindowBaseImage(ExecState*, JSObject*, JSValue*) +{ + ASSERT_NOT_REACHED(); +} + +void setJSDOMWindowBaseMessageChannel(ExecState*, JSObject*, JSValue*) +{ + ASSERT_NOT_REACHED(); +} + +void setJSDOMWindowBaseOption(ExecState*, JSObject*, JSValue*) +{ + ASSERT_NOT_REACHED(); +} + +void setJSDOMWindowBaseWorker(ExecState*, JSObject*, JSValue*) +{ + ASSERT_NOT_REACHED(); +} + +void setJSDOMWindowBaseXMLHttpRequest(ExecState*, JSObject*, JSValue*) +{ + ASSERT_NOT_REACHED(); +} + +void setJSDOMWindowBaseXSLTProcessor(ExecState*, JSObject*, JSValue*) +{ + ASSERT_NOT_REACHED(); +} + +namespace WebCore { + +String JSDOMWindowBase::crossDomainAccessErrorMessage(const JSGlobalObject* other) const +{ + KURL originURL = asJSDOMWindow(other)->impl()->url(); + KURL targetURL = impl()->frame()->document()->url(); + if (originURL.isNull() || targetURL.isNull()) + return String(); + + // FIXME: this error message should contain more specifics of why the same origin check has failed. + return String::format("Unsafe JavaScript attempt to access frame with URL %s from frame with URL %s. Domains, protocols and ports must match.\n", + targetURL.string().utf8().data(), originURL.string().utf8().data()); +} + +void JSDOMWindowBase::printErrorMessage(const String& message) const +{ + if (message.isEmpty()) + return; + + Frame* frame = impl()->frame(); + if (!frame) + return; + + Settings* settings = frame->settings(); + if (!settings) + return; + + if (settings->privateBrowsingEnabled()) + return; + + impl()->console()->addMessage(JSMessageSource, ErrorMessageLevel, message, 1, String()); // FIXME: provide a real line number and source URL. +} + +ExecState* JSDOMWindowBase::globalExec() +{ + // We need to make sure that any script execution happening in this + // frame does not destroy it + if (Frame *frame = impl()->frame()) + frame->keepAlive(); + return Base::globalExec(); +} + +bool JSDOMWindowBase::supportsProfiling() const +{ + Frame* frame = impl()->frame(); + if (!frame) + return false; + + Page* page = frame->page(); + if (!page) + return false; + + return page->inspectorController()->profilerEnabled(); +} + +bool JSDOMWindowBase::shouldInterruptScript() const +{ + ASSERT(impl()->frame()); + Page* page = impl()->frame()->page(); + + // See <rdar://problem/5479443>. We don't think that page can ever be NULL + // in this case, but if it is, we've gotten into a state where we may have + // hung the UI, with no way to ask the client whether to cancel execution. + // For now, our solution is just to cancel execution no matter what, + // ensuring that we never hang. We might want to consider other solutions + // if we discover problems with this one. + ASSERT(page); + if (!page) + return true; + + return page->chrome()->shouldInterruptJavaScript(); +} + +void JSDOMWindowBase::clearHelperObjectProperties() +{ + setCurrentEvent(0); +} + +void JSDOMWindowBase::clear() +{ + JSLock lock(false); + + if (d()->returnValueSlot && !*d()->returnValueSlot) + *d()->returnValueSlot = getDirect(Identifier(globalExec(), "returnValue")); + + clearAllTimeouts(); + clearHelperObjectProperties(); +} + +JSObject* JSDOMWindowBase::toThisObject(ExecState*) const +{ + return shell(); +} + +JSDOMWindowShell* JSDOMWindowBase::shell() const +{ + return d()->shell; +} + +JSGlobalData* JSDOMWindowBase::commonJSGlobalData() +{ + static JSGlobalData* globalData = JSGlobalData::createLeaked().releaseRef(); + return globalData; +} + +} // namespace WebCore + +using namespace WebCore; + +JSValue* windowProtoFuncOpen(ExecState* exec, JSObject*, JSValue* thisValue, const ArgList& args) +{ + JSDOMWindow* window = toJSDOMWindow(thisValue); + if (!window) + return throwError(exec, TypeError); + if (!window->allowsAccessFrom(exec)) + return jsUndefined(); + + Frame* frame = window->impl()->frame(); + if (!frame) + return jsUndefined(); + Frame* activeFrame = asJSDOMWindow(exec->dynamicGlobalObject())->impl()->frame(); + if (!activeFrame) + return jsUndefined(); + + Page* page = frame->page(); + + String urlString = valueToStringWithUndefinedOrNullCheck(exec, args.at(exec, 0)); + AtomicString frameName = args.at(exec, 1)->isUndefinedOrNull() ? "_blank" : AtomicString(args.at(exec, 1)->toString(exec)); + + // Because FrameTree::find() returns true for empty strings, we must check for empty framenames. + // Otherwise, illegitimate window.open() calls with no name will pass right through the popup blocker. + if (!allowPopUp(exec) && (frameName.isEmpty() || !frame->tree()->find(frameName))) + return jsUndefined(); + + // Get the target frame for the special cases of _top and _parent. In those + // cases, we can schedule a location change right now and return early. + bool topOrParent = false; + if (frameName == "_top") { + frame = frame->tree()->top(); + topOrParent = true; + } else if (frameName == "_parent") { + if (Frame* parent = frame->tree()->parent()) + frame = parent; + topOrParent = true; + } + if (topOrParent) { + if (!activeFrame->loader()->shouldAllowNavigation(frame)) + return jsUndefined(); + + String completedURL; + if (!urlString.isEmpty()) + completedURL = activeFrame->document()->completeURL(urlString).string(); + + const JSDOMWindow* targetedWindow = toJSDOMWindow(frame); + if (!completedURL.isEmpty() && (!protocolIs(completedURL, "javascript") || (targetedWindow && targetedWindow->allowsAccessFrom(exec)))) { + bool userGesture = activeFrame->script()->processingUserGesture(); + frame->loader()->scheduleLocationChange(completedURL, activeFrame->loader()->outgoingReferrer(), false, userGesture); + } + return toJS(exec, frame->domWindow()); + } + + // In the case of a named frame or a new window, we'll use the createWindow() helper + WindowFeatures windowFeatures(valueToStringWithUndefinedOrNullCheck(exec, args.at(exec, 2))); + FloatRect windowRect(windowFeatures.xSet ? windowFeatures.x : 0, windowFeatures.ySet ? windowFeatures.y : 0, + windowFeatures.widthSet ? windowFeatures.width : 0, windowFeatures.heightSet ? windowFeatures.height : 0); + DOMWindow::adjustWindowRect(screenAvailableRect(page ? page->mainFrame()->view() : 0), windowRect, windowRect); + + windowFeatures.x = windowRect.x(); + windowFeatures.y = windowRect.y(); + windowFeatures.height = windowRect.height(); + windowFeatures.width = windowRect.width(); + + frame = createWindow(exec, frame, urlString, frameName, windowFeatures, noValue()); + + if (!frame) + return jsUndefined(); + + return toJS(exec, frame->domWindow()); // global object +} + +JSValue* windowProtoFuncShowModalDialog(ExecState* exec, JSObject*, JSValue* thisValue, const ArgList& args) +{ + JSDOMWindow* window = toJSDOMWindow(thisValue); + if (!window) + return throwError(exec, TypeError); + if (!window->allowsAccessFrom(exec)) + return jsUndefined(); + + Frame* frame = window->impl()->frame(); + if (!frame) + return jsUndefined(); + + return showModalDialog(exec, frame, valueToStringWithUndefinedOrNullCheck(exec, args.at(exec, 0)), args.at(exec, 1), valueToStringWithUndefinedOrNullCheck(exec, args.at(exec, 2))); +} + +JSValue* windowProtoFuncNotImplemented(ExecState* exec, JSObject*, JSValue* thisValue, const ArgList&) +{ + if (!toJSDOMWindow(thisValue)) + return throwError(exec, TypeError); + return jsUndefined(); +} + +namespace WebCore { + +void JSDOMWindowBase::setReturnValueSlot(JSValue** slot) +{ + d()->returnValueSlot = slot; +} + +////////////////////// timeouts //////////////////////// + +void JSDOMWindowBase::clearAllTimeouts() +{ + deleteAllValues(d()->timeouts); + d()->timeouts.clear(); +} + +int JSDOMWindowBase::installTimeout(ScheduledAction* a, int t, bool singleShot) +{ + int timeoutId = ++lastUsedTimeoutId; + + // avoid wraparound going negative on us + if (timeoutId <= 0) + timeoutId = 1; + + int nestLevel = timerNestingLevel + 1; + DOMWindowTimer* timer = new DOMWindowTimer(timeoutId, nestLevel, this, a); + ASSERT(!d()->timeouts.get(timeoutId)); + d()->timeouts.set(timeoutId, timer); + // Use a minimum interval of 10 ms to match other browsers, but only once we've + // nested enough to notice that we're repeating. + // Faster timers might be "better", but they're incompatible. + double interval = max(0.001, t * 0.001); + if (interval < cMinimumTimerInterval && nestLevel >= cMaxTimerNestingLevel) + interval = cMinimumTimerInterval; + if (singleShot) + timer->startOneShot(interval); + else + timer->startRepeating(interval); + return timeoutId; +} + +int JSDOMWindowBase::installTimeout(const UString& handler, int t, bool singleShot) +{ + return installTimeout(new ScheduledAction(handler), t, singleShot); +} + +int JSDOMWindowBase::installTimeout(ExecState* exec, JSValue* func, const ArgList& args, int t, bool singleShot) +{ + return installTimeout(new ScheduledAction(exec, func, args), t, singleShot); +} + +void JSDOMWindowBase::pauseTimeouts(OwnPtr<PausedTimeouts>& result) +{ + size_t timeoutsCount = d()->timeouts.size(); + if (!timeoutsCount) { + result.clear(); + return; + } + + PausedTimeout* t = new PausedTimeout[timeoutsCount]; + result.set(new PausedTimeouts(t, timeoutsCount)); + + JSDOMWindowBaseData::TimeoutsMap::iterator it = d()->timeouts.begin(); + for (size_t i = 0; i != timeoutsCount; ++i, ++it) { + int timeoutId = it->first; + DOMWindowTimer* timer = it->second; + t[i].timeoutId = timeoutId; + t[i].nestingLevel = timer->nestingLevel(); + t[i].nextFireInterval = timer->nextFireInterval(); + t[i].repeatInterval = timer->repeatInterval(); + t[i].action = timer->takeAction(); + } + ASSERT(it == d()->timeouts.end()); + + deleteAllValues(d()->timeouts); + d()->timeouts.clear(); +} + +void JSDOMWindowBase::resumeTimeouts(OwnPtr<PausedTimeouts>& timeouts) +{ + if (!timeouts) + return; + size_t count = timeouts->numTimeouts(); + PausedTimeout* array = timeouts->takeTimeouts(); + for (size_t i = 0; i != count; ++i) { + int timeoutId = array[i].timeoutId; + DOMWindowTimer* timer = new DOMWindowTimer(timeoutId, array[i].nestingLevel, this, array[i].action); + d()->timeouts.set(timeoutId, timer); + timer->start(array[i].nextFireInterval, array[i].repeatInterval); + } + delete [] array; + timeouts.clear(); +} + +void JSDOMWindowBase::removeTimeout(int timeoutId, bool delAction) +{ + // timeout IDs have to be positive, and 0 and -1 are unsafe to + // even look up since they are the empty and deleted value + // respectively + if (timeoutId <= 0) + return; + + delete d()->timeouts.take(timeoutId); +} + +void JSDOMWindowBase::timerFired(DOMWindowTimer* timer) +{ + // Simple case for non-one-shot timers. + if (timer->isActive()) { + int timeoutId = timer->timeoutId(); + + timer->action()->execute(shell()); + // The DOMWindowTimer object may have been deleted or replaced during execution, + // so we re-fetch it. + timer = d()->timeouts.get(timeoutId); + if (!timer) + return; + + if (timer->repeatInterval() && timer->repeatInterval() < cMinimumTimerInterval) { + timer->setNestingLevel(timer->nestingLevel() + 1); + if (timer->nestingLevel() >= cMaxTimerNestingLevel) + timer->augmentRepeatInterval(cMinimumTimerInterval - timer->repeatInterval()); + } + return; + } + + // Delete timer before executing the action for one-shot timers. + ScheduledAction* action = timer->takeAction(); + d()->timeouts.remove(timer->timeoutId()); + delete timer; + action->execute(shell()); + + JSLock lock(false); + delete action; +} + +void JSDOMWindowBase::disconnectFrame() +{ + clearAllTimeouts(); +} + +void DOMWindowTimer::fired() +{ + timerNestingLevel = m_nestingLevel; + m_object->timerFired(this); + timerNestingLevel = 0; +} + +JSValue* toJS(ExecState*, DOMWindow* domWindow) +{ + if (!domWindow) + return jsNull(); + Frame* frame = domWindow->frame(); + if (!frame) + return jsNull(); + return frame->script()->windowShell(); +} + +JSDOMWindow* toJSDOMWindow(Frame* frame) +{ + if (!frame) + return 0; + return frame->script()->windowShell()->window(); +} + +JSDOMWindow* toJSDOMWindow(JSValue* value) +{ + if (!value->isObject()) + return 0; + const ClassInfo* classInfo = asObject(value)->classInfo(); + if (classInfo == &JSDOMWindow::s_info) + return static_cast<JSDOMWindow*>(asObject(value)); + if (classInfo == &JSDOMWindowShell::s_info) + return static_cast<JSDOMWindowShell*>(asObject(value))->window(); + return 0; +} + +} // namespace WebCore diff --git a/WebCore/bindings/js/JSDOMWindowBase.h b/WebCore/bindings/js/JSDOMWindowBase.h new file mode 100644 index 0000000..f345f47 --- /dev/null +++ b/WebCore/bindings/js/JSDOMWindowBase.h @@ -0,0 +1,144 @@ +/* + * Copyright (C) 2000 Harri Porten (porten@kde.org) + * Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008 Apple Inc. All rights reseved. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#ifndef JSDOMWindowBase_h +#define JSDOMWindowBase_h + +#include "PlatformString.h" +#include "JSDOMBinding.h" +#include <kjs/protect.h> +#include <wtf/HashMap.h> +#include <wtf/OwnPtr.h> + +namespace WebCore { + + class AtomicString; + class DOMWindow; + class DOMWindowTimer; + class Event; + class Frame; + class JSDOMWindow; + class JSDOMWindowShell; + class JSEventListener; + class JSLocation; + class JSUnprotectedEventListener; + class PausedTimeouts; + class ScheduledAction; + class SecurityOrigin; + + class JSDOMWindowBasePrivate; + + // This is the only WebCore JS binding which does not inherit from DOMObject + class JSDOMWindowBase : public JSDOMGlobalObject { + typedef JSDOMGlobalObject Base; + + friend class ScheduledAction; + protected: + JSDOMWindowBase(PassRefPtr<JSC::StructureID>, PassRefPtr<DOMWindow>, JSDOMWindowShell*); + + public: + virtual ~JSDOMWindowBase(); + + void updateDocument(); + + DOMWindow* impl() const { return d()->impl.get(); } + virtual ScriptExecutionContext* scriptExecutionContext() const; + + void disconnectFrame(); + + virtual void markCrossHeapDependentObjects(); + + virtual bool getOwnPropertySlot(JSC::ExecState*, const JSC::Identifier&, JSC::PropertySlot&); + virtual void put(JSC::ExecState*, const JSC::Identifier& propertyName, JSC::JSValue*, JSC::PutPropertySlot&); + + int installTimeout(const JSC::UString& handler, int t, bool singleShot); + int installTimeout(JSC::ExecState*, JSC::JSValue* function, const JSC::ArgList& args, int t, bool singleShot); + void removeTimeout(int timerId, bool delAction = true); + + void pauseTimeouts(OwnPtr<PausedTimeouts>&); + void resumeTimeouts(OwnPtr<PausedTimeouts>&); + + void timerFired(DOMWindowTimer*); + + void clear(); + + // Set a place to put a dialog return value when the window is cleared. + void setReturnValueSlot(JSC::JSValue** slot); + + virtual const JSC::ClassInfo* classInfo() const { return &s_info; } + static const JSC::ClassInfo s_info; + + virtual JSC::ExecState* globalExec(); + + virtual bool supportsProfiling() const; + + virtual bool shouldInterruptScript() const; + + bool allowsAccessFrom(JSC::ExecState*) const; + bool allowsAccessFromNoErrorMessage(JSC::ExecState*) const; + bool allowsAccessFrom(JSC::ExecState*, String& message) const; + + void printErrorMessage(const String&) const; + + // Don't call this version of allowsAccessFrom -- it's a slightly incorrect implementation used only by WebScriptObject + virtual bool allowsAccessFrom(const JSC::JSGlobalObject*) const; + + virtual JSC::JSObject* toThisObject(JSC::ExecState*) const; + JSDOMWindowShell* shell() const; + + static JSC::JSGlobalData* commonJSGlobalData(); + + void clearAllTimeouts(); + + private: + struct JSDOMWindowBaseData : public JSDOMGlobalObjectData { + JSDOMWindowBaseData(PassRefPtr<DOMWindow>, JSDOMWindowShell*); + + RefPtr<DOMWindow> impl; + + JSC::JSValue** returnValueSlot; + JSDOMWindowShell* shell; + + typedef HashMap<int, DOMWindowTimer*> TimeoutsMap; + TimeoutsMap timeouts; + }; + + static JSC::JSValue* childFrameGetter(JSC::ExecState*, const JSC::Identifier&, const JSC::PropertySlot&); + static JSC::JSValue* indexGetter(JSC::ExecState*, const JSC::Identifier&, const JSC::PropertySlot&); + static JSC::JSValue* namedItemGetter(JSC::ExecState*, const JSC::Identifier&, const JSC::PropertySlot&); + + void clearHelperObjectProperties(); + int installTimeout(ScheduledAction*, int interval, bool singleShot); + + bool allowsAccessFromPrivate(const JSC::JSGlobalObject*) const; + String crossDomainAccessErrorMessage(const JSC::JSGlobalObject*) const; + + JSDOMWindowBaseData* d() const { return static_cast<JSDOMWindowBaseData*>(JSC::JSVariableObject::d); } + }; + + // Returns a JSDOMWindow or jsNull() + JSC::JSValue* toJS(JSC::ExecState*, DOMWindow*); + + // Returns JSDOMWindow or 0 + JSDOMWindow* toJSDOMWindow(Frame*); + JSDOMWindow* toJSDOMWindow(JSC::JSValue*); + +} // namespace WebCore + +#endif // JSDOMWindowBase_h diff --git a/WebCore/bindings/js/JSDOMWindowCustom.cpp b/WebCore/bindings/js/JSDOMWindowCustom.cpp index 66631f6..4b5f386 100644 --- a/WebCore/bindings/js/JSDOMWindowCustom.cpp +++ b/WebCore/bindings/js/JSDOMWindowCustom.cpp @@ -18,150 +18,308 @@ */ #include "config.h" -#include "JSDOMWindow.h" +#include "JSDOMWindowCustom.h" #include "AtomicString.h" +#include "Base64.h" #include "DOMWindow.h" #include "Document.h" #include "ExceptionCode.h" #include "Frame.h" #include "FrameLoader.h" #include "FrameTree.h" -#include "kjs_window.h" -#include <kjs/object.h> +#include "JSDOMWindowShell.h" +#include "JSEventListener.h" +#include "JSMessagePort.h" +#include "MessagePort.h" +#include "ScriptController.h" +#include "Settings.h" +#include <runtime/JSObject.h> +#include <runtime/PrototypeFunction.h> -using namespace KJS; +using namespace JSC; namespace WebCore { -bool JSDOMWindow::customGetOwnPropertySlot(ExecState* exec, const Identifier& propertyName, PropertySlot& slot) +void JSDOMWindow::mark() { - // When accessing a Window cross-domain, functions are always the native built-in ones, and they - // are not affected by properties changed on the Window or anything in its prototype chain. - // This is consistent with the behavior of Firefox. + Base::mark(); - const HashEntry* entry; + JSGlobalData& globalData = *Heap::heap(this)->globalData(); - // We don't want any properties other than "close" and "closed" on a closed window. - if (!impl()->frame()) { - // The following code is safe for cross-domain and same domain use. - // It ignores any custom properties that might be set on the DOMWindow (including a custom prototype). - entry = Lookup::findEntry(info.propHashTable, propertyName); - if (entry && !(entry->attr & Function) && entry->value.intValue == ClosedAttrNum) { - slot.setStaticEntry(this, entry, staticValueGetter<JSDOMWindow>); - return true; - } - entry = Lookup::findEntry(JSDOMWindowPrototype::info.propHashTable, propertyName); - if (entry && (entry->attr & Function) && entry->value.functionValue == jsDOMWindowPrototypeFunctionClose) { - slot.setStaticEntry(this, entry, nonCachingStaticFunctionGetter); - return true; - } + markDOMObjectWrapper(globalData, impl()->optionalConsole()); + markDOMObjectWrapper(globalData, impl()->optionalHistory()); + markDOMObjectWrapper(globalData, impl()->optionalLocationbar()); + markDOMObjectWrapper(globalData, impl()->optionalMenubar()); + markDOMObjectWrapper(globalData, impl()->optionalNavigator()); + markDOMObjectWrapper(globalData, impl()->optionalPersonalbar()); + markDOMObjectWrapper(globalData, impl()->optionalScreen()); + markDOMObjectWrapper(globalData, impl()->optionalScrollbars()); + markDOMObjectWrapper(globalData, impl()->optionalSelection()); + markDOMObjectWrapper(globalData, impl()->optionalStatusbar()); + markDOMObjectWrapper(globalData, impl()->optionalToolbar()); + markDOMObjectWrapper(globalData, impl()->optionalLocation()); +#if ENABLE(DOM_STORAGE) + markDOMObjectWrapper(globalData, impl()->optionalSessionStorage()); + markDOMObjectWrapper(globalData, impl()->optionalLocalStorage()); +#endif +#if ENABLE(OFFLINE_WEB_APPLICATIONS) + markDOMObjectWrapper(globalData, impl()->optionalApplicationCache()); +#endif +} - // FIXME: We should have a message here that explains why the property access/function call was - // not allowed. - slot.setUndefined(this); +bool JSDOMWindow::deleteProperty(ExecState* exec, const Identifier& propertyName) +{ + // Only allow deleting properties by frames in the same origin. + if (!allowsAccessFrom(exec)) + return false; + return Base::deleteProperty(exec, propertyName); +} + +bool JSDOMWindow::customGetPropertyNames(ExecState* exec, PropertyNameArray&) +{ + // Only allow the window to enumerated by frames in the same origin. + if (!allowsAccessFrom(exec)) return true; - } + return false; +} - // We need to check for cross-domain access here without printing the generic warning message - // because we always allow access to some function, just different ones depending whether access - // is allowed. - bool allowsAccess = allowsAccessFromNoErrorMessage(exec); +bool JSDOMWindow::getPropertyAttributes(JSC::ExecState* exec, const Identifier& propertyName, unsigned& attributes) const +{ + // Only allow getting property attributes properties by frames in the same origin. + if (!allowsAccessFrom(exec)) + return false; + return Base::getPropertyAttributes(exec, propertyName, attributes); +} - // Look for overrides before looking at any of our own properties. - if (JSGlobalObject::getOwnPropertySlot(exec, propertyName, slot)) { - // But ignore overrides completely if this is cross-domain access. - if (allowsAccess) - return true; - } +void JSDOMWindow::defineGetter(ExecState* exec, const Identifier& propertyName, JSObject* getterFunction) +{ + // Only allow defining getters by frames in the same origin. + if (!allowsAccessFrom(exec)) + return; + Base::defineGetter(exec, propertyName, getterFunction); +} - // We need this code here because otherwise KJS::Window will stop the search before we even get to the - // prototype due to the blanket same origin (allowsAccessFrom) check at the end of getOwnPropertySlot. - // Also, it's important to get the implementation straight out of the DOMWindow prototype regardless of - // what prototype is actually set on this object. - entry = Lookup::findEntry(JSDOMWindowPrototype::info.propHashTable, propertyName); - if (entry) { - if ((entry->attr & Function) - && (entry->value.functionValue == jsDOMWindowPrototypeFunctionBlur - || entry->value.functionValue == jsDOMWindowPrototypeFunctionClose - || entry->value.functionValue == jsDOMWindowPrototypeFunctionFocus -#if ENABLE(CROSS_DOCUMENT_MESSAGING) - || entry->value.functionValue == jsDOMWindowPrototypeFunctionPostMessage -#endif - )) { - if (!allowsAccess) { - slot.setStaticEntry(this, entry, nonCachingStaticFunctionGetter); - return true; - } - } - } else { - // Allow access to toString() cross-domain, but always Object.prototype.toString. - if (propertyName == exec->propertyNames().toString) { - if (!allowsAccess) { - slot.setCustom(this, objectToStringFunctionGetter); - return true; - } +void JSDOMWindow::defineSetter(ExecState* exec, const Identifier& propertyName, JSObject* setterFunction) +{ + // Only allow defining setters by frames in the same origin. + if (!allowsAccessFrom(exec)) + return; + Base::defineSetter(exec, propertyName, setterFunction); +} + +JSValue* JSDOMWindow::lookupGetter(ExecState* exec, const Identifier& propertyName) +{ + // Only allow looking-up getters by frames in the same origin. + if (!allowsAccessFrom(exec)) + return jsUndefined(); + return Base::lookupGetter(exec, propertyName); +} + +JSValue* JSDOMWindow::lookupSetter(ExecState* exec, const Identifier& propertyName) +{ + // Only allow looking-up setters by frames in the same origin. + if (!allowsAccessFrom(exec)) + return jsUndefined(); + return Base::lookupSetter(exec, propertyName); +} + +void JSDOMWindow::setLocation(ExecState* exec, JSValue* value) +{ + Frame* activeFrame = asJSDOMWindow(exec->dynamicGlobalObject())->impl()->frame(); + if (!activeFrame) + return; + +#if ENABLE(DASHBOARD_SUPPORT) + // To avoid breaking old widgets, make "var location =" in a top-level frame create + // a property named "location" instead of performing a navigation (<rdar://problem/5688039>). + if (Settings* settings = activeFrame->settings()) { + if (settings->usesDashboardBackwardCompatibilityMode() && !activeFrame->tree()->parent()) { + if (allowsAccessFrom(exec)) + putDirect(Identifier(exec, "location"), value); + return; } } +#endif - return false; + if (!activeFrame->loader()->shouldAllowNavigation(impl()->frame())) + return; + String dstUrl = activeFrame->loader()->completeURL(value->toString(exec)).string(); + if (!protocolIs(dstUrl, "javascript") || allowsAccessFrom(exec)) { + bool userGesture = activeFrame->script()->processingUserGesture(); + // We want a new history item if this JS was called via a user gesture + impl()->frame()->loader()->scheduleLocationChange(dstUrl, activeFrame->loader()->outgoingReferrer(), false, userGesture); + } } -bool JSDOMWindow::customPut(ExecState* exec, const Identifier& propertyName, JSValue* value, int attr) +JSValue* JSDOMWindow::postMessage(ExecState* exec, const ArgList& args) { - if (!impl()->frame()) - return true; + DOMWindow* window = impl(); - // Called by an internal KJS, save time and jump directly to JSGlobalObject. - if (attr != None && attr != DontDelete) { - JSGlobalObject::put(exec, propertyName, value, attr); - return true; - } + DOMWindow* source = asJSDOMWindow(exec->dynamicGlobalObject())->impl(); + String message = args.at(exec, 0)->toString(exec); - // We have a local override (e.g. "var location"), save time and jump directly to JSGlobalObject. - PropertySlot slot; - if (JSGlobalObject::getOwnPropertySlot(exec, propertyName, slot)) { - if (allowsAccessFrom(exec)) - JSGlobalObject::put(exec, propertyName, value, attr); - return true; + if (exec->hadException()) + return jsUndefined(); + + MessagePort* messagePort = (args.size() == 2) ? 0 : toMessagePort(args.at(exec, 1)); + + String targetOrigin = valueToStringWithUndefinedOrNullCheck(exec, args.at(exec, (args.size() == 2) ? 1 : 2)); + if (exec->hadException()) + return jsUndefined(); + + ExceptionCode ec = 0; + window->postMessage(message, messagePort, targetOrigin, source, ec); + setDOMException(exec, ec); + + return jsUndefined(); +} + +static JSValue* setTimeoutOrInterval(ExecState* exec, JSDOMWindow* window, const ArgList& args, bool timeout) +{ + JSValue* v = args.at(exec, 0); + int delay = args.at(exec, 1)->toInt32(exec); + if (v->isString()) + return jsNumber(exec, window->installTimeout(asString(v)->value(), delay, timeout)); + CallData callData; + if (v->getCallData(callData) == CallTypeNone) + return jsUndefined(); + ArgList argsTail; + args.getSlice(2, argsTail); + return jsNumber(exec, window->installTimeout(exec, v, argsTail, delay, timeout)); +} + +JSValue* JSDOMWindow::setTimeout(ExecState* exec, const ArgList& args) +{ + return setTimeoutOrInterval(exec, this, args, true); +} + +JSValue* JSDOMWindow::clearTimeout(ExecState* exec, const ArgList& args) +{ + removeTimeout(args.at(exec, 0)->toInt32(exec)); + return jsUndefined(); +} + +JSValue* JSDOMWindow::setInterval(ExecState* exec, const ArgList& args) +{ + return setTimeoutOrInterval(exec, this, args, false); +} + +JSValue* JSDOMWindow::clearInterval(ExecState* exec, const ArgList& args) +{ + removeTimeout(args.at(exec, 0)->toInt32(exec)); + return jsUndefined(); +} + +JSValue* JSDOMWindow::atob(ExecState* exec, const ArgList& args) +{ + if (args.size() < 1) + return throwError(exec, SyntaxError, "Not enough arguments"); + + JSValue* v = args.at(exec, 0); + if (v->isNull()) + return jsEmptyString(exec); + + UString s = v->toString(exec); + if (!s.is8Bit()) { + setDOMException(exec, INVALID_CHARACTER_ERR); + return jsUndefined(); } - return false; + Vector<char> in(s.size()); + for (int i = 0; i < s.size(); ++i) + in[i] = static_cast<char>(s.data()[i]); + Vector<char> out; + + if (!base64Decode(in, out)) + return throwError(exec, GeneralError, "Cannot decode base64"); + + return jsString(exec, String(out.data(), out.size())); } -bool JSDOMWindow::deleteProperty(ExecState* exec, const Identifier& propertyName) +JSValue* JSDOMWindow::btoa(ExecState* exec, const ArgList& args) { - // Only allow deleting properties by frames in the same origin. - if (!allowsAccessFrom(exec)) - return false; - return Base::deleteProperty(exec, propertyName); + if (args.size() < 1) + return throwError(exec, SyntaxError, "Not enough arguments"); + + JSValue* v = args.at(exec, 0); + if (v->isNull()) + return jsEmptyString(exec); + + UString s = v->toString(exec); + if (!s.is8Bit()) { + setDOMException(exec, INVALID_CHARACTER_ERR); + return jsUndefined(); + } + + Vector<char> in(s.size()); + for (int i = 0; i < s.size(); ++i) + in[i] = static_cast<char>(s.data()[i]); + Vector<char> out; + + base64Encode(in, out); + + return jsString(exec, String(out.data(), out.size())); } -bool JSDOMWindow::customGetPropertyNames(ExecState* exec, PropertyNameArray&) +JSValue* JSDOMWindow::addEventListener(ExecState* exec, const ArgList& args) { - // Only allow the window to enumerated by frames in the same origin. - if (!allowsAccessFrom(exec)) - return true; - return false; + Frame* frame = impl()->frame(); + if (!frame) + return jsUndefined(); + + if (RefPtr<JSEventListener> listener = findOrCreateJSEventListener(exec, args.at(exec, 1))) { + if (Document* doc = frame->document()) + doc->addWindowEventListener(AtomicString(args.at(exec, 0)->toString(exec)), listener.release(), args.at(exec, 2)->toBoolean(exec)); + } + + return jsUndefined(); } -#if ENABLE(CROSS_DOCUMENT_MESSAGING) -JSValue* JSDOMWindow::postMessage(ExecState* exec, const List& args) +JSValue* JSDOMWindow::removeEventListener(ExecState* exec, const ArgList& args) { - DOMWindow* window = impl(); - - DOMWindow* source = static_cast<JSDOMWindow*>(exec->dynamicGlobalObject())->impl(); - String domain = source->frame()->loader()->url().host(); - String uri = source->frame()->loader()->url().string(); - String message = args[0]->toString(exec); - - if (exec->hadException()) + Frame* frame = impl()->frame(); + if (!frame) return jsUndefined(); - - window->postMessage(message, domain, uri, source); - + + if (JSEventListener* listener = findJSEventListener(args.at(exec, 1))) { + if (Document* doc = frame->document()) + doc->removeWindowEventListener(AtomicString(args.at(exec, 0)->toString(exec)), listener, args.at(exec, 2)->toBoolean(exec)); + } + return jsUndefined(); } -#endif + +DOMWindow* toDOMWindow(JSValue* value) +{ + if (!value->isObject()) + return 0; + JSObject* object = asObject(value); + if (object->inherits(&JSDOMWindow::s_info)) + return static_cast<JSDOMWindow*>(object)->impl(); + if (object->inherits(&JSDOMWindowShell::s_info)) + return static_cast<JSDOMWindowShell*>(object)->impl(); + return 0; +} + +JSValue* nonCachingStaticCloseFunctionGetter(ExecState* exec, const Identifier& propertyName, const PropertySlot& slot) +{ + return new (exec) PrototypeFunction(exec, 0, propertyName, jsDOMWindowPrototypeFunctionClose); +} + +JSValue* nonCachingStaticBlurFunctionGetter(ExecState* exec, const Identifier& propertyName, const PropertySlot& slot) +{ + return new (exec) PrototypeFunction(exec, 0, propertyName, jsDOMWindowPrototypeFunctionBlur); +} + +JSValue* nonCachingStaticFocusFunctionGetter(ExecState* exec, const Identifier& propertyName, const PropertySlot& slot) +{ + return new (exec) PrototypeFunction(exec, 0, propertyName, jsDOMWindowPrototypeFunctionFocus); +} + +JSValue* nonCachingStaticPostMessageFunctionGetter(ExecState* exec, const Identifier& propertyName, const PropertySlot& slot) +{ + return new (exec) PrototypeFunction(exec, 2, propertyName, jsDOMWindowPrototypeFunctionPostMessage); +} } // namespace WebCore diff --git a/WebCore/bindings/js/JSDOMWindowCustom.h b/WebCore/bindings/js/JSDOMWindowCustom.h new file mode 100644 index 0000000..c8ce088 --- /dev/null +++ b/WebCore/bindings/js/JSDOMWindowCustom.h @@ -0,0 +1,202 @@ +/* + * Copyright (C) 2008 Apple Inc. All rights reseved. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#ifndef JSDOMWindowCustom_h +#define JSDOMWindowCustom_h + +#include "JSDOMWindow.h" +#include "JSDOMWindowShell.h" +#include <wtf/AlwaysInline.h> + +namespace WebCore { + +inline JSDOMWindow* asJSDOMWindow(JSC::JSGlobalObject* globalObject) +{ + return static_cast<JSDOMWindow*>(globalObject); +} + +inline const JSDOMWindow* asJSDOMWindow(const JSC::JSGlobalObject* globalObject) +{ + return static_cast<const JSDOMWindow*>(globalObject); +} + +JSC::JSValue* nonCachingStaticCloseFunctionGetter(JSC::ExecState*, const JSC::Identifier&, const JSC::PropertySlot&); +JSC::JSValue* nonCachingStaticBlurFunctionGetter(JSC::ExecState*, const JSC::Identifier&, const JSC::PropertySlot&); +JSC::JSValue* nonCachingStaticFocusFunctionGetter(JSC::ExecState*, const JSC::Identifier&, const JSC::PropertySlot&); +JSC::JSValue* nonCachingStaticPostMessageFunctionGetter(JSC::ExecState*, const JSC::Identifier&, const JSC::PropertySlot&); + +ALWAYS_INLINE bool JSDOMWindow::customGetOwnPropertySlot(JSC::ExecState* exec, const JSC::Identifier& propertyName, JSC::PropertySlot& slot) +{ + // When accessing a Window cross-domain, functions are always the native built-in ones, and they + // are not affected by properties changed on the Window or anything in its prototype chain. + // This is consistent with the behavior of Firefox. + + const JSC::HashEntry* entry; + + // We don't want any properties other than "close" and "closed" on a closed window. + if (!impl()->frame()) { + // The following code is safe for cross-domain and same domain use. + // It ignores any custom properties that might be set on the DOMWindow (including a custom prototype). + entry = s_info.propHashTable(exec)->entry(exec, propertyName); + if (entry && !(entry->attributes() & JSC::Function) && entry->propertyGetter() == jsDOMWindowClosed) { + slot.setCustom(this, entry->propertyGetter()); + return true; + } + entry = JSDOMWindowPrototype::s_info.propHashTable(exec)->entry(exec, propertyName); + if (entry && (entry->attributes() & JSC::Function) && entry->function() == jsDOMWindowPrototypeFunctionClose) { + slot.setCustom(this, nonCachingStaticCloseFunctionGetter); + return true; + } + + // FIXME: We should have a message here that explains why the property access/function call was + // not allowed. + slot.setUndefined(); + return true; + } + + // We need to check for cross-domain access here without printing the generic warning message + // because we always allow access to some function, just different ones depending whether access + // is allowed. + bool allowsAccess = allowsAccessFromNoErrorMessage(exec); + + // Look for overrides before looking at any of our own properties. + if (JSGlobalObject::getOwnPropertySlot(exec, propertyName, slot)) { + // But ignore overrides completely if this is cross-domain access. + if (allowsAccess) + return true; + } + + // We need this code here because otherwise JSC::Window will stop the search before we even get to the + // prototype due to the blanket same origin (allowsAccessFrom) check at the end of getOwnPropertySlot. + // Also, it's important to get the implementation straight out of the DOMWindow prototype regardless of + // what prototype is actually set on this object. + entry = JSDOMWindowPrototype::s_info.propHashTable(exec)->entry(exec, propertyName); + if (entry) { + if (entry->attributes() & JSC::Function) { + if (entry->function() == jsDOMWindowPrototypeFunctionBlur) { + if (!allowsAccess) { + slot.setCustom(this, nonCachingStaticBlurFunctionGetter); + return true; + } + } else if (entry->function() == jsDOMWindowPrototypeFunctionClose) { + if (!allowsAccess) { + slot.setCustom(this, nonCachingStaticCloseFunctionGetter); + return true; + } + } else if (entry->function() == jsDOMWindowPrototypeFunctionFocus) { + if (!allowsAccess) { + slot.setCustom(this, nonCachingStaticFocusFunctionGetter); + return true; + } + } else if (entry->function() == jsDOMWindowPrototypeFunctionPostMessage) { + if (!allowsAccess) { + slot.setCustom(this, nonCachingStaticPostMessageFunctionGetter); + return true; + } + } + } + } else { + // Allow access to toString() cross-domain, but always Object.prototype.toString. + if (propertyName == exec->propertyNames().toString) { + if (!allowsAccess) { + slot.setCustom(this, objectToStringFunctionGetter); + return true; + } + } + } + + return false; +} + +inline bool JSDOMWindow::customPut(JSC::ExecState* exec, const JSC::Identifier& propertyName, JSC::JSValue* value, JSC::PutPropertySlot& slot) +{ + if (!impl()->frame()) + return true; + + // We have a local override (e.g. "var location"), save time and jump directly to JSGlobalObject. + JSC::PropertySlot getSlot; + bool slotIsWriteable; + if (JSGlobalObject::getOwnPropertySlot(exec, propertyName, getSlot, slotIsWriteable)) { + if (allowsAccessFrom(exec)) { + if (slotIsWriteable) { + getSlot.putValue(value); + if (getSlot.isCacheable()) + slot.setExistingProperty(this, getSlot.cachedOffset()); + } else + JSGlobalObject::put(exec, propertyName, value, slot); + } + return true; + } + + return false; +} + + + +inline bool JSDOMWindowBase::allowsAccessFrom(const JSGlobalObject* other) const +{ + if (allowsAccessFromPrivate(other)) + return true; + printErrorMessage(crossDomainAccessErrorMessage(other)); + return false; +} + + inline bool JSDOMWindowBase::allowsAccessFrom(JSC::ExecState* exec) const +{ + if (allowsAccessFromPrivate(exec->lexicalGlobalObject())) + return true; + printErrorMessage(crossDomainAccessErrorMessage(exec->lexicalGlobalObject())); + return false; +} + +inline bool JSDOMWindowBase::allowsAccessFromNoErrorMessage(JSC::ExecState* exec) const +{ + return allowsAccessFromPrivate(exec->lexicalGlobalObject()); +} + +inline bool JSDOMWindowBase::allowsAccessFrom(JSC::ExecState* exec, String& message) const +{ + if (allowsAccessFromPrivate(exec->lexicalGlobalObject())) + return true; + message = crossDomainAccessErrorMessage(exec->lexicalGlobalObject()); + return false; +} + +ALWAYS_INLINE bool JSDOMWindowBase::allowsAccessFromPrivate(const JSGlobalObject* other) const +{ + const JSDOMWindow* originWindow = asJSDOMWindow(other); + const JSDOMWindow* targetWindow = d()->shell->window(); + + if (originWindow == targetWindow) + return true; + + // JS may be attempting to access the "window" object, which should be valid, + // even if the document hasn't been constructed yet. If the document doesn't + // exist yet allow JS to access the window object. + if (!originWindow->impl()->document()) + return true; + + const SecurityOrigin* originSecurityOrigin = originWindow->impl()->securityOrigin(); + const SecurityOrigin* targetSecurityOrigin = targetWindow->impl()->securityOrigin(); + + return originSecurityOrigin->canAccess(targetSecurityOrigin); +} + +} + +#endif // JSDOMWindowCustom_h diff --git a/WebCore/bindings/js/JSDOMWindowShell.cpp b/WebCore/bindings/js/JSDOMWindowShell.cpp new file mode 100644 index 0000000..ee4a76f --- /dev/null +++ b/WebCore/bindings/js/JSDOMWindowShell.cpp @@ -0,0 +1,177 @@ +/* + * Copyright (C) 2008 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of + * its contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "JSDOMWindowShell.h" + +#include "Frame.h" +#include "JSDOMWindow.h" +#include "DOMWindow.h" +#include "ScriptController.h" +#include <runtime/JSObject.h> + +using namespace JSC; + +namespace WebCore { + +ASSERT_CLASS_FITS_IN_CELL(JSDOMWindowShell) + +const ClassInfo JSDOMWindowShell::s_info = { "JSDOMWindowShell", 0, 0, 0 }; + +JSDOMWindowShell::JSDOMWindowShell(PassRefPtr<DOMWindow> window) + : Base(JSDOMWindowShell::createStructureID(jsNull())) + , m_window(0) +{ + setWindow(window); +} + +JSDOMWindowShell::~JSDOMWindowShell() +{ +} + +void JSDOMWindowShell::setWindow(PassRefPtr<DOMWindow> window) +{ + RefPtr<StructureID> prototypeStructure = JSDOMWindowPrototype::createStructureID(jsNull()); + RefPtr<StructureID> structure = JSDOMWindow::createStructureID(new JSDOMWindowPrototype(prototypeStructure.release())); + setWindow(new (JSDOMWindow::commonJSGlobalData()) JSDOMWindow(structure.release(), window, this)); +} + +// ---- +// JSObject methods +// ---- + +void JSDOMWindowShell::mark() +{ + Base::mark(); + if (m_window && !m_window->marked()) + m_window->mark(); +} + +UString JSDOMWindowShell::className() const +{ + return m_window->className(); +} + +bool JSDOMWindowShell::getOwnPropertySlot(ExecState* exec, const Identifier& propertyName, PropertySlot& slot) +{ + return m_window->getOwnPropertySlot(exec, propertyName, slot); +} + +void JSDOMWindowShell::put(ExecState* exec, const Identifier& propertyName, JSValue* value, PutPropertySlot& slot) +{ + m_window->put(exec, propertyName, value, slot); +} + +void JSDOMWindowShell::putWithAttributes(ExecState* exec, const Identifier& propertyName, JSValue* value, unsigned attributes) +{ + m_window->putWithAttributes(exec, propertyName, value, attributes); +} + +bool JSDOMWindowShell::deleteProperty(ExecState* exec, const Identifier& propertyName) +{ + return m_window->deleteProperty(exec, propertyName); +} + +void JSDOMWindowShell::getPropertyNames(ExecState* exec, PropertyNameArray& propertyNames) +{ + m_window->getPropertyNames(exec, propertyNames); +} + +bool JSDOMWindowShell::getPropertyAttributes(JSC::ExecState* exec, const Identifier& propertyName, unsigned& attributes) const +{ + return m_window->getPropertyAttributes(exec, propertyName, attributes); +} + +void JSDOMWindowShell::defineGetter(ExecState* exec, const Identifier& propertyName, JSObject* getterFunction) +{ + m_window->defineGetter(exec, propertyName, getterFunction); +} + +void JSDOMWindowShell::defineSetter(ExecState* exec, const Identifier& propertyName, JSObject* setterFunction) +{ + m_window->defineSetter(exec, propertyName, setterFunction); +} + +JSValue* JSDOMWindowShell::lookupGetter(ExecState* exec, const Identifier& propertyName) +{ + return m_window->lookupGetter(exec, propertyName); +} + +JSValue* JSDOMWindowShell::lookupSetter(ExecState* exec, const Identifier& propertyName) +{ + return m_window->lookupSetter(exec, propertyName); +} + +JSGlobalObject* JSDOMWindowShell::toGlobalObject(ExecState*) const +{ + return m_window; +} + +// ---- +// JSDOMWindow methods +// ---- + +DOMWindow* JSDOMWindowShell::impl() const +{ + return m_window->impl(); +} + +void JSDOMWindowShell::disconnectFrame() +{ + m_window->disconnectFrame(); +} + +void JSDOMWindowShell::clear() +{ + m_window->clear(); +} + +void* JSDOMWindowShell::operator new(size_t size) +{ + return JSDOMWindow::commonJSGlobalData()->heap.allocate(size); +} + +// ---- +// Conversion methods +// ---- + +JSValue* toJS(ExecState*, Frame* frame) +{ + if (!frame) + return jsNull(); + return frame->script()->windowShell(); +} + +JSDOMWindowShell* toJSDOMWindowShell(Frame* frame) +{ + if (!frame) + return 0; + return frame->script()->windowShell(); +} + +} // namespace WebCore diff --git a/WebCore/bindings/js/JSDOMWindowShell.h b/WebCore/bindings/js/JSDOMWindowShell.h new file mode 100644 index 0000000..7cda4d4 --- /dev/null +++ b/WebCore/bindings/js/JSDOMWindowShell.h @@ -0,0 +1,92 @@ +/* + * Copyright (C) 2008 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of + * its contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef JSDOMWindowShell_h +#define JSDOMWindowShell_h + +#include "JSDOMWindow.h" +#include "JSDOMBinding.h" + +namespace WebCore { + + class DOMWindow; + class Frame; + + class JSDOMWindowShell : public DOMObject { + typedef DOMObject Base; + public: + JSDOMWindowShell(PassRefPtr<DOMWindow>); + virtual ~JSDOMWindowShell(); + + JSDOMWindow* window() const { return m_window; } + void setWindow(JSDOMWindow* window) + { + ASSERT_ARG(window, window); + m_window = window; + setPrototype(window->prototype()); + } + void setWindow(PassRefPtr<DOMWindow>); + + static const JSC::ClassInfo s_info; + + DOMWindow* impl() const; + void disconnectFrame(); + void clear(); + + void* operator new(size_t); + + static PassRefPtr<JSC::StructureID> createStructureID(JSC::JSValue* prototype) + { + return JSC::StructureID::create(prototype, JSC::TypeInfo(JSC::ObjectType)); + } + + private: + virtual void mark(); + virtual JSC::UString className() const; + virtual bool getOwnPropertySlot(JSC::ExecState*, const JSC::Identifier& propertyName, JSC::PropertySlot&); + virtual void put(JSC::ExecState*, const JSC::Identifier& propertyName, JSC::JSValue*, JSC::PutPropertySlot&); + virtual void putWithAttributes(JSC::ExecState*, const JSC::Identifier& propertyName, JSC::JSValue*, unsigned attributes); + virtual bool deleteProperty(JSC::ExecState*, const JSC::Identifier& propertyName); + virtual void getPropertyNames(JSC::ExecState*, JSC::PropertyNameArray&); + virtual bool getPropertyAttributes(JSC::ExecState*, const JSC::Identifier& propertyName, unsigned& attributes) const; + virtual void defineGetter(JSC::ExecState*, const JSC::Identifier& propertyName, JSC::JSObject* getterFunction); + virtual void defineSetter(JSC::ExecState*, const JSC::Identifier& propertyName, JSC::JSObject* setterFunction); + virtual JSC::JSValue* lookupGetter(JSC::ExecState*, const JSC::Identifier& propertyName); + virtual JSC::JSValue* lookupSetter(JSC::ExecState*, const JSC::Identifier& propertyName); + virtual JSC::JSGlobalObject* toGlobalObject(JSC::ExecState*) const; + virtual const JSC::ClassInfo* classInfo() const { return &s_info; } + + JSDOMWindow* m_window; + }; + + JSC::JSValue* toJS(JSC::ExecState*, Frame*); + JSDOMWindowShell* toJSDOMWindowShell(Frame*); + +} // namespace WebCore + +#endif // JSDOMWindowShell_h diff --git a/WebCore/bindings/js/JSDatabaseCustom.cpp b/WebCore/bindings/js/JSDatabaseCustom.cpp index c4e9265..f17340c 100644 --- a/WebCore/bindings/js/JSDatabaseCustom.cpp +++ b/WebCore/bindings/js/JSDatabaseCustom.cpp @@ -29,54 +29,53 @@ #include "config.h" #include "JSDatabase.h" +#include "DOMWindow.h" #include "Database.h" #include "Document.h" -#include "DOMWindow.h" #include "ExceptionCode.h" -#include "kjs_window.h" #include "JSCustomSQLTransactionCallback.h" #include "JSCustomSQLTransactionErrorCallback.h" #include "JSCustomVoidCallback.h" +#include "JSDOMWindowCustom.h" #include "PlatformString.h" #include "SQLValue.h" -#include <kjs/array_instance.h> +#include <runtime/JSArray.h> namespace WebCore { -using namespace KJS; +using namespace JSC; -JSValue* JSDatabase::changeVersion(ExecState* exec, const List& args) +JSValue* JSDatabase::changeVersion(ExecState* exec, const ArgList& args) { - String oldVersion = args[0]->toString(exec); - String newVersion = args[1]->toString(exec); + String oldVersion = args.at(exec, 0)->toString(exec); + String newVersion = args.at(exec, 1)->toString(exec); - Frame* frame = Window::retrieveActive(exec)->impl()->frame(); + Frame* frame = asJSDOMWindow(exec->dynamicGlobalObject())->impl()->frame(); if (!frame) return jsUndefined(); JSObject *object; - if (!(object = args[2]->getObject())) { + if (!(object = args.at(exec, 2)->getObject())) { setDOMException(exec, TYPE_MISMATCH_ERR); return jsUndefined(); } - RefPtr<SQLTransactionCallback> callback(new JSCustomSQLTransactionCallback(object, frame)); + RefPtr<SQLTransactionCallback> callback(JSCustomSQLTransactionCallback::create(object, frame)); RefPtr<SQLTransactionErrorCallback> errorCallback; - if (!args[3]->isNull()) { - if (!(object = args[3]->getObject())) { + if (!args.at(exec, 3)->isNull()) { + if (!(object = args.at(exec, 3)->getObject())) { setDOMException(exec, TYPE_MISMATCH_ERR); return jsUndefined(); } - errorCallback = new JSCustomSQLTransactionErrorCallback(object, frame); + errorCallback = JSCustomSQLTransactionErrorCallback::create(object, frame); } RefPtr<VoidCallback> successCallback; - if (!args[4]->isNull()) { - bool ok; - successCallback = toVoidCallback(exec, args[4], ok); - if (!ok) { + if (!args.at(exec, 4)->isNull()) { + successCallback = toVoidCallback(exec, args.at(exec, 4)); + if (!successCallback) { setDOMException(exec, TYPE_MISMATCH_ERR); return jsUndefined(); } @@ -87,36 +86,35 @@ JSValue* JSDatabase::changeVersion(ExecState* exec, const List& args) return jsUndefined(); } -JSValue* JSDatabase::transaction(ExecState* exec, const List& args) +JSValue* JSDatabase::transaction(ExecState* exec, const ArgList& args) { JSObject* object; - if (!(object = args[0]->getObject())) { + if (!(object = args.at(exec, 0)->getObject())) { setDOMException(exec, TYPE_MISMATCH_ERR); return jsUndefined(); } - Frame* frame = Window::retrieveActive(exec)->impl()->frame(); + Frame* frame = asJSDOMWindow(exec->dynamicGlobalObject())->impl()->frame(); if (!frame) return jsUndefined(); - RefPtr<SQLTransactionCallback> callback(new JSCustomSQLTransactionCallback(object, frame)); + RefPtr<SQLTransactionCallback> callback(JSCustomSQLTransactionCallback::create(object, frame)); RefPtr<SQLTransactionErrorCallback> errorCallback; - if (args.size() > 1 && !args[1]->isNull()) { - if (!(object = args[1]->getObject())) { + if (args.size() > 1 && !args.at(exec, 1)->isNull()) { + if (!(object = args.at(exec, 1)->getObject())) { setDOMException(exec, TYPE_MISMATCH_ERR); return jsUndefined(); } - errorCallback = new JSCustomSQLTransactionErrorCallback(object, frame); + errorCallback = JSCustomSQLTransactionErrorCallback::create(object, frame); } RefPtr<VoidCallback> successCallback; - if (args.size() > 2 && !args[2]->isNull()) { - bool ok; - successCallback = toVoidCallback(exec, args[2], ok); - if (!ok) { + if (args.size() > 2 && !args.at(exec, 2)->isNull()) { + successCallback = toVoidCallback(exec, args.at(exec, 2)); + if (!successCallback) { setDOMException(exec, TYPE_MISMATCH_ERR); return jsUndefined(); } diff --git a/WebCore/bindings/js/JSDedicatedWorkerConstructor.cpp b/WebCore/bindings/js/JSDedicatedWorkerConstructor.cpp new file mode 100644 index 0000000..58ea258 --- /dev/null +++ b/WebCore/bindings/js/JSDedicatedWorkerConstructor.cpp @@ -0,0 +1,74 @@ +/* + * Copyright (C) 2008 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" + +#if ENABLE(WORKERS) + +#include "JSDedicatedWorkerConstructor.h" + +#include "DedicatedWorker.h" +#include "Document.h" +#include "ExceptionCode.h" +#include "JSDOMWindowCustom.h" +#include "JSDedicatedWorker.h" + +using namespace JSC; + +namespace WebCore { + +const ClassInfo JSDedicatedWorkerConstructor::s_info = { "DedicatedWorkerConstructor", 0, 0, 0 }; + +JSDedicatedWorkerConstructor::JSDedicatedWorkerConstructor(ExecState* exec) + : DOMObject(JSDedicatedWorkerConstructor::createStructureID(exec->lexicalGlobalObject()->objectPrototype())) +{ + putDirect(exec->propertyNames().length, jsNumber(exec, 1), ReadOnly|DontDelete|DontEnum); +} + +static JSObject* constructDedicatedWorker(ExecState* exec, JSObject* constructor, const ArgList& args) +{ + if (args.size() == 0) + return throwError(exec, SyntaxError, "Not enough arguments"); + + UString scriptURL = args.at(exec, 0)->toString(exec); + + DOMWindow* window = asJSDOMWindow(exec->lexicalGlobalObject())->impl(); + + ExceptionCode ec = 0; + RefPtr<DedicatedWorker> worker = DedicatedWorker::create(scriptURL, window->document(), ec); + setDOMException(exec, ec); + + return asObject(toJS(exec, worker.release())); +} + +ConstructType JSDedicatedWorkerConstructor::getConstructData(ConstructData& constructData) +{ + constructData.native.function = constructDedicatedWorker; + return ConstructTypeHost; +} + +} // namespace WebCore + +#endif // ENABLE(WORKERS) diff --git a/WebCore/bindings/js/JSDedicatedWorkerConstructor.h b/WebCore/bindings/js/JSDedicatedWorkerConstructor.h new file mode 100644 index 0000000..3eda174 --- /dev/null +++ b/WebCore/bindings/js/JSDedicatedWorkerConstructor.h @@ -0,0 +1,51 @@ +/* + * Copyright (C) 2008 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef JSDedicatedWorkerConstructor_h +#define JSDedicatedWorkerConstructor_h + +#if ENABLE(WORKERS) + +#include "JSDOMBinding.h" + +namespace WebCore { + + class JSDedicatedWorkerConstructor : public DOMObject { + public: + JSDedicatedWorkerConstructor(JSC::ExecState*); + + static const JSC::ClassInfo s_info; + + private: + virtual JSC::ConstructType getConstructData(JSC::ConstructData&); + + virtual const JSC::ClassInfo* classInfo() const { return &s_info; } + }; + +} // namespace WebCore + +#endif // ENABLE(WORKERS) + +#endif // JSDedicatedWorkerConstructor_h diff --git a/WebCore/bindings/js/JSDedicatedWorkerCustom.cpp b/WebCore/bindings/js/JSDedicatedWorkerCustom.cpp new file mode 100644 index 0000000..d70f55a --- /dev/null +++ b/WebCore/bindings/js/JSDedicatedWorkerCustom.cpp @@ -0,0 +1,124 @@ +/* + * Copyright (C) 2008 Apple Inc. All Rights Reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" + +#if ENABLE(WORKERS) + +#include "JSDedicatedWorker.h" + +#include "DedicatedWorker.h" +#include "Document.h" +#include "JSDOMWindowCustom.h" +#include "JSEventListener.h" +#include "JSMessagePort.h" +#include "MessagePort.h" + +using namespace JSC; + +namespace WebCore { + +void JSDedicatedWorker::mark() +{ + DOMObject::mark(); + + if (JSUnprotectedEventListener* listener = static_cast<JSUnprotectedEventListener*>(m_impl->onMessageListener())) + listener->mark(); + + if (JSUnprotectedEventListener* listener = static_cast<JSUnprotectedEventListener*>(m_impl->onCloseListener())) + listener->mark(); + + if (JSUnprotectedEventListener* listener = static_cast<JSUnprotectedEventListener*>(m_impl->onErrorListener())) + listener->mark(); +} + +JSValue* JSDedicatedWorker::startConversation(ExecState* exec, const ArgList& args) +{ + DOMWindow* window = asJSDOMWindow(exec->lexicalGlobalObject())->impl(); + const UString& message = args.at(exec, 0)->toString(exec); + + return toJS(exec, impl()->startConversation(window->document(), message).get()); +} + +void JSDedicatedWorker::setOnmessage(ExecState* exec, JSValue* value) +{ + Document* document = impl()->document(); + if (!document) + return; + JSDOMWindow* window = toJSDOMWindow(document->frame()); + if (!window) + return; + impl()->setOnMessageListener(window->findOrCreateJSUnprotectedEventListener(exec, value, true)); +} + +JSValue* JSDedicatedWorker::onmessage(ExecState*) const +{ + if (JSUnprotectedEventListener* listener = static_cast<JSUnprotectedEventListener*>(impl()->onMessageListener())) + if (JSObject* listenerObj = listener->listenerObj()) + return listenerObj; + return jsNull(); +} + +void JSDedicatedWorker::setOnclose(ExecState* exec, JSValue* value) +{ + Document* document = impl()->document(); + if (!document) + return; + JSDOMWindow* window = toJSDOMWindow(document->frame()); + if (!window) + return; + impl()->setOnCloseListener(window->findOrCreateJSUnprotectedEventListener(exec, value, true)); +} + +JSValue* JSDedicatedWorker::onclose(ExecState*) const +{ + if (JSUnprotectedEventListener* listener = static_cast<JSUnprotectedEventListener*>(impl()->onCloseListener())) + if (JSObject* listenerObj = listener->listenerObj()) + return listenerObj; + return jsNull(); +} + +void JSDedicatedWorker::setOnerror(ExecState* exec, JSValue* value) +{ + Document* document = impl()->document(); + if (!document) + return; + JSDOMWindow* window = toJSDOMWindow(document->frame()); + if (!window) + return; + impl()->setOnErrorListener(window->findOrCreateJSUnprotectedEventListener(exec, value, true)); +} + +JSValue* JSDedicatedWorker::onerror(ExecState*) const +{ + if (JSUnprotectedEventListener* listener = static_cast<JSUnprotectedEventListener*>(impl()->onErrorListener())) + if (JSObject* listenerObj = listener->listenerObj()) + return listenerObj; + return jsNull(); +} + +} // namespace WebCore + +#endif // ENABLE(WORKERS) diff --git a/WebCore/bindings/js/JSDocumentCustom.cpp b/WebCore/bindings/js/JSDocumentCustom.cpp index 133c576..661dbed 100644 --- a/WebCore/bindings/js/JSDocumentCustom.cpp +++ b/WebCore/bindings/js/JSDocumentCustom.cpp @@ -21,29 +21,32 @@ #include "JSDocument.h" #include "DOMWindow.h" -#include "Document.h" +#include "ExceptionCode.h" #include "Frame.h" #include "FrameLoader.h" #include "HTMLDocument.h" -#include "JSDOMWindow.h" +#include "JSDOMWindowCustom.h" #include "JSHTMLDocument.h" #include "JSLocation.h" -#include "kjs_binding.h" -#include "kjs_proxy.h" +#include "JSNodeList.h" +#include "Location.h" +#include "NodeList.h" +#include "ScriptController.h" #if ENABLE(SVG) #include "JSSVGDocument.h" #include "SVGDocument.h" #endif -namespace WebCore { +using namespace JSC; -using namespace KJS; +namespace WebCore { void JSDocument::mark() { JSEventTargetNode::mark(); - ScriptInterpreter::markDOMNodesForDocument(static_cast<Document*>(impl())); + markDOMNodesForDocument(impl()); + markActiveObjectsForContext(*Heap::heap(this)->globalData(), impl()); } JSValue* JSDocument::location(ExecState* exec) const @@ -52,9 +55,7 @@ JSValue* JSDocument::location(ExecState* exec) const if (!frame) return jsNull(); - KJS::Window* win = KJS::Window::retrieveWindow(frame); - ASSERT(win); - return win->location(); + return toJS(exec, frame->domWindow()->location()); } void JSDocument::setLocation(ExecState* exec, JSValue* value) @@ -67,47 +68,43 @@ void JSDocument::setLocation(ExecState* exec, JSValue* value) // IE and Mozilla both resolve the URL relative to the source frame, // not the target frame. - Frame* activeFrame = static_cast<JSDOMWindow*>(exec->dynamicGlobalObject())->impl()->frame(); + Frame* activeFrame = asJSDOMWindow(exec->dynamicGlobalObject())->impl()->frame(); if (activeFrame) - str = activeFrame->document()->completeURL(str); + str = activeFrame->document()->completeURL(str).string(); - bool userGesture = activeFrame->scriptProxy()->processingUserGesture(); + bool userGesture = activeFrame->script()->processingUserGesture(); frame->loader()->scheduleLocationChange(str, activeFrame->loader()->outgoingReferrer(), false, userGesture); } -JSValue* toJS(ExecState* exec, Document* doc) +JSValue* toJS(ExecState* exec, Document* document) { - if (!doc) + if (!document) return jsNull(); - JSDocument* ret = static_cast<JSDocument*>(ScriptInterpreter::getDOMObject(doc)); - if (ret) - return ret; + DOMObject* wrapper = getCachedDOMObjectWrapper(exec->globalData(), document); + if (wrapper) + return wrapper; - if (doc->isHTMLDocument()) - ret = new JSHTMLDocument(JSHTMLDocumentPrototype::self(exec), static_cast<HTMLDocument*>(doc)); + if (document->isHTMLDocument()) + wrapper = CREATE_DOM_OBJECT_WRAPPER(exec, HTMLDocument, document); #if ENABLE(SVG) - else if (doc->isSVGDocument()) - ret = new JSSVGDocument(JSSVGDocumentPrototype::self(exec), static_cast<SVGDocument*>(doc)); + else if (document->isSVGDocument()) + wrapper = CREATE_DOM_OBJECT_WRAPPER(exec, SVGDocument, document); #endif else - ret = new JSDocument(JSDocumentPrototype::self(exec), doc); + wrapper = CREATE_DOM_OBJECT_WRAPPER(exec, Document, document); // Make sure the document is kept around by the window object, and works right with the // back/forward cache. - if (doc->frame()) - KJS::Window::retrieveWindow(doc->frame())->putDirect("document", ret, DontDelete|ReadOnly); - else { + if (!document->frame()) { size_t nodeCount = 0; - for (Node* n = doc; n; n = n->traverseNextNode()) + for (Node* n = document; n; n = n->traverseNextNode()) nodeCount++; - Collector::reportExtraMemoryCost(nodeCount * sizeof(Node)); + exec->heap()->reportExtraMemoryCost(nodeCount * sizeof(Node)); } - ScriptInterpreter::putDOMObject(doc, ret); - - return ret; + return wrapper; } } // namespace WebCore diff --git a/WebCore/bindings/js/JSDocumentFragmentCustom.cpp b/WebCore/bindings/js/JSDocumentFragmentCustom.cpp new file mode 100644 index 0000000..7bc7d68 --- /dev/null +++ b/WebCore/bindings/js/JSDocumentFragmentCustom.cpp @@ -0,0 +1,40 @@ +/* + * Copyright (C) 2008 Apple Inc. All Rights Reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "JSDocumentFragment.h" + +#include "DocumentFragment.h" +#include "Element.h" +#include "ExceptionCode.h" +#include "JSElement.h" +#include "JSNodeList.h" +#include "NodeList.h" + +using namespace JSC; + +namespace WebCore { + +} // namespace WebCore diff --git a/WebCore/bindings/js/JSElementCustom.cpp b/WebCore/bindings/js/JSElementCustom.cpp index f300f85..22480a2 100644 --- a/WebCore/bindings/js/JSElementCustom.cpp +++ b/WebCore/bindings/js/JSElementCustom.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2007 Apple Inc. All rights reserved. + * Copyright (C) 2007, 2008 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -30,31 +30,30 @@ #include "config.h" #include "JSElement.h" -#include "Attr.h" -#include "Document.h" -#include "Element.h" #include "CSSHelper.h" +#include "Document.h" #include "ExceptionCode.h" #include "HTMLFrameElementBase.h" #include "HTMLNames.h" -#include "PlatformString.h" -#include "kjs_binding.h" -#include "kjs_dom.h" -#ifdef ANDROID_JAVASCRIPT_SECURITY -#include "KURL.h" +#include "JSAttr.h" +#include "JSHTMLElementWrapperFactory.h" +#include "JSNodeList.h" +#include "NodeList.h" + +#if ENABLE(SVG) +#include "JSSVGElementWrapperFactory.h" +#include "SVGElement.h" #endif +using namespace JSC; + namespace WebCore { using namespace HTMLNames; -static inline bool allowSettingSrcToJavascriptURL(KJS::ExecState* exec, Element* element, String name, String value) +static inline bool allowSettingSrcToJavascriptURL(ExecState* exec, Element* element, const String& name, const String& value) { -#ifdef ANDROID_JAVASCRIPT_SECURITY if ((element->hasTagName(iframeTag) || element->hasTagName(frameTag)) && equalIgnoringCase(name, "src") && protocolIs(parseURL(value), "javascript")) { -#else - if ((element->hasTagName(iframeTag) || element->hasTagName(frameTag)) && equalIgnoringCase(name, "src") && parseURL(value).startsWith("javascript:", false)) { -#endif HTMLFrameElementBase* frame = static_cast<HTMLFrameElementBase*>(element); if (!checkNodeSecurity(exec, frame->contentDocument())) return false; @@ -62,73 +61,91 @@ static inline bool allowSettingSrcToJavascriptURL(KJS::ExecState* exec, Element* return true; } -KJS::JSValue* JSElement::setAttribute(KJS::ExecState* exec, const KJS::List& args) +JSValue* JSElement::setAttribute(ExecState* exec, const ArgList& args) { ExceptionCode ec = 0; - String name = args[0]->toString(exec); - String value = args[1]->toString(exec); + AtomicString name = args.at(exec, 0)->toString(exec); + AtomicString value = args.at(exec, 1)->toString(exec); Element* imp = impl(); if (!allowSettingSrcToJavascriptURL(exec, imp, name, value)) - return KJS::jsUndefined(); + return jsUndefined(); imp->setAttribute(name, value, ec); - KJS::setDOMException(exec, ec); - return KJS::jsUndefined(); + setDOMException(exec, ec); + return jsUndefined(); } -KJS::JSValue* JSElement::setAttributeNode(KJS::ExecState* exec, const KJS::List& args) +JSValue* JSElement::setAttributeNode(ExecState* exec, const ArgList& args) { ExceptionCode ec = 0; - bool newAttrOk; - Attr* newAttr = toAttr(args[0], newAttrOk); - if (!newAttrOk) { + Attr* newAttr = toAttr(args.at(exec, 0)); + if (!newAttr) { setDOMException(exec, TYPE_MISMATCH_ERR); - return KJS::jsUndefined(); + return jsUndefined(); } Element* imp = impl(); if (!allowSettingSrcToJavascriptURL(exec, imp, newAttr->name(), newAttr->value())) - return KJS::jsUndefined(); + return jsUndefined(); - KJS::JSValue* result = toJS(exec, WTF::getPtr(imp->setAttributeNode(newAttr, ec))); - KJS::setDOMException(exec, ec); + JSValue* result = toJS(exec, WTF::getPtr(imp->setAttributeNode(newAttr, ec))); + setDOMException(exec, ec); return result; } -KJS::JSValue* JSElement::setAttributeNS(KJS::ExecState* exec, const KJS::List& args) +JSValue* JSElement::setAttributeNS(ExecState* exec, const ArgList& args) { ExceptionCode ec = 0; - String namespaceURI = valueToStringWithNullCheck(exec, args[0]); - String qualifiedName = args[1]->toString(exec); - String value = args[2]->toString(exec); + AtomicString namespaceURI = valueToStringWithNullCheck(exec, args.at(exec, 0)); + AtomicString qualifiedName = args.at(exec, 1)->toString(exec); + AtomicString value = args.at(exec, 2)->toString(exec); Element* imp = impl(); if (!allowSettingSrcToJavascriptURL(exec, imp, qualifiedName, value)) - return KJS::jsUndefined(); + return jsUndefined(); imp->setAttributeNS(namespaceURI, qualifiedName, value, ec); - KJS::setDOMException(exec, ec); - return KJS::jsUndefined(); + setDOMException(exec, ec); + return jsUndefined(); } -KJS::JSValue* JSElement::setAttributeNodeNS(KJS::ExecState* exec, const KJS::List& args) +JSValue* JSElement::setAttributeNodeNS(ExecState* exec, const ArgList& args) { ExceptionCode ec = 0; - bool newAttrOk; - Attr* newAttr = toAttr(args[0], newAttrOk); - if (!newAttrOk) { - KJS::setDOMException(exec, TYPE_MISMATCH_ERR); - return KJS::jsUndefined(); + Attr* newAttr = toAttr(args.at(exec, 0)); + if (!newAttr) { + setDOMException(exec, TYPE_MISMATCH_ERR); + return jsUndefined(); } Element* imp = impl(); if (!allowSettingSrcToJavascriptURL(exec, imp, newAttr->name(), newAttr->value())) - return KJS::jsUndefined(); + return jsUndefined(); - KJS::JSValue* result = toJS(exec, WTF::getPtr(imp->setAttributeNodeNS(newAttr, ec))); - KJS::setDOMException(exec, ec); + JSValue* result = toJS(exec, WTF::getPtr(imp->setAttributeNodeNS(newAttr, ec))); + setDOMException(exec, ec); return result; } +JSValue* toJSNewlyCreated(ExecState* exec, Element* element) +{ + if (!element) + return jsNull(); + + ASSERT(!getCachedDOMNodeWrapper(element->document(), element)); + + JSNode* wrapper; + if (element->isHTMLElement()) + wrapper = createJSHTMLWrapper(exec, static_cast<HTMLElement*>(element)); +#if ENABLE(SVG) + else if (element->isSVGElement()) + wrapper = createJSSVGWrapper(exec, static_cast<SVGElement*>(element)); +#endif + else + wrapper = CREATE_DOM_NODE_WRAPPER(exec, Element, element); + + return wrapper; +} + } // namespace WebCore diff --git a/WebCore/bindings/js/JSEventCustom.cpp b/WebCore/bindings/js/JSEventCustom.cpp index 4ba7f96..9c7d7a0 100644 --- a/WebCore/bindings/js/JSEventCustom.cpp +++ b/WebCore/bindings/js/JSEventCustom.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2007 Apple Inc. All rights reserved. + * Copyright (C) 2007, 2008 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -31,6 +31,7 @@ #include "Clipboard.h" #include "Event.h" +#include "JSClipboard.h" #include "JSKeyboardEvent.h" #include "JSMessageEvent.h" #include "JSMouseEvent.h" @@ -39,7 +40,10 @@ #include "JSProgressEvent.h" #include "JSTextEvent.h" #include "JSUIEvent.h" +#include "JSWebKitAnimationEvent.h" +#include "JSWebKitTransitionEvent.h" #include "JSWheelEvent.h" +#include "JSXMLHttpRequestProgressEvent.h" #include "KeyboardEvent.h" #include "MessageEvent.h" #include "MouseEvent.h" @@ -48,10 +52,28 @@ #include "ProgressEvent.h" #include "TextEvent.h" #include "UIEvent.h" +#include "WebKitAnimationEvent.h" +#include "WebKitTransitionEvent.h" #include "WheelEvent.h" -#include "kjs_events.h" +#include "XMLHttpRequestProgressEvent.h" +#include <runtime/JSLock.h> -using namespace KJS; +#if ENABLE(DOM_STORAGE) +#include "JSStorageEvent.h" +#include "StorageEvent.h" +#endif + +#if ENABLE(SVG) +#include "JSSVGZoomEvent.h" +#include "SVGZoomEvent.h" +#endif + +#if ENABLE(TOUCH_EVENTS) // Android +#include "JSTouchEvent.h" +#include "TouchEvent.h" +#endif + +using namespace JSC; namespace WebCore { @@ -62,41 +84,58 @@ JSValue* JSEvent::clipboardData(ExecState* exec) const JSValue* toJS(ExecState* exec, Event* event) { - JSLock lock; + JSLock lock(false); if (!event) return jsNull(); + DOMObject* wrapper = getCachedDOMObjectWrapper(exec->globalData(), event); + if (wrapper) + return wrapper; - DOMObject* ret = ScriptInterpreter::getDOMObject(event); - if (ret) - return ret; - - if (event->isKeyboardEvent()) - ret = new JSKeyboardEvent(JSKeyboardEventPrototype::self(exec), static_cast<KeyboardEvent*>(event)); - else if (event->isTextEvent()) - ret = new JSTextEvent(JSTextEventPrototype::self(exec), static_cast<TextEvent*>(event)); - else if (event->isMouseEvent()) - ret = new JSMouseEvent(JSMouseEventPrototype::self(exec), static_cast<MouseEvent*>(event)); - else if (event->isWheelEvent()) - ret = new JSWheelEvent(JSWheelEventPrototype::self(exec), static_cast<WheelEvent*>(event)); - else if (event->isUIEvent()) - ret = new JSUIEvent(JSUIEventPrototype::self(exec), static_cast<UIEvent*>(event)); - else if (event->isMutationEvent()) - ret = new JSMutationEvent(JSMutationEventPrototype::self(exec), static_cast<MutationEvent*>(event)); + if (event->isUIEvent()) { + if (event->isKeyboardEvent()) + wrapper = CREATE_DOM_OBJECT_WRAPPER(exec, KeyboardEvent, event); + else if (event->isTextEvent()) + wrapper = CREATE_DOM_OBJECT_WRAPPER(exec, TextEvent, event); + else if (event->isMouseEvent()) + wrapper = CREATE_DOM_OBJECT_WRAPPER(exec, MouseEvent, event); + else if (event->isWheelEvent()) + wrapper = CREATE_DOM_OBJECT_WRAPPER(exec, WheelEvent, event); +#if ENABLE(SVG) + else if (event->isSVGZoomEvent()) + wrapper = CREATE_SVG_OBJECT_WRAPPER(exec, SVGZoomEvent, event, 0); +#endif +#if ENABLE(TOUCH_EVENTS) // Android + else if (event->isTouchEvent()) + wrapper = CREATE_DOM_OBJECT_WRAPPER(exec, TouchEvent, event); +#endif + else + wrapper = CREATE_DOM_OBJECT_WRAPPER(exec, UIEvent, event); + } else if (event->isMutationEvent()) + wrapper = CREATE_DOM_OBJECT_WRAPPER(exec, MutationEvent, event); else if (event->isOverflowEvent()) - ret = new JSOverflowEvent(JSOverflowEventPrototype::self(exec), static_cast<OverflowEvent*>(event)); -#if ENABLE(CROSS_DOCUMENT_MESSAGING) + wrapper = CREATE_DOM_OBJECT_WRAPPER(exec, OverflowEvent, event); else if (event->isMessageEvent()) - ret = new JSMessageEvent(JSMessageEventPrototype::self(exec), static_cast<MessageEvent*>(event)); + wrapper = CREATE_DOM_OBJECT_WRAPPER(exec, MessageEvent, event); + else if (event->isProgressEvent()) { + if (event->isXMLHttpRequestProgressEvent()) + wrapper = CREATE_DOM_OBJECT_WRAPPER(exec, XMLHttpRequestProgressEvent, event); + else + wrapper = CREATE_DOM_OBJECT_WRAPPER(exec, ProgressEvent, event); + } +#if ENABLE(DOM_STORAGE) + else if (event->isStorageEvent()) + wrapper = CREATE_DOM_OBJECT_WRAPPER(exec, StorageEvent, event); #endif - else if (event->isProgressEvent()) - ret = new JSProgressEvent(JSProgressEventPrototype::self(exec), static_cast<ProgressEvent*>(event)); + else if (event->isWebKitAnimationEvent()) + wrapper = CREATE_DOM_OBJECT_WRAPPER(exec, WebKitAnimationEvent, event); + else if (event->isWebKitTransitionEvent()) + wrapper = CREATE_DOM_OBJECT_WRAPPER(exec, WebKitTransitionEvent, event); else - ret = new JSEvent(JSEventPrototype::self(exec), event); + wrapper = CREATE_DOM_OBJECT_WRAPPER(exec, Event, event); - ScriptInterpreter::putDOMObject(event, ret); - return ret; + return wrapper; } } // namespace WebCore diff --git a/WebCore/bindings/js/JSEventListener.cpp b/WebCore/bindings/js/JSEventListener.cpp new file mode 100644 index 0000000..e72af16 --- /dev/null +++ b/WebCore/bindings/js/JSEventListener.cpp @@ -0,0 +1,337 @@ +/* + * Copyright (C) 2001 Peter Kelly (pmk@post.com) + * Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008 Apple Inc. All Rights Reserved. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include "config.h" +#include "JSEventListener.h" + +#include "CString.h" +#include "Console.h" +#include "DOMWindow.h" +#include "Document.h" +#include "Event.h" +#include "Frame.h" +#include "FrameLoader.h" +#include "JSDOMWindow.h" +#include "JSEvent.h" +#include "JSEventTarget.h" +#include "JSEventTargetNode.h" +#include "ScriptController.h" +#include <runtime/FunctionConstructor.h> +#include <runtime/JSLock.h> +#include <wtf/RefCountedLeakCounter.h> + +using namespace JSC; + +namespace WebCore { + +ASSERT_CLASS_FITS_IN_CELL(JSAbstractEventListener) + +void JSAbstractEventListener::handleEvent(Event* event, bool isWindowEvent) +{ + JSLock lock(false); + + JSObject* listener = listenerObj(); + if (!listener) + return; + + JSDOMGlobalObject* globalObject = this->globalObject(); + // Null check as clearGlobalObject() can clear this and we still get called back by + // xmlhttprequest objects. See http://bugs.webkit.org/show_bug.cgi?id=13275 + // FIXME: Is this check still necessary? Requests are supposed to be stopped before clearGlobalObject() is called. + if (!globalObject) + return; + + ScriptExecutionContext* scriptExecutionContext = globalObject->scriptExecutionContext(); + if (!scriptExecutionContext) + return; + + Frame* frame = 0; + if (scriptExecutionContext->isDocument()) { + JSDOMWindow* window = static_cast<JSDOMWindow*>(globalObject); + frame = window->impl()->frame(); + if (!frame) + return; + // The window must still be active in its frame. See <https://bugs.webkit.org/show_bug.cgi?id=21921>. + // FIXME: A better fix for this may be to change DOMWindow::frame() to not return a frame the detached window used to be in. + if (frame->domWindow() != window->impl()) + return; + // FIXME: Is this check needed for other contexts? + ScriptController* script = frame->script(); + if (!script->isEnabled() || script->isPaused()) + return; + } + + ExecState* exec = globalObject->globalExec(); + + JSValue* handleEventFunction = listener->get(exec, Identifier(exec, "handleEvent")); + CallData callData; + CallType callType = handleEventFunction->getCallData(callData); + if (callType == CallTypeNone) { + handleEventFunction = noValue(); + callType = listener->getCallData(callData); + } + + if (callType != CallTypeNone) { + ref(); + + ArgList args; + args.append(toJS(exec, event)); + + Event* savedEvent = globalObject->currentEvent(); + globalObject->setCurrentEvent(event); + + JSValue* retval; + if (handleEventFunction) { + globalObject->startTimeoutCheck(); + retval = call(exec, handleEventFunction, callType, callData, listener, args); + } else { + JSValue* thisValue; + if (isWindowEvent) + thisValue = globalObject->toThisObject(exec); + else + thisValue = toJS(exec, event->currentTarget()); + globalObject->startTimeoutCheck(); + retval = call(exec, listener, callType, callData, thisValue, args); + } + globalObject->stopTimeoutCheck(); + + globalObject->setCurrentEvent(savedEvent); + + if (exec->hadException()) { + // FIXME: Report exceptions in non-Document contexts. + if (frame) + frame->domWindow()->console()->reportCurrentException(exec); + } else { + if (!retval->isUndefinedOrNull() && event->storesResultAsString()) + event->storeResult(retval->toString(exec)); + if (m_isInline) { + bool retvalbool; + if (retval->getBoolean(retvalbool) && !retvalbool) + event->preventDefault(); + } + } + + Document::updateDocumentsRendering(); + deref(); + } +} + +bool JSAbstractEventListener::isInline() const +{ + return m_isInline; +} + +// ------------------------------------------------------------------------- + +JSUnprotectedEventListener::JSUnprotectedEventListener(JSObject* listener, JSDOMGlobalObject* globalObject, bool isInline) + : JSAbstractEventListener(isInline) + , m_listener(listener) + , m_globalObject(globalObject) +{ + if (m_listener) { + JSDOMWindow::UnprotectedListenersMap& listeners = isInline + ? globalObject->jsUnprotectedInlineEventListeners() : globalObject->jsUnprotectedEventListeners(); + listeners.set(m_listener, this); + } +} + +JSUnprotectedEventListener::~JSUnprotectedEventListener() +{ + if (m_listener && m_globalObject) { + JSDOMWindow::UnprotectedListenersMap& listeners = isInline() + ? m_globalObject->jsUnprotectedInlineEventListeners() : m_globalObject->jsUnprotectedEventListeners(); + listeners.remove(m_listener); + } +} + +JSObject* JSUnprotectedEventListener::listenerObj() const +{ + return m_listener; +} + +JSDOMGlobalObject* JSUnprotectedEventListener::globalObject() const +{ + return m_globalObject; +} + +void JSUnprotectedEventListener::clearGlobalObject() +{ + m_globalObject = 0; +} + +void JSUnprotectedEventListener::mark() +{ + if (m_listener && !m_listener->marked()) + m_listener->mark(); +} + +#ifndef NDEBUG +static WTF::RefCountedLeakCounter eventListenerCounter("EventListener"); +#endif + +// ------------------------------------------------------------------------- + +JSEventListener::JSEventListener(JSObject* listener, JSDOMGlobalObject* globalObject, bool isInline) + : JSAbstractEventListener(isInline) + , m_listener(listener) + , m_globalObject(globalObject) +{ + if (m_listener) { + JSDOMWindow::ListenersMap& listeners = isInline + ? m_globalObject->jsInlineEventListeners() : m_globalObject->jsEventListeners(); + listeners.set(m_listener, this); + } +#ifndef NDEBUG + eventListenerCounter.increment(); +#endif +} + +JSEventListener::~JSEventListener() +{ + if (m_listener && m_globalObject) { + JSDOMWindow::ListenersMap& listeners = isInline() + ? m_globalObject->jsInlineEventListeners() : m_globalObject->jsEventListeners(); + listeners.remove(m_listener); + } +#ifndef NDEBUG + eventListenerCounter.decrement(); +#endif +} + +JSObject* JSEventListener::listenerObj() const +{ + return m_listener; +} + +JSDOMGlobalObject* JSEventListener::globalObject() const +{ + return m_globalObject; +} + +void JSEventListener::clearGlobalObject() +{ + m_globalObject = 0; +} + +// ------------------------------------------------------------------------- + +JSLazyEventListener::JSLazyEventListener(LazyEventListenerType type, const String& functionName, const String& code, JSDOMGlobalObject* globalObject, Node* node, int lineNumber) + : JSEventListener(0, globalObject, true) + , m_functionName(functionName) + , m_code(code) + , m_parsed(false) + , m_lineNumber(lineNumber) + , m_originalNode(node) + , m_type(type) +{ + // We don't retain the original node because we assume it + // will stay alive as long as this handler object is around + // and we need to avoid a reference cycle. If JS transfers + // this handler to another node, parseCode will be called and + // then originalNode is no longer needed. + + // A JSLazyEventListener can be created with a line number of zero when it is created with + // a setAttribute call from JavaScript, so make the line number 1 in that case. + if (m_lineNumber == 0) + m_lineNumber = 1; +} + +JSObject* JSLazyEventListener::listenerObj() const +{ + parseCode(); + return m_listener; +} + +// Helper function +inline JSValue* eventParameterName(JSLazyEventListener::LazyEventListenerType type, ExecState* exec) +{ + switch (type) { + case JSLazyEventListener::HTMLLazyEventListener: + return jsNontrivialString(exec, "event"); +#if ENABLE(SVG) + case JSLazyEventListener::SVGLazyEventListener: + return jsNontrivialString(exec, "evt"); +#endif + default: + ASSERT_NOT_REACHED(); + return jsUndefined(); + } +} + +void JSLazyEventListener::parseCode() const +{ + if (m_parsed) + return; + + Frame* frame = 0; + if (globalObject()->scriptExecutionContext()->isDocument()) { + JSDOMWindow* window = static_cast<JSDOMWindow*>(globalObject()); + frame = window->impl()->frame(); + if (!frame) + return; + // FIXME: Is this check needed for non-Document contexts? + ScriptController* script = frame->script(); + if (!script->isEnabled() || script->isPaused()) + return; + } + + m_parsed = true; + + ExecState* exec = globalObject()->globalExec(); + + ArgList args; + UString sourceURL(globalObject()->scriptExecutionContext()->url().string()); + args.append(eventParameterName(m_type, exec)); + args.append(jsString(exec, m_code)); + + // FIXME: Passing the document's URL to construct is not always correct, since this event listener might + // have been added with setAttribute from a script, and we should pass String() in that case. + m_listener = constructFunction(exec, args, Identifier(exec, m_functionName), sourceURL, m_lineNumber); // FIXME: is globalExec ok? + + JSFunction* listenerAsFunction = static_cast<JSFunction*>(m_listener.get()); + + if (exec->hadException()) { + exec->clearException(); + + // failed to parse, so let's just make this listener a no-op + m_listener = 0; + } else if (m_originalNode) { + // Add the event's home element to the scope + // (and the document, and the form - see JSHTMLElement::eventHandlerScope) + ScopeChain scope = listenerAsFunction->scope(); + + JSValue* thisObj = toJS(exec, m_originalNode); + if (thisObj->isObject()) { + static_cast<JSEventTargetNode*>(asObject(thisObj))->pushEventHandlerScope(exec, scope); + listenerAsFunction->setScope(scope); + } + } + + // no more need to keep the unparsed code around + m_functionName = String(); + m_code = String(); + + if (m_listener) { + ASSERT(isInline()); + JSDOMWindow::ListenersMap& listeners = globalObject()->jsInlineEventListeners(); + listeners.set(m_listener, const_cast<JSLazyEventListener*>(this)); + } +} + +} // namespace WebCore diff --git a/WebCore/bindings/js/JSEventListener.h b/WebCore/bindings/js/JSEventListener.h new file mode 100644 index 0000000..3c9edd0 --- /dev/null +++ b/WebCore/bindings/js/JSEventListener.h @@ -0,0 +1,125 @@ +/* + * Copyright (C) 2001 Peter Kelly (pmk@post.com) + * Copyright (C) 2003, 2008 Apple Inc. All rights reserved. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#ifndef JSEventListener_h +#define JSEventListener_h + +#include "EventListener.h" +#include "PlatformString.h" +#include <kjs/protect.h> + +namespace WebCore { + + class Event; + class JSDOMGlobalObject; + class Node; + + class JSAbstractEventListener : public EventListener { + public: + virtual void handleEvent(Event*, bool isWindowEvent); + virtual bool isInline() const; + virtual JSC::JSObject* listenerObj() const = 0; + virtual JSDOMGlobalObject* globalObject() const = 0; + + protected: + JSAbstractEventListener(bool isInline) + : m_isInline(isInline) + { + } + + private: + bool m_isInline; + }; + + class JSUnprotectedEventListener : public JSAbstractEventListener { + public: + static PassRefPtr<JSUnprotectedEventListener> create(JSC::JSObject* listener, JSDOMGlobalObject* globalObject, bool isInline) + { + return adoptRef(new JSUnprotectedEventListener(listener, globalObject, isInline)); + } + virtual ~JSUnprotectedEventListener(); + + virtual JSC::JSObject* listenerObj() const; + virtual JSDOMGlobalObject* globalObject() const; + void clearGlobalObject(); + void mark(); + + private: + JSUnprotectedEventListener(JSC::JSObject* listener, JSDOMGlobalObject*, bool isInline); + + JSC::JSObject* m_listener; + JSDOMGlobalObject* m_globalObject; + }; + + class JSEventListener : public JSAbstractEventListener { + public: + static PassRefPtr<JSEventListener> create(JSC::JSObject* listener, JSDOMGlobalObject* globalObject, bool isInline) + { + return adoptRef(new JSEventListener(listener, globalObject, isInline)); + } + virtual ~JSEventListener(); + + virtual JSC::JSObject* listenerObj() const; + virtual JSDOMGlobalObject* globalObject() const; + void clearGlobalObject(); + + protected: + JSEventListener(JSC::JSObject* listener, JSDOMGlobalObject*, bool isInline); + + mutable JSC::ProtectedPtr<JSC::JSObject> m_listener; + + private: + JSC::ProtectedPtr<JSDOMGlobalObject> m_globalObject; + }; + + class JSLazyEventListener : public JSEventListener { + public: + enum LazyEventListenerType { + HTMLLazyEventListener +#if ENABLE(SVG) + , SVGLazyEventListener +#endif + }; + + virtual bool wasCreatedFromMarkup() const { return true; } + + static PassRefPtr<JSLazyEventListener> create(LazyEventListenerType type, const String& functionName, const String& code, JSDOMGlobalObject* globalObject, Node* node, int lineNumber) + { + return adoptRef(new JSLazyEventListener(type, functionName, code, globalObject, node, lineNumber)); + } + virtual JSC::JSObject* listenerObj() const; + + protected: + JSLazyEventListener(LazyEventListenerType type, const String& functionName, const String& code, JSDOMGlobalObject*, Node*, int lineNumber); + + private: + void parseCode() const; + + mutable String m_functionName; + mutable String m_code; + mutable bool m_parsed; + int m_lineNumber; + Node* m_originalNode; + + LazyEventListenerType m_type; + }; + +} // namespace WebCore + +#endif // JSEventListener_h diff --git a/WebCore/bindings/js/JSEventTarget.cpp b/WebCore/bindings/js/JSEventTarget.cpp new file mode 100644 index 0000000..185756d --- /dev/null +++ b/WebCore/bindings/js/JSEventTarget.cpp @@ -0,0 +1,78 @@ +/* + * Copyright (C) 2008 Apple Inc. All Rights Reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "JSEventTarget.h" + +#include "Document.h" +#include "JSEventListener.h" +#include "JSEventTargetNode.h" +#include "JSMessagePort.h" +#include "JSXMLHttpRequestUpload.h" + +#if ENABLE(SVG) +#include "SVGElementInstance.h" +#include "JSSVGElementInstance.h" +#endif + +using namespace JSC; + +namespace WebCore { + +JSValue* toJS(ExecState* exec, EventTarget* target) +{ + if (!target) + return jsNull(); + +#if ENABLE(SVG) + // SVGElementInstance supports both toSVGElementInstance and toNode since so much mouse handling code depends on toNode returning a valid node. + if (SVGElementInstance* instance = target->toSVGElementInstance()) + return toJS(exec, instance); +#endif + + if (Node* node = target->toNode()) + return toJS(exec, node); + + if (XMLHttpRequest* xhr = target->toXMLHttpRequest()) + // XMLHttpRequest is always created via JS, so we don't need to use cacheDOMObject() here. + return getCachedDOMObjectWrapper(exec->globalData(), xhr); + + if (XMLHttpRequestUpload* upload = target->toXMLHttpRequestUpload()) + return toJS(exec, upload); + +#if ENABLE(OFFLINE_WEB_APPLICATIONS) + if (DOMApplicationCache* cache = target->toDOMApplicationCache()) + // DOMApplicationCache is always created via JS, so we don't need to use cacheDOMObject() here. + return getCachedDOMObjectWrapper(exec->globalData(), cache); +#endif + + if (MessagePort* messagePort = target->toMessagePort()) + return toJS(exec, messagePort); + + ASSERT_NOT_REACHED(); + return jsNull(); +} + +} // namespace WebCore diff --git a/WebCore/bindings/js/JSEventTarget.h b/WebCore/bindings/js/JSEventTarget.h new file mode 100644 index 0000000..1ee854f --- /dev/null +++ b/WebCore/bindings/js/JSEventTarget.h @@ -0,0 +1,43 @@ +/* + * Copyright (C) 2008 Apple Inc. All Rights Reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef JSEventTarget_h +#define JSEventTarget_h + +#include <runtime/JSValue.h> + +namespace JSC { + class ExecState; +} + +namespace WebCore { + + class EventTarget; + + JSC::JSValue* toJS(JSC::ExecState*, EventTarget*); + +} // namespace WebCore + +#endif // JSEventTarget_h diff --git a/WebCore/bindings/js/JSEventTargetBase.cpp b/WebCore/bindings/js/JSEventTargetBase.cpp deleted file mode 100644 index d15171c..0000000 --- a/WebCore/bindings/js/JSEventTargetBase.cpp +++ /dev/null @@ -1,244 +0,0 @@ -/* - * Copyright (C) 2007 Apple Inc. All rights reserved. - * (C) 2007 Nikolas Zimmermann <zimmermann@kde.org> - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" -#include "JSEventTargetBase.h" - -#include "JSEventTargetNode.h" - -#include "JSEventTargetBase.lut.h" - -using namespace KJS; - -namespace WebCore { - -/* Source for JSEventTargetPropertiesTable -@begin JSEventTargetPropertiesTable 50 -onabort WebCore::JSEventTargetProperties::OnAbort DontDelete -onblur WebCore::JSEventTargetProperties::OnBlur DontDelete -onchange WebCore::JSEventTargetProperties::OnChange DontDelete -onclick WebCore::JSEventTargetProperties::OnClick DontDelete -oncontextmenu WebCore::JSEventTargetProperties::OnContextMenu DontDelete -ondblclick WebCore::JSEventTargetProperties::OnDblClick DontDelete -onbeforecut WebCore::JSEventTargetProperties::OnBeforeCut DontDelete -oncut WebCore::JSEventTargetProperties::OnCut DontDelete -onbeforecopy WebCore::JSEventTargetProperties::OnBeforeCopy DontDelete -oncopy WebCore::JSEventTargetProperties::OnCopy DontDelete -onbeforepaste WebCore::JSEventTargetProperties::OnBeforePaste DontDelete -onpaste WebCore::JSEventTargetProperties::OnPaste DontDelete -ondrag WebCore::JSEventTargetProperties::OnDrag DontDelete -ondragend WebCore::JSEventTargetProperties::OnDragEnd DontDelete -ondragenter WebCore::JSEventTargetProperties::OnDragEnter DontDelete -ondragleave WebCore::JSEventTargetProperties::OnDragLeave DontDelete -ondragover WebCore::JSEventTargetProperties::OnDragOver DontDelete -ondragstart WebCore::JSEventTargetProperties::OnDragStart DontDelete -ondrop WebCore::JSEventTargetProperties::OnDrop DontDelete -onerror WebCore::JSEventTargetProperties::OnError DontDelete -onfocus WebCore::JSEventTargetProperties::OnFocus DontDelete -oninput WebCore::JSEventTargetProperties::OnInput DontDelete -onkeydown WebCore::JSEventTargetProperties::OnKeyDown DontDelete -onkeypress WebCore::JSEventTargetProperties::OnKeyPress DontDelete -onkeyup WebCore::JSEventTargetProperties::OnKeyUp DontDelete -onload WebCore::JSEventTargetProperties::OnLoad DontDelete -onmousedown WebCore::JSEventTargetProperties::OnMouseDown DontDelete -onmousemove WebCore::JSEventTargetProperties::OnMouseMove DontDelete -onmouseout WebCore::JSEventTargetProperties::OnMouseOut DontDelete -onmouseover WebCore::JSEventTargetProperties::OnMouseOver DontDelete -onmouseup WebCore::JSEventTargetProperties::OnMouseUp DontDelete -onmousewheel WebCore::JSEventTargetProperties::OnMouseWheel DontDelete -onreset WebCore::JSEventTargetProperties::OnReset DontDelete -onresize WebCore::JSEventTargetProperties::OnResize DontDelete -onscroll WebCore::JSEventTargetProperties::OnScroll DontDelete -onsearch WebCore::JSEventTargetProperties::OnSearch DontDelete -onselect WebCore::JSEventTargetProperties::OnSelect DontDelete -onselectstart WebCore::JSEventTargetProperties::OnSelectStart DontDelete -onsubmit WebCore::JSEventTargetProperties::OnSubmit DontDelete -onunload WebCore::JSEventTargetProperties::OnUnload DontDelete -@end -*/ - -/* -@begin JSEventTargetPrototypeTable 5 -addEventListener WebCore::jsEventTargetAddEventListener DontDelete|Function 3 -removeEventListener WebCore::jsEventTargetRemoveEventListener DontDelete|Function 3 -dispatchEvent WebCore::jsEventTargetDispatchEvent DontDelete|Function 1 -@end -*/ - -JSValue* jsEventTargetAddEventListener(ExecState* exec, JSObject* thisObj, const List& args) -{ - DOMExceptionTranslator exception(exec); - - Node* eventNode = 0; - EventTarget* eventTarget = 0; - if (!retrieveEventTargetAndCorrespondingNode(exec, thisObj, eventNode, eventTarget)) - return throwError(exec, TypeError); - - Frame* frame = eventNode->document()->frame(); - if (!frame) - return jsUndefined(); - - if (JSEventListener* listener = Window::retrieveWindow(frame)->findOrCreateJSEventListener(args[1])) - eventTarget->addEventListener(args[0]->toString(exec), listener, args[2]->toBoolean(exec)); - - return jsUndefined(); -} - -JSValue* jsEventTargetRemoveEventListener(ExecState* exec, JSObject* thisObj, const List& args) -{ - DOMExceptionTranslator exception(exec); - - Node* eventNode = 0; - EventTarget* eventTarget = 0; - if (!retrieveEventTargetAndCorrespondingNode(exec, thisObj, eventNode, eventTarget)) - return throwError(exec, TypeError); - - Frame* frame = eventNode->document()->frame(); - if (!frame) - return jsUndefined(); - - if (JSEventListener* listener = Window::retrieveWindow(frame)->findJSEventListener(args[1])) - eventTarget->removeEventListener(args[0]->toString(exec), listener, args[2]->toBoolean(exec)); - - return jsUndefined(); -} - -JSValue* jsEventTargetDispatchEvent(ExecState* exec, JSObject* thisObj, const List& args) -{ - Node* eventNode = 0; - EventTarget* eventTarget = 0; - if (!retrieveEventTargetAndCorrespondingNode(exec, thisObj, eventNode, eventTarget)) - return throwError(exec, TypeError); - - DOMExceptionTranslator exception(exec); - return jsBoolean(eventTarget->dispatchEvent(toEvent(args[0]), exception)); -} - -bool retrieveEventTargetAndCorrespondingNode(KJS::ExecState*, KJS::JSObject* thisObj, Node*& eventNode, EventTarget*& eventTarget) -{ - if (!thisObj->inherits(&JSNode::info)) - return false; - - JSEventTargetNode* jsNode = static_cast<JSEventTargetNode*>(thisObj); - ASSERT(jsNode); - - EventTargetNode* node = static_cast<EventTargetNode*>(jsNode->impl()); - ASSERT(node); - - eventNode = node; - eventTarget = node; - return true; -} - -AtomicString eventNameForPropertyToken(int token) -{ - switch (token) { - case JSEventTargetProperties::OnAbort: - return abortEvent; - case JSEventTargetProperties::OnBlur: - return blurEvent; - case JSEventTargetProperties::OnChange: - return changeEvent; - case JSEventTargetProperties::OnClick: - return clickEvent; - case JSEventTargetProperties::OnContextMenu: - return contextmenuEvent; - case JSEventTargetProperties::OnDblClick: - return dblclickEvent; - case JSEventTargetProperties::OnError: - return errorEvent; - case JSEventTargetProperties::OnFocus: - return focusEvent; - case JSEventTargetProperties::OnInput: - return inputEvent; - case JSEventTargetProperties::OnKeyDown: - return keydownEvent; - case JSEventTargetProperties::OnKeyPress: - return keypressEvent; - case JSEventTargetProperties::OnKeyUp: - return keyupEvent; - case JSEventTargetProperties::OnLoad: - return loadEvent; - case JSEventTargetProperties::OnMouseDown: - return mousedownEvent; - case JSEventTargetProperties::OnMouseMove: - return mousemoveEvent; - case JSEventTargetProperties::OnMouseOut: - return mouseoutEvent; - case JSEventTargetProperties::OnMouseOver: - return mouseoverEvent; - case JSEventTargetProperties::OnMouseUp: - return mouseupEvent; - case JSEventTargetProperties::OnMouseWheel: - return mousewheelEvent; - case JSEventTargetProperties::OnBeforeCut: - return beforecutEvent; - case JSEventTargetProperties::OnCut: - return cutEvent; - case JSEventTargetProperties::OnBeforeCopy: - return beforecopyEvent; - case JSEventTargetProperties::OnCopy: - return copyEvent; - case JSEventTargetProperties::OnBeforePaste: - return beforepasteEvent; - case JSEventTargetProperties::OnPaste: - return pasteEvent; - case JSEventTargetProperties::OnDragEnter: - return dragenterEvent; - case JSEventTargetProperties::OnDragOver: - return dragoverEvent; - case JSEventTargetProperties::OnDragLeave: - return dragleaveEvent; - case JSEventTargetProperties::OnDrop: - return dropEvent; - case JSEventTargetProperties::OnDragStart: - return dragstartEvent; - case JSEventTargetProperties::OnDrag: - return dragEvent; - case JSEventTargetProperties::OnDragEnd: - return dragendEvent; - case JSEventTargetProperties::OnReset: - return resetEvent; - case JSEventTargetProperties::OnResize: - return resizeEvent; - case JSEventTargetProperties::OnScroll: - return scrollEvent; - case JSEventTargetProperties::OnSearch: - return searchEvent; - case JSEventTargetProperties::OnSelect: - return selectEvent; - case JSEventTargetProperties::OnSelectStart: - return selectstartEvent; - case JSEventTargetProperties::OnSubmit: - return submitEvent; - case JSEventTargetProperties::OnUnload: - return unloadEvent; - } - - return AtomicString(); -} - -} // namespace WebCore diff --git a/WebCore/bindings/js/JSEventTargetBase.h b/WebCore/bindings/js/JSEventTargetBase.h index e62459a..e1395d3 100644 --- a/WebCore/bindings/js/JSEventTargetBase.h +++ b/WebCore/bindings/js/JSEventTargetBase.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2007 Apple Inc. All rights reserved. + * Copyright (C) 2007, 2008 Apple Inc. All rights reserved. * (C) 2007 Nikolas Zimmermann <zimmermann@kde.org> * * Redistribution and use in source and binary forms, with or without @@ -27,129 +27,72 @@ #ifndef JSEventTargetBase_h #define JSEventTargetBase_h -#include "Document.h" #include "Event.h" #include "EventNames.h" #include "JSEvent.h" -#include "kjs_events.h" -#include "kjs_window.h" -namespace KJS { - - extern const struct HashTable JSEventTargetPropertiesTable; - extern const struct HashTable JSEventTargetPrototypeTable; - -} - -namespace WebCore { - - using namespace EventNames; - - class AtomicString; - class EventTarget; - - // Event target properties (shared across all JSEventTarget* classes) - struct JSEventTargetProperties { - enum { - AddEventListener, RemoveEventListener, DispatchEvent, - OnAbort, OnBlur, OnChange, OnClick, OnContextMenu, OnDblClick, OnError, - OnDragEnter, OnDragOver, OnDragLeave, OnDrop, OnDragStart, OnDrag, OnDragEnd, - OnBeforeCut, OnCut, OnBeforeCopy, OnCopy, OnBeforePaste, OnPaste, OnSelectStart, - OnFocus, OnInput, OnKeyDown, OnKeyPress, OnKeyUp, OnLoad, OnMouseDown, - OnMouseMove, OnMouseOut, OnMouseOver, OnMouseUp, OnMouseWheel, OnReset, - OnResize, OnScroll, OnSearch, OnSelect, OnSubmit, OnUnload - }; - }; - - // Helper function for the partial specializated template functions below - bool retrieveEventTargetAndCorrespondingNode(KJS::ExecState*, KJS::JSObject* thisObj, Node*&, EventTarget*&); - - // Functions - KJS::JSValue* jsEventTargetAddEventListener(KJS::ExecState*, KJS::JSObject*, const KJS::List&); - KJS::JSValue* jsEventTargetRemoveEventListener(KJS::ExecState*, KJS::JSObject*, const KJS::List&); - KJS::JSValue* jsEventTargetDispatchEvent(KJS::ExecState*, KJS::JSObject*, const KJS::List&); - - // Helper function for getValueProperty/putValueProperty - AtomicString eventNameForPropertyToken(int token); - - template<class JSEventTarget> - class JSEventTargetBase { - public: - JSEventTargetBase() { } - - KJS::JSValue* getValueProperty(const JSEventTarget* owner, KJS::ExecState* exec, int token) const - { - AtomicString eventName = eventNameForPropertyToken(token); - if (!eventName.isEmpty()) - return owner->getListener(eventName); - - return KJS::jsUndefined(); - } - - void putValueProperty(const JSEventTarget* owner, KJS::ExecState* exec, int token, KJS::JSValue* value, int attr) - { - AtomicString eventName = eventNameForPropertyToken(token); - if (!eventName.isEmpty()) - owner->setListener(exec, eventName, value); - } - - private: - friend class JSEventTargetNode; - friend class JSEventTargetSVGElementInstance; - - template<class JSParent> - bool getOwnPropertySlot(JSEventTarget* owner, KJS::ExecState* exec, const KJS::Identifier& propertyName, KJS::PropertySlot& slot) - { - return KJS::getStaticValueSlot<JSEventTarget, JSParent>(exec, &KJS::JSEventTargetPropertiesTable, owner, propertyName, slot); - } - - template<class JSParent> - void put(JSEventTarget* owner, KJS::ExecState* exec, const KJS::Identifier& propertyName, KJS::JSValue* value, int attr) - { - KJS::lookupPut<JSEventTarget, JSParent>(exec, propertyName, value, attr, &KJS::JSEventTargetPropertiesTable, owner); - } - }; - - // This class is a modified version of the code the KJS_DEFINE_PROTOTYPE_WITH_PROTOTYPE - // and KJS_IMPLEMENT_PROTOTYPE macros produce - the idea is that classes like JSEventTargetNode - // and JSEventTargetSVGElementInstance can share a single prototype just differing in the - // naming "EventTargetNodePrototype" vs "EventTargetSVGElementInstancePrototype". Above mentioned - // macros force the existance of several prototype tables for each of the classes - avoid that. - template<class JSEventTargetPrototypeParent, class JSEventTargetPrototypeInformation> - class JSEventTargetPrototype : public KJS::JSObject { - public: - JSEventTargetPrototype(KJS::ExecState* exec) - : KJS::JSObject(JSEventTargetPrototypeParent::self(exec)) - { - } - - static KJS::JSObject* self(KJS::ExecState* exec) - { - static KJS::Identifier* prototypeName = new KJS::Identifier(JSEventTargetPrototypeInformation::prototypeClassName()); - - KJS::JSGlobalObject* globalObject = exec->lexicalGlobalObject(); - if (KJS::JSValue* objectValue = globalObject->getDirect(*prototypeName)) { - ASSERT(objectValue->isObject()); - return static_cast<KJS::JSObject*>(objectValue); - } - - KJS::JSObject* newObject = new JSEventTargetPrototype<JSEventTargetPrototypeParent, JSEventTargetPrototypeInformation>(exec); - globalObject->putDirect(*prototypeName, newObject, KJS::Internal | KJS::DontEnum); - return newObject; - } - - bool getOwnPropertySlot(KJS::ExecState* exec, const KJS::Identifier& propertyName, KJS::PropertySlot& slot) - { - return KJS::getStaticFunctionSlot<KJS::JSObject>(exec, &KJS::JSEventTargetPrototypeTable, this, propertyName, slot); - } - - virtual const KJS::ClassInfo* classInfo() const - { - static const KJS::ClassInfo s_classInfo = { JSEventTargetPrototypeInformation::prototypeClassName(), 0, &KJS::JSEventTargetPrototypeTable }; - return &s_classInfo; - } - }; - -} // namespace WebCore +#define JS_EVENT_LISTENER_FOR_EACH_LISTENER(specificEventTarget, macro) \ + macro(specificEventTarget, OnAbort, abortEvent) \ + macro(specificEventTarget, OnBlur, blurEvent) \ + macro(specificEventTarget, OnChange, changeEvent) \ + macro(specificEventTarget, OnClick, clickEvent) \ + macro(specificEventTarget, OnContextMenu, contextmenuEvent) \ + macro(specificEventTarget, OnDblClick, dblclickEvent) \ + macro(specificEventTarget, OnError, errorEvent) \ + macro(specificEventTarget, OnFocus, focusEvent) \ + macro(specificEventTarget, OnInput, inputEvent) \ + macro(specificEventTarget, OnKeyDown, keydownEvent) \ + macro(specificEventTarget, OnKeyPress, keypressEvent) \ + macro(specificEventTarget, OnKeyUp, keyupEvent) \ + macro(specificEventTarget, OnLoad, loadEvent) \ + macro(specificEventTarget, OnMouseDown, mousedownEvent) \ + macro(specificEventTarget, OnMouseMove, mousemoveEvent) \ + macro(specificEventTarget, OnMouseOut, mouseoutEvent) \ + macro(specificEventTarget, OnMouseOver, mouseoverEvent) \ + macro(specificEventTarget, OnMouseUp, mouseupEvent) \ + macro(specificEventTarget, OnMouseWheel, mousewheelEvent) \ + macro(specificEventTarget, OnBeforeCut, beforecutEvent) \ + macro(specificEventTarget, OnCut, cutEvent) \ + macro(specificEventTarget, OnBeforeCopy, beforecopyEvent) \ + macro(specificEventTarget, OnCopy, copyEvent) \ + macro(specificEventTarget, OnBeforePaste, beforepasteEvent) \ + macro(specificEventTarget, OnPaste, pasteEvent) \ + macro(specificEventTarget, OnDragEnter, dragenterEvent) \ + macro(specificEventTarget, OnDragOver, dragoverEvent) \ + macro(specificEventTarget, OnDragLeave, dragleaveEvent) \ + macro(specificEventTarget, OnDrop, dropEvent) \ + macro(specificEventTarget, OnDragStart, dragstartEvent) \ + macro(specificEventTarget, OnDrag, dragEvent) \ + macro(specificEventTarget, OnDragEnd, dragendEvent) \ + macro(specificEventTarget, OnReset, resetEvent) \ + macro(specificEventTarget, OnResize, resizeEvent) \ + macro(specificEventTarget, OnScroll, scrollEvent) \ + macro(specificEventTarget, OnSearch, searchEvent) \ + macro(specificEventTarget, OnSelect, selectEvent) \ + macro(specificEventTarget, OnSelectStart, selectstartEvent) \ + macro(specificEventTarget, OnSubmit, submitEvent) \ + macro(specificEventTarget, OnUnload, unloadEvent) \ +/* #if ENABLE(TOUCH_EVENTS) // Android */ \ + macro(specificEventTarget, OnTouchStart, touchstartEvent) \ + macro(specificEventTarget, OnTouchMove, touchmoveEvent) \ + macro(specificEventTarget, OnTouchEnd, touchendEvent) \ + macro(specificEventTarget, OnTouchCancel, touchcancelEvent) \ +/* #endif */ \ + +#define EVENT_LISTENER_GETTER(specificEventTarget, name, event) \ +JSC::JSValue* js##specificEventTarget##name(JSC::ExecState*, const JSC::Identifier&, const JSC::PropertySlot& slot) \ +{ \ + return static_cast<JS##specificEventTarget*>(slot.slotBase())->getListener(event); \ +} \ + +#define EVENT_LISTENER_SETTER(specificEventTarget, name, event) \ +void setJS##specificEventTarget##name(JSC::ExecState* exec, JSC::JSObject* baseObject, JSC::JSValue* value) \ +{ \ + static_cast<JS##specificEventTarget*>(baseObject)->setListener(exec, event, value); \ +} \ + +#define DECLARE_JS_EVENT_LISTENERS(specificEventTarget) \ + JS_EVENT_LISTENER_FOR_EACH_LISTENER(specificEventTarget, EVENT_LISTENER_GETTER) \ + JS_EVENT_LISTENER_FOR_EACH_LISTENER(specificEventTarget, EVENT_LISTENER_SETTER) \ #endif // JSEventTargetBase_h diff --git a/WebCore/bindings/js/JSEventTargetNode.cpp b/WebCore/bindings/js/JSEventTargetNode.cpp deleted file mode 100644 index d097aad..0000000 --- a/WebCore/bindings/js/JSEventTargetNode.cpp +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Copyright (C) 2007 Apple Inc. All rights reserved. - * (C) 2007 Nikolas Zimmermann <zimmermann@kde.org> - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" -#include "JSEventTargetNode.h" - -namespace WebCore { - -using namespace KJS; - -JSEventTargetNode::JSEventTargetNode(JSObject* prototype, Node* node) - : JSNode(prototype, node) -{ -} - -bool JSEventTargetNode::getOwnPropertySlot(ExecState* exec, const Identifier& propertyName, PropertySlot& slot) -{ - return m_base.getOwnPropertySlot<JSNode>(this, exec, propertyName, slot); -} - -JSValue* JSEventTargetNode::getValueProperty(ExecState* exec, int token) const -{ - return m_base.getValueProperty(this, exec, token); -} - -void JSEventTargetNode::put(ExecState* exec, const Identifier& propertyName, JSValue* value, int attr) -{ - m_base.put<JSNode>(this, exec, propertyName, value, attr); -} - -void JSEventTargetNode::putValueProperty(ExecState* exec, int token, JSValue* value, int attr) -{ - m_base.putValueProperty(this, exec, token, value, attr); -} - -void JSEventTargetNode::setListener(ExecState* exec, const AtomicString& eventType, JSValue* func) const -{ - Frame* frame = impl()->document()->frame(); - if (frame) - EventTargetNodeCast(impl())->setHTMLEventListener(eventType, KJS::Window::retrieveWindow(frame)->findOrCreateJSEventListener(func, true)); -} - -JSValue* JSEventTargetNode::getListener(const AtomicString& eventType) const -{ - EventListener* listener = EventTargetNodeCast(impl())->getHTMLEventListener(eventType); - JSEventListener* jsListener = static_cast<JSEventListener*>(listener); - if (jsListener && jsListener->listenerObj()) - return jsListener->listenerObj(); - - return jsNull(); -} - -void JSEventTargetNode::pushEventHandlerScope(ExecState*, ScopeChain&) const -{ -} - -EventTargetNode* toEventTargetNode(JSValue* val) -{ - if (!val || !val->isObject(&JSEventTargetNode::info)) - return 0; - - return static_cast<EventTargetNode*>(static_cast<JSEventTargetNode*>(val)->impl()); -} - -} // namespace WebCore diff --git a/WebCore/bindings/js/JSEventTargetNode.h b/WebCore/bindings/js/JSEventTargetNode.h deleted file mode 100644 index b73482a..0000000 --- a/WebCore/bindings/js/JSEventTargetNode.h +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright (C) 2007 Apple Inc. All rights reserved. - * (C) 2007 Nikolas Zimmermann <zimmermann@kde.org> - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef JSEventTargetNode_h -#define JSEventTargetNode_h - -#include "JSNode.h" -#include "JSEventTargetBase.h" - -namespace WebCore { - - class EventTargetNode; - class Node; - - class JSEventTargetNode : public JSNode { - public: - JSEventTargetNode(KJS::JSObject* prototype, Node*); - - void setListener(KJS::ExecState*, const AtomicString& eventType, KJS::JSValue* func) const; - KJS::JSValue* getListener(const AtomicString& eventType) const; - virtual void pushEventHandlerScope(KJS::ExecState*, KJS::ScopeChain&) const; - - bool getOwnPropertySlot(KJS::ExecState*, const KJS::Identifier&, KJS::PropertySlot&); - KJS::JSValue* getValueProperty(KJS::ExecState*, int token) const; - virtual void put(KJS::ExecState*, const KJS::Identifier&, KJS::JSValue* value, int attr); - void putValueProperty(KJS::ExecState*, int token, KJS::JSValue* value, int attr); - - private: - JSEventTargetBase<JSEventTargetNode> m_base; - }; - - struct JSEventTargetPrototypeInformation { - static const char* prototypeClassName() - { - return "EventTargetNodePrototype"; - } - - static const char* prototypeIdentifier() - { - return "[[EventTargetNode.prototype]]"; - } - }; - - typedef JSEventTargetPrototype<JSNodePrototype, JSEventTargetPrototypeInformation> JSEventTargetNodePrototype; - EventTargetNode* toEventTargetNode(KJS::JSValue*); - -} // namespace WebCore - -#endif // JSEventTargetNode_h diff --git a/WebCore/bindings/js/JSEventTargetNodeCustom.cpp b/WebCore/bindings/js/JSEventTargetNodeCustom.cpp new file mode 100644 index 0000000..7e80f70 --- /dev/null +++ b/WebCore/bindings/js/JSEventTargetNodeCustom.cpp @@ -0,0 +1,71 @@ +/* + * Copyright (C) 2008 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "JSEventTargetNode.h" + +#include "AtomicString.h" +#include "Document.h" +#include "Event.h" +#include "EventTargetNode.h" +#include "ExceptionCode.h" +#include "Frame.h" +#include "JSDOMWindow.h" +#include "JSEvent.h" +#include "JSEventListener.h" + +using namespace JSC; + +namespace WebCore { + +JSValue* JSEventTargetNode::addEventListener(ExecState* exec, const ArgList& args) +{ + JSDOMGlobalObject* globalObject = toJSDOMGlobalObject(impl()->scriptExecutionContext()); + if (!globalObject) + return jsUndefined(); + + if (RefPtr<JSEventListener> listener = globalObject->findOrCreateJSEventListener(exec, args.at(exec, 1))) + impl()->addEventListener(args.at(exec, 0)->toString(exec), listener.release(), args.at(exec, 2)->toBoolean(exec)); + + return jsUndefined(); +} + +JSValue* JSEventTargetNode::removeEventListener(ExecState* exec, const ArgList& args) +{ + JSDOMGlobalObject* globalObject = toJSDOMGlobalObject(impl()->scriptExecutionContext()); + if (!globalObject) + return jsUndefined(); + + if (JSEventListener* listener = globalObject->findJSEventListener(args.at(exec, 1))) + impl()->removeEventListener(args.at(exec, 0)->toString(exec), listener, args.at(exec, 2)->toBoolean(exec)); + + return jsUndefined(); +} + +void JSEventTargetNode::pushEventHandlerScope(ExecState*, ScopeChain&) const +{ +} + +} // namespace WebCore diff --git a/WebCore/bindings/js/JSGeolocationCustom.cpp b/WebCore/bindings/js/JSGeolocationCustom.cpp new file mode 100644 index 0000000..9c11172 --- /dev/null +++ b/WebCore/bindings/js/JSGeolocationCustom.cpp @@ -0,0 +1,113 @@ +/* + * Copyright (C) 2008 Apple Inc. All Rights Reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "JSGeolocation.h" + +#include "DOMWindow.h" +#include "ExceptionCode.h" +#include "Geolocation.h" +#include "GeolocationService.h" +#include "JSCustomPositionCallback.h" +#include "JSCustomPositionErrorCallback.h" +#include "JSDOMWindow.h" +#include "JSPositionOptions.h" + +using namespace JSC; + +namespace WebCore { + +JSValue* JSGeolocation::getCurrentPosition(ExecState* exec, const ArgList& args) +{ + // Arguments: PositionCallback, (optional)PositionErrorCallback, (optional)PositionOptions + RefPtr<PositionCallback> positionCallback; + JSObject* object = args.at(exec, 0)->getObject(); + if (exec->hadException()) + return jsUndefined(); + if (!object) { + setDOMException(exec, TYPE_MISMATCH_ERR); + return jsUndefined(); + } + + if (Frame* frame = toJSDOMWindow(exec->lexicalGlobalObject())->impl()->frame()) + positionCallback = JSCustomPositionCallback::create(object, frame); + + RefPtr<PositionErrorCallback> positionErrorCallback; + if (!args.at(exec, 1)->isUndefinedOrNull()) { + JSObject* object = args.at(exec, 1)->getObject(); + if (!object) { + setDOMException(exec, TYPE_MISMATCH_ERR); + return jsUndefined(); + } + + if (Frame* frame = toJSDOMWindow(exec->lexicalGlobalObject())->impl()->frame()) + positionErrorCallback = JSCustomPositionErrorCallback::create(object, frame); + } + + RefPtr<PositionOptions> positionOptions; + if (!args.at(exec, 2)->isUndefinedOrNull()) + positionOptions = toPositionOptions(args.at(exec, 2)); + + m_impl->getCurrentPosition(positionCallback.release(), positionErrorCallback.release(), positionOptions.get()); + + return jsUndefined(); +} + +JSValue* JSGeolocation::watchPosition(ExecState* exec, const ArgList& args) +{ + // Arguments: PositionCallback, (optional)PositionErrorCallback, (optional)PositionOptions + RefPtr<PositionCallback> positionCallback; + JSObject* object = args.at(exec, 0)->getObject(); + if (exec->hadException()) + return jsUndefined(); + if (!object) { + setDOMException(exec, TYPE_MISMATCH_ERR); + return jsUndefined(); + } + + if (Frame* frame = toJSDOMWindow(exec->lexicalGlobalObject())->impl()->frame()) + positionCallback = JSCustomPositionCallback::create(object, frame); + + RefPtr<PositionErrorCallback> positionErrorCallback; + if (!args.at(exec, 1)->isUndefinedOrNull()) { + JSObject* object = args.at(exec, 1)->getObject(); + if (!object) { + setDOMException(exec, TYPE_MISMATCH_ERR); + return jsUndefined(); + } + + if (Frame* frame = toJSDOMWindow(exec->lexicalGlobalObject())->impl()->frame()) + positionErrorCallback = JSCustomPositionErrorCallback::create(object, frame); + } + + RefPtr<PositionOptions> positionOptions; + if (!args.at(exec, 2)->isUndefinedOrNull()) + positionOptions = toPositionOptions(args.at(exec, 2)); + + int watchID = m_impl->watchPosition(positionCallback.release(), positionErrorCallback.release(), positionOptions.get()); + return jsNumber(exec, watchID); +} + +} // namespace WebCore diff --git a/WebCore/bindings/js/JSHTMLAllCollection.cpp b/WebCore/bindings/js/JSHTMLAllCollection.cpp new file mode 100644 index 0000000..ce2609c --- /dev/null +++ b/WebCore/bindings/js/JSHTMLAllCollection.cpp @@ -0,0 +1,35 @@ +/* + * Copyright (C) 2008 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "JSHTMLAllCollection.h" + +using namespace JSC; + +namespace WebCore { + +const ClassInfo JSHTMLAllCollection::s_info = { "HTMLAllCollection", 0, 0, 0 }; + +} // namespace WebCore diff --git a/WebCore/bindings/js/JSHTMLAllCollection.h b/WebCore/bindings/js/JSHTMLAllCollection.h index 4661e12..f85c997 100644 --- a/WebCore/bindings/js/JSHTMLAllCollection.h +++ b/WebCore/bindings/js/JSHTMLAllCollection.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2007 Apple Inc. All rights reserved. + * Copyright (C) 2007, 2008 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -26,6 +26,7 @@ #ifndef JSHTMLAllCollection_h #define JSHTMLAllCollection_h +#include "HTMLCollection.h" #include "JSHTMLCollection.h" namespace WebCore { @@ -34,13 +35,20 @@ namespace WebCore { class JSHTMLAllCollection : public JSHTMLCollection { public: - JSHTMLAllCollection(KJS::JSObject* prototype, HTMLCollection* collection) - : JSHTMLCollection(prototype, collection) + JSHTMLAllCollection(PassRefPtr<JSC::StructureID> structure, PassRefPtr<HTMLCollection> collection) + : JSHTMLCollection(structure, collection) { } - virtual bool toBoolean(KJS::ExecState*) const { return false; } - virtual bool masqueradeAsUndefined() const { return true; } + static PassRefPtr<JSC::StructureID> createStructureID(JSC::JSValue* proto) + { + return JSC::StructureID::create(proto, JSC::TypeInfo(JSC::ObjectType, JSC::MasqueradesAsUndefined)); + } + + static const JSC::ClassInfo s_info; + + private: + virtual bool toBoolean(JSC::ExecState*) const { return false; } }; } // namespace WebCore diff --git a/WebCore/bindings/js/JSHTMLAppletElementCustom.cpp b/WebCore/bindings/js/JSHTMLAppletElementCustom.cpp index fc21b80..ca9e08e 100644 --- a/WebCore/bindings/js/JSHTMLAppletElementCustom.cpp +++ b/WebCore/bindings/js/JSHTMLAppletElementCustom.cpp @@ -24,34 +24,28 @@ */ #include "config.h" -#include "JSHTMLAppletElement.h" +#include "JSHTMLAppletElementCustom.h" #include "HTMLAppletElement.h" -#include "kjs_dom.h" -#include "kjs_html.h" +#include "JSPluginElementFunctions.h" namespace WebCore { -using namespace KJS; +using namespace JSC; bool JSHTMLAppletElement::customGetOwnPropertySlot(ExecState* exec, const Identifier& propertyName, PropertySlot& slot) { - return runtimeObjectCustomGetOwnPropertySlot(exec, propertyName, slot, this, static_cast<HTMLElement*>(impl())); + return runtimeObjectCustomGetOwnPropertySlot(exec, propertyName, slot, this); } -bool JSHTMLAppletElement::customPut(ExecState* exec, const Identifier& propertyName, JSValue* value, int attr) +bool JSHTMLAppletElement::customPut(ExecState* exec, const Identifier& propertyName, JSValue* value, PutPropertySlot& slot) { - return runtimeObjectCustomPut(exec, propertyName, value, attr, static_cast<HTMLElement*>(impl())); + return runtimeObjectCustomPut(exec, propertyName, value, impl(), slot); } -bool JSHTMLAppletElement::implementsCall() const +CallType JSHTMLAppletElement::getCallData(CallData& callData) { - return runtimeObjectImplementsCall(static_cast<HTMLElement*>(impl())); -} - -JSValue* JSHTMLAppletElement::callAsFunction(ExecState* exec, JSObject* thisObj, const List& args) -{ - return runtimeObjectCallAsFunction(exec, thisObj, args, static_cast<HTMLElement*>(impl())); + return runtimeObjectGetCallData(impl(), callData); } bool JSHTMLAppletElement::canGetItemsForName(ExecState*, HTMLAppletElement*, const Identifier& propertyName) @@ -59,9 +53,9 @@ bool JSHTMLAppletElement::canGetItemsForName(ExecState*, HTMLAppletElement*, con return propertyName == "__apple_runtime_object"; } -JSValue* JSHTMLAppletElement::nameGetter(ExecState* exec, JSObject* originalObject, const Identifier& propertyName, const PropertySlot& slot) +JSValue* JSHTMLAppletElement::nameGetter(ExecState* exec, const Identifier& propertyName, const PropertySlot& slot) { - return runtimeObjectGetter(exec, originalObject, propertyName, slot); + return runtimeObjectGetter(exec, propertyName, slot); } } // namespace WebCore diff --git a/WebCore/bindings/js/JSHTMLAppletElementCustom.h b/WebCore/bindings/js/JSHTMLAppletElementCustom.h new file mode 100644 index 0000000..5df9a66 --- /dev/null +++ b/WebCore/bindings/js/JSHTMLAppletElementCustom.h @@ -0,0 +1,31 @@ +/* + * Copyright (C) 2008 Apple Inc. All Rights Reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef JSHTMLAppletElementCustom_h +#define JSHTMLAppletElementCustom_h + +#include "JSHTMLAppletElement.h" + +#endif // JSHTMLAppletElementCustom_h diff --git a/WebCore/bindings/js/JSHTMLCollectionCustom.cpp b/WebCore/bindings/js/JSHTMLCollectionCustom.cpp index 2c44ab0..3e98194 100644 --- a/WebCore/bindings/js/JSHTMLCollectionCustom.cpp +++ b/WebCore/bindings/js/JSHTMLCollectionCustom.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2007 Apple Inc. All rights reserved. + * Copyright (C) 2007, 2008 Apple Inc. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public @@ -28,11 +28,10 @@ #include "JSNamedNodesCollection.h" #include "JSNode.h" #include "Node.h" -#include "kjs_binding.h" -#include "kjs_html.h" +#include "JSDOMBinding.h" #include <wtf/Vector.h> -using namespace KJS; +using namespace JSC; namespace WebCore { @@ -47,37 +46,37 @@ static JSValue* getNamedItems(ExecState* exec, HTMLCollection* impl, const Ident if (namedItems.size() == 1) return toJS(exec, namedItems[0].get()); - return new JSNamedNodesCollection(exec->lexicalGlobalObject()->objectPrototype(), namedItems); + return new (exec) JSNamedNodesCollection(exec, namedItems); } // HTMLCollections are strange objects, they support both get and call, // so that document.forms.item(0) and document.forms(0) both work. -JSValue* JSHTMLCollection::callAsFunction(ExecState* exec, JSObject*, const List& args) +static JSValue* callHTMLCollection(ExecState* exec, JSObject* function, JSValue*, const ArgList& args) { if (args.size() < 1) return jsUndefined(); // Do not use thisObj here. It can be the JSHTMLDocument, in the document.forms(i) case. - HTMLCollection* collection = impl(); + HTMLCollection* collection = static_cast<JSHTMLCollection*>(function)->impl(); // Also, do we need the TypeError test here ? if (args.size() == 1) { // Support for document.all(<index>) etc. bool ok; - UString string = args[0]->toString(exec); + UString string = args.at(exec, 0)->toString(exec); unsigned index = string.toUInt32(&ok, false); if (ok) return toJS(exec, collection->item(index)); // Support for document.images('<name>') etc. - return getNamedItems(exec, collection, Identifier(string)); + return getNamedItems(exec, collection, Identifier(exec, string)); } // The second arg, if set, is the index of the item we want bool ok; - UString string = args[0]->toString(exec); - unsigned index = args[1]->toString(exec).toUInt32(&ok, false); + UString string = args.at(exec, 0)->toString(exec); + unsigned index = args.at(exec, 1)->toString(exec).toUInt32(&ok, false); if (ok) { String pstr = string; Node* node = collection->namedItem(pstr); @@ -92,9 +91,10 @@ JSValue* JSHTMLCollection::callAsFunction(ExecState* exec, JSObject*, const List return jsUndefined(); } -bool JSHTMLCollection::implementsCall() const +CallType JSHTMLCollection::getCallData(CallData& callData) { - return true; + callData.native.function = callHTMLCollection; + return CallTypeHost; } bool JSHTMLCollection::canGetItemsForName(ExecState* exec, HTMLCollection* thisObj, const Identifier& propertyName) @@ -102,24 +102,24 @@ bool JSHTMLCollection::canGetItemsForName(ExecState* exec, HTMLCollection* thisO return !getNamedItems(exec, thisObj, propertyName)->isUndefined(); } -JSValue* JSHTMLCollection::nameGetter(ExecState* exec, JSObject* originalObject, const Identifier& propertyName, const PropertySlot& slot) +JSValue* JSHTMLCollection::nameGetter(ExecState* exec, const Identifier& propertyName, const PropertySlot& slot) { - JSHTMLCollection* thisObj = static_cast<JSHTMLCollection*>(slot.slotBase()); + JSHTMLCollection* thisObj = static_cast<JSHTMLCollection*>(asObject(slot.slotBase())); return getNamedItems(exec, thisObj->impl(), propertyName); } -JSValue* JSHTMLCollection::item(ExecState* exec, const List& args) +JSValue* JSHTMLCollection::item(ExecState* exec, const ArgList& args) { bool ok; - uint32_t index = args[0]->toString(exec).toUInt32(&ok, false); + uint32_t index = args.at(exec, 0)->toString(exec).toUInt32(&ok, false); if (ok) return toJS(exec, impl()->item(index)); - return getNamedItems(exec, impl(), Identifier(args[0]->toString(exec))); + return getNamedItems(exec, impl(), Identifier(exec, args.at(exec, 0)->toString(exec))); } -JSValue* JSHTMLCollection::namedItem(ExecState* exec, const List& args) +JSValue* JSHTMLCollection::namedItem(ExecState* exec, const ArgList& args) { - return getNamedItems(exec, impl(), Identifier(args[0]->toString(exec))); + return getNamedItems(exec, impl(), Identifier(exec, args.at(exec, 0)->toString(exec))); } JSValue* toJS(ExecState* exec, HTMLCollection* collection) @@ -127,25 +127,25 @@ JSValue* toJS(ExecState* exec, HTMLCollection* collection) if (!collection) return jsNull(); - DOMObject* ret = ScriptInterpreter::getDOMObject(collection); + DOMObject* wrapper = getCachedDOMObjectWrapper(exec->globalData(), collection); - if (ret) - return ret; + if (wrapper) + return wrapper; switch (collection->type()) { case HTMLCollection::SelectOptions: - ret = new JSHTMLOptionsCollection(JSHTMLOptionsCollectionPrototype::self(exec), static_cast<HTMLOptionsCollection*>(collection)); + wrapper = CREATE_DOM_OBJECT_WRAPPER(exec, HTMLOptionsCollection, collection); break; case HTMLCollection::DocAll: - ret = new JSHTMLAllCollection(JSHTMLCollectionPrototype::self(exec), static_cast<HTMLCollection*>(collection)); + typedef HTMLCollection HTMLAllCollection; + wrapper = CREATE_DOM_OBJECT_WRAPPER(exec, HTMLAllCollection, collection); break; default: - ret = new JSHTMLCollection(JSHTMLCollectionPrototype::self(exec), static_cast<HTMLCollection*>(collection)); + wrapper = CREATE_DOM_OBJECT_WRAPPER(exec, HTMLCollection, collection); break; } - ScriptInterpreter::putDOMObject(collection, ret); - return ret; + return wrapper; } } // namespace WebCore diff --git a/WebCore/bindings/js/JSHTMLDocumentCustom.cpp b/WebCore/bindings/js/JSHTMLDocumentCustom.cpp index 5455617..be57a3d 100644 --- a/WebCore/bindings/js/JSHTMLDocumentCustom.cpp +++ b/WebCore/bindings/js/JSHTMLDocumentCustom.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2007 Apple Inc. All rights reserved. + * Copyright (C) 2007, 2008 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -33,27 +33,31 @@ #include "HTMLElement.h" #include "HTMLIFrameElement.h" #include "HTMLNames.h" +#include "JSDOMWindow.h" +#include "JSDOMWindowCustom.h" +#include "JSDOMWindowShell.h" #include "JSHTMLCollection.h" -#include "kjs_html.h" -#include "kjs_window.h" +#include <runtime/Error.h> + +using namespace JSC; namespace WebCore { -using namespace KJS; using namespace HTMLNames; -bool JSHTMLDocument::canGetItemsForName(ExecState*, HTMLDocument* doc, const Identifier& propertyName) +bool JSHTMLDocument::canGetItemsForName(ExecState*, HTMLDocument* document, const Identifier& propertyName) { - return doc->hasNamedItem(propertyName) || doc->hasDocExtraNamedItem(propertyName); + AtomicStringImpl* atomicPropertyName = AtomicString::find(propertyName); + return atomicPropertyName && (document->hasNamedItem(atomicPropertyName) || document->hasExtraNamedItem(atomicPropertyName)); } -JSValue* JSHTMLDocument::nameGetter(ExecState* exec, JSObject* originalObject, const Identifier& propertyName, const PropertySlot& slot) +JSValue* JSHTMLDocument::nameGetter(ExecState* exec, const Identifier& propertyName, const PropertySlot& slot) { - JSHTMLDocument* thisObj = static_cast<JSHTMLDocument*>(slot.slotBase()); - HTMLDocument* doc = static_cast<HTMLDocument*>(thisObj->impl()); + JSHTMLDocument* thisObj = static_cast<JSHTMLDocument*>(asObject(slot.slotBase())); + HTMLDocument* document = static_cast<HTMLDocument*>(thisObj->impl()); String name = propertyName; - RefPtr<HTMLCollection> collection = doc->documentNamedItems(name); + RefPtr<HTMLCollection> collection = document->documentNamedItems(name); unsigned length = collection->length(); if (!length) @@ -64,7 +68,7 @@ JSValue* JSHTMLDocument::nameGetter(ExecState* exec, JSObject* originalObject, c Frame* frame; if (node->hasTagName(iframeTag) && (frame = static_cast<HTMLIFrameElement*>(node)->contentFrame())) - return KJS::Window::retrieve(frame); + return toJS(exec, frame); return toJS(exec, node); } @@ -77,68 +81,74 @@ JSValue* JSHTMLDocument::nameGetter(ExecState* exec, JSObject* originalObject, c JSValue* JSHTMLDocument::all(ExecState* exec) const { // If "all" has been overwritten, return the overwritten value - if (JSValue* v = getDirect("all")) + if (JSValue* v = getDirect(Identifier(exec, "all"))) return v; return toJS(exec, static_cast<HTMLDocument*>(impl())->all().get()); } -void JSHTMLDocument::setAll(ExecState*, JSValue* value) +void JSHTMLDocument::setAll(ExecState* exec, JSValue* value) { // Add "all" to the property map. - putDirect("all", value); + putDirect(Identifier(exec, "all"), value); } // Custom functions -JSValue* JSHTMLDocument::open(ExecState* exec, const List& args) +JSValue* JSHTMLDocument::open(ExecState* exec, const ArgList& args) { // For compatibility with other browsers, pass open calls with more than 2 parameters to the window. if (args.size() > 2) { Frame* frame = static_cast<HTMLDocument*>(impl())->frame(); if (frame) { - KJS::Window* window = KJS::Window::retrieveWindow(frame); - if (window) { - JSObject* functionObject = window->get(exec, "open")->getObject(); - if (!functionObject || !functionObject->implementsCall()) + JSDOMWindowShell* wrapper = toJSDOMWindowShell(frame); + if (wrapper) { + JSValue* function = wrapper->get(exec, Identifier(exec, "open")); + CallData callData; + CallType callType = function->getCallData(callData); + if (callType == CallTypeNone) return throwError(exec, TypeError); - return functionObject->call(exec, window, args); + return call(exec, function, callType, callData, wrapper, args); } } return jsUndefined(); } + // document.open clobbers the security context of the document and + // aliases it with the active security context. + Document* activeDocument = asJSDOMWindow(exec->lexicalGlobalObject())->impl()->document(); + // In the case of two parameters or fewer, do a normal document open. - static_cast<HTMLDocument*>(impl())->open(); + static_cast<HTMLDocument*>(impl())->open(activeDocument); return jsUndefined(); } -static String writeHelper(ExecState* exec, const List& args) +static String writeHelper(ExecState* exec, const ArgList& args) { // DOM only specifies single string argument, but NS & IE allow multiple // or no arguments. - String str = ""; - for (unsigned int i = 0; i < args.size(); ++i) - str += args[i]->toString(exec); - return str; -} -JSValue* JSHTMLDocument::write(ExecState* exec, const List& args) -{ - static_cast<HTMLDocument*>(impl())->write(writeHelper(exec, args)); - return jsUndefined(); + unsigned size = args.size(); + if (size == 1) + return args.at(exec, 0)->toString(exec); + + Vector<UChar> result; + for (unsigned i = 0; i < size; ++i) + append(result, args.at(exec, i)->toString(exec)); + return String::adopt(result); } -JSValue* JSHTMLDocument::writeln(ExecState* exec, const List& args) +JSValue* JSHTMLDocument::write(ExecState* exec, const ArgList& args) { - static_cast<HTMLDocument*>(impl())->write(writeHelper(exec, args) + "\n"); + Document* activeDocument = asJSDOMWindow(exec->lexicalGlobalObject())->impl()->document(); + static_cast<HTMLDocument*>(impl())->write(writeHelper(exec, args), activeDocument); return jsUndefined(); } -JSValue* JSHTMLDocument::clear(ExecState*, const List&) +JSValue* JSHTMLDocument::writeln(ExecState* exec, const ArgList& args) { - // even IE doesn't support this one... - // static_cast<HTMLDocument*>(impl())->clear(); + Document* activeDocument = asJSDOMWindow(exec->lexicalGlobalObject())->impl()->document(); + static_cast<HTMLDocument*>(impl())->write(writeHelper(exec, args) + "\n", activeDocument); return jsUndefined(); } diff --git a/WebCore/bindings/js/JSHTMLElementCustom.cpp b/WebCore/bindings/js/JSHTMLElementCustom.cpp index 755277a..3345764 100644 --- a/WebCore/bindings/js/JSHTMLElementCustom.cpp +++ b/WebCore/bindings/js/JSHTMLElementCustom.cpp @@ -28,25 +28,24 @@ #include "Document.h" #include "HTMLFormElement.h" -#include "kjs_dom.h" namespace WebCore { -using namespace KJS; +using namespace JSC; void JSHTMLElement::pushEventHandlerScope(ExecState* exec, ScopeChain& scope) const { HTMLElement* element = impl(); // The document is put on first, fall back to searching it only after the element and form. - scope.push(static_cast<JSObject*>(toJS(exec, element->ownerDocument()))); + scope.push(asObject(toJS(exec, element->ownerDocument()))); // The form is next, searched before the document, but after the element itself. if (HTMLFormElement* form = element->form()) - scope.push(static_cast<JSObject*>(toJS(exec, form))); + scope.push(asObject(toJS(exec, form))); // The element is on top, searched first. - scope.push(static_cast<JSObject*>(toJS(exec, element))); + scope.push(asObject(toJS(exec, element))); } } // namespace WebCore diff --git a/WebCore/bindings/js/JSHTMLElementWrapperFactory.cpp b/WebCore/bindings/js/JSHTMLElementWrapperFactory.cpp deleted file mode 100644 index 1202e6c..0000000 --- a/WebCore/bindings/js/JSHTMLElementWrapperFactory.cpp +++ /dev/null @@ -1,273 +0,0 @@ -/* - * Copyright (C) 2006, 2007 Apple Inc. All rights reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#include "config.h" -#include "JSHTMLElementWrapperFactory.h" - -#include "HTMLAnchorElement.h" -#include "HTMLAppletElement.h" -#include "HTMLAreaElement.h" -#include "HTMLAudioElement.h" -#include "HTMLBRElement.h" -#include "HTMLBaseElement.h" -#include "HTMLBaseFontElement.h" -#include "HTMLBlockquoteElement.h" -#include "HTMLBodyElement.h" -#include "HTMLButtonElement.h" -#include "HTMLCanvasElement.h" -#include "HTMLDListElement.h" -#include "HTMLDirectoryElement.h" -#include "HTMLDivElement.h" -#include "HTMLEmbedElement.h" -#include "HTMLFieldSetElement.h" -#include "HTMLFontElement.h" -#include "HTMLFormElement.h" -#include "HTMLFrameElement.h" -#include "HTMLFrameSetElement.h" -#include "HTMLHRElement.h" -#include "HTMLHeadElement.h" -#include "HTMLHeadingElement.h" -#include "HTMLHtmlElement.h" -#include "HTMLIFrameElement.h" -#include "HTMLImageElement.h" -#include "HTMLInputElement.h" -#include "HTMLIsIndexElement.h" -#include "HTMLLIElement.h" -#include "HTMLLabelElement.h" -#include "HTMLLegendElement.h" -#include "HTMLLinkElement.h" -#include "HTMLMapElement.h" -#include "HTMLMarqueeElement.h" -#include "HTMLMenuElement.h" -#include "HTMLMetaElement.h" -#include "HTMLModElement.h" -#include "HTMLOListElement.h" -#include "HTMLObjectElement.h" -#include "HTMLOptGroupElement.h" -#include "HTMLOptionElement.h" -#include "HTMLParagraphElement.h" -#include "HTMLParamElement.h" -#include "HTMLPreElement.h" -#include "HTMLQuoteElement.h" -#include "HTMLScriptElement.h" -#include "HTMLSelectElement.h" -#include "HTMLSourceElement.h" -#include "HTMLStyleElement.h" -#include "HTMLTableCaptionElement.h" -#include "HTMLTableCellElement.h" -#include "HTMLTableColElement.h" -#include "HTMLTableElement.h" -#include "HTMLTableRowElement.h" -#include "HTMLTableSectionElement.h" -#include "HTMLTextAreaElement.h" -#include "HTMLTitleElement.h" -#include "HTMLUListElement.h" -#include "HTMLVideoElement.h" - -#include "HTMLNames.h" - -#include "JSHTMLAnchorElement.h" -#include "JSHTMLAppletElement.h" -#include "JSHTMLAreaElement.h" -#include "JSHTMLBRElement.h" -#include "JSHTMLBaseElement.h" -#include "JSHTMLBaseFontElement.h" -#include "JSHTMLBlockquoteElement.h" -#include "JSHTMLBodyElement.h" -#include "JSHTMLButtonElement.h" -#include "JSHTMLCanvasElement.h" -#include "JSHTMLDListElement.h" -#include "JSHTMLDirectoryElement.h" -#include "JSHTMLDivElement.h" -#include "JSHTMLEmbedElement.h" -#include "JSHTMLFieldSetElement.h" -#include "JSHTMLFontElement.h" -#include "JSHTMLFormElement.h" -#include "JSHTMLFrameElement.h" -#include "JSHTMLFrameSetElement.h" -#include "JSHTMLHRElement.h" -#include "JSHTMLHeadElement.h" -#include "JSHTMLHeadingElement.h" -#include "JSHTMLHtmlElement.h" -#include "JSHTMLIFrameElement.h" -#include "JSHTMLImageElement.h" -#include "JSHTMLInputElement.h" -#include "JSHTMLIsIndexElement.h" -#include "JSHTMLLIElement.h" -#include "JSHTMLLabelElement.h" -#include "JSHTMLLegendElement.h" -#include "JSHTMLLinkElement.h" -#include "JSHTMLMapElement.h" -#include "JSHTMLMarqueeElement.h" -#include "JSHTMLMenuElement.h" -#include "JSHTMLMetaElement.h" -#include "JSHTMLModElement.h" -#include "JSHTMLOListElement.h" -#include "JSHTMLObjectElement.h" -#include "JSHTMLOptGroupElement.h" -#include "JSHTMLOptionElement.h" -#include "JSHTMLParagraphElement.h" -#include "JSHTMLParamElement.h" -#include "JSHTMLPreElement.h" -#include "JSHTMLQuoteElement.h" -#include "JSHTMLScriptElement.h" -#include "JSHTMLSelectElement.h" -#include "JSHTMLStyleElement.h" -#include "JSHTMLTableCaptionElement.h" -#include "JSHTMLTableCellElement.h" -#include "JSHTMLTableColElement.h" -#include "JSHTMLTableElement.h" -#include "JSHTMLTableRowElement.h" -#include "JSHTMLTableSectionElement.h" -#include "JSHTMLTextAreaElement.h" -#include "JSHTMLTitleElement.h" -#include "JSHTMLUListElement.h" - -#if ENABLE(VIDEO) -#include "JSHTMLAudioElement.h" -#include "JSHTMLSourceElement.h" -#include "JSHTMLVideoElement.h" -#endif - -#include "kjs_html.h" - -using namespace KJS; - -// FIXME: Eventually this file should be autogenerated, just like HTMLNames, HTMLElementFactory, etc. - -namespace WebCore { - -using namespace HTMLNames; - -typedef JSNode* (*CreateHTMLElementWrapperFunction)(ExecState*, PassRefPtr<HTMLElement>); - -#define FOR_EACH_TAG(macro) \ - macro(a, Anchor) \ - macro(applet, Applet) \ - macro(area, Area) \ - macro(base, Base) \ - macro(basefont, BaseFont) \ - macro(blockquote, Blockquote) \ - macro(body, Body) \ - macro(br, BR) \ - macro(button, Button) \ - macro(canvas, Canvas) \ - macro(caption, TableCaption) \ - macro(col, TableCol) \ - macro(del, Mod) \ - macro(dir, Directory) \ - macro(div, Div) \ - macro(dl, DList) \ - macro(embed, Embed) \ - macro(fieldset, FieldSet) \ - macro(font, Font) \ - macro(form, Form) \ - macro(frame, Frame) \ - macro(frameset, FrameSet) \ - macro(h1, Heading) \ - macro(head, Head) \ - macro(hr, HR) \ - macro(html, Html) \ - macro(iframe, IFrame) \ - macro(img, Image) \ - macro(input, Input) \ - macro(isindex, IsIndex) \ - macro(label, Label) \ - macro(legend, Legend) \ - macro(li, LI) \ - macro(link, Link) \ - macro(map, Map) \ - macro(marquee, Marquee) \ - macro(menu, Menu) \ - macro(meta, Meta) \ - macro(object, Object) \ - macro(ol, OList) \ - macro(optgroup, OptGroup) \ - macro(option, Option) \ - macro(p, Paragraph) \ - macro(param, Param) \ - macro(pre, Pre) \ - macro(q, Quote) \ - macro(script, Script) \ - macro(select, Select) \ - macro(style, Style) \ - macro(table, Table) \ - macro(tbody, TableSection) \ - macro(td, TableCell) \ - macro(textarea, TextArea) \ - macro(tr, TableRow) \ - macro(title, Title) \ - macro(ul, UList) \ - // end of macro - -#define FOR_EACH_MEDIA_TAG(macro) \ - macro(audio, Audio) \ - macro(source, Source) \ - macro(video, Video) \ - // end of macro - -#define CREATE_WRAPPER_FUNCTION(tag, name) \ -static JSNode* create##name##Wrapper(ExecState* exec, PassRefPtr<HTMLElement> element) \ -{ \ - return new JSHTML##name##Element(JSHTML##name##ElementPrototype::self(exec), static_cast<HTML##name##Element*>(element.get())); \ -} -#define CREATE_MEDIA_WRAPPER_FUNCTION(tag, name) \ -static JSNode* create##name##Wrapper(ExecState* exec, PassRefPtr<HTMLElement> element) \ -{ \ - if (!MediaPlayer::isAvailable()) \ - return new JSHTMLElement(JSHTMLElementPrototype::self(exec), element.get()); \ - return new JSHTML##name##Element(JSHTML##name##ElementPrototype::self(exec), static_cast<HTML##name##Element*>(element.get())); \ -} -FOR_EACH_TAG(CREATE_WRAPPER_FUNCTION) -#if ENABLE(VIDEO) - FOR_EACH_MEDIA_TAG(CREATE_MEDIA_WRAPPER_FUNCTION) -#endif -#undef CREATE_WRAPPER_FUNCTION - -JSNode* createJSHTMLWrapper(ExecState* exec, PassRefPtr<HTMLElement> element) -{ - static HashMap<AtomicStringImpl*, CreateHTMLElementWrapperFunction> map; - if (map.isEmpty()) { -#define ADD_TO_HASH_MAP(tag, name) map.set(tag##Tag.localName().impl(), create##name##Wrapper); -FOR_EACH_TAG(ADD_TO_HASH_MAP) -#if ENABLE(VIDEO) -FOR_EACH_MEDIA_TAG(ADD_TO_HASH_MAP) -#endif -#undef ADD_TO_HASH_MAP - map.set(colgroupTag.localName().impl(), createTableColWrapper); - map.set(h2Tag.localName().impl(), createHeadingWrapper); - map.set(h3Tag.localName().impl(), createHeadingWrapper); - map.set(h4Tag.localName().impl(), createHeadingWrapper); - map.set(h5Tag.localName().impl(), createHeadingWrapper); - map.set(h6Tag.localName().impl(), createHeadingWrapper); - map.set(imageTag.localName().impl(), createImageWrapper); - map.set(insTag.localName().impl(), createModWrapper); - map.set(keygenTag.localName().impl(), createSelectWrapper); - map.set(listingTag.localName().impl(), createPreWrapper); - map.set(tfootTag.localName().impl(), createTableSectionWrapper); - map.set(thTag.localName().impl(), createTableCellWrapper); - map.set(theadTag.localName().impl(), createTableSectionWrapper); - map.set(xmpTag.localName().impl(), createPreWrapper); - } - CreateHTMLElementWrapperFunction createWrapperFunction = map.get(element->localName().impl()); - if (createWrapperFunction) - return createWrapperFunction(exec, element); - return new JSHTMLElement(JSHTMLElementPrototype::self(exec), element.get()); -} - -} // namespace WebCore diff --git a/WebCore/bindings/js/JSHTMLEmbedElementCustom.cpp b/WebCore/bindings/js/JSHTMLEmbedElementCustom.cpp index 2652a82..ae9ebf6 100644 --- a/WebCore/bindings/js/JSHTMLEmbedElementCustom.cpp +++ b/WebCore/bindings/js/JSHTMLEmbedElementCustom.cpp @@ -24,34 +24,28 @@ */ #include "config.h" -#include "JSHTMLEmbedElement.h" +#include "JSHTMLEmbedElementCustom.h" #include "HTMLEmbedElement.h" -#include "kjs_dom.h" -#include "kjs_html.h" +#include "JSPluginElementFunctions.h" namespace WebCore { -using namespace KJS; +using namespace JSC; bool JSHTMLEmbedElement::customGetOwnPropertySlot(ExecState* exec, const Identifier& propertyName, PropertySlot& slot) { - return runtimeObjectCustomGetOwnPropertySlot(exec, propertyName, slot, this, static_cast<HTMLElement*>(impl())); + return runtimeObjectCustomGetOwnPropertySlot(exec, propertyName, slot, this); } -bool JSHTMLEmbedElement::customPut(ExecState* exec, const Identifier& propertyName, JSValue* value, int attr) +bool JSHTMLEmbedElement::customPut(ExecState* exec, const Identifier& propertyName, JSValue* value, PutPropertySlot& slot) { - return runtimeObjectCustomPut(exec, propertyName, value, attr, static_cast<HTMLElement*>(impl())); + return runtimeObjectCustomPut(exec, propertyName, value, impl(), slot); } -bool JSHTMLEmbedElement::implementsCall() const +CallType JSHTMLEmbedElement::getCallData(CallData& callData) { - return runtimeObjectImplementsCall(static_cast<HTMLElement*>(impl())); -} - -JSValue* JSHTMLEmbedElement::callAsFunction(ExecState* exec, JSObject* thisObj, const List& args) -{ - return runtimeObjectCallAsFunction(exec, thisObj, args, static_cast<HTMLElement*>(impl())); + return runtimeObjectGetCallData(impl(), callData); } bool JSHTMLEmbedElement::canGetItemsForName(ExecState*, HTMLEmbedElement*, const Identifier& propertyName) @@ -59,9 +53,9 @@ bool JSHTMLEmbedElement::canGetItemsForName(ExecState*, HTMLEmbedElement*, const return propertyName == "__apple_runtime_object"; } -JSValue* JSHTMLEmbedElement::nameGetter(ExecState* exec, JSObject* originalObject, const Identifier& propertyName, const PropertySlot& slot) +JSValue* JSHTMLEmbedElement::nameGetter(ExecState* exec, const Identifier& propertyName, const PropertySlot& slot) { - return runtimeObjectGetter(exec, originalObject, propertyName, slot); + return runtimeObjectGetter(exec, propertyName, slot); } } // namespace WebCore diff --git a/WebCore/bindings/js/JSHTMLEmbedElementCustom.h b/WebCore/bindings/js/JSHTMLEmbedElementCustom.h new file mode 100644 index 0000000..58833ae --- /dev/null +++ b/WebCore/bindings/js/JSHTMLEmbedElementCustom.h @@ -0,0 +1,31 @@ +/* + * Copyright (C) 2008 Apple Inc. All Rights Reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef JSHTMLEmbedElementCustom_h +#define JSHTMLEmbedElementCustom_h + +#include "JSHTMLEmbedElement.h" + +#endif // JSHTMLEmbedElementCustom_h diff --git a/WebCore/bindings/js/JSHTMLFormElementCustom.cpp b/WebCore/bindings/js/JSHTMLFormElementCustom.cpp index 8e24618..196cb6d 100644 --- a/WebCore/bindings/js/JSHTMLFormElementCustom.cpp +++ b/WebCore/bindings/js/JSHTMLFormElementCustom.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2006, 2007 Apple Inc. All rights reserved. + * Copyright (C) 2006, 2007, 2008 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -29,9 +29,8 @@ #include "HTMLCollection.h" #include "HTMLFormElement.h" #include "JSNamedNodesCollection.h" -#include "kjs_dom.h" -using namespace KJS; +using namespace JSC; namespace WebCore { @@ -42,9 +41,9 @@ bool JSHTMLFormElement::canGetItemsForName(ExecState* exec, HTMLFormElement* for return namedItems.size(); } -JSValue* JSHTMLFormElement::nameGetter(ExecState* exec, JSObject*, const Identifier& propertyName, const PropertySlot& slot) +JSValue* JSHTMLFormElement::nameGetter(ExecState* exec, const Identifier& propertyName, const PropertySlot& slot) { - HTMLFormElement* form = static_cast<HTMLFormElement*>(static_cast<JSHTMLElement*>(slot.slotBase())->impl()); + HTMLFormElement* form = static_cast<HTMLFormElement*>(static_cast<JSHTMLElement*>(asObject(slot.slotBase()))->impl()); Vector<RefPtr<Node> > namedItems; form->getNamedElements(propertyName, namedItems); @@ -52,7 +51,7 @@ JSValue* JSHTMLFormElement::nameGetter(ExecState* exec, JSObject*, const Identif if (namedItems.size() == 1) return toJS(exec, namedItems[0].get()); if (namedItems.size() > 1) - return new JSNamedNodesCollection(exec->lexicalGlobalObject()->objectPrototype(), namedItems); + return new (exec) JSNamedNodesCollection(exec, namedItems); return jsUndefined(); } diff --git a/WebCore/bindings/js/JSHTMLFrameElementCustom.cpp b/WebCore/bindings/js/JSHTMLFrameElementCustom.cpp index 9f729b4..594349a 100644 --- a/WebCore/bindings/js/JSHTMLFrameElementCustom.cpp +++ b/WebCore/bindings/js/JSHTMLFrameElementCustom.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2007 Apple Inc. All rights reserved. + * Copyright (C) 2007, 2008 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -29,35 +29,28 @@ #include "config.h" #include "JSHTMLFrameElement.h" -#include "Document.h" #include "CSSHelper.h" +#include "Document.h" #include "HTMLFrameElement.h" -#include "PlatformString.h" -#include "kjs_binding.h" -#include "kjs_dom.h" -#ifdef ANDROID_JAVASCRIPT_SECURITY -#include "KURL.h" -#endif +#include "JSDOMBinding.h" + +using namespace JSC; namespace WebCore { -static inline bool allowSettingJavascriptURL(KJS::ExecState* exec, HTMLFrameElement* imp, String value) +static inline bool allowSettingJavascriptURL(ExecState* exec, HTMLFrameElement* imp, const String& value) { -#ifdef ANDROID_JAVASCRIPT_SECURITY if (protocolIs(parseURL(value), "javascript")) { -#else - if (parseURL(value).startsWith("javascript:", false)) { -#endif if (!checkNodeSecurity(exec, imp->contentDocument())) return false; } return true; } -void JSHTMLFrameElement::setSrc(KJS::ExecState* exec, KJS::JSValue* value) +void JSHTMLFrameElement::setSrc(ExecState* exec, JSValue* value) { HTMLFrameElement* imp = static_cast<HTMLFrameElement*>(impl()); - String srcValue = KJS::valueToStringWithNullCheck(exec, value); + String srcValue = valueToStringWithNullCheck(exec, value); if (!allowSettingJavascriptURL(exec, imp, srcValue)) return; @@ -66,10 +59,10 @@ void JSHTMLFrameElement::setSrc(KJS::ExecState* exec, KJS::JSValue* value) return; } -void JSHTMLFrameElement::setLocation(KJS::ExecState* exec, KJS::JSValue* value) +void JSHTMLFrameElement::setLocation(ExecState* exec, JSValue* value) { HTMLFrameElement* imp = static_cast<HTMLFrameElement*>(impl()); - String locationValue = KJS::valueToStringWithNullCheck(exec, value); + String locationValue = valueToStringWithNullCheck(exec, value); if (!allowSettingJavascriptURL(exec, imp, locationValue)) return; diff --git a/WebCore/bindings/js/JSHTMLFrameSetElementCustom.cpp b/WebCore/bindings/js/JSHTMLFrameSetElementCustom.cpp index 1e10dc2..126ad8b 100644 --- a/WebCore/bindings/js/JSHTMLFrameSetElementCustom.cpp +++ b/WebCore/bindings/js/JSHTMLFrameSetElementCustom.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2007 Apple Inc. All rights reserved. + * Copyright (C) 2007, 2008 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -30,12 +30,14 @@ #include "HTMLFrameElement.h" #include "HTMLFrameSetElement.h" #include "HTMLNames.h" -#include "kjs_binding.h" -#include "kjs_window.h" +#include "JSDOMWindow.h" +#include "JSDOMWindowShell.h" +#include "JSDOMBinding.h" + +using namespace JSC; namespace WebCore { -using namespace KJS; using namespace HTMLNames; bool JSHTMLFrameSetElement::canGetItemsForName(ExecState*, HTMLFrameSetElement* frameSet, const Identifier& propertyName) @@ -44,14 +46,14 @@ bool JSHTMLFrameSetElement::canGetItemsForName(ExecState*, HTMLFrameSetElement* return frame && frame->hasTagName(frameTag); } -JSValue* JSHTMLFrameSetElement::nameGetter(ExecState* exec, JSObject* originalObject, const Identifier& propertyName, const PropertySlot& slot) +JSValue* JSHTMLFrameSetElement::nameGetter(ExecState* exec, const Identifier& propertyName, const PropertySlot& slot) { - JSHTMLElement* thisObj = static_cast<JSHTMLElement*>(slot.slotBase()); + JSHTMLElement* thisObj = static_cast<JSHTMLElement*>(asObject(slot.slotBase())); HTMLElement* element = static_cast<HTMLElement*>(thisObj->impl()); Node* frame = element->children()->namedItem(propertyName); if (Document* doc = static_cast<HTMLFrameElement*>(frame)->contentDocument()) { - if (KJS::Window* window = KJS::Window::retrieveWindow(doc->frame())) + if (JSDOMWindowShell* window = toJSDOMWindowShell(doc->frame())) return window; } diff --git a/WebCore/bindings/js/JSHTMLIFrameElementCustom.cpp b/WebCore/bindings/js/JSHTMLIFrameElementCustom.cpp index 0f9f5a5..3f27462 100644 --- a/WebCore/bindings/js/JSHTMLIFrameElementCustom.cpp +++ b/WebCore/bindings/js/JSHTMLIFrameElementCustom.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2007 Apple Inc. All rights reserved. + * Copyright (C) 2007, 2008 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -29,35 +29,27 @@ #include "config.h" #include "JSHTMLIFrameElement.h" -#include "Document.h" #include "CSSHelper.h" +#include "Document.h" #include "HTMLIFrameElement.h" -#include "PlatformString.h" -#include "kjs_binding.h" -#include "kjs_dom.h" -#ifdef ANDROID_JAVASCRIPT_SECURITY -#include "KURL.h" -#endif +#include "JSDOMBinding.h" + +using namespace JSC; namespace WebCore { -void JSHTMLIFrameElement::setSrc(KJS::ExecState* exec, KJS::JSValue* value) +void JSHTMLIFrameElement::setSrc(ExecState* exec, JSValue* value) { HTMLIFrameElement* imp = static_cast<HTMLIFrameElement*>(impl()); String srcValue = valueToStringWithNullCheck(exec, value); -#ifdef ANDROID_JAVASCRIPT_SECURITY if (protocolIs(parseURL(srcValue), "javascript")) { -#else - if (parseURL(srcValue).startsWith("javascript:", false)) { -#endif if (!checkNodeSecurity(exec, imp->contentDocument())) return; } imp->setSrc(srcValue); - return; } } // namespace WebCore diff --git a/WebCore/bindings/js/JSHTMLInputElementBase.cpp b/WebCore/bindings/js/JSHTMLInputElementBase.cpp deleted file mode 100644 index e0417bc..0000000 --- a/WebCore/bindings/js/JSHTMLInputElementBase.cpp +++ /dev/null @@ -1,113 +0,0 @@ -/* - * Copyright (C) 2006 Apple Computer, Inc. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#include "config.h" -#include "JSHTMLInputElementBase.h" - -#include "HTMLInputElement.h" - -#include "JSHTMLInputElementBaseTable.cpp" - -using namespace KJS; - -namespace WebCore { - -/* -@begin JSHTMLInputElementBaseTable 3 - selectionStart WebCore::JSHTMLInputElementBase::SelectionStart DontDelete - selectionEnd WebCore::JSHTMLInputElementBase::SelectionEnd DontDelete -@end -@begin JSHTMLInputElementBasePrototypeTable 0 -@end -@begin JSHTMLInputElementBaseFunctionTable 1 - setSelectionRange WebCore::jsHTMLInputElementBaseFunctionSetSelectionRange DontDelete|Function 2 -@end -*/ - -KJS_IMPLEMENT_PROTOTYPE("JSHTMLInputElementBase", JSHTMLInputElementBasePrototype) - -JSValue* jsHTMLInputElementBaseFunctionSetSelectionRange(ExecState* exec, JSObject* thisObj, const List& args) -{ - HTMLInputElement& input = *static_cast<HTMLInputElement*>(static_cast<JSHTMLInputElementBase*>(thisObj)->impl()); - input.setSelectionRange(args[0]->toInt32(exec), args[1]->toInt32(exec)); - return jsUndefined(); -} - -const ClassInfo JSHTMLInputElementBase::info = { "JSHTMLInputElementBase", &JSHTMLElement::info, &JSHTMLInputElementBaseTable }; - -JSHTMLInputElementBase::JSHTMLInputElementBase(KJS::JSObject* prototype, PassRefPtr<HTMLInputElement> e) - : JSHTMLElement(prototype, e.get()) -{ -} - -bool JSHTMLInputElementBase::getOwnPropertySlot(ExecState* exec, const Identifier& propertyName, PropertySlot& slot) -{ - HTMLInputElement& input = *static_cast<HTMLInputElement*>(impl()); - - // if this element doesn't support selection, we have nothing to do, try our parent - if (!input.canHaveSelection()) - return JSHTMLElement::getOwnPropertySlot(exec, propertyName, slot); - - // otherwise, do our own function lookup on our function table - const HashEntry* entry = Lookup::findEntry(&JSHTMLInputElementBaseFunctionTable, propertyName); - if (entry && (entry->attr & KJS::Function) && entry->value.functionValue == jsHTMLInputElementBaseFunctionSetSelectionRange) { - slot.setStaticEntry(this, entry, staticFunctionGetter); - return true; - } - ASSERT(!entry); - - // finally try value lookup or walk the parent chain - return getStaticValueSlot<JSHTMLInputElementBase, JSHTMLElement>(exec, &JSHTMLInputElementBaseTable, this, propertyName, slot); -} - -JSValue* JSHTMLInputElementBase::getValueProperty(ExecState* exec, int token) const -{ - HTMLInputElement& input = *static_cast<HTMLInputElement*>(impl()); - ASSERT(input.canHaveSelection()); - switch (token) { - case SelectionStart: - return jsNumber(input.selectionStart()); - case SelectionEnd: - return jsNumber(input.selectionEnd()); - } - ASSERT_NOT_REACHED(); - return jsUndefined(); -} - -void JSHTMLInputElementBase::put(ExecState* exec, const Identifier& propertyName, JSValue* value, int attr) -{ - lookupPut<JSHTMLInputElementBase, JSHTMLElement>(exec, propertyName, value, attr, &JSHTMLInputElementBaseTable, this); -} - -void JSHTMLInputElementBase::putValueProperty(ExecState* exec, int token, JSValue* value, int /*attr*/) -{ - HTMLInputElement& input = *static_cast<HTMLInputElement*>(impl()); - ASSERT(input.canHaveSelection()); - switch (token) { - case SelectionStart: - input.setSelectionStart(value->toInt32(exec)); - return; - case SelectionEnd: - input.setSelectionEnd(value->toInt32(exec)); - return; - } - ASSERT_NOT_REACHED(); -} - -} // namespace WebCore diff --git a/WebCore/bindings/js/JSHTMLInputElementBase.h b/WebCore/bindings/js/JSHTMLInputElementBase.h deleted file mode 100644 index 32bca58..0000000 --- a/WebCore/bindings/js/JSHTMLInputElementBase.h +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright (C) 2006 Apple Computer, Inc. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#ifndef JSHTMLInputElementBase_h -#define JSHTMLInputElementBase_h - -#include "JSHTMLElement.h" -#include "kjs_binding.h" -#include "kjs_html.h" - -namespace WebCore { - - class HTMLInputElement; - - KJS_DEFINE_PROTOTYPE_WITH_PROTOTYPE(JSHTMLInputElementBasePrototype, JSHTMLElementPrototype) - - class JSHTMLInputElementBase : public JSHTMLElement { - public: - JSHTMLInputElementBase(KJS::JSObject* prototype, PassRefPtr<HTMLInputElement>); - - virtual bool getOwnPropertySlot(KJS::ExecState*, const KJS::Identifier&, KJS::PropertySlot&); - KJS::JSValue* getValueProperty(KJS::ExecState*, int token) const; - virtual void put(KJS::ExecState*, const KJS::Identifier& propertyName, JSValue*, int attr); - void putValueProperty(KJS::ExecState*, int token, KJS::JSValue*, int attr); - virtual const KJS::ClassInfo* classInfo() const { return &info; } - static const KJS::ClassInfo info; - enum { SelectionStart, SelectionEnd }; - }; - - // SetSelectionRange is implemented on the class instead of on the prototype - // to make it easier to enable/disable lookup of the function based on input type. - KJS::JSValue* jsHTMLInputElementBaseFunctionSetSelectionRange(KJS::ExecState*, KJS::JSObject*, const KJS::List&); - -} // namespace WebCore - -#endif // JSHTMLInputElementBase_h diff --git a/WebCore/bindings/js/JSHTMLInputElementCustom.cpp b/WebCore/bindings/js/JSHTMLInputElementCustom.cpp new file mode 100644 index 0000000..f097e1e --- /dev/null +++ b/WebCore/bindings/js/JSHTMLInputElementCustom.cpp @@ -0,0 +1,72 @@ +/* + * Copyright (C) 2008 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "JSHTMLInputElement.h" + +#include "HTMLInputElement.h" + +using namespace JSC; + +namespace WebCore { + +bool JSHTMLInputElement::customGetOwnPropertySlot(ExecState* exec, const Identifier& propertyName, PropertySlot& slot) +{ + HTMLInputElement* input = static_cast<HTMLInputElement*>(impl()); + if (input->canHaveSelection()) + return false; + + const HashEntry* entry = JSHTMLInputElementPrototype::s_info.propHashTable(exec)->entry(exec, propertyName); + if (entry) { + if (entry->attributes() & Function) { + if (entry->function() == jsHTMLInputElementPrototypeFunctionSetSelectionRange) { + slot.setUndefined(); + return true; + } + } + } + + return false; +} + +JSValue* JSHTMLInputElement::selectionStart(ExecState* exec) const +{ + HTMLInputElement* input = static_cast<HTMLInputElement*>(impl()); + if (!input->canHaveSelection()) + return jsUndefined(); + + return jsNumber(exec, input->selectionStart()); +} + +JSValue* JSHTMLInputElement::selectionEnd(ExecState* exec) const +{ + HTMLInputElement* input = static_cast<HTMLInputElement*>(impl()); + if (!input->canHaveSelection()) + return jsUndefined(); + + return jsNumber(exec, input->selectionEnd()); +} + +} // namespace WebCore diff --git a/WebCore/bindings/js/JSHTMLInputElementCustom.h b/WebCore/bindings/js/JSHTMLInputElementCustom.h new file mode 100644 index 0000000..f5222d2 --- /dev/null +++ b/WebCore/bindings/js/JSHTMLInputElementCustom.h @@ -0,0 +1,31 @@ +/* + * Copyright (C) 2008 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef JSHTMLInputElementCustom_h +#define JSHTMLInputElementCustom_h + +#include "JSHTMLInputElement.h" + +#endif // JSHTMLInputElementCustom_h diff --git a/WebCore/bindings/js/JSHTMLObjectElementCustom.cpp b/WebCore/bindings/js/JSHTMLObjectElementCustom.cpp index 7976138..9208af0 100644 --- a/WebCore/bindings/js/JSHTMLObjectElementCustom.cpp +++ b/WebCore/bindings/js/JSHTMLObjectElementCustom.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2007 Apple Inc. All rights reserved. + * Copyright (C) 2007, 2008 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -24,34 +24,28 @@ */ #include "config.h" -#include "JSHTMLObjectElement.h" +#include "JSHTMLObjectElementCustom.h" #include "HTMLObjectElement.h" -#include "kjs_dom.h" -#include "kjs_html.h" +#include "JSPluginElementFunctions.h" namespace WebCore { -using namespace KJS; +using namespace JSC; bool JSHTMLObjectElement::customGetOwnPropertySlot(ExecState* exec, const Identifier& propertyName, PropertySlot& slot) { - return runtimeObjectCustomGetOwnPropertySlot(exec, propertyName, slot, this, static_cast<HTMLElement*>(impl())); + return runtimeObjectCustomGetOwnPropertySlot(exec, propertyName, slot, this); } -bool JSHTMLObjectElement::customPut(ExecState* exec, const Identifier& propertyName, JSValue* value, int attr) +bool JSHTMLObjectElement::customPut(ExecState* exec, const Identifier& propertyName, JSValue* value, PutPropertySlot& slot) { - return runtimeObjectCustomPut(exec, propertyName, value, attr, static_cast<HTMLElement*>(impl())); + return runtimeObjectCustomPut(exec, propertyName, value, impl(), slot); } -bool JSHTMLObjectElement::implementsCall() const +CallType JSHTMLObjectElement::getCallData(CallData& callData) { - return runtimeObjectImplementsCall(static_cast<HTMLElement*>(impl())); -} - -JSValue* JSHTMLObjectElement::callAsFunction(ExecState* exec, JSObject* thisObj, const List& args) -{ - return runtimeObjectCallAsFunction(exec, thisObj, args, static_cast<HTMLElement*>(impl())); + return runtimeObjectGetCallData(impl(), callData); } bool JSHTMLObjectElement::canGetItemsForName(ExecState*, HTMLObjectElement*, const Identifier& propertyName) @@ -59,9 +53,9 @@ bool JSHTMLObjectElement::canGetItemsForName(ExecState*, HTMLObjectElement*, con return propertyName == "__apple_runtime_object"; } -JSValue* JSHTMLObjectElement::nameGetter(ExecState* exec, JSObject* originalObject, const Identifier& propertyName, const PropertySlot& slot) +JSValue* JSHTMLObjectElement::nameGetter(ExecState* exec, const Identifier& propertyName, const PropertySlot& slot) { - return runtimeObjectGetter(exec, originalObject, propertyName, slot); + return runtimeObjectGetter(exec, propertyName, slot); } } // namespace WebCore diff --git a/WebCore/bindings/js/JSHTMLObjectElementCustom.h b/WebCore/bindings/js/JSHTMLObjectElementCustom.h new file mode 100644 index 0000000..38659f9 --- /dev/null +++ b/WebCore/bindings/js/JSHTMLObjectElementCustom.h @@ -0,0 +1,31 @@ +/* + * Copyright (C) 2008 Apple Inc. All Rights Reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef JSHTMLObjectElementCustom_h +#define JSHTMLObjectElementCustom_h + +#include "JSHTMLObjectElement.h" + +#endif // JSHTMLObjectElementCustom_h diff --git a/WebCore/bindings/js/JSHTMLOptionElementConstructor.cpp b/WebCore/bindings/js/JSHTMLOptionElementConstructor.cpp deleted file mode 100644 index 0311b32..0000000 --- a/WebCore/bindings/js/JSHTMLOptionElementConstructor.cpp +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright (C) 2006, 2007 Apple Inc. All rights reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#include "config.h" -#include "JSHTMLOptionElementConstructor.h" - -#include "Document.h" -#include "HTMLOptionElement.h" -#include "JSHTMLOptionElement.h" -#include "Text.h" - -namespace WebCore { - -using namespace KJS; - -JSHTMLOptionElementConstructor::JSHTMLOptionElementConstructor(ExecState* exec, Document* d) - : KJS::DOMObject(exec->lexicalGlobalObject()->objectPrototype()) - , m_doc(d) -{ - putDirect(exec->propertyNames().length, jsNumber(4), ReadOnly|DontDelete|DontEnum); -} - -bool JSHTMLOptionElementConstructor::implementsConstruct() const -{ - return true; -} - -JSObject* JSHTMLOptionElementConstructor::construct(ExecState* exec, const List& args) -{ - int exception = 0; - RefPtr<Element> el(m_doc->createElement("option", exception)); - HTMLOptionElement* opt = 0; - if (el) { - opt = static_cast<HTMLOptionElement*>(el.get()); - int sz = args.size(); - RefPtr<Text> text = m_doc->createTextNode(""); - opt->appendChild(text, exception); - if (exception == 0 && sz > 0) - text->setData(args[0]->toString(exec), exception); - if (exception == 0 && sz > 1) - opt->setValue(args[1]->toString(exec)); - if (exception == 0 && sz > 2) - opt->setDefaultSelected(args[2]->toBoolean(exec)); - if (exception == 0 && sz > 3) - opt->setSelected(args[3]->toBoolean(exec)); - } - - setDOMException(exec, exception); - return static_cast<JSObject*>(toJS(exec, opt)); -} - -} // namespace WebCore diff --git a/WebCore/bindings/js/JSHTMLOptionsCollectionCustom.cpp b/WebCore/bindings/js/JSHTMLOptionsCollectionCustom.cpp index b0da9a7..2b3c04e 100644 --- a/WebCore/bindings/js/JSHTMLOptionsCollectionCustom.cpp +++ b/WebCore/bindings/js/JSHTMLOptionsCollectionCustom.cpp @@ -31,14 +31,14 @@ #include <wtf/MathExtras.h> -using namespace KJS; +using namespace JSC; namespace WebCore { JSValue* JSHTMLOptionsCollection::length(ExecState* exec) const { HTMLOptionsCollection* imp = static_cast<HTMLOptionsCollection*>(impl()); - return jsNumber(imp->length()); + return jsNumber(exec, imp->length()); } void JSHTMLOptionsCollection::setLength(ExecState* exec, JSValue* value) @@ -60,23 +60,23 @@ void JSHTMLOptionsCollection::setLength(ExecState* exec, JSValue* value) setDOMException(exec, ec); } -void JSHTMLOptionsCollection::indexSetter(ExecState* exec, unsigned index, JSValue* value, int attr) +void JSHTMLOptionsCollection::indexSetter(ExecState* exec, unsigned index, JSValue* value) { HTMLOptionsCollection* imp = static_cast<HTMLOptionsCollection*>(impl()); HTMLSelectElement* base = static_cast<HTMLSelectElement*>(imp->base()); selectIndexSetter(base, exec, index, value); } -JSValue* JSHTMLOptionsCollection::add(ExecState* exec, const List& args) +JSValue* JSHTMLOptionsCollection::add(ExecState* exec, const ArgList& args) { HTMLOptionsCollection* imp = static_cast<HTMLOptionsCollection*>(impl()); - HTMLOptionElement* option = toHTMLOptionElement(args[0]); + HTMLOptionElement* option = toHTMLOptionElement(args.at(exec, 0)); ExceptionCode ec = 0; if (args.size() < 2) imp->add(option, ec); else { bool ok; - int index = args[1]->toInt32(exec, ok); + int index = args.at(exec, 1)->toInt32(exec, ok); if (exec->hadException()) return jsUndefined(); if (!ok) @@ -88,10 +88,10 @@ JSValue* JSHTMLOptionsCollection::add(ExecState* exec, const List& args) return jsUndefined(); } -JSValue* JSHTMLOptionsCollection::remove(ExecState* exec, const List& args) +JSValue* JSHTMLOptionsCollection::remove(ExecState* exec, const ArgList& args) { HTMLOptionsCollection* imp = static_cast<HTMLOptionsCollection*>(impl()); - JSHTMLSelectElement* base = static_cast<JSHTMLSelectElement*>(toJS(exec, imp->base())); + JSHTMLSelectElement* base = static_cast<JSHTMLSelectElement*>(asObject(toJS(exec, imp->base()))); return base->remove(exec, args); } diff --git a/WebCore/bindings/js/JSHTMLSelectElementCustom.cpp b/WebCore/bindings/js/JSHTMLSelectElementCustom.cpp index c127d4b..06789ac 100644 --- a/WebCore/bindings/js/JSHTMLSelectElementCustom.cpp +++ b/WebCore/bindings/js/JSHTMLSelectElementCustom.cpp @@ -26,28 +26,27 @@ #include "HTMLOptionElement.h" #include "HTMLSelectElement.h" #include "JSHTMLOptionElement.h" -#include "kjs_html.h" namespace WebCore { -using namespace KJS; +using namespace JSC; using namespace HTMLNames; -JSValue* JSHTMLSelectElement::remove(ExecState* exec, const List& args) +JSValue* JSHTMLSelectElement::remove(ExecState* exec, const ArgList& args) { HTMLSelectElement& select = *static_cast<HTMLSelectElement*>(impl()); // we support both options index and options objects - HTMLElement* element = toHTMLElement(args[0]); + HTMLElement* element = toHTMLElement(args.at(exec, 0)); if (element && element->hasTagName(optionTag)) select.remove(static_cast<HTMLOptionElement*>(element)->index()); else - select.remove(args[0]->toInt32(exec)); + select.remove(args.at(exec, 0)->toInt32(exec)); return jsUndefined(); } -void selectIndexSetter(HTMLSelectElement* select, KJS::ExecState* exec, unsigned index, KJS::JSValue* value) +void selectIndexSetter(HTMLSelectElement* select, JSC::ExecState* exec, unsigned index, JSC::JSValue* value) { if (value->isUndefinedOrNull()) select->remove(index); @@ -62,7 +61,7 @@ void selectIndexSetter(HTMLSelectElement* select, KJS::ExecState* exec, unsigned } } -void JSHTMLSelectElement::indexSetter(KJS::ExecState* exec, unsigned index, KJS::JSValue* value, int attr) +void JSHTMLSelectElement::indexSetter(JSC::ExecState* exec, unsigned index, JSC::JSValue* value) { selectIndexSetter(static_cast<HTMLSelectElement*>(impl()), exec, index, value); } diff --git a/WebCore/bindings/js/JSHTMLSelectElementCustom.h b/WebCore/bindings/js/JSHTMLSelectElementCustom.h index b6f08c7..de32c72 100644 --- a/WebCore/bindings/js/JSHTMLSelectElementCustom.h +++ b/WebCore/bindings/js/JSHTMLSelectElementCustom.h @@ -33,7 +33,7 @@ namespace WebCore { -void selectIndexSetter(HTMLSelectElement*, KJS::ExecState*, unsigned index, KJS::JSValue*); +void selectIndexSetter(HTMLSelectElement*, JSC::ExecState*, unsigned index, JSC::JSValue*); } diff --git a/WebCore/bindings/js/JSHistoryCustom.cpp b/WebCore/bindings/js/JSHistoryCustom.cpp index 36f1785..31699a0 100644 --- a/WebCore/bindings/js/JSHistoryCustom.cpp +++ b/WebCore/bindings/js/JSHistoryCustom.cpp @@ -27,16 +27,31 @@ */ #include "config.h" -#include "JSHistory.h" +#include "JSHistoryCustom.h" #include "Frame.h" #include "History.h" -#include "kjs_window.h" +#include <runtime/PrototypeFunction.h> -using namespace KJS; +using namespace JSC; namespace WebCore { +JSValue* nonCachingStaticBackFunctionGetter(ExecState* exec, const Identifier& propertyName, const PropertySlot& slot) +{ + return new (exec) PrototypeFunction(exec, 0, propertyName, jsHistoryPrototypeFunctionBack); +} + +JSValue* nonCachingStaticForwardFunctionGetter(ExecState* exec, const Identifier& propertyName, const PropertySlot& slot) +{ + return new (exec) PrototypeFunction(exec, 0, propertyName, jsHistoryPrototypeFunctionForward); +} + +JSValue* nonCachingStaticGoFunctionGetter(ExecState* exec, const Identifier& propertyName, const PropertySlot& slot) +{ + return new (exec) PrototypeFunction(exec, 1, propertyName, jsHistoryPrototypeFunctionGo); +} + bool JSHistory::customGetOwnPropertySlot(ExecState* exec, const Identifier& propertyName, PropertySlot& slot) { // When accessing History cross-domain, functions are always the native built-in ones. @@ -49,15 +64,20 @@ bool JSHistory::customGetOwnPropertySlot(ExecState* exec, const Identifier& prop return false; // Check for the few functions that we allow, even when called cross-domain. - const HashEntry* entry = Lookup::findEntry(JSHistoryPrototype::info.propHashTable, propertyName); + const HashEntry* entry = JSHistoryPrototype::s_info.propHashTable(exec)->entry(exec, propertyName); if (entry) { // Allow access to back(), forward() and go() from any frame. - if ((entry->attr & Function) - && (entry->value.functionValue == jsHistoryPrototypeFunctionBack - || entry->value.functionValue == jsHistoryPrototypeFunctionForward - || entry->value.functionValue == jsHistoryPrototypeFunctionGo)) { - slot.setStaticEntry(this, entry, nonCachingStaticFunctionGetter); - return true; + if (entry->attributes() & Function) { + if (entry->function() == jsHistoryPrototypeFunctionBack) { + slot.setCustom(this, nonCachingStaticBackFunctionGetter); + return true; + } else if (entry->function() == jsHistoryPrototypeFunctionForward) { + slot.setCustom(this, nonCachingStaticForwardFunctionGetter); + return true; + } else if (entry->function() == jsHistoryPrototypeFunctionGo) { + slot.setCustom(this, nonCachingStaticGoFunctionGetter); + return true; + } } } else { // Allow access to toString() cross-domain, but always Object.toString. @@ -68,11 +88,11 @@ bool JSHistory::customGetOwnPropertySlot(ExecState* exec, const Identifier& prop } printErrorMessageForFrame(impl()->frame(), message); - slot.setUndefined(this); + slot.setUndefined(); return true; } -bool JSHistory::customPut(ExecState* exec, const Identifier& propertyName, JSValue* value, int attr) +bool JSHistory::customPut(ExecState* exec, const Identifier& propertyName, JSValue* value, PutPropertySlot&) { // Only allow putting by frames in the same origin. if (!allowsAccessFromFrame(exec, impl()->frame())) diff --git a/WebCore/bindings/js/JSHistoryCustom.h b/WebCore/bindings/js/JSHistoryCustom.h new file mode 100644 index 0000000..40edc6f --- /dev/null +++ b/WebCore/bindings/js/JSHistoryCustom.h @@ -0,0 +1,33 @@ +/* + * Copyright (C) 2008 Apple Inc. All Rights Reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef JSHistoryCustom_h +#define JSHistoryCustom_h + +#include "JSHistory.h" + +#endif // JSHistoryCustom_h + + diff --git a/WebCore/bindings/js/JSImageConstructor.cpp b/WebCore/bindings/js/JSImageConstructor.cpp new file mode 100644 index 0000000..c1e4630 --- /dev/null +++ b/WebCore/bindings/js/JSImageConstructor.cpp @@ -0,0 +1,85 @@ +/* + * Copyright (C) 1999-2000 Harri Porten (porten@kde.org) + * Copyright (C) 2004, 2005, 2006, 2007, 2008 Apple Inc. All rights reserved. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include "config.h" +#include "JSImageConstructor.h" + +#include "HTMLImageElement.h" +#include "JSNode.h" +#include "ScriptExecutionContext.h" + +using namespace JSC; + +namespace WebCore { + +ASSERT_CLASS_FITS_IN_CELL(JSImageConstructor) + +const ClassInfo JSImageConstructor::s_info = { "ImageConstructor", 0, 0, 0 }; + +JSImageConstructor::JSImageConstructor(ExecState* exec, ScriptExecutionContext* context) + : DOMObject(JSImageConstructor::createStructureID(exec->lexicalGlobalObject()->objectPrototype())) +{ + ASSERT(context->isDocument()); + m_document = static_cast<JSDocument*>(asObject(toJS(exec, static_cast<Document*>(context)))); +} + +static JSObject* constructImage(ExecState* exec, JSObject* constructor, const ArgList& args) +{ + bool widthSet = false; + bool heightSet = false; + int width = 0; + int height = 0; + if (args.size() > 0) { + widthSet = true; + width = args.at(exec, 0)->toInt32(exec); + } + if (args.size() > 1) { + heightSet = true; + height = args.at(exec, 1)->toInt32(exec); + } + + Document* document = static_cast<JSImageConstructor*>(constructor)->document(); + + // Calling toJS on the document causes the JS document wrapper to be + // added to the window object. This is done to ensure that JSDocument::mark + // will be called (which will cause the image element to be marked if necessary). + toJS(exec, document); + + RefPtr<HTMLImageElement> image = new HTMLImageElement(document); + if (widthSet) + image->setWidth(width); + if (heightSet) + image->setHeight(height); + return asObject(toJS(exec, image.release())); +} + +ConstructType JSImageConstructor::getConstructData(ConstructData& constructData) +{ + constructData.native.function = constructImage; + return ConstructTypeHost; +} + +void JSImageConstructor::mark() +{ + DOMObject::mark(); + if (!m_document->marked()) + m_document->mark(); +} + +} // namespace WebCore diff --git a/WebCore/bindings/js/JSImageConstructor.h b/WebCore/bindings/js/JSImageConstructor.h new file mode 100644 index 0000000..13cce26 --- /dev/null +++ b/WebCore/bindings/js/JSImageConstructor.h @@ -0,0 +1,45 @@ +/* + * Copyright (C) 1999 Harri Porten (porten@kde.org) + * Copyright (C) 2004, 2006, 2007, 2008 Apple Inc. All rights reserved. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#ifndef JSImageConstructor_h +#define JSImageConstructor_h + +#include "JSDOMBinding.h" +#include "JSDocument.h" + +namespace WebCore { + + class JSImageConstructor : public DOMObject { + public: + JSImageConstructor(JSC::ExecState*, ScriptExecutionContext*); + Document* document() const { return m_document->impl(); } + + static const JSC::ClassInfo s_info; + + virtual void mark(); + private: + virtual JSC::ConstructType getConstructData(JSC::ConstructData&); + virtual const JSC::ClassInfo* classInfo() const { return &s_info; } + + JSDocument* m_document; + }; + +} // namespace WebCore + +#endif // JSImageConstructor_h diff --git a/WebCore/bindings/js/JSImageDataCustom.cpp b/WebCore/bindings/js/JSImageDataCustom.cpp new file mode 100644 index 0000000..50f237a --- /dev/null +++ b/WebCore/bindings/js/JSImageDataCustom.cpp @@ -0,0 +1,50 @@ +/* + * Copyright (C) 2008 Apple Inc. All Rights Reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "JSImageData.h" + +#include "ImageData.h" +using namespace JSC; + +namespace WebCore { + +JSValue* toJS(ExecState* exec, ImageData* imageData) +{ + if (!imageData) + return jsNull(); + + DOMObject* wrapper = getCachedDOMObjectWrapper(exec->globalData(), imageData); + if (wrapper) + return wrapper; + + wrapper = CREATE_DOM_OBJECT_WRAPPER(exec, ImageData, imageData); + + exec->heap()->reportExtraMemoryCost(imageData->data()->length()); + + return wrapper; +} + +} diff --git a/WebCore/bindings/js/JSInspectedObjectWrapper.cpp b/WebCore/bindings/js/JSInspectedObjectWrapper.cpp new file mode 100644 index 0000000..9bc7e7d --- /dev/null +++ b/WebCore/bindings/js/JSInspectedObjectWrapper.cpp @@ -0,0 +1,126 @@ +/* + * Copyright (C) 2008 Apple Inc. All Rights Reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "JSInspectedObjectWrapper.h" + +#include "JSInspectorCallbackWrapper.h" +#include <runtime/JSGlobalObject.h> + +using namespace JSC; + +namespace WebCore { + +ASSERT_CLASS_FITS_IN_CELL(JSInspectedObjectWrapper) + +typedef HashMap<JSObject*, JSInspectedObjectWrapper*> WrapperMap; +typedef HashMap<JSGlobalObject*, WrapperMap*> GlobalObjectWrapperMap; + +static GlobalObjectWrapperMap& wrappers() +{ + static GlobalObjectWrapperMap map; + return map; +} + +const ClassInfo JSInspectedObjectWrapper::s_info = { "JSInspectedObjectWrapper", &JSQuarantinedObjectWrapper::s_info, 0, 0 }; + +JSValue* JSInspectedObjectWrapper::wrap(ExecState* unwrappedExec, JSValue* unwrappedValue) +{ + if (!unwrappedValue->isObject()) + return unwrappedValue; + + JSObject* unwrappedObject = asObject(unwrappedValue); + + if (unwrappedObject->inherits(&JSInspectedObjectWrapper::s_info)) + return unwrappedObject; + + if (WrapperMap* wrapperMap = wrappers().get(unwrappedExec->dynamicGlobalObject())) + if (JSInspectedObjectWrapper* wrapper = wrapperMap->get(unwrappedObject)) + return wrapper; + + JSValue* prototype = unwrappedObject->prototype(); + ASSERT(prototype->isNull() || prototype->isObject()); + + if (prototype->isNull()) + return new (unwrappedExec) JSInspectedObjectWrapper(unwrappedExec, unwrappedObject, JSQuarantinedObjectWrapper::createStructureID(jsNull())); + return new (unwrappedExec) JSInspectedObjectWrapper(unwrappedExec, unwrappedObject, JSQuarantinedObjectWrapper::createStructureID(asObject(wrap(unwrappedExec, prototype)))); +} + +JSInspectedObjectWrapper::JSInspectedObjectWrapper(ExecState* unwrappedExec, JSObject* unwrappedObject, PassRefPtr<StructureID> structureID) + : JSQuarantinedObjectWrapper(unwrappedExec, unwrappedObject, structureID) +{ + WrapperMap* wrapperMap = wrappers().get(unwrappedGlobalObject()); + if (!wrapperMap) { + wrapperMap = new WrapperMap; + wrappers().set(unwrappedGlobalObject(), wrapperMap); + } + + ASSERT(!wrapperMap->contains(unwrappedObject)); + wrapperMap->set(unwrappedObject, this); +} + +JSInspectedObjectWrapper::~JSInspectedObjectWrapper() +{ + ASSERT(wrappers().contains(unwrappedGlobalObject())); + WrapperMap* wrapperMap = wrappers().get(unwrappedGlobalObject()); + + ASSERT(wrapperMap->contains(unwrappedObject())); + wrapperMap->remove(unwrappedObject()); + + if (wrapperMap->isEmpty()) { + wrappers().remove(unwrappedGlobalObject()); + delete wrapperMap; + } +} + +JSValue* JSInspectedObjectWrapper::prepareIncomingValue(ExecState*, JSValue* value) const +{ + // The Inspector is only allowed to pass primitive values and wrapped objects to objects from the inspected page. + + if (!value->isObject()) + return value; + + JSQuarantinedObjectWrapper* wrapper = asWrapper(value); + ASSERT_WITH_MESSAGE(wrapper, "Objects passed to JSInspectedObjectWrapper must be wrapped"); + if (!wrapper) + return jsUndefined(); + + if (wrapper->allowsUnwrappedAccessFrom(unwrappedExecState())) { + ASSERT_WITH_MESSAGE(wrapper->inherits(&s_info), "A wrapper contains an object from the inspected page but is not a JSInspectedObjectWrapper"); + if (!wrapper->inherits(&s_info)) + return jsUndefined(); + + // Return the unwrapped object so the inspected page never sees one of its own objects in wrapped form. + return wrapper->unwrappedObject(); + } + + ASSERT_WITH_MESSAGE(wrapper->inherits(&JSInspectorCallbackWrapper::s_info), "A wrapper that was not from the inspected page and is not an Inspector callback was passed to a JSInspectedObjectWrapper"); + if (!wrapper->inherits(&JSInspectorCallbackWrapper::s_info)) + return jsUndefined(); + + return wrapper; +} + +} // namespace WebCore diff --git a/WebCore/bindings/js/JSInspectedObjectWrapper.h b/WebCore/bindings/js/JSInspectedObjectWrapper.h new file mode 100644 index 0000000..1c6f2db --- /dev/null +++ b/WebCore/bindings/js/JSInspectedObjectWrapper.h @@ -0,0 +1,59 @@ +/* + * Copyright (C) 2008 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef JSInspectedObjectWrapper_h +#define JSInspectedObjectWrapper_h + +#include "JSQuarantinedObjectWrapper.h" + +namespace WebCore { + + class JSInspectedObjectWrapper : public JSQuarantinedObjectWrapper { + public: + static JSC::JSValue* wrap(JSC::ExecState* unwrappedExec, JSC::JSValue* unwrappedValue); + virtual ~JSInspectedObjectWrapper(); + + static const JSC::ClassInfo s_info; + + private: + JSInspectedObjectWrapper(JSC::ExecState* unwrappedExec, JSC::JSObject* unwrappedObject, PassRefPtr<JSC::StructureID>); + + virtual bool allowsGetProperty() const { return true; } + virtual bool allowsSetProperty() const { return true; } + virtual bool allowsDeleteProperty() const { return true; } + virtual bool allowsConstruct() const { return true; } + virtual bool allowsHasInstance() const { return true; } + virtual bool allowsCallAsFunction() const { return true; } + virtual bool allowsGetPropertyNames() const { return true; } + + virtual JSC::JSValue* prepareIncomingValue(JSC::ExecState* unwrappedExec, JSC::JSValue* unwrappedValue) const; + virtual JSC::JSValue* wrapOutgoingValue(JSC::ExecState* unwrappedExec, JSC::JSValue* unwrappedValue) const { return wrap(unwrappedExec, unwrappedValue); } + + virtual const JSC::ClassInfo* classInfo() const { return &s_info; } + }; + +} // namespace WebCore + +#endif // JSInspectedObjectWrapper_h diff --git a/WebCore/bindings/js/JSInspectorCallbackWrapper.cpp b/WebCore/bindings/js/JSInspectorCallbackWrapper.cpp new file mode 100644 index 0000000..8440a1f --- /dev/null +++ b/WebCore/bindings/js/JSInspectorCallbackWrapper.cpp @@ -0,0 +1,106 @@ +/* + * Copyright (C) 2008 Apple Inc. All Rights Reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "JSInspectorCallbackWrapper.h" + +#include "JSInspectedObjectWrapper.h" + +using namespace JSC; + +namespace WebCore { + +ASSERT_CLASS_FITS_IN_CELL(JSInspectorCallbackWrapper) + +typedef HashMap<JSObject*, JSInspectorCallbackWrapper*> WrapperMap; + +static WrapperMap& wrappers() +{ + static WrapperMap map; + return map; +} + +const ClassInfo JSInspectorCallbackWrapper::s_info = { "JSInspectorCallbackWrapper", &JSQuarantinedObjectWrapper::s_info, 0, 0 }; + +static StructureID* leakInspectorCallbackWrapperStructure() +{ + StructureID::startIgnoringLeaks(); + StructureID* structure = JSInspectorCallbackWrapper::createStructureID(jsNull()).releaseRef(); + StructureID::stopIgnoringLeaks(); + return structure; +} + +JSValue* JSInspectorCallbackWrapper::wrap(ExecState* unwrappedExec, JSValue* unwrappedValue) +{ + if (!unwrappedValue->isObject()) + return unwrappedValue; + + JSObject* unwrappedObject = asObject(unwrappedValue); + + if (unwrappedObject->inherits(&JSInspectorCallbackWrapper::s_info)) + return unwrappedObject; + + if (JSInspectorCallbackWrapper* wrapper = wrappers().get(unwrappedObject)) + return wrapper; + + JSValue* prototype = unwrappedObject->prototype(); + ASSERT(prototype->isNull() || prototype->isObject()); + + if (prototype->isNull()) { + static StructureID* structure = leakInspectorCallbackWrapperStructure(); + return new (unwrappedExec) JSInspectorCallbackWrapper(unwrappedExec, unwrappedObject, structure); + } + return new (unwrappedExec) JSInspectorCallbackWrapper(unwrappedExec, unwrappedObject, asObject(wrap(unwrappedExec, prototype))->inheritorID()); +} + +JSInspectorCallbackWrapper::JSInspectorCallbackWrapper(ExecState* unwrappedExec, JSObject* unwrappedObject, PassRefPtr<StructureID> structureID) + : JSQuarantinedObjectWrapper(unwrappedExec, unwrappedObject, structureID) +{ + ASSERT(!wrappers().contains(unwrappedObject)); + wrappers().set(unwrappedObject, this); +} + +JSInspectorCallbackWrapper::~JSInspectorCallbackWrapper() +{ + wrappers().remove(unwrappedObject()); +} + +JSValue* JSInspectorCallbackWrapper::prepareIncomingValue(ExecState* unwrappedExec, JSValue* unwrappedValue) const +{ + if (JSQuarantinedObjectWrapper* wrapper = asWrapper(unwrappedValue)) { + // The only time a wrapper should be passed into a JSInspectorCallbackWrapper is when a client-side storage callback + // is called. (The client-side storage API calls the callback with the `this` object set to the callback itself.) + ASSERT_WITH_MESSAGE(wrapper == this, "A different wrapper was passed into a JSInspectorCallbackWrapper"); + if (wrapper != this) + return jsUndefined(); + + return wrapper->unwrappedObject(); + } + + // Any value being passed to the Inspector from the inspected page should be wrapped in a JSInspectedObjectWrapper. + return JSInspectedObjectWrapper::wrap(unwrappedExec, unwrappedValue); +} + +} // namespace WebCore diff --git a/WebCore/bindings/js/JSInspectorCallbackWrapper.h b/WebCore/bindings/js/JSInspectorCallbackWrapper.h new file mode 100644 index 0000000..5238add --- /dev/null +++ b/WebCore/bindings/js/JSInspectorCallbackWrapper.h @@ -0,0 +1,53 @@ +/* + * Copyright (C) 2008 Apple Inc. All Rights Reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef JSInspectorCallbackWrapper_h +#define JSInspectorCallbackWrapper_h + +#include "JSQuarantinedObjectWrapper.h" + +namespace WebCore { + + class JSInspectorCallbackWrapper : public JSQuarantinedObjectWrapper { + public: + static JSC::JSValue* wrap(JSC::ExecState* unwrappedExec, JSC::JSValue* unwrappedValue); + + virtual ~JSInspectorCallbackWrapper(); + + virtual const JSC::ClassInfo* classInfo() const { return &s_info; } + static const JSC::ClassInfo s_info; + + protected: + JSInspectorCallbackWrapper(JSC::ExecState* unwrappedExec, JSC::JSObject* unwrappedObject, PassRefPtr<JSC::StructureID>); + + virtual bool allowsCallAsFunction() const { return true; } + + virtual JSC::JSValue* prepareIncomingValue(JSC::ExecState* unwrappedExec, JSC::JSValue* unwrappedValue) const; + virtual JSC::JSValue* wrapOutgoingValue(JSC::ExecState* unwrappedExec, JSC::JSValue* unwrappedValue) const { return wrap(unwrappedExec, unwrappedValue); } + }; + +} // namespace WebCore + +#endif // JSInspectorCallbackWrapper_h diff --git a/WebCore/bindings/js/JSJavaScriptCallFrameCustom.cpp b/WebCore/bindings/js/JSJavaScriptCallFrameCustom.cpp new file mode 100644 index 0000000..ce16b31 --- /dev/null +++ b/WebCore/bindings/js/JSJavaScriptCallFrameCustom.cpp @@ -0,0 +1,86 @@ +/* + * Copyright (C) 2008 Apple Inc. All Rights Reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "JSJavaScriptCallFrame.h" + +#include "JavaScriptCallFrame.h" +#include <runtime/ArrayPrototype.h> + +using namespace JSC; + +namespace WebCore { + +JSValue* JSJavaScriptCallFrame::evaluate(ExecState* exec, const ArgList& args) +{ + JSValue* exception = noValue(); + JSValue* result = impl()->evaluate(args.at(exec, 0)->toString(exec), exception); + + if (exception) + exec->setException(exception); + + return result; +} + +JSValue* JSJavaScriptCallFrame::thisObject(ExecState* exec) const +{ + return impl()->thisObject() ? impl()->thisObject() : jsNull(); +} + +JSValue* JSJavaScriptCallFrame::type(ExecState* exec) const +{ + switch (impl()->type()) { + case DebuggerCallFrame::FunctionType: + return jsString(exec, "function"); + case DebuggerCallFrame::ProgramType: + return jsString(exec, "program"); + } + + ASSERT_NOT_REACHED(); + return jsNull(); +} + +JSValue* JSJavaScriptCallFrame::scopeChain(ExecState* exec) const +{ + if (!impl()->scopeChain()) + return jsNull(); + + const ScopeChainNode* scopeChain = impl()->scopeChain(); + ScopeChainIterator iter = scopeChain->begin(); + ScopeChainIterator end = scopeChain->end(); + + // we must always have something in the scope chain + ASSERT(iter != end); + + ArgList list; + do { + list.append(*iter); + ++iter; + } while (iter != end); + + return constructArray(exec, list); +} + +} // namespace WebCore diff --git a/WebCore/bindings/js/JSLocation.cpp b/WebCore/bindings/js/JSLocation.cpp deleted file mode 100644 index b4e63de..0000000 --- a/WebCore/bindings/js/JSLocation.cpp +++ /dev/null @@ -1,326 +0,0 @@ -/* - * Copyright (C) 2000 Harri Porten (porten@kde.org) - * Copyright (C) 2006 Jon Shier (jshier@iastate.edu) - * Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008 Apple Inc. All rights reseved. - * Copyright (C) 2006 Alexey Proskuryakov (ap@webkit.org) - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 - * USA - */ - -#include "config.h" -#include "JSLocation.h" - -#include "DOMWindow.h" -#include "Frame.h" -#include "FrameLoader.h" -#include "PlatformString.h" -#include "kjs_proxy.h" -#include "kjs_window.h" - -#include "JSLocation.lut.h" - -using namespace KJS; - -namespace WebCore { - -const ClassInfo JSLocation::info = { "Location", 0, &JSLocationTable }; - -/* -@begin JSLocationTable 12 - assign WebCore::jsLocationProtoFuncAssign DontDelete|Function 1 - hash WebCore::JSLocation::Hash DontDelete - host WebCore::JSLocation::Host DontDelete - hostname WebCore::JSLocation::Hostname DontDelete - href WebCore::JSLocation::Href DontDelete - pathname WebCore::JSLocation::Pathname DontDelete - port WebCore::JSLocation::Port DontDelete - protocol WebCore::JSLocation::Protocol DontDelete - search WebCore::JSLocation::Search DontDelete - toString WebCore::jsLocationProtoFuncToString DontEnum|DontDelete|Function 0 - replace WebCore::jsLocationProtoFuncReplace DontDelete|Function 1 - reload WebCore::jsLocationProtoFuncReload DontDelete|Function 0 -@end -*/ - -JSLocation::JSLocation(JSObject* /*prototype*/, Frame* frame) - : DOMObject(jsNull()) // FIXME: this needs to take a real prototype - , m_frame(frame) -{ -} - -JSValue* JSLocation::getValueProperty(ExecState* exec, int token) const -{ - const KURL& url = m_frame->loader()->url(); - switch (token) { - case Hash: - return jsString(url.ref().isNull() ? "" : "#" + url.ref()); - case Host: { - // Note: this is the IE spec. The NS spec swaps the two, it says - // "The hostname property is the concatenation of the host and port properties, separated by a colon." - // Bleh. - UString str = url.host(); - if (url.port()) - str += ":" + String::number((int)url.port()); - return jsString(str); - } - case Hostname: - return jsString(url.host()); - case Href: - if (!url.hasPath()) - return jsString(url.prettyURL() + "/"); - return jsString(url.prettyURL()); - case Pathname: - return jsString(url.path().isEmpty() ? "/" : url.path()); - case Port: - return jsString(url.port() ? String::number((int)url.port()) : ""); - case Protocol: - return jsString(url.protocol() + ":"); - case Search: - return jsString(url.query()); - default: - ASSERT_NOT_REACHED(); - return jsUndefined(); - } -} - -bool JSLocation::getOwnPropertySlot(ExecState* exec, const Identifier& propertyName, PropertySlot& slot) -{ - if (customGetOwnPropertySlot(exec, propertyName, slot)) - return true; - return getStaticPropertySlot<JSLocation, JSObject>(exec, &JSLocationTable, this, propertyName, slot); -} - -bool JSLocation::customGetOwnPropertySlot(ExecState* exec, const Identifier& propertyName, PropertySlot& slot) -{ - // When accessing Location cross-domain, functions are always the native built-in ones. - // See JSDOMWindow::customGetOwnPropertySlot for additional details. - - // Our custom code is only needed to implement the Window cross-domain scheme, so if access is - // allowed, return false so the normal lookup will take place. - String message; - if (allowsAccessFromFrame(exec, m_frame, message)) - return false; - - // Check for the few functions that we allow, even when called cross-domain. - const HashEntry* entry = Lookup::findEntry(&JSLocationTable, propertyName); - if (entry && (entry->attr & Function) - && (entry->value.functionValue == jsLocationProtoFuncReplace - || entry->value.functionValue == jsLocationProtoFuncReload - || entry->value.functionValue == jsLocationProtoFuncAssign)) { - slot.setStaticEntry(this, entry, nonCachingStaticFunctionGetter); - return true; - } - // FIXME: Other implementers of the Window cross-domain scheme (Window, History) allow toString, - // but for now we have decided not to, partly because it seems silly to return "[Object Location]" in - // such cases when normally the string form of Location would be the URL. - - printErrorMessageForFrame(m_frame, message); - slot.setUndefined(this); - return true; -} - -void JSLocation::put(ExecState* exec, const Identifier& propertyName, JSValue* value, int attr) -{ - if (!m_frame) - return; - - DeprecatedString str = value->toString(exec); - KURL url = m_frame->loader()->url(); - bool sameDomainAccess = allowsAccessFromFrame(exec, m_frame); - - const HashEntry* entry = Lookup::findEntry(&JSLocationTable, propertyName); - - if (entry) { - // cross-domain access to the location is allowed when assigning the whole location, - // but not when assigning the individual pieces, since that might inadvertently - // disclose other parts of the original location. - if (entry->value.intValue != Href && !sameDomainAccess) - return; - - switch (entry->value.intValue) { - case Href: { - Frame* frame = Window::retrieveActive(exec)->impl()->frame(); - if (!frame) - return; - if (!frame->loader()->shouldAllowNavigation(m_frame)) - return; - url = frame->loader()->completeURL(str); - break; - } - case Hash: { - if (str.startsWith("#")) - str = str.mid(1); - if (url.ref() == str) - return; - url.setRef(str); - break; - } - case Host: { - url.setHostAndPort(str); - break; - } - case Hostname: - url.setHost(str); - break; - case Pathname: - url.setPath(str); - break; - case Port: - url.setPort(str.toUInt()); - break; - case Protocol: - url.setProtocol(str); - break; - case Search: - url.setQuery(str); - break; - default: - // Disallow changing other properties in JSLocationTable. e.g., "window.location.toString = ...". - // <http://bugs.webkit.org/show_bug.cgi?id=12720> - return; - } - } else { - if (sameDomainAccess) - JSObject::put(exec, propertyName, value, attr); - return; - } - - Frame* activeFrame = Window::retrieveActive(exec)->impl()->frame(); -#ifdef ANDROID_JAVASCRIPT_SECURITY - if (!url.protocolIs("javascript") || sameDomainAccess) { -#else - if (!url.deprecatedString().startsWith("javascript:", false) || sameDomainAccess) { -#endif - bool userGesture = activeFrame->scriptProxy()->processingUserGesture(); - m_frame->loader()->scheduleLocationChange(url.string(), activeFrame->loader()->outgoingReferrer(), false, userGesture); - } -} - -bool JSLocation::deleteProperty(ExecState* exec, const Identifier& propertyName) -{ - // Only allow deleting by frames in the same origin. - if (!allowsAccessFromFrame(exec, m_frame)) - return false; - return Base::deleteProperty(exec, propertyName); -} - -void JSLocation::getPropertyNames(ExecState* exec, PropertyNameArray& propertyNames) -{ - // Only allow the location object to enumerated by frames in the same origin. - if (!allowsAccessFromFrame(exec, m_frame)) - return; - Base::getPropertyNames(exec, propertyNames); -} - -JSValue* jsLocationProtoFuncReplace(ExecState* exec, JSObject* thisObj, const List& args) -{ - if (!thisObj->inherits(&JSLocation::info)) - return throwError(exec, TypeError); - JSLocation* location = static_cast<JSLocation*>(thisObj); - Frame* frame = location->frame(); - if (!frame) - return jsUndefined(); - - Frame* activeFrame = Window::retrieveActive(exec)->impl()->frame(); - if (activeFrame) { - if (!activeFrame->loader()->shouldAllowNavigation(frame)) - return jsUndefined(); - DeprecatedString str = args[0]->toString(exec); - const Window* window = Window::retrieveWindow(frame); -#ifdef ANDROID_JAVASCRIPT_SECURITY - if (!protocolIs(str, "javascript") || (window && window->allowsAccessFrom(exec))) { -#else - if (!str.startsWith("javascript:", false) || (window && window->allowsAccessFrom(exec))) { -#endif - bool userGesture = activeFrame->scriptProxy()->processingUserGesture(); - frame->loader()->scheduleLocationChange(activeFrame->loader()->completeURL(str).string(), activeFrame->loader()->outgoingReferrer(), true, userGesture); - } - } - - return jsUndefined(); -} - -JSValue* jsLocationProtoFuncReload(ExecState* exec, JSObject* thisObj, const List& args) -{ - if (!thisObj->inherits(&JSLocation::info)) - return throwError(exec, TypeError); - JSLocation* location = static_cast<JSLocation*>(thisObj); - Frame* frame = location->frame(); - if (!frame) - return jsUndefined(); - - Window* window = Window::retrieveWindow(frame); - if (!window->allowsAccessFrom(exec)) - return jsUndefined(); - -#ifdef ANDROID_JAVASCRIPT_SECURITY - if (!frame->loader()->url().protocolIs("javascript") || (window && window->allowsAccessFrom(exec))) { -#else - if (!frame->loader()->url().deprecatedString().startsWith("javascript:", false) || (window && window->allowsAccessFrom(exec))) { -#endif - bool userGesture = Window::retrieveActive(exec)->impl()->frame()->scriptProxy()->processingUserGesture(); - frame->loader()->scheduleRefresh(userGesture); - } - return jsUndefined(); -} - -JSValue* jsLocationProtoFuncAssign(ExecState* exec, JSObject* thisObj, const List& args) -{ - if (!thisObj->inherits(&JSLocation::info)) - return throwError(exec, TypeError); - JSLocation* location = static_cast<JSLocation*>(thisObj); - Frame* frame = location->frame(); - if (!frame) - return jsUndefined(); - - Frame* activeFrame = Window::retrieveActive(exec)->impl()->frame(); - if (activeFrame) { - if (!activeFrame->loader()->shouldAllowNavigation(frame)) - return jsUndefined(); - const Window* window = Window::retrieveWindow(frame); - String dstUrl = activeFrame->loader()->completeURL(args[0]->toString(exec)).string(); -#ifdef ANDROID_JAVASCRIPT_SECURITY - if (!protocolIs(dstUrl, "javascript") || (window && window->allowsAccessFrom(exec))) { -#else - if (!dstUrl.startsWith("javascript:", false) || (window && window->allowsAccessFrom(exec))) { -#endif - bool userGesture = activeFrame->scriptProxy()->processingUserGesture(); - // We want a new history item if this JS was called via a user gesture - frame->loader()->scheduleLocationChange(dstUrl, activeFrame->loader()->outgoingReferrer(), false, userGesture); - } - } - - return jsUndefined(); -} - -JSValue* jsLocationProtoFuncToString(ExecState* exec, JSObject* thisObj, const List& args) -{ - if (!thisObj->inherits(&JSLocation::info)) - return throwError(exec, TypeError); - JSLocation* location = static_cast<JSLocation*>(thisObj); - Frame* frame = location->frame(); - if (!frame) - return jsUndefined(); - if (!allowsAccessFromFrame(exec, frame)) - return jsUndefined(); - - const KURL& url = frame->loader()->url(); - if (!url.hasPath()) - return jsString(url.prettyURL() + "/"); - return jsString(url.prettyURL()); -} - -} // namespace WebCore diff --git a/WebCore/bindings/js/JSLocation.h b/WebCore/bindings/js/JSLocation.h deleted file mode 100644 index 684cb40..0000000 --- a/WebCore/bindings/js/JSLocation.h +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright (C) 2000 Harri Porten (porten@kde.org) - * Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008 Apple Inc. All rights reseved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#ifndef JSLocation_h -#define JSLocation_h - -#include "kjs_binding.h" - -namespace KJS { - class Window; -} - -namespace WebCore { - - class Frame; - - class JSLocation : public KJS::DOMObject { - typedef KJS::DOMObject Base; - - friend class KJS::Window; - public: - JSLocation(KJS::JSObject* protoype, Frame*); - - virtual bool getOwnPropertySlot(KJS::ExecState*, const KJS::Identifier&, KJS::PropertySlot&); - KJS::JSValue* getValueProperty(KJS::ExecState*, int token) const; - virtual void put(KJS::ExecState*, const KJS::Identifier&, KJS::JSValue*, int attr = KJS::None); - virtual bool deleteProperty(KJS::ExecState*, const KJS::Identifier&); - virtual void getPropertyNames(KJS::ExecState*, KJS::PropertyNameArray&); - - enum { - Hash, Href, Hostname, Host, - Pathname, Port, Protocol, Search, - Replace, Reload, ToString, Assign - }; - - Frame* frame() const { return m_frame; } - - virtual const KJS::ClassInfo* classInfo() const { return &info; } - static const KJS::ClassInfo info; - - private: - bool customGetOwnPropertySlot(KJS::ExecState*, const KJS::Identifier&, KJS::PropertySlot&); - - Frame* m_frame; - }; - - // Functions - KJS::JSValue* jsLocationProtoFuncAssign(KJS::ExecState*, KJS::JSObject*, const KJS::List&); - KJS::JSValue* jsLocationProtoFuncToString(KJS::ExecState*, KJS::JSObject*, const KJS::List&); - KJS::JSValue* jsLocationProtoFuncReplace(KJS::ExecState*, KJS::JSObject*, const KJS::List&); - KJS::JSValue* jsLocationProtoFuncReload(KJS::ExecState*, KJS::JSObject*, const KJS::List&); - -} // namespace WebCore - -#endif // JSLocation_h diff --git a/WebCore/bindings/js/JSLocationCustom.cpp b/WebCore/bindings/js/JSLocationCustom.cpp new file mode 100644 index 0000000..a5ad179 --- /dev/null +++ b/WebCore/bindings/js/JSLocationCustom.cpp @@ -0,0 +1,309 @@ +/* + * Copyright (C) 2000 Harri Porten (porten@kde.org) + * Copyright (C) 2006 Jon Shier (jshier@iastate.edu) + * Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008 Apple Inc. All rights reseved. + * Copyright (C) 2006 Alexey Proskuryakov (ap@webkit.org) + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 + * USA + */ + +#include "config.h" +#include "JSLocationCustom.h" + +#include "DOMWindow.h" +#include "Frame.h" +#include "FrameLoader.h" +#include "JSDOMBinding.h" +#include "JSDOMWindowCustom.h" +#include "KURL.h" +#include "Location.h" +#include "ScriptController.h" +#include <runtime/PrototypeFunction.h> + +using namespace JSC; + +namespace WebCore { + +JSValue* nonCachingStaticReplaceFunctionGetter(ExecState* exec, const Identifier& propertyName, const PropertySlot& slot) +{ + return new (exec) PrototypeFunction(exec, 1, propertyName, jsLocationPrototypeFunctionReplace); +} + +JSValue* nonCachingStaticReloadFunctionGetter(ExecState* exec, const Identifier& propertyName, const PropertySlot& slot) +{ + return new (exec) PrototypeFunction(exec, 0, propertyName, jsLocationPrototypeFunctionReload); +} + +JSValue* nonCachingStaticAssignFunctionGetter(ExecState* exec, const Identifier& propertyName, const PropertySlot& slot) +{ + return new (exec) PrototypeFunction(exec, 1, propertyName, jsLocationPrototypeFunctionAssign); +} + +bool JSLocation::customGetOwnPropertySlot(ExecState* exec, const Identifier& propertyName, PropertySlot& slot) +{ + Frame* frame = impl()->frame(); + if (!frame) { + slot.setUndefined(); + return true; + } + + // When accessing Location cross-domain, functions are always the native built-in ones. + // See JSDOMWindow::customGetOwnPropertySlot for additional details. + + // Our custom code is only needed to implement the Window cross-domain scheme, so if access is + // allowed, return false so the normal lookup will take place. + String message; + if (allowsAccessFromFrame(exec, frame, message)) + return false; + + // Check for the few functions that we allow, even when called cross-domain. + const HashEntry* entry = JSLocationPrototype::s_info.propHashTable(exec)->entry(exec, propertyName); + if (entry && (entry->attributes() & Function)) { + if (entry->function() == jsLocationPrototypeFunctionReplace) { + slot.setCustom(this, nonCachingStaticReplaceFunctionGetter); + return true; + } else if (entry->function() == jsLocationPrototypeFunctionReload) { + slot.setCustom(this, nonCachingStaticReplaceFunctionGetter); + return true; + } else if (entry->function() == jsLocationPrototypeFunctionAssign) { + slot.setCustom(this, nonCachingStaticAssignFunctionGetter); + return true; + } + } + + // FIXME: Other implementers of the Window cross-domain scheme (Window, History) allow toString, + // but for now we have decided not to, partly because it seems silly to return "[Object Location]" in + // such cases when normally the string form of Location would be the URL. + + printErrorMessageForFrame(frame, message); + slot.setUndefined(); + return true; +} + +bool JSLocation::customPut(ExecState* exec, const Identifier& propertyName, JSValue* value, PutPropertySlot& slot) +{ + Frame* frame = impl()->frame(); + if (!frame) + return true; + + bool sameDomainAccess = allowsAccessFromFrame(exec, frame); + + const HashEntry* entry = JSLocation::s_info.propHashTable(exec)->entry(exec, propertyName); + if (!entry) { + if (sameDomainAccess) + JSObject::put(exec, propertyName, value, slot); + return true; + } + + // Cross-domain access to the location is allowed when assigning the whole location, + // but not when assigning the individual pieces, since that might inadvertently + // disclose other parts of the original location. + if (entry->propertyPutter() != setJSLocationHref && !sameDomainAccess) + return true; + + return false; +} + +bool JSLocation::deleteProperty(ExecState* exec, const Identifier& propertyName) +{ + // Only allow deleting by frames in the same origin. + if (!allowsAccessFromFrame(exec, impl()->frame())) + return false; + return Base::deleteProperty(exec, propertyName); +} + +bool JSLocation::customGetPropertyNames(ExecState* exec, PropertyNameArray&) +{ + // Only allow the location object to enumerated by frames in the same origin. + if (!allowsAccessFromFrame(exec, impl()->frame())) + return true; + return false; +} + +static void navigateIfAllowed(ExecState* exec, Frame* frame, const KURL& url, bool lockHistory) +{ + Frame* activeFrame = asJSDOMWindow(exec->dynamicGlobalObject())->impl()->frame(); + if (!url.protocolIs("javascript") || allowsAccessFromFrame(exec, frame)) { + bool userGesture = activeFrame->script()->processingUserGesture(); + frame->loader()->scheduleLocationChange(url.string(), activeFrame->loader()->outgoingReferrer(), lockHistory, userGesture); + } +} + +void JSLocation::setHref(ExecState* exec, JSValue* value) +{ + Frame* frame = impl()->frame(); + ASSERT(frame); + + Frame* activeFrame = asJSDOMWindow(exec->dynamicGlobalObject())->impl()->frame(); + if (!activeFrame) + return; + if (!activeFrame->loader()->shouldAllowNavigation(frame)) + return; + + KURL url = activeFrame->loader()->completeURL(value->toString(exec)); + navigateIfAllowed(exec, frame, url, false); +} + +void JSLocation::setProtocol(ExecState* exec, JSValue* value) +{ + Frame* frame = impl()->frame(); + ASSERT(frame); + + KURL url = frame->loader()->url(); + url.setProtocol(value->toString(exec)); + + navigateIfAllowed(exec, frame, url, false); +} + +void JSLocation::setHost(ExecState* exec, JSValue* value) +{ + Frame* frame = impl()->frame(); + ASSERT(frame); + + KURL url = frame->loader()->url(); + url.setHostAndPort(value->toString(exec)); + + navigateIfAllowed(exec, frame, url, false); +} + +void JSLocation::setHostname(ExecState* exec, JSValue* value) +{ + Frame* frame = impl()->frame(); + ASSERT(frame); + + KURL url = frame->loader()->url(); + url.setHost(value->toString(exec)); + + navigateIfAllowed(exec, frame, url, false); +} + +void JSLocation::setPort(ExecState* exec, JSValue* value) +{ + Frame* frame = impl()->frame(); + ASSERT(frame); + + KURL url = frame->loader()->url(); + // FIXME: Could make this a little less ugly if String provided a toUnsignedShort function. + const UString& portString = value->toString(exec); + int port = charactersToInt(portString.data(), portString.size()); + if (port < 0 || port > 0xFFFF) + port = 0; + url.setPort(port); + + navigateIfAllowed(exec, frame, url, false); +} + +void JSLocation::setPathname(ExecState* exec, JSValue* value) +{ + Frame* frame = impl()->frame(); + ASSERT(frame); + + KURL url = frame->loader()->url(); + url.setPath(value->toString(exec)); + + navigateIfAllowed(exec, frame, url, false); +} + +void JSLocation::setSearch(ExecState* exec, JSValue* value) +{ + Frame* frame = impl()->frame(); + ASSERT(frame); + + KURL url = frame->loader()->url(); + url.setQuery(value->toString(exec)); + + navigateIfAllowed(exec, frame, url, false); +} + +void JSLocation::setHash(ExecState* exec, JSValue* value) +{ + Frame* frame = impl()->frame(); + ASSERT(frame); + + KURL url = frame->loader()->url(); + String oldRef = url.ref(); + String str = value->toString(exec); + if (str.startsWith("#")) + str = str.substring(1); + if (oldRef == str || (oldRef.isNull() && str.isEmpty())) + return; + url.setRef(str); + + navigateIfAllowed(exec, frame, url, false); +} + +JSValue* JSLocation::replace(ExecState* exec, const ArgList& args) +{ + Frame* frame = impl()->frame(); + if (!frame) + return jsUndefined(); + + Frame* activeFrame = asJSDOMWindow(exec->dynamicGlobalObject())->impl()->frame(); + if (!activeFrame) + return jsUndefined(); + if (!activeFrame->loader()->shouldAllowNavigation(frame)) + return jsUndefined(); + + navigateIfAllowed(exec, frame, activeFrame->loader()->completeURL(args.at(exec, 0)->toString(exec)), true); + return jsUndefined(); +} + +JSValue* JSLocation::reload(ExecState* exec, const ArgList& args) +{ + Frame* frame = impl()->frame(); + if (!frame) + return jsUndefined(); + + JSDOMWindow* window = toJSDOMWindow(frame); + if (!window->allowsAccessFrom(exec)) + return jsUndefined(); + + if (!frame->loader()->url().protocolIs("javascript") || (window && window->allowsAccessFrom(exec))) { + bool userGesture = asJSDOMWindow(exec->dynamicGlobalObject())->impl()->frame()->script()->processingUserGesture(); + frame->loader()->scheduleRefresh(userGesture); + } + return jsUndefined(); +} + +JSValue* JSLocation::assign(ExecState* exec, const ArgList& args) +{ + Frame* frame = impl()->frame(); + if (!frame) + return jsUndefined(); + + Frame* activeFrame = asJSDOMWindow(exec->dynamicGlobalObject())->impl()->frame(); + if (!activeFrame) + return jsUndefined(); + if (!activeFrame->loader()->shouldAllowNavigation(frame)) + return jsUndefined(); + + // We want a new history item if this JS was called via a user gesture + navigateIfAllowed(exec, frame, activeFrame->loader()->completeURL(args.at(exec, 0)->toString(exec)), false); + return jsUndefined(); +} + +JSValue* JSLocation::toString(ExecState* exec, const ArgList&) +{ + Frame* frame = impl()->frame(); + if (!frame) + return jsUndefined(); + if (!allowsAccessFromFrame(exec, frame)) + return jsUndefined(); + + return jsString(exec, impl()->toString()); +} + +} // namespace WebCore diff --git a/WebCore/bindings/js/JSLocationCustom.h b/WebCore/bindings/js/JSLocationCustom.h new file mode 100644 index 0000000..127871e --- /dev/null +++ b/WebCore/bindings/js/JSLocationCustom.h @@ -0,0 +1,33 @@ +/* + * Copyright (C) 2008 Apple Inc. All Rights Reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef JSLocationCustom_h +#define JSLocationCustom_h + +#include "JSLocation.h" + +#endif // JSLocationCustom_h + + diff --git a/WebCore/bindings/js/JSMessageChannelConstructor.cpp b/WebCore/bindings/js/JSMessageChannelConstructor.cpp new file mode 100644 index 0000000..0151128 --- /dev/null +++ b/WebCore/bindings/js/JSMessageChannelConstructor.cpp @@ -0,0 +1,76 @@ +/* + * Copyright (C) 2008 Apple Inc. All Rights Reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "JSMessageChannelConstructor.h" + +#include "Document.h" +#include "JSDocument.h" +#include "JSMessageChannel.h" +#include "MessageChannel.h" + +using namespace JSC; + +namespace WebCore { + +const ClassInfo JSMessageChannelConstructor::s_info = { "MessageChannelConstructor", 0, 0, 0 }; + +JSMessageChannelConstructor::JSMessageChannelConstructor(ExecState* exec, ScriptExecutionContext* scriptExecutionContext) + : DOMObject(JSMessageChannelConstructor::createStructureID(exec->lexicalGlobalObject()->objectPrototype())) + , m_scriptExecutionContext(scriptExecutionContext) +{ + if (m_scriptExecutionContext->isDocument()) + m_contextWrapper = toJS(exec, static_cast<Document*>(scriptExecutionContext)); + else if (m_scriptExecutionContext->isWorkerContext()) + ; // Not yet implemented. + else + ASSERT_NOT_REACHED(); + + putDirect(exec->propertyNames().prototype, JSMessageChannelPrototype::self(exec), None); +} + +JSMessageChannelConstructor::~JSMessageChannelConstructor() +{ +} + +ConstructType JSMessageChannelConstructor::getConstructData(ConstructData& constructData) +{ + constructData.native.function = construct; + return ConstructTypeHost; +} + +JSObject* JSMessageChannelConstructor::construct(ExecState* exec, JSObject* constructor, const ArgList&) +{ + return asObject(toJS(exec, MessageChannel::create(static_cast<JSMessageChannelConstructor*>(constructor)->scriptExecutionContext()))); +} + +void JSMessageChannelConstructor::mark() +{ + DOMObject::mark(); + if (!m_contextWrapper->marked()) + m_contextWrapper->mark(); +} + +} // namespace WebCore diff --git a/WebCore/bindings/js/JSMessageChannelConstructor.h b/WebCore/bindings/js/JSMessageChannelConstructor.h new file mode 100644 index 0000000..0d26b4e --- /dev/null +++ b/WebCore/bindings/js/JSMessageChannelConstructor.h @@ -0,0 +1,55 @@ +/* + * Copyright (C) 2008 Apple Inc. All Rights Reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef JSMessageChannelConstructor_h +#define JSMessageChannelConstructor_h + +#include "JSDOMBinding.h" + +namespace WebCore { + + class JSMessageChannelConstructor : public DOMObject { + public: + JSMessageChannelConstructor(JSC::ExecState*, ScriptExecutionContext*); + virtual ~JSMessageChannelConstructor(); + virtual const JSC::ClassInfo* classInfo() const { return &s_info; } + static const JSC::ClassInfo s_info; + + ScriptExecutionContext* scriptExecutionContext() const { return m_scriptExecutionContext; } + + virtual bool implementsHasInstance() const { return true; } + static JSC::JSObject* construct(JSC::ExecState*, JSC::JSObject*, const JSC::ArgList&); + virtual JSC::ConstructType getConstructData(JSC::ConstructData&); + + virtual void mark(); + + private: + ScriptExecutionContext* m_scriptExecutionContext; + JSC::JSValue* m_contextWrapper; + }; + +} // namespace WebCore + +#endif // JSMessageChannelConstructor_h diff --git a/WebCore/bindings/js/JSMessageChannelCustom.cpp b/WebCore/bindings/js/JSMessageChannelCustom.cpp new file mode 100644 index 0000000..70329e2 --- /dev/null +++ b/WebCore/bindings/js/JSMessageChannelCustom.cpp @@ -0,0 +1,52 @@ +/* + * Copyright (C) 2008 Apple Inc. All Rights Reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "JSMessageChannel.h" + +#include "MessageChannel.h" + +using namespace JSC; + +namespace WebCore { + +void JSMessageChannel::mark() +{ + DOMObject::mark(); + + if (MessagePort* port = m_impl->port1()) { + DOMObject* wrapper = getCachedDOMObjectWrapper(*Heap::heap(this)->globalData(), port); + if (wrapper && !wrapper->marked()) + wrapper->mark(); + } + + if (MessagePort* port = m_impl->port2()) { + DOMObject* wrapper = getCachedDOMObjectWrapper(*Heap::heap(this)->globalData(), port); + if (wrapper && !wrapper->marked()) + wrapper->mark(); + } +} + +} // namespace WebCore diff --git a/WebCore/bindings/js/JSMessagePortCustom.cpp b/WebCore/bindings/js/JSMessagePortCustom.cpp new file mode 100644 index 0000000..5768b0f --- /dev/null +++ b/WebCore/bindings/js/JSMessagePortCustom.cpp @@ -0,0 +1,100 @@ +/* + * Copyright (C) 2008 Apple Inc. All Rights Reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "JSMessagePort.h" + +#include "AtomicString.h" +#include "Event.h" +#include "Frame.h" +#include "JSDOMGlobalObject.h" +#include "JSEvent.h" +#include "JSEventListener.h" +#include "MessagePort.h" + +using namespace JSC; + +namespace WebCore { + +void JSMessagePort::mark() +{ + DOMObject::mark(); + + if (JSUnprotectedEventListener* listener = static_cast<JSUnprotectedEventListener*>(m_impl->onmessage())) + listener->mark(); + + if (JSUnprotectedEventListener* listener = static_cast<JSUnprotectedEventListener*>(m_impl->onclose())) + listener->mark(); + + if (MessagePort* entangledPort = m_impl->entangledPort()) { + DOMObject* wrapper = getCachedDOMObjectWrapper(*Heap::heap(this)->globalData(), entangledPort); + if (wrapper && !wrapper->marked()) + wrapper->mark(); + } + + typedef MessagePort::EventListenersMap EventListenersMap; + typedef MessagePort::ListenerVector ListenerVector; + EventListenersMap& eventListeners = m_impl->eventListeners(); + for (EventListenersMap::iterator mapIter = eventListeners.begin(); mapIter != eventListeners.end(); ++mapIter) { + for (ListenerVector::iterator vecIter = mapIter->second.begin(); vecIter != mapIter->second.end(); ++vecIter) { + JSUnprotectedEventListener* listener = static_cast<JSUnprotectedEventListener*>(vecIter->get()); + listener->mark(); + } + } +} + +JSValue* JSMessagePort::startConversation(ExecState* exec, const ArgList& args) +{ + JSDOMGlobalObject* globalObject = static_cast<JSDOMGlobalObject*>(exec->lexicalGlobalObject()); + const UString& message = args.at(exec, 0)->toString(exec); + + return toJS(exec, impl()->startConversation(globalObject->scriptExecutionContext(), message).get()); +} + +JSValue* JSMessagePort::addEventListener(ExecState* exec, const ArgList& args) +{ + JSDOMGlobalObject* globalObject = toJSDOMGlobalObject(impl()->scriptExecutionContext()); + if (!globalObject) + return jsUndefined(); + RefPtr<JSUnprotectedEventListener> listener = globalObject->findOrCreateJSUnprotectedEventListener(exec, args.at(exec, 1)); + if (!listener) + return jsUndefined(); + impl()->addEventListener(args.at(exec, 0)->toString(exec), listener.release(), args.at(exec, 2)->toBoolean(exec)); + return jsUndefined(); +} + +JSValue* JSMessagePort::removeEventListener(ExecState* exec, const ArgList& args) +{ + JSDOMGlobalObject* globalObject = toJSDOMGlobalObject(impl()->scriptExecutionContext()); + if (!globalObject) + return jsUndefined(); + JSUnprotectedEventListener* listener = globalObject->findJSUnprotectedEventListener(exec, args.at(exec, 1)); + if (!listener) + return jsUndefined(); + impl()->removeEventListener(args.at(exec, 0)->toString(exec), listener, args.at(exec, 2)->toBoolean(exec)); + return jsUndefined(); +} + +} // namespace WebCore diff --git a/WebCore/bindings/js/kjs_dom.h b/WebCore/bindings/js/JSMimeTypeArrayCustom.cpp index 413e627..7cbba53 100644 --- a/WebCore/bindings/js/kjs_dom.h +++ b/WebCore/bindings/js/JSMimeTypeArrayCustom.cpp @@ -1,6 +1,5 @@ /* - * Copyright (C) 2000 Harri Porten (porten@kde.org) - * Copyright (C) 2003, 2004, 2005, 2006, 2007 Apple Inc. All rights reserved. + * Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -17,25 +16,25 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ -#ifndef kjs_dom_h -#define kjs_dom_h +#include "config.h" +#include "JSMimeTypeArray.h" -#include "JSNode.h" -#include "Node.h" -#include "kjs_binding.h" +#include "AtomicString.h" +#include "MimeTypeArray.h" namespace WebCore { - class Attr; - class EventTarget; +using namespace JSC; - Attr* toAttr(KJS::JSValue*, bool& ok); +bool JSMimeTypeArray::canGetItemsForName(ExecState*, MimeTypeArray* mimeTypeArray, const Identifier& propertyName) +{ + return mimeTypeArray->canGetItemsForName(propertyName); +} - bool checkNodeSecurity(KJS::ExecState*, Node*); - KJS::JSValue* getRuntimeObject(KJS::ExecState*, Node*); - KJS::JSValue* toJS(KJS::ExecState*, EventTarget*); - KJS::JSObject* getNodeConstructor(KJS::ExecState*); +JSValue* JSMimeTypeArray::nameGetter(ExecState* exec, const Identifier& propertyName, const PropertySlot& slot) +{ + JSMimeTypeArray* thisObj = static_cast<JSMimeTypeArray*>(asObject(slot.slotBase())); + return toJS(exec, thisObj->impl()->nameGetter(propertyName)); +} -} // namespace WebCore - -#endif // kjs_dom_h +} diff --git a/WebCore/bindings/js/JSNamedNodeMapCustom.cpp b/WebCore/bindings/js/JSNamedNodeMapCustom.cpp index ae63a12..1930b6b 100644 --- a/WebCore/bindings/js/JSNamedNodeMapCustom.cpp +++ b/WebCore/bindings/js/JSNamedNodeMapCustom.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2007 Apple Inc. All rights reserved. + * Copyright (C) 2007, 2008 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -26,22 +26,25 @@ #include "config.h" #include "JSNamedNodeMap.h" +#include "JSNode.h" #include "NamedNodeMap.h" +#include "Node.h" #include "PlatformString.h" -#include "kjs_binding.h" -#include "kjs_dom.h" +#include "JSDOMBinding.h" + +using namespace JSC; namespace WebCore { -bool JSNamedNodeMap::canGetItemsForName(KJS::ExecState*, NamedNodeMap* impl, const KJS::Identifier& propertyName) +bool JSNamedNodeMap::canGetItemsForName(ExecState*, NamedNodeMap* impl, const Identifier& propertyName) { return impl->getNamedItem(propertyName); } -KJS::JSValue* JSNamedNodeMap::nameGetter(KJS::ExecState* exec, KJS::JSObject* originalObject, const KJS::Identifier& propertyName, const KJS::PropertySlot& slot) +JSValue* JSNamedNodeMap::nameGetter(ExecState* exec, const Identifier& propertyName, const PropertySlot& slot) { - JSNamedNodeMap* thisObj = static_cast<JSNamedNodeMap*>(slot.slotBase()); - return KJS::toJS(exec, thisObj->impl()->getNamedItem(propertyName)); + JSNamedNodeMap* thisObj = static_cast<JSNamedNodeMap*>(asObject(slot.slotBase())); + return toJS(exec, thisObj->impl()->getNamedItem(propertyName)); } } // namespace WebCore diff --git a/WebCore/bindings/js/JSNamedNodesCollection.cpp b/WebCore/bindings/js/JSNamedNodesCollection.cpp index 977ce82..ccf90f7 100644 --- a/WebCore/bindings/js/JSNamedNodesCollection.cpp +++ b/WebCore/bindings/js/JSNamedNodesCollection.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2007 Apple Inc. All rights reserved. + * Copyright (C) 2007, 2008 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -27,35 +27,37 @@ #include "JSNamedNodesCollection.h" #include "AtomicString.h" +#include "Element.h" +#include "JSNode.h" #include "NamedAttrMap.h" -#include "Node.h" -#include "kjs_dom.h" namespace WebCore { -using namespace KJS; +using namespace JSC; -const ClassInfo JSNamedNodesCollection::info = { "Collection", 0, 0 }; +ASSERT_CLASS_FITS_IN_CELL(JSNamedNodesCollection) + +const ClassInfo JSNamedNodesCollection::s_info = { "Collection", 0, 0, 0 }; // Such a collection is usually very short-lived, it only exists // for constructs like document.forms.<name>[1], // so it shouldn't be a problem that it's storing all the nodes (with the same name). (David) -JSNamedNodesCollection::JSNamedNodesCollection(KJS::JSObject* prototype, const Vector<RefPtr<Node> >& nodes) - : KJS::DOMObject(prototype) - , m_nodes(nodes) +JSNamedNodesCollection::JSNamedNodesCollection(ExecState* exec, const Vector<RefPtr<Node> >& nodes) + : DOMObject(getDOMStructure<JSNamedNodesCollection>(exec)) + , m_nodes(new Vector<RefPtr<Node> >(nodes)) { } -JSValue* JSNamedNodesCollection::lengthGetter(ExecState* exec, JSObject* originalObject, const Identifier& propertyName, const PropertySlot& slot) +JSValue* JSNamedNodesCollection::lengthGetter(ExecState* exec, const Identifier& propertyName, const PropertySlot& slot) { - JSNamedNodesCollection* thisObj = static_cast<JSNamedNodesCollection*>(slot.slotBase()); - return jsNumber(thisObj->m_nodes.size()); + JSNamedNodesCollection* thisObj = static_cast<JSNamedNodesCollection*>(asObject(slot.slotBase())); + return jsNumber(exec, thisObj->m_nodes->size()); } -JSValue* JSNamedNodesCollection::indexGetter(ExecState* exec, JSObject* originalObject, const Identifier& propertyName, const PropertySlot& slot) +JSValue* JSNamedNodesCollection::indexGetter(ExecState* exec, const Identifier& propertyName, const PropertySlot& slot) { - JSNamedNodesCollection *thisObj = static_cast<JSNamedNodesCollection*>(slot.slotBase()); - return toJS(exec, thisObj->m_nodes[slot.index()].get()); + JSNamedNodesCollection *thisObj = static_cast<JSNamedNodesCollection*>(asObject(slot.slotBase())); + return toJS(exec, (*thisObj->m_nodes)[slot.index()].get()); } bool JSNamedNodesCollection::getOwnPropertySlot(ExecState* exec, const Identifier& propertyName, PropertySlot& slot) @@ -67,7 +69,7 @@ bool JSNamedNodesCollection::getOwnPropertySlot(ExecState* exec, const Identifie bool ok; unsigned index = propertyName.toUInt32(&ok); - if (ok && index < m_nodes.size()) { + if (ok && index < m_nodes->size()) { slot.setCustomIndex(this, index, indexGetter); return true; } @@ -76,8 +78,8 @@ bool JSNamedNodesCollection::getOwnPropertySlot(ExecState* exec, const Identifie // document.formName.name result by id as well as be index. AtomicString atomicPropertyName = propertyName; - for (unsigned i = 0; i < m_nodes.size(); i++) { - Node* node = m_nodes[i].get(); + for (unsigned i = 0; i < m_nodes->size(); i++) { + Node* node = (*m_nodes)[i].get(); if (node->hasAttributes() && node->attributes()->id() == atomicPropertyName) { slot.setCustomIndex(this, i, indexGetter); return true; diff --git a/WebCore/bindings/js/JSNamedNodesCollection.h b/WebCore/bindings/js/JSNamedNodesCollection.h index 336e0cb..e929400 100644 --- a/WebCore/bindings/js/JSNamedNodesCollection.h +++ b/WebCore/bindings/js/JSNamedNodesCollection.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2007 Apple Inc. All rights reserved. + * Copyright (C) 2007, 2008 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -26,7 +26,7 @@ #ifndef JSNamedNodesCollection_h #define JSNamedNodesCollection_h -#include "kjs_binding.h" +#include "JSDOMBinding.h" #include <wtf/Vector.h> namespace WebCore { @@ -35,20 +35,30 @@ namespace WebCore { // Internal class, used for the collection return by e.g. document.forms.myinput // when multiple nodes have the same name. - class JSNamedNodesCollection : public KJS::DOMObject { + class JSNamedNodesCollection : public DOMObject { public: - JSNamedNodesCollection(KJS::JSObject* prototype, const Vector<RefPtr<Node> >&); + JSNamedNodesCollection(JSC::ExecState*, const Vector<RefPtr<Node> >&); - virtual bool getOwnPropertySlot(KJS::ExecState*, const KJS::Identifier&, KJS::PropertySlot&); + virtual bool getOwnPropertySlot(JSC::ExecState*, const JSC::Identifier&, JSC::PropertySlot&); - virtual const KJS::ClassInfo* classInfo() const { return &info; } - static const KJS::ClassInfo info; + virtual const JSC::ClassInfo* classInfo() const { return &s_info; } + static const JSC::ClassInfo s_info; + + static JSC::ObjectPrototype* createPrototype(JSC::ExecState* exec) + { + return exec->lexicalGlobalObject()->objectPrototype(); + } + + static PassRefPtr<JSC::StructureID> createStructureID(JSC::JSValue* prototype) + { + return JSC::StructureID::create(prototype, JSC::TypeInfo(JSC::ObjectType)); + } private: - static KJS::JSValue* lengthGetter(KJS::ExecState*, KJS::JSObject*, const KJS::Identifier&, const KJS::PropertySlot&); - static KJS::JSValue* indexGetter(KJS::ExecState*, KJS::JSObject*, const KJS::Identifier&, const KJS::PropertySlot&); + static JSC::JSValue* lengthGetter(JSC::ExecState*, const JSC::Identifier&, const JSC::PropertySlot&); + static JSC::JSValue* indexGetter(JSC::ExecState*, const JSC::Identifier&, const JSC::PropertySlot&); - Vector<RefPtr<Node> > m_nodes; + OwnPtr<Vector<RefPtr<Node> > > m_nodes; }; } // namespace WebCore diff --git a/WebCore/bindings/js/JSNavigatorCustom.cpp b/WebCore/bindings/js/JSNavigatorCustom.cpp new file mode 100644 index 0000000..a85eb93 --- /dev/null +++ b/WebCore/bindings/js/JSNavigatorCustom.cpp @@ -0,0 +1,125 @@ +/* + * Copyright (C) 2000 Harri Porten (porten@kde.org) + * Copyright (c) 2000 Daniel Molkentin (molkentin@kde.org) + * Copyright (c) 2000 Stefan Schimanski (schimmi@kde.org) + * Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008 Apple Inc. All Rights Reserved. + * Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies) + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include "config.h" +#include "JSNavigator.h" + +#include "Frame.h" +#include "FrameLoader.h" +#include "KURL.h" +#include "Navigator.h" +#include "Settings.h" + +namespace WebCore { + +using namespace JSC; + +static bool needsYouTubeQuirk(ExecState*, Frame*); + +#if 1 + +static inline bool needsYouTubeQuirk(ExecState*, Frame*) +{ + return false; +} + +#else + +static bool needsYouTubeQuirk(ExecState* exec, Frame* frame) +{ + // This quirk works around a mistaken check in an ad at youtube.com. + // There's a function called isSafari that returns false if the function + // called isWindows returns true; thus the site malfunctions with Windows Safari. + + // Do the quirk only if the function's name is "isWindows". + JSFunction* function = exec->function(); + if (!function) + return false; + static const Identifier& isWindowsFunctionName = *new Identifier(exec, "isWindows"); + if (function->functionName() != isWindowsFunctionName) + return false; + + // Do the quirk only if the function is called by an "isSafari" function. + // However, that function is not itself named -- it is stored in the isSafari + // property, though, so that's how we recognize it. + ExecState* callingExec = exec->callingExecState(); + if (!callingExec) + return false; + JSFunction* callingFunction = callingExec->function(); + if (!callingFunction) + return false; + JSObject* thisObject = callingExec->thisValue(); + if (!thisObject) + return false; + static const Identifier& isSafariFunctionName = *new Identifier(exec, "isSafari"); + JSValue* isSafariFunction = thisObject->getDirect(isSafariFunctionName); + if (isSafariFunction != callingFunction) + return false; + + Document* document = frame->document(); + // FIXME: The document is never null, so we should remove this check along with the + // other similar ones in this file when we are absolutely sure it's safe. + if (!document) + return false; + + // Do the quirk only on the front page of the global version of YouTube. + const KURL& url = document->url(); + if (url.host() != "youtube.com" && url.host() != "www.youtube.com") + return false; + if (url.path() != "/") + return false; + + // As with other site-specific quirks, allow website developers to turn this off. + // In theory, this allows website developers to check if their fixes are effective. + Settings* settings = frame->settings(); + if (!settings) + return false; + if (!settings->needsSiteSpecificQuirks()) + return false; + + return true; +} + +#endif + +JSValue* JSNavigator::appVersion(ExecState* exec) const +{ + Navigator* imp = static_cast<Navigator*>(impl()); + Frame* frame = imp->frame(); + if (!frame) + return jsString(exec, ""); + + if (needsYouTubeQuirk(exec, frame)) + return jsString(exec, ""); + return jsString(exec, imp->appVersion()); +} + +void JSNavigator::mark() +{ + Base::mark(); + + JSGlobalData& globalData = *Heap::heap(this)->globalData(); + + markDOMObjectWrapper(globalData, impl()->optionalGeolocation()); +} + +} diff --git a/WebCore/bindings/js/JSNodeCustom.cpp b/WebCore/bindings/js/JSNodeCustom.cpp index 20fdad2..c40777b 100644 --- a/WebCore/bindings/js/JSNodeCustom.cpp +++ b/WebCore/bindings/js/JSNodeCustom.cpp @@ -60,49 +60,49 @@ #include "SVGElement.h" #endif -using namespace KJS; +using namespace JSC; namespace WebCore { typedef int ExpectionCode; -JSValue* JSNode::insertBefore(ExecState* exec, const List& args) +JSValue* JSNode::insertBefore(ExecState* exec, const ArgList& args) { ExceptionCode ec = 0; - bool ok = impl()->insertBefore(toNode(args[0]), toNode(args[1]), ec); + bool ok = impl()->insertBefore(toNode(args.at(exec, 0)), toNode(args.at(exec, 1)), ec, true); setDOMException(exec, ec); if (ok) - return args[0]; + return args.at(exec, 0); return jsNull(); } -JSValue* JSNode::replaceChild(ExecState* exec, const List& args) +JSValue* JSNode::replaceChild(ExecState* exec, const ArgList& args) { ExceptionCode ec = 0; - bool ok = impl()->replaceChild(toNode(args[0]), toNode(args[1]), ec); + bool ok = impl()->replaceChild(toNode(args.at(exec, 0)), toNode(args.at(exec, 1)), ec, true); setDOMException(exec, ec); if (ok) - return args[1]; + return args.at(exec, 1); return jsNull(); } -JSValue* JSNode::removeChild(ExecState* exec, const List& args) +JSValue* JSNode::removeChild(ExecState* exec, const ArgList& args) { ExceptionCode ec = 0; - bool ok = impl()->removeChild(toNode(args[0]), ec); + bool ok = impl()->removeChild(toNode(args.at(exec, 0)), ec); setDOMException(exec, ec); if (ok) - return args[0]; + return args.at(exec, 0); return jsNull(); } -JSValue* JSNode::appendChild(ExecState* exec, const List& args) +JSValue* JSNode::appendChild(ExecState* exec, const ArgList& args) { ExceptionCode ec = 0; - bool ok = impl()->appendChild(toNode(args[0]), ec); + bool ok = impl()->appendChild(toNode(args.at(exec, 0)), ec, true); setDOMException(exec, ec); if (ok) - return args[0]; + return args.at(exec, 0); return jsNull(); } @@ -115,6 +115,12 @@ void JSNode::mark() // Nodes in the document are kept alive by ScriptInterpreter::mark, // so we have no special responsibilities and can just call the base class here. if (node->inDocument()) { + // But if the document isn't marked we have to mark it to ensure that + // nodes reachable from this one are also marked + if (Document* doc = node->ownerDocument()) + if (DOMObject* docWrapper = getCachedDOMObjectWrapper(*Heap::heap(this)->globalData(), doc)) + if (!docWrapper->marked()) + docWrapper->mark(); DOMObject::mark(); return; } @@ -127,15 +133,15 @@ void JSNode::mark() // If we're already marking this tree, then we can simply mark this wrapper // by calling the base class; our caller is iterating the tree. - if (root->m_inSubtreeMark) { + if (root->inSubtreeMark()) { DOMObject::mark(); return; } // Mark the whole tree; use the global set of roots to avoid reentering. - root->m_inSubtreeMark = true; + root->setInSubtreeMark(true); for (Node* nodeToMark = root; nodeToMark; nodeToMark = nodeToMark->traverseNextNode()) { - JSNode* wrapper = ScriptInterpreter::getDOMNodeForDocument(m_impl->document(), nodeToMark); + JSNode* wrapper = getCachedDOMNodeWrapper(m_impl->document(), nodeToMark); if (wrapper) { if (!wrapper->marked()) wrapper->mark(); @@ -149,74 +155,87 @@ void JSNode::mark() mark(); } } - root->m_inSubtreeMark = false; + root->setInSubtreeMark(false); // Double check that we actually ended up marked. This assert caught problems in the past. ASSERT(marked()); } -JSValue* toJS(ExecState* exec, PassRefPtr<Node> n) +static ALWAYS_INLINE JSValue* createWrapper(ExecState* exec, Node* node) { - Node* node = n.get(); - if (!node) - return jsNull(); - - Document* doc = node->document(); - JSNode* ret = ScriptInterpreter::getDOMNodeForDocument(doc, node); - if (ret) - return ret; - + ASSERT(node); + ASSERT(!getCachedDOMNodeWrapper(node->document(), node)); + + JSNode* wrapper; switch (node->nodeType()) { case Node::ELEMENT_NODE: if (node->isHTMLElement()) - ret = createJSHTMLWrapper(exec, static_pointer_cast<HTMLElement>(n)); + wrapper = createJSHTMLWrapper(exec, static_cast<HTMLElement*>(node)); #if ENABLE(SVG) else if (node->isSVGElement()) - ret = createJSSVGWrapper(exec, static_pointer_cast<SVGElement>(n)); + wrapper = createJSSVGWrapper(exec, static_cast<SVGElement*>(node)); #endif else - ret = new JSElement(JSElementPrototype::self(exec), static_cast<Element*>(node)); + wrapper = CREATE_DOM_NODE_WRAPPER(exec, Element, node); break; case Node::ATTRIBUTE_NODE: - ret = new JSAttr(JSAttrPrototype::self(exec), static_cast<Attr*>(node)); + wrapper = CREATE_DOM_NODE_WRAPPER(exec, Attr, node); break; case Node::TEXT_NODE: - ret = new JSText(JSTextPrototype::self(exec), static_cast<Text*>(node)); + wrapper = CREATE_DOM_NODE_WRAPPER(exec, Text, node); break; case Node::CDATA_SECTION_NODE: - ret = new JSCDATASection(JSCDATASectionPrototype::self(exec), static_cast<CDATASection*>(node)); + wrapper = CREATE_DOM_NODE_WRAPPER(exec, CDATASection, node); break; case Node::ENTITY_NODE: - ret = new JSEntity(JSEntityPrototype::self(exec), static_cast<Entity*>(node)); + wrapper = CREATE_DOM_NODE_WRAPPER(exec, Entity, node); break; case Node::PROCESSING_INSTRUCTION_NODE: - ret = new JSProcessingInstruction(JSProcessingInstructionPrototype::self(exec), static_cast<ProcessingInstruction*>(node)); + wrapper = CREATE_DOM_NODE_WRAPPER(exec, ProcessingInstruction, node); break; case Node::COMMENT_NODE: - ret = new JSComment(JSCommentPrototype::self(exec), static_cast<Comment*>(node)); + wrapper = CREATE_DOM_NODE_WRAPPER(exec, Comment, node); break; case Node::DOCUMENT_NODE: // we don't want to cache the document itself in the per-document dictionary return toJS(exec, static_cast<Document*>(node)); case Node::DOCUMENT_TYPE_NODE: - ret = new JSDocumentType(JSDocumentTypePrototype::self(exec), static_cast<DocumentType*>(node)); + wrapper = CREATE_DOM_NODE_WRAPPER(exec, DocumentType, node); break; case Node::NOTATION_NODE: - ret = new JSNotation(JSNotationPrototype::self(exec), static_cast<Notation*>(node)); + wrapper = CREATE_DOM_NODE_WRAPPER(exec, Notation, node); break; case Node::DOCUMENT_FRAGMENT_NODE: - ret = new JSDocumentFragment(JSDocumentFragmentPrototype::self(exec), static_cast<DocumentFragment*>(node)); + wrapper = CREATE_DOM_NODE_WRAPPER(exec, DocumentFragment, node); break; case Node::ENTITY_REFERENCE_NODE: - ret = new JSEntityReference(JSEntityReferencePrototype::self(exec), static_cast<EntityReference*>(node)); + wrapper = CREATE_DOM_NODE_WRAPPER(exec, EntityReference, node); break; default: - ret = new JSNode(JSNodePrototype::self(exec), node); + wrapper = CREATE_DOM_NODE_WRAPPER(exec, Node, node); } - ScriptInterpreter::putDOMNodeForDocument(doc, node, ret); + return wrapper; +} + +JSValue* toJSNewlyCreated(ExecState* exec, Node* node) +{ + if (!node) + return jsNull(); + + return createWrapper(exec, node); +} + +JSValue* toJS(ExecState* exec, Node* node) +{ + if (!node) + return jsNull(); + + JSNode* wrapper = getCachedDOMNodeWrapper(node->document(), node); + if (wrapper) + return wrapper; - return ret; + return createWrapper(exec, node); } } // namespace WebCore diff --git a/WebCore/bindings/js/JSNodeFilterCondition.cpp b/WebCore/bindings/js/JSNodeFilterCondition.cpp index a21509a..bc5f01d 100644 --- a/WebCore/bindings/js/JSNodeFilterCondition.cpp +++ b/WebCore/bindings/js/JSNodeFilterCondition.cpp @@ -1,6 +1,6 @@ /* * Copyright (C) 2001 Peter Kelly (pmk@post.com) - * Copyright (C) 2007 Apple Inc. All rights reserved. + * Copyright (C) 2007, 2008 Apple Inc. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -20,41 +20,60 @@ #include "config.h" #include "JSNodeFilterCondition.h" -#include "Document.h" -#include "Frame.h" #include "JSNode.h" #include "JSNodeFilter.h" #include "NodeFilter.h" -#include "kjs_proxy.h" +#include <runtime/JSLock.h> namespace WebCore { -JSNodeFilterCondition::JSNodeFilterCondition(KJS::JSObject* filter) +using namespace JSC; + +ASSERT_CLASS_FITS_IN_CELL(JSNodeFilterCondition) + +JSNodeFilterCondition::JSNodeFilterCondition(JSValue* filter) : m_filter(filter) { } void JSNodeFilterCondition::mark() { - m_filter->mark(); + if (!m_filter->marked()) + m_filter->mark(); } -short JSNodeFilterCondition::acceptNode(Node* filterNode) const +short JSNodeFilterCondition::acceptNode(JSC::ExecState* exec, Node* filterNode) const { - Node* node = filterNode; - Frame* frame = node->document()->frame(); - KJSProxy* proxy = frame->scriptProxy(); - if (proxy && m_filter->implementsCall()) { - KJS::JSLock lock; - KJS::ExecState* exec = proxy->globalObject()->globalExec(); - KJS::List args; - args.append(toJS(exec, node)); - KJS::JSObject* obj = m_filter; - KJS::JSValue* result = obj->call(exec, obj, args); - return result->toInt32(exec); - } - - return NodeFilter::FILTER_REJECT; + JSLock lock(false); + + CallData callData; + CallType callType = m_filter->getCallData(callData); + if (callType == CallTypeNone) + return NodeFilter::FILTER_ACCEPT; + + // The exec argument here should only be null if this was called from a + // non-JavaScript language, and this is a JavaScript filter, and the document + // in question is not associated with the frame. In that case, we're going to + // behave incorrectly, and just reject nodes instead of calling the filter function. + // To fix that we'd need to come up with a way to find a suitable JavaScript + // execution context for the filter function to run in. + if (!exec) + return NodeFilter::FILTER_REJECT; + + ArgList args; + args.append(toJS(exec, filterNode)); + if (exec->hadException()) + return NodeFilter::FILTER_REJECT; + + JSValue* result = call(exec, m_filter, callType, callData, m_filter, args); + if (exec->hadException()) + return NodeFilter::FILTER_REJECT; + + int intResult = result->toInt32(exec); + if (exec->hadException()) + return NodeFilter::FILTER_REJECT; + + return intResult; } } // namespace WebCore diff --git a/WebCore/bindings/js/JSNodeFilterCondition.h b/WebCore/bindings/js/JSNodeFilterCondition.h index bd172b9..e39d094 100644 --- a/WebCore/bindings/js/JSNodeFilterCondition.h +++ b/WebCore/bindings/js/JSNodeFilterCondition.h @@ -1,6 +1,6 @@ /* * Copyright (C) 2001 Peter Kelly (pmk@post.com) - * Copyright (C) 2007 Apple Inc. All rights reserved. + * Copyright (C) 2007, 2008 Apple Inc. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -21,7 +21,8 @@ #define JSNodeFilterCondition_h #include "NodeFilterCondition.h" -#include "kjs_dom.h" +#include <runtime/JSValue.h> +#include <wtf/PassRefPtr.h> namespace WebCore { @@ -29,12 +30,18 @@ namespace WebCore { class JSNodeFilterCondition : public NodeFilterCondition { public: - JSNodeFilterCondition(KJS::JSObject* filter); - virtual short acceptNode(Node*) const; + static PassRefPtr<JSNodeFilterCondition> create(JSC::JSValue* filter) + { + return adoptRef(new JSNodeFilterCondition(filter)); + } + + private: + JSNodeFilterCondition(JSC::JSValue* filter); + + virtual short acceptNode(JSC::ExecState*, Node*) const; virtual void mark(); - protected: - KJS::JSObject* m_filter; + JSC::JSValue* m_filter; }; } // namespace WebCore diff --git a/WebCore/bindings/js/JSNodeFilterCustom.cpp b/WebCore/bindings/js/JSNodeFilterCustom.cpp index 258059c..351062b 100644 --- a/WebCore/bindings/js/JSNodeFilterCustom.cpp +++ b/WebCore/bindings/js/JSNodeFilterCustom.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2007 Apple Inc. All rights reserved. + * Copyright (C) 2007, 2008 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -26,9 +26,12 @@ #include "config.h" #include "JSNodeFilter.h" +#include "JSNode.h" #include "JSNodeFilterCondition.h" #include "NodeFilter.h" -#include "kjs_binding.h" +#include "JSDOMBinding.h" + +using namespace JSC; namespace WebCore { @@ -38,19 +41,17 @@ void JSNodeFilter::mark() DOMObject::mark(); } -NodeFilter* toNodeFilter(KJS::JSValue* val) +JSValue* JSNodeFilter::acceptNode(ExecState* exec, const ArgList& args) { - if (!val || !val->isObject()) - return 0; - - if (val->isObject(&JSNodeFilter::info)) - return static_cast<JSNodeFilter*>(val)->impl(); + return jsNumber(exec, impl()->acceptNode(exec, toNode(args.at(exec, 0)))); +} - KJS::JSObject* o = static_cast<KJS::JSObject*>(val); - if (o->implementsCall()) - return new NodeFilter(new JSNodeFilterCondition(o)); +PassRefPtr<NodeFilter> toNodeFilter(JSValue* value) +{ + if (value->isObject(&JSNodeFilter::s_info)) + return static_cast<JSNodeFilter*>(asObject(value))->impl(); - return 0; + return NodeFilter::create(JSNodeFilterCondition::create(value)); } } // namespace WebCore diff --git a/WebCore/bindings/js/JSNodeIteratorCustom.cpp b/WebCore/bindings/js/JSNodeIteratorCustom.cpp index deb0ffe..445c8cb 100644 --- a/WebCore/bindings/js/JSNodeIteratorCustom.cpp +++ b/WebCore/bindings/js/JSNodeIteratorCustom.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2006 Apple Computer, Inc. + * Copyright (C) 2006, 2008 Apple Inc. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public @@ -16,12 +16,17 @@ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ + #include "config.h" #include "JSNodeIterator.h" +#include "JSNode.h" +#include "Node.h" #include "NodeFilter.h" #include "NodeIterator.h" +using namespace JSC; + namespace WebCore { void JSNodeIterator::mark() @@ -32,4 +37,34 @@ void JSNodeIterator::mark() DOMObject::mark(); } +JSValue* JSNodeIterator::nextNode(ExecState* exec, const ArgList& args) +{ + ExceptionCode ec = 0; + RefPtr<Node> node = impl()->nextNode(exec, ec); + if (ec) { + setDOMException(exec, ec); + return jsUndefined(); + } + + if (exec->hadException()) + return jsUndefined(); + + return toJS(exec, node.get()); +} + +JSValue* JSNodeIterator::previousNode(ExecState* exec, const ArgList& args) +{ + ExceptionCode ec = 0; + RefPtr<Node> node = impl()->previousNode(exec, ec); + if (ec) { + setDOMException(exec, ec); + return jsUndefined(); + } + + if (exec->hadException()) + return jsUndefined(); + + return toJS(exec, node.get()); +} + } diff --git a/WebCore/bindings/js/JSNodeListCustom.cpp b/WebCore/bindings/js/JSNodeListCustom.cpp index e484cb4..973538e 100644 --- a/WebCore/bindings/js/JSNodeListCustom.cpp +++ b/WebCore/bindings/js/JSNodeListCustom.cpp @@ -31,34 +31,34 @@ #include "Node.h" #include "NodeList.h" +using namespace JSC; + namespace WebCore { -// Need to support both get and call, so that list[0] and list(0) work. -KJS::JSValue* JSNodeList::callAsFunction(KJS::ExecState* exec, KJS::JSObject* thisObj, const KJS::List& args) +// Need to support call so that list(0) works. +static JSValue* callNodeList(ExecState* exec, JSObject* function, JSValue*, const ArgList& args) { - // Do not use thisObj here. See JSHTMLCollection. - KJS::UString s = args[0]->toString(exec); bool ok; - unsigned u = s.toUInt32(&ok); - if (ok) - return toJS(exec, impl()->item(u)); - - return KJS::jsUndefined(); + unsigned index = args.at(exec, 0)->toString(exec).toUInt32(&ok); + if (!ok) + return jsUndefined(); + return toJS(exec, static_cast<JSNodeList*>(function)->impl()->item(index)); } -bool JSNodeList::implementsCall() const +CallType JSNodeList::getCallData(CallData& callData) { - return true; + callData.native.function = callNodeList; + return CallTypeHost; } -bool JSNodeList::canGetItemsForName(KJS::ExecState*, NodeList* impl, const KJS::Identifier& propertyName) +bool JSNodeList::canGetItemsForName(ExecState*, NodeList* impl, const Identifier& propertyName) { return impl->itemWithName(propertyName); } -KJS::JSValue* JSNodeList::nameGetter(KJS::ExecState* exec, KJS::JSObject* originalObject, const KJS::Identifier& propertyName, const KJS::PropertySlot& slot) +JSValue* JSNodeList::nameGetter(ExecState* exec, const Identifier& propertyName, const PropertySlot& slot) { - JSNodeList* thisObj = static_cast<JSNodeList*>(slot.slotBase()); + JSNodeList* thisObj = static_cast<JSNodeList*>(asObject(slot.slotBase())); return toJS(exec, thisObj->impl()->itemWithName(propertyName)); } diff --git a/WebCore/bindings/js/JSOptionConstructor.cpp b/WebCore/bindings/js/JSOptionConstructor.cpp new file mode 100644 index 0000000..8fffb55 --- /dev/null +++ b/WebCore/bindings/js/JSOptionConstructor.cpp @@ -0,0 +1,87 @@ +/* + * Copyright (C) 2006, 2007, 2008 Apple Inc. All rights reserved. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + */ + +#include "config.h" +#include "JSOptionConstructor.h" + +#include "HTMLOptionElement.h" +#include "JSHTMLOptionElement.h" +#include "ScriptExecutionContext.h" +#include "Text.h" + +using namespace JSC; + +namespace WebCore { + +ASSERT_CLASS_FITS_IN_CELL(JSOptionConstructor) + +const ClassInfo JSOptionConstructor::s_info = { "OptionConstructor", 0, 0, 0 }; + +JSOptionConstructor::JSOptionConstructor(ExecState* exec, ScriptExecutionContext* context) + : DOMObject(JSOptionConstructor::createStructureID(exec->lexicalGlobalObject()->objectPrototype())) +{ + ASSERT(context->isDocument()); + m_document = static_cast<JSDocument*>(asObject(toJS(exec, static_cast<Document*>(context)))); + + putDirect(exec->propertyNames().length, jsNumber(exec, 4), ReadOnly|DontDelete|DontEnum); +} + +static JSObject* constructHTMLOptionElement(ExecState* exec, JSObject* constructor, const ArgList& args) +{ + Document* document = static_cast<JSOptionConstructor*>(constructor)->document(); + + ExceptionCode ec = 0; + + RefPtr<HTMLOptionElement> element = static_pointer_cast<HTMLOptionElement>(document->createElement("option", ec)); + RefPtr<Text> text; + if (ec == 0) + text = document->createTextNode(""); + if (ec == 0 && !args.at(exec, 0)->isUndefined()) + text->setData(args.at(exec, 0)->toString(exec), ec); + if (ec == 0) + element->appendChild(text.release(), ec); + if (ec == 0 && !args.at(exec, 1)->isUndefined()) + element->setValue(args.at(exec, 1)->toString(exec)); + if (ec == 0) + element->setDefaultSelected(args.at(exec, 2)->toBoolean(exec)); + if (ec == 0) + element->setSelected(args.at(exec, 3)->toBoolean(exec)); + + if (ec) { + setDOMException(exec, ec); + return 0; + } + + return asObject(toJS(exec, element.release())); +} + +ConstructType JSOptionConstructor::getConstructData(ConstructData& constructData) +{ + constructData.native.function = constructHTMLOptionElement; + return ConstructTypeHost; +} + +void JSOptionConstructor::mark() +{ + DOMObject::mark(); + if (!m_document->marked()) + m_document->mark(); +} + +} // namespace WebCore diff --git a/WebCore/bindings/js/JSHTMLOptionElementConstructor.h b/WebCore/bindings/js/JSOptionConstructor.h index ac347fa..5234c49 100644 --- a/WebCore/bindings/js/JSHTMLOptionElementConstructor.h +++ b/WebCore/bindings/js/JSOptionConstructor.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2006 Apple Computer, Inc. + * Copyright (C) 2006, 2008 Apple Inc. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public @@ -17,23 +17,30 @@ * Boston, MA 02110-1301, USA. */ -#ifndef JSHTMLOptionElementConstructor_h -#define JSHTMLOptionElementConstructor_h +#ifndef JSOptionConstructor_h +#define JSOptionConstructor_h -#include "kjs_binding.h" +#include "JSDOMBinding.h" +#include "JSDocument.h" #include <wtf/RefPtr.h> namespace WebCore { - class JSHTMLOptionElementConstructor : public KJS::DOMObject { + class JSOptionConstructor : public DOMObject { public: - JSHTMLOptionElementConstructor(KJS::ExecState*, Document*); - virtual bool implementsConstruct() const; - virtual KJS::JSObject *construct(KJS::ExecState*, const KJS::List& args); + JSOptionConstructor(JSC::ExecState*, ScriptExecutionContext*); + Document* document() const { return m_document->impl(); } + + static const JSC::ClassInfo s_info; + + virtual void mark(); private: - RefPtr<Document> m_doc; + virtual JSC::ConstructType getConstructData(JSC::ConstructData&); + virtual const JSC::ClassInfo* classInfo() const { return &s_info; } + + JSDocument* m_document; }; -} +} // namespace WebCore -#endif +#endif // JSOptionConstructor_h diff --git a/WebCore/bindings/js/JSSVGElementWrapperFactory.h b/WebCore/bindings/js/JSPluginArrayCustom.cpp index 3083fec..eb379a7 100644 --- a/WebCore/bindings/js/JSSVGElementWrapperFactory.h +++ b/WebCore/bindings/js/JSPluginArrayCustom.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2006, 2007 Apple Inc. All rights reserved. + * Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -16,26 +16,25 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ -#ifndef JSSVGElementWrapperFactory_h -#define JSSVGElementWrapperFactory_h +#include "config.h" +#include "JSPluginArray.h" -#if ENABLE(SVG) - -#include <wtf/Forward.h> - -namespace KJS { - class ExecState; -} +#include "AtomicString.h" +#include "PluginArray.h" namespace WebCore { - class JSNode; - class SVGElement; - - JSNode* createJSSVGWrapper(KJS::ExecState*, PassRefPtr<SVGElement>); +using namespace JSC; +bool JSPluginArray::canGetItemsForName(ExecState*, PluginArray* pluginArray, const Identifier& propertyName) +{ + return pluginArray->canGetItemsForName(propertyName); } -#endif // ENABLE(SVG) +JSValue* JSPluginArray::nameGetter(ExecState* exec, const Identifier& propertyName, const PropertySlot& slot) +{ + JSPluginArray* thisObj = static_cast<JSPluginArray*>(asObject(slot.slotBase())); + return toJS(exec, thisObj->impl()->nameGetter(propertyName)); +} -#endif // JSSVGElementWrapperFactory_h +} diff --git a/WebCore/bindings/js/JSHTMLElementWrapperFactory.h b/WebCore/bindings/js/JSPluginCustom.cpp index 8e8bffa..5cc4a92 100644 --- a/WebCore/bindings/js/JSHTMLElementWrapperFactory.h +++ b/WebCore/bindings/js/JSPluginCustom.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2006, 2007 Apple Inc. All ri + * Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -16,22 +16,25 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ -#ifndef JSHTMLElementWrapperFactory_h -#define JSHTMLElementWrapperFactory_h +#include "config.h" +#include "JSPlugin.h" -#include <wtf/Forward.h> - -namespace KJS { - class ExecState; -} +#include "AtomicString.h" +#include "Plugin.h" namespace WebCore { - class JSNode; - class HTMLElement; +using namespace JSC; - JSNode* createJSHTMLWrapper(KJS::ExecState*, PassRefPtr<HTMLElement>); +bool JSPlugin::canGetItemsForName(ExecState*, Plugin* plugin, const Identifier& propertyName) +{ + return plugin->canGetItemsForName(propertyName); +} +JSValue* JSPlugin::nameGetter(ExecState* exec, const Identifier& propertyName, const PropertySlot& slot) +{ + JSPlugin* thisObj = static_cast<JSPlugin*>(asObject(slot.slotBase())); + return toJS(exec, thisObj->impl()->nameGetter(propertyName)); } -#endif +} diff --git a/WebCore/bindings/js/JSPluginElementFunctions.cpp b/WebCore/bindings/js/JSPluginElementFunctions.cpp new file mode 100644 index 0000000..94e9806 --- /dev/null +++ b/WebCore/bindings/js/JSPluginElementFunctions.cpp @@ -0,0 +1,121 @@ +/* + * Copyright (C) 1999-2000 Harri Porten (porten@kde.org) + * Copyright (C) 2004, 2005, 2006, 2007, 2008 Apple Inc. All rights reserved. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include "config.h" +#include "JSPluginElementFunctions.h" + +#include "Frame.h" +#include "FrameLoader.h" +#include "HTMLDocument.h" +#include "HTMLNames.h" +#include "HTMLPlugInElement.h" +#include "JSHTMLElement.h" +#include "ScriptController.h" +#include "runtime.h" +#include "runtime_object.h" + +using namespace JSC; + +namespace WebCore { + +using namespace Bindings; +using namespace HTMLNames; + +// Runtime object support code for JSHTMLAppletElement, JSHTMLEmbedElement and JSHTMLObjectElement. + +static Instance* pluginInstance(Node* node) +{ + if (!node) + return 0; + if (!(node->hasTagName(objectTag) || node->hasTagName(embedTag) || node->hasTagName(appletTag))) + return 0; + HTMLPlugInElement* plugInElement = static_cast<HTMLPlugInElement*>(node); + Instance* instance = plugInElement->getInstance(); + if (!instance || !instance->rootObject()) + return 0; + return instance; +} + +static RuntimeObjectImp* getRuntimeObject(ExecState* exec, Node* node) +{ + Instance* instance = pluginInstance(node); + if (!instance) + return 0; + return JSC::Bindings::Instance::createRuntimeObject(exec, instance); +} + +JSValue* runtimeObjectGetter(ExecState* exec, const Identifier& propertyName, const PropertySlot& slot) +{ + JSHTMLElement* thisObj = static_cast<JSHTMLElement*>(asObject(slot.slotBase())); + HTMLElement* element = static_cast<HTMLElement*>(thisObj->impl()); + RuntimeObjectImp* runtimeObject = getRuntimeObject(exec, element); + return runtimeObject ? runtimeObject : jsUndefined(); +} + +JSValue* runtimeObjectPropertyGetter(ExecState* exec, const Identifier& propertyName, const PropertySlot& slot) +{ + JSHTMLElement* thisObj = static_cast<JSHTMLElement*>(asObject(slot.slotBase())); + HTMLElement* element = static_cast<HTMLElement*>(thisObj->impl()); + RuntimeObjectImp* runtimeObject = getRuntimeObject(exec, element); + if (!runtimeObject) + return jsUndefined(); + return runtimeObject->get(exec, propertyName); +} + +bool runtimeObjectCustomGetOwnPropertySlot(ExecState* exec, const Identifier& propertyName, PropertySlot& slot, JSHTMLElement* element) +{ + RuntimeObjectImp* runtimeObject = getRuntimeObject(exec, element->impl()); + if (!runtimeObject) + return false; + if (!runtimeObject->hasProperty(exec, propertyName)) + return false; + slot.setCustom(element, runtimeObjectPropertyGetter); + return true; +} + +bool runtimeObjectCustomPut(ExecState* exec, const Identifier& propertyName, JSValue* value, HTMLElement* element, PutPropertySlot& slot) +{ + RuntimeObjectImp* runtimeObject = getRuntimeObject(exec, element); + if (!runtimeObject) + return 0; + if (!runtimeObject->hasProperty(exec, propertyName)) + return false; + runtimeObject->put(exec, propertyName, value, slot); + return true; +} + +static JSValue* callPlugin(ExecState* exec, JSObject* function, JSValue*, const ArgList& args) +{ + Instance* instance = pluginInstance(static_cast<JSHTMLElement*>(function)->impl()); + instance->begin(); + JSValue* result = instance->invokeDefaultMethod(exec, args); + instance->end(); + return result; +} + +CallType runtimeObjectGetCallData(HTMLElement* element, CallData& callData) +{ + Instance* instance = pluginInstance(element); + if (!instance || !instance->supportsInvokeDefaultMethod()) + return CallTypeNone; + callData.native.function = callPlugin; + return CallTypeHost; +} + +} // namespace WebCore diff --git a/WebCore/bindings/js/JSPluginElementFunctions.h b/WebCore/bindings/js/JSPluginElementFunctions.h new file mode 100644 index 0000000..280ffb7 --- /dev/null +++ b/WebCore/bindings/js/JSPluginElementFunctions.h @@ -0,0 +1,41 @@ +/* + * Copyright (C) 1999 Harri Porten (porten@kde.org) + * Copyright (C) 2004, 2006, 2007, 2008 Apple Inc. All rights reserved. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#ifndef JSPluginElementFunctions_h +#define JSPluginElementFunctions_h + +#include "JSDOMBinding.h" + +namespace WebCore { + + class HTMLElement; + class JSHTMLElement; + class Node; + + // Runtime object support code for JSHTMLAppletElement, JSHTMLEmbedElement and JSHTMLObjectElement. + + JSC::JSValue* runtimeObjectGetter(JSC::ExecState*, const JSC::Identifier&, const JSC::PropertySlot&); + JSC::JSValue* runtimeObjectPropertyGetter(JSC::ExecState*, const JSC::Identifier&, const JSC::PropertySlot&); + bool runtimeObjectCustomGetOwnPropertySlot(JSC::ExecState*, const JSC::Identifier&, JSC::PropertySlot&, JSHTMLElement*); + bool runtimeObjectCustomPut(JSC::ExecState*, const JSC::Identifier&, JSC::JSValue*, HTMLElement*, JSC::PutPropertySlot&); + JSC::CallType runtimeObjectGetCallData(HTMLElement*, JSC::CallData&); + +} // namespace WebCore + +#endif // JSPluginElementFunctions_h diff --git a/WebCore/bindings/js/JSQuarantinedObjectWrapper.cpp b/WebCore/bindings/js/JSQuarantinedObjectWrapper.cpp new file mode 100644 index 0000000..7bb0c79 --- /dev/null +++ b/WebCore/bindings/js/JSQuarantinedObjectWrapper.cpp @@ -0,0 +1,278 @@ +/* + * Copyright (C) 2008 Apple Inc. All Rights Reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "JSQuarantinedObjectWrapper.h" + +#include <runtime/JSGlobalObject.h> + +using namespace JSC; + +namespace WebCore { + +ASSERT_CLASS_FITS_IN_CELL(JSQuarantinedObjectWrapper) + +const ClassInfo JSQuarantinedObjectWrapper::s_info = { "JSQuarantinedObjectWrapper", 0, 0, 0 }; + +JSQuarantinedObjectWrapper* JSQuarantinedObjectWrapper::asWrapper(JSValue* value) +{ + if (!value->isObject()) + return 0; + + JSObject* object = asObject(value); + + if (!object->inherits(&JSQuarantinedObjectWrapper::s_info)) + return 0; + + return static_cast<JSQuarantinedObjectWrapper*>(object); +} + +JSValue* JSQuarantinedObjectWrapper::cachedValueGetter(ExecState*, const Identifier&, const PropertySlot& slot) +{ + JSValue* v = slot.slotBase(); + ASSERT(v); + return v; +} + +JSQuarantinedObjectWrapper::JSQuarantinedObjectWrapper(ExecState* unwrappedExec, JSObject* unwrappedObject, PassRefPtr<StructureID> structureID) + : JSObject(structureID) + , m_unwrappedGlobalObject(unwrappedExec->dynamicGlobalObject()) + , m_unwrappedObject(unwrappedObject) +{ + ASSERT_ARG(unwrappedExec, unwrappedExec); + ASSERT_ARG(unwrappedObject, unwrappedObject); + ASSERT(this->structureID()); +} + +JSQuarantinedObjectWrapper::~JSQuarantinedObjectWrapper() +{ +} + +bool JSQuarantinedObjectWrapper::allowsUnwrappedAccessFrom(ExecState* exec) const +{ + return m_unwrappedGlobalObject->profileGroup() == exec->dynamicGlobalObject()->profileGroup(); +} + +ExecState* JSQuarantinedObjectWrapper::unwrappedExecState() const +{ + return m_unwrappedGlobalObject->globalExec(); +} + +void JSQuarantinedObjectWrapper::transferExceptionToExecState(ExecState* exec) const +{ + ASSERT(exec != unwrappedExecState()); + + if (!unwrappedExecState()->hadException()) + return; + + exec->setException(wrapOutgoingValue(unwrappedExecState(), unwrappedExecState()->exception())); + unwrappedExecState()->clearException(); +} + +void JSQuarantinedObjectWrapper::mark() +{ + JSObject::mark(); + + if (!m_unwrappedObject->marked()) + m_unwrappedObject->mark(); + if (!m_unwrappedGlobalObject->marked()) + m_unwrappedGlobalObject->mark(); +} + +bool JSQuarantinedObjectWrapper::getOwnPropertySlot(ExecState* exec, const Identifier& identifier, PropertySlot& slot) +{ + if (!allowsGetProperty()) { + slot.setUndefined(); + return true; + } + + PropertySlot unwrappedSlot(m_unwrappedObject); + bool result = m_unwrappedObject->getOwnPropertySlot(unwrappedExecState(), identifier, unwrappedSlot); + if (result) { + JSValue* unwrappedValue = unwrappedSlot.getValue(unwrappedExecState(), identifier); + slot.setCustom(wrapOutgoingValue(unwrappedExecState(), unwrappedValue), cachedValueGetter); + } + + transferExceptionToExecState(exec); + + return result; +} + +bool JSQuarantinedObjectWrapper::getOwnPropertySlot(ExecState* exec, unsigned identifier, PropertySlot& slot) +{ + if (!allowsGetProperty()) { + slot.setUndefined(); + return true; + } + + PropertySlot unwrappedSlot(m_unwrappedObject); + bool result = m_unwrappedObject->getOwnPropertySlot(unwrappedExecState(), identifier, unwrappedSlot); + if (result) { + JSValue* unwrappedValue = unwrappedSlot.getValue(unwrappedExecState(), identifier); + slot.setCustom(wrapOutgoingValue(unwrappedExecState(), unwrappedValue), cachedValueGetter); + } + + transferExceptionToExecState(exec); + + return result; +} + +void JSQuarantinedObjectWrapper::put(ExecState* exec, const Identifier& identifier, JSValue* value, PutPropertySlot& slot) +{ + if (!allowsSetProperty()) + return; + + m_unwrappedObject->put(unwrappedExecState(), identifier, prepareIncomingValue(exec, value), slot); + + transferExceptionToExecState(exec); +} + +void JSQuarantinedObjectWrapper::put(ExecState* exec, unsigned identifier, JSValue* value) +{ + if (!allowsSetProperty()) + return; + + m_unwrappedObject->put(unwrappedExecState(), identifier, prepareIncomingValue(exec, value)); + + transferExceptionToExecState(exec); +} + +bool JSQuarantinedObjectWrapper::deleteProperty(ExecState* exec, const Identifier& identifier) +{ + if (!allowsDeleteProperty()) + return false; + + bool result = m_unwrappedObject->deleteProperty(unwrappedExecState(), identifier); + + transferExceptionToExecState(exec); + + return result; +} + +bool JSQuarantinedObjectWrapper::deleteProperty(ExecState* exec, unsigned identifier) +{ + if (!allowsDeleteProperty()) + return false; + + bool result = m_unwrappedObject->deleteProperty(unwrappedExecState(), identifier); + + transferExceptionToExecState(exec); + + return result; +} + +JSObject* JSQuarantinedObjectWrapper::construct(ExecState* exec, JSObject* constructor, const ArgList& args) +{ + JSQuarantinedObjectWrapper* wrapper = static_cast<JSQuarantinedObjectWrapper*>(constructor); + + ArgList preparedArgs; + for (size_t i = 0; i < args.size(); ++i) + preparedArgs.append(wrapper->prepareIncomingValue(exec, args.at(exec, i))); + + // FIXME: Would be nice to find a way to reuse the result of m_unwrappedObject->getConstructData + // from when we called it in JSQuarantinedObjectWrapper::getConstructData. + ConstructData unwrappedConstructData; + ConstructType unwrappedConstructType = wrapper->m_unwrappedObject->getConstructData(unwrappedConstructData); + ASSERT(unwrappedConstructType != ConstructTypeNone); + + JSValue* unwrappedResult = JSC::construct(wrapper->unwrappedExecState(), wrapper->m_unwrappedObject, unwrappedConstructType, unwrappedConstructData, preparedArgs); + + JSValue* resultValue = wrapper->wrapOutgoingValue(wrapper->unwrappedExecState(), unwrappedResult); + ASSERT(resultValue->isObject()); + JSObject* result = asObject(resultValue); + + wrapper->transferExceptionToExecState(exec); + + return result; +} + +ConstructType JSQuarantinedObjectWrapper::getConstructData(ConstructData& constructData) +{ + if (!allowsConstruct()) + return ConstructTypeNone; + ConstructData unwrappedConstructData; + if (m_unwrappedObject->getConstructData(unwrappedConstructData) == ConstructTypeNone) + return ConstructTypeNone; + constructData.native.function = construct; + return ConstructTypeHost; +} + +bool JSQuarantinedObjectWrapper::hasInstance(ExecState* exec, JSValue* value, JSValue* proto) +{ + if (!allowsHasInstance()) + return false; + + bool result = m_unwrappedObject->hasInstance(unwrappedExecState(), prepareIncomingValue(exec, value), prepareIncomingValue(exec, proto)); + + transferExceptionToExecState(exec); + + return result; +} + +JSValue* JSQuarantinedObjectWrapper::call(ExecState* exec, JSObject* function, JSValue* thisValue, const ArgList& args) +{ + JSQuarantinedObjectWrapper* wrapper = static_cast<JSQuarantinedObjectWrapper*>(function); + + JSValue* preparedThisValue = wrapper->prepareIncomingValue(exec, thisValue); + + ArgList preparedArgs; + for (size_t i = 0; i < args.size(); ++i) + preparedArgs.append(wrapper->prepareIncomingValue(exec, args.at(exec, i))); + + // FIXME: Would be nice to find a way to reuse the result of m_unwrappedObject->getCallData + // from when we called it in JSQuarantinedObjectWrapper::getCallData. + CallData unwrappedCallData; + CallType unwrappedCallType = wrapper->m_unwrappedObject->getCallData(unwrappedCallData); + ASSERT(unwrappedCallType != CallTypeNone); + + JSValue* unwrappedResult = JSC::call(wrapper->unwrappedExecState(), wrapper->m_unwrappedObject, unwrappedCallType, unwrappedCallData, preparedThisValue, preparedArgs); + + JSValue* result = wrapper->wrapOutgoingValue(wrapper->unwrappedExecState(), unwrappedResult); + + wrapper->transferExceptionToExecState(exec); + + return result; +} + +CallType JSQuarantinedObjectWrapper::getCallData(CallData& callData) +{ + if (!allowsCallAsFunction()) + return CallTypeNone; + CallData unwrappedCallData; + if (m_unwrappedObject->getCallData(unwrappedCallData) == CallTypeNone) + return CallTypeNone; + callData.native.function = call; + return CallTypeHost; +} + +void JSQuarantinedObjectWrapper::getPropertyNames(ExecState* exec, PropertyNameArray& array) +{ + if (!allowsGetPropertyNames()) + return; + + m_unwrappedObject->getPropertyNames(unwrappedExecState(), array); +} + +} // namespace WebCore diff --git a/WebCore/bindings/js/JSQuarantinedObjectWrapper.h b/WebCore/bindings/js/JSQuarantinedObjectWrapper.h new file mode 100644 index 0000000..ff684bf --- /dev/null +++ b/WebCore/bindings/js/JSQuarantinedObjectWrapper.h @@ -0,0 +1,100 @@ +/* + * Copyright (C) 2008 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef JSQuarantinedObjectWrapper_h +#define JSQuarantinedObjectWrapper_h + +#include <runtime/JSObject.h> + +namespace WebCore { + + class JSQuarantinedObjectWrapper : public JSC::JSObject { + public: + static JSQuarantinedObjectWrapper* asWrapper(JSC::JSValue*); + + virtual ~JSQuarantinedObjectWrapper(); + + JSC::JSObject* unwrappedObject() const { return m_unwrappedObject; } + JSC::JSGlobalObject* unwrappedGlobalObject() const { return m_unwrappedGlobalObject; }; + JSC::ExecState* unwrappedExecState() const; + + bool allowsUnwrappedAccessFrom(JSC::ExecState*) const; + + static const JSC::ClassInfo s_info; + + static PassRefPtr<JSC::StructureID> createStructureID(JSC::JSValue* proto) + { + return JSC::StructureID::create(proto, JSC::TypeInfo(JSC::ObjectType, JSC::ImplementsHasInstance | JSC::OverridesHasInstance)); + } + + protected: + JSQuarantinedObjectWrapper(JSC::ExecState* unwrappedExec, JSC::JSObject* unwrappedObject, PassRefPtr<JSC::StructureID>); + + virtual void mark(); + + private: + virtual bool getOwnPropertySlot(JSC::ExecState*, const JSC::Identifier&, JSC::PropertySlot&); + virtual bool getOwnPropertySlot(JSC::ExecState*, unsigned, JSC::PropertySlot&); + + virtual void put(JSC::ExecState*, const JSC::Identifier&, JSC::JSValue*, JSC::PutPropertySlot&); + virtual void put(JSC::ExecState*, unsigned, JSC::JSValue*); + + virtual bool deleteProperty(JSC::ExecState*, const JSC::Identifier&); + virtual bool deleteProperty(JSC::ExecState*, unsigned); + + virtual JSC::CallType getCallData(JSC::CallData&); + virtual JSC::ConstructType getConstructData(JSC::ConstructData&); + + virtual bool hasInstance(JSC::ExecState*, JSC::JSValue*, JSC::JSValue* proto); + + virtual void getPropertyNames(JSC::ExecState*, JSC::PropertyNameArray&); + + virtual JSC::UString className() const { return m_unwrappedObject->className(); } + + virtual bool allowsGetProperty() const { return false; } + virtual bool allowsSetProperty() const { return false; } + virtual bool allowsDeleteProperty() const { return false; } + virtual bool allowsConstruct() const { return false; } + virtual bool allowsHasInstance() const { return false; } + virtual bool allowsCallAsFunction() const { return false; } + virtual bool allowsGetPropertyNames() const { return false; } + + virtual JSC::JSValue* prepareIncomingValue(JSC::ExecState* unwrappedExec, JSC::JSValue* unwrappedValue) const = 0; + virtual JSC::JSValue* wrapOutgoingValue(JSC::ExecState* unwrappedExec, JSC::JSValue* unwrappedValue) const = 0; + + static JSC::JSValue* cachedValueGetter(JSC::ExecState*, const JSC::Identifier&, const JSC::PropertySlot&); + + void transferExceptionToExecState(JSC::ExecState*) const; + + static JSC::JSValue* call(JSC::ExecState*, JSC::JSObject* function, JSC::JSValue* thisValue, const JSC::ArgList&); + static JSC::JSObject* construct(JSC::ExecState*, JSC::JSObject*, const JSC::ArgList&); + + JSC::JSGlobalObject* m_unwrappedGlobalObject; + JSC::JSObject* m_unwrappedObject; + }; + +} // namespace WebCore + +#endif // JSQuarantinedObjectWrapper_h diff --git a/WebCore/bindings/js/JSRGBColor.cpp b/WebCore/bindings/js/JSRGBColor.cpp new file mode 100644 index 0000000..4541bfa --- /dev/null +++ b/WebCore/bindings/js/JSRGBColor.cpp @@ -0,0 +1,85 @@ +/* + * Copyright (C) 2000 Harri Porten (porten@kde.org) + * Copyright (C) 2001 Peter Kelly (pmk@post.com) + * Copyright (C) 2004, 2005, 2006, 2007, 2008 Apple Inc. All rights reserved. + * Copyright (C) 2006 James G. Speth (speth@end.com) + * Copyright (C) 2006 Samuel Weinig (sam@webkit.org) + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include "config.h" +#include "JSRGBColor.h" + +#include "CSSPrimitiveValue.h" +#include "JSCSSPrimitiveValue.h" + +using namespace JSC; + +static JSValue* jsRGBColorRed(ExecState*, const Identifier&, const PropertySlot&); +static JSValue* jsRGBColorGreen(ExecState*, const Identifier&, const PropertySlot&); +static JSValue* jsRGBColorBlue(ExecState*, const Identifier&, const PropertySlot&); + +/* +@begin JSRGBColorTable + red jsRGBColorRed DontDelete|ReadOnly + green jsRGBColorGreen DontDelete|ReadOnly + blue jsRGBColorBlue DontDelete|ReadOnly +@end +*/ + +#include "JSRGBColor.lut.h" + +namespace WebCore { + +ASSERT_CLASS_FITS_IN_CELL(JSRGBColor) + +const ClassInfo JSRGBColor::s_info = { "RGBColor", 0, &JSRGBColorTable, 0 }; + +JSRGBColor::JSRGBColor(ExecState* exec, unsigned color) + : DOMObject(getDOMStructure<JSRGBColor>(exec)) + , m_color(color) +{ +} + +bool JSRGBColor::getOwnPropertySlot(ExecState* exec, const Identifier& propertyName, PropertySlot& slot) +{ + return getStaticValueSlot<JSRGBColor, DOMObject>(exec, &JSRGBColorTable, this, propertyName, slot); +} + +JSValue* getJSRGBColor(ExecState* exec, unsigned color) +{ + return new (exec) JSRGBColor(exec, color); +} + +} // namespace WebCore + +using namespace WebCore; + +JSValue* jsRGBColorRed(ExecState* exec, const Identifier&, const PropertySlot& slot) +{ + return toJS(exec, CSSPrimitiveValue::create((static_cast<JSRGBColor*>(asObject(slot.slotBase()))->impl() >> 16) & 0xFF, CSSPrimitiveValue::CSS_NUMBER)); +} + +JSValue* jsRGBColorGreen(ExecState* exec, const Identifier&, const PropertySlot& slot) +{ + return toJS(exec, CSSPrimitiveValue::create((static_cast<JSRGBColor*>(asObject(slot.slotBase()))->impl() >> 8) & 0xFF, CSSPrimitiveValue::CSS_NUMBER)); +} + +JSValue* jsRGBColorBlue(ExecState* exec, const Identifier&, const PropertySlot& slot) +{ + return toJS(exec, CSSPrimitiveValue::create(static_cast<JSRGBColor*>(asObject(slot.slotBase()))->impl() & 0xFF, CSSPrimitiveValue::CSS_NUMBER)); +} + diff --git a/WebCore/bindings/js/kjs_css.h b/WebCore/bindings/js/JSRGBColor.h index d7f14aa..afd5264 100644 --- a/WebCore/bindings/js/kjs_css.h +++ b/WebCore/bindings/js/JSRGBColor.h @@ -1,9 +1,7 @@ - // -*- c-basic-offset: 2 -*- /* - * This file is part of the KDE libraries * Copyright (C) 2000 Harri Porten (porten@kde.org) * Copyright (C) 2001 Peter Kelly (pmk@post.com) - * Copyright (C) 2004, 2006, 2007 Apple Inc. All rights reserved. + * Copyright (C) 2004, 2006, 2007, 2008 Apple Inc. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -20,36 +18,42 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ -#ifndef kjs_css_h -#define kjs_css_h +#ifndef JSRGBColor_h +#define JSRGBColor_h #include "Color.h" -#include "kjs_binding.h" +#include "JSDOMBinding.h" namespace WebCore { - class JSRGBColor : public KJS::DOMObject { + // FIXME: JSRGBColor should have a proper prototype and a constructor. + class JSRGBColor : public DOMObject { public: - JSRGBColor(KJS::JSObject* prototype, unsigned color); - ~JSRGBColor(); + JSRGBColor(JSC::ExecState*, unsigned color); - virtual bool getOwnPropertySlot(KJS::ExecState*, const KJS::Identifier&, KJS::PropertySlot&); - KJS::JSValue* getValueProperty(KJS::ExecState*, int token) const; - // no put - all read-only + virtual bool getOwnPropertySlot(JSC::ExecState*, const JSC::Identifier&, JSC::PropertySlot&); - virtual const KJS::ClassInfo* classInfo() const { return &info; } - static const KJS::ClassInfo info; - - enum { Red, Green, Blue }; + virtual const JSC::ClassInfo* classInfo() const { return &s_info; } + static const JSC::ClassInfo s_info; unsigned impl() const { return m_color; } + static JSC::ObjectPrototype* createPrototype(JSC::ExecState* exec) + { + return exec->lexicalGlobalObject()->objectPrototype(); + } + + static PassRefPtr<JSC::StructureID> createStructureID(JSC::JSValue* prototype) + { + return JSC::StructureID::create(prototype, JSC::TypeInfo(JSC::ObjectType)); + } + private: unsigned m_color; }; - KJS::JSValue* getJSRGBColor(KJS::ExecState*, unsigned color); + JSC::JSValue* getJSRGBColor(JSC::ExecState*, unsigned color); } // namespace WebCore -#endif // kjs_css_h +#endif // JSRGBColor_h diff --git a/WebCore/bindings/js/JSSQLResultSetRowListCustom.cpp b/WebCore/bindings/js/JSSQLResultSetRowListCustom.cpp index 62dcd5d..14e9baa 100644 --- a/WebCore/bindings/js/JSSQLResultSetRowListCustom.cpp +++ b/WebCore/bindings/js/JSSQLResultSetRowListCustom.cpp @@ -33,14 +33,14 @@ #include "SQLValue.h" #include "SQLResultSetRowList.h" -using namespace KJS; +using namespace JSC; namespace WebCore { -JSValue* JSSQLResultSetRowList::item(ExecState* exec, const List& args) +JSValue* JSSQLResultSetRowList::item(ExecState* exec, const ArgList& args) { bool indexOk; - int index = args[0]->toInt32(exec, indexOk); + int index = args.at(exec, 0)->toInt32(exec, indexOk); if (!indexOk) { setDOMException(exec, TYPE_MISMATCH_ERR); return jsUndefined(); @@ -50,29 +50,29 @@ JSValue* JSSQLResultSetRowList::item(ExecState* exec, const List& args) return jsUndefined(); } - JSObject* object = new JSObject(exec->lexicalGlobalObject()->objectPrototype()); + JSObject* object = constructEmptyObject(exec); unsigned numColumns = m_impl->columnNames().size(); unsigned valuesIndex = index * numColumns; for (unsigned i = 0; i < numColumns; i++) { const SQLValue& value = m_impl->values()[valuesIndex + i]; - JSValue* jsValue = 0; + JSValue* jsValue = noValue(); switch (value.type()) { case SQLValue::StringValue: - jsValue = jsString(value.string()); + jsValue = jsString(exec, value.string()); break; case SQLValue::NullValue: jsValue = jsNull(); break; case SQLValue::NumberValue: - jsValue = jsNumber(value.number()); + jsValue = jsNumber(exec, value.number()); break; default: ASSERT_NOT_REACHED(); } - object->putDirect(m_impl->columnNames()[i], jsValue, DontDelete | ReadOnly); + object->putDirect(Identifier(exec, m_impl->columnNames()[i]), jsValue, DontDelete | ReadOnly); } return object; diff --git a/WebCore/bindings/js/JSSQLTransactionCustom.cpp b/WebCore/bindings/js/JSSQLTransactionCustom.cpp index 1dca46d..5138517 100644 --- a/WebCore/bindings/js/JSSQLTransactionCustom.cpp +++ b/WebCore/bindings/js/JSSQLTransactionCustom.cpp @@ -33,23 +33,23 @@ #include "ExceptionCode.h" #include "JSCustomSQLStatementCallback.h" #include "JSCustomSQLStatementErrorCallback.h" +#include "JSDOMWindowCustom.h" #include "SQLTransaction.h" -#include "kjs_window.h" -using namespace KJS; +using namespace JSC; namespace WebCore { -JSValue* JSSQLTransaction::executeSql(ExecState* exec, const List& args) +JSValue* JSSQLTransaction::executeSql(ExecState* exec, const ArgList& args) { - String sqlStatement = args[0]->toString(exec); + String sqlStatement = args.at(exec, 0)->toString(exec); if (exec->hadException()) return jsUndefined(); // Now assemble the list of SQL arguments Vector<SQLValue> sqlValues; - if (!args[1]->isUndefinedOrNull()) { - JSObject* object = args[1]->getObject(); + if (!args.at(exec, 1)->isUndefinedOrNull()) { + JSObject* object = args.at(exec, 1)->getObject(); if (!object) { setDOMException(exec, TYPE_MISMATCH_ERR); return jsUndefined(); @@ -81,27 +81,27 @@ JSValue* JSSQLTransaction::executeSql(ExecState* exec, const List& args) } RefPtr<SQLStatementCallback> callback; - if (!args[2]->isUndefinedOrNull()) { - JSObject* object = args[2]->getObject(); + if (!args.at(exec, 2)->isUndefinedOrNull()) { + JSObject* object = args.at(exec, 2)->getObject(); if (!object) { setDOMException(exec, TYPE_MISMATCH_ERR); return jsUndefined(); } - if (Frame* frame = Window::retrieveActive(exec)->impl()->frame()) - callback = new JSCustomSQLStatementCallback(object, frame); + if (Frame* frame = asJSDOMWindow(exec->dynamicGlobalObject())->impl()->frame()) + callback = JSCustomSQLStatementCallback::create(object, frame); } RefPtr<SQLStatementErrorCallback> errorCallback; - if (!args[3]->isUndefinedOrNull()) { - JSObject* object = args[3]->getObject(); + if (!args.at(exec, 3)->isUndefinedOrNull()) { + JSObject* object = args.at(exec, 3)->getObject(); if (!object) { setDOMException(exec, TYPE_MISMATCH_ERR); return jsUndefined(); } - if (Frame* frame = Window::retrieveActive(exec)->impl()->frame()) - errorCallback = new JSCustomSQLStatementErrorCallback(object, frame); + if (Frame* frame = asJSDOMWindow(exec->dynamicGlobalObject())->impl()->frame()) + errorCallback = JSCustomSQLStatementErrorCallback::create(object, frame); } ExceptionCode ec = 0; diff --git a/WebCore/bindings/js/JSSVGElementInstanceCustom.cpp b/WebCore/bindings/js/JSSVGElementInstanceCustom.cpp new file mode 100644 index 0000000..471486b --- /dev/null +++ b/WebCore/bindings/js/JSSVGElementInstanceCustom.cpp @@ -0,0 +1,69 @@ +/* + * Copyright (C) 2008 Nikolas Zimmermann <zimmermann@kde.org> + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" + +#if ENABLE(SVG) +#include "SVGElementInstance.h" +#include "JSSVGElementInstance.h" + +#include "JSEventListener.h" +#include "JSDOMWindow.h" + +using namespace JSC; + +namespace WebCore { + +JSValue* JSSVGElementInstance::addEventListener(ExecState* exec, const ArgList& args) +{ + JSDOMGlobalObject* globalObject = toJSDOMGlobalObject(impl()->scriptExecutionContext()); + if (!globalObject) + return jsUndefined(); + + if (RefPtr<JSEventListener> listener = globalObject->findOrCreateJSEventListener(exec, args.at(exec, 1))) + impl()->addEventListener(args.at(exec, 0)->toString(exec), listener.release(), args.at(exec, 2)->toBoolean(exec)); + + return jsUndefined(); +} + +JSValue* JSSVGElementInstance::removeEventListener(ExecState* exec, const ArgList& args) +{ + JSDOMGlobalObject* globalObject = toJSDOMGlobalObject(impl()->scriptExecutionContext()); + if (!globalObject) + return jsUndefined(); + + if (JSEventListener* listener = globalObject->findJSEventListener(args.at(exec, 1))) + impl()->removeEventListener(args.at(exec, 0)->toString(exec), listener, args.at(exec, 2)->toBoolean(exec)); + + return jsUndefined(); +} + +void JSSVGElementInstance::pushEventHandlerScope(ExecState*, ScopeChain&) const +{ +} + +} + +#endif diff --git a/WebCore/bindings/js/JSSVGElementWrapperFactory.cpp b/WebCore/bindings/js/JSSVGElementWrapperFactory.cpp deleted file mode 100644 index 29ead3d..0000000 --- a/WebCore/bindings/js/JSSVGElementWrapperFactory.cpp +++ /dev/null @@ -1,316 +0,0 @@ -/* - * Copyright (C) 2006, 2007 Apple Inc. All rights reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#include "config.h" - -#if ENABLE(SVG) - -#include "JSSVGElementWrapperFactory.h" - -#include "JSSVGAElement.h" -#include "JSSVGAnimateColorElement.h" -#include "JSSVGAnimateElement.h" -#include "JSSVGAnimateTransformElement.h" -#include "JSSVGCircleElement.h" -#include "JSSVGClipPathElement.h" -#include "JSSVGCursorElement.h" -#include "JSSVGDefsElement.h" -#include "JSSVGDefinitionSrcElement.h" -#include "JSSVGDescElement.h" -#include "JSSVGEllipseElement.h" -#include "JSSVGFEBlendElement.h" -#include "JSSVGFEColorMatrixElement.h" -#include "JSSVGFEComponentTransferElement.h" -#include "JSSVGFECompositeElement.h" -#include "JSSVGFEDiffuseLightingElement.h" -#include "JSSVGFEDisplacementMapElement.h" -#include "JSSVGFEDistantLightElement.h" -#include "JSSVGFEFloodElement.h" -#include "JSSVGFEFuncAElement.h" -#include "JSSVGFEFuncBElement.h" -#include "JSSVGFEFuncGElement.h" -#include "JSSVGFEFuncRElement.h" -#include "JSSVGFEGaussianBlurElement.h" -#include "JSSVGFEImageElement.h" -#include "JSSVGFEMergeElement.h" -#include "JSSVGFEMergeNodeElement.h" -#include "JSSVGFEOffsetElement.h" -#include "JSSVGFEPointLightElement.h" -#include "JSSVGFESpecularLightingElement.h" -#include "JSSVGFESpotLightElement.h" -#include "JSSVGFETileElement.h" -#include "JSSVGFETurbulenceElement.h" -#include "JSSVGFilterElement.h" -#include "JSSVGForeignObjectElement.h" -#include "JSSVGFontElement.h" -#include "JSSVGFontFaceElement.h" -#include "JSSVGFontFaceFormatElement.h" -#include "JSSVGFontFaceNameElement.h" -#include "JSSVGFontFaceSrcElement.h" -#include "JSSVGFontFaceUriElement.h" -#include "JSSVGGElement.h" -#include "JSSVGGlyphElement.h" -#include "JSSVGImageElement.h" -#include "JSSVGLinearGradientElement.h" -#include "JSSVGLineElement.h" -#include "JSSVGMarkerElement.h" -#include "JSSVGMaskElement.h" -#include "JSSVGMetadataElement.h" -#include "JSSVGMissingGlyphElement.h" -#include "JSSVGPathElement.h" -#include "JSSVGPatternElement.h" -#include "JSSVGPolygonElement.h" -#include "JSSVGPolylineElement.h" -#include "JSSVGRadialGradientElement.h" -#include "JSSVGRectElement.h" -#include "JSSVGScriptElement.h" -#include "JSSVGSetElement.h" -#include "JSSVGStopElement.h" -#include "JSSVGStyleElement.h" -#include "JSSVGSVGElement.h" -#include "JSSVGSwitchElement.h" -#include "JSSVGSymbolElement.h" -#include "JSSVGTextElement.h" -#include "JSSVGTextPathElement.h" -#include "JSSVGTitleElement.h" -#include "JSSVGTRefElement.h" -#include "JSSVGTSpanElement.h" -#include "JSSVGUseElement.h" -#include "JSSVGViewElement.h" - -#include "SVGNames.h" - -#include "SVGAElement.h" -#include "SVGAnimateColorElement.h" -#include "SVGAnimateElement.h" -#include "SVGAnimateTransformElement.h" -#include "SVGCircleElement.h" -#include "SVGClipPathElement.h" -#include "SVGCursorElement.h" -#include "SVGDefsElement.h" -#include "SVGDefinitionSrcElement.h" -#include "SVGDescElement.h" -#include "SVGEllipseElement.h" -#include "SVGFEBlendElement.h" -#include "SVGFEColorMatrixElement.h" -#include "SVGFEComponentTransferElement.h" -#include "SVGFECompositeElement.h" -#include "SVGFEDiffuseLightingElement.h" -#include "SVGFEDisplacementMapElement.h" -#include "SVGFEDistantLightElement.h" -#include "SVGFEFloodElement.h" -#include "SVGFEFuncAElement.h" -#include "SVGFEFuncBElement.h" -#include "SVGFEFuncGElement.h" -#include "SVGFEFuncRElement.h" -#include "SVGFEGaussianBlurElement.h" -#include "SVGFEImageElement.h" -#include "SVGFEMergeElement.h" -#include "SVGFEMergeNodeElement.h" -#include "SVGFEOffsetElement.h" -#include "SVGFEPointLightElement.h" -#include "SVGFESpecularLightingElement.h" -#include "SVGFESpotLightElement.h" -#include "SVGFETileElement.h" -#include "SVGFETurbulenceElement.h" -#include "SVGFilterElement.h" -#include "SVGForeignObjectElement.h" -#include "SVGFontElement.h" -#include "SVGFontFaceElement.h" -#include "SVGFontFaceFormatElement.h" -#include "SVGFontFaceNameElement.h" -#include "SVGFontFaceSrcElement.h" -#include "SVGFontFaceUriElement.h" -#include "SVGGElement.h" -#include "SVGGlyphElement.h" -#include "SVGImageElement.h" -#include "SVGLinearGradientElement.h" -#include "SVGLineElement.h" -#include "SVGMarkerElement.h" -#include "SVGMaskElement.h" -#include "SVGMetadataElement.h" -#include "SVGMissingGlyphElement.h" -#include "SVGPathElement.h" -#include "SVGPatternElement.h" -#include "SVGPolygonElement.h" -#include "SVGPolylineElement.h" -#include "SVGRadialGradientElement.h" -#include "SVGRectElement.h" -#include "SVGScriptElement.h" -#include "SVGSetElement.h" -#include "SVGStopElement.h" -#include "SVGStyleElement.h" -#include "SVGSVGElement.h" -#include "SVGSwitchElement.h" -#include "SVGSymbolElement.h" -#include "SVGTextElement.h" -#include "SVGTextPathElement.h" -#include "SVGTitleElement.h" -#include "SVGTRefElement.h" -#include "SVGTSpanElement.h" -#include "SVGUseElement.h" -#include "SVGViewElement.h" - -using namespace KJS; - -// FIXME: Eventually this file should be autogenerated, just like SVGNames, SVGElementFactory, etc. - -namespace WebCore { - -using namespace SVGNames; - -typedef JSNode* (*CreateSVGElementWrapperFunction)(ExecState*, PassRefPtr<SVGElement>); - -#if ENABLE(SVG_ANIMATION) -#define FOR_EACH_ANIMATION_TAG(macro) \ - macro(animateColor, AnimateColor) \ - macro(animate, Animate) \ - macro(animateTransform, AnimateTransform) \ - // end of macro - -#else -#define FOR_EACH_ANIMATION_TAG(macro) -#endif - - -#if ENABLE(SVG_FONTS) -#define FOR_EACH_FONT_TAG(macro) \ - macro(definition_src, DefinitionSrc) \ - macro(font, Font) \ - macro(font_face, FontFace) \ - macro(font_face_format, FontFaceFormat) \ - macro(font_face_name, FontFaceName) \ - macro(font_face_src, FontFaceSrc) \ - macro(font_face_uri, FontFaceUri) \ - macro(glyph, Glyph) \ - macro(missing_glyph, MissingGlyph) - // end of macro - -#else -#define FOR_EACH_FONT_TAG(macro) -#endif - -#if ENABLE(SVG_FILTERS) -#define FOR_EACH_FILTER_TAG(macro) \ - macro(feBlend, FEBlend) \ - macro(feColorMatrix, FEColorMatrix) \ - macro(feComponentTransfer, FEComponentTransfer) \ - macro(feComposite, FEComposite) \ - macro(feDiffuseLighting, FEDiffuseLighting) \ - macro(feDisplacementMap, FEDisplacementMap) \ - macro(feDistantLight, FEDistantLight) \ - macro(feFlood, FEFlood) \ - macro(feFuncA, FEFuncA) \ - macro(feFuncB, FEFuncB) \ - macro(feFuncG, FEFuncG) \ - macro(feFuncR, FEFuncR) \ - macro(feGaussianBlur, FEGaussianBlur) \ - macro(feImage, FEImage) \ - macro(feMerge, FEMerge) \ - macro(feMergeNode, FEMergeNode) \ - macro(feOffset, FEOffset) \ - macro(fePointLight, FEPointLight) \ - macro(feSpecularLighting, FESpecularLighting) \ - macro(feSpotLight, FESpotLight) \ - macro(feTile, FETile) \ - macro(feTurbulence, FETurbulence) \ - macro(filter, Filter) \ - // end of macro -#else -#define FOR_EACH_FILTER_TAG(macro) -#endif - -#if ENABLE(SVG_FOREIGN_OBJECT) -#define FOR_EACH_FOREIGN_OBJECT_TAG(macro) \ - macro(foreignObject, ForeignObject) \ - // end of macro -#else -#define FOR_EACH_FOREIGN_OBJECT_TAG(macro) -#endif - -#define FOR_EACH_TAG(macro) \ - macro(a, A) \ - macro(circle, Circle) \ - macro(clipPath, ClipPath) \ - macro(cursor, Cursor) \ - macro(defs, Defs) \ - macro(desc, Desc) \ - macro(ellipse, Ellipse) \ - macro(g, G) \ - macro(image, Image) \ - macro(linearGradient, LinearGradient) \ - macro(line, Line) \ - macro(marker, Marker) \ - macro(mask, Mask) \ - macro(metadata, Metadata) \ - macro(path, Path) \ - macro(pattern, Pattern) \ - macro(polyline, Polyline) \ - macro(polygon, Polygon) \ - macro(radialGradient, RadialGradient) \ - macro(rect, Rect) \ - macro(script, Script) \ - macro(set, Set) \ - macro(stop, Stop) \ - macro(style, Style) \ - macro(svg, SVG) \ - macro(switch, Switch) \ - macro(symbol, Symbol) \ - macro(text, Text) \ - macro(textPath, TextPath) \ - macro(title, Title) \ - macro(tref, TRef) \ - macro(tspan, TSpan) \ - macro(use, Use) \ - macro(view, View) \ - // end of macro - -#define CREATE_WRAPPER_FUNCTION(tag, name) \ -static JSNode* create##name##Wrapper(ExecState* exec, PassRefPtr<SVGElement> element) \ -{ \ - return new JSSVG##name##Element(JSSVG##name##ElementPrototype::self(exec), static_cast<SVG##name##Element*>(element.get())); \ -} -FOR_EACH_TAG(CREATE_WRAPPER_FUNCTION) -FOR_EACH_ANIMATION_TAG(CREATE_WRAPPER_FUNCTION) -FOR_EACH_FONT_TAG(CREATE_WRAPPER_FUNCTION) -FOR_EACH_FILTER_TAG(CREATE_WRAPPER_FUNCTION) -FOR_EACH_FOREIGN_OBJECT_TAG(CREATE_WRAPPER_FUNCTION) - -#undef CREATE_WRAPPER_FUNCTION - -JSNode* createJSSVGWrapper(ExecState* exec, PassRefPtr<SVGElement> element) -{ - static HashMap<WebCore::AtomicStringImpl*, CreateSVGElementWrapperFunction> map; - if (map.isEmpty()) { -#define ADD_TO_HASH_MAP(tag, name) map.set(tag##Tag.localName().impl(), create##name##Wrapper); -FOR_EACH_TAG(ADD_TO_HASH_MAP) -FOR_EACH_ANIMATION_TAG(ADD_TO_HASH_MAP) -FOR_EACH_FONT_TAG(ADD_TO_HASH_MAP) -FOR_EACH_FILTER_TAG(ADD_TO_HASH_MAP) -FOR_EACH_FOREIGN_OBJECT_TAG(ADD_TO_HASH_MAP) -#undef ADD_TO_HASH_MAP - } - CreateSVGElementWrapperFunction createWrapperFunction = map.get(element->localName().impl()); - if (createWrapperFunction) - return createWrapperFunction(exec, element); - return new JSSVGElement(JSSVGElementPrototype::self(exec), element.get()); -} - -} - -#endif // ENABLE(SVG) diff --git a/WebCore/bindings/js/JSSVGLazyEventListener.h b/WebCore/bindings/js/JSSVGLazyEventListener.h deleted file mode 100644 index 8247bdb..0000000 --- a/WebCore/bindings/js/JSSVGLazyEventListener.h +++ /dev/null @@ -1,42 +0,0 @@ -/* - Copyright (C) 2006 Apple Computer, Inc. - - This file is part of the WebKit project - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#ifndef JSSVGLazyEventListener_h -#define JSSVGLazyEventListener_h -#if ENABLE(SVG) - -#include "kjs_events.h" - -namespace WebCore { - - class JSSVGLazyEventListener : public JSLazyEventListener { - public: - JSSVGLazyEventListener(const String& functionName, const String& code, KJS::Window*, Node*, int lineno = 0); - private: - virtual KJS::JSValue* eventParameterName() const; - }; - -} - -#endif // ENABLE(SVG) -#endif - -// vim:ts=4:noet diff --git a/WebCore/bindings/js/JSSVGLazyEventListener.cpp b/WebCore/bindings/js/JSSVGLengthCustom.cpp index 87d0cc6..f199517 100644 --- a/WebCore/bindings/js/JSSVGLazyEventListener.cpp +++ b/WebCore/bindings/js/JSSVGLengthCustom.cpp @@ -1,7 +1,5 @@ /* - Copyright (C) 2006 Apple Computer, Inc. - - This file is part of the WebKit project + Copyright (C) 2008 Nikolas Zimmermann <zimmermann@kde.org> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public @@ -20,27 +18,31 @@ */ #include "config.h" -#if ENABLE(SVG) -#include "JSSVGLazyEventListener.h" +#if ENABLE(SVG) +#include "JSSVGLength.h" -using namespace KJS; +using namespace JSC; namespace WebCore { -JSSVGLazyEventListener::JSSVGLazyEventListener(const String& functionName, const String& code, KJS::Window* win, Node* node, int lineno) - : JSLazyEventListener(functionName, code, win, node, lineno) +JSValue* JSSVGLength::value(ExecState* exec) const { + SVGLength imp(*impl()); + return jsNumber(exec, imp.value(context())); } -JSValue *JSSVGLazyEventListener::eventParameterName() const +JSValue* JSSVGLength::convertToSpecifiedUnits(ExecState* exec, const ArgList& args) { - static ProtectedPtr<JSValue> eventString = jsString("evt"); - return eventString.get(); + JSSVGPODTypeWrapper<SVGLength>* wrapper = impl(); + + SVGLength imp(*wrapper); + imp.convertToSpecifiedUnits(args.at(exec, 0)->toInt32(exec), context()); + + wrapper->commitChange(imp, context()); + return jsUndefined(); } } #endif // ENABLE(SVG) - -// vim:ts=4:noet diff --git a/WebCore/bindings/js/JSSVGMatrixCustom.cpp b/WebCore/bindings/js/JSSVGMatrixCustom.cpp index 99da930..d20a55e 100644 --- a/WebCore/bindings/js/JSSVGMatrixCustom.cpp +++ b/WebCore/bindings/js/JSSVGMatrixCustom.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2006, 2007 Nikolas Zimmermann <zimmermann@kde.org> + * Copyright (C) 2006, 2007, 2008 Nikolas Zimmermann <zimmermann@kde.org> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public @@ -20,28 +20,27 @@ #include "config.h" #if ENABLE(SVG) - #include "JSSVGMatrix.h" #include "AffineTransform.h" #include "SVGException.h" -using namespace KJS; +using namespace JSC; namespace WebCore { -JSValue* JSSVGMatrix::multiply(ExecState* exec, const List& args) +JSValue* JSSVGMatrix::multiply(ExecState* exec, const ArgList& args) { AffineTransform imp(*impl()); - AffineTransform secondMatrix = toSVGMatrix(args[0]); - return toJS(exec, new JSSVGPODTypeWrapperCreatorReadOnly<AffineTransform>(imp.multiply(secondMatrix)), m_context.get()); + AffineTransform secondMatrix = toSVGMatrix(args.at(exec, 0)); + return toJS(exec, JSSVGStaticPODTypeWrapper<AffineTransform>::create(imp.multiply(secondMatrix)).get(), m_context.get()); } -JSValue* JSSVGMatrix::inverse(ExecState* exec, const List&) +JSValue* JSSVGMatrix::inverse(ExecState* exec, const ArgList&) { AffineTransform imp(*impl()); - KJS::JSValue* result = toJS(exec, new JSSVGPODTypeWrapperCreatorReadOnly<AffineTransform>(imp.inverse()), m_context.get()); + JSC::JSValue* result = toJS(exec, JSSVGStaticPODTypeWrapper<AffineTransform>::create(imp.inverse()).get(), m_context.get()); if (!imp.isInvertible()) setDOMException(exec, SVGException::SVG_MATRIX_NOT_INVERTABLE); @@ -49,50 +48,50 @@ JSValue* JSSVGMatrix::inverse(ExecState* exec, const List&) return result; } -JSValue* JSSVGMatrix::translate(ExecState* exec, const List& args) +JSValue* JSSVGMatrix::translate(ExecState* exec, const ArgList& args) { AffineTransform imp(*impl()); - float x = args[0]->toFloat(exec); - float y = args[1]->toFloat(exec); + float x = args.at(exec, 0)->toFloat(exec); + float y = args.at(exec, 1)->toFloat(exec); - return toJS(exec, new JSSVGPODTypeWrapperCreatorReadOnly<AffineTransform>(imp.translate(x, y)), m_context.get()); + return toJS(exec, JSSVGStaticPODTypeWrapper<AffineTransform>::create(imp.translate(x, y)).get(), m_context.get()); } -JSValue* JSSVGMatrix::scale(ExecState* exec, const List& args) +JSValue* JSSVGMatrix::scale(ExecState* exec, const ArgList& args) { AffineTransform imp(*impl()); - float scaleFactor = args[0]->toFloat(exec); - return toJS(exec, new JSSVGPODTypeWrapperCreatorReadOnly<AffineTransform>(imp.scale(scaleFactor)), m_context.get()); + float scaleFactor = args.at(exec, 0)->toFloat(exec); + return toJS(exec, JSSVGStaticPODTypeWrapper<AffineTransform>::create(imp.scale(scaleFactor)).get(), m_context.get()); } -JSValue* JSSVGMatrix::scaleNonUniform(ExecState* exec, const List& args) +JSValue* JSSVGMatrix::scaleNonUniform(ExecState* exec, const ArgList& args) { AffineTransform imp(*impl()); - float scaleFactorX = args[0]->toFloat(exec); - float scaleFactorY = args[1]->toFloat(exec); + float scaleFactorX = args.at(exec, 0)->toFloat(exec); + float scaleFactorY = args.at(exec, 1)->toFloat(exec); - return toJS(exec, new JSSVGPODTypeWrapperCreatorReadOnly<AffineTransform>(imp.scaleNonUniform(scaleFactorX, scaleFactorY)), m_context.get()); + return toJS(exec, JSSVGStaticPODTypeWrapper<AffineTransform>::create(imp.scaleNonUniform(scaleFactorX, scaleFactorY)).get(), m_context.get()); } -JSValue* JSSVGMatrix::rotate(ExecState* exec, const List& args) +JSValue* JSSVGMatrix::rotate(ExecState* exec, const ArgList& args) { AffineTransform imp(*impl()); - float angle = args[0]->toFloat(exec); - return toJS(exec, new JSSVGPODTypeWrapperCreatorReadOnly<AffineTransform>(imp.rotate(angle)), m_context.get()); + float angle = args.at(exec, 0)->toFloat(exec); + return toJS(exec, JSSVGStaticPODTypeWrapper<AffineTransform>::create(imp.rotate(angle)).get(), m_context.get()); } -JSValue* JSSVGMatrix::rotateFromVector(ExecState* exec, const List& args) +JSValue* JSSVGMatrix::rotateFromVector(ExecState* exec, const ArgList& args) { AffineTransform imp(*impl()); - float x = args[0]->toFloat(exec); - float y = args[1]->toFloat(exec); + float x = args.at(exec, 0)->toFloat(exec); + float y = args.at(exec, 1)->toFloat(exec); - KJS::JSValue* result = toJS(exec, new JSSVGPODTypeWrapperCreatorReadOnly<AffineTransform>(imp.rotateFromVector(x, y)), m_context.get()); + JSC::JSValue* result = toJS(exec, JSSVGStaticPODTypeWrapper<AffineTransform>::create(imp.rotateFromVector(x, y)).get(), m_context.get()); if (x == 0.0 || y == 0.0) setDOMException(exec, SVGException::SVG_INVALID_VALUE_ERR); @@ -100,36 +99,34 @@ JSValue* JSSVGMatrix::rotateFromVector(ExecState* exec, const List& args) return result; } -JSValue* JSSVGMatrix::flipX(ExecState* exec, const List&) +JSValue* JSSVGMatrix::flipX(ExecState* exec, const ArgList&) { AffineTransform imp(*impl()); - return toJS(exec, new JSSVGPODTypeWrapperCreatorReadOnly<AffineTransform>(imp.flipX()), m_context.get()); + return toJS(exec, JSSVGStaticPODTypeWrapper<AffineTransform>::create(imp.flipX()).get(), m_context.get()); } -JSValue* JSSVGMatrix::flipY(ExecState* exec, const List&) +JSValue* JSSVGMatrix::flipY(ExecState* exec, const ArgList&) { AffineTransform imp(*impl()); - return toJS(exec, new JSSVGPODTypeWrapperCreatorReadOnly<AffineTransform>(imp.flipY()), m_context.get()); + return toJS(exec, JSSVGStaticPODTypeWrapper<AffineTransform>::create(imp.flipY()).get(), m_context.get()); } -JSValue* JSSVGMatrix::skewX(ExecState* exec, const List& args) +JSValue* JSSVGMatrix::skewX(ExecState* exec, const ArgList& args) { AffineTransform imp(*impl()); - float angle = args[0]->toFloat(exec); - return toJS(exec, new JSSVGPODTypeWrapperCreatorReadOnly<AffineTransform>(imp.skewX(angle)), m_context.get()); + float angle = args.at(exec, 0)->toFloat(exec); + return toJS(exec, JSSVGStaticPODTypeWrapper<AffineTransform>::create(imp.skewX(angle)).get(), m_context.get()); } -JSValue* JSSVGMatrix::skewY(ExecState* exec, const List& args) +JSValue* JSSVGMatrix::skewY(ExecState* exec, const ArgList& args) { AffineTransform imp(*impl()); - float angle = args[0]->toFloat(exec); - return toJS(exec, new JSSVGPODTypeWrapperCreatorReadOnly<AffineTransform>(imp.skewY(angle)), m_context.get()); + float angle = args.at(exec, 0)->toFloat(exec); + return toJS(exec, JSSVGStaticPODTypeWrapper<AffineTransform>::create(imp.skewY(angle)).get(), m_context.get()); } } #endif // ENABLE(SVG) - -// vim:ts=4:noet diff --git a/WebCore/bindings/js/JSSVGPODTypeWrapper.h b/WebCore/bindings/js/JSSVGPODTypeWrapper.h index 03cb401..7eb665a 100644 --- a/WebCore/bindings/js/JSSVGPODTypeWrapper.h +++ b/WebCore/bindings/js/JSSVGPODTypeWrapper.h @@ -1,5 +1,6 @@ /* * Copyright (C) 2006, 2008 Nikolas Zimmermann <zimmermann@kde.org> + * Copyright (C) 2008 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -27,57 +28,66 @@ #define JSSVGPODTypeWrapper_h #if ENABLE(SVG) - #include "Frame.h" -#include <wtf/RefCounted.h> #include "SVGElement.h" -#include <wtf/Assertions.h> -#include <wtf/HashMap.h> - namespace WebCore { template<typename PODType> -class JSSVGPODTypeWrapper : public RefCounted<JSSVGPODTypeWrapper<PODType> > -{ +class JSSVGPODTypeWrapper : public RefCounted<JSSVGPODTypeWrapper<PODType> > { public: virtual ~JSSVGPODTypeWrapper() { } - // Getter wrapper virtual operator PODType() = 0; - - // Setter wrapper virtual void commitChange(PODType, SVGElement*) = 0; }; +// This file contains JS wrapper objects for SVG datatypes, that are passed around by value +// in WebCore/svg (aka. 'POD types'). For instance SVGMatrix is mapped to AffineTransform, and +// passed around as const reference. SVG DOM demands these objects to be "live", changes to any +// of the writable attributes of SVGMatrix need to be reflected in the object which exposed the +// SVGMatrix object (ie. 'someElement.transform.matrix.a = 50.0', in that case 'SVGTransform'). +// The SVGTransform class stores its "AffineTransform m_matrix" object on the stack. If it would +// be stored as pointer we could just build an auto-generated JSSVG* wrapper object around it +// and all changes to that object would automatically affect the AffineTransform* object stored +// in the SVGTransform object. For the sake of efficiency and memory we don't pass around any +// primitive values as pointers, so a custom JS wrapper object is needed for all SVG types, that +// are internally represented by POD types (SVGRect <-> FloatRect, SVGPoint <-> FloatPoint, ...). +// Those custom wrappers are called JSSVGPODTypeWrapper and are capable of updating the POD types +// by taking function pointers to the getter & setter functions of the "creator object", the object +// which exposed a SVG POD type. For example, the JSSVGPODTypeWrapper object wrapping a SVGMatrix +// object takes (SVGTransform*, &SVGTransform::matrix, &SVGTransform::setMatrix). A JS call like +// "someElement.transform.matrix.a = 50.0' causes the JSSVGMatrix object to call SVGTransform::setMatrix, +// method, which in turn notifies 'someElement' that the 'SVGNames::transformAttr' has changed. +// That's a short sketch of our SVG DOM implementation. + +// Represents a JS wrapper object for SVGAnimated* classes, exposing SVG POD types that contain writable properties +// (Two cases: SVGAnimatedLength exposing SVGLength, SVGAnimatedRect exposing SVGRect) + +#if COMPILER(MSVC) +// GetterMethod and SetterMethod are each 12 bytes. We have to pack to a size +// greater than or equal to that to avoid an alignment warning (C4121). 16 is +// the next-largest size allowed for packing, so we use that. +#pragma pack(16) +#endif template<typename PODType, typename PODTypeCreator> -class JSSVGPODTypeWrapperCreatorReadWrite : public JSSVGPODTypeWrapper<PODType> -{ +class JSSVGDynamicPODTypeWrapper : public JSSVGPODTypeWrapper<PODType> { public: typedef PODType (PODTypeCreator::*GetterMethod)() const; typedef void (PODTypeCreator::*SetterMethod)(PODType); - JSSVGPODTypeWrapperCreatorReadWrite(PODTypeCreator* creator, GetterMethod getter, SetterMethod setter) - : m_creator(creator) - , m_getter(getter) - , m_setter(setter) + static PassRefPtr<JSSVGDynamicPODTypeWrapper> create(PassRefPtr<PODTypeCreator> creator, GetterMethod getter, SetterMethod setter) { - ASSERT(creator); - ASSERT(getter); - ASSERT(setter); + return adoptRef(new JSSVGDynamicPODTypeWrapper(creator, getter, setter)); } - virtual ~JSSVGPODTypeWrapperCreatorReadWrite() { } - - // Getter wrapper - virtual operator PODType() { return (m_creator.get()->*m_getter)(); } + virtual operator PODType() + { + return (m_creator.get()->*m_getter)(); + } - // Setter wrapper virtual void commitChange(PODType type, SVGElement* context) { - if (!m_setter) - return; - (m_creator.get()->*m_setter)(type); if (context) @@ -85,62 +95,146 @@ public: } private: + JSSVGDynamicPODTypeWrapper(PassRefPtr<PODTypeCreator> creator, GetterMethod getter, SetterMethod setter) + : m_creator(creator) + , m_getter(getter) + , m_setter(setter) + { + ASSERT(m_creator); + ASSERT(m_getter); + ASSERT(m_setter); + } + // Update callbacks RefPtr<PODTypeCreator> m_creator; GetterMethod m_getter; SetterMethod m_setter; }; +// Represents a JS wrapper object for SVG POD types (not for SVGAnimated* clases). Any modification to the SVG POD +// types don't cause any updates unlike JSSVGDynamicPODTypeWrapper. This class is used for return values (ie. getBBox()) +// and for properties where SVG specification explicitely states, that the contents of the POD type are immutable. + template<typename PODType> -class JSSVGPODTypeWrapperCreatorReadOnly : public JSSVGPODTypeWrapper<PODType> -{ +class JSSVGStaticPODTypeWrapper : public JSSVGPODTypeWrapper<PODType> { public: - JSSVGPODTypeWrapperCreatorReadOnly(PODType type) - : m_podType(type) - { } - - virtual ~JSSVGPODTypeWrapperCreatorReadOnly() { } + static PassRefPtr<JSSVGStaticPODTypeWrapper> create(PODType type) + { + return adoptRef(new JSSVGStaticPODTypeWrapper(type)); + } - // Getter wrapper - virtual operator PODType() { return m_podType; } + virtual operator PODType() + { + return m_podType; + } - // Setter wrapper virtual void commitChange(PODType type, SVGElement*) { m_podType = type; } -private: +protected: + JSSVGStaticPODTypeWrapper(PODType type) + : m_podType(type) + { + } + PODType m_podType; }; +template<typename PODType, typename ParentTypeArg> +class JSSVGStaticPODTypeWrapperWithPODTypeParent : public JSSVGStaticPODTypeWrapper<PODType> { +public: + typedef JSSVGPODTypeWrapper<ParentTypeArg> ParentType; + + static PassRefPtr<JSSVGStaticPODTypeWrapperWithPODTypeParent> create(PODType type, PassRefPtr<ParentType> parent) + { + return adoptRef(new JSSVGStaticPODTypeWrapperWithPODTypeParent(type, parent)); + } + + virtual void commitChange(PODType type, SVGElement* context) + { + JSSVGStaticPODTypeWrapper<PODType>::commitChange(type, context); + m_parentType->commitChange(ParentTypeArg(type), context); + } + +private: + JSSVGStaticPODTypeWrapperWithPODTypeParent(PODType type, PassRefPtr<ParentType> parent) + : JSSVGStaticPODTypeWrapper<PODType>(type) + , m_parentType(parent) + { + } + + RefPtr<ParentType> m_parentType; +}; + +#if COMPILER(MSVC) +// GetterMethod and SetterMethod are each 12 bytes. We have to pack to a size +// greater than or equal to that to avoid an alignment warning (C4121). 16 is +// the next-largest size allowed for packing, so we use that. +#pragma pack(16) +#endif +template<typename PODType, typename ParentType> +class JSSVGStaticPODTypeWrapperWithParent : public JSSVGPODTypeWrapper<PODType> { +public: + typedef PODType (ParentType::*GetterMethod)() const; + typedef void (ParentType::*SetterMethod)(const PODType&); + + static PassRefPtr<JSSVGStaticPODTypeWrapperWithParent> create(PassRefPtr<ParentType> parent, GetterMethod getter, SetterMethod setter) + { + return adoptRef(new JSSVGStaticPODTypeWrapperWithParent(parent, getter, setter)); + } + + virtual operator PODType() + { + return (m_parent.get()->*m_getter)(); + } + + virtual void commitChange(PODType type, SVGElement* context) + { + (m_parent.get()->*m_setter)(type); + } + +private: + JSSVGStaticPODTypeWrapperWithParent(PassRefPtr<ParentType> parent, GetterMethod getter, SetterMethod setter) + : m_parent(parent) + , m_getter(getter) + , m_setter(setter) + { + ASSERT(m_parent); + ASSERT(m_getter); + ASSERT(m_setter); + } + + // Update callbacks + RefPtr<ParentType> m_parent; + GetterMethod m_getter; + SetterMethod m_setter; +}; + template<typename PODType> class SVGPODListItem; +// Just like JSSVGDynamicPODTypeWrapper, but only used for SVGList* objects wrapping around POD values. + template<typename PODType> -class JSSVGPODTypeWrapperCreatorForList : public JSSVGPODTypeWrapper<PODType> -{ +class JSSVGPODTypeWrapperCreatorForList : public JSSVGPODTypeWrapper<PODType> { public: + typedef SVGPODListItem<PODType> PODListItemPtrType; + typedef PODType (SVGPODListItem<PODType>::*GetterMethod)() const; typedef void (SVGPODListItem<PODType>::*SetterMethod)(PODType); - JSSVGPODTypeWrapperCreatorForList(SVGPODListItem<PODType>* creator, const QualifiedName& attributeName) - : m_creator(creator) - , m_getter(&SVGPODListItem<PODType>::value) - , m_setter(&SVGPODListItem<PODType>::setValue) - , m_associatedAttributeName(attributeName) + static PassRefPtr<JSSVGPODTypeWrapperCreatorForList> create(PassRefPtr<PODListItemPtrType> creator, const QualifiedName& attributeName) { - ASSERT(m_creator); - ASSERT(m_getter); - ASSERT(m_setter); + return adoptRef(new JSSVGPODTypeWrapperCreatorForList(creator, attributeName)); } - virtual ~JSSVGPODTypeWrapperCreatorForList() { } - - // Getter wrapper - virtual operator PODType() { return (m_creator.get()->*m_getter)(); } + virtual operator PODType() + { + return (m_creator.get()->*m_getter)(); + } - // Setter wrapper virtual void commitChange(PODType type, SVGElement* context) { if (!m_setter) @@ -153,8 +247,19 @@ public: } private: + JSSVGPODTypeWrapperCreatorForList(PassRefPtr<PODListItemPtrType> creator, const QualifiedName& attributeName) + : m_creator(creator) + , m_getter(&PODListItemPtrType::value) + , m_setter(&PODListItemPtrType::setValue) + , m_associatedAttributeName(attributeName) + { + ASSERT(m_creator); + ASSERT(m_getter); + ASSERT(m_setter); + } + // Update callbacks - RefPtr<SVGPODListItem<PODType> > m_creator; + RefPtr<PODListItemPtrType> m_creator; GetterMethod m_getter; SetterMethod m_setter; const QualifiedName& m_associatedAttributeName; @@ -162,25 +267,29 @@ private: // Caching facilities template<typename PODType, typename PODTypeCreator> -struct PODTypeReadWriteHashInfo { +struct PODTypeWrapperCacheInfo { typedef PODType (PODTypeCreator::*GetterMethod)() const; typedef void (PODTypeCreator::*SetterMethod)(PODType); // Empty value - PODTypeReadWriteHashInfo() + PODTypeWrapperCacheInfo() : creator(0) , getter(0) , setter(0) - { } + { + } // Deleted value - explicit PODTypeReadWriteHashInfo(bool) + PODTypeWrapperCacheInfo(WTF::HashTableDeletedValueType) : creator(reinterpret_cast<PODTypeCreator*>(-1)) - , getter(0) - , setter(0) - { } + { + } + bool isHashTableDeletedValue() const + { + return creator == reinterpret_cast<PODTypeCreator*>(-1); + } - PODTypeReadWriteHashInfo(PODTypeCreator* _creator, GetterMethod _getter, SetterMethod _setter) + PODTypeWrapperCacheInfo(PODTypeCreator* _creator, GetterMethod _getter, SetterMethod _setter) : creator(_creator) , getter(_getter) , setter(_setter) @@ -189,7 +298,7 @@ struct PODTypeReadWriteHashInfo { ASSERT(getter); } - bool operator==(const PODTypeReadWriteHashInfo& other) const + bool operator==(const PODTypeWrapperCacheInfo& other) const { return creator == other.creator && getter == other.getter && setter == other.setter; } @@ -200,13 +309,15 @@ struct PODTypeReadWriteHashInfo { }; template<typename PODType, typename PODTypeCreator> -struct PODTypeReadWriteHashInfoHash { - static unsigned hash(const PODTypeReadWriteHashInfo<PODType, PODTypeCreator>& info) +struct PODTypeWrapperCacheInfoHash { + typedef PODTypeWrapperCacheInfo<PODType, PODTypeCreator> CacheInfo; + + static unsigned hash(const CacheInfo& info) { - return StringImpl::computeHash((::UChar*) &info, sizeof(PODTypeReadWriteHashInfo<PODType, PODTypeCreator>) / sizeof(::UChar)); + return StringImpl::computeHash(reinterpret_cast<const UChar*>(&info), sizeof(CacheInfo) / sizeof(UChar)); } - static bool equal(const PODTypeReadWriteHashInfo<PODType, PODTypeCreator>& a, const PODTypeReadWriteHashInfo<PODType, PODTypeCreator>& b) + static bool equal(const CacheInfo& a, const CacheInfo& b) { return a == b; } @@ -215,65 +326,76 @@ struct PODTypeReadWriteHashInfoHash { }; template<typename PODType, typename PODTypeCreator> -struct PODTypeReadWriteHashInfoTraits : WTF::GenericHashTraits<PODTypeReadWriteHashInfo<PODType, PODTypeCreator> > { +struct PODTypeWrapperCacheInfoTraits : WTF::GenericHashTraits<PODTypeWrapperCacheInfo<PODType, PODTypeCreator> > { + typedef PODTypeWrapperCacheInfo<PODType, PODTypeCreator> CacheInfo; + static const bool emptyValueIsZero = true; static const bool needsDestruction = false; - static const PODTypeReadWriteHashInfo<PODType, PODTypeCreator>& deletedValue() + static const CacheInfo& emptyValue() { - static PODTypeReadWriteHashInfo<PODType, PODTypeCreator> key(true); + static CacheInfo key; return key; } - static const PODTypeReadWriteHashInfo<PODType, PODTypeCreator>& emptyValue() + static void constructDeletedValue(CacheInfo& slot) { - static PODTypeReadWriteHashInfo<PODType, PODTypeCreator> key; - return key; + new (&slot) CacheInfo(WTF::HashTableDeletedValue); + } + + static bool isDeletedValue(const CacheInfo& value) + { + return value.isHashTableDeletedValue(); } }; template<typename PODType, typename PODTypeCreator> -class JSSVGPODTypeWrapperCache -{ +class JSSVGDynamicPODTypeWrapperCache { public: typedef PODType (PODTypeCreator::*GetterMethod)() const; typedef void (PODTypeCreator::*SetterMethod)(PODType); - typedef HashMap<PODTypeReadWriteHashInfo<PODType, PODTypeCreator>, JSSVGPODTypeWrapperCreatorReadWrite<PODType, PODTypeCreator>*, PODTypeReadWriteHashInfoHash<PODType, PODTypeCreator>, PODTypeReadWriteHashInfoTraits<PODType, PODTypeCreator> > ReadWriteHashMap; - typedef typename ReadWriteHashMap::const_iterator ReadWriteHashMapIterator; + typedef PODTypeWrapperCacheInfo<PODType, PODTypeCreator> CacheInfo; + typedef PODTypeWrapperCacheInfoHash<PODType, PODTypeCreator> CacheInfoHash; + typedef PODTypeWrapperCacheInfoTraits<PODType, PODTypeCreator> CacheInfoTraits; + + typedef JSSVGPODTypeWrapper<PODType> WrapperBase; + typedef JSSVGDynamicPODTypeWrapper<PODType, PODTypeCreator> DynamicWrapper; + typedef HashMap<CacheInfo, DynamicWrapper*, CacheInfoHash, CacheInfoTraits> DynamicWrapperHashMap; + typedef typename DynamicWrapperHashMap::const_iterator DynamicWrapperHashMapIterator; - static ReadWriteHashMap& readWriteHashMap() + static DynamicWrapperHashMap& dynamicWrapperHashMap() { - static ReadWriteHashMap _readWriteHashMap; - return _readWriteHashMap; + static DynamicWrapperHashMap s_dynamicWrapperHashMap; + return s_dynamicWrapperHashMap; } // Used for readwrite attributes only - static JSSVGPODTypeWrapper<PODType>* lookupOrCreateWrapper(PODTypeCreator* creator, GetterMethod getter, SetterMethod setter) + static PassRefPtr<WrapperBase> lookupOrCreateWrapper(PODTypeCreator* creator, GetterMethod getter, SetterMethod setter) { - ReadWriteHashMap& map(readWriteHashMap()); - PODTypeReadWriteHashInfo<PODType, PODTypeCreator> info(creator, getter, setter); + DynamicWrapperHashMap& map(dynamicWrapperHashMap()); + CacheInfo info(creator, getter, setter); if (map.contains(info)) return map.get(info); - JSSVGPODTypeWrapperCreatorReadWrite<PODType, PODTypeCreator>* wrapper = new JSSVGPODTypeWrapperCreatorReadWrite<PODType, PODTypeCreator>(creator, getter, setter); - map.set(info, wrapper); - return wrapper; + RefPtr<DynamicWrapper> wrapper = DynamicWrapper::create(creator, getter, setter); + map.set(info, wrapper.get()); + return wrapper.release(); } - static void forgetWrapper(JSSVGPODTypeWrapper<PODType>* wrapper) + static void forgetWrapper(WrapperBase* wrapper) { - ReadWriteHashMap& map(readWriteHashMap()); + DynamicWrapperHashMap& map(dynamicWrapperHashMap()); - ReadWriteHashMapIterator it = map.begin(); - ReadWriteHashMapIterator end = map.end(); + DynamicWrapperHashMapIterator it = map.begin(); + DynamicWrapperHashMapIterator end = map.end(); for (; it != end; ++it) { if (it->second != wrapper) continue; - // It's guaruanteed that there's just one object we need to take care of. + // It's guaranteed that there's just one object we need to take care of. map.remove(it->first); break; } diff --git a/WebCore/bindings/js/JSSVGPathSegCustom.cpp b/WebCore/bindings/js/JSSVGPathSegCustom.cpp index 55db3a1..8c0a4ef 100644 --- a/WebCore/bindings/js/JSSVGPathSegCustom.cpp +++ b/WebCore/bindings/js/JSSVGPathSegCustom.cpp @@ -41,7 +41,7 @@ #include "JSSVGPathSegMovetoAbs.h" #include "JSSVGPathSegMovetoRel.h" -#include "kjs_binding.h" +#include "JSDOMBinding.h" #include "SVGPathSeg.h" #include "SVGPathSegArc.h" @@ -55,57 +55,60 @@ #include "SVGPathSegLinetoVertical.h" #include "SVGPathSegMoveto.h" -using namespace KJS; +using namespace JSC; namespace WebCore { -JSValue* toJS(ExecState* exec, SVGPathSeg* obj, SVGElement* context) +JSValue* toJS(ExecState* exec, SVGPathSeg* object, SVGElement* context) { - if (!obj) + if (!object) return jsNull(); - - switch (obj->pathSegType()) { + + if (DOMObject* wrapper = getCachedDOMObjectWrapper(exec->globalData(), object)) + return wrapper; + + switch (object->pathSegType()) { case SVGPathSeg::PATHSEG_CLOSEPATH: - return cacheSVGDOMObject<SVGPathSegClosePath, JSSVGPathSegClosePath, JSSVGPathSegClosePathPrototype>(exec, static_cast<SVGPathSegClosePath*>(obj), context); + return CREATE_SVG_OBJECT_WRAPPER(exec, SVGPathSegClosePath, object, context); case SVGPathSeg::PATHSEG_MOVETO_ABS: - return cacheSVGDOMObject<SVGPathSegMovetoAbs, JSSVGPathSegMovetoAbs, JSSVGPathSegMovetoAbsPrototype>(exec, static_cast<SVGPathSegMovetoAbs*>(obj), context); + return CREATE_SVG_OBJECT_WRAPPER(exec, SVGPathSegMovetoAbs, object, context); case SVGPathSeg::PATHSEG_MOVETO_REL: - return cacheSVGDOMObject<SVGPathSegMovetoRel, JSSVGPathSegMovetoRel, JSSVGPathSegMovetoRelPrototype>(exec, static_cast<SVGPathSegMovetoRel*>(obj), context); + return CREATE_SVG_OBJECT_WRAPPER(exec, SVGPathSegMovetoRel, object, context); case SVGPathSeg::PATHSEG_LINETO_ABS: - return cacheSVGDOMObject<SVGPathSegLinetoAbs, JSSVGPathSegLinetoAbs, JSSVGPathSegLinetoAbsPrototype>(exec, static_cast<SVGPathSegLinetoAbs*>(obj), context); + return CREATE_SVG_OBJECT_WRAPPER(exec, SVGPathSegLinetoAbs, object, context); case SVGPathSeg::PATHSEG_LINETO_REL: - return cacheSVGDOMObject<SVGPathSegLinetoRel, JSSVGPathSegLinetoRel, JSSVGPathSegLinetoRelPrototype>(exec, static_cast<SVGPathSegLinetoRel*>(obj), context); + return CREATE_SVG_OBJECT_WRAPPER(exec, SVGPathSegLinetoRel, object, context); case SVGPathSeg::PATHSEG_CURVETO_CUBIC_ABS: - return cacheSVGDOMObject<SVGPathSegCurvetoCubicAbs, JSSVGPathSegCurvetoCubicAbs, JSSVGPathSegCurvetoCubicAbsPrototype>(exec, static_cast<SVGPathSegCurvetoCubicAbs*>(obj), context); + return CREATE_SVG_OBJECT_WRAPPER(exec, SVGPathSegCurvetoCubicAbs, object, context); case SVGPathSeg::PATHSEG_CURVETO_CUBIC_REL: - return cacheSVGDOMObject<SVGPathSegCurvetoCubicRel, JSSVGPathSegCurvetoCubicRel, JSSVGPathSegCurvetoCubicRelPrototype>(exec, static_cast<SVGPathSegCurvetoCubicRel*>(obj), context); + return CREATE_SVG_OBJECT_WRAPPER(exec, SVGPathSegCurvetoCubicRel, object, context); case SVGPathSeg::PATHSEG_CURVETO_QUADRATIC_ABS: - return cacheSVGDOMObject<SVGPathSegCurvetoQuadraticAbs, JSSVGPathSegCurvetoQuadraticAbs, JSSVGPathSegCurvetoQuadraticAbsPrototype>(exec, static_cast<SVGPathSegCurvetoQuadraticAbs*>(obj), context); + return CREATE_SVG_OBJECT_WRAPPER(exec, SVGPathSegCurvetoQuadraticAbs, object, context); case SVGPathSeg::PATHSEG_CURVETO_QUADRATIC_REL: - return cacheSVGDOMObject<SVGPathSegCurvetoQuadraticRel, JSSVGPathSegCurvetoQuadraticRel, JSSVGPathSegCurvetoQuadraticRelPrototype>(exec, static_cast<SVGPathSegCurvetoQuadraticRel*>(obj), context); + return CREATE_SVG_OBJECT_WRAPPER(exec, SVGPathSegCurvetoQuadraticRel, object, context); case SVGPathSeg::PATHSEG_ARC_ABS: - return cacheSVGDOMObject<SVGPathSegArcAbs, JSSVGPathSegArcAbs, JSSVGPathSegArcAbsPrototype>(exec, static_cast<SVGPathSegArcAbs*>(obj), context); + return CREATE_SVG_OBJECT_WRAPPER(exec, SVGPathSegArcAbs, object, context); case SVGPathSeg::PATHSEG_ARC_REL: - return cacheSVGDOMObject<SVGPathSegArcRel, JSSVGPathSegArcRel, JSSVGPathSegArcRelPrototype>(exec, static_cast<SVGPathSegArcRel*>(obj), context); + return CREATE_SVG_OBJECT_WRAPPER(exec, SVGPathSegArcRel, object, context); case SVGPathSeg::PATHSEG_LINETO_HORIZONTAL_ABS: - return cacheSVGDOMObject<SVGPathSegLinetoHorizontalAbs, JSSVGPathSegLinetoHorizontalAbs, JSSVGPathSegLinetoHorizontalAbsPrototype>(exec, static_cast<SVGPathSegLinetoHorizontalAbs*>(obj), context); + return CREATE_SVG_OBJECT_WRAPPER(exec, SVGPathSegLinetoHorizontalAbs, object, context); case SVGPathSeg::PATHSEG_LINETO_HORIZONTAL_REL: - return cacheSVGDOMObject<SVGPathSegLinetoHorizontalRel, JSSVGPathSegLinetoHorizontalRel, JSSVGPathSegLinetoHorizontalRelPrototype>(exec, static_cast<SVGPathSegLinetoHorizontalRel*>(obj), context); + return CREATE_SVG_OBJECT_WRAPPER(exec, SVGPathSegLinetoHorizontalRel, object, context); case SVGPathSeg::PATHSEG_LINETO_VERTICAL_ABS: - return cacheSVGDOMObject<SVGPathSegLinetoVerticalAbs, JSSVGPathSegLinetoVerticalAbs, JSSVGPathSegLinetoVerticalAbsPrototype>(exec, static_cast<SVGPathSegLinetoVerticalAbs*>(obj), context); + return CREATE_SVG_OBJECT_WRAPPER(exec, SVGPathSegLinetoVerticalAbs, object, context); case SVGPathSeg::PATHSEG_LINETO_VERTICAL_REL: - return cacheSVGDOMObject<SVGPathSegLinetoVerticalRel, JSSVGPathSegLinetoVerticalRel, JSSVGPathSegLinetoVerticalRelPrototype>(exec, static_cast<SVGPathSegLinetoVerticalRel*>(obj), context); + return CREATE_SVG_OBJECT_WRAPPER(exec, SVGPathSegLinetoVerticalRel, object, context); case SVGPathSeg::PATHSEG_CURVETO_CUBIC_SMOOTH_ABS: - return cacheSVGDOMObject<SVGPathSegCurvetoCubicSmoothAbs, JSSVGPathSegCurvetoCubicSmoothAbs, JSSVGPathSegCurvetoCubicSmoothAbsPrototype>(exec, static_cast<SVGPathSegCurvetoCubicSmoothAbs*>(obj), context); + return CREATE_SVG_OBJECT_WRAPPER(exec, SVGPathSegCurvetoCubicSmoothAbs, object, context); case SVGPathSeg::PATHSEG_CURVETO_CUBIC_SMOOTH_REL: - return cacheSVGDOMObject<SVGPathSegCurvetoCubicSmoothRel, JSSVGPathSegCurvetoCubicSmoothRel, JSSVGPathSegCurvetoCubicSmoothRelPrototype>(exec, static_cast<SVGPathSegCurvetoCubicSmoothRel*>(obj), context); + return CREATE_SVG_OBJECT_WRAPPER(exec, SVGPathSegCurvetoCubicSmoothRel, object, context); case SVGPathSeg::PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS: - return cacheSVGDOMObject<SVGPathSegCurvetoQuadraticSmoothAbs, JSSVGPathSegCurvetoQuadraticSmoothAbs, JSSVGPathSegCurvetoQuadraticSmoothAbsPrototype>(exec, static_cast<SVGPathSegCurvetoQuadraticSmoothAbs*>(obj), context); + return CREATE_SVG_OBJECT_WRAPPER(exec, SVGPathSegCurvetoQuadraticSmoothAbs, object, context); case SVGPathSeg::PATHSEG_CURVETO_QUADRATIC_SMOOTH_REL: - return cacheSVGDOMObject<SVGPathSegCurvetoQuadraticSmoothRel, JSSVGPathSegCurvetoQuadraticSmoothRel, JSSVGPathSegCurvetoQuadraticSmoothRelPrototype>(exec, static_cast<SVGPathSegCurvetoQuadraticSmoothRel*>(obj), context); + return CREATE_SVG_OBJECT_WRAPPER(exec, SVGPathSegCurvetoQuadraticSmoothRel, object, context); case SVGPathSeg::PATHSEG_UNKNOWN: default: - return cacheSVGDOMObject<SVGPathSeg, JSSVGPathSeg, JSSVGPathSegPrototype>(exec, obj, context); + return CREATE_SVG_OBJECT_WRAPPER(exec, SVGPathSeg, object, context); } } diff --git a/WebCore/bindings/js/JSSVGPathSegListCustom.cpp b/WebCore/bindings/js/JSSVGPathSegListCustom.cpp index 19972a2..95b60aa 100644 --- a/WebCore/bindings/js/JSSVGPathSegListCustom.cpp +++ b/WebCore/bindings/js/JSSVGPathSegListCustom.cpp @@ -31,11 +31,11 @@ #include <wtf/Assertions.h> -using namespace KJS; +using namespace JSC; namespace WebCore { -JSValue* JSSVGPathSegList::clear(ExecState* exec, const List& args) +JSValue* JSSVGPathSegList::clear(ExecState* exec, const ArgList& args) { ExceptionCode ec = 0; @@ -48,28 +48,28 @@ JSValue* JSSVGPathSegList::clear(ExecState* exec, const List& args) return jsUndefined(); } -JSValue* JSSVGPathSegList::initialize(ExecState* exec, const List& args) +JSValue* JSSVGPathSegList::initialize(ExecState* exec, const ArgList& args) { ExceptionCode ec = 0; - SVGPathSeg* newItem = toSVGPathSeg(args[0]); + SVGPathSeg* newItem = toSVGPathSeg(args.at(exec, 0)); SVGPathSegList* imp = static_cast<SVGPathSegList*>(impl()); SVGPathSeg* obj = WTF::getPtr(imp->initialize(newItem, ec)); - KJS::JSValue* result = toJS(exec, obj, m_context.get()); + JSC::JSValue* result = toJS(exec, obj, m_context.get()); setDOMException(exec, ec); m_context->svgAttributeChanged(imp->associatedAttributeName()); return result; } -JSValue* JSSVGPathSegList::getItem(ExecState* exec, const List& args) +JSValue* JSSVGPathSegList::getItem(ExecState* exec, const ArgList& args) { ExceptionCode ec = 0; bool indexOk; - unsigned index = args[0]->toInt32(exec, indexOk); + unsigned index = args.at(exec, 0)->toInt32(exec, indexOk); if (!indexOk) { setDOMException(exec, TYPE_MISMATCH_ERR); return jsUndefined(); @@ -78,18 +78,18 @@ JSValue* JSSVGPathSegList::getItem(ExecState* exec, const List& args) SVGPathSegList* imp = static_cast<SVGPathSegList*>(impl()); SVGPathSeg* obj = WTF::getPtr(imp->getItem(index, ec)); - KJS::JSValue* result = toJS(exec, obj, m_context.get()); + JSC::JSValue* result = toJS(exec, obj, m_context.get()); setDOMException(exec, ec); return result; } -JSValue* JSSVGPathSegList::insertItemBefore(ExecState* exec, const List& args) +JSValue* JSSVGPathSegList::insertItemBefore(ExecState* exec, const ArgList& args) { ExceptionCode ec = 0; - SVGPathSeg* newItem = toSVGPathSeg(args[0]); + SVGPathSeg* newItem = toSVGPathSeg(args.at(exec, 0)); bool indexOk; - unsigned index = args[1]->toInt32(exec, indexOk); + unsigned index = args.at(exec, 1)->toInt32(exec, indexOk); if (!indexOk) { setDOMException(exec, TYPE_MISMATCH_ERR); return jsUndefined(); @@ -97,20 +97,20 @@ JSValue* JSSVGPathSegList::insertItemBefore(ExecState* exec, const List& args) SVGPathSegList* imp = static_cast<SVGPathSegList*>(impl()); - KJS::JSValue* result = toJS(exec, WTF::getPtr(imp->insertItemBefore(newItem, index, ec)), m_context.get()); + JSC::JSValue* result = toJS(exec, WTF::getPtr(imp->insertItemBefore(newItem, index, ec)), m_context.get()); setDOMException(exec, ec); m_context->svgAttributeChanged(imp->associatedAttributeName()); return result; } -JSValue* JSSVGPathSegList::replaceItem(ExecState* exec, const List& args) +JSValue* JSSVGPathSegList::replaceItem(ExecState* exec, const ArgList& args) { ExceptionCode ec = 0; - SVGPathSeg* newItem = toSVGPathSeg(args[0]); + SVGPathSeg* newItem = toSVGPathSeg(args.at(exec, 0)); bool indexOk; - unsigned index = args[1]->toInt32(exec, indexOk); + unsigned index = args.at(exec, 1)->toInt32(exec, indexOk); if (!indexOk) { setDOMException(exec, TYPE_MISMATCH_ERR); return jsUndefined(); @@ -118,19 +118,19 @@ JSValue* JSSVGPathSegList::replaceItem(ExecState* exec, const List& args) SVGPathSegList* imp = static_cast<SVGPathSegList*>(impl()); - KJS::JSValue* result = toJS(exec, WTF::getPtr(imp->replaceItem(newItem, index, ec)), m_context.get()); + JSC::JSValue* result = toJS(exec, WTF::getPtr(imp->replaceItem(newItem, index, ec)), m_context.get()); setDOMException(exec, ec); m_context->svgAttributeChanged(imp->associatedAttributeName()); return result; } -JSValue* JSSVGPathSegList::removeItem(ExecState* exec, const List& args) +JSValue* JSSVGPathSegList::removeItem(ExecState* exec, const ArgList& args) { ExceptionCode ec = 0; bool indexOk; - unsigned index = args[0]->toInt32(exec, indexOk); + unsigned index = args.at(exec, 0)->toInt32(exec, indexOk); if (!indexOk) { setDOMException(exec, TYPE_MISMATCH_ERR); return jsUndefined(); @@ -140,21 +140,21 @@ JSValue* JSSVGPathSegList::removeItem(ExecState* exec, const List& args) RefPtr<SVGPathSeg> obj(imp->removeItem(index, ec)); - KJS::JSValue* result = toJS(exec, obj.get(), m_context.get()); + JSC::JSValue* result = toJS(exec, obj.get(), m_context.get()); setDOMException(exec, ec); m_context->svgAttributeChanged(imp->associatedAttributeName()); return result; } -JSValue* JSSVGPathSegList::appendItem(ExecState* exec, const List& args) +JSValue* JSSVGPathSegList::appendItem(ExecState* exec, const ArgList& args) { ExceptionCode ec = 0; - SVGPathSeg* newItem = toSVGPathSeg(args[0]); + SVGPathSeg* newItem = toSVGPathSeg(args.at(exec, 0)); SVGPathSegList* imp = static_cast<SVGPathSegList*>(impl()); - KJS::JSValue* result = toJS(exec, WTF::getPtr(imp->appendItem(newItem, ec)), m_context.get()); + JSC::JSValue* result = toJS(exec, WTF::getPtr(imp->appendItem(newItem, ec)), m_context.get()); setDOMException(exec, ec); m_context->svgAttributeChanged(imp->associatedAttributeName()); diff --git a/WebCore/bindings/js/JSSVGPointListCustom.cpp b/WebCore/bindings/js/JSSVGPointListCustom.cpp index 2c7127f..6c13123 100644 --- a/WebCore/bindings/js/JSSVGPointListCustom.cpp +++ b/WebCore/bindings/js/JSSVGPointListCustom.cpp @@ -1,5 +1,6 @@ /* * Copyright (C) 2006, 2007, 2008 Nikolas Zimmermann <zimmermann@kde.org> + * Copyright (C) 2008 Apple Inc. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public @@ -22,167 +23,129 @@ #if ENABLE(SVG) #include "JSSVGPointList.h" -#include "Document.h" -#include "Frame.h" #include "JSSVGPoint.h" -#include "SVGDocumentExtensions.h" #include "SVGPointList.h" -#include "SVGStyledElement.h" -#include <wtf/Assertions.h> - -using namespace KJS; +using namespace JSC; namespace WebCore { -JSValue* JSSVGPointList::clear(ExecState* exec, const List&) -{ - ExceptionCode ec = 0; +typedef SVGPODListItem<FloatPoint> PODListItem; +typedef SVGList<RefPtr<PODListItem> > SVGPointListBase; - SVGPointList* imp = static_cast<SVGPointList*>(impl()); - imp->clear(ec); - setDOMException(exec, ec); +static JSValue* finishGetter(ExecState* exec, ExceptionCode& ec, SVGElement* context, SVGPointList* list, PassRefPtr<PODListItem > item) +{ + if (ec) { + setDOMException(exec, ec); + return jsUndefined(); + } + return toJS(exec, JSSVGPODTypeWrapperCreatorForList<FloatPoint>::create(item.get(), list->associatedAttributeName()).get(), context); +} - m_context->svgAttributeChanged(imp->associatedAttributeName()); +static JSValue* finishSetter(ExecState* exec, ExceptionCode& ec, SVGElement* context, SVGPointList* list, PassRefPtr<PODListItem > item) +{ + if (ec) { + setDOMException(exec, ec); + return jsUndefined(); + } + const QualifiedName& attributeName = list->associatedAttributeName(); + context->svgAttributeChanged(attributeName); + return toJS(exec, JSSVGPODTypeWrapperCreatorForList<FloatPoint>::create(item.get(), attributeName).get(), context); +} - return jsUndefined(); +static JSValue* finishSetterReadOnlyResult(ExecState* exec, ExceptionCode& ec, SVGElement* context, SVGPointList* list, PassRefPtr<PODListItem> item) +{ + if (ec) { + setDOMException(exec, ec); + return jsUndefined(); + } + context->svgAttributeChanged(list->associatedAttributeName()); + return toJS(exec, JSSVGStaticPODTypeWrapper<FloatPoint>::create(*item).get(), context); } -JSValue* JSSVGPointList::initialize(ExecState* exec, const List& args) +JSValue* JSSVGPointList::clear(ExecState* exec, const ArgList&) { ExceptionCode ec = 0; - FloatPoint newItem = toSVGPoint(args[0]); - - SVGPointList* imp = static_cast<SVGPointList*>(impl()); - SVGList<RefPtr<SVGPODListItem<FloatPoint> > >* listImp = imp; - - SVGPODListItem<FloatPoint>* listItem = listImp->initialize(new SVGPODListItem<FloatPoint>(newItem), ec).get(); - JSSVGPODTypeWrapperCreatorForList<FloatPoint>* obj = new JSSVGPODTypeWrapperCreatorForList<FloatPoint>(listItem, imp->associatedAttributeName()); - - KJS::JSValue* result = toJS(exec, obj, m_context.get()); + impl()->clear(ec); setDOMException(exec, ec); - - m_context->svgAttributeChanged(imp->associatedAttributeName()); - - return result; + m_context->svgAttributeChanged(impl()->associatedAttributeName()); + return jsUndefined(); } -JSValue* JSSVGPointList::getItem(ExecState* exec, const List& args) +JSValue* JSSVGPointList::initialize(ExecState* exec, const ArgList& args) { ExceptionCode ec = 0; + SVGPointListBase* listImp = impl(); + return finishSetter(exec, ec, context(), impl(), + listImp->initialize(PODListItem::copy(toSVGPoint(args.at(exec, 0))), ec)); +} +JSValue* JSSVGPointList::getItem(ExecState* exec, const ArgList& args) +{ bool indexOk; - unsigned index = args[0]->toInt32(exec, indexOk); + unsigned index = args.at(exec, 0)->toUInt32(exec, indexOk); if (!indexOk) { setDOMException(exec, TYPE_MISMATCH_ERR); return jsUndefined(); } - SVGPointList* imp = static_cast<SVGPointList*>(impl()); - SVGList<RefPtr<SVGPODListItem<FloatPoint> > >* listImp = imp; - - SVGPODListItem<FloatPoint>* listItem = listImp->getItem(index, ec).get(); - JSSVGPODTypeWrapperCreatorForList<FloatPoint>* obj = new JSSVGPODTypeWrapperCreatorForList<FloatPoint>(listItem, imp->associatedAttributeName()); - - KJS::JSValue* result = toJS(exec, obj, m_context.get()); - setDOMException(exec, ec); - return result; + ExceptionCode ec = 0; + SVGPointListBase* listImp = impl(); + return finishGetter(exec, ec, context(), impl(), + listImp->getItem(index, ec)); } -JSValue* JSSVGPointList::insertItemBefore(ExecState* exec, const List& args) +JSValue* JSSVGPointList::insertItemBefore(ExecState* exec, const ArgList& args) { - ExceptionCode ec = 0; - FloatPoint newItem = toSVGPoint(args[0]); - bool indexOk; - unsigned index = args[1]->toInt32(exec, indexOk); + unsigned index = args.at(exec, 1)->toUInt32(exec, indexOk); if (!indexOk) { setDOMException(exec, TYPE_MISMATCH_ERR); return jsUndefined(); } - SVGPointList* imp = static_cast<SVGPointList*>(impl()); - SVGList<RefPtr<SVGPODListItem<FloatPoint> > >* listImp = imp; - - SVGPODListItem<FloatPoint>* listItem = listImp->insertItemBefore(new SVGPODListItem<FloatPoint>(newItem), index, ec).get(); - JSSVGPODTypeWrapperCreatorForList<FloatPoint>* obj = new JSSVGPODTypeWrapperCreatorForList<FloatPoint>(listItem, imp->associatedAttributeName()); - - KJS::JSValue* result = toJS(exec, obj, m_context.get()); - setDOMException(exec, ec); - - m_context->svgAttributeChanged(imp->associatedAttributeName()); - - return result; + ExceptionCode ec = 0; + SVGPointListBase* listImp = impl(); + return finishSetter(exec, ec, context(), impl(), + listImp->insertItemBefore(PODListItem::copy(toSVGPoint(args.at(exec, 0))), index, ec)); } -JSValue* JSSVGPointList::replaceItem(ExecState* exec, const List& args) +JSValue* JSSVGPointList::replaceItem(ExecState* exec, const ArgList& args) { - ExceptionCode ec = 0; - FloatPoint newItem = toSVGPoint(args[0]); - bool indexOk; - unsigned index = args[1]->toInt32(exec, indexOk); + unsigned index = args.at(exec, 1)->toInt32(exec, indexOk); if (!indexOk) { setDOMException(exec, TYPE_MISMATCH_ERR); return jsUndefined(); } - SVGPointList* imp = static_cast<SVGPointList*>(impl()); - SVGList<RefPtr<SVGPODListItem<FloatPoint> > >* listImp = imp; - - SVGPODListItem<FloatPoint>* listItem = listImp->replaceItem(new SVGPODListItem<FloatPoint>(newItem), index, ec).get(); - JSSVGPODTypeWrapperCreatorForList<FloatPoint>* obj = new JSSVGPODTypeWrapperCreatorForList<FloatPoint>(listItem, imp->associatedAttributeName()); - - KJS::JSValue* result = toJS(exec, obj, m_context.get()); - setDOMException(exec, ec); - - m_context->svgAttributeChanged(imp->associatedAttributeName()); - - return result; + ExceptionCode ec = 0; + SVGPointListBase* listImp = impl(); + return finishSetter(exec, ec, context(), impl(), + listImp->replaceItem(PODListItem::copy(toSVGPoint(args.at(exec, 0))), index, ec)); } -JSValue* JSSVGPointList::removeItem(ExecState* exec, const List& args) +JSValue* JSSVGPointList::removeItem(ExecState* exec, const ArgList& args) { - ExceptionCode ec = 0; - bool indexOk; - unsigned index = args[0]->toInt32(exec, indexOk); + unsigned index = args.at(exec, 0)->toInt32(exec, indexOk); if (!indexOk) { setDOMException(exec, TYPE_MISMATCH_ERR); return jsUndefined(); } - SVGPointList* imp = static_cast<SVGPointList*>(impl()); - SVGList<RefPtr<SVGPODListItem<FloatPoint> > >* listImp = imp; - - RefPtr<SVGPODListItem<FloatPoint> > listItem(listImp->removeItem(index, ec)); - JSSVGPODTypeWrapper<FloatPoint>* obj = new JSSVGPODTypeWrapperCreatorReadOnly<FloatPoint>(*listItem.get()); - - KJS::JSValue* result = toJS(exec, obj, m_context.get()); - setDOMException(exec, ec); - - m_context->svgAttributeChanged(imp->associatedAttributeName()); - - return result; + ExceptionCode ec = 0; + SVGPointListBase* listImp = impl(); + return finishSetterReadOnlyResult(exec, ec, context(), impl(), + listImp->removeItem(index, ec)); } -JSValue* JSSVGPointList::appendItem(ExecState* exec, const List& args) +JSValue* JSSVGPointList::appendItem(ExecState* exec, const ArgList& args) { ExceptionCode ec = 0; - FloatPoint newItem = toSVGPoint(args[0]); - - SVGPointList* imp = static_cast<SVGPointList*>(impl()); - SVGList<RefPtr<SVGPODListItem<FloatPoint> > >* listImp = imp; - - SVGPODListItem<FloatPoint>* listItem = listImp->appendItem(new SVGPODListItem<FloatPoint>(newItem), ec).get(); - JSSVGPODTypeWrapperCreatorForList<FloatPoint>* obj = new JSSVGPODTypeWrapperCreatorForList<FloatPoint>(listItem, imp->associatedAttributeName()); - - KJS::JSValue* result = toJS(exec, obj, m_context.get()); - setDOMException(exec, ec); - - m_context->svgAttributeChanged(imp->associatedAttributeName()); - - return result; + SVGPointListBase* listImp = impl(); + return finishSetter(exec, ec, context(), impl(), + listImp->appendItem(PODListItem::copy(toSVGPoint(args.at(exec, 0))), ec)); } } diff --git a/WebCore/bindings/js/JSSVGTransformListCustom.cpp b/WebCore/bindings/js/JSSVGTransformListCustom.cpp index 1251131..57cc662 100644 --- a/WebCore/bindings/js/JSSVGTransformListCustom.cpp +++ b/WebCore/bindings/js/JSSVGTransformListCustom.cpp @@ -1,5 +1,6 @@ /* * Copyright (C) 2007, 2008 Nikolas Zimmermann <zimmermann@kde.org> + * Copyright (C) 2008 Apple Inc. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public @@ -22,167 +23,129 @@ #if ENABLE(SVG) #include "JSSVGTransformList.h" -#include "Document.h" -#include "Frame.h" #include "JSSVGTransform.h" -#include "SVGDocumentExtensions.h" #include "SVGTransformList.h" -#include "SVGStyledElement.h" -#include <wtf/Assertions.h> - -using namespace KJS; +using namespace JSC; namespace WebCore { -JSValue* JSSVGTransformList::clear(ExecState* exec, const List&) -{ - ExceptionCode ec = 0; +typedef SVGPODListItem<SVGTransform> PODListItem; +typedef SVGList<RefPtr<PODListItem> > SVGTransformListBase; - SVGTransformList* imp = static_cast<SVGTransformList*>(impl()); - imp->clear(ec); - setDOMException(exec, ec); +static JSValue* finishGetter(ExecState* exec, ExceptionCode& ec, SVGElement* context, SVGTransformList* list, PassRefPtr<PODListItem> item) +{ + if (ec) { + setDOMException(exec, ec); + return jsUndefined(); + } + return toJS(exec, JSSVGPODTypeWrapperCreatorForList<SVGTransform>::create(item.get(), list->associatedAttributeName()).get(), context); +} - m_context->svgAttributeChanged(imp->associatedAttributeName()); +static JSValue* finishSetter(ExecState* exec, ExceptionCode& ec, SVGElement* context, SVGTransformList* list, PassRefPtr<PODListItem> item) +{ + if (ec) { + setDOMException(exec, ec); + return jsUndefined(); + } + const QualifiedName& attributeName = list->associatedAttributeName(); + context->svgAttributeChanged(attributeName); + return toJS(exec, JSSVGPODTypeWrapperCreatorForList<SVGTransform>::create(item.get(), attributeName).get(), context); +} - return jsUndefined(); +static JSValue* finishSetterReadOnlyResult(ExecState* exec, ExceptionCode& ec, SVGElement* context, SVGTransformList* list, PassRefPtr<PODListItem> item) +{ + if (ec) { + setDOMException(exec, ec); + return jsUndefined(); + } + context->svgAttributeChanged(list->associatedAttributeName()); + return toJS(exec, JSSVGStaticPODTypeWrapper<SVGTransform>::create(*item).get(), context); } -JSValue* JSSVGTransformList::initialize(ExecState* exec, const List& args) +JSValue* JSSVGTransformList::clear(ExecState* exec, const ArgList&) { ExceptionCode ec = 0; - SVGTransform newItem = toSVGTransform(args[0]); - - SVGTransformList* imp = static_cast<SVGTransformList*>(impl()); - SVGList<RefPtr<SVGPODListItem<SVGTransform> > >* listImp = imp; - - SVGPODListItem<SVGTransform>* listItem = listImp->initialize(new SVGPODListItem<SVGTransform>(newItem), ec).get(); - JSSVGPODTypeWrapperCreatorForList<SVGTransform>* obj = new JSSVGPODTypeWrapperCreatorForList<SVGTransform>(listItem, imp->associatedAttributeName()); - - KJS::JSValue* result = toJS(exec, obj, m_context.get()); + impl()->clear(ec); setDOMException(exec, ec); - - m_context->svgAttributeChanged(imp->associatedAttributeName()); - - return result; + m_context->svgAttributeChanged(impl()->associatedAttributeName()); + return jsUndefined(); } -JSValue* JSSVGTransformList::getItem(ExecState* exec, const List& args) +JSValue* JSSVGTransformList::initialize(ExecState* exec, const ArgList& args) { ExceptionCode ec = 0; + SVGTransformListBase* listImp = impl(); + return finishSetter(exec, ec, context(), impl(), + listImp->initialize(PODListItem::copy(toSVGTransform(args.at(exec, 0))), ec)); +} +JSValue* JSSVGTransformList::getItem(ExecState* exec, const ArgList& args) +{ bool indexOk; - unsigned index = args[0]->toInt32(exec, indexOk); + unsigned index = args.at(exec, 0)->toUInt32(exec, indexOk); if (!indexOk) { setDOMException(exec, TYPE_MISMATCH_ERR); return jsUndefined(); } - SVGTransformList* imp = static_cast<SVGTransformList*>(impl()); - SVGList<RefPtr<SVGPODListItem<SVGTransform> > >* listImp = imp; - - SVGPODListItem<SVGTransform>* listItem = listImp->getItem(index, ec).get(); - JSSVGPODTypeWrapperCreatorForList<SVGTransform>* obj = new JSSVGPODTypeWrapperCreatorForList<SVGTransform>(listItem, imp->associatedAttributeName()); - - KJS::JSValue* result = toJS(exec, obj, m_context.get()); - setDOMException(exec, ec); - return result; + ExceptionCode ec = 0; + SVGTransformListBase* listImp = impl(); + return finishGetter(exec, ec, context(), impl(), + listImp->getItem(index, ec)); } -JSValue* JSSVGTransformList::insertItemBefore(ExecState* exec, const List& args) +JSValue* JSSVGTransformList::insertItemBefore(ExecState* exec, const ArgList& args) { - ExceptionCode ec = 0; - SVGTransform newItem = toSVGTransform(args[0]); - bool indexOk; - unsigned index = args[1]->toInt32(exec, indexOk); + unsigned index = args.at(exec, 1)->toUInt32(exec, indexOk); if (!indexOk) { setDOMException(exec, TYPE_MISMATCH_ERR); return jsUndefined(); } - SVGTransformList* imp = static_cast<SVGTransformList*>(impl()); - SVGList<RefPtr<SVGPODListItem<SVGTransform> > >* listImp = imp; - - SVGPODListItem<SVGTransform>* listItem = listImp->insertItemBefore(new SVGPODListItem<SVGTransform>(newItem), index, ec).get(); - JSSVGPODTypeWrapperCreatorForList<SVGTransform>* obj = new JSSVGPODTypeWrapperCreatorForList<SVGTransform>(listItem, imp->associatedAttributeName()); - - KJS::JSValue* result = toJS(exec, obj, m_context.get()); - setDOMException(exec, ec); - - m_context->svgAttributeChanged(imp->associatedAttributeName()); - - return result; + ExceptionCode ec = 0; + SVGTransformListBase* listImp = impl(); + return finishSetter(exec, ec, context(), impl(), + listImp->insertItemBefore(PODListItem::copy(toSVGTransform(args.at(exec, 0))), index, ec)); } -JSValue* JSSVGTransformList::replaceItem(ExecState* exec, const List& args) +JSValue* JSSVGTransformList::replaceItem(ExecState* exec, const ArgList& args) { - ExceptionCode ec = 0; - SVGTransform newItem = toSVGTransform(args[0]); - bool indexOk; - unsigned index = args[1]->toInt32(exec, indexOk); + unsigned index = args.at(exec, 1)->toUInt32(exec, indexOk); if (!indexOk) { setDOMException(exec, TYPE_MISMATCH_ERR); return jsUndefined(); } - SVGTransformList* imp = static_cast<SVGTransformList*>(impl()); - SVGList<RefPtr<SVGPODListItem<SVGTransform> > >* listImp = imp; - - SVGPODListItem<SVGTransform>* listItem = listImp->replaceItem(new SVGPODListItem<SVGTransform>(newItem), index, ec).get(); - JSSVGPODTypeWrapperCreatorForList<SVGTransform>* obj = new JSSVGPODTypeWrapperCreatorForList<SVGTransform>(listItem, imp->associatedAttributeName()); - - KJS::JSValue* result = toJS(exec, obj, m_context.get()); - setDOMException(exec, ec); - - m_context->svgAttributeChanged(imp->associatedAttributeName()); - - return result; + ExceptionCode ec = 0; + SVGTransformListBase* listImp = impl(); + return finishSetter(exec, ec, context(), impl(), + listImp->replaceItem(PODListItem::copy(toSVGTransform(args.at(exec, 0))), index, ec)); } -JSValue* JSSVGTransformList::removeItem(ExecState* exec, const List& args) +JSValue* JSSVGTransformList::removeItem(ExecState* exec, const ArgList& args) { - ExceptionCode ec = 0; - bool indexOk; - unsigned index = args[0]->toInt32(exec, indexOk); + unsigned index = args.at(exec, 0)->toUInt32(exec, indexOk); if (!indexOk) { setDOMException(exec, TYPE_MISMATCH_ERR); return jsUndefined(); } - SVGTransformList* imp = static_cast<SVGTransformList*>(impl()); - SVGList<RefPtr<SVGPODListItem<SVGTransform> > >* listImp = imp; - - RefPtr<SVGPODListItem<SVGTransform> > listItem(listImp->removeItem(index, ec)); - JSSVGPODTypeWrapper<SVGTransform>* obj = new JSSVGPODTypeWrapperCreatorReadOnly<SVGTransform>(*listItem.get()); - - KJS::JSValue* result = toJS(exec, obj, m_context.get()); - setDOMException(exec, ec); - - m_context->svgAttributeChanged(imp->associatedAttributeName()); - - return result; + ExceptionCode ec = 0; + SVGTransformListBase* listImp = impl(); + return finishSetterReadOnlyResult(exec, ec, context(), impl(), + listImp->removeItem(index, ec)); } -JSValue* JSSVGTransformList::appendItem(ExecState* exec, const List& args) +JSValue* JSSVGTransformList::appendItem(ExecState* exec, const ArgList& args) { ExceptionCode ec = 0; - SVGTransform newItem = toSVGTransform(args[0]); - - SVGTransformList* imp = static_cast<SVGTransformList*>(impl()); - SVGList<RefPtr<SVGPODListItem<SVGTransform> > >* listImp = imp; - - SVGPODListItem<SVGTransform>* listItem = listImp->appendItem(new SVGPODListItem<SVGTransform>(newItem), ec).get(); - JSSVGPODTypeWrapperCreatorForList<SVGTransform>* obj = new JSSVGPODTypeWrapperCreatorForList<SVGTransform>(listItem, imp->associatedAttributeName()); - - KJS::JSValue* result = toJS(exec, obj, m_context.get()); - setDOMException(exec, ec); - - m_context->svgAttributeChanged(imp->associatedAttributeName()); - - return result; + SVGTransformListBase* listImp = impl(); + return finishSetter(exec, ec, context(), impl(), + listImp->appendItem(PODListItem::copy(toSVGTransform(args.at(exec, 0))), ec)); } } diff --git a/WebCore/bindings/js/JSStorageCustom.cpp b/WebCore/bindings/js/JSStorageCustom.cpp new file mode 100644 index 0000000..1966392 --- /dev/null +++ b/WebCore/bindings/js/JSStorageCustom.cpp @@ -0,0 +1,103 @@ +/* + * Copyright (C) 2008 Apple Inc. All Rights Reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "JSStorageCustom.h" + +#if ENABLE(DOM_STORAGE) + +#include "PlatformString.h" +#include <runtime/PropertyNameArray.h> +#include "Storage.h" + +using namespace JSC; + +namespace WebCore { + +bool JSStorage::canGetItemsForName(ExecState*, Storage* impl, const Identifier& propertyName) +{ + return impl->contains(propertyName); +} + +JSValue* JSStorage::nameGetter(ExecState* exec, const Identifier& propertyName, const PropertySlot& slot) +{ + JSStorage* thisObj = static_cast<JSStorage*>(asObject(slot.slotBase())); + return jsStringOrNull(exec, thisObj->impl()->getItem(propertyName)); +} + +bool JSStorage::deleteProperty(ExecState* exec, const Identifier& propertyName) +{ + // Only perform the custom delete if the object doesn't have a native property by this name. + // Since hasProperty() would end up calling canGetItemsForName() and be fooled, we need to check + // the native property slots manually. + PropertySlot slot; + if (getStaticValueSlot<JSStorage, Base>(exec, s_info.propHashTable(exec), this, propertyName, slot)) + return false; + + JSValue* prototype = this->prototype(); + if (prototype->isObject() && asObject(prototype)->hasProperty(exec, propertyName)) + return false; + + m_impl->removeItem(propertyName); + return true; +} + +bool JSStorage::customGetPropertyNames(ExecState* exec, PropertyNameArray& propertyNames) +{ + ExceptionCode ec; + unsigned length = m_impl->length(); + for (unsigned i = 0; i < length; ++i) + propertyNames.add(Identifier(exec, m_impl->key(i, ec))); + + return false; +} + +bool JSStorage::customPut(ExecState* exec, const Identifier& propertyName, JSValue* value, PutPropertySlot&) +{ + // Only perform the custom put if the object doesn't have a native property by this name. + // Since hasProperty() would end up calling canGetItemsForName() and be fooled, we need to check + // the native property slots manually. + PropertySlot slot; + if (getStaticValueSlot<JSStorage, Base>(exec, s_info.propHashTable(exec), this, propertyName, slot)) + return false; + + JSValue* prototype = this->prototype(); + if (prototype->isObject() && asObject(prototype)->hasProperty(exec, propertyName)) + return false; + + String stringValue = valueToStringWithNullCheck(exec, value); + if (exec->hadException()) + return true; + + ExceptionCode ec = 0; + impl()->setItem(propertyName, stringValue, ec); + setDOMException(exec, ec); + + return true; +} + +} // namespace WebCore + +#endif // ENABLE(DOM_STORAGE) diff --git a/WebCore/bindings/js/JSStorageCustom.h b/WebCore/bindings/js/JSStorageCustom.h new file mode 100644 index 0000000..45f62df --- /dev/null +++ b/WebCore/bindings/js/JSStorageCustom.h @@ -0,0 +1,31 @@ +/* + * Copyright (C) 2008 Apple Inc. All Rights Reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef JSStorageCustom_h +#define JSStorageCustom_h + +#include "JSStorage.h" + +#endif // JSStorageCustom_h diff --git a/WebCore/bindings/js/JSStyleSheetCustom.cpp b/WebCore/bindings/js/JSStyleSheetCustom.cpp index 4122831..c9914ae 100644 --- a/WebCore/bindings/js/JSStyleSheetCustom.cpp +++ b/WebCore/bindings/js/JSStyleSheetCustom.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2007 Apple Inc. All rights reserved. + * Copyright (C) 2007, 2008 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -28,9 +28,9 @@ #include "CSSStyleSheet.h" #include "JSCSSStyleSheet.h" -#include "StyleSheet.h" +#include "JSNode.h" -using namespace KJS; +using namespace JSC; namespace WebCore { @@ -39,17 +39,33 @@ JSValue* toJS(ExecState* exec, StyleSheet* styleSheet) if (!styleSheet) return jsNull(); - DOMObject* ret = ScriptInterpreter::getDOMObject(styleSheet); - if (ret) - return ret; + DOMObject* wrapper = getCachedDOMObjectWrapper(exec->globalData(), styleSheet); + if (wrapper) + return wrapper; if (styleSheet->isCSSStyleSheet()) - ret = new JSCSSStyleSheet(JSCSSStyleSheetPrototype::self(exec), static_cast<CSSStyleSheet*>(styleSheet)); + wrapper = CREATE_DOM_OBJECT_WRAPPER(exec, CSSStyleSheet, styleSheet); else - ret = new JSStyleSheet(JSStyleSheetPrototype::self(exec), styleSheet); + wrapper = CREATE_DOM_OBJECT_WRAPPER(exec, StyleSheet, styleSheet); - ScriptInterpreter::putDOMObject(styleSheet, ret); - return ret; + return wrapper; +} + +void JSStyleSheet::mark() +{ + Base::mark(); + + // This prevents us from having a style sheet with a dangling ownerNode pointer. + // A better solution would be to handle this on the DOM side -- if the style sheet + // is kept around, then we want the node to stay around too. One possibility would + // be to make ref/deref on the style sheet ref/deref the node instead, but there's + // a lot of disentangling of the CSS DOM objects that would need to happen first. + if (Node* ownerNode = impl()->ownerNode()) { + if (JSNode* ownerNodeWrapper = getCachedDOMNodeWrapper(ownerNode->document(), ownerNode)) { + if (!ownerNodeWrapper->marked()) + ownerNodeWrapper->mark(); + } + } } } // namespace WebCore diff --git a/WebCore/bindings/js/JSStyleSheetListCustom.cpp b/WebCore/bindings/js/JSStyleSheetListCustom.cpp index aa4014f..2a24fe2 100644 --- a/WebCore/bindings/js/JSStyleSheetListCustom.cpp +++ b/WebCore/bindings/js/JSStyleSheetListCustom.cpp @@ -1,4 +1,3 @@ - /* * Copyright (C) 2007 Apple Inc. All rights reserved. * @@ -32,16 +31,18 @@ #include "StyleSheet.h" #include "StyleSheetList.h" +using namespace JSC; + namespace WebCore { -bool JSStyleSheetList::canGetItemsForName(KJS::ExecState*, StyleSheetList* styleSheetList, const KJS::Identifier& propertyName) +bool JSStyleSheetList::canGetItemsForName(ExecState*, StyleSheetList* styleSheetList, const Identifier& propertyName) { return styleSheetList->getNamedItem(propertyName); } -KJS::JSValue* JSStyleSheetList::nameGetter(KJS::ExecState* exec, KJS::JSObject*, const KJS::Identifier& propertyName, const KJS::PropertySlot& slot) +JSValue* JSStyleSheetList::nameGetter(ExecState* exec, const Identifier& propertyName, const PropertySlot& slot) { - JSStyleSheetList* thisObj = static_cast<JSStyleSheetList*>(slot.slotBase()); + JSStyleSheetList* thisObj = static_cast<JSStyleSheetList*>(asObject(slot.slotBase())); HTMLStyleElement* element = thisObj->impl()->getNamedItem(propertyName); ASSERT(element); return toJS(exec, element->sheet()); diff --git a/WebCore/bindings/js/JSTextCustom.cpp b/WebCore/bindings/js/JSTextCustom.cpp new file mode 100644 index 0000000..245b4bd --- /dev/null +++ b/WebCore/bindings/js/JSTextCustom.cpp @@ -0,0 +1,43 @@ +/* + * Copyright (C) 2008 Apple Inc. All Rights Reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "JSText.h" + +#include "Text.h" + +using namespace JSC; + +namespace WebCore { + +JSValue* toJSNewlyCreated(ExecState* exec, Text* text) +{ + if (!text) + return jsNull(); + + return CREATE_DOM_NODE_WRAPPER(exec, Text, text); +} + +} // namespace WebCore diff --git a/WebCore/bindings/js/JSTreeWalkerCustom.cpp b/WebCore/bindings/js/JSTreeWalkerCustom.cpp index c73fe40..9822e1a 100644 --- a/WebCore/bindings/js/JSTreeWalkerCustom.cpp +++ b/WebCore/bindings/js/JSTreeWalkerCustom.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2006 Apple Computer, Inc. + * Copyright (C) 2006, 2008 Apple Inc. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public @@ -16,12 +16,17 @@ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ + #include "config.h" #include "JSTreeWalker.h" +#include "JSNode.h" +#include "Node.h" #include "NodeFilter.h" #include "TreeWalker.h" +using namespace JSC; + namespace WebCore { void JSTreeWalker::mark() @@ -32,4 +37,60 @@ void JSTreeWalker::mark() DOMObject::mark(); } +JSValue* JSTreeWalker::parentNode(ExecState* exec, const ArgList& args) +{ + Node* node = impl()->parentNode(exec); + if (exec->hadException()) + return jsUndefined(); + return toJS(exec, node); +} + +JSValue* JSTreeWalker::firstChild(ExecState* exec, const ArgList& args) +{ + Node* node = impl()->firstChild(exec); + if (exec->hadException()) + return jsUndefined(); + return toJS(exec, node); +} + +JSValue* JSTreeWalker::lastChild(ExecState* exec, const ArgList& args) +{ + Node* node = impl()->lastChild(exec); + if (exec->hadException()) + return jsUndefined(); + return toJS(exec, node); +} + +JSValue* JSTreeWalker::nextSibling(ExecState* exec, const ArgList& args) +{ + Node* node = impl()->nextSibling(exec); + if (exec->hadException()) + return jsUndefined(); + return toJS(exec, node); +} + +JSValue* JSTreeWalker::previousSibling(ExecState* exec, const ArgList& args) +{ + Node* node = impl()->previousSibling(exec); + if (exec->hadException()) + return jsUndefined(); + return toJS(exec, node); +} + +JSValue* JSTreeWalker::previousNode(ExecState* exec, const ArgList& args) +{ + Node* node = impl()->previousNode(exec); + if (exec->hadException()) + return jsUndefined(); + return toJS(exec, node); +} + +JSValue* JSTreeWalker::nextNode(ExecState* exec, const ArgList& args) +{ + Node* node = impl()->nextNode(exec); + if (exec->hadException()) + return jsUndefined(); + return toJS(exec, node); +} + } diff --git a/WebCore/bindings/js/JSXMLHttpRequest.cpp b/WebCore/bindings/js/JSXMLHttpRequest.cpp deleted file mode 100644 index 1d9b281..0000000 --- a/WebCore/bindings/js/JSXMLHttpRequest.cpp +++ /dev/null @@ -1,403 +0,0 @@ -/* - * Copyright (C) 2004, 2007 Apple Inc. All rights reserved. - * Copyright (C) 2005, 2006 Alexey Proskuryakov <ap@nypop.com> - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#include "config.h" -#include "JSXMLHttpRequest.h" - -#include "DOMWindow.h" -#include "Event.h" -#include "Frame.h" -#include "FrameLoader.h" -#include "HTMLDocument.h" -#include "JSDocument.h" -#include "JSEvent.h" -#include "XMLHttpRequest.h" -#include "kjs_events.h" -#include "kjs_window.h" - -#include "JSXMLHttpRequest.lut.h" - -namespace KJS { - -using namespace WebCore; - -////////////////////// JSXMLHttpRequest Object //////////////////////// - -/* Source for JSXMLHttpRequestPrototypeTable. -@begin JSXMLHttpRequestPrototypeTable 7 - abort jsXMLHttpRequestPrototypeFunctionAbort DontDelete|Function 0 - getAllResponseHeaders jsXMLHttpRequestPrototypeFunctionGetAllResponseHeaders DontDelete|Function 0 - getResponseHeader jsXMLHttpRequestPrototypeFunctionGetResponseHeader DontDelete|Function 1 - open jsXMLHttpRequestPrototypeFunctionOpen DontDelete|Function 5 - overrideMimeType jsXMLHttpRequestPrototypeFunctionOverrideMIMEType DontDelete|Function 1 - send jsXMLHttpRequestPrototypeFunctionSend DontDelete|Function 1 - setRequestHeader jsXMLHttpRequestPrototypeFunctionSetRequestHeader DontDelete|Function 2 -# from the EventTarget interface -# FIXME: add DOM3 EventTarget methods (addEventListenerNS, removeEventListenerNS). - addEventListener jsXMLHttpRequestPrototypeFunctionAddEventListener DontDelete|Function 3 - removeEventListener jsXMLHttpRequestPrototypeFunctionRemoveEventListener DontDelete|Function 3 - dispatchEvent jsXMLHttpRequestPrototypeFunctionDispatchEvent DontDelete|Function 1 -@end -*/ -KJS_DEFINE_PROTOTYPE(JSXMLHttpRequestPrototype) -KJS_IMPLEMENT_PROTOTYPE("JSXMLHttpRequest", JSXMLHttpRequestPrototype) - -JSXMLHttpRequestConstructorImp::JSXMLHttpRequestConstructorImp(ExecState* exec, Document* d) - : DOMObject(exec->lexicalGlobalObject()->objectPrototype()) - , doc(d) -{ - putDirect(exec->propertyNames().prototype, JSXMLHttpRequestPrototype::self(exec), None); -} - -bool JSXMLHttpRequestConstructorImp::implementsConstruct() const -{ - return true; -} - -JSObject* JSXMLHttpRequestConstructorImp::construct(ExecState* exec, const List&) -{ - return new JSXMLHttpRequest(JSXMLHttpRequestPrototype::self(exec), doc.get()); -} - -const ClassInfo JSXMLHttpRequest::info = { "JSXMLHttpRequest", 0, &JSXMLHttpRequestTable }; - -/* Source for JSXMLHttpRequestTable. -@begin JSXMLHttpRequestTable 7 - readyState JSXMLHttpRequest::ReadyState DontDelete|ReadOnly - responseText JSXMLHttpRequest::ResponseText DontDelete|ReadOnly - responseXML JSXMLHttpRequest::ResponseXML DontDelete|ReadOnly - status JSXMLHttpRequest::Status DontDelete|ReadOnly - statusText JSXMLHttpRequest::StatusText DontDelete|ReadOnly - onreadystatechange JSXMLHttpRequest::Onreadystatechange DontDelete - onload JSXMLHttpRequest::Onload DontDelete -@end -*/ - -bool JSXMLHttpRequest::getOwnPropertySlot(ExecState* exec, const Identifier& propertyName, PropertySlot& slot) -{ - return getStaticValueSlot<JSXMLHttpRequest, DOMObject>(exec, &JSXMLHttpRequestTable, this, propertyName, slot); -} - -JSValue* JSXMLHttpRequest::getValueProperty(ExecState* exec, int token) const -{ - ExceptionCode ec = 0; - - switch (token) { - case ReadyState: - return jsNumber(m_impl->getReadyState()); - case ResponseText: { - JSValue* result = jsOwnedStringOrNull(m_impl->getResponseText(ec)); - setDOMException(exec, ec); - return result; - } - case ResponseXML: { - Document* responseXML = m_impl->getResponseXML(ec); - setDOMException(exec, ec); - if (responseXML) - return toJS(exec, responseXML); - - return jsNull(); - } - case Status: { - JSValue* result = jsNumber(m_impl->getStatus(ec)); - setDOMException(exec, ec); - return result; - } - case StatusText: { - JSValue* result = jsString(m_impl->getStatusText(ec)); - setDOMException(exec, ec); - return result; - } - case Onreadystatechange: - if (JSUnprotectedEventListener* listener = static_cast<JSUnprotectedEventListener*>(m_impl->onReadyStateChangeListener())) - if (JSObject* listenerObj = listener->listenerObj()) - return listenerObj; - return jsNull(); - case Onload: - if (JSUnprotectedEventListener* listener = static_cast<JSUnprotectedEventListener*>(m_impl->onLoadListener())) - if (JSObject* listenerObj = listener->listenerObj()) - return listenerObj; - return jsNull(); - default: - return 0; - } -} - -void JSXMLHttpRequest::put(ExecState* exec, const Identifier& propertyName, JSValue* value, int attr) -{ - lookupPut<JSXMLHttpRequest,DOMObject>(exec, propertyName, value, attr, &JSXMLHttpRequestTable, this ); -} - -void JSXMLHttpRequest::putValueProperty(ExecState* exec, int token, JSValue* value, int /*attr*/) -{ - switch (token) { - case Onreadystatechange: { - Document* doc = m_impl->document(); - if (!doc) - return; - Frame* frame = doc->frame(); - if (!frame) - return; - m_impl->setOnReadyStateChangeListener(KJS::Window::retrieveWindow(frame)->findOrCreateJSUnprotectedEventListener(value, true)); - break; - } - case Onload: { - Document* doc = m_impl->document(); - if (!doc) - return; - Frame* frame = doc->frame(); - if (!frame) - return; - m_impl->setOnLoadListener(KJS::Window::retrieveWindow(frame)->findOrCreateJSUnprotectedEventListener(value, true)); - break; - } - } -} - -void JSXMLHttpRequest::mark() -{ - DOMObject::mark(); - - JSUnprotectedEventListener* onReadyStateChangeListener = static_cast<JSUnprotectedEventListener*>(m_impl->onReadyStateChangeListener()); - JSUnprotectedEventListener* onLoadListener = static_cast<JSUnprotectedEventListener*>(m_impl->onLoadListener()); - - if (onReadyStateChangeListener) - onReadyStateChangeListener->mark(); - - if (onLoadListener) - onLoadListener->mark(); - - typedef XMLHttpRequest::EventListenersMap EventListenersMap; - typedef XMLHttpRequest::ListenerVector ListenerVector; - EventListenersMap& eventListeners = m_impl->eventListeners(); - for (EventListenersMap::iterator mapIter = eventListeners.begin(); mapIter != eventListeners.end(); ++mapIter) { - for (ListenerVector::iterator vecIter = mapIter->second.begin(); vecIter != mapIter->second.end(); ++vecIter) { - JSUnprotectedEventListener* listener = static_cast<JSUnprotectedEventListener*>(vecIter->get()); - listener->mark(); - } - } -} - - -JSXMLHttpRequest::JSXMLHttpRequest(JSObject* prototype, Document* d) - : DOMObject(prototype) - , m_impl(new XMLHttpRequest(d)) -{ - ScriptInterpreter::putDOMObject(m_impl.get(), this); -} - -JSXMLHttpRequest::~JSXMLHttpRequest() -{ - m_impl->setOnReadyStateChangeListener(0); - m_impl->setOnLoadListener(0); - m_impl->eventListeners().clear(); - ScriptInterpreter::forgetDOMObject(m_impl.get()); -} - -JSValue* jsXMLHttpRequestPrototypeFunctionAbort(ExecState* exec, JSObject* thisObj, const List& args) -{ - if (!thisObj->inherits(&JSXMLHttpRequest::info)) - return throwError(exec, TypeError); - - JSXMLHttpRequest* request = static_cast<JSXMLHttpRequest*>(thisObj); - - request->impl()->abort(); - return jsUndefined(); -} - -JSValue* jsXMLHttpRequestPrototypeFunctionGetAllResponseHeaders(ExecState* exec, JSObject* thisObj, const List& args) -{ - if (!thisObj->inherits(&JSXMLHttpRequest::info)) - return throwError(exec, TypeError); - - JSXMLHttpRequest* request = static_cast<JSXMLHttpRequest*>(thisObj); - ExceptionCode ec = 0; - - JSValue* headers = jsStringOrUndefined(request->impl()->getAllResponseHeaders(ec)); - setDOMException(exec, ec); - return headers; -} - -JSValue* jsXMLHttpRequestPrototypeFunctionGetResponseHeader(ExecState* exec, JSObject* thisObj, const List& args) -{ - if (!thisObj->inherits(&JSXMLHttpRequest::info)) - return throwError(exec, TypeError); - - JSXMLHttpRequest* request = static_cast<JSXMLHttpRequest*>(thisObj); - ExceptionCode ec = 0; - - if (args.size() < 1) - return throwError(exec, SyntaxError, "Not enough arguments"); - - JSValue* header = jsStringOrNull(request->impl()->getResponseHeader(args[0]->toString(exec), ec)); - setDOMException(exec, ec); - return header; -} - - -JSValue* jsXMLHttpRequestPrototypeFunctionOpen(ExecState* exec, JSObject* thisObj, const List& args) -{ - if (!thisObj->inherits(&JSXMLHttpRequest::info)) - return throwError(exec, TypeError); - - JSXMLHttpRequest* request = static_cast<JSXMLHttpRequest*>(thisObj); - ExceptionCode ec = 0; - - if (args.size() < 2) - return throwError(exec, SyntaxError, "Not enough arguments"); - - String method = args[0]->toString(exec); - Frame* frame = Window::retrieveActive(exec)->impl()->frame(); - if (!frame) - return jsUndefined(); - KURL url = frame->loader()->completeURL(DeprecatedString(args[1]->toString(exec))); - - bool async = true; - if (args.size() >= 3) - async = args[2]->toBoolean(exec); - - if (args.size() >= 4 && !args[3]->isUndefined()) { - String user = valueToStringWithNullCheck(exec, args[3]); - - if (args.size() >= 5 && !args[4]->isUndefined()) { - String password = valueToStringWithNullCheck(exec, args[4]); - request->impl()->open(method, url, async, user, password, ec); - } else - request->impl()->open(method, url, async, user, ec); - } else - request->impl()->open(method, url, async, ec); - - setDOMException(exec, ec); - return jsUndefined(); -} - -JSValue* jsXMLHttpRequestPrototypeFunctionSend(ExecState* exec, JSObject* thisObj, const List& args) -{ - if (!thisObj->inherits(&JSXMLHttpRequest::info)) - return throwError(exec, TypeError); - - JSXMLHttpRequest* request = static_cast<JSXMLHttpRequest*>(thisObj); - ExceptionCode ec = 0; - - String body; - - if (args.size() >= 1) { - if (args[0]->toObject(exec)->inherits(&JSDocument::info)) { - Document* doc = static_cast<Document*>(static_cast<JSDocument*>(args[0]->toObject(exec))->impl()); - body = doc->toString().deprecatedString(); - } else { - // converting certain values (like null) to object can set an exception - if (exec->hadException()) - exec->clearException(); - else - body = args[0]->toString(exec); - } - } - - request->impl()->send(body, ec); - setDOMException(exec, ec); - - return jsUndefined(); -} - -JSValue* jsXMLHttpRequestPrototypeFunctionSetRequestHeader(ExecState* exec, JSObject* thisObj, const List& args) -{ - if (!thisObj->inherits(&JSXMLHttpRequest::info)) - return throwError(exec, TypeError); - - JSXMLHttpRequest* request = static_cast<JSXMLHttpRequest*>(thisObj); - ExceptionCode ec = 0; - - if (args.size() < 2) - return throwError(exec, SyntaxError, "Not enough arguments"); - - request->impl()->setRequestHeader(args[0]->toString(exec), args[1]->toString(exec), ec); - setDOMException(exec, ec); - return jsUndefined(); - -} - -JSValue* jsXMLHttpRequestPrototypeFunctionOverrideMIMEType(ExecState* exec, JSObject* thisObj, const List& args) -{ - if (!thisObj->inherits(&JSXMLHttpRequest::info)) - return throwError(exec, TypeError); - - JSXMLHttpRequest* request = static_cast<JSXMLHttpRequest*>(thisObj); - - if (args.size() < 1) - return throwError(exec, SyntaxError, "Not enough arguments"); - - request->impl()->overrideMIMEType(args[0]->toString(exec)); - return jsUndefined(); -} - -JSValue* jsXMLHttpRequestPrototypeFunctionAddEventListener(ExecState* exec, JSObject* thisObj, const List& args) -{ - if (!thisObj->inherits(&JSXMLHttpRequest::info)) - return throwError(exec, TypeError); - - JSXMLHttpRequest* request = static_cast<JSXMLHttpRequest*>(thisObj); - - Document* doc = request->impl()->document(); - if (!doc) - return jsUndefined(); - Frame* frame = doc->frame(); - if (!frame) - return jsUndefined(); - JSUnprotectedEventListener* listener = KJS::Window::retrieveWindow(frame)->findOrCreateJSUnprotectedEventListener(args[1], true); - if (!listener) - return jsUndefined(); - request->impl()->addEventListener(args[0]->toString(exec), listener, args[2]->toBoolean(exec)); - return jsUndefined(); -} - -JSValue* jsXMLHttpRequestPrototypeFunctionRemoveEventListener(ExecState* exec, JSObject* thisObj, const List& args) -{ - if (!thisObj->inherits(&JSXMLHttpRequest::info)) - return throwError(exec, TypeError); - - JSXMLHttpRequest* request = static_cast<JSXMLHttpRequest*>(thisObj); - - Document* doc = request->impl()->document(); - if (!doc) - return jsUndefined(); - Frame* frame = doc->frame(); - if (!frame) - return jsUndefined(); - JSUnprotectedEventListener* listener = KJS::Window::retrieveWindow(frame)->findOrCreateJSUnprotectedEventListener(args[1], true); - if (!listener) - return jsUndefined(); - request->impl()->removeEventListener(args[0]->toString(exec), listener, args[2]->toBoolean(exec)); - return jsUndefined(); -} - -JSValue* jsXMLHttpRequestPrototypeFunctionDispatchEvent(ExecState* exec, JSObject* thisObj, const List& args) -{ - if (!thisObj->inherits(&JSXMLHttpRequest::info)) - return throwError(exec, TypeError); - - JSXMLHttpRequest* request = static_cast<JSXMLHttpRequest*>(thisObj); - ExceptionCode ec = 0; - - bool result = request->impl()->dispatchEvent(toEvent(args[0]), ec); - setDOMException(exec, ec); - return jsBoolean(result); -} - -} // end namespace diff --git a/WebCore/bindings/js/JSXMLHttpRequest.h b/WebCore/bindings/js/JSXMLHttpRequest.h deleted file mode 100644 index 23ea7d0..0000000 --- a/WebCore/bindings/js/JSXMLHttpRequest.h +++ /dev/null @@ -1,84 +0,0 @@ -// -*- c-basic-offset: 2 -*- -/* - * This file is part of the KDE libraries - * Copyright (C) 2003 Apple Computer, Inc. - * Copyright (C) 2005, 2006 Alexey Proskuryakov <ap@nypop.com> - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#ifndef JSXMLHttpRequest_h -#define JSXMLHttpRequest_h - -#include "kjs_binding.h" - -namespace WebCore { - -class XMLHttpRequest; -class Document; - -} - -namespace KJS { - -class JSXMLHttpRequestConstructorImp : public DOMObject { -public: - JSXMLHttpRequestConstructorImp(ExecState*, WebCore::Document*); - - virtual bool implementsConstruct() const; - virtual JSObject* construct(ExecState*, const List&); - -private: - RefPtr<WebCore::Document> doc; -}; - -class JSXMLHttpRequest : public DOMObject { -public: - JSXMLHttpRequest(JSObject* prototype, WebCore::Document*); - ~JSXMLHttpRequest(); - - virtual const ClassInfo* classInfo() const { return &info; } - static const ClassInfo info; - enum { Onload, Onreadystatechange, ReadyState, ResponseText, ResponseXML, Status, - StatusText, Abort, GetAllResponseHeaders, GetResponseHeader, Open, Send, SetRequestHeader, OverrideMIMEType, - AddEventListener, RemoveEventListener, DispatchEvent }; - - virtual bool getOwnPropertySlot(ExecState*, const Identifier&, PropertySlot&); - JSValue* getValueProperty(ExecState*, int token) const; - virtual void put(ExecState*, const Identifier& propertyName, JSValue* value, int attr = None); - void putValueProperty(ExecState*, int token, JSValue* value, int /*attr*/); - virtual bool toBoolean(ExecState*) const { return true; } - virtual void mark(); - - WebCore::XMLHttpRequest* impl() const { return m_impl.get(); } - -private: - RefPtr<WebCore::XMLHttpRequest> m_impl; -}; - -JSValue* jsXMLHttpRequestPrototypeFunctionAbort(ExecState*, JSObject*, const List&); -JSValue* jsXMLHttpRequestPrototypeFunctionGetAllResponseHeaders(ExecState*, JSObject*, const List&); -JSValue* jsXMLHttpRequestPrototypeFunctionGetResponseHeader(ExecState*, JSObject*, const List&); -JSValue* jsXMLHttpRequestPrototypeFunctionOpen(ExecState*, JSObject*, const List&); -JSValue* jsXMLHttpRequestPrototypeFunctionSend(ExecState*, JSObject*, const List&); -JSValue* jsXMLHttpRequestPrototypeFunctionSetRequestHeader(ExecState*, JSObject*, const List&); -JSValue* jsXMLHttpRequestPrototypeFunctionOverrideMIMEType(ExecState*, JSObject*, const List&); -JSValue* jsXMLHttpRequestPrototypeFunctionAddEventListener(ExecState*, JSObject*, const List&); -JSValue* jsXMLHttpRequestPrototypeFunctionRemoveEventListener(ExecState*, JSObject*, const List&); -JSValue* jsXMLHttpRequestPrototypeFunctionDispatchEvent(ExecState*, JSObject*, const List&); - -} // namespace KJS - -#endif // JSXMLHttpRequest_h diff --git a/WebCore/bindings/js/JSXMLHttpRequestConstructor.cpp b/WebCore/bindings/js/JSXMLHttpRequestConstructor.cpp new file mode 100644 index 0000000..31d4dd7 --- /dev/null +++ b/WebCore/bindings/js/JSXMLHttpRequestConstructor.cpp @@ -0,0 +1,63 @@ +/* + * Copyright (C) 2004, 2007, 2008 Apple Inc. All rights reserved. + * Copyright (C) 2005, 2006 Alexey Proskuryakov <ap@nypop.com> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include "config.h" +#include "JSXMLHttpRequestConstructor.h" + +#include "JSXMLHttpRequest.h" +#include "ScriptExecutionContext.h" +#include "XMLHttpRequest.h" + +using namespace JSC; + +namespace WebCore { + +ASSERT_CLASS_FITS_IN_CELL(JSXMLHttpRequestConstructor) + +const ClassInfo JSXMLHttpRequestConstructor::s_info = { "XMLHttpRequestConstructor", 0, 0, 0 }; + +JSXMLHttpRequestConstructor::JSXMLHttpRequestConstructor(ExecState* exec, ScriptExecutionContext* context) + : DOMObject(JSXMLHttpRequestConstructor::createStructureID(exec->lexicalGlobalObject()->objectPrototype())) +{ + ASSERT(context->isDocument()); + m_document = static_cast<JSDocument*>(asObject(toJS(exec, static_cast<Document*>(context)))); + + putDirect(exec->propertyNames().prototype, JSXMLHttpRequestPrototype::self(exec), None); +} + +static JSObject* constructXMLHttpRequest(ExecState* exec, JSObject* constructor, const ArgList&) +{ + RefPtr<XMLHttpRequest> xmlHttpRequest = XMLHttpRequest::create(static_cast<JSXMLHttpRequestConstructor*>(constructor)->document()); + return CREATE_DOM_OBJECT_WRAPPER(exec, XMLHttpRequest, xmlHttpRequest.get()); +} + +ConstructType JSXMLHttpRequestConstructor::getConstructData(ConstructData& constructData) +{ + constructData.native.function = constructXMLHttpRequest; + return ConstructTypeHost; +} + +void JSXMLHttpRequestConstructor::mark() +{ + DOMObject::mark(); + if (!m_document->marked()) + m_document->mark(); +} + +} // namespace WebCore diff --git a/WebCore/bindings/js/JSXMLHttpRequestConstructor.h b/WebCore/bindings/js/JSXMLHttpRequestConstructor.h new file mode 100644 index 0000000..f235af6 --- /dev/null +++ b/WebCore/bindings/js/JSXMLHttpRequestConstructor.h @@ -0,0 +1,44 @@ +/* + * Copyright (C) 2003, 2008 Apple Inc. All rights reserved. + * Copyright (C) 2005, 2006 Alexey Proskuryakov <ap@nypop.com> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#ifndef JSXMLHttpRequestConstructor_h +#define JSXMLHttpRequestConstructor_h + +#include "JSDOMBinding.h" +#include "JSDocument.h" + +namespace WebCore { + +class JSXMLHttpRequestConstructor : public DOMObject { +public: + JSXMLHttpRequestConstructor(JSC::ExecState*, ScriptExecutionContext*); + Document* document() const { return m_document->impl(); } + static const JSC::ClassInfo s_info; + + virtual void mark(); +private: + virtual JSC::ConstructType getConstructData(JSC::ConstructData&); + virtual const JSC::ClassInfo* classInfo() const { return &s_info; } + + JSDocument* m_document; +}; + +} // namespace WebCore + +#endif // JSXMLHttpRequestConstructor_h diff --git a/WebCore/bindings/js/JSXMLHttpRequestCustom.cpp b/WebCore/bindings/js/JSXMLHttpRequestCustom.cpp new file mode 100644 index 0000000..4524b16 --- /dev/null +++ b/WebCore/bindings/js/JSXMLHttpRequestCustom.cpp @@ -0,0 +1,208 @@ +/* + * Copyright (C) 2008 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of + * its contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "JSXMLHttpRequest.h" + +#include "DOMWindow.h" +#include "Document.h" +#include "Event.h" +#include "File.h" +#include "Frame.h" +#include "FrameLoader.h" +#include "HTMLDocument.h" +#include "JSDOMWindowCustom.h" +#include "JSDocument.h" +#include "JSEvent.h" +#include "JSEventListener.h" +#include "JSFile.h" +#include "XMLHttpRequest.h" +#include <runtime/Error.h> +#include <VM/Machine.h> + +using namespace JSC; + +namespace WebCore { + +void JSXMLHttpRequest::mark() +{ + Base::mark(); + + if (XMLHttpRequestUpload* upload = m_impl->optionalUpload()) { + DOMObject* wrapper = getCachedDOMObjectWrapper(*Heap::heap(this)->globalData(), upload); + if (wrapper && !wrapper->marked()) + wrapper->mark(); + } + + if (JSUnprotectedEventListener* onReadyStateChangeListener = static_cast<JSUnprotectedEventListener*>(m_impl->onreadystatechange())) + onReadyStateChangeListener->mark(); + + if (JSUnprotectedEventListener* onAbortListener = static_cast<JSUnprotectedEventListener*>(m_impl->onabort())) + onAbortListener->mark(); + + if (JSUnprotectedEventListener* onErrorListener = static_cast<JSUnprotectedEventListener*>(m_impl->onerror())) + onErrorListener->mark(); + + if (JSUnprotectedEventListener* onLoadListener = static_cast<JSUnprotectedEventListener*>(m_impl->onload())) + onLoadListener->mark(); + + if (JSUnprotectedEventListener* onLoadStartListener = static_cast<JSUnprotectedEventListener*>(m_impl->onloadstart())) + onLoadStartListener->mark(); + + if (JSUnprotectedEventListener* onProgressListener = static_cast<JSUnprotectedEventListener*>(m_impl->onprogress())) + onProgressListener->mark(); + + typedef XMLHttpRequest::EventListenersMap EventListenersMap; + typedef XMLHttpRequest::ListenerVector ListenerVector; + EventListenersMap& eventListeners = m_impl->eventListeners(); + for (EventListenersMap::iterator mapIter = eventListeners.begin(); mapIter != eventListeners.end(); ++mapIter) { + for (ListenerVector::iterator vecIter = mapIter->second.begin(); vecIter != mapIter->second.end(); ++vecIter) { + JSUnprotectedEventListener* listener = static_cast<JSUnprotectedEventListener*>(vecIter->get()); + listener->mark(); + } + } +} + +// Custom functions +JSValue* JSXMLHttpRequest::open(ExecState* exec, const ArgList& args) +{ + if (args.size() < 2) + return throwError(exec, SyntaxError, "Not enough arguments"); + + Frame* frame = asJSDOMWindow(exec->dynamicGlobalObject())->impl()->frame(); + if (!frame) + return jsUndefined(); + const KURL& url = frame->loader()->completeURL(args.at(exec, 1)->toString(exec)); + + ExceptionCode ec = 0; + + String method = args.at(exec, 0)->toString(exec); + bool async = true; + if (args.size() >= 3) + async = args.at(exec, 2)->toBoolean(exec); + + if (args.size() >= 4 && !args.at(exec, 3)->isUndefined()) { + String user = valueToStringWithNullCheck(exec, args.at(exec, 3)); + + if (args.size() >= 5 && !args.at(exec, 4)->isUndefined()) { + String password = valueToStringWithNullCheck(exec, args.at(exec, 4)); + impl()->open(method, url, async, user, password, ec); + } else + impl()->open(method, url, async, user, ec); + } else + impl()->open(method, url, async, ec); + + setDOMException(exec, ec); + return jsUndefined(); +} + +JSValue* JSXMLHttpRequest::setRequestHeader(ExecState* exec, const ArgList& args) +{ + if (args.size() < 2) + return throwError(exec, SyntaxError, "Not enough arguments"); + + ExceptionCode ec = 0; + impl()->setRequestHeader(args.at(exec, 0)->toString(exec), args.at(exec, 1)->toString(exec), ec); + setDOMException(exec, ec); + return jsUndefined(); +} + +JSValue* JSXMLHttpRequest::send(ExecState* exec, const ArgList& args) +{ + ExceptionCode ec = 0; + if (args.isEmpty()) + impl()->send(ec); + else { + JSValue* val = args.at(exec, 0); + if (val->isUndefinedOrNull()) + impl()->send(ec); + else if (val->isObject(&JSDocument::s_info)) + impl()->send(toDocument(val), ec); + else if (val->isObject(&JSFile::s_info)) + impl()->send(toFile(val), ec); + else + impl()->send(val->toString(exec), ec); + } + + int signedLineNumber; + intptr_t sourceID; + UString sourceURL; + JSValue* function; + exec->machine()->retrieveLastCaller(exec, signedLineNumber, sourceID, sourceURL, function); + impl()->setLastSendLineNumber(signedLineNumber >= 0 ? signedLineNumber : 0); + impl()->setLastSendURL(sourceURL); + + setDOMException(exec, ec); + return jsUndefined(); +} + +JSValue* JSXMLHttpRequest::getResponseHeader(ExecState* exec, const ArgList& args) +{ + if (args.size() < 1) + return throwError(exec, SyntaxError, "Not enough arguments"); + + ExceptionCode ec = 0; + JSValue* header = jsStringOrNull(exec, impl()->getResponseHeader(args.at(exec, 0)->toString(exec), ec)); + setDOMException(exec, ec); + return header; +} + +JSValue* JSXMLHttpRequest::overrideMimeType(ExecState* exec, const ArgList& args) +{ + if (args.size() < 1) + return throwError(exec, SyntaxError, "Not enough arguments"); + + impl()->overrideMimeType(args.at(exec, 0)->toString(exec)); + return jsUndefined(); +} + +JSValue* JSXMLHttpRequest::addEventListener(ExecState* exec, const ArgList& args) +{ + JSDOMGlobalObject* globalObject = toJSDOMGlobalObject(impl()->scriptExecutionContext()); + if (!globalObject) + return jsUndefined(); + RefPtr<JSUnprotectedEventListener> listener = globalObject->findOrCreateJSUnprotectedEventListener(exec, args.at(exec, 1)); + if (!listener) + return jsUndefined(); + impl()->addEventListener(args.at(exec, 0)->toString(exec), listener.release(), args.at(exec, 2)->toBoolean(exec)); + return jsUndefined(); +} + +JSValue* JSXMLHttpRequest::removeEventListener(ExecState* exec, const ArgList& args) +{ + JSDOMGlobalObject* globalObject = toJSDOMGlobalObject(impl()->scriptExecutionContext()); + if (!globalObject) + return jsUndefined(); + JSUnprotectedEventListener* listener = globalObject->findJSUnprotectedEventListener(exec, args.at(exec, 1)); + if (!listener) + return jsUndefined(); + impl()->removeEventListener(args.at(exec, 0)->toString(exec), listener, args.at(exec, 2)->toBoolean(exec)); + return jsUndefined(); +} + +} // namespace WebCore diff --git a/WebCore/bindings/js/JSXMLHttpRequestUploadCustom.cpp b/WebCore/bindings/js/JSXMLHttpRequestUploadCustom.cpp new file mode 100644 index 0000000..ae673d9 --- /dev/null +++ b/WebCore/bindings/js/JSXMLHttpRequestUploadCustom.cpp @@ -0,0 +1,104 @@ +/* + * Copyright (C) 2008 Apple Inc. All Rights Reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "JSXMLHttpRequestUpload.h" + +#include "DOMWindow.h" +#include "Document.h" +#include "Event.h" +#include "Frame.h" +#include "JSDOMWindowCustom.h" +#include "JSEvent.h" +#include "JSEventListener.h" +#include "XMLHttpRequest.h" +#include "XMLHttpRequestUpload.h" +#include <runtime/Error.h> + +using namespace JSC; + +namespace WebCore { + +void JSXMLHttpRequestUpload::mark() +{ + Base::mark(); + + if (XMLHttpRequest* xmlHttpRequest = m_impl->associatedXMLHttpRequest()) { + DOMObject* wrapper = getCachedDOMObjectWrapper(*Heap::heap(this)->globalData(), xmlHttpRequest); + if (wrapper && !wrapper->marked()) + wrapper->mark(); + } + + if (JSUnprotectedEventListener* onAbortListener = static_cast<JSUnprotectedEventListener*>(m_impl->onabort())) + onAbortListener->mark(); + + if (JSUnprotectedEventListener* onErrorListener = static_cast<JSUnprotectedEventListener*>(m_impl->onerror())) + onErrorListener->mark(); + + if (JSUnprotectedEventListener* onLoadListener = static_cast<JSUnprotectedEventListener*>(m_impl->onload())) + onLoadListener->mark(); + + if (JSUnprotectedEventListener* onLoadStartListener = static_cast<JSUnprotectedEventListener*>(m_impl->onloadstart())) + onLoadStartListener->mark(); + + if (JSUnprotectedEventListener* onProgressListener = static_cast<JSUnprotectedEventListener*>(m_impl->onprogress())) + onProgressListener->mark(); + + typedef XMLHttpRequestUpload::EventListenersMap EventListenersMap; + typedef XMLHttpRequestUpload::ListenerVector ListenerVector; + EventListenersMap& eventListeners = m_impl->eventListeners(); + for (EventListenersMap::iterator mapIter = eventListeners.begin(); mapIter != eventListeners.end(); ++mapIter) { + for (ListenerVector::iterator vecIter = mapIter->second.begin(); vecIter != mapIter->second.end(); ++vecIter) { + JSUnprotectedEventListener* listener = static_cast<JSUnprotectedEventListener*>(vecIter->get()); + listener->mark(); + } + } +} + +JSValue* JSXMLHttpRequestUpload::addEventListener(ExecState* exec, const ArgList& args) +{ + JSDOMGlobalObject* globalObject = toJSDOMGlobalObject(impl()->scriptExecutionContext()); + if (!globalObject) + return jsUndefined(); + RefPtr<JSUnprotectedEventListener> listener = globalObject->findOrCreateJSUnprotectedEventListener(exec, args.at(exec, 1)); + if (!listener) + return jsUndefined(); + impl()->addEventListener(args.at(exec, 0)->toString(exec), listener.release(), args.at(exec, 2)->toBoolean(exec)); + return jsUndefined(); +} + +JSValue* JSXMLHttpRequestUpload::removeEventListener(ExecState* exec, const ArgList& args) +{ + JSDOMGlobalObject* globalObject = toJSDOMGlobalObject(impl()->scriptExecutionContext()); + if (!globalObject) + return jsUndefined(); + JSUnprotectedEventListener* listener = globalObject->findJSUnprotectedEventListener(exec, args.at(exec, 1)); + if (!listener) + return jsUndefined(); + impl()->removeEventListener(args.at(exec, 0)->toString(exec), listener, args.at(exec, 2)->toBoolean(exec)); + return jsUndefined(); +} + +} // namespace WebCore diff --git a/WebCore/bindings/js/JSXSLTProcessor.cpp b/WebCore/bindings/js/JSXSLTProcessor.cpp deleted file mode 100644 index 20481fe..0000000 --- a/WebCore/bindings/js/JSXSLTProcessor.cpp +++ /dev/null @@ -1,206 +0,0 @@ -/* - * Copyright (C) 2005, 2006, 2007 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "config.h" - -#if ENABLE(XSLT) - -#include "JSXSLTProcessor.h" - -#include "XSLTProcessor.h" -#include "JSXSLTProcessor.lut.h" -#include "kjs_dom.h" -#include "JSDocument.h" -#include "Document.h" -#include "DocumentFragment.h" - -using namespace WebCore; - -namespace KJS { - -const ClassInfo JSXSLTProcessor::info = { "XSLTProcessor", 0, 0 }; - -/* -@begin XSLTProcessorPrototypeTable 7 - importStylesheet jsXSLTProcessorPrototypeFunctionImportStylesheet DontDelete|Function 1 - transformToFragment jsXSLTProcessorPrototypeFunctionTransformToFragment DontDelete|Function 2 - transformToDocument jsXSLTProcessorPrototypeFunctionTransformToDocument DontDelete|Function 2 - setParameter jsXSLTProcessorPrototypeFunctionSetParameter DontDelete|Function 3 - getParameter jsXSLTProcessorPrototypeFunctionGetParameter DontDelete|Function 2 - removeParameter jsXSLTProcessorPrototypeFunctionRemoveParameter DontDelete|Function 2 - clearParameters jsXSLTProcessorPrototypeFunctionClearParameters DontDelete|Function 0 - reset jsXSLTProcessorPrototypeFunctionReset DontDelete|Function 0 -@end -*/ - -KJS_DEFINE_PROTOTYPE(XSLTProcessorPrototype) -KJS_IMPLEMENT_PROTOTYPE("XSLTProcessor", XSLTProcessorPrototype) - -JSXSLTProcessor::JSXSLTProcessor(JSObject* prototype) - : DOMObject(prototype) - , m_impl(new XSLTProcessor()) -{ -} - -JSXSLTProcessor::~JSXSLTProcessor() -{ - ScriptInterpreter::forgetDOMObject(m_impl.get()); -} - -JSValue* jsXSLTProcessorPrototypeFunctionImportStylesheet(ExecState* exec, JSObject* thisObj, const List& args) -{ - if (!thisObj->inherits(&KJS::JSXSLTProcessor::info)) - return throwError(exec, TypeError); - XSLTProcessor& processor = *static_cast<JSXSLTProcessor*>(thisObj)->impl(); - - JSValue *nodeVal = args[0]; - if (nodeVal->isObject(&JSNode::info)) { - JSNode* node = static_cast<JSNode*>(nodeVal); - processor.importStylesheet(node->impl()); - return jsUndefined(); - } - // Throw exception? - return jsUndefined(); -} - -JSValue* jsXSLTProcessorPrototypeFunctionTransformToFragment(ExecState* exec, JSObject* thisObj, const List& args) -{ - if (!thisObj->inherits(&KJS::JSXSLTProcessor::info)) - return throwError(exec, TypeError); - XSLTProcessor& processor = *static_cast<JSXSLTProcessor*>(thisObj)->impl(); - - JSValue *nodeVal = args[0]; - JSValue *docVal = args[1]; - if (nodeVal->isObject(&JSNode::info) && docVal->isObject(&JSDocument::info)) { - WebCore::Node* node = static_cast<JSNode*>(nodeVal)->impl(); - Document* doc = static_cast<Document*>(static_cast<JSDocument *>(docVal)->impl()); - return toJS(exec, processor.transformToFragment(node, doc).get()); - } - // Throw exception? - return jsUndefined(); -} - -JSValue* jsXSLTProcessorPrototypeFunctionTransformToDocument(ExecState* exec, JSObject* thisObj, const List& args) -{ - if (!thisObj->inherits(&KJS::JSXSLTProcessor::info)) - return throwError(exec, TypeError); - XSLTProcessor& processor = *static_cast<JSXSLTProcessor*>(thisObj)->impl(); - - JSValue *nodeVal = args[0]; - if (nodeVal->isObject(&JSNode::info)) { - JSNode* node = static_cast<JSNode*>(nodeVal); - RefPtr<Document> resultDocument = processor.transformToDocument(node->impl()); - if (resultDocument) - return toJS(exec, resultDocument.get()); - return jsUndefined(); - } - // Throw exception? - return jsUndefined(); -} - -JSValue* jsXSLTProcessorPrototypeFunctionSetParameter(ExecState* exec, JSObject* thisObj, const List& args) -{ - if (!thisObj->inherits(&KJS::JSXSLTProcessor::info)) - return throwError(exec, TypeError); - XSLTProcessor& processor = *static_cast<JSXSLTProcessor*>(thisObj)->impl(); - - if (args[1]->isUndefinedOrNull() || args[2]->isUndefinedOrNull()) - return jsUndefined(); // Throw exception? - String namespaceURI = args[0]->toString(exec); - String localName = args[1]->toString(exec); - String value = args[2]->toString(exec); - processor.setParameter(namespaceURI, localName, value); - return jsUndefined(); -} - -JSValue* jsXSLTProcessorPrototypeFunctionGetParameter(ExecState* exec, JSObject* thisObj, const List& args) -{ - if (!thisObj->inherits(&KJS::JSXSLTProcessor::info)) - return throwError(exec, TypeError); - XSLTProcessor& processor = *static_cast<JSXSLTProcessor*>(thisObj)->impl(); - - if (args[1]->isUndefinedOrNull()) - return jsUndefined(); - String namespaceURI = args[0]->toString(exec); - String localName = args[1]->toString(exec); - String value = processor.getParameter(namespaceURI, localName); - if (!value.isNull()) - return jsString(value); - return jsUndefined(); -} - -JSValue* jsXSLTProcessorPrototypeFunctionRemoveParameter(ExecState* exec, JSObject* thisObj, const List& args) -{ - if (!thisObj->inherits(&KJS::JSXSLTProcessor::info)) - return throwError(exec, TypeError); - XSLTProcessor& processor = *static_cast<JSXSLTProcessor*>(thisObj)->impl(); - - if (args[1]->isUndefinedOrNull()) - return jsUndefined(); - String namespaceURI = args[0]->toString(exec); - String localName = args[1]->toString(exec); - processor.removeParameter(namespaceURI, localName); - return jsUndefined(); -} - -JSValue* jsXSLTProcessorPrototypeFunctionClearParameters(ExecState* exec, JSObject* thisObj, const List& args) -{ - if (!thisObj->inherits(&KJS::JSXSLTProcessor::info)) - return throwError(exec, TypeError); - XSLTProcessor& processor = *static_cast<JSXSLTProcessor*>(thisObj)->impl(); - - processor.clearParameters(); - return jsUndefined(); -} - -JSValue* jsXSLTProcessorPrototypeFunctionReset(ExecState* exec, JSObject* thisObj, const List& args) -{ - if (!thisObj->inherits(&KJS::JSXSLTProcessor::info)) - return throwError(exec, TypeError); - XSLTProcessor& processor = *static_cast<JSXSLTProcessor*>(thisObj)->impl(); - - processor.reset(); - return jsUndefined(); -} - -XSLTProcessorConstructorImp::XSLTProcessorConstructorImp(ExecState *exec) - : DOMObject(exec->lexicalGlobalObject()->objectPrototype()) -{ - putDirect(exec->propertyNames().prototype, XSLTProcessorPrototype::self(exec), None); -} - -bool XSLTProcessorConstructorImp::implementsConstruct() const -{ - return true; -} - -JSObject* XSLTProcessorConstructorImp::construct(ExecState* exec, const List& args) -{ - return new JSXSLTProcessor(XSLTProcessorPrototype::self(exec)); -} - -} // namespace KJS - -#endif // ENABLE(XSLT) diff --git a/WebCore/bindings/js/JSXSLTProcessor.h b/WebCore/bindings/js/JSXSLTProcessor.h deleted file mode 100644 index 05cde1e..0000000 --- a/WebCore/bindings/js/JSXSLTProcessor.h +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright (C) 2005 Apple Computer, Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef JSXSLTProcessor_h -#define JSXSLTProcessor_h - -#if ENABLE(XSLT) - -#include "kjs_binding.h" - -namespace WebCore { - class XSLTProcessor; -} - -// Eventually we should implement XSLTException: -// http://lxr.mozilla.org/seamonkey/source/content/xsl/public/nsIXSLTException.idl -// http://bugs.webkit.org/show_bug.cgi?id=5446 - -namespace KJS { - -class JSXSLTProcessor : public DOMObject { -public: - JSXSLTProcessor(JSObject* prototype); - ~JSXSLTProcessor(); - - virtual const ClassInfo *classInfo() const { return &info; } - static const ClassInfo info; - - WebCore::XSLTProcessor *impl() const { return m_impl.get(); } -private: - RefPtr<WebCore::XSLTProcessor> m_impl; -}; - -class XSLTProcessorConstructorImp : public DOMObject { -public: - XSLTProcessorConstructorImp(ExecState*); - - virtual bool implementsConstruct() const; - virtual JSObject* construct(ExecState*, const List&); -}; - -JSValue* jsXSLTProcessorPrototypeFunctionImportStylesheet(ExecState*, JSObject*, const List&); -JSValue* jsXSLTProcessorPrototypeFunctionTransformToFragment(ExecState*, JSObject*, const List&); -JSValue* jsXSLTProcessorPrototypeFunctionTransformToDocument(ExecState*, JSObject*, const List&); -JSValue* jsXSLTProcessorPrototypeFunctionSetParameter(ExecState*, JSObject*, const List&); -JSValue* jsXSLTProcessorPrototypeFunctionGetParameter(ExecState*, JSObject*, const List&); -JSValue* jsXSLTProcessorPrototypeFunctionRemoveParameter(ExecState*, JSObject*, const List&); -JSValue* jsXSLTProcessorPrototypeFunctionClearParameters(ExecState*, JSObject*, const List&); -JSValue* jsXSLTProcessorPrototypeFunctionReset(ExecState*, JSObject*, const List&); - -} // namespace KJS - -#endif // ENABLE(XSLT) - -#endif // JSXSLTProcessor_h diff --git a/WebCore/bindings/js/JSXSLTProcessorConstructor.cpp b/WebCore/bindings/js/JSXSLTProcessorConstructor.cpp new file mode 100644 index 0000000..e27e7a5 --- /dev/null +++ b/WebCore/bindings/js/JSXSLTProcessorConstructor.cpp @@ -0,0 +1,63 @@ +/* + * Copyright (C) 2005, 2006, 2007, 2008 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" + +#if ENABLE(XSLT) + +#include "JSXSLTProcessorConstructor.h" + +#include "JSXSLTProcessor.h" +#include "XSLTProcessor.h" +#include <wtf/RefPtr.h> + +using namespace JSC; + +namespace WebCore { + +ASSERT_CLASS_FITS_IN_CELL(JSXSLTProcessorConstructor) + +const ClassInfo JSXSLTProcessorConstructor::s_info = { "XSLTProcessorConsructor", 0, 0, 0 }; + +JSXSLTProcessorConstructor::JSXSLTProcessorConstructor(ExecState* exec) + : DOMObject(JSXSLTProcessorConstructor::createStructureID(exec->lexicalGlobalObject()->objectPrototype())) +{ + putDirect(exec->propertyNames().prototype, JSXSLTProcessorPrototype::self(exec), None); +} + +static JSObject* constructXSLTProcessor(ExecState* exec, JSObject*, const ArgList& args) +{ + return CREATE_DOM_OBJECT_WRAPPER(exec, XSLTProcessor, XSLTProcessor::create().get()); +} + +ConstructType JSXSLTProcessorConstructor::getConstructData(ConstructData& constructData) +{ + constructData.native.function = constructXSLTProcessor; + return ConstructTypeHost; +} + +} // namespace WebCore + +#endif // ENABLE(XSLT) diff --git a/WebCore/bindings/js/JSXSLTProcessorConstructor.h b/WebCore/bindings/js/JSXSLTProcessorConstructor.h new file mode 100644 index 0000000..64ef944 --- /dev/null +++ b/WebCore/bindings/js/JSXSLTProcessorConstructor.h @@ -0,0 +1,49 @@ +/* + * Copyright (C) 2005, 2008 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef JSXSLTProcessorConstructor_h +#define JSXSLTProcessorConstructor_h + +#if ENABLE(XSLT) + +#include "JSDOMBinding.h" + +namespace WebCore { + + class JSXSLTProcessorConstructor : public DOMObject { + public: + JSXSLTProcessorConstructor(JSC::ExecState*); + static const JSC::ClassInfo s_info; + + private: + virtual JSC::ConstructType getConstructData(JSC::ConstructData&); + virtual const JSC::ClassInfo* classInfo() const { return &s_info; } + }; + +} // namespace WebCore + +#endif // ENABLE(XSLT) + +#endif // JSXSLTProcessorConstructor_h diff --git a/WebCore/bindings/js/JSXSLTProcessorCustom.cpp b/WebCore/bindings/js/JSXSLTProcessorCustom.cpp new file mode 100644 index 0000000..6a5d29b --- /dev/null +++ b/WebCore/bindings/js/JSXSLTProcessorCustom.cpp @@ -0,0 +1,121 @@ +/* + * Copyright (C) 2008 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of + * its contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" + +#if ENABLE(XSLT) + +#include "JSXSLTProcessor.h" + +#include "Document.h" +#include "DocumentFragment.h" +#include "JSDocument.h" +#include "JSDocumentFragment.h" +#include "JSNode.h" +#include "Node.h" +#include "PlatformString.h" +#include "XSLTProcessor.h" +#include "JSDOMBinding.h" + +using namespace JSC; + +namespace WebCore { + +JSValue* JSXSLTProcessor::importStylesheet(ExecState* exec, const ArgList& args) +{ + JSValue* nodeVal = args.at(exec, 0); + if (nodeVal->isObject(&JSNode::s_info)) { + JSNode* node = static_cast<JSNode*>(asObject(nodeVal)); + impl()->importStylesheet(node->impl()); + return jsUndefined(); + } + // Throw exception? + return jsUndefined(); +} + +JSValue* JSXSLTProcessor::transformToFragment(ExecState* exec, const ArgList& args) +{ + JSValue* nodeVal = args.at(exec, 0); + JSValue* docVal = args.at(exec, 1); + if (nodeVal->isObject(&JSNode::s_info) && docVal->isObject(&JSDocument::s_info)) { + WebCore::Node* node = static_cast<JSNode*>(asObject(nodeVal))->impl(); + Document* doc = static_cast<Document*>(static_cast<JSDocument*>(asObject(docVal))->impl()); + return toJS(exec, impl()->transformToFragment(node, doc).get()); + } + // Throw exception? + return jsUndefined(); +} + +JSValue* JSXSLTProcessor::transformToDocument(ExecState* exec, const ArgList& args) +{ + JSValue* nodeVal = args.at(exec, 0); + if (nodeVal->isObject(&JSNode::s_info)) { + JSNode* node = static_cast<JSNode*>(asObject(nodeVal)); + RefPtr<Document> resultDocument = impl()->transformToDocument(node->impl()); + if (resultDocument) + return toJS(exec, resultDocument.get()); + return jsUndefined(); + } + // Throw exception? + return jsUndefined(); +} + +JSValue* JSXSLTProcessor::setParameter(ExecState* exec, const ArgList& args) +{ + if (args.at(exec, 1)->isUndefinedOrNull() || args.at(exec, 2)->isUndefinedOrNull()) + return jsUndefined(); // Throw exception? + String namespaceURI = args.at(exec, 0)->toString(exec); + String localName = args.at(exec, 1)->toString(exec); + String value = args.at(exec, 2)->toString(exec); + impl()->setParameter(namespaceURI, localName, value); + return jsUndefined(); +} + +JSValue* JSXSLTProcessor::getParameter(ExecState* exec, const ArgList& args) +{ + if (args.at(exec, 1)->isUndefinedOrNull()) + return jsUndefined(); + String namespaceURI = args.at(exec, 0)->toString(exec); + String localName = args.at(exec, 1)->toString(exec); + String value = impl()->getParameter(namespaceURI, localName); + return jsStringOrUndefined(exec, value); +} + +JSValue* JSXSLTProcessor::removeParameter(ExecState* exec, const ArgList& args) +{ + if (args.at(exec, 1)->isUndefinedOrNull()) + return jsUndefined(); + String namespaceURI = args.at(exec, 0)->toString(exec); + String localName = args.at(exec, 1)->toString(exec); + impl()->removeParameter(namespaceURI, localName); + return jsUndefined(); +} + +} // namespace WebCore + +#endif // ENABLE(XSLT) diff --git a/WebCore/bindings/js/ScheduledAction.cpp b/WebCore/bindings/js/ScheduledAction.cpp index a26923d..8d13cd2 100644 --- a/WebCore/bindings/js/ScheduledAction.cpp +++ b/WebCore/bindings/js/ScheduledAction.cpp @@ -1,7 +1,7 @@ /* * Copyright (C) 2000 Harri Porten (porten@kde.org) * Copyright (C) 2006 Jon Shier (jshier@iastate.edu) - * Copyright (C) 2003, 2004, 2005, 2006, 2007 Apple Inc. All rights reseved. + * Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008 Apple Inc. All rights reseved. * Copyright (C) 2006 Alexey Proskuryakov (ap@webkit.org) * * This library is free software; you can redistribute it and/or @@ -24,66 +24,57 @@ #include "ScheduledAction.h" #include "CString.h" -#include "Chrome.h" +#include "Console.h" #include "DOMWindow.h" #include "Document.h" #include "Frame.h" #include "FrameLoader.h" -#include "Page.h" -#include "kjs_proxy.h" -#include "kjs_window.h" +#include "JSDOMWindow.h" +#include "ScriptController.h" +#include <runtime/JSLock.h> -using namespace KJS; +using namespace JSC; namespace WebCore { -ScheduledAction::ScheduledAction(JSValue* func, const List& args) - : m_func(func) +ScheduledAction::ScheduledAction(ExecState* exec, JSValue* function, const ArgList& args) + : m_function(function) { - List::const_iterator end = args.end(); - for (List::const_iterator it = args.begin(); it != end; ++it) - m_args.append(*it); + ArgList::const_iterator end = args.end(); + for (ArgList::const_iterator it = args.begin(); it != end; ++it) + m_args.append((*it).jsValue(exec)); } - -void ScheduledAction::execute(Window* window) +void ScheduledAction::execute(JSDOMWindowShell* windowShell) { - RefPtr<Frame> frame = window->impl()->frame(); + RefPtr<Frame> frame = windowShell->window()->impl()->frame(); if (!frame) return; - if (!frame->scriptProxy()->isEnabled()) + if (!frame->script()->isEnabled()) return; - KJSProxy* scriptProxy = frame->scriptProxy(); - Window* globalObject = scriptProxy->globalObject(); + frame->script()->setProcessingTimerCallback(true); - scriptProxy->setProcessingTimerCallback(true); + JSLock lock(false); - if (JSValue* func = m_func.get()) { - JSLock lock; - if (func->isObject() && static_cast<JSObject*>(func)->implementsCall()) { + if (m_function) { + CallData callData; + CallType callType = m_function->getCallData(callData); + if (callType != CallTypeNone) { + JSDOMWindow* window = windowShell->window(); ExecState* exec = window->globalExec(); - ASSERT(window == globalObject); - List args; + ArgList args; size_t size = m_args.size(); for (size_t i = 0; i < size; ++i) args.append(m_args[i]); - globalObject->startTimeoutCheck(); - static_cast<JSObject*>(func)->call(exec, window, args); - globalObject->stopTimeoutCheck(); - if (exec->hadException()) { - JSObject* exception = exec->exception()->toObject(exec); - exec->clearException(); - String message = exception->get(exec, exec->propertyNames().message)->toString(exec); - int lineNumber = exception->get(exec, "line")->toInt32(exec); - if (Interpreter::shouldPrintExceptions()) - printf("(timer):%s\n", message.utf8().data()); - if (Page* page = frame->page()) - page->chrome()->addMessageToConsole(JSMessageSource, ErrorMessageLevel, message, lineNumber, String()); - } + window->startTimeoutCheck(); + call(exec, m_function, callType, callData, windowShell, args); + window->stopTimeoutCheck(); + if (exec->hadException()) + frame->domWindow()->console()->reportCurrentException(exec); } } else frame->loader()->executeScript(m_code); @@ -93,10 +84,10 @@ void ScheduledAction::execute(Window* window) // FIXME: Is this really the right point to do the update? We need a place that works // for all possible entry points that might possibly execute script, but this seems // to be a bit too low-level. - if (Document* doc = frame->document()) - doc->updateRendering(); + if (Document* document = frame->document()) + document->updateRendering(); - scriptProxy->setProcessingTimerCallback(false); + frame->script()->setProcessingTimerCallback(false); } } // namespace WebCore diff --git a/WebCore/bindings/js/ScheduledAction.h b/WebCore/bindings/js/ScheduledAction.h index a3b1858..938ac7b 100644 --- a/WebCore/bindings/js/ScheduledAction.h +++ b/WebCore/bindings/js/ScheduledAction.h @@ -1,6 +1,6 @@ /* * Copyright (C) 2000 Harri Porten (porten@kde.org) - * Copyright (C) 2003, 2004, 2005, 2006, 2007 Apple Inc. All rights reseved. + * Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008 Apple Inc. All rights reseved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -24,32 +24,27 @@ #include <kjs/protect.h> #include <wtf/Vector.h> -namespace KJS { - class Window; - class JSValue; - class List; -} - namespace WebCore { - /** - * An action (either function or string) to be executed after a specified - * time interval, either once or repeatedly. Used for window.setTimeout() - * and window.setInterval() - */ + class JSDOMWindowShell; + + /* An action (either function or string) to be executed after a specified + * time interval, either once or repeatedly. Used for window.setTimeout() + * and window.setInterval() + */ class ScheduledAction { public: - ScheduledAction(KJS::JSValue* func, const KJS::List& args); + ScheduledAction(JSC::ExecState* exec, JSC::JSValue* function, const JSC::ArgList&); ScheduledAction(const String& code) : m_code(code) { } - void execute(KJS::Window*); + void execute(JSDOMWindowShell*); private: - KJS::ProtectedPtr<KJS::JSValue> m_func; - Vector<KJS::ProtectedPtr<KJS::JSValue> > m_args; + JSC::ProtectedPtr<JSC::JSValue> m_function; + Vector<JSC::ProtectedPtr<JSC::JSValue> > m_args; String m_code; }; diff --git a/WebCore/bindings/js/ScriptController.cpp b/WebCore/bindings/js/ScriptController.cpp new file mode 100644 index 0000000..5346c07 --- /dev/null +++ b/WebCore/bindings/js/ScriptController.cpp @@ -0,0 +1,376 @@ +/* + * Copyright (C) 1999-2001 Harri Porten (porten@kde.org) + * Copyright (C) 2001 Peter Kelly (pmk@post.com) + * Copyright (C) 2006, 2007, 2008 Apple Inc. All rights reserved. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include "config.h" +#include "ScriptController.h" + +#include "Console.h" +#include "DOMWindow.h" +#include "Document.h" +#include "Event.h" +#include "EventNames.h" +#include "Frame.h" +#include "FrameLoader.h" +#include "GCController.h" +#include "JSDOMWindow.h" +#include "JSDocument.h" +#include "JSEventListener.h" +#include "npruntime_impl.h" +#include "NP_jsobject.h" +#include "Page.h" +#include "PageGroup.h" +#include "PausedTimeouts.h" +#include "runtime_root.h" +#include "Settings.h" +#include "StringSourceProvider.h" + +#include <kjs/completion.h> +#include <debugger/Debugger.h> +#include <runtime/JSLock.h> + +#if ENABLE(NETSCAPE_PLUGIN_API) +#include "HTMLPlugInElement.h" +#endif + +using namespace JSC; + +namespace WebCore { + +ScriptController::ScriptController(Frame* frame) + : m_frame(frame) + , m_handlerLineno(0) + , m_sourceURL(0) + , m_processingTimerCallback(false) + , m_paused(false) +#if ENABLE(NETSCAPE_PLUGIN_API) + , m_windowScriptNPObject(0) +#endif +#if PLATFORM(MAC) + , m_windowScriptObject(0) +#endif +{ +#if PLATFORM(MAC) && ENABLE(MAC_JAVA_BRIDGE) + static bool initializedJavaJSBindings; + if (!initializedJavaJSBindings) { + initializedJavaJSBindings = true; + initJavaJSBindings(); + } +#endif +} + +ScriptController::~ScriptController() +{ + if (m_windowShell) { + m_windowShell = 0; + + // It's likely that releasing the global object has created a lot of garbage. + gcController().garbageCollectSoon(); + } + + disconnectPlatformScriptObjects(); +} + +JSValue* ScriptController::evaluate(const String& sourceURL, int baseLine, const String& str) +{ + // evaluate code. Returns the JS return value or 0 + // if there was none, an error occured or the type couldn't be converted. + + initScriptIfNeeded(); + // inlineCode is true for <a href="javascript:doSomething()"> + // and false for <script>doSomething()</script>. Check if it has the + // expected value in all cases. + // See smart window.open policy for where this is used. + ExecState* exec = m_windowShell->window()->globalExec(); + const String* savedSourceURL = m_sourceURL; + m_sourceURL = &sourceURL; + + JSLock lock(false); + + // Evaluating the JavaScript could cause the frame to be deallocated + // so we start the keep alive timer here. + m_frame->keepAlive(); + + m_windowShell->window()->startTimeoutCheck(); + Completion comp = Interpreter::evaluate(exec, exec->dynamicGlobalObject()->globalScopeChain(), makeSource(str, sourceURL, baseLine), m_windowShell); + m_windowShell->window()->stopTimeoutCheck(); + + if (comp.complType() == Normal || comp.complType() == ReturnValue) { + m_sourceURL = savedSourceURL; + return comp.value(); + } + + if (comp.complType() == Throw) + m_frame->domWindow()->console()->reportException(exec, comp.value()); + + m_sourceURL = savedSourceURL; + return noValue(); +} + +void ScriptController::clearWindowShell() +{ + if (!m_windowShell) + return; + + JSLock lock(false); + m_windowShell->window()->clear(); + m_liveFormerWindows.add(m_windowShell->window()); + m_windowShell->setWindow(m_frame->domWindow()); + if (Page* page = m_frame->page()) { + attachDebugger(page->debugger()); + m_windowShell->window()->setProfileGroup(page->group().identifier()); + } + + // There is likely to be a lot of garbage now. + gcController().garbageCollectSoon(); +} + +PassRefPtr<EventListener> ScriptController::createInlineEventListener(const String& functionName, const String& code, Node* node) +{ + initScriptIfNeeded(); + JSLock lock(false); + return JSLazyEventListener::create(JSLazyEventListener::HTMLLazyEventListener, functionName, code, m_windowShell->window(), node, m_handlerLineno); +} + +#if ENABLE(SVG) +PassRefPtr<EventListener> ScriptController::createSVGEventHandler(const String& functionName, const String& code, Node* node) +{ + initScriptIfNeeded(); + JSLock lock(false); + return JSLazyEventListener::create(JSLazyEventListener::SVGLazyEventListener, functionName, code, m_windowShell->window(), node, m_handlerLineno); +} +#endif + +void ScriptController::initScript() +{ + if (m_windowShell) + return; + + JSLock lock(false); + + m_windowShell = new JSDOMWindowShell(m_frame->domWindow()); + updateDocument(); + + if (Page* page = m_frame->page()) { + attachDebugger(page->debugger()); + m_windowShell->window()->setProfileGroup(page->group().identifier()); + } + + m_frame->loader()->dispatchWindowObjectAvailable(); +} + +bool ScriptController::processingUserGesture() const +{ + if (!m_windowShell) + return false; + + if (Event* event = m_windowShell->window()->currentEvent()) { + const AtomicString& type = event->type(); + if ( // mouse events + type == eventNames().clickEvent || type == eventNames().mousedownEvent || + type == eventNames().mouseupEvent || type == eventNames().dblclickEvent || + // keyboard events + type == eventNames().keydownEvent || type == eventNames().keypressEvent || + type == eventNames().keyupEvent || +#if ENABLE(TOUCH_EVENTS) // Android + // touch events + type == eventNames().touchstartEvent || type == eventNames().touchmoveEvent || + type == eventNames().touchendEvent || type == eventNames().touchcancelEvent || +#endif + // other accepted events + type == eventNames().selectEvent || type == eventNames().changeEvent || + type == eventNames().focusEvent || type == eventNames().blurEvent || + type == eventNames().submitEvent) + return true; + } else { // no event + if (m_sourceURL && m_sourceURL->isNull() && !m_processingTimerCallback) { + // This is the <a href="javascript:window.open('...')> case -> we let it through + return true; + } + // This is the <script>window.open(...)</script> case or a timer callback -> block it + } + return false; +} + +bool ScriptController::isEnabled() +{ + Settings* settings = m_frame->settings(); + return (settings && settings->isJavaScriptEnabled()); +} + +void ScriptController::attachDebugger(JSC::Debugger* debugger) +{ + if (!m_windowShell) + return; + + if (debugger) + debugger->attach(m_windowShell->window()); + else if (JSC::Debugger* currentDebugger = m_windowShell->window()->debugger()) + currentDebugger->detach(m_windowShell->window()); +} + +void ScriptController::updateDocument() +{ + if (!m_frame->document()) + return; + + JSLock lock(false); + if (m_windowShell) + m_windowShell->window()->updateDocument(); + HashSet<JSDOMWindow*>::iterator end = m_liveFormerWindows.end(); + for (HashSet<JSDOMWindow*>::iterator it = m_liveFormerWindows.begin(); it != end; ++it) + (*it)->updateDocument(); +} + + +Bindings::RootObject* ScriptController::bindingRootObject() +{ + if (!isEnabled()) + return 0; + + if (!m_bindingRootObject) { + JSLock lock(false); + m_bindingRootObject = Bindings::RootObject::create(0, globalObject()); + } + return m_bindingRootObject.get(); +} + +PassRefPtr<Bindings::RootObject> ScriptController::createRootObject(void* nativeHandle) +{ + RootObjectMap::iterator it = m_rootObjects.find(nativeHandle); + if (it != m_rootObjects.end()) + return it->second; + + RefPtr<Bindings::RootObject> rootObject = Bindings::RootObject::create(nativeHandle, globalObject()); + + m_rootObjects.set(nativeHandle, rootObject); + return rootObject.release(); +} + +#if ENABLE(NETSCAPE_PLUGIN_API) +NPObject* ScriptController::windowScriptNPObject() +{ + if (!m_windowScriptNPObject) { + if (isEnabled()) { + // JavaScript is enabled, so there is a JavaScript window object. + // Return an NPObject bound to the window object. + JSC::JSLock lock(false); + JSObject* win = windowShell()->window(); + ASSERT(win); + Bindings::RootObject* root = bindingRootObject(); + m_windowScriptNPObject = _NPN_CreateScriptObject(0, win, root); + } else { + // JavaScript is not enabled, so we cannot bind the NPObject to the JavaScript window object. + // Instead, we create an NPObject of a different class, one which is not bound to a JavaScript object. + m_windowScriptNPObject = _NPN_CreateNoScriptObject(); + } + } + + return m_windowScriptNPObject; +} + +NPObject* ScriptController::createScriptObjectForPluginElement(HTMLPlugInElement* plugin) +{ + // Can't create NPObjects when JavaScript is disabled + if (!isEnabled()) + return _NPN_CreateNoScriptObject(); + + // Create a JSObject bound to this element + JSLock lock(false); + ExecState* exec = globalObject()->globalExec(); + JSValue* jsElementValue = toJS(exec, plugin); + if (!jsElementValue || !jsElementValue->isObject()) + return _NPN_CreateNoScriptObject(); + + // Wrap the JSObject in an NPObject + return _NPN_CreateScriptObject(0, jsElementValue->getObject(), bindingRootObject()); +} +#endif + +#if !PLATFORM(MAC) +void ScriptController::clearPlatformScriptObjects() +{ +} + +void ScriptController::disconnectPlatformScriptObjects() +{ +} +#endif + +void ScriptController::cleanupScriptObjectsForPlugin(void* nativeHandle) +{ + RootObjectMap::iterator it = m_rootObjects.find(nativeHandle); + + if (it == m_rootObjects.end()) + return; + + it->second->invalidate(); + m_rootObjects.remove(it); +} + +void ScriptController::clearScriptObjects() +{ + JSLock lock(false); + + RootObjectMap::const_iterator end = m_rootObjects.end(); + for (RootObjectMap::const_iterator it = m_rootObjects.begin(); it != end; ++it) + it->second->invalidate(); + + m_rootObjects.clear(); + + if (m_bindingRootObject) { + m_bindingRootObject->invalidate(); + m_bindingRootObject = 0; + } + +#if ENABLE(NETSCAPE_PLUGIN_API) + if (m_windowScriptNPObject) { + // Call _NPN_DeallocateObject() instead of _NPN_ReleaseObject() so that we don't leak if a plugin fails to release the window + // script object properly. + // This shouldn't cause any problems for plugins since they should have already been stopped and destroyed at this point. + _NPN_DeallocateObject(m_windowScriptNPObject); + m_windowScriptNPObject = 0; + } +#endif + + clearPlatformScriptObjects(); +} + +void ScriptController::pauseTimeouts(OwnPtr<PausedTimeouts>& result) +{ + if (!haveWindowShell()) { + result.clear(); + return; + } + + windowShell()->window()->pauseTimeouts(result); +} + +void ScriptController::resumeTimeouts(OwnPtr<PausedTimeouts>& pausedTimeouts) +{ + if (!haveWindowShell()) { + // Callers can assume we will always clear the passed in timeouts + pausedTimeouts.clear(); + return; + } + + windowShell()->window()->resumeTimeouts(pausedTimeouts); +} + +} // namespace WebCore diff --git a/WebCore/bindings/js/ScriptController.h b/WebCore/bindings/js/ScriptController.h new file mode 100644 index 0000000..047957c --- /dev/null +++ b/WebCore/bindings/js/ScriptController.h @@ -0,0 +1,160 @@ +/* + * Copyright (C) 1999 Harri Porten (porten@kde.org) + * Copyright (C) 2001 Peter Kelly (pmk@post.com) + * Copyright (C) 2008 Apple Inc. All rights reserved. + * Copyright (C) 2008 Eric Seidel <eric@webkit.org> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#ifndef ScriptController_h +#define ScriptController_h + +#include "JSDOMWindowShell.h" +#include <kjs/protect.h> +#include <wtf/RefPtr.h> + +#if PLATFORM(MAC) +#include <wtf/RetainPtr.h> + +#ifdef __OBJC__ +@class WebScriptObject; +#else +class WebScriptObject; +#endif +#endif + +struct NPObject; + +namespace JSC { + class JSGlobalObject; + + namespace Bindings { + class Instance; + class RootObject; + } +} + +namespace WebCore { + +class Event; +class EventListener; +class HTMLPlugInElement; +class Frame; +class Node; +class String; +class Widget; + +typedef HashMap<void*, RefPtr<JSC::Bindings::RootObject> > RootObjectMap; + +class ScriptController { +public: + ScriptController(Frame*); + ~ScriptController(); + + bool haveWindowShell() const { return m_windowShell; } + JSDOMWindowShell* windowShell() + { + initScriptIfNeeded(); + return m_windowShell; + } + + JSDOMWindow* globalObject() + { + initScriptIfNeeded(); + return m_windowShell->window(); + } + + JSC::JSValue* evaluate(const String& sourceURL, int baseLine, const String& code); + + PassRefPtr<EventListener> createInlineEventListener(const String& functionName, const String& code, Node*); +#if ENABLE(SVG) + PassRefPtr<EventListener> createSVGEventHandler(const String& functionName, const String& code, Node*); +#endif + void setEventHandlerLineno(int lineno) { m_handlerLineno = lineno; } + + void setProcessingTimerCallback(bool b) { m_processingTimerCallback = b; } + bool processingUserGesture() const; + + bool isEnabled(); + + void attachDebugger(JSC::Debugger*); + + void setPaused(bool b) { m_paused = b; } + bool isPaused() const { return m_paused; } + + const String* sourceURL() const { return m_sourceURL; } // 0 if we are not evaluating any script + + void clearWindowShell(); + void clearFormerWindow(JSDOMWindow* window) { m_liveFormerWindows.remove(window); } + void updateDocument(); + + void pauseTimeouts(OwnPtr<PausedTimeouts>&); + void resumeTimeouts(OwnPtr<PausedTimeouts>&); + + void clearScriptObjects(); + void cleanupScriptObjectsForPlugin(void*); + + PassRefPtr<JSC::Bindings::Instance> createScriptInstanceForWidget(Widget*); + JSC::Bindings::RootObject* bindingRootObject(); + + PassRefPtr<JSC::Bindings::RootObject> createRootObject(void* nativeHandle); + +#if PLATFORM(MAC) +#if ENABLE(MAC_JAVA_BRIDGE) + static void initJavaJSBindings(); +#endif + WebScriptObject* windowScriptObject(); +#endif + +#if ENABLE(NETSCAPE_PLUGIN_API) + NPObject* createScriptObjectForPluginElement(HTMLPlugInElement*); + NPObject* windowScriptNPObject(); +#endif + +private: + void initScriptIfNeeded() + { + if (!m_windowShell) + initScript(); + } + void initScript(); + + void clearPlatformScriptObjects(); + void disconnectPlatformScriptObjects(); + + JSC::ProtectedPtr<JSDOMWindowShell> m_windowShell; + HashSet<JSDOMWindow*> m_liveFormerWindows; + Frame* m_frame; + int m_handlerLineno; + const String* m_sourceURL; + + bool m_processingTimerCallback; + bool m_paused; + + // The root object used for objects bound outside the context of a plugin. + RefPtr<JSC::Bindings::RootObject> m_bindingRootObject; + RootObjectMap m_rootObjects; +#if ENABLE(NETSCAPE_PLUGIN_API) + NPObject* m_windowScriptNPObject; +#endif +#if PLATFORM(MAC) + RetainPtr<WebScriptObject> m_windowScriptObject; +#endif +}; + +} // namespace WebCore + +#endif // ScriptController_h diff --git a/WebCore/bindings/js/ScriptControllerAndroid.cpp b/WebCore/bindings/js/ScriptControllerAndroid.cpp new file mode 100644 index 0000000..6c95f44 --- /dev/null +++ b/WebCore/bindings/js/ScriptControllerAndroid.cpp @@ -0,0 +1,35 @@ +/* +** Copyright 2008, The Android Open Source Project +** +** Licensed under the Apache License, Version 2.0 (the "License"); +** you may not use this file except in compliance with the License. +** You may obtain a copy of the License at +** +** http://www.apache.org/licenses/LICENSE-2.0 +** +** Unless required by applicable law or agreed to in writing, software +** distributed under the License is distributed on an "AS IS" BASIS, +** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +** See the License for the specific language governing permissions and +** limitations under the License. +*/ + +#include "config.h" +#include "ScriptController.h" + +#include "PluginView.h" +#include "runtime.h" + +namespace WebCore { + +#ifdef ANDROID_PLUGINS +PassRefPtr<JSC::Bindings::Instance> ScriptController::createScriptInstanceForWidget(Widget* widget) +{ + if (!widget->isPluginView()) + return 0; + + return static_cast<PluginView*>(widget)->bindingInstance(); +} +#endif + +} // namespace WebCore diff --git a/WebCore/bindings/js/ScriptControllerGtk.cpp b/WebCore/bindings/js/ScriptControllerGtk.cpp new file mode 100644 index 0000000..c906034 --- /dev/null +++ b/WebCore/bindings/js/ScriptControllerGtk.cpp @@ -0,0 +1,48 @@ +/* + * Copyright (C) 2006 Apple Computer, Inc. All rights reserved. + * Copyright (C) 2006 Michael Emmel mike.emmel@gmail.com + * Copyright (C) 2007 Holger Hans Peter Freyther + * Copyright (C) 2008 Collabora Ltd. All rights reserved. + * Copyright (C) 2008 Eric Seidel <eric@webkit.org> + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "ScriptController.h" + +#include "PluginView.h" +#include "runtime_root.h" +#include "runtime.h" + +namespace WebCore { + +PassRefPtr<JSC::Bindings::Instance> ScriptController::createScriptInstanceForWidget(Widget* widget) +{ + if (!widget->isPluginView()) + return 0; + + return static_cast<PluginView*>(widget)->bindingInstance(); +} + +} diff --git a/WebCore/bindings/js/ScriptControllerMac.mm b/WebCore/bindings/js/ScriptControllerMac.mm new file mode 100644 index 0000000..df65352 --- /dev/null +++ b/WebCore/bindings/js/ScriptControllerMac.mm @@ -0,0 +1,170 @@ +/* + * Copyright (C) 2004, 2005, 2006, 2007, 2008 Apple Inc. All rights reserved. + * Copyright (C) 2006 Alexey Proskuryakov (ap@nypop.com) + * Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies) + * Copyright (C) 2008 Eric Seidel <eric@webkit.org> + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#import "config.h" +#import "ScriptController.h" + +#import "DOMAbstractViewFrame.h" +#import "DOMWindow.h" +#import "Frame.h" +#import "FrameLoader.h" +#import "FrameLoaderClient.h" +#import "JSDOMWindow.h" +#import "WebScriptObjectPrivate.h" +#import "Widget.h" +#import <JavaScriptCore/APICast.h> +#import <runtime/JSLock.h> + +#if ENABLE(NETSCAPE_PLUGIN_API) +#import "c_instance.h" +#import "NP_jsobject.h" +#import "npruntime_impl.h" +#endif + +#import "objc_instance.h" +#import "runtime_root.h" +#import "runtime.h" + +#if ENABLE(MAC_JAVA_BRIDGE) +#import "jni_instance.h" +#endif + +@interface NSObject (WebPlugin) +- (id)objectForWebScript; +- (NPObject *)createPluginScriptableObject; +@end + +using namespace JSC::Bindings; + +namespace WebCore { + +PassRefPtr<JSC::Bindings::Instance> ScriptController::createScriptInstanceForWidget(Widget* widget) +{ + NSView* widgetView = widget->platformWidget(); + if (!widgetView) + return 0; + + RefPtr<RootObject> rootObject = createRootObject(widgetView); + + if ([widgetView respondsToSelector:@selector(objectForWebScript)]) { + id objectForWebScript = [widgetView objectForWebScript]; + if (!objectForWebScript) + return 0; + return JSC::Bindings::ObjcInstance::create(objectForWebScript, rootObject.release()); + } + + if ([widgetView respondsToSelector:@selector(createPluginScriptableObject)]) { +#if !ENABLE(NETSCAPE_PLUGIN_API) + return 0; +#else + NPObject* npObject = [widgetView createPluginScriptableObject]; + if (!npObject) + return 0; + RefPtr<Instance> instance = JSC::Bindings::CInstance::create(npObject, rootObject.release()); + // -createPluginScriptableObject returns a retained NPObject. The caller is expected to release it. + _NPN_ReleaseObject(npObject); + return instance.release(); +#endif + } + +#if ENABLE(MAC_JAVA_BRIDGE) + jobject applet = m_frame->loader()->client()->javaApplet(widgetView); + if (!applet) + return 0; + return JSC::Bindings::JavaInstance::create(applet, rootObject.release()); +#else + return 0; +#endif +} + +WebScriptObject* ScriptController::windowScriptObject() +{ + if (!isEnabled()) + return 0; + + if (!m_windowScriptObject) { + JSC::JSLock lock(false); + JSC::Bindings::RootObject* root = bindingRootObject(); + m_windowScriptObject = [WebScriptObject scriptObjectForJSObject:toRef(windowShell()) originRootObject:root rootObject:root]; + } + + ASSERT([m_windowScriptObject.get() isKindOfClass:[DOMAbstractView class]]); + return m_windowScriptObject.get(); +} + +void ScriptController::clearPlatformScriptObjects() +{ + if (m_windowScriptObject) { + JSC::Bindings::RootObject* root = bindingRootObject(); + [m_windowScriptObject.get() _setOriginRootObject:root andRootObject:root]; + } +} + +void ScriptController::disconnectPlatformScriptObjects() +{ + if (m_windowScriptObject) { + ASSERT([m_windowScriptObject.get() isKindOfClass:[DOMAbstractView class]]); + [(DOMAbstractView *)m_windowScriptObject.get() _disconnectFrame]; + } +} + +#if ENABLE(MAC_JAVA_BRIDGE) +static pthread_t mainThread; + +static void updateRenderingForBindings(JSC::ExecState* exec, JSC::JSObject* rootObject) +{ + if (pthread_self() != mainThread) + return; + + if (!rootObject) + return; + + JSDOMWindow* window = static_cast<JSDOMWindow*>(rootObject); + if (!window) + return; + + Frame* frame = window->impl()->frame(); + if (!frame) + return; + + Document* document = frame->document(); + if (!document) + return; + + document->updateRendering(); +} + +void ScriptController::initJavaJSBindings() +{ + mainThread = pthread_self(); + JSC::Bindings::JavaJSObject::initializeJNIThreading(); + JSC::Bindings::Instance::setDidExecuteFunction(updateRenderingForBindings); +} +#endif + +} diff --git a/WebCore/bindings/js/ScriptControllerQt.cpp b/WebCore/bindings/js/ScriptControllerQt.cpp new file mode 100644 index 0000000..a09c7b7 --- /dev/null +++ b/WebCore/bindings/js/ScriptControllerQt.cpp @@ -0,0 +1,65 @@ +/* + * Copyright (C) 2006 Dirk Mueller <mueller@kde.org> + * Copyright (C) 2006 Zack Rusin <zack@kde.org> + * Copyright (C) 2006 George Staikos <staikos@kde.org> + * Copyright (C) 2006 Simon Hausmann <hausmann@kde.org> + * Copyright (C) 2006 Rob Buis <buis@kde.org> + * Copyright (C) 2006 Nikolas Zimmermann <zimmermann@kde.org> + * Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies) + * Copyright (C) 2008 Collabora Ltd. All rights reserved. + * Copyright (C) 2008 Eric Seidel <eric@webkit.org> + * + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "ScriptController.h" + +#include "DOMWindow.h" +#include "PluginView.h" +#include "qt_instance.h" +#include "runtime_root.h" +#include "runtime.h" + +#include <QWidget> + +namespace WebCore { + +PassRefPtr<JSC::Bindings::Instance> ScriptController::createScriptInstanceForWidget(WebCore::Widget* widget) +{ + if (!widget->isPluginView()) + return 0; + + PluginView* pluginView = static_cast<PluginView*>(widget); + if (pluginView->isNPAPIPlugin()) + return pluginView->bindingInstance(); + + QWidget* platformWidget = widget->platformWidget(); + if (!platformWidget) + return 0; + return JSC::Bindings::QtInstance::getQtInstance(platformWidget, bindingRootObject()); +} + +} +// vim: ts=4 sw=4 et diff --git a/WebCore/bindings/js/ScriptControllerWin.cpp b/WebCore/bindings/js/ScriptControllerWin.cpp new file mode 100644 index 0000000..703cf7c --- /dev/null +++ b/WebCore/bindings/js/ScriptControllerWin.cpp @@ -0,0 +1,45 @@ +/* + * Copyright (C) 2006, 2007, 2008 Apple Inc. All rights reserved. + * Copyright (C) 2008 Eric Seidel <eric@webkit.org> + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "ScriptController.h" + +#include "PluginView.h" +#include "runtime.h" + +using namespace JSC::Bindings; + +namespace WebCore { + +PassRefPtr<JSC::Bindings::Instance> ScriptController::createScriptInstanceForWidget(Widget* widget) +{ + if (!widget->isPluginView()) + return 0; + + return static_cast<PluginView*>(widget)->bindingInstance(); +} + +} // namespace WebCore diff --git a/WebCore/bindings/js/ScriptControllerWx.cpp b/WebCore/bindings/js/ScriptControllerWx.cpp new file mode 100644 index 0000000..1c14928 --- /dev/null +++ b/WebCore/bindings/js/ScriptControllerWx.cpp @@ -0,0 +1,44 @@ +/* + * Copyright (C) 2008 Apple Computer, Inc. All rights reserved. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "ScriptController.h" + +#include "PluginView.h" +#include "runtime_root.h" +#include "runtime.h" + +namespace WebCore { + +PassRefPtr<JSC::Bindings::Instance> ScriptController::createScriptInstanceForWidget(Widget* widget) +{ + if (!widget->isPluginView()) + return 0; + + return static_cast<PluginView*>(widget)->bindingInstance(); +} + +} diff --git a/WebCore/bindings/js/StringSourceProvider.h b/WebCore/bindings/js/StringSourceProvider.h new file mode 100644 index 0000000..faa848c --- /dev/null +++ b/WebCore/bindings/js/StringSourceProvider.h @@ -0,0 +1,60 @@ +/* + * Copyright (C) 2008 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of + * its contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef StringSourceProvider_h +#define StringSourceProvider_h + +#include <kjs/SourceCode.h> + +namespace WebCore { + + class StringSourceProvider : public JSC::SourceProvider { + public: + static PassRefPtr<StringSourceProvider> create(const String& source, const String& url) { return adoptRef(new StringSourceProvider(source, url)); } + + JSC::UString getRange(int start, int end) const { return JSC::UString(m_source.characters() + start, end - start); } + const UChar* data() const { return m_source.characters(); } + int length() const { return m_source.length(); } + + private: + StringSourceProvider(const String& source, const String& url) + : SourceProvider(url) + , m_source(source) + { + } + + String m_source; + }; + + inline JSC::SourceCode makeSource(const String& source, const JSC::UString& url = JSC::UString(), int firstLine = 1) + { + return JSC::SourceCode(StringSourceProvider::create(source, url), firstLine); + } +} + +#endif diff --git a/WebCore/bindings/js/kjs_binding.cpp b/WebCore/bindings/js/kjs_binding.cpp deleted file mode 100644 index 31078c7..0000000 --- a/WebCore/bindings/js/kjs_binding.cpp +++ /dev/null @@ -1,362 +0,0 @@ -/* - * Copyright (C) 1999-2001 Harri Porten (porten@kde.org) - * Copyright (C) 2004, 2005, 2006, 2007, 2008 Apple Inc. All rights reserved. - * Copyright (C) 2007 Samuel Weinig <sam@webkit.org> - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -// gcc 3.x can't handle including the HashMap pointer specialization in this file -#if defined __GNUC__ && !defined __GLIBCXX__ // less than gcc 3.4 -#define HASH_MAP_PTR_SPEC_WORKAROUND 1 -#endif - -#include "config.h" -#include "kjs_binding.h" - -#include "DOMCoreException.h" -#include "EventException.h" -#include "ExceptionCode.h" -#include "HTMLImageElement.h" -#include "HTMLNames.h" -#include "JSDOMCoreException.h" -#include "JSEventException.h" -#include "JSNode.h" -#include "JSRangeException.h" -#include "JSXMLHttpRequestException.h" -#include "RangeException.h" -#include "XMLHttpRequestException.h" -#include "kjs_window.h" - -#if ENABLE(SVG) -#include "JSSVGException.h" -#include "SVGException.h" -#endif - -#if ENABLE(XPATH) -#include "JSXPathException.h" -#include "XPathException.h" -#endif - -using namespace KJS; -using namespace WebCore; -using namespace HTMLNames; - -// FIXME: Move all this stuff into the WebCore namespace. - -namespace KJS { - -typedef HashMap<void*, DOMObject*> DOMObjectMap; -typedef HashMap<WebCore::Node*, JSNode*> NodeMap; -typedef HashMap<Document*, NodeMap*> NodePerDocMap; - -// For debugging, keep a set of wrappers currently registered, and check that -// all are unregistered before they are destroyed. This has helped us fix at -// least one bug. - -static void addWrapper(DOMObject* wrapper); -static void removeWrapper(DOMObject* wrapper); -static void removeWrappers(const NodeMap& wrappers); - -#ifdef NDEBUG - -static inline void addWrapper(DOMObject*) -{ -} - -static inline void removeWrapper(DOMObject*) -{ -} - -static inline void removeWrappers(const NodeMap&) -{ -} - -#else - -static HashSet<DOMObject*>& wrapperSet() -{ - static HashSet<DOMObject*> staticWrapperSet; - return staticWrapperSet; -} - -static void addWrapper(DOMObject* wrapper) -{ - ASSERT(!wrapperSet().contains(wrapper)); - wrapperSet().add(wrapper); -} - -static void removeWrapper(DOMObject* wrapper) -{ - if (!wrapper) - return; - ASSERT(wrapperSet().contains(wrapper)); - wrapperSet().remove(wrapper); -} - -static void removeWrappers(const NodeMap& wrappers) -{ - for (NodeMap::const_iterator it = wrappers.begin(); it != wrappers.end(); ++it) - removeWrapper(it->second); -} - -DOMObject::~DOMObject() -{ - ASSERT(!wrapperSet().contains(this)); -} - -#endif - -static DOMObjectMap& domObjects() -{ - // Don't use malloc here. Calling malloc from a mark function can deadlock. - static DOMObjectMap staticDOMObjects; - return staticDOMObjects; -} - -static NodePerDocMap& domNodesPerDocument() -{ - // domNodesPerDocument() callers must synchronize using the JSLock because - // domNodesPerDocument() is called from a mark function, which can run - // on a secondary thread. - ASSERT(JSLock::lockCount()); - - // Don't use malloc here. Calling malloc from a mark function can deadlock. - static NodePerDocMap staticDOMNodesPerDocument; - return staticDOMNodesPerDocument; -} - -DOMObject* ScriptInterpreter::getDOMObject(void* objectHandle) -{ - return domObjects().get(objectHandle); -} - -void ScriptInterpreter::putDOMObject(void* objectHandle, DOMObject* wrapper) -{ - addWrapper(wrapper); - domObjects().set(objectHandle, wrapper); -} - -void ScriptInterpreter::forgetDOMObject(void* objectHandle) -{ - removeWrapper(domObjects().take(objectHandle)); -} - -JSNode* ScriptInterpreter::getDOMNodeForDocument(Document* document, WebCore::Node* node) -{ - if (!document) - return static_cast<JSNode*>(domObjects().get(node)); - NodeMap* documentDict = domNodesPerDocument().get(document); - if (documentDict) - return documentDict->get(node); - return NULL; -} - -void ScriptInterpreter::forgetDOMNodeForDocument(Document* document, WebCore::Node* node) -{ - if (!document) { - removeWrapper(domObjects().take(node)); - return; - } - NodeMap* documentDict = domNodesPerDocument().get(document); - if (documentDict) - removeWrapper(documentDict->take(node)); -} - -void ScriptInterpreter::putDOMNodeForDocument(Document* document, WebCore::Node* node, JSNode* wrapper) -{ - addWrapper(wrapper); - if (!document) { - domObjects().set(node, wrapper); - return; - } - NodeMap* documentDict = domNodesPerDocument().get(document); - if (!documentDict) { - documentDict = new NodeMap; - domNodesPerDocument().set(document, documentDict); - } - documentDict->set(node, wrapper); -} - -void ScriptInterpreter::forgetAllDOMNodesForDocument(Document* document) -{ - ASSERT(document); - NodeMap* map = domNodesPerDocument().take(document); - if (!map) - return; - removeWrappers(*map); - delete map; -} - -void ScriptInterpreter::markDOMNodesForDocument(Document* doc) -{ - NodePerDocMap::iterator dictIt = domNodesPerDocument().find(doc); - if (dictIt != domNodesPerDocument().end()) { - NodeMap* nodeDict = dictIt->second; - NodeMap::iterator nodeEnd = nodeDict->end(); - for (NodeMap::iterator nodeIt = nodeDict->begin(); nodeIt != nodeEnd; ++nodeIt) { - JSNode* jsNode = nodeIt->second; - WebCore::Node* node = jsNode->impl(); - - // don't mark wrappers for nodes that are no longer in the - // document - they should not be saved if the node is not - // otherwise reachable from JS. - // However, image elements that aren't in the document are also - // marked, if they are not done loading yet. - if (!jsNode->marked() && (node->inDocument() || (node->hasTagName(imgTag) && - !static_cast<HTMLImageElement*>(node)->haveFiredLoadEvent()))) - jsNode->mark(); - } - } -} - -void ScriptInterpreter::updateDOMNodeDocument(WebCore::Node* node, Document* oldDoc, Document* newDoc) -{ - ASSERT(oldDoc != newDoc); - JSNode* wrapper = getDOMNodeForDocument(oldDoc, node); - if (wrapper) { - removeWrapper(wrapper); - putDOMNodeForDocument(newDoc, node, wrapper); - forgetDOMNodeForDocument(oldDoc, node); - addWrapper(wrapper); - } -} - -JSValue* jsStringOrNull(const String& s) -{ - if (s.isNull()) - return jsNull(); - return jsString(s); -} - -JSValue* jsOwnedStringOrNull(const KJS::UString& s) -{ - if (s.isNull()) - return jsNull(); - return jsOwnedString(s); -} - -JSValue* jsStringOrUndefined(const String& s) -{ - if (s.isNull()) - return jsUndefined(); - return jsString(s); -} - -JSValue* jsStringOrFalse(const String& s) -{ - if (s.isNull()) - return jsBoolean(false); - return jsString(s); -} - -String valueToStringWithNullCheck(ExecState* exec, JSValue* val) -{ - if (val->isNull()) - return String(); - return val->toString(exec); -} - -String valueToStringWithUndefinedOrNullCheck(ExecState* exec, JSValue* val) -{ - if (val->isUndefinedOrNull()) - return String(); - return val->toString(exec); -} - -void setDOMException(ExecState* exec, ExceptionCode ec) -{ - if (!ec || exec->hadException()) - return; - - // To be removed: See XMLHttpRequest.h. - if (ec == XMLHttpRequestException::PERMISSION_DENIED) { - throwError(exec, GeneralError, "Permission denied"); - return; - } - - ExceptionCodeDescription description; - getExceptionCodeDescription(ec, description); - - JSValue* errorObject = 0; - switch (description.type) { - case DOMExceptionType: - errorObject = toJS(exec, new DOMCoreException(description)); - break; - case RangeExceptionType: - errorObject = toJS(exec, new RangeException(description)); - break; - case EventExceptionType: - errorObject = toJS(exec, new EventException(description)); - break; - case XMLHttpRequestExceptionType: - errorObject = toJS(exec, new XMLHttpRequestException(description)); - break; -#if ENABLE(SVG) - case SVGExceptionType: - errorObject = toJS(exec, new SVGException(description), 0); - break; -#endif -#if ENABLE(XPATH) - case XPathExceptionType: - errorObject = toJS(exec, new XPathException(description)); - break; -#endif - } - - ASSERT(errorObject); - exec->setException(errorObject); -} - -} // namespace KJS - -namespace WebCore { - -bool allowsAccessFromFrame(ExecState* exec, Frame* frame) -{ - if (!frame) - return false; - Window* window = Window::retrieveWindow(frame); - return window && window->allowsAccessFrom(exec); -} - -bool allowsAccessFromFrame(ExecState* exec, Frame* frame, String& message) -{ - if (!frame) - return false; - Window* window = Window::retrieveWindow(frame); - return window && window->allowsAccessFrom(exec, message); -} - -void printErrorMessageForFrame(Frame* frame, const String& message) -{ - if (!frame) - return; - if (Window* window = Window::retrieveWindow(frame)) - window->printErrorMessage(message); -} - -JSValue* nonCachingStaticFunctionGetter(ExecState* exec, JSObject*, const Identifier& propertyName, const PropertySlot& slot) -{ - const HashEntry* entry = slot.staticEntry(); - return new PrototypeFunction(exec, entry->params, propertyName, entry->value.functionValue); -} - -JSValue* objectToStringFunctionGetter(ExecState* exec, JSObject*, const Identifier& propertyName, const PropertySlot&) -{ - return new PrototypeFunction(exec, 0, propertyName, objectProtoFuncToString); -} - -} // namespace WebCore diff --git a/WebCore/bindings/js/kjs_binding.h b/WebCore/bindings/js/kjs_binding.h deleted file mode 100644 index 00e98d5..0000000 --- a/WebCore/bindings/js/kjs_binding.h +++ /dev/null @@ -1,159 +0,0 @@ -/* - * Copyright (C) 1999-2001 Harri Porten (porten@kde.org) - * Copyright (C) 2003, 2004, 2005, 2006, 2008 Apple Inc. All rights reserved. - * Copyright (C) 2007 Samuel Weinig <sam@webkit.org> - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#ifndef kjs_binding_h -#define kjs_binding_h - -#include <kjs/function.h> -#include <kjs/interpreter.h> -#include <kjs/lookup.h> -#include <wtf/Noncopyable.h> - -#if PLATFORM(MAC) -#include <JavaScriptCore/runtime.h> -#endif - -namespace WebCore { - class AtomicString; - class Document; - class Event; - class Frame; - class Node; - class String; - class JSNode; - - typedef int ExceptionCode; - -#if ENABLE(SVG) - class SVGElement; -#endif -} - -namespace KJS { - - /** - * Base class for all objects in this binding EXCEPT Window - */ - class DOMObject : public JSObject { - protected: - explicit DOMObject(JSValue* prototype) // FIXME: this should take a JSObject once JSLocation has a real prototype - : JSObject(prototype) - { - // DOMObject destruction is not thread-safe because DOMObjects wrap - // unsafe WebCore DOM data structures. - Collector::collectOnMainThreadOnly(this); - } - -#ifndef NDEBUG - virtual ~DOMObject(); -#endif - - private: - DOMObject(); - }; - - class ScriptInterpreter : public Interpreter { - public: - static DOMObject* getDOMObject(void* objectHandle); - static void putDOMObject(void* objectHandle, DOMObject*); - static void forgetDOMObject(void* objectHandle); - - static WebCore::JSNode* getDOMNodeForDocument(WebCore::Document*, WebCore::Node*); - static void putDOMNodeForDocument(WebCore::Document*, WebCore::Node*, WebCore::JSNode* nodeWrapper); - static void forgetDOMNodeForDocument(WebCore::Document*, WebCore::Node*); - static void forgetAllDOMNodesForDocument(WebCore::Document*); - static void updateDOMNodeDocument(WebCore::Node*, WebCore::Document* oldDoc, WebCore::Document* newDoc); - static void markDOMNodesForDocument(WebCore::Document*); - }; - - /** - * Retrieve from cache, or create, a JS object around a DOM object - */ - template<class DOMObj, class JSDOMObj, class JSDOMObjPrototype> inline JSValue* cacheDOMObject(ExecState* exec, DOMObj* domObj) - { - if (!domObj) - return jsNull(); - if (DOMObject* ret = ScriptInterpreter::getDOMObject(domObj)) - return ret; - DOMObject* ret = new JSDOMObj(JSDOMObjPrototype::self(exec), domObj); - ScriptInterpreter::putDOMObject(domObj, ret); - return ret; - } - -#if ENABLE(SVG) - /** - * Retrieve from cache, or create, a JS object around a SVG DOM object - */ - template<class DOMObj, class JSDOMObj, class JSDOMObjPrototype> inline JSValue* cacheSVGDOMObject(ExecState* exec, DOMObj* domObj, WebCore::SVGElement* context) - { - if (!domObj) - return jsNull(); - if (DOMObject* ret = ScriptInterpreter::getDOMObject(domObj)) - return ret; - DOMObject* ret = new JSDOMObj(JSDOMObjPrototype::self(exec), domObj, context); - ScriptInterpreter::putDOMObject(domObj, ret); - return ret; - } -#endif - - // Convert a DOM implementation exception code into a JavaScript exception in the execution state. - void setDOMException(ExecState*, WebCore::ExceptionCode); - - // Helper class to call setDOMException on exit without adding lots of separate calls to that function. - class DOMExceptionTranslator : Noncopyable { - public: - explicit DOMExceptionTranslator(ExecState* exec) : m_exec(exec), m_code(0) { } - ~DOMExceptionTranslator() { setDOMException(m_exec, m_code); } - operator WebCore::ExceptionCode&() { return m_code; } - private: - ExecState* m_exec; - WebCore::ExceptionCode m_code; - }; - - JSValue* jsStringOrNull(const WebCore::String&); // null if the string is null - JSValue* jsStringOrUndefined(const WebCore::String&); // undefined if the string is null - JSValue* jsStringOrFalse(const WebCore::String&); // boolean false if the string is null - - // see JavaScriptCore for explanation should be used for UString that is already owned - // by another object, so that collecting the JSString wrapper is unlikely to save memory. - JSValue* jsOwnedStringOrNull(const KJS::UString&); - - WebCore::String valueToStringWithNullCheck(ExecState*, JSValue*); // null String if the value is null - WebCore::String valueToStringWithUndefinedOrNullCheck(ExecState*, JSValue*); // null String if the value is null or undefined - - template <typename T> inline JSValue* toJS(ExecState* exec, PassRefPtr<T> ptr) { return toJS(exec, ptr.get()); } - -} // namespace KJS - -namespace WebCore { - - // Helpers for Window, History, and Location classes to implement cross-domain policy. - // Besides the cross-domain check, they need non-caching versions of staticFunctionGetter for - // because we do not want current property values involved at all. - bool allowsAccessFromFrame(KJS::ExecState*, Frame*); - bool allowsAccessFromFrame(KJS::ExecState*, Frame*, String& message); - void printErrorMessageForFrame(Frame*, const String& message); - - KJS::JSValue* nonCachingStaticFunctionGetter(KJS::ExecState*, KJS::JSObject*, const KJS::Identifier& propertyName, const KJS::PropertySlot&); - KJS::JSValue* objectToStringFunctionGetter(KJS::ExecState*, KJS::JSObject*, const KJS::Identifier& propertyName, const KJS::PropertySlot&); - -} // namespace WebCore - -#endif // kjs_binding_h diff --git a/WebCore/bindings/js/kjs_css.cpp b/WebCore/bindings/js/kjs_css.cpp deleted file mode 100644 index e2ab70d..0000000 --- a/WebCore/bindings/js/kjs_css.cpp +++ /dev/null @@ -1,85 +0,0 @@ -// -*- c-basic-offset: 2 -*- -/* - * Copyright (C) 2000 Harri Porten (porten@kde.org) - * Copyright (C) 2001 Peter Kelly (pmk@post.com) - * Copyright (C) 2004, 2005, 2006, 2007 Apple Inc. All rights reserved. - * Copyright (C) 2006 James G. Speth (speth@end.com) - * Copyright (C) 2006 Samuel Weinig (sam@webkit.org) - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#include "config.h" -#include "kjs_css.h" - -#include "CSSPrimitiveValue.h" -#include "JSCSSPrimitiveValue.h" -#include "kjs_dom.h" - -#include "kjs_css.lut.h" - -namespace WebCore { - -using namespace KJS; - -const ClassInfo JSRGBColor::info = { "RGBColor", 0, &JSRGBColorTable }; - -/* -@begin JSRGBColorTable 3 - red WebCore::JSRGBColor::Red DontDelete|ReadOnly - green WebCore::JSRGBColor::Green DontDelete|ReadOnly - blue WebCore::JSRGBColor::Blue DontDelete|ReadOnly -@end -*/ - -JSRGBColor::JSRGBColor(JSObject* prototype, unsigned color) - : DOMObject(prototype) - , m_color(color) -{ -} - -JSRGBColor::~JSRGBColor() -{ -} - -bool JSRGBColor::getOwnPropertySlot(ExecState* exec, const Identifier& propertyName, PropertySlot& slot) -{ - return getStaticValueSlot<JSRGBColor, DOMObject>(exec, &JSRGBColorTable, this, propertyName, slot); -} - -JSValue* JSRGBColor::getValueProperty(ExecState* exec, int token) const -{ - int color = m_color; - switch (token) { - case Red: - color >>= 8; - // fall through - case Green: - color >>= 8; - // fall through - case Blue: - return toJS(exec, new CSSPrimitiveValue(color & 0xFF, CSSPrimitiveValue::CSS_NUMBER)); - default: - return 0; - } -} - -JSValue* getJSRGBColor(ExecState* exec, unsigned color) -{ - // FIXME: implement equals for RGBColor since they're not refcounted objects - return new JSRGBColor(exec->lexicalGlobalObject()->objectPrototype(), color); -} - -} // namespace WebCore diff --git a/WebCore/bindings/js/kjs_dom.cpp b/WebCore/bindings/js/kjs_dom.cpp deleted file mode 100644 index 0f8c616..0000000 --- a/WebCore/bindings/js/kjs_dom.cpp +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Copyright (C) 2000 Harri Porten (porten@kde.org) - * Copyright (C) 2006 Jon Shier (jshier@iastate.edu) - * Copyright (C) 2004, 2005, 2006, 2007 Apple Inc. All rights reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#include "config.h" -#include "kjs_dom.h" - -#include "Document.h" -#include "EventTarget.h" -#include "Frame.h" -#include "HTMLNames.h" -#include "HTMLPlugInElement.h" -#include "JSAttr.h" -#include "JSNode.h" -#include "XMLHttpRequest.h" -#include "kjs_events.h" -#include "kjs_window.h" - -#if ENABLE(SVG) -#include "JSSVGElementInstance.h" -#endif - -#if USE(JAVASCRIPTCORE_BINDINGS) -#include <bindings/runtime_object.h> -#endif - -namespace WebCore { - -using namespace KJS; -using namespace HTMLNames; - -Attr* toAttr(JSValue* val, bool& ok) -{ - if (!val || !val->isObject(&JSAttr::info)) { - ok = false; - return 0; - } - - ok = true; - return static_cast<Attr*>(static_cast<JSNode*>(val)->impl()); -} - -bool checkNodeSecurity(ExecState* exec, Node* node) -{ - return node && allowsAccessFromFrame(exec, node->document()->frame()); -} - -JSValue* toJS(ExecState* exec, EventTarget* target) -{ - if (!target) - return jsNull(); - -#if ENABLE(SVG) - // SVGElementInstance supports both toSVGElementInstance and toNode since so much mouse handling code depends on toNode returning a valid node. - SVGElementInstance* instance = target->toSVGElementInstance(); - if (instance) - return toJS(exec, instance); -#endif - - Node* node = target->toNode(); - if (node) - return toJS(exec, node); - - if (XMLHttpRequest* xhr = target->toXMLHttpRequest()) - // XMLHttpRequest is always created via JS, so we don't need to use cacheDOMObject() here. - return ScriptInterpreter::getDOMObject(xhr); - - // There are two kinds of EventTargets: EventTargetNode and XMLHttpRequest. - // If SVG support is enabled, there is also SVGElementInstance. - ASSERT(0); - return jsNull(); -} - -JSValue* getRuntimeObject(ExecState* exec, Node* n) -{ - if (!n) - return 0; - -#if USE(JAVASCRIPTCORE_BINDINGS) - if (n->hasTagName(objectTag) || n->hasTagName(embedTag) || n->hasTagName(appletTag)) { - HTMLPlugInElement* plugInElement = static_cast<HTMLPlugInElement*>(n); - if (plugInElement->getInstance() && plugInElement->getInstance()->rootObject()) - // The instance is owned by the PlugIn element. - return KJS::Bindings::Instance::createRuntimeObject(plugInElement->getInstance()); - } -#endif - - // If we don't have a runtime object return 0. - return 0; -} - -} // namespace WebCore diff --git a/WebCore/bindings/js/kjs_events.cpp b/WebCore/bindings/js/kjs_events.cpp deleted file mode 100644 index 8976c04..0000000 --- a/WebCore/bindings/js/kjs_events.cpp +++ /dev/null @@ -1,519 +0,0 @@ -/* - * Copyright (C) 2001 Peter Kelly (pmk@post.com) - * Copyright (C) 2003, 2004, 2005, 2006, 2007 Apple Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#include "config.h" -#include "kjs_events.h" - -#include "CString.h" -#include "Chrome.h" -#include "Clipboard.h" -#include "ClipboardEvent.h" -#include "DOMWindow.h" -#include "Document.h" -#include "Event.h" -#include "EventNames.h" -#include "Frame.h" -#include "FrameLoader.h" -#include "HTMLImageElement.h" -#include "HTMLNames.h" -#include "JSEvent.h" -#include "JSEventTargetNode.h" -#include "KURL.h" -#include "Page.h" -#include "kjs_proxy.h" -#include "kjs_window.h" -#include <kjs/array_object.h> -#include <kjs/function_object.h> - -#include "kjs_events.lut.h" - -namespace WebCore { - -using namespace KJS; -using namespace EventNames; -using namespace HTMLNames; - -JSAbstractEventListener::JSAbstractEventListener(bool html) - : m_html(html) -{ -} - -void JSAbstractEventListener::handleEvent(Event* ele, bool isWindowEvent) -{ -#ifdef KJS_DEBUGGER - if (KJSDebugWin::instance() && KJSDebugWin::instance()->inSession()) - return; -#endif - - Event* event = ele; - - JSObject* listener = listenerObj(); - if (!listener) - return; - - KJS::Window* window = windowObj(); - // Null check as clearWindowObj() can clear this and we still get called back by - // xmlhttprequest objects. See http://bugs.webkit.org/show_bug.cgi?id=13275 - if (!window) - return; - Frame *frame = window->impl()->frame(); - if (!frame) - return; - if (!frame->scriptProxy()->isEnabled()) - return; - - JSLock lock; - - JSGlobalObject* globalObject = frame->scriptProxy()->globalObject(); - ExecState* exec = globalObject->globalExec(); - - JSValue* handleEventFuncValue = listener->get(exec, "handleEvent"); - JSObject* handleEventFunc = 0; - if (handleEventFuncValue->isObject()) { - handleEventFunc = static_cast<JSObject*>(handleEventFuncValue); - if (!handleEventFunc->implementsCall()) - handleEventFunc = 0; - } - - if (handleEventFunc || listener->implementsCall()) { - ref(); - - List args; - args.append(toJS(exec, event)); - - window->setCurrentEvent(event); - - JSValue* retval; - if (handleEventFunc) { - globalObject->startTimeoutCheck(); - retval = handleEventFunc->call(exec, listener, args); - } else { - JSObject* thisObj; - if (isWindowEvent) - thisObj = window; - else - thisObj = static_cast<JSObject*>(toJS(exec, event->currentTarget())); - globalObject->startTimeoutCheck(); - retval = listener->call(exec, thisObj, args); - } - globalObject->stopTimeoutCheck(); - - window->setCurrentEvent(0); - - if (exec->hadException()) { - JSObject* exception = exec->exception()->toObject(exec); - String message = exception->get(exec, exec->propertyNames().message)->toString(exec); - int lineNumber = exception->get(exec, "line")->toInt32(exec); - String sourceURL = exception->get(exec, "sourceURL")->toString(exec); - if (Interpreter::shouldPrintExceptions()) - printf("(event handler):%s\n", message.utf8().data()); - if (Page* page = frame->page()) - page->chrome()->addMessageToConsole(JSMessageSource, ErrorMessageLevel, message, lineNumber, sourceURL); - exec->clearException(); - } else { - if (!retval->isUndefinedOrNull() && event->storesResultAsString()) - event->storeResult(retval->toString(exec)); - if (m_html) { - bool retvalbool; - if (retval->getBoolean(retvalbool) && !retvalbool) - event->preventDefault(); - } - } - - Document::updateDocumentsRendering(); - deref(); - } -} - -bool JSAbstractEventListener::isHTMLEventListener() const -{ - return m_html; -} - -// ------------------------------------------------------------------------- - -JSUnprotectedEventListener::JSUnprotectedEventListener(JSObject* listener, KJS::Window* win, bool html) - : JSAbstractEventListener(html) - , m_listener(listener) - , m_win(win) -{ - if (m_listener) { - KJS::Window::UnprotectedListenersMap& listeners = html - ? m_win->jsUnprotectedHTMLEventListeners() : m_win->jsUnprotectedEventListeners(); - listeners.set(m_listener, this); - } -} - -JSUnprotectedEventListener::~JSUnprotectedEventListener() -{ - if (m_listener && m_win) { - KJS::Window::UnprotectedListenersMap& listeners = isHTMLEventListener() - ? m_win->jsUnprotectedHTMLEventListeners() : m_win->jsUnprotectedEventListeners(); - listeners.remove(m_listener); - } -} - -JSObject* JSUnprotectedEventListener::listenerObj() const -{ - return m_listener; -} - -KJS::Window* JSUnprotectedEventListener::windowObj() const -{ - return m_win; -} - -void JSUnprotectedEventListener::clearWindowObj() -{ - m_win = 0; -} - -void JSUnprotectedEventListener::mark() -{ - if (m_listener && !m_listener->marked()) - m_listener->mark(); -} - -#ifndef NDEBUG -#ifndef LOG_CHANNEL_PREFIX -#define LOG_CHANNEL_PREFIX Log -#endif -WTFLogChannel LogWebCoreEventListenerLeaks = { 0x00000000, "", WTFLogChannelOn }; - -struct EventListenerCounter { - static unsigned count; - ~EventListenerCounter() - { - if (count) - LOG(WebCoreEventListenerLeaks, "LEAK: %u EventListeners\n", count); - } -}; -unsigned EventListenerCounter::count = 0; -static EventListenerCounter eventListenerCounter; -#endif - -// ------------------------------------------------------------------------- - -JSEventListener::JSEventListener(JSObject* listener, KJS::Window* win, bool html) - : JSAbstractEventListener(html) - , m_listener(listener) - , m_win(win) -{ - if (m_listener) { - KJS::Window::ListenersMap& listeners = html - ? m_win->jsHTMLEventListeners() : m_win->jsEventListeners(); - listeners.set(m_listener, this); - } -#ifndef NDEBUG - ++eventListenerCounter.count; -#endif -} - -JSEventListener::~JSEventListener() -{ - if (m_listener && m_win) { - KJS::Window::ListenersMap& listeners = isHTMLEventListener() - ? m_win->jsHTMLEventListeners() : m_win->jsEventListeners(); - listeners.remove(m_listener); - } -#ifndef NDEBUG - --eventListenerCounter.count; -#endif -} - -JSObject* JSEventListener::listenerObj() const -{ - return m_listener; -} - -KJS::Window* JSEventListener::windowObj() const -{ - return m_win; -} - -void JSEventListener::clearWindowObj() -{ - m_win = 0; -} - -// ------------------------------------------------------------------------- - -JSLazyEventListener::JSLazyEventListener(const String& functionName, const String& code, KJS::Window* win, Node* node, int lineNumber) - : JSEventListener(0, win, true) - , m_functionName(functionName) - , m_code(code) - , m_parsed(false) - , m_lineNumber(lineNumber) - , m_originalNode(node) -{ - // We don't retain the original node because we assume it - // will stay alive as long as this handler object is around - // and we need to avoid a reference cycle. If JS transfers - // this handler to another node, parseCode will be called and - // then originalNode is no longer needed. -} - -JSObject* JSLazyEventListener::listenerObj() const -{ - parseCode(); - return m_listener; -} - -JSValue* JSLazyEventListener::eventParameterName() const -{ - static ProtectedPtr<JSValue> eventString = jsString("event"); - return eventString.get(); -} - -void JSLazyEventListener::parseCode() const -{ - if (m_parsed) - return; - m_parsed = true; - - Frame* frame = windowObj()->impl()->frame(); - if (frame && frame->scriptProxy()->isEnabled()) { - ExecState* exec = frame->scriptProxy()->globalObject()->globalExec(); - - JSLock lock; - JSObject* constr = frame->scriptProxy()->globalObject()->functionConstructor(); - List args; - - UString sourceURL(frame->loader()->url().string()); - args.append(eventParameterName()); - args.append(jsString(m_code)); - m_listener = constr->construct(exec, args, m_functionName, sourceURL, m_lineNumber); // FIXME: is globalExec ok ? - - FunctionImp* listenerAsFunction = static_cast<FunctionImp*>(m_listener.get()); - - if (exec->hadException()) { - exec->clearException(); - - // failed to parse, so let's just make this listener a no-op - m_listener = 0; - } else if (m_originalNode) { - // Add the event's home element to the scope - // (and the document, and the form - see JSHTMLElement::eventHandlerScope) - ScopeChain scope = listenerAsFunction->scope(); - - JSValue* thisObj = toJS(exec, m_originalNode); - if (thisObj->isObject()) { - static_cast<JSEventTargetNode*>(thisObj)->pushEventHandlerScope(exec, scope); - listenerAsFunction->setScope(scope); - } - } - } - - // no more need to keep the unparsed code around - m_functionName = String(); - m_code = String(); - - if (m_listener) { - KJS::Window::ListenersMap& listeners = isHTMLEventListener() - ? windowObj()->jsHTMLEventListeners() : windowObj()->jsEventListeners(); - listeners.set(m_listener, const_cast<JSLazyEventListener*>(this)); - } -} - -JSValue* getNodeEventListener(EventTargetNode* n, const AtomicString& eventType) -{ - if (JSAbstractEventListener* listener = static_cast<JSAbstractEventListener*>(n->getHTMLEventListener(eventType))) { - if (JSValue* obj = listener->listenerObj()) - return obj; - } - return jsNull(); -} - -// ------------------------------------------------------------------------- - -const ClassInfo JSClipboard::info = { "Clipboard", 0, &JSClipboardTable }; - -/* Source for JSClipboardTable. Use "make hashtables" to regenerate. -@begin JSClipboardTable 3 - dropEffect WebCore::JSClipboard::DropEffect DontDelete - effectAllowed WebCore::JSClipboard::EffectAllowed DontDelete - types WebCore::JSClipboard::Types DontDelete|ReadOnly -@end -@begin JSClipboardPrototypeTable 4 - clearData WebCore::jsClipboardPrototypeFunctionClearData DontDelete|Function 0 - getData WebCore::jsClipboardPrototypeFunctionGetData DontDelete|Function 1 - setData WebCore::jsClipboardPrototypeFunctionSetData DontDelete|Function 2 - setDragImage WebCore::jsClipboardPrototypeFunctionSetDragImage DontDelete|Function 3 -@end -*/ - -KJS_DEFINE_PROTOTYPE(JSClipboardPrototype) -KJS_IMPLEMENT_PROTOTYPE("Clipboard", JSClipboardPrototype) - -JSClipboard::JSClipboard(JSObject* prototype, Clipboard* clipboard) - : DOMObject(prototype) - , m_impl(clipboard) -{ -} - -JSClipboard::~JSClipboard() -{ - ScriptInterpreter::forgetDOMObject(m_impl.get()); -} - -bool JSClipboard::getOwnPropertySlot(ExecState* exec, const Identifier& propertyName, PropertySlot& slot) -{ - return getStaticValueSlot<JSClipboard, DOMObject>(exec, &JSClipboardTable, this, propertyName, slot); -} - -JSValue* JSClipboard::getValueProperty(ExecState* exec, int token) const -{ - Clipboard* clipboard = impl(); - switch (token) { - case DropEffect: - ASSERT(clipboard->isForDragging() || clipboard->dropEffect().isNull()); - return jsStringOrUndefined(clipboard->dropEffect()); - case EffectAllowed: - ASSERT(clipboard->isForDragging() || clipboard->effectAllowed().isNull()); - return jsStringOrUndefined(clipboard->effectAllowed()); - case Types: - { - HashSet<String> types = clipboard->types(); - if (types.isEmpty()) - return jsNull(); - else { - List list; - HashSet<String>::const_iterator end = types.end(); - for (HashSet<String>::const_iterator it = types.begin(); it != end; ++it) - list.append(jsString(UString(*it))); - return exec->lexicalGlobalObject()->arrayConstructor()->construct(exec, list); - } - } - default: - return 0; - } -} - -void JSClipboard::put(ExecState* exec, const Identifier& propertyName, JSValue* value, int attr) -{ - lookupPut<JSClipboard, DOMObject>(exec, propertyName, value, attr, &JSClipboardTable, this ); -} - -void JSClipboard::putValueProperty(ExecState* exec, int token, JSValue* value, int /*attr*/) -{ - Clipboard* clipboard = impl(); - switch (token) { - case DropEffect: - // can never set this when not for dragging, thus getting always returns NULL string - if (clipboard->isForDragging()) - clipboard->setDropEffect(value->toString(exec)); - break; - case EffectAllowed: - // can never set this when not for dragging, thus getting always returns NULL string - if (clipboard->isForDragging()) - clipboard->setEffectAllowed(value->toString(exec)); - break; - } -} - -JSValue* jsClipboardPrototypeFunctionClearData(ExecState* exec, JSObject* thisObj, const List& args) -{ - if (!thisObj->inherits(&JSClipboard::info)) - return throwError(exec, TypeError); - - Clipboard* clipboard = static_cast<JSClipboard*>(thisObj)->impl(); - - if (args.size() == 0) { - clipboard->clearAllData(); - return jsUndefined(); - } else if (args.size() == 1) { - clipboard->clearData(args[0]->toString(exec)); - return jsUndefined(); - } else - return throwError(exec, SyntaxError, "clearData: Invalid number of arguments"); -} - -JSValue* jsClipboardPrototypeFunctionGetData(ExecState* exec, JSObject* thisObj, const List& args) -{ - if (!thisObj->inherits(&JSClipboard::info)) - return throwError(exec, TypeError); - - Clipboard* clipboard = static_cast<JSClipboard*>(thisObj)->impl(); - - if (args.size() == 1) { - bool success; - String result = clipboard->getData(args[0]->toString(exec), success); - if (success) - return jsString(result); - return jsUndefined(); - } else - return throwError(exec, SyntaxError, "getData: Invalid number of arguments"); -} - -JSValue* jsClipboardPrototypeFunctionSetData(ExecState* exec, JSObject* thisObj, const List& args) -{ - if (!thisObj->inherits(&JSClipboard::info)) - return throwError(exec, TypeError); - - Clipboard* clipboard = static_cast<JSClipboard*>(thisObj)->impl(); - - if (args.size() == 2) - return jsBoolean(clipboard->setData(args[0]->toString(exec), args[1]->toString(exec))); - return throwError(exec, SyntaxError, "setData: Invalid number of arguments"); -} - -JSValue* jsClipboardPrototypeFunctionSetDragImage(ExecState* exec, JSObject* thisObj, const List& args) -{ - if (!thisObj->inherits(&JSClipboard::info)) - return throwError(exec, TypeError); - - Clipboard* clipboard = static_cast<JSClipboard*>(thisObj)->impl(); - - if (!clipboard->isForDragging()) - return jsUndefined(); - - if (args.size() != 3) - return throwError(exec, SyntaxError, "setDragImage: Invalid number of arguments"); - - int x = args[1]->toInt32(exec); - int y = args[2]->toInt32(exec); - - // See if they passed us a node - Node* node = toNode(args[0]); - if (!node) - return throwError(exec, TypeError); - - if (!node->isElementNode()) - return throwError(exec, SyntaxError, "setDragImageFromElement: Invalid first argument"); - - if (static_cast<Element*>(node)->hasLocalName(imgTag) && - !node->inDocument()) - clipboard->setDragImage(static_cast<HTMLImageElement*>(node)->cachedImage(), IntPoint(x, y)); - else - clipboard->setDragImageElement(node, IntPoint(x, y)); - - return jsUndefined(); -} - -JSValue* toJS(ExecState* exec, Clipboard* obj) -{ - return cacheDOMObject<Clipboard, JSClipboard, JSClipboardPrototype>(exec, obj); -} - -Clipboard* toClipboard(JSValue* val) -{ - return val->isObject(&JSClipboard::info) ? static_cast<JSClipboard*>(val)->impl() : 0; -} - -} // namespace WebCore diff --git a/WebCore/bindings/js/kjs_events.h b/WebCore/bindings/js/kjs_events.h deleted file mode 100644 index 03d9f6c..0000000 --- a/WebCore/bindings/js/kjs_events.h +++ /dev/null @@ -1,132 +0,0 @@ -/* - * This file is part of the KDE libraries - * Copyright (C) 2001 Peter Kelly (pmk@post.com) - * Copyright (C) 2003 Apple Computer, Inc. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#ifndef kjs_events_h -#define kjs_events_h - -#include "EventListener.h" -#include "PlatformString.h" -#include "kjs_dom.h" -#include "kjs_html.h" -#include <kjs/protect.h> - -namespace KJS { - class Window; -} - -namespace WebCore { - - class Clipboard; - class Event; - - class JSAbstractEventListener : public EventListener { - public: - JSAbstractEventListener(bool html = false); - - virtual void handleEvent(Event*, bool isWindowEvent); - virtual bool isHTMLEventListener() const; - virtual KJS::JSObject* listenerObj() const = 0; - virtual KJS::Window* windowObj() const = 0; - - private: - bool m_html; - }; - - class JSUnprotectedEventListener : public JSAbstractEventListener { - public: - JSUnprotectedEventListener(KJS::JSObject* listener, KJS::Window*, bool html = false); - virtual ~JSUnprotectedEventListener(); - - virtual KJS::JSObject* listenerObj() const; - virtual KJS::Window* windowObj() const; - void clearWindowObj(); - void mark(); - private: - KJS::JSObject* m_listener; - KJS::Window* m_win; - }; - - class JSEventListener : public JSAbstractEventListener { - public: - JSEventListener(KJS::JSObject* listener, KJS::Window*, bool html = false); - virtual ~JSEventListener(); - - virtual KJS::JSObject* listenerObj() const; - virtual KJS::Window* windowObj() const; - void clearWindowObj(); - - protected: - mutable KJS::ProtectedPtr<KJS::JSObject> m_listener; - - private: - KJS::ProtectedPtr<KJS::Window> m_win; - }; - - class JSLazyEventListener : public JSEventListener { - public: - JSLazyEventListener(const String& functionName, const String& code, KJS::Window*, Node*, int lineNumber = 0); - virtual KJS::JSObject* listenerObj() const; - - private: - virtual KJS::JSValue* eventParameterName() const; - void parseCode() const; - - mutable String m_functionName; - mutable String m_code; - mutable bool m_parsed; - int m_lineNumber; - Node* m_originalNode; - }; - - KJS::JSValue* getNodeEventListener(Node*, const AtomicString& eventType); - - class JSClipboard : public KJS::DOMObject { - public: - JSClipboard(KJS::JSObject* prototype, Clipboard*); - virtual ~JSClipboard(); - - virtual bool getOwnPropertySlot(KJS::ExecState*, const KJS::Identifier&, KJS::PropertySlot&); - KJS::JSValue* getValueProperty(KJS::ExecState*, int token) const; - virtual void put(KJS::ExecState*, const KJS::Identifier&, KJS::JSValue*, int attr = KJS::None); - void putValueProperty(KJS::ExecState*, int token, KJS::JSValue*, int attr); - - virtual const KJS::ClassInfo* classInfo() const { return &info; } - static const KJS::ClassInfo info; - - enum { ClearData, GetData, SetData, Types, SetDragImage, DropEffect, EffectAllowed }; - - Clipboard* impl() const { return m_impl.get(); } - - private: - RefPtr<Clipboard> m_impl; - }; - - KJS::JSValue* toJS(KJS::ExecState*, Clipboard*); - Clipboard* toClipboard(KJS::JSValue*); - - // Functions - KJS::JSValue* jsClipboardPrototypeFunctionClearData(KJS::ExecState*, KJS::JSObject*, const KJS::List&); - KJS::JSValue* jsClipboardPrototypeFunctionGetData(KJS::ExecState*, KJS::JSObject*, const KJS::List&); - KJS::JSValue* jsClipboardPrototypeFunctionSetData(KJS::ExecState*, KJS::JSObject*, const KJS::List&); - KJS::JSValue* jsClipboardPrototypeFunctionSetDragImage(KJS::ExecState*, KJS::JSObject*, const KJS::List&); - -} // namespace WebCore - -#endif // kjs_events_h diff --git a/WebCore/bindings/js/kjs_html.cpp b/WebCore/bindings/js/kjs_html.cpp deleted file mode 100644 index c143c1e..0000000 --- a/WebCore/bindings/js/kjs_html.cpp +++ /dev/null @@ -1,147 +0,0 @@ -// -*- c-basic-offset: 4 -*- -/* - * This file is part of the KDE libraries - * Copyright (C) 1999-2000 Harri Porten (porten@kde.org) - * Copyright (C) 2004, 2005, 2006, 2007 Apple Inc. All rights reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#include "config.h" -#include "kjs_html.h" - -#include "Frame.h" -#include "FrameLoader.h" -#include "JSHTMLElement.h" -#include "HTMLDocument.h" -#include "HTMLImageElement.h" -#include "kjs_proxy.h" - -namespace WebCore { - -using namespace KJS; - -ImageConstructorImp::ImageConstructorImp(ExecState* exec, Document* doc) - : DOMObject(exec->lexicalGlobalObject()->objectPrototype()) - , m_doc(doc) -{ -} - -JSObject* ImageConstructorImp::construct(ExecState* exec, const List& list) -{ - bool widthSet = false; - bool heightSet = false; - int width = 0; - int height = 0; - - if (list.size() > 0) { - widthSet = true; - JSValue* w = list.at(0); - width = w->toInt32(exec); - } - - if (list.size() > 1) { - heightSet = true; - JSValue* h = list.at(1); - height = h->toInt32(exec); - } - - // Calling toJS on the document causes the JS document wrapper to be - // added to the window object. This is done to ensure that JSDocument::mark - // will be called (which will cause the image element to be marked if necessary). - // This is only a problem for elements created using the Image constructor since all - // other elements are created through the document, using document.createElement for example. - toJS(exec, m_doc.get()); - - HTMLImageElement* image = new HTMLImageElement(m_doc.get()); - JSObject* result = static_cast<JSObject*>(toJS(exec, image)); - - if (widthSet) - image->setWidth(width); - if (heightSet) - image->setHeight(height); - - return result; -} - -// ------------------------------------------------------------------------- - -// Runtime object support code for JSHTMLAppletElement, JSHTMLEmbedElement and JSHTMLObjectElement. - -JSValue* runtimeObjectGetter(ExecState* exec, JSObject* originalObject, const Identifier& propertyName, const PropertySlot& slot) -{ - JSHTMLElement* thisObj = static_cast<JSHTMLElement*>(slot.slotBase()); - HTMLElement* element = static_cast<HTMLElement*>(thisObj->impl()); - - return getRuntimeObject(exec, element); -} - -JSValue* runtimeObjectPropertyGetter(ExecState* exec, JSObject* originalObject, const Identifier& propertyName, const PropertySlot& slot) -{ - JSHTMLElement* thisObj = static_cast<JSHTMLElement*>(slot.slotBase()); - HTMLElement* element = static_cast<HTMLElement*>(thisObj->impl()); - - if (JSValue* runtimeObject = getRuntimeObject(exec, element)) - return static_cast<JSObject*>(runtimeObject)->get(exec, propertyName); - return jsUndefined(); -} - -bool runtimeObjectCustomGetOwnPropertySlot(ExecState* exec, const Identifier& propertyName, PropertySlot& slot, WebCore::JSHTMLElement* originalObj, HTMLElement* thisImp) -{ - JSValue* runtimeObject = getRuntimeObject(exec, thisImp); - if (runtimeObject) { - JSObject* imp = static_cast<JSObject*>(runtimeObject); - if (imp->hasProperty(exec, propertyName)) { - slot.setCustom(originalObj, runtimeObjectPropertyGetter); - return true; - } - } - - return false; -} - -bool runtimeObjectCustomPut(ExecState* exec, const Identifier& propertyName, JSValue* value, int /*attr*/, HTMLElement* thisImp) -{ - if (JSValue* runtimeObject = getRuntimeObject(exec, thisImp)) { - JSObject* imp = static_cast<JSObject*>(runtimeObject); - if (imp->canPut(exec, propertyName)) { - imp->put(exec, propertyName, value); - return true; - } - } - - return false; -} - -bool runtimeObjectImplementsCall(HTMLElement* thisImp) -{ - Frame* frame = thisImp->document()->frame(); - if (!frame) - return false; - ExecState* exec = frame->scriptProxy()->globalObject()->globalExec(); - if (JSValue* runtimeObject = getRuntimeObject(exec, thisImp)) - return static_cast<JSObject*>(runtimeObject)->implementsCall(); - - return false; -} - -JSValue* runtimeObjectCallAsFunction(ExecState* exec, JSObject* thisObj, const List& args, HTMLElement* thisImp) -{ - if (JSValue* runtimeObject = getRuntimeObject(exec, thisImp)) - return static_cast<JSObject*>(runtimeObject)->call(exec, thisObj, args); - return jsUndefined(); -} - -} // namespace WebCore diff --git a/WebCore/bindings/js/kjs_html.h b/WebCore/bindings/js/kjs_html.h deleted file mode 100644 index cebd299..0000000 --- a/WebCore/bindings/js/kjs_html.h +++ /dev/null @@ -1,58 +0,0 @@ -// -*- c-basic-offset: 2 -*- -/* - * This file is part of the KDE libraries - * Copyright (C) 1999 Harri Porten (porten@kde.org) - * Copyright (C) 2004, 2006, 2007 Apple Inc. All rights reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#ifndef kjs_html_h -#define kjs_html_h - -#include "kjs_dom.h" - -namespace WebCore { - - class Document; - class HTMLCollection; - class HTMLElement; - class JSHTMLElement; - - class ImageConstructorImp : public KJS::DOMObject { - public: - ImageConstructorImp(KJS::ExecState*, Document*); - - virtual bool implementsConstruct() const { return true; } - virtual KJS::JSObject* construct(KJS::ExecState*, const KJS::List&); - - private: - RefPtr<Document> m_doc; - }; - - - // Runtime object support code for JSHTMLAppletElement, JSHTMLEmbedElement and JSHTMLObjectElement. - // FIXME: Move these to a more appropriate place. - - KJS::JSValue* runtimeObjectGetter(KJS::ExecState*, KJS::JSObject*, const KJS::Identifier&, const KJS::PropertySlot&); - KJS::JSValue* runtimeObjectPropertyGetter(KJS::ExecState*, KJS::JSObject*, const KJS::Identifier&, const KJS::PropertySlot&); - bool runtimeObjectCustomGetOwnPropertySlot(KJS::ExecState*, const KJS::Identifier&, KJS::PropertySlot&, JSHTMLElement*, HTMLElement*); - bool runtimeObjectCustomPut(KJS::ExecState*, const KJS::Identifier&, KJS::JSValue*, int attr, HTMLElement*); - bool runtimeObjectImplementsCall(HTMLElement*); - KJS::JSValue* runtimeObjectCallAsFunction(KJS::ExecState*, KJS::JSObject*, const KJS::List&, HTMLElement*); - -} // namespace WebCore - -#endif // kjs_html_h diff --git a/WebCore/bindings/js/kjs_navigator.cpp b/WebCore/bindings/js/kjs_navigator.cpp deleted file mode 100644 index dcdcf61..0000000 --- a/WebCore/bindings/js/kjs_navigator.cpp +++ /dev/null @@ -1,621 +0,0 @@ -// -*- c-basic-offset: 2 -*- -/* - * Copyright (C) 2000 Harri Porten (porten@kde.org) - * Copyright (c) 2000 Daniel Molkentin (molkentin@kde.org) - * Copyright (c) 2000 Stefan Schimanski (schimmi@kde.org) - * Copyright (C) 2003, 2004, 2005, 2006, 2007 Apple Inc. All Rights Reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#include "config.h" -#include "kjs_navigator.h" - -#include "AtomicString.h" -#include "CookieJar.h" -#include "DOMWindow.h" -#include "Document.h" -#include "Frame.h" -#include "FrameLoader.h" -#include "Language.h" -#include "Page.h" -#include "PluginInfoStore.h" -#include "Settings.h" -#include "kjs_window.h" -#include <kjs/object_object.h> - -#ifndef WEBCORE_NAVIGATOR_PLATFORM -#if PLATFORM(MAC) && PLATFORM(PPC) -#define WEBCORE_NAVIGATOR_PLATFORM "MacPPC" -#elif PLATFORM(MAC) && PLATFORM(X86) -#define WEBCORE_NAVIGATOR_PLATFORM "MacIntel" -#elif PLATFORM(WIN_OS) -#define WEBCORE_NAVIGATOR_PLATFORM "Win32" -#else -#define WEBCORE_NAVIGATOR_PLATFORM "" -#endif -#endif // ifndef WEBCORE_NAVIGATOR_PLATFORM - -#ifndef WEBCORE_NAVIGATOR_PRODUCT -#define WEBCORE_NAVIGATOR_PRODUCT "Gecko" -#endif // ifndef WEBCORE_NAVIGATOR_PRODUCT - -#ifndef WEBCORE_NAVIGATOR_PRODUCT_SUB -#define WEBCORE_NAVIGATOR_PRODUCT_SUB "20030107" -#endif // ifndef WEBCORE_NAVIGATOR_PRODUCT_SUB - -#ifndef WEBCORE_NAVIGATOR_VENDOR -#define WEBCORE_NAVIGATOR_VENDOR "Apple Computer, Inc." -#endif // ifndef WEBCORE_NAVIGATOR_VENDOR - -#ifndef WEBCORE_NAVIGATOR_VENDOR_SUB -#define WEBCORE_NAVIGATOR_VENDOR_SUB "" -#endif // ifndef WEBCORE_NAVIGATOR_VENDOR_SUB - -using namespace WebCore; - -namespace KJS { - - class PluginBase : public DOMObject { - public: - PluginBase(ExecState *exec); - virtual ~PluginBase(); - - static void refresh(bool reload); - - protected: - static void cachePluginDataIfNecessary(); - static Vector<PluginInfo*> *plugins; - static Vector<MimeClassInfo*> *mimes; - - private: - static int m_plugInCacheRefCount; - }; - - - class Plugins : public PluginBase { - public: - Plugins(ExecState *exec) : PluginBase(exec) {}; - virtual bool getOwnPropertySlot(ExecState *, const Identifier&, PropertySlot&); - JSValue *getValueProperty(ExecState *, int token) const; - virtual const ClassInfo* classInfo() const { return &info; } - static const ClassInfo info; - enum { Length }; - private: - static JSValue *indexGetter(ExecState *, JSObject *, const Identifier&, const PropertySlot&); - static JSValue *nameGetter(ExecState *, JSObject *, const Identifier&, const PropertySlot&); - }; - - JSValue* pluginsFunctionRefresh(ExecState*, JSObject*, const List&); - - class MimeTypes : public PluginBase { - public: - MimeTypes(ExecState *exec) : PluginBase(exec) { }; - virtual bool getOwnPropertySlot(ExecState *, const Identifier&, PropertySlot&); - JSValue *getValueProperty(ExecState *, int token) const; - virtual const ClassInfo* classInfo() const { return &info; } - static const ClassInfo info; - enum { Length }; - private: - static JSValue *indexGetter(ExecState *, JSObject *, const Identifier&, const PropertySlot&); - static JSValue *nameGetter(ExecState *, JSObject *, const Identifier&, const PropertySlot&); - }; - - class Plugin : public PluginBase { - public: - Plugin(ExecState *exec, PluginInfo *info) : PluginBase(exec), m_info(info) { } - virtual bool getOwnPropertySlot(ExecState *, const Identifier&, PropertySlot&); - JSValue *getValueProperty(ExecState *, int token) const; - virtual const ClassInfo* classInfo() const { return &info; } - static const ClassInfo info; - enum { Name, Filename, Description, Length }; - private: - static JSValue *indexGetter(ExecState *, JSObject *, const Identifier&, const PropertySlot&); - static JSValue *nameGetter(ExecState *, JSObject *, const Identifier&, const PropertySlot&); - - PluginInfo *m_info; - }; - - class MimeType : public PluginBase { - public: - MimeType( ExecState *exec, MimeClassInfo *info ) : PluginBase(exec), m_info(info) { } - virtual bool getOwnPropertySlot(ExecState *, const Identifier&, PropertySlot&); - JSValue *getValueProperty(ExecState *, int token) const; - virtual const ClassInfo* classInfo() const { return &info; } - static const ClassInfo info; - enum { Type, Suffixes, Description, EnabledPlugin }; - private: - MimeClassInfo *m_info; - }; - -} // namespace - -#include "kjs_navigator.lut.h" - -namespace KJS { - -const ClassInfo Plugins::info = { "PluginArray", 0, &PluginsTable }; -const ClassInfo MimeTypes::info = { "MimeTypeArray", 0, &MimeTypesTable }; -const ClassInfo Plugin::info = { "Plugin", 0, &PluginTable }; -const ClassInfo MimeType::info = { "MimeType", 0, &MimeTypeTable }; - -Vector<PluginInfo*> *KJS::PluginBase::plugins = 0; -Vector<MimeClassInfo*> *KJS::PluginBase::mimes = 0; -int KJS::PluginBase::m_plugInCacheRefCount = 0; - -const ClassInfo Navigator::info = { "Navigator", 0, &NavigatorTable }; -/* -@begin NavigatorTable 13 - appCodeName Navigator::AppCodeName DontDelete|ReadOnly - appName Navigator::AppName DontDelete|ReadOnly - appVersion Navigator::AppVersion DontDelete|ReadOnly - language Navigator::Language DontDelete|ReadOnly - userAgent Navigator::UserAgent DontDelete|ReadOnly - platform Navigator::Platform DontDelete|ReadOnly - plugins Navigator::_Plugins DontDelete|ReadOnly - mimeTypes Navigator::_MimeTypes DontDelete|ReadOnly - product Navigator::Product DontDelete|ReadOnly - productSub Navigator::ProductSub DontDelete|ReadOnly - vendor Navigator::Vendor DontDelete|ReadOnly - vendorSub Navigator::VendorSub DontDelete|ReadOnly - cookieEnabled Navigator::CookieEnabled DontDelete|ReadOnly - javaEnabled navigatorProtoFuncJavaEnabled DontDelete|Function 0 -@end -*/ - -Navigator::Navigator(JSObject* prototype, Frame* frame) - : DOMObject(prototype) - , m_frame(frame) -{ -} - -bool Navigator::getOwnPropertySlot(ExecState *exec, const Identifier& propertyName, PropertySlot& slot) -{ - return getStaticPropertySlot<Navigator, JSObject>(exec, &NavigatorTable, this, propertyName, slot); -} - -static bool needsYouTubeQuirk(ExecState*, Frame*); - -#if !PLATFORM(WIN) - -static inline bool needsYouTubeQuirk(ExecState*, Frame*) -{ - return false; -} - -#else - -static bool needsYouTubeQuirk(ExecState* exec, Frame* frame) -{ - // This quirk works around a mistaken check in an ad at youtube.com. - // There's a function called isSafari that returns false if the function - // called isWindows returns true; thus the site malfunctions with Windows Safari. - - // Do the quirk only if the function's name is "isWindows". - FunctionImp* function = exec->function(); - if (!function) - return false; - static const Identifier& isWindowsFunctionName = *new Identifier("isWindows"); - if (function->functionName() != isWindowsFunctionName) - return false; - - // Do the quirk only if the function is called by an "isSafari" function. - // However, that function is not itself named -- it is stored in the isSafari - // property, though, so that's how recognize it. - ExecState* callingExec = exec->callingExecState(); - if (!callingExec) - return false; - FunctionImp* callingFunction = callingExec->function(); - if (!callingFunction) - return false; - JSObject* thisObject = callingExec->thisValue(); - if (!thisObject) - return false; - static const Identifier& isSafariFunctionName = *new Identifier("isSafari"); - JSValue* isSafariFunction = thisObject->getDirect(isSafariFunctionName); - if (isSafariFunction != callingFunction) - return false; - - // FIXME: The document is never null, so we should remove this check along with the - // other similar ones in this file when we are absolutely sure it's safe. - Document* document = frame->document(); - if (!document) - return false; - - // Do the quirk only on the front page of the global version of YouTube. - const KURL& url = document->url(); - if (url.host() != "youtube.com" && url.host() != "www.youtube.com") - return false; - if (url.path() != "/") - return false; - - // As with other site-specific quirks, allow website developers to turn this off. - // In theory, this allows website developers to check if their fixes are effective. - Settings* settings = frame->settings(); - if (!settings) - return false; - if (!settings->needsSiteSpecificQuirks()) - return false; - - return true; -} - -#endif - -JSValue* Navigator::getValueProperty(ExecState* exec, int token) const -{ - switch (token) { - case AppCodeName: - return jsString("Mozilla"); - case AppName: - return jsString("Netscape"); - case AppVersion: { - if (needsYouTubeQuirk(exec, m_frame)) - return jsString(""); - // Version is everything in the user agent string past the "Mozilla/" prefix. - const String userAgent = m_frame->loader()->userAgent(m_frame->document() ? m_frame->document()->url() : KURL()); - return jsString(userAgent.substring(userAgent.find('/') + 1)); - } - case Product: - return jsString(WEBCORE_NAVIGATOR_PRODUCT); - case ProductSub: - return jsString(WEBCORE_NAVIGATOR_PRODUCT_SUB); - case Vendor: - return jsString(WEBCORE_NAVIGATOR_VENDOR); - case VendorSub: - return jsString(WEBCORE_NAVIGATOR_VENDOR_SUB); - case Language: - return jsString(defaultLanguage()); - case UserAgent: - return jsString(m_frame->loader()->userAgent(m_frame->document() ? m_frame->document()->url() : KURL())); - case Platform: - return jsString(WEBCORE_NAVIGATOR_PLATFORM); - case _Plugins: - return new Plugins(exec); - case _MimeTypes: - return new MimeTypes(exec); - case CookieEnabled: - return jsBoolean(cookiesEnabled(m_frame->document())); - } - return 0; -} - -/*******************************************************************/ - -void PluginBase::cachePluginDataIfNecessary() -{ - if (!plugins) { - plugins = new Vector<PluginInfo*>; - mimes = new Vector<MimeClassInfo*>; - - // read configuration - PluginInfoStore c; - unsigned pluginCount = c.pluginCount(); - for (unsigned n = 0; n < pluginCount; n++) { - PluginInfo* plugin = c.createPluginInfoForPluginAtIndex(n); - if (!plugin) - continue; - - plugins->append(plugin); - if (plugin->mimes.isEmpty()) - continue; - - Vector<MimeClassInfo*>::iterator end = plugin->mimes.end(); - for (Vector<MimeClassInfo*>::iterator itr = plugin->mimes.begin(); itr != end; itr++) - mimes->append(*itr); - } - } -} - -PluginBase::PluginBase(ExecState* exec) - : DOMObject(exec->lexicalGlobalObject()->objectPrototype()) -{ - cachePluginDataIfNecessary(); - m_plugInCacheRefCount++; -} - -PluginBase::~PluginBase() -{ - m_plugInCacheRefCount--; - if (!m_plugInCacheRefCount) { - if (plugins) { - deleteAllValues(*plugins); - delete plugins; - plugins = 0; - } - if (mimes) { - deleteAllValues(*mimes); - delete mimes; - mimes = 0; - } - } -} - -void PluginBase::refresh(bool reload) -{ - if (plugins) { - deleteAllValues(*plugins); - delete plugins; - plugins = 0; - } - if (mimes) { - deleteAllValues(*mimes); - delete mimes; - mimes = 0; - } - - refreshPlugins(reload); - cachePluginDataIfNecessary(); -} - - -/*******************************************************************/ - -/* -@begin PluginsTable 2 - length Plugins::Length DontDelete|ReadOnly - refresh pluginsFunctionRefresh DontDelete|Function 0 -@end -*/ - -JSValue *Plugins::getValueProperty(ExecState *exec, int token) const -{ - ASSERT(token == Length); - return jsNumber(plugins->size()); -} - -JSValue *Plugins::indexGetter(ExecState *exec, JSObject *originalObject, const Identifier& propertyName, const PropertySlot& slot) -{ - return new Plugin(exec, plugins->at(slot.index())); -} - -JSValue *Plugins::nameGetter(ExecState *exec, JSObject *originalObject, const Identifier& propertyName, const PropertySlot& slot) -{ - AtomicString atomicPropertyName = propertyName; - Vector<PluginInfo*>::iterator end = plugins->end(); - for (Vector<PluginInfo*>::iterator itr = plugins->begin(); itr != end; itr++) { - PluginInfo *pl = *itr; - if (pl->name == atomicPropertyName) - return new Plugin(exec, pl); - } - return jsUndefined(); -} - -bool Plugins::getOwnPropertySlot(ExecState *exec, const Identifier& propertyName, PropertySlot& slot) -{ - const HashEntry* entry = Lookup::findEntry(&PluginsTable, propertyName); - if (entry) { - if (entry->attr & Function) - slot.setStaticEntry(this, entry, staticFunctionGetter); - else - slot.setStaticEntry(this, entry, staticValueGetter<Plugins>); - return true; - } else { - // plugins[#] - bool ok; - unsigned int i = propertyName.toUInt32(&ok); - if (ok && i < plugins->size()) { - slot.setCustomIndex(this, i, indexGetter); - return true; - } - - // plugin[name] - AtomicString atomicPropertyName = propertyName; - Vector<PluginInfo*>::iterator end = plugins->end(); - for (Vector<PluginInfo*>::iterator itr = plugins->begin(); itr != end; itr++) { - if ((*itr)->name == atomicPropertyName) { - slot.setCustom(this, nameGetter); - return true; - } - } - } - - return PluginBase::getOwnPropertySlot(exec, propertyName, slot); -} - -/*******************************************************************/ - -/* -@begin MimeTypesTable 1 - length MimeTypes::Length DontDelete|ReadOnly -@end -*/ - -JSValue *MimeTypes::getValueProperty(ExecState *exec, int token) const -{ - ASSERT(token == Length); - return jsNumber(mimes->size()); -} - -JSValue *MimeTypes::indexGetter(ExecState *exec, JSObject *originalObject, const Identifier& propertyName, const PropertySlot& slot) -{ - return new MimeType(exec, mimes->at(slot.index())); -} - -JSValue *MimeTypes::nameGetter(ExecState *exec, JSObject *originalObject, const Identifier& propertyName, const PropertySlot& slot) -{ - AtomicString atomicPropertyName = propertyName; - Vector<MimeClassInfo*>::iterator end = mimes->end(); - for (Vector<MimeClassInfo*>::iterator itr = mimes->begin(); itr != end; itr++) { - MimeClassInfo *m = (*itr); - if (m->type == atomicPropertyName) - return new MimeType(exec, m); - } - return jsUndefined(); -} - -bool MimeTypes::getOwnPropertySlot(ExecState *exec, const Identifier& propertyName, PropertySlot& slot) -{ - const HashEntry* entry = Lookup::findEntry(&MimeTypesTable, propertyName); - if (entry) { - slot.setStaticEntry(this, entry, staticValueGetter<MimeTypes>); - return true; - } else { - // mimeTypes[#] - bool ok; - unsigned int i = propertyName.toUInt32(&ok); - if (ok && i < mimes->size()) { - slot.setCustomIndex(this, i, indexGetter); - return true; - } - - // mimeTypes[name] - AtomicString atomicPropertyName = propertyName; - Vector<MimeClassInfo*>::iterator end = mimes->end(); - for (Vector<MimeClassInfo*>::iterator itr = mimes->begin(); itr != end; itr++) { - if ((*itr)->type == atomicPropertyName) { - slot.setCustom(this, nameGetter); - return true; - } - } - } - - return PluginBase::getOwnPropertySlot(exec, propertyName, slot); -} - - -/************************************************************************/ - -/* -@begin PluginTable 4 - name Plugin::Name DontDelete|ReadOnly - filename Plugin::Filename DontDelete|ReadOnly - description Plugin::Description DontDelete|ReadOnly - length Plugin::Length DontDelete|ReadOnly -@end -*/ - -JSValue *Plugin::getValueProperty(ExecState *exec, int token) const -{ - switch (token) { - case Name: - return jsString(m_info->name); - case Filename: - return jsString(m_info->file); - case Description: - return jsString(m_info->desc); - case Length: - return jsNumber(m_info->mimes.size()); - default: - ASSERT(0); - return jsUndefined(); - } -} - -JSValue *Plugin::indexGetter(ExecState *exec, JSObject *originalObject, const Identifier& propertyName, const PropertySlot& slot) -{ - Plugin *thisObj = static_cast<Plugin *>(slot.slotBase()); - return new MimeType(exec, thisObj->m_info->mimes.at(slot.index())); -} - -JSValue *Plugin::nameGetter(ExecState *exec, JSObject *originalObject, const Identifier& propertyName, const PropertySlot& slot) -{ - Plugin *thisObj = static_cast<Plugin *>(slot.slotBase()); - AtomicString atomicPropertyName = propertyName; - Vector<MimeClassInfo*>::iterator end = thisObj->m_info->mimes.end(); - for (Vector<MimeClassInfo*>::iterator itr = thisObj->m_info->mimes.begin(); itr != end; itr++) { - MimeClassInfo *m = (*itr); - if (m->type == atomicPropertyName) - return new MimeType(exec, m); - } - return jsUndefined(); -} - - -bool Plugin::getOwnPropertySlot(ExecState *exec, const Identifier& propertyName, PropertySlot& slot) -{ - const HashEntry* entry = Lookup::findEntry(&PluginTable, propertyName); - if (entry) { - slot.setStaticEntry(this, entry, staticValueGetter<Plugin>); - return true; - } else { - // plugin[#] - bool ok; - unsigned int i = propertyName.toUInt32(&ok); - if (ok && i < m_info->mimes.size()) { - slot.setCustomIndex(this, i, indexGetter); - return true; - } - - // plugin["name"] - AtomicString atomicPropertyName = propertyName; - Vector<MimeClassInfo*>::iterator end = m_info->mimes.end(); - for (Vector<MimeClassInfo*>::iterator itr = m_info->mimes.begin(); itr != end; itr++) { - if ((*itr)->type == atomicPropertyName) { - slot.setCustom(this, nameGetter); - return true; - } - } - } - - return PluginBase::getOwnPropertySlot(exec, propertyName, slot); -} - -/*****************************************************************************/ - -/* -@begin MimeTypeTable 4 - type MimeType::Type DontDelete|ReadOnly - suffixes MimeType::Suffixes DontDelete|ReadOnly - description MimeType::Description DontDelete|ReadOnly - enabledPlugin MimeType::EnabledPlugin DontDelete|ReadOnly -@end -*/ - -JSValue *MimeType::getValueProperty(ExecState *exec, int token) const -{ - switch (token) { - case Type: - return jsString(m_info->type); - case Suffixes: - return jsString(m_info->suffixes); - case Description: - return jsString(m_info->desc); - case EnabledPlugin: { - Frame* frame = Window::retrieveActive(exec)->impl()->frame(); - ASSERT(frame); - Settings* settings = frame->settings(); - if (settings && settings->arePluginsEnabled()) - return new Plugin(exec, m_info->plugin); - else - return jsUndefined(); - } - default: - return jsUndefined(); - } -} - -bool MimeType::getOwnPropertySlot(ExecState *exec, const Identifier& propertyName, PropertySlot& slot) -{ - return getStaticValueSlot<MimeType, PluginBase>(exec, &MimeTypeTable, this, propertyName, slot); -} - -JSValue* pluginsFunctionRefresh(ExecState* exec, JSObject*, const List& args) -{ - PluginBase::refresh(args[0]->toBoolean(exec)); - return jsUndefined(); -} - -JSValue* navigatorProtoFuncJavaEnabled(ExecState* exec, JSObject* thisObj, const List&) -{ - if (!thisObj->inherits(&KJS::Navigator::info)) - return throwError(exec, TypeError); - Navigator *nav = static_cast<Navigator *>(thisObj); - // javaEnabled() - Settings* settings = nav->frame() ? nav->frame()->settings() : 0; - return jsBoolean(settings && settings->isJavaEnabled()); -} - -} // namespace diff --git a/WebCore/bindings/js/kjs_navigator.h b/WebCore/bindings/js/kjs_navigator.h deleted file mode 100644 index 032a696..0000000 --- a/WebCore/bindings/js/kjs_navigator.h +++ /dev/null @@ -1,52 +0,0 @@ -// -*- c-basic-offset: 2 -*- -/* - * This file is part of the KDE libraries - * Copyright (C) 2000 Harri Porten (porten@kde.org) - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#ifndef kjs_navigator_h -#define kjs_navigator_h - -#include "kjs_binding.h" - -namespace WebCore { - class Frame; -} - -namespace KJS { - - class Navigator : public DOMObject { - public: - Navigator(JSObject* prototype, WebCore::Frame*); - - virtual bool getOwnPropertySlot(ExecState *, const Identifier&, PropertySlot&); - JSValue *getValueProperty(ExecState *exec, int token) const; - virtual const ClassInfo* classInfo() const { return &info; } - static const ClassInfo info; - enum { AppCodeName, AppName, AppVersion, Language, UserAgent, Platform, - _Plugins, _MimeTypes, Product, ProductSub, Vendor, VendorSub, CookieEnabled }; - WebCore::Frame *frame() const { return m_frame; } - private: - WebCore::Frame *m_frame; - }; - - // Functions - JSValue* navigatorProtoFuncJavaEnabled(ExecState*, JSObject*, const List&); - -} // namespace - -#endif diff --git a/WebCore/bindings/js/kjs_proxy.cpp b/WebCore/bindings/js/kjs_proxy.cpp deleted file mode 100644 index 433c9e9..0000000 --- a/WebCore/bindings/js/kjs_proxy.cpp +++ /dev/null @@ -1,206 +0,0 @@ -/* - * Copyright (C) 1999-2001 Harri Porten (porten@kde.org) - * Copyright (C) 2001 Peter Kelly (pmk@post.com) - * Copyright (C) 2006, 2007 Apple Inc. All rights reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#include "config.h" -#include "kjs_proxy.h" - -#include "Chrome.h" -#include "Document.h" -#include "Event.h" -#include "EventNames.h" -#include "Frame.h" -#include "FrameLoader.h" -#include "GCController.h" -#include "JSDocument.h" -#include "JSDOMWindow.h" -#include "Page.h" -#include "Settings.h" -#include "kjs_events.h" -#include "kjs_window.h" - -#if ENABLE(SVG) -#include "JSSVGLazyEventListener.h" -#endif - -using namespace KJS; -using namespace WebCore::EventNames; - -namespace WebCore { - -KJSProxy::KJSProxy(Frame* frame) - : m_frame(frame) - , m_handlerLineno(0) - , m_processingTimerCallback(0) - , m_processingInlineCode(0) -{ -} - -KJSProxy::~KJSProxy() -{ - if (m_globalObject) { - m_globalObject = 0; - - // It's likely that releasing the global object has created a lot of garbage. - gcController().garbageCollectSoon(); - } -} - -JSValue* KJSProxy::evaluate(const String& filename, int baseLine, const String& str) -{ - // evaluate code. Returns the JS return value or 0 - // if there was none, an error occured or the type couldn't be converted. - - initScriptIfNeeded(); - // inlineCode is true for <a href="javascript:doSomething()"> - // and false for <script>doSomething()</script>. Check if it has the - // expected value in all cases. - // See smart window.open policy for where this is used. - ExecState* exec = m_globalObject->globalExec(); - m_processingInlineCode = filename.isNull(); - - JSLock lock; - - // Evaluating the JavaScript could cause the frame to be deallocated - // so we start the keep alive timer here. - m_frame->keepAlive(); - - JSValue* thisNode = Window::retrieve(m_frame); - - m_globalObject->startTimeoutCheck(); - Completion comp = Interpreter::evaluate(exec, filename, baseLine, reinterpret_cast<const KJS::UChar*>(str.characters()), str.length(), thisNode); - m_globalObject->stopTimeoutCheck(); - - if (comp.complType() == Normal || comp.complType() == ReturnValue) { - m_processingInlineCode = false; - return comp.value(); - } - - if (comp.complType() == Throw) { - UString errorMessage = comp.value()->toString(exec); - int lineNumber = comp.value()->toObject(exec)->get(exec, "line")->toInt32(exec); - UString sourceURL = comp.value()->toObject(exec)->get(exec, "sourceURL")->toString(exec); - if (Page* page = m_frame->page()) - page->chrome()->addMessageToConsole(JSMessageSource, ErrorMessageLevel, errorMessage, lineNumber, sourceURL); - } - - m_processingInlineCode = false; - return 0; -} - -void KJSProxy::clear() -{ - // clear resources allocated by the global object, and make it ready to be used by another page - // We have to keep it, so that the Window object for the frame remains the same. - // (we used to delete and re-create it, previously) - if (m_globalObject) - m_globalObject->clear(); -} - -EventListener* KJSProxy::createHTMLEventHandler(const String& functionName, const String& code, Node* node) -{ - initScriptIfNeeded(); - JSLock lock; - return new JSLazyEventListener(functionName, code, Window::retrieveWindow(m_frame), node, m_handlerLineno); -} - -#if ENABLE(SVG) -EventListener* KJSProxy::createSVGEventHandler(const String& functionName, const String& code, Node* node) -{ - initScriptIfNeeded(); - JSLock lock; - return new JSSVGLazyEventListener(functionName, code, Window::retrieveWindow(m_frame), node, m_handlerLineno); -} -#endif - -void KJSProxy::finishedWithEvent(Event* event) -{ - // This is called when the DOM implementation has finished with a particular event. This - // is the case in sitations where an event has been created just for temporary usage, - // e.g. an image load or mouse move. Once the event has been dispatched, it is forgotten - // by the DOM implementation and so does not need to be cached still by the interpreter - ScriptInterpreter::forgetDOMObject(event); -} - -void KJSProxy::initScript() -{ - if (m_globalObject) - return; - - JSLock lock; - - m_globalObject = new JSDOMWindow(m_frame->domWindow()); - - // FIXME: We can get rid of this (and eliminate compatMode entirely). - String userAgent = m_frame->loader()->userAgent(m_frame->document() ? m_frame->document()->url() : KURL()); - if (userAgent.find("Microsoft") >= 0 || userAgent.find("MSIE") >= 0) - m_globalObject->setCompatMode(IECompat); - else { - // If we find "Mozilla" but not "(compatible, ...)" we are a real Netscape - if (userAgent.find("Mozilla") >= 0 && userAgent.find("compatible") == -1) - m_globalObject->setCompatMode(NetscapeCompat); - } - - m_frame->loader()->dispatchWindowObjectAvailable(); -} - -void KJSProxy::clearDocumentWrapper() -{ - if (!m_globalObject) - return; - - JSLock lock; - m_globalObject->removeDirect("document"); -} - -bool KJSProxy::processingUserGesture() const -{ - if (!m_globalObject) - return false; - - if (Event* event = m_globalObject->currentEvent()) { - const AtomicString& type = event->type(); - if ( // mouse events - type == clickEvent || type == mousedownEvent || - type == mouseupEvent || type == dblclickEvent || - // keyboard events - type == keydownEvent || type == keypressEvent || - type == keyupEvent || - // other accepted events - type == selectEvent || type == changeEvent || - type == focusEvent || type == blurEvent || - type == submitEvent) - return true; - } else { // no event - if (m_processingInlineCode && !m_processingTimerCallback) { - // This is the <a href="javascript:window.open('...')> case -> we let it through - return true; - } - // This is the <script>window.open(...)</script> case or a timer callback -> block it - } - return false; -} - -bool KJSProxy::isEnabled() -{ - Settings* settings = m_frame->settings(); - return (settings && settings->isJavaScriptEnabled()); -} - -} // namespace WebCore diff --git a/WebCore/bindings/js/kjs_proxy.h b/WebCore/bindings/js/kjs_proxy.h deleted file mode 100644 index c746566..0000000 --- a/WebCore/bindings/js/kjs_proxy.h +++ /dev/null @@ -1,89 +0,0 @@ -/* - * This file is part of the KDE libraries - * Copyright (C) 1999 Harri Porten (porten@kde.org) - * Copyright (C) 2001 Peter Kelly (pmk@post.com) - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#ifndef kjs_proxy_h -#define kjs_proxy_h - -#include "JSDOMWindow.h" -#include <kjs/protect.h> -#include <wtf/RefPtr.h> - -namespace KJS { - class JSGlobalObject; - class JSValue; -} - -namespace WebCore { - -class Event; -class EventListener; -class Frame; -class Node; -class String; - -// FIXME: Rename this class to JSController and the Frame function to javaScript(). - -class KJSProxy { -public: - KJSProxy(Frame*); - ~KJSProxy(); - - bool haveGlobalObject() const { return m_globalObject; } - JSDOMWindow* globalObject() - { - initScriptIfNeeded(); - return m_globalObject; - } - - KJS::JSValue* evaluate(const String& filename, int baseLine, const String& code); - void clear(); - EventListener* createHTMLEventHandler(const String& functionName, const String& code, Node*); -#if ENABLE(SVG) - EventListener* createSVGEventHandler(const String& functionName, const String& code, Node*); -#endif - void finishedWithEvent(Event*); - void setEventHandlerLineno(int lineno) { m_handlerLineno = lineno; } - - void clearDocumentWrapper(); - - void setProcessingTimerCallback(bool b) { m_processingTimerCallback = b; } - bool processingUserGesture() const; - - bool isEnabled(); - -private: - void initScriptIfNeeded() - { - if (!m_globalObject) - initScript(); - } - void initScript(); - - KJS::ProtectedPtr<JSDOMWindow> m_globalObject; - Frame* m_frame; - int m_handlerLineno; - - bool m_processingTimerCallback; - bool m_processingInlineCode; -}; - -} - -#endif diff --git a/WebCore/bindings/js/kjs_window.cpp b/WebCore/bindings/js/kjs_window.cpp deleted file mode 100644 index 4cc7bbf..0000000 --- a/WebCore/bindings/js/kjs_window.cpp +++ /dev/null @@ -1,1514 +0,0 @@ -/* - * Copyright (C) 2000 Harri Porten (porten@kde.org) - * Copyright (C) 2006 Jon Shier (jshier@iastate.edu) - * Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008 Apple Inc. All rights reseved. - * Copyright (C) 2006 Alexey Proskuryakov (ap@webkit.org) - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 - * USA - */ - -#include "config.h" -#include "kjs_window.h" - -#include "Base64.h" -#include "CString.h" -#include "Chrome.h" -#include "DOMWindow.h" -#include "Element.h" -#include "EventListener.h" -#include "EventNames.h" -#include "ExceptionCode.h" -#include "FloatRect.h" -#include "Frame.h" -#include "FrameLoadRequest.h" -#include "FrameLoader.h" -#include "FrameTree.h" -#include "GCController.h" -#include "HTMLDocument.h" -#include "JSDOMWindow.h" -#include "JSEvent.h" -#include "JSAudioConstructor.h" -#include "JSHTMLCollection.h" -#include "JSHTMLOptionElementConstructor.h" -#include "JSXMLHttpRequest.h" -#include "JSLocation.h" -#include "Logging.h" -#include "MediaPlayer.h" -#include "Page.h" -#include "PausedTimeouts.h" -#include "PlatformScreen.h" -#include "PluginInfoStore.h" -#include "RenderView.h" -#include "ScheduledAction.h" -#include "SecurityOrigin.h" -#include "Settings.h" -#include "WindowFeatures.h" -#include "htmlediting.h" -#include "kjs_css.h" -#include "kjs_events.h" -#include "kjs_navigator.h" -#include "kjs_proxy.h" -#include <wtf/AlwaysInline.h> -#include <wtf/MathExtras.h> - -#if ENABLE(XSLT) -#include "JSXSLTProcessor.h" -#endif - -using namespace WebCore; -using namespace EventNames; - -namespace KJS { - -static int lastUsedTimeoutId; - -static int timerNestingLevel = 0; -const int cMaxTimerNestingLevel = 5; -const double cMinimumTimerInterval = 0.010; - -struct WindowPrivate { - WindowPrivate() - : loc(0) - , m_evt(0) - , m_returnValueSlot(0) - { - } - - Window::ListenersMap jsEventListeners; - Window::ListenersMap jsHTMLEventListeners; - Window::UnprotectedListenersMap jsUnprotectedEventListeners; - Window::UnprotectedListenersMap jsUnprotectedHTMLEventListeners; - mutable WebCore::JSLocation* loc; - WebCore::Event* m_evt; - JSValue** m_returnValueSlot; - - typedef HashMap<int, DOMWindowTimer*> TimeoutsMap; - TimeoutsMap m_timeouts; -}; - -class DOMWindowTimer : public TimerBase { -public: - DOMWindowTimer(int timeoutId, int nestingLevel, Window* object, WebCore::ScheduledAction* action) - : m_timeoutId(timeoutId) - , m_nestingLevel(nestingLevel) - , m_object(object) - , m_action(action) - { - } - - virtual ~DOMWindowTimer() - { - JSLock lock; - delete m_action; - } - - int timeoutId() const { return m_timeoutId; } - - int nestingLevel() const { return m_nestingLevel; } - void setNestingLevel(int n) { m_nestingLevel = n; } - - WebCore::ScheduledAction* action() const { return m_action; } - WebCore::ScheduledAction* takeAction() { WebCore::ScheduledAction* a = m_action; m_action = 0; return a; } - -private: - virtual void fired(); - - int m_timeoutId; - int m_nestingLevel; - Window* m_object; - WebCore::ScheduledAction* m_action; -}; - -} // namespace KJS - -#include "kjs_window.lut.h" - -namespace KJS { - -////////////////////// Window Object //////////////////////// - -const ClassInfo Window::info = { "Window", 0, &WindowTable }; - -/* -@begin WindowTable 118 -# Warning, when adding a function to this object you need to add a case in Window::get -# -- Functions -- - atob windowProtoFuncAToB DontDelete|Function 1 - btoa windowProtoFuncBToA DontDelete|Function 1 - open windowProtoFuncOpen DontDelete|Function 3 - setTimeout windowProtoFuncSetTimeout DontDelete|Function 2 - clearTimeout windowProtoFuncClearTimeout DontDelete|Function 1 - setInterval windowProtoFuncSetInterval DontDelete|Function 2 - clearInterval windowProtoFuncClearTimeout DontDelete|Function 1 - addEventListener windowProtoFuncAddEventListener DontDelete|Function 3 - removeEventListener windowProtoFuncRemoveEventListener DontDelete|Function 3 - showModalDialog windowProtoFuncShowModalDialog DontDelete|Function 1 -# Not implemented - captureEvents windowProtoFuncNotImplemented DontDelete|Function 0 - releaseEvents windowProtoFuncNotImplemented DontDelete|Function 0 - -# -- Attributes -- - crypto Window::Crypto DontDelete|ReadOnly - event Window::Event_ DontDelete - location Window::Location_ DontDelete - navigator Window::Navigator_ DontDelete - clientInformation Window::ClientInformation DontDelete -# -- Event Listeners -- - onabort Window::Onabort DontDelete - onblur Window::Onblur DontDelete - onchange Window::Onchange DontDelete - onclick Window::Onclick DontDelete - ondblclick Window::Ondblclick DontDelete - onerror Window::Onerror DontDelete - onfocus Window::Onfocus DontDelete - onkeydown Window::Onkeydown DontDelete - onkeypress Window::Onkeypress DontDelete - onkeyup Window::Onkeyup DontDelete - onload Window::Onload DontDelete - onmousedown Window::Onmousedown DontDelete - onmousemove Window::Onmousemove DontDelete - onmouseout Window::Onmouseout DontDelete - onmouseover Window::Onmouseover DontDelete - onmouseup Window::Onmouseup DontDelete - onmousewheel Window::OnWindowMouseWheel DontDelete - onreset Window::Onreset DontDelete - onresize Window::Onresize DontDelete - onscroll Window::Onscroll DontDelete - onsearch Window::Onsearch DontDelete - onselect Window::Onselect DontDelete - onsubmit Window::Onsubmit DontDelete - onunload Window::Onunload DontDelete - onbeforeunload Window::Onbeforeunload DontDelete -# -- Constructors -- - Audio Window::Audio DontDelete - Image Window::Image DontDelete - Option Window::Option DontDelete - XMLHttpRequest Window::XMLHttpRequest DontDelete - XSLTProcessor Window::XSLTProcessor_ DontDelete -@end -*/ - -Window::Window(JSObject* prototype, DOMWindow* window) - : JSGlobalObject(prototype) - , m_impl(window) - , d(new WindowPrivate) -{ - // Window destruction is not thread-safe because of - // the non-thread-safe WebCore structures it references. - Collector::collectOnMainThreadOnly(this); - - // Time in milliseconds before the script timeout handler kicks in. - setTimeoutTime(10000); -} - -Window::~Window() -{ - clearAllTimeouts(); - - // Clear any backpointers to the window - - ListenersMap::iterator i2 = d->jsEventListeners.begin(); - ListenersMap::iterator e2 = d->jsEventListeners.end(); - for (; i2 != e2; ++i2) - i2->second->clearWindowObj(); - i2 = d->jsHTMLEventListeners.begin(); - e2 = d->jsHTMLEventListeners.end(); - for (; i2 != e2; ++i2) - i2->second->clearWindowObj(); - - UnprotectedListenersMap::iterator i1 = d->jsUnprotectedEventListeners.begin(); - UnprotectedListenersMap::iterator e1 = d->jsUnprotectedEventListeners.end(); - for (; i1 != e1; ++i1) - i1->second->clearWindowObj(); - i1 = d->jsUnprotectedHTMLEventListeners.begin(); - e1 = d->jsUnprotectedHTMLEventListeners.end(); - for (; i1 != e1; ++i1) - i1->second->clearWindowObj(); -} - -Window* Window::retrieveWindow(Frame* frame) -{ - JSObject* o = retrieve(frame)->getObject(); - - ASSERT(o || !frame->scriptProxy()->isEnabled()); - return static_cast<Window*>(o); -} - -Window* Window::retrieveActive(ExecState* exec) -{ - JSGlobalObject* globalObject = exec->dynamicGlobalObject(); - ASSERT(globalObject); - return static_cast<Window*>(globalObject); -} - -JSValue* Window::retrieve(Frame* frame) -{ - ASSERT(frame); - if (frame->scriptProxy()->isEnabled()) - return frame->scriptProxy()->globalObject(); // the Global object is the "window" - - return jsUndefined(); // This can happen with JS disabled on the domain of that window -} - -WebCore::JSLocation* Window::location() const -{ - if (!d->loc) - d->loc = new JSLocation(0, impl()->frame()); // FIXME: we need to pass a prototype. - return d->loc; -} - -void Window::mark() -{ - Base::mark(); - if (d->loc && !d->loc->marked()) - d->loc->mark(); -} - -static bool allowPopUp(ExecState* exec) -{ - Frame* frame = Window::retrieveActive(exec)->impl()->frame(); - - ASSERT(frame); - if (frame->scriptProxy()->processingUserGesture()) - return true; - Settings* settings = frame->settings(); - return settings && settings->JavaScriptCanOpenWindowsAutomatically(); -} - -static HashMap<String, String> parseModalDialogFeatures(const String& featuresArg) -{ - HashMap<String, String> map; - - Vector<String> features = featuresArg.split(';'); - Vector<String>::const_iterator end = features.end(); - for (Vector<String>::const_iterator it = features.begin(); it != end; ++it) { - String s = *it; - int pos = s.find('='); - int colonPos = s.find(':'); - if (pos >= 0 && colonPos >= 0) - continue; // ignore any strings that have both = and : - if (pos < 0) - pos = colonPos; - if (pos < 0) { - // null string for value means key without value - map.set(s.stripWhiteSpace().lower(), String()); - } else { - String key = s.left(pos).stripWhiteSpace().lower(); - String val = s.substring(pos + 1).stripWhiteSpace().lower(); - int spacePos = val.find(' '); - if (spacePos != -1) - val = val.left(spacePos); - map.set(key, val); - } - } - - return map; -} - -static Frame* createWindow(ExecState* exec, Frame* openerFrame, const String& url, - const String& frameName, const WindowFeatures& windowFeatures, JSValue* dialogArgs) -{ - Frame* activeFrame = Window::retrieveActive(exec)->impl()->frame(); - - ResourceRequest request; - if (activeFrame) - request.setHTTPReferrer(activeFrame->loader()->outgoingReferrer()); - FrameLoadRequest frameRequest(request, frameName); - - FrameLoader* loader; - if (activeFrame) - // We need to use the active frame's loader to let FrameLoader know - // which principal is requesting the navigation. Unfortunately, there - // might not be an activeFrame, in which case we resort to using the - // opener's loader. - // - // See http://bugs.webkit.org/show_bug.cgi?id=16522 - loader = activeFrame->loader(); - else - loader = openerFrame->loader(); - - // FIXME: It's much better for client API if a new window starts with a URL, here where we - // know what URL we are going to open. Unfortunately, this code passes the empty string - // for the URL, but there's a reason for that. Before loading we have to set up the opener, - // openedByDOM, and dialogArguments values. Also, to decide whether to use the URL we currently - // do an allowsAccessFrom call using the window we create, which can't be done before creating it. - // We'd have to resolve all those issues to pass the URL instead of "". - - bool created; - Frame* newFrame = loader->createWindow(frameRequest, windowFeatures, created); - if (!newFrame) - return 0; - - newFrame->loader()->setOpener(openerFrame); - newFrame->loader()->setOpenedByDOM(); - - Window* newWindow = Window::retrieveWindow(newFrame); - - if (dialogArgs) - newWindow->putDirect("dialogArguments", dialogArgs); - -#ifdef ANDROID_JAVASCRIPT_SECURITY - if (!protocolIs(url, "javascript") || newWindow->allowsAccessFrom(exec)) { -#else - if (!url.startsWith("javascript:", false) || newWindow->allowsAccessFrom(exec)) { -#endif - String completedURL = url.isEmpty() ? url : activeFrame->document()->completeURL(url); - bool userGesture = activeFrame->scriptProxy()->processingUserGesture(); - - if (created) { - newFrame->loader()->changeLocation(KURL(completedURL.deprecatedString()), activeFrame->loader()->outgoingReferrer(), false, userGesture); - if (Document* oldDoc = openerFrame->document()) - newFrame->document()->setBaseURL(oldDoc->baseURL()); - } else if (!url.isEmpty()) - newFrame->loader()->scheduleLocationChange(completedURL, activeFrame->loader()->outgoingReferrer(), false, userGesture); - } - - return newFrame; -} - -static bool canShowModalDialog(const Frame* frame) -{ - if (!frame) - return false; - return frame->page()->chrome()->canRunModal(); -} - -static bool canShowModalDialogNow(const Frame* frame) -{ - if (!frame) - return false; - return frame->page()->chrome()->canRunModalNow(); -} - -static JSValue* showModalDialog(ExecState* exec, Frame* frame, const String& url, JSValue* dialogArgs, const String& featureArgs) -{ - if (!canShowModalDialogNow(frame) || !allowPopUp(exec)) - return jsUndefined(); - - const HashMap<String, String> features = parseModalDialogFeatures(featureArgs); - - const bool trusted = false; - - // The following features from Microsoft's documentation are not implemented: - // - default font settings - // - width, height, left, and top specified in units other than "px" - // - edge (sunken or raised, default is raised) - // - dialogHide: trusted && boolFeature(features, "dialoghide"), makes dialog hide when you print - // - help: boolFeature(features, "help", true), makes help icon appear in dialog (what does it do on Windows?) - // - unadorned: trusted && boolFeature(features, "unadorned"); - - if (!frame) - return jsUndefined(); - - FloatRect screenRect = screenAvailableRect(frame->view()); - - WindowFeatures wargs; - wargs.width = WindowFeatures::floatFeature(features, "dialogwidth", 100, screenRect.width(), 620); // default here came from frame size of dialog in MacIE - wargs.widthSet = true; - wargs.height = WindowFeatures::floatFeature(features, "dialogheight", 100, screenRect.height(), 450); // default here came from frame size of dialog in MacIE - wargs.heightSet = true; - - wargs.x = WindowFeatures::floatFeature(features, "dialogleft", screenRect.x(), screenRect.right() - wargs.width, -1); - wargs.xSet = wargs.x > 0; - wargs.y = WindowFeatures::floatFeature(features, "dialogtop", screenRect.y(), screenRect.bottom() - wargs.height, -1); - wargs.ySet = wargs.y > 0; - - if (WindowFeatures::boolFeature(features, "center", true)) { - if (!wargs.xSet) { - wargs.x = screenRect.x() + (screenRect.width() - wargs.width) / 2; - wargs.xSet = true; - } - if (!wargs.ySet) { - wargs.y = screenRect.y() + (screenRect.height() - wargs.height) / 2; - wargs.ySet = true; - } - } - - wargs.dialog = true; - wargs.resizable = WindowFeatures::boolFeature(features, "resizable"); - wargs.scrollbarsVisible = WindowFeatures::boolFeature(features, "scroll", true); - wargs.statusBarVisible = WindowFeatures::boolFeature(features, "status", !trusted); - wargs.menuBarVisible = false; - wargs.toolBarVisible = false; - wargs.locationBarVisible = false; - wargs.fullscreen = false; - - Frame* dialogFrame = createWindow(exec, frame, url, "", wargs, dialogArgs); - if (!dialogFrame) - return jsUndefined(); - - Window* dialogWindow = Window::retrieveWindow(dialogFrame); - - // Get the return value either just before clearing the dialog window's - // properties (in Window::clear), or when on return from runModal. - JSValue* returnValue = 0; - dialogWindow->setReturnValueSlot(&returnValue); - dialogFrame->page()->chrome()->runModal(); - dialogWindow->setReturnValueSlot(0); - - // If we don't have a return value, get it now. - // Either Window::clear was not called yet, or there was no return value, - // and in that case, there's no harm in trying again (no benefit either). - if (!returnValue) - returnValue = dialogWindow->getDirect("returnValue"); - - return returnValue ? returnValue : jsUndefined(); -} - -JSValue *Window::getValueProperty(ExecState *exec, int token) const -{ - ASSERT(impl()->frame()); - - switch (token) { - case Crypto: - return jsUndefined(); // FIXME: implement this - case Event_: - if (!allowsAccessFrom(exec)) - return jsUndefined(); - if (!d->m_evt) - return jsUndefined(); - return toJS(exec, d->m_evt); - case Location_: - return location(); - case Navigator_: - case ClientInformation: { - if (!allowsAccessFrom(exec)) - return jsUndefined(); - // Store the navigator in the object so we get the same one each time. - Navigator* n = new Navigator(exec->lexicalGlobalObject()->objectPrototype(), impl()->frame()); - // FIXME: this will make the "navigator" object accessible from windows that fail - // the security check the first time, but not subsequent times, seems weird. - const_cast<Window *>(this)->putDirect("navigator", n, DontDelete); - const_cast<Window *>(this)->putDirect("clientInformation", n, DontDelete); - return n; - } - case Image: - if (!allowsAccessFrom(exec)) - return jsUndefined(); - // FIXME: this property (and the few below) probably shouldn't create a new object every - // time - return new ImageConstructorImp(exec, impl()->frame()->document()); - case Option: - if (!allowsAccessFrom(exec)) - return jsUndefined(); - return new JSHTMLOptionElementConstructor(exec, impl()->frame()->document()); - case XMLHttpRequest: - if (!allowsAccessFrom(exec)) - return jsUndefined(); - return new JSXMLHttpRequestConstructorImp(exec, impl()->frame()->document()); - case Audio: -#if ENABLE(VIDEO) - if (!allowsAccessFrom(exec)) - return jsUndefined(); - if (!MediaPlayer::isAvailable()) - return jsUndefined(); - return new JSAudioConstructor(exec, impl()->frame()->document()); -#else - return jsUndefined(); -#endif -#if ENABLE(XSLT) - case XSLTProcessor_: - if (!allowsAccessFrom(exec)) - return jsUndefined(); - return new XSLTProcessorConstructorImp(exec); -#else - case XSLTProcessor_: - return jsUndefined(); -#endif - } - - if (!allowsAccessFrom(exec)) - return jsUndefined(); - - switch (token) { - case Onabort: - return getListener(exec, abortEvent); - case Onblur: - return getListener(exec, blurEvent); - case Onchange: - return getListener(exec, changeEvent); - case Onclick: - return getListener(exec, clickEvent); - case Ondblclick: - return getListener(exec, dblclickEvent); - case Onerror: - return getListener(exec, errorEvent); - case Onfocus: - return getListener(exec, focusEvent); - case Onkeydown: - return getListener(exec, keydownEvent); - case Onkeypress: - return getListener(exec, keypressEvent); - case Onkeyup: - return getListener(exec, keyupEvent); - case Onload: - return getListener(exec, loadEvent); - case Onmousedown: - return getListener(exec, mousedownEvent); - case Onmousemove: - return getListener(exec, mousemoveEvent); - case Onmouseout: - return getListener(exec, mouseoutEvent); - case Onmouseover: - return getListener(exec, mouseoverEvent); - case Onmouseup: - return getListener(exec, mouseupEvent); - case OnWindowMouseWheel: - return getListener(exec, mousewheelEvent); - case Onreset: - return getListener(exec, resetEvent); - case Onresize: - return getListener(exec,resizeEvent); - case Onscroll: - return getListener(exec,scrollEvent); - case Onsearch: - return getListener(exec,searchEvent); - case Onselect: - return getListener(exec,selectEvent); - case Onsubmit: - return getListener(exec,submitEvent); - case Onbeforeunload: - return getListener(exec, beforeunloadEvent); - case Onunload: - return getListener(exec, unloadEvent); - } - ASSERT_NOT_REACHED(); - return jsUndefined(); -} - -JSValue* Window::childFrameGetter(ExecState*, JSObject*, const Identifier& propertyName, const PropertySlot& slot) -{ - return retrieve(static_cast<Window*>(slot.slotBase())->impl()->frame()->tree()->child(AtomicString(propertyName))); -} - -JSValue* Window::indexGetter(ExecState*, JSObject*, const Identifier&, const PropertySlot& slot) -{ - return retrieve(static_cast<Window*>(slot.slotBase())->impl()->frame()->tree()->child(slot.index())); -} - -JSValue* Window::namedItemGetter(ExecState* exec, JSObject* originalObject, const Identifier& propertyName, const PropertySlot& slot) -{ - Window* thisObj = static_cast<Window*>(slot.slotBase()); - Document* doc = thisObj->impl()->frame()->document(); - ASSERT(thisObj->allowsAccessFrom(exec)); - ASSERT(doc); - ASSERT(doc->isHTMLDocument()); - - RefPtr<WebCore::HTMLCollection> collection = doc->windowNamedItems(propertyName); - if (collection->length() == 1) - return toJS(exec, collection->firstItem()); - return toJS(exec, collection.get()); -} - -bool Window::getOwnPropertySlot(ExecState* exec, const Identifier& propertyName, PropertySlot& slot) -{ - // Check for child frames by name before built-in properties to - // match Mozilla. This does not match IE, but some sites end up - // naming frames things that conflict with window properties that - // are in Moz but not IE. Since we have some of these, we have to do - // it the Moz way. - if (impl()->frame()->tree()->child(propertyName)) { - slot.setCustom(this, childFrameGetter); - return true; - } - - const HashEntry* entry = Lookup::findEntry(&WindowTable, propertyName); - if (entry) { - if (entry->attr & Function) { - if (entry->value.functionValue == windowProtoFuncShowModalDialog) { - if (!canShowModalDialog(impl()->frame())) - return false; - } - if (allowsAccessFrom(exec)) - slot.setStaticEntry(this, entry, staticFunctionGetter); - else - slot.setUndefined(this); - } else - slot.setStaticEntry(this, entry, staticValueGetter<Window>); - return true; - } - - // Do prototype lookup early so that functions and attributes in the prototype can have - // precedence over the index and name getters. - JSValue* proto = prototype(); - if (proto->isObject()) { - if (static_cast<JSObject*>(proto)->getOwnPropertySlot(exec, propertyName, slot)) { - if (!allowsAccessFrom(exec)) - slot.setUndefined(this); - return true; - } - } - - // FIXME: Search the whole frame hierachy somewhere around here. - // We need to test the correct priority order. - - // allow window[1] or parent[1] etc. (#56983) - bool ok; - unsigned i = propertyName.toArrayIndex(&ok); - if (ok && i < impl()->frame()->tree()->childCount()) { - slot.setCustomIndex(this, i, indexGetter); - return true; - } - - if (!allowsAccessFrom(exec)) { - slot.setUndefined(this); - return true; - } - - // Allow shortcuts like 'Image1' instead of document.images.Image1 - Document* doc = impl()->frame()->document(); - if (doc && doc->isHTMLDocument()) { - AtomicString atomicPropertyName = propertyName; - if (static_cast<HTMLDocument*>(doc)->hasNamedItem(atomicPropertyName) || doc->getElementById(atomicPropertyName)) { - slot.setCustom(this, namedItemGetter); - return true; - } - } - - return Base::getOwnPropertySlot(exec, propertyName, slot); -} - -void Window::put(ExecState* exec, const Identifier& propertyName, JSValue* value, int attr) -{ - const HashEntry* entry = Lookup::findEntry(&WindowTable, propertyName); - if (entry) { - if (entry->attr & Function) { - if (allowsAccessFrom(exec)) - Base::put(exec, propertyName, value, attr); - return; - } - if (entry->attr & ReadOnly) - return; - - switch (entry->value.intValue) { - case Location_: { - if (Frame* p = Window::retrieveActive(exec)->impl()->frame()) { - // To avoid breaking old widgets, make "var location =" in a top-level frame create - // a property named "location" instead of performing a navigation (<rdar://problem/5688039>). - if (Settings* settings = p->settings()) { - if (settings->usesDashboardBackwardCompatibilityMode() && !p->tree()->parent()) { - if (allowsAccessFrom(exec)) - putDirect(propertyName, value, attr); - return; - } - } - - if (!p->loader()->shouldAllowNavigation(impl()->frame())) - return; - String dstUrl = p->loader()->completeURL(value->toString(exec)).string(); -#ifdef ANDROID_JAVASCRIPT_SECURITY - if (!protocolIs(dstUrl, "javascript") || allowsAccessFrom(exec)) { -#else - if (!dstUrl.startsWith("javascript:", false) || allowsAccessFrom(exec)) { -#endif - bool userGesture = p->scriptProxy()->processingUserGesture(); - // We want a new history item if this JS was called via a user gesture - impl()->frame()->loader()->scheduleLocationChange(dstUrl, p->loader()->outgoingReferrer(), false, userGesture); - } - } - return; - } - case Onabort: - if (allowsAccessFrom(exec)) - setListener(exec, abortEvent,value); - return; - case Onblur: - if (allowsAccessFrom(exec)) - setListener(exec, blurEvent,value); - return; - case Onchange: - if (allowsAccessFrom(exec)) - setListener(exec, changeEvent,value); - return; - case Onclick: - if (allowsAccessFrom(exec)) - setListener(exec,clickEvent,value); - return; - case Ondblclick: - if (allowsAccessFrom(exec)) - setListener(exec, dblclickEvent,value); - return; - case Onerror: - if (allowsAccessFrom(exec)) - setListener(exec, errorEvent, value); - return; - case Onfocus: - if (allowsAccessFrom(exec)) - setListener(exec,focusEvent,value); - return; - case Onkeydown: - if (allowsAccessFrom(exec)) - setListener(exec,keydownEvent,value); - return; - case Onkeypress: - if (allowsAccessFrom(exec)) - setListener(exec,keypressEvent,value); - return; - case Onkeyup: - if (allowsAccessFrom(exec)) - setListener(exec,keyupEvent,value); - return; - case Onload: - if (allowsAccessFrom(exec)) - setListener(exec,loadEvent,value); - return; - case Onmousedown: - if (allowsAccessFrom(exec)) - setListener(exec,mousedownEvent,value); - return; - case Onmousemove: - if (allowsAccessFrom(exec)) - setListener(exec,mousemoveEvent,value); - return; - case Onmouseout: - if (allowsAccessFrom(exec)) - setListener(exec,mouseoutEvent,value); - return; - case Onmouseover: - if (allowsAccessFrom(exec)) - setListener(exec,mouseoverEvent,value); - return; - case Onmouseup: - if (allowsAccessFrom(exec)) - setListener(exec,mouseupEvent,value); - return; - case OnWindowMouseWheel: - if (allowsAccessFrom(exec)) - setListener(exec, mousewheelEvent,value); - return; - case Onreset: - if (allowsAccessFrom(exec)) - setListener(exec,resetEvent,value); - return; - case Onresize: - if (allowsAccessFrom(exec)) - setListener(exec,resizeEvent,value); - return; - case Onscroll: - if (allowsAccessFrom(exec)) - setListener(exec,scrollEvent,value); - return; - case Onsearch: - if (allowsAccessFrom(exec)) - setListener(exec,searchEvent,value); - return; - case Onselect: - if (allowsAccessFrom(exec)) - setListener(exec,selectEvent,value); - return; - case Onsubmit: - if (allowsAccessFrom(exec)) - setListener(exec,submitEvent,value); - return; - case Onbeforeunload: - if (allowsAccessFrom(exec)) - setListener(exec, beforeunloadEvent, value); - return; - case Onunload: - if (allowsAccessFrom(exec)) - setListener(exec, unloadEvent, value); - return; - default: - break; - } - } - if (allowsAccessFrom(exec)) - Base::put(exec, propertyName, value, attr); -} - -bool Window::allowsAccessFrom(const JSGlobalObject* other) const -{ - SecurityOrigin::Reason reason; - if (allowsAccessFromPrivate(other, reason)) - return true; - printErrorMessage(crossDomainAccessErrorMessage(other, reason)); - return false; -} - -bool Window::allowsAccessFrom(ExecState* exec) const -{ - SecurityOrigin::Reason reason; - if (allowsAccessFromPrivate(exec, reason)) - return true; - printErrorMessage(crossDomainAccessErrorMessage(exec->dynamicGlobalObject(), reason)); - return false; -} - -bool Window::allowsAccessFromNoErrorMessage(ExecState* exec) const -{ - SecurityOrigin::Reason reason; - return allowsAccessFromPrivate(exec, reason); -} - -bool Window::allowsAccessFrom(ExecState* exec, String& message) const -{ - SecurityOrigin::Reason reason; - if (allowsAccessFromPrivate(exec, reason)) - return true; - message = crossDomainAccessErrorMessage(exec->dynamicGlobalObject(), reason); - return false; -} - -ALWAYS_INLINE bool Window::allowsAccessFromPrivate(const ExecState* exec, SecurityOrigin::Reason& reason) const -{ - if (allowsAccessFromPrivate(exec->dynamicGlobalObject(), reason)) - return true; - if (reason == SecurityOrigin::DomainSetInDOMMismatch) { - // If the only reason the access failed was a domainSetInDOM bit mismatch, try again against - // lexical global object <rdar://problem/5698200> - if (allowsAccessFromPrivate(exec->lexicalGlobalObject(), reason)) - return true; - } - return false; -} - -ALWAYS_INLINE bool Window::allowsAccessFromPrivate(const JSGlobalObject* other, SecurityOrigin::Reason& reason) const -{ - const Frame* originFrame = static_cast<const Window*>(other)->impl()->frame(); - if (!originFrame) { - reason = SecurityOrigin::GenericMismatch; - return false; - } - - const Frame* targetFrame = impl()->frame(); - - if (originFrame == targetFrame) - return true; - - if (!targetFrame) { - reason = SecurityOrigin::GenericMismatch; - return false; - } - - WebCore::Document* targetDocument = targetFrame->document(); - - // JS may be attempting to access the "window" object, which should be valid, - // even if the document hasn't been constructed yet. If the document doesn't - // exist yet allow JS to access the window object. - if (!targetDocument) - return true; - - WebCore::Document* originDocument = originFrame->document(); - - const SecurityOrigin* originSecurityOrigin = originDocument->securityOrigin(); - const SecurityOrigin* targetSecurityOrigin = targetDocument->securityOrigin(); - - if (originSecurityOrigin->canAccess(targetSecurityOrigin, reason)) - return true; - - return false; -} - -String Window::crossDomainAccessErrorMessage(const JSGlobalObject* other, SecurityOrigin::Reason) const -{ - const Frame* originFrame = static_cast<const Window*>(other)->impl()->frame(); - const Frame* targetFrame = impl()->frame(); - if (!originFrame || !targetFrame) - return String(); - WebCore::Document* targetDocument = targetFrame->document(); - WebCore::Document* originDocument = originFrame->document(); - if (!originDocument || !targetDocument) - return String(); - // FIXME: this error message should contain more specifics of why the same origin check has failed. - return String::format("Unsafe JavaScript attempt to access frame with URL %s from frame with URL %s. Domains, protocols and ports must match.\n", - targetDocument->url().utf8().data(), originDocument->url().utf8().data()); -} - -void Window::printErrorMessage(const String& message) const -{ - if (message.isEmpty()) - return; - - Frame* frame = impl()->frame(); - if (!frame) - return; - - if (frame->settings()->privateBrowsingEnabled()) - return; - - if (Interpreter::shouldPrintExceptions()) - printf("%s", message.utf8().data()); - - if (Page* page = frame->page()) - page->chrome()->addMessageToConsole(JSMessageSource, ErrorMessageLevel, message, 1, String()); // FIXME: provide a real line number and source URL. -} - -ExecState* Window::globalExec() -{ - // We need to make sure that any script execution happening in this - // frame does not destroy it - ASSERT(impl()->frame()); - impl()->frame()->keepAlive(); - return Base::globalExec(); -} - -bool Window::shouldInterruptScript() const -{ - ASSERT(impl()->frame()); - Page* page = impl()->frame()->page(); - - // See <rdar://problem/5479443>. We don't think that page can ever be NULL - // in this case, but if it is, we've gotten into a state where we may have - // hung the UI, with no way to ask the client whether to cancel execution. - // For now, our solution is just to cancel execution no matter what, - // ensuring that we never hang. We might want to consider other solutions - // if we discover problems with this one. - ASSERT(page); - if (!page) - return true; - - return page->chrome()->shouldInterruptJavaScript(); -} - -void Window::setListener(ExecState* exec, const AtomicString& eventType, JSValue* func) -{ - ASSERT(impl()->frame()); - Document* doc = impl()->frame()->document(); - if (!doc) - return; - - doc->setHTMLWindowEventListener(eventType, findOrCreateJSEventListener(func, true)); -} - -JSValue* Window::getListener(ExecState* exec, const AtomicString& eventType) const -{ - ASSERT(impl()->frame()); - Document* doc = impl()->frame()->document(); - if (!doc) - return jsUndefined(); - - WebCore::EventListener* listener = doc->getHTMLWindowEventListener(eventType); - if (listener && static_cast<JSEventListener*>(listener)->listenerObj()) - return static_cast<JSEventListener*>(listener)->listenerObj(); - return jsNull(); -} - -JSEventListener* Window::findJSEventListener(JSValue* val, bool html) -{ - if (!val->isObject()) - return 0; - JSObject* object = static_cast<JSObject*>(val); - ListenersMap& listeners = html ? d->jsHTMLEventListeners : d->jsEventListeners; - return listeners.get(object); -} - -JSEventListener* Window::findOrCreateJSEventListener(JSValue* val, bool html) -{ - JSEventListener* listener = findJSEventListener(val, html); - if (listener) - return listener; - - if (!val->isObject()) - return 0; - JSObject* object = static_cast<JSObject*>(val); - - // Note that the JSEventListener constructor adds it to our jsEventListeners list - return new JSEventListener(object, this, html); -} - -JSUnprotectedEventListener* Window::findJSUnprotectedEventListener(JSValue* val, bool html) -{ - if (!val->isObject()) - return 0; - JSObject* object = static_cast<JSObject*>(val); - UnprotectedListenersMap& listeners = html ? d->jsUnprotectedHTMLEventListeners : d->jsUnprotectedEventListeners; - return listeners.get(object); -} - -JSUnprotectedEventListener* Window::findOrCreateJSUnprotectedEventListener(JSValue* val, bool html) -{ - JSUnprotectedEventListener* listener = findJSUnprotectedEventListener(val, html); - if (listener) - return listener; - if (!val->isObject()) - return 0; - JSObject* object = static_cast<JSObject*>(val); - - // The JSUnprotectedEventListener constructor adds it to our jsUnprotectedEventListeners map. - return new JSUnprotectedEventListener(object, this, html); -} - -void Window::clearHelperObjectProperties() -{ - d->loc = 0; - d->m_evt = 0; -} - -void Window::clear() -{ - JSLock lock; - - if (d->m_returnValueSlot && !*d->m_returnValueSlot) - *d->m_returnValueSlot = getDirect("returnValue"); - - clearAllTimeouts(); - clearHelperObjectProperties(); - - // Now recreate a working global object for the next URL that will use us; but only if we haven't been - // disconnected yet - if (Frame* frame = impl()->frame()) - frame->scriptProxy()->globalObject()->reset(JSDOMWindowPrototype::self()); - - // there's likely to be lots of garbage now - gcController().garbageCollectSoon(); -} - -void Window::setCurrentEvent(Event* evt) -{ - d->m_evt = evt; -} - -Event* Window::currentEvent() -{ - return d->m_evt; -} - -JSValue* windowProtoFuncAToB(ExecState* exec, JSObject* thisObj, const List& args) -{ - if (!thisObj->inherits(&Window::info)) - return throwError(exec, TypeError); - if (!static_cast<Window*>(thisObj)->allowsAccessFrom(exec)) - return jsUndefined(); - - if (args.size() < 1) - return throwError(exec, SyntaxError, "Not enough arguments"); - - JSValue* v = args[0]; - if (v->isNull()) - return jsString(); - - UString s = v->toString(exec); - if (!s.is8Bit()) { - setDOMException(exec, INVALID_CHARACTER_ERR); - return jsUndefined(); - } - - Vector<char> in(s.size()); - for (int i = 0; i < s.size(); ++i) - in[i] = static_cast<char>(s.data()[i].unicode()); - Vector<char> out; - - if (!base64Decode(in, out)) - return throwError(exec, GeneralError, "Cannot decode base64"); - - return jsString(String(out.data(), out.size())); -} - -JSValue* windowProtoFuncBToA(ExecState* exec, JSObject* thisObj, const List& args) -{ - if (!thisObj->inherits(&Window::info)) - return throwError(exec, TypeError); - if (!static_cast<Window*>(thisObj)->allowsAccessFrom(exec)) - return jsUndefined(); - - if (args.size() < 1) - return throwError(exec, SyntaxError, "Not enough arguments"); - - JSValue* v = args[0]; - if (v->isNull()) - return jsString(); - - UString s = v->toString(exec); - if (!s.is8Bit()) { - setDOMException(exec, INVALID_CHARACTER_ERR); - return jsUndefined(); - } - - Vector<char> in(s.size()); - for (int i = 0; i < s.size(); ++i) - in[i] = static_cast<char>(s.data()[i].unicode()); - Vector<char> out; - - base64Encode(in, out); - - return jsString(String(out.data(), out.size())); -} - -JSValue* windowProtoFuncOpen(ExecState* exec, JSObject* thisObj, const List& args) -{ - if (!thisObj->inherits(&Window::info)) - return throwError(exec, TypeError); - Window* window = static_cast<Window*>(thisObj); - if (!window->allowsAccessFrom(exec)) - return jsUndefined(); - - Frame* frame = window->impl()->frame(); - if (!frame) - return jsUndefined(); - Frame* activeFrame = Window::retrieveActive(exec)->impl()->frame(); - if (!activeFrame) - return jsUndefined(); - - Page* page = frame->page(); - - String urlString = valueToStringWithUndefinedOrNullCheck(exec, args[0]); - AtomicString frameName = args[1]->isUndefinedOrNull() ? "_blank" : AtomicString(args[1]->toString(exec)); - - // Because FrameTree::find() returns true for empty strings, we must check for empty framenames. - // Otherwise, illegitimate window.open() calls with no name will pass right through the popup blocker. - if (!allowPopUp(exec) && (frameName.isEmpty() || !frame->tree()->find(frameName))) - return jsUndefined(); - - // Get the target frame for the special cases of _top and _parent. In those - // cases, we can schedule a location change right now and return early. - bool topOrParent = false; - if (frameName == "_top") { - frame = frame->tree()->top(); - topOrParent = true; - } else if (frameName == "_parent") { - if (Frame* parent = frame->tree()->parent()) - frame = parent; - topOrParent = true; - } - if (topOrParent) { - if (!activeFrame->loader()->shouldAllowNavigation(frame)) - return jsUndefined(); - - String completedURL; - if (!urlString.isEmpty()) - completedURL = activeFrame->document()->completeURL(urlString); - - const Window* targetedWindow = Window::retrieveWindow(frame); -#ifdef ANDROID_JAVASCRIPT_SECURITY - if (!completedURL.isEmpty() && (!protocolIs(completedURL, "javascript") || (targetedWindow && targetedWindow->allowsAccessFrom(exec)))) { -#else - if (!completedURL.isEmpty() && (!completedURL.startsWith("javascript:", false) || (targetedWindow && targetedWindow->allowsAccessFrom(exec)))) { -#endif - bool userGesture = activeFrame->scriptProxy()->processingUserGesture(); - frame->loader()->scheduleLocationChange(completedURL, activeFrame->loader()->outgoingReferrer(), false, userGesture); - } - return Window::retrieve(frame); - } - - // In the case of a named frame or a new window, we'll use the createWindow() helper - WindowFeatures windowFeatures(valueToStringWithUndefinedOrNullCheck(exec, args[2])); - FloatRect windowRect(windowFeatures.x, windowFeatures.y, windowFeatures.width, windowFeatures.height); - WebCore::DOMWindow::adjustWindowRect(screenAvailableRect(page->mainFrame()->view()), windowRect, windowRect); - - windowFeatures.x = windowRect.x(); - windowFeatures.y = windowRect.y(); - windowFeatures.height = windowRect.height(); - windowFeatures.width = windowRect.width(); - - frame = createWindow(exec, frame, urlString, frameName, windowFeatures, 0); - - if (!frame) - return jsUndefined(); - - return Window::retrieve(frame); // global object -} - -JSValue* windowProtoFuncSetTimeout(ExecState* exec, JSObject* thisObj, const List& args) -{ - if (!thisObj->inherits(&Window::info)) - return throwError(exec, TypeError); - Window* window = static_cast<Window*>(thisObj); - if (!window->allowsAccessFrom(exec)) - return jsUndefined(); - - JSValue* v = args[0]; - if (v->isString()) - return jsNumber(window->installTimeout(v->toString(exec), args[1]->toInt32(exec), true /*single shot*/)); - if (v->isObject() && static_cast<JSObject*>(v)->implementsCall()) { - List argsTail; - args.getSlice(2, argsTail); - return jsNumber(window->installTimeout(v, argsTail, args[1]->toInt32(exec), true /*single shot*/)); - } - - return jsUndefined(); -} - -JSValue* windowProtoFuncClearTimeout(ExecState* exec, JSObject* thisObj, const List& args) -{ - // Also the implementation for window.clearInterval() - - if (!thisObj->inherits(&Window::info)) - return throwError(exec, TypeError); - Window* window = static_cast<Window*>(thisObj); - if (!window->allowsAccessFrom(exec)) - return jsUndefined(); - - window->clearTimeout(args[0]->toInt32(exec)); - return jsUndefined(); -} - -JSValue* windowProtoFuncSetInterval(ExecState* exec, JSObject* thisObj, const List& args) -{ - if (!thisObj->inherits(&Window::info)) - return throwError(exec, TypeError); - Window* window = static_cast<Window*>(thisObj); - if (!window->allowsAccessFrom(exec)) - return jsUndefined(); - - if (args.size() >= 2) { - JSValue* v = args[0]; - int delay = args[1]->toInt32(exec); - if (v->isString()) - return jsNumber(window->installTimeout(v->toString(exec), delay, false)); - if (v->isObject() && static_cast<JSObject*>(v)->implementsCall()) { - List argsTail; - args.getSlice(2, argsTail); - return jsNumber(window->installTimeout(v, argsTail, delay, false)); - } - } - - return jsUndefined(); - -} - -JSValue* windowProtoFuncAddEventListener(ExecState* exec, JSObject* thisObj, const List& args) -{ - if (!thisObj->inherits(&Window::info)) - return throwError(exec, TypeError); - Window* window = static_cast<Window*>(thisObj); - if (!window->allowsAccessFrom(exec)) - return jsUndefined(); - Frame* frame = window->impl()->frame(); - if (!frame) - return jsUndefined(); - - if (JSEventListener* listener = window->findOrCreateJSEventListener(args[1])) { - if (Document* doc = frame->document()) - doc->addWindowEventListener(AtomicString(args[0]->toString(exec)), listener, args[2]->toBoolean(exec)); - } - - return jsUndefined(); -} - -JSValue* windowProtoFuncRemoveEventListener(ExecState* exec, JSObject* thisObj, const List& args) -{ - if (!thisObj->inherits(&Window::info)) - return throwError(exec, TypeError); - Window* window = static_cast<Window*>(thisObj); - if (!window->allowsAccessFrom(exec)) - return jsUndefined(); - Frame* frame = window->impl()->frame(); - if (!frame) - return jsUndefined(); - - if (JSEventListener* listener = window->findJSEventListener(args[1])) { - if (Document* doc = frame->document()) - doc->removeWindowEventListener(AtomicString(args[0]->toString(exec)), listener, args[2]->toBoolean(exec)); - } - - return jsUndefined(); -} - -JSValue* windowProtoFuncShowModalDialog(ExecState* exec, JSObject* thisObj, const List& args) -{ - if (!thisObj->inherits(&Window::info)) - return throwError(exec, TypeError); - Window* window = static_cast<Window*>(thisObj); - Frame* frame = window->impl()->frame(); - if (!frame) - return jsUndefined(); - - return showModalDialog(exec, frame, valueToStringWithUndefinedOrNullCheck(exec, args[0]), args[1], valueToStringWithUndefinedOrNullCheck(exec, args[2])); -} - -JSValue* windowProtoFuncNotImplemented(ExecState* exec, JSObject* thisObj, const List& args) -{ - if (!thisObj->inherits(&Window::info)) - return throwError(exec, TypeError); - - return jsUndefined(); -} - -void Window::setReturnValueSlot(JSValue** slot) -{ - d->m_returnValueSlot = slot; -} - -////////////////////// timeouts //////////////////////// - -void Window::clearAllTimeouts() -{ - deleteAllValues(d->m_timeouts); - d->m_timeouts.clear(); -} - -int Window::installTimeout(WebCore::ScheduledAction* a, int t, bool singleShot) -{ - int timeoutId = ++lastUsedTimeoutId; - - // avoid wraparound going negative on us - if (timeoutId <= 0) - timeoutId = 1; - - int nestLevel = timerNestingLevel + 1; - DOMWindowTimer* timer = new DOMWindowTimer(timeoutId, nestLevel, this, a); - ASSERT(!d->m_timeouts.get(timeoutId)); - d->m_timeouts.set(timeoutId, timer); - // Use a minimum interval of 10 ms to match other browsers, but only once we've - // nested enough to notice that we're repeating. - // Faster timers might be "better", but they're incompatible. - double interval = max(0.001, t * 0.001); - if (interval < cMinimumTimerInterval && nestLevel >= cMaxTimerNestingLevel) - interval = cMinimumTimerInterval; - if (singleShot) - timer->startOneShot(interval); - else - timer->startRepeating(interval); - return timeoutId; -} - -int Window::installTimeout(const UString& handler, int t, bool singleShot) -{ - return installTimeout(new WebCore::ScheduledAction(handler), t, singleShot); -} - -int Window::installTimeout(JSValue* func, const List& args, int t, bool singleShot) -{ - return installTimeout(new WebCore::ScheduledAction(func, args), t, singleShot); -} - -WebCore::PausedTimeouts* Window::pauseTimeouts() -{ - size_t count = d->m_timeouts.size(); - if (count == 0) - return 0; - - PausedTimeout* t = new PausedTimeout [count]; - PausedTimeouts* result = new PausedTimeouts(t, count); - - WindowPrivate::TimeoutsMap::iterator it = d->m_timeouts.begin(); - for (size_t i = 0; i != count; ++i, ++it) { - int timeoutId = it->first; - DOMWindowTimer* timer = it->second; - t[i].timeoutId = timeoutId; - t[i].nestingLevel = timer->nestingLevel(); - t[i].nextFireInterval = timer->nextFireInterval(); - t[i].repeatInterval = timer->repeatInterval(); - t[i].action = timer->takeAction(); - } - ASSERT(it == d->m_timeouts.end()); - - deleteAllValues(d->m_timeouts); - d->m_timeouts.clear(); - - return result; -} - -void Window::resumeTimeouts(PausedTimeouts* timeouts) -{ - if (!timeouts) - return; - size_t count = timeouts->numTimeouts(); - PausedTimeout* array = timeouts->takeTimeouts(); - for (size_t i = 0; i != count; ++i) { - int timeoutId = array[i].timeoutId; - DOMWindowTimer* timer = new DOMWindowTimer(timeoutId, array[i].nestingLevel, this, array[i].action); - d->m_timeouts.set(timeoutId, timer); - timer->start(array[i].nextFireInterval, array[i].repeatInterval); - } - delete [] array; -} - -void Window::clearTimeout(int timeoutId, bool delAction) -{ - // timeout IDs have to be positive, and 0 and -1 are unsafe to - // even look up since they are the empty and deleted value - // respectively - if (timeoutId <= 0) - return; - - delete d->m_timeouts.take(timeoutId); -} - -void Window::timerFired(DOMWindowTimer* timer) -{ - // Simple case for non-one-shot timers. - if (timer->isActive()) { - int timeoutId = timer->timeoutId(); - - timer->action()->execute(this); - // The DOMWindowTimer object may have been deleted or replaced during execution, - // so we re-fetch it. - timer = d->m_timeouts.get(timeoutId); - if (!timer) - return; - - if (timer->repeatInterval() && timer->repeatInterval() < cMinimumTimerInterval) { - timer->setNestingLevel(timer->nestingLevel() + 1); - if (timer->nestingLevel() >= cMaxTimerNestingLevel) - timer->augmentRepeatInterval(cMinimumTimerInterval - timer->repeatInterval()); - } - return; - } - - // Delete timer before executing the action for one-shot timers. - WebCore::ScheduledAction* action = timer->takeAction(); - d->m_timeouts.remove(timer->timeoutId()); - delete timer; - action->execute(this); - - JSLock lock; - delete action; -} - -void Window::disconnectFrame() -{ - clearAllTimeouts(); - if (d->loc) - d->loc->m_frame = 0; -} - -Window::ListenersMap& Window::jsEventListeners() -{ - return d->jsEventListeners; -} - -Window::ListenersMap& Window::jsHTMLEventListeners() -{ - return d->jsHTMLEventListeners; -} - -Window::UnprotectedListenersMap& Window::jsUnprotectedEventListeners() -{ - return d->jsUnprotectedEventListeners; -} - -Window::UnprotectedListenersMap& Window::jsUnprotectedHTMLEventListeners() -{ - return d->jsUnprotectedHTMLEventListeners; -} - -///////////////////////////////////////////////////////////////////////////// - -void DOMWindowTimer::fired() -{ - timerNestingLevel = m_nestingLevel; - m_object->timerFired(this); - timerNestingLevel = 0; -} - -} // namespace KJS - -using namespace KJS; - -namespace WebCore { - -JSValue* toJS(ExecState*, DOMWindow* domWindow) -{ - if (!domWindow) - return jsNull(); - Frame* frame = domWindow->frame(); - if (!frame) - return jsNull(); - return Window::retrieve(frame); -} - -} // namespace WebCore diff --git a/WebCore/bindings/js/kjs_window.h b/WebCore/bindings/js/kjs_window.h deleted file mode 100644 index 14887a5..0000000 --- a/WebCore/bindings/js/kjs_window.h +++ /dev/null @@ -1,191 +0,0 @@ -/* - * Copyright (C) 2000 Harri Porten (porten@kde.org) - * Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008 Apple Inc. All rights reseved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#ifndef kjs_window_h -#define kjs_window_h - -#include "PlatformString.h" -#include "kjs_binding.h" -#include <kjs/protect.h> -#include "SecurityOrigin.h" -#include <wtf/HashMap.h> -#include <wtf/Noncopyable.h> -#include <wtf/OwnPtr.h> - -namespace WebCore { - class AtomicString; - class DOMWindow; - class Frame; - class JSEventListener; - class JSLocation; - class JSUnprotectedEventListener; - class PausedTimeouts; - class ScheduledAction; -} - -namespace KJS { - - class DOMWindowTimer; - class WindowPrivate; - - // This is the only WebCore JS binding which does not inherit from DOMObject - class Window : public JSGlobalObject { - typedef JSGlobalObject Base; - - friend class WebCore::ScheduledAction; - protected: - Window(JSObject* prototype, WebCore::DOMWindow*); - - public: - virtual ~Window(); - - WebCore::DOMWindow* impl() const { return m_impl.get(); } - - void disconnectFrame(); - - // Returns and registers a window object. In case there's already a Window - // for the specified frame p this will be returned in order to have unique - // bindings. - static JSValue* retrieve(WebCore::Frame*); - - // Returns the Window object for a given HTML frame - static Window* retrieveWindow(WebCore::Frame*); - - // Returns a pointer to the Window object this javascript interpreting instance - // was called from. - static Window* retrieveActive(ExecState*); - - virtual void mark(); - - virtual bool getOwnPropertySlot(ExecState*, const Identifier&, PropertySlot&); - JSValue* getValueProperty(ExecState*, int token) const; - virtual void put(ExecState*, const Identifier& propertyName, JSValue*, int attr = None); - - int installTimeout(const UString& handler, int t, bool singleShot); - int installTimeout(JSValue* function, const List& args, int t, bool singleShot); - void clearTimeout(int timerId, bool delAction = true); - WebCore::PausedTimeouts* pauseTimeouts(); - void resumeTimeouts(WebCore::PausedTimeouts*); - - void timerFired(DOMWindowTimer*); - - WebCore::JSLocation* location() const; - - // Finds a wrapper of a JS EventListener, returns 0 if no existing one. - WebCore::JSEventListener* findJSEventListener(JSValue*, bool html = false); - - // Finds or creates a wrapper of a JS EventListener. JS EventListener object is GC-protected. - WebCore::JSEventListener *findOrCreateJSEventListener(JSValue*, bool html = false); - - // Finds a wrapper of a GC-unprotected JS EventListener, returns 0 if no existing one. - WebCore::JSUnprotectedEventListener* findJSUnprotectedEventListener(JSValue*, bool html = false); - - // Finds or creates a wrapper of a JS EventListener. JS EventListener object is *NOT* GC-protected. - WebCore::JSUnprotectedEventListener *findOrCreateJSUnprotectedEventListener(JSValue*, bool html = false); - - void clear(); - - void setCurrentEvent(WebCore::Event*); - WebCore::Event* currentEvent(); - - // Set a place to put a dialog return value when the window is cleared. - void setReturnValueSlot(JSValue** slot); - - typedef HashMap<JSObject*, WebCore::JSEventListener*> ListenersMap; - typedef HashMap<JSObject*, WebCore::JSUnprotectedEventListener*> UnprotectedListenersMap; - - ListenersMap& jsEventListeners(); - ListenersMap& jsHTMLEventListeners(); - UnprotectedListenersMap& jsUnprotectedEventListeners(); - UnprotectedListenersMap& jsUnprotectedHTMLEventListeners(); - - virtual const ClassInfo* classInfo() const { return &info; } - static const ClassInfo info; - - virtual ExecState* globalExec(); - - virtual bool shouldInterruptScript() const; - - bool allowsAccessFrom(ExecState*) const; - bool allowsAccessFromNoErrorMessage(ExecState*) const; - bool allowsAccessFrom(ExecState*, WebCore::String& message) const; - - void printErrorMessage(const WebCore::String&) const; - - // Don't call this version of allowsAccessFrom -- it's a slightly incorrect implementation used only by WebScriptObject - virtual bool allowsAccessFrom(const JSGlobalObject*) const; - - enum { - // Attributes - Crypto, Event_, Location_, Navigator_, - ClientInformation, - - // Event Listeners - Onabort, Onblur, Onchange, Onclick, - Ondblclick, Onerror, Onfocus, Onkeydown, - Onkeypress, Onkeyup, Onload, Onmousedown, - Onmousemove, Onmouseout, Onmouseover, Onmouseup, - OnWindowMouseWheel, Onreset, Onresize, Onscroll, - Onsearch, Onselect, Onsubmit, Onunload, - Onbeforeunload, - - // Constructors - DOMException, Audio, Image, Option, XMLHttpRequest, - XSLTProcessor_ - }; - - private: - JSValue* getListener(ExecState*, const WebCore::AtomicString& eventType) const; - void setListener(ExecState*, const WebCore::AtomicString& eventType, JSValue* func); - - static JSValue* childFrameGetter(ExecState*, JSObject*, const Identifier&, const PropertySlot&); - static JSValue* indexGetter(ExecState*, JSObject*, const Identifier&, const PropertySlot&); - static JSValue* namedItemGetter(ExecState*, JSObject*, const Identifier&, const PropertySlot&); - - void clearHelperObjectProperties(); - void clearAllTimeouts(); - int installTimeout(WebCore::ScheduledAction*, int interval, bool singleShot); - - bool allowsAccessFromPrivate(const JSGlobalObject*, WebCore::SecurityOrigin::Reason&) const; - bool allowsAccessFromPrivate(const ExecState*, WebCore::SecurityOrigin::Reason&) const; - WebCore::String crossDomainAccessErrorMessage(const JSGlobalObject*, WebCore::SecurityOrigin::Reason) const; - - RefPtr<WebCore::DOMWindow> m_impl; - OwnPtr<WindowPrivate> d; - }; - - // Functions - JSValue* windowProtoFuncAToB(ExecState*, JSObject*, const List&); - JSValue* windowProtoFuncBToA(ExecState*, JSObject*, const List&); - JSValue* windowProtoFuncOpen(ExecState*, JSObject*, const List&); - JSValue* windowProtoFuncSetTimeout(ExecState*, JSObject*, const List&); - JSValue* windowProtoFuncClearTimeout(ExecState*, JSObject*, const List&); - JSValue* windowProtoFuncSetInterval(ExecState*, JSObject*, const List&); - JSValue* windowProtoFuncAddEventListener(ExecState*, JSObject*, const List&); - JSValue* windowProtoFuncRemoveEventListener(ExecState*, JSObject*, const List&); - JSValue* windowProtoFuncShowModalDialog(ExecState*, JSObject*, const List&); - JSValue* windowProtoFuncNotImplemented(ExecState*, JSObject*, const List&); - -} // namespace KJS - -namespace WebCore { - KJS::JSValue* toJS(KJS::ExecState*, DOMWindow*); -} // namespace WebCore - -#endif // kjs_window_h diff --git a/WebCore/bindings/objc/DOM.mm b/WebCore/bindings/objc/DOM.mm index 93deb23..485d011 100644 --- a/WebCore/bindings/objc/DOM.mm +++ b/WebCore/bindings/objc/DOM.mm @@ -1,5 +1,5 @@ /* - * Copyright (C) 2004, 2005, 2006, 2007 Apple Inc. All rights reserved. + * Copyright (C) 2004, 2005, 2006, 2007, 2008 Apple Inc. All rights reserved. * Copyright (C) 2006 James G. Speth (speth@end.com) * Copyright (C) 2006 Samuel Weinig (sam.weinig@gmail.com) * @@ -28,73 +28,30 @@ #import "config.h" #import "DOM.h" -#import "CDATASection.h" -#import "CSSHelper.h" -#import "CSSStyleSheet.h" -#import "Comment.h" #import "DOMHTMLCanvasElement.h" #import "DOMInternal.h" -#import "DOMPrivate.h" -#import "Document.h" -#import "DocumentFragment.h" -#import "DocumentType.h" -#import "EntityReference.h" -#import "Event.h" -#import "EventListener.h" -#import "EventTarget.h" #import "ExceptionHandlers.h" -#import "FoundationExtras.h" -#import "Frame.h" -#import "FrameView.h" -#import "HTMLDocument.h" #import "HTMLNames.h" #import "HTMLPlugInElement.h" -#import "Image.h" -#import "IntRect.h" -#import "NodeFilter.h" -#import "NodeFilterCondition.h" #import "NodeIterator.h" -#import "NodeList.h" -#import "ProcessingInstruction.h" -#import "QualifiedName.h" #import "Range.h" #import "RenderImage.h" #import "RenderView.h" +#import "ScriptController.h" #import "SimpleFontData.h" -#import "Text.h" #import "TreeWalker.h" -#import "WebScriptObjectPrivate.h" -#import <objc/objc-class.h> + #import <wtf/HashMap.h> #if ENABLE(SVG) -#import "SVGDocument.h" #import "SVGElement.h" +#import "SVGElementInstance.h" #import "SVGNames.h" #import "DOMSVG.h" #endif -namespace WebCore { - -class ObjCEventListener : public EventListener { -public: - static ObjCEventListener* find(id <DOMEventListener>); - static ObjCEventListener* create(id <DOMEventListener>); - -private: - ObjCEventListener(id <DOMEventListener>); - virtual ~ObjCEventListener(); - - virtual void handleEvent(Event*, bool isWindowEvent); - - id <DOMEventListener> m_listener; -}; - -typedef HashMap<id, ObjCEventListener*> ListenerMap; -static ListenerMap* listenerMap; - -} // namespace WebCore - +using namespace JSC; +using namespace WebCore; //------------------------------------------------------------------------------------------ // DOMNode @@ -188,10 +145,12 @@ static void createElementClassMap() #if ENABLE(SVG) addElementClass(SVGNames::aTag, [DOMSVGAElement class]); + addElementClass(SVGNames::altGlyphTag, [DOMSVGAltGlyphElement class]); #if ENABLE(SVG_ANIMATION) addElementClass(SVGNames::animateTag, [DOMSVGAnimateElement class]); addElementClass(SVGNames::animateColorTag, [DOMSVGAnimateColorElement class]); addElementClass(SVGNames::animateTransformTag, [DOMSVGAnimateTransformElement class]); + addElementClass(SVGNames::setTag, [DOMSVGSetElement class]); #endif addElementClass(SVGNames::circleTag, [DOMSVGCircleElement class]); addElementClass(SVGNames::clipPathTag, [DOMSVGClipPathElement class]); @@ -253,7 +212,6 @@ static void createElementClassMap() addElementClass(SVGNames::radialGradientTag, [DOMSVGRadialGradientElement class]); addElementClass(SVGNames::rectTag, [DOMSVGRectElement class]); addElementClass(SVGNames::scriptTag, [DOMSVGScriptElement class]); - addElementClass(SVGNames::setTag, [DOMSVGSetElement class]); addElementClass(SVGNames::stopTag, [DOMSVGStopElement class]); addElementClass(SVGNames::styleTag, [DOMSVGStyleElement class]); addElementClass(SVGNames::svgTag, [DOMSVGSVGElement class]); @@ -400,7 +358,7 @@ static NSArray *kit(const Vector<IntRect>& rects) { if (!eventTarget) return nil; - + // We don't have an ObjC binding for XMLHttpRequest return [DOMNode _wrapNode:eventTarget->toNode()]; } @@ -410,11 +368,11 @@ static NSArray *kit(const Vector<IntRect>& rects) return reinterpret_cast<WebCore::Node*>(_internal); } -- (KJS::Bindings::RootObject*)_rootObject +- (JSC::Bindings::RootObject*)_rootObject { if (WebCore::Node *n = [self _node]) { if (WebCore::Frame* frame = n->document()->frame()) - return frame->bindingRootObject(); + return frame->script()->bindingRootObject(); } return 0; } @@ -450,67 +408,75 @@ static NSArray *kit(const Vector<IntRect>& rects) @end -@implementation DOMRange (DOMRangeExtensions) +#if ENABLE(SVG) +@implementation DOMSVGElementInstance (WebCoreInternal) -- (NSRect)boundingBox +- (id)_initWithSVGElementInstance:(WebCore::SVGElementInstance *)impl { - [self _range]->ownerDocument()->updateLayoutIgnorePendingStylesheets(); - return [self _range]->boundingBox(); + ASSERT(impl); + + [super _init]; + _internal = reinterpret_cast<DOMObjectInternal*>(impl); + impl->ref(); + WebCore::addDOMWrapper(self, impl); + return self; } -- (NSArray *)lineBoxRects ++ (DOMSVGElementInstance *)_wrapSVGElementInstance:(WebCore::SVGElementInstance *)impl { - Vector<WebCore::IntRect> rects; - [self _range]->ownerDocument()->updateLayoutIgnorePendingStylesheets(); - [self _range]->addLineBoxRects(rects); - return kit(rects); + if (!impl) + return nil; + + id cachedInstance; + cachedInstance = WebCore::getDOMWrapper(impl); + if (cachedInstance) + return [[cachedInstance retain] autorelease]; + + return [[[self alloc] _initWithSVGElementInstance:impl] autorelease]; } -@end ++ (id <DOMEventTarget>)_wrapEventTarget:(WebCore::EventTarget *)eventTarget +{ + if (!eventTarget) + return nil; -// FIXME: this should be auto-generated -@implementation DOMNode (DOMEventTarget) + return [DOMSVGElementInstance _wrapSVGElementInstance:eventTarget->toSVGElementInstance()]; +} -- (void)addEventListener:(NSString *)type listener:(id <DOMEventListener>)listener useCapture:(BOOL)useCapture +- (WebCore::SVGElementInstance *)_SVGElementInstance { - if (![self _node]->isEventTargetNode()) - WebCore::raiseDOMException(DOM_NOT_SUPPORTED_ERR); - - WebCore::EventListener *wrapper = WebCore::ObjCEventListener::create(listener); - WebCore::EventTargetNodeCast([self _node])->addEventListener(type, wrapper, useCapture); - wrapper->deref(); + return reinterpret_cast<WebCore::SVGElementInstance*>(_internal); } -- (void)addEventListener:(NSString *)type :(id <DOMEventListener>)listener :(BOOL)useCapture +@end +#endif + +@implementation DOMNode (DOMNodeExtensionsPendingPublic) + +- (NSImage *)renderedImage { - // FIXME: this method can be removed once Mail changes to use the new method <rdar://problem/4746649> - [self addEventListener:type listener:listener useCapture:useCapture]; + if (WebCore::Node *node = [self _node]) + if (WebCore::Frame* frame = node->document()->frame()) + return frame->nodeImage(node); + return nil; } -- (void)removeEventListener:(NSString *)type listener:(id <DOMEventListener>)listener useCapture:(BOOL)useCapture -{ - if (![self _node]->isEventTargetNode()) - WebCore::raiseDOMException(DOM_NOT_SUPPORTED_ERR); +@end - if (WebCore::EventListener *wrapper = WebCore::ObjCEventListener::find(listener)) - WebCore::EventTargetNodeCast([self _node])->removeEventListener(type, wrapper, useCapture); -} +@implementation DOMRange (DOMRangeExtensions) -- (void)removeEventListener:(NSString *)type :(id <DOMEventListener>)listener :(BOOL)useCapture +- (NSRect)boundingBox { - // FIXME: this method can be removed once Mail changes to use the new method <rdar://problem/4746649> - [self removeEventListener:type listener:listener useCapture:useCapture]; + [self _range]->ownerDocument()->updateLayoutIgnorePendingStylesheets(); + return [self _range]->boundingBox(); } -- (BOOL)dispatchEvent:(DOMEvent *)event +- (NSArray *)lineBoxRects { - if (![self _node]->isEventTargetNode()) - WebCore::raiseDOMException(DOM_NOT_SUPPORTED_ERR); - - WebCore::ExceptionCode ec = 0; - BOOL result = WebCore::EventTargetNodeCast([self _node])->dispatchEvent([event _event], ec); - WebCore::raiseOnDOMError(ec); - return result; + Vector<WebCore::IntRect> rects; + [self _range]->ownerDocument()->updateLayoutIgnorePendingStylesheets(); + [self _range]->addLineBoxRects(rects); + return kit(rects); } @end @@ -576,13 +542,13 @@ static NSArray *kit(const Vector<IntRect>& rects) ASSERT(name); WebCore::Element* element = [self _element]; ASSERT(element); - return WebCore::KURL(element->document()->completeURL(parseURL(element->getAttribute(name)).deprecatedString())).getNSURL(); + return element->document()->completeURL(parseURL(element->getAttribute(name))); } // FIXME: this should be implemented in the implementation - (void *)_NPObject { -#if USE(NPOBJECT) +#if ENABLE(NETSCAPE_PLUGIN_API) WebCore::Element* element = [self _element]; if (element->hasTagName(WebCore::HTMLNames::appletTag) || element->hasTagName(WebCore::HTMLNames::embedTag) || element->hasTagName(WebCore::HTMLNames::objectTag)) return static_cast<WebCore::HTMLPlugInElement*>(element)->getNPObject(); @@ -647,12 +613,12 @@ static NSArray *kit(const Vector<IntRect>& rects) { if (!impl) return nil; - + id cachedInstance; cachedInstance = WebCore::getDOMWrapper(impl); if (cachedInstance) return [[cachedInstance retain] autorelease]; - + return [[[self alloc] _initWithNodeFilter:impl] autorelease]; } @@ -681,130 +647,3 @@ static NSArray *kit(const Vector<IntRect>& rects) } @end - - -//------------------------------------------------------------------------------------------ -// ObjCNodeFilterCondition - -class ObjCNodeFilterCondition : public WebCore::NodeFilterCondition { -public: - ObjCNodeFilterCondition(id <DOMNodeFilter>); - virtual ~ObjCNodeFilterCondition(); - virtual short acceptNode(WebCore::Node*) const; - -private: - ObjCNodeFilterCondition(const ObjCNodeFilterCondition&); - ObjCNodeFilterCondition &operator=(const ObjCNodeFilterCondition&); - - id <DOMNodeFilter> m_filter; -}; - -ObjCNodeFilterCondition::ObjCNodeFilterCondition(id <DOMNodeFilter> filter) - : m_filter(filter) -{ - ASSERT(m_filter); - HardRetain(m_filter); -} - -ObjCNodeFilterCondition::~ObjCNodeFilterCondition() -{ - HardRelease(m_filter); -} - -short ObjCNodeFilterCondition::acceptNode(WebCore::Node* node) const -{ - if (!node) - return WebCore::NodeFilter::FILTER_REJECT; - return [m_filter acceptNode:[DOMNode _wrapNode:node]]; -} - - -//------------------------------------------------------------------------------------------ -// DOMDocument (DOMDocumentTraversal) - -// FIXME: this should be auto-generated in DOMDocument.mm -@implementation DOMDocument (DOMDocumentTraversal) - -- (DOMNodeIterator *)createNodeIterator:(DOMNode *)root whatToShow:(unsigned)whatToShow filter:(id <DOMNodeFilter>)filter expandEntityReferences:(BOOL)expandEntityReferences -{ - WebCore::NodeFilter* cppFilter = 0; - if (filter) - cppFilter = new WebCore::NodeFilter(new ObjCNodeFilterCondition(filter)); - WebCore::ExceptionCode ec = 0; - RefPtr<WebCore::NodeIterator> impl = [self _document]->createNodeIterator([root _node], whatToShow, cppFilter, expandEntityReferences, ec); - WebCore::raiseOnDOMError(ec); - return [DOMNodeIterator _wrapNodeIterator:impl.get() filter:filter]; -} - -- (DOMTreeWalker *)createTreeWalker:(DOMNode *)root whatToShow:(unsigned)whatToShow filter:(id <DOMNodeFilter>)filter expandEntityReferences:(BOOL)expandEntityReferences -{ - WebCore::NodeFilter* cppFilter = 0; - if (filter) - cppFilter = new WebCore::NodeFilter(new ObjCNodeFilterCondition(filter)); - WebCore::ExceptionCode ec = 0; - RefPtr<WebCore::TreeWalker> impl = [self _document]->createTreeWalker([root _node], whatToShow, cppFilter, expandEntityReferences, ec); - WebCore::raiseOnDOMError(ec); - return [DOMTreeWalker _wrapTreeWalker:impl.get() filter:filter]; -} - -@end - -@implementation DOMDocument (DOMDocumentTraversalDeprecated) - -- (DOMNodeIterator *)createNodeIterator:(DOMNode *)root :(unsigned)whatToShow :(id <DOMNodeFilter>)filter :(BOOL)expandEntityReferences -{ - return [self createNodeIterator:root whatToShow:whatToShow filter:filter expandEntityReferences:expandEntityReferences]; -} - -- (DOMTreeWalker *)createTreeWalker:(DOMNode *)root :(unsigned)whatToShow :(id <DOMNodeFilter>)filter :(BOOL)expandEntityReferences -{ - return [self createTreeWalker:root whatToShow:whatToShow filter:filter expandEntityReferences:expandEntityReferences]; -} - -@end - - -//------------------------------------------------------------------------------------------ -// ObjCEventListener - -namespace WebCore { - -ObjCEventListener* ObjCEventListener::find(id <DOMEventListener> listener) -{ - if (ListenerMap* map = listenerMap) - return map->get(listener); - return 0; -} - -ObjCEventListener *ObjCEventListener::create(id <DOMEventListener> listener) -{ - ObjCEventListener* wrapper = find(listener); - if (!wrapper) - wrapper = new ObjCEventListener(listener); - wrapper->ref(); - return wrapper; -} - -ObjCEventListener::ObjCEventListener(id <DOMEventListener> listener) - : m_listener([listener retain]) -{ - ListenerMap* map = listenerMap; - if (!map) { - map = new ListenerMap; - listenerMap = map; - } - map->set(listener, this); -} - -ObjCEventListener::~ObjCEventListener() -{ - listenerMap->remove(m_listener); - [m_listener release]; -} - -void ObjCEventListener::handleEvent(Event* event, bool) -{ - [m_listener handleEvent:[DOMEvent _wrapEvent:event]]; -} - -} // namespace WebCore diff --git a/WebCore/bindings/objc/DOMAbstractView.mm b/WebCore/bindings/objc/DOMAbstractView.mm new file mode 100644 index 0000000..c751903 --- /dev/null +++ b/WebCore/bindings/objc/DOMAbstractView.mm @@ -0,0 +1,110 @@ +/* + * Copyright (C) 2008 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of + * its contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#import "config.h" +#import "DOMAbstractView.h" + +#import "DOMDocument.h" +#import "DOMInternal.h" +#import "DOMWindow.h" +#import "Document.h" +#import "ExceptionHandlers.h" +#import "Frame.h" +#import "ThreadCheck.h" +#import <wtf/GetPtr.h> + +#define IMPL reinterpret_cast<WebCore::Frame*>(_internal) + +@implementation DOMAbstractView + +- (void)dealloc +{ + { DOM_ASSERT_MAIN_THREAD(); WebCoreThreadViolationCheck(); } + [super dealloc]; +} + +- (void)finalize +{ + [super finalize]; +} + +- (DOMDocument *)document +{ + if (!_internal) + return nil; + return [DOMDocument _wrapDocument:WTF::getPtr(IMPL->domWindow()->document())]; +} + +@end + +@implementation DOMAbstractView (Frame) + +- (void)_disconnectFrame +{ + ASSERT(_internal); + WebCore::removeDOMWrapper(_internal); + _internal = 0; +} + +@end + +@implementation DOMAbstractView (WebCoreInternal) + +- (WebCore::DOMWindow *)_abstractView +{ + if (!_internal) + return nil; + return IMPL->domWindow(); +} + +- (id)_initWithFrame:(WebCore::Frame *)impl +{ + { DOM_ASSERT_MAIN_THREAD(); WebCoreThreadViolationCheck(); }; + [super _init]; + _internal = reinterpret_cast<DOMObjectInternal*>(impl); + WebCore::addDOMWrapper(self, impl); + return self; +} + ++ (DOMAbstractView *)_wrapAbstractView:(WebCore::DOMWindow *)impl +{ + { DOM_ASSERT_MAIN_THREAD(); WebCoreThreadViolationCheck(); }; + + if (!impl) + return nil; + WebCore::Frame* frame = impl->frame(); + if (!frame) + return nil; + id cachedInstance; + cachedInstance = WebCore::getDOMWrapper(frame); + if (cachedInstance) + return [[cachedInstance retain] autorelease]; + return [[[self alloc] _initWithFrame:frame] autorelease]; +} + +@end diff --git a/WebCore/bindings/objc/DOMAbstractViewFrame.h b/WebCore/bindings/objc/DOMAbstractViewFrame.h new file mode 100644 index 0000000..386a912 --- /dev/null +++ b/WebCore/bindings/objc/DOMAbstractViewFrame.h @@ -0,0 +1,33 @@ +/* + * Copyright (C) 2008 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of + * its contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#import <WebCore/DOMAbstractView.h> + +@interface DOMAbstractView (Frame) +- (void)_disconnectFrame; +@end diff --git a/WebCore/bindings/objc/DOMCSS.h b/WebCore/bindings/objc/DOMCSS.h index 7bae9ed..daaa8a0 100644 --- a/WebCore/bindings/objc/DOMCSS.h +++ b/WebCore/bindings/objc/DOMCSS.h @@ -48,6 +48,8 @@ #import <WebCore/DOMRGBColor.h> #import <WebCore/DOMRect.h> +#if WEBKIT_VERSION_MAX_ALLOWED >= WEBKIT_VERSION_1_3 + @interface DOMCSSStyleDeclaration (DOMCSS2Properties) - (NSString *)azimuth; - (void)setAzimuth:(NSString *)azimuth; @@ -294,3 +296,5 @@ - (NSString *)zIndex; - (void)setZIndex:(NSString *)zIndex; @end + +#endif diff --git a/WebCore/bindings/objc/DOMCSS.mm b/WebCore/bindings/objc/DOMCSS.mm index 83ba748..4e9cd0c 100644 --- a/WebCore/bindings/objc/DOMCSS.mm +++ b/WebCore/bindings/objc/DOMCSS.mm @@ -141,6 +141,15 @@ case DOM_PAGE_RULE: wrapperClass = [DOMCSSPageRule class]; break; + case DOM_VARIABLES_RULE: + wrapperClass = [DOMCSSVariablesRule class]; + break; + case DOM_WEBKIT_KEYFRAMES_RULE: + wrapperClass = [DOMWebKitCSSKeyframesRule class]; + break; + case DOM_WEBKIT_KEYFRAME_RULE: + wrapperClass = [DOMWebKitCSSKeyframeRule class]; + break; } return [[[wrapperClass alloc] _initWithCSSRule:impl] autorelease]; } diff --git a/WebCore/bindings/objc/DOMCustomXPathNSResolver.h b/WebCore/bindings/objc/DOMCustomXPathNSResolver.h index 47cd939..2609e90 100644 --- a/WebCore/bindings/objc/DOMCustomXPathNSResolver.h +++ b/WebCore/bindings/objc/DOMCustomXPathNSResolver.h @@ -31,6 +31,7 @@ #include "XPathNSResolver.h" #include "DOMXPathNSResolver.h" +#include <wtf/PassRefPtr.h> namespace WebCore { @@ -38,13 +39,14 @@ namespace WebCore { class DOMCustomXPathNSResolver : public XPathNSResolver { public: - DOMCustomXPathNSResolver(id <DOMXPathNSResolver>); + static PassRefPtr<DOMCustomXPathNSResolver> create(id <DOMXPathNSResolver> customResolver) { return adoptRef(new DOMCustomXPathNSResolver(customResolver)); } virtual ~DOMCustomXPathNSResolver(); virtual String lookupNamespaceURI(const String& prefix); private: - id <DOMXPathNSResolver> m_customResolver; // DOMCustomXPathNSResolvers are always temporary, thus no need to GC protect the object. + DOMCustomXPathNSResolver(id <DOMXPathNSResolver>); + id <DOMXPathNSResolver> m_customResolver; // DOMCustomXPathNSResolvers are always temporary, thus no need to GC protect the object. }; } // namespace WebCore diff --git a/WebCore/bindings/objc/DOMEventException.h b/WebCore/bindings/objc/DOMEventException.h index 4e805ad..a485955 100644 --- a/WebCore/bindings/objc/DOMEventException.h +++ b/WebCore/bindings/objc/DOMEventException.h @@ -24,6 +24,10 @@ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ +#import <JavaScriptCore/WebKitAvailability.h> + +#if WEBKIT_VERSION_MAX_ALLOWED >= WEBKIT_VERSION_1_3 + @class NSString; extern NSString * const DOMEventException; @@ -31,3 +35,5 @@ extern NSString * const DOMEventException; enum DOMEventExceptionCode { DOM_UNSPECIFIED_EVENT_TYPE_ERR = 0 }; + +#endif diff --git a/WebCore/bindings/objc/DOMEvents.h b/WebCore/bindings/objc/DOMEvents.h index d7248a5..ba3bd3e 100644 --- a/WebCore/bindings/objc/DOMEvents.h +++ b/WebCore/bindings/objc/DOMEvents.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2004, 2006 Apple Computer, Inc. All rights reserved. + * Copyright (C) 2004, 2006, 2008 Apple Computer, Inc. All rights reserved. * Copyright (C) 2006 Samuel Weinig <sam.weinig@gmail.com> * * Redistribution and use in source and binary forms, with or without @@ -39,6 +39,3 @@ #import <WebCore/DOMOverflowEvent.h> #import <WebCore/DOMUIEvent.h> #import <WebCore/DOMWheelEvent.h> - -@interface DOMNode (DOMEventTarget) <DOMEventTarget> -@end diff --git a/WebCore/bindings/objc/DOMEvents.mm b/WebCore/bindings/objc/DOMEvents.mm index 9901049..6f7f72d 100644 --- a/WebCore/bindings/objc/DOMEvents.mm +++ b/WebCore/bindings/objc/DOMEvents.mm @@ -1,5 +1,5 @@ /* - * Copyright (C) 2004 Apple Computer, Inc. All rights reserved. + * Copyright (C) 2004, 2008 Apple Inc. All rights reserved. * Copyright (C) 2006 Jonas Witt <jonas.witt@gmail.com> * Copyright (C) 2006 Samuel Weinig <sam.weinig@gmail.com> * @@ -29,12 +29,16 @@ #import "DOMEvents.h" #import "DOMInternal.h" +#import "DOMMessageEvent.h" #import "DOMPrivate.h" +#import "DOMProgressEvent.h" #import "Event.h" #import "KeyboardEvent.h" +#import "MessageEvent.h" #import "MouseEvent.h" #import "MutationEvent.h" #import "OverflowEvent.h" +#import "ProgressEvent.h" #import "UIEvent.h" #if ENABLE(SVG) @@ -72,26 +76,31 @@ cachedInstance = WebCore::getDOMWrapper(impl); if (cachedInstance) return [[cachedInstance retain] autorelease]; - + Class wrapperClass = nil; - if (impl->isWheelEvent()) - wrapperClass = [DOMWheelEvent class]; - else if (impl->isMouseEvent()) - wrapperClass = [DOMMouseEvent class]; - else if (impl->isMutationEvent()) - wrapperClass = [DOMMutationEvent class]; - else if (impl->isKeyboardEvent()) - wrapperClass = [DOMKeyboardEvent class]; - else if (impl->isTextEvent()) - wrapperClass = [DOMTextEvent class]; + if (impl->isUIEvent()) { + if (impl->isKeyboardEvent()) + wrapperClass = [DOMKeyboardEvent class]; + else if (impl->isTextEvent()) + wrapperClass = [DOMTextEvent class]; + else if (impl->isMouseEvent()) + wrapperClass = [DOMMouseEvent class]; + else if (impl->isWheelEvent()) + wrapperClass = [DOMWheelEvent class]; #if ENABLE(SVG) - else if (impl->isSVGZoomEvent()) - wrapperClass = [DOMSVGZoomEvent class]; + else if (impl->isSVGZoomEvent()) + wrapperClass = [DOMSVGZoomEvent class]; #endif - else if (impl->isUIEvent()) - wrapperClass = [DOMUIEvent class]; + else + wrapperClass = [DOMUIEvent class]; + } else if (impl->isMutationEvent()) + wrapperClass = [DOMMutationEvent class]; else if (impl->isOverflowEvent()) wrapperClass = [DOMOverflowEvent class]; + else if (impl->isMessageEvent()) + wrapperClass = [DOMMessageEvent class]; + else if (impl->isProgressEvent()) + wrapperClass = [DOMProgressEvent class]; else wrapperClass = [DOMEvent class]; diff --git a/WebCore/bindings/objc/DOMException.h b/WebCore/bindings/objc/DOMException.h index 1efdf24..64d7194 100644 --- a/WebCore/bindings/objc/DOMException.h +++ b/WebCore/bindings/objc/DOMException.h @@ -24,12 +24,15 @@ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ +#import <JavaScriptCore/WebKitAvailability.h> + +#if WEBKIT_VERSION_MAX_ALLOWED >= WEBKIT_VERSION_1_3 + @class NSString; extern NSString * const DOMException; -// DOM exception codes -enum { +enum DOMExceptionCode { DOM_INDEX_SIZE_ERR = 1, DOM_DOMSTRING_SIZE_ERR = 2, DOM_HIERARCHY_REQUEST_ERR = 3, @@ -46,3 +49,5 @@ enum { DOM_NAMESPACE_ERR = 14, DOM_INVALID_ACCESS_ERR = 15 }; + +#endif diff --git a/WebCore/bindings/objc/DOMExtensions.h b/WebCore/bindings/objc/DOMExtensions.h index 8188c30..7748a22 100644 --- a/WebCore/bindings/objc/DOMExtensions.h +++ b/WebCore/bindings/objc/DOMExtensions.h @@ -48,15 +48,15 @@ @class NSURL; @interface DOMNode (DOMNodeExtensions) -- (NSRect)boundingBox; -- (NSArray *)lineBoxRects; +- (NSRect)boundingBox WEBKIT_OBJC_METHOD_ANNOTATION(AVAILABLE_WEBKIT_VERSION_3_0_AND_LATER); +- (NSArray *)lineBoxRects WEBKIT_OBJC_METHOD_ANNOTATION(AVAILABLE_WEBKIT_VERSION_3_0_AND_LATER); @end @interface DOMElement (DOMElementAppKitExtensions) -- (NSImage *)image; +- (NSImage *)image WEBKIT_OBJC_METHOD_ANNOTATION(AVAILABLE_WEBKIT_VERSION_3_0_AND_LATER); @end @interface DOMHTMLDocument (DOMHTMLDocumentExtensions) -- (DOMDocumentFragment *)createDocumentFragmentWithMarkupString:(NSString *)markupString baseURL:(NSURL *)baseURL; -- (DOMDocumentFragment *)createDocumentFragmentWithText:(NSString *)text; +- (DOMDocumentFragment *)createDocumentFragmentWithMarkupString:(NSString *)markupString baseURL:(NSURL *)baseURL WEBKIT_OBJC_METHOD_ANNOTATION(AVAILABLE_WEBKIT_VERSION_3_0_AND_LATER); +- (DOMDocumentFragment *)createDocumentFragmentWithText:(NSString *)text WEBKIT_OBJC_METHOD_ANNOTATION(AVAILABLE_WEBKIT_VERSION_3_0_AND_LATER); @end diff --git a/WebCore/bindings/objc/DOMHTML.mm b/WebCore/bindings/objc/DOMHTML.mm index e2fa509..59f2d7f 100644 --- a/WebCore/bindings/objc/DOMHTML.mm +++ b/WebCore/bindings/objc/DOMHTML.mm @@ -36,7 +36,6 @@ #import "HTMLDocument.h" #import "HTMLInputElement.h" #import "HTMLObjectElement.h" -#import "KURL.h" #import "Range.h" #import "RenderTextControl.h" #import "markup.h" @@ -63,7 +62,7 @@ - (DOMDocumentFragment *)_createDocumentFragmentWithMarkupString:(NSString *)markupString baseURLString:(NSString *)baseURLString { - NSURL *baseURL = WebCore::KURL([self _document]->completeURL(WebCore::parseURL(baseURLString)).deprecatedString()).getNSURL(); + NSURL *baseURL = [self _document]->completeURL(WebCore::parseURL(baseURLString)); return [self createDocumentFragmentWithMarkupString:markupString baseURL:baseURL]; } @@ -116,7 +115,7 @@ if (![self _HTMLInputElement]->document()->view()) return result; - NSView* view = [self _HTMLInputElement]->document()->view()->getDocumentView(); + NSView* view = [self _HTMLInputElement]->document()->view()->documentView(); result = [view convertRect:result toView:nil]; result.origin = [[view window] convertBaseToScreen:result.origin]; return result; diff --git a/WebCore/bindings/objc/DOMImplementationFront.cpp b/WebCore/bindings/objc/DOMImplementationFront.cpp index 19a2d76..93db83b 100644 --- a/WebCore/bindings/objc/DOMImplementationFront.cpp +++ b/WebCore/bindings/objc/DOMImplementationFront.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2006 Apple Computer, Inc. + * Copyright (C) 2006, 2008 Apple Inc. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public @@ -64,9 +64,9 @@ PassRefPtr<Document> DOMImplementationFront::createDocument(const String& namesp return reinterpret_cast<DOMImplementation*>(this)->createDocument(namespaceURI, qualifiedName, type, ec); } -DOMImplementationFront* DOMImplementationFront::getInterface(const String& feature) const +DOMImplementationFront* DOMImplementationFront::getInterface(const String& feature) { - return reinterpret_cast<DOMImplementationFront*>(reinterpret_cast<const DOMImplementation*>(this)->getInterface(feature)); + return reinterpret_cast<DOMImplementationFront*>(reinterpret_cast<DOMImplementation*>(this)->getInterface(feature)); } PassRefPtr<CSSStyleSheet> DOMImplementationFront::createCSSStyleSheet(const String& title, const String& media, ExceptionCode& ec) diff --git a/WebCore/bindings/objc/DOMImplementationFront.h b/WebCore/bindings/objc/DOMImplementationFront.h index 14c1037..877a3b6 100644 --- a/WebCore/bindings/objc/DOMImplementationFront.h +++ b/WebCore/bindings/objc/DOMImplementationFront.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2006 Apple Computer, Inc. + * Copyright (C) 2006, 2008 Apple Inc. All rights reserved. * Copyright (C) 2006 Samuel Weinig <sam.weinig@gmail.com> * * This library is free software; you can redistribute it and/or @@ -48,7 +48,7 @@ public: bool hasFeature(const String& feature, const String& version) const; PassRefPtr<DocumentType> createDocumentType(const String& qualifiedName, const String& publicId, const String& systemId, ExceptionCode&); PassRefPtr<Document> createDocument(const String& namespaceURI, const String& qualifiedName, DocumentType*, ExceptionCode&); - DOMImplementationFront* getInterface(const String& feature) const; + DOMImplementationFront* getInterface(const String& feature); PassRefPtr<CSSStyleSheet> createCSSStyleSheet(const String& title, const String& media, ExceptionCode&); PassRefPtr<HTMLDocument> createHTMLDocument(const String& title); }; diff --git a/WebCore/bindings/objc/DOMInternal.h b/WebCore/bindings/objc/DOMInternal.h index 5bd8c77..a1ca9fe 100644 --- a/WebCore/bindings/objc/DOMInternal.h +++ b/WebCore/bindings/objc/DOMInternal.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2004-2006 Apple Computer, Inc. All rights reserved. + * Copyright (C) 2004, 2005, 2006, 2007, 2008 Apple, Inc. All rights reserved. * Copyright (C) 2006 James G. Speth (speth@end.com) * Copyright (C) 2006 Samuel Weinig (sam.weinig@gmail.com) * @@ -27,9 +27,7 @@ #import "DOM.h" -#import "Color.h" #import "DOMObject.h" -#import "DOMRGBColor.h" #import "HitTestResult.h" #if ENABLE(XPATH) @@ -56,6 +54,8 @@ #import "DOMCSSUnknownRuleInternal.h" #import "DOMCSSValueInternal.h" #import "DOMCSSValueListInternal.h" +#import "DOMCSSVariablesRuleInternal.h" +#import "DOMCSSVariablesDeclarationInternal.h" #import "DOMCharacterDataInternal.h" #import "DOMCommentInternal.h" #import "DOMCounterInternal.h" @@ -67,6 +67,8 @@ #import "DOMEntityInternal.h" #import "DOMEntityReferenceInternal.h" #import "DOMEventInternal.h" +#import "DOMFileInternal.h" +#import "DOMFileListInternal.h" #import "DOMHTMLAnchorElementInternal.h" #import "DOMHTMLAppletElementInternal.h" #import "DOMHTMLAreaElementInternal.h" @@ -127,6 +129,7 @@ #import "DOMHTMLUListElementInternal.h" #import "DOMKeyboardEventInternal.h" #import "DOMMediaListInternal.h" +#import "DOMMessagePortInternal.h" #import "DOMMouseEventInternal.h" #import "DOMMutationEventInternal.h" #import "DOMNamedNodeMapInternal.h" @@ -136,18 +139,23 @@ #import "DOMNotationInternal.h" #import "DOMOverflowEventInternal.h" #import "DOMProcessingInstructionInternal.h" +#import "DOMRGBColorInternal.h" #import "DOMRangeInternal.h" #import "DOMRectInternal.h" #import "DOMStyleSheetInternal.h" #import "DOMStyleSheetListInternal.h" -#import "DOMTextInternal.h" #import "DOMTextEventInternal.h" +#import "DOMTextInternal.h" #import "DOMTreeWalkerInternal.h" #import "DOMUIEventInternal.h" +#import "DOMWebKitCSSKeyframeRuleInternal.h" +#import "DOMWebKitCSSKeyframesRuleInternal.h" +#import "DOMWebKitCSSTransformValueInternal.h" #import "DOMWheelEventInternal.h" #if ENABLE(SVG) #import "DOMSVGAElementInternal.h" +#import "DOMSVGAltGlyphElementInternal.h" #import "DOMSVGAngleInternal.h" #import "DOMSVGAnimateColorElementInternal.h" #import "DOMSVGAnimateElementInternal.h" @@ -279,7 +287,7 @@ #import "DOMSVGZoomEventInternal.h" #endif // ENABLE(SVG) -namespace KJS { +namespace JSC { class JSObject; namespace Bindings { @@ -307,13 +315,6 @@ namespace WebCore { - (id)_init; @end -// CSS Internal Interfaces - -@interface DOMRGBColor (WebCoreInternal) -+ (DOMRGBColor *)_wrapRGBColor:(WebCore::RGBA32)value; -- (WebCore::RGBA32)_RGBColor; -@end - // Traversal Internal Interfaces @interface DOMNodeFilter : DOMObject <DOMNodeFilter> @@ -335,7 +336,7 @@ namespace WebCore { namespace WebCore { - id createDOMWrapper(KJS::JSObject*, PassRefPtr<KJS::Bindings::RootObject> origin, PassRefPtr<KJS::Bindings::RootObject> current); + id createDOMWrapper(JSC::JSObject*, PassRefPtr<JSC::Bindings::RootObject> origin, PassRefPtr<JSC::Bindings::RootObject> current); NSObject* getDOMWrapper(DOMObjectInternal*); void addDOMWrapper(NSObject* wrapper, DOMObjectInternal*); diff --git a/WebCore/bindings/objc/DOMInternal.mm b/WebCore/bindings/objc/DOMInternal.mm index afef8c8..f0b6305 100644 --- a/WebCore/bindings/objc/DOMInternal.mm +++ b/WebCore/bindings/objc/DOMInternal.mm @@ -37,7 +37,8 @@ #import "SVGException.h" #import "WebScriptObjectPrivate.h" #import "XPathEvaluator.h" -#import "kjs_proxy.h" +#import "ScriptController.h" +#import "runtime_root.h" //------------------------------------------------------------------------------------------ // Wrapping WebCore implementation objects @@ -113,12 +114,12 @@ void removeDOMWrapper(DOMObjectInternal* impl) if (!frame) return; - KJS::ExecState *exec = frame->scriptProxy()->globalObject()->globalExec(); + JSC::ExecState *exec = frame->script()->globalObject()->globalExec(); // Get (or create) a cached JS object for the DOM node. - KJS::JSObject *scriptImp = static_cast<KJS::JSObject*>(WebCore::toJS(exec, nodeImpl)); + JSC::JSObject *scriptImp = asObject(WebCore::toJS(exec, nodeImpl)); - KJS::Bindings::RootObject* rootObject = frame->bindingRootObject(); + JSC::Bindings::RootObject* rootObject = frame->script()->bindingRootObject(); [self _setImp:scriptImp originRootObject:rootObject rootObject:rootObject]; } diff --git a/WebCore/bindings/objc/DOMObject.h b/WebCore/bindings/objc/DOMObject.h index 22d739e..166637d 100644 --- a/WebCore/bindings/objc/DOMObject.h +++ b/WebCore/bindings/objc/DOMObject.h @@ -27,6 +27,8 @@ #import <WebCore/DOMException.h> #import <WebCore/WebScriptObject.h> +#if WEBKIT_VERSION_MAX_ALLOWED >= WEBKIT_VERSION_1_3 + @class DOMStyleSheet; typedef unsigned long long DOMTimeStamp; @@ -46,3 +48,5 @@ typedef struct DOMObjectInternal DOMObjectInternal; - (DOMStyleSheet *)sheet; #endif @end + +#endif diff --git a/WebCore/bindings/objc/DOMPrivate.h b/WebCore/bindings/objc/DOMPrivate.h index 1322560..0ee5979 100644 --- a/WebCore/bindings/objc/DOMPrivate.h +++ b/WebCore/bindings/objc/DOMPrivate.h @@ -47,8 +47,6 @@ #import <WebCore/DOMHTMLFrameElementPrivate.h> #import <WebCore/DOMHTMLImageElementPrivate.h> #import <WebCore/DOMHTMLInputElementPrivate.h> -#import <WebCore/DOMHTMLLabelElementPrivate.h> -#import <WebCore/DOMHTMLLegendElementPrivate.h> #import <WebCore/DOMHTMLLinkElementPrivate.h> #import <WebCore/DOMHTMLOptionsCollectionPrivate.h> #import <WebCore/DOMHTMLPreElementPrivate.h> @@ -63,6 +61,10 @@ #import <WebCore/DOMUIEventPrivate.h> #import <WebCore/DOMWheelEventPrivate.h> +@interface DOMNode (DOMNodeExtensionsPendingPublic) +- (NSImage *)renderedImage; +@end + // FIXME: this should be removed as soon as all internal Apple uses of it have been replaced with // calls to the public method - (NSColor *)color. @interface DOMRGBColor (WebPrivate) diff --git a/WebCore/bindings/objc/DOMRGBColor.mm b/WebCore/bindings/objc/DOMRGBColor.mm index 8c35a9f..eca2c25 100644 --- a/WebCore/bindings/objc/DOMRGBColor.mm +++ b/WebCore/bindings/objc/DOMRGBColor.mm @@ -76,6 +76,9 @@ void removeWrapperForRGB(WebCore::RGBA32 value) - (void)dealloc { + if (WebCoreObjCScheduleDeallocateOnMainThread([DOMRGBColor class], self)) + return; + WebCore::removeWrapperForRGB(reinterpret_cast<uintptr_t>(_internal)); _internal = 0; [super dealloc]; @@ -91,28 +94,28 @@ void removeWrapperForRGB(WebCore::RGBA32 value) { WebCore::RGBA32 rgb = reinterpret_cast<uintptr_t>(_internal); int value = (rgb >> 16) & 0xFF; - return [DOMCSSPrimitiveValue _wrapCSSPrimitiveValue:new WebCore::CSSPrimitiveValue(value, WebCore::CSSPrimitiveValue::CSS_NUMBER)]; + return [DOMCSSPrimitiveValue _wrapCSSPrimitiveValue:WebCore::CSSPrimitiveValue::create(value, WebCore::CSSPrimitiveValue::CSS_NUMBER).get()]; } - (DOMCSSPrimitiveValue *)green { WebCore::RGBA32 rgb = reinterpret_cast<uintptr_t>(_internal); int value = (rgb >> 8) & 0xFF; - return [DOMCSSPrimitiveValue _wrapCSSPrimitiveValue:new WebCore::CSSPrimitiveValue(value, WebCore::CSSPrimitiveValue::CSS_NUMBER)]; + return [DOMCSSPrimitiveValue _wrapCSSPrimitiveValue:WebCore::CSSPrimitiveValue::create(value, WebCore::CSSPrimitiveValue::CSS_NUMBER).get()]; } - (DOMCSSPrimitiveValue *)blue { WebCore::RGBA32 rgb = reinterpret_cast<uintptr_t>(_internal); int value = rgb & 0xFF; - return [DOMCSSPrimitiveValue _wrapCSSPrimitiveValue:new WebCore::CSSPrimitiveValue(value, WebCore::CSSPrimitiveValue::CSS_NUMBER)]; + return [DOMCSSPrimitiveValue _wrapCSSPrimitiveValue:WebCore::CSSPrimitiveValue::create(value, WebCore::CSSPrimitiveValue::CSS_NUMBER).get()]; } - (DOMCSSPrimitiveValue *)alpha { WebCore::RGBA32 rgb = reinterpret_cast<uintptr_t>(_internal); float value = static_cast<float>(WebCore::Color(rgb).alpha()) / 0xFF; - return [DOMCSSPrimitiveValue _wrapCSSPrimitiveValue:new WebCore::CSSPrimitiveValue(value, WebCore::CSSPrimitiveValue::CSS_NUMBER)]; + return [DOMCSSPrimitiveValue _wrapCSSPrimitiveValue:WebCore::CSSPrimitiveValue::create(value, WebCore::CSSPrimitiveValue::CSS_NUMBER).get()]; } diff --git a/WebCore/bindings/objc/DOMRangeException.h b/WebCore/bindings/objc/DOMRangeException.h index a625d49..874a540 100644 --- a/WebCore/bindings/objc/DOMRangeException.h +++ b/WebCore/bindings/objc/DOMRangeException.h @@ -24,6 +24,10 @@ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ +#import <JavaScriptCore/WebKitAvailability.h> + +#if WEBKIT_VERSION_MAX_ALLOWED >= WEBKIT_VERSION_1_3 + @class NSString; extern NSString * const DOMRangeException; @@ -32,3 +36,5 @@ enum DOMRangeExceptionCode { DOM_BAD_BOUNDARYPOINTS_ERR = 1, DOM_INVALID_NODE_TYPE_ERR = 2 }; + +#endif diff --git a/WebCore/bindings/objc/DOMSVG.h b/WebCore/bindings/objc/DOMSVG.h index 8a7388f..f1321d8 100644 --- a/WebCore/bindings/objc/DOMSVG.h +++ b/WebCore/bindings/objc/DOMSVG.h @@ -25,6 +25,7 @@ */ #import <WebCore/DOMSVGAElement.h> +#import <WebCore/DOMSVGAltGlyphElement.h> #import <WebCore/DOMSVGAngle.h> #import <WebCore/DOMSVGAnimateColorElement.h> #import <WebCore/DOMSVGAnimateElement.h> diff --git a/WebCore/bindings/objc/DOMSVGException.h b/WebCore/bindings/objc/DOMSVGException.h index 1eb121a..b757978 100644 --- a/WebCore/bindings/objc/DOMSVGException.h +++ b/WebCore/bindings/objc/DOMSVGException.h @@ -24,6 +24,10 @@ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ +#import <JavaScriptCore/WebKitAvailability.h> + +#if WEBKIT_VERSION_MAX_ALLOWED >= WEBKIT_VERSION_LATEST + @class NSString; extern NSString * const DOMSVGException; @@ -33,3 +37,5 @@ enum DOMSVGException { DOM_SVG_INVALID_VALUE_ERR = 1, DOM_SVG_MATRIX_NOT_INVERTABLE = 2 }; + +#endif diff --git a/WebCore/bindings/objc/DOMTraversal.h b/WebCore/bindings/objc/DOMTraversal.h index e2d291e..db9dea8 100644 --- a/WebCore/bindings/objc/DOMTraversal.h +++ b/WebCore/bindings/objc/DOMTraversal.h @@ -31,18 +31,3 @@ #import <WebCore/DOMNodeFilter.h> #import <WebCore/DOMNodeIterator.h> #import <WebCore/DOMTreeWalker.h> - -@interface DOMDocument (DOMDocumentTraversal) -- (DOMNodeIterator *)createNodeIterator:(DOMNode *)root whatToShow:(unsigned)whatToShow filter:(id <DOMNodeFilter>)filter expandEntityReferences:(BOOL)expandEntityReferences; -- (DOMTreeWalker *)createTreeWalker:(DOMNode *)root whatToShow:(unsigned)whatToShow filter:(id <DOMNodeFilter>)filter expandEntityReferences:(BOOL)expandEntityReferences; -@end - -@interface DOMDocument (DOMDocumentTraversalDeprecated) -#ifndef BUILDING_ON_TIGER -- (DOMNodeIterator *)createNodeIterator:(DOMNode *)root :(unsigned)whatToShow :(id <DOMNodeFilter>)filter :(BOOL)expandEntityReferences DEPRECATED_IN_MAC_OS_X_VERSION_10_5_AND_LATER; -- (DOMTreeWalker *)createTreeWalker:(DOMNode *)root :(unsigned)whatToShow :(id <DOMNodeFilter>)filter :(BOOL)expandEntityReferences DEPRECATED_IN_MAC_OS_X_VERSION_10_5_AND_LATER; -#else -- (DOMNodeIterator *)createNodeIterator:(DOMNode *)root :(unsigned)whatToShow :(id <DOMNodeFilter>)filter :(BOOL)expandEntityReferences; -- (DOMTreeWalker *)createTreeWalker:(DOMNode *)root :(unsigned)whatToShow :(id <DOMNodeFilter>)filter :(BOOL)expandEntityReferences; -#endif -@end diff --git a/WebCore/bindings/objc/DOMUtility.mm b/WebCore/bindings/objc/DOMUtility.mm index 16204a3..e346c9e 100644 --- a/WebCore/bindings/objc/DOMUtility.mm +++ b/WebCore/bindings/objc/DOMUtility.mm @@ -1,5 +1,5 @@ /* - * Copyright (C) 2004, 2005, 2006, 2007 Apple Inc. All rights reserved. + * Copyright (C) 2004, 2005, 2006, 2007, 2008 Apple Inc. All rights reserved. * Copyright (C) 2006 James G. Speth (speth@end.com) * * Redistribution and use in source and binary forms, with or without @@ -34,6 +34,8 @@ #import "JSCSSValue.h" #import "JSCounter.h" #import "JSDOMImplementation.h" +#import "JSDOMWindow.h" +#import "JSDOMWindowShell.h" #import "JSEvent.h" #import "JSHTMLCollection.h" #import "JSHTMLOptionsCollection.h" @@ -42,6 +44,7 @@ #import "JSNode.h" #import "JSNodeIterator.h" #import "JSNodeList.h" +#import "JSRGBColor.h" #import "JSRange.h" #import "JSRect.h" #import "JSStyleSheet.h" @@ -51,9 +54,7 @@ #import "JSXPathResult.h" #import "Node.h" #import "WebScriptObjectPrivate.h" -#import "kjs_css.h" -#import "kjs_html.h" -#import "kjs_window.h" +#import "runtime_root.h" #import <objc/objc-runtime.h> // This file makes use of both the ObjC DOM API and the C++ DOM API, so we need to be careful about what @@ -66,12 +67,12 @@ // Some day if the compiler is fixed, or if all the JS wrappers are named with a "JS" prefix, // we could move the function into the WebCore namespace where it belongs. -namespace KJS { +namespace JSC { -static inline id createDOMWrapper(KJS::JSObject* object) +static inline id createDOMWrapper(JSC::JSObject* object) { #define WRAP(className) \ - if (object->inherits(&WebCore::JS##className::info)) \ + if (object->inherits(&WebCore::JS##className::s_info)) \ return [DOM##className _wrap##className:static_cast<WebCore::JS##className*>(object)->impl()]; WRAP(CSSRule) @@ -84,14 +85,18 @@ static inline id createDOMWrapper(KJS::JSObject* object) WRAP(MediaList) WRAP(NamedNodeMap) WRAP(Node) + WRAP(NodeIterator) WRAP(NodeList) WRAP(RGBColor) WRAP(Range) WRAP(Rect) WRAP(StyleSheet) WRAP(StyleSheetList) + WRAP(TreeWalker) +#if ENABLE(XPATH) WRAP(XPathExpression) WRAP(XPathResult) +#endif // This must be after the HTMLOptionsCollection check, because it's a subclass in the JavaScript // binding, but not a subclass in the ObjC binding. @@ -99,14 +104,11 @@ static inline id createDOMWrapper(KJS::JSObject* object) #undef WRAP - if (object->inherits(&Window::info)) - return [DOMAbstractView _wrapAbstractView:static_cast<Window*>(object)->impl()]; - if (object->inherits(&WebCore::JSDOMImplementation::info)) + if (object->inherits(&WebCore::JSDOMWindowShell::s_info)) + return [DOMAbstractView _wrapAbstractView:static_cast<WebCore::JSDOMWindowShell*>(object)->impl()]; + + if (object->inherits(&WebCore::JSDOMImplementation::s_info)) return [DOMImplementation _wrapDOMImplementation:implementationFront(static_cast<WebCore::JSDOMImplementation*>(object))]; - if (object->inherits(&WebCore::JSNodeIterator::info)) - return [DOMNodeIterator _wrapNodeIterator:static_cast<WebCore::JSNodeIterator*>(object)->impl() filter:nil]; - if (object->inherits(&WebCore::JSTreeWalker::info)) - return [DOMTreeWalker _wrapTreeWalker:static_cast<WebCore::JSTreeWalker*>(object)->impl() filter:nil]; return nil; } @@ -115,9 +117,9 @@ static inline id createDOMWrapper(KJS::JSObject* object) namespace WebCore { -id createDOMWrapper(KJS::JSObject* object, PassRefPtr<KJS::Bindings::RootObject> origin, PassRefPtr<KJS::Bindings::RootObject> current) +id createDOMWrapper(JSC::JSObject* object, PassRefPtr<JSC::Bindings::RootObject> origin, PassRefPtr<JSC::Bindings::RootObject> current) { - id wrapper = KJS::createDOMWrapper(object); + id wrapper = JSC::createDOMWrapper(object); if (![wrapper _hasImp]) // new wrapper, not from cache [wrapper _setImp:object originRootObject:origin rootObject:current]; return wrapper; diff --git a/WebCore/bindings/objc/DOMXPathException.h b/WebCore/bindings/objc/DOMXPathException.h index 6db8292..32f95fb 100644 --- a/WebCore/bindings/objc/DOMXPathException.h +++ b/WebCore/bindings/objc/DOMXPathException.h @@ -24,6 +24,10 @@ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ +#import <JavaScriptCore/WebKitAvailability.h> + +#if WEBKIT_VERSION_MAX_ALLOWED >= WEBKIT_VERSION_3_0 + @class NSString; extern NSString * const DOMXPathException; @@ -32,3 +36,5 @@ enum DOMXPathExceptionCode { DOM_INVALID_EXPRESSION_ERR = 51, DOM_TYPE_ERR = 52 }; + +#endif diff --git a/WebCore/bindings/objc/ExceptionHandlers.h b/WebCore/bindings/objc/ExceptionHandlers.h index 5f85b9b..911ae2c 100644 --- a/WebCore/bindings/objc/ExceptionHandlers.h +++ b/WebCore/bindings/objc/ExceptionHandlers.h @@ -26,7 +26,7 @@ #ifndef ExceptionHandlers_h #define ExceptionHandlers_h -#include <JavaScriptCore/Assertions.h> +#include <wtf/Assertions.h> #if !defined(NDEBUG) && !defined(DISABLE_THREAD_CHECK) #define DOM_ASSERT_MAIN_THREAD() do \ diff --git a/WebCore/bindings/objc/ObjCEventListener.h b/WebCore/bindings/objc/ObjCEventListener.h new file mode 100644 index 0000000..6056b01 --- /dev/null +++ b/WebCore/bindings/objc/ObjCEventListener.h @@ -0,0 +1,55 @@ +/* + * Copyright (C) 2004, 2006, 2008 Apple Computer, Inc. All rights reserved. + * Copyright (C) 2006 Samuel Weinig <sam.weinig@gmail.com> + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef ObjCEventListener_h +#define ObjCEventListener_h + +#include "EventListener.h" + +#include <wtf/PassRefPtr.h> + +@protocol DOMEventListener; + +namespace WebCore { + + class ObjCEventListener : public EventListener { + public: + static PassRefPtr<ObjCEventListener> wrap(id <DOMEventListener>); + + private: + static ObjCEventListener* find(id <DOMEventListener>); + + ObjCEventListener(id <DOMEventListener>); + virtual ~ObjCEventListener(); + + virtual void handleEvent(Event*, bool isWindowEvent); + + id <DOMEventListener> m_listener; + }; + +} // namespace WebCore + +#endif diff --git a/WebCore/bindings/objc/ObjCEventListener.mm b/WebCore/bindings/objc/ObjCEventListener.mm new file mode 100644 index 0000000..46c04c1 --- /dev/null +++ b/WebCore/bindings/objc/ObjCEventListener.mm @@ -0,0 +1,82 @@ +/* + * Copyright (C) 2004, 2005, 2006, 2007, 2008 Apple Inc. All rights reserved. + * Copyright (C) 2006 James G. Speth (speth@end.com) + * Copyright (C) 2006 Samuel Weinig (sam.weinig@gmail.com) + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#import "config.h" + +#import "ObjCEventListener.h" + +#import "DOMEventInternal.h" +#import "DOMEventListener.h" +#import "Event.h" +#import "EventListener.h" + +#import <objc/objc-class.h> +#import <wtf/HashMap.h> + +namespace WebCore { + +typedef HashMap<id, ObjCEventListener*> ListenerMap; +static ListenerMap* listenerMap; + +ObjCEventListener* ObjCEventListener::find(id <DOMEventListener> listener) +{ + if (ListenerMap* map = listenerMap) + return map->get(listener); + return 0; +} + +PassRefPtr<ObjCEventListener> ObjCEventListener::wrap(id <DOMEventListener> listener) +{ + RefPtr<ObjCEventListener> wrapper = find(listener); + if (wrapper) + return wrapper; + return adoptRef(new ObjCEventListener(listener)); +} + +ObjCEventListener::ObjCEventListener(id <DOMEventListener> listener) + : m_listener([listener retain]) +{ + ListenerMap* map = listenerMap; + if (!map) { + map = new ListenerMap; + listenerMap = map; + } + map->set(listener, this); +} + +ObjCEventListener::~ObjCEventListener() +{ + listenerMap->remove(m_listener); + [m_listener release]; +} + +void ObjCEventListener::handleEvent(Event* event, bool) +{ + [m_listener handleEvent:[DOMEvent _wrapEvent:event]]; +} + +} // namespace WebCore diff --git a/WebCore/bindings/objc/ObjCNodeFilterCondition.h b/WebCore/bindings/objc/ObjCNodeFilterCondition.h new file mode 100644 index 0000000..e136bc4 --- /dev/null +++ b/WebCore/bindings/objc/ObjCNodeFilterCondition.h @@ -0,0 +1,60 @@ +/* + * Copyright (C) 2004, 2006, 2008 Apple Computer, Inc. All rights reserved. + * Copyright (C) 2006 Samuel Weinig <sam.weinig@gmail.com> + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef ObjCNodeFilterCondition_h +#define ObjCNodeFilterCondition_h + +#include "NodeFilterCondition.h" + +#include <wtf/PassRefPtr.h> +#include <wtf/RetainPtr.h> + +@protocol DOMNodeFilter; + +namespace WebCore { + class Node; + + class ObjCNodeFilterCondition : public NodeFilterCondition { + public: + static PassRefPtr<ObjCNodeFilterCondition> create(id <DOMNodeFilter> filter) + { + return adoptRef(new ObjCNodeFilterCondition(filter)); + } + + virtual short acceptNode(JSC::ExecState*, Node*) const; + + private: + ObjCNodeFilterCondition(id <DOMNodeFilter> filter) + : m_filter(filter) + { + } + + RetainPtr<id <DOMNodeFilter> > m_filter; + }; + +} // namespace WebCore + +#endif diff --git a/WebCore/bindings/objc/ObjCNodeFilterCondition.mm b/WebCore/bindings/objc/ObjCNodeFilterCondition.mm new file mode 100644 index 0000000..982cfe0 --- /dev/null +++ b/WebCore/bindings/objc/ObjCNodeFilterCondition.mm @@ -0,0 +1,47 @@ +/* + * Copyright (C) 2004, 2005, 2006, 2007, 2008 Apple Inc. All rights reserved. + * Copyright (C) 2006 James G. Speth (speth@end.com) + * Copyright (C) 2006 Samuel Weinig (sam.weinig@gmail.com) + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#import "config.h" + +#import "ObjCNodeFilterCondition.h" + +#import "DOMNodeFilter.h" +#import "DOMNodeInternal.h" +#import "NodeFilter.h" + +using namespace JSC; + +namespace WebCore { + +short ObjCNodeFilterCondition::acceptNode(ExecState*, Node* node) const +{ + if (!node) + return NodeFilter::FILTER_REJECT; + return [m_filter.get() acceptNode:[DOMNode _wrapNode:node]]; +} + +} // namespace WebCore diff --git a/WebCore/bindings/objc/PublicDOMInterfaces.h b/WebCore/bindings/objc/PublicDOMInterfaces.h index 00591f6..349abaf 100644 --- a/WebCore/bindings/objc/PublicDOMInterfaces.h +++ b/WebCore/bindings/objc/PublicDOMInterfaces.h @@ -30,51 +30,51 @@ #error Do not include this header, instead include the appropriate DOM header. #endif -@interface DOMAttr : DOMNode +@interface DOMAttr : DOMNode WEBKIT_VERSION_1_3 @property(readonly, copy) NSString *name; @property(readonly) BOOL specified; @property(copy) NSString *value; @property(readonly, retain) DOMElement *ownerElement; -@property(readonly, retain) DOMCSSStyleDeclaration *style; +@property(readonly, retain) DOMCSSStyleDeclaration *style AVAILABLE_WEBKIT_VERSION_3_0_AND_LATER; @end -@interface DOMCDATASection : DOMText +@interface DOMCDATASection : DOMText WEBKIT_VERSION_1_3 @end -@interface DOMCharacterData : DOMNode +@interface DOMCharacterData : DOMNode WEBKIT_VERSION_1_3 @property(copy) NSString *data; @property(readonly) unsigned length; - (NSString *)substringData:(unsigned)offset :(unsigned)length; -- (NSString *)substringData:(unsigned)offset length:(unsigned)length; +- (NSString *)substringData:(unsigned)offset length:(unsigned)length AVAILABLE_WEBKIT_VERSION_3_0_AND_LATER; - (void)appendData:(NSString *)data; - (void)insertData:(unsigned)offset :(NSString *)data; - (void)deleteData:(unsigned)offset :(unsigned)length; - (void)replaceData:(unsigned)offset :(unsigned)length :(NSString *)data; -- (void)insertData:(unsigned)offset data:(NSString *)data; -- (void)deleteData:(unsigned)offset length:(unsigned)length; -- (void)replaceData:(unsigned)offset length:(unsigned)length data:(NSString *)data; +- (void)insertData:(unsigned)offset data:(NSString *)data AVAILABLE_WEBKIT_VERSION_3_0_AND_LATER; +- (void)deleteData:(unsigned)offset length:(unsigned)length AVAILABLE_WEBKIT_VERSION_3_0_AND_LATER; +- (void)replaceData:(unsigned)offset length:(unsigned)length data:(NSString *)data AVAILABLE_WEBKIT_VERSION_3_0_AND_LATER; @end -@interface DOMComment : DOMCharacterData +@interface DOMComment : DOMCharacterData WEBKIT_VERSION_1_3 @end -@interface DOMImplementation : DOMObject +@interface DOMImplementation : DOMObject WEBKIT_VERSION_1_3 - (BOOL)hasFeature:(NSString *)feature :(NSString *)version; - (DOMDocumentType *)createDocumentType:(NSString *)qualifiedName :(NSString *)publicId :(NSString *)systemId; - (DOMDocument *)createDocument:(NSString *)namespaceURI :(NSString *)qualifiedName :(DOMDocumentType *)doctype; - (DOMCSSStyleSheet *)createCSSStyleSheet:(NSString *)title :(NSString *)media; -- (BOOL)hasFeature:(NSString *)feature version:(NSString *)version; -- (DOMDocumentType *)createDocumentType:(NSString *)qualifiedName publicId:(NSString *)publicId systemId:(NSString *)systemId; -- (DOMDocument *)createDocument:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName doctype:(DOMDocumentType *)doctype; -- (DOMCSSStyleSheet *)createCSSStyleSheet:(NSString *)title media:(NSString *)media; -- (DOMHTMLDocument *)createHTMLDocument:(NSString *)title; +- (BOOL)hasFeature:(NSString *)feature version:(NSString *)version AVAILABLE_WEBKIT_VERSION_3_0_AND_LATER; +- (DOMDocumentType *)createDocumentType:(NSString *)qualifiedName publicId:(NSString *)publicId systemId:(NSString *)systemId AVAILABLE_WEBKIT_VERSION_3_0_AND_LATER; +- (DOMDocument *)createDocument:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName doctype:(DOMDocumentType *)doctype AVAILABLE_WEBKIT_VERSION_3_0_AND_LATER; +- (DOMCSSStyleSheet *)createCSSStyleSheet:(NSString *)title media:(NSString *)media AVAILABLE_WEBKIT_VERSION_3_0_AND_LATER; +- (DOMHTMLDocument *)createHTMLDocument:(NSString *)title AVAILABLE_WEBKIT_VERSION_3_0_AND_LATER; @end -@interface DOMAbstractView : DOMObject +@interface DOMAbstractView : DOMObject WEBKIT_VERSION_1_3 @property(readonly, retain) DOMDocument *document; @end -@interface DOMDocument : DOMNode +@interface DOMDocument : DOMNode WEBKIT_VERSION_1_3 @property(readonly, retain) DOMDocumentType *doctype; @property(readonly, retain) DOMImplementation *implementation; @property(readonly, retain) DOMElement *documentElement; @@ -97,7 +97,7 @@ - (DOMComment *)createComment:(NSString *)data; - (DOMCDATASection *)createCDATASection:(NSString *)data; - (DOMProcessingInstruction *)createProcessingInstruction:(NSString *)target :(NSString *)data; -- (DOMProcessingInstruction *)createProcessingInstruction:(NSString *)target data:(NSString *)data; +- (DOMProcessingInstruction *)createProcessingInstruction:(NSString *)target data:(NSString *)data AVAILABLE_WEBKIT_VERSION_3_0_AND_LATER; - (DOMAttr *)createAttribute:(NSString *)name; - (DOMEntityReference *)createEntityReference:(NSString *)name; - (DOMNodeList *)getElementsByTagName:(NSString *)tagname; @@ -105,35 +105,39 @@ - (DOMElement *)createElementNS:(NSString *)namespaceURI :(NSString *)qualifiedName; - (DOMAttr *)createAttributeNS:(NSString *)namespaceURI :(NSString *)qualifiedName; - (DOMNodeList *)getElementsByTagNameNS:(NSString *)namespaceURI :(NSString *)localName; -- (DOMNode *)importNode:(DOMNode *)importedNode deep:(BOOL)deep; -- (DOMNode *)adoptNode:(DOMNode *)source; -- (DOMElement *)createElementNS:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName; -- (DOMAttr *)createAttributeNS:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName; -- (DOMNodeList *)getElementsByTagNameNS:(NSString *)namespaceURI localName:(NSString *)localName; +- (DOMNode *)importNode:(DOMNode *)importedNode deep:(BOOL)deep AVAILABLE_WEBKIT_VERSION_3_0_AND_LATER; +- (DOMNode *)adoptNode:(DOMNode *)source AVAILABLE_WEBKIT_VERSION_3_0_AND_LATER; +- (DOMElement *)createElementNS:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName AVAILABLE_WEBKIT_VERSION_3_0_AND_LATER; +- (DOMAttr *)createAttributeNS:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName AVAILABLE_WEBKIT_VERSION_3_0_AND_LATER; +- (DOMNodeList *)getElementsByTagNameNS:(NSString *)namespaceURI localName:(NSString *)localName AVAILABLE_WEBKIT_VERSION_3_0_AND_LATER; - (DOMElement *)getElementById:(NSString *)elementId; - (DOMEvent *)createEvent:(NSString *)eventType; - (DOMRange *)createRange; -- (DOMCSSStyleDeclaration *)createCSSStyleDeclaration; +- (DOMCSSStyleDeclaration *)createCSSStyleDeclaration AVAILABLE_WEBKIT_VERSION_3_0_AND_LATER; - (DOMCSSStyleDeclaration *)getOverrideStyle:(DOMElement *)element :(NSString *)pseudoElement; -- (DOMCSSStyleDeclaration *)getOverrideStyle:(DOMElement *)element pseudoElement:(NSString *)pseudoElement; +- (DOMCSSStyleDeclaration *)getOverrideStyle:(DOMElement *)element pseudoElement:(NSString *)pseudoElement AVAILABLE_WEBKIT_VERSION_3_0_AND_LATER; - (DOMCSSStyleDeclaration *)getComputedStyle:(DOMElement *)element :(NSString *)pseudoElement; -- (DOMCSSStyleDeclaration *)getComputedStyle:(DOMElement *)element pseudoElement:(NSString *)pseudoElement; -- (DOMCSSRuleList *)getMatchedCSSRules:(DOMElement *)element pseudoElement:(NSString *)pseudoElement; -- (DOMCSSRuleList *)getMatchedCSSRules:(DOMElement *)element pseudoElement:(NSString *)pseudoElement authorOnly:(BOOL)authorOnly; +- (DOMCSSStyleDeclaration *)getComputedStyle:(DOMElement *)element pseudoElement:(NSString *)pseudoElement AVAILABLE_WEBKIT_VERSION_3_0_AND_LATER; +- (DOMCSSRuleList *)getMatchedCSSRules:(DOMElement *)element pseudoElement:(NSString *)pseudoElement AVAILABLE_WEBKIT_VERSION_3_0_AND_LATER; +- (DOMCSSRuleList *)getMatchedCSSRules:(DOMElement *)element pseudoElement:(NSString *)pseudoElement authorOnly:(BOOL)authorOnly AVAILABLE_WEBKIT_VERSION_3_0_AND_LATER; - (DOMNodeList *)getElementsByName:(NSString *)elementName; -#ifdef ENABLE_XPATH -- (DOMXPathExpression *)createExpression:(NSString *)expression :(id <DOMXPathNSResolver>)resolver; -- (DOMXPathExpression *)createExpression:(NSString *)expression resolver:(id <DOMXPathNSResolver>)resolver; -- (id <DOMXPathNSResolver>)createNSResolver:(DOMNode *)nodeResolver; -- (DOMXPathResult *)evaluate:(NSString *)expression :(DOMNode *)contextNode :(id <DOMXPathNSResolver>)resolver :(unsigned short)type :(DOMXPathResult *)inResult; -- (DOMXPathResult *)evaluate:(NSString *)expression contextNode:(DOMNode *)contextNode resolver:(id <DOMXPathNSResolver>)resolver type:(unsigned short)type inResult:(DOMXPathResult *)inResult; +- (DOMNodeIterator *)createNodeIterator:(DOMNode *)root whatToShow:(unsigned)whatToShow filter:(id <DOMNodeFilter>)filter expandEntityReferences:(BOOL)expandEntityReferences AVAILABLE_WEBKIT_VERSION_3_0_AND_LATER; +- (DOMTreeWalker *)createTreeWalker:(DOMNode *)root whatToShow:(unsigned)whatToShow filter:(id <DOMNodeFilter>)filter expandEntityReferences:(BOOL)expandEntityReferences AVAILABLE_WEBKIT_VERSION_3_0_AND_LATER; +- (DOMNodeIterator *)createNodeIterator:(DOMNode *)root :(unsigned)whatToShow :(id <DOMNodeFilter>)filter :(BOOL)expandEntityReferences; +- (DOMTreeWalker *)createTreeWalker:(DOMNode *)root :(unsigned)whatToShow :(id <DOMNodeFilter>)filter :(BOOL)expandEntityReferences; +#if ENABLE_XPATH +- (DOMXPathExpression *)createExpression:(NSString *)expression :(id <DOMXPathNSResolver>)resolver AVAILABLE_WEBKIT_VERSION_3_0_AND_LATER_BUT_DEPRECATED; +- (DOMXPathExpression *)createExpression:(NSString *)expression resolver:(id <DOMXPathNSResolver>)resolver AVAILABLE_WEBKIT_VERSION_3_0_AND_LATER; +- (id <DOMXPathNSResolver>)createNSResolver:(DOMNode *)nodeResolver AVAILABLE_WEBKIT_VERSION_3_0_AND_LATER; +- (DOMXPathResult *)evaluate:(NSString *)expression :(DOMNode *)contextNode :(id <DOMXPathNSResolver>)resolver :(unsigned short)type :(DOMXPathResult *)inResult AVAILABLE_WEBKIT_VERSION_3_0_AND_LATER_BUT_DEPRECATED; +- (DOMXPathResult *)evaluate:(NSString *)expression contextNode:(DOMNode *)contextNode resolver:(id <DOMXPathNSResolver>)resolver type:(unsigned short)type inResult:(DOMXPathResult *)inResult AVAILABLE_WEBKIT_VERSION_3_0_AND_LATER; #endif @end -@interface DOMDocumentFragment : DOMNode +@interface DOMDocumentFragment : DOMNode WEBKIT_VERSION_1_3 @end -@interface DOMDocumentType : DOMNode +@interface DOMDocumentType : DOMNode WEBKIT_VERSION_1_3 @property(readonly, copy) NSString *name; @property(readonly, retain) DOMNamedNodeMap *entities; @property(readonly, retain) DOMNamedNodeMap *notations; @@ -142,7 +146,7 @@ @property(readonly, copy) NSString *internalSubset; @end -@interface DOMElement : DOMNode +@interface DOMElement : DOMNode WEBKIT_VERSION_1_3 @property(readonly, copy) NSString *tagName; @property(readonly, retain) DOMCSSStyleDeclaration *style; @property(readonly) int offsetLeft; @@ -158,7 +162,7 @@ @property(readonly) int scrollHeight; - (NSString *)getAttribute:(NSString *)name; - (void)setAttribute:(NSString *)name :(NSString *)value; -- (void)setAttribute:(NSString *)name value:(NSString *)value; +- (void)setAttribute:(NSString *)name value:(NSString *)value AVAILABLE_WEBKIT_VERSION_3_0_AND_LATER; - (void)removeAttribute:(NSString *)name; - (DOMAttr *)getAttributeNode:(NSString *)name; - (DOMAttr *)setAttributeNode:(DOMAttr *)newAttr; @@ -169,44 +173,42 @@ - (void)removeAttributeNS:(NSString *)namespaceURI :(NSString *)localName; - (DOMNodeList *)getElementsByTagNameNS:(NSString *)namespaceURI :(NSString *)localName; - (DOMAttr *)getAttributeNodeNS:(NSString *)namespaceURI :(NSString *)localName; -- (NSString *)getAttributeNS:(NSString *)namespaceURI localName:(NSString *)localName; -- (void)setAttributeNS:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName value:(NSString *)value; -- (void)removeAttributeNS:(NSString *)namespaceURI localName:(NSString *)localName; -- (DOMNodeList *)getElementsByTagNameNS:(NSString *)namespaceURI localName:(NSString *)localName; -- (DOMAttr *)getAttributeNodeNS:(NSString *)namespaceURI localName:(NSString *)localName; +- (NSString *)getAttributeNS:(NSString *)namespaceURI localName:(NSString *)localName AVAILABLE_WEBKIT_VERSION_3_0_AND_LATER; +- (void)setAttributeNS:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName value:(NSString *)value AVAILABLE_WEBKIT_VERSION_3_0_AND_LATER; +- (void)removeAttributeNS:(NSString *)namespaceURI localName:(NSString *)localName AVAILABLE_WEBKIT_VERSION_3_0_AND_LATER; +- (DOMNodeList *)getElementsByTagNameNS:(NSString *)namespaceURI localName:(NSString *)localName AVAILABLE_WEBKIT_VERSION_3_0_AND_LATER; +- (DOMAttr *)getAttributeNodeNS:(NSString *)namespaceURI localName:(NSString *)localName AVAILABLE_WEBKIT_VERSION_3_0_AND_LATER; - (DOMAttr *)setAttributeNodeNS:(DOMAttr *)newAttr; - (BOOL)hasAttribute:(NSString *)name; - (BOOL)hasAttributeNS:(NSString *)namespaceURI :(NSString *)localName; -- (BOOL)hasAttributeNS:(NSString *)namespaceURI localName:(NSString *)localName; -- (void)focus; -- (void)blur; -- (void)scrollIntoView:(BOOL)alignWithTop; -- (void)scrollIntoViewIfNeeded:(BOOL)centerIfNeeded; +- (BOOL)hasAttributeNS:(NSString *)namespaceURI localName:(NSString *)localName AVAILABLE_WEBKIT_VERSION_3_0_AND_LATER; +- (void)scrollIntoView:(BOOL)alignWithTop AVAILABLE_WEBKIT_VERSION_3_0_AND_LATER; +- (void)scrollIntoViewIfNeeded:(BOOL)centerIfNeeded AVAILABLE_WEBKIT_VERSION_3_0_AND_LATER; @end -@interface DOMEntity : DOMNode +@interface DOMEntity : DOMNode WEBKIT_VERSION_1_3 @property(readonly, copy) NSString *publicId; @property(readonly, copy) NSString *systemId; @property(readonly, copy) NSString *notationName; @end -@interface DOMEntityReference : DOMNode +@interface DOMEntityReference : DOMNode WEBKIT_VERSION_1_3 @end -@interface DOMNamedNodeMap : DOMObject +@interface DOMNamedNodeMap : DOMObject WEBKIT_VERSION_1_3 @property(readonly) unsigned length; - (DOMNode *)getNamedItem:(NSString *)name; - (DOMNode *)setNamedItem:(DOMNode *)node; - (DOMNode *)removeNamedItem:(NSString *)name; - (DOMNode *)item:(unsigned)index; - (DOMNode *)getNamedItemNS:(NSString *)namespaceURI :(NSString *)localName; -- (DOMNode *)getNamedItemNS:(NSString *)namespaceURI localName:(NSString *)localName; +- (DOMNode *)getNamedItemNS:(NSString *)namespaceURI localName:(NSString *)localName AVAILABLE_WEBKIT_VERSION_3_0_AND_LATER; - (DOMNode *)setNamedItemNS:(DOMNode *)node; - (DOMNode *)removeNamedItemNS:(NSString *)namespaceURI :(NSString *)localName; -- (DOMNode *)removeNamedItemNS:(NSString *)namespaceURI localName:(NSString *)localName; +- (DOMNode *)removeNamedItemNS:(NSString *)namespaceURI localName:(NSString *)localName AVAILABLE_WEBKIT_VERSION_3_0_AND_LATER; @end -@interface DOMNode : DOMObject +@interface DOMNode : DOMObject WEBKIT_VERSION_1_3 @property(readonly, copy) NSString *nodeName; @property(copy) NSString *nodeValue; @property(readonly) unsigned short nodeType; @@ -221,43 +223,43 @@ @property(readonly, copy) NSString *namespaceURI; @property(copy) NSString *prefix; @property(readonly, copy) NSString *localName; -@property(copy) NSString *textContent; +@property(copy) NSString *textContent AVAILABLE_WEBKIT_VERSION_3_0_AND_LATER; - (DOMNode *)insertBefore:(DOMNode *)newChild :(DOMNode *)refChild; -- (DOMNode *)insertBefore:(DOMNode *)newChild refChild:(DOMNode *)refChild; +- (DOMNode *)insertBefore:(DOMNode *)newChild refChild:(DOMNode *)refChild AVAILABLE_WEBKIT_VERSION_3_0_AND_LATER; - (DOMNode *)replaceChild:(DOMNode *)newChild :(DOMNode *)oldChild; -- (DOMNode *)replaceChild:(DOMNode *)newChild oldChild:(DOMNode *)oldChild; +- (DOMNode *)replaceChild:(DOMNode *)newChild oldChild:(DOMNode *)oldChild AVAILABLE_WEBKIT_VERSION_3_0_AND_LATER; - (DOMNode *)removeChild:(DOMNode *)oldChild; - (DOMNode *)appendChild:(DOMNode *)newChild; - (BOOL)hasChildNodes; - (DOMNode *)cloneNode:(BOOL)deep; - (void)normalize; - (BOOL)isSupported:(NSString *)feature :(NSString *)version; -- (BOOL)isSupported:(NSString *)feature version:(NSString *)version; +- (BOOL)isSupported:(NSString *)feature version:(NSString *)version AVAILABLE_WEBKIT_VERSION_3_0_AND_LATER; - (BOOL)hasAttributes; -- (BOOL)isSameNode:(DOMNode *)other; -- (BOOL)isEqualNode:(DOMNode *)other; +- (BOOL)isSameNode:(DOMNode *)other AVAILABLE_WEBKIT_VERSION_3_0_AND_LATER; +- (BOOL)isEqualNode:(DOMNode *)other AVAILABLE_WEBKIT_VERSION_3_0_AND_LATER; @end -@interface DOMNodeList : DOMObject +@interface DOMNodeList : DOMObject WEBKIT_VERSION_1_3 @property(readonly) unsigned length; - (DOMNode *)item:(unsigned)index; @end -@interface DOMNotation : DOMNode +@interface DOMNotation : DOMNode WEBKIT_VERSION_1_3 @property(readonly, copy) NSString *publicId; @property(readonly, copy) NSString *systemId; @end -@interface DOMProcessingInstruction : DOMNode +@interface DOMProcessingInstruction : DOMNode WEBKIT_VERSION_1_3 @property(readonly, copy) NSString *target; @property(copy) NSString *data; @end -@interface DOMText : DOMCharacterData +@interface DOMText : DOMCharacterData WEBKIT_VERSION_1_3 - (DOMText *)splitText:(unsigned)offset; @end -@interface DOMHTMLAnchorElement : DOMHTMLElement +@interface DOMHTMLAnchorElement : DOMHTMLElement WEBKIT_VERSION_1_3 @property(copy) NSString *accessKey; @property(copy) NSString *charset; @property(copy) NSString *coords; @@ -267,15 +269,12 @@ @property(copy) NSString *rel; @property(copy) NSString *rev; @property(copy) NSString *shape; -@property int tabIndex; @property(copy) NSString *target; @property(copy) NSString *type; -@property(readonly, copy) NSURL *absoluteLinkURL; -- (void)blur; -- (void)focus; +@property(readonly, copy) NSURL *absoluteLinkURL AVAILABLE_WEBKIT_VERSION_3_0_AND_LATER; @end -@interface DOMHTMLAppletElement : DOMHTMLElement +@interface DOMHTMLAppletElement : DOMHTMLElement WEBKIT_VERSION_1_3 @property(copy) NSString *align; @property(copy) NSString *alt; @property(copy) NSString *archive; @@ -289,34 +288,33 @@ @property(copy) NSString *width; @end -@interface DOMHTMLAreaElement : DOMHTMLElement +@interface DOMHTMLAreaElement : DOMHTMLElement WEBKIT_VERSION_1_3 @property(copy) NSString *accessKey; @property(copy) NSString *alt; @property(copy) NSString *coords; @property(copy) NSString *href; @property BOOL noHref; @property(copy) NSString *shape; -@property int tabIndex; @property(copy) NSString *target; -@property(readonly, copy) NSURL *absoluteLinkURL; +@property(readonly, copy) NSURL *absoluteLinkURL AVAILABLE_WEBKIT_VERSION_3_0_AND_LATER; @end -@interface DOMHTMLBRElement : DOMHTMLElement +@interface DOMHTMLBRElement : DOMHTMLElement WEBKIT_VERSION_1_3 @property(copy) NSString *clear; @end -@interface DOMHTMLBaseElement : DOMHTMLElement +@interface DOMHTMLBaseElement : DOMHTMLElement WEBKIT_VERSION_1_3 @property(copy) NSString *href; @property(copy) NSString *target; @end -@interface DOMHTMLBaseFontElement : DOMHTMLElement +@interface DOMHTMLBaseFontElement : DOMHTMLElement WEBKIT_VERSION_1_3 @property(copy) NSString *color; @property(copy) NSString *face; @property(copy) NSString *size; @end -@interface DOMHTMLBodyElement : DOMHTMLElement +@interface DOMHTMLBodyElement : DOMHTMLElement WEBKIT_VERSION_1_3 @property(copy) NSString *aLink; @property(copy) NSString *background; @property(copy) NSString *bgColor; @@ -325,47 +323,46 @@ @property(copy) NSString *vLink; @end -@interface DOMHTMLButtonElement : DOMHTMLElement +@interface DOMHTMLButtonElement : DOMHTMLElement WEBKIT_VERSION_1_3 @property(readonly, retain) DOMHTMLFormElement *form; @property(copy) NSString *accessKey; @property BOOL disabled; @property(copy) NSString *name; -@property int tabIndex; @property(readonly, copy) NSString *type; @property(copy) NSString *value; @end -@interface DOMHTMLCanvasElement : DOMHTMLElement +@interface DOMHTMLCanvasElement : DOMHTMLElement WEBKIT_VERSION_3_0 @property int height; @property int width; @end -@interface DOMHTMLCollection : DOMObject +@interface DOMHTMLCollection : DOMObject WEBKIT_VERSION_1_3 @property(readonly) unsigned length; - (DOMNode *)item:(unsigned)index; - (DOMNode *)namedItem:(NSString *)name; @end -@interface DOMHTMLDListElement : DOMHTMLElement +@interface DOMHTMLDListElement : DOMHTMLElement WEBKIT_VERSION_1_3 @property BOOL compact; @end -@interface DOMHTMLDirectoryElement : DOMHTMLElement +@interface DOMHTMLDirectoryElement : DOMHTMLElement WEBKIT_VERSION_1_3 @property BOOL compact; @end -@interface DOMHTMLDivElement : DOMHTMLElement +@interface DOMHTMLDivElement : DOMHTMLElement WEBKIT_VERSION_1_3 @property(copy) NSString *align; @end -@interface DOMHTMLDocument : DOMDocument +@interface DOMHTMLDocument : DOMDocument WEBKIT_VERSION_1_3 - (void)open; - (void)close; - (void)write:(NSString *)text; - (void)writeln:(NSString *)text; @end -@interface DOMHTMLElement : DOMElement +@interface DOMHTMLElement : DOMElement WEBKIT_VERSION_1_3 @property(copy) NSString *title; @property(copy) NSString *idName; @property(copy) NSString *lang; @@ -378,10 +375,13 @@ @property(readonly, retain) DOMHTMLCollection *children; @property(copy) NSString *contentEditable; @property(readonly) BOOL isContentEditable; -@property(readonly, copy) NSString *titleDisplayString; +@property(readonly, copy) NSString *titleDisplayString AVAILABLE_WEBKIT_VERSION_3_0_AND_LATER; +@property int tabIndex; +- (void)blur; +- (void)focus; @end -@interface DOMHTMLEmbedElement : DOMHTMLElement +@interface DOMHTMLEmbedElement : DOMHTMLElement WEBKIT_VERSION_1_3 @property(copy) NSString *align; @property int height; @property(copy) NSString *name; @@ -390,17 +390,17 @@ @property int width; @end -@interface DOMHTMLFieldSetElement : DOMHTMLElement +@interface DOMHTMLFieldSetElement : DOMHTMLElement WEBKIT_VERSION_1_3 @property(readonly, retain) DOMHTMLFormElement *form; @end -@interface DOMHTMLFontElement : DOMHTMLElement +@interface DOMHTMLFontElement : DOMHTMLElement WEBKIT_VERSION_1_3 @property(copy) NSString *color; @property(copy) NSString *face; @property(copy) NSString *size; @end -@interface DOMHTMLFormElement : DOMHTMLElement +@interface DOMHTMLFormElement : DOMHTMLElement WEBKIT_VERSION_1_3 @property(readonly, retain) DOMHTMLCollection *elements; @property(readonly) int length; @property(copy) NSString *name; @@ -413,7 +413,7 @@ - (void)reset; @end -@interface DOMHTMLFrameElement : DOMHTMLElement +@interface DOMHTMLFrameElement : DOMHTMLElement WEBKIT_VERSION_1_3 @property(copy) NSString *frameBorder; @property(copy) NSString *longDesc; @property(copy) NSString *marginHeight; @@ -425,31 +425,31 @@ @property(readonly, retain) DOMDocument *contentDocument; @end -@interface DOMHTMLFrameSetElement : DOMHTMLElement +@interface DOMHTMLFrameSetElement : DOMHTMLElement WEBKIT_VERSION_1_3 @property(copy) NSString *cols; @property(copy) NSString *rows; @end -@interface DOMHTMLHRElement : DOMHTMLElement +@interface DOMHTMLHRElement : DOMHTMLElement WEBKIT_VERSION_1_3 @property(copy) NSString *align; @property BOOL noShade; @property(copy) NSString *size; @property(copy) NSString *width; @end -@interface DOMHTMLHeadElement : DOMHTMLElement +@interface DOMHTMLHeadElement : DOMHTMLElement WEBKIT_VERSION_1_3 @property(copy) NSString *profile; @end -@interface DOMHTMLHeadingElement : DOMHTMLElement +@interface DOMHTMLHeadingElement : DOMHTMLElement WEBKIT_VERSION_1_3 @property(copy) NSString *align; @end -@interface DOMHTMLHtmlElement : DOMHTMLElement +@interface DOMHTMLHtmlElement : DOMHTMLElement WEBKIT_VERSION_1_3 @property(copy) NSString *version; @end -@interface DOMHTMLIFrameElement : DOMHTMLElement +@interface DOMHTMLIFrameElement : DOMHTMLElement WEBKIT_VERSION_1_3 @property(copy) NSString *align; @property(copy) NSString *frameBorder; @property(copy) NSString *height; @@ -463,7 +463,7 @@ @property(readonly, retain) DOMDocument *contentDocument; @end -@interface DOMHTMLImageElement : DOMHTMLElement +@interface DOMHTMLImageElement : DOMHTMLElement WEBKIT_VERSION_1_3 @property(copy) NSString *name; @property(copy) NSString *align; @property(copy) NSString *alt; @@ -476,11 +476,11 @@ @property(copy) NSString *useMap; @property int vspace; @property int width; -@property(readonly, copy) NSString *altDisplayString; -@property(readonly, copy) NSURL *absoluteImageURL; +@property(readonly, copy) NSString *altDisplayString AVAILABLE_WEBKIT_VERSION_3_0_AND_LATER; +@property(readonly, copy) NSURL *absoluteImageURL AVAILABLE_WEBKIT_VERSION_3_0_AND_LATER; @end -@interface DOMHTMLInputElement : DOMHTMLElement +@interface DOMHTMLInputElement : DOMHTMLElement WEBKIT_VERSION_1_3 @property(copy) NSString *defaultValue; @property BOOL defaultChecked; @property(readonly, retain) DOMHTMLFormElement *form; @@ -495,41 +495,38 @@ @property BOOL readOnly; @property(copy) NSString *size; @property(copy) NSString *src; -@property int tabIndex; @property(copy) NSString *type; @property(copy) NSString *useMap; @property(copy) NSString *value; -@property(readonly, copy) NSString *altDisplayString; -@property(readonly, copy) NSURL *absoluteImageURL; -- (void)blur; -- (void)focus; +@property(readonly, copy) NSString *altDisplayString AVAILABLE_WEBKIT_VERSION_3_0_AND_LATER; +@property(readonly, copy) NSURL *absoluteImageURL AVAILABLE_WEBKIT_VERSION_3_0_AND_LATER; - (void)select; - (void)click; @end -@interface DOMHTMLIsIndexElement : DOMHTMLInputElement +@interface DOMHTMLIsIndexElement : DOMHTMLInputElement WEBKIT_VERSION_1_3 @property(readonly, retain) DOMHTMLFormElement *form; @property(copy) NSString *prompt; @end -@interface DOMHTMLLIElement : DOMHTMLElement +@interface DOMHTMLLIElement : DOMHTMLElement WEBKIT_VERSION_1_3 @property(copy) NSString *type; @property int value; @end -@interface DOMHTMLLabelElement : DOMHTMLElement +@interface DOMHTMLLabelElement : DOMHTMLElement WEBKIT_VERSION_1_3 @property(readonly, retain) DOMHTMLFormElement *form; @property(copy) NSString *accessKey; @property(copy) NSString *htmlFor; @end -@interface DOMHTMLLegendElement : DOMHTMLElement +@interface DOMHTMLLegendElement : DOMHTMLElement WEBKIT_VERSION_1_3 @property(readonly, retain) DOMHTMLFormElement *form; @property(copy) NSString *accessKey; @property(copy) NSString *align; @end -@interface DOMHTMLLinkElement : DOMHTMLElement +@interface DOMHTMLLinkElement : DOMHTMLElement WEBKIT_VERSION_1_3 @property BOOL disabled; @property(copy) NSString *charset; @property(copy) NSString *href; @@ -539,42 +536,42 @@ @property(copy) NSString *rev; @property(copy) NSString *target; @property(copy) NSString *type; -@property(readonly, copy) NSURL *absoluteLinkURL; +@property(readonly, copy) NSURL *absoluteLinkURL AVAILABLE_WEBKIT_VERSION_3_0_AND_LATER; @end -@interface DOMHTMLMapElement : DOMHTMLElement +@interface DOMHTMLMapElement : DOMHTMLElement WEBKIT_VERSION_1_3 @property(readonly, retain) DOMHTMLCollection *areas; @property(copy) NSString *name; @end -@interface DOMHTMLMarqueeElement : DOMHTMLElement +@interface DOMHTMLMarqueeElement : DOMHTMLElement WEBKIT_VERSION_3_0 - (void)start; - (void)stop; @end -@interface DOMHTMLMenuElement : DOMHTMLElement +@interface DOMHTMLMenuElement : DOMHTMLElement WEBKIT_VERSION_1_3 @property BOOL compact; @end -@interface DOMHTMLMetaElement : DOMHTMLElement +@interface DOMHTMLMetaElement : DOMHTMLElement WEBKIT_VERSION_1_3 @property(copy) NSString *content; @property(copy) NSString *httpEquiv; @property(copy) NSString *name; @property(copy) NSString *scheme; @end -@interface DOMHTMLModElement : DOMHTMLElement +@interface DOMHTMLModElement : DOMHTMLElement WEBKIT_VERSION_1_3 @property(copy) NSString *cite; @property(copy) NSString *dateTime; @end -@interface DOMHTMLOListElement : DOMHTMLElement +@interface DOMHTMLOListElement : DOMHTMLElement WEBKIT_VERSION_1_3 @property BOOL compact; @property int start; @property(copy) NSString *type; @end -@interface DOMHTMLObjectElement : DOMHTMLElement +@interface DOMHTMLObjectElement : DOMHTMLElement WEBKIT_VERSION_1_3 @property(readonly, retain) DOMHTMLFormElement *form; @property(copy) NSString *code; @property(copy) NSString *align; @@ -588,21 +585,20 @@ @property int hspace; @property(copy) NSString *name; @property(copy) NSString *standby; -@property int tabIndex; @property(copy) NSString *type; @property(copy) NSString *useMap; @property int vspace; @property(copy) NSString *width; @property(readonly, retain) DOMDocument *contentDocument; -@property(readonly, copy) NSURL *absoluteImageURL; +@property(readonly, copy) NSURL *absoluteImageURL AVAILABLE_WEBKIT_VERSION_3_0_AND_LATER; @end -@interface DOMHTMLOptGroupElement : DOMHTMLElement +@interface DOMHTMLOptGroupElement : DOMHTMLElement WEBKIT_VERSION_1_3 @property BOOL disabled; @property(copy) NSString *label; @end -@interface DOMHTMLOptionElement : DOMHTMLElement +@interface DOMHTMLOptionElement : DOMHTMLElement WEBKIT_VERSION_1_3 @property(readonly, retain) DOMHTMLFormElement *form; @property BOOL defaultSelected; @property(readonly, copy) NSString *text; @@ -613,32 +609,32 @@ @property(copy) NSString *value; @end -@interface DOMHTMLOptionsCollection : DOMObject +@interface DOMHTMLOptionsCollection : DOMObject WEBKIT_VERSION_1_3 @property unsigned length; - (DOMNode *)item:(unsigned)index; - (DOMNode *)namedItem:(NSString *)name; @end -@interface DOMHTMLParagraphElement : DOMHTMLElement +@interface DOMHTMLParagraphElement : DOMHTMLElement WEBKIT_VERSION_1_3 @property(copy) NSString *align; @end -@interface DOMHTMLParamElement : DOMHTMLElement +@interface DOMHTMLParamElement : DOMHTMLElement WEBKIT_VERSION_1_3 @property(copy) NSString *name; @property(copy) NSString *type; @property(copy) NSString *value; @property(copy) NSString *valueType; @end -@interface DOMHTMLPreElement : DOMHTMLElement +@interface DOMHTMLPreElement : DOMHTMLElement WEBKIT_VERSION_1_3 @property int width; @end -@interface DOMHTMLQuoteElement : DOMHTMLElement +@interface DOMHTMLQuoteElement : DOMHTMLElement WEBKIT_VERSION_1_3 @property(copy) NSString *cite; @end -@interface DOMHTMLScriptElement : DOMHTMLElement +@interface DOMHTMLScriptElement : DOMHTMLElement WEBKIT_VERSION_1_3 @property(copy) NSString *text; @property(copy) NSString *htmlFor; @property(copy) NSString *event; @@ -648,7 +644,7 @@ @property(copy) NSString *type; @end -@interface DOMHTMLSelectElement : DOMHTMLElement +@interface DOMHTMLSelectElement : DOMHTMLElement WEBKIT_VERSION_1_3 @property(readonly, copy) NSString *type; @property int selectedIndex; @property(copy) NSString *value; @@ -659,25 +655,22 @@ @property BOOL multiple; @property(copy) NSString *name; @property int size; -@property int tabIndex; - (void)add:(DOMHTMLElement *)element :(DOMHTMLElement *)before; -- (void)add:(DOMHTMLElement *)element before:(DOMHTMLElement *)before; +- (void)add:(DOMHTMLElement *)element before:(DOMHTMLElement *)before AVAILABLE_WEBKIT_VERSION_3_0_AND_LATER; - (void)remove:(int)index; -- (void)blur; -- (void)focus; @end -@interface DOMHTMLStyleElement : DOMHTMLElement +@interface DOMHTMLStyleElement : DOMHTMLElement WEBKIT_VERSION_1_3 @property BOOL disabled; @property(copy) NSString *media; @property(copy) NSString *type; @end -@interface DOMHTMLTableCaptionElement : DOMHTMLElement +@interface DOMHTMLTableCaptionElement : DOMHTMLElement WEBKIT_VERSION_1_3 @property(copy) NSString *align; @end -@interface DOMHTMLTableCellElement : DOMHTMLElement +@interface DOMHTMLTableCellElement : DOMHTMLElement WEBKIT_VERSION_1_3 @property(readonly) int cellIndex; @property(copy) NSString *abbr; @property(copy) NSString *align; @@ -695,7 +688,7 @@ @property(copy) NSString *width; @end -@interface DOMHTMLTableColElement : DOMHTMLElement +@interface DOMHTMLTableColElement : DOMHTMLElement WEBKIT_VERSION_1_3 @property(copy) NSString *align; @property(copy) NSString *ch; @property(copy) NSString *chOff; @@ -704,7 +697,7 @@ @property(copy) NSString *width; @end -@interface DOMHTMLTableElement : DOMHTMLElement +@interface DOMHTMLTableElement : DOMHTMLElement WEBKIT_VERSION_1_3 @property(retain) DOMHTMLTableCaptionElement *caption; @property(retain) DOMHTMLTableSectionElement *tHead; @property(retain) DOMHTMLTableSectionElement *tFoot; @@ -729,7 +722,7 @@ - (void)deleteRow:(int)index; @end -@interface DOMHTMLTableRowElement : DOMHTMLElement +@interface DOMHTMLTableRowElement : DOMHTMLElement WEBKIT_VERSION_1_3 @property(readonly) int rowIndex; @property(readonly) int sectionRowIndex; @property(readonly, retain) DOMHTMLCollection *cells; @@ -742,7 +735,7 @@ - (void)deleteCell:(int)index; @end -@interface DOMHTMLTableSectionElement : DOMHTMLElement +@interface DOMHTMLTableSectionElement : DOMHTMLElement WEBKIT_VERSION_1_3 @property(copy) NSString *align; @property(copy) NSString *ch; @property(copy) NSString *chOff; @@ -752,7 +745,7 @@ - (void)deleteRow:(int)index; @end -@interface DOMHTMLTextAreaElement : DOMHTMLElement +@interface DOMHTMLTextAreaElement : DOMHTMLElement WEBKIT_VERSION_1_3 @property(copy) NSString *defaultValue; @property(readonly, retain) DOMHTMLFormElement *form; @property(copy) NSString *accessKey; @@ -761,89 +754,86 @@ @property(copy) NSString *name; @property BOOL readOnly; @property int rows; -@property int tabIndex; @property(readonly, copy) NSString *type; @property(copy) NSString *value; -- (void)blur; -- (void)focus; - (void)select; @end -@interface DOMHTMLTitleElement : DOMHTMLElement +@interface DOMHTMLTitleElement : DOMHTMLElement WEBKIT_VERSION_1_3 @property(copy) NSString *text; @end -@interface DOMHTMLUListElement : DOMHTMLElement +@interface DOMHTMLUListElement : DOMHTMLElement WEBKIT_VERSION_1_3 @property BOOL compact; @property(copy) NSString *type; @end -@interface DOMStyleSheetList : DOMObject +@interface DOMStyleSheetList : DOMObject WEBKIT_VERSION_1_3 @property(readonly) unsigned length; - (DOMStyleSheet *)item:(unsigned)index; @end -@interface DOMCSSCharsetRule : DOMCSSRule +@interface DOMCSSCharsetRule : DOMCSSRule WEBKIT_VERSION_1_3 @property(readonly, copy) NSString *encoding; @end -@interface DOMCSSFontFaceRule : DOMCSSRule +@interface DOMCSSFontFaceRule : DOMCSSRule WEBKIT_VERSION_1_3 @property(readonly, retain) DOMCSSStyleDeclaration *style; @end -@interface DOMCSSImportRule : DOMCSSRule +@interface DOMCSSImportRule : DOMCSSRule WEBKIT_VERSION_1_3 @property(readonly, copy) NSString *href; @property(readonly, retain) DOMMediaList *media; @property(readonly, retain) DOMCSSStyleSheet *styleSheet; @end -@interface DOMCSSMediaRule : DOMCSSRule +@interface DOMCSSMediaRule : DOMCSSRule WEBKIT_VERSION_1_3 @property(readonly, retain) DOMMediaList *media; @property(readonly, retain) DOMCSSRuleList *cssRules; - (unsigned)insertRule:(NSString *)rule :(unsigned)index; -- (unsigned)insertRule:(NSString *)rule index:(unsigned)index; +- (unsigned)insertRule:(NSString *)rule index:(unsigned)index AVAILABLE_WEBKIT_VERSION_3_0_AND_LATER; - (void)deleteRule:(unsigned)index; @end -@interface DOMCSSPageRule : DOMCSSRule +@interface DOMCSSPageRule : DOMCSSRule WEBKIT_VERSION_1_3 @property(copy) NSString *selectorText; @property(readonly, retain) DOMCSSStyleDeclaration *style; @end -@interface DOMCSSPrimitiveValue : DOMCSSValue +@interface DOMCSSPrimitiveValue : DOMCSSValue WEBKIT_VERSION_1_3 @property(readonly) unsigned short primitiveType; - (void)setFloatValue:(unsigned short)unitType :(float)floatValue; -- (void)setFloatValue:(unsigned short)unitType floatValue:(float)floatValue; +- (void)setFloatValue:(unsigned short)unitType floatValue:(float)floatValue AVAILABLE_WEBKIT_VERSION_3_0_AND_LATER; - (float)getFloatValue:(unsigned short)unitType; - (void)setStringValue:(unsigned short)stringType :(NSString *)stringValue; -- (void)setStringValue:(unsigned short)stringType stringValue:(NSString *)stringValue; +- (void)setStringValue:(unsigned short)stringType stringValue:(NSString *)stringValue AVAILABLE_WEBKIT_VERSION_3_0_AND_LATER; - (NSString *)getStringValue; - (DOMCounter *)getCounterValue; - (DOMRect *)getRectValue; - (DOMRGBColor *)getRGBColorValue; @end -@interface DOMRGBColor : DOMObject +@interface DOMRGBColor : DOMObject WEBKIT_VERSION_1_3 @property(readonly, retain) DOMCSSPrimitiveValue *red; @property(readonly, retain) DOMCSSPrimitiveValue *green; @property(readonly, retain) DOMCSSPrimitiveValue *blue; @property(readonly, retain) DOMCSSPrimitiveValue *alpha; -@property(readonly, copy) NSColor *color; +@property(readonly, copy) NSColor *color AVAILABLE_WEBKIT_VERSION_3_0_AND_LATER; @end -@interface DOMCSSRule : DOMObject +@interface DOMCSSRule : DOMObject WEBKIT_VERSION_1_3 @property(readonly) unsigned short type; @property(copy) NSString *cssText; @property(readonly, retain) DOMCSSStyleSheet *parentStyleSheet; @property(readonly, retain) DOMCSSRule *parentRule; @end -@interface DOMCSSRuleList : DOMObject +@interface DOMCSSRuleList : DOMObject WEBKIT_VERSION_1_3 @property(readonly) unsigned length; - (DOMCSSRule *)item:(unsigned)index; @end -@interface DOMCSSStyleDeclaration : DOMObject +@interface DOMCSSStyleDeclaration : DOMObject WEBKIT_VERSION_1_3 @property(copy) NSString *cssText; @property(readonly) unsigned length; @property(readonly, retain) DOMCSSRule *parentRule; @@ -852,18 +842,18 @@ - (NSString *)removeProperty:(NSString *)propertyName; - (NSString *)getPropertyPriority:(NSString *)propertyName; - (void)setProperty:(NSString *)propertyName :(NSString *)value :(NSString *)priority; -- (void)setProperty:(NSString *)propertyName value:(NSString *)value priority:(NSString *)priority; +- (void)setProperty:(NSString *)propertyName value:(NSString *)value priority:(NSString *)priority AVAILABLE_WEBKIT_VERSION_3_0_AND_LATER; - (NSString *)item:(unsigned)index; -- (NSString *)getPropertyShorthand:(NSString *)propertyName; -- (BOOL)isPropertyImplicit:(NSString *)propertyName; +- (NSString *)getPropertyShorthand:(NSString *)propertyName AVAILABLE_WEBKIT_VERSION_3_0_AND_LATER; +- (BOOL)isPropertyImplicit:(NSString *)propertyName AVAILABLE_WEBKIT_VERSION_3_0_AND_LATER; @end -@interface DOMCSSStyleRule : DOMCSSRule +@interface DOMCSSStyleRule : DOMCSSRule WEBKIT_VERSION_1_3 @property(copy) NSString *selectorText; @property(readonly, retain) DOMCSSStyleDeclaration *style; @end -@interface DOMStyleSheet : DOMObject +@interface DOMStyleSheet : DOMObject WEBKIT_VERSION_1_3 @property(readonly, copy) NSString *type; @property BOOL disabled; @property(readonly, retain) DOMNode *ownerNode; @@ -873,41 +863,41 @@ @property(readonly, retain) DOMMediaList *media; @end -@interface DOMCSSStyleSheet : DOMStyleSheet +@interface DOMCSSStyleSheet : DOMStyleSheet WEBKIT_VERSION_1_3 @property(readonly, retain) DOMCSSRule *ownerRule; @property(readonly, retain) DOMCSSRuleList *cssRules; - (unsigned)insertRule:(NSString *)rule :(unsigned)index; -- (unsigned)insertRule:(NSString *)rule index:(unsigned)index; +- (unsigned)insertRule:(NSString *)rule index:(unsigned)index AVAILABLE_WEBKIT_VERSION_3_0_AND_LATER; - (void)deleteRule:(unsigned)index; @end -@interface DOMCSSValue : DOMObject +@interface DOMCSSValue : DOMObject WEBKIT_VERSION_1_3 @property(copy) NSString *cssText; @property(readonly) unsigned short cssValueType; @end -@interface DOMCSSValueList : DOMCSSValue +@interface DOMCSSValueList : DOMCSSValue WEBKIT_VERSION_1_3 @property(readonly) unsigned length; - (DOMCSSValue *)item:(unsigned)index; @end -@interface DOMCSSUnknownRule : DOMCSSRule +@interface DOMCSSUnknownRule : DOMCSSRule WEBKIT_VERSION_1_3 @end -@interface DOMCounter : DOMObject +@interface DOMCounter : DOMObject WEBKIT_VERSION_1_3 @property(readonly, copy) NSString *identifier; @property(readonly, copy) NSString *listStyle; @property(readonly, copy) NSString *separator; @end -@interface DOMRect : DOMObject +@interface DOMRect : DOMObject WEBKIT_VERSION_1_3 @property(readonly, retain) DOMCSSPrimitiveValue *top; @property(readonly, retain) DOMCSSPrimitiveValue *right; @property(readonly, retain) DOMCSSPrimitiveValue *bottom; @property(readonly, retain) DOMCSSPrimitiveValue *left; @end -@interface DOMEvent : DOMObject +@interface DOMEvent : DOMObject WEBKIT_VERSION_1_3 @property(readonly, copy) NSString *type; @property(readonly, retain) id <DOMEventTarget> target; @property(readonly, retain) id <DOMEventTarget> currentTarget; @@ -917,35 +907,35 @@ @property(readonly) DOMTimeStamp timeStamp; - (void)stopPropagation; - (void)preventDefault; -- (void)initEvent:(NSString *)eventTypeArg canBubbleArg:(BOOL)canBubbleArg cancelableArg:(BOOL)cancelableArg; +- (void)initEvent:(NSString *)eventTypeArg canBubbleArg:(BOOL)canBubbleArg cancelableArg:(BOOL)cancelableArg AVAILABLE_WEBKIT_VERSION_3_0_AND_LATER; - (void)initEvent:(NSString *)eventTypeArg :(BOOL)canBubbleArg :(BOOL)cancelableArg; @end -@interface DOMUIEvent : DOMEvent +@interface DOMUIEvent : DOMEvent WEBKIT_VERSION_1_3 @property(readonly, retain) DOMAbstractView *view; @property(readonly) int detail; -- (void)initUIEvent:(NSString *)type canBubble:(BOOL)canBubble cancelable:(BOOL)cancelable view:(DOMAbstractView *)view detail:(int)detail; +- (void)initUIEvent:(NSString *)type canBubble:(BOOL)canBubble cancelable:(BOOL)cancelable view:(DOMAbstractView *)view detail:(int)detail AVAILABLE_WEBKIT_VERSION_3_0_AND_LATER; - (void)initUIEvent:(NSString *)type :(BOOL)canBubble :(BOOL)cancelable :(DOMAbstractView *)view :(int)detail; @end -@interface DOMMutationEvent : DOMEvent +@interface DOMMutationEvent : DOMEvent WEBKIT_VERSION_1_3 @property(readonly, retain) DOMNode *relatedNode; @property(readonly, copy) NSString *prevValue; @property(readonly, copy) NSString *newValue; @property(readonly, copy) NSString *attrName; @property(readonly) unsigned short attrChange; -- (void)initMutationEvent:(NSString *)type canBubble:(BOOL)canBubble cancelable:(BOOL)cancelable relatedNode:(DOMNode *)relatedNode prevValue:(NSString *)prevValue newValue:(NSString *)newValue attrName:(NSString *)attrName attrChange:(unsigned short)attrChange; +- (void)initMutationEvent:(NSString *)type canBubble:(BOOL)canBubble cancelable:(BOOL)cancelable relatedNode:(DOMNode *)relatedNode prevValue:(NSString *)prevValue newValue:(NSString *)newValue attrName:(NSString *)attrName attrChange:(unsigned short)attrChange AVAILABLE_WEBKIT_VERSION_3_0_AND_LATER; - (void)initMutationEvent:(NSString *)type :(BOOL)canBubble :(BOOL)cancelable :(DOMNode *)relatedNode :(NSString *)prevValue :(NSString *)newValue :(NSString *)attrName :(unsigned short)attrChange; @end -@interface DOMOverflowEvent : DOMEvent +@interface DOMOverflowEvent : DOMEvent WEBKIT_VERSION_3_0 @property(readonly) unsigned short orient; @property(readonly) BOOL horizontalOverflow; @property(readonly) BOOL verticalOverflow; - (void)initOverflowEvent:(unsigned short)orient horizontalOverflow:(BOOL)horizontalOverflow verticalOverflow:(BOOL)verticalOverflow; @end -@interface DOMWheelEvent : DOMUIEvent +@interface DOMWheelEvent : DOMUIEvent WEBKIT_VERSION_3_0 @property(readonly) int screenX; @property(readonly) int screenY; @property(readonly) int clientX; @@ -958,7 +948,7 @@ @property(readonly) int wheelDelta; @end -@interface DOMKeyboardEvent : DOMUIEvent +@interface DOMKeyboardEvent : DOMUIEvent WEBKIT_VERSION_3_0 @property(readonly, copy) NSString *keyIdentifier; @property(readonly) unsigned keyLocation; @property(readonly) BOOL ctrlKey; @@ -970,7 +960,7 @@ - (BOOL)getModifierState:(NSString *)keyIdentifierArg; @end -@interface DOMMouseEvent : DOMUIEvent +@interface DOMMouseEvent : DOMUIEvent WEBKIT_VERSION_1_3 @property(readonly) int screenX; @property(readonly) int screenY; @property(readonly) int clientX; @@ -981,21 +971,21 @@ @property(readonly) BOOL metaKey; @property(readonly) unsigned short button; @property(readonly, retain) id <DOMEventTarget> relatedTarget; -- (void)initMouseEvent:(NSString *)type canBubble:(BOOL)canBubble cancelable:(BOOL)cancelable view:(DOMAbstractView *)view detail:(int)detail screenX:(int)screenX screenY:(int)screenY clientX:(int)clientX clientY:(int)clientY ctrlKey:(BOOL)ctrlKey altKey:(BOOL)altKey shiftKey:(BOOL)shiftKey metaKey:(BOOL)metaKey button:(unsigned short)button relatedTarget:(id <DOMEventTarget>)relatedTarget; +- (void)initMouseEvent:(NSString *)type canBubble:(BOOL)canBubble cancelable:(BOOL)cancelable view:(DOMAbstractView *)view detail:(int)detail screenX:(int)screenX screenY:(int)screenY clientX:(int)clientX clientY:(int)clientY ctrlKey:(BOOL)ctrlKey altKey:(BOOL)altKey shiftKey:(BOOL)shiftKey metaKey:(BOOL)metaKey button:(unsigned short)button relatedTarget:(id <DOMEventTarget>)relatedTarget AVAILABLE_WEBKIT_VERSION_3_0_AND_LATER; - (void)initMouseEvent:(NSString *)type :(BOOL)canBubble :(BOOL)cancelable :(DOMAbstractView *)view :(int)detail :(int)screenX :(int)screenY :(int)clientX :(int)clientY :(BOOL)ctrlKey :(BOOL)altKey :(BOOL)shiftKey :(BOOL)metaKey :(unsigned short)button :(id <DOMEventTarget>)relatedTarget; @end -@interface DOMRange : DOMObject +@interface DOMRange : DOMObject WEBKIT_VERSION_1_3 @property(readonly, retain) DOMNode *startContainer; @property(readonly) int startOffset; @property(readonly, retain) DOMNode *endContainer; @property(readonly) int endOffset; @property(readonly) BOOL collapsed; @property(readonly, retain) DOMNode *commonAncestorContainer; -@property(readonly, copy) NSString *text; -- (void)setStart:(DOMNode *)refNode offset:(int)offset; +@property(readonly, copy) NSString *text AVAILABLE_WEBKIT_VERSION_3_0_AND_LATER; +- (void)setStart:(DOMNode *)refNode offset:(int)offset AVAILABLE_WEBKIT_VERSION_3_0_AND_LATER; - (void)setStart:(DOMNode *)refNode :(int)offset; -- (void)setEnd:(DOMNode *)refNode offset:(int)offset; +- (void)setEnd:(DOMNode *)refNode offset:(int)offset AVAILABLE_WEBKIT_VERSION_3_0_AND_LATER; - (void)setEnd:(DOMNode *)refNode :(int)offset; - (void)setStartBefore:(DOMNode *)refNode; - (void)setStartAfter:(DOMNode *)refNode; @@ -1004,7 +994,7 @@ - (void)collapse:(BOOL)toStart; - (void)selectNode:(DOMNode *)refNode; - (void)selectNodeContents:(DOMNode *)refNode; -- (short)compareBoundaryPoints:(unsigned short)how sourceRange:(DOMRange *)sourceRange; +- (short)compareBoundaryPoints:(unsigned short)how sourceRange:(DOMRange *)sourceRange AVAILABLE_WEBKIT_VERSION_3_0_AND_LATER; - (short)compareBoundaryPoints:(unsigned short)how :(DOMRange *)sourceRange; - (void)deleteContents; - (DOMDocumentFragment *)extractContents; @@ -1016,7 +1006,7 @@ - (void)detach; @end -@interface DOMNodeIterator : DOMObject +@interface DOMNodeIterator : DOMObject WEBKIT_VERSION_1_3 @property(readonly, retain) DOMNode *root; @property(readonly) unsigned whatToShow; @property(readonly, retain) id <DOMNodeFilter> filter; @@ -1026,7 +1016,7 @@ - (void)detach; @end -@interface DOMMediaList : DOMObject +@interface DOMMediaList : DOMObject WEBKIT_VERSION_1_3 @property(copy) NSString *mediaText; @property(readonly) unsigned length; - (NSString *)item:(unsigned)index; @@ -1034,7 +1024,7 @@ - (void)appendMedium:(NSString *)newMedium; @end -@interface DOMTreeWalker : DOMObject +@interface DOMTreeWalker : DOMObject WEBKIT_VERSION_1_3 @property(readonly, retain) DOMNode *root; @property(readonly) unsigned whatToShow; @property(readonly, retain) id <DOMNodeFilter> filter; @@ -1049,7 +1039,7 @@ - (DOMNode *)nextNode; @end -@interface DOMXPathResult : DOMObject +@interface DOMXPathResult : DOMObject WEBKIT_VERSION_3_0 @property(readonly) unsigned short resultType; @property(readonly) double numberValue; @property(readonly, copy) NSString *stringValue; @@ -1061,32 +1051,29 @@ - (DOMNode *)snapshotItem:(unsigned)index; @end -@interface DOMXPathExpression : DOMObject -// We should be able to remove the old style version of this method -// once we can verify that all the internal Apple usages have switched -// to the new style, because this has never been in a public release. -- (DOMXPathResult *)evaluate:(DOMNode *)contextNode type:(unsigned short)type inResult:(DOMXPathResult *)inResult; -- (DOMXPathResult *)evaluate:(DOMNode *)contextNode :(unsigned short)type :(DOMXPathResult *)inResult; +@interface DOMXPathExpression : DOMObject WEBKIT_VERSION_3_0 +- (DOMXPathResult *)evaluate:(DOMNode *)contextNode type:(unsigned short)type inResult:(DOMXPathResult *)inResult AVAILABLE_WEBKIT_VERSION_3_0_AND_LATER; +- (DOMXPathResult *)evaluate:(DOMNode *)contextNode :(unsigned short)type :(DOMXPathResult *)inResult AVAILABLE_WEBKIT_VERSION_3_0_AND_LATER_BUT_DEPRECATED; @end // Protocols -@protocol DOMEventListener <NSObject> +@protocol DOMEventListener <NSObject> WEBKIT_VERSION_1_3 - (void)handleEvent:(DOMEvent *)evt; @end -@protocol DOMEventTarget <NSObject, NSCopying> +@protocol DOMEventTarget <NSObject, NSCopying> WEBKIT_VERSION_1_3 - (void)addEventListener:(NSString *)type :(id <DOMEventListener>)listener :(BOOL)useCapture; - (void)removeEventListener:(NSString *)type :(id <DOMEventListener>)listener :(BOOL)useCapture; -- (void)addEventListener:(NSString *)type listener:(id <DOMEventListener>)listener useCapture:(BOOL)useCapture; -- (void)removeEventListener:(NSString *)type listener:(id <DOMEventListener>)listener useCapture:(BOOL)useCapture; +- (void)addEventListener:(NSString *)type listener:(id <DOMEventListener>)listener useCapture:(BOOL)useCapture AVAILABLE_WEBKIT_VERSION_3_0_AND_LATER; +- (void)removeEventListener:(NSString *)type listener:(id <DOMEventListener>)listener useCapture:(BOOL)useCapture AVAILABLE_WEBKIT_VERSION_3_0_AND_LATER; - (BOOL)dispatchEvent:(DOMEvent *)event; @end -@protocol DOMNodeFilter <NSObject> +@protocol DOMNodeFilter <NSObject> WEBKIT_VERSION_1_3 - (short)acceptNode:(DOMNode *)n; @end -@protocol DOMXPathNSResolver <NSObject> +@protocol DOMXPathNSResolver <NSObject> WEBKIT_VERSION_3_0 - (NSString *)lookupNamespaceURI:(NSString *)prefix; @end diff --git a/WebCore/bindings/objc/WebScriptObject.h b/WebCore/bindings/objc/WebScriptObject.h index 9ad04ac..f75f458 100644 --- a/WebCore/bindings/objc/WebScriptObject.h +++ b/WebCore/bindings/objc/WebScriptObject.h @@ -1,11 +1,33 @@ /* - Copyright (C) 2004, 2006, 2007 Apple Inc. All rights reserved. - - Public header file. + * Copyright (C) 2004, 2006, 2007 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #import <Foundation/Foundation.h> #import <JavaScriptCore/JSBase.h> +#import <JavaScriptCore/WebKitAvailability.h> + +#if WEBKIT_VERSION_MAX_ALLOWED >= WEBKIT_VERSION_1_3 // NSObject (WebScripting) ----------------------------------------------------- @@ -212,7 +234,7 @@ @discussion Use this method to bridge between the WebScriptObject and JavaScriptCore APIs. */ -- (JSObjectRef)JSObject; +- (JSObjectRef)JSObject WEBKIT_OBJC_METHOD_ANNOTATION(AVAILABLE_WEBKIT_VERSION_3_0_AND_LATER); /*! @method callWebScriptMethod:withArguments: @@ -292,3 +314,5 @@ + (WebUndefined *)undefined; @end + +#endif diff --git a/WebCore/bindings/objc/WebScriptObject.mm b/WebCore/bindings/objc/WebScriptObject.mm index 4f1168b..6262b97 100644 --- a/WebCore/bindings/objc/WebScriptObject.mm +++ b/WebCore/bindings/objc/WebScriptObject.mm @@ -26,30 +26,34 @@ #import "config.h" #import "WebScriptObjectPrivate.h" +#import "Console.h" #import "DOMInternal.h" +#import "DOMWindow.h" #import "Frame.h" +#import "JSDOMWindow.h" +#import "JSDOMWindowCustom.h" #import "PlatformString.h" +#import "StringSourceProvider.h" #import "WebCoreObjCExtras.h" -#import "WebCoreFrameBridge.h" -#import <JavaScriptCore/ExecState.h> -#import <JavaScriptCore/objc_instance.h> -#import <JavaScriptCore/runtime_object.h> +#import "objc_instance.h" +#import "runtime.h" +#import "runtime_object.h" +#import "runtime_root.h" #import <JavaScriptCore/APICast.h> -#import <JavaScriptCore/JSGlobalObject.h> -#import <JavaScriptCore/interpreter.h> +#import <runtime/ExecState.h> +#import <runtime/JSGlobalObject.h> +#import <runtime/JSLock.h> +#import <kjs/completion.h> +#import <kjs/interpreter.h> + +#ifdef BUILDING_ON_TIGER +typedef unsigned NSUInteger; +#endif -using namespace KJS; -using namespace KJS::Bindings; +using namespace JSC; +using namespace JSC::Bindings; using namespace WebCore; -#define LOG_EXCEPTION(exec) \ - if (Interpreter::shouldPrintExceptions()) \ - printf("%s:%d:[%d] JavaScript exception: %s\n", __FILE__, __LINE__, getpid(), exec->exception()->toObject(exec)->get(exec, exec->propertyNames().message)->toString(exec).ascii()); - -@interface WebFrame -- (WebCoreFrameBridge *)_bridge; // implemented in WebKit -@end - namespace WebCore { typedef HashMap<JSObject*, NSObject*> JSWrapperMap; @@ -76,13 +80,21 @@ void removeJSWrapper(JSObject* impl) JSWrapperCache->remove(impl); } -id createJSWrapper(KJS::JSObject* object, PassRefPtr<KJS::Bindings::RootObject> origin, PassRefPtr<KJS::Bindings::RootObject> root) +id createJSWrapper(JSC::JSObject* object, PassRefPtr<JSC::Bindings::RootObject> origin, PassRefPtr<JSC::Bindings::RootObject> root) { if (id wrapper = getJSWrapper(object)) return [[wrapper retain] autorelease]; return [[[WebScriptObject alloc] _initWithJSObject:object originRootObject:origin rootObject:root] autorelease]; } +static void addExceptionToConsole(ExecState* exec) +{ + JSDOMWindow* window = asJSDOMWindow(exec->dynamicGlobalObject()); + if (!window || !exec->hadException()) + return; + window->impl()->console()->reportCurrentException(exec); +} + } // namespace WebCore @implementation WebScriptObjectPrivate @@ -158,7 +170,7 @@ static void _didExecute(WebScriptObject *obj) _private->originRootObject = originRootObject.releaseRef(); } -- (id)_initWithJSObject:(KJS::JSObject*)imp originRootObject:(PassRefPtr<KJS::Bindings::RootObject>)originRootObject rootObject:(PassRefPtr<KJS::Bindings::RootObject>)rootObject +- (id)_initWithJSObject:(JSC::JSObject*)imp originRootObject:(PassRefPtr<JSC::Bindings::RootObject>)originRootObject rootObject:(PassRefPtr<JSC::Bindings::RootObject>)rootObject { ASSERT(imp); @@ -212,6 +224,9 @@ static void _didExecute(WebScriptObject *obj) - (void)dealloc { + if (WebCoreObjCScheduleDeallocateOnMainThread([WebScriptObject class], self)) + return; + if (_private->imp) WebCore::removeJSWrapper(_private->imp); @@ -248,22 +263,11 @@ static void _didExecute(WebScriptObject *obj) + (BOOL)throwException:(NSString *)exceptionMessage { - JSLock lock; - - // This code assumes that we only ever have one running interpreter. A - // good assumption for now, as we depend on that elsewhere. However, - // in the future we may have the ability to run multiple interpreters, - // in which case this will have to change. - - if (ExecState::activeExecStates().size()) { - throwError(ExecState::activeExecStates().last(), GeneralError, exceptionMessage); - return YES; - } - - return NO; + ObjcInstance::setGlobalException(exceptionMessage); + return YES; } -static void getListFromNSArray(ExecState *exec, NSArray *array, RootObject* rootObject, List& aList) +static void getListFromNSArray(ExecState *exec, NSArray *array, RootObject* rootObject, ArgList& aList) { int i, numObjects = array ? [array count] : 0; @@ -278,35 +282,30 @@ static void getListFromNSArray(ExecState *exec, NSArray *array, RootObject* root if (![self _isSafeScript]) return nil; + JSLock lock(false); + // Look up the function object. ExecState* exec = [self _rootObject]->globalObject()->globalExec(); ASSERT(!exec->hadException()); - JSLock lock; - - JSValue* func = [self _imp]->get(exec, String(name)); - - if (!func || !func->isObject()) - // Maybe throw an exception here? - return 0; - - // Call the function object. - JSObject *funcImp = static_cast<JSObject*>(func); - if (!funcImp->implementsCall()) - return 0; + JSValue* function = [self _imp]->get(exec, Identifier(exec, String(name))); + CallData callData; + CallType callType = function->getCallData(callData); + if (callType == CallTypeNone) + return nil; - List argList; + ArgList argList; getListFromNSArray(exec, args, [self _rootObject], argList); if (![self _isSafeScript]) return nil; [self _rootObject]->globalObject()->startTimeoutCheck(); - JSValue *result = funcImp->call(exec, [self _imp], argList); + JSValue* result = call(exec, function, callType, callData, [self _imp], argList); [self _rootObject]->globalObject()->stopTimeoutCheck(); if (exec->hadException()) { - LOG_EXCEPTION(exec); + addExceptionToConsole(exec); result = jsUndefined(); exec->clearException(); } @@ -327,11 +326,11 @@ static void getListFromNSArray(ExecState *exec, NSArray *array, RootObject* root ExecState* exec = [self _rootObject]->globalObject()->globalExec(); ASSERT(!exec->hadException()); - JSValue *result; - JSLock lock; + JSValue* result; + JSLock lock(false); [self _rootObject]->globalObject()->startTimeoutCheck(); - Completion completion = Interpreter::evaluate([self _rootObject]->globalObject()->globalExec(), UString(), 0, String(script)); + Completion completion = Interpreter::evaluate([self _rootObject]->globalObject()->globalExec(), [self _rootObject]->globalObject()->globalScopeChain(), makeSource(String(script))); [self _rootObject]->globalObject()->stopTimeoutCheck(); ComplType type = completion.complType(); @@ -343,7 +342,7 @@ static void getListFromNSArray(ExecState *exec, NSArray *array, RootObject* root result = jsUndefined(); if (exec->hadException()) { - LOG_EXCEPTION(exec); + addExceptionToConsole(exec); result = jsUndefined(); exec->clearException(); } @@ -363,11 +362,13 @@ static void getListFromNSArray(ExecState *exec, NSArray *array, RootObject* root ExecState* exec = [self _rootObject]->globalObject()->globalExec(); ASSERT(!exec->hadException()); - JSLock lock; - [self _imp]->put(exec, String(key), convertObjcValueToValue(exec, &value, ObjcObjectType, [self _rootObject])); + JSLock lock(false); + + PutPropertySlot slot; + [self _imp]->put(exec, Identifier(exec, String(key)), convertObjcValueToValue(exec, &value, ObjcObjectType, [self _rootObject]), slot); if (exec->hadException()) { - LOG_EXCEPTION(exec); + addExceptionToConsole(exec); exec->clearException(); } @@ -387,12 +388,12 @@ static void getListFromNSArray(ExecState *exec, NSArray *array, RootObject* root // Need to scope this lock to ensure that we release the lock before calling // [super valueForKey:key] which might throw an exception and bypass the JSLock destructor, // leaving the lock permanently held - JSLock lock; + JSLock lock(false); - JSValue *result = [self _imp]->get(exec, String(key)); + JSValue* result = [self _imp]->get(exec, Identifier(exec, String(key))); if (exec->hadException()) { - LOG_EXCEPTION(exec); + addExceptionToConsole(exec); result = jsUndefined(); exec->clearException(); } @@ -403,7 +404,7 @@ static void getListFromNSArray(ExecState *exec, NSArray *array, RootObject* root if ([resultObj isKindOfClass:[WebUndefined class]]) resultObj = [super valueForKey:key]; // defaults to throwing an exception - JSLock lock; + JSLock lock(false); _didExecute(self); return resultObj; @@ -417,11 +418,11 @@ static void getListFromNSArray(ExecState *exec, NSArray *array, RootObject* root ExecState* exec = [self _rootObject]->globalObject()->globalExec(); ASSERT(!exec->hadException()); - JSLock lock; - [self _imp]->deleteProperty(exec, String(key)); + JSLock lock(false); + [self _imp]->deleteProperty(exec, Identifier(exec, String(key))); if (exec->hadException()) { - LOG_EXCEPTION(exec); + addExceptionToConsole(exec); exec->clearException(); } @@ -434,7 +435,7 @@ static void getListFromNSArray(ExecState *exec, NSArray *array, RootObject* root // This is a workaround for a gcc 3.3 internal compiler error. return @"Undefined"; - JSLock lock; + JSLock lock(false); ExecState* exec = [self _rootObject]->globalObject()->globalExec(); id result = convertValueToObjcValue(exec, [self _imp], ObjcObjectType).objectValue; @@ -454,11 +455,11 @@ static void getListFromNSArray(ExecState *exec, NSArray *array, RootObject* root ExecState* exec = [self _rootObject]->globalObject()->globalExec(); ASSERT(!exec->hadException()); - JSLock lock; - JSValue *result = [self _imp]->get(exec, index); + JSLock lock(false); + JSValue* result = [self _imp]->get(exec, index); if (exec->hadException()) { - LOG_EXCEPTION(exec); + addExceptionToConsole(exec); result = jsUndefined(); exec->clearException(); } @@ -478,11 +479,11 @@ static void getListFromNSArray(ExecState *exec, NSArray *array, RootObject* root ExecState* exec = [self _rootObject]->globalObject()->globalExec(); ASSERT(!exec->hadException()); - JSLock lock; + JSLock lock(false); [self _imp]->put(exec, index, convertObjcValueToValue(exec, &value, ObjcObjectType, [self _rootObject])); if (exec->hadException()) { - LOG_EXCEPTION(exec); + addExceptionToConsole(exec); exec->clearException(); } @@ -493,18 +494,7 @@ static void getListFromNSArray(ExecState *exec, NSArray *array, RootObject* root { if (![self _rootObject]) return; - - JSLock lock; - - ExecState* exec = 0; - JSObject* globalObject = [self _rootObject]->globalObject(); - ExecStateStack::const_iterator end = ExecState::activeExecStates().end(); - for (ExecStateStack::const_iterator it = ExecState::activeExecStates().begin(); it != end; ++it) - if ((*it)->dynamicGlobalObject() == globalObject) - exec = *it; - - if (exec) - throwError(exec, GeneralError, description); + ObjcInstance::setGlobalException(description, [self _rootObject]->globalObject()); } - (JSObjectRef)JSObject @@ -518,17 +508,17 @@ static void getListFromNSArray(ExecState *exec, NSArray *array, RootObject* root + (id)_convertValueToObjcValue:(JSValue*)value originRootObject:(RootObject*)originRootObject rootObject:(RootObject*)rootObject { if (value->isObject()) { - JSObject* object = static_cast<JSObject*>(value); + JSObject* object = asObject(value); ExecState* exec = rootObject->globalObject()->globalExec(); - JSLock lock; + JSLock lock(false); - if (object->classInfo() != &RuntimeObjectImp::info) { - JSValue* runtimeObject = object->get(exec, "__apple_runtime_object"); + if (object->classInfo() != &RuntimeObjectImp::s_info) { + JSValue* runtimeObject = object->get(exec, Identifier(exec, "__apple_runtime_object")); if (runtimeObject && runtimeObject->isObject()) - object = static_cast<RuntimeObjectImp*>(runtimeObject); + object = asObject(runtimeObject); } - if (object->classInfo() == &RuntimeObjectImp::info) { + if (object->classInfo() == &RuntimeObjectImp::s_info) { RuntimeObjectImp* imp = static_cast<RuntimeObjectImp*>(object); ObjcInstance *instance = static_cast<ObjcInstance*>(imp->getInternalInstance()); if (instance) @@ -540,8 +530,8 @@ static void getListFromNSArray(ExecState *exec, NSArray *array, RootObject* root } if (value->isString()) { - UString u = value->getString(); - return [NSString stringWithCharacters:(const unichar*)u.data() length:u.size()]; + const UString& u = asString(value)->value(); + return [NSString stringWithCharacters:u.data() length:u.size()]; } if (value->isNumber()) @@ -629,7 +619,7 @@ static void getListFromNSArray(ExecState *exec, NSArray *array, RootObject* root { } -- (unsigned)retainCount +- (NSUInteger)retainCount { return UINT_MAX; } diff --git a/WebCore/bindings/objc/WebScriptObjectPrivate.h b/WebCore/bindings/objc/WebScriptObjectPrivate.h index 53982ad..569d6f6 100644 --- a/WebCore/bindings/objc/WebScriptObjectPrivate.h +++ b/WebCore/bindings/objc/WebScriptObjectPrivate.h @@ -1,43 +1,70 @@ /* - Copyright (C) 2004, 2005, 2006, 2007 Apple Inc. All rights reserved. -*/ + * Copyright (C) 2004, 2005, 2006, 2007 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + #ifndef _WEB_SCRIPT_OBJECT_PRIVATE_H_ #define _WEB_SCRIPT_OBJECT_PRIVATE_H_ #import "WebScriptObject.h" +#import <runtime/JSValue.h> +#import <wtf/PassRefPtr.h> -#include <JavaScriptCore/internal.h> -#include <JavaScriptCore/object.h> -#include <JavaScriptCore/runtime_root.h> -#include <JavaScriptCore/APICast.h> - +namespace JSC { + + class JSObject; + + namespace Bindings { + class RootObject; + } +} namespace WebCore { - NSObject* getJSWrapper(KJS::JSObject*); - void addJSWrapper(NSObject* wrapper, KJS::JSObject*); - void removeJSWrapper(KJS::JSObject*); - id createJSWrapper(KJS::JSObject*, PassRefPtr<KJS::Bindings::RootObject> origin, PassRefPtr<KJS::Bindings::RootObject> root); + NSObject* getJSWrapper(JSC::JSObject*); + void addJSWrapper(NSObject* wrapper, JSC::JSObject*); + void removeJSWrapper(JSC::JSObject*); + id createJSWrapper(JSC::JSObject*, PassRefPtr<JSC::Bindings::RootObject> origin, PassRefPtr<JSC::Bindings::RootObject> root); } @interface WebScriptObject (Private) -+ (id)_convertValueToObjcValue:(KJS::JSValue*)value originRootObject:(KJS::Bindings::RootObject*)originRootObject rootObject:(KJS::Bindings::RootObject*)rootObject; -+ (id)scriptObjectForJSObject:(JSObjectRef)jsObject originRootObject:(KJS::Bindings::RootObject*)originRootObject rootObject:(KJS::Bindings::RootObject*)rootObject; ++ (id)_convertValueToObjcValue:(JSC::JSValue*)value originRootObject:(JSC::Bindings::RootObject*)originRootObject rootObject:(JSC::Bindings::RootObject*)rootObject; ++ (id)scriptObjectForJSObject:(JSObjectRef)jsObject originRootObject:(JSC::Bindings::RootObject*)originRootObject rootObject:(JSC::Bindings::RootObject*)rootObject; - (id)_init; -- (id)_initWithJSObject:(KJS::JSObject*)imp originRootObject:(PassRefPtr<KJS::Bindings::RootObject>)originRootObject rootObject:(PassRefPtr<KJS::Bindings::RootObject>)rootObject; -- (void)_setImp:(KJS::JSObject*)imp originRootObject:(PassRefPtr<KJS::Bindings::RootObject>)originRootObject rootObject:(PassRefPtr<KJS::Bindings::RootObject>)rootObject; -- (void)_setOriginRootObject:(PassRefPtr<KJS::Bindings::RootObject>)originRootObject andRootObject:(PassRefPtr<KJS::Bindings::RootObject>)rootObject; +- (id)_initWithJSObject:(JSC::JSObject*)imp originRootObject:(PassRefPtr<JSC::Bindings::RootObject>)originRootObject rootObject:(PassRefPtr<JSC::Bindings::RootObject>)rootObject; +- (void)_setImp:(JSC::JSObject*)imp originRootObject:(PassRefPtr<JSC::Bindings::RootObject>)originRootObject rootObject:(PassRefPtr<JSC::Bindings::RootObject>)rootObject; +- (void)_setOriginRootObject:(PassRefPtr<JSC::Bindings::RootObject>)originRootObject andRootObject:(PassRefPtr<JSC::Bindings::RootObject>)rootObject; - (void)_initializeScriptDOMNodeImp; -- (KJS::JSObject *)_imp; +- (JSC::JSObject *)_imp; - (BOOL)_hasImp; -- (KJS::Bindings::RootObject*)_rootObject; -- (KJS::Bindings::RootObject*)_originRootObject; +- (JSC::Bindings::RootObject*)_rootObject; +- (JSC::Bindings::RootObject*)_originRootObject; @end @interface WebScriptObjectPrivate : NSObject { @public - KJS::JSObject *imp; - KJS::Bindings::RootObject* rootObject; - KJS::Bindings::RootObject* originRootObject; + JSC::JSObject *imp; + JSC::Bindings::RootObject* rootObject; + JSC::Bindings::RootObject* originRootObject; BOOL isCreatedByDOMWrapper; } @end diff --git a/WebCore/bindings/scripts/CodeGenerator.pm b/WebCore/bindings/scripts/CodeGenerator.pm index 2095c88..7a4d095 100644 --- a/WebCore/bindings/scripts/CodeGenerator.pm +++ b/WebCore/bindings/scripts/CodeGenerator.pm @@ -1,6 +1,6 @@ # # WebKit IDL parser -# +# # Copyright (C) 2005 Nikolas Zimmermann <wildfox@kde.org> # Copyright (C) 2006 Samuel Weinig <sam.weinig@gmail.com> # Copyright (C) 2007 Apple Inc. All rights reserved. @@ -34,13 +34,14 @@ my $codeGenerator = 0; my $verbose = 0; -my %primitiveTypeHash = ("int" => 1, "short" => 1, "long" => 1, +my %primitiveTypeHash = ("int" => 1, "short" => 1, "long" => 1, "long long" => 1, "unsigned int" => 1, "unsigned short" => 1, - "unsigned long" => 1, "float" => 1, - "double" => 1, "boolean" => 1, "void" => 1); + "unsigned long" => 1, "unsigned long long" => 1, + "float" => 1, "double" => 1, + "boolean" => 1, "void" => 1); -my %podTypeHash = ("RGBColor" => 1, "SVGLength" => 1, "SVGPoint" => 1, "SVGRect" => 1, "SVGNumber" => 1, "SVGMatrix" => 1, "SVGTransform" => 1); - +my %podTypeHash = ("RGBColor" => 1, "SVGNumber" => 1, "SVGTransform" => 1); +my %podTypesWithWritablePropertiesHash = ("SVGLength" => 1, "SVGMatrix" => 1, "SVGPoint" => 1, "SVGRect" => 1); my %stringTypeHash = ("DOMString" => 1, "AtomicString" => 1); my %nonPointerTypeHash = ("DOMTimeStamp" => 1, "CompareHow" => 1, "SVGPaintType" => 1); @@ -269,6 +270,16 @@ sub IsPodType my $type = shift; return 1 if $podTypeHash{$type}; + return 1 if $podTypesWithWritablePropertiesHash{$type}; + return 0; +} + +sub IsPodTypeWithWriteableProperties +{ + my $object = shift; + my $type = shift; + + return 1 if $podTypesWithWritablePropertiesHash{$type}; return 0; } diff --git a/WebCore/bindings/scripts/CodeGeneratorCOM.pm b/WebCore/bindings/scripts/CodeGeneratorCOM.pm index 5fcf0cd..0c86ef2 100644 --- a/WebCore/bindings/scripts/CodeGeneratorCOM.pm +++ b/WebCore/bindings/scripts/CodeGeneratorCOM.pm @@ -3,7 +3,7 @@ # Copyright (C) 2006 Anders Carlsson <andersca@mac.com> # Copyright (C) 2006, 2007 Samuel Weinig <sam@webkit.org> # Copyright (C) 2006 Alexey Proskuryakov <ap@webkit.org> -# Copyright (C) 2006, 2007 Apple Inc. All rights reserved. +# Copyright (C) 2006, 2007, 2008 Apple Inc. All rights reserved. # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Library General Public @@ -267,6 +267,11 @@ sub AddIncludesForTypeInCPPHeader return if $codeGenerator->IsNonPointerType($type); # Add special Cases HERE + + if ($type =~ m/^I/) { + $type = "WebKit"; + } + if ($useAngleBrackets) { $CPPHeaderIncludesAngle{"$type.h"} = 1; return; @@ -304,9 +309,9 @@ sub AddIncludesForTypeInCPPImplementation return if $codeGenerator->IsNonPointerType($type); if ($codeGenerator->IsStringType($type)) { - $CPPImplementationWebCoreIncludes{"PlatformString.h"} = 1; - $CPPImplementationWebCoreIncludes{"BString.h"} = 1; $CPPImplementationWebCoreIncludes{"AtomicString.h"} = 1; + $CPPImplementationWebCoreIncludes{"BString.h"} = 1; + $CPPImplementationWebCoreIncludes{"KURL.h"} = 1; return; } @@ -349,11 +354,15 @@ sub GenerateIDL push(@IDLHeader, "\n"); # - INCLUDES - + push(@IDLHeader, "#ifndef DO_NO_IMPORTS\n"); push(@IDLHeader, "import \"oaidl.idl\";\n"); - push(@IDLHeader, "import \"ocidl.idl\";\n\n"); + push(@IDLHeader, "import \"ocidl.idl\";\n"); + push(@IDLHeader, "#endif\n\n"); unless ($pureInterface) { - push(@IDLHeader, "import \"${parentInterfaceName}.idl\";\n\n"); + push(@IDLHeader, "#ifndef DO_NO_IMPORTS\n"); + push(@IDLHeader, "import \"${parentInterfaceName}.idl\";\n"); + push(@IDLHeader, "#endif\n\n"); $IDLDontForwardDeclare{$outInterfaceName} = 1; $IDLDontImport{$outInterfaceName} = 1; @@ -457,7 +466,7 @@ sub GenerateInterfaceHeader @CPPInterfaceHeader = @licenseTemplate; push(@CPPInterfaceHeader, "\n"); - # - Header gaurds - + # - Header guards - push(@CPPInterfaceHeader, "#ifndef " . $className . "_h\n"); push(@CPPInterfaceHeader, "#define " . $className . "_h\n\n"); @@ -469,7 +478,7 @@ sub GenerateInterfaceHeader # - Default Interface Creator - push(@CPPInterfaceHeader, "${interfaceName}* to${interfaceName}(${implementationClass}*) { return 0; }\n\n"); - + push(@CPPInterfaceHeader, "#endif // " . $className . "_h\n"); } @@ -834,7 +843,7 @@ sub GenerateCPPHeader @CPPHeaderHeader = @licenseTemplate; push(@CPPHeaderHeader, "\n"); - # - Header gaurds - + # - Header guards - push(@CPPHeaderHeader, "#ifndef " . $className . "_h\n"); push(@CPPHeaderHeader, "#define " . $className . "_h\n\n"); @@ -891,7 +900,7 @@ sub GenerateCPPHeader foreach my $attribute (@attributeList) { # Don't forward an attribute that this class redefines. next if $attributeNameSet{$attribute->signature->name}; - + AddForwardDeclarationsForTypeInCPPHeader($attribute->signature->type); my %attributes = GenerateCPPAttributeSignature($attribute, $className, { "NewLines" => 0, @@ -1215,7 +1224,9 @@ sub WriteData print OUTPUTIDL map { "interface $_;\n" } sort keys(%IDLForwardDeclarations); print OUTPUTIDL "\n"; + print OUTPUTIDL "#ifndef DO_NO_IMPORTS\n"; print OUTPUTIDL map { ($_ eq "IGEN_DOMImplementation") ? "import \"IGEN_DOMDOMImplementation.idl\";\n" : "import \"$_.idl\";\n" } sort keys(%IDLImports); + print OUTPUTIDL "#endif\n"; print OUTPUTIDL "\n"; # Add content diff --git a/WebCore/bindings/scripts/CodeGeneratorJS.pm b/WebCore/bindings/scripts/CodeGeneratorJS.pm index 7b00bdf..a095fc7 100644 --- a/WebCore/bindings/scripts/CodeGeneratorJS.pm +++ b/WebCore/bindings/scripts/CodeGeneratorJS.pm @@ -1,10 +1,10 @@ # -# Copyright (C) 2005, 2006, 2007 Nikolas Zimmermann <zimmermann@kde.org> +# Copyright (C) 2005, 2006, 2007, 2008 Nikolas Zimmermann <zimmermann@kde.org> # Copyright (C) 2006 Anders Carlsson <andersca@mac.com> # Copyright (C) 2006, 2007 Samuel Weinig <sam@webkit.org> # Copyright (C) 2006 Alexey Proskuryakov <ap@webkit.org> # Copyright (C) 2006, 2007, 2008 Apple Inc. All rights reserved. -# +# # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Library General Public # License as published by the Free Software Foundation; either @@ -27,10 +27,14 @@ use File::stat; my $module = ""; my $outputDir = ""; +my @headerContentHeader = (); my @headerContent = (); +my %headerIncludes = (); + my @implContentHeader = (); my @implContent = (); my %implIncludes = (); +my %implKJSIncludes = (); # Default .h template my $headerTemplate = << "EOF"; @@ -116,23 +120,10 @@ sub GetParentClassName my $dataNode = shift; return $dataNode->extendedAttributes->{"LegacyParent"} if $dataNode->extendedAttributes->{"LegacyParent"}; - return "KJS::DOMObject" if @{$dataNode->parents} eq 0; + return "DOMObject" if @{$dataNode->parents} eq 0; return "JS" . $codeGenerator->StripModule($dataNode->parents(0)); } -sub GetLegacyHeaderIncludes -{ - my $legacyParent = shift; - - return "#include \"JSHTMLInputElementBase.h\"\n\n" if $legacyParent eq "JSHTMLInputElementBase"; - return "#include \"kjs_window.h\"\n\n" if $legacyParent eq "KJS::Window"; - return "#include \"kjs_events.h\"\n\n" if $module eq "events"; - return "#include \"kjs_css.h\"\n\n" if $module eq "css"; - return "#include \"kjs_html.h\"\n\n" if $module eq "html"; - - die "Don't know what headers to include for module $module"; -} - sub GetVisibleClassName { my $className = shift; @@ -154,7 +145,7 @@ sub UsesManualToJSImplementation { my $type = shift; - return 1 if $type eq "Node" or $type eq "Document" or $type eq "HTMLCollection" or $type eq "SVGPathSeg" or $type eq "StyleSheet" or $type eq "CSSRule" or $type eq "CSSValue" or $type eq "Event"; + return 1 if $type eq "Node" or $type eq "Document" or $type eq "HTMLCollection" or $type eq "SVGPathSeg" or $type eq "StyleSheet" or $type eq "CSSRule" or $type eq "CSSValue" or $type eq "Event" or $type eq "ImageData" or $type eq "Element" or $type eq "Text"; return 0; } @@ -162,7 +153,7 @@ sub IndexGetterReturnsStrings { my $type = shift; - return 1 if $type eq "CSSStyleDeclaration" or $type eq "MediaList"; + return 1 if $type eq "CSSStyleDeclaration" or $type eq "MediaList" or $type eq "CSSVariablesDeclaration"; return 0; } @@ -204,9 +195,13 @@ sub AddIncludesForType $implIncludes{"CanvasStyle.h"} = 1; } - if ($type eq "CanvasGradient" or $type eq "XPathNSResolver") { + if ($type eq "CanvasGradient" or $type eq "XPathNSResolver" or $type eq "MessagePort") { $implIncludes{"PlatformString.h"} = 1; } + + if ($type eq "Document") { + $implIncludes{"NodeFilter.h"} = 1; + } } sub AddIncludesForSVGAnimatedType @@ -253,6 +248,103 @@ sub HashValueForClassAndName return "${class}::$name"; } +sub hashTableAccessor +{ + my $noStaticTables = shift; + my $className = shift; + if ($noStaticTables) { + return "get${className}Table(exec)"; + } else { + return "&${className}Table"; + } +} + +sub prototypeHashTableAccessor +{ + my $noStaticTables = shift; + my $className = shift; + if ($noStaticTables) { + return "get${className}PrototypeTable(exec)"; + } else { + return "&${className}PrototypeTable"; + } +} + +sub GenerateGetOwnPropertySlotBody +{ + my ($dataNode, $interfaceName, $className, $implClassName, $hasAttributes, $inlined) = @_; + + my $namespaceMaybe = ($inlined ? "JSC::" : ""); + + my @getOwnPropertySlotImpl = (); + + if ($interfaceName eq "NamedNodeMap" or $interfaceName eq "HTMLCollection") { + push(@getOwnPropertySlotImpl, " ${namespaceMaybe}JSValue* proto = prototype();\n"); + push(@getOwnPropertySlotImpl, " if (proto->isObject() && static_cast<${namespaceMaybe}JSObject*>(asObject(proto))->hasProperty(exec, propertyName))\n"); + push(@getOwnPropertySlotImpl, " return false;\n\n"); + } + + my $hasNameGetterGeneration = sub { + push(@getOwnPropertySlotImpl, " if (canGetItemsForName(exec, static_cast<$implClassName*>(impl()), propertyName)) {\n"); + push(@getOwnPropertySlotImpl, " slot.setCustom(this, nameGetter);\n"); + push(@getOwnPropertySlotImpl, " return true;\n"); + push(@getOwnPropertySlotImpl, " }\n"); + if ($inlined) { + $headerIncludes{"AtomicString.h"} = 1; + } else { + $implIncludes{"AtomicString.h"} = 1; + } + }; + + if ($dataNode->extendedAttributes->{"HasOverridingNameGetter"}) { + &$hasNameGetterGeneration(); + } + + my $requiresManualLookup = $dataNode->extendedAttributes->{"HasIndexGetter"} || $dataNode->extendedAttributes->{"HasNameGetter"}; + if ($requiresManualLookup) { + push(@getOwnPropertySlotImpl, " const ${namespaceMaybe}HashEntry* entry = ${className}Table.entry(exec, propertyName);\n"); + push(@getOwnPropertySlotImpl, " if (entry) {\n"); + push(@getOwnPropertySlotImpl, " slot.setCustom(this, entry->propertyGetter());\n"); + push(@getOwnPropertySlotImpl, " return true;\n"); + push(@getOwnPropertySlotImpl, " }\n"); + } + + if ($dataNode->extendedAttributes->{"HasIndexGetter"} || $dataNode->extendedAttributes->{"HasCustomIndexGetter"}) { + push(@getOwnPropertySlotImpl, " bool ok;\n"); + push(@getOwnPropertySlotImpl, " unsigned index = propertyName.toUInt32(&ok, false);\n"); + push(@getOwnPropertySlotImpl, " if (ok && index < static_cast<$implClassName*>(impl())->length()) {\n"); + if ($dataNode->extendedAttributes->{"HasCustomIndexGetter"}) { + push(@getOwnPropertySlotImpl, " slot.setValue(getByIndex(exec, index));\n"); + } else { + push(@getOwnPropertySlotImpl, " slot.setCustomIndex(this, index, indexGetter);\n"); + } + push(@getOwnPropertySlotImpl, " return true;\n"); + push(@getOwnPropertySlotImpl, " }\n"); + } + + if ($dataNode->extendedAttributes->{"HasNameGetter"}) { + &$hasNameGetterGeneration(); + } + + if ($dataNode->extendedAttributes->{"CustomGetOwnPropertySlot"}) { + push(@getOwnPropertySlotImpl, " if (customGetOwnPropertySlot(exec, propertyName, slot))\n"); + push(@getOwnPropertySlotImpl, " return true;\n"); + } + + if ($hasAttributes) { + if ($inlined) { + die "Cannot inline if NoStaticTables is set." if ($dataNode->extendedAttributes->{"NoStaticTables"}); + push(@getOwnPropertySlotImpl, " return ${namespaceMaybe}getStaticValueSlot<$className, Base>(exec, s_info.staticPropHashTable, this, propertyName, slot);\n"); + } else { + push(@getOwnPropertySlotImpl, " return ${namespaceMaybe}getStaticValueSlot<$className, Base>(exec, " . hashTableAccessor($dataNode->extendedAttributes->{"NoStaticTables"}, $className) . ", this, propertyName, slot);\n"); + } + } else { + push(@getOwnPropertySlotImpl, " return Base::getOwnPropertySlot(exec, propertyName, slot);\n"); + } + + return @getOwnPropertySlotImpl; +} + sub GenerateHeader { my $object = shift; @@ -275,36 +367,48 @@ sub GenerateHeader my $conditional = $dataNode->extendedAttributes->{"Conditional"}; # - Add default header template - @headerContent = split("\r", $headerTemplate); + @headerContentHeader = split("\r", $headerTemplate); # - Add header protection - push(@headerContent, "\n#ifndef $className" . "_H"); - push(@headerContent, "\n#define $className" . "_H\n\n"); + push(@headerContentHeader, "\n#ifndef $className" . "_h"); + push(@headerContentHeader, "\n#define $className" . "_h\n\n"); my $conditionalString; if ($conditional) { $conditionalString = "ENABLE(" . join(") && ENABLE(", split(/&/, $conditional)) . ")"; - push(@headerContent, "\n#if ${conditionalString}\n\n"); + push(@headerContentHeader, "\n#if ${conditionalString}\n\n"); } - if (exists $dataNode->extendedAttributes->{"LegacyParent"}) { - push(@headerContent, GetLegacyHeaderIncludes($dataNode->extendedAttributes->{"LegacyParent"})); + if ($hasParent) { + push(@headerContentHeader, "#include \"$parentClassName.h\"\n"); } else { - if ($hasParent) { - push(@headerContent, "#include \"$parentClassName.h\"\n"); - } else { - push(@headerContent, "#include \"kjs_binding.h\"\n"); - push(@headerContent, "#include <kjs/JSGlobalObject.h>\n"); - push(@headerContent, "#include <kjs/object_object.h>\n"); - } + push(@headerContentHeader, "#include \"JSDOMBinding.h\"\n"); + push(@headerContentHeader, "#include <runtime/JSGlobalObject.h>\n"); + push(@headerContentHeader, "#include <runtime/ObjectPrototype.h>\n"); + } + if ($interfaceName eq "Node") { + push(@headerContentHeader, "#include \"EventTargetNode.h\"\n"); + } + + if ($dataNode->extendedAttributes->{"CustomCall"}) { + push(@headerContentHeader, "#include <runtime/CallData.h>\n"); + } + + if ($dataNode->extendedAttributes->{"InlineGetOwnPropertySlot"}) { + push(@headerContentHeader, "#include <kjs/lookup.h>\n"); + push(@headerContentHeader, "#include <wtf/AlwaysInline.h>\n"); + } + + if ($hasParent && $dataNode->extendedAttributes->{"GenerateNativeConverter"}) { + push(@headerContentHeader, "#include \"${implClassName}.h\""); } # Get correct pass/store types respecting PODType flag my $podType = $dataNode->extendedAttributes->{"PODType"}; - my $passType = $podType ? "JSSVGPODTypeWrapper<$podType>*" : "$implClassName*"; - push(@headerContent, "#include \"$podType.h\"\n") if $podType and $podType ne "float"; + my $implType = $podType ? "JSSVGPODTypeWrapper<$podType> " : $implClassName; + push(@headerContentHeader, "#include \"$podType.h\"\n") if $podType and $podType ne "float"; - push(@headerContent, "#include \"JSSVGPODTypeWrapper.h\"\n") if $podType; + push(@headerContentHeader, "#include \"JSSVGPODTypeWrapper.h\"\n") if $podType; my $numConstants = @{$dataNode->constants}; my $numAttributes = @{$dataNode->attributes}; @@ -314,6 +418,7 @@ sub GenerateHeader # Implementation class forward declaration AddClassForwardIfNeeded($implClassName) unless $podType; + AddClassForwardIfNeeded("JSDOMWindowShell") if $interfaceName eq "DOMWindow"; # Class declaration push(@headerContent, "class $className : public $parentClassName {\n"); @@ -321,20 +426,35 @@ sub GenerateHeader push(@headerContent, "public:\n"); # Constructor - if ($dataNode->extendedAttributes->{"DoNotCache"}) { - push(@headerContent, " $className($passType);\n"); + if ($interfaceName eq "DOMWindow") { + push(@headerContent, " $className(PassRefPtr<JSC::StructureID>, PassRefPtr<$implType>, JSDOMWindowShell*);\n"); + } elsif (IsSVGTypeNeedingContextParameter($implClassName)) { + push(@headerContent, " $className(PassRefPtr<JSC::StructureID>, PassRefPtr<$implType>, SVGElement* context);\n"); } else { - push(@headerContent, " $className(KJS::JSObject* prototype, $passType" . (IsSVGTypeNeedingContextParameter($implClassName) ? ", SVGElement* context" : "") .");\n"); + push(@headerContent, " $className(PassRefPtr<JSC::StructureID>, PassRefPtr<$implType>);\n"); } # Destructor push(@headerContent, " virtual ~$className();\n") if (!$hasParent or $interfaceName eq "Document"); + # Prototype + push(@headerContent, " static JSC::JSObject* createPrototype(JSC::ExecState*);\n") if $interfaceName ne "DOMWindow"; + + $implIncludes{"${className}Custom.h"} = 1 if $dataNode->extendedAttributes->{"CustomHeader"} || $dataNode->extendedAttributes->{"CustomPutFunction"}; + + my $hasGetter = $numAttributes > 0 + || $dataNode->extendedAttributes->{"GenerateConstructor"} + || $dataNode->extendedAttributes->{"HasIndexGetter"} + || $dataNode->extendedAttributes->{"HasCustomIndexGetter"} + || $dataNode->extendedAttributes->{"CustomGetOwnPropertySlot"} + || $dataNode->extendedAttributes->{"HasNameGetter"} + || $dataNode->extendedAttributes->{"HasOverridingNameGetter"}; + # Getters - if ($numAttributes > 0 || $dataNode->extendedAttributes->{"GenerateConstructor"}) { - push(@headerContent, " virtual bool getOwnPropertySlot(KJS::ExecState*, const KJS::Identifier&, KJS::PropertySlot&);\n"); - push(@headerContent, " KJS::JSValue* getValueProperty(KJS::ExecState*, int token) const;\n"); - push(@headerContent, " bool customGetOwnPropertySlot(KJS::ExecState*, const KJS::Identifier&, KJS::PropertySlot&);\n") if $dataNode->extendedAttributes->{"CustomGetOwnPropertySlot"}; + if ($hasGetter) { + push(@headerContent, " virtual bool getOwnPropertySlot(JSC::ExecState*, const JSC::Identifier& propertyName, JSC::PropertySlot&);\n"); + push(@headerContent, " virtual bool getOwnPropertySlot(JSC::ExecState*, unsigned propertyName, JSC::PropertySlot&);\n") if ($dataNode->extendedAttributes->{"HasIndexGetter"} || $dataNode->extendedAttributes->{"HasCustomIndexGetter"}) && !$dataNode->extendedAttributes->{"HasOverridingNameGetter"}; + push(@headerContent, " bool customGetOwnPropertySlot(JSC::ExecState*, const JSC::Identifier&, JSC::PropertySlot&);\n") if $dataNode->extendedAttributes->{"CustomGetOwnPropertySlot"}; } # Check if we have any writable properties @@ -345,89 +465,97 @@ sub GenerateHeader } } - push(@headerContent, " virtual void put(KJS::ExecState*, const KJS::Identifier&, KJS::JSValue*, int attr = KJS::None);\n") if ($hasReadWriteProperties || $dataNode->extendedAttributes->{"CustomPutFunction"}); - push(@headerContent, " void putValueProperty(KJS::ExecState*, int, KJS::JSValue*, int attr);\n") if $hasReadWriteProperties; - push(@headerContent, " bool customPut(KJS::ExecState*, const KJS::Identifier&, KJS::JSValue*, int attr);\n") if $dataNode->extendedAttributes->{"CustomPutFunction"}; + my $hasSetter = $hasReadWriteProperties + || $dataNode->extendedAttributes->{"CustomPutFunction"} + || $dataNode->extendedAttributes->{"HasCustomIndexSetter"}; + + # Getters + if ($hasSetter) { + push(@headerContent, " virtual void put(JSC::ExecState*, const JSC::Identifier& propertyName, JSC::JSValue*, JSC::PutPropertySlot&);\n"); + push(@headerContent, " virtual void put(JSC::ExecState*, unsigned propertyName, JSC::JSValue*);\n") if $dataNode->extendedAttributes->{"HasCustomIndexSetter"}; + push(@headerContent, " bool customPut(JSC::ExecState*, const JSC::Identifier&, JSC::JSValue*, JSC::PutPropertySlot&);\n") if $dataNode->extendedAttributes->{"CustomPutFunction"}; + } # Class info - push(@headerContent, " virtual const KJS::ClassInfo* classInfo() const { return &info; }\n"); - push(@headerContent, " static const KJS::ClassInfo info;\n\n"); + push(@headerContent, " virtual const JSC::ClassInfo* classInfo() const { return &s_info; }\n"); + push(@headerContent, " static const JSC::ClassInfo s_info;\n\n"); + + # Structure ID + if ($interfaceName eq "DOMWindow") { + push(@headerContent, + " static PassRefPtr<JSC::StructureID> createStructureID(JSC::JSValue* prototype)\n" . + " {\n" . + " return JSC::StructureID::create(prototype, JSC::TypeInfo(JSC::ObjectType, JSC::ImplementsHasInstance | JSC::NeedsThisConversion));\n" . + " }\n\n"); + } elsif ($hasGetter) { + push(@headerContent, + " static PassRefPtr<JSC::StructureID> createStructureID(JSC::JSValue* prototype)\n" . + " {\n" . + " return JSC::StructureID::create(prototype, JSC::TypeInfo(JSC::ObjectType));\n" . + " }\n\n"); + } # Custom mark function push(@headerContent, " virtual void mark();\n\n") if $dataNode->extendedAttributes->{"CustomMarkFunction"}; # Custom pushEventHandlerScope function - push(@headerContent, " virtual void pushEventHandlerScope(KJS::ExecState*, KJS::ScopeChain&) const;\n\n") if $dataNode->extendedAttributes->{"CustomPushEventHandlerScope"}; + push(@headerContent, " virtual void pushEventHandlerScope(JSC::ExecState*, JSC::ScopeChain&) const;\n\n") if $dataNode->extendedAttributes->{"CustomPushEventHandlerScope"}; # Custom call functions - if ($dataNode->extendedAttributes->{"CustomCall"}) { - push(@headerContent, " virtual KJS::JSValue* callAsFunction(KJS::ExecState*, KJS::JSObject*, const KJS::List&);\n"); - push(@headerContent, " virtual bool implementsCall() const;\n\n"); - } + push(@headerContent, " virtual JSC::CallType getCallData(JSC::CallData&);\n\n") if $dataNode->extendedAttributes->{"CustomCall"}; # Custom deleteProperty function - push(@headerContent, " virtual bool deleteProperty(KJS::ExecState*, const KJS::Identifier&);\n") if $dataNode->extendedAttributes->{"CustomDeleteProperty"}; + push(@headerContent, " virtual bool deleteProperty(JSC::ExecState*, const JSC::Identifier&);\n") if $dataNode->extendedAttributes->{"CustomDeleteProperty"}; # Custom getPropertyNames function - push(@headerContent, " virtual void getPropertyNames(KJS::ExecState*, KJS::PropertyNameArray&);\n") if ($dataNode->extendedAttributes->{"CustomGetPropertyNames"} || $dataNode->extendedAttributes->{"HasIndexGetter"}); - push(@headerContent, " bool customGetPropertyNames(KJS::ExecState*, KJS::PropertyNameArray&);\n") if $dataNode->extendedAttributes->{"CustomGetPropertyNames"}; + push(@headerContent, " virtual void getPropertyNames(JSC::ExecState*, JSC::PropertyNameArray&);\n") if ($dataNode->extendedAttributes->{"CustomGetPropertyNames"} || $dataNode->extendedAttributes->{"HasIndexGetter"} || $dataNode->extendedAttributes->{"HasCustomIndexGetter"}); + push(@headerContent, " bool customGetPropertyNames(JSC::ExecState*, JSC::PropertyNameArray&);\n") if $dataNode->extendedAttributes->{"CustomGetPropertyNames"}; + + # Custom getPropertyAttributes function + push(@headerContent, " virtual bool getPropertyAttributes(JSC::ExecState*, const JSC::Identifier&, unsigned& attributes) const;\n") if $dataNode->extendedAttributes->{"CustomGetPropertyAttributes"}; + + # Custom defineGetter function + push(@headerContent, " virtual void defineGetter(JSC::ExecState*, const JSC::Identifier& propertyName, JSC::JSObject* getterFunction);\n") if $dataNode->extendedAttributes->{"CustomDefineGetter"}; + + # Custom defineSetter function + push(@headerContent, " virtual void defineSetter(JSC::ExecState*, const JSC::Identifier& propertyName, JSC::JSObject* setterFunction);\n") if $dataNode->extendedAttributes->{"CustomDefineSetter"}; + + # Custom lookupGetter function + push(@headerContent, " virtual JSC::JSValue* lookupGetter(JSC::ExecState*, const JSC::Identifier& propertyName);\n") if $dataNode->extendedAttributes->{"CustomLookupGetter"}; + + # Custom lookupSetter function + push(@headerContent, " virtual JSC::JSValue* lookupSetter(JSC::ExecState*, const JSC::Identifier& propertyName);\n") if $dataNode->extendedAttributes->{"CustomLookupSetter"}; # Constructor object getter - push(@headerContent, " static KJS::JSValue* getConstructor(KJS::ExecState*);\n") if $dataNode->extendedAttributes->{"GenerateConstructor"}; + push(@headerContent, " static JSC::JSValue* getConstructor(JSC::ExecState*);\n") if $dataNode->extendedAttributes->{"GenerateConstructor"}; my $numCustomFunctions = 0; my $numCustomAttributes = 0; # Attribute and function enums - my $hasAttrEnum = ($numAttributes > 0) || $dataNode->extendedAttributes->{"GenerateConstructor"}; - push(@headerContent, " enum {\n") if ($hasAttrEnum); - if ($numAttributes > 0) { - push(@headerContent, " // Attributes\n "); - - my $i = -1; foreach (@{$dataNode->attributes}) { my $attribute = $_; - $numCustomAttributes++ if $attribute->signature->extendedAttributes->{"Custom"}; $numCustomAttributes++ if $attribute->signature->extendedAttributes->{"CustomGetter"}; $numCustomAttributes++ if $attribute->signature->extendedAttributes->{"CustomSetter"}; - - $i++; - if ((($i % 4) eq 0) and ($i ne 0)) { - push(@headerContent, "\n "); - } - - my $value = $codeGenerator->WK_ucfirst($attribute->signature->name) - . ($attribute->signature->type =~ /Constructor$/ ? "Constructor" : "") - . "AttrNum"; - $value .= ", " if (($i < $numAttributes - 1) or (($i eq $numAttributes - 1) and (($numFunctions ne 0) or $dataNode->extendedAttributes->{"GenerateConstructor"}))); - push(@headerContent, $value); } } - if ($dataNode->extendedAttributes->{"GenerateConstructor"}) { - push(@headerContent, "\n\n") if $numAttributes > 0; - push(@headerContent, " // The Constructor Attribute\n"); - push(@headerContent, " ConstructorAttrNum"); - } - - push(@headerContent, "\n };\n") if ($hasAttrEnum); - if ($numCustomAttributes > 0) { push(@headerContent, "\n // Custom attributes\n"); foreach my $attribute (@{$dataNode->attributes}) { if ($attribute->signature->extendedAttributes->{"Custom"}) { - push(@headerContent, " KJS::JSValue* " . $codeGenerator->WK_lcfirst($attribute->signature->name) . "(KJS::ExecState*) const;\n"); + push(@headerContent, " JSC::JSValue* " . $codeGenerator->WK_lcfirst($attribute->signature->name) . "(JSC::ExecState*) const;\n"); if ($attribute->type !~ /^readonly/) { - push(@headerContent, " void set" . $codeGenerator->WK_ucfirst($attribute->signature->name) . "(KJS::ExecState*, KJS::JSValue*);\n"); + push(@headerContent, " void set" . $codeGenerator->WK_ucfirst($attribute->signature->name) . "(JSC::ExecState*, JSC::JSValue*);\n"); } } elsif ($attribute->signature->extendedAttributes->{"CustomGetter"}) { - push(@headerContent, " KJS::JSValue* " . $codeGenerator->WK_lcfirst($attribute->signature->name) . "(KJS::ExecState*) const;\n"); + push(@headerContent, " JSC::JSValue* " . $codeGenerator->WK_lcfirst($attribute->signature->name) . "(JSC::ExecState*) const;\n"); } elsif ($attribute->signature->extendedAttributes->{"CustomSetter"}) { if ($attribute->type !~ /^readonly/) { - push(@headerContent, " void set" . $codeGenerator->WK_ucfirst($attribute->signature->name) . "(KJS::ExecState*, KJS::JSValue*);\n"); + push(@headerContent, " void set" . $codeGenerator->WK_ucfirst($attribute->signature->name) . "(JSC::ExecState*, JSC::JSValue*);\n"); } } } @@ -441,16 +569,12 @@ sub GenerateHeader push(@headerContent, "\n // Custom functions\n"); foreach my $function (@{$dataNode->functions}) { if ($function->signature->extendedAttributes->{"Custom"}) { - push(@headerContent, " KJS::JSValue* " . $codeGenerator->WK_lcfirst($function->signature->name) . "(KJS::ExecState*, const KJS::List&);\n"); + my $functionImplementationName = $function->signature->extendedAttributes->{"ImplementationFunction"} || $codeGenerator->WK_lcfirst($function->signature->name); + push(@headerContent, " JSC::JSValue* " . $functionImplementationName . "(JSC::ExecState*, const JSC::ArgList&);\n"); } } } - # Index setter - if ($dataNode->extendedAttributes->{"HasCustomIndexSetter"}) { - push(@headerContent, " void indexSetter(KJS::ExecState*, unsigned index, KJS::JSValue*, int attr);\n"); - } - if (!$hasParent) { if ($podType) { push(@headerContent, " JSSVGPODTypeWrapper<$podType>* impl() const { return m_impl.get(); }\n"); @@ -470,69 +594,87 @@ sub GenerateHeader push(@headerContent, " RefPtr<$implClassName> m_impl;\n"); } } elsif ($dataNode->extendedAttributes->{"GenerateNativeConverter"}) { - push(@headerContent, " $implClassName* impl() const;\n"); + push(@headerContent, " $implClassName* impl() const\n"); + push(@headerContent, " {\n"); + push(@headerContent, " return static_cast<$implClassName*>(Base::impl());\n"); + push(@headerContent, " }\n"); } # Index getter if ($dataNode->extendedAttributes->{"HasIndexGetter"}) { - push(@headerContent, "private:\n"); - push(@headerContent, " static KJS::JSValue* indexGetter(KJS::ExecState*, KJS::JSObject*, const KJS::Identifier&, const KJS::PropertySlot&);\n"); + push(@headerContent, " static JSC::JSValue* indexGetter(JSC::ExecState*, const JSC::Identifier&, const JSC::PropertySlot&);\n"); + } + if ($dataNode->extendedAttributes->{"HasCustomIndexGetter"}) { + push(@headerContent, " JSC::JSValue* getByIndex(JSC::ExecState*, unsigned index);\n"); + } + + # Index setter + if ($dataNode->extendedAttributes->{"HasCustomIndexSetter"}) { + push(@headerContent, " void indexSetter(JSC::ExecState*, unsigned index, JSC::JSValue*);\n"); } # Name getter if ($dataNode->extendedAttributes->{"HasNameGetter"} || $dataNode->extendedAttributes->{"HasOverridingNameGetter"}) { push(@headerContent, "private:\n"); - push(@headerContent, " static bool canGetItemsForName(KJS::ExecState*, $implClassName*, const KJS::Identifier&);\n"); - push(@headerContent, " static KJS::JSValue* nameGetter(KJS::ExecState*, KJS::JSObject*, const KJS::Identifier&, const KJS::PropertySlot&);\n"); + push(@headerContent, " static bool canGetItemsForName(JSC::ExecState*, $implClassName*, const JSC::Identifier&);\n"); + push(@headerContent, " static JSC::JSValue* nameGetter(JSC::ExecState*, const JSC::Identifier&, const JSC::PropertySlot&);\n"); } push(@headerContent, "};\n\n"); + if ($dataNode->extendedAttributes->{"InlineGetOwnPropertySlot"}) { + push(@headerContent, "ALWAYS_INLINE bool ${className}::getOwnPropertySlot(JSC::ExecState* exec, const JSC::Identifier& propertyName, JSC::PropertySlot& slot)\n"); + push(@headerContent, "{\n"); + push(@headerContent, GenerateGetOwnPropertySlotBody($dataNode, $interfaceName, $className, $implClassName, $numAttributes > 0, 1)); + push(@headerContent, "}\n\n"); + } + if (!$hasParent || $dataNode->extendedAttributes->{"GenerateToJS"}) { if ($podType) { - push(@headerContent, "KJS::JSValue* toJS(KJS::ExecState*, JSSVGPODTypeWrapper<$podType>*, SVGElement* context);\n"); + push(@headerContent, "JSC::JSValue* toJS(JSC::ExecState*, JSSVGPODTypeWrapper<$podType>*, SVGElement* context);\n"); } elsif (IsSVGTypeNeedingContextParameter($implClassName)) { - push(@headerContent, "KJS::JSValue* toJS(KJS::ExecState*, $passType, SVGElement* context);\n"); - } elsif ($interfaceName eq "Node") { - push(@headerContent, "KJS::JSValue* toJS(KJS::ExecState*, PassRefPtr<Node>);\n"); + push(@headerContent, "JSC::JSValue* toJS(JSC::ExecState*, $implType*, SVGElement* context);\n"); } else { - push(@headerContent, "KJS::JSValue* toJS(KJS::ExecState*, $passType);\n"); + push(@headerContent, "JSC::JSValue* toJS(JSC::ExecState*, $implType*);\n"); + } + + # Resolve ambiguity with EventTarget that otherwise exists. + if ($interfaceName eq "Node") { + push(@headerContent, "inline JSC::JSValue* toJS(JSC::ExecState* exec, EventTargetNode* node) { return toJS(exec, static_cast<Node*>(node)); }\n"); } } if (!$hasParent || $dataNode->extendedAttributes->{"GenerateNativeConverter"}) { if ($podType) { - push(@headerContent, "$podType to${interfaceName}(KJS::JSValue*);\n"); + push(@headerContent, "$podType to${interfaceName}(JSC::JSValue*);\n"); + } elsif ($interfaceName eq "NodeFilter") { + push(@headerContent, "PassRefPtr<NodeFilter> toNodeFilter(JSC::JSValue*);\n"); } else { - push(@headerContent, "$implClassName* to${interfaceName}(KJS::JSValue*);\n"); + push(@headerContent, "$implClassName* to${interfaceName}(JSC::JSValue*);\n"); + } + if ($interfaceName eq "Node" or $interfaceName eq "Element" or $interfaceName eq "Text") { + push(@headerContent, "JSC::JSValue* toJSNewlyCreated(JSC::ExecState*, $interfaceName*);\n"); } } push(@headerContent, "\n"); - # Add prototype declaration -- code adopted from the KJS_DEFINE_PROTOTYPE and KJS_DEFINE_PROTOTYPE_WITH_PROTOTYPE macros - push(@headerContent, "class ${className}Prototype : public KJS::JSObject {\n"); + # Add prototype declaration. + push(@headerContent, "class ${className}Prototype : public JSC::JSObject {\n"); push(@headerContent, "public:\n"); - if ($dataNode->extendedAttributes->{"DoNotCache"}) { - push(@headerContent, " static KJS::JSObject* self();\n"); + if ($interfaceName eq "DOMWindow") { + push(@headerContent, " void* operator new(size_t);\n"); } else { - push(@headerContent, " static KJS::JSObject* self(KJS::ExecState* exec);\n"); + push(@headerContent, " static JSC::JSObject* self(JSC::ExecState*);\n"); } - push(@headerContent, " virtual const KJS::ClassInfo* classInfo() const { return &info; }\n"); - push(@headerContent, " static const KJS::ClassInfo info;\n"); + push(@headerContent, " virtual const JSC::ClassInfo* classInfo() const { return &s_info; }\n"); + push(@headerContent, " static const JSC::ClassInfo s_info;\n"); if ($numFunctions > 0 || $numConstants > 0) { - push(@headerContent, " bool getOwnPropertySlot(KJS::ExecState*, const KJS::Identifier&, KJS::PropertySlot&);\n"); - } - if ($numConstants ne 0) { - push(@headerContent, " KJS::JSValue* getValueProperty(KJS::ExecState*, int token) const;\n"); - } - if ($dataNode->extendedAttributes->{"DoNotCache"}) { - push(@headerContent, " ${className}Prototype() { }\n"); - } else { - push(@headerContent, " ${className}Prototype(KJS::ExecState* exec)\n"); - if ($hasParent && $parentClassName ne "KJS::DOMNodeFilter") { - push(@headerContent, " : KJS::JSObject(${parentClassName}Prototype::self(exec)) { }\n"); - } else { - push(@headerContent, " : KJS::JSObject(exec->lexicalGlobalObject()->objectPrototype()) { }\n"); - } + push(@headerContent, " virtual bool getOwnPropertySlot(JSC::ExecState*, const JSC::Identifier&, JSC::PropertySlot&);\n"); + push(@headerContent, + " static PassRefPtr<JSC::StructureID> createStructureID(JSC::JSValue* prototype)\n" . + " {\n" . + " return JSC::StructureID::create(prototype, JSC::TypeInfo(JSC::ObjectType));\n" . + " }\n"); } + push(@headerContent, " ${className}Prototype(PassRefPtr<JSC::StructureID> structure) : JSC::JSObject(structure) { }\n"); push(@headerContent, "};\n\n"); @@ -540,11 +682,36 @@ sub GenerateHeader push(@headerContent,"// Functions\n\n"); foreach my $function (@{$dataNode->functions}) { my $functionName = $codeGenerator->WK_lcfirst($className) . "PrototypeFunction" . $codeGenerator->WK_ucfirst($function->signature->name); - push(@headerContent, "KJS::JSValue* ${functionName}(KJS::ExecState*, KJS::JSObject*, const KJS::List&);\n"); + push(@headerContent, "JSC::JSValue* ${functionName}(JSC::ExecState*, JSC::JSObject*, JSC::JSValue*, const JSC::ArgList&);\n"); + } + } + + if ($numAttributes > 0 || $dataNode->extendedAttributes->{"GenerateConstructor"}) { + push(@headerContent,"// Attributes\n\n"); + foreach my $attribute (@{$dataNode->attributes}) { + my $getter = "js" . $interfaceName . $codeGenerator->WK_ucfirst($attribute->signature->name) . ($attribute->signature->type =~ /Constructor$/ ? "Constructor" : ""); + push(@headerContent, "JSC::JSValue* ${getter}(JSC::ExecState*, const JSC::Identifier&, const JSC::PropertySlot&);\n"); + unless ($attribute->type =~ /readonly/) { + my $setter = "setJS" . $interfaceName . $codeGenerator->WK_ucfirst($attribute->signature->name) . ($attribute->signature->type =~ /Constructor$/ ? "Constructor" : ""); + push(@headerContent, "void ${setter}(JSC::ExecState*, JSC::JSObject*, JSC::JSValue*);\n"); + } + } + + if ($dataNode->extendedAttributes->{"GenerateConstructor"}) { + my $getter = "js" . $interfaceName . "Constructor"; + push(@headerContent, "JSC::JSValue* ${getter}(JSC::ExecState*, const JSC::Identifier&, const JSC::PropertySlot&);\n"); + } + } + + if ($numConstants > 0) { + push(@headerContent,"// Constants\n\n"); + foreach my $constant (@{$dataNode->constants}) { + my $getter = "js" . $interfaceName . $codeGenerator->WK_ucfirst($constant->name); + push(@headerContent, "JSC::JSValue* ${getter}(JSC::ExecState*, const JSC::Identifier&, const JSC::PropertySlot&);\n"); } } - push(@headerContent, "} // namespace WebCore\n\n"); + push(@headerContent, "\n} // namespace WebCore\n\n"); push(@headerContent, "#endif // ${conditionalString}\n\n") if $conditional; push(@headerContent, "#endif\n"); } @@ -574,11 +741,7 @@ sub GenerateImplementation } if ($className =~ /^JSSVG/) { - push(@implContentHeader, "#include \"Document.h\"\n"); - push(@implContentHeader, "#include \"Frame.h\"\n"); - push(@implContentHeader, "#include \"SVGDocumentExtensions.h\"\n"); push(@implContentHeader, "#include \"SVGElement.h\"\n"); - push(@implContentHeader, "#include \"SVGAnimatedTemplate.h\"\n"); if ($className =~ /^JSSVGAnimated/) { AddIncludesForSVGAnimatedType($interfaceName); @@ -588,37 +751,35 @@ sub GenerateImplementation push(@implContentHeader, "#include \"$className.h\"\n\n"); push(@implContentHeader, "#include <wtf/GetPtr.h>\n\n"); - push(@implContentHeader, "#include <kjs/PropertyNameArray.h>\n") if $dataNode->extendedAttributes->{"HasIndexGetter"}; + push(@implContentHeader, "#include <runtime/PropertyNameArray.h>\n") if $dataNode->extendedAttributes->{"HasIndexGetter"} || $dataNode->extendedAttributes->{"HasCustomIndexGetter"}; AddIncludesForType($interfaceName); @implContent = (); - push(@implContent, "\nusing namespace KJS;\n\n"); + push(@implContent, "\nusing namespace JSC;\n\n"); push(@implContent, "namespace WebCore {\n\n"); + push(@implContent, "ASSERT_CLASS_FITS_IN_CELL($className)\n\n"); + # - Add all attributes in a hashtable definition my $numAttributes = @{$dataNode->attributes}; $numAttributes++ if $dataNode->extendedAttributes->{"GenerateConstructor"}; if ($numAttributes > 0) { - my $hashSize = $numAttributes; my $hashName = $className . "Table"; - my @hashKeys = (); # ie. 'insertBefore' - my @hashValues = (); # ie. 'JSNode::InsertBefore' - my @hashSpecials = (); # ie. 'DontDelete|Function' - my @hashParameters = (); # ie. '2' + my @hashKeys = (); + my @hashSpecials = (); + my @hashValue1 = (); + my @hashValue2 = (); + + my @entries = (); foreach my $attribute (@{$dataNode->attributes}) { my $name = $attribute->signature->name; push(@hashKeys, $name); - my $value = $className . "::" . $codeGenerator->WK_ucfirst($attribute->signature->name) - . ($attribute->signature->type =~ /Constructor$/ ? "Constructor" : "") - . "AttrNum"; - push(@hashValues, $value); - my @specials = (); push(@specials, "DontDelete") unless $attribute->signature->extendedAttributes->{"Deletable"}; push(@specials, "DontEnum") if $attribute->signature->extendedAttributes->{"DontEnum"}; @@ -626,20 +787,28 @@ sub GenerateImplementation my $special = (@specials > 0) ? join("|", @specials) : "0"; push(@hashSpecials, $special); - my $numParameters = "0"; - push(@hashParameters, $numParameters); + my $getter = "js" . $interfaceName . $codeGenerator->WK_ucfirst($attribute->signature->name) . ($attribute->signature->type =~ /Constructor$/ ? "Constructor" : ""); + push(@hashValue1, $getter); + + if ($attribute->type =~ /readonly/) { + push(@hashValue2, "0"); + } else { + my $setter = "setJS" . $interfaceName . $codeGenerator->WK_ucfirst($attribute->signature->name) . ($attribute->signature->type =~ /Constructor$/ ? "Constructor" : ""); + push(@hashValue2, $setter); + } } if ($dataNode->extendedAttributes->{"GenerateConstructor"}) { push(@hashKeys, "constructor"); - push(@hashValues, $className . "::ConstructorAttrNum"); - push(@hashSpecials, "DontDelete|DontEnum|ReadOnly"); - push(@hashParameters, "0"); + my $getter = "js" . $interfaceName . "Constructor"; + push(@hashValue1, $getter); + push(@hashValue2, "0"); + push(@hashSpecials, "DontEnum|ReadOnly"); # FIXME: Setting the constructor should be possible. } - $object->GenerateHashTable($hashName, $hashSize, - \@hashKeys, \@hashValues, - \@hashSpecials, \@hashParameters); + $object->GenerateHashTable($hashName, + \@hashKeys, \@hashSpecials, + \@hashValue1, \@hashValue2); } my $numConstants = @{$dataNode->constants}; @@ -647,31 +816,25 @@ sub GenerateImplementation # - Add all constants if ($dataNode->extendedAttributes->{"GenerateConstructor"}) { - $hashSize = $numConstants; $hashName = $className . "ConstructorTable"; @hashKeys = (); - @hashValues = (); + @hashValue1 = (); + @hashValue2 = (); @hashSpecials = (); - @hashParameters = (); + # FIXME: we should not need a function for every constant. foreach my $constant (@{$dataNode->constants}) { - my $name = $constant->name; - push(@hashKeys, $name); - - my $value = $constant->value; - push(@hashValues, $value); - - my $special = "DontDelete|ReadOnly"; - push(@hashSpecials, $special); - - my $numParameters = 0; - push(@hashParameters, $numParameters); + push(@hashKeys, $constant->name); + my $getter = "js" . $interfaceName . $codeGenerator->WK_ucfirst($constant->name); + push(@hashValue1, $getter); + push(@hashValue2, "0"); + push(@hashSpecials, "DontDelete|ReadOnly"); } - $object->GenerateHashTable($hashName, $hashSize, - \@hashKeys, \@hashValues, - \@hashSpecials, \@hashParameters); + $object->GenerateHashTable($hashName, + \@hashKeys, \@hashSpecials, + \@hashValue1, \@hashValue2); my $protoClassName; $protoClassName = "${className}Prototype"; @@ -680,26 +843,20 @@ sub GenerateImplementation } # - Add functions and constants to a hashtable definition - $hashSize = $numFunctions + $numConstants; $hashName = $className . "PrototypeTable"; @hashKeys = (); - @hashValues = (); + @hashValue1 = (); + @hashValue2 = (); @hashSpecials = (); - @hashParameters = (); + # FIXME: we should not need a function for every constant. foreach my $constant (@{$dataNode->constants}) { - my $name = $constant->name; - push(@hashKeys, $name); - - my $value = $constant->value; - push(@hashValues, $value); - - my $special = "DontDelete|ReadOnly"; - push(@hashSpecials, $special); - - my $numParameters = 0; - push(@hashParameters, $numParameters); + push(@hashKeys, $constant->name); + my $getter = "js" . $interfaceName . $codeGenerator->WK_ucfirst($constant->name); + push(@hashValue1, $getter); + push(@hashValue2, "0"); + push(@hashSpecials, "DontDelete|ReadOnly"); } foreach my $function (@{$dataNode->functions}) { @@ -707,7 +864,10 @@ sub GenerateImplementation push(@hashKeys, $name); my $value = $codeGenerator->WK_lcfirst($className) . "PrototypeFunction" . $codeGenerator->WK_ucfirst($name); - push(@hashValues, $value); + push(@hashValue1, $value); + + my $numParameters = @{$function->parameters}; + push(@hashValue2, $numParameters); my @specials = (); push(@specials, "DontDelete") unless $function->signature->extendedAttributes->{"Deletable"}; @@ -715,81 +875,93 @@ sub GenerateImplementation push(@specials, "Function"); my $special = (@specials > 0) ? join("|", @specials) : "0"; push(@hashSpecials, $special); - - my $numParameters = @{$function->parameters}; - push(@hashParameters, $numParameters); } - $object->GenerateHashTable($hashName, $hashSize, - \@hashKeys, \@hashValues, - \@hashSpecials, \@hashParameters); + $object->GenerateHashTable($hashName, + \@hashKeys, \@hashSpecials, + \@hashValue1, \@hashValue2); - push(@implContent, "const ClassInfo ${className}Prototype::info = { \"${visibleClassName}Prototype\", 0, &${className}PrototypeTable };\n\n"); - if ($dataNode->extendedAttributes->{"DoNotCache"}) { - push(@implContent, "JSObject* ${className}Prototype::self()\n"); + if ($dataNode->extendedAttributes->{"NoStaticTables"}) { + push(@implContent, "static const HashTable* get${className}PrototypeTable(ExecState* exec)\n"); push(@implContent, "{\n"); - push(@implContent, " return new ${className}Prototype();\n"); - push(@implContent, "}\n\n"); + push(@implContent, " return getHashTableForGlobalData(exec->globalData(), &${className}PrototypeTable);\n"); + push(@implContent, "}\n"); + push(@implContent, "const ClassInfo ${className}Prototype::s_info = { \"${visibleClassName}Prototype\", 0, 0, get${className}PrototypeTable };\n\n"); } else { + push(@implContent, "const ClassInfo ${className}Prototype::s_info = { \"${visibleClassName}Prototype\", 0, &${className}PrototypeTable, 0 };\n\n"); + } + if ($interfaceName ne "DOMWindow") { push(@implContent, "JSObject* ${className}Prototype::self(ExecState* exec)\n"); push(@implContent, "{\n"); - push(@implContent, " return KJS::cacheGlobalObject<${className}Prototype>(exec, \"[[${className}.prototype]]\");\n"); + push(@implContent, " return getDOMPrototype<${className}>(exec);\n"); + push(@implContent, "}\n\n"); + } + if ($interfaceName eq "DOMWindow") { + push(@implContent, "void* ${className}Prototype::operator new(size_t size)\n"); + push(@implContent, "{\n"); + push(@implContent, " return JSDOMWindow::commonJSGlobalData()->heap.allocate(size);\n"); push(@implContent, "}\n\n"); } if ($numConstants > 0 || $numFunctions > 0) { push(@implContent, "bool ${className}Prototype::getOwnPropertySlot(ExecState* exec, const Identifier& propertyName, PropertySlot& slot)\n"); push(@implContent, "{\n"); if ($numConstants eq 0) { - push(@implContent, " return getStaticFunctionSlot<JSObject>(exec, &${className}PrototypeTable, this, propertyName, slot);\n"); + push(@implContent, " return getStaticFunctionSlot<JSObject>(exec, " . prototypeHashTableAccessor($dataNode->extendedAttributes->{"NoStaticTables"}, $className) . ", this, propertyName, slot);\n"); } elsif ($numFunctions eq 0) { - push(@implContent, " return getStaticValueSlot<${className}Prototype, JSObject>(exec, &${className}PrototypeTable, this, propertyName, slot);\n"); + push(@implContent, " return getStaticValueSlot<${className}Prototype, JSObject>(exec, " . prototypeHashTableAccessor($dataNode->extendedAttributes->{"NoStaticTables"}, $className) . ", this, propertyName, slot);\n"); } else { - push(@implContent, " return getStaticPropertySlot<${className}Prototype, JSObject>(exec, &${className}PrototypeTable, this, propertyName, slot);\n"); + push(@implContent, " return getStaticPropertySlot<${className}Prototype, JSObject>(exec, " . prototypeHashTableAccessor($dataNode->extendedAttributes->{"NoStaticTables"}, $className) . ", this, propertyName, slot);\n"); } push(@implContent, "}\n\n"); } - if ($numConstants ne 0) { - push(@implContent, "JSValue* ${className}Prototype::getValueProperty(ExecState*, int token) const\n{\n"); - push(@implContent, " // The token is the numeric value of its associated constant\n"); - push(@implContent, " return jsNumber(token);\n}\n\n"); - } # - Initialize static ClassInfo object - push(@implContent, "const ClassInfo $className" . "::info = { \"${visibleClassName}\", "); + if ($numAttributes > 0 && $dataNode->extendedAttributes->{"NoStaticTables"}) { + push(@implContent, "static const HashTable* get${className}Table(ExecState* exec)\n"); + push(@implContent, "{\n"); + push(@implContent, " return getHashTableForGlobalData(exec->globalData(), &${className}Table);\n"); + push(@implContent, "}\n"); + } + push(@implContent, "const ClassInfo $className" . "::s_info = { \"${visibleClassName}\", "); if ($hasParent) { - push(@implContent, "&" . $parentClassName . "::info, "); + push(@implContent, "&" . $parentClassName . "::s_info, "); } else { push(@implContent, "0, "); } - if ($numAttributes > 0) { - push(@implContent, "&${className}Table "); + if ($numAttributes > 0 && !$dataNode->extendedAttributes->{"NoStaticTables"}) { + push(@implContent, "&${className}Table"); + } else { + push(@implContent, "0"); + } + if ($numAttributes > 0 && $dataNode->extendedAttributes->{"NoStaticTables"}) { + push(@implContent, ", get${className}Table "); } else { - push(@implContent, "0 ") + push(@implContent, ", 0 "); } push(@implContent, "};\n\n"); # Get correct pass/store types respecting PODType flag my $podType = $dataNode->extendedAttributes->{"PODType"}; - my $passType = $podType ? "JSSVGPODTypeWrapper<$podType>*" : "$implClassName*"; + my $implType = $podType ? "JSSVGPODTypeWrapper<$podType> " : $implClassName; my $needsSVGContext = IsSVGTypeNeedingContextParameter($implClassName); my $parentNeedsSVGContext = ($needsSVGContext and $parentClassName =~ /SVG/); # Constructor - if ($dataNode->extendedAttributes->{"DoNotCache"}) { - push(@implContent, "${className}::$className($passType impl)\n"); - push(@implContent, " : $parentClassName(${className}Prototype::self(), impl)\n"); + if ($interfaceName eq "DOMWindow") { + AddIncludesForType("JSDOMWindowShell"); + push(@implContent, "${className}::$className(PassRefPtr<StructureID> structure, PassRefPtr<$implType> impl, JSDOMWindowShell* shell)\n"); + push(@implContent, " : $parentClassName(structure, impl, shell)\n"); } else { - push(@implContent, "${className}::$className(JSObject* prototype, $passType impl" . ($needsSVGContext ? ", SVGElement* context" : "") . ")\n"); + push(@implContent, "${className}::$className(PassRefPtr<StructureID> structure, PassRefPtr<$implType> impl" . ($needsSVGContext ? ", SVGElement* context" : "") . ")\n"); if ($hasParent) { - push(@implContent, " : $parentClassName(prototype, impl" . ($parentNeedsSVGContext ? ", context" : "") . ")\n"); + push(@implContent, " : $parentClassName(structure, impl" . ($parentNeedsSVGContext ? ", context" : "") . ")\n"); } else { - push(@implContent, " : $parentClassName(prototype)\n"); + push(@implContent, " : $parentClassName(structure)\n"); push(@implContent, " , m_context(context)\n") if $needsSVGContext; push(@implContent, " , m_impl(impl)\n"); } - } push(@implContent, "{\n"); push(@implContent, "}\n\n"); @@ -800,7 +972,7 @@ sub GenerateImplementation push(@implContent, "{\n"); if ($interfaceName eq "Node") { - push(@implContent, " ScriptInterpreter::forgetDOMNodeForDocument(m_impl->document(), m_impl.get());\n"); + push(@implContent, " forgetDOMNode(m_impl->document(), m_impl.get());\n"); } else { if ($podType) { my $animatedType = $implClassName; @@ -808,10 +980,10 @@ sub GenerateImplementation # Special case for JSSVGNumber if ($codeGenerator->IsSVGAnimatedType($animatedType) and $podType ne "float") { - push(@implContent, " JSSVGPODTypeWrapperCache<$podType, $animatedType>::forgetWrapper(m_impl.get());\n"); + push(@implContent, " JSSVGDynamicPODTypeWrapperCache<$podType, $animatedType>::forgetWrapper(m_impl.get());\n"); } } - push(@implContent, " ScriptInterpreter::forgetDOMObject(m_impl.get());\n"); + push(@implContent, " forgetDOMObject(*Heap::heap(this)->globalData(), m_impl.get());\n"); } push(@implContent, "\n}\n\n"); @@ -821,253 +993,282 @@ sub GenerateImplementation # its own special handling rather than relying on the caching that Node normally does. if ($interfaceName eq "Document") { push(@implContent, "${className}::~$className()\n"); - push(@implContent, "{\n ScriptInterpreter::forgetDOMObject(static_cast<${implClassName}*>(impl()));\n}\n\n"); + push(@implContent, "{\n forgetDOMObject(*Heap::heap(this)->globalData(), static_cast<${implClassName}*>(impl()));\n}\n\n"); } - # Attributes - if ($numAttributes ne 0) { - push(@implContent, "bool ${className}::getOwnPropertySlot(ExecState* exec, const Identifier& propertyName, PropertySlot& slot)\n"); + if ($interfaceName ne "DOMWindow") { + push(@implContent, "JSObject* ${className}::createPrototype(ExecState* exec)\n"); push(@implContent, "{\n"); - - if ($interfaceName eq "NamedNodeMap" or $interfaceName eq "HTMLCollection") { - push(@implContent, " JSValue* proto = prototype();\n"); - push(@implContent, " if (proto->isObject() && static_cast<JSObject*>(proto)->hasProperty(exec, propertyName))\n"); - push(@implContent, " return false;\n\n"); + if ($hasParent && $parentClassName ne "JSC::DOMNodeFilter") { + push(@implContent, " return new (exec) ${className}Prototype(${className}Prototype::createStructureID(${parentClassName}Prototype::self(exec)));\n"); + } else { + push(@implContent, " return new (exec) ${className}Prototype(${className}Prototype::createStructureID(exec->lexicalGlobalObject()->objectPrototype()));\n"); } + push(@implContent, "}\n\n"); + } - my $hasNameGetterGeneration = sub { - push(@implContent, " if (canGetItemsForName(exec, static_cast<$implClassName*>(impl()), propertyName)) {\n"); - push(@implContent, " slot.setCustom(this, nameGetter);\n"); - push(@implContent, " return true;\n"); - push(@implContent, " }\n"); - $implIncludes{"AtomicString.h"} = 1; - }; - - if ($dataNode->extendedAttributes->{"HasOverridingNameGetter"}) { - &$hasNameGetterGeneration(); - } + my $hasGetter = $numAttributes > 0 + || $dataNode->extendedAttributes->{"GenerateConstructor"} + || $dataNode->extendedAttributes->{"HasIndexGetter"} + || $dataNode->extendedAttributes->{"HasCustomIndexGetter"} + || $dataNode->extendedAttributes->{"CustomGetOwnPropertySlot"} + || $dataNode->extendedAttributes->{"HasNameGetter"} + || $dataNode->extendedAttributes->{"HasOverridingNameGetter"}; - my $requiresManualLookup = $dataNode->extendedAttributes->{"HasIndexGetter"} || $dataNode->extendedAttributes->{"HasNameGetter"}; - if ($requiresManualLookup) { - push(@implContent, " const HashEntry* entry = Lookup::findEntry(&${className}Table, propertyName);\n"); - push(@implContent, " if (entry) {\n"); - push(@implContent, " slot.setStaticEntry(this, entry, staticValueGetter<$className>);\n"); - push(@implContent, " return true;\n"); - push(@implContent, " }\n"); + # Attributes + if ($hasGetter) { + if (!$dataNode->extendedAttributes->{"InlineGetOwnPropertySlot"}) { + push(@implContent, "bool ${className}::getOwnPropertySlot(ExecState* exec, const Identifier& propertyName, PropertySlot& slot)\n"); + push(@implContent, "{\n"); + push(@implContent, GenerateGetOwnPropertySlotBody($dataNode, $interfaceName, $className, $implClassName, $numAttributes > 0, 0)); + push(@implContent, "}\n\n"); } - if ($dataNode->extendedAttributes->{"HasIndexGetter"}) { - push(@implContent, " bool ok;\n"); - push(@implContent, " unsigned index = propertyName.toUInt32(&ok, false);\n"); - push(@implContent, " if (ok && index < static_cast<$implClassName*>(impl())->length()) {\n"); - push(@implContent, " slot.setCustomIndex(this, index, indexGetter);\n"); + if (($dataNode->extendedAttributes->{"HasIndexGetter"} || $dataNode->extendedAttributes->{"HasCustomIndexGetter"}) + && !$dataNode->extendedAttributes->{"HasOverridingNameGetter"}) { + push(@implContent, "bool ${className}::getOwnPropertySlot(ExecState* exec, unsigned propertyName, PropertySlot& slot)\n"); + push(@implContent, "{\n"); + push(@implContent, " if (propertyName < static_cast<$implClassName*>(impl())->length()) {\n"); + if ($dataNode->extendedAttributes->{"HasCustomIndexGetter"}) { + push(@implContent, " slot.setValue(getByIndex(exec, propertyName));\n"); + } else { + push(@implContent, " slot.setCustomIndex(this, propertyName, indexGetter);\n"); + } push(@implContent, " return true;\n"); push(@implContent, " }\n"); + push(@implContent, " return getOwnPropertySlot(exec, Identifier::from(exec, propertyName), slot);\n"); + push(@implContent, "}\n\n"); } + + if ($numAttributes > 0) { + foreach my $attribute (@{$dataNode->attributes}) { + my $name = $attribute->signature->name; + my $type = $codeGenerator->StripModule($attribute->signature->type); + my $getFunctionName = "js" . $interfaceName . $codeGenerator->WK_ucfirst($attribute->signature->name) . ($attribute->signature->type =~ /Constructor$/ ? "Constructor" : ""); + my $implGetterFunctionName = $codeGenerator->WK_lcfirst($name); + + push(@implContent, "JSValue* ${getFunctionName}(ExecState* exec, const Identifier&, const PropertySlot& slot)\n"); + push(@implContent, "{\n"); - if ($dataNode->extendedAttributes->{"HasNameGetter"}) { - &$hasNameGetterGeneration(); - } - - if ($dataNode->extendedAttributes->{"CustomGetOwnPropertySlot"}) { - push(@implContent, " if (customGetOwnPropertySlot(exec, propertyName, slot))\n"); - push(@implContent, " return true;\n"); - } - - if ($requiresManualLookup) { - push(@implContent, " return Base::getOwnPropertySlot(exec, propertyName, slot);\n"); - } else { - push(@implContent, " return getStaticValueSlot<$className, Base>(exec, &${className}Table, this, propertyName, slot);\n"); - } - push(@implContent, "}\n\n"); - - push(@implContent, "JSValue* ${className}::getValueProperty(ExecState* exec, int token) const\n{\n"); - - push(@implContent, " switch (token) {\n"); - - foreach my $attribute (@{$dataNode->attributes}) { - my $getterFunctionName = $codeGenerator->WK_lcfirst($attribute->signature->name); - - my $implClassNameForValueConversion = ""; - if (!$podType and ($codeGenerator->IsSVGAnimatedType($implClassName) or $attribute->type !~ /^readonly/)) { - $implClassNameForValueConversion = $implClassName; - } - - push(@implContent, " case " . $codeGenerator->WK_ucfirst($attribute->signature->name) - . ($attribute->signature->type =~ /Constructor$/ ? "Constructor" : "") - . "AttrNum: {\n"); + my $implClassNameForValueConversion = ""; + if (!$podType and ($codeGenerator->IsSVGAnimatedType($implClassName) or $attribute->type !~ /^readonly/)) { + $implClassNameForValueConversion = $implClassName; + } - if ($dataNode->extendedAttributes->{"CheckDomainSecurity"} && - !$attribute->signature->extendedAttributes->{"DoNotCheckDomainSecurity"} && - !$attribute->signature->extendedAttributes->{"DoNotCheckDomainSecurityOnGet"}) { - push(@implContent, " if (!allowsAccessFrom(exec))\n"); - push(@implContent, " return jsUndefined();\n"); - } + if ($dataNode->extendedAttributes->{"CheckDomainSecurity"} && + !$attribute->signature->extendedAttributes->{"DoNotCheckDomainSecurity"} && + !$attribute->signature->extendedAttributes->{"DoNotCheckDomainSecurityOnGet"}) { + push(@implContent, " if (!static_cast<$className*>(asObject(slot.slotBase()))->allowsAccessFrom(exec))\n"); + push(@implContent, " return jsUndefined();\n"); + } - if ($attribute->signature->extendedAttributes->{"Custom"} || $attribute->signature->extendedAttributes->{"CustomGetter"}) { - push(@implContent, " return $getterFunctionName(exec);\n"); - } elsif ($attribute->signature->extendedAttributes->{"CheckNodeSecurity"}) { - $implIncludes{"kjs_dom.h"} = 1; - push(@implContent, " $implClassName* imp = static_cast<$implClassName*>(impl());\n"); - push(@implContent, " return checkNodeSecurity(exec, imp->$getterFunctionName()) ? " . NativeToJSValue($attribute->signature, 0, $implClassName, $implClassNameForValueConversion, "imp->$getterFunctionName()") . " : jsUndefined();\n"); - } elsif ($attribute->signature->extendedAttributes->{"CheckFrameSecurity"}) { - $implIncludes{"Document.h"} = 1; - $implIncludes{"kjs_dom.h"} = 1; - push(@implContent, " $implClassName* imp = static_cast<$implClassName*>(impl());\n"); - push(@implContent, " return checkNodeSecurity(exec, imp->contentDocument()) ? " . NativeToJSValue($attribute->signature, 0, $implClassName, $implClassNameForValueConversion, "imp->$getterFunctionName()") . " : jsUndefined();\n"); - } elsif ($attribute->signature->type =~ /Constructor$/) { - my $constructorType = $codeGenerator->StripModule($attribute->signature->type); - $constructorType =~ s/Constructor$//; - push(@implContent, " return JS" . $constructorType . "::getConstructor(exec);\n"); - } elsif (!@{$attribute->getterExceptions}) { - if ($podType) { - push(@implContent, " $podType imp(*impl());\n"); - if ($podType eq "float") { # Special case for JSSVGNumber - push(@implContent, " return " . NativeToJSValue($attribute->signature, 0, $implClassName, "", "imp") . ";\n"); + if ($attribute->signature->extendedAttributes->{"Custom"} || $attribute->signature->extendedAttributes->{"CustomGetter"}) { + push(@implContent, " return static_cast<$className*>(asObject(slot.slotBase()))->$implGetterFunctionName(exec);\n"); + } elsif ($attribute->signature->extendedAttributes->{"CheckNodeSecurity"}) { + $implIncludes{"JSDOMBinding.h"} = 1; + push(@implContent, " $implClassName* imp = static_cast<$implClassName*>(static_cast<$className*>(asObject(slot.slotBase()))->impl());\n"); + push(@implContent, " return checkNodeSecurity(exec, imp->$implGetterFunctionName()) ? " . NativeToJSValue($attribute->signature, 0, $implClassName, $implClassNameForValueConversion, "imp->$implGetterFunctionName()", "static_cast<$className*>(asObject(slot.slotBase()))") . " : jsUndefined();\n"); + } elsif ($attribute->signature->extendedAttributes->{"CheckFrameSecurity"}) { + $implIncludes{"Document.h"} = 1; + $implIncludes{"JSDOMBinding.h"} = 1; + push(@implContent, " $implClassName* imp = static_cast<$implClassName*>(static_cast<$className*>(asObject(slot.slotBase()))->impl());\n"); + push(@implContent, " return checkNodeSecurity(exec, imp->contentDocument()) ? " . NativeToJSValue($attribute->signature, 0, $implClassName, $implClassNameForValueConversion, "imp->$implGetterFunctionName()", "static_cast<$className*>(asObject(slot.slotBase()))") . " : jsUndefined();\n"); + } elsif ($type eq "EventListener") { + $implIncludes{"JSEventListener.h"} = 1; + $implIncludes{"EventListener.h"} = 1; + my $listenerType; + if ($attribute->signature->extendedAttributes->{"ProtectedListener"}) { + $listenerType = "JSEventListener"; } else { - push(@implContent, " return " . NativeToJSValue($attribute->signature, 0, $implClassName, "", "imp.$getterFunctionName()") . ";\n"); + $listenerType = "JSUnprotectedEventListener"; + } + push(@implContent, " $implClassName* imp = static_cast<$implClassName*>(static_cast<$className*>(asObject(slot.slotBase()))->impl());\n"); + push(@implContent, " if (${listenerType}* listener = static_cast<${listenerType}*>(imp->$implGetterFunctionName())) {\n"); + push(@implContent, " if (JSObject* listenerObj = listener->listenerObj())\n"); + push(@implContent, " return listenerObj;\n"); + push(@implContent, " }\n"); + push(@implContent, " return jsNull();\n"); + } elsif ($attribute->signature->type =~ /Constructor$/) { + my $constructorType = $codeGenerator->StripModule($attribute->signature->type); + $constructorType =~ s/Constructor$//; + push(@implContent, " return JS" . $constructorType . "::getConstructor(exec);\n"); + } elsif (!@{$attribute->getterExceptions}) { + if ($podType) { + push(@implContent, " $podType imp(*static_cast<$className*>(asObject(slot.slotBase()))->impl());\n"); + if ($podType eq "float") { # Special case for JSSVGNumber + push(@implContent, " return " . NativeToJSValue($attribute->signature, 0, $implClassName, "", "imp", "static_cast<$className*>(asObject(slot.slotBase()))") . ";\n"); + } else { + push(@implContent, " return " . NativeToJSValue($attribute->signature, 0, $implClassName, "", "imp.$implGetterFunctionName()", "static_cast<$className*>(asObject(slot.slotBase()))") . ";\n"); + } + } else { + push(@implContent, " $implClassName* imp = static_cast<$implClassName*>(static_cast<$className*>(asObject(slot.slotBase()))->impl());\n"); + my $jsType = NativeToJSValue($attribute->signature, 0, $implClassName, $implClassNameForValueConversion, "imp->$implGetterFunctionName()", "static_cast<$className*>(asObject(slot.slotBase()))"); + if ($codeGenerator->IsSVGAnimatedType($type)) { + push(@implContent, " RefPtr<$type> obj = $jsType;\n"); + push(@implContent, " return toJS(exec, obj.get(), imp);\n"); + } else { + push(@implContent, " return $jsType;\n"); + } } } else { - push(@implContent, " $implClassName* imp = static_cast<$implClassName*>(impl());\n"); - my $type = $codeGenerator->StripModule($attribute->signature->type); - my $jsType = NativeToJSValue($attribute->signature, 0, $implClassName, $implClassNameForValueConversion, "imp->$getterFunctionName()"); - if ($codeGenerator->IsSVGAnimatedType($type)) { - push(@implContent, " RefPtr<$type> obj = $jsType;\n"); - push(@implContent, " return toJS(exec, obj.get(), imp);\n"); + push(@implContent, " ExceptionCode ec = 0;\n"); + + if ($podType) { + push(@implContent, " $podType imp(*static_cast<$className*>(asObject(slot.slotBase()))->impl());\n"); + push(@implContent, " JSC::JSValue* result = " . NativeToJSValue($attribute->signature, 0, $implClassName, "", "imp.$implGetterFunctionName(ec)", "static_cast<$className*>(asObject(slot.slotBase()))") . ";\n"); } else { - push(@implContent, " return $jsType;\n"); + push(@implContent, " $implClassName* imp = static_cast<$implClassName*>(static_cast<$className*>(asObject(slot.slotBase()))->impl());\n"); + push(@implContent, " JSC::JSValue* result = " . NativeToJSValue($attribute->signature, 0, $implClassName, $implClassNameForValueConversion, "imp->$implGetterFunctionName(ec)", "static_cast<$className*>(asObject(slot.slotBase()))") . ";\n"); } - } - } else { - push(@implContent, " ExceptionCode ec = 0;\n"); - if ($podType) { - push(@implContent, " $podType imp(*impl());\n"); - push(@implContent, " KJS::JSValue* result = " . NativeToJSValue($attribute->signature, 0, $implClassName, "", "imp.$getterFunctionName(ec)") . ";\n"); - } else { - push(@implContent, " $implClassName* imp = static_cast<$implClassName*>(impl());\n"); - push(@implContent, " KJS::JSValue* result = " . NativeToJSValue($attribute->signature, 0, $implClassName, $implClassNameForValueConversion, "imp->$getterFunctionName(ec)") . ";\n"); + push(@implContent, " setDOMException(exec, ec);\n"); + push(@implContent, " return result;\n"); } - push(@implContent, " setDOMException(exec, ec);\n"); - push(@implContent, " return result;\n"); + push(@implContent, "}\n\n"); } - push(@implContent, " }\n"); - } - if ($dataNode->extendedAttributes->{"GenerateConstructor"}) { - push(@implContent, " case ConstructorAttrNum:\n"); - push(@implContent, " return getConstructor(exec);\n"); - } + if ($dataNode->extendedAttributes->{"GenerateConstructor"}) { + my $constructorFunctionName = "js" . $interfaceName . "Constructor"; - push(@implContent, " }\n"); - push(@implContent, " return 0;\n}\n\n"); + push(@implContent, "JSValue* ${constructorFunctionName}(ExecState* exec, const Identifier&, const PropertySlot& slot)\n"); + push(@implContent, "{\n"); + push(@implContent, " return static_cast<$className*>(asObject(slot.slotBase()))->getConstructor(exec);\n"); + push(@implContent, "}\n"); + } + } # Check if we have any writable attributes my $hasReadWriteProperties = 0; foreach my $attribute (@{$dataNode->attributes}) { $hasReadWriteProperties = 1 if $attribute->type !~ /^readonly/; } - if ($hasReadWriteProperties || $dataNode->extendedAttributes->{"CustomPutFunction"}) { - push(@implContent, "void ${className}::put(ExecState* exec, const Identifier& propertyName, JSValue* value, int attr)\n"); + + my $hasSetter = $hasReadWriteProperties + || $dataNode->extendedAttributes->{"CustomPutFunction"} + || $dataNode->extendedAttributes->{"HasCustomIndexSetter"}; + + if ($hasSetter) { + push(@implContent, "void ${className}::put(ExecState* exec, const Identifier& propertyName, JSValue* value, PutPropertySlot& slot)\n"); push(@implContent, "{\n"); if ($dataNode->extendedAttributes->{"HasCustomIndexSetter"}) { push(@implContent, " bool ok;\n"); push(@implContent, " unsigned index = propertyName.toUInt32(&ok, false);\n"); push(@implContent, " if (ok) {\n"); - push(@implContent, " indexSetter(exec, index, value, attr);\n"); + push(@implContent, " indexSetter(exec, index, value);\n"); push(@implContent, " return;\n"); push(@implContent, " }\n"); } if ($dataNode->extendedAttributes->{"CustomPutFunction"}) { - push(@implContent, " if (customPut(exec, propertyName, value, attr))\n"); + push(@implContent, " if (customPut(exec, propertyName, value, slot))\n"); push(@implContent, " return;\n"); } + if ($hasReadWriteProperties) { - push(@implContent, " lookupPut<$className, Base>(exec, propertyName, value, attr, &${className}Table, this);\n"); + push(@implContent, " lookupPut<$className, Base>(exec, propertyName, value, " . hashTableAccessor($dataNode->extendedAttributes->{"NoStaticTables"}, $className) . ", this, slot);\n"); } else { - push(@implContent, " Base::put(exec, propertyName, value, attr);\n"); + push(@implContent, " Base::put(exec, propertyName, value, slot);\n"); } - push(@implContent, "}\n\n"); - if ($hasReadWriteProperties) { - push(@implContent, "void ${className}::putValueProperty(ExecState* exec, int token, JSValue* value, int /*attr*/)\n"); + if ($dataNode->extendedAttributes->{"HasCustomIndexSetter"}) { + push(@implContent, "void ${className}::put(ExecState* exec, unsigned propertyName, JSValue* value)\n"); push(@implContent, "{\n"); + push(@implContent, " indexSetter(exec, propertyName, value);\n"); + push(@implContent, " return;\n"); + push(@implContent, "}\n\n"); + } - push(@implContent, " switch (token) {\n"); - + if ($hasReadWriteProperties) { foreach my $attribute (@{$dataNode->attributes}) { if ($attribute->type !~ /^readonly/) { my $name = $attribute->signature->name; - my $setterFunctionName = $codeGenerator->WK_ucfirst($name); + my $type = $codeGenerator->StripModule($attribute->signature->type); + my $putFunctionName = "setJS" . $interfaceName . $codeGenerator->WK_ucfirst($name) . ($attribute->signature->type =~ /Constructor$/ ? "Constructor" : ""); + my $implSetterFunctionName = $codeGenerator->WK_ucfirst($name); - push(@implContent, " case " . $codeGenerator->WK_ucfirst($attribute->signature->name) - . ($attribute->signature->type =~ /Constructor$/ ? "Constructor" : "") - . "AttrNum: {\n"); + push(@implContent, "void ${putFunctionName}(ExecState* exec, JSObject* thisObject, JSValue* value)\n"); + push(@implContent, "{\n"); if ($dataNode->extendedAttributes->{"CheckDomainSecurity"} && !$attribute->signature->extendedAttributes->{"DoNotCheckDomainSecurity"}) { if ($interfaceName eq "DOMWindow") { - push(@implContent, " if (!allowsAccessFrom(exec))\n"); + push(@implContent, " if (!static_cast<$className*>(thisObject)->allowsAccessFrom(exec))\n"); } else { - push(@implContent, " if (!allowsAccessFromFrame(exec, impl()->frame()))\n"); + push(@implContent, " if (!allowsAccessFromFrame(exec, static_cast<$className*>(thisObject)->impl()->frame()))\n"); } - push(@implContent, " return;\n"); + push(@implContent, " return;\n"); } if ($attribute->signature->extendedAttributes->{"Custom"} || $attribute->signature->extendedAttributes->{"CustomSetter"}) { - push(@implContent, " set$setterFunctionName(exec, value);\n"); + push(@implContent, " static_cast<$className*>(thisObject)->set$implSetterFunctionName(exec, value);\n"); + } elsif ($type eq "EventListener") { + $implIncludes{"JSEventListener.h"} = 1; + push(@implContent, " $implClassName* imp = static_cast<$implClassName*>(static_cast<$className*>(thisObject)->impl());\n"); + my $listenerType; + if ($attribute->signature->extendedAttributes->{"ProtectedListener"}) { + $listenerType = "JSEventListener"; + } else { + $listenerType = "JSUnprotectedEventListener"; + } + if ($interfaceName eq "DOMWindow") { + push(@implContent, " JSDOMGlobalObject* globalObject = static_cast<JSDOMWindow*>(thisObject);\n"); + } else { + $implIncludes{"Frame.h"} = 1; + $implIncludes{"JSDOMGlobalObject.h"} = 1; + push(@implContent, " JSDOMGlobalObject* globalObject = toJSDOMGlobalObject(imp->scriptExecutionContext());\n"); + push(@implContent, " if (!globalObject)\n"); + push(@implContent, " return;\n"); + } + push(@implContent, " imp->set$implSetterFunctionName(globalObject->findOrCreate${listenerType}(exec, value, true));\n"); } elsif ($attribute->signature->type =~ /Constructor$/) { my $constructorType = $attribute->signature->type; $constructorType =~ s/Constructor$//; $implIncludes{"JS" . $constructorType . ".h"} = 1; - push(@implContent, " // Shadowing a built-in constructor\n"); - push(@implContent, " putDirect(\"$name\", value);\n"); + push(@implContent, " // Shadowing a built-in constructor\n"); + push(@implContent, " static_cast<$className*>(thisObject)->putDirect(Identifier(exec, \"$name\"), value);\n"); } elsif ($attribute->signature->extendedAttributes->{"Replaceable"}) { - push(@implContent, " putDirect(\"$name\", value);\n"); + push(@implContent, " static_cast<$className*>(thisObject)->putDirect(Identifier(exec, \"$name\"), value);\n"); } else { if ($podType) { - push(@implContent, " $podType imp(*impl());\n"); + push(@implContent, " $podType imp(*static_cast<$className*>(thisObject)->impl());\n"); if ($podType eq "float") { # Special case for JSSVGNumber - push(@implContent, " imp = " . JSValueToNative($attribute->signature, "value") . ";\n"); + push(@implContent, " imp = " . JSValueToNative($attribute->signature, "value") . ";\n"); } else { - push(@implContent, " imp.set$setterFunctionName(" . JSValueToNative($attribute->signature, "value") . ");\n"); + push(@implContent, " imp.set$implSetterFunctionName(" . JSValueToNative($attribute->signature, "value") . ");\n"); } - push(@implContent, " m_impl->commitChange(imp, context());\n"); + push(@implContent, " static_cast<$className*>(thisObject)->impl()->commitChange(imp, static_cast<$className*>(thisObject)->context());\n"); } else { - push(@implContent, " $implClassName* imp = static_cast<$implClassName*>(impl());\n"); - push(@implContent, " ExceptionCode ec = 0;\n") if @{$attribute->setterExceptions}; - push(@implContent, " imp->set$setterFunctionName(" . JSValueToNative($attribute->signature, "value")); + push(@implContent, " $implClassName* imp = static_cast<$implClassName*>(static_cast<$className*>(thisObject)->impl());\n"); + push(@implContent, " ExceptionCode ec = 0;\n") if @{$attribute->setterExceptions}; + push(@implContent, " imp->set$implSetterFunctionName(" . JSValueToNative($attribute->signature, "value")); push(@implContent, ", ec") if @{$attribute->setterExceptions}; push(@implContent, ");\n"); - push(@implContent, " setDOMException(exec, ec);\n") if @{$attribute->setterExceptions}; + push(@implContent, " setDOMException(exec, ec);\n") if @{$attribute->setterExceptions}; if (IsSVGTypeNeedingContextParameter($implClassName)) { - push(@implContent, " if (context())\n"); - push(@implContent, " context()->svgAttributeChanged(impl()->associatedAttributeName());\n"); + push(@implContent, " if (static_cast<$className*>(thisObject)->context())\n"); + push(@implContent, " static_cast<$className*>(thisObject)->context()->svgAttributeChanged(static_cast<$className*>(thisObject)->impl()->associatedAttributeName());\n"); } } } - push(@implContent, " break;\n"); - push(@implContent, " }\n"); + + push(@implContent, "}\n\n"); } } - push(@implContent, " }\n"); # end switch - push(@implContent, "}\n\n"); # end function } } } - if ($dataNode->extendedAttributes->{"CustomGetPropertyNames"} || $dataNode->extendedAttributes->{"HasIndexGetter"}) { + if ($dataNode->extendedAttributes->{"CustomGetPropertyNames"} || $dataNode->extendedAttributes->{"HasIndexGetter"} || $dataNode->extendedAttributes->{"HasCustomIndexGetter"}) { push(@implContent, "void ${className}::getPropertyNames(ExecState* exec, PropertyNameArray& propertyNames)\n"); push(@implContent, "{\n"); if ($dataNode->extendedAttributes->{"CustomGetPropertyNames"}) { push(@implContent, " if (customGetPropertyNames(exec, propertyNames))\n"); push(@implContent, " return;\n"); } - if ($dataNode->extendedAttributes->{"HasIndexGetter"}) { + if ($dataNode->extendedAttributes->{"HasIndexGetter"} || $dataNode->extendedAttributes->{"HasCustomIndexGetter"}) { push(@implContent, " for (unsigned i = 0; i < static_cast<${implClassName}*>(impl())->length(); ++i)\n"); - push(@implContent, " propertyNames.add(Identifier::from(i));\n"); + push(@implContent, " propertyNames.add(Identifier::from(exec, i));\n"); } push(@implContent, " Base::getPropertyNames(exec, propertyNames);\n"); push(@implContent, "}\n\n"); @@ -1075,22 +1276,32 @@ sub GenerateImplementation if ($dataNode->extendedAttributes->{"GenerateConstructor"}) { push(@implContent, "JSValue* ${className}::getConstructor(ExecState* exec)\n{\n"); - push(@implContent, " return KJS::cacheGlobalObject<${className}Constructor>(exec, \"[[${interfaceName}.constructor]]\");\n"); + push(@implContent, " return getDOMConstructor<${className}Constructor>(exec);\n"); push(@implContent, "}\n\n"); } # Functions if ($numFunctions > 0) { foreach my $function (@{$dataNode->functions}) { + AddIncludesForType($function->signature->type); + my $functionName = $codeGenerator->WK_lcfirst($className) . "PrototypeFunction" . $codeGenerator->WK_ucfirst($function->signature->name); - push(@implContent, "JSValue* ${functionName}(ExecState* exec, JSObject* thisObj, const List& args)\n"); + my $functionImplementationName = $function->signature->extendedAttributes->{"ImplementationFunction"} || $codeGenerator->WK_lcfirst($function->signature->name); + + push(@implContent, "JSValue* ${functionName}(ExecState* exec, JSObject*, JSValue* thisValue, const ArgList& args)\n"); push(@implContent, "{\n"); - push(@implContent, " if (!thisObj->inherits(&${className}::info))\n"); - push(@implContent, " return throwError(exec, TypeError);\n"); - AddIncludesForType($function->signature->type); + $implKJSInclude{"Error.h"} = 1; - push(@implContent, " $className* castedThisObj = static_cast<$className*>(thisObj);\n"); + if ($interfaceName eq "DOMWindow") { + push(@implContent, " $className* castedThisObj = toJSDOMWindow(thisValue);\n"); + push(@implContent, " if (!castedThisObj)\n"); + push(@implContent, " return throwError(exec, TypeError);\n"); + } else { + push(@implContent, " if (!thisValue->isObject(&${className}::s_info))\n"); + push(@implContent, " return throwError(exec, TypeError);\n"); + push(@implContent, " $className* castedThisObj = static_cast<$className*>(asObject(thisValue));\n"); + } if ($dataNode->extendedAttributes->{"CheckDomainSecurity"} && !$function->signature->extendedAttributes->{"DoNotCheckDomainSecurity"}) { @@ -1099,7 +1310,7 @@ sub GenerateImplementation } if ($function->signature->extendedAttributes->{"Custom"}) { - push(@implContent, " return castedThisObj->" . $codeGenerator->WK_lcfirst($function->signature->name) . "(exec, args);\n"); + push(@implContent, " return castedThisObj->" . $functionImplementationName . "(exec, args);\n"); } else { if ($podType) { push(@implContent, " JSSVGPODTypeWrapper<$podType>* wrapper = castedThisObj->impl();\n"); @@ -1122,11 +1333,11 @@ sub GenerateImplementation if ($function->signature->extendedAttributes->{"SVGCheckSecurityDocument"}) { push(@implContent, " if (!checkNodeSecurity(exec, imp->getSVGDocument(" . (@{$function->raisesExceptions} ? "ec" : "") .")))\n"); push(@implContent, " return jsUndefined();\n"); - $implIncludes{"kjs_dom.h"} = 1; + $implIncludes{"JSDOMBinding.h"} = 1; } my $paramIndex = 0; - my $functionString = "imp" . ($podType ? "." : "->") . $codeGenerator->WK_lcfirst($function->signature->name) . "("; + my $functionString = "imp" . ($podType ? "." : "->") . $functionImplementationName . "("; my $hasOptionalArguments = 0; @@ -1146,25 +1357,19 @@ sub GenerateImplementation if ($parameter->type eq "XPathNSResolver") { push(@implContent, " RefPtr<XPathNSResolver> customResolver;\n"); - push(@implContent, " XPathNSResolver* resolver = toXPathNSResolver(args[$paramIndex]);\n"); + push(@implContent, " XPathNSResolver* resolver = toXPathNSResolver(args.at(exec, $paramIndex));\n"); push(@implContent, " if (!resolver) {\n"); - push(@implContent, " customResolver = JSCustomXPathNSResolver::create(exec, args[$paramIndex]);\n"); + push(@implContent, " customResolver = JSCustomXPathNSResolver::create(exec, args.at(exec, $paramIndex));\n"); push(@implContent, " if (exec->hadException())\n"); push(@implContent, " return jsUndefined();\n"); push(@implContent, " resolver = customResolver.get();\n"); push(@implContent, " }\n"); } else { - push(@implContent, " bool ${name}Ok;\n") if TypeCanFailConversion($parameter); - push(@implContent, " " . GetNativeTypeFromSignature($parameter) . " $name = " . JSValueToNative($parameter, "args[$paramIndex]", TypeCanFailConversion($parameter) ? "${name}Ok" : undef) . ";\n"); - if (TypeCanFailConversion($parameter)) { - push(@implContent, " if (!${name}Ok) {\n"); - push(@implContent, " setDOMException(exec, TYPE_MISMATCH_ERR);\n"); - push(@implContent, " return jsUndefined();\n"); - push(@implContent, " }\n"); - } + push(@implContent, " " . GetNativeTypeFromSignature($parameter) . " $name = " . JSValueToNative($parameter, "args.at(exec, $paramIndex)") . ";\n"); - # If a parameter is "an index", it should throw an INDEX_SIZE_ERR - # exception + # If a parameter is "an index" and it's negative it should throw an INDEX_SIZE_ERR exception. + # But this needs to be done in the bindings, because the type is unsigned and the fact that it + # was negative will be lost by the time we're inside the DOM. if ($parameter->extendedAttributes->{"IsIndex"}) { $implIncludes{"ExceptionCode.h"} = 1; push(@implContent, " if ($name < 0) {\n"); @@ -1175,7 +1380,12 @@ sub GenerateImplementation } $functionString .= ", " if $paramIndex; - $functionString .= $name; + + if ($parameter->type eq "NodeFilter") { + $functionString .= "$name.get()"; + } else { + $functionString .= $name; + } $paramIndex++; } @@ -1187,13 +1397,27 @@ sub GenerateImplementation } } + if ($numConstants > 0) { + push(@implContent, "// Constant getters\n\n"); + + foreach my $constant (@{$dataNode->constants}) { + my $getter = "js" . $interfaceName . $codeGenerator->WK_ucfirst($constant->name); + + # FIXME: this casts into int to match our previous behavior which turned 0xFFFFFFFF in -1 for NodeFilter.SHOW_ALL + push(@implContent, "JSValue* ${getter}(ExecState* exec, const Identifier&, const PropertySlot&)\n"); + push(@implContent, "{\n"); + push(@implContent, " return jsNumber(exec, static_cast<int>(" . $constant->value . "));\n"); + push(@implContent, "}\n\n"); + } + } + if ($dataNode->extendedAttributes->{"HasIndexGetter"}) { - push(@implContent, "\nJSValue* ${className}::indexGetter(ExecState* exec, JSObject* originalObject, const Identifier& propertyName, const PropertySlot& slot)\n"); + push(@implContent, "\nJSValue* ${className}::indexGetter(ExecState* exec, const Identifier& propertyName, const PropertySlot& slot)\n"); push(@implContent, "{\n"); - push(@implContent, " ${className}* thisObj = static_cast<$className*>(slot.slotBase());\n"); + push(@implContent, " ${className}* thisObj = static_cast<$className*>(asObject(slot.slotBase()));\n"); if (IndexGetterReturnsStrings($implClassName)) { - $implIncludes{"PlatformString.h"} = 1; - push(@implContent, " return jsStringOrNull(thisObj->impl()->item(slot.index()));\n"); + $implIncludes{"KURL.h"} = 1; + push(@implContent, " return jsStringOrNull(exec, thisObj->impl()->item(slot.index()));\n"); } else { push(@implContent, " return toJS(exec, static_cast<$implClassName*>(thisObj->impl())->item(slot.index()));\n"); } @@ -1206,34 +1430,34 @@ sub GenerateImplementation if ((!$hasParent or $dataNode->extendedAttributes->{"GenerateToJS"}) and !UsesManualToJSImplementation($implClassName)) { if ($podType) { - push(@implContent, "KJS::JSValue* toJS(KJS::ExecState* exec, JSSVGPODTypeWrapper<$podType>* obj, SVGElement* context)\n"); + push(@implContent, "JSC::JSValue* toJS(JSC::ExecState* exec, JSSVGPODTypeWrapper<$podType>* object, SVGElement* context)\n"); } elsif (IsSVGTypeNeedingContextParameter($implClassName)) { - push(@implContent, "KJS::JSValue* toJS(KJS::ExecState* exec, $passType obj, SVGElement* context)\n"); + push(@implContent, "JSC::JSValue* toJS(JSC::ExecState* exec, $implType* object, SVGElement* context)\n"); } else { - push(@implContent, "KJS::JSValue* toJS(KJS::ExecState* exec, $passType obj)\n"); + push(@implContent, "JSC::JSValue* toJS(JSC::ExecState* exec, $implType* object)\n"); } push(@implContent, "{\n"); if ($podType) { - push(@implContent, " return KJS::cacheSVGDOMObject<JSSVGPODTypeWrapper<$podType>, $className, ${className}Prototype>(exec, obj, context);\n"); + push(@implContent, " return getDOMObjectWrapper<$className, JSSVGPODTypeWrapper<$podType> >(exec, object, context);\n"); } elsif (IsSVGTypeNeedingContextParameter($implClassName)) { - push(@implContent, " return KJS::cacheSVGDOMObject<$implClassName, $className, ${className}Prototype>(exec, obj, context);\n"); + push(@implContent, " return getDOMObjectWrapper<$className>(exec, object, context);\n"); } else { - push(@implContent, " return KJS::cacheDOMObject<$implClassName, $className, ${className}Prototype>(exec, obj);\n"); + push(@implContent, " return getDOMObjectWrapper<$className>(exec, object);\n"); } push(@implContent, "}\n"); } if ((!$hasParent or $dataNode->extendedAttributes->{"GenerateNativeConverter"}) and !$dataNode->extendedAttributes->{"CustomNativeConverter"}) { if ($podType) { - push(@implContent, "$podType to${interfaceName}(KJS::JSValue* val)\n"); + push(@implContent, "$podType to${interfaceName}(JSC::JSValue* value)\n"); } else { - push(@implContent, "$implClassName* to${interfaceName}(KJS::JSValue* val)\n"); + push(@implContent, "$implClassName* to${interfaceName}(JSC::JSValue* value)\n"); } push(@implContent, "{\n"); - push(@implContent, " return val->isObject(&${className}::info) ? " . ($podType ? "($podType) *" : "") . "static_cast<$className*>(val)->impl() : "); + push(@implContent, " return value->isObject(&${className}::s_info) ? " . ($podType ? "($podType) *" : "") . "static_cast<$className*>(asObject(value))->impl() : "); if ($podType and $podType ne "float") { push(@implContent, "$podType();\n}\n"); } else { @@ -1241,13 +1465,6 @@ sub GenerateImplementation } } - if ($dataNode->extendedAttributes->{"GenerateNativeConverter"} && $hasParent) { - push(@implContent, "\n$implClassName* ${className}::impl() const\n"); - push(@implContent, "{\n"); - push(@implContent, " return static_cast<$implClassName*>(Base::impl());\n"); - push(@implContent, "}\n"); - } - push(@implContent, "\n}\n"); push(@implContent, "\n#endif // ${conditionalString}\n") if $conditional; @@ -1278,7 +1495,7 @@ sub GenerateImplementationFunctionCall() push(@implContent, $indent . "return jsUndefined();\n"); } else { - push(@implContent, "\n" . $indent . "KJS::JSValue* result = " . NativeToJSValue($function->signature, 1, $implClassName, "", $functionString) . ";\n"); + push(@implContent, "\n" . $indent . "JSC::JSValue* result = " . NativeToJSValue($function->signature, 1, $implClassName, "", $functionString, "castedThisObj") . ";\n"); push(@implContent, $indent . "setDOMException(exec, ec);\n") if @{$function->raisesExceptions}; if ($podType) { @@ -1303,10 +1520,10 @@ sub GetNativeTypeFromSignature } my %nativeType = ( - "AtomicString" => "AtomicString", "CompareHow" => "Range::CompareHow", - "DOMString" => "String", + "DOMString" => "const UString&", "EventTarget" => "EventTargetNode*", + "NodeFilter" => "RefPtr<NodeFilter>", "SVGLength" => "SVGLength", "SVGMatrix" => "AffineTransform", "SVGNumber" => "float", @@ -1332,76 +1549,21 @@ sub GetNativeType return "${type}*"; } -my %typeCanFailConversion = ( - "AtomicString" => 0, - "Attr" => 1, - "CompareHow" => 0, - "DOMString" => 0, - "DOMWindow" => 0, - "DocumentType" => 0, - "Element" => 0, - "Event" => 0, - "EventListener" => 0, - "EventTarget" => 0, - "HTMLElement" => 0, - "HTMLOptionElement" => 0, - "Node" => 0, - "NodeFilter" => 0, - "Range" => 0, - "SQLResultSet" => 0, - "SVGAngle" => 0, - "SVGElement" => 0, - "SVGLength" => 0, - "SVGMatrix" => 0, - "SVGNumber" => 0, - "SVGPaintType" => 0, - "SVGPathSeg" => 0, - "SVGPoint" => 0, - "SVGRect" => 0, - "SVGTransform" => 0, - "VoidCallback" => 1, - "XPathEvaluator" => 0, - "XPathNSResolver" => 0, - "XPathResult" => 0, - "boolean" => 0, - "double" => 0, - "float" => 0, - "long" => 0, - "unsigned long" => 0, - "unsigned short" => 0, -); - -sub TypeCanFailConversion -{ - my $signature = shift; - - my $type = $codeGenerator->StripModule($signature->type); - - $implIncludes{"ExceptionCode.h"} = 1 if $type eq "Attr"; - - return $typeCanFailConversion{$type} if exists $typeCanFailConversion{$type}; - - die "Don't know whether a JS value can fail conversion to type $type."; -} - sub JSValueToNative { my $signature = shift; my $value = shift; - my $okParam = shift; - my $maybeOkParam = $okParam ? ", ${okParam}" : ""; my $type = $codeGenerator->StripModule($signature->type); return "$value->toBoolean(exec)" if $type eq "boolean"; return "$value->toNumber(exec)" if $type eq "double"; return "$value->toFloat(exec)" if $type eq "float" or $type eq "SVGNumber"; - return "$value->toInt32(exec${maybeOkParam})" if $type eq "unsigned long" or $type eq "long" or $type eq "unsigned short"; + return "$value->toInt32(exec)" if $type eq "unsigned long" or $type eq "long" or $type eq "unsigned short"; return "static_cast<Range::CompareHow>($value->toInt32(exec))" if $type eq "CompareHow"; return "static_cast<SVGPaint::SVGPaintType>($value->toInt32(exec))" if $type eq "SVGPaintType"; - return "$value->toString(exec)" if $type eq "AtomicString"; if ($type eq "DOMString") { return "valueToStringWithNullCheck(exec, $value)" if $signature->extendedAttributes->{"ConvertNullToNullString"}; return "valueToStringWithUndefinedOrNullCheck(exec, $value)" if $signature->extendedAttributes->{"ConvertUndefinedOrNullToNullString"}; @@ -1413,19 +1575,11 @@ sub JSValueToNative return "toEventTargetNode($value)"; } - if ($type eq "Attr") { - $implIncludes{"kjs_dom.h"} = 1; - return "toAttr($value${maybeOkParam})"; - } - - if ($type eq "VoidCallback") { - $implIncludes{"JSCustomVoidCallback.h"} = 1; - return "toVoidCallback(exec, $value${maybeOkParam})"; - } - $implIncludes{"FloatPoint.h"} = 1 if $type eq "SVGPoint"; $implIncludes{"FloatRect.h"} = 1 if $type eq "SVGRect"; $implIncludes{"HTMLOptionElement.h"} = 1 if $type eq "HTMLOptionElement"; + $implIncludes{"JSCustomVoidCallback.h"} = 1 if $type eq "VoidCallback"; + $implIncludes{"Event.h"} = 1 if $type eq "Event"; # Default, assume autogenerated type conversion routines $implIncludes{"JS$type.h"} = 1; @@ -1439,27 +1593,33 @@ sub NativeToJSValue my $implClassName = shift; my $implClassNameForValueConversion = shift; my $value = shift; + my $thisValue = shift; my $type = $codeGenerator->StripModule($signature->type); return "jsBoolean($value)" if $type eq "boolean"; - return "jsNumber($value)" if $codeGenerator->IsPrimitiveType($type) or $type eq "SVGPaintType" or $type eq "DOMTimeStamp"; + + if ($codeGenerator->IsPrimitiveType($type) or $type eq "SVGPaintType" or $type eq "DOMTimeStamp") { + $implKJSInclude{"JSNumberCell.h"} = 1; + return "jsNumber(exec, $value)"; + } if ($codeGenerator->IsStringType($type)) { - $implIncludes{"PlatformString.h"} = 1; + $implIncludes{"KURL.h"} = 1; my $conv = $signature->extendedAttributes->{"ConvertNullStringTo"}; if (defined $conv) { - return "jsStringOrNull($value)" if $conv eq "Null"; - return "jsStringOrUndefined($value)" if $conv eq "Undefined"; - return "jsStringOrFalse($value)" if $conv eq "False"; + return "jsStringOrNull(exec, $value)" if $conv eq "Null"; + return "jsStringOrUndefined(exec, $value)" if $conv eq "Undefined"; + return "jsStringOrFalse(exec, $value)" if $conv eq "False"; die "Unknown value for ConvertNullStringTo extended attribute"; } - return "jsString($value)"; + $implKJSInclude{"JSString.h"} = 1; + return "jsString(exec, $value)"; } if ($type eq "RGBColor") { - $implIncludes{"kjs_css.h"} = 1; + $implIncludes{"JS$type.h"} = 1; return "getJSRGBColor(exec, $value)"; } @@ -1474,18 +1634,30 @@ sub NativeToJSValue my $setter = "set" . $codeGenerator->WK_ucfirst($getter); + # Function calls will never return 'modifyable' POD types (ie. SVGRect getBBox()) - no need to keep track changes to the returned SVGRect + if ($inFunctionCall eq 0 + and not $codeGenerator->IsSVGAnimatedType($implClassName) + and $codeGenerator->IsPodTypeWithWriteableProperties($type) + and not defined $signature->extendedAttributes->{"Immutable"}) { + if ($codeGenerator->IsPodType($implClassName)) { + return "toJS(exec, JSSVGStaticPODTypeWrapperWithPODTypeParent<$nativeType, $implClassName>::create($value, $thisValue->impl()).get(), $thisValue->context())"; + } else { + return "toJS(exec, JSSVGStaticPODTypeWrapperWithParent<$nativeType, $implClassName>::create(imp, &${implClassName}::$getter, &${implClassName}::$setter).get(), imp)"; + } + } + if ($implClassNameForValueConversion eq "") { if (IsSVGTypeNeedingContextParameter($implClassName)) { - return "toJS(exec, new JSSVGPODTypeWrapperCreatorReadOnly<$nativeType>($value), castedThisObj->context())" if $inFunctionCall eq 1; + return "toJS(exec, JSSVGStaticPODTypeWrapper<$nativeType>::create($value).get(), castedThisObj->context())" if $inFunctionCall eq 1; # Special case: SVGZoomEvent - it doesn't have a context, but it's no problem, as there are no readwrite props - return "toJS(exec, new JSSVGPODTypeWrapperCreatorReadOnly<$nativeType>($value), 0)" if $implClassName eq "SVGZoomEvent"; - return "toJS(exec, new JSSVGPODTypeWrapperCreatorReadOnly<$nativeType>($value), context())"; + return "toJS(exec, JSSVGStaticPODTypeWrapper<$nativeType>::create($value).get(), 0)" if $implClassName eq "SVGZoomEvent"; + return "toJS(exec, JSSVGStaticPODTypeWrapper<$nativeType>::create($value).get(), $thisValue->context())"; } else { - return "toJS(exec, new JSSVGPODTypeWrapperCreatorReadOnly<$nativeType>($value), imp)"; + return "toJS(exec, JSSVGStaticPODTypeWrapper<$nativeType>::create($value).get(), imp)"; } } else { # These classes, always have a m_context pointer! - return "toJS(exec, JSSVGPODTypeWrapperCache<$nativeType, $implClassNameForValueConversion>::lookupOrCreateWrapper(imp, &${implClassNameForValueConversion}::$getter, &${implClassNameForValueConversion}::$setter), context())"; + return "toJS(exec, JSSVGDynamicPODTypeWrapperCache<$nativeType, $implClassNameForValueConversion>::lookupOrCreateWrapper(imp, &${implClassNameForValueConversion}::$getter, &${implClassNameForValueConversion}::$setter).get(), $thisValue->context())"; } } @@ -1506,17 +1678,8 @@ sub NativeToJSValue $implIncludes{"NameNodeList.h"} = 1; } - if ($type eq "EventTarget") { - $implIncludes{"EventTargetNode.h"} = 1; - $implIncludes{"JSEventTargetNode.h"} = 1; - $implIncludes{"kjs_dom.h"} = 1; - } elsif ($type eq "DOMWindow") { - $implIncludes{"kjs_window.h"} = 1; - } elsif ($type eq "DOMObject") { + if ($type eq "DOMObject") { $implIncludes{"JSCanvasRenderingContext2D.h"} = 1; - } elsif ($type eq "Clipboard") { - $implIncludes{"kjs_events.h"} = 1; - $implIncludes{"Clipboard.h"} = 1; } elsif ($type =~ /SVGPathSeg/) { $implIncludes{"JS$type.h"} = 1; $joinedName = $type; @@ -1532,16 +1695,16 @@ sub NativeToJSValue if (IsSVGTypeNeedingContextParameter($type)) { if (IsSVGTypeNeedingContextParameter($implClassName)) { - if ($inFunctionCall eq 1) { - return "toJS(exec, WTF::getPtr($value), castedThisObj->context())"; - } else { - return "toJS(exec, WTF::getPtr($value), context())"; - } + return "toJS(exec, WTF::getPtr($value), $thisValue->context())"; } else { return "toJS(exec, WTF::getPtr($value), imp)"; } } + if ($signature->extendedAttributes->{"ReturnsNew"}) { + return "toJSNewlyCreated(exec, WTF::getPtr($value))"; + } + return "toJS(exec, WTF::getPtr($value))"; } @@ -1563,53 +1726,32 @@ sub GenerateHashTable my $object = shift; my $name = shift; - my $size = shift; my $keys = shift; - my $values = shift; my $specials = shift; - my $parameters = shift; - - # Helpers - my @table = (); - my @links = (); - - $size = ceilingToPowerOf2($size * 2); + my $value1 = shift; + my $value2 = shift; - my $maxDepth = 0; - my $collisions = 0; - my $numEntries = $size; + my @hashes = (); + foreach my $key (@{$keys}) { + push @hashes, $object->GenerateHashValue($key); + } # Collect hashtable information - my $i = 0; - foreach (@{$keys}) { - my $depth = 0; - my $h = $object->GenerateHashValue($_) % $numEntries; - - while (defined($table[$h])) { - if (defined($links[$h])) { - $h = $links[$h]; - $depth++; - } else { - $collisions++; - $links[$h] = $size; - $h = $size; - $size++; - } + my $size; +tableSizeLoop: + for ($size = ceilingToPowerOf2(scalar @{$keys}); ; $size += $size) { + my @table = (); + my $i = 0; + foreach my $hash (@hashes) { + my $h = $hash % $size; + next tableSizeLoop if defined $table[$h]; + $table[$h] = $i++; } - - $table[$h] = $i; - - $i++; - $maxDepth = $depth if ($depth > $maxDepth); - } - - # Ensure table is big enough (in case of undef entries at the end) - if ($#table + 1 < $size) { - $#table = $size - 1; + last; } # Start outputing the hashtables - my $nameEntries = "${name}Entries"; + my $nameEntries = "${name}Values"; $nameEntries =~ s/:/_/g; if (($name =~ /Prototype/) or ($name =~ /Constructor/)) { @@ -1630,39 +1772,17 @@ sub GenerateHashTable } # Dump the hash table - push(@implContent, "\nstatic const HashEntry $nameEntries\[\] =\n\{\n"); - - $i = 0; - foreach $entry (@table) { - if (defined($entry)) { - my $key = @$keys[$entry]; - - push(@implContent, " \{ \"" . $key . "\""); - push(@implContent, ", \{ (intptr_t)" . @$values[$entry] . " \}"); - push(@implContent, ", " . @$specials[$entry]); - push(@implContent, ", " . @$parameters[$entry]); - push(@implContent, ", "); - - if (defined($links[$i])) { - push(@implContent, "&" . $nameEntries . "[$links[$i]]" . " \}"); - } else { - push(@implContent, "0 \}"); - } - } else { - push(@implContent, " { 0, { 0 }, 0, 0, 0 }"); - } - - push(@implContent, ",") unless($i eq $size - 1); - push(@implContent, "\n"); - - $i++; + my $count = scalar @{$keys} + 1; + push(@implContent, "\nstatic const HashTableValue $nameEntries\[$count\] =\n\{\n"); + my $i = 0; + foreach my $key (@{$keys}) { + push(@implContent, " { \"$key\", @$specials[$i], (intptr_t)@$value1[$i], (intptr_t)@$value2[$i] },\n"); + ++$i; } - - my $sizeMask = $numEntries - 1; - + push(@implContent, " { 0, 0, 0, 0 }\n"); push(@implContent, "};\n\n"); - push(@implContent, "static const HashTable $name = \n"); - push(@implContent, "{\n 3, $size, $nameEntries, $sizeMask\n};\n\n"); + my $sizeMask = $size - 1; + push(@implContent, "static const HashTable $name = { $sizeMask, $nameEntries, 0 };\n\n"); } # Internal helper @@ -1732,23 +1852,38 @@ sub WriteData print $IMPL "#include \"$implInclude\"\n" unless $codeGenerator->IsSVGAnimatedType($checkType); } + + print $IMPL "\n"; + + foreach my $implKJSInclude (sort keys(%implKJSInclude)) { + print $IMPL "#include <runtime/$implKJSInclude>\n"; + } print $IMPL @implContent; close($IMPL); undef($IMPL); - @implHeaderContent = (); + @implContentHeader = (); @implContent = (); %implIncludes = (); + %implKJSIncludes = (); } if (defined($HEADER)) { # Write content to file. + print $HEADER @headerContentHeader; + + foreach my $headerInclude (sort keys(%headerIncludes)) { + print $HEADER "#include \"$headerInclude\"\n"; + } + print $HEADER @headerContent; close($HEADER); undef($HEADER); + @headerContentHeader = (); @headerContent = (); + %headerIncludes = (); } } @@ -1764,43 +1899,48 @@ my $implContent = << "EOF"; class ${className}Constructor : public DOMObject { public: ${className}Constructor(ExecState* exec) - : DOMObject(exec->lexicalGlobalObject()->objectPrototype()) + : DOMObject(${className}Constructor::createStructureID(exec->lexicalGlobalObject()->objectPrototype())) { putDirect(exec->propertyNames().prototype, ${protoClassName}::self(exec), None); } virtual bool getOwnPropertySlot(ExecState*, const Identifier&, PropertySlot&); - JSValue* getValueProperty(ExecState*, int token) const; - virtual const ClassInfo* classInfo() const { return &info; } - static const ClassInfo info; + virtual const ClassInfo* classInfo() const { return &s_info; } + static const ClassInfo s_info; - virtual bool implementsHasInstance() const { return true; } + static PassRefPtr<StructureID> createStructureID(JSValue* proto) + { + return StructureID::create(proto, TypeInfo(ObjectType, ImplementsHasInstance)); + } EOF if ($canConstruct) { $implContent .= << "EOF"; - virtual bool implementsConstruct() const { return true; } - virtual JSObject* construct(ExecState* exec, const List& args) { return static_cast<JSObject*>(toJS(exec, new $interfaceName)); } + static JSObject* construct(ExecState* exec, JSObject*, const ArgList&) + { + return asObject(toJS(exec, ${interfaceName}::create())); + } + virtual ConstructType getConstructData(ConstructData& constructData) + { + constructData.native.function = construct; + return ConstructTypeHost; + } EOF } $implContent .= << "EOF"; }; -const ClassInfo ${className}Constructor::info = { "${visibleClassName}Constructor", 0, &${className}ConstructorTable }; +const ClassInfo ${className}Constructor::s_info = { "${visibleClassName}Constructor", 0, &${className}ConstructorTable, 0 }; bool ${className}Constructor::getOwnPropertySlot(ExecState* exec, const Identifier& propertyName, PropertySlot& slot) { return getStaticValueSlot<${className}Constructor, DOMObject>(exec, &${className}ConstructorTable, this, propertyName, slot); } -JSValue* ${className}Constructor::getValueProperty(ExecState*, int token) const -{ - // The token is the numeric value of its associated constant - return jsNumber(token); -} - EOF + $implKJSInclude{"JSNumberCell.h"} = 1; + return $implContent; } diff --git a/WebCore/bindings/scripts/CodeGeneratorObjC.pm b/WebCore/bindings/scripts/CodeGeneratorObjC.pm index d49596b..7969b2c 100644 --- a/WebCore/bindings/scripts/CodeGeneratorObjC.pm +++ b/WebCore/bindings/scripts/CodeGeneratorObjC.pm @@ -3,7 +3,7 @@ # Copyright (C) 2006 Anders Carlsson <andersca@mac.com> # Copyright (C) 2006, 2007 Samuel Weinig <sam@webkit.org> # Copyright (C) 2006 Alexey Proskuryakov <ap@webkit.org> -# Copyright (C) 2006, 2007 Apple Inc. All rights reserved. +# Copyright (C) 2006, 2007, 2008 Apple Inc. All rights reserved. # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Library General Public @@ -30,6 +30,7 @@ my $module = ""; my $outputDir = ""; my %publicInterfaces = (); my $newPublicClass = 0; +my $interfaceAvailabilityVersion = ""; my $isProtocol = 0; my $noImpl = 0; my @ivars = (); @@ -54,7 +55,8 @@ my %implIncludes = (); my %protocolTypeHash = ("XPathNSResolver" => 1, "EventListener" => 1, "EventTarget" => 1, "NodeFilter" => 1, "SVGLocatable" => 1, "SVGTransformable" => 1, "SVGStylable" => 1, "SVGFilterPrimitiveStandardAttributes" => 1, "SVGTests" => 1, "SVGLangSpace" => 1, "SVGExternalResourcesRequired" => 1, "SVGURIReference" => 1, - "SVGZoomAndPan" => 1, "SVGFitToViewBox" => 1, "SVGAnimatedPathData" => 1, "SVGAnimatedPoints" => 1); + "SVGZoomAndPan" => 1, "SVGFitToViewBox" => 1, "SVGAnimatedPathData" => 1, "SVGAnimatedPoints" => 1, + "ElementTimeControl" => 1); my %nativeObjCTypeHash = ("URL" => 1, "Color" => 1); # FIXME: this should be replaced with a function that recurses up the tree @@ -131,7 +133,7 @@ my $fatalError = 0; # Default Licence Templates my $headerLicenceTemplate = << "EOF"; /* - * Copyright (C) 2004, 2005, 2006, 2007 Apple Inc. All rights reserved. + * Copyright (C) 2004, 2005, 2006, 2007, 2008 Apple Inc. All rights reserved. * Copyright (C) 2006 Samuel Weinig <sam.weinig\@gmail.com> * * Redistribution and use in source and binary forms, with or without @@ -221,15 +223,17 @@ sub ReadPublicInterfaces close FILE; foreach $line (@documentContent) { - if (!$isProtocol && $line =~ /^\s*\@interface\s*$class\s*:\s*(\w+)\s*/) { + if (!$isProtocol && $line =~ /^\s*\@interface\s*$class\s*:\s*(\w+)\s*([A-Z0-9_]*)/) { if ($superClass ne $1) { warn "Public API change. Superclass for \"$class\" differs ($1 != $superClass)"; $fatalError = 1; } + $interfaceAvailabilityVersion = $2 if defined $2; $found = 1; next; - } elsif ($isProtocol && $line =~ /^\s*\@protocol $class\s*/) { + } elsif ($isProtocol && $line =~ /^\s*\@protocol $class\s*<[^>]+>\s*([A-Z0-9_]*)/) { + $interfaceAvailabilityVersion = $1 if defined $1; $found = 1; next; } @@ -240,12 +244,18 @@ sub ReadPublicInterfaces # trim whitspace $line =~ s/^\s+//; $line =~ s/\s+$//; - $publicInterfaces{$line} = 1 if length($line); + + my $availabilityMacro = ""; + $line =~ s/\s([A-Z0-9_]+)\s*;$/;/; + $availabilityMacro = $1 if defined $1; + + $publicInterfaces{$line} = $availabilityMacro if length $line; } } # If this class was not found in PublicDOMInterfaces.h then it should be considered as an entirely new public class. - $newPublicClass = ! $found; + $newPublicClass = !$found; + $interfaceAvailabilityVersion = "WEBKIT_VERSION_LATEST" if $newPublicClass; } # Params: 'domClass' struct @@ -400,7 +410,7 @@ sub GetBaseClass return $parent if $parent eq "Object" or IsBaseType($parent); return "Event" if $parent eq "UIEvent"; - return "CSSValue" if $parent eq "SVGColor"; + return "CSSValue" if $parent eq "SVGColor" or $parent eq "CSSValueList"; return "Node"; } @@ -477,7 +487,7 @@ sub GetObjCTypeGetterName my $type = $codeGenerator->StripModule(shift); my $typeGetter = ""; - if ($type =~ /^(HTML|CSS|SVG)/ or $type eq "DOMImplementation" or $type eq "CDATASection") { + if ($type =~ /^(HTML|CSS|SVG)/ or $type eq "DOMImplementation" or $type eq "CDATASection" or $type eq "RGBColor") { $typeGetter = $type; } elsif ($type =~ /^XPath(.+)/) { $typeGetter = "xpath" . $1; @@ -503,10 +513,64 @@ sub GetObjCTypeGetter my $typeGetterMethodName = GetObjCTypeGetterName($type); - return "nativeResolver" if $type eq "XPathNSResolver"; + return "WTF::getPtr(nativeEventListener)" if $type eq "EventListener"; + return "WTF::getPtr(nativeNodeFilter)" if $type eq "NodeFilter"; + return "WTF::getPtr(nativeResolver)" if $type eq "XPathNSResolver"; return "[$argName $typeGetterMethodName]"; } +sub GetInternalTypeGetterSignature +{ + my ($interfaceName, $podType) = @_; + + my $implClassNameWithNamespace = "WebCore::" . GetImplClassName($interfaceName); + my $podTypeWithNamespace; + if ($podType) { + $podTypeWithNamespace = ($podType eq "float") ? "$podType" : "WebCore::$podType"; + } + + # - Type-Getter + # - (WebCore::FooBar *)_fooBar for implementation class FooBar + my $typeGetterName = GetObjCTypeGetterName($interfaceName); + return "- " . ($podType ? "($podTypeWithNamespace)" : "($implClassNameWithNamespace *)") . $typeGetterName; +} + +sub GetInternalTypeMakerSignature +{ + my ($interfaceName, $podType) = @_; + + my $className = GetClassName($interfaceName); + my $implClassNameWithNamespace = "WebCore::" . GetImplClassName($interfaceName); + my $podTypeWithNamespace; + if ($podType) { + $podTypeWithNamespace = ($podType eq "float") ? "$podType" : "WebCore::$podType"; + } + + my @ivarsToRetain = (); + my $ivarsToInit = ""; + my $typeMakerSigAddition = ""; + if (@ivars > 0) { + my @ivarsInitSig = (); + my @ivarsInitCall = (); + foreach $attribute (@ivars) { + my $name = $attribute->signature->name; + my $memberName = "m_" . $name; + my $varName = "in" . $name; + my $type = GetObjCType($attribute->signature->type); + push(@ivarsInitSig, "$name:($type)$varName"); + push(@ivarsInitCall, "$name:$varName"); + push(@ivarsToRetain, " $memberName = [$varName retain];\n"); + } + $ivarsToInit = " " . join(" ", @ivarsInitCall); + $typeMakerSigAddition = " " . join(" ", @ivarsInitSig); + } + + my $typeMakerName = GetObjCTypeMaker($interfaceName); + return ("+ ($className *)$typeMakerName:(" . ($podType ? "$podTypeWithNamespace" : "$implClassNameWithNamespace *") . ")impl" . $typeMakerSigAddition, + $typeMakerSigAddition, + $ivarsToInit); +} + sub AddForwardDeclarationsForType { my $type = $codeGenerator->StripModule(shift); @@ -536,7 +600,7 @@ sub AddIncludesForType return if $codeGenerator->IsNonPointerType($type) or IsNativeObjCType($type); if ($codeGenerator->IsStringType($type)) { - $implIncludes{"PlatformString.h"} = 1; + $implIncludes{"KURL.h"} = 1; return; } @@ -600,9 +664,9 @@ sub AddIncludesForType return; } - if ($type eq "XPathNSResolver") { - $implIncludes{"DOMCustomXPathNSResolver.h"} = 1; - } + $implIncludes{"ObjCEventListener.h"} = 1 if $type eq "EventListener"; + $implIncludes{"ObjCNodeFilterCondition.h"} = 1 if $type eq "NodeFilter"; + $implIncludes{"DOMCustomXPathNSResolver.h"} = 1 if $type eq "XPathNSResolver"; # FIXME: won't compile without these $implIncludes{"CSSMutableStyleDeclaration.h"} = 1 if $type eq "CSSStyleDeclaration"; @@ -619,11 +683,6 @@ sub GenerateHeader my $object = shift; my $dataNode = shift; - # We only support multiple parents with SVG (for now). - if (@{$dataNode->parents} > 1) { - die "A class can't have more than one parent" unless $module eq "svg"; - } - my $interfaceName = $dataNode->name; my $className = GetClassName($interfaceName); @@ -640,14 +699,18 @@ sub GenerateHeader push(@headerContentHeader, "\n"); # - INCLUDES - + my $includedWebKitAvailabilityHeader = 0; unless ($isProtocol) { my $parentHeaderName = GetClassHeaderName($parentName); push(@headerContentHeader, "#import <WebCore/$parentHeaderName.h>\n"); + $includedWebKitAvailabilityHeader = 1; } + foreach my $parentProtocol (@protocolsToImplement) { next if $parentProtocol =~ /^NS/; $parentProtocol = GetClassHeaderName($parentProtocol); push(@headerContentHeader, "#import <WebCore/$parentProtocol.h>\n"); + $includedWebKitAvailabilityHeader = 1; } # Special case needed for legacy support of DOMRange @@ -655,9 +718,15 @@ sub GenerateHeader push(@headerContentHeader, "#import <WebCore/DOMCore.h>\n"); push(@headerContentHeader, "#import <WebCore/DOMDocument.h>\n"); push(@headerContentHeader, "#import <WebCore/DOMRangeException.h>\n"); + $includedWebKitAvailabilityHeader = 1; } + push(@headerContentHeader, "#import <JavaScriptCore/WebKitAvailability.h>\n") unless $includedWebKitAvailabilityHeader; + + my $interfaceAvailabilityVersionCheck = "#if WEBKIT_VERSION_MAX_ALLOWED >= $interfaceAvailabilityVersion\n\n"; + push(@headerContentHeader, "\n"); + push(@headerContentHeader, $interfaceAvailabilityVersionCheck) if length $interfaceAvailabilityVersion; # - Add constants. if ($numConstants > 0) { @@ -682,17 +751,11 @@ sub GenerateHeader } # - Begin @interface or @protocol - if ($isProtocol) { - my $parentProtocols = join(", ", @protocolsToImplement); - push(@headerContent, "\@protocol $className <$parentProtocols>\n"); - } else { - if (@protocolsToImplement eq 0) { - push(@headerContent, "\@interface $className : $parentName\n"); - } else { - my $parentProtocols = join(", ", @protocolsToImplement); - push(@headerContent, "\@interface $className : $parentName <$parentProtocols>\n"); - } - } + my $interfaceDeclaration = ($isProtocol ? "\@protocol $className" : "\@interface $className : $parentName"); + $interfaceDeclaration .= " <" . join(", ", @protocolsToImplement) . ">" if @protocolsToImplement > 0; + $interfaceDeclaration .= "\n"; + + push(@headerContent, $interfaceDeclaration); my @headerAttributes = (); my @privateHeaderAttributes = (); @@ -708,7 +771,7 @@ sub GenerateHeader if (@ivars > 0) { push(@headerContent, "{\n"); foreach my $attribute (@ivars) { - my $type = GetObjCType($attribute->signature->type);; + my $type = GetObjCType($attribute->signature->type); my $name = "m_" . $attribute->signature->name; my $ivarDeclaration = "$type $name"; push(@headerContent, " $ivarDeclaration;\n"); @@ -731,10 +794,22 @@ sub GenerateHeader my $attributeIsReadonly = ($attribute->type =~ /^readonly/); my $property = "\@property" . GetPropertyAttributes($attribute->signature->type, $attributeIsReadonly); - $property .= " " . $attributeType . ($attributeType =~ /\*$/ ? "" : " ") . $attributeName . ";"; + $property .= " " . $attributeType . ($attributeType =~ /\*$/ ? "" : " ") . $attributeName; + + my $publicInterfaceKey = $property . ";"; + + my $availabilityMacro = ""; + if (defined $publicInterfaces{$publicInterfaceKey} and length $publicInterfaces{$publicInterfaceKey}) { + $availabilityMacro = $publicInterfaces{$publicInterfaceKey}; + } - my $public = ($publicInterfaces{$property} or $newPublicClass); - delete $publicInterfaces{$property}; + $availabilityMacro = "WEBKIT_OBJC_METHOD_ANNOTATION($availabilityMacro)" if length $availabilityMacro and $buildingForTigerOrEarlier; + + my $declarationSuffix = ";\n"; + $declarationSuffix = " $availabilityMacro;\n" if length $availabilityMacro; + + my $public = (defined $publicInterfaces{$publicInterfaceKey} or $newPublicClass); + delete $publicInterfaces{$publicInterfaceKey}; AddForwardDeclarationsForType($attribute->signature->type, $public); @@ -753,18 +828,18 @@ sub GenerateHeader } if ($buildingForLeopardOrLater) { - $property .= "\n"; + $property .= $declarationSuffix; push(@headerAttributes, $property) if $public; push(@privateHeaderAttributes, $property) unless $public; } else { # - GETTER - my $getter = "- (" . $attributeType . ")" . $attributeName . ";\n"; + my $getter = "- (" . $attributeType . ")" . $attributeName . $declarationSuffix; push(@headerAttributes, $getter) if $public; push(@privateHeaderAttributes, $getter) unless $public; # - SETTER if (!$attributeIsReadonly) { - my $setter = "- (void)$setterName(" . $attributeType . ")new" . ucfirst($attributeName) . ";\n"; + my $setter = "- (void)$setterName(" . $attributeType . ")new" . ucfirst($attributeName) . $declarationSuffix; push(@headerAttributes, $setter) if $public; push(@privateHeaderAttributes, $setter) unless $public; } @@ -810,7 +885,7 @@ sub GenerateHeader $parameterIndex++; } - $functionSig .= ";"; + my $publicInterfaceKey = $functionSig . ";"; my $conflict = $conflictMethod{$methodName}; if ($conflict) { @@ -818,15 +893,24 @@ sub GenerateHeader $fatalError = 1; } - if ($isProtocol && !$newPublicClass && !defined $publicInterfaces{$functionSig}) { - warn "Protocol method $functionSig is not in PublicDOMInterfaces.h. Protocols require all methods to be public"; + if ($isProtocol && !$newPublicClass && !defined $publicInterfaces{$publicInterfaceKey}) { + warn "Protocol method $publicInterfaceKey is not in PublicDOMInterfaces.h. Protocols require all methods to be public"; $fatalError = 1; } - my $public = ($publicInterfaces{$functionSig} or $newPublicClass); - delete $publicInterfaces{$functionSig}; + my $availabilityMacro = ""; + if (defined $publicInterfaces{$publicInterfaceKey} and length $publicInterfaces{$publicInterfaceKey}) { + $availabilityMacro = $publicInterfaces{$publicInterfaceKey}; + } + + $availabilityMacro = "WEBKIT_OBJC_METHOD_ANNOTATION($availabilityMacro)" if length $availabilityMacro and $buildingForTigerOrEarlier; - $functionSig .= "\n"; + my $functionDeclaration = $functionSig; + $functionDeclaration .= " " . $availabilityMacro if length $availabilityMacro; + $functionDeclaration .= ";\n"; + + my $public = (defined $publicInterfaces{$publicInterfaceKey} or $newPublicClass); + delete $publicInterfaces{$publicInterfaceKey}; foreach my $type (keys %typesToForwardDeclare) { # add any forward declarations to the public header if a deprecated version will be generated @@ -834,26 +918,33 @@ sub GenerateHeader AddForwardDeclarationsForType($type, $public) unless $public and $needsDeprecatedVersion; } - push(@headerFunctions, $functionSig) if $public; - push(@privateHeaderFunctions, $functionSig) unless $public; + push(@headerFunctions, $functionDeclaration) if $public; + push(@privateHeaderFunctions, $functionDeclaration) unless $public; # generate the old style method names with un-named parameters, these methods are deprecated if ($needsDeprecatedVersion) { my $deprecatedFunctionSig = $functionSig; $deprecatedFunctionSig =~ s/\s\w+:/ :/g; # remove parameter names - my $deprecatedFunctionKey = $deprecatedFunctionSig; - $deprecatedFunctionSig =~ s/;\n$/ DEPRECATED_IN_MAC_OS_X_VERSION_10_5_AND_LATER;\n/ if $buildingForLeopardOrLater; - push(@deprecatedHeaderFunctions, $deprecatedFunctionSig); + $publicInterfaceKey = $deprecatedFunctionSig . ";"; + + my $availabilityMacro = "AVAILABLE_WEBKIT_VERSION_1_3_AND_LATER_BUT_DEPRECATED_IN_WEBKIT_VERSION_3_0"; + if (defined $publicInterfaces{$publicInterfaceKey} and length $publicInterfaces{$publicInterfaceKey}) { + $availabilityMacro = $publicInterfaces{$publicInterfaceKey}; + } + + $availabilityMacro = "WEBKIT_OBJC_METHOD_ANNOTATION($availabilityMacro)" if $buildingForTigerOrEarlier; - $deprecatedFunctionKey =~ s/\n$//; # remove the newline + $functionDeclaration = "$deprecatedFunctionSig $availabilityMacro;\n"; - unless (defined $publicInterfaces{$deprecatedFunctionKey}) { - warn "Deprecated method $deprecatedFunctionKey is not in PublicDOMInterfaces.h. All deprecated methods need to be public, or should have the OldStyleObjC IDL attribute removed"; + push(@deprecatedHeaderFunctions, $functionDeclaration); + + unless (defined $publicInterfaces{$publicInterfaceKey}) { + warn "Deprecated method $publicInterfaceKey is not in PublicDOMInterfaces.h. All deprecated methods need to be public, or should have the OldStyleObjC IDL attribute removed"; $fatalError = 1; } - delete $publicInterfaces{$deprecatedFunctionKey}; + delete $publicInterfaces{$publicInterfaceKey}; } } @@ -877,16 +968,18 @@ sub GenerateHeader push(@headerContent, "\@end\n"); } + push(@headerContent, "\n#endif\n") if length $interfaceAvailabilityVersion; + my %alwaysGenerateForNoSVGBuild = map { $_ => 1 } qw(DOMHTMLEmbedElement DOMHTMLObjectElement); - if (@privateHeaderAttributes > 0 or @privateHeaderFunctions > 0 - or exists $alwaysGenerateForNoSVGBuild{$className}) { + if (@privateHeaderAttributes > 0 or @privateHeaderFunctions > 0 or exists $alwaysGenerateForNoSVGBuild{$className}) { # - Private category @interface @privateHeaderContentHeader = split("\r", $headerLicenceTemplate); - push(@headerContentHeader, "\n"); + push(@privateHeaderContentHeader, "\n"); my $classHeaderName = GetClassHeaderName($className); push(@privateHeaderContentHeader, "#import <WebCore/$classHeaderName.h>\n\n"); + push(@privateHeaderContentHeader, $interfaceAvailabilityVersionCheck) if length $interfaceAvailabilityVersion; @privateHeaderContent = (); push(@privateHeaderContent, "\@interface $className (" . $className . "Private)\n"); @@ -894,6 +987,53 @@ sub GenerateHeader push(@privateHeaderContent, "\n") if $buildingForLeopardOrLater and @privateHeaderAttributes > 0 and @privateHeaderFunctions > 0; push(@privateHeaderContent, @privateHeaderFunctions) if @privateHeaderFunctions > 0; push(@privateHeaderContent, "\@end\n"); + + push(@privateHeaderContent, "\n#endif\n") if length $interfaceAvailabilityVersion; + } + + unless ($isProtocol) { + # Generate internal interfaces + my $podType = $dataNode->extendedAttributes->{"PODType"}; + my $typeGetterSig = GetInternalTypeGetterSignature($interfaceName, $podType); + my ($typeMakerSig, $typeMakerSigAddition, $ivarsToInit) = GetInternalTypeMakerSignature($interfaceName, $podType); + + # Generate interface definitions. + @internalHeaderContent = split("\r", $implementationLicenceTemplate); + + push(@internalHeaderContent, "\n#import <WebCore/$className.h>\n\n"); + push(@internalHeaderContent, $interfaceAvailabilityVersionCheck) if length $interfaceAvailabilityVersion; + + if ($interfaceName eq "Node" or $interfaceName eq "SVGElementInstance") { + push(@internalHeaderContent, "\@protocol DOMEventTarget;\n\n"); + } + + if ($codeGenerator->IsSVGAnimatedType($interfaceName)) { + push(@internalHeaderContent, "#import <WebCore/SVGAnimatedTemplate.h>\n\n"); + } elsif ($interfaceName eq "RGBColor") { + push(@internalHeaderContent, "#import <WebCore/Color.h>\n\n"); + } else { + if ($podType and $podType ne "float") { + push(@internalHeaderContent, "namespace WebCore { class $podType; }\n\n"); + } elsif ($interfaceName eq "Node") { + push(@internalHeaderContent, "namespace WebCore { class Node; class EventTarget; }\n\n"); + } elsif ($interfaceName eq "SVGElementInstance") { + push(@internalHeaderContent, "namespace WebCore { class SVGElementInstance; class EventTarget; }\n\n"); + } else { + my $implClassName = GetImplClassName($interfaceName); + push(@internalHeaderContent, "namespace WebCore { class $implClassName; }\n\n"); + } + } + + push(@internalHeaderContent, "\@interface $className (WebCoreInternal)\n"); + push(@internalHeaderContent, $typeGetterSig . ";\n"); + push(@internalHeaderContent, $typeMakerSig . ";\n"); + + if ($interfaceName eq "Node" or $interfaceName eq "SVGElementInstance") { + push(@internalHeaderContent, "+ (id <DOMEventTarget>)_wrapEventTarget:(WebCore::EventTarget *)eventTarget;\n"); + } + + push(@internalHeaderContent, "\@end\n"); + push(@internalHeaderContent, "\n#endif\n") if length $interfaceAvailabilityVersion; } } @@ -902,9 +1042,7 @@ sub GenerateImplementation my $object = shift; my $dataNode = shift; - # We only support multiple parents with SVG (for now). if (@{$dataNode->parents} > 1) { - die "A class can't have more than one parent" unless $module eq "svg"; $codeGenerator->AddMethodsConstantsAndAttributesFromParentClasses($dataNode); } @@ -1064,6 +1202,11 @@ sub GenerateImplementation $getterContentTail = ""; } + # TODO: Handle special case for DOMSVGLength + if ($podType and $podType eq "SVGLength" and $attributeName eq "value") { + $getterContentHead = "IMPL->value(0 /* FIXME */"; + } + my $attributeTypeSansPtr = $attributeType; $attributeTypeSansPtr =~ s/ \*$//; # Remove trailing " *" from pointer types. @@ -1099,13 +1242,6 @@ sub GenerateImplementation } } $implIncludes{"DOMPrivate.h"} = 1; - } elsif ($idlType eq "NodeFilter") { - push(@customGetterContent, " if (m_filter)\n"); - push(@customGetterContent, " // This node iterator was created from the Objective-C side.\n"); - push(@customGetterContent, " return [[m_filter retain] autorelease];\n\n"); - push(@customGetterContent, " // This node iterator was created from the C++ side.\n"); - $getterContentHead = "[$attributeClassName $typeMaker:WTF::getPtr(" . $getterContentHead; - $getterContentTail .= ")]"; } elsif ($attribute->signature->extendedAttributes->{"ConvertToString"}) { $getterContentHead = "WebCore::String::number(" . $getterContentHead; $getterContentTail .= ")"; @@ -1114,6 +1250,9 @@ sub GenerateImplementation } elsif ($codeGenerator->IsPodType($idlType)) { $getterContentHead = "[$attributeTypeSansPtr $typeMaker:" . $getterContentHead; $getterContentTail .= "]"; + } elsif (IsProtocolType($idlType) and $idlType ne "EventTarget") { + $getterContentHead = "[$attributeClassName $typeMaker:WTF::getPtr(" . $getterContentHead; + $getterContentTail .= ")]"; } elsif ($typeMaker ne "") { # Surround getter with TypeMaker $getterContentHead = "[$attributeTypeSansPtr $typeMaker:WTF::getPtr(" . $getterContentHead; @@ -1194,8 +1333,6 @@ sub GenerateImplementation } } - my @deprecatedFunctions = (); - # - Functions if ($numFunctions > 0) { foreach my $function (@{$dataNode->functions}) { @@ -1226,6 +1363,8 @@ sub GenerateImplementation push(@parameterNames, $implGetter); $needsCustom{"XPathNSResolver"} = $paramName if $idlType eq "XPathNSResolver"; + $needsCustom{"NodeFilter"} = $paramName if $idlType eq "NodeFilter"; + $needsCustom{"EventListener"} = $paramName if $idlType eq "EventListener"; $needsCustom{"EventTarget"} = $paramName if $idlType eq "EventTarget"; $needsCustom{"NodeToReturn"} = $paramName if $param->extendedAttributes->{"Return"}; @@ -1256,8 +1395,8 @@ sub GenerateImplementation push(@functionContent, " if ([$paramName isMemberOfClass:[DOMNativeXPathNSResolver class]])\n"); push(@functionContent, " nativeResolver = [(DOMNativeXPathNSResolver *)$paramName _xpathNSResolver];\n"); push(@functionContent, " else {\n"); - push(@functionContent, " customResolver = new WebCore::DOMCustomXPathNSResolver($paramName);\n"); - push(@functionContent, " nativeResolver = customResolver.get();\n"); + push(@functionContent, " customResolver = WebCore::DOMCustomXPathNSResolver::create($paramName);\n"); + push(@functionContent, " nativeResolver = WTF::getPtr(customResolver);\n"); push(@functionContent, " }\n"); push(@functionContent, " }\n"); } @@ -1280,9 +1419,34 @@ sub GenerateImplementation $caller = "dv"; } - # FIXME! We need [Custom] support for ObjC, to move these hacks into DOMSVGMatrixCustom.mm + if ($function->signature->extendedAttributes->{"EventTargetNodeCast"}) { + if ($dataNode->name =~ /^SVG/) { + $caller = "static_cast<WebCore::SVGElementInstance*>($caller)"; + } else { + push(@functionContent, " if (!$caller->isEventTargetNode())\n"); + $caller = "WebCore::EventTargetNodeCast($caller)"; + push(@functionContent, " WebCore::raiseDOMException(DOM_NOT_SUPPORTED_ERR);\n"); + } + } + + # special case the EventListener + if (defined $needsCustom{"EventListener"}) { + my $paramName = $needsCustom{"EventListener"}; + push(@functionContent, " RefPtr<WebCore::EventListener> nativeEventListener = WebCore::ObjCEventListener::wrap($paramName);\n"); + } + + # special case the NodeFilter + if (defined $needsCustom{"NodeFilter"}) { + my $paramName = $needsCustom{"NodeFilter"}; + push(@functionContent, " RefPtr<WebCore::NodeFilter> nativeNodeFilter;\n"); + push(@functionContent, " if ($paramName)\n"); + push(@functionContent, " nativeNodeFilter = WebCore::NodeFilter::create(WebCore::ObjCNodeFilterCondition::create($paramName));\n"); + } + + # FIXME! We need [Custom] support for ObjC, to move these hacks into DOMSVGLength/MatrixCustom.mm my $svgMatrixRotateFromVector = ($podType and $podType eq "AffineTransform" and $functionName eq "rotateFromVector"); my $svgMatrixInverse = ($podType and $podType eq "AffineTransform" and $functionName eq "inverse"); + my $svgLengthConvertToSpecifiedUnits = ($podType and $podType eq "SVGLength" and $functionName eq "convertToSpecifiedUnits"); push(@parameterNames, "ec") if $raisesExceptions and !($svgMatrixRotateFromVector || $svgMatrixInverse); my $content = $caller . "->" . $codeGenerator->WK_lcfirst($functionName) . "(" . join(", ", @parameterNames) . ")"; @@ -1301,6 +1465,8 @@ sub GenerateImplementation push(@functionContent, " ec = WebCore::SVGException::SVG_MATRIX_NOT_INVERTABLE;\n"); push(@functionContent, " $exceptionRaiseOnError\n"); push(@functionContent, " return [DOMSVGMatrix _wrapSVGMatrix:$content];\n"); + } elsif ($svgLengthConvertToSpecifiedUnits) { + push(@functionContent, " IMPL->convertToSpecifiedUnits(inUnitType, 0 /* FIXME */);\n"); } elsif ($returnType eq "void") { # Special case 'void' return type. if ($raisesExceptions) { @@ -1377,10 +1543,10 @@ sub GenerateImplementation my $deprecatedFunctionSig = $functionSig; $deprecatedFunctionSig =~ s/\s\w+:/ :/g; # remove parameter names - push(@deprecatedFunctions, "$deprecatedFunctionSig\n"); - push(@deprecatedFunctions, "{\n"); - push(@deprecatedFunctions, @functionContent); - push(@deprecatedFunctions, "}\n\n"); + push(@implContent, "$deprecatedFunctionSig\n"); + push(@implContent, "{\n"); + push(@implContent, @functionContent); + push(@implContent, "}\n\n"); } # Clear the hash @@ -1391,75 +1557,12 @@ sub GenerateImplementation # END implementation push(@implContent, "\@end\n"); - if (@deprecatedFunctions > 0) { - # - Deprecated category @implementation - push(@implContent, "\n\@implementation $className (" . $className . "Deprecated)\n\n"); - push(@implContent, @deprecatedFunctions); - push(@implContent, "\@end\n"); - } - - # Generate internal interfaces - - # - Type-Getter - # - (WebCore::FooBar *)_fooBar for implementation class FooBar - my $typeGetterName = GetObjCTypeGetterName($interfaceName); - my $typeGetterSig = "- " . ($podType ? "($podTypeWithNamespace)" : "($implClassNameWithNamespace *)") . $typeGetterName; - - my @ivarsToRetain = (); - my $ivarsToInit = ""; - my $typeMakerSigAddition = ""; - if (@ivars > 0) { - my @ivarsInitSig = (); - my @ivarsInitCall = (); - foreach $attribute (@ivars) { - my $name = $attribute->signature->name; - my $memberName = "m_" . $name; - my $varName = "in" . $name; - my $type = GetObjCType($attribute->signature->type); - push(@ivarsInitSig, "$name:($type)$varName"); - push(@ivarsInitCall, "$name:$varName"); - push(@ivarsToRetain, " $memberName = [$varName retain];\n"); - } - $ivarsToInit = " " . join(" ", @ivarsInitCall); - $typeMakerSigAddition = " " . join(" ", @ivarsInitSig); - } - - # - Type-Maker - my $typeMakerName = GetObjCTypeMaker($interfaceName); - my $typeMakerSig = "+ ($className *)$typeMakerName:($implClassNameWithNamespace *)impl" . $typeMakerSigAddition; - $typeMakerSig = "+ ($className *)$typeMakerName:($podTypeWithNamespace)impl" . $typeMakerSigAddition if $podType; - - # Generate interface definitions. - @internalHeaderContent = split("\r", $implementationLicenceTemplate); - push(@internalHeaderContent, "\n#import <WebCore/$className.h>\n"); - if ($interfaceName eq "Node") { - push(@internalHeaderContent, "\n\@protocol DOMEventTarget;\n"); - } - if ($codeGenerator->IsSVGAnimatedType($interfaceName)) { - push(@internalHeaderContent, "#import <WebCore/SVGAnimatedTemplate.h>\n\n"); - } else { - if ($podType and $podType ne "float") { - push(@internalHeaderContent, "\nnamespace WebCore { class $podType; }\n\n"); - } elsif ($interfaceName eq "Node") { - push(@internalHeaderContent, "\nnamespace WebCore { class Node; class EventTarget; }\n\n"); - } else { - push(@internalHeaderContent, "\nnamespace WebCore { class $implClassName; }\n\n"); - } - } - - push(@internalHeaderContent, "\@interface $className (WebCoreInternal)\n"); - push(@internalHeaderContent, $typeGetterSig . ";\n"); - push(@internalHeaderContent, $typeMakerSig . ";\n"); - if ($interfaceName eq "Node") { - push(@internalHeaderContent, "+ (id <DOMEventTarget>)_wrapEventTarget:(WebCore::EventTarget *)eventTarget;\n"); - } - push(@internalHeaderContent, "\@end\n"); - unless ($dataNode->extendedAttributes->{ObjCCustomInternalImpl}) { # - BEGIN WebCoreInternal category @implementation push(@implContent, "\n\@implementation $className (WebCoreInternal)\n\n"); + my $typeGetterSig = GetInternalTypeGetterSignature($interfaceName, $podType); push(@implContent, "$typeGetterSig\n"); push(@implContent, "{\n"); @@ -1471,6 +1574,8 @@ sub GenerateImplementation push(@implContent, "}\n\n"); + my ($typeMakerSig, $typeMakerSigAddition, $ivarsToInit) = GetInternalTypeMakerSignature($interfaceName, $podType); + if ($podType) { # - (id)_initWithFooBar:(WebCore::FooBar)impl for implementation class FooBar my $initWithImplName = "_initWith" . $implClassName; diff --git a/WebCore/bindings/scripts/IDLStructure.pm b/WebCore/bindings/scripts/IDLStructure.pm index 4d41350..5a59ff1 100644 --- a/WebCore/bindings/scripts/IDLStructure.pm +++ b/WebCore/bindings/scripts/IDLStructure.pm @@ -80,7 +80,7 @@ $idlType = '[a-zA-Z0-9_]'; # Generic type/"value string" identifier $idlDataType = '[a-zA-Z0-9\ ]'; # Generic data type identifier # Magic IDL parsing regular expressions -my $supportedTypes = "((?:unsigned )?(?:int|short|long)|(?:$idlIdNs*))"; +my $supportedTypes = "((?:unsigned )?(?:int|short|(?:long )?long)|(?:$idlIdNs*))"; # Special IDL notations $extendedAttributeSyntax = '\[[^]]*\]'; # Used for extended attributes diff --git a/WebCore/bindings/scripts/InFilesParser.pm b/WebCore/bindings/scripts/InFilesParser.pm new file mode 100644 index 0000000..89664ed --- /dev/null +++ b/WebCore/bindings/scripts/InFilesParser.pm @@ -0,0 +1,140 @@ +#!/usr/bin/perl -w + +# Copyright (C) 2008 Julien Chaffraix <jchaffraix@webkit.org> +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# +# THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY +# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +# OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# + +use strict; + +package InFilesParser; + +my $isParsingCommonParameters; +my $hasStartedParsing; + +# Helper functions + +sub trimComment +{ + my $string = shift; + $string =~ s/#.+$//; + chomp($string); + return $string; +} + +sub trimWS +{ + my $string = shift; + $string =~ s/^\s+//; + $string =~ s/\s+$//; + chomp($string); + return $string; +} + +sub trimQuoteAndWS +{ + my $string = shift; + $string =~ s/\"([^\"]+)\"/$1/; + return trimWS($string); +} + +# Default constructor + +sub new +{ + my $object = shift; + my $reference = { }; + + # Initialize the parser. + $isParsingCommonParameters = 1; + $hasStartedParsing = 0; + + bless($reference, $object); + return $reference; +} + +# parse take 3 attributes: +# - the filestream to read from (the caller has to open / close it). +# - the commonParameterHandler called when parsing the first part of the file with the parameter and the value. +# - the perTagHandler called for each optional parameter with the element name, the parameter and its value. +# If no parameter were provided, it is called once with an empty parameter and value. +sub parse($) +{ + my $object = shift; + my $fileStream = shift; # IO::File only + my $commonParameterHandler = shift; + my $perTagHandler = shift; + + foreach (<$fileStream>) { + # Empty line, change from common parameter part + # to per tag part if we have started parsing. + if (/^$/) { + if ($hasStartedParsing) { + $isParsingCommonParameters = 0; + } + next; + } + + # There may be a few empty lines at the beginning of the file + # so detect the first non empty line which starts the common + # parameters part. + $hasStartedParsing = 1; + + if (/^#/) { + next; + } + + $_ = trimComment($_); + + if ($isParsingCommonParameters) { + my ($name, $value) = split '=', $_; + + $name = trimWS($name); + $value = trimQuoteAndWS($value); + + &$commonParameterHandler($name, $value); + } else { + # Parsing per-tag parameters. + + # Split the tag name ($1) from the optionnal parameter(s) ($2) + /^(\S+)\s*(.*)$/; + my $elementName = $1; + + if ($2) { + my @options = split "," , $2; + my ($option, $value); + for (my $i = 0; $i < @options; ++$i) { + ($option, $value) = split "=", $options[$i]; + $option = trimWS($option); + $value = trimQuoteAndWS($value); + + &$perTagHandler($elementName, $option, $value); + } + } else { + # No parameter was given so call it with empty strings. + &$perTagHandler($elementName, "", ""); + } + } + } +} + +1; diff --git a/WebCore/bindings/scripts/generate-bindings.pl b/WebCore/bindings/scripts/generate-bindings.pl index afc730e..9c374bf 100755 --- a/WebCore/bindings/scripts/generate-bindings.pl +++ b/WebCore/bindings/scripts/generate-bindings.pl @@ -44,7 +44,7 @@ my $defines; my $preprocessor; GetOptions('include=s@' => \@idlDirectories, - 'outputdir=s' => \$outputDirectory, + 'outputDir=s' => \$outputDirectory, 'generator=s' => \$generator, 'defines=s' => \$defines, 'preprocessor=s' => \$preprocessor); |