-
Notifications
You must be signed in to change notification settings - Fork 177
/
qqmlengine.cpp
2241 lines (1840 loc) · 73.4 KB
/
qqmlengine.cpp
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
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include "qqmlengine_p.h"
#include "qqmlengine.h"
#include "qqmlcontext_p.h"
#include "qqml.h"
#include "qqmlcontext.h"
#include "qqmlscriptstring.h"
#include "qqmlglobal_p.h"
#include "qqmlnotifier_p.h"
#include "qqmlincubator.h"
#include "qqmlabstracturlinterceptor.h"
#include <private/qqmldirparser_p.h>
#include <private/qqmlboundsignal_p.h>
#include <private/qqmljsdiagnosticmessage_p.h>
#include <private/qqmltype_p_p.h>
#include <private/qqmlpluginimporter_p.h>
#include <QtCore/qstandardpaths.h>
#include <QtCore/qmetaobject.h>
#include <QDebug>
#include <QtCore/qcoreapplication.h>
#include <QtCore/qcryptographichash.h>
#include <QtCore/qdir.h>
#include <QtCore/qmutex.h>
#include <QtCore/qthread.h>
#include <private/qthread_p.h>
#include <private/qqmlscriptdata_p.h>
#include <QtQml/private/qqmlcomponentattached_p.h>
#include <QtQml/private/qqmlsourcecoordinate_p.h>
#include <QtQml/private/qqmlcomponent_p.h>
#if QT_CONFIG(qml_network)
#include "qqmlnetworkaccessmanagerfactory.h"
#include <QNetworkAccessManager>
#endif
#include <private/qobject_p.h>
#include <private/qmetaobject_p.h>
#if QT_CONFIG(qml_locale)
#include <private/qqmllocale_p.h>
#endif
#include <private/qqmlbind_p.h>
#include <private/qqmlconnections_p.h>
#if QT_CONFIG(qml_animation)
#include <private/qqmltimer_p.h>
#endif
#include <private/qqmlplatform_p.h>
#include <private/qqmlloggingcategory_p.h>
#include <private/qv4sequenceobject_p.h>
#ifdef Q_OS_WIN // for %APPDATA%
# include <qt_windows.h>
# include <shlobj.h>
# include <qlibrary.h>
# ifndef CSIDL_APPDATA
# define CSIDL_APPDATA 0x001a // <username>\Application Data
# endif
#endif // Q_OS_WIN
QT_BEGIN_NAMESPACE
/*!
\qmltype QtObject
\instantiates QObject
\inqmlmodule QtQml
\ingroup qml-utility-elements
\brief A basic QML type.
The QtObject type is a non-visual element which contains only the
objectName property.
It can be useful to create a QtObject if you need an extremely
lightweight type to enclose a set of custom properties:
\snippet qml/qtobject.qml 0
It can also be useful for C++ integration, as it is just a plain
QObject. See the QObject documentation for further details.
*/
/*!
\qmlproperty string QtObject::objectName
This property holds the QObject::objectName for this specific object instance.
This allows a C++ application to locate an item within a QML component
using the QObject::findChild() method. For example, the following C++
application locates the child \l Rectangle item and dynamically changes its
\c color value:
\qml
// MyRect.qml
import QtQuick 2.0
Item {
width: 200; height: 200
Rectangle {
anchors.fill: parent
color: "red"
objectName: "myRect"
}
}
\endqml
\code
// main.cpp
QQuickView view;
view.setSource(QUrl::fromLocalFile("MyRect.qml"));
view.show();
QQuickItem *item = view.rootObject()->findChild<QQuickItem*>("myRect");
if (item)
item->setProperty("color", QColor(Qt::yellow));
\endcode
*/
Q_CONSTINIT std::atomic<bool> QQmlEnginePrivate::qml_debugging_enabled{false};
bool QQmlEnginePrivate::s_designerMode = false;
bool QQmlEnginePrivate::designerMode()
{
return s_designerMode;
}
void QQmlEnginePrivate::activateDesignerMode()
{
s_designerMode = true;
}
/*!
\class QQmlImageProviderBase
\brief The QQmlImageProviderBase class is used to register image providers in the QML engine.
\inmodule QtQml
Image providers must be registered with the QML engine. The only information the QML
engine knows about image providers is the type of image data they provide. To use an
image provider to acquire image data, you must cast the QQmlImageProviderBase pointer
to a QQuickImageProvider pointer.
\sa QQuickImageProvider, QQuickTextureFactory
*/
/*!
\enum QQmlImageProviderBase::ImageType
Defines the type of image supported by this image provider.
\value Image The Image Provider provides QImage images.
The QQuickImageProvider::requestImage() method will be called for all image requests.
\value Pixmap The Image Provider provides QPixmap images.
The QQuickImageProvider::requestPixmap() method will be called for all image requests.
\value Texture The Image Provider provides QSGTextureProvider based images.
The QQuickImageProvider::requestTexture() method will be called for all image requests.
\value ImageResponse The Image provider provides QQuickTextureFactory based images.
Should only be used in QQuickAsyncImageProvider or its subclasses.
The QQuickAsyncImageProvider::requestImageResponse() method will be called for all image requests.
Since Qt 5.6
\omitvalue Invalid
*/
/*!
\enum QQmlImageProviderBase::Flag
Defines specific requirements or features of this image provider.
\value ForceAsynchronousImageLoading Ensures that image requests to the provider are
run in a separate thread, which allows the provider to spend as much time as needed
on producing the image without blocking the main thread.
*/
/*!
\fn QQmlImageProviderBase::imageType() const
Implement this method to return the image type supported by this image provider.
*/
/*!
\fn QQmlImageProviderBase::flags() const
Implement this to return the properties of this image provider.
*/
/*! \internal */
QQmlImageProviderBase::QQmlImageProviderBase()
{
}
/*! \internal */
QQmlImageProviderBase::~QQmlImageProviderBase()
{
}
QQmlEnginePrivate::~QQmlEnginePrivate()
{
if (inProgressCreations)
qWarning() << QQmlEngine::tr("There are still \"%1\" items in the process of being created at engine destruction.").arg(inProgressCreations);
if (incubationController) incubationController->d = nullptr;
incubationController = nullptr;
QQmlMetaType::freeUnusedTypesAndCaches();
#if QT_CONFIG(qml_debug)
delete profiler;
#endif
qDeleteAll(cachedValueTypeInstances);
}
void QQmlPrivate::qdeclarativeelement_destructor(QObject *o)
{
QObjectPrivate *p = QObjectPrivate::get(o);
if (QQmlData *d = QQmlData::get(p)) {
if (d->ownContext) {
for (QQmlRefPointer<QQmlContextData> lc = d->ownContext->linkedContext(); lc;
lc = lc->linkedContext()) {
lc->invalidate();
if (lc->contextObject() == o)
lc->setContextObject(nullptr);
}
d->ownContext->invalidate();
if (d->ownContext->contextObject() == o)
d->ownContext->setContextObject(nullptr);
d->ownContext.reset();
d->context = nullptr;
}
if (d->outerContext && d->outerContext->contextObject() == o)
d->outerContext->setContextObject(nullptr);
if (d->hasVMEMetaObject || d->hasInterceptorMetaObject) {
// This is somewhat dangerous because another thread might concurrently
// try to resolve the dynamic metaobject. In practice this will then
// lead to either the code path that still returns the interceptor
// metaobject or the code path that returns the string casted one. Both
// is fine if you cannot actually touch the object itself. Since the
// other thread is obviously not synchronized to this one, it can't.
//
// In particular we do this when delivering the frameSwapped() signal
// in QQuickWindow. The handler for frameSwapped() is written in a way
// that is thread safe as long as QQuickWindow's dtor hasn't finished.
// QQuickWindow's dtor does synchronize with the render thread, but it
// runs _after_ qdeclarativeelement_destructor.
static_cast<QQmlInterceptorMetaObject *>(p->metaObject)->invalidate();
d->hasVMEMetaObject = d->hasInterceptorMetaObject = false;
}
// Mark this object as in the process of deletion to
// prevent it resolving in bindings
QQmlData::markAsDeleted(o);
}
}
QQmlData::QQmlData(Ownership ownership)
: ownMemory(ownership == OwnsMemory), indestructible(true), explicitIndestructibleSet(false),
hasTaintedV4Object(false), isQueuedForDeletion(false), rootObjectInCreation(false),
hasInterceptorMetaObject(false), hasVMEMetaObject(false), hasConstWrapper(false), dummy(0),
bindingBitsArraySize(InlineBindingArraySize)
{
memset(bindingBitsValue, 0, sizeof(bindingBitsValue));
init();
}
QQmlData::~QQmlData()
{
}
void QQmlData::destroyed(QAbstractDeclarativeData *d, QObject *o)
{
QQmlData *ddata = static_cast<QQmlData *>(d);
ddata->destroyed(o);
}
class QQmlThreadNotifierProxyObject : public QObject
{
public:
QPointer<QObject> target;
int qt_metacall(QMetaObject::Call, int methodIndex, void **a) override {
if (!target)
return -1;
QMetaMethod method = target->metaObject()->method(methodIndex);
Q_ASSERT(method.methodType() == QMetaMethod::Signal);
int signalIndex = QMetaObjectPrivate::signalIndex(method);
QQmlData *ddata = QQmlData::get(target, false);
QQmlNotifierEndpoint *ep = ddata->notify(signalIndex);
if (ep) QQmlNotifier::emitNotify(ep, a);
delete this;
return -1;
}
};
void QQmlData::signalEmitted(QAbstractDeclarativeData *, QObject *object, int index, void **a)
{
QQmlData *ddata = QQmlData::get(object, false);
if (!ddata) return; // Probably being deleted
// In general, QML only supports QObject's that live on the same thread as the QQmlEngine
// that they're exposed to. However, to make writing "worker objects" that calculate data
// in a separate thread easier, QML allows a QObject that lives in the same thread as the
// QQmlEngine to emit signals from a different thread. These signals are then automatically
// marshalled back onto the QObject's thread and handled by QML from there. This is tested
// by the qqmlecmascript::threadSignal() autotest.
// Relaxed semantics here. If we're on a different thread we might schedule a useless event,
// but that should be rare.
if (!ddata->notifyList.loadRelaxed())
return;
auto objectThreadData = QObjectPrivate::get(object)->threadData.loadRelaxed();
if (QThread::currentThreadId() != objectThreadData->threadId.loadRelaxed()) {
if (!objectThreadData->thread.loadAcquire())
return;
QMetaMethod m = QMetaObjectPrivate::signal(object->metaObject(), index);
QList<QByteArray> parameterTypes = m.parameterTypes();
auto ev = std::make_unique<QMetaCallEvent>(m.methodIndex(), 0, nullptr,
object, index,
parameterTypes.size() + 1);
void **args = ev->args();
QMetaType *types = ev->types();
for (int ii = 0; ii < parameterTypes.size(); ++ii) {
const QByteArray &typeName = parameterTypes.at(ii);
if (typeName.endsWith('*'))
types[ii + 1] = QMetaType(QMetaType::VoidStar);
else
types[ii + 1] = QMetaType::fromName(typeName);
if (!types[ii + 1].isValid()) {
qWarning("QObject::connect: Cannot queue arguments of type '%s'\n"
"(Make sure '%s' is registered using qRegisterMetaType().)",
typeName.constData(), typeName.constData());
return;
}
args[ii + 1] = types[ii + 1].create(a[ii + 1]);
}
QQmlThreadNotifierProxyObject *mpo = new QQmlThreadNotifierProxyObject;
mpo->target = object;
mpo->moveToThread(objectThreadData->thread.loadAcquire());
QCoreApplication::postEvent(mpo, ev.release());
} else {
QQmlNotifierEndpoint *ep = ddata->notify(index);
if (ep) QQmlNotifier::emitNotify(ep, a);
}
}
int QQmlData::receivers(QAbstractDeclarativeData *d, const QObject *, int index)
{
QQmlData *ddata = static_cast<QQmlData *>(d);
return ddata->endpointCount(index);
}
bool QQmlData::isSignalConnected(QAbstractDeclarativeData *d, const QObject *, int index)
{
QQmlData *ddata = static_cast<QQmlData *>(d);
return ddata->signalHasEndpoint(index);
}
int QQmlData::endpointCount(int index)
{
int count = 0;
QQmlNotifierEndpoint *ep = notify(index);
if (!ep)
return count;
++count;
while (ep->next) {
++count;
ep = ep->next;
}
return count;
}
void QQmlData::markAsDeleted(QObject *o)
{
QVarLengthArray<QObject *> workStack;
workStack.push_back(o);
while (!workStack.isEmpty()) {
auto currentObject = workStack.last();
workStack.pop_back();
QQmlData::setQueuedForDeletion(currentObject);
auto currentObjectPriv = QObjectPrivate::get(currentObject);
for (QObject *child: std::as_const(currentObjectPriv->children))
workStack.push_back(child);
}
}
void QQmlData::setQueuedForDeletion(QObject *object)
{
if (object) {
if (QQmlData *ddata = QQmlData::get(object)) {
if (ddata->ownContext) {
Q_ASSERT(ddata->ownContext.data() == ddata->context);
ddata->context->emitDestruction();
if (ddata->ownContext->contextObject() == object)
ddata->ownContext->setContextObject(nullptr);
ddata->ownContext.reset();
ddata->context = nullptr;
}
ddata->isQueuedForDeletion = true;
// Disconnect the notifiers now - during object destruction this would be too late,
// since the disconnect call wouldn't be able to call disconnectNotify(), as it isn't
// possible to get the metaobject anymore.
// Also, there is no point in evaluating bindings in order to set properties on
// half-deleted objects.
ddata->disconnectNotifiers(DeleteNotifyList::No);
}
}
}
void QQmlData::flushPendingBinding(int coreIndex)
{
clearPendingBindingBit(coreIndex);
// Find the binding
QQmlAbstractBinding *b = bindings;
while (b && (b->targetPropertyIndex().coreIndex() != coreIndex ||
b->targetPropertyIndex().hasValueTypeIndex()))
b = b->nextBinding();
if (b && b->targetPropertyIndex().coreIndex() == coreIndex &&
!b->targetPropertyIndex().hasValueTypeIndex())
b->setEnabled(true, QQmlPropertyData::BypassInterceptor |
QQmlPropertyData::DontRemoveBinding);
}
QQmlData::DeferredData::DeferredData() = default;
QQmlData::DeferredData::~DeferredData() = default;
template<>
int qmlRegisterType<void>(const char *uri, int versionMajor, int versionMinor, const char *qmlName)
{
QQmlPrivate::RegisterType type = {
QQmlPrivate::RegisterType::CurrentVersion,
QMetaType(),
QMetaType(),
0, nullptr, nullptr,
QString(),
nullptr,
uri,
QTypeRevision::fromVersion(versionMajor, versionMinor),
qmlName,
nullptr,
nullptr,
nullptr,
-1,
-1,
-1,
nullptr,
nullptr,
nullptr,
QTypeRevision::zero(),
-1,
QQmlPrivate::ValueTypeCreationMethod::None,
};
return QQmlPrivate::qmlregister(QQmlPrivate::TypeRegistration, &type);
}
bool QQmlEnginePrivate::baseModulesUninitialized = true;
void QQmlEnginePrivate::init()
{
Q_Q(QQmlEngine);
if (baseModulesUninitialized) {
// Named builtins
qmlRegisterType<void>("QML", 1, 0, "void");
const int varId = qmlRegisterType<QVariant>("QML", 1, 0, "var");
QQmlMetaType::registerTypeAlias(varId, QLatin1String("variant"));
qmlRegisterAnonymousSequentialContainer<QList<QVariant>>("QML", 1);
qmlRegisterType<QObject>("QML", 1, 0, "QtObject");
qmlRegisterType<QQmlComponent>("QML", 1, 0, "Component");
qmlRegisterType<int>("QML", 1, 0, "int");
qmlRegisterAnonymousSequentialContainer<QList<int>>("QML", 1);
const int realId = qmlRegisterType<double>("QML", 1, 0, "real");
QQmlMetaType::registerTypeAlias(realId, QLatin1String("double"));
qmlRegisterAnonymousSequentialContainer<QList<double>>("QML", 1);
qmlRegisterType<QString>("QML", 1, 0, "string");
qmlRegisterAnonymousSequentialContainer<QList<QString>>("QML", 1);
qmlRegisterType<bool>("QML", 1, 0, "bool");
qmlRegisterAnonymousSequentialContainer<QList<bool>>("QML", 1);
qmlRegisterType<QDateTime>("QML", 1, 0, "date");
qmlRegisterAnonymousSequentialContainer<QList<QDateTime>>("QML", 1);
qmlRegisterType<QUrl>("QML", 1, 0, "url");
qmlRegisterAnonymousSequentialContainer<QList<QUrl>>("QML", 1);
#if QT_CONFIG(regularexpression)
qmlRegisterType<QRegularExpression>("QML", 1, 0, "regexp");
qmlRegisterAnonymousSequentialContainer<QList<QRegularExpression>>("QML", 1);
#else
qmlRegisterType<void>("QML", 1, 0, "regexp");
#endif
// Anonymous builtins
qmlRegisterAnonymousType<std::nullptr_t>("QML", 1);
qmlRegisterAnonymousType<QVariantMap>("QML", 1);
qmlRegisterAnonymousType<QJSValue>("QML", 1);
qmlRegisterAnonymousSequentialContainer<QList<QJSValue>>("QML", 1);
qmlRegisterAnonymousType<qint8>("QML", 1);
qmlRegisterAnonymousSequentialContainer<QList<qint8>>("QML", 1);
qmlRegisterAnonymousType<quint8>("QML", 1);
qmlRegisterAnonymousSequentialContainer<QList<quint8>>("QML", 1);
qmlRegisterAnonymousType<short>("QML", 1);
qmlRegisterAnonymousSequentialContainer<QList<short>>("QML", 1);
qmlRegisterAnonymousType<ushort>("QML", 1);
qmlRegisterAnonymousSequentialContainer<QList<ushort>>("QML", 1);
qmlRegisterAnonymousType<uint>("QML", 1);
qmlRegisterAnonymousSequentialContainer<QList<uint>>("QML", 1);
qmlRegisterAnonymousType<qlonglong>("QML", 1);
qmlRegisterAnonymousSequentialContainer<QList<qlonglong>>("QML", 1);
qmlRegisterAnonymousType<qulonglong>("QML", 1);
qmlRegisterAnonymousSequentialContainer<QList<qulonglong>>("QML", 1);
qmlRegisterAnonymousType<float>("QML", 1);
qmlRegisterAnonymousSequentialContainer<QList<float>>("QML", 1);
qmlRegisterAnonymousType<QChar>("QML", 1);
qmlRegisterAnonymousSequentialContainer<QList<QChar>>("QML", 1);
qmlRegisterAnonymousType<QDate>("QML", 1);
qmlRegisterAnonymousSequentialContainer<QList<QDate>>("QML", 1);
qmlRegisterAnonymousType<QTime>("QML", 1);
qmlRegisterAnonymousSequentialContainer<QList<QTime>>("QML", 1);
qmlRegisterAnonymousType<QByteArray>("QML", 1);
qmlRegisterAnonymousSequentialContainer<QList<QByteArray>>("QML", 1);
// No need to specifically register those.
static_assert(std::is_same_v<QStringList, QList<QString>>);
static_assert(std::is_same_v<QVariantList, QList<QVariant>>);
qRegisterMetaType<QQmlScriptString>();
qRegisterMetaType<QQmlComponent::Status>();
qRegisterMetaType<QList<QObject*> >();
qRegisterMetaType<QQmlBinding*>();
QQmlData::init();
baseModulesUninitialized = false;
}
q->handle()->setQmlEngine(q);
rootContext = new QQmlContext(q,true);
}
/*!
\class QQmlEngine
\since 5.0
\inmodule QtQml
\brief The QQmlEngine class provides an environment for instantiating QML components.
Each QML component is instantiated in a QQmlContext.
QQmlContext's are essential for passing data to QML
components. In QML, contexts are arranged hierarchically and this
hierarchy is managed by the QQmlEngine.
Prior to creating any QML components, an application must have
created a QQmlEngine to gain access to a QML context. The
following example shows how to create a simple Text item.
\code
QQmlEngine engine;
QQmlComponent component(&engine);
component.setData("import QtQuick 2.0\nText { text: \"Hello world!\" }", QUrl());
QQuickItem *item = qobject_cast<QQuickItem *>(component.create());
//add item to view, etc
...
\endcode
In this case, the Text item will be created in the engine's
\l {QQmlEngine::rootContext()}{root context}.
\sa QQmlComponent, QQmlContext, {QML Global Object}
*/
/*!
Create a new QQmlEngine with the given \a parent.
*/
QQmlEngine::QQmlEngine(QObject *parent)
: QJSEngine(*new QQmlEnginePrivate(this), parent)
{
Q_D(QQmlEngine);
d->init();
QJSEnginePrivate::addToDebugServer(this);
}
/*!
* \internal
*/
QQmlEngine::QQmlEngine(QQmlEnginePrivate &dd, QObject *parent)
: QJSEngine(dd, parent)
{
Q_D(QQmlEngine);
d->init();
}
/*!
Destroys the QQmlEngine.
Any QQmlContext's created on this engine will be
invalidated, but not destroyed (unless they are parented to the
QQmlEngine object).
See ~QJSEngine() for details on cleaning up the JS engine.
*/
QQmlEngine::~QQmlEngine()
{
Q_D(QQmlEngine);
QJSEnginePrivate::removeFromDebugServer(this);
// Emit onDestruction signals for the root context before
// we destroy the contexts, engine, Singleton Types etc. that
// may be required to handle the destruction signal.
QQmlContextPrivate::get(rootContext())->emitDestruction();
// clean up all singleton type instances which we own.
// we do this here and not in the private dtor since otherwise a crash can
// occur (if we are the QObject parent of the QObject singleton instance)
// XXX TODO: performance -- store list of singleton types separately?
d->singletonInstances.clear();
delete d->rootContext;
d->rootContext = nullptr;
d->typeLoader.invalidate();
}
/*! \fn void QQmlEngine::quit()
This signal is emitted when the QML loaded by the engine would like to quit.
\sa exit()
*/
/*! \fn void QQmlEngine::exit(int retCode)
This signal is emitted when the QML loaded by the engine would like to exit
from the event loop with the specified return code \a retCode.
\since 5.8
\sa quit()
*/
/*! \fn void QQmlEngine::warnings(const QList<QQmlError> &warnings)
This signal is emitted when \a warnings messages are generated by QML.
*/
/*!
Clears the engine's internal component cache.
This function causes the property metadata of all components previously
loaded by the engine to be destroyed. All previously loaded components and
the property bindings for all extant objects created from those components will
cease to function.
This function returns the engine to a state where it does not contain any loaded
component data. This may be useful in order to reload a smaller subset of the
previous component set, or to load a new version of a previously loaded component.
Once the component cache has been cleared, components must be loaded before
any new objects can be created.
\note Any existing objects created from QML components retain their types,
even if you clear the component cache. This includes singleton objects. If you
create more objects from the same QML code after clearing the cache, the new
objects will be of different types than the old ones. Assigning such a new
object to a property of its declared type belonging to an object created
before clearing the cache won't work.
As a general rule of thumb, make sure that no objects created from QML
components are alive when you clear the component cache.
\sa trimComponentCache(), clearSingletons()
*/
void QQmlEngine::clearComponentCache()
{
Q_D(QQmlEngine);
d->typeLoader.lock();
d->typeLoader.clearCache();
d->typeLoader.unlock();
}
/*!
Trims the engine's internal component cache.
This function causes the property metadata of any loaded components which are
not currently in use to be destroyed.
A component is considered to be in use if there are any extant instances of
the component itself, any instances of other components that use the component,
or any objects instantiated by any of those components.
\sa clearComponentCache()
*/
void QQmlEngine::trimComponentCache()
{
Q_D(QQmlEngine);
d->typeLoader.trimCache();
}
/*!
Clears all singletons the engine owns.
This function drops all singleton instances, deleting any QObjects owned by
the engine among them. This is useful to make sure that no QML-created objects
are left before calling clearComponentCache().
QML properties holding QObject-based singleton instances become null if the
engine owns the singleton or retain their value if the engine doesn't own it.
The singletons are not automatically re-created by accessing existing
QML-created objects. Only when new components are instantiated, the singletons
are re-created.
\sa clearComponentCache()
*/
void QQmlEngine::clearSingletons()
{
Q_D(QQmlEngine);
d->singletonInstances.clear();
}
/*!
Returns the engine's root context.
The root context is automatically created by the QQmlEngine.
Data that should be available to all QML component instances
instantiated by the engine should be put in the root context.
Additional data that should only be available to a subset of
component instances should be added to sub-contexts parented to the
root context.
*/
QQmlContext *QQmlEngine::rootContext() const
{
Q_D(const QQmlEngine);
return d->rootContext;
}
#if QT_DEPRECATED_SINCE(6, 0)
/*!
\internal
\deprecated
This API is private for 5.1
Returns the last QQmlAbstractUrlInterceptor. It must not be modified outside
the GUI thread.
*/
QQmlAbstractUrlInterceptor *QQmlEngine::urlInterceptor() const
{
Q_D(const QQmlEngine);
return d->urlInterceptors.last();
}
#endif
/*!
Adds a \a urlInterceptor to be used when resolving URLs in QML.
This also applies to URLs used for loading script files and QML types.
The URL interceptors should not be modifed while the engine is loading files,
or URL selection may be inconsistent. Multiple URL interceptors, when given,
will be called in the order they were added for each URL.
QQmlEngine does not take ownership of the interceptor and won't delete it.
*/
void QQmlEngine::addUrlInterceptor(QQmlAbstractUrlInterceptor *urlInterceptor)
{
Q_D(QQmlEngine);
d->urlInterceptors.append(urlInterceptor);
}
/*!
Remove a \a urlInterceptor that was previously added using
\l addUrlInterceptor. The URL interceptors should not be modifed while the
engine is loading files, or URL selection may be inconsistent.
This does not delete the interceptor, but merely removes it from the engine.
You can re-use it on the same or a different engine afterwards.
*/
void QQmlEngine::removeUrlInterceptor(QQmlAbstractUrlInterceptor *urlInterceptor)
{
Q_D(QQmlEngine);
d->urlInterceptors.removeOne(urlInterceptor);
}
/*!
Run the current URL interceptors on the given \a url of the given \a type and
return the result.
*/
QUrl QQmlEngine::interceptUrl(const QUrl &url, QQmlAbstractUrlInterceptor::DataType type) const
{
Q_D(const QQmlEngine);
QUrl result = url;
for (QQmlAbstractUrlInterceptor *interceptor : d->urlInterceptors)
result = interceptor->intercept(result, type);
return result;
}
/*!
Returns the list of currently active URL interceptors.
*/
QList<QQmlAbstractUrlInterceptor *> QQmlEngine::urlInterceptors() const
{
Q_D(const QQmlEngine);
return d->urlInterceptors;
}
QSharedPointer<QQmlImageProviderBase> QQmlEnginePrivate::imageProvider(const QString &providerId) const
{
const QString providerIdLower = providerId.toLower();
QMutexLocker locker(&imageProviderMutex);
return imageProviders.value(providerIdLower);
}
#if QT_CONFIG(qml_network)
/*!
Sets the \a factory to use for creating QNetworkAccessManager(s).
QNetworkAccessManager is used for all network access by QML. By
implementing a factory it is possible to create custom
QNetworkAccessManager with specialized caching, proxy and cookie
support.
The factory must be set before executing the engine.
\note QQmlEngine does not take ownership of the factory.
*/
void QQmlEngine::setNetworkAccessManagerFactory(QQmlNetworkAccessManagerFactory *factory)
{
Q_D(QQmlEngine);
QMutexLocker locker(&d->networkAccessManagerMutex);
d->networkAccessManagerFactory = factory;
}
/*!
Returns the current QQmlNetworkAccessManagerFactory.
\sa setNetworkAccessManagerFactory()
*/
QQmlNetworkAccessManagerFactory *QQmlEngine::networkAccessManagerFactory() const
{
Q_D(const QQmlEngine);
return d->networkAccessManagerFactory;
}
QNetworkAccessManager *QQmlEnginePrivate::createNetworkAccessManager(QObject *parent) const
{
QMutexLocker locker(&networkAccessManagerMutex);
QNetworkAccessManager *nam;
if (networkAccessManagerFactory) {
nam = networkAccessManagerFactory->create(parent);
} else {
nam = new QNetworkAccessManager(parent);
}
return nam;
}
QNetworkAccessManager *QQmlEnginePrivate::getNetworkAccessManager() const
{
Q_Q(const QQmlEngine);
if (!networkAccessManager)
networkAccessManager = createNetworkAccessManager(const_cast<QQmlEngine*>(q));
return networkAccessManager;
}
/*!
Returns a common QNetworkAccessManager which can be used by any QML
type instantiated by this engine.
If a QQmlNetworkAccessManagerFactory has been set and a
QNetworkAccessManager has not yet been created, the
QQmlNetworkAccessManagerFactory will be used to create the
QNetworkAccessManager; otherwise the returned QNetworkAccessManager
will have no proxy or cache set.
\sa setNetworkAccessManagerFactory()
*/
QNetworkAccessManager *QQmlEngine::networkAccessManager() const
{
Q_D(const QQmlEngine);
return d->getNetworkAccessManager();
}
#endif // qml_network
/*!
Sets the \a provider to use for images requested via the \e
image: url scheme, with host \a providerId. The QQmlEngine
takes ownership of \a provider.
Image providers enable support for pixmap and threaded image
requests. See the QQuickImageProvider documentation for details on
implementing and using image providers.
All required image providers should be added to the engine before any
QML sources files are loaded.
\sa removeImageProvider(), QQuickImageProvider, QQmlImageProviderBase
*/
void QQmlEngine::addImageProvider(const QString &providerId, QQmlImageProviderBase *provider)
{
Q_D(QQmlEngine);
QString providerIdLower = providerId.toLower();
QSharedPointer<QQmlImageProviderBase> sp(provider);
QMutexLocker locker(&d->imageProviderMutex);
d->imageProviders.insert(std::move(providerIdLower), std::move(sp));
}
/*!
Returns the image provider set for \a providerId if found; otherwise returns \nullptr.
\sa QQuickImageProvider
*/
QQmlImageProviderBase *QQmlEngine::imageProvider(const QString &providerId) const
{
Q_D(const QQmlEngine);
const QString providerIdLower = providerId.toLower();
QMutexLocker locker(&d->imageProviderMutex);
return d->imageProviders.value(providerIdLower).data();
}
/*!
Removes the image provider for \a providerId.
\sa addImageProvider(), QQuickImageProvider
*/
void QQmlEngine::removeImageProvider(const QString &providerId)
{
Q_D(QQmlEngine);
const QString providerIdLower = providerId.toLower();
QMutexLocker locker(&d->imageProviderMutex);
d->imageProviders.take(providerIdLower);
}
/*!
Return the base URL for this engine. The base URL is only used to
resolve components when a relative URL is passed to the
QQmlComponent constructor.
If a base URL has not been explicitly set, this method returns the
application's current working directory.
\sa setBaseUrl()
*/
QUrl QQmlEngine::baseUrl() const
{
Q_D(const QQmlEngine);
if (d->baseUrl.isEmpty()) {
const QString currentPath = QDir::currentPath();
const QString rootPath = QDir::rootPath();
return QUrl::fromLocalFile((currentPath == rootPath) ? rootPath : (currentPath + QDir::separator()));
} else {
return d->baseUrl;
}
}
/*!
Set the base URL for this engine to \a url.
\sa baseUrl()
*/
void QQmlEngine::setBaseUrl(const QUrl &url)
{
Q_D(QQmlEngine);
d->baseUrl = url;
}
/*!
Returns true if warning messages will be output to stderr in addition
to being emitted by the warnings() signal, otherwise false.