Qt 6.x
The Qt SDK
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
267// Qt.include() is implemented in qv4include.cpp
268
269QtObject::QtObject(ExecutionEngine *engine)
270 : m_engine(engine)
271{
272}
273
274QtObject::Contexts QtObject::getContexts() const
275{
276 QQmlEngine *engine = qmlEngine();
277 if (!engine)
278 return {};
279
281 if (!context)
283
285 QQmlRefPointer<QQmlContextData> effectiveContext
286 = context->isPragmaLibraryContext() ? nullptr : context;
287 return {context, effectiveContext};
288}
289
291{
292 QV4::ExecutionEngine *v4 = jsEngine->handle();
293 QV4::Scope scope(v4);
295 ScopedString qtName(scope, v4->newString(QStringLiteral("Qt")));
296 QV4::ScopedValue result(scope, globalObject->get(qtName->toPropertyKey()));
297 return qobject_cast<QtObject *>(result->as<QV4::QObjectWrapper>()->object());
298}
299
300QJSValue QtObject::include(const QString &url, const QJSValue &callback) const
301{
302 return QV4Include::method_include(v4Engine(), v4Engine()->resolvedUrl(url), callback);
303}
304
305
313{
314 return qjsvalue_cast<QObject *>(value) != nullptr;
315}
316
324{
325 bool ok = false;
327 if (ok)
328 return v;
329
330 v4Engine()->throwError(QStringLiteral("\"%1\" is not a valid color name").arg(name));
331 return QVariant::fromValue(nullptr);
332}
333
340QVariant QtObject::rgba(double r, double g, double b, double a) const
341{
342 if (r < 0.0) r=0.0;
343 if (r > 1.0) r=1.0;
344 if (g < 0.0) g=0.0;
345 if (g > 1.0) g=1.0;
346 if (b < 0.0) b=0.0;
347 if (b > 1.0) b=1.0;
348 if (a < 0.0) a=0.0;
349 if (a > 1.0) a=1.0;
350
351 return QQml_colorProvider()->fromRgbF(r, g, b, a);
352}
353
360QVariant QtObject::hsla(double h, double s, double l, double a) const
361{
362 if (h < 0.0) h=0.0;
363 if (h > 1.0) h=1.0;
364 if (s < 0.0) s=0.0;
365 if (s > 1.0) s=1.0;
366 if (l < 0.0) l=0.0;
367 if (l > 1.0) l=1.0;
368 if (a < 0.0) a=0.0;
369 if (a > 1.0) a=1.0;
370
371 return QQml_colorProvider()->fromHslF(h, s, l, a);
372}
373
382QVariant QtObject::hsva(double h, double s, double v, double a) const
383{
384 h = qBound(0.0, h, 1.0);
385 s = qBound(0.0, s, 1.0);
386 v = qBound(0.0, v, 1.0);
387 a = qBound(0.0, a, 1.0);
388
389 return QQml_colorProvider()->fromHsvF(h, s, v, a);
390}
391
400bool QtObject::colorEqual(const QVariant &lhs, const QVariant &rhs) const
401{
402 bool ok = false;
403
404 QVariant color1 = lhs;
405 if (color1.userType() == QMetaType::QString) {
406 color1 = QQmlStringConverters::colorFromString(color1.toString(), &ok);
407 if (!ok) {
408 v4Engine()->throwError(QStringLiteral("Qt.colorEqual(): Invalid color name"));
409 return false;
410 }
411 } else if (color1.userType() != QMetaType::QColor) {
412 v4Engine()->throwError(QStringLiteral("Qt.colorEqual(): Invalid arguments"));
413 return false;
414 }
415
416 QVariant color2 = rhs;
417 if (color2.userType() == QMetaType::QString) {
419 if (!ok) {
420 v4Engine()->throwError(QStringLiteral("Qt.colorEqual(): Invalid color name"));
421 return false;
422 }
423 } else if (color2.userType() != QMetaType::QColor) {
424 v4Engine()->throwError(QStringLiteral("Qt.colorEqual(): Invalid arguments"));
425 return false;
426 }
427
428 return color1 == color2;
429}
430
436QRectF QtObject::rect(double x, double y, double width, double height) const
437{
438 return QRectF(x, y, width, height);
439}
440
446QPointF QtObject::point(double x, double y) const
447{
448 return QPointF(x, y);
449}
450
456QSizeF QtObject::size(double w, double h) const
457{
458 return QSizeF(w, h);
459}
460
470QVariant QtObject::font(const QJSValue &fontSpecifier) const
471{
472 if (!fontSpecifier.isObject()) {
473 v4Engine()->throwError(QStringLiteral("Qt.font(): Invalid arguments"));
474 return QVariant();
475 }
476
477 {
479 fontSpecifier, QMetaType(QMetaType::QFont));
480 if (v.isValid())
481 return v;
482 }
483
484 v4Engine()->throwError(QStringLiteral("Qt.font(): Invalid argument: "
485 "no valid font subproperties specified"));
486 return QVariant();
487}
488
489template<typename T>
490void addParameters(QJSEngine *e, QJSValue &result, int i, T parameter)
491{
492 result.setProperty(i, e->toScriptValue(parameter));
493}
494
495template<>
496void addParameters<double>(QJSEngine *, QJSValue &result, int i, double parameter)
497{
498 result.setProperty(i, QJSValue(parameter));
499}
500
501template<typename T, typename ...Others>
502void addParameters(QJSEngine *e, QJSValue &result, int i, T parameter, Others... others)
503{
504 addParameters<T>(e, result, i, parameter);
505 addParameters<Others...>(e, result, ++i, others...);
506}
507
508template<typename ...T>
510{
511 if (!e)
512 return QVariant();
513 QJSValue params = e->newArray(sizeof...(parameters));
514 addParameters(e, params, 0, parameters...);
516 return variant.isValid() ? variant : QVariant(type);
517}
518
524QVariant QtObject::vector2d(double x, double y) const
525{
526 return constructFromJSValue(jsEngine(), QMetaType(QMetaType::QVector2D), x, y);
527}
528
534QVariant QtObject::vector3d(double x, double y, double z) const
535{
536 return constructFromJSValue(jsEngine(), QMetaType(QMetaType::QVector3D), x, y, z);
537}
538
544QVariant QtObject::vector4d(double x, double y, double z, double w) const
545{
546 return constructFromJSValue(jsEngine(), QMetaType(QMetaType::QVector4D), x, y, z, w);
547}
548
554QVariant QtObject::quaternion(double scalar, double x, double y, double z) const
555{
556 return constructFromJSValue(jsEngine(), QMetaType(QMetaType::QQuaternion), scalar, x, y, z);
557}
558
565{
566 const QMetaType metaType(QMetaType::QMatrix4x4);
568 return variant.isValid() ? variant : QVariant(metaType);
569}
570
587{
588 if (value.isObject()) {
590 value, QMetaType(QMetaType::QMatrix4x4));
591 if (v.isValid())
592 return v;
593 }
594
595 v4Engine()->throwError(QStringLiteral("Qt.matrix4x4(): Invalid argument: "
596 "not a valid matrix4x4 values array"));
597 return QVariant();
598}
599
614QVariant QtObject::matrix4x4(double m11, double m12, double m13, double m14,
615 double m21, double m22, double m23, double m24,
616 double m31, double m32, double m33, double m34,
617 double m41, double m42, double m43, double m44) const
618{
619 return constructFromJSValue(jsEngine(), QMetaType(QMetaType::QMatrix4x4),
620 m11, m12, m13, m14, m21, m22, m23, m24,
621 m31, m32, m33, m34, m41, m42, m43, m44);
622}
623
625{
626 QVariant v;
627 if (color.isString()) {
629 if (!(*ok))
630 return QVariant::fromValue(nullptr);
631 } else {
632 v = color.toVariant();
633 if (v.userType() != QMetaType::QColor) {
634 *ok = false;
635 return QVariant::fromValue(nullptr);
636 }
637 }
638
639 *ok = true;
640 return v;
641}
642
658QVariant QtObject::lighter(const QJSValue &color, double factor) const
659{
660 bool ok;
662 return ok ? QQml_colorProvider()->lighter(v, factor) : v;
663}
664
681QVariant QtObject::darker(const QJSValue &color, double factor) const
682{
683 bool ok;
685 return ok ? QQml_colorProvider()->darker(v, factor) : v;
686}
687
695QVariant QtObject::alpha(const QJSValue &baseColor, double value) const
696{
697 bool ok;
698 const QVariant v = colorVariantFromJSValue(baseColor, &ok);
699 return ok ? QQml_colorProvider()->alpha(v, value) : v;
700}
701
728QVariant QtObject::tint(const QJSValue &baseColor, const QJSValue &tintColor) const
729{
730 bool ok;
731
732 // base color
733 const QVariant v1 = colorVariantFromJSValue(baseColor, &ok);
734 if (!ok)
735 return v1;
736
737 // tint color
738 const QVariant v2 = colorVariantFromJSValue(tintColor, &ok);
739
740 return ok ? QQml_colorProvider()->tint(v1, v2) : v2;
741}
742
743namespace {
744template <typename T>
745QString formatDateTimeObjectUsingDateFormat(T formatThis, Qt::DateFormat format) {
746 switch (format) {
747 case Qt::TextDate:
748 case Qt::ISODate:
749 case Qt::RFC2822Date:
751 return formatThis.toString(format);
752 default: // ### Qt 6: remove once qtbase has removed the rest of the enum !
753 break;
754 }
755 // Q_UNREACHABLE(); // ### Qt 6: restore once the default is gone
756 return QString();
757}
758}
759
761{
762 return dateTime.toLocalTime().time();
763}
764
781static std::optional<QDate> dateFromString(const QString &string, QV4::ExecutionEngine *engine)
782{
783 {
784 const QDate date = QDate::fromString(string, Qt::ISODate);
785 if (date.isValid())
786 return date;
787 }
788
789 {
790 // For historical reasons, the string argument is parsed as datetime, not as only date
791 const QDateTime dateTime = QDateTime::fromString(string, Qt::ISODate);
792 if (dateTime.isValid()) {
793 qCWarning(lcRootProperties())
794 << string << "is a date/time string being passed to formatDate()."
795 << "You should only pass date strings to formatDate().";
796 return dateTime.date();
797 }
798 }
799
800 {
801 // Since we can coerce QDate to QString, allow the resulting string format here.
803 if (dateTime.isValid())
805 }
806
807 engine->throwError(QStringLiteral("Invalid argument passed to formatDate(): %1").arg(string));
808 return std::nullopt;
809}
810
812{
813 return date.toString(format);
814}
815
817{
818 return formatDateTimeObjectUsingDateFormat(date, format);
819}
820
822{
824}
825
827{
828 if (const auto qDate = dateFromString(string, v4Engine()))
829 return formatDate(qDate.value(), format);
830
831 return QString();
832}
833
835{
836 return formatDateTimeObjectUsingDateFormat(DateObject::dateTimeToDate(dateTime), format);
837}
838
840{
841 if (const auto qDate = dateFromString(string, v4Engine()))
842 return formatDate(qDate.value(), format);
843
844 return QString();
845}
846
847#if QT_CONFIG(qml_locale)
848QString QtObject::formatDate(const QDate &date, const QLocale &locale,
849 QLocale::FormatType formatType) const
850{
851 return locale.toString(date, formatType);
852}
853
855 QLocale::FormatType formatType) const
856{
857 return locale.toString(DateObject::dateTimeToDate(dateTime), formatType);
858}
859
860QString QtObject::formatDate(const QString &string, const QLocale &locale,
861 QLocale::FormatType formatType) const
862{
863 if (const auto qDate = dateFromString(string, v4Engine()))
864 return locale.toString(qDate.value(), formatType);
865
866 return QString();
867}
868#endif
869
886static std::optional<QTime> timeFromString(const QString &string, QV4::ExecutionEngine *engine)
887{
888 {
889 const QTime time = QTime::fromString(string, Qt::ISODate);
890 if (time.isValid())
891 return time;
892 }
893
894 {
895 // For historical reasons, the string argument is parsed as datetime, not as only time
896 const QDateTime dateTime = QDateTime::fromString(string, Qt::ISODate);
897 if (dateTime.isValid()) {
898 qCWarning(lcRootProperties())
899 << string << "is a date/time string being passed to formatTime()."
900 << "You should only pass time strings to formatTime().";
901 return dateTime.time();
902 }
903 }
904
905 {
906 // Since we can coerce QTime to QString, allow the resulting string format here.
908 if (dateTime.isValid())
909 return dateTimeToTime(dateTime);
910 }
911
912 engine->throwError(QStringLiteral("Invalid argument passed to formatTime(): %1").arg(string));
913 return std::nullopt;
914}
915
917{
918 return time.toString(format);
919}
920
922{
923 return dateTimeToTime(dateTime).toString(format);
924}
925
927{
928
929 if (auto qTime = timeFromString(time, v4Engine()))
930 return formatTime(qTime.value(), format);
931
932 return QString();
933}
934
936{
937 return formatDateTimeObjectUsingDateFormat(time, format);
938}
939
941{
942 return formatDateTimeObjectUsingDateFormat(dateTimeToTime(dateTime), format);
943}
944
946{
947 if (auto qTime = timeFromString(time, v4Engine()))
948 return formatTime(qTime.value(), format);
949
950 return QString();
951}
952
953#if QT_CONFIG(qml_locale)
954QString QtObject::formatTime(const QTime &time, const QLocale &locale,
955 QLocale::FormatType formatType) const
956{
957 return locale.toString(time, formatType);
958}
959
961 QLocale::FormatType formatType) const
962{
963 return locale.toString(dateTimeToTime(dateTime), formatType);
964}
965
966QString QtObject::formatTime(const QString &time, const QLocale &locale,
967 QLocale::FormatType formatType) const
968{
969 if (auto qTime = timeFromString(time, v4Engine()))
970 return locale.toString(qTime.value(), formatType);
971
972 return QString();
973}
974#endif
975
1074static std::optional<QDateTime> dateTimeFromString(const QString &string, QV4::ExecutionEngine *engine)
1075{
1076 {
1077 const QDateTime dateTime = QDateTime::fromString(string, Qt::ISODate);
1078 if (dateTime.isValid())
1079 return dateTime;
1080 }
1081
1082 {
1083 // Since we can coerce QDateTime to QString, allow the resulting string format here.
1085 if (dateTime.isValid())
1086 return dateTime;
1087 }
1088
1089 engine->throwError(QStringLiteral("Invalid argument passed to formatDateTime(): %1").arg(string));
1090 return std::nullopt;
1091}
1092
1094{
1095 return dateTime.toString(format);
1096}
1097
1099{
1100
1101 if (const auto qDateTime = dateTimeFromString(string, v4Engine()))
1102 return formatDateTime(qDateTime.value(), format);
1103
1104 return QString();
1105}
1106
1108{
1109 return formatDateTimeObjectUsingDateFormat(dateTime, format);
1110}
1111
1113{
1114
1115 if (const auto qDateTime = dateTimeFromString(string, v4Engine()))
1116 return formatDateTime(qDateTime.value(), format);
1117
1118 return QString();
1119}
1120
1121#if QT_CONFIG(qml_locale)
1123 QLocale::FormatType formatType) const
1124{
1125 return locale.toString(dateTime, formatType);
1126}
1127
1128QString QtObject::formatDateTime(const QString &string, const QLocale &locale,
1129 QLocale::FormatType formatType) const
1130{
1131
1132 if (const auto qDateTime = dateTimeFromString(string, v4Engine()))
1133 return formatDateTime(qDateTime.value(), locale, formatType);
1134
1135 return QString();
1136}
1137#endif
1138
1151{
1153}
1154
1166{
1167 return url;
1168}
1169
1182{
1183 if (QQmlRefPointer<QQmlContextData> ctxt = v4Engine()->callingQmlContext())
1184 return ctxt->resolvedUrl(url);
1185 if (QQmlEngine *engine = qmlEngine())
1186 return engine->baseUrl().resolved(url);
1187 return url;
1188}
1189
1201{
1202 if (context) {
1204 if (data && data->outerContext)
1205 return data->outerContext->resolvedUrl(url);
1206 }
1207
1208 if (QQmlEngine *engine = qmlEngine())
1209 return engine->baseUrl().resolved(url);
1210 return url;
1211}
1212
1219{
1220 return QQml_guiProvider()->fontFamilies();
1221}
1222
1228{
1230}
1231
1237{
1238 return QLatin1String(data.toUtf8().toBase64());
1239}
1240
1246{
1247 return QString::fromUtf8(QByteArray::fromBase64(data.toLatin1()));
1248}
1249
1261void QtObject::quit() const
1262{
1263 if (QQmlEngine *engine = qmlEngine())
1265}
1266
1279void QtObject::exit(int retCode) const
1280{
1281 if (QQmlEngine *engine = qmlEngine())
1283}
1284
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
1348 if (!context)
1350
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
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) {
1401
1402 obj->setParent(parent);
1403
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
1493{
1495}
1496
1498 QObject *parent) const
1499{
1501 v4Engine()->throwError(QStringLiteral("Invalid compilation mode %1").arg(mode));
1502 return nullptr;
1503 }
1504
1505 if (url.isEmpty())
1506 return nullptr;
1507
1508 QQmlEngine *engine = qmlEngine();
1509 if (!engine)
1510 return nullptr;
1511
1512 auto [context, effectiveContext] = getContexts();
1513 if (!context)
1514 return nullptr;
1515
1516 QQmlComponent *c = new QQmlComponent(engine, context->resolvedUrl(url), mode, parent);
1517 QQmlComponentPrivate::get(c)->creationContext = effectiveContext;
1519 QQmlData::get(c)->indestructible = false;
1520 return c;
1521}
1522
1524 QObject *parent) const
1525{
1527}
1528
1530{
1532 v4Engine()->throwError(QStringLiteral("Invalid compilation mode %1").arg(mode));
1533 return nullptr;
1534 }
1535
1536 QQmlEngine *engine = qmlEngine();
1537 if (!engine)
1538 return nullptr;
1539
1540 if (moduleUri.isEmpty() || typeName.isEmpty())
1541 return nullptr;
1542
1543 auto [context, effectiveContext] = getContexts();
1544 if (!context)
1545 return nullptr;
1546
1547 QQmlComponent *c = new QQmlComponent(engine, moduleUri, typeName, mode, parent);
1548 if (c->isError() && !parent && moduleUri.endsWith(u".qml")) {
1549 v4Engine()->throwTypeError(
1550 QStringLiteral("Invalid arguments; did you swap mode and parent"));
1551 }
1552 QQmlComponentPrivate::get(c)->creationContext = effectiveContext;
1554 QQmlData::get(c)->indestructible = false;
1555 return c;
1556}
1557
1558#if QT_CONFIG(translation)
1559QString QtObject::uiLanguage() const
1560{
1561 if (const QJSEngine *e = jsEngine())
1562 return e->uiLanguage();
1563 return QString();
1564}
1565
1566void QtObject::setUiLanguage(const QString &uiLanguage)
1567{
1568 if (QJSEngine *e = jsEngine())
1569 e->setUiLanguage(uiLanguage);
1570}
1571
1572QBindable<QString> QtObject::uiLanguageBindable()
1573{
1574 if (QJSEngine *e = jsEngine())
1575 return QBindable<QString>(&QJSEnginePrivate::get(e)->uiLanguage);
1576 return QBindable<QString>();
1577}
1578#endif
1579
1580#if QT_CONFIG(qml_locale)
1601QLocale QtObject::locale() const
1602{
1603 return QLocale();
1604}
1605
1606QLocale QtObject::locale(const QString &name) const
1607{
1608 return QLocale(name);
1609}
1610#endif
1611
1612void Heap::QQmlBindingFunction::init(const QV4::FunctionObject *bindingFunction)
1613{
1614 Scope scope(bindingFunction->engine());
1615 ScopedContext context(scope, bindingFunction->scope());
1616 FunctionObject::init(context, bindingFunction->function());
1617 this->bindingFunction.set(internalClass->engine, bindingFunction->d());
1618}
1619
1621{
1623 if (frame->v4Function) // synchronous loading:
1624 return QQmlSourceLocation(frame->source(), frame->lineNumber(), 0);
1625 else // async loading:
1626 return bindingFunction()->function->sourceLocation();
1627}
1628
1630
1673{
1674 const QV4::FunctionObject *f = QJSValuePrivate::asManagedType<FunctionObject>(&function);
1676 if (!f) {
1678 e->throwError(
1680 "binding(): argument (binding expression) must be a function")));
1681 }
1682
1684 Encode(e->memoryManager->allocate<QQmlBindingFunction>(f)));
1685}
1686
1688{
1689 m_engine->delayedCallQueue()->addUniquelyAndExecuteLater(m_engine, args);
1690}
1691
1692
1694{
1695 if (!m_platform)
1696 m_platform = new QQmlPlatform(this);
1697 return m_platform;
1698}
1699
1701{
1702 if (!m_application)
1703 // Only allocate an application object once
1704 m_application = QQml_guiProvider()->application(this);
1705
1706 return m_application;
1707}
1708
1710{
1711 return QQml_guiProvider()->inputMethod();
1712}
1713
1715{
1716 return QQml_guiProvider()->styleHints();
1717}
1718
1720{
1721 Object::init();
1722 QV4::Scope scope(internalClass->engine);
1723 QV4::ScopedObject o(scope, this);
1724
1725 o->defineDefaultProperty(QStringLiteral("debug"), QV4::ConsoleObject::method_log);
1726 o->defineDefaultProperty(QStringLiteral("log"), QV4::ConsoleObject::method_log);
1727 o->defineDefaultProperty(QStringLiteral("info"), QV4::ConsoleObject::method_info);
1728 o->defineDefaultProperty(QStringLiteral("warn"), QV4::ConsoleObject::method_warn);
1729 o->defineDefaultProperty(QStringLiteral("error"), QV4::ConsoleObject::method_error);
1730 o->defineDefaultProperty(QStringLiteral("assert"), QV4::ConsoleObject::method_assert);
1731
1732 o->defineDefaultProperty(QStringLiteral("count"), QV4::ConsoleObject::method_count);
1733 o->defineDefaultProperty(QStringLiteral("profile"), QV4::ConsoleObject::method_profile);
1734 o->defineDefaultProperty(QStringLiteral("profileEnd"), QV4::ConsoleObject::method_profileEnd);
1735 o->defineDefaultProperty(QStringLiteral("time"), QV4::ConsoleObject::method_time);
1736 o->defineDefaultProperty(QStringLiteral("timeEnd"), QV4::ConsoleObject::method_timeEnd);
1737 o->defineDefaultProperty(QStringLiteral("trace"), QV4::ConsoleObject::method_trace);
1738 o->defineDefaultProperty(QStringLiteral("exception"), QV4::ConsoleObject::method_exception);
1739}
1740
1741
1746 Error
1748
1750 QString stack;
1751
1752 QVector<QV4::StackFrame> stackTrace = engine->stackTrace(10);
1753
1754 for (int i = 0; i < stackTrace.size(); i++) {
1755 const QV4::StackFrame &frame = stackTrace.at(i);
1756
1757 QString stackFrame;
1758 if (frame.column >= 0) {
1759 stackFrame = QStringLiteral("%1 (%2:%3:%4)").arg(
1760 frame.function, frame.source,
1762 } else {
1763 stackFrame = QStringLiteral("%1 (%2:%3)").arg(
1764 frame.function, frame.source, QString::number(qAbs(frame.line)));
1765 }
1766
1767 if (i)
1768 stack += QLatin1Char('\n');
1769 stack += stackFrame;
1770 }
1771 return stack;
1772}
1773
1775 Scope scope(v4);
1776 ScopedValue val(scope);
1778
1779 alreadySeen.insert(array->d());
1780 result += QLatin1Char('[');
1781 const uint length = array->getLength();
1782 for (uint i = 0; i < length; ++i) {
1783 if (i != 0)
1784 result += QLatin1Char(',');
1785 val = array->get(i);
1786 if (val->isManaged() && val->managed()->isArrayLike())
1787 if (!alreadySeen.contains(val->objectValue()->d()))
1788 result += serializeArray(val->objectValue(), v4, alreadySeen);
1789 else
1790 result += QLatin1String("[Circular]");
1791 else
1792 result += val->toQStringNoThrow();
1793 }
1794 result += QLatin1Char(']');
1795 alreadySeen.remove(array->d());
1796 return result;
1797};
1798
1799static ReturnedValue writeToConsole(const FunctionObject *b, const Value *argv, int argc,
1800 ConsoleLogTypes logType, bool printStack = false)
1801{
1802 const QLoggingCategory *loggingCategory = nullptr;
1804 QV4::Scope scope(b);
1805 QV4::ExecutionEngine *v4 = scope.engine;
1806
1807 int start = 0;
1808 if (argc > 0) {
1809 if (const QObjectWrapper* wrapper = argv[0].as<QObjectWrapper>()) {
1810 if (QQmlLoggingCategory* category = qobject_cast<QQmlLoggingCategory*>(wrapper->object())) {
1811 if (category->category())
1812 loggingCategory = category->category();
1813 else
1814 THROW_GENERIC_ERROR("A QmlLoggingCatgory was provided without a valid name");
1815 start = 1;
1816 }
1817 }
1818 }
1819
1820
1821 for (int i = start, ei = argc; i < ei; ++i) {
1822 if (i != start)
1823 result.append(QLatin1Char(' '));
1824
1825 QSet<QV4::Heap::Object *> alreadySeenElements;
1826 if (argv[i].isManaged() && argv[i].managed()->isArrayLike())
1827 result.append(serializeArray(argv[i].objectValue(), v4, alreadySeenElements));
1828 else
1829 result.append(argv[i].toQStringNoThrow());
1830 }
1831
1832 if (printStack)
1833 result += QLatin1Char('\n') + jsStack(v4);
1834
1835 if (!loggingCategory)
1836 loggingCategory = v4->qmlEngine() ? &lcQml() : &lcJs();
1838 const QByteArray baSource = frame ? frame->source().toUtf8() : QByteArray();
1839 const QByteArray baFunction = frame ? frame->function().toUtf8() : QByteArray();
1840 QMessageLogger logger(baSource.constData(), frame ? frame->lineNumber() : 0,
1841 baFunction.constData(), loggingCategory->categoryName());
1842
1843 switch (logType) {
1844 case Log:
1845 if (loggingCategory->isDebugEnabled())
1846 logger.debug("%s", result.toUtf8().constData());
1847 break;
1848 case Info:
1849 if (loggingCategory->isInfoEnabled())
1850 logger.info("%s", result.toUtf8().constData());
1851 break;
1852 case Warn:
1853 if (loggingCategory->isWarningEnabled())
1854 logger.warning("%s", result.toUtf8().constData());
1855 break;
1856 case Error:
1857 if (loggingCategory->isCriticalEnabled())
1858 logger.critical("%s", result.toUtf8().constData());
1859 break;
1860 default:
1861 break;
1862 }
1863
1864 return Encode::undefined();
1865}
1866
1868
1870{
1871 return writeToConsole(b, argv, argc, Error);
1872}
1873
1875{
1876 //console.log
1877 //console.debug
1878 //print
1879 return writeToConsole(b, argv, argc, Log);
1880}
1881
1883{
1884 return writeToConsole(b, argv, argc, Info);
1885}
1886
1888{
1889 QV4::Scope scope(b);
1890 QV4::ExecutionEngine *v4 = scope.engine;
1891
1893 const QByteArray baSource = frame->source().toUtf8();
1894 const QByteArray baFunction = frame->function().toUtf8();
1895 QMessageLogger logger(baSource.constData(), frame->lineNumber(), baFunction.constData());
1896 QQmlProfilerService *service = QQmlDebugConnector::service<QQmlProfilerService>();
1897 if (!service) {
1898 logger.warning("Cannot start profiling because debug service is disabled. Start with -qmljsdebugger=port:XXXXX.");
1899 } else {
1900 service->startProfiling(v4->jsEngine());
1901 logger.debug("Profiling started.");
1902 }
1903
1904 return QV4::Encode::undefined();
1905}
1906
1908{
1909 QV4::Scope scope(b);
1910 QV4::ExecutionEngine *v4 = scope.engine;
1911
1913 const QByteArray baSource = frame->source().toUtf8();
1914 const QByteArray baFunction = frame->function().toUtf8();
1915 QMessageLogger logger(baSource.constData(), frame->lineNumber(), baFunction.constData());
1916
1917 QQmlProfilerService *service = QQmlDebugConnector::service<QQmlProfilerService>();
1918 if (!service) {
1919 logger.warning("Ignoring console.profileEnd(): the debug service is disabled.");
1920 } else {
1921 service->stopProfiling(v4->jsEngine());
1922 logger.debug("Profiling ended.");
1923 }
1924
1925 return QV4::Encode::undefined();
1926}
1927
1929{
1930 QV4::Scope scope(b);
1931 if (argc != 1)
1932 THROW_GENERIC_ERROR("console.time(): Invalid arguments");
1933
1934 QString name = argv[0].toQStringNoThrow();
1935 scope.engine->startTimer(name);
1936 return QV4::Encode::undefined();
1937}
1938
1940{
1941 QV4::Scope scope(b);
1942 if (argc != 1)
1943 THROW_GENERIC_ERROR("console.timeEnd(): Invalid arguments");
1944
1945 QString name = argv[0].toQStringNoThrow();
1946 bool wasRunning;
1947 qint64 elapsed = scope.engine->stopTimer(name, &wasRunning);
1948 if (wasRunning) {
1949 qDebug("%s: %llims", qPrintable(name), elapsed);
1950 }
1951 return QV4::Encode::undefined();
1952}
1953
1955{
1956 // first argument: name to print. Ignore any additional arguments
1957 QString name;
1958 if (argc > 0)
1959 name = argv[0].toQStringNoThrow();
1960
1961 Scope scope(b);
1962 QV4::ExecutionEngine *v4 = scope.engine;
1963
1965
1966 QString scriptName = frame->source();
1967
1968 int value = v4->consoleCountHelper(scriptName, frame->lineNumber(), 0);
1970
1971 QMessageLogger(qPrintable(scriptName), frame->lineNumber(),
1972 qPrintable(frame->function()))
1973 .debug("%s", qPrintable(message));
1974
1975 return QV4::Encode::undefined();
1976}
1977
1979{
1980 QV4::Scope scope(b);
1981 if (argc != 0)
1982 THROW_GENERIC_ERROR("console.trace(): Invalid arguments");
1983
1984 QV4::ExecutionEngine *v4 = scope.engine;
1985
1986 QString stack = jsStack(v4);
1987
1989 QMessageLogger(frame->source().toUtf8().constData(), frame->lineNumber(),
1990 frame->function().toUtf8().constData())
1991 .debug("%s", qPrintable(stack));
1992
1993 return QV4::Encode::undefined();
1994}
1995
1997{
1998 return writeToConsole(b, argv, argc, Warn);
1999}
2000
2002{
2003 QV4::Scope scope(b);
2004 if (argc == 0)
2005 THROW_GENERIC_ERROR("console.assert(): Missing argument");
2006
2007 QV4::ExecutionEngine *v4 = scope.engine;
2008
2009 if (!argv[0].toBoolean()) {
2011 for (int i = 1, ei = argc; i < ei; ++i) {
2012 if (i != 1)
2013 message.append(QLatin1Char(' '));
2014
2015 message.append(argv[i].toQStringNoThrow());
2016 }
2017
2018 QString stack = jsStack(v4);
2019
2021 QMessageLogger(frame->source().toUtf8().constData(), frame->lineNumber(),
2022 frame->function().toUtf8().constData())
2023 .critical("%s\n%s",qPrintable(message), qPrintable(stack));
2024
2025 }
2026 return QV4::Encode::undefined();
2027}
2028
2030{
2031 QV4::Scope scope(b);
2032 if (argc == 0)
2033 THROW_GENERIC_ERROR("console.exception(): Missing argument");
2034
2035 return writeToConsole(b, argv, argc, Error, true);
2036}
2037
2038void QV4::GlobalExtensions::init(Object *globalObject, QJSEngine::Extensions extensions)
2039{
2040 ExecutionEngine *v4 = globalObject->engine();
2041 Scope scope(v4);
2042
2043 if (extensions.testFlag(QJSEngine::TranslationExtension)) {
2044 #if QT_CONFIG(translation)
2045 globalObject->defineDefaultProperty(QStringLiteral("qsTranslate"), QV4::GlobalExtensions::method_qsTranslate);
2046 globalObject->defineDefaultProperty(QStringLiteral("QT_TRANSLATE_NOOP"), QV4::GlobalExtensions::method_qsTranslateNoOp);
2047 globalObject->defineDefaultProperty(QStringLiteral("qsTr"), QV4::GlobalExtensions::method_qsTr);
2048 globalObject->defineDefaultProperty(QStringLiteral("QT_TR_NOOP"), QV4::GlobalExtensions::method_qsTrNoOp);
2049 globalObject->defineDefaultProperty(QStringLiteral("qsTrId"), QV4::GlobalExtensions::method_qsTrId);
2050 globalObject->defineDefaultProperty(QStringLiteral("QT_TRID_NOOP"), QV4::GlobalExtensions::method_qsTrIdNoOp);
2051
2052 // Initialize the Qt global object for the uiLanguage property
2053 ScopedString qtName(scope, v4->newString(QStringLiteral("Qt")));
2054 ScopedObject qt(scope, globalObject->get(qtName));
2055 if (!qt)
2056 v4->createQtObject();
2057
2058 // string prototype extension
2060 #endif
2061 }
2062
2063 if (extensions.testFlag(QJSEngine::ConsoleExtension)) {
2064 globalObject->defineDefaultProperty(QStringLiteral("print"), QV4::ConsoleObject::method_log);
2065
2066
2067 QV4::ScopedObject console(scope, globalObject->engine()->memoryManager->allocate<QV4::ConsoleObject>());
2068 globalObject->defineDefaultProperty(QStringLiteral("console"), console);
2069 }
2070
2071 if (extensions.testFlag(QJSEngine::GarbageCollectionExtension)) {
2072 globalObject->defineDefaultProperty(QStringLiteral("gc"), QV4::GlobalExtensions::method_gc);
2073 }
2074}
2075
2076
2077#if QT_CONFIG(translation)
2095ReturnedValue GlobalExtensions::method_qsTranslate(const FunctionObject *b, const Value *, const Value *argv, int argc)
2096{
2097 QV4::Scope scope(b);
2098 if (argc < 2)
2099 THROW_GENERIC_ERROR("qsTranslate() requires at least two arguments");
2100 if (!argv[0].isString())
2101 THROW_GENERIC_ERROR("qsTranslate(): first argument (context) must be a string");
2102 if (!argv[1].isString())
2103 THROW_GENERIC_ERROR("qsTranslate(): second argument (sourceText) must be a string");
2104 if ((argc > 2) && !argv[2].isString())
2105 THROW_GENERIC_ERROR("qsTranslate(): third argument (disambiguation) must be a string");
2106
2107 QString context = argv[0].toQStringNoThrow();
2108 QString text = argv[1].toQStringNoThrow();
2109 QString comment;
2110 if (argc > 2) comment = argv[2].toQStringNoThrow();
2111
2112 int i = 3;
2113 if (argc > i && argv[i].isString()) {
2114 qWarning("qsTranslate(): specifying the encoding as fourth argument is deprecated");
2115 ++i;
2116 }
2117
2118 int n = -1;
2119 if (argc > i)
2120 n = argv[i].toInt32();
2121
2122 if (QQmlEnginePrivate *ep = (scope.engine->qmlEngine() ? QQmlEnginePrivate::get(scope.engine->qmlEngine()) : nullptr))
2123 if (ep->propertyCapture)
2124 ep->propertyCapture->captureTranslation();
2125
2126 QString result = QCoreApplication::translate(context.toUtf8().constData(),
2127 text.toUtf8().constData(),
2128 comment.toUtf8().constData(),
2129 n);
2130
2131 return Encode(scope.engine->newString(result));
2132}
2133
2156ReturnedValue GlobalExtensions::method_qsTranslateNoOp(const FunctionObject *b, const Value *, const Value *argv, int argc)
2157{
2158 QV4::Scope scope(b);
2159 if (argc < 2)
2160 return QV4::Encode::undefined();
2161 else
2162 return argv[1].asReturnedValue();
2163}
2164
2165QString GlobalExtensions::currentTranslationContext(ExecutionEngine *engine)
2166{
2168 CppStackFrame *frame = engine->currentStackFrame;
2169
2170 // The first non-empty source URL in the call stack determines the translation context.
2171 while (frame && context.isEmpty()) {
2172 if (CompiledData::CompilationUnitBase *baseUnit = frame->v4Function->compilationUnit) {
2173 const auto *unit = static_cast<const CompiledData::CompilationUnit *>(baseUnit);
2174 QString fileName = unit->fileName();
2175 QUrl url(unit->fileName());
2176 if (url.isValid() && url.isRelative()) {
2177 context = url.fileName();
2178 } else {
2180 if (context.isEmpty() && fileName.startsWith(QLatin1String(":/")))
2181 context = fileName;
2182 }
2184 }
2185 frame = frame->parentFrame();
2186 }
2187
2188 if (context.isEmpty()) {
2189 if (QQmlRefPointer<QQmlContextData> ctxt = engine->callingQmlContext()) {
2190 QString path = ctxt->urlString();
2191 int lastSlash = path.lastIndexOf(QLatin1Char('/'));
2192 int lastDot = path.lastIndexOf(QLatin1Char('.'));
2193 int length = lastDot - (lastSlash + 1);
2194 context = (lastSlash > -1) ? path.mid(lastSlash + 1, (length > -1) ? length : -1) : QString();
2195 }
2196 }
2197
2198 return context;
2199}
2200
2218ReturnedValue GlobalExtensions::method_qsTr(const FunctionObject *b, const Value *, const Value *argv, int argc)
2219{
2220 QV4::Scope scope(b);
2221 if (argc < 1)
2222 THROW_GENERIC_ERROR("qsTr() requires at least one argument");
2223 if (!argv[0].isString())
2224 THROW_GENERIC_ERROR("qsTr(): first argument (sourceText) must be a string");
2225 if ((argc > 1) && !argv[1].isString())
2226 THROW_GENERIC_ERROR("qsTr(): second argument (disambiguation) must be a string");
2227 if ((argc > 2) && !argv[2].isNumber())
2228 THROW_GENERIC_ERROR("qsTr(): third argument (n) must be a number");
2229
2230 const QString context = currentTranslationContext(scope.engine);
2231 const QString text = argv[0].toQStringNoThrow();
2232 const QString comment = argc > 1 ? argv[1].toQStringNoThrow() : QString();
2233 const int n = argc > 2 ? argv[2].toInt32() : -1;
2234
2235 if (QQmlEnginePrivate *ep = (scope.engine->qmlEngine() ? QQmlEnginePrivate::get(scope.engine->qmlEngine()) : nullptr))
2236 if (ep->propertyCapture)
2237 ep->propertyCapture->captureTranslation();
2238
2240 comment.toUtf8().constData(), n);
2241
2242 return Encode(scope.engine->newString(result));
2243}
2244
2267ReturnedValue GlobalExtensions::method_qsTrNoOp(const FunctionObject *, const Value *, const Value *argv, int argc)
2268{
2269 if (argc < 1)
2270 return QV4::Encode::undefined();
2271 else
2272 return argv[0].asReturnedValue();
2273}
2274
2305ReturnedValue GlobalExtensions::method_qsTrId(const FunctionObject *b, const Value *, const Value *argv, int argc)
2306{
2307 QV4::Scope scope(b);
2308 if (argc < 1)
2309 THROW_GENERIC_ERROR("qsTrId() requires at least one argument");
2310 if (!argv[0].isString())
2311 THROW_TYPE_ERROR_WITH_MESSAGE("qsTrId(): first argument (id) must be a string");
2312 if (argc > 1 && !argv[1].isNumber())
2313 THROW_TYPE_ERROR_WITH_MESSAGE("qsTrId(): second argument (n) must be a number");
2314
2315 int n = -1;
2316 if (argc > 1)
2317 n = argv[1].toInt32();
2318
2319 if (QQmlEnginePrivate *ep = (scope.engine->qmlEngine() ? QQmlEnginePrivate::get(scope.engine->qmlEngine()) : nullptr))
2320 if (ep->propertyCapture)
2321 ep->propertyCapture->captureTranslation();
2322
2323 return Encode(scope.engine->newString(qtTrId(argv[0].toQStringNoThrow().toUtf8().constData(), n)));
2324}
2325
2342ReturnedValue GlobalExtensions::method_qsTrIdNoOp(const FunctionObject *, const Value *, const Value *argv, int argc)
2343{
2344 if (argc < 1)
2345 return QV4::Encode::undefined();
2346 else
2347 return argv[0].asReturnedValue();
2348}
2349#endif // translation
2350
2351
2353{
2354 b->engine()->memoryManager->runGC();
2355
2356 return QV4::Encode::undefined();
2357}
2358
2359
2360
2361ReturnedValue GlobalExtensions::method_string_arg(const FunctionObject *b, const Value *thisObject, const Value *argv, int argc)
2362{
2363 QV4::Scope scope(b);
2364 if (argc != 1)
2365 THROW_GENERIC_ERROR("String.arg(): Invalid arguments");
2366
2367 QString value = thisObject->toQString();
2368
2369 QV4::ScopedValue arg(scope, argv[0]);
2370 if (arg->isInteger())
2371 RETURN_RESULT(scope.engine->newString(value.arg(arg->integerValue())));
2372 else if (arg->isDouble())
2373 RETURN_RESULT(scope.engine->newString(value.arg(arg->doubleValue())));
2374 else if (arg->isBoolean())
2375 RETURN_RESULT(scope.engine->newString(value.arg(arg->booleanValue())));
2376
2377 RETURN_RESULT(scope.engine->newString(value.arg(arg->toQString())));
2378}
2379
2402
2403#include "moc_qqmlbuiltinfunctions_p.cpp"
Definition main.cpp:8
\inmodule QtCore
Definition qproperty.h:809
\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:122
static QByteArray fromBase64(const QByteArray &base64, Base64Options options=Base64Encoding)
QByteArray toHex(char separator='\0') const
Returns a hex encoded copy of the byte array.
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:257
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:27
constexpr bool isValid() const
Returns true if this date is valid; otherwise returns false.
Definition qdatetime.h:86
\inmodule QtCore \reentrant
Definition qfileinfo.h:22
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:292
void throwError(const QString &message)
Throws a run-time error (exception) with the given message.
@ ConsoleExtension
Definition qjsengine.h:281
@ TranslationExtension
Definition qjsengine.h:280
@ GarbageCollectionExtension
Definition qjsengine.h:282
static QJSValue fromReturnedValue(QV4::ReturnedValue d)
Definition qjsvalue_p.h:189
The QJSValue class acts as a container for Qt/JavaScript data types.
Definition qjsvalue.h:31
bool isObject() const
Returns true if this QJSValue is of the Object type; otherwise returns false.
Definition qjsvalue.cpp:434
Definition qlist.h:74
qsizetype size() const noexcept
Definition qlist.h:386
const_reference at(qsizetype i) const noexcept
Definition qlist.h:429
\inmodule QtCore
bool isInfoEnabled() const
Returns true if informational messages should be shown for this category; false otherwise.
bool isWarningEnabled() const
Returns true if warning messages should be shown for this category; false otherwise.
bool isCriticalEnabled() const
Returns true if critical messages should be shown for this category; false otherwise.
const char * categoryName() const
Returns the name of the category.
bool isDebugEnabled() const
Returns true if debug messages should be shown for this category; false otherwise.
\inmodule QtCore
Definition qlogging.h:68
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:648
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:764
void debug(const char *msg,...) const Q_ATTRIBUTE_FORMAT_PRINTF(2
Logs a debug message specified with format msg.
Definition qlogging.cpp:385
\inmodule QtCore
Definition qmetatype.h:320
\inmodule QtCore
Definition qobject.h:90
QObject * parent() const
Returns a pointer to the parent object.
Definition qobject.h:311
\inmodule QtCore\reentrant
Definition qpoint.h:214
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)
QQmlGuardedContextData creationContext
void fromTypeData(const QQmlRefPointer< QQmlTypeData > &data)
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.
quint32 explicitIndestructibleSet
Definition qqmldata_p.h:95
static QQmlData * get(QObjectPrivate *priv, bool create)
Definition qqmldata_p.h:199
quint32 indestructible
Definition qqmldata_p.h:92
void sendExit(int retCode=0)
QQmlTypeLoader typeLoader
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 QFile.
Definition qqmlfile.cpp:643
virtual bool openUrlExternally(const QUrl &)
virtual QStringList fontFamilies()
virtual QQmlApplication * application(QObject *parent)
virtual QObject * styleHints()
virtual QObject * inputMethod()
static QList< QQmlPrivate::AutoParentFunction > parentFunctions()
QQmlRefPointer< QQmlTypeData > getType(const QUrl &unNormalizedUrl, Mode mode=PreferSynchronous)
Returns a QQmlTypeData for the specified url.
static QVariant createValueType(const QJSValue &, QMetaType)
\inmodule QtCore\reentrant
Definition qrect.h:483
Definition qset.h:18
bool remove(const T &value)
Definition qset.h:63
bool contains(const T &value) const
Definition qset.h:71
iterator insert(const T &value)
Definition qset.h:155
\inmodule QtCore
Definition qsize.h:207
\inmodule QtCore
\macro QT_RESTRICTED_CAST_FROM_ASCII
Definition qstring.h:127
qsizetype lastIndexOf(QChar c, Qt::CaseSensitivity cs=Qt::CaseSensitive) const noexcept
Definition qstring.h:279
static QString fromUtf8(QByteArrayView utf8)
This is an overloaded member function, provided for convenience. It differs from the above function o...
Definition qstring.cpp:5857
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:5350
bool isEmpty() const
Returns true if the string has no characters; otherwise returns false.
Definition qstring.h:1083
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:7822
QByteArray toUtf8() const &
Definition qstring.h:563
\inmodule QtCore \reentrant
Definition qdatetime.h:189
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:2494
bool isRelative() const
Returns true if the URL is relative; otherwise returns false.
Definition qurl.cpp:2797
bool isValid() const
Returns true if the URL is non-empty and valid; otherwise returns false.
Definition qurl.cpp:1874
bool isEmpty() const
Returns true if the URL has no data; otherwise returns false.
Definition qurl.cpp:1888
static QJSValue method_include(QV4::ExecutionEngine *engine, const QUrl &url, const QJSValue &callbackFunction)
\inmodule QtCore
Definition qvariant.h:64
bool isValid() const
Returns true if the storage type of this variant is not QMetaType::UnknownType; otherwise returns fal...
Definition qvariant.h:707
int userType() const
Definition qvariant.h:336
QString toString() const
Returns the variant as a QString if the variant has a userType() including, but not limited to:
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:531
Q_INVOKABLE QVariant darker(const QJSValue &color, double factor=2.0) const
\qmlmethod color Qt::darker(color baseColor, real factor)
Q_INVOKABLE QString formatDate(const QDate &date, const QString &format) const
QObject * inputMethod
Q_INVOKABLE bool colorEqual(const QVariant &lhs, const QVariant &rhs) const
\qmlmethod color Qt::colorEqual(color lhs, string rhs)
Q_INVOKABLE void callLater(QQmlV4Function *args)
Q_INVOKABLE QVariant font(const QJSValue &fontSpecifier) const
\qmlmethod font Qt::font(object fontSpecifier)
Q_INVOKABLE QString formatTime(const QTime &time, const QString &format) const
Q_INVOKABLE bool isQtObject(const QJSValue &value) const
\qmlmethod bool Qt::isQtObject(object)
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 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]
double e
QJSManagedValue managed(std::move(val), &engine)
Q_QML_PRIVATE_EXPORT QV4::ReturnedValue locale(QV4::ExecutionEngine *engine, const QString &localeName)
Provides locale specific properties and formatted data.
Q_QML_PRIVATE_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)
\qmltype Particle \inqmlmodule QtQuick.Particles
quint64 ReturnedValue
DateFormat
@ RFC2822Date
@ ISODate
@ ISODateWithMs
@ TextDate
static void * context
DBusConnection const char DBusError DBusBusType DBusError return DBusConnection DBusHandleMessageFunction function
DBusConnection const char DBusError * error
EGLOutputLayerEXT EGLint EGLAttrib value
[5]
static QV4::ExecutionEngine * v4Engine(QV4::Value *d)
#define qDebug
[1]
Definition qlogging.h:160
#define qWarning
Definition qlogging.h:162
#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
GLfloat GLfloat f
GLint GLsizei width
GLenum type
GLint GLfloat GLfloat v1
GLuint GLsizei const GLchar * message
GLint GLsizei GLsizei GLenum GLenum GLsizei void * data
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]
const GLubyte * c
GLuint GLfloat * val
GLenum array
GLsizei const GLchar *const * path
GLuint64EXT * result
[6]
GLdouble s
[6]
Definition qopenglext.h:235
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:1391
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:29
long long qint64
Definition qtypes.h:55
#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:17
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()
CppStackFrame * currentStackFrame
QQmlRefPointer< QQmlContextData > callingQmlContext() const
Heap::String * newString(const QString &s=QString())
Object * stringPrototype() const
ReturnedValue throwError(const Value &value)
Heap::Object * newObject()
int consoleCountHelper(const QString &file, quint16 line, quint16 column)
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)
Function * function() const
Heap::ExecutionContext * scope() const
static void init(Object *globalObject, QJSEngine::Extensions extensions)
static ReturnedValue method_gc(const FunctionObject *b, const Value *thisObject, const Value *argv, int argc)
static ReturnedValue method_string_arg(const FunctionObject *b, const Value *thisObject, const Value *argv, int argc)
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::FunctionObject * bindingFunction() const
ExecutionEngine * engine
QML_NEARLY_ALWAYS_INLINE ReturnedValue asReturnedValue() const
constexpr ReturnedValue asReturnedValue() const
static constexpr Value fromInt32(int i)
Definition qv4value_p.h:187
int toInt32() const
Definition qv4value_p.h:350
bool toBoolean() const
Definition qv4value_p.h:97
QString toQString() const
Definition qv4value.cpp:158
QString toQStringNoThrow() const
Definition qv4value.cpp:122
void wrapper()
IUIAutomationTreeWalker __RPC__deref_out_opt IUIAutomationElement ** parent