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 <private/qqmlcomponent_p.h>
7#include <private/qqmldebugconnector_p.h>
8#include <private/qqmldebugserviceinterfaces_p.h>
9#include <private/qqmldelayedcallqueue_p.h>
10#include <private/qqmlengine_p.h>
11#include <private/qqmlloggingcategorybase_p.h>
12#include <private/qqmlplatform_p.h>
13#include <private/qqmlstringconverters_p.h>
14
15#include <private/qv4dateobject_p.h>
16#include <private/qv4engine_p.h>
17#include <private/qv4functionobject_p.h>
18#include <private/qv4include_p.h>
19#include <private/qv4mm_p.h>
20#include <private/qv4qobjectwrapper_p.h>
21#include <private/qv4stackframe_p.h>
22
23#include <QtQml/qqmlfile.h>
24
25#include <QtCore/qcoreapplication.h>
26#include <QtCore/qcryptographichash.h>
27#include <QtCore/qdatetime.h>
28#include <QtCore/qfileinfo.h>
29#include <QtCore/qloggingcategory.h>
30#include <QtCore/qpoint.h>
31#include <QtCore/qrect.h>
32#include <QtCore/qsize.h>
33#include <QtCore/qstring.h>
34#include <QtCore/qurl.h>
35
37
38Q_STATIC_LOGGING_CATEGORY(lcRootProperties, "qt.qml.rootObjectProperties");
39Q_LOGGING_CATEGORY(lcQml, "qml");
41
42using namespace QV4;
43
44#define THROW_TYPE_ERROR_WITH_MESSAGE(msg) \
45 do { \
46 return scope.engine->throwTypeError(QString::fromUtf8(msg)); \
47 } while (false)
48
53
262// Qt.include() is implemented in qv4include.cpp
263
264QtObject::QtObject(ExecutionEngine *engine)
265 : m_engine(engine)
266{
267}
268
269QtObject::Contexts QtObject::getContexts() const
270{
271 QQmlEngine *engine = qmlEngine();
272 if (!engine)
273 return {};
274
275 QQmlRefPointer<QQmlContextData> context = v4Engine()->callingQmlContext();
276 if (!context)
278
279 Q_ASSERT(context);
280 QQmlRefPointer<QQmlContextData> effectiveContext
281 = context->isPragmaLibraryContext() ? nullptr : context;
282 return {context, effectiveContext};
283}
284
286{
287 QV4::ExecutionEngine *v4 = jsEngine->handle();
288 QV4::Scope scope(v4);
290 ScopedString qtName(scope, v4->newString(QStringLiteral("Qt")));
291 QV4::ScopedValue result(scope, globalObject->get(qtName->toPropertyKey()));
292 return qobject_cast<QtObject *>(result->as<QV4::QObjectWrapper>()->object());
293}
294
295QJSValue QtObject::include(const QString &url, const QJSValue &callback) const
296{
297 return QV4Include::method_include(v4Engine(), v4Engine()->resolvedUrl(url), callback);
298}
299
300
308{
309 return qjsvalue_cast<QObject *>(value) != nullptr;
310}
311
319{
320 bool ok = false;
322 if (ok)
323 return v;
324
325 v4Engine()->throwError(QStringLiteral("\"%1\" is not a valid color name").arg(name));
326 return QVariant::fromValue(nullptr);
327}
328
335QVariant QtObject::rgba(double r, double g, double b, double a) const
336{
337 if (r < 0.0) r=0.0;
338 if (r > 1.0) r=1.0;
339 if (g < 0.0) g=0.0;
340 if (g > 1.0) g=1.0;
341 if (b < 0.0) b=0.0;
342 if (b > 1.0) b=1.0;
343 if (a < 0.0) a=0.0;
344 if (a > 1.0) a=1.0;
345
346 return QQml_colorProvider()->fromRgbF(r, g, b, a);
347}
348
355QVariant QtObject::hsla(double h, double s, double l, double a) const
356{
357 if (h < 0.0) h=0.0;
358 if (h > 1.0) h=1.0;
359 if (s < 0.0) s=0.0;
360 if (s > 1.0) s=1.0;
361 if (l < 0.0) l=0.0;
362 if (l > 1.0) l=1.0;
363 if (a < 0.0) a=0.0;
364 if (a > 1.0) a=1.0;
365
366 return QQml_colorProvider()->fromHslF(h, s, l, a);
367}
368
377QVariant QtObject::hsva(double h, double s, double v, double a) const
378{
379 h = qBound(0.0, h, 1.0);
380 s = qBound(0.0, s, 1.0);
381 v = qBound(0.0, v, 1.0);
382 a = qBound(0.0, a, 1.0);
383
384 return QQml_colorProvider()->fromHsvF(h, s, v, a);
385}
386
395bool QtObject::colorEqual(const QVariant &lhs, const QVariant &rhs) const
396{
397 bool ok = false;
398
399 QVariant color1 = lhs;
400 if (color1.userType() == QMetaType::QString) {
401 color1 = QQmlStringConverters::colorFromString(color1.toString(), &ok);
402 if (!ok) {
403 v4Engine()->throwError(QStringLiteral("Qt.colorEqual(): Invalid color name"));
404 return false;
405 }
406 } else if (color1.userType() != QMetaType::QColor) {
407 v4Engine()->throwError(QStringLiteral("Qt.colorEqual(): Invalid arguments"));
408 return false;
409 }
410
411 QVariant color2 = rhs;
412 if (color2.userType() == QMetaType::QString) {
413 color2 = QQmlStringConverters::colorFromString(color2.toString(), &ok);
414 if (!ok) {
415 v4Engine()->throwError(QStringLiteral("Qt.colorEqual(): Invalid color name"));
416 return false;
417 }
418 } else if (color2.userType() != QMetaType::QColor) {
419 v4Engine()->throwError(QStringLiteral("Qt.colorEqual(): Invalid arguments"));
420 return false;
421 }
422
423 return color1 == color2;
424}
425
431QRectF QtObject::rect(double x, double y, double width, double height) const
432{
433 return QRectF(x, y, width, height);
434}
435
441QPointF QtObject::point(double x, double y) const
442{
443 return QPointF(x, y);
444}
445
451QSizeF QtObject::size(double w, double h) const
452{
453 return QSizeF(w, h);
454}
455
465QVariant QtObject::font(const QJSValue &fontSpecifier) const
466{
467 if (!fontSpecifier.isObject()) {
468 v4Engine()->throwError(QStringLiteral("Qt.font(): Invalid arguments"));
469 return QVariant();
470 }
471
472 {
474 fontSpecifier, QMetaType(QMetaType::QFont));
475 if (v.isValid())
476 return v;
477 }
478
479 v4Engine()->throwError(QStringLiteral("Qt.font(): Invalid argument: "
480 "no valid font subproperties specified"));
481 return QVariant();
482}
483
484template<typename T>
485void addParameters(QJSEngine *e, QJSValue &result, int i, T parameter)
486{
487 result.setProperty(i, e->toScriptValue(parameter));
488}
489
490template<>
491void addParameters<double>(QJSEngine *, QJSValue &result, int i, double parameter)
492{
493 result.setProperty(i, QJSValue(parameter));
494}
495
496template<typename T, typename ...Others>
497void addParameters(QJSEngine *e, QJSValue &result, int i, T parameter, Others... others)
498{
499 addParameters<T>(e, result, i, parameter);
500 addParameters<Others...>(e, result, ++i, others...);
501}
502
503template<typename ...T>
505{
506 if (!e)
507 return QVariant();
508 QJSValue params = e->newArray(sizeof...(parameters));
509 addParameters(e, params, 0, parameters...);
511 return variant.isValid() ? variant : QVariant(type);
512}
513
519QVariant QtObject::vector2d(double x, double y) const
520{
521 return constructFromJSValue(jsEngine(), QMetaType(QMetaType::QVector2D), x, y);
522}
523
529QVariant QtObject::vector3d(double x, double y, double z) const
530{
531 return constructFromJSValue(jsEngine(), QMetaType(QMetaType::QVector3D), x, y, z);
532}
533
539QVariant QtObject::vector4d(double x, double y, double z, double w) const
540{
541 return constructFromJSValue(jsEngine(), QMetaType(QMetaType::QVector4D), x, y, z, w);
542}
543
549QVariant QtObject::quaternion(double scalar, double x, double y, double z) const
550{
551 return constructFromJSValue(jsEngine(), QMetaType(QMetaType::QQuaternion), scalar, x, y, z);
552}
553
560{
561 const QMetaType metaType(QMetaType::QMatrix4x4);
563 return variant.isValid() ? variant : QVariant(metaType);
564}
565
582{
583 if (value.isObject()) {
585 value, QMetaType(QMetaType::QMatrix4x4));
586 if (v.isValid())
587 return v;
588 }
589
590 v4Engine()->throwError(QStringLiteral("Qt.matrix4x4(): Invalid argument: "
591 "not a valid matrix4x4 values array"));
592 return QVariant();
593}
594
609QVariant QtObject::matrix4x4(double m11, double m12, double m13, double m14,
610 double m21, double m22, double m23, double m24,
611 double m31, double m32, double m33, double m34,
612 double m41, double m42, double m43, double m44) const
613{
614 return constructFromJSValue(jsEngine(), QMetaType(QMetaType::QMatrix4x4),
615 m11, m12, m13, m14, m21, m22, m23, m24,
616 m31, m32, m33, m34, m41, m42, m43, m44);
617}
618
620{
621 QVariant v;
622 if (color.isString()) {
624 if (!(*ok))
625 return QVariant::fromValue(nullptr);
626 } else {
627 v = color.toVariant();
628 if (v.userType() != QMetaType::QColor) {
629 *ok = false;
630 return QVariant::fromValue(nullptr);
631 }
632 }
633
634 *ok = true;
635 return v;
636}
637
653QVariant QtObject::lighter(const QJSValue &color, double factor) const
654{
655 bool ok;
657 return ok ? QQml_colorProvider()->lighter(v, factor) : v;
658}
659
676QVariant QtObject::darker(const QJSValue &color, double factor) const
677{
678 bool ok;
680 return ok ? QQml_colorProvider()->darker(v, factor) : v;
681}
682
690QVariant QtObject::alpha(const QJSValue &baseColor, double value) const
691{
692 bool ok;
693 const QVariant v = colorVariantFromJSValue(baseColor, &ok);
694 return ok ? QQml_colorProvider()->alpha(v, value) : v;
695}
696
723QVariant QtObject::tint(const QJSValue &baseColor, const QJSValue &tintColor) const
724{
725 bool ok;
726
727 // base color
728 const QVariant v1 = colorVariantFromJSValue(baseColor, &ok);
729 if (!ok)
730 return v1;
731
732 // tint color
733 const QVariant v2 = colorVariantFromJSValue(tintColor, &ok);
734
735 return ok ? QQml_colorProvider()->tint(v1, v2) : v2;
736}
737
738namespace {
739template <typename T>
740QString formatDateTimeObjectUsingDateFormat(T formatThis, Qt::DateFormat format) {
741 switch (format) {
742 case Qt::TextDate:
743 case Qt::ISODate:
744 case Qt::RFC2822Date:
746 return formatThis.toString(format);
747 default: // ### Qt 6: remove once qtbase has removed the rest of the enum !
748 break;
749 }
750 // Q_UNREACHABLE(); // ### Qt 6: restore once the default is gone
751 return QString();
752}
753}
754
756{
757 return dateTime.toLocalTime().time();
758}
759
776static std::optional<QDate> dateFromString(const QString &string, QV4::ExecutionEngine *engine)
777{
778 {
779 const QDate date = QDate::fromString(string, Qt::ISODate);
780 if (date.isValid())
781 return date;
782 }
783
784 {
785 // For historical reasons, the string argument is parsed as datetime, not as only date
786 const QDateTime dateTime = QDateTime::fromString(string, Qt::ISODate);
787 if (dateTime.isValid()) {
788 qCWarning(lcRootProperties())
789 << string << "is a date/time string being passed to formatDate()."
790 << "You should only pass date strings to formatDate().";
791 return dateTime.date();
792 }
793 }
794
795 {
796 // Since we can coerce QDate to QString, allow the resulting string format here.
798 if (dateTime.isValid())
800 }
801
802 engine->throwError(QStringLiteral("Invalid argument passed to formatDate(): %1").arg(string));
803 return std::nullopt;
804}
805
807{
808 return date.toString(format);
809}
810
812{
813 return formatDateTimeObjectUsingDateFormat(date, format);
814}
815
820
822{
823 if (const auto qDate = dateFromString(string, v4Engine()))
824 return formatDate(qDate.value(), format);
825
826 return QString();
827}
828
830{
831 return formatDateTimeObjectUsingDateFormat(DateObject::dateTimeToDate(dateTime), format);
832}
833
835{
836 if (const auto qDate = dateFromString(string, v4Engine()))
837 return formatDate(qDate.value(), format);
838
839 return QString();
840}
841
842#if QT_CONFIG(qml_locale)
844 QLocale::FormatType formatType) const
845{
846 return locale.toString(date, formatType);
847}
848
850 QLocale::FormatType formatType) const
851{
852 return locale.toString(DateObject::dateTimeToDate(dateTime), formatType);
853}
854
855QString QtObject::formatDate(const QString &string, const QLocale &locale,
856 QLocale::FormatType formatType) const
857{
858 if (const auto qDate = dateFromString(string, v4Engine()))
859 return locale.toString(qDate.value(), formatType);
860
861 return QString();
862}
863#endif
864
881static std::optional<QTime> timeFromString(const QString &string, QV4::ExecutionEngine *engine)
882{
883 {
884 const QTime time = QTime::fromString(string, Qt::ISODate);
885 if (time.isValid())
886 return time;
887 }
888
889 {
890 // For historical reasons, the string argument is parsed as datetime, not as only time
891 const QDateTime dateTime = QDateTime::fromString(string, Qt::ISODate);
892 if (dateTime.isValid()) {
893 qCWarning(lcRootProperties())
894 << string << "is a date/time string being passed to formatTime()."
895 << "You should only pass time strings to formatTime().";
896 return dateTime.time();
897 }
898 }
899
900 {
901 // Since we can coerce QTime to QString, allow the resulting string format here.
903 if (dateTime.isValid())
904 return dateTimeToTime(dateTime);
905 }
906
907 engine->throwError(QStringLiteral("Invalid argument passed to formatTime(): %1").arg(string));
908 return std::nullopt;
909}
910
912{
913 return time.toString(format);
914}
915
917{
918 return dateTimeToTime(dateTime).toString(format);
919}
920
922{
923
924 if (auto qTime = timeFromString(time, v4Engine()))
925 return formatTime(qTime.value(), format);
926
927 return QString();
928}
929
931{
932 return formatDateTimeObjectUsingDateFormat(time, format);
933}
934
936{
937 return formatDateTimeObjectUsingDateFormat(dateTimeToTime(dateTime), format);
938}
939
941{
942 if (auto qTime = timeFromString(time, v4Engine()))
943 return formatTime(qTime.value(), format);
944
945 return QString();
946}
947
948#if QT_CONFIG(qml_locale)
950 QLocale::FormatType formatType) const
951{
952 return locale.toString(time, formatType);
953}
954
956 QLocale::FormatType formatType) const
957{
958 return locale.toString(dateTimeToTime(dateTime), formatType);
959}
960
961QString QtObject::formatTime(const QString &time, const QLocale &locale,
962 QLocale::FormatType formatType) const
963{
964 if (auto qTime = timeFromString(time, v4Engine()))
965 return locale.toString(qTime.value(), formatType);
966
967 return QString();
968}
969#endif
970
1069static std::optional<QDateTime> dateTimeFromString(const QString &string, QV4::ExecutionEngine *engine)
1070{
1071 {
1072 const QDateTime dateTime = QDateTime::fromString(string, Qt::ISODate);
1073 if (dateTime.isValid())
1074 return dateTime;
1075 }
1076
1077 {
1078 // Since we can coerce QDateTime to QString, allow the resulting string format here.
1080 if (dateTime.isValid())
1081 return dateTime;
1082 }
1083
1084 engine->throwError(QStringLiteral("Invalid argument passed to formatDateTime(): %1").arg(string));
1085 return std::nullopt;
1086}
1087
1089{
1090 return dateTime.toString(format);
1091}
1092
1094{
1095
1096 if (const auto qDateTime = dateTimeFromString(string, v4Engine()))
1097 return formatDateTime(qDateTime.value(), format);
1098
1099 return QString();
1100}
1101
1103{
1104 return formatDateTimeObjectUsingDateFormat(dateTime, format);
1105}
1106
1108{
1109
1110 if (const auto qDateTime = dateTimeFromString(string, v4Engine()))
1111 return formatDateTime(qDateTime.value(), format);
1112
1113 return QString();
1114}
1115
1116#if QT_CONFIG(qml_locale)
1118 QLocale::FormatType formatType) const
1119{
1120 return locale.toString(dateTime, formatType);
1121}
1122
1123QString QtObject::formatDateTime(const QString &string, const QLocale &locale,
1124 QLocale::FormatType formatType) const
1125{
1126
1127 if (const auto qDateTime = dateTimeFromString(string, v4Engine()))
1128 return formatDateTime(qDateTime.value(), locale, formatType);
1129
1130 return QString();
1131}
1132#endif
1133
1149
1161{
1162 return url;
1163}
1164
1177{
1178 if (QQmlRefPointer<QQmlContextData> ctxt = v4Engine()->callingQmlContext())
1179 return ctxt->resolvedUrl(url);
1180 if (QQmlEngine *engine = qmlEngine())
1181 return engine->baseUrl().resolved(url);
1182 return url;
1183}
1184
1196{
1197 if (context) {
1198 QQmlData *data = QQmlData::get(context);
1199 if (data && data->outerContext)
1200 return data->outerContext->resolvedUrl(url);
1201 }
1202
1203 if (QQmlEngine *engine = qmlEngine())
1204 return engine->baseUrl().resolved(url);
1205 return url;
1206}
1207
1217
1223{
1225}
1226
1232{
1233 return QLatin1String(data.toUtf8().toBase64());
1234}
1235
1241{
1242 return QString::fromUtf8(QByteArray::fromBase64(data.toLatin1()));
1243}
1244
1256void QtObject::quit() const
1257{
1258 if (QQmlEngine *engine = qmlEngine())
1259 QQmlEnginePrivate::get(engine)->sendQuit();
1260}
1261
1274void QtObject::exit(int retCode) const
1275{
1276 if (QQmlEngine *engine = qmlEngine())
1277 QQmlEnginePrivate::get(engine)->sendExit(retCode);
1278}
1279
1309QObject *QtObject::createQmlObject(const QString &qml, QObject *parent, const QUrl &url) const
1310{
1311 QQmlEngine *engine = qmlEngine();
1312 if (!engine) {
1313 v4Engine()->throwError(QStringLiteral("Qt.createQmlObject(): "
1314 "Can only be called on a QML engine."));
1315 return nullptr;
1316 }
1317
1318 struct Error {
1319 static ReturnedValue create(QV4::ExecutionEngine *v4, const QList<QQmlError> &errors) {
1320 Scope scope(v4);
1321 QString errorstr;
1322 // '+=' reserves extra capacity. Follow-up appending will be probably free.
1323 errorstr += QLatin1String("Qt.createQmlObject(): failed to create object: ");
1324
1325 QV4::ScopedArrayObject qmlerrors(scope, v4->newArrayObject());
1326 QV4::ScopedObject qmlerror(scope);
1327 QV4::ScopedString s(scope);
1328 QV4::ScopedValue v(scope);
1329 for (int ii = 0; ii < errors.size(); ++ii) {
1330 const QQmlError &error = errors.at(ii);
1331 errorstr += QLatin1String("\n ") + error.toString();
1332 qmlerror = v4->newObject();
1333 qmlerror->put((s = v4->newString(QStringLiteral("lineNumber"))), (v = QV4::Value::fromInt32(error.line())));
1334 qmlerror->put((s = v4->newString(QStringLiteral("columnNumber"))), (v = QV4::Value::fromInt32(error.column())));
1335 qmlerror->put((s = v4->newString(QStringLiteral("fileName"))), (v = v4->newString(error.url().toString())));
1336 qmlerror->put((s = v4->newString(QStringLiteral("message"))), (v = v4->newString(error.description())));
1337 qmlerrors->put(ii, qmlerror);
1338 }
1339
1340 v = v4->newString(errorstr);
1341 ScopedObject errorObject(scope, v4->newErrorObject(v));
1342 errorObject->put((s = v4->newString(QStringLiteral("qmlErrors"))), qmlerrors);
1343 return errorObject.asReturnedValue();
1344 }
1345 };
1346
1347 QQmlRefPointer<QQmlContextData> context = v4Engine()->callingQmlContext();
1348 if (!context)
1349 context = QQmlContextData::get(QQmlEnginePrivate::get(engine)->rootContext);
1350
1351 Q_ASSERT(context);
1352 QQmlContext *effectiveContext = nullptr;
1353 if (context->isPragmaLibraryContext())
1354 effectiveContext = engine->rootContext();
1355 else
1356 effectiveContext = context->asQQmlContext();
1357 Q_ASSERT(effectiveContext);
1358
1359 if (qml.isEmpty())
1360 return nullptr;
1361
1363 if (url.isValid() && url.isRelative())
1364 resolvedUrl = context->resolvedUrl(url);
1365
1366 if (!parent) {
1367 v4Engine()->throwError(QStringLiteral("Qt.createQmlObject(): Missing parent object"));
1368 return nullptr;
1369 }
1370
1371 QQmlRefPointer<QQmlTypeData> typeData = QQmlEnginePrivate::get(engine)->typeLoader.getType(
1373 Q_ASSERT(typeData->isCompleteOrError());
1376 componentPrivate->fromTypeData(typeData);
1377 componentPrivate->progress = 1.0;
1378
1379 Scope scope(v4Engine());
1380 if (component.isError()) {
1381 ScopedValue v(scope, Error::create(scope.engine, component.errors()));
1382 scope.engine->throwError(v);
1383 return nullptr;
1384 }
1385
1386 if (!component.isReady()) {
1387 v4Engine()->throwError(QStringLiteral("Qt.createQmlObject(): Component is not ready"));
1388 return nullptr;
1389 }
1390
1391 if (!effectiveContext->isValid()) {
1392 v4Engine()->throwError(QStringLiteral("Qt.createQmlObject(): Cannot create a component "
1393 "in an invalid context"));
1394 return nullptr;
1395 }
1396
1397 QObject *obj = component.beginCreate(effectiveContext);
1398 if (obj) {
1399 QQmlData::get(obj, true)->explicitIndestructibleSet = false;
1400 QQmlData::get(obj)->indestructible = false;
1401
1402 obj->setParent(parent);
1403
1404 QList<QQmlPrivate::AutoParentFunction> functions = QQmlMetaType::parentFunctions();
1405 for (int ii = 0; ii < functions.size(); ++ii) {
1406 if (QQmlPrivate::Parented == functions.at(ii)(obj, parent))
1407 break;
1408 }
1409 }
1410 component.completeCreate();
1411
1412 if (component.isError()) {
1413 ScopedValue v(scope, Error::create(scope.engine, component.errors()));
1414 scope.engine->throwError(v);
1415 return nullptr;
1416 }
1417
1418 Q_ASSERT(obj);
1419 return obj;
1420}
1421
1497
1499 QObject *parent) const
1500{
1502 v4Engine()->throwError(QStringLiteral("Invalid compilation mode %1").arg(mode));
1503 return nullptr;
1504 }
1505
1506 if (url.isEmpty())
1507 return nullptr;
1508
1509 QQmlEngine *engine = qmlEngine();
1510 if (!engine)
1511 return nullptr;
1512
1513 auto [context, effectiveContext] = getContexts();
1514 if (!context)
1515 return nullptr;
1516
1517 QQmlComponent *c = new QQmlComponent(engine, context->resolvedUrl(url), mode, parent);
1518 QQmlComponentPrivate::get(c)->creationContext = effectiveContext;
1519 QQmlData::get(c, true)->explicitIndestructibleSet = false;
1520 QQmlData::get(c)->indestructible = false;
1521 return c;
1522}
1523
1525 QObject *parent) const
1526{
1528}
1529
1531{
1533 v4Engine()->throwError(QStringLiteral("Invalid compilation mode %1").arg(mode));
1534 return nullptr;
1535 }
1536
1537 QQmlEngine *engine = qmlEngine();
1538 if (!engine)
1539 return nullptr;
1540
1541 if (moduleUri.isEmpty() || typeName.isEmpty())
1542 return nullptr;
1543
1544 auto [context, effectiveContext] = getContexts();
1545 if (!context)
1546 return nullptr;
1547
1548 QQmlComponent *c = new QQmlComponent(engine, moduleUri, typeName, mode, parent);
1549 if (c->isError() && !parent && moduleUri.endsWith(u".qml")) {
1550 v4Engine()->throwTypeError(
1551 QStringLiteral("Invalid arguments; did you swap mode and parent"));
1552 }
1553 QQmlComponentPrivate::get(c)->creationContext = effectiveContext;
1554 QQmlData::get(c, true)->explicitIndestructibleSet = false;
1555 QQmlData::get(c)->indestructible = false;
1556 return c;
1557}
1558
1559#if QT_CONFIG(translation)
1560QString QtObject::uiLanguage() const
1561{
1562 if (const QJSEngine *e = jsEngine())
1563 return e->uiLanguage();
1564 return QString();
1565}
1566
1567void QtObject::setUiLanguage(const QString &uiLanguage)
1568{
1569 if (QJSEngine *e = jsEngine())
1570 e->setUiLanguage(uiLanguage);
1571}
1572
1573QBindable<QString> QtObject::uiLanguageBindable()
1574{
1575 if (QJSEngine *e = jsEngine())
1576 return QBindable<QString>(&QJSEnginePrivate::get(e)->uiLanguage);
1577 return QBindable<QString>();
1578}
1579#endif
1580
1581#if QT_CONFIG(qml_locale)
1602QLocale QtObject::locale() const
1603{
1604 return QLocale();
1605}
1606
1607QLocale QtObject::locale(const QString &name) const
1608{
1609 return QLocale(name);
1610}
1611#endif
1612
1613void Heap::QQmlBindingFunction::init(const QV4::JavaScriptFunctionObject *bindingFunction)
1614{
1615 Scope scope(bindingFunction->engine());
1616 ScopedContext context(scope, bindingFunction->scope());
1617 JavaScriptFunctionObject::init(context, bindingFunction->function());
1618 this->bindingFunction.set(internalClass->engine, bindingFunction->d());
1619}
1620
1622 const FunctionObject *f, const Value *, const Value *, int)
1623{
1624 // Mark this as a callable object, so that we can perform the binding magic on it.
1625 return f->engine()->throwTypeError(QStringLiteral("Bindings must not be called directly."));
1626}
1627
1629{
1630 QV4::CppStackFrame *frame = engine()->currentStackFrame;
1631 if (frame->v4Function) // synchronous loading:
1632 return QQmlSourceLocation(frame->source(), frame->lineNumber(), 0);
1633 else // async loading:
1634 return bindingFunction()->function->sourceLocation();
1635}
1636
1638
1681{
1683 = QJSValuePrivate::asManagedType<JavaScriptFunctionObject>(&function);
1685 if (!f) {
1687 e->throwError(
1689 "binding(): argument (binding expression) must be a function")));
1690 }
1691
1694}
1695
1697{
1698 m_engine->delayedCallQueue()->addUniquelyAndExecuteLater(m_engine, args);
1699}
1700
1701
1703{
1704 if (!m_platform)
1705 m_platform = new QQmlPlatform(this);
1706 return m_platform;
1707}
1708
1710{
1711 if (!m_application)
1712 // Only allocate an application object once
1713 m_application = QQml_guiProvider()->application(this);
1714
1715 return m_application;
1716}
1717
1719{
1720 return QQml_guiProvider()->inputMethod();
1721}
1722
1724{
1725 return QQml_guiProvider()->styleHints();
1726}
1727
1729{
1730 Object::init();
1731 QV4::Scope scope(internalClass->engine);
1732 QV4::ScopedObject o(scope, this);
1733
1734 o->defineDefaultProperty(QStringLiteral("debug"), QV4::ConsoleObject::method_log);
1735 o->defineDefaultProperty(QStringLiteral("log"), QV4::ConsoleObject::method_log);
1736 o->defineDefaultProperty(QStringLiteral("info"), QV4::ConsoleObject::method_info);
1737 o->defineDefaultProperty(QStringLiteral("warn"), QV4::ConsoleObject::method_warn);
1738 o->defineDefaultProperty(QStringLiteral("error"), QV4::ConsoleObject::method_error);
1739 o->defineDefaultProperty(QStringLiteral("assert"), QV4::ConsoleObject::method_assert);
1740
1741 o->defineDefaultProperty(QStringLiteral("count"), QV4::ConsoleObject::method_count);
1742 o->defineDefaultProperty(QStringLiteral("profile"), QV4::ConsoleObject::method_profile);
1743 o->defineDefaultProperty(QStringLiteral("profileEnd"), QV4::ConsoleObject::method_profileEnd);
1744 o->defineDefaultProperty(QStringLiteral("time"), QV4::ConsoleObject::method_time);
1745 o->defineDefaultProperty(QStringLiteral("timeEnd"), QV4::ConsoleObject::method_timeEnd);
1746 o->defineDefaultProperty(QStringLiteral("trace"), QV4::ConsoleObject::method_trace);
1747 o->defineDefaultProperty(QStringLiteral("exception"), QV4::ConsoleObject::method_exception);
1748}
1749
1750
1757
1759 QString stack;
1760
1761 int i = 0;
1762 for (CppStackFrame *f = engine->currentStackFrame; f && i < 10; f = f->parentFrame(), ++i) {
1763 QString stackFrame;
1764
1765 if (f->isJSTypesFrame() && static_cast<JSTypesStackFrame *>(f)->isTailCalling()) {
1766 stackFrame = QStringLiteral("[elided tail calls]");
1767 } else {
1768 const int line = f->lineNumber();
1769 if (line != f->missingLineNumber()) {
1770 stackFrame = QStringLiteral("%1 (%2:%3)").arg(
1771 f->function(), f->source(), QString::number(qAbs(line)));
1772 } else {
1773 stackFrame = QStringLiteral("%1 (%2)").arg(
1774 f->function(), f->source());
1775 }
1776 }
1777
1778 if (i)
1779 stack += QLatin1Char('\n');
1780 stack += stackFrame;
1781 }
1782 return stack;
1783}
1784
1785static QString serializeArray(Object *array, ExecutionEngine *v4, QSet<QV4::Heap::Object *> &alreadySeen) {
1786 Scope scope(v4);
1787 ScopedValue val(scope);
1789
1790 alreadySeen.insert(array->d());
1791 result += QLatin1Char('[');
1792 const uint length = array->getLength();
1793 for (uint i = 0; i < length; ++i) {
1794 if (i != 0)
1795 result += QLatin1Char(',');
1796 val = array->get(i);
1797 if (val->isManaged() && val->managed()->isArrayLike())
1798 if (!alreadySeen.contains(val->objectValue()->d()))
1799 result += serializeArray(val->objectValue(), v4, alreadySeen);
1800 else
1801 result += QLatin1String("[Circular]");
1802 else
1803 result += val->toQStringNoThrow();
1804 }
1805 result += QLatin1Char(']');
1806 alreadySeen.remove(array->d());
1807 return result;
1808};
1809
1810static ReturnedValue writeToConsole(const FunctionObject *b, const Value *argv, int argc,
1811 ConsoleLogTypes logType, bool printStack = false)
1812{
1813 const QLoggingCategory *loggingCategory = nullptr;
1815 QV4::Scope scope(b);
1816 QV4::ExecutionEngine *v4 = scope.engine;
1817
1818 int start = 0;
1819 if (argc > 0) {
1820 if (const QObjectWrapper* wrapper = argv[0].as<QObjectWrapper>()) {
1822 = qobject_cast<QQmlLoggingCategoryBase *>(wrapper->object())) {
1823 if (category->category())
1824 loggingCategory = category->category();
1825 else
1826 THROW_GENERIC_ERROR("A QmlLoggingCatgory was provided without a valid name");
1827 start = 1;
1828 }
1829 }
1830 }
1831
1832
1833 for (int i = start, ei = argc; i < ei; ++i) {
1834 if (i != start)
1835 result.append(QLatin1Char(' '));
1836
1837 QSet<QV4::Heap::Object *> alreadySeenElements;
1838 if (argv[i].isManaged() && argv[i].managed()->isArrayLike())
1839 result.append(serializeArray(argv[i].objectValue(), v4, alreadySeenElements));
1840 else
1841 result.append(argv[i].toQStringNoThrow());
1842 }
1843
1844 if (printStack)
1845 result += QLatin1Char('\n') + jsStack(v4);
1846
1847 if (!loggingCategory)
1848 loggingCategory = v4->qmlEngine() ? &lcQml() : &lcJs();
1850 const QByteArray baSource = frame ? frame->source().toUtf8() : QByteArray();
1851 const QByteArray baFunction = frame ? frame->function().toUtf8() : QByteArray();
1852 QMessageLogger logger(baSource.constData(), frame ? frame->lineNumber() : 0,
1853 baFunction.constData(), loggingCategory->categoryName());
1854
1855 switch (logType) {
1856 case Log:
1857 if (loggingCategory->isDebugEnabled())
1858 logger.debug("%s", result.toUtf8().constData());
1859 break;
1860 case Info:
1861 if (loggingCategory->isInfoEnabled())
1862 logger.info("%s", result.toUtf8().constData());
1863 break;
1864 case Warn:
1865 if (loggingCategory->isWarningEnabled())
1866 logger.warning("%s", result.toUtf8().constData());
1867 break;
1868 case Error:
1869 if (loggingCategory->isCriticalEnabled())
1870 logger.critical("%s", result.toUtf8().constData());
1871 break;
1872 default:
1873 break;
1874 }
1875
1876 return Encode::undefined();
1877}
1878
1880
1882{
1883 return writeToConsole(b, argv, argc, Error);
1884}
1885
1887{
1888 //console.log
1889 //console.debug
1890 //print
1891 return writeToConsole(b, argv, argc, Log);
1892}
1893
1895{
1896 return writeToConsole(b, argv, argc, Info);
1897}
1898
1900{
1901 QV4::Scope scope(b);
1902 QV4::ExecutionEngine *v4 = scope.engine;
1903
1905 const QByteArray baSource = frame->source().toUtf8();
1906 const QByteArray baFunction = frame->function().toUtf8();
1907 QMessageLogger logger(baSource.constData(), frame->lineNumber(), baFunction.constData());
1908 QQmlProfilerService *service = QQmlDebugConnector::service<QQmlProfilerService>();
1909 if (!service) {
1910 logger.warning("Cannot start profiling because debug service is disabled. Start with -qmljsdebugger=port:XXXXX.");
1911 } else {
1912 service->startProfiling(v4->jsEngine());
1913 logger.debug("Profiling started.");
1914 }
1915
1916 return QV4::Encode::undefined();
1917}
1918
1920{
1921 QV4::Scope scope(b);
1922 QV4::ExecutionEngine *v4 = scope.engine;
1923
1925 const QByteArray baSource = frame->source().toUtf8();
1926 const QByteArray baFunction = frame->function().toUtf8();
1927 QMessageLogger logger(baSource.constData(), frame->lineNumber(), baFunction.constData());
1928
1929 QQmlProfilerService *service = QQmlDebugConnector::service<QQmlProfilerService>();
1930 if (!service) {
1931 logger.warning("Ignoring console.profileEnd(): the debug service is disabled.");
1932 } else {
1933 service->stopProfiling(v4->jsEngine());
1934 logger.debug("Profiling ended.");
1935 }
1936
1937 return QV4::Encode::undefined();
1938}
1939
1941{
1942 QV4::Scope scope(b);
1943 if (argc != 1)
1944 THROW_GENERIC_ERROR("console.time(): Invalid arguments");
1945
1946 QString name = argv[0].toQStringNoThrow();
1947 scope.engine->startTimer(name);
1948 return QV4::Encode::undefined();
1949}
1950
1952{
1953 QV4::Scope scope(b);
1954 if (argc != 1)
1955 THROW_GENERIC_ERROR("console.timeEnd(): Invalid arguments");
1956
1957 QString name = argv[0].toQStringNoThrow();
1958 bool wasRunning;
1959 qint64 elapsed = scope.engine->stopTimer(name, &wasRunning);
1960 if (wasRunning) {
1961 qDebug("%s: %llims", qPrintable(name), elapsed);
1962 }
1963 return QV4::Encode::undefined();
1964}
1965
1967{
1968 // first argument: name to print. Ignore any additional arguments
1969 QString name;
1970 if (argc > 0)
1971 name = argv[0].toQStringNoThrow();
1972
1973 Scope scope(b);
1974 QV4::ExecutionEngine *v4 = scope.engine;
1975
1977
1978 QString scriptName = frame->source();
1979
1980 int value = v4->consoleCountHelper(scriptName, frame->lineNumber(), 0);
1982
1983 QMessageLogger(qPrintable(scriptName), frame->lineNumber(),
1984 qPrintable(frame->function()))
1985 .debug("%s", qPrintable(message));
1986
1987 return QV4::Encode::undefined();
1988}
1989
1991{
1992 QV4::Scope scope(b);
1993 if (argc != 0)
1994 THROW_GENERIC_ERROR("console.trace(): Invalid arguments");
1995
1996 QV4::ExecutionEngine *v4 = scope.engine;
1997
1998 QString stack = jsStack(v4);
1999
2001 QMessageLogger(frame->source().toUtf8().constData(), frame->lineNumber(),
2002 frame->function().toUtf8().constData())
2003 .debug(v4->qmlEngine() ? lcQml() : lcJs(), "%s", qPrintable(stack));
2004
2005 return QV4::Encode::undefined();
2006}
2007
2009{
2010 return writeToConsole(b, argv, argc, Warn);
2011}
2012
2014{
2015 QV4::Scope scope(b);
2016 if (argc == 0)
2017 THROW_GENERIC_ERROR("console.assert(): Missing argument");
2018
2019 QV4::ExecutionEngine *v4 = scope.engine;
2020
2021 if (!argv[0].toBoolean()) {
2023 for (int i = 1, ei = argc; i < ei; ++i) {
2024 if (i != 1)
2025 message.append(QLatin1Char(' '));
2026
2027 message.append(argv[i].toQStringNoThrow());
2028 }
2029
2030 QString stack = jsStack(v4);
2031
2033 QMessageLogger(frame->source().toUtf8().constData(), frame->lineNumber(),
2034 frame->function().toUtf8().constData())
2035 .critical("%s\n%s",qPrintable(message), qPrintable(stack));
2036
2037 }
2038 return QV4::Encode::undefined();
2039}
2040
2042{
2043 QV4::Scope scope(b);
2044 if (argc == 0)
2045 THROW_GENERIC_ERROR("console.exception(): Missing argument");
2046
2047 return writeToConsole(b, argv, argc, Error, true);
2048}
2049
2050void QV4::GlobalExtensions::init(Object *globalObject, QJSEngine::Extensions extensions)
2051{
2052 ExecutionEngine *v4 = globalObject->engine();
2053 Scope scope(v4);
2054
2055 if (extensions.testFlag(QJSEngine::TranslationExtension)) {
2056 #if QT_CONFIG(translation)
2057 globalObject->defineDefaultProperty(QStringLiteral("qsTranslate"), QV4::GlobalExtensions::method_qsTranslate);
2058 globalObject->defineDefaultProperty(QStringLiteral("QT_TRANSLATE_NOOP"), QV4::GlobalExtensions::method_qsTranslateNoOp);
2059 globalObject->defineDefaultProperty(QStringLiteral("qsTr"), QV4::GlobalExtensions::method_qsTr);
2060 globalObject->defineDefaultProperty(QStringLiteral("QT_TR_NOOP"), QV4::GlobalExtensions::method_qsTrNoOp);
2061 globalObject->defineDefaultProperty(QStringLiteral("qsTrId"), QV4::GlobalExtensions::method_qsTrId);
2062 globalObject->defineDefaultProperty(QStringLiteral("QT_TRID_NOOP"), QV4::GlobalExtensions::method_qsTrIdNoOp);
2063
2064 // Initialize the Qt global object for the uiLanguage property
2065 ScopedString qtName(scope, v4->newString(QStringLiteral("Qt")));
2066 ScopedObject qt(scope, globalObject->get(qtName));
2067 if (!qt)
2068 v4->createQtObject();
2069
2070 // string prototype extension
2072 #endif
2073 }
2074
2075 if (extensions.testFlag(QJSEngine::ConsoleExtension)) {
2076 globalObject->defineDefaultProperty(QStringLiteral("print"), QV4::ConsoleObject::method_log);
2077
2078
2080 globalObject->defineDefaultProperty(QStringLiteral("console"), console);
2081 }
2082
2083 if (extensions.testFlag(QJSEngine::GarbageCollectionExtension)) {
2084 globalObject->defineDefaultProperty(QStringLiteral("gc"), QV4::GlobalExtensions::method_gc);
2085 }
2086}
2087
2088
2089#if QT_CONFIG(translation)
2107ReturnedValue GlobalExtensions::method_qsTranslate(const FunctionObject *b, const Value *, const Value *argv, int argc)
2108{
2109 QV4::Scope scope(b);
2110 if (argc < 2)
2111 THROW_GENERIC_ERROR("qsTranslate() requires at least two arguments");
2112 if (!argv[0].isString())
2113 THROW_GENERIC_ERROR("qsTranslate(): first argument (context) must be a string");
2114 if (!argv[1].isString())
2115 THROW_GENERIC_ERROR("qsTranslate(): second argument (sourceText) must be a string");
2116 if ((argc > 2) && !argv[2].isString())
2117 THROW_GENERIC_ERROR("qsTranslate(): third argument (disambiguation) must be a string");
2118
2119 QString context = argv[0].toQStringNoThrow();
2120 QString text = argv[1].toQStringNoThrow();
2121 QString comment;
2122 if (argc > 2) comment = argv[2].toQStringNoThrow();
2123
2124 int i = 3;
2125 if (argc > i && argv[i].isString()) {
2126 qWarning("qsTranslate(): specifying the encoding as fourth argument is deprecated");
2127 ++i;
2128 }
2129
2130 int n = -1;
2131 if (argc > i)
2132 n = argv[i].toInt32();
2133
2134 if (QQmlEnginePrivate *ep = (scope.engine->qmlEngine() ? QQmlEnginePrivate::get(scope.engine->qmlEngine()) : nullptr))
2135 if (ep->propertyCapture)
2136 ep->propertyCapture->captureTranslation();
2137
2138 QString result = QCoreApplication::translate(context.toUtf8().constData(),
2139 text.toUtf8().constData(),
2140 comment.toUtf8().constData(),
2141 n);
2142
2143 return Encode(scope.engine->newString(result));
2144}
2145
2168ReturnedValue GlobalExtensions::method_qsTranslateNoOp(const FunctionObject *b, const Value *, const Value *argv, int argc)
2169{
2170 QV4::Scope scope(b);
2171 if (argc < 2)
2172 return QV4::Encode::undefined();
2173 else
2174 return argv[1].asReturnedValue();
2175}
2176
2177QString GlobalExtensions::currentTranslationContext(ExecutionEngine *engine)
2178{
2180 CppStackFrame *frame = engine->currentStackFrame;
2181
2182 // The first non-empty source URL in the call stack determines the translation context.
2183 while (frame && context.isEmpty()) {
2184 if (ExecutableCompilationUnit *unit = frame->v4Function->executableCompilationUnit()) {
2185 auto translationContextIndex = unit->unitData()->translationContextIndex();
2186 if (translationContextIndex)
2187 context = unit->stringAt(*translationContextIndex);
2188 if (!context.isEmpty())
2189 break;
2190 QString fileName = unit->fileName();
2191 QUrl url(unit->fileName());
2192 if (url.isValid() && url.isRelative()) {
2193 context = url.fileName();
2194 } else {
2196 if (context.isEmpty() && fileName.startsWith(QLatin1String(":/")))
2197 context = fileName;
2198 }
2199 context = QFileInfo(context).completeBaseName();
2200 }
2201 frame = frame->parentFrame();
2202 }
2203
2204 if (context.isEmpty()) {
2205 if (QQmlRefPointer<QQmlContextData> ctxt = engine->callingQmlContext()) {
2206 QString path = ctxt->urlString();
2207 int lastSlash = path.lastIndexOf(QLatin1Char('/'));
2208 int lastDot = path.lastIndexOf(QLatin1Char('.'));
2209 int length = lastDot - (lastSlash + 1);
2210 context = (lastSlash > -1) ? path.mid(lastSlash + 1, (length > -1) ? length : -1) : QString();
2211 }
2212 }
2213
2214 return context;
2215}
2216
2234ReturnedValue GlobalExtensions::method_qsTr(const FunctionObject *b, const Value *, const Value *argv, int argc)
2235{
2236 QV4::Scope scope(b);
2237 if (argc < 1)
2238 THROW_GENERIC_ERROR("qsTr() requires at least one argument");
2239 if (!argv[0].isString())
2240 THROW_GENERIC_ERROR("qsTr(): first argument (sourceText) must be a string");
2241 if ((argc > 1) && !argv[1].isString())
2242 THROW_GENERIC_ERROR("qsTr(): second argument (disambiguation) must be a string");
2243 if ((argc > 2) && !argv[2].isNumber())
2244 THROW_GENERIC_ERROR("qsTr(): third argument (n) must be a number");
2245
2246 const QString context = currentTranslationContext(scope.engine);
2247 const QString text = argv[0].toQStringNoThrow();
2248 const QString comment = argc > 1 ? argv[1].toQStringNoThrow() : QString();
2249 const int n = argc > 2 ? argv[2].toInt32() : -1;
2250
2251 if (QQmlEnginePrivate *ep = (scope.engine->qmlEngine() ? QQmlEnginePrivate::get(scope.engine->qmlEngine()) : nullptr))
2252 if (ep->propertyCapture)
2253 ep->propertyCapture->captureTranslation();
2254
2256 comment.toUtf8().constData(), n);
2257
2258 return Encode(scope.engine->newString(result));
2259}
2260
2283ReturnedValue GlobalExtensions::method_qsTrNoOp(const FunctionObject *, const Value *, const Value *argv, int argc)
2284{
2285 if (argc < 1)
2286 return QV4::Encode::undefined();
2287 else
2288 return argv[0].asReturnedValue();
2289}
2290
2321ReturnedValue GlobalExtensions::method_qsTrId(const FunctionObject *b, const Value *, const Value *argv, int argc)
2322{
2323 QV4::Scope scope(b);
2324 if (argc < 1)
2325 THROW_GENERIC_ERROR("qsTrId() requires at least one argument");
2326 if (!argv[0].isString())
2327 THROW_TYPE_ERROR_WITH_MESSAGE("qsTrId(): first argument (id) must be a string");
2328 if (argc > 1 && !argv[1].isNumber())
2329 THROW_TYPE_ERROR_WITH_MESSAGE("qsTrId(): second argument (n) must be a number");
2330
2331 int n = -1;
2332 if (argc > 1)
2333 n = argv[1].toInt32();
2334
2335 if (QQmlEnginePrivate *ep = (scope.engine->qmlEngine() ? QQmlEnginePrivate::get(scope.engine->qmlEngine()) : nullptr))
2336 if (ep->propertyCapture)
2337 ep->propertyCapture->captureTranslation();
2338
2339 return Encode(scope.engine->newString(qtTrId(argv[0].toQStringNoThrow().toUtf8().constData(), n)));
2340}
2341
2358ReturnedValue GlobalExtensions::method_qsTrIdNoOp(const FunctionObject *, const Value *, const Value *argv, int argc)
2359{
2360 if (argc < 1)
2361 return QV4::Encode::undefined();
2362 else
2363 return argv[0].asReturnedValue();
2364}
2365#endif // translation
2366
2377{
2378 auto mm = b->engine()->memoryManager;
2379 mm->runFullGC();
2380
2381 return QV4::Encode::undefined();
2382}
2383
2384ReturnedValue GlobalExtensions::method_string_arg(const FunctionObject *b, const Value *thisObject, const Value *argv, int argc)
2385{
2386 QV4::Scope scope(b);
2387 if (argc != 1)
2388 THROW_GENERIC_ERROR("String.arg(): Invalid arguments");
2389
2390 QString value = thisObject->toQString();
2391
2392 QV4::ScopedValue arg(scope, argv[0]);
2393 if (arg->isInteger())
2394 RETURN_RESULT(scope.engine->newString(value.arg(arg->integerValue())));
2395 else if (arg->isDouble())
2396 RETURN_RESULT(scope.engine->newString(value.arg(arg->doubleValue())));
2397 else if (arg->isBoolean())
2398 RETURN_RESULT(scope.engine->newString(value.arg(arg->booleanValue())));
2399
2400 RETURN_RESULT(scope.engine->newString(value.arg(arg->toQString())));
2401}
2402
2425
2426#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:292
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
QString toString(qlonglong i) const
Returns a localized string representation of i.
Definition qlocale.cpp:2052
\inmodule QtCore
\inmodule QtCore
Definition qlogging.h:73
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:342
\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:6028
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:5516
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:8095
QByteArray toUtf8() const &
Definition qstring.h:634
\inmodule QtCore \reentrant
Definition qdatetime.h:224
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:715
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:537
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 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
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:165
#define qWarning
Definition qlogging.h:167
#define Q_LOGGING_CATEGORY(name,...)
#define qCWarning(category,...)
#define Q_STATIC_LOGGING_CATEGORY(name,...)
const char * typeName
constexpr const T & qBound(const T &min, const T &val, const T &max)
Definition qminmax.h:23
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()