From c8198d40af104b5555a975b3156e9d5ba1981e25 Mon Sep 17 00:00:00 2001 From: Aaron Kennedy Date: Tue, 13 Oct 2009 17:00:21 +1000 Subject: Doc --- doc/src/declarative/ecmascriptblocks.qdoc | 126 +++++++++++++++++++++++++++--- 1 file changed, 117 insertions(+), 9 deletions(-) diff --git a/doc/src/declarative/ecmascriptblocks.qdoc b/doc/src/declarative/ecmascriptblocks.qdoc index 4dde19d..f683af8 100644 --- a/doc/src/declarative/ecmascriptblocks.qdoc +++ b/doc/src/declarative/ecmascriptblocks.qdoc @@ -43,17 +43,21 @@ \page qmlecmascript.html \title ECMAScript Blocks -QML encourages building UIs declaratively, using \l {Property Binding} and existing -\l {QML Elements}. When imperative code is required to implementing more advanced -behavior, the \l Script element can be used to add ECMAScript code directly to a -QML file, or to include an external ECMAScript file. +QML encourages building UIs declaratively, using \l {Property Binding} and the +composition of existing \l {QML Elements}. If imperative code is required to implement +more advanced behavior, the \l Script element can be used to add ECMAScript code directly +to a QML file, or to include an external ECMAScript file. The \l Script element is a QML language \e intrinsic. It can be used anywhere in a -QML file. \e except as the root element of a file or sub-component. The included -ECMAScript is evaluated in a scope chain. The \l {QML Scope} documentation covers -the specifics of scoping in QML. +QML file, \e except as the root element of a file or sub-component, but cannot be +assigned to an object property or given an id. The included ECMAScript is evaluated +in a scope chain. The \l {QML Scope} documentation covers the specifics of scoping +in QML. -\section1 Inline ECMAScript +\section1 Inline Script + +Small blocks of ECMAScript can be included directly inside a \l {QML Document} as +the body of the \l Script element. \code Rectangle { @@ -69,6 +73,110 @@ Rectangle { } \endcode -\section1 Including a ECMAScript File +Good programming practice dictates that only small script snippets should be written +inline. QML prohibits the declaration of anything other than functions in an inline +script block. For example, the following script is illegal as an inline script block +as it declares the non-function variable \c lastResult. + +\code +// Illegal inline code block +var lastResult = 0 +function factorial(var a) { + a = Integer(a); + if (a <= 0) + lastResult = 1; + else + lastResult = a * factorial(a - 1); + return lastResult; +} +\endcode + +\section1 Including an External File + +To avoid cluttering the QML file, large script blocks should be in a separate file. +The \l Script element's \c source property is used to load script from an external +file. + +If the previous factorial code that was illegal as an inline script block was saved +into a "factorial.js" file, it could be included like this. + +\code +Rectangle { + Script { + source: "factorial.js" + } +} +\endcode + +The \c source property may reference a relative file, or an absolute path. In the +case of a relative file, the location is resolved relative to the location of the +\l {QML Document} that contains the \l Script element. If the script file is not +accessible, an error will occur. If the source is on a network resource, the +enclosing QML document will remain in the \l {QmlComponent::status()}{waiting state} +until the script has been retrieved. + +\section1 QML Script Restrictions + +QML \l Script blocks contain standard ECMAScript code. QML introduces the following +restrictions. + +\list +\o Script code cannot modify the global object. + +In QML, the global object is constant - existing properties cannot be modified or +deleted, and no new properties may be created. + +Most ECMAScript programs do not explicitly modify the global object. However, +ECMAScript's automatic creation of undeclared variables is an implicit modification +of the global object, and is prohibited in QML. + +Assuming that the \c a variable does not exist in the scope chain, the following code +is illegal in QML. + +\code +// Illegal modification of undeclared variable +a = 1; +for (var ii = 1; ii < 10; ++ii) a = a * ii; +print("Result: " + a); +\endcode + +It can be trivially modified to this legal code. + +\code +var a = 1; +for (var ii = 1; ii < 10; ++ii) a = a * ii; +print("Result: " + a); +\endcode + +Any attempt to modify the global object - either implicitly or explicitly - will +cause an exception. If uncaught, this will result in an warning being printed, +that includes the file and line number of the offending code. + +\o Global code is run in a reduced scope + +During startup, if a \l Script block includes an external file with "global" +code, it is executed in a scope that contains only the external file itself and +the global object. That is, it will not have access to the QML objects and +properties it \l {QML Scope}{normally would}. + +Global code that only accesses script local variable is permitted. This is an +example of valid global code. + +\code +var colors = [ "red", "blue", "green", "orange", "purple" ]; +\endcode + +Global code that accesses QML objects will not run correctly. + +\code +// Invalid global code - the "rootObject" variable is undefined +var initialPosition = { rootObject.x, rootObject.y } +\endcode + +This restriction exists as the QML environment is not yet fully established. +To run code after the environment setup has completed - at "startup" - use +the \l Component \c onCompleted attached property. + +\endlist */ -- cgit v0.12 From 3491cdb2c1c9184adfb0fab1e636afd784a6565e Mon Sep 17 00:00:00 2001 From: Warwick Allison Date: Wed, 14 Oct 2009 09:17:53 +1000 Subject: fix test (data now shadowed, Script changed) --- tests/auto/declarative/qbindablemap/tst_qbindablemap.cpp | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/tests/auto/declarative/qbindablemap/tst_qbindablemap.cpp b/tests/auto/declarative/qbindablemap/tst_qbindablemap.cpp index c9c37ab..c1b31c2 100644 --- a/tests/auto/declarative/qbindablemap/tst_qbindablemap.cpp +++ b/tests/auto/declarative/qbindablemap/tst_qbindablemap.cpp @@ -3,6 +3,7 @@ #include #include #include +#include #include class tst_QBindableMap : public QObject @@ -58,11 +59,13 @@ void tst_QBindableMap::changed() //make changes in QML QmlEngine engine; QmlContext *ctxt = engine.rootContext(); - ctxt->setContextProperty(QLatin1String("data"), &map); - QmlComponent component(&engine, "import Qt 4.6\nScript { script: \"data.key1 = 'Hello World';\" }", + ctxt->setContextProperty(QLatin1String("testdata"), &map); + QmlComponent component(&engine, "import Qt 4.6\nText { text: { testdata.key1 = 'Hello World'; 'X' } }", QUrl("file://")); QVERIFY(component.isReady()); - component.create(); + QFxText *txt = qobject_cast(component.create()); + QVERIFY(txt); + QCOMPARE(txt->text(), QString('X')); QCOMPARE(spy.count(), 1); QList arguments = spy.takeFirst(); QCOMPARE(arguments.at(0).toString(),QLatin1String("key1")); -- cgit v0.12 From 0a10af2463d73106c2f1268553aa6e60890f6180 Mon Sep 17 00:00:00 2001 From: Aaron Kennedy Date: Wed, 14 Oct 2009 11:32:03 +1000 Subject: Add Component::onCompleted attached property --- doc/src/declarative/ecmascriptblocks.qdoc | 35 +++++++++++- src/declarative/qml/qmlcomponent.cpp | 65 ++++++++++++++++++++++ src/declarative/qml/qmlcomponent.h | 3 + src/declarative/qml/qmlcomponent_p.h | 21 ++++++- src/declarative/qml/qmlengine.cpp | 4 +- src/declarative/qml/qmlengine_p.h | 2 + .../qmllanguage/data/OnCompletedType.qml | 8 +++ .../declarative/qmllanguage/data/onCompleted.qml | 17 ++++++ .../declarative/qmllanguage/tst_qmllanguage.cpp | 13 +++++ 9 files changed, 163 insertions(+), 5 deletions(-) create mode 100644 tests/auto/declarative/qmllanguage/data/OnCompletedType.qml create mode 100644 tests/auto/declarative/qmllanguage/data/onCompleted.qml diff --git a/doc/src/declarative/ecmascriptblocks.qdoc b/doc/src/declarative/ecmascriptblocks.qdoc index f683af8..815c68c 100644 --- a/doc/src/declarative/ecmascriptblocks.qdoc +++ b/doc/src/declarative/ecmascriptblocks.qdoc @@ -115,6 +115,37 @@ accessible, an error will occur. If the source is on a network resource, the enclosing QML document will remain in the \l {QmlComponent::status()}{waiting state} until the script has been retrieved. +\section1 Running Script at Startup + +It is occasionally necessary to run a block of ECMAScript code at application (or +component instance) "startup". While it is tempting to just include the startup +script as \e {global code} in an external script file, this can have sever limitations +as the QML environment may not have been fully established. For example, some objects +might not have been created or some \l {Property Binding}s may not have been run. +\l {QML Script Restrictions} covers the exact limitations of global script code. + +The QML \l Component element provides an \e attached \c onCompleted property that +can be used to trigger the execution of script code at startup after the +QML environment has been completely established. + +The following QML code shows how to use the \c Component::onCompleted property. + +\code +Rectangle { + Script { + function startupFunction() { + // ... startup code + } + } + + Component.onCompleted: startupFunction(); +} +\endcode + +Any element in a QML file - including nested elements and nested QML component +instances - can use this attached property. If there is more than one script to +execute at startup, they are run sequentially in an undefined order. + \section1 QML Script Restrictions QML \l Script blocks contain standard ECMAScript code. QML introduces the following @@ -174,8 +205,8 @@ var initialPosition = { rootObject.x, rootObject.y } \endcode This restriction exists as the QML environment is not yet fully established. -To run code after the environment setup has completed - at "startup" - use -the \l Component \c onCompleted attached property. +To run code after the environment setup has completed, refer to +\l {Running Script at Startup}. \endlist diff --git a/src/declarative/qml/qmlcomponent.cpp b/src/declarative/qml/qmlcomponent.cpp index 9a761b2..dc71989 100644 --- a/src/declarative/qml/qmlcomponent.cpp +++ b/src/declarative/qml/qmlcomponent.cpp @@ -95,6 +95,27 @@ Item { Loader { sourceComponent: RedSquare; x: 20 } } \endqml + + \section1 Attached Properties + + \e onCompleted + + Emitted after component "startup" has completed. This can be used to + execute script code at startup, once the full QML environment has been + established. + + The \c {Component::onCompleted} attached property can be applied to + any element. The order of running the \c onCompleted scripts is + undefined. + + \qml + Rectangle { + Component.onCompleted: print("Completed Running!") + Rectangle { + Component.onCompleted: print("Nested Completed Running!") + } + } + \endqml */ QML_DEFINE_TYPE(Qt,4,6,(QT_VERSION&0x00ff00)>>8,Component,QmlComponent); @@ -532,6 +553,11 @@ QmlComponentPrivate::beginCreate(QmlContext *context, const QBitField &bindings) bindValues = ep->bindValues; parserStatus = ep->parserStatus; + componentAttacheds = ep->componentAttacheds; + if (componentAttacheds) + componentAttacheds->prev = &componentAttacheds; + + ep->componentAttacheds = 0; ep->bindValues.clear(); ep->parserStatus.clear(); completePending = true; @@ -593,10 +619,49 @@ void QmlComponentPrivate::completeCreate() QmlEnginePrivate::clear(ps); } + while (componentAttacheds) { + QmlComponentAttached *a = componentAttacheds; + if (a->next) a->next->prev = &componentAttacheds; + componentAttacheds = a->next; + a->prev = 0; a->next = 0; + emit a->completed(); + } + bindValues.clear(); parserStatus.clear(); completePending = false; } } +QmlComponentAttached::QmlComponentAttached(QObject *parent) +: QObject(parent), prev(0), next(0) +{ +} + +QmlComponentAttached::~QmlComponentAttached() +{ + if (prev) *prev = next; + if (next) next->prev = prev; + prev = 0; + next = 0; +} + +QmlComponentAttached *QmlComponent::qmlAttachedProperties(QObject *obj) +{ + QmlComponentAttached *a = new QmlComponentAttached(obj); + + QmlEngine *engine = qmlEngine(obj); + if (!engine || !QmlEnginePrivate::get(engine)->rootComponent) + return a; + + QmlEnginePrivate *p = QmlEnginePrivate::get(engine); + + a->next = p->componentAttacheds; + a->prev = &p->componentAttacheds; + if (a->next) a->next->prev = &a->next; + p->componentAttacheds = a; + + return a; +} + QT_END_NAMESPACE diff --git a/src/declarative/qml/qmlcomponent.h b/src/declarative/qml/qmlcomponent.h index c6924e3..dcf9347 100644 --- a/src/declarative/qml/qmlcomponent.h +++ b/src/declarative/qml/qmlcomponent.h @@ -59,6 +59,7 @@ class QmlCompiledData; class QByteArray; class QmlComponentPrivate; class QmlEngine; +class QmlComponentAttached; class Q_DECLARATIVE_EXPORT QmlComponent : public QObject { Q_OBJECT @@ -95,6 +96,8 @@ public: void loadUrl(const QUrl &url); void setData(const QByteArray &, const QUrl &baseUrl); + static QmlComponentAttached *qmlAttachedProperties(QObject *); + Q_SIGNALS: void statusChanged(QmlComponent::Status); void progressChanged(qreal); diff --git a/src/declarative/qml/qmlcomponent_p.h b/src/declarative/qml/qmlcomponent_p.h index 2d0c77f..7eedfbd 100644 --- a/src/declarative/qml/qmlcomponent_p.h +++ b/src/declarative/qml/qmlcomponent_p.h @@ -70,12 +70,13 @@ class QmlComponent; class QmlEngine; class QmlCompiledData; +class QmlComponentAttached; class QmlComponentPrivate : public QObjectPrivate { Q_DECLARE_PUBLIC(QmlComponent) public: - QmlComponentPrivate() : typeData(0), progress(0.), start(-1), count(-1), cc(0), completePending(false), engine(0) {} + QmlComponentPrivate() : typeData(0), progress(0.), start(-1), count(-1), cc(0), completePending(false), componentAttacheds(0), engine(0) {} QObject *create(QmlContext *context, const QBitField &); @@ -98,6 +99,7 @@ public: QList > bindValues; QList > parserStatus; + QmlComponentAttached *componentAttacheds; bool completePending; @@ -110,6 +112,23 @@ public: } }; +class QmlComponentAttached : public QObject +{ + Q_OBJECT +public: + QmlComponentAttached(QObject *parent = 0); + ~QmlComponentAttached(); + + QmlComponentAttached **prev; + QmlComponentAttached *next; + +signals: + void completed(); + +private: + friend class QmlComponentPrivate; +}; + QT_END_NAMESPACE #endif // QMLCOMPONENT_P_H diff --git a/src/declarative/qml/qmlengine.cpp b/src/declarative/qml/qmlengine.cpp index ef0f975..7e95428 100644 --- a/src/declarative/qml/qmlengine.cpp +++ b/src/declarative/qml/qmlengine.cpp @@ -125,8 +125,8 @@ static QString userLocalDataPath(const QString& app) QmlEnginePrivate::QmlEnginePrivate(QmlEngine *e) : rootContext(0), currentExpression(0), isDebugging(false), contextClass(0), objectClass(0), valueTypeClass(0), globalClass(0), - nodeListClass(0), namedNodeMapClass(0), sqlQueryClass(0), scriptEngine(this), rootComponent(0), - networkAccessManager(0), typeManager(e), uniqueId(1) + nodeListClass(0), namedNodeMapClass(0), sqlQueryClass(0), scriptEngine(this), + componentAttacheds(0), rootComponent(0), networkAccessManager(0), typeManager(e), uniqueId(1) { QScriptValue qtObject = scriptEngine.newQMetaObject(StaticQtMetaObject::get()); diff --git a/src/declarative/qml/qmlengine_p.h b/src/declarative/qml/qmlengine_p.h index 7978023..4c90a80 100644 --- a/src/declarative/qml/qmlengine_p.h +++ b/src/declarative/qml/qmlengine_p.h @@ -95,6 +95,7 @@ class QmlAbstractBinding; class QScriptDeclarativeClass; class QmlTypeNameScriptClass; class QmlTypeNameCache; +class QmlComponentAttached; class QmlEnginePrivate : public QObjectPrivate { @@ -174,6 +175,7 @@ public: QList > bindValues; QList > parserStatus; + QmlComponentAttached *componentAttacheds; QmlComponent *rootComponent; mutable QNetworkAccessManager *networkAccessManager; diff --git a/tests/auto/declarative/qmllanguage/data/OnCompletedType.qml b/tests/auto/declarative/qmllanguage/data/OnCompletedType.qml new file mode 100644 index 0000000..cdba495 --- /dev/null +++ b/tests/auto/declarative/qmllanguage/data/OnCompletedType.qml @@ -0,0 +1,8 @@ +import Test 1.0 +import Qt 4.6 + +MyQmlObject { + property int a: Math.max(10, 9) + property int b: 11 + Component.onCompleted: print("Completed " + a + " " + b); +} diff --git a/tests/auto/declarative/qmllanguage/data/onCompleted.qml b/tests/auto/declarative/qmllanguage/data/onCompleted.qml new file mode 100644 index 0000000..ae47d4b --- /dev/null +++ b/tests/auto/declarative/qmllanguage/data/onCompleted.qml @@ -0,0 +1,17 @@ +import Test 1.0 +import Qt 4.6 + +MyTypeObject { + // We set a and b to ensure that onCompleted is executed after bindings and + // constants have been assigned + property int a: Math.min(6, 7) + Component.onCompleted: print("Completed " + a + " " + nestedObject.b) + + objectProperty: OnCompletedType { + qmlobjectProperty: MyQmlObject { + id: nestedObject + property int b: 10 + Component.onCompleted: print("Completed " + a + " " + nestedObject.b) + } + } +} diff --git a/tests/auto/declarative/qmllanguage/tst_qmllanguage.cpp b/tests/auto/declarative/qmllanguage/tst_qmllanguage.cpp index cf42792..b99d040 100644 --- a/tests/auto/declarative/qmllanguage/tst_qmllanguage.cpp +++ b/tests/auto/declarative/qmllanguage/tst_qmllanguage.cpp @@ -60,6 +60,7 @@ private slots: void componentCompositeType(); void i18n(); void i18n_data(); + void onCompleted(); void importsBuiltin_data(); void importsBuiltin(); @@ -705,6 +706,18 @@ void tst_qmllanguage::i18n() delete object; } +// Check that the Component::onCompleted attached property works +void tst_qmllanguage::onCompleted() +{ + QmlComponent component(&engine, TEST_FILE("onCompleted.qml")); + VERIFY_ERRORS(0); + QTest::ignoreMessage(QtDebugMsg, "Completed 6 10"); + QTest::ignoreMessage(QtDebugMsg, "Completed 6 10"); + QTest::ignoreMessage(QtDebugMsg, "Completed 10 11"); + QObject *object = component.create(); + QVERIFY(object != 0); +} + // Check that first child of qml is of given type. Empty type insists on error. void tst_qmllanguage::testType(const QString& qml, const QString& type) { -- cgit v0.12 From cca9125431672193e93676ebd449c48664b52ba3 Mon Sep 17 00:00:00 2001 From: Michael Brasser Date: Wed, 14 Oct 2009 13:05:06 +1000 Subject: Fix animation autotests. --- tests/auto/declarative/animations/data/badproperty1.qml | 2 +- tests/auto/declarative/animations/tst_animations.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/auto/declarative/animations/data/badproperty1.qml b/tests/auto/declarative/animations/data/badproperty1.qml index a01753e..78da34a 100644 --- a/tests/auto/declarative/animations/data/badproperty1.qml +++ b/tests/auto/declarative/animations/data/badproperty1.qml @@ -16,7 +16,7 @@ Rectangle { } states: State { name: "state1" - PropertyChanges { target: MyRect; pen.color: "blue" } + PropertyChanges { target: MyRect; border.color: "blue" } } transitions: Transition { ColorAnimation { target: MyRect; to: "red"; properties: "pen.colr"; duration: 1000 } diff --git a/tests/auto/declarative/animations/tst_animations.cpp b/tests/auto/declarative/animations/tst_animations.cpp index 0e46224..336f0d3 100644 --- a/tests/auto/declarative/animations/tst_animations.cpp +++ b/tests/auto/declarative/animations/tst_animations.cpp @@ -86,7 +86,7 @@ void tst_animations::dotProperty() QTest::qWait(animation.duration() + 50); QCOMPARE(rect.border()->width(), 10); - rect.border()->setWidth(1); + rect.border()->setWidth(0); animation.start(); animation.pause(); animation.setCurrentTime(125); -- cgit v0.12 From 403350d5d6d85fb1ef9718401a6a60af313eaf5a Mon Sep 17 00:00:00 2001 From: Warwick Allison Date: Wed, 14 Oct 2009 13:09:38 +1000 Subject: Workaround QUrl::toLocalFile not knowing about qrc: QNetworkAccess does similar things. --- src/declarative/extra/qmlfontloader.cpp | 14 ++++++++++++-- src/declarative/fx/qfxborderimage.cpp | 14 ++++++++++++-- src/declarative/fx/qfxpixmapcache.cpp | 18 ++++++++++++++---- src/declarative/qml/qmlcompositetypemanager.cpp | 18 ++++++++++++++---- src/declarative/qml/qmlengine.cpp | 13 +++++++++++-- 5 files changed, 63 insertions(+), 14 deletions(-) diff --git a/src/declarative/extra/qmlfontloader.cpp b/src/declarative/extra/qmlfontloader.cpp index 66c8567..4a447de 100644 --- a/src/declarative/extra/qmlfontloader.cpp +++ b/src/declarative/extra/qmlfontloader.cpp @@ -92,6 +92,15 @@ QmlFontLoader::~QmlFontLoader() { } +static QString toLocalFileOrQrc(const QUrl& url) +{ + QString r = url.toLocalFile(); + if (r.isEmpty() && url.scheme() == QLatin1String("qrc")) + r = QLatin1Char(':') + url.path(); + return r; +} + + /*! \qmlproperty url FontLoader::source The url of the font to load. @@ -112,8 +121,9 @@ void QmlFontLoader::setSource(const QUrl &url) d->status = Loading; emit statusChanged(); #ifndef QT_NO_LOCALFILE_OPTIMIZED_QML - if (d->url.scheme() == QLatin1String("file")) { - QFile file(d->url.toLocalFile()); + QString lf = toLocalFileOrQrc(d->url); + if (!lf.isEmpty()) { + QFile file(lf); file.open(QIODevice::ReadOnly); QByteArray ba = file.readAll(); d->addFontToDatabase(ba); diff --git a/src/declarative/fx/qfxborderimage.cpp b/src/declarative/fx/qfxborderimage.cpp index 8f98a11..f1574e5 100644 --- a/src/declarative/fx/qfxborderimage.cpp +++ b/src/declarative/fx/qfxborderimage.cpp @@ -138,6 +138,15 @@ QFxBorderImage::~QFxBorderImage() The URL may be absolute, or relative to the URL of the component. */ +static QString toLocalFileOrQrc(const QUrl& url) +{ + QString r = url.toLocalFile(); + if (r.isEmpty() && url.scheme() == QLatin1String("qrc")) + r = QLatin1Char(':') + url.path(); + return r; +} + + void QFxBorderImage::setSource(const QUrl &url) { Q_D(QFxBorderImage); @@ -180,8 +189,9 @@ void QFxBorderImage::setSource(const QUrl &url) d->status = Loading; if (d->url.path().endsWith(QLatin1String(".sci"))) { #ifndef QT_NO_LOCALFILE_OPTIMIZED_QML - if (d->url.scheme() == QLatin1String("file")) { - QFile file(d->url.toLocalFile()); + QString lf = toLocalFileOrQrc(d->url); + if (!lf.isEmpty()) { + QFile file(lf); file.open(QIODevice::ReadOnly); setGridScaledImage(QFxGridScaledImage(&file)); } else diff --git a/src/declarative/fx/qfxpixmapcache.cpp b/src/declarative/fx/qfxpixmapcache.cpp index 80b5011..13e1b16 100644 --- a/src/declarative/fx/qfxpixmapcache.cpp +++ b/src/declarative/fx/qfxpixmapcache.cpp @@ -124,6 +124,14 @@ static bool readImage(QIODevice *dev, QPixmap *pixmap) This class is NOT reentrant. */ +static QString toLocalFileOrQrc(const QUrl& url) +{ + QString r = url.toLocalFile(); + if (r.isEmpty() && url.scheme() == QLatin1String("qrc")) + r = QLatin1Char(':') + url.path(); + return r; +} + /*! Finds the cached pixmap corresponding to \a url. A previous call to get() must have requested the URL, @@ -142,8 +150,9 @@ bool QFxPixmapCache::find(const QUrl& url, QPixmap *pixmap) bool ok = true; if (!QPixmapCache::find(key,pixmap)) { #ifndef QT_NO_LOCALFILE_OPTIMIZED_QML - if (url.scheme()==QLatin1String("file")) { - QFile f(url.toLocalFile()); + QString lf = toLocalFileOrQrc(url); + if (!lf.isEmpty()) { + QFile f(lf); if (f.open(QIODevice::ReadOnly)) { if (!readImage(&f, pixmap)) { qWarning() << "Format error loading" << url; @@ -207,10 +216,11 @@ bool QFxPixmapCache::find(const QUrl& url, QPixmap *pixmap) QNetworkReply *QFxPixmapCache::get(QmlEngine *engine, const QUrl& url, QPixmap *pixmap) { #ifndef QT_NO_LOCALFILE_OPTIMIZED_QML - if (url.scheme()==QLatin1String("file")) { + QString lf = toLocalFileOrQrc(url); + if (!lf.isEmpty()) { QString key = url.toString(); if (!QPixmapCache::find(key,pixmap)) { - QFile f(url.toLocalFile()); + QFile f(lf); if (f.open(QIODevice::ReadOnly)) { if (!readImage(&f, pixmap)) { qWarning() << "Format error loading" << url; diff --git a/src/declarative/qml/qmlcompositetypemanager.cpp b/src/declarative/qml/qmlcompositetypemanager.cpp index 13bd02c..3c76344 100644 --- a/src/declarative/qml/qmlcompositetypemanager.cpp +++ b/src/declarative/qml/qmlcompositetypemanager.cpp @@ -262,13 +262,22 @@ void QmlCompositeTypeManager::resourceReplyFinished() reply->deleteLater(); } +static QString toLocalFileOrQrc(const QUrl& url) +{ + QString r = url.toLocalFile(); + if (r.isEmpty() && url.scheme() == QLatin1String("qrc")) + r = QLatin1Char(':') + url.path(); + return r; +} + void QmlCompositeTypeManager::loadResource(QmlCompositeTypeResource *resource) { QUrl url(resource->url); - if (url.scheme() == QLatin1String("file")) { + QString lf = toLocalFileOrQrc(url); + if (!lf.isEmpty()) { - QFile file(url.toLocalFile()); + QFile file(lf); if (file.open(QFile::ReadOnly)) { resource->data = file.readAll(); resource->status = QmlCompositeTypeResource::Complete; @@ -290,9 +299,10 @@ void QmlCompositeTypeManager::loadSource(QmlCompositeTypeData *unit) { QUrl url(unit->imports.baseUrl()); - if (url.scheme() == QLatin1String("file")) { + QString lf = toLocalFileOrQrc(url); + if (!lf.isEmpty()) { - QFile file(url.toLocalFile()); + QFile file(lf); if (file.open(QFile::ReadOnly)) { QByteArray data = file.readAll(); setData(unit, data, url); diff --git a/src/declarative/qml/qmlengine.cpp b/src/declarative/qml/qmlengine.cpp index ef0f975..2bec140 100644 --- a/src/declarative/qml/qmlengine.cpp +++ b/src/declarative/qml/qmlengine.cpp @@ -955,6 +955,15 @@ QVariant QmlScriptClass::toVariant(QmlEngine *engine, const QScriptValue &val) return QVariant(); } +// XXX this beyonds in QUrl::toLocalFile() +static QString toLocalFileOrQrc(const QUrl& url) +{ + QString r = url.toLocalFile(); + if (r.isEmpty() && url.scheme() == QLatin1String("qrc")) + r = QLatin1Char(':') + url.path(); + return r; +} + ///////////////////////////////////////////////////////////// struct QmlEnginePrivate::ImportedNamespace { QStringList urls; @@ -985,7 +994,7 @@ struct QmlEnginePrivate::ImportedNamespace { QUrl url = QUrl(urls.at(i) + QLatin1String("/") + QString::fromUtf8(type) + QLatin1String(".qml")); if (vmaj || vmin) { // Check version file - XXX cache these in QmlEngine! - QFile qmldir(QUrl(urls.at(i)+QLatin1String("/qmldir")).toLocalFile()); + QFile qmldir(toLocalFileOrQrc(QUrl(urls.at(i)+QLatin1String("/qmldir")))); if (qmldir.open(QIODevice::ReadOnly)) { do { QByteArray lineba = qmldir.readLine(); @@ -1016,7 +1025,7 @@ struct QmlEnginePrivate::ImportedNamespace { } } else { // XXX search non-files too! (eg. zip files, see QT-524) - QFileInfo f(url.toLocalFile()); + QFileInfo f(toLocalFileOrQrc(url)); if (f.exists()) { if (url_return) *url_return = url; -- cgit v0.12 From f4d605eb2dddad17638d69d6024bc3d0efc878e6 Mon Sep 17 00:00:00 2001 From: Warwick Allison Date: Wed, 14 Oct 2009 13:16:19 +1000 Subject: doc --- doc/src/declarative/network.qdoc | 81 ++++++++++++++++++++++++++++++++++++++-- 1 file changed, 77 insertions(+), 4 deletions(-) diff --git a/doc/src/declarative/network.qdoc b/doc/src/declarative/network.qdoc index 3d75706..da4495f 100644 --- a/doc/src/declarative/network.qdoc +++ b/doc/src/declarative/network.qdoc @@ -43,11 +43,84 @@ \page qmlnetwork.html \title Network Transparency +QML supports network transparency by using URLs (rather than file names) for all +references from a QML document to other content. Since a \i relative URL is the same +as a relative file, development of QML on regular file systems remains simple. + +\section1 Accessing Network Reesources from QML + +Whenever an object has a property of type URL (QUrl), assigning a string to that +property will actually assign an absolute URL - by resolving the string against +the URL of the document where the string is used. + +For example, consider this content in \c{http://example.com/mystuff/test.qml}: + +\code +Image { + source: "images/logo.png" +} +\endcode + +The \l Image source property will be assigned \c{http://example.com/mystuff/images/logo.png}, +but while the QML is being developed, in say \c C:\User\Fred\Documents\MyStuff\test.qml, it will be assigned +\c C:\User\Fred\Documents\MyStuff\images\logo.png. + +Network transparency is supported throughout QML: + +\list +\o Types - if the \c test.qml file above used "Hello { }", that would refer to \c http://example.com/mystuff/Hello.qml +\o Scripts - the \c source property of \l Script is a URL +\o Images - the \c source property of \l Image and similar types is a URL +\o Fonts - the \c source property of FontLoader is a URL +\o WebViews - the \c url property of WebView may be assigned a relative URL string +\endlist + +Because of the declarative nature of QML and the asynchronous nature of network resources, +objects which reference network resource generally change state as the network resource loads. +For example, an Image with a network source will initially have +a \c width and \c height of 0, a \c status of \c Loading, and a \c progress of 0.0. +While the content loads, the \c progress will increase until +the content is fully loaded from the network, +at which point the \c width and \c height become the content size, the \c status becomes \c Ready, and the \c progress reaches 1.0. +Applications can bind to these changing states to provide visual progress indicators where appropriate, or simply +bind to the \c width and \c height as if the content was a local file, adapting as those bound values change. + +Note that when objects reference local files they immediately have the \c Ready status, but applications wishing +to remain network transparent should not rely on this. Future versions of QML may also use asynchronous local file I/O +to improve performance. + +\section1 Limitations + +The \c import statement only works network transparently if it has an "as" clause. + \list -\o Documents and script blocks can be fetched transparently over the network (blocking) -\o Images, fonts can be fetched transparently over the network (non-blocking) -\o Configuring the network access manager -\o Relative URL resolution from ECMAScript/QML +\o \c{import "dir"} only works on local file systems +\o \c{import libraryUri} only works on local file systems +\o \c{import "dir" as D} works network transparently +\o \c{import libraryUrl as U} works network transparently \endlist +\section1 Configuring the Network Access Manager + +All network access from QML is managed by a QNetworkAccessManager set on the QmlEngine which executes the QML. +By default, this is an unmodified Qt QNetworkAccessManager. You may set a different manager using +QmlEngine::setNetworkAccessManager() as appropriate for the policies of your application. +For eample, the \l qmlviewer tool sets a new QNetworkAccessManager which +trusts HTTP Expiry headers to avoid network cache checks, allows HTTP Pipelining, adds a persistent HTTP CookieJar, +a simple disk cache, and supports proxy settings. + +\section1 QRC Resources + +One of the URL schemes built into Qt is the "qrc" scheme. This allows content to be compiled into +the executable using \l{The Qt Resource System}. Using this, an executable can reference QML content +that is compiled into the executable: + +\code + QmlView *canvas = new QmlView; + canvas->setUrl(QUrl("qrc:/dial.qml")); +\endcode + +The content itself can then use relative URLs, and so be transparently unaware that the content is +compiled into the executable. + */ -- cgit v0.12