tizen beta release
[profile/ivi/webkit-efl.git] / Source / WebCore / bindings / v8 / V8DOMWrapper.cpp
1 /*
2  * Copyright (C) 2009 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 "V8DOMWrapper.h"
33
34 #include "ArrayBufferView.h"
35 #include "CSSMutableStyleDeclaration.h"
36 #include "DOMDataStore.h"
37 #include "DocumentLoader.h"
38 #include "EventTargetHeaders.h"
39 #include "EventTargetInterfaces.h"
40 #include "FrameLoaderClient.h"
41 #include "V8AbstractEventListener.h"
42 #include "V8Binding.h"
43 #include "V8Collection.h"
44 #include "V8DOMMap.h"
45 #include "V8EventListener.h"
46 #include "V8EventListenerList.h"
47 #include "V8HTMLCollection.h"
48 #include "V8HTMLDocument.h"
49 #include "V8HiddenPropertyName.h"
50 #include "V8IsolatedContext.h"
51 #include "V8Location.h"
52 #include "V8NamedNodeMap.h"
53 #include "V8NodeFilterCondition.h"
54 #include "V8NodeList.h"
55 #include "V8Proxy.h"
56 #include "V8StyleSheet.h"
57 #include "V8WorkerContextEventListener.h"
58 #include "WebGLContextAttributes.h"
59 #include "WebGLUniformLocation.h"
60 #include "WorkerContextExecutionProxy.h"
61 #include "WrapperTypeInfo.h"
62 #include <algorithm>
63 #include <utility>
64 #include <v8-debug.h>
65 #include <wtf/Assertions.h>
66 #include <wtf/OwnArrayPtr.h>
67 #include <wtf/StdLibExtras.h>
68 #include <wtf/UnusedParam.h>
69
70 namespace WebCore {
71
72 typedef HashMap<Node*, v8::Object*> DOMNodeMap;
73 typedef HashMap<void*, v8::Object*> DOMObjectMap;
74
75 // The caller must have increased obj's ref count.
76 void V8DOMWrapper::setJSWrapperForDOMObject(void* object, v8::Persistent<v8::Object> wrapper)
77 {
78     ASSERT(V8DOMWrapper::maybeDOMWrapper(wrapper));
79     ASSERT(!domWrapperType(wrapper)->toActiveDOMObjectFunction);
80     getDOMObjectMap().set(object, wrapper);
81 }
82
83 // The caller must have increased obj's ref count.
84 void V8DOMWrapper::setJSWrapperForActiveDOMObject(void* object, v8::Persistent<v8::Object> wrapper)
85 {
86     ASSERT(V8DOMWrapper::maybeDOMWrapper(wrapper));
87     ASSERT(domWrapperType(wrapper)->toActiveDOMObjectFunction);
88     getActiveDOMObjectMap().set(object, wrapper);
89 }
90
91 // The caller must have increased node's ref count.
92 void V8DOMWrapper::setJSWrapperForDOMNode(Node* node, v8::Persistent<v8::Object> wrapper)
93 {
94     ASSERT(V8DOMWrapper::maybeDOMWrapper(wrapper));
95     if (node->isActiveNode())
96         getActiveDOMNodeMap().set(node, wrapper);
97     else
98         getDOMNodeMap().set(node, wrapper);
99 }
100
101 v8::Local<v8::Function> V8DOMWrapper::getConstructor(WrapperTypeInfo* type, v8::Handle<v8::Value> objectPrototype)
102 {
103     // A DOM constructor is a function instance created from a DOM constructor
104     // template. There is one instance per context. A DOM constructor is
105     // different from a normal function in two ways:
106     //   1) it cannot be called as constructor (aka, used to create a DOM object)
107     //   2) its __proto__ points to Object.prototype rather than
108     //      Function.prototype.
109     // The reason for 2) is that, in Safari, a DOM constructor is a normal JS
110     // object, but not a function. Hotmail relies on the fact that, in Safari,
111     // HTMLElement.__proto__ == Object.prototype.
112     v8::Handle<v8::FunctionTemplate> functionTemplate = type->getTemplate();
113     // Getting the function might fail if we're running out of
114     // stack or memory.
115     v8::TryCatch tryCatch;
116     v8::Local<v8::Function> value = functionTemplate->GetFunction();
117     if (value.IsEmpty())
118         return v8::Local<v8::Function>();
119     // Hotmail fix, see comments above.
120     if (!objectPrototype.IsEmpty())
121         value->SetPrototype(objectPrototype);
122     return value;
123 }
124
125 v8::Local<v8::Function> V8DOMWrapper::getConstructorForContext(WrapperTypeInfo* type, v8::Handle<v8::Context> context)
126 {
127     // Enter the scope for this context to get the correct constructor.
128     v8::Context::Scope scope(context);
129
130     return getConstructor(type, V8DOMWindowShell::getHiddenObjectPrototype(context));
131 }
132
133 v8::Local<v8::Function> V8DOMWrapper::getConstructor(WrapperTypeInfo* type, DOMWindow* window)
134 {
135     Frame* frame = window->frame();
136     if (!frame)
137         return v8::Local<v8::Function>();
138
139     v8::Handle<v8::Context> context = V8Proxy::context(frame);
140     if (context.IsEmpty())
141         return v8::Local<v8::Function>();
142
143     return getConstructorForContext(type, context);
144 }
145
146 #if ENABLE(WORKERS)
147 v8::Local<v8::Function> V8DOMWrapper::getConstructor(WrapperTypeInfo* type, WorkerContext*)
148 {
149     WorkerScriptController* controller = WorkerScriptController::controllerForContext();
150     WorkerContextExecutionProxy* proxy = controller ? controller->proxy() : 0;
151     if (!proxy)
152         return v8::Local<v8::Function>();
153
154     v8::Handle<v8::Context> context = proxy->context();
155     if (context.IsEmpty())
156         return v8::Local<v8::Function>();
157
158     return getConstructorForContext(type, context);
159 }
160 #endif
161
162
163 void V8DOMWrapper::setNamedHiddenReference(v8::Handle<v8::Object> parent, const char* name, v8::Handle<v8::Value> child)
164 {
165     parent->SetHiddenValue(V8HiddenPropertyName::hiddenReferenceName(name), child);
166 }
167
168 void V8DOMWrapper::setNamedHiddenWindowReference(Frame* frame, const char* name, v8::Handle<v8::Value> jsObject)
169 {
170     // Get DOMWindow
171     if (!frame)
172         return; // Object might be detached from window
173     v8::Handle<v8::Context> context = V8Proxy::context(frame);
174     if (context.IsEmpty())
175         return;
176
177     v8::Handle<v8::Object> global = context->Global();
178     // Look for real DOM wrapper.
179     global = V8DOMWrapper::lookupDOMWrapper(V8DOMWindow::GetTemplate(), global);
180     ASSERT(!global.IsEmpty());
181
182     setNamedHiddenReference(global, name, jsObject);
183 }
184
185 WrapperTypeInfo* V8DOMWrapper::domWrapperType(v8::Handle<v8::Object> object)
186 {
187     ASSERT(V8DOMWrapper::maybeDOMWrapper(object));
188     return static_cast<WrapperTypeInfo*>(object->GetPointerFromInternalField(v8DOMWrapperTypeIndex));
189 }
190
191 PassRefPtr<NodeFilter> V8DOMWrapper::wrapNativeNodeFilter(v8::Handle<v8::Value> filter)
192 {
193     // A NodeFilter is used when walking through a DOM tree or iterating tree
194     // nodes.
195     // FIXME: we may want to cache NodeFilterCondition and NodeFilter
196     // object, but it is minor.
197     // NodeFilter is passed to NodeIterator that has a ref counted pointer
198     // to NodeFilter. NodeFilter has a ref counted pointer to NodeFilterCondition.
199     // In NodeFilterCondition, filter object is persisted in its constructor,
200     // and disposed in its destructor.
201     return NodeFilter::create(V8NodeFilterCondition::create(filter));
202 }
203
204 v8::Local<v8::Object> V8DOMWrapper::instantiateV8Object(V8Proxy* proxy, WrapperTypeInfo* type, void* impl)
205 {
206 #if ENABLE(WORKERS)
207     WorkerContext* workerContext = 0;
208 #endif
209     if (V8IsolatedContext::getEntered()) {
210         // This effectively disables the wrapper cache for isolated worlds.
211         proxy = 0;
212         // FIXME: Do we need a wrapper cache for the isolated world?  We should
213         //        see if the performance gains are worth while.
214         // We'll get one once we give the isolated context a proper window shell.
215     } else if (!proxy) {
216         v8::Handle<v8::Context> context = v8::Context::GetCurrent();
217         if (!context.IsEmpty()) {
218             v8::Handle<v8::Object> globalPrototype = v8::Handle<v8::Object>::Cast(context->Global()->GetPrototype());
219             if (isWrapperOfType(globalPrototype, &V8DOMWindow::info))
220                 proxy = V8Proxy::retrieve(V8DOMWindow::toNative(globalPrototype)->frame());
221 #if ENABLE(WORKERS)
222             else
223                 workerContext = V8WorkerContext::toNative(lookupDOMWrapper(V8WorkerContext::GetTemplate(), context->Global()));
224 #endif
225         }
226     }
227
228     v8::Local<v8::Object> instance;
229     if (proxy)
230         // FIXME: Fix this to work properly with isolated worlds (see above).
231         instance = proxy->windowShell()->createWrapperFromCache(type);
232     else {
233         v8::Local<v8::Function> function;
234 #if ENABLE(WORKERS)
235         if (workerContext)
236             function = getConstructor(type, workerContext);
237         else
238 #endif
239             function = type->getTemplate()->GetFunction();
240         instance = SafeAllocation::newInstance(function);
241     }
242     if (!instance.IsEmpty()) {
243         // Avoid setting the DOM wrapper for failed allocations.
244         setDOMWrapper(instance, type, impl);
245         if (type == &V8HTMLDocument::info)
246             instance = V8HTMLDocument::WrapInShadowObject(instance, static_cast<Node*>(impl));
247     }
248     return instance;
249 }
250
251 #ifndef NDEBUG
252 bool V8DOMWrapper::maybeDOMWrapper(v8::Handle<v8::Value> value)
253 {
254     if (value.IsEmpty() || !value->IsObject())
255         return false;
256
257     v8::Handle<v8::Object> object = v8::Handle<v8::Object>::Cast(value);
258     if (!object->InternalFieldCount())
259         return false;
260
261     ASSERT(object->InternalFieldCount() >= v8DefaultWrapperInternalFieldCount);
262
263     v8::Handle<v8::Value> wrapper = object->GetInternalField(v8DOMWrapperObjectIndex);
264     ASSERT(wrapper->IsNumber() || wrapper->IsExternal());
265
266     return true;
267 }
268 #endif
269
270 bool V8DOMWrapper::isValidDOMObject(v8::Handle<v8::Value> value)
271 {
272     if (value.IsEmpty() || !value->IsObject())
273         return false;
274     return v8::Handle<v8::Object>::Cast(value)->InternalFieldCount();
275 }
276
277 bool V8DOMWrapper::isWrapperOfType(v8::Handle<v8::Value> value, WrapperTypeInfo* type)
278 {
279     if (!isValidDOMObject(value))
280         return false;
281
282     v8::Handle<v8::Object> object = v8::Handle<v8::Object>::Cast(value);
283     ASSERT(object->InternalFieldCount() >= v8DefaultWrapperInternalFieldCount);
284
285     v8::Handle<v8::Value> wrapper = object->GetInternalField(v8DOMWrapperObjectIndex);
286     ASSERT_UNUSED(wrapper, wrapper->IsNumber() || wrapper->IsExternal());
287
288     WrapperTypeInfo* typeInfo = static_cast<WrapperTypeInfo*>(object->GetPointerFromInternalField(v8DOMWrapperTypeIndex));
289     return typeInfo == type;
290 }
291
292 v8::Handle<v8::Object> V8DOMWrapper::getWrapperSlow(Node* node)
293 {
294     V8IsolatedContext* context = V8IsolatedContext::getEntered();
295     if (LIKELY(!context)) {
296         v8::Persistent<v8::Object>* wrapper = node->wrapper();
297         if (!wrapper)
298             return v8::Handle<v8::Object>();
299         return *wrapper;
300     }
301     DOMDataStore* store = context->world()->domDataStore();
302     DOMNodeMapping& domNodeMap = node->isActiveNode() ? store->activeDomNodeMap() : store->domNodeMap();
303     return domNodeMap.get(node);
304 }
305
306 #define TRY_TO_WRAP_WITH_INTERFACE(interfaceName) \
307     if (eventNames().interfaceFor##interfaceName == desiredInterface) \
308         return toV8(static_cast<interfaceName*>(target));
309
310 // A JS object of type EventTarget is limited to a small number of possible classes.
311 v8::Handle<v8::Value> V8DOMWrapper::convertEventTargetToV8Object(EventTarget* target)
312 {
313     if (!target)
314         return v8::Null();
315
316     AtomicString desiredInterface = target->interfaceName();
317     DOM_EVENT_TARGET_INTERFACES_FOR_EACH(TRY_TO_WRAP_WITH_INTERFACE)
318
319     ASSERT_NOT_REACHED();
320     return notHandledByInterceptor();
321 }
322
323 PassRefPtr<EventListener> V8DOMWrapper::getEventListener(v8::Local<v8::Value> value, bool isAttribute, ListenerLookupType lookup)
324 {
325     v8::Handle<v8::Context> context = v8::Context::GetCurrent();
326     if (context.IsEmpty())
327         return 0;
328     if (lookup == ListenerFindOnly)
329         return V8EventListenerList::findWrapper(value, isAttribute);
330     v8::Handle<v8::Object> globalPrototype = v8::Handle<v8::Object>::Cast(context->Global()->GetPrototype());
331     if (isWrapperOfType(globalPrototype, &V8DOMWindow::info))
332         return V8EventListenerList::findOrCreateWrapper<V8EventListener>(value, isAttribute);
333 #if ENABLE(WORKERS)
334     return V8EventListenerList::findOrCreateWrapper<V8WorkerContextEventListener>(value, isAttribute);
335 #else
336     return 0;
337 #endif
338 }
339
340 // XPath-related utilities
341 RefPtr<XPathNSResolver> V8DOMWrapper::getXPathNSResolver(v8::Handle<v8::Value> value, V8Proxy* proxy)
342 {
343     RefPtr<XPathNSResolver> resolver;
344     if (V8XPathNSResolver::HasInstance(value))
345         resolver = V8XPathNSResolver::toNative(v8::Handle<v8::Object>::Cast(value));
346     else if (value->IsObject())
347         resolver = V8CustomXPathNSResolver::create(value->ToObject());
348     return resolver;
349 }
350
351 }  // namespace WebCore