Qt
Internal/Contributor docs for the Qt SDK. <b>Note:</b> These are NOT official API docs; those are found <a href='https://doc.qt.io/'>here</a>.
Loading...
Searching...
No Matches
qqmlbuiltinfunctions.cpp
Go to the documentation of this file.
1// Copyright (C) 2021 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3
5
6#include <QtQml/qqmlcomponent.h>
7#include <QtQml/qqmlfile.h>
8#include <private/qqmlengine_p.h>
9#include <private/qqmlcomponent_p.h>
10#include <private/qqmlloggingcategory_p.h>
11#include <private/qqmlstringconverters_p.h>
12#if QT_CONFIG(qml_locale)
13#include <private/qqmllocale_p.h>
14#endif
15#include <private/qqmldelayedcallqueue_p.h>
16#include <QFileInfo>
17
18#include <private/qqmldebugconnector_p.h>
19#include <private/qqmldebugserviceinterfaces_p.h>
20#include <private/qqmlglobal_p.h>
21
22#include <private/qqmlplatform_p.h>
23
24#include <private/qv4engine_p.h>
25#include <private/qv4functionobject_p.h>
26#include <private/qv4include_p.h>
27#include <private/qv4context_p.h>
28#include <private/qv4stringobject_p.h>
29#include <private/qv4dateobject_p.h>
30#include <private/qv4mm_p.h>
31#include <private/qv4jsonobject_p.h>
32#include <private/qv4objectproto_p.h>
33#include <private/qv4qobjectwrapper_p.h>
34#include <private/qv4stackframe_p.h>
35
36#include <QtCore/qstring.h>
37#include <QtCore/qdatetime.h>
38#include <QtCore/qcryptographichash.h>
39#include <QtCore/qrect.h>
40#include <QtCore/qsize.h>
41#include <QtCore/qpoint.h>
42#include <QtCore/qurl.h>
43#include <QtCore/qfile.h>
44#include <QtCore/qcoreapplication.h>
45#include <QtCore/qloggingcategory.h>
46
47#include <QDebug>
48
50
51Q_LOGGING_CATEGORY(lcRootProperties, "qt.qml.rootObjectProperties");
52Q_LOGGING_CATEGORY(lcQml, "qml");
54
55using namespace QV4;
56
57#define THROW_TYPE_ERROR_WITH_MESSAGE(msg) \
58 do { \
59 return scope.engine->throwTypeError(QString::fromUtf8(msg)); \
60 } while (false)
61
66
269// Qt.include() is implemented in qv4include.cpp
270
271QtObject::QtObject(ExecutionEngine *engine)
272 : m_engine(engine)
273{
274}
275
276QtObject::Contexts QtObject::getContexts() const
277{
278 QQmlEngine *engine = qmlEngine();
279 if (!engine)
280 return {};
281
282 QQmlRefPointer<QQmlContextData> context = v4Engine()->callingQmlContext();
283 if (!context)
285
287 QQmlRefPointer<QQmlContextData> effectiveContext
288 = context->isPragmaLibraryContext() ? nullptr : context;
289 return {context, effectiveContext};
290}
291
293{
294 QV4::ExecutionEngine *v4 = jsEngine->handle();
295 QV4::Scope scope(v4);
297 ScopedString qtName(scope, v4->newString(QStringLiteral("Qt")));
298 QV4::ScopedValue result(scope, globalObject->get(qtName->toPropertyKey()));
299 return qobject_cast<QtObject *>(result->as<QV4::QObjectWrapper>()->object());
300}
301
302QJSValue QtObject::include(const QString &url, const QJSValue &callback) const
303{
304 return QV4Include::method_include(v4Engine(), v4Engine()->resolvedUrl(url), callback);
305}
306
307
315{
316 return qjsvalue_cast<QObject *>(value) != nullptr;
317}
318
326{
327 bool ok = false;
329 if (ok)
330 return v;
331
332 v4Engine()->throwError(QStringLiteral("\"%1\" is not a valid color name").arg(name));
333 return QVariant::fromValue(nullptr);
334}
335
342QVariant QtObject::rgba(double r, double g, double b, double a) const
343{
344 if (r < 0.0) r=0.0;
345 if (r > 1.0) r=1.0;
346 if (g < 0.0) g=0.0;
347 if (g > 1.0) g=1.0;
348 if (b < 0.0) b=0.0;
349 if (b > 1.0) b=1.0;
350 if (a < 0.0) a=0.0;
351 if (a > 1.0) a=1.0;
352
353 return QQml_colorProvider()->fromRgbF(r, g, b, a);
354}
355
362QVariant QtObject::hsla(double h, double s, double l, double a) const
363{
364 if (h < 0.0) h=0.0;
365 if (h > 1.0) h=1.0;
366 if (s < 0.0) s=0.0;
367 if (s > 1.0) s=1.0;
368 if (l < 0.0) l=0.0;
369 if (l > 1.0) l=1.0;
370 if (a < 0.0) a=0.0;
371 if (a > 1.0) a=1.0;
372
373 return QQml_colorProvider()->fromHslF(h, s, l, a);
374}
375
384QVariant QtObject::hsva(double h, double s, double v, double a) const
385{
386 h = qBound(0.0, h, 1.0);
387 s = qBound(0.0, s, 1.0);
388 v = qBound(0.0, v, 1.0);
389 a = qBound(0.0, a, 1.0);
390
391 return QQml_colorProvider()->fromHsvF(h, s, v, a);
392}
393
402bool QtObject::colorEqual(const QVariant &lhs, const QVariant &rhs) const
403{
404 bool ok = false;
405
406 QVariant color1 = lhs;
407 if (color1.userType() == QMetaType::QString) {
408 color1 = QQmlStringConverters::colorFromString(color1.toString(), &ok);
409 if (!ok) {
410 v4Engine()->throwError(QStringLiteral("Qt.colorEqual(): Invalid color name"));
411 return false;
412 }
413 } else if (color1.userType() != QMetaType::QColor) {
414 v4Engine()->throwError(QStringLiteral("Qt.colorEqual(): Invalid arguments"));
415 return false;
416 }
417
418 QVariant color2 = rhs;
419 if (color2.userType() == QMetaType::QString) {
420 color2 = QQmlStringConverters::colorFromString(color2.toString(), &ok);
421 if (!ok) {
422 v4Engine()->throwError(QStringLiteral("Qt.colorEqual(): Invalid color name"));
423 return false;
424 }
425 } else if (color2.userType() != QMetaType::QColor) {
426 v4Engine()->throwError(QStringLiteral("Qt.colorEqual(): Invalid arguments"));
427 return false;
428 }
429
430 return color1 == color2;
431}
432
438QRectF QtObject::rect(double x, double y, double width, double height) const
439{
440 return QRectF(x, y, width, height);
441}
442
448QPointF QtObject::point(double x, double y) const
449{
450 return QPointF(x, y);
451}
452
458QSizeF QtObject::size(double w, double h) const
459{
460 return QSizeF(w, h);
461}
462
472QVariant QtObject::font(const QJSValue &fontSpecifier) const
473{
474 if (!fontSpecifier.isObject()) {
475 v4Engine()->throwError(QStringLiteral("Qt.font(): Invalid arguments"));
476 return QVariant();
477 }
478
479 {
481 fontSpecifier, QMetaType(QMetaType::QFont));
482 if (v.isValid())
483 return v;
484 }
485
486 v4Engine()->throwError(QStringLiteral("Qt.font(): Invalid argument: "
487 "no valid font subproperties specified"));
488 return QVariant();
489}
490
491template<typename T>
492void addParameters(QJSEngine *e, QJSValue &result, int i, T parameter)
493{
494 result.setProperty(i, e->toScriptValue(parameter));
495}
496
497template<>
498void addParameters<double>(QJSEngine *, QJSValue &result, int i, double parameter)
499{
500 result.setProperty(i, QJSValue(parameter));
501}
502
503template<typename T, typename ...Others>
504void addParameters(QJSEngine *e, QJSValue &result, int i, T parameter, Others... others)
505{
506 addParameters<T>(e, result, i, parameter);
507 addParameters<Others...>(e, result, ++i, others...);
508}
509
510template<typename ...T>
512{
513 if (!e)
514 return QVariant();
515 QJSValue params = e->newArray(sizeof...(parameters));
516 addParameters(e, params, 0, parameters...);
518 return variant.isValid() ? variant : QVariant(type);
519}
520
526QVariant QtObject::vector2d(double x, double y) const
527{
528 return constructFromJSValue(jsEngine(), QMetaType(QMetaType::QVector2D), x, y);
529}
530
536QVariant QtObject::vector3d(double x, double y, double z) const
537{
538 return constructFromJSValue(jsEngine(), QMetaType(QMetaType::QVector3D), x, y, z);
539}
540
546QVariant QtObject::vector4d(double x, double y, double z, double w) const
547{
548 return constructFromJSValue(jsEngine(), QMetaType(QMetaType::QVector4D), x, y, z, w);
549}
550
556QVariant QtObject::quaternion(double scalar, double x, double y, double z) const
557{
558 return constructFromJSValue(jsEngine(), QMetaType(QMetaType::QQuaternion), scalar, x, y, z);
559}
560
567{
568 const QMetaType metaType(QMetaType::QMatrix4x4);
570 return variant.isValid() ? variant : QVariant(metaType);
571}
572
589{
590 if (value.isObject()) {
592 value, QMetaType(QMetaType::QMatrix4x4));
593 if (v.isValid())
594 return v;
595 }
596
597 v4Engine()->throwError(QStringLiteral("Qt.matrix4x4(): Invalid argument: "
598 "not a valid matrix4x4 values array"));
599 return QVariant();
600}
601
616QVariant QtObject::matrix4x4(double m11, double m12, double m13, double m14,
617 double m21, double m22, double m23, double m24,
618 double m31, double m32, double m33, double m34,
619 double m41, double m42, double m43, double m44) const
620{
621 return constructFromJSValue(jsEngine(), QMetaType(QMetaType::QMatrix4x4),
622 m11, m12, m13, m14, m21, m22, m23, m24,
623 m31, m32, m33, m34, m41, m42, m43, m44);
624}
625
627{
628 QVariant v;
629 if (color.isString()) {
631 if (!(*ok))
632 return QVariant::fromValue(nullptr);
633 } else {
634 v = color.toVariant();
635 if (v.userType() != QMetaType::QColor) {
636 *ok = false;
637 return QVariant::fromValue(nullptr);
638 }
639 }
640
641 *ok = true;
642 return v;
643}
644
660QVariant QtObject::lighter(const QJSValue &color, double factor) const
661{
662 bool ok;
664 return ok ? QQml_colorProvider()->lighter(v, factor) : v;
665}
666
683QVariant QtObject::darker(const QJSValue &color, double factor) const
684{
685 bool ok;
687 return ok ? QQml_colorProvider()->darker(v, factor) : v;
688}
689
697QVariant QtObject::alpha(const QJSValue &baseColor, double value) const
698{
699 bool ok;
700 const QVariant v = colorVariantFromJSValue(baseColor, &ok);
701 return ok ? QQml_colorProvider()->alpha(v, value) : v;
702}
703
730QVariant QtObject::tint(const QJSValue &baseColor, const QJSValue &tintColor) const
731{
732 bool ok;
733
734 // base color
735 const QVariant v1 = colorVariantFromJSValue(baseColor, &ok);
736 if (!ok)
737 return v1;
738
739 // tint color
740 const QVariant v2 = colorVariantFromJSValue(tintColor, &ok);
741
742 return ok ? QQml_colorProvider()->tint(v1, v2) : v2;
743}
744
745namespace {
746template <typename T>
747QString formatDateTimeObjectUsingDateFormat(T formatThis, Qt::DateFormat format) {
748 switch (format) {
749 case Qt::TextDate:
750 case Qt::ISODate:
751 case Qt::RFC2822Date:
753 return formatThis.toString(format);
754 default: // ### Qt 6: remove once qtbase has removed the rest of the enum !
755 break;
756 }
757 // Q_UNREACHABLE(); // ### Qt 6: restore once the default is gone
758 return QString();
759}
760}
761
763{
764 return dateTime.toLocalTime().time();
765}
766
783static std::optional<QDate> dateFromString(const QString &string, QV4::ExecutionEngine *engine)
784{
785 {
786 const QDate date = QDate::fromString(string, Qt::ISODate);
787 if (date.isValid())
788 return date;
789 }
790
791 {
792 // For historical reasons, the string argument is parsed as datetime, not as only date
793 const QDateTime dateTime = QDateTime::fromString(string, Qt::ISODate);
794 if (dateTime.isValid()) {
795 qCWarning(lcRootProperties())
796 << string << "is a date/time string being passed to formatDate()."
797 << "You should only pass date strings to formatDate().";
798 return dateTime.date();
799 }
800 }
801
802 {
803 // Since we can coerce QDate to QString, allow the resulting string format here.
805 if (dateTime.isValid())
807 }
808
809 engine->throwError(QStringLiteral("Invalid argument passed to formatDate(): %1").arg(string));
810 return std::nullopt;
811}
812
814{
815 return date.toString(format);
816}
817
819{
820 return formatDateTimeObjectUsingDateFormat(date, format);
821}
822
827
829{
830 if (const auto qDate = dateFromString(string, v4Engine()))
831 return formatDate(qDate.value(), format);
832
833 return QString();
834}
835
837{
838 return formatDateTimeObjectUsingDateFormat(DateObject::dateTimeToDate(dateTime), format);
839}
840
842{
843 if (const auto qDate = dateFromString(string, v4Engine()))
844 return formatDate(qDate.value(), format);
845
846 return QString();
847}
848
849#if QT_CONFIG(qml_locale)
851 QLocale::FormatType formatType) const
852{
853 return locale.toString(date, formatType);
854}
855
857 QLocale::FormatType formatType) const
858{
859 return locale.toString(DateObject::dateTimeToDate(dateTime), formatType);
860}
861
862QString QtObject::formatDate(const QString &string, const QLocale &locale,
863 QLocale::FormatType formatType) const
864{
865 if (const auto qDate = dateFromString(string, v4Engine()))
866 return locale.toString(qDate.value(), formatType);
867
868 return QString();
869}
870#endif
871
888static std::optional<QTime> timeFromString(const QString &string, QV4::ExecutionEngine *engine)
889{
890 {
891 const QTime time = QTime::fromString(string, Qt::ISODate);
892 if (time.isValid())
893 return time;
894 }
895
896 {
897 // For historical reasons, the string argument is parsed as datetime, not as only time
898 const QDateTime dateTime = QDateTime::fromString(string, Qt::ISODate);
899 if (dateTime.isValid()) {
900 qCWarning(lcRootProperties())
901 << string << "is a date/time string being passed to formatTime()."
902 << "You should only pass time strings to formatTime().";
903 return dateTime.time();
904 }
905 }
906
907 {
908 // Since we can coerce QTime to QString, allow the resulting string format here.
910 if (dateTime.isValid())
911 return dateTimeToTime(dateTime);
912 }
913
914 engine->throwError(QStringLiteral("Invalid argument passed to formatTime(): %1").arg(string));
915 return std::nullopt;
916}
917
919{
920 return time.toString(format);
921}
922
924{
925 return dateTimeToTime(dateTime).toString(format);
926}
927
929{
930
931 if (auto qTime = timeFromString(time, v4Engine()))
932 return formatTime(qTime.value(), format);
933
934 return QString();
935}
936
938{
939 return formatDateTimeObjectUsingDateFormat(time, format);
940}
941
943{
944 return formatDateTimeObjectUsingDateFormat(dateTimeToTime(dateTime), format);
945}
946
948{
949 if (auto qTime = timeFromString(time, v4Engine()))
950 return formatTime(qTime.value(), format);
951
952 return QString();
953}
954
955#if QT_CONFIG(qml_locale)
957 QLocale::FormatType formatType) const
958{
959 return locale.toString(time, formatType);
960}
961
963 QLocale::FormatType formatType) const
964{
965 return locale.toString(dateTimeToTime(dateTime), formatType);
966}
967
968QString QtObject::formatTime(const QString &time, const QLocale &locale,
969 QLocale::FormatType formatType) const
970{
971 if (auto qTime = timeFromString(time, v4Engine()))
972 return locale.toString(qTime.value(), formatType);
973
974 return QString();
975}
976#endif
977
1076static std::optional<QDateTime> dateTimeFromString(const QString &string, QV4::ExecutionEngine *engine)
1077{
1078 {
1079 const QDateTime dateTime = QDateTime::fromString(string, Qt::ISODate);
1080 if (dateTime.isValid())
1081 return dateTime;
1082 }
1083
1084 {
1085 // Since we can coerce QDateTime to QString, allow the resulting string format here.
1087 if (dateTime.isValid())
1088 return dateTime;
1089 }
1090
1091 engine->throwError(QStringLiteral("Invalid argument passed to formatDateTime(): %1").arg(string));
1092 return std::nullopt;
1093}
1094
1096{
1097 return dateTime.toString(format);
1098}
1099
1101{
1102
1103 if (const auto qDateTime = dateTimeFromString(string, v4Engine()))
1104 return formatDateTime(qDateTime.value(), format);
1105
1106 return QString();
1107}
1108
1110{
1111 return formatDateTimeObjectUsingDateFormat(dateTime, format);
1112}
1113
1115{
1116
1117 if (const auto qDateTime = dateTimeFromString(string, v4Engine()))
1118 return formatDateTime(qDateTime.value(), format);
1119
1120 return QString();
1121}
1122
1123#if QT_CONFIG(qml_locale)
1125 QLocale::FormatType formatType) const
1126{
1127 return locale.toString(dateTime, formatType);
1128}
1129
1130QString QtObject::formatDateTime(const QString &string, const QLocale &locale,
1131 QLocale::FormatType formatType) const
1132{
1133
1134 if (const auto qDateTime = dateTimeFromString(string, v4Engine()))
1135 return formatDateTime(qDateTime.value(), locale, formatType);
1136
1137 return QString();
1138}
1139#endif
1140
1156
1168{
1169 return url;
1170}
1171
1184{
1185 if (QQmlRefPointer<QQmlContextData> ctxt = v4Engine()->callingQmlContext())
1186 return ctxt->resolvedUrl(url);
1187 if (QQmlEngine *engine = qmlEngine())
1188 return engine->baseUrl().resolved(url);
1189 return url;
1190}
1191
1203{
1204 if (context) {
1206 if (data && data->outerContext)
1207 return data->outerContext->resolvedUrl(url);
1208 }
1209
1210 if (QQmlEngine *engine = qmlEngine())
1211 return engine->baseUrl().resolved(url);
1212 return url;
1213}
1214
1224
1230{
1232}
1233
1239{
1240 return QLatin1String(data.toUtf8().toBase64());
1241}
1242
1248{
1249 return QString::fromUtf8(QByteArray::fromBase64(data.toLatin1()));
1250}
1251
1263void QtObject::quit() const
1264{
1265 if (QQmlEngine *engine = qmlEngine())
1266 QQmlEnginePrivate::get(engine)->sendQuit();
1267}
1268
1281void QtObject::exit(int retCode) const
1282{
1283 if (QQmlEngine *engine = qmlEngine())
1284 QQmlEnginePrivate::get(engine)->sendExit(retCode);
1285}
1286
1316QObject *QtObject::createQmlObject(const QString &qml, QObject *parent, const QUrl &url) const
1317{
1318 QQmlEngine *engine = qmlEngine();
1319 if (!engine) {
1320 v4Engine()->throwError(QStringLiteral("Qt.createQmlObject(): "
1321 "Can only be called on a QML engine."));
1322 return nullptr;
1323 }
1324
1325 struct Error {
1326 static ReturnedValue create(QV4::ExecutionEngine *v4, const QList<QQmlError> &errors) {
1327 Scope scope(v4);
1328 QString errorstr;
1329 // '+=' reserves extra capacity. Follow-up appending will be probably free.
1330 errorstr += QLatin1String("Qt.createQmlObject(): failed to create object: ");
1331
1332 QV4::ScopedArrayObject qmlerrors(scope, v4->newArrayObject());
1333 QV4::ScopedObject qmlerror(scope);
1334 QV4::ScopedString s(scope);
1335 QV4::ScopedValue v(scope);
1336 for (int ii = 0; ii < errors.size(); ++ii) {
1337 const QQmlError &error = errors.at(ii);
1338 errorstr += QLatin1String("\n ") + error.toString();
1339 qmlerror = v4->newObject();
1340 qmlerror->put((s = v4->newString(QStringLiteral("lineNumber"))), (v = QV4::Value::fromInt32(error.line())));
1341 qmlerror->put((s = v4->newString(QStringLiteral("columnNumber"))), (v = QV4::Value::fromInt32(error.column())));
1342 qmlerror->put((s = v4->newString(QStringLiteral("fileName"))), (v = v4->newString(error.url().toString())));
1343 qmlerror->put((s = v4->newString(QStringLiteral("message"))), (v = v4->newString(error.description())));
1344 qmlerrors->put(ii, qmlerror);
1345 }
1346
1347 v = v4->newString(errorstr);
1348 ScopedObject errorObject(scope, v4->newErrorObject(v));
1349 errorObject->put((s = v4->newString(QStringLiteral("qmlErrors"))), qmlerrors);
1350 return errorObject.asReturnedValue();
1351 }
1352 };
1353
1354 QQmlRefPointer<QQmlContextData> context = v4Engine()->callingQmlContext();
1355 if (!context)
1357
1359 QQmlContext *effectiveContext = nullptr;
1360 if (context->isPragmaLibraryContext())
1361 effectiveContext = engine->rootContext();
1362 else
1363 effectiveContext = context->asQQmlContext();
1364 Q_ASSERT(effectiveContext);
1365
1366 if (qml.isEmpty())
1367 return nullptr;
1368
1370 if (url.isValid() && url.isRelative())
1371 resolvedUrl = context->resolvedUrl(url);
1372
1373 if (!parent) {
1374 v4Engine()->throwError(QStringLiteral("Qt.createQmlObject(): Missing parent object"));
1375 return nullptr;
1376 }
1377
1378 QQmlRefPointer<QQmlTypeData> typeData = QQmlEnginePrivate::get(engine)->typeLoader.getType(
1380 Q_ASSERT(typeData->isCompleteOrError());
1383 componentPrivate->fromTypeData(typeData);
1384 componentPrivate->progress = 1.0;
1385
1386 Scope scope(v4Engine());
1387 if (component.isError()) {
1388 ScopedValue v(scope, Error::create(scope.engine, component.errors()));
1389 scope.engine->throwError(v);
1390 return nullptr;
1391 }
1392
1393 if (!component.isReady()) {
1394 v4Engine()->throwError(QStringLiteral("Qt.createQmlObject(): Component is not ready"));
1395 return nullptr;
1396 }
1397
1398 if (!effectiveContext->isValid()) {
1399 v4Engine()->throwError(QStringLiteral("Qt.createQmlObject(): Cannot create a component "
1400 "in an invalid context"));
1401 return nullptr;
1402 }
1403
1404 QObject *obj = component.beginCreate(effectiveContext);
1405 if (obj) {
1406 QQmlData::get(obj, true)->explicitIndestructibleSet = false;
1407 QQmlData::get(obj)->indestructible = false;
1408
1409 obj->setParent(parent);
1410
1411 QList<QQmlPrivate::AutoParentFunction> functions = QQmlMetaType::parentFunctions();
1412 for (int ii = 0; ii < functions.size(); ++ii) {
1413 if (QQmlPrivate::Parented == functions.at(ii)(obj, parent))
1414 break;
1415 }
1416 }
1417 component.completeCreate();
1418
1419 if (component.isError()) {
1420 ScopedValue v(scope, Error::create(scope.engine, component.errors()));
1421 scope.engine->throwError(v);
1422 return nullptr;
1423 }
1424
1425 Q_ASSERT(obj);
1426 return obj;
1427}
1428
1503
1505 QObject *parent) const
1506{
1508 v4Engine()->throwError(QStringLiteral("Invalid compilation mode %1").arg(mode));
1509 return nullptr;
1510 }
1511
1512 if (url.isEmpty())
1513 return nullptr;
1514
1515 QQmlEngine *engine = qmlEngine();
1516 if (!engine)
1517 return nullptr;
1518
1519 auto [context, effectiveContext] = getContexts();
1520 if (!context)
1521 return nullptr;
1522
1523 QQmlComponent *c = new QQmlComponent(engine, context->resolvedUrl(url), mode, parent);
1524 QQmlComponentPrivate::get(c)->creationContext = effectiveContext;
1525 QQmlData::get(c, true)->explicitIndestructibleSet = false;
1526 QQmlData::get(c)->indestructible = false;
1527 return c;
1528}
1529
1531 QObject *parent) const
1532{
1534}
1535
1537{
1539 v4Engine()->throwError(QStringLiteral("Invalid compilation mode %1").arg(mode));
1540 return nullptr;
1541 }
1542
1543 QQmlEngine *engine = qmlEngine();
1544 if (!engine)
1545 return nullptr;
1546
1547 if (moduleUri.isEmpty() || typeName.isEmpty())
1548 return nullptr;
1549
1550 auto [context, effectiveContext] = getContexts();
1551 if (!context)
1552 return nullptr;
1553
1554 QQmlComponent *c = new QQmlComponent(engine, moduleUri, typeName, mode, parent);
1555 if (c->isError() && !parent && moduleUri.endsWith(u".qml")) {
1556 v4Engine()->throwTypeError(
1557 QStringLiteral("Invalid arguments; did you swap mode and parent"));
1558 }
1559 QQmlComponentPrivate::get(c)->creationContext = effectiveContext;
1560 QQmlData::get(c, true)->explicitIndestructibleSet = false;
1561 QQmlData::get(c)->indestructible = false;
1562 return c;
1563}
1564
1565#if QT_CONFIG(translation)
1566QString QtObject::uiLanguage() const
1567{
1568 if (const QJSEngine *e = jsEngine())
1569 return e->uiLanguage();
1570 return QString();
1571}
1572
1573void QtObject::setUiLanguage(const QString &uiLanguage)
1574{
1575 if (QJSEngine *e = jsEngine())
1576 e->setUiLanguage(uiLanguage);
1577}
1578
1579QBindable<QString> QtObject::uiLanguageBindable()
1580{
1581 if (QJSEngine *e = jsEngine())
1582 return QBindable<QString>(&QJSEnginePrivate::get(e)->uiLanguage);
1583 return QBindable<QString>();
1584}
1585#endif
1586
1587#if QT_CONFIG(qml_locale)
1608QLocale QtObject::locale() const
1609{
1610 return QLocale();
1611}
1612
1613QLocale QtObject::locale(const QString &name) const
1614{
1615 return QLocale(name);
1616}
1617#endif
1618
1619void Heap::QQmlBindingFunction::init(const QV4::JavaScriptFunctionObject *bindingFunction)
1620{
1621 Scope scope(bindingFunction->engine());
1622 ScopedContext context(scope, bindingFunction->scope());
1623 JavaScriptFunctionObject::init(context, bindingFunction->function());
1624 this->bindingFunction.set(internalClass->engine, bindingFunction->d());
1625}
1626
1628 const FunctionObject *f, const Value *, const Value *, int)
1629{
1630 // Mark this as a callable object, so that we can perform the binding magic on it.
1631 return f->engine()->throwTypeError(QStringLiteral("Bindings must not be called directly."));
1632}
1633
1635{
1636 QV4::CppStackFrame *frame = engine()->currentStackFrame;
1637 if (frame->v4Function) // synchronous loading:
1638 return QQmlSourceLocation(frame->source(), frame->lineNumber(), 0);
1639 else // async loading:
1640 return bindingFunction()->function->sourceLocation();
1641}
1642
1644
1687{
1689 = QJSValuePrivate::asManagedType<JavaScriptFunctionObject>(&function);
1691 if (!f) {
1693 e->throwError(
1695 "binding(): argument (binding expression) must be a function")));
1696 }
1697
1700}
1701
1703{
1704 m_engine->delayedCallQueue()->addUniquelyAndExecuteLater(m_engine, args);
1705}
1706
1707
1709{
1710 if (!m_platform)
1711 m_platform = new QQmlPlatform(this);
1712 return m_platform;
1713}
1714
1716{
1717 if (!m_application)
1718 // Only allocate an application object once
1719 m_application = QQml_guiProvider()->application(this);
1720
1721 return m_application;
1722}
1723
1725{
1726 return QQml_guiProvider()->inputMethod();
1727}
1728
1730{
1731 return QQml_guiProvider()->styleHints();
1732}
1733
1735{
1736 Object::init();
1737 QV4::Scope scope(internalClass->engine);
1738 QV4::ScopedObject o(scope, this);
1739
1740 o->defineDefaultProperty(QStringLiteral("debug"), QV4::ConsoleObject::method_log);
1741 o->defineDefaultProperty(QStringLiteral("log"), QV4::ConsoleObject::method_log);
1742 o->defineDefaultProperty(QStringLiteral("info"), QV4::ConsoleObject::method_info);
1743 o->defineDefaultProperty(QStringLiteral("warn"), QV4::ConsoleObject::method_warn);
1744 o->defineDefaultProperty(QStringLiteral("error"), QV4::ConsoleObject::method_error);
1745 o->defineDefaultProperty(QStringLiteral("assert"), QV4::ConsoleObject::method_assert);
1746
1747 o->defineDefaultProperty(QStringLiteral("count"), QV4::ConsoleObject::method_count);
1748 o->defineDefaultProperty(QStringLiteral("profile"), QV4::ConsoleObject::method_profile);
1749 o->defineDefaultProperty(QStringLiteral("profileEnd"), QV4::ConsoleObject::method_profileEnd);
1750 o->defineDefaultProperty(QStringLiteral("time"), QV4::ConsoleObject::method_time);
1751 o->defineDefaultProperty(QStringLiteral("timeEnd"), QV4::ConsoleObject::method_timeEnd);
1752 o->defineDefaultProperty(QStringLiteral("trace"), QV4::ConsoleObject::method_trace);
1753 o->defineDefaultProperty(QStringLiteral("exception"), QV4::ConsoleObject::method_exception);
1754}
1755
1756
1763
1765 QString stack;
1766
1767 int i = 0;
1768 for (CppStackFrame *f = engine->currentStackFrame; f && i < 10; f = f->parentFrame(), ++i) {
1769 QString stackFrame;
1770
1771 if (f->isJSTypesFrame() && static_cast<JSTypesStackFrame *>(f)->isTailCalling()) {
1772 stackFrame = QStringLiteral("[elided tail calls]");
1773 } else {
1774 const int line = f->lineNumber();
1775 if (line != f->missingLineNumber()) {
1776 stackFrame = QStringLiteral("%1 (%2:%3)").arg(
1777 f->function(), f->source(), QString::number(qAbs(line)));
1778 } else {
1779 stackFrame = QStringLiteral("%1 (%2)").arg(
1780 f->function(), f->source());
1781 }
1782 }
1783
1784 if (i)
1785 stack += QLatin1Char('\n');
1786 stack += stackFrame;
1787 }
1788 return stack;
1789}
1790
1791static QString serializeArray(Object *array, ExecutionEngine *v4, QSet<QV4::Heap::Object *> &alreadySeen) {
1792 Scope scope(v4);
1793 ScopedValue val(scope);
1795
1796 alreadySeen.insert(array->d());
1797 result += QLatin1Char('[');
1798 const uint length = array->getLength();
1799 for (uint i = 0; i < length; ++i) {
1800 if (i != 0)
1801 result += QLatin1Char(',');
1802 val = array->get(i);
1803 if (val->isManaged() && val->managed()->isArrayLike())
1804 if (!alreadySeen.contains(val->objectValue()->d()))
1805 result += serializeArray(val->objectValue(), v4, alreadySeen);
1806 else
1807 result += QLatin1String("[Circular]");
1808 else
1809 result += val->toQStringNoThrow();
1810 }
1811 result += QLatin1Char(']');
1812 alreadySeen.remove(array->d());
1813 return result;
1814};
1815
1816static ReturnedValue writeToConsole(const FunctionObject *b, const Value *argv, int argc,
1817 ConsoleLogTypes logType, bool printStack = false)
1818{
1819 const QLoggingCategory *loggingCategory = nullptr;
1821 QV4::Scope scope(b);
1822 QV4::ExecutionEngine *v4 = scope.engine;
1823
1824 int start = 0;
1825 if (argc > 0) {
1826 if (const QObjectWrapper* wrapper = argv[0].as<QObjectWrapper>()) {
1827 if (QQmlLoggingCategory* category = qobject_cast<QQmlLoggingCategory*>(wrapper->object())) {
1828 if (category->category())
1829 loggingCategory = category->category();
1830 else
1831 THROW_GENERIC_ERROR("A QmlLoggingCatgory was provided without a valid name");
1832 start = 1;
1833 }
1834 }
1835 }
1836
1837
1838 for (int i = start, ei = argc; i < ei; ++i) {
1839 if (i != start)
1840 result.append(QLatin1Char(' '));
1841
1842 QSet<QV4::Heap::Object *> alreadySeenElements;
1843 if (argv[i].isManaged() && argv[i].managed()->isArrayLike())
1844 result.append(serializeArray(argv[i].objectValue(), v4, alreadySeenElements));
1845 else
1846 result.append(argv[i].toQStringNoThrow());
1847 }
1848
1849 if (printStack)
1850 result += QLatin1Char('\n') + jsStack(v4);
1851
1852 if (!loggingCategory)
1853 loggingCategory = v4->qmlEngine() ? &lcQml() : &lcJs();
1855 const QByteArray baSource = frame ? frame->source().toUtf8() : QByteArray();
1856 const QByteArray baFunction = frame ? frame->function().toUtf8() : QByteArray();
1857 QMessageLogger logger(baSource.constData(), frame ? frame->lineNumber() : 0,
1858 baFunction.constData(), loggingCategory->categoryName());
1859
1860 switch (logType) {
1861 case Log:
1862 if (loggingCategory->isDebugEnabled())
1863 logger.debug("%s", result.toUtf8().constData());
1864 break;
1865 case Info:
1866 if (loggingCategory->isInfoEnabled())
1867 logger.info("%s", result.toUtf8().constData());
1868 break;
1869 case Warn:
1870 if (loggingCategory->isWarningEnabled())
1871 logger.warning("%s", result.toUtf8().constData());
1872 break;
1873 case Error:
1874 if (loggingCategory->isCriticalEnabled())
1875 logger.critical("%s", result.toUtf8().constData());
1876 break;
1877 default:
1878 break;
1879 }
1880
1881 return Encode::undefined();
1882}
1883
1885
1887{
1888 return writeToConsole(b, argv, argc, Error);
1889}
1890
1892{
1893 //console.log
1894 //console.debug
1895 //print
1896 return writeToConsole(b, argv, argc, Log);
1897}
1898
1900{
1901 return writeToConsole(b, argv, argc, Info);
1902}
1903
1905{
1906 QV4::Scope scope(b);
1907 QV4::ExecutionEngine *v4 = scope.engine;
1908
1910 const QByteArray baSource = frame->source().toUtf8();
1911 const QByteArray baFunction = frame->function().toUtf8();
1912 QMessageLogger logger(baSource.constData(), frame->lineNumber(), baFunction.constData());
1913 QQmlProfilerService *service = QQmlDebugConnector::service<QQmlProfilerService>();
1914 if (!service) {
1915 logger.warning("Cannot start profiling because debug service is disabled. Start with -qmljsdebugger=port:XXXXX.");
1916 } else {
1917 service->startProfiling(v4->jsEngine());
1918 logger.debug("Profiling started.");
1919 }
1920
1921 return QV4::Encode::undefined();
1922}
1923
1925{
1926 QV4::Scope scope(b);
1927 QV4::ExecutionEngine *v4 = scope.engine;
1928
1930 const QByteArray baSource = frame->source().toUtf8();
1931 const QByteArray baFunction = frame->function().toUtf8();
1932 QMessageLogger logger(baSource.constData(), frame->lineNumber(), baFunction.constData());
1933
1934 QQmlProfilerService *service = QQmlDebugConnector::service<QQmlProfilerService>();
1935 if (!service) {
1936 logger.warning("Ignoring console.profileEnd(): the debug service is disabled.");
1937 } else {
1938 service->stopProfiling(v4->jsEngine());
1939 logger.debug("Profiling ended.");
1940 }
1941
1942 return QV4::Encode::undefined();
1943}
1944
1946{
1947 QV4::Scope scope(b);
1948 if (argc != 1)
1949 THROW_GENERIC_ERROR("console.time(): Invalid arguments");
1950
1951 QString name = argv[0].toQStringNoThrow();
1952 scope.engine->startTimer(name);
1953 return QV4::Encode::undefined();
1954}
1955
1957{
1958 QV4::Scope scope(b);
1959 if (argc != 1)
1960 THROW_GENERIC_ERROR("console.timeEnd(): Invalid arguments");
1961
1962 QString name = argv[0].toQStringNoThrow();
1963 bool wasRunning;
1964 qint64 elapsed = scope.engine->stopTimer(name, &wasRunning);
1965 if (wasRunning) {
1966 qDebug("%s: %llims", qPrintable(name), elapsed);
1967 }
1968 return QV4::Encode::undefined();
1969}
1970
1972{
1973 // first argument: name to print. Ignore any additional arguments
1974 QString name;
1975 if (argc > 0)
1976 name = argv[0].toQStringNoThrow();
1977
1978 Scope scope(b);
1979 QV4::ExecutionEngine *v4 = scope.engine;
1980
1982
1983 QString scriptName = frame->source();
1984
1985 int value = v4->consoleCountHelper(scriptName, frame->lineNumber(), 0);
1987
1988 QMessageLogger(qPrintable(scriptName), frame->lineNumber(),
1989 qPrintable(frame->function()))
1990 .debug("%s", qPrintable(message));
1991
1992 return QV4::Encode::undefined();
1993}
1994
1996{
1997 QV4::Scope scope(b);
1998 if (argc != 0)
1999 THROW_GENERIC_ERROR("console.trace(): Invalid arguments");
2000
2001 QV4::ExecutionEngine *v4 = scope.engine;
2002
2003 QString stack = jsStack(v4);
2004
2006 QMessageLogger(frame->source().toUtf8().constData(), frame->lineNumber(),
2007 frame->function().toUtf8().constData())
2008 .debug(v4->qmlEngine() ? lcQml : lcJs, "%s", qPrintable(stack));
2009
2010 return QV4::Encode::undefined();
2011}
2012
2014{
2015 return writeToConsole(b, argv, argc, Warn);
2016}
2017
2019{
2020 QV4::Scope scope(b);
2021 if (argc == 0)
2022 THROW_GENERIC_ERROR("console.assert(): Missing argument");
2023
2024 QV4::ExecutionEngine *v4 = scope.engine;
2025
2026 if (!argv[0].toBoolean()) {
2028 for (int i = 1, ei = argc; i < ei; ++i) {
2029 if (i != 1)
2030 message.append(QLatin1Char(' '));
2031
2032 message.append(argv[i].toQStringNoThrow());
2033 }
2034
2035 QString stack = jsStack(v4);
2036
2038 QMessageLogger(frame->source().toUtf8().constData(), frame->lineNumber(),
2039 frame->function().toUtf8().constData())
2040 .critical("%s\n%s",qPrintable(message), qPrintable(stack));
2041
2042 }
2043 return QV4::Encode::undefined();
2044}
2045
2047{
2048 QV4::Scope scope(b);
2049 if (argc == 0)
2050 THROW_GENERIC_ERROR("console.exception(): Missing argument");
2051
2052 return writeToConsole(b, argv, argc, Error, true);
2053}
2054
2055void QV4::GlobalExtensions::init(Object *globalObject, QJSEngine::Extensions extensions)
2056{
2057 ExecutionEngine *v4 = globalObject->engine();
2058 Scope scope(v4);
2059
2060 if (extensions.testFlag(QJSEngine::TranslationExtension)) {
2061 #if QT_CONFIG(translation)
2062 globalObject->defineDefaultProperty(QStringLiteral("qsTranslate"), QV4::GlobalExtensions::method_qsTranslate);
2063 globalObject->defineDefaultProperty(QStringLiteral("QT_TRANSLATE_NOOP"), QV4::GlobalExtensions::method_qsTranslateNoOp);
2064 globalObject->defineDefaultProperty(QStringLiteral("qsTr"), QV4::GlobalExtensions::method_qsTr);
2065 globalObject->defineDefaultProperty(QStringLiteral("QT_TR_NOOP"), QV4::GlobalExtensions::method_qsTrNoOp);
2066 globalObject->defineDefaultProperty(QStringLiteral("qsTrId"), QV4::GlobalExtensions::method_qsTrId);
2067 globalObject->defineDefaultProperty(QStringLiteral("QT_TRID_NOOP"), QV4::GlobalExtensions::method_qsTrIdNoOp);
2068
2069 // Initialize the Qt global object for the uiLanguage property
2070 ScopedString qtName(scope, v4->newString(QStringLiteral("Qt")));
2071 ScopedObject qt(scope, globalObject->get(qtName));
2072 if (!qt)
2073 v4->createQtObject();
2074
2075 // string prototype extension
2077 #endif
2078 }
2079
2080 if (extensions.testFlag(QJSEngine::ConsoleExtension)) {
2081 globalObject->defineDefaultProperty(QStringLiteral("print"), QV4::ConsoleObject::method_log);
2082
2083
2085 globalObject->defineDefaultProperty(QStringLiteral("console"), console);
2086 }
2087
2088 if (extensions.testFlag(QJSEngine::GarbageCollectionExtension)) {
2089 globalObject->defineDefaultProperty(QStringLiteral("gc"), QV4::GlobalExtensions::method_gc);
2090 }
2091}
2092
2093
2094#if QT_CONFIG(translation)
2112ReturnedValue GlobalExtensions::method_qsTranslate(const FunctionObject *b, const Value *, const Value *argv, int argc)
2113{
2114 QV4::Scope scope(b);
2115 if (argc < 2)
2116 THROW_GENERIC_ERROR("qsTranslate() requires at least two arguments");
2117 if (!argv[0].isString())
2118 THROW_GENERIC_ERROR("qsTranslate(): first argument (context) must be a string");
2119 if (!argv[1].isString())
2120 THROW_GENERIC_ERROR("qsTranslate(): second argument (sourceText) must be a string");
2121 if ((argc > 2) && !argv[2].isString())
2122 THROW_GENERIC_ERROR("qsTranslate(): third argument (disambiguation) must be a string");
2123
2124 QString context = argv[0].toQStringNoThrow();
2125 QString text = argv[1].toQStringNoThrow();
2126 QString comment;
2127 if (argc > 2) comment = argv[2].toQStringNoThrow();
2128
2129 int i = 3;
2130 if (argc > i && argv[i].isString()) {
2131 qWarning("qsTranslate(): specifying the encoding as fourth argument is deprecated");
2132 ++i;
2133 }
2134
2135 int n = -1;
2136 if (argc > i)
2137 n = argv[i].toInt32();
2138
2139 if (QQmlEnginePrivate *ep = (scope.engine->qmlEngine() ? QQmlEnginePrivate::get(scope.engine->qmlEngine()) : nullptr))
2140 if (ep->propertyCapture)
2141 ep->propertyCapture->captureTranslation();
2142
2143 QString result = QCoreApplication::translate(context.toUtf8().constData(),
2144 text.toUtf8().constData(),
2145 comment.toUtf8().constData(),
2146 n);
2147
2148 return Encode(scope.engine->newString(result));
2149}
2150
2173ReturnedValue GlobalExtensions::method_qsTranslateNoOp(const FunctionObject *b, const Value *, const Value *argv, int argc)
2174{
2175 QV4::Scope scope(b);
2176 if (argc < 2)
2177 return QV4::Encode::undefined();
2178 else
2179 return argv[1].asReturnedValue();
2180}
2181
2182QString GlobalExtensions::currentTranslationContext(ExecutionEngine *engine)
2183{
2185 CppStackFrame *frame = engine->currentStackFrame;
2186
2187 // The first non-empty source URL in the call stack determines the translation context.
2188 while (frame && context.isEmpty()) {
2189 if (ExecutableCompilationUnit *unit = frame->v4Function->executableCompilationUnit()) {
2190 auto translationContextIndex = unit->unitData()->translationContextIndex();
2191 if (translationContextIndex)
2192 context = unit->stringAt(*translationContextIndex);
2193 if (!context.isEmpty())
2194 break;
2195 QString fileName = unit->fileName();
2196 QUrl url(unit->fileName());
2197 if (url.isValid() && url.isRelative()) {
2198 context = url.fileName();
2199 } else {
2201 if (context.isEmpty() && fileName.startsWith(QLatin1String(":/")))
2202 context = fileName;
2203 }
2205 }
2206 frame = frame->parentFrame();
2207 }
2208
2209 if (context.isEmpty()) {
2210 if (QQmlRefPointer<QQmlContextData> ctxt = engine->callingQmlContext()) {
2211 QString path = ctxt->urlString();
2212 int lastSlash = path.lastIndexOf(QLatin1Char('/'));
2213 int lastDot = path.lastIndexOf(QLatin1Char('.'));
2214 int length = lastDot - (lastSlash + 1);
2215 context = (lastSlash > -1) ? path.mid(lastSlash + 1, (length > -1) ? length : -1) : QString();
2216 }
2217 }
2218
2219 return context;
2220}
2221
2239ReturnedValue GlobalExtensions::method_qsTr(const FunctionObject *b, const Value *, const Value *argv, int argc)
2240{
2241 QV4::Scope scope(b);
2242 if (argc < 1)
2243 THROW_GENERIC_ERROR("qsTr() requires at least one argument");
2244 if (!argv[0].isString())
2245 THROW_GENERIC_ERROR("qsTr(): first argument (sourceText) must be a string");
2246 if ((argc > 1) && !argv[1].isString())
2247 THROW_GENERIC_ERROR("qsTr(): second argument (disambiguation) must be a string");
2248 if ((argc > 2) && !argv[2].isNumber())
2249 THROW_GENERIC_ERROR("qsTr(): third argument (n) must be a number");
2250
2251 const QString context = currentTranslationContext(scope.engine);
2252 const QString text = argv[0].toQStringNoThrow();
2253 const QString comment = argc > 1 ? argv[1].toQStringNoThrow() : QString();
2254 const int n = argc > 2 ? argv[2].toInt32() : -1;
2255
2256 if (QQmlEnginePrivate *ep = (scope.engine->qmlEngine() ? QQmlEnginePrivate::get(scope.engine->qmlEngine()) : nullptr))
2257 if (ep->propertyCapture)
2258 ep->propertyCapture->captureTranslation();
2259
2261 comment.toUtf8().constData(), n);
2262
2263 return Encode(scope.engine->newString(result));
2264}
2265
2288ReturnedValue GlobalExtensions::method_qsTrNoOp(const FunctionObject *, const Value *, const Value *argv, int argc)
2289{
2290 if (argc < 1)
2291 return QV4::Encode::undefined();
2292 else
2293 return argv[0].asReturnedValue();
2294}
2295
2326ReturnedValue GlobalExtensions::method_qsTrId(const FunctionObject *b, const Value *, const Value *argv, int argc)
2327{
2328 QV4::Scope scope(b);
2329 if (argc < 1)
2330 THROW_GENERIC_ERROR("qsTrId() requires at least one argument");
2331 if (!argv[0].isString())
2332 THROW_TYPE_ERROR_WITH_MESSAGE("qsTrId(): first argument (id) must be a string");
2333 if (argc > 1 && !argv[1].isNumber())
2334 THROW_TYPE_ERROR_WITH_MESSAGE("qsTrId(): second argument (n) must be a number");
2335
2336 int n = -1;
2337 if (argc > 1)
2338 n = argv[1].toInt32();
2339
2340 if (QQmlEnginePrivate *ep = (scope.engine->qmlEngine() ? QQmlEnginePrivate::get(scope.engine->qmlEngine()) : nullptr))
2341 if (ep->propertyCapture)
2342 ep->propertyCapture->captureTranslation();
2343
2344 return Encode(scope.engine->newString(qtTrId(argv[0].toQStringNoThrow().toUtf8().constData(), n)));
2345}
2346
2363ReturnedValue GlobalExtensions::method_qsTrIdNoOp(const FunctionObject *, const Value *, const Value *argv, int argc)
2364{
2365 if (argc < 1)
2366 return QV4::Encode::undefined();
2367 else
2368 return argv[0].asReturnedValue();
2369}
2370#endif // translation
2371
2382{
2383 auto mm = b->engine()->memoryManager;
2384 mm->runFullGC();
2385
2386 return QV4::Encode::undefined();
2387}
2388
2389ReturnedValue GlobalExtensions::method_string_arg(const FunctionObject *b, const Value *thisObject, const Value *argv, int argc)
2390{
2391 QV4::Scope scope(b);
2392 if (argc != 1)
2393 THROW_GENERIC_ERROR("String.arg(): Invalid arguments");
2394
2395 QString value = thisObject->toQString();
2396
2397 QV4::ScopedValue arg(scope, argv[0]);
2398 if (arg->isInteger())
2399 RETURN_RESULT(scope.engine->newString(value.arg(arg->integerValue())));
2400 else if (arg->isDouble())
2401 RETURN_RESULT(scope.engine->newString(value.arg(arg->doubleValue())));
2402 else if (arg->isBoolean())
2403 RETURN_RESULT(scope.engine->newString(value.arg(arg->booleanValue())));
2404
2405 RETURN_RESULT(scope.engine->newString(value.arg(arg->toQString())));
2406}
2407
2430
2431#include "moc_qqmlbuiltinfunctions_p.cpp"
Definition main.cpp:8
\inmodule QtCore
Definition qbytearray.h:57
const char * constData() const noexcept
Returns a pointer to the const data stored in the byte array.
Definition qbytearray.h:124
static QByteArray fromBase64(const QByteArray &base64, Base64Options options=Base64Encoding)
static QString translate(const char *context, const char *key, const char *disambiguation=nullptr, int n=-1)
\threadsafe
static QByteArray hash(QByteArrayView data, Algorithm method)
Returns the hash of data using method.
\inmodule QtCore\reentrant
Definition qdatetime.h:283
QTime time() const
Returns the time part of the datetime.
QDateTime toLocalTime() const
Returns a copy of this datetime converted to local time.
bool isValid() const
Returns true if this datetime represents a definite moment, otherwise false.
QDate date() const
Returns the date part of the datetime.
\inmodule QtCore \reentrant
Definition qdatetime.h:29
constexpr bool isValid() const
Returns true if this date is valid; otherwise returns false.
Definition qdatetime.h:71
QString completeBaseName() const
Returns the complete base name of the file without the path.
static QJSEnginePrivate * get(QJSEngine *e)
Definition qjsengine_p.h:38
The QJSEngine class provides an environment for evaluating JavaScript code.
Definition qjsengine.h:26
QV4::ExecutionEngine * handle() const
Definition qjsengine.h:298
void throwError(const QString &message)
Throws a run-time error (exception) with the given message.
QJSValue newArray(uint length=0)
Creates a JavaScript object of class Array with the given length.
QJSValue toScriptValue(const T &value)
Creates a QJSValue with the given value.
Definition qjsengine.h:58
@ ConsoleExtension
Definition qjsengine.h:287
@ TranslationExtension
Definition qjsengine.h:286
@ GarbageCollectionExtension
Definition qjsengine.h:288
static QJSValue fromReturnedValue(QV4::ReturnedValue d)
Definition qjsvalue_p.h:197
The QJSValue class acts as a container for Qt/JavaScript data types.
Definition qjsvalue.h:31
\inmodule QtCore
\inmodule QtCore
Definition qlogging.h:72
void void Q_DECL_COLD_FUNCTION void warning(const char *msg,...) const Q_ATTRIBUTE_FORMAT_PRINTF(2
Logs a warning message specified with format msg.
Definition qlogging.cpp:625
void void Q_DECL_COLD_FUNCTION void Q_DECL_COLD_FUNCTION void critical(const char *msg,...) const Q_ATTRIBUTE_FORMAT_PRINTF(2
Logs a critical message specified with format msg.
Definition qlogging.cpp:727
void debug(const char *msg,...) const Q_ATTRIBUTE_FORMAT_PRINTF(2
Logs a debug message specified with format msg.
Definition qlogging.cpp:389
\inmodule QtCore
Definition qmetatype.h:341
\inmodule QtCore
Definition qobject.h:103
QObject * parent() const
Returns a pointer to the parent object.
Definition qobject.h:346
\inmodule QtCore\reentrant
Definition qpoint.h:217
virtual QVariant lighter(const QVariant &, qreal)
virtual QVariant tint(const QVariant &, const QVariant &)
virtual QVariant fromRgbF(double, double, double, double)
virtual QVariant fromHsvF(double, double, double, double)
virtual QVariant fromHslF(double, double, double, double)
virtual QVariant darker(const QVariant &, qreal)
virtual QVariant alpha(const QVariant &, qreal)
static QQmlComponentPrivate * get(QQmlComponent *c)
The QQmlComponent class encapsulates a QML component definition.
CompilationMode
Specifies whether the QQmlComponent should load the component immediately, or asynchonously.
static QQmlRefPointer< QQmlContextData > get(QQmlContext *context)
The QQmlContext class defines a context within a QML engine.
Definition qqmlcontext.h:25
bool isValid() const
Returns whether the context is valid.
static QQmlData * get(QObjectPrivate *priv, bool create)
Definition qqmldata_p.h:199
static QQmlEnginePrivate * get(QQmlEngine *e)
The QQmlEngine class provides an environment for instantiating QML components.
Definition qqmlengine.h:57
The QQmlError class encapsulates a QML error.
Definition qqmlerror.h:18
static QString urlToLocalFileOrQrc(const QString &)
If url is a local file returns a path suitable for passing to \l{QFile}.
Definition qqmlfile.cpp:742
virtual bool openUrlExternally(const QUrl &)
virtual QStringList fontFamilies()
virtual QQmlApplication * application(QObject *parent)
virtual QObject * styleHints()
virtual QObject * inputMethod()
static QList< QQmlPrivate::AutoParentFunction > parentFunctions()
static QVariant createValueType(const QJSValue &, QMetaType)
\inmodule QtCore\reentrant
Definition qrect.h:484
\inmodule QtCore
Definition qsize.h:208
\inmodule QtCore
\macro QT_RESTRICTED_CAST_FROM_ASCII
Definition qstring.h:129
qsizetype lastIndexOf(QChar c, Qt::CaseSensitivity cs=Qt::CaseSensitive) const noexcept
Definition qstring.h:296
bool isEmpty() const noexcept
Returns true if the string has no characters; otherwise returns false.
Definition qstring.h:192
static QString fromUtf8(QByteArrayView utf8)
This is an overloaded member function, provided for convenience. It differs from the above function o...
Definition qstring.cpp:6018
bool endsWith(const QString &s, Qt::CaseSensitivity cs=Qt::CaseSensitive) const
Returns true if the string ends with s; otherwise returns false.
Definition qstring.cpp:5506
static QString number(int, int base=10)
This is an overloaded member function, provided for convenience. It differs from the above function o...
Definition qstring.cpp:8084
QByteArray toUtf8() const &
Definition qstring.h:634
\inmodule QtCore \reentrant
Definition qdatetime.h:215
bool isValid() const
Returns true if the time is valid; otherwise returns false.
\inmodule QtCore
Definition qurl.h:94
QString fileName(ComponentFormattingOptions options=FullyDecoded) const
Definition qurl.cpp:2497
bool isRelative() const
Returns true if the URL is relative; otherwise returns false.
Definition qurl.cpp:2800
bool isValid() const
Returns true if the URL is non-empty and valid; otherwise returns false.
Definition qurl.cpp:1882
bool isEmpty() const
Returns true if the URL has no data; otherwise returns false.
Definition qurl.cpp:1896
static QJSValue method_include(QV4::ExecutionEngine *engine, const QUrl &url, const QJSValue &callbackFunction)
ObjectType::Data * allocate(Args &&... args)
Definition qv4mm_p.h:298
\inmodule QtCore
Definition qvariant.h:65
bool isValid() const
Returns true if the storage type of this variant is not QMetaType::UnknownType; otherwise returns fal...
Definition qvariant.h:714
static auto fromValue(T &&value) noexcept(std::is_nothrow_copy_constructible_v< T > &&Private::CanUseInternalSpace< T >) -> std::enable_if_t< std::conjunction_v< std::is_copy_constructible< T >, std::is_destructible< T > >, QVariant >
Definition qvariant.h:536
Q_INVOKABLE QVariant darker(const QJSValue &color, double factor=2.0) const
\qmlmethod color Qt::darker(color baseColor, real factor)
QObject * inputMethod
Q_INVOKABLE bool colorEqual(const QVariant &lhs, const QVariant &rhs) const
\qmlmethod color Qt::colorEqual(color lhs, string rhs)
Q_INVOKABLE QString formatDate(QDate date, const QString &format) const
Q_INVOKABLE QVariant font(const QJSValue &fontSpecifier) const
\qmlmethod font Qt::font(object fontSpecifier)
Q_INVOKABLE bool isQtObject(const QJSValue &value) const
\qmlmethod bool Qt::isQtObject(object)
Q_INVOKABLE QString formatTime(QTime time, const QString &format) const
Q_INVOKABLE QUrl url(const QUrl &url) const
\qmlmethod url Qt::url(url url)
Q_INVOKABLE QVariant hsla(double h, double s, double l, double a=1) const
\qmlmethod color Qt::hsla(real hue, real saturation, real lightness, real alpha)
Q_INVOKABLE QVariant hsva(double h, double s, double v, double a=1) const
Q_INVOKABLE void quit() const
\qmlmethod Qt::quit()
Q_INVOKABLE void callLater(QQmlV4FunctionPtr args)
Q_INVOKABLE void exit(int retCode) const
\qmlmethod Qt::exit(int retCode)
QQmlApplication * application
Q_INVOKABLE QSizeF size(double width, double height) const
\qmlmethod size Qt::size(real width, real height)
Q_INVOKABLE QVariant quaternion(double scalar, double x, double y, double z) const
\qmlmethod quaternion Qt::quaternion(real scalar, real x, real y, real z)
Q_INVOKABLE QVariant matrix4x4() const
\qmlmethod matrix4x4 Qt::matrix4x4()
Q_INVOKABLE QVariant lighter(const QJSValue &color, double factor=1.5) const
\qmlmethod color Qt::lighter(color baseColor, real factor)
static QtObject * create(QQmlEngine *, QJSEngine *jsEngine)
Q_INVOKABLE QVariant vector3d(double x, double y, double z) const
\qmlmethod vector3d Qt::vector3d(real x, real y, real z)
Q_INVOKABLE QQmlComponent * createComponent(const QUrl &url, QObject *parent) const
\qmlmethod Component Qt::createComponent(url url, enumeration mode, QtObject parent)
Q_INVOKABLE QVariant tint(const QJSValue &baseColor, const QJSValue &tintColor) const
\qmlmethod color Qt::tint(color baseColor, color tintColor)
Q_INVOKABLE QVariant rgba(double r, double g, double b, double a=1) const
\qmlmethod color Qt::rgba(real red, real green, real blue, real alpha)
QQmlPlatform * platform
Q_INVOKABLE QString md5(const QString &data) const
\qmlmethod string Qt::md5(data) Returns a hex string of the md5 hash of data.
Q_INVOKABLE QString btoa(const QString &data) const
\qmlmethod string Qt::btoa(data) Binary to ASCII - this function returns a base64 encoding of data.
Q_INVOKABLE QRectF rect(double x, double y, double width, double height) const
\qmlmethod rect Qt::rect(real x, real y, real width, real height)
Q_INVOKABLE QVariant alpha(const QJSValue &baseColor, double value) const
\qmlmethod color Qt::alpha(color baseColor, real value)
Q_INVOKABLE bool openUrlExternally(const QUrl &url) const
\qmlmethod bool Qt::openUrlExternally(url target)
Q_INVOKABLE QUrl resolvedUrl(const QUrl &url) const
\qmlmethod url Qt::resolvedUrl(url url)
Q_INVOKABLE QVariant color(const QString &name) const
\qmlmethod color Qt::color(string name)
Q_INVOKABLE QJSValue binding(const QJSValue &function) const
\qmlmethod Qt::binding(function)
Q_INVOKABLE QVariant vector4d(double x, double y, double z, double w) const
\qmlmethod vector4d Qt::vector4d(real x, real y, real z, real w)
Q_INVOKABLE QStringList fontFamilies() const
\qmlmethod list<string> Qt::fontFamilies()
Q_INVOKABLE QJSValue include(const QString &url, const QJSValue &callback=QJSValue()) const
Q_INVOKABLE QString atob(const QString &data) const
\qmlmethod string Qt::atob(data) ASCII to binary - this function decodes the base64 encoded data stri...
Q_INVOKABLE QObject * createQmlObject(const QString &qml, QObject *parent, const QUrl &url=QUrl(QStringLiteral("inline"))) const
\qmlmethod object Qt::createQmlObject(string qml, object parent, string filepath)
Q_INVOKABLE QString formatDateTime(const QDateTime &date, const QString &format) const
Q_INVOKABLE QPointF point(double x, double y) const
\qmlmethod point Qt::point(real x, real y)
Q_INVOKABLE QVariant vector2d(double x, double y) const
\qmlmethod vector2d Qt::vector2d(real x, real y)
const QLoggingCategory & category()
[1]
QString text
QDate date
[1]
QJSManagedValue managed(std::move(val), &engine)
Q_QML_EXPORT QV4::ReturnedValue locale(QV4::ExecutionEngine *engine, const QString &localeName)
Provides locale specific properties and formatted data.
Q_QML_EXPORT QVariant colorFromString(const QString &, bool *ok=nullptr)
Combined button and popup list for selecting options.
int toUtf8(char16_t u, OutputPtr &dst, InputPtr &src, InputPtr end)
quint64 ReturnedValue
Scoped< String > ScopedString
Scoped< ExecutionContext > ScopedContext
DateFormat
@ RFC2822Date
@ ISODate
@ ISODateWithMs
@ TextDate
static void * context
DBusConnection const char DBusError * error
typedef QByteArray(EGLAPIENTRYP PFNQGSGETDISPLAYSPROC)()
EGLOutputLayerEXT EGLint EGLAttrib value
[5]
static QV4::ExecutionEngine * v4Engine(QV4::Value *d)
#define qDebug
[1]
Definition qlogging.h:164
#define qWarning
Definition qlogging.h:166
#define Q_LOGGING_CATEGORY(name,...)
#define qCWarning(category,...)
const char * typeName
constexpr const T & qBound(const T &min, const T &val, const T &max)
Definition qminmax.h:44
static bool isNumber(char s)
constexpr T qAbs(const T &t)
Definition qnumeric.h:328
GLint GLfloat GLfloat GLfloat v2
GLboolean GLboolean GLboolean b
GLsizei const GLfloat * v
[13]
GLuint GLfloat GLfloat GLfloat GLfloat GLfloat z
GLint GLint GLint GLint GLint x
[0]
GLenum mode
GLfloat GLfloat GLfloat w
[0]
GLint GLsizei GLsizei height
GLboolean GLboolean GLboolean GLboolean a
[7]
GLboolean r
[2]
GLenum GLuint GLenum GLsizei length
GLint GLsizei GLsizei GLenum GLenum GLsizei void * data
GLfloat GLfloat f
GLint GLsizei width
GLuint color
[2]
GLenum type
GLint GLfloat GLfloat v1
GLuint GLsizei const GLchar * message
GLuint start
GLboolean GLboolean g
GLuint name
GLfloat n
GLint GLsizei GLsizei GLenum format
GLint y
GLfloat GLfloat GLfloat GLfloat h
void ** params
GLhandleARB obj
[2]
GLdouble s
[6]
Definition qopenglext.h:235
const GLubyte * c
GLuint GLfloat * val
GLenum array
GLsizei const GLchar *const * path
GLuint64EXT * result
[6]
static qreal component(const QPointF &point, unsigned int i)
#define THROW_TYPE_ERROR_WITH_MESSAGE(msg)
static QTime dateTimeToTime(const QDateTime &dateTime)
static QString serializeArray(Object *array, ExecutionEngine *v4, QSet< QV4::Heap::Object * > &alreadySeen)
static QVariant constructFromJSValue(QJSEngine *e, QMetaType type, T... parameters)
void addParameters< double >(QJSEngine *, QJSValue &result, int i, double parameter)
static std::optional< QDate > dateFromString(const QString &string, QV4::ExecutionEngine *engine)
\qmlmethod string Qt::formatDate(datetime date, variant format, variant localeFormatOption)
static ReturnedValue writeToConsole(const FunctionObject *b, const Value *argv, int argc, ConsoleLogTypes logType, bool printStack=false)
void addParameters(QJSEngine *e, QJSValue &result, int i, T parameter)
static QString jsStack(QV4::ExecutionEngine *engine)
static std::optional< QTime > timeFromString(const QString &string, QV4::ExecutionEngine *engine)
\qmlmethod string Qt::formatTime(datetime time, variant format, variant localeFormatOption)
static std::optional< QDateTime > dateTimeFromString(const QString &string, QV4::ExecutionEngine *engine)
\qmlmethod string Qt::formatDateTime(datetime dateTime, variant format, variant localeFormatOption)
static QVariant colorVariantFromJSValue(const QJSValue &color, bool *ok)
Q_AUTOTEST_EXPORT QQmlGuiProvider * QQml_guiProvider(void)
Q_AUTOTEST_EXPORT QQmlColorProvider * QQml_colorProvider(void)
#define Q_ASSERT(cond)
Definition qrandom.cpp:47
SSL_CTX int void * arg
#define qPrintable(string)
Definition qstring.h:1531
QLatin1StringView QLatin1String
Definition qstringfwd.h:31
#define QStringLiteral(str)
#define v1
static double elapsed(qint64 after, qint64 before)
Q_CORE_EXPORT QString qtTrId(const char *id, int n=-1)
unsigned int uint
Definition qtypes.h:34
long long qint64
Definition qtypes.h:60
#define THROW_GENERIC_ERROR(str)
#define RETURN_RESULT(r)
#define DEFINE_OBJECT_VTABLE(classname)
if(qFloatDistance(a, b)<(1<< 7))
[0]
QUrl url("example.com")
[constructor-url-reference]
QObject::connect nullptr
QVariant variant
[1]
QDateTime dateTime
[12]
QFrame frame
[0]
view create()
engine globalObject().setProperty("myObject"
QJSValueList args
QJSEngine engine
[0]
\inmodule QtCore \reentrant
Definition qchar.h:18
static ReturnedValue method_profile(const FunctionObject *b, const Value *thisObject, const Value *argv, int argc)
static ReturnedValue method_warn(const FunctionObject *b, const Value *thisObject, const Value *argv, int argc)
static ReturnedValue method_log(const FunctionObject *b, const Value *thisObject, const Value *argv, int argc)
static ReturnedValue method_count(const FunctionObject *b, const Value *thisObject, const Value *argv, int argc)
static ReturnedValue method_info(const FunctionObject *b, const Value *thisObject, const Value *argv, int argc)
static ReturnedValue method_timeEnd(const FunctionObject *b, const Value *thisObject, const Value *argv, int argc)
static ReturnedValue method_exception(const FunctionObject *b, const Value *thisObject, const Value *argv, int argc)
static ReturnedValue method_assert(const FunctionObject *b, const Value *thisObject, const Value *argv, int argc)
static ReturnedValue method_time(const FunctionObject *b, const Value *thisObject, const Value *argv, int argc)
static ReturnedValue method_error(const FunctionObject *b, const Value *thisObject, const Value *argv, int argc)
static ReturnedValue method_profileEnd(const FunctionObject *b, const Value *thisObject, const Value *argv, int argc)
static ReturnedValue method_trace(const FunctionObject *b, const Value *thisObject, const Value *argv, int argc)
static QDate dateTimeToDate(const QDateTime &dateTime)
static QDateTime stringToDateTime(const QString &string, ExecutionEngine *engine)
static constexpr ReturnedValue undefined()
MemoryManager * memoryManager
CppStackFrame * currentStackFrame
QQmlRefPointer< QQmlContextData > callingQmlContext() const
Object * stringPrototype() const
ReturnedValue throwError(const Value &value)
Heap::Object * newObject()
int consoleCountHelper(const QString &file, quint16 line, quint16 column)
Heap::String * newString(char16_t c)
QJSEngine * jsEngine() const
void startTimer(const QString &timerName)
QQmlEngine * qmlEngine() const
qint64 stopTimer(const QString &timerName, bool *wasRunning)
Heap::ArrayObject * newArrayObject(int count=0)
ReturnedValue throwTypeError()
Heap::Object * newErrorObject(const Value &value)
static void init(Object *globalObject, QJSEngine::Extensions extensions)
static ReturnedValue method_gc(const FunctionObject *b, const Value *thisObject, const Value *argv, int argc)
\qmlmethod void Qt::gc()
static ReturnedValue method_string_arg(const FunctionObject *b, const Value *thisObject, const Value *argv, int argc)
V4_NEEDS_DESTROY Heap::ExecutionContext * scope() const
ExecutionEngine * engine() const
void defineDefaultProperty(StringOrSymbol *name, const Value &value, PropertyAttributes attributes=Attr_Data|Attr_NotEnumerable)
bool set(StringOrSymbol *name, const Value &v, ThrowOnFailure shouldThrow)
QObject * object() const
QQmlSourceLocation currentLocation() const
Heap::JavaScriptFunctionObject * bindingFunction() const
static ReturnedValue virtualCall(const FunctionObject *f, const Value *thisObject, const Value *argv, int argc)
ExecutionEngine * engine
constexpr ReturnedValue asReturnedValue() const
static constexpr Value fromInt32(int i)
Definition qv4value_p.h:187
int toInt32() const
Definition qv4value_p.h:353
bool toBoolean() const
Definition qv4value_p.h:97
QString toQString() const
Definition qv4value.cpp:158
QString toQStringNoThrow() const
Definition qv4value.cpp:122
void wrapper()