1 /****************************************************************************
3 ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/
6 ** This file is part of the QtQml module of the Qt Toolkit.
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.
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.
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.
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.
40 ****************************************************************************/
42 #include "qv8contextwrapper_p.h"
43 #include "qv8engine_p.h"
45 #include <private/qqmlengine_p.h>
46 #include <private/qqmlcontext_p.h>
50 static QString internal(QLatin1String("You've stumbled onto an internal implementation detail "
51 "that should never have been exposed."));
53 class QV8ContextResource : public QV8ObjectResource
55 V8_RESOURCE_TYPE(ContextType);
58 QV8ContextResource(QV8Engine *engine, QQmlContextData *context, QObject *scopeObject);
59 ~QV8ContextResource();
61 inline QQmlContextData *getContext() const;
62 inline QObject *getScopeObject() const;
64 quint32 isSharedContext:1;
65 quint32 hasSubContexts:1;
69 QObject *secondaryScope;
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;
81 virtual const uint16_t* data() const { return (const uint16_t *)internal.constData(); }
82 virtual size_t length() const { return internal.length(); }
86 QQmlGuardedContextData context;
87 QQmlGuard<QObject> scopeObject;
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)
97 QV8ContextResource::~QV8ContextResource()
99 if (context && context->isJSContext)
103 // Returns the scope object
104 QObject *QV8ContextResource::getScopeObject() const
107 return QQmlEnginePrivate::get(engine->engine())->sharedScope;
112 // Returns the context, including resolving a subcontext
113 QQmlContextData *QV8ContextResource::getContext() const
116 return QQmlEnginePrivate::get(engine->engine())->sharedContext;
121 v8::Local<v8::Value> callingdata = v8::Context::GetCallingScriptData();
122 if (callingdata.IsEmpty() || !callingdata->IsString())
125 v8::Local<v8::String> callingstring = callingdata->ToString();
126 Q_ASSERT(callingstring->IsExternal());
127 Q_ASSERT(callingstring->GetExternalStringResource());
129 SubContext *sc = static_cast<SubContext *>(callingstring->GetExternalStringResource());
133 QV8ContextWrapper::QV8ContextWrapper()
138 QV8ContextWrapper::~QV8ContextWrapper()
142 void QV8ContextWrapper::destroy()
144 qPersistentDispose(m_sharedContext);
145 qPersistentDispose(m_urlConstructor);
146 qPersistentDispose(m_constructor);
149 void QV8ContextWrapper::init(QV8Engine *engine)
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());
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());
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);
173 v8::Local<v8::Object> QV8ContextWrapper::qmlScope(QQmlContextData *ctxt, QObject *scope)
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);
182 v8::Local<v8::Object> QV8ContextWrapper::urlScope(const QUrl &url)
184 QQmlContextData *context = new QQmlContextData;
186 context->isInternal = true;
187 context->isJSContext = true;
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);
196 void QV8ContextWrapper::setReadOnly(v8::Handle<v8::Object> qmlglobal, bool readOnly)
198 QV8ContextResource *resource = v8_resource_cast<QV8ContextResource>(qmlglobal);
200 resource->readOnly = readOnly;
203 void QV8ContextWrapper::addSubContext(v8::Handle<v8::Object> qmlglobal, v8::Handle<v8::Script> script,
204 QQmlContextData *ctxt)
206 QV8ContextResource *resource = v8_resource_cast<QV8ContextResource>(qmlglobal);
208 resource->hasSubContexts = true;
209 script->SetData(v8::String::NewExternal(new QV8ContextResource::SubContext(ctxt)));
212 QObject *QV8ContextWrapper::setSecondaryScope(v8::Handle<v8::Object> ctxt, QObject *scope)
214 QV8ContextResource *resource = v8_resource_cast<QV8ContextResource>(ctxt);
215 if (!resource) return 0;
217 QObject *rv = resource->secondaryScope;
218 resource->secondaryScope = scope;
222 QQmlContextData *QV8ContextWrapper::callingContext()
224 v8::Local<v8::Object> qmlglobal = v8::Context::GetCallingQmlGlobal();
225 if (qmlglobal.IsEmpty()) return 0;
227 QV8ContextResource *r = v8_resource_cast<QV8ContextResource>(qmlglobal);
228 return r?r->getContext():0;
231 QQmlContextData *QV8ContextWrapper::context(v8::Handle<v8::Value> value)
233 if (!value->IsObject())
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;
241 v8::Handle<v8::Value> QV8ContextWrapper::NullGetter(v8::Local<v8::String>,
242 const v8::AccessorInfo &)
244 // V8 will throw a ReferenceError if appropriate ("typeof" should not throw)
245 return v8::Handle<v8::Value>();
248 v8::Handle<v8::Value> QV8ContextWrapper::Getter(v8::Local<v8::String> property,
249 const v8::AccessorInfo &info)
251 QV8ContextResource *resource = v8_resource_check<QV8ContextResource>(info.This());
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;
259 return v8::Undefined();
261 if (v8::Context::GetCallingQmlGlobal() != info.This())
262 return v8::Handle<v8::Value>();
264 // Search type (attached property/enum/imported scripts) names
265 // Secondary scope object
267 // Search context properties
268 // Search scope object
269 // Search context object
270 // context = context->parent
273 QV8Engine *engine = resource->engine;
275 QObject *scopeObject = resource->getScopeObject();
277 QHashedV8String propertystring(property);
279 if (context->imports && QV8Engine::startsWithUpper(property)) {
280 // Search for attached properties, enums and imported scripts
281 QQmlTypeNameCache::Result r = context->imports->query(propertystring);
284 if (r.scriptIndex != -1) {
285 int index = r.scriptIndex;
286 if (index < context->importedScripts.count())
287 return context->importedScripts.at(index);
289 return v8::Undefined();
291 return engine->typeWrapper()->newObject(scopeObject, r.type);
292 } else if (r.importNamespace) {
293 return engine->typeWrapper()->newObject(scopeObject, context->imports, r.importNamespace);
295 Q_ASSERT(!"Unreachable");
301 QQmlEnginePrivate *ep = QQmlEnginePrivate::get(engine->engine());
302 QV8QObjectWrapper *qobjectWrapper = engine->qobjectWrapper();
304 if (resource->secondaryScope) {
305 v8::Handle<v8::Value> result = qobjectWrapper->getProperty(resource->secondaryScope, propertystring,
306 QV8QObjectWrapper::IgnoreRevision);
307 if (!result.IsEmpty()) return result;
311 // Search context properties
312 if (context->propertyNames) {
313 int propertyIdx = context->propertyNames->value(propertystring);
315 if (propertyIdx != -1) {
317 if (propertyIdx < context->idValueCount) {
319 ep->captureProperty(&context->idValues[propertyIdx].bindings);
320 return engine->newQObject(context->idValues[propertyIdx]);
323 QQmlContextPrivate *cp = context->asQQmlContextPrivate();
325 ep->captureProperty(context->asQQmlContext(), -1,
326 propertyIdx + cp->notifyIndex);
328 const QVariant &value = cp->propertyValues.at(propertyIdx);
329 if (value.userType() == qMetaTypeId<QList<QObject*> >()) {
330 QQmlListProperty<QObject> prop(context->asQQmlContext(), (void*) qintptr(propertyIdx),
332 QQmlContextPrivate::context_count,
333 QQmlContextPrivate::context_at);
334 return engine->listWrapper()->newList(prop, qMetaTypeId<QQmlListProperty<QObject> >());
336 return engine->fromVariant(cp->propertyValues.at(propertyIdx));
342 // Search scope object
344 v8::Handle<v8::Value> result = qobjectWrapper->getProperty(scopeObject, propertystring,
345 QV8QObjectWrapper::CheckRevision);
346 if (!result.IsEmpty()) return result;
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;
358 context = context->parent;
361 expressionContext->unresolvedNames = true;
363 // V8 will throw a ReferenceError if appropriate ("typeof" should not throw)
364 return v8::Handle<v8::Value>();
367 v8::Handle<v8::Value> QV8ContextWrapper::NullSetter(v8::Local<v8::String> property,
368 v8::Local<v8::Value>,
369 const v8::AccessorInfo &info)
371 QV8ContextResource *resource = v8_resource_check<QV8ContextResource>(info.This());
373 QV8Engine *engine = resource->engine;
375 if (!resource->readOnly) {
376 return v8::Handle<v8::Value>();
378 QString error = QLatin1String("Invalid write to global property \"") + engine->toString(property) +
380 v8::ThrowException(v8::Exception::Error(engine->toString(error)));
381 return v8::Handle<v8::Value>();
385 v8::Handle<v8::Value> QV8ContextWrapper::Setter(v8::Local<v8::String> property,
386 v8::Local<v8::Value> value,
387 const v8::AccessorInfo &info)
389 QV8ContextResource *resource = v8_resource_check<QV8ContextResource>(info.This());
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;
397 return v8::Undefined();
399 if (v8::Context::GetCallingQmlGlobal() != info.This())
400 return v8::Handle<v8::Value>();
402 // See QV8ContextWrapper::Getter for resolution order
404 QV8Engine *engine = resource->engine;
405 QObject *scopeObject = resource->getScopeObject();
407 QHashedV8String propertystring(property);
409 QV8QObjectWrapper *qobjectWrapper = engine->qobjectWrapper();
411 // Search scope object
412 if (resource->secondaryScope &&
413 qobjectWrapper->setProperty(resource->secondaryScope, propertystring, value,
414 QV8QObjectWrapper::IgnoreRevision))
418 // Search context properties
419 if (context->propertyNames && -1 != context->propertyNames->value(propertystring))
422 // Search scope object
424 qobjectWrapper->setProperty(scopeObject, propertystring, value, QV8QObjectWrapper::CheckRevision))
428 // Search context object
429 if (context->contextObject &&
430 qobjectWrapper->setProperty(context->contextObject, propertystring, value,
431 QV8QObjectWrapper::CheckRevision))
434 context = context->parent;
437 expressionContext->unresolvedNames = true;
439 if (!resource->readOnly) {
440 return v8::Handle<v8::Value>();
442 QString error = QLatin1String("Invalid write to global property \"") + engine->toString(property) +
444 v8::ThrowException(v8::Exception::Error(engine->toString(error)));
445 return v8::Undefined();