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 "qqmlengine_p.h"
43 #include "qqmlengine.h"
44 #include "qqmlcomponentattached_p.h"
46 #include "qqmlcontext_p.h"
47 #include "qqmlcompiler_p.h"
49 #include "qqmlcontext.h"
50 #include "qqmlexpression.h"
51 #include "qqmlcomponent.h"
52 #include "qqmlvme_p.h"
53 #include <private/qqmlenginedebugservice_p.h>
54 #include "qqmlstringconverters_p.h"
55 #include "qqmlxmlhttprequest_p.h"
56 #include "qqmlscriptstring.h"
57 #include "qqmlglobal_p.h"
58 #include "qquicklistmodel_p.h"
59 #include "qquickworkerscript_p.h"
60 #include "qqmlcomponent_p.h"
61 #include "qqmlnetworkaccessmanagerfactory.h"
62 #include "qqmldirparser_p.h"
63 #include "qqmlextensioninterface.h"
64 #include "qqmllist_p.h"
65 #include "qqmltypenamecache_p.h"
66 #include "qqmlnotifier_p.h"
67 #include <private/qqmlprofilerservice_p.h>
68 #include <private/qv8debugservice_p.h>
69 #include <private/qdebugmessageservice_p.h>
70 #include "qqmlincubator.h"
71 #include <private/qv8profilerservice_p.h>
72 #include <private/qqmlboundsignal_p.h>
74 #include <QtCore/qstandardpaths.h>
75 #include <QtCore/qsettings.h>
77 #include <QtCore/qmetaobject.h>
78 #include <QNetworkAccessManager>
80 #include <QMetaObject>
81 #include <QtCore/qcoreapplication.h>
82 #include <QtCore/qdir.h>
83 #include <QtCore/qmutex.h>
84 #include <QtNetwork/qnetworkconfigmanager.h>
86 #include <private/qobject_p.h>
88 #include <private/qqmllocale_p.h>
90 #ifdef Q_OS_WIN // for %APPDATA%
91 #include <qt_windows.h>
95 #define CSIDL_APPDATA 0x001a // <username>\Application Data
98 Q_DECLARE_METATYPE(QQmlProperty)
102 void qmlRegisterBaseTypes(const char *uri, int versionMajor, int versionMinor)
104 QQmlEnginePrivate::registerBaseTypes(uri, versionMajor, versionMinor);
105 QQmlValueTypeFactory::registerBaseTypes(uri, versionMajor, versionMinor);
109 \qmlclass QtObject QObject
110 \ingroup qml-utility-elements
112 \brief The QtObject element is the most basic element in QML.
114 The QtObject element is a non-visual element which contains only the
117 It can be useful to create a QtObject if you need an extremely
118 lightweight element to enclose a set of custom properties:
120 \snippet doc/src/snippets/qml/qtobject.qml 0
122 It can also be useful for C++ integration, as it is just a plain
123 QObject. See the QObject documentation for further details.
126 \qmlproperty string QtObject::objectName
127 This property holds the QObject::objectName for this specific object instance.
129 This allows a C++ application to locate an item within a QML component
130 using the QObject::findChild() method. For example, the following C++
131 application locates the child \l Rectangle item and dynamically changes its
140 width: 200; height: 200
154 view.setSource(QUrl::fromLocalFile("MyRect.qml"));
157 QQuickItem *item = view.rootObject()->findChild<QQuickItem*>("myRect");
159 item->setProperty("color", QColor(Qt::yellow));
163 bool QQmlEnginePrivate::qml_debugging_enabled = false;
165 void QQmlEnginePrivate::registerBaseTypes(const char *uri, int versionMajor, int versionMinor)
167 qmlRegisterType<QQmlComponent>(uri,versionMajor,versionMinor,"Component");
168 qmlRegisterType<QObject>(uri,versionMajor,versionMinor,"QtObject");
169 qmlRegisterType<QQuickListElement>(uri, versionMajor, versionMinor,"ListElement");
170 qmlRegisterCustomType<QQuickListModel>(uri, versionMajor, versionMinor,"ListModel", new QQuickListModelParser);
171 qmlRegisterType<QQuickWorkerScript>(uri,versionMajor,versionMinor,"WorkerScript");
174 void QQmlEnginePrivate::defineModule()
176 registerBaseTypes("QtQuick", 2, 0);
177 qmlRegisterUncreatableType<QQmlLocale>("QtQuick",2,0,"Locale",QQmlEngine::tr("Locale cannot be instantiated. Use Qt.locale()"));
182 \class QQmlImageProviderBase
183 \brief The QQmlImageProviderBase class is used to register image providers in the QML engine.
186 Image providers must be registered with the QML engine. The only information the QML
187 engine knows about image providers is the type of image data they provide. To use an
188 image provider to acquire image data, you must cast the QQmlImageProviderBase pointer
189 to a QQuickImageProvider pointer.
191 \sa QQuickImageProvider, QQuickTextureFactory
195 \enum QQmlImageProviderBase::ImageType
197 Defines the type of image supported by this image provider.
199 \value Image The Image Provider provides QImage images.
200 The QQuickImageProvider::requestImage() method will be called for all image requests.
201 \value Pixmap The Image Provider provides QPixmap images.
202 The QQuickImageProvider::requestPixmap() method will be called for all image requests.
203 \value Texture The Image Provider provides QSGTextureProvider based images.
204 The QQuickImageProvider::requestTexture() method will be called for all image requests. \omitvalue
208 QQmlImageProviderBase::QQmlImageProviderBase()
213 QQmlImageProviderBase::~QQmlImageProviderBase()
219 \qmlclass Qt QQmlEnginePrivate
220 \ingroup qml-utility-elements
221 \brief The QML global Qt object provides useful enums and functions from Qt.
223 \keyword QmlGlobalQtObject
225 \brief The \c Qt object provides useful enums and functions from Qt, for use in all QML files.
227 The \c Qt object is a global object with utility functions, properties and enums.
229 It is not instantiable; to use it, call the members of the global \c Qt object directly.
236 color: Qt.rgba(1, 0, 0, 1)
237 text: Qt.md5("hello, world")
244 The Qt object contains the enums available in the \l {Qt Namespace}. For example, you can access
245 the \l Qt::LeftButton and \l Qt::RightButton enum values as \c Qt.LeftButton and \c Qt.RightButton.
249 The Qt object also contains helper functions for creating objects of specific
250 data types. This is primarily useful when setting the properties of an item
251 when the property has one of the following types:
254 \li \c color - use \l{Qt::rgba()}{Qt.rgba()}, \l{Qt::hsla()}{Qt.hsla()}, \l{Qt::darker()}{Qt.darker()}, \l{Qt::lighter()}{Qt.lighter()} or \l{Qt::tint()}{Qt.tint()}
255 \li \c rect - use \l{Qt::rect()}{Qt.rect()}
256 \li \c point - use \l{Qt::point()}{Qt.point()}
257 \li \c size - use \l{Qt::size()}{Qt.size()}
258 \li \c vector3d - use \l{Qt::vector3d()}{Qt.vector3d()}
261 There are also string based constructors for these types. See \l{qdeclarativebasictypes.html}{QML Basic Types} for more information.
263 \section1 Date/Time Formatters
265 The Qt object contains several functions for formatting QDateTime, QDate and QTime values.
268 \li \l{Qt::formatDateTime}{string Qt.formatDateTime(datetime date, variant format)}
269 \li \l{Qt::formatDate}{string Qt.formatDate(datetime date, variant format)}
270 \li \l{Qt::formatTime}{string Qt.formatTime(datetime date, variant format)}
273 The format specification is described at \l{Qt::formatDateTime}{Qt.formatDateTime}.
276 \section1 Dynamic Object Creation
277 The following functions on the global object allow you to dynamically create QML
278 items from files or strings. See \l{Dynamic Object Management in QML} for an overview
282 \li \l{Qt::createComponent()}{object Qt.createComponent(url)}
283 \li \l{Qt::createQmlObject()}{object Qt.createQmlObject(string qml, object parent, string filepath)}
289 \qmlproperty object Qt::application
292 The \c application object provides access to global application state
293 properties shared by many QML components.
299 \li \c application.active
301 This read-only property indicates whether the application is the top-most and focused
302 application, and the user is able to interact with the application. The property
303 is false when the application is in the background, the device keylock or screen
304 saver is active, the screen backlight is turned off, or the global system dialog
305 is being displayed on top of the application. It can be used for stopping and
306 pausing animations, timers and active processing of data in order to save device
307 battery power and free device memory and processor load when the application is not
311 \li \c application.layoutDirection
313 This read-only property can be used to query the default layout direction of the
314 application. On system start-up, the default layout direction depends on the
315 application's language. The property has a value of \c Qt.RightToLeft in locales
316 where text and graphic elements are read from right to left, and \c Qt.LeftToRight
317 where the reading direction flows from left to right. You can bind to this
318 property to customize your application layouts to support both layout directions.
323 \li Qt.LeftToRight - Text and graphics elements should be positioned
325 \li Qt.RightToLeft - Text and graphics elements should be positioned
330 \li \c application.inputPanel
332 This read-only property allows access to application's QInputPanel object
333 and all its properties and slots. See the QInputPanel documentation for
334 further details. Deprecated in favor of Qt.InputMethod
337 The following example uses the \c application object to indicate
338 whether the application is currently active:
340 \snippet doc/src/snippets/qml/application.qml document
342 \qmlproperty object Qt::inputMethod
345 The \c inputMethod object allows access to application's QInputMethod object
346 and all its properties and slots. See the QInputMethod documentation for
352 \qmlmethod object Qt::include(string url, jsobject callback)
354 Includes another JavaScript file. This method can only be used from within JavaScript files,
355 and not regular QML files.
357 This imports all functions from \a url into the current script's namespace.
359 Qt.include() returns an object that describes the status of the operation. The object has
360 a single property, \c {status}, that is set to one of the following values:
363 \header \li Symbol \li Value \li Description
364 \row \li result.OK \li 0 \li The include completed successfully.
365 \row \li result.LOADING \li 1 \li Data is being loaded from the network.
366 \row \li result.NETWORK_ERROR \li 2 \li A network error occurred while fetching the url.
367 \row \li result.EXCEPTION \li 3 \li A JavaScript exception occurred while executing the included code.
368 An additional \c exception property will be set in this case.
371 The \c status property will be updated as the operation progresses.
373 If provided, \a callback is invoked when the operation completes. The callback is passed
374 the same object as is returned from the Qt.include() call.
376 // Qt.include() is implemented in qv8include.cpp
379 QQmlEnginePrivate::QQmlEnginePrivate(QQmlEngine *e)
380 : propertyCapture(0), rootContext(0), isDebugging(false),
381 outputWarningsToStdErr(true), sharedContext(0), sharedScope(0),
382 cleanup(0), erroredBindings(0), inProgressCreations(0),
383 workerScriptEngine(0), activeVME(0),
384 networkAccessManager(0), networkAccessManagerFactory(0),
385 scarceResourcesRefCount(0), typeLoader(e), importDatabase(e), uniqueId(1),
386 incubatorCount(0), incubationController(0), mutex(QMutex::Recursive)
390 QQmlEnginePrivate::~QQmlEnginePrivate()
392 if (inProgressCreations)
393 qWarning() << QQmlEngine::tr("There are still \"%1\" items in the process of being created at engine destruction.").arg(inProgressCreations);
396 QQmlCleanup *c = cleanup;
398 if (cleanup) cleanup->prev = &cleanup;
404 doDeleteInEngineThread();
406 if (incubationController) incubationController->d = 0;
407 incubationController = 0;
412 for(QHash<int, QQmlCompiledData*>::ConstIterator iter = m_compositeTypes.constBegin(); iter != m_compositeTypes.constEnd(); ++iter)
414 for(QHash<const QMetaObject *, QQmlPropertyCache *>::Iterator iter = propertyCache.begin(); iter != propertyCache.end(); ++iter)
416 for(QHash<QPair<QQmlType *, int>, QQmlPropertyCache *>::Iterator iter = typePropertyCache.begin(); iter != typePropertyCache.end(); ++iter)
418 for(QHash<QQmlMetaType::ModuleApi, QQmlMetaType::ModuleApiInstance *>::Iterator iter = moduleApiInstances.begin(); iter != moduleApiInstances.end(); ++iter) {
419 delete (*iter)->qobjectApi;
424 void QQmlPrivate::qdeclarativeelement_destructor(QObject *o)
426 QObjectPrivate *p = QObjectPrivate::get(o);
427 if (p->declarativeData) {
428 QQmlData *d = static_cast<QQmlData*>(p->declarativeData);
429 if (d->ownContext && d->context) {
430 d->context->destroy();
436 void QQmlData::destroyed(QAbstractDeclarativeData *d, QObject *o)
438 static_cast<QQmlData *>(d)->destroyed(o);
441 void QQmlData::parentChanged(QAbstractDeclarativeData *d, QObject *o, QObject *p)
443 static_cast<QQmlData *>(d)->parentChanged(o, p);
446 void QQmlData::objectNameChanged(QAbstractDeclarativeData *d, QObject *o)
448 static_cast<QQmlData *>(d)->objectNameChanged(o);
451 void QQmlData::signalEmitted(QAbstractDeclarativeData *, QObject *object, int index, void **)
453 QQmlData *ddata = QQmlData::get(object, false);
454 if (!ddata) return; // Probably being deleted
456 QQmlNotifierEndpoint *ep = ddata->notify(index);
457 if (ep) QQmlNotifier::emitNotify(ep);
460 void QQmlEnginePrivate::init()
464 static bool firstTime = true;
466 qmlRegisterType<QQmlComponent>("QML", 1, 0, "Component");
471 qRegisterMetaType<QVariant>("QVariant");
472 qRegisterMetaType<QQmlScriptString>("QQmlScriptString");
473 qRegisterMetaType<QJSValue>("QJSValue");
474 qRegisterMetaType<QQmlComponent::Status>("QQmlComponent::Status");
475 qRegisterMetaType<QList<QObject*> >("QList<QObject*>");
476 qRegisterMetaType<QList<int> >("QList<int>");
477 qRegisterMetaType<QQmlV8Handle>("QQmlV8Handle");
481 v8engine()->setEngine(q);
483 rootContext = new QQmlContext(q,true);
485 if (QCoreApplication::instance()->thread() == q->thread() &&
486 QQmlEngineDebugService::isDebuggingEnabled()) {
488 QQmlEngineDebugService::instance()->addEngine(q);
489 QV8DebugService::initialize(v8engine());
490 QV8ProfilerService::initialize();
491 QQmlProfilerService::initialize();
492 QDebugMessageService::instance();
495 QString dataLocation = QStandardPaths::writableLocation(QStandardPaths::DataLocation);
496 offlineStoragePath = dataLocation.replace(QLatin1Char('/'), QDir::separator()) +
497 QDir::separator() + QLatin1String("QML") +
498 QDir::separator() + QLatin1String("OfflineStorage");
501 QQuickWorkerScriptEngine *QQmlEnginePrivate::getWorkerScriptEngine()
504 if (!workerScriptEngine)
505 workerScriptEngine = new QQuickWorkerScriptEngine(q);
506 return workerScriptEngine;
513 \brief The QQmlEngine class provides an environment for instantiating QML components.
516 Each QML component is instantiated in a QQmlContext.
517 QQmlContext's are essential for passing data to QML
518 components. In QML, contexts are arranged hierarchically and this
519 hierarchy is managed by the QQmlEngine.
521 Prior to creating any QML components, an application must have
522 created a QQmlEngine to gain access to a QML context. The
523 following example shows how to create a simple Text item.
527 QQmlComponent component(&engine);
528 component.setData("import QtQuick 2.0\nText { text: \"Hello world!\" }", QUrl());
529 QQuickItem *item = qobject_cast<QQuickItem *>(component.create());
531 //add item to view, etc
535 In this case, the Text item will be created in the engine's
536 \l {QQmlEngine::rootContext()}{root context}.
538 Note that the QtQuick 1 version is called QDeclarativeEngine.
540 \sa QQmlComponent QQmlContext
544 Create a new QQmlEngine with the given \a parent.
546 QQmlEngine::QQmlEngine(QObject *parent)
547 : QJSEngine(*new QQmlEnginePrivate(this), parent)
554 Destroys the QQmlEngine.
556 Any QQmlContext's created on this engine will be
557 invalidated, but not destroyed (unless they are parented to the
560 QQmlEngine::~QQmlEngine()
563 if (d->isDebugging) {
564 QQmlEngineDebugService::instance()->remEngine(this);
567 // if we are the parent of any of the qobject module api instances,
568 // we need to remove them from our internal list, in order to prevent
569 // a segfault in engine private dtor.
570 QList<QQmlMetaType::ModuleApi> keys = d->moduleApiInstances.keys();
571 QObject *currQObjectApi = 0;
572 QQmlMetaType::ModuleApiInstance *currInstance = 0;
573 foreach (const QQmlMetaType::ModuleApi &key, keys) {
574 currInstance = d->moduleApiInstances.value(key);
575 currQObjectApi = currInstance->qobjectApi;
576 if (this->children().contains(currQObjectApi)) {
577 delete currQObjectApi;
579 d->moduleApiInstances.remove(key);
583 // ensure we clean up QObjects with JS ownership
586 if (d->incubationController)
587 d->incubationController->d = 0;
590 /*! \fn void QQmlEngine::quit()
591 This signal is emitted when the QML loaded by the engine would like to quit.
594 /*! \fn void QQmlEngine::warnings(const QList<QQmlError> &warnings)
595 This signal is emitted when \a warnings messages are generated by QML.
599 Clears the engine's internal component cache.
601 This function causes the property metadata of all components previously
602 loaded by the engine to be destroyed. All previously loaded components and
603 the property bindings for all extant objects created from those components will
606 This function returns the engine to a state where it does not contain any loaded
607 component data. This may be useful in order to reload a smaller subset of the
608 previous component set, or to load a new version of a previously loaded component.
610 Once the component cache has been cleared, components must be loaded before
611 any new objects can be created.
613 void QQmlEngine::clearComponentCache()
616 d->typeLoader.clearCache();
620 Returns the engine's root context.
622 The root context is automatically created by the QQmlEngine.
623 Data that should be available to all QML component instances
624 instantiated by the engine should be put in the root context.
626 Additional data that should only be available to a subset of
627 component instances should be added to sub-contexts parented to the
630 QQmlContext *QQmlEngine::rootContext() const
632 Q_D(const QQmlEngine);
633 return d->rootContext;
637 Sets the \a factory to use for creating QNetworkAccessManager(s).
639 QNetworkAccessManager is used for all network access by QML. By
640 implementing a factory it is possible to create custom
641 QNetworkAccessManager with specialized caching, proxy and cookie
644 The factory must be set before executing the engine.
646 void QQmlEngine::setNetworkAccessManagerFactory(QQmlNetworkAccessManagerFactory *factory)
649 QMutexLocker locker(&d->mutex);
650 d->networkAccessManagerFactory = factory;
654 Returns the current QQmlNetworkAccessManagerFactory.
656 \sa setNetworkAccessManagerFactory()
658 QQmlNetworkAccessManagerFactory *QQmlEngine::networkAccessManagerFactory() const
660 Q_D(const QQmlEngine);
661 return d->networkAccessManagerFactory;
664 void QQmlEnginePrivate::registerFinalizeCallback(QObject *obj, int index)
667 activeVME->finalizeCallbacks.append(qMakePair(QQmlGuard<QObject>(obj), index));
669 void *args[] = { 0 };
670 QMetaObject::metacall(obj, QMetaObject::InvokeMetaMethod, index, args);
674 QNetworkAccessManager *QQmlEnginePrivate::createNetworkAccessManager(QObject *parent) const
676 QMutexLocker locker(&mutex);
677 QNetworkAccessManager *nam;
678 if (networkAccessManagerFactory) {
679 nam = networkAccessManagerFactory->create(parent);
681 nam = new QNetworkAccessManager(parent);
687 QNetworkAccessManager *QQmlEnginePrivate::getNetworkAccessManager() const
689 Q_Q(const QQmlEngine);
690 if (!networkAccessManager)
691 networkAccessManager = createNetworkAccessManager(const_cast<QQmlEngine*>(q));
692 return networkAccessManager;
696 Returns a common QNetworkAccessManager which can be used by any QML
697 element instantiated by this engine.
699 If a QQmlNetworkAccessManagerFactory has been set and a
700 QNetworkAccessManager has not yet been created, the
701 QQmlNetworkAccessManagerFactory will be used to create the
702 QNetworkAccessManager; otherwise the returned QNetworkAccessManager
703 will have no proxy or cache set.
705 \sa setNetworkAccessManagerFactory()
707 QNetworkAccessManager *QQmlEngine::networkAccessManager() const
709 Q_D(const QQmlEngine);
710 return d->getNetworkAccessManager();
715 Sets the \a provider to use for images requested via the \e
716 image: url scheme, with host \a providerId. The QQmlEngine
717 takes ownership of \a provider.
719 Image providers enable support for pixmap and threaded image
720 requests. See the QQuickImageProvider documentation for details on
721 implementing and using image providers.
723 All required image providers should be added to the engine before any
724 QML sources files are loaded.
726 \sa removeImageProvider(), QQuickImageProvider, QQmlImageProviderBase
728 void QQmlEngine::addImageProvider(const QString &providerId, QQmlImageProviderBase *provider)
731 QMutexLocker locker(&d->mutex);
732 d->imageProviders.insert(providerId.toLower(), QSharedPointer<QQmlImageProviderBase>(provider));
736 Returns the image provider set for \a providerId.
738 Returns the provider if it was found; otherwise returns 0.
740 \sa QQuickImageProvider
742 QQmlImageProviderBase *QQmlEngine::imageProvider(const QString &providerId) const
744 Q_D(const QQmlEngine);
745 QMutexLocker locker(&d->mutex);
746 return d->imageProviders.value(providerId).data();
750 Removes the image provider for \a providerId.
752 \sa addImageProvider(), QQuickImageProvider
754 void QQmlEngine::removeImageProvider(const QString &providerId)
757 QMutexLocker locker(&d->mutex);
758 d->imageProviders.take(providerId);
762 Return the base URL for this engine. The base URL is only used to
763 resolve components when a relative URL is passed to the
764 QQmlComponent constructor.
766 If a base URL has not been explicitly set, this method returns the
767 application's current working directory.
771 QUrl QQmlEngine::baseUrl() const
773 Q_D(const QQmlEngine);
774 if (d->baseUrl.isEmpty()) {
775 return QUrl::fromLocalFile(QDir::currentPath() + QDir::separator());
782 Set the base URL for this engine to \a url.
786 void QQmlEngine::setBaseUrl(const QUrl &url)
793 Returns true if warning messages will be output to stderr in addition
794 to being emitted by the warnings() signal, otherwise false.
796 The default value is true.
798 bool QQmlEngine::outputWarningsToStandardError() const
800 Q_D(const QQmlEngine);
801 return d->outputWarningsToStdErr;
805 Set whether warning messages will be output to stderr to \a enabled.
807 If \a enabled is true, any warning messages generated by QML will be
808 output to stderr and emitted by the warnings() signal. If \a enabled
809 is false, on the warnings() signal will be emitted. This allows
810 applications to handle warning output themselves.
812 The default value is true.
814 void QQmlEngine::setOutputWarningsToStandardError(bool enabled)
817 d->outputWarningsToStdErr = enabled;
821 Attempt to free unused memory.
823 void QQmlEngine::collectGarbage()
829 Returns the QQmlContext for the \a object, or 0 if no
830 context has been set.
832 When the QQmlEngine instantiates a QObject, the context is
835 QQmlContext *QQmlEngine::contextForObject(const QObject *object)
840 QObjectPrivate *priv = QObjectPrivate::get(const_cast<QObject *>(object));
843 static_cast<QQmlData *>(priv->declarativeData);
847 else if (data->outerContext)
848 return data->outerContext->asQQmlContext();
854 Sets the QQmlContext for the \a object to \a context.
855 If the \a object already has a context, a warning is
856 output, but the context is not changed.
858 When the QQmlEngine instantiates a QObject, the context is
861 void QQmlEngine::setContextForObject(QObject *object, QQmlContext *context)
863 if (!object || !context)
866 QQmlData *data = QQmlData::get(object, true);
868 qWarning("QQmlEngine::setContextForObject(): Object already has a QQmlContext");
872 QQmlContextData *contextData = QQmlContextData::get(context);
873 contextData->addObject(object);
877 \enum QQmlEngine::ObjectOwnership
879 Ownership controls whether or not QML automatically destroys the
880 QObject when the object is garbage collected by the JavaScript
881 engine. The two ownership options are:
883 \value CppOwnership The object is owned by C++ code, and will
884 never be deleted by QML. The JavaScript destroy() method cannot be
885 used on objects with CppOwnership. This option is similar to
886 QScriptEngine::QtOwnership.
888 \value JavaScriptOwnership The object is owned by JavaScript.
889 When the object is returned to QML as the return value of a method
890 call or property access, QML will delete the object if there are no
891 remaining JavaScript references to it and it has no
892 QObject::parent(). This option is similar to
893 QScriptEngine::ScriptOwnership.
895 Generally an application doesn't need to set an object's ownership
896 explicitly. QML uses a heuristic to set the default object
897 ownership. By default, an object that is created by QML has
898 JavaScriptOwnership. The exception to this are the root objects
899 created by calling QQmlComponent::create() or
900 QQmlComponent::beginCreate() which have CppOwnership by
901 default. The ownership of these root-level objects is considered to
902 have been transferred to the C++ caller.
904 Objects not-created by QML have CppOwnership by default. The
905 exception to this is objects returned from a C++ method call. The
906 ownership of these objects is passed to JavaScript.
908 Calling setObjectOwnership() overrides the default ownership
909 heuristic used by QML.
913 Sets the \a ownership of \a object.
915 void QQmlEngine::setObjectOwnership(QObject *object, ObjectOwnership ownership)
920 QQmlData *ddata = QQmlData::get(object, true);
924 ddata->indestructible = (ownership == CppOwnership)?true:false;
925 ddata->explicitIndestructibleSet = true;
929 Returns the ownership of \a object.
931 QQmlEngine::ObjectOwnership QQmlEngine::objectOwnership(QObject *object)
936 QQmlData *ddata = QQmlData::get(object, false);
940 return ddata->indestructible?CppOwnership:JavaScriptOwnership;
943 bool QQmlEngine::event(QEvent *e)
946 if (e->type() == QEvent::User)
947 d->doDeleteInEngineThread();
949 return QJSEngine::event(e);
952 void QQmlEnginePrivate::doDeleteInEngineThread()
954 QFieldList<Deletable, &Deletable::next> list;
956 list.copyAndClear(toDeleteInEngineThread);
959 while (Deletable *d = list.takeFirst())
963 Q_AUTOTEST_EXPORT void qmlExecuteDeferred(QObject *object)
965 QQmlData *data = QQmlData::get(object);
967 if (data && data->deferredComponent) {
968 QQmlObjectCreatingProfiler prof;
970 QQmlType *type = QQmlMetaType::qmlType(object->metaObject());
971 prof.setTypeName(type ? type->qmlTypeName()
972 : QString::fromUtf8(object->metaObject()->className()));
973 if (data->outerContext)
974 prof.setLocation(data->outerContext->url, data->lineNumber, data->columnNumber);
976 QQmlEnginePrivate *ep = QQmlEnginePrivate::get(data->context->engine);
978 QQmlComponentPrivate::ConstructionState state;
979 QQmlComponentPrivate::beginDeferred(ep, object, &state);
981 data->deferredComponent->release();
982 data->deferredComponent = 0;
984 QQmlComponentPrivate::complete(ep, &state);
988 QQmlContext *qmlContext(const QObject *obj)
990 return QQmlEngine::contextForObject(obj);
993 QQmlEngine *qmlEngine(const QObject *obj)
995 QQmlData *data = QQmlData::get(obj, false);
996 if (!data || !data->context)
998 return data->context->engine;
1001 QObject *qmlAttachedPropertiesObjectById(int id, const QObject *object, bool create)
1003 QQmlData *data = QQmlData::get(object);
1005 return 0; // Attached properties are only on objects created by QML
1007 QObject *rv = data->hasExtendedData()?data->attachedProperties()->value(id):0;
1011 QQmlAttachedPropertiesFunc pf = QQmlMetaType::attachedPropertiesFuncById(id);
1015 rv = pf(const_cast<QObject *>(object));
1018 data->attachedProperties()->insert(id, rv);
1023 QObject *qmlAttachedPropertiesObject(int *idCache, const QObject *object,
1024 const QMetaObject *attachedMetaObject, bool create)
1027 *idCache = QQmlMetaType::attachedPropertiesFuncId(attachedMetaObject);
1029 if (*idCache == -1 || !object)
1032 return qmlAttachedPropertiesObjectById(*idCache, object, create);
1035 QQmlDebuggingEnabler::QQmlDebuggingEnabler(bool printWarning)
1037 #ifndef QQML_NO_DEBUG_PROTOCOL
1038 if (!QQmlEnginePrivate::qml_debugging_enabled
1040 qDebug("QML debugging is enabled. Only use this in a safe environment.");
1042 QQmlEnginePrivate::qml_debugging_enabled = true;
1047 class QQmlDataExtended {
1050 ~QQmlDataExtended();
1052 QHash<int, QObject *> attachedProperties;
1053 QQmlNotifier objectNameNotifier;
1056 QQmlDataExtended::QQmlDataExtended()
1060 QQmlDataExtended::~QQmlDataExtended()
1064 void QQmlData::NotifyList::layout(QQmlNotifierEndpoint *endpoint)
1067 layout(endpoint->next);
1069 int index = endpoint->sourceSignal;
1070 index = qMin(index, 0xFFFF - 1);
1072 endpoint->next = notifies[index];
1073 if (endpoint->next) endpoint->next->prev = &endpoint->next;
1074 endpoint->prev = ¬ifies[index];
1075 notifies[index] = endpoint;
1078 void QQmlData::NotifyList::layout()
1080 Q_ASSERT(maximumTodoIndex >= notifiesSize);
1083 QQmlNotifierEndpoint **old = notifies;
1084 const int reallocSize = (maximumTodoIndex + 1) * sizeof(QQmlNotifierEndpoint*);
1085 notifies = (QQmlNotifierEndpoint**)realloc(notifies, reallocSize);
1086 const int memsetSize = (maximumTodoIndex - notifiesSize + 1) *
1087 sizeof(QQmlNotifierEndpoint*);
1088 memset(notifies + notifiesSize, 0, memsetSize);
1090 if (notifies != old) {
1091 for (int ii = 0; ii < notifiesSize; ++ii)
1093 notifies[ii]->prev = ¬ifies[ii];
1096 notifiesSize = maximumTodoIndex + 1;
1101 maximumTodoIndex = 0;
1105 void QQmlData::addNotify(int index, QQmlNotifierEndpoint *endpoint)
1108 notifyList = (NotifyList *)malloc(sizeof(NotifyList));
1109 notifyList->connectionMask = 0;
1110 notifyList->maximumTodoIndex = 0;
1111 notifyList->notifiesSize = 0;
1112 notifyList->todo = 0;
1113 notifyList->notifies = 0;
1116 Q_ASSERT(!endpoint->isConnected());
1118 index = qMin(index, 0xFFFF - 1);
1119 notifyList->connectionMask |= (1ULL << quint64(index % 64));
1121 if (index < notifyList->notifiesSize) {
1123 endpoint->next = notifyList->notifies[index];
1124 if (endpoint->next) endpoint->next->prev = &endpoint->next;
1125 endpoint->prev = ¬ifyList->notifies[index];
1126 notifyList->notifies[index] = endpoint;
1129 notifyList->maximumTodoIndex = qMax(int(notifyList->maximumTodoIndex), index);
1131 endpoint->next = notifyList->todo;
1132 if (endpoint->next) endpoint->next->prev = &endpoint->next;
1133 endpoint->prev = ¬ifyList->todo;
1134 notifyList->todo = endpoint;
1138 QQmlNotifier *QQmlData::objectNameNotifier() const
1140 if (!extendedData) extendedData = new QQmlDataExtended;
1141 return &extendedData->objectNameNotifier;
1144 QHash<int, QObject *> *QQmlData::attachedProperties() const
1146 if (!extendedData) extendedData = new QQmlDataExtended;
1147 return &extendedData->attachedProperties;
1150 void QQmlData::destroyed(QObject *object)
1152 if (deferredComponent)
1153 deferredComponent->release();
1155 if (nextContextObject)
1156 nextContextObject->prevContextObject = prevContextObject;
1157 if (prevContextObject)
1158 *prevContextObject = nextContextObject;
1160 QQmlAbstractBinding *binding = bindings;
1162 QQmlAbstractBinding *next = binding->m_nextBinding;
1163 binding->m_prevBinding = 0;
1164 binding->m_nextBinding = 0;
1169 QQmlAbstractBoundSignal *signalHandler = signalHandlers;
1170 while (signalHandler) {
1171 QQmlAbstractBoundSignal *next = signalHandler->m_nextSignal;
1172 signalHandler->m_prevSignal = 0;
1173 signalHandler->m_nextSignal = 0;
1174 delete signalHandler;
1175 signalHandler = next;
1182 propertyCache->release();
1184 if (ownContext && context)
1188 QQmlGuard<QObject> *guard = static_cast<QQmlGuard<QObject> *>(guards);
1189 *guard = (QObject *)0;
1190 guard->objectDestroyed(object);
1194 while (notifyList->todo)
1195 notifyList->todo->disconnect();
1196 for (int ii = 0; ii < notifyList->notifiesSize; ++ii) {
1197 while (QQmlNotifierEndpoint *ep = notifyList->notifies[ii])
1200 free(notifyList->notifies);
1205 delete extendedData;
1207 v8object.Clear(); // The WeakReference handler will clean the actual handle
1213 void QQmlData::parentChanged(QObject *object, QObject *parent)
1219 void QQmlData::objectNameChanged(QObject *)
1221 if (extendedData) objectNameNotifier()->notify();
1224 bool QQmlData::hasBindingBit(int bit) const
1226 if (bindingBitsSize > bit)
1227 return bindingBits[bit / 32] & (1 << (bit % 32));
1232 void QQmlData::clearBindingBit(int bit)
1234 if (bindingBitsSize > bit)
1235 bindingBits[bit / 32] &= ~(1 << (bit % 32));
1238 void QQmlData::setBindingBit(QObject *obj, int bit)
1240 if (bindingBitsSize <= bit) {
1241 int props = obj->metaObject()->propertyCount();
1242 Q_ASSERT(bit < props);
1244 int arraySize = (props + 31) / 32;
1245 int oldArraySize = bindingBitsSize / 32;
1247 bindingBits = (quint32 *)realloc(bindingBits,
1248 arraySize * sizeof(quint32));
1250 memset(bindingBits + oldArraySize,
1252 sizeof(quint32) * (arraySize - oldArraySize));
1254 bindingBitsSize = arraySize * 32;
1257 bindingBits[bit / 32] |= (1 << (bit % 32));
1260 QString QQmlEnginePrivate::urlToLocalFileOrQrc(const QUrl& url)
1262 if (url.scheme().compare(QLatin1String("qrc"), Qt::CaseInsensitive) == 0) {
1263 if (url.authority().isEmpty())
1264 return QLatin1Char(':') + url.path();
1267 return url.toLocalFile();
1271 static QString toLocalFile(const QString &url)
1273 if (!url.startsWith(QLatin1String("file://"), Qt::CaseInsensitive))
1276 QString file = url.mid(7);
1278 //XXX TODO: handle windows hostnames: "//servername/path/to/file.txt"
1280 // magic for drives on windows
1281 if (file.length() > 2 && file.at(0) == QLatin1Char('/') && file.at(2) == QLatin1Char(':'))
1287 QString QQmlEnginePrivate::urlToLocalFileOrQrc(const QString& url)
1289 if (url.startsWith(QLatin1String("qrc:"), Qt::CaseInsensitive)) {
1290 if (url.length() > 4)
1291 return QLatin1Char(':') + url.mid(4);
1295 return toLocalFile(url);
1298 void QQmlEnginePrivate::sendQuit()
1302 if (q->receivers(SIGNAL(quit())) == 0) {
1303 qWarning("Signal QQmlEngine::quit() emitted, but no receivers connected to handle it.");
1307 static void dumpwarning(const QQmlError &error)
1309 qWarning().nospace() << qPrintable(error.toString());
1312 static void dumpwarning(const QList<QQmlError> &errors)
1314 for (int ii = 0; ii < errors.count(); ++ii)
1315 dumpwarning(errors.at(ii));
1318 void QQmlEnginePrivate::warning(const QQmlError &error)
1321 q->warnings(QList<QQmlError>() << error);
1322 if (outputWarningsToStdErr)
1326 void QQmlEnginePrivate::warning(const QList<QQmlError> &errors)
1329 q->warnings(errors);
1330 if (outputWarningsToStdErr)
1331 dumpwarning(errors);
1334 void QQmlEnginePrivate::warning(QQmlEngine *engine, const QQmlError &error)
1337 QQmlEnginePrivate::get(engine)->warning(error);
1342 void QQmlEnginePrivate::warning(QQmlEngine *engine, const QList<QQmlError> &error)
1345 QQmlEnginePrivate::get(engine)->warning(error);
1350 void QQmlEnginePrivate::warning(QQmlEnginePrivate *engine, const QQmlError &error)
1353 engine->warning(error);
1358 void QQmlEnginePrivate::warning(QQmlEnginePrivate *engine, const QList<QQmlError> &error)
1361 engine->warning(error);
1367 This function should be called prior to evaluation of any js expression,
1368 so that scarce resources are not freed prematurely (eg, if there is a
1369 nested javascript expression).
1371 void QQmlEnginePrivate::referenceScarceResources()
1373 scarceResourcesRefCount += 1;
1377 This function should be called after evaluation of the js expression is
1378 complete, and so the scarce resources may be freed safely.
1380 void QQmlEnginePrivate::dereferenceScarceResources()
1382 Q_ASSERT(scarceResourcesRefCount > 0);
1383 scarceResourcesRefCount -= 1;
1385 // if the refcount is zero, then evaluation of the "top level"
1386 // expression must have completed. We can safely release the
1387 // scarce resources.
1388 if (scarceResourcesRefCount == 0) {
1389 // iterate through the list and release them all.
1390 // note that the actual SRD is owned by the JS engine,
1391 // so we cannot delete the SRD; but we can free the
1392 // memory used by the variant in the SRD.
1393 while (ScarceResourceData *sr = scarceResources.first()) {
1394 sr->data = QVariant();
1395 scarceResources.remove(sr);
1401 Adds \a path as a directory where the engine searches for
1402 installed modules in a URL-based directory structure.
1403 The \a path may be a local filesystem directory or a URL.
1405 The newly added \a path will be first in the importPathList().
1407 \sa setImportPathList(), {QML Modules}
1409 void QQmlEngine::addImportPath(const QString& path)
1412 d->importDatabase.addImportPath(path);
1416 Returns the list of directories where the engine searches for
1417 installed modules in a URL-based directory structure.
1419 For example, if \c /opt/MyApp/lib/imports is in the path, then QML that
1420 imports \c com.mycompany.Feature will cause the QQmlEngine to look
1421 in \c /opt/MyApp/lib/imports/com/mycompany/Feature/ for the components
1422 provided by that module. A \c qmldir file is required for defining the
1423 type version mapping and possibly QML extensions plugins.
1425 By default, the list contains the directory of the application executable,
1426 paths specified in the \c QML_IMPORT_PATH environment variable,
1427 and the builtin \c ImportsPath from QLibraryInfo.
1429 \sa addImportPath() setImportPathList()
1431 QStringList QQmlEngine::importPathList() const
1433 Q_D(const QQmlEngine);
1434 return d->importDatabase.importPathList();
1438 Sets \a paths as the list of directories where the engine searches for
1439 installed modules in a URL-based directory structure.
1441 By default, the list contains the directory of the application executable,
1442 paths specified in the \c QML_IMPORT_PATH environment variable,
1443 and the builtin \c ImportsPath from QLibraryInfo.
1445 \sa importPathList() addImportPath()
1447 void QQmlEngine::setImportPathList(const QStringList &paths)
1450 d->importDatabase.setImportPathList(paths);
1455 Adds \a path as a directory where the engine searches for
1456 native plugins for imported modules (referenced in the \c qmldir file).
1458 By default, the list contains only \c ., i.e. the engine searches
1459 in the directory of the \c qmldir file itself.
1461 The newly added \a path will be first in the pluginPathList().
1463 \sa setPluginPathList()
1465 void QQmlEngine::addPluginPath(const QString& path)
1468 d->importDatabase.addPluginPath(path);
1473 Returns the list of directories where the engine searches for
1474 native plugins for imported modules (referenced in the \c qmldir file).
1476 By default, the list contains only \c ., i.e. the engine searches
1477 in the directory of the \c qmldir file itself.
1479 \sa addPluginPath() setPluginPathList()
1481 QStringList QQmlEngine::pluginPathList() const
1483 Q_D(const QQmlEngine);
1484 return d->importDatabase.pluginPathList();
1488 Sets the list of directories where the engine searches for
1489 native plugins for imported modules (referenced in the \c qmldir file)
1492 By default, the list contains only \c ., i.e. the engine searches
1493 in the directory of the \c qmldir file itself.
1495 \sa pluginPathList() addPluginPath()
1497 void QQmlEngine::setPluginPathList(const QStringList &paths)
1500 d->importDatabase.setPluginPathList(paths);
1504 Imports the plugin named \a filePath with the \a uri provided.
1505 Returns true if the plugin was successfully imported; otherwise returns false.
1507 On failure and if non-null, the \a errors list will have any errors which occurred prepended to it.
1509 The plugin has to be a Qt plugin which implements the QQmlExtensionPlugin interface.
1511 bool QQmlEngine::importPlugin(const QString &filePath, const QString &uri, QList<QQmlError> *errors)
1514 return d->importDatabase.importPlugin(filePath, uri, errors);
1518 Imports the plugin named \a filePath with the \a uri provided.
1519 Returns true if the plugin was successfully imported; otherwise returns false.
1521 On failure and if non-null, *\a errorString will be set to a message describing the failure.
1523 The plugin has to be a Qt plugin which implements the QQmlExtensionPlugin interface.
1525 bool QQmlEngine::importPlugin(const QString &filePath, const QString &uri, QString *errorString)
1528 QList<QQmlError> errors;
1529 bool retn = d->importDatabase.importPlugin(filePath, uri, &errors);
1530 if (!errors.isEmpty()) {
1532 for (int i = 0; i < errors.size(); ++i) {
1533 builtError = QString(QLatin1String("%1\n %2"))
1535 .arg(errors.at(i).toString());
1537 *errorString = builtError;
1543 \property QQmlEngine::offlineStoragePath
1544 \brief the directory for storing offline user data
1546 Returns the directory where SQL and other offline
1549 QQuickWebView and the SQL databases created with openDatabase()
1552 The default is QML/OfflineStorage in the platform-standard
1553 user application data directory.
1555 Note that the path may not currently exist on the filesystem, so
1556 callers wanting to \e create new files at this location should create
1557 it first - see QDir::mkpath().
1559 void QQmlEngine::setOfflineStoragePath(const QString& dir)
1562 d->offlineStoragePath = dir;
1565 QString QQmlEngine::offlineStoragePath() const
1567 Q_D(const QQmlEngine);
1568 return d->offlineStoragePath;
1571 static void voidptr_destructor(void *v)
1573 void **ptr = (void **)v;
1577 static void *voidptr_constructor(const void *v)
1582 return new void*(*(void **)v);
1586 QQmlPropertyCache *QQmlEnginePrivate::createCache(const QMetaObject *mo)
1590 if (!mo->superClass()) {
1591 QQmlPropertyCache *rv = new QQmlPropertyCache(q, mo);
1592 propertyCache.insert(mo, rv);
1595 QQmlPropertyCache *super = cache(mo->superClass());
1596 QQmlPropertyCache *rv = super->copyAndAppend(q, mo);
1597 propertyCache.insert(mo, rv);
1602 QQmlPropertyCache *QQmlEnginePrivate::createCache(QQmlType *type, int minorVersion,
1605 QList<QQmlType *> types;
1607 int maxMinorVersion = 0;
1609 const QMetaObject *metaObject = type->metaObject();
1611 while (metaObject) {
1612 QQmlType *t = QQmlMetaType::qmlType(metaObject, type->module(),
1613 type->majorVersion(), minorVersion);
1615 maxMinorVersion = qMax(maxMinorVersion, t->minorVersion());
1621 metaObject = metaObject->superClass();
1624 if (QQmlPropertyCache *c = typePropertyCache.value(qMakePair(type, maxMinorVersion))) {
1626 typePropertyCache.insert(qMakePair(type, minorVersion), c);
1630 QQmlPropertyCache *raw = cache(type->metaObject());
1632 bool hasCopied = false;
1634 for (int ii = 0; ii < types.count(); ++ii) {
1635 QQmlType *currentType = types.at(ii);
1639 int rev = currentType->metaObjectRevision();
1640 int moIndex = types.count() - 1 - ii;
1642 if (raw->allowedRevisionCache[moIndex] != rev) {
1647 raw->allowedRevisionCache[moIndex] = rev;
1651 // Test revision compatibility - the basic rule is:
1652 // * Anything that is excluded, cannot overload something that is not excluded *
1654 // Signals override:
1655 // * other signals and methods of the same name.
1656 // * properties named on<Signal Name>
1657 // * automatic <property name>Changed notify signals
1659 // Methods override:
1660 // * other methods of the same name
1662 // Properties override:
1663 // * other elements of the same name
1665 bool overloadError = false;
1666 QString overloadName;
1669 for (QQmlPropertyCache::StringCache::ConstIterator iter = raw->stringCache.begin();
1670 !overloadError && iter != raw->stringCache.end();
1673 QQmlPropertyData *d = *iter;
1674 if (raw->isAllowedInRevision(d))
1675 continue; // Not excluded - no problems
1677 // check that a regular "name" overload isn't happening
1678 QQmlPropertyData *current = d;
1679 while (!overloadError && current) {
1680 current = d->overrideData(current);
1681 if (current && raw->isAllowedInRevision(current))
1682 overloadError = true;
1687 if (overloadError) {
1688 if (hasCopied) raw->release();
1690 error.setDescription(QLatin1String("Type ") + type->qmlTypeName() + QLatin1String(" ") + QString::number(type->majorVersion()) + QLatin1String(".") + QString::number(minorVersion) + QLatin1String(" contains an illegal property \"") + overloadName + QLatin1String("\". This is an error in the type's implementation."));
1694 if (!hasCopied) raw->addref();
1695 typePropertyCache.insert(qMakePair(type, minorVersion), raw);
1697 if (minorVersion != maxMinorVersion) {
1699 typePropertyCache.insert(qMakePair(type, maxMinorVersion), raw);
1705 QQmlMetaType::ModuleApiInstance *
1706 QQmlEnginePrivate::moduleApiInstance(const QQmlMetaType::ModuleApi &module)
1708 Locker locker(this);
1710 QQmlMetaType::ModuleApiInstance *a = moduleApiInstances.value(module);
1712 a = new QQmlMetaType::ModuleApiInstance;
1713 a->scriptCallback = module.script;
1714 a->qobjectCallback = module.qobject;
1715 a->instanceMetaObject = module.instanceMetaObject;
1716 moduleApiInstances.insert(module, a);
1722 bool QQmlEnginePrivate::isQObject(int t)
1724 Locker locker(this);
1725 return m_compositeTypes.contains(t) || QQmlMetaType::isQObject(t);
1728 QObject *QQmlEnginePrivate::toQObject(const QVariant &v, bool *ok) const
1730 Locker locker(this);
1731 int t = v.userType();
1732 if (t == QMetaType::QObjectStar || m_compositeTypes.contains(t)) {
1734 return *(QObject **)(v.constData());
1736 return QQmlMetaType::toQObject(v, ok);
1740 QQmlMetaType::TypeCategory QQmlEnginePrivate::typeCategory(int t) const
1742 Locker locker(this);
1743 if (m_compositeTypes.contains(t))
1744 return QQmlMetaType::Object;
1745 else if (m_qmlLists.contains(t))
1746 return QQmlMetaType::List;
1748 return QQmlMetaType::typeCategory(t);
1751 bool QQmlEnginePrivate::isList(int t) const
1753 Locker locker(this);
1754 return m_qmlLists.contains(t) || QQmlMetaType::isList(t);
1757 int QQmlEnginePrivate::listType(int t) const
1759 Locker locker(this);
1760 QHash<int, int>::ConstIterator iter = m_qmlLists.find(t);
1761 if (iter != m_qmlLists.end())
1764 return QQmlMetaType::listType(t);
1767 const QMetaObject *QQmlEnginePrivate::rawMetaObjectForType(int t) const
1769 Locker locker(this);
1770 QHash<int, QQmlCompiledData*>::ConstIterator iter = m_compositeTypes.find(t);
1771 if (iter != m_compositeTypes.end()) {
1772 return (*iter)->root;
1774 QQmlType *type = QQmlMetaType::qmlType(t);
1775 return type?type->baseMetaObject():0;
1779 const QMetaObject *QQmlEnginePrivate::metaObjectForType(int t) const
1781 Locker locker(this);
1782 QHash<int, QQmlCompiledData*>::ConstIterator iter = m_compositeTypes.find(t);
1783 if (iter != m_compositeTypes.end()) {
1784 return (*iter)->root;
1786 QQmlType *type = QQmlMetaType::qmlType(t);
1787 return type?type->metaObject():0;
1791 void QQmlEnginePrivate::registerCompositeType(QQmlCompiledData *data)
1793 QByteArray name = data->root->className();
1795 QByteArray ptr = name + '*';
1796 QByteArray lst = "QQmlListProperty<" + name + '>';
1798 int ptr_type = QMetaType::registerType(ptr.constData(), voidptr_destructor,
1799 voidptr_constructor);
1800 int lst_type = QMetaType::registerType(lst.constData(), voidptr_destructor,
1801 voidptr_constructor);
1805 Locker locker(this);
1806 m_qmlLists.insert(lst_type, ptr_type);
1807 m_compositeTypes.insert(ptr_type, data);
1810 bool QQml_isFileCaseCorrect(const QString &fileName)
1812 #if defined(Q_OS_MAC) || defined(Q_OS_WIN)
1813 QFileInfo info(fileName);
1814 const QString absolute = info.absoluteFilePath();
1816 #if defined(Q_OS_MAC)
1817 const QString canonical = info.canonicalFilePath();
1818 #elif defined(Q_OS_WIN)
1819 wchar_t buffer[1024];
1821 DWORD rv = ::GetShortPathName((wchar_t*)absolute.utf16(), buffer, 1024);
1822 if (rv == 0 || rv >= 1024) return true;
1823 rv = ::GetLongPathName(buffer, buffer, 1024);
1824 if (rv == 0 || rv >= 1024) return true;
1826 const QString canonical = QString::fromWCharArray(buffer);
1829 const int absoluteLength = absolute.length();
1830 const int canonicalLength = canonical.length();
1832 const int length = qMin(absoluteLength, canonicalLength);
1833 for (int ii = 0; ii < length; ++ii) {
1834 const QChar &a = absolute.at(absoluteLength - 1 - ii);
1835 const QChar &c = canonical.at(canonicalLength - 1 - ii);
1837 if (a.toLower() != c.toLower())
1849 \fn QQmlEngine *qmlEngine(const QObject *object)
1852 Returns the QQmlEngine associated with \a object, if any. This is equivalent to
1853 QQmlEngine::contextForObject(object)->engine(), but more efficient.
1857 \fn QQmlContext *qmlContext(const QObject *object)
1860 Returns the QQmlContext associated with \a object, if any. This is equivalent to
1861 QQmlEngine::contextForObject(object).