QtQuick: Fix string related warnings, single character strings.
[profile/ivi/qtdeclarative.git] / src / qml / qml / v8 / qv8contextwrapper.cpp
1 /****************************************************************************
2 **
3 ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/
5 **
6 ** This file is part of the QtQml module of the Qt Toolkit.
7 **
8 ** $QT_BEGIN_LICENSE:LGPL$
9 ** GNU Lesser General Public License Usage
10 ** This file may be used under the terms of the GNU Lesser General Public
11 ** License version 2.1 as published by the Free Software Foundation and
12 ** appearing in the file LICENSE.LGPL included in the packaging of this
13 ** file. Please review the following information to ensure the GNU Lesser
14 ** General Public License version 2.1 requirements will be met:
15 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
16 **
17 ** In addition, as a special exception, Nokia gives you certain additional
18 ** rights. These rights are described in the Nokia Qt LGPL Exception
19 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
20 **
21 ** GNU General Public License Usage
22 ** Alternatively, this file may be used under the terms of the GNU General
23 ** Public License version 3.0 as published by the Free Software Foundation
24 ** and appearing in the file LICENSE.GPL included in the packaging of this
25 ** file. Please review the following information to ensure the GNU General
26 ** Public License version 3.0 requirements will be met:
27 ** http://www.gnu.org/copyleft/gpl.html.
28 **
29 ** Other Usage
30 ** Alternatively, this file may be used in accordance with the terms and
31 ** conditions contained in a signed written agreement between you and Nokia.
32 **
33 **
34 **
35 **
36 **
37 **
38 ** $QT_END_LICENSE$
39 **
40 ****************************************************************************/
41
42 #include "qv8contextwrapper_p.h"
43 #include "qv8engine_p.h"
44
45 #include <private/qqmlengine_p.h>
46 #include <private/qqmlcontext_p.h>
47
48 QT_BEGIN_NAMESPACE
49
50 static QString internal(QLatin1String("You've stumbled onto an internal implementation detail "
51                                       "that should never have been exposed."));
52
53 class QV8ContextResource : public QV8ObjectResource
54 {
55     V8_RESOURCE_TYPE(ContextType);
56
57 public:
58     QV8ContextResource(QV8Engine *engine, QQmlContextData *context, QObject *scopeObject);
59     ~QV8ContextResource();
60
61     inline QQmlContextData *getContext() const;
62     inline QObject *getScopeObject() const;
63
64     quint32 isSharedContext:1;
65     quint32 hasSubContexts:1;
66     quint32 readOnly:1;
67     quint32 dummy:29;
68
69     QObject *secondaryScope;
70
71     // This is a pretty horrible hack, and an abuse of external strings.  When we create a 
72     // sub-context (a context created by a Qt.include() in an external javascript file),
73     // we pass a specially crafted SubContext external string as the v8::Script::Data() to
74     // the script, which contains a pointer to the context.  We can then access the 
75     // v8::Script::Data() later on to resolve names and URLs against the sub-context instead
76     // of the main outer context.
77     struct SubContext : public v8::String::ExternalStringResource {
78         SubContext(QQmlContextData *context) : context(context) {}
79         QQmlGuardedContextData context;
80
81         virtual const uint16_t* data() const { return (const uint16_t *)internal.constData(); }
82         virtual size_t length() const { return internal.length(); }
83     };
84
85 private:
86     QQmlGuardedContextData context;
87     QQmlGuard<QObject> scopeObject;
88
89 };
90
91 QV8ContextResource::QV8ContextResource(QV8Engine *engine, QQmlContextData *context, QObject *scopeObject)
92 : QV8ObjectResource(engine), isSharedContext(false), hasSubContexts(false), readOnly(true), 
93   secondaryScope(0), context(context), scopeObject(scopeObject)
94 {
95 }
96
97 QV8ContextResource::~QV8ContextResource()
98 {
99     if (context && context->isJSContext)
100         context->destroy();
101 }
102
103 // Returns the scope object
104 QObject *QV8ContextResource::getScopeObject() const
105 {
106     if (isSharedContext)
107         return QQmlEnginePrivate::get(engine->engine())->sharedScope;
108     else
109         return scopeObject;
110 }
111
112 // Returns the context, including resolving a subcontext
113 QQmlContextData *QV8ContextResource::getContext() const
114 {
115     if (isSharedContext)
116         return QQmlEnginePrivate::get(engine->engine())->sharedContext;
117     
118     if (!hasSubContexts)
119         return context;
120
121     v8::Local<v8::Value> callingdata = v8::Context::GetCallingScriptData();
122     if (callingdata.IsEmpty() || !callingdata->IsString())
123         return context;
124
125     v8::Local<v8::String> callingstring = callingdata->ToString();
126     Q_ASSERT(callingstring->IsExternal());
127     Q_ASSERT(callingstring->GetExternalStringResource());
128
129     SubContext *sc = static_cast<SubContext *>(callingstring->GetExternalStringResource());
130     return sc->context;
131 }
132
133 QV8ContextWrapper::QV8ContextWrapper()
134 : m_engine(0)
135 {
136 }
137
138 QV8ContextWrapper::~QV8ContextWrapper()
139 {
140 }
141
142 void QV8ContextWrapper::destroy()
143 {
144     qPersistentDispose(m_sharedContext);
145     qPersistentDispose(m_urlConstructor);
146     qPersistentDispose(m_constructor);
147 }
148
149 void QV8ContextWrapper::init(QV8Engine *engine)
150 {
151     m_engine = engine;
152     {
153     v8::Local<v8::FunctionTemplate> ft = v8::FunctionTemplate::New();
154     ft->InstanceTemplate()->SetHasExternalResource(true);
155     ft->InstanceTemplate()->SetFallbackPropertyHandler(Getter, Setter);
156     m_constructor = qPersistentNew<v8::Function>(ft->GetFunction());
157     }
158     {
159     v8::Local<v8::FunctionTemplate> ft = v8::FunctionTemplate::New();
160     ft->InstanceTemplate()->SetHasExternalResource(true);
161     ft->InstanceTemplate()->SetFallbackPropertyHandler(NullGetter, NullSetter);
162     m_urlConstructor = qPersistentNew<v8::Function>(ft->GetFunction());
163     }
164     {
165     v8::Local<v8::Object> sharedContext = m_constructor->NewInstance();
166     QV8ContextResource *r = new QV8ContextResource(engine, 0, 0);
167     r->isSharedContext = true;
168     sharedContext->SetExternalResource(r);
169     m_sharedContext = qPersistentNew<v8::Object>(sharedContext);
170     }
171 }
172
173 v8::Local<v8::Object> QV8ContextWrapper::qmlScope(QQmlContextData *ctxt, QObject *scope)
174 {
175     // XXX NewInstance() should be optimized
176     v8::Local<v8::Object> rv = m_constructor->NewInstance(); 
177     QV8ContextResource *r = new QV8ContextResource(m_engine, ctxt, scope);
178     rv->SetExternalResource(r);
179     return rv;
180 }
181
182 v8::Local<v8::Object> QV8ContextWrapper::urlScope(const QUrl &url)
183 {
184     QQmlContextData *context = new QQmlContextData;
185     context->url = url;
186     context->isInternal = true;
187     context->isJSContext = true;
188
189     // XXX NewInstance() should be optimized
190     v8::Local<v8::Object> rv = m_urlConstructor->NewInstance(); 
191     QV8ContextResource *r = new QV8ContextResource(m_engine, context, 0);
192     rv->SetExternalResource(r);
193     return rv;
194 }
195
196 void QV8ContextWrapper::setReadOnly(v8::Handle<v8::Object> qmlglobal, bool readOnly)
197 {
198     QV8ContextResource *resource = v8_resource_cast<QV8ContextResource>(qmlglobal);
199     Q_ASSERT(resource);
200     resource->readOnly = readOnly;
201 }
202
203 void QV8ContextWrapper::addSubContext(v8::Handle<v8::Object> qmlglobal, v8::Handle<v8::Script> script, 
204                                       QQmlContextData *ctxt)
205 {
206     QV8ContextResource *resource = v8_resource_cast<QV8ContextResource>(qmlglobal);
207     Q_ASSERT(resource);
208     resource->hasSubContexts = true;
209     script->SetData(v8::String::NewExternal(new QV8ContextResource::SubContext(ctxt)));
210 }
211
212 QObject *QV8ContextWrapper::setSecondaryScope(v8::Handle<v8::Object> ctxt, QObject *scope)
213 {
214     QV8ContextResource *resource = v8_resource_cast<QV8ContextResource>(ctxt);
215     if (!resource) return 0;
216
217     QObject *rv = resource->secondaryScope;
218     resource->secondaryScope = scope;
219     return rv;
220 }
221
222 QQmlContextData *QV8ContextWrapper::callingContext()
223 {
224     v8::Local<v8::Object> qmlglobal = v8::Context::GetCallingQmlGlobal();
225     if (qmlglobal.IsEmpty()) return 0;
226
227     QV8ContextResource *r = v8_resource_cast<QV8ContextResource>(qmlglobal);
228     return r?r->getContext():0;
229 }
230
231 QQmlContextData *QV8ContextWrapper::context(v8::Handle<v8::Value> value)
232 {
233     if (!value->IsObject())
234         return 0;
235
236     v8::Handle<v8::Object> qmlglobal = v8::Handle<v8::Object>::Cast(value);
237     QV8ContextResource *r = v8_resource_cast<QV8ContextResource>(qmlglobal);
238     return r?r->getContext():0;
239 }
240
241 v8::Handle<v8::Value> QV8ContextWrapper::NullGetter(v8::Local<v8::String>,
242                                                     const v8::AccessorInfo &)
243 {
244     // V8 will throw a ReferenceError if appropriate ("typeof" should not throw)
245     return v8::Handle<v8::Value>();
246 }
247
248 v8::Handle<v8::Value> QV8ContextWrapper::Getter(v8::Local<v8::String> property, 
249                                                 const v8::AccessorInfo &info)
250 {
251     QV8ContextResource *resource = v8_resource_check<QV8ContextResource>(info.This());
252
253     // Its possible we could delay the calculation of the "actual" context (in the case
254     // of sub contexts) until it is definately needed.
255     QQmlContextData *context = resource->getContext();
256     QQmlContextData *expressionContext = context;
257
258     if (!context)
259         return v8::Undefined();
260
261     if (v8::Context::GetCallingQmlGlobal() != info.This())
262         return v8::Handle<v8::Value>();
263
264     // Search type (attached property/enum/imported scripts) names
265     // Secondary scope object
266     // while (context) {
267     //     Search context properties
268     //     Search scope object
269     //     Search context object
270     //     context = context->parent
271     // }
272
273     QV8Engine *engine = resource->engine;
274
275     QObject *scopeObject = resource->getScopeObject();
276
277     QHashedV8String propertystring(property);
278
279     if (context->imports && QV8Engine::startsWithUpper(property)) {
280         // Search for attached properties, enums and imported scripts
281         QQmlTypeNameCache::Result r = context->imports->query(propertystring);
282         
283         if (r.isValid()) { 
284             if (r.scriptIndex != -1) {
285                 int index = r.scriptIndex;
286                 if (index < context->importedScripts.count())
287                     return context->importedScripts.at(index);
288                 else
289                     return v8::Undefined();
290             } else if (r.type) {
291                 return engine->typeWrapper()->newObject(scopeObject, r.type);
292             } else if (r.importNamespace) {
293                 return engine->typeWrapper()->newObject(scopeObject, context->imports, r.importNamespace);
294             }
295             Q_ASSERT(!"Unreachable");
296         }
297
298         // Fall through
299     }
300
301     QQmlEnginePrivate *ep = QQmlEnginePrivate::get(engine->engine());
302     QV8QObjectWrapper *qobjectWrapper = engine->qobjectWrapper();
303
304     if (resource->secondaryScope) {
305         v8::Handle<v8::Value> result = qobjectWrapper->getProperty(resource->secondaryScope, propertystring, 
306                                                                    QV8QObjectWrapper::IgnoreRevision);
307         if (!result.IsEmpty()) return result;
308     }
309
310     while (context) {
311         // Search context properties
312         if (context->propertyNames) {
313             int propertyIdx = context->propertyNames->value(propertystring);
314
315             if (propertyIdx != -1) {
316
317                 if (propertyIdx < context->idValueCount) {
318
319                     ep->captureProperty(&context->idValues[propertyIdx].bindings);
320                     return engine->newQObject(context->idValues[propertyIdx]);
321                 } else {
322
323                     QQmlContextPrivate *cp = context->asQQmlContextPrivate();
324
325                     ep->captureProperty(context->asQQmlContext(), -1,
326                                         propertyIdx + cp->notifyIndex);
327
328                     const QVariant &value = cp->propertyValues.at(propertyIdx);
329                     if (value.userType() == qMetaTypeId<QList<QObject*> >()) {
330                         QQmlListProperty<QObject> prop(context->asQQmlContext(), (void*) qintptr(propertyIdx),
331                                                                0,
332                                                                QQmlContextPrivate::context_count,
333                                                                QQmlContextPrivate::context_at);
334                         return engine->listWrapper()->newList(prop, qMetaTypeId<QQmlListProperty<QObject> >());
335                     } else {
336                         return engine->fromVariant(cp->propertyValues.at(propertyIdx));
337                     }
338                 }
339             }
340         }
341
342         // Search scope object
343         if (scopeObject) {
344             v8::Handle<v8::Value> result = qobjectWrapper->getProperty(scopeObject, propertystring,
345                                                                        QV8QObjectWrapper::CheckRevision);
346             if (!result.IsEmpty()) return result;
347         }
348         scopeObject = 0;
349
350
351         // Search context object
352         if (context->contextObject) {
353             v8::Handle<v8::Value> result = qobjectWrapper->getProperty(context->contextObject, propertystring,
354                                                                        QV8QObjectWrapper::CheckRevision);
355             if (!result.IsEmpty()) return result;
356         }
357
358         context = context->parent;
359     }
360
361     expressionContext->unresolvedNames = true;
362
363     // V8 will throw a ReferenceError if appropriate ("typeof" should not throw)
364     return v8::Handle<v8::Value>();
365 }
366
367 v8::Handle<v8::Value> QV8ContextWrapper::NullSetter(v8::Local<v8::String> property, 
368                                                     v8::Local<v8::Value>,
369                                                     const v8::AccessorInfo &info)
370 {
371     QV8ContextResource *resource = v8_resource_check<QV8ContextResource>(info.This());
372
373     QV8Engine *engine = resource->engine;
374
375     if (!resource->readOnly) {
376         return v8::Handle<v8::Value>();
377     } else {
378         QString error = QLatin1String("Invalid write to global property \"") + engine->toString(property) + 
379                         QLatin1Char('"');
380         v8::ThrowException(v8::Exception::Error(engine->toString(error)));
381         return v8::Handle<v8::Value>();
382     }
383 }
384
385 v8::Handle<v8::Value> QV8ContextWrapper::Setter(v8::Local<v8::String> property, 
386                                                 v8::Local<v8::Value> value,
387                                                 const v8::AccessorInfo &info)
388 {
389     QV8ContextResource *resource = v8_resource_check<QV8ContextResource>(info.This());
390
391     // Its possible we could delay the calculation of the "actual" context (in the case
392     // of sub contexts) until it is definately needed.
393     QQmlContextData *context = resource->getContext();
394     QQmlContextData *expressionContext = context;
395
396     if (!context)
397         return v8::Undefined();
398
399     if (v8::Context::GetCallingQmlGlobal() != info.This())
400         return v8::Handle<v8::Value>();
401
402     // See QV8ContextWrapper::Getter for resolution order
403     
404     QV8Engine *engine = resource->engine;
405     QObject *scopeObject = resource->getScopeObject();
406
407     QHashedV8String propertystring(property);
408
409     QV8QObjectWrapper *qobjectWrapper = engine->qobjectWrapper();
410
411     // Search scope object
412     if (resource->secondaryScope && 
413         qobjectWrapper->setProperty(resource->secondaryScope, propertystring, value, 
414                                     QV8QObjectWrapper::IgnoreRevision))
415         return value;
416
417     while (context) {
418         // Search context properties
419         if (context->propertyNames && -1 != context->propertyNames->value(propertystring))
420             return value;
421
422         // Search scope object
423         if (scopeObject && 
424             qobjectWrapper->setProperty(scopeObject, propertystring, value, QV8QObjectWrapper::CheckRevision))
425             return value;
426         scopeObject = 0;
427
428         // Search context object
429         if (context->contextObject &&
430             qobjectWrapper->setProperty(context->contextObject, propertystring, value, 
431                                         QV8QObjectWrapper::CheckRevision))
432             return value;
433
434         context = context->parent;
435     }
436
437     expressionContext->unresolvedNames = true;
438
439     if (!resource->readOnly) {
440         return v8::Handle<v8::Value>();
441     } else {
442         QString error = QLatin1String("Invalid write to global property \"") + engine->toString(property) + 
443                         QLatin1Char('"');
444         v8::ThrowException(v8::Exception::Error(engine->toString(error)));
445         return v8::Undefined();
446     }
447 }
448
449 QT_END_NAMESPACE