aboutsummaryrefslogtreecommitdiffstats
path: root/src/qml/qml/qqmlapplicationengine.cpp
blob: f7b8750d762bf4bf243e8c0b2c9d97ff8c8bdd97 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
/****************************************************************************
**
** Copyright (C) 2016 Research In Motion.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the QtQml module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or (at your option) the GNU General
** Public license version 3 or any later version approved by the KDE Free
** Qt Foundation. The licenses are as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-2.0.html and
** https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include <QtQml/qqmlfile.h>
#include <QtCore/QCoreApplication>
#include <QtCore/QTranslator>
#include <QQmlComponent>
#include "qqmlapplicationengine.h"
#include "qqmlapplicationengine_p.h"
#include "qqmlfileselector.h"

QT_BEGIN_NAMESPACE

QQmlApplicationEnginePrivate::QQmlApplicationEnginePrivate(QQmlEngine *e)
    : QQmlEnginePrivate(e)
{
    uiLanguage = QLocale().bcp47Name();
}

QQmlApplicationEnginePrivate::~QQmlApplicationEnginePrivate()
{
}

void QQmlApplicationEnginePrivate::cleanUp()
{
    Q_Q(QQmlApplicationEngine);
    for (auto obj : qAsConst(objects))
        obj->disconnect(q);

    qDeleteAll(objects);
}

void QQmlApplicationEnginePrivate::init()
{
    Q_Q(QQmlApplicationEngine);
    q->connect(q, &QQmlApplicationEngine::quit, QCoreApplication::instance(),
               &QCoreApplication::quit, Qt::QueuedConnection);
    q->connect(q, &QQmlApplicationEngine::exit, QCoreApplication::instance(),
               &QCoreApplication::exit, Qt::QueuedConnection);
    q->connect(q, SIGNAL(uiLanguageChanged()), q_func(), SLOT(_q_loadTranslations()));
#if QT_CONFIG(translation)
    QTranslator* qtTranslator = new QTranslator(q);
    if (qtTranslator->load(QLocale(), QLatin1String("qt"), QLatin1String("_"), QLibraryInfo::location(QLibraryInfo::TranslationsPath), QLatin1String(".qm")))
        QCoreApplication::installTranslator(qtTranslator);
    else
        delete qtTranslator;
#endif
    auto *selector = new QQmlFileSelector(q,q);
    selector->setExtraSelectors(extraFileSelectors);
    QCoreApplication::instance()->setProperty("__qml_using_qqmlapplicationengine", QVariant(true));
}

void QQmlApplicationEnginePrivate::_q_loadTranslations()
{
#if QT_CONFIG(translation)
    if (translationsDirectory.isEmpty())
        return;

    Q_Q(QQmlApplicationEngine);

    QScopedPointer<QTranslator> translator(new QTranslator);
    if (!uiLanguage.value().isEmpty()) {
        QLocale locale(uiLanguage);
        if (translator->load(locale, QLatin1String("qml"), QLatin1String("_"), translationsDirectory, QLatin1String(".qm"))) {
            if (activeTranslator)
                QCoreApplication::removeTranslator(activeTranslator.data());
            QCoreApplication::installTranslator(translator.data());
            activeTranslator.swap(translator);
        }
    } else {
        activeTranslator.reset();
    }
    q->retranslate();
#endif
}

void QQmlApplicationEnginePrivate::startLoad(const QUrl &url, const QByteArray &data, bool dataFlag)
{
    Q_Q(QQmlApplicationEngine);

    if (!isInitialized) {
        init();
        isInitialized = true;
    }

    if (url.scheme() == QLatin1String("file") || url.scheme() == QLatin1String("qrc")) {
        QFileInfo fi(QQmlFile::urlToLocalFileOrQrc(url));
        translationsDirectory = fi.path() + QLatin1String("/i18n");
    } else {
        translationsDirectory.clear();
    }

    _q_loadTranslations(); //Translations must be loaded before the QML file is
    QQmlComponent *c = new QQmlComponent(q, q);

    if (dataFlag)
        c->setData(data,url);
    else
        c->loadUrl(url);

    if (!c->isLoading()) {
        finishLoad(c);
        return;
    }
    QObject::connect(c, &QQmlComponent::statusChanged, q, [this, c] { this->finishLoad(c); });
}

void QQmlApplicationEnginePrivate::finishLoad(QQmlComponent *c)
{
    Q_Q(QQmlApplicationEngine);
    switch (c->status()) {
    case QQmlComponent::Error:
        qWarning() << "QQmlApplicationEngine failed to load component";
        warning(c->errors());
        q->objectCreated(nullptr, c->url());
        break;
    case QQmlComponent::Ready: {
        auto newObj = initialProperties.empty() ? c->create() : c->createWithInitialProperties(initialProperties);
        objects << newObj;
        QObject::connect(newObj, &QObject::destroyed, q, [&](QObject *obj) { objects.removeAll(obj); });
        q->objectCreated(objects.constLast(), c->url());
        }
        break;
    case QQmlComponent::Loading:
    case QQmlComponent::Null:
        return; //These cases just wait for the next status update
    }

    c->deleteLater();
}

/*!
  \class QQmlApplicationEngine
  \since 5.1
  \inmodule QtQml
  \brief QQmlApplicationEngine provides a convenient way to load an application from a single QML file.

  This class combines a QQmlEngine and QQmlComponent to provide a convenient way to load a single QML file. It also exposes some central application functionality to QML, which a C++/QML hybrid application would normally control from C++.

  It can be used like so:

  \code
  #include <QGuiApplication>
  #include <QQmlApplicationEngine>

  int main(int argc, char *argv[])
  {
      QGuiApplication app(argc, argv);
      QQmlApplicationEngine engine("main.qml");
      return app.exec();
  }
  \endcode

  Unlike QQuickView, QQmlApplicationEngine does not automatically create a root
  window. If you are using visual items from Qt Quick, you will need to place
  them inside of a \l [QML] {Window}.

  You can also use QCoreApplication with QQmlApplicationEngine, if you are not using any QML modules which require a QGuiApplication (such as \c QtQuick).

  List of configuration changes from a default QQmlEngine:

  \list
  \li Connecting Qt.quit() to QCoreApplication::quit()
  \li Automatically loads translation files from an i18n directory adjacent to the main QML file.
      \list
          \li Translation files must have "qml_" prefix e.g. qml_ja_JP.qm.
      \endlist
  \li Translations are reloaded when the \c QJSEngine::uiLanguage / \c Qt.uiLanguage property is changed.
  \li Automatically sets an incubation controller if the scene contains a QQuickWindow.
  \li Automatically sets a \c QQmlFileSelector as the url interceptor, applying file selectors to all
  QML files and assets.
  \endlist

  The engine behavior can be further tweaked by using the inherited methods from QQmlEngine.

*/

/*!
  \fn QQmlApplicationEngine::objectCreated(QObject *object, const QUrl &url)

  This signal is emitted when an object finishes loading. If loading was
  successful, \a object contains a pointer to the loaded object, otherwise
  the pointer is NULL.

  The \a url to the component the \a object came from is also provided.

  \note If the path to the component was provided as a QString containing a
  relative path, the \a url will contain a fully resolved path to the file.
*/

/*!
  Create a new QQmlApplicationEngine with the given \a parent. You will have to call load() later in
  order to load a QML file.
*/
QQmlApplicationEngine::QQmlApplicationEngine(QObject *parent)
: QQmlEngine(*(new QQmlApplicationEnginePrivate(this)), parent)
{
    QJSEnginePrivate::addToDebugServer(this);
}

/*!
  Create a new QQmlApplicationEngine and loads the QML file at the given \a url.
  This is provided as a convenience,  and is the same as using the empty constructor and calling load afterwards.
*/
QQmlApplicationEngine::QQmlApplicationEngine(const QUrl &url, QObject *parent)
    : QQmlApplicationEngine(parent)
{
    load(url);
}

/*!
  Create a new QQmlApplicationEngine and loads the QML file at the given
  \a filePath, which must be a local file path. If a relative path is
  given then it will be interpreted as relative to the working directory of the
  application.

  This is provided as a convenience, and is the same as using the empty constructor and calling load afterwards.
*/
QQmlApplicationEngine::QQmlApplicationEngine(const QString &filePath, QObject *parent)
    : QQmlApplicationEngine(QUrl::fromUserInput(filePath, QLatin1String("."), QUrl::AssumeLocalFile), parent)
{
}

/*!
  Destroys the QQmlApplicationEngine and all QML objects it loaded.
*/
QQmlApplicationEngine::~QQmlApplicationEngine()
{
    Q_D(QQmlApplicationEngine);
    QJSEnginePrivate::removeFromDebugServer(this);
    d->cleanUp();//Instantiated root objects must be deleted before the engine
}

/*!
  Loads the root QML file located at \a url. The object tree defined by the file
  is created immediately for local file urls. Remote urls are loaded asynchronously,
  listen to the \l {QQmlApplicationEngine::objectCreated()}{objectCreated} signal to
  determine when the object tree is ready.

  If an error occurs, the \l {QQmlApplicationEngine::objectCreated()}{objectCreated}
  signal is emitted with a null pointer as parameter and error messages are printed
  with qWarning.
*/
void QQmlApplicationEngine::load(const QUrl &url)
{
    Q_D(QQmlApplicationEngine);
    d->startLoad(url);
}

/*!
  Loads the root QML file located at \a filePath. \a filePath must be a path to
  a local file. If \a filePath is a relative path, it is taken as relative to
  the application's working directory. The object tree defined by the file is
  instantiated immediately.

  If an error occurs, error messages are printed with qWarning.
*/
void QQmlApplicationEngine::load(const QString &filePath)
{
    Q_D(QQmlApplicationEngine);
    d->startLoad(QUrl::fromUserInput(filePath, QLatin1String("."), QUrl::AssumeLocalFile));
}

/*!
   Sets the \a initialProperties with which the QML component gets initialized after
   it gets loaded.

   \code
    QQmlApplicationEngine engine;

    EventDatabase eventDatabase;
    EventMonitor eventMonitor;

    engine.setInitialProperties({
        { "eventDatabase", QVariant::fromValue(&eventDatabase) },
        { "eventMonitor", QVariant::fromValue(&eventMonitor) }
    });
   \endcode

   \sa QQmlComponent::setInitialProperties
   \sa QQmlApplicationEngine::load
   \sa QQmlApplicationEngine::loadData
   \since 5.14
*/
void QQmlApplicationEngine::setInitialProperties(const QVariantMap &initialProperties)
{
    Q_D(QQmlApplicationEngine);
    d->initialProperties = initialProperties;
}

/*!
  Sets the \a extraFileSelectors to be passed to the internal QQmlFileSelector
  used for resolving URLs to local files. The \a extraFileSelectors are applied
  when the first QML file is loaded. Setting them afterwards has no effect.

  \sa QQmlFileSelector
  \sa QFileSelector::setExtraSelectors
  \since 6.0
*/
void QQmlApplicationEngine::setExtraFileSelectors(const QStringList &extraFileSelectors)
{
    Q_D(QQmlApplicationEngine);
    if (d->isInitialized) {
        qWarning() << "QQmlApplicationEngine::setExtraFileSelectors()"
                   << "called after loading QML files. This has no effect.";
    } else {
        d->extraFileSelectors = extraFileSelectors;
    }
}

/*!
  Loads the QML given in \a data. The object tree defined by \a data is
  instantiated immediately.

  If a \a url is specified it is used as the base url of the component. This affects
  relative paths within the data and error messages.

  If an error occurs, error messages are printed with qWarning.
*/
void QQmlApplicationEngine::loadData(const QByteArray &data, const QUrl &url)
{
    Q_D(QQmlApplicationEngine);
    d->startLoad(url, data, true);
}

/*!
  Returns a list of all the root objects instantiated by the
  QQmlApplicationEngine. This will only contain objects loaded via load() or a
  convenience constructor.

  \note In Qt versions prior to 5.9, this function is marked as non-\c{const}.
*/

QList<QObject *> QQmlApplicationEngine::rootObjects() const
{
    Q_D(const QQmlApplicationEngine);
    return d->objects;
}

QT_END_NAMESPACE

#include "moc_qqmlapplicationengine.cpp"