Upstream version 5.34.98.0
[platform/framework/web/crosswalk.git] / src / third_party / WebKit / Source / bindings / v8 / CustomElementConstructorBuilder.cpp
1 /*
2  * Copyright (C) 2013 Google Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions are
6  * met:
7  *
8  *     * Redistributions of source code must retain the above copyright
9  * notice, this list of conditions and the following disclaimer.
10  *     * Redistributions in binary form must reproduce the above
11  * copyright notice, this list of conditions and the following disclaimer
12  * in the documentation and/or other materials provided with the
13  * distribution.
14  *     * Neither the name of Google Inc. nor the names of its
15  * contributors may be used to endorse or promote products derived from
16  * this software without specific prior written permission.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29  */
30
31 #include "config.h"
32 #include "bindings/v8/CustomElementConstructorBuilder.h"
33
34 #include "HTMLNames.h"
35 #include "SVGNames.h"
36 #include "V8Document.h"
37 #include "V8HTMLElementWrapperFactory.h"
38 #include "V8SVGElementWrapperFactory.h"
39 #include "bindings/v8/CustomElementBinding.h"
40 #include "bindings/v8/DOMWrapperWorld.h"
41 #include "bindings/v8/Dictionary.h"
42 #include "bindings/v8/ExceptionState.h"
43 #include "bindings/v8/ScriptState.h"
44 #include "bindings/v8/UnsafePersistent.h"
45 #include "bindings/v8/V8Binding.h"
46 #include "bindings/v8/V8PerContextData.h"
47 #include "core/dom/Document.h"
48 #include "core/dom/custom/CustomElementCallbackDispatcher.h"
49 #include "core/dom/custom/CustomElementDefinition.h"
50 #include "core/dom/custom/CustomElementDescriptor.h"
51 #include "core/dom/custom/CustomElementException.h"
52 #include "wtf/Assertions.h"
53
54 namespace WebCore {
55
56 static void constructCustomElement(const v8::FunctionCallbackInfo<v8::Value>&);
57
58 CustomElementConstructorBuilder::CustomElementConstructorBuilder(ScriptState* state, const Dictionary* options)
59     : m_context(state->context())
60     , m_options(options)
61     , m_wrapperType(0)
62 {
63     ASSERT(m_context == v8::Isolate::GetCurrent()->GetCurrentContext());
64 }
65
66 bool CustomElementConstructorBuilder::isFeatureAllowed() const
67 {
68     // Check that we are in the main world
69     return !DOMWrapperWorld::isolatedWorld(m_context);
70 }
71
72 bool CustomElementConstructorBuilder::validateOptions(const AtomicString& type, QualifiedName& tagName, ExceptionState& exceptionState)
73 {
74     ASSERT(m_prototype.IsEmpty());
75
76     ScriptValue prototypeScriptValue;
77     if (m_options->get("prototype", prototypeScriptValue) && !prototypeScriptValue.isNull()) {
78         if (!prototypeScriptValue.isObject()) {
79             CustomElementException::throwException(CustomElementException::PrototypeNotAnObject, type, exceptionState);
80             return false;
81         }
82         m_prototype = prototypeScriptValue.v8Value().As<v8::Object>();
83     } else {
84         m_prototype = v8::Object::New(m_context->GetIsolate());
85         v8::Local<v8::Object> basePrototype = V8PerContextData::from(m_context)->prototypeForType(&V8HTMLElement::wrapperTypeInfo);
86         if (!basePrototype.IsEmpty())
87             m_prototype->SetPrototype(basePrototype);
88     }
89
90     AtomicString extends;
91     bool extendsProvidedAndNonNull = m_options->get("extends", extends);
92
93     if (!V8PerContextData::from(m_context)) {
94         // FIXME: This should generate an InvalidContext exception at a later point.
95         CustomElementException::throwException(CustomElementException::ContextDestroyedCheckingPrototype, type, exceptionState);
96         return false;
97     }
98
99     AtomicString namespaceURI = HTMLNames::xhtmlNamespaceURI;
100     if (hasValidPrototypeChainFor(&V8SVGElement::wrapperTypeInfo))
101         namespaceURI = SVGNames::svgNamespaceURI;
102
103     AtomicString localName;
104
105     if (extendsProvidedAndNonNull) {
106         localName = extends.lower();
107
108         if (!Document::isValidName(localName)) {
109             CustomElementException::throwException(CustomElementException::ExtendsIsInvalidName, type, exceptionState);
110             return false;
111         }
112         if (CustomElement::isValidName(localName)) {
113             CustomElementException::throwException(CustomElementException::ExtendsIsCustomElementName, type, exceptionState);
114             return false;
115         }
116     } else {
117         if (namespaceURI == SVGNames::svgNamespaceURI) {
118             CustomElementException::throwException(CustomElementException::ExtendsIsInvalidName, type, exceptionState);
119             return false;
120         }
121         localName = type;
122     }
123
124     if (!extendsProvidedAndNonNull)
125         m_wrapperType = &V8HTMLElement::wrapperTypeInfo;
126     else if (namespaceURI == HTMLNames::xhtmlNamespaceURI)
127         m_wrapperType = findWrapperTypeForHTMLTagName(localName);
128     else
129         m_wrapperType = findWrapperTypeForSVGTagName(localName);
130
131     ASSERT(m_wrapperType);
132     tagName = QualifiedName(nullAtom, localName, namespaceURI);
133     return m_wrapperType;
134 }
135
136 PassRefPtr<CustomElementLifecycleCallbacks> CustomElementConstructorBuilder::createCallbacks()
137 {
138     ASSERT(!m_prototype.IsEmpty());
139
140     RefPtr<ExecutionContext> executionContext(toExecutionContext(m_context));
141
142     v8::TryCatch exceptionCatcher;
143     exceptionCatcher.SetVerbose(true);
144
145     v8::Isolate* isolate = v8::Isolate::GetCurrent();
146     v8::Handle<v8::Function> created = retrieveCallback(isolate, "createdCallback");
147     v8::Handle<v8::Function> attached = retrieveCallback(isolate, "attachedCallback");
148     v8::Handle<v8::Function> detached = retrieveCallback(isolate, "detachedCallback");
149     v8::Handle<v8::Function> attributeChanged = retrieveCallback(isolate, "attributeChangedCallback");
150
151     m_callbacks = V8CustomElementLifecycleCallbacks::create(executionContext.get(), m_prototype, created, attached, detached, attributeChanged);
152     return m_callbacks.get();
153 }
154
155 v8::Handle<v8::Function> CustomElementConstructorBuilder::retrieveCallback(v8::Isolate* isolate, const char* name)
156 {
157     v8::Handle<v8::Value> value = m_prototype->Get(v8String(isolate, name));
158     if (value.IsEmpty() || !value->IsFunction())
159         return v8::Handle<v8::Function>();
160     return value.As<v8::Function>();
161 }
162
163 bool CustomElementConstructorBuilder::createConstructor(Document* document, CustomElementDefinition* definition, ExceptionState& exceptionState)
164 {
165     ASSERT(!m_prototype.IsEmpty());
166     ASSERT(m_constructor.IsEmpty());
167     ASSERT(document);
168
169     v8::Isolate* isolate = m_context->GetIsolate();
170
171     if (!prototypeIsValid(definition->descriptor().type(), exceptionState))
172         return false;
173
174     v8::Local<v8::FunctionTemplate> constructorTemplate = v8::FunctionTemplate::New(isolate);
175     constructorTemplate->SetCallHandler(constructCustomElement);
176     m_constructor = constructorTemplate->GetFunction();
177     if (m_constructor.IsEmpty()) {
178         CustomElementException::throwException(CustomElementException::ContextDestroyedRegisteringDefinition, definition->descriptor().type(), exceptionState);
179         return false;
180     }
181
182     const CustomElementDescriptor& descriptor = definition->descriptor();
183
184     v8::Handle<v8::String> v8TagName = v8String(isolate, descriptor.localName());
185     v8::Handle<v8::Value> v8Type;
186     if (descriptor.isTypeExtension())
187         v8Type = v8String(isolate, descriptor.type());
188     else
189         v8Type = v8::Null(isolate);
190
191     m_constructor->SetName(v8Type->IsNull() ? v8TagName : v8Type.As<v8::String>());
192
193     setHiddenValue(isolate, m_constructor, "customElementDocument", toV8(document, m_context->Global(), isolate));
194     setHiddenValue(isolate, m_constructor, "customElementNamespaceURI", v8String(isolate, descriptor.namespaceURI()));
195     setHiddenValue(isolate, m_constructor, "customElementTagName", v8TagName);
196     setHiddenValue(isolate, m_constructor, "customElementType", v8Type);
197
198     v8::Handle<v8::String> prototypeKey = v8String(isolate, "prototype");
199     ASSERT(m_constructor->HasOwnProperty(prototypeKey));
200     // This sets the property *value*; calling Set is safe because
201     // "prototype" is a non-configurable data property so there can be
202     // no side effects.
203     m_constructor->Set(prototypeKey, m_prototype);
204     // This *configures* the property. ForceSet of a function's
205     // "prototype" does not affect the value, but can reconfigure the
206     // property.
207     m_constructor->ForceSet(prototypeKey, m_prototype, v8::PropertyAttribute(v8::ReadOnly | v8::DontEnum | v8::DontDelete));
208
209     setHiddenValue(isolate, m_prototype, "customElementIsInterfacePrototypeObject", v8::True(isolate));
210     m_prototype->ForceSet(v8String(isolate, "constructor"), m_constructor, v8::DontEnum);
211
212     return true;
213 }
214
215 bool CustomElementConstructorBuilder::prototypeIsValid(const AtomicString& type, ExceptionState& exceptionState) const
216 {
217     if (m_prototype->InternalFieldCount() || !getHiddenValue(m_context->GetIsolate(), m_prototype, "customElementIsInterfacePrototypeObject").IsEmpty()) {
218         CustomElementException::throwException(CustomElementException::PrototypeInUse, type, exceptionState);
219         return false;
220     }
221
222     if (m_prototype->GetPropertyAttributes(v8String(m_context->GetIsolate(), "constructor")) & v8::DontDelete) {
223         CustomElementException::throwException(CustomElementException::ConstructorPropertyNotConfigurable, type, exceptionState);
224         return false;
225     }
226
227     return true;
228 }
229
230 bool CustomElementConstructorBuilder::didRegisterDefinition(CustomElementDefinition* definition) const
231 {
232     ASSERT(!m_constructor.IsEmpty());
233
234     return m_callbacks->setBinding(definition, CustomElementBinding::create(m_context->GetIsolate(), m_prototype, m_wrapperType));
235 }
236
237 ScriptValue CustomElementConstructorBuilder::bindingsReturnValue() const
238 {
239     return ScriptValue(m_constructor, m_context->GetIsolate());
240 }
241
242 bool CustomElementConstructorBuilder::hasValidPrototypeChainFor(const WrapperTypeInfo* type) const
243 {
244     v8::Handle<v8::Object> elementPrototype = V8PerContextData::from(m_context)->prototypeForType(type);
245     if (elementPrototype.IsEmpty())
246         return false;
247
248     v8::Handle<v8::Value> chain = m_prototype;
249     while (!chain.IsEmpty() && chain->IsObject()) {
250         if (chain == elementPrototype)
251             return true;
252         chain = chain.As<v8::Object>()->GetPrototype();
253     }
254
255     return false;
256 }
257
258 static void constructCustomElement(const v8::FunctionCallbackInfo<v8::Value>& info)
259 {
260     v8::Isolate* isolate = info.GetIsolate();
261
262     if (!info.IsConstructCall()) {
263         throwTypeError("DOM object constructor cannot be called as a function.", isolate);
264         return;
265     }
266
267     if (info.Length() > 0) {
268         throwTypeError("This constructor should be called without arguments.", isolate);
269         return;
270     }
271
272     Document* document = V8Document::toNative(getHiddenValue(isolate, info.Callee(), "customElementDocument").As<v8::Object>());
273     V8TRYCATCH_FOR_V8STRINGRESOURCE_VOID(V8StringResource<>, namespaceURI, getHiddenValue(isolate, info.Callee(), "customElementNamespaceURI"));
274     V8TRYCATCH_FOR_V8STRINGRESOURCE_VOID(V8StringResource<>, tagName, getHiddenValue(isolate, info.Callee(), "customElementTagName"));
275     v8::Handle<v8::Value> maybeType = getHiddenValue(isolate, info.Callee(), "customElementType");
276     V8TRYCATCH_FOR_V8STRINGRESOURCE_VOID(V8StringResource<>, type, maybeType);
277
278     ExceptionState exceptionState(ExceptionState::ConstructionContext, "CustomElement", info.Holder(), info.GetIsolate());
279     CustomElementCallbackDispatcher::CallbackDeliveryScope deliveryScope;
280     RefPtr<Element> element = document->createElementNS(namespaceURI, tagName, maybeType->IsNull() ? nullAtom : type, exceptionState);
281     if (exceptionState.throwIfNeeded())
282         return;
283     v8SetReturnValueFast(info, element.release(), document);
284 }
285
286 } // namespace WebCore