7#include <private/qqmlcomponent_p.h>
8#include <private/qqmldebugconnector_p.h>
9#include <private/qqmldebugserviceinterfaces_p.h>
10#include <private/qqmldelayedcallqueue_p.h>
11#include <private/qqmlengine_p.h>
12#include <private/qqmlloggingcategorybase_p.h>
13#include <private/qqmlplatform_p.h>
14#include <private/qqmlstringconverters_p.h>
16#include <private/qv4dateobject_p.h>
17#include <private/qv4domerrors_p.h>
18#include <private/qv4engine_p.h>
19#include <private/qv4functionobject_p.h>
20#include <private/qv4include_p.h>
21#include <private/qv4mm_p.h>
22#include <private/qv4qobjectwrapper_p.h>
23#include <private/qv4sequenceobject_p.h>
24#include <private/qv4stackframe_p.h>
26#include <QtQml/qqmlfile.h>
28#include <QtCore/qcoreapplication.h>
29#include <QtCore/qcryptographichash.h>
30#include <QtCore/qdatetime.h>
31#include <QtCore/qfileinfo.h>
32#include <QtCore/qloggingcategory.h>
33#include <QtCore/qpoint.h>
34#include <QtCore/qrect.h>
35#include <QtCore/qsize.h>
36#include <QtCore/qstring.h>
37#include <QtCore/qurl.h>
38#include <QtCore/qvarlengtharray.h>
42Q_STATIC_LOGGING_CATEGORY(lcRootProperties,
"qt.qml.rootObjectProperties");
48#define THROW_TYPE_ERROR_WITH_MESSAGE(msg)
50 return scope.engine->throwTypeError(QString::fromUtf8(msg));
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
210
211
212
213
214
215
216
217
218
221
222
223
224
225
226
227
228
229
230
231
232
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
268QtObject::QtObject(ExecutionEngine *engine)
271#if QT_CONFIG(translation)
272 connect(m_engine->jsEngine(), &QJSEngine::uiLanguageChanged,
273 this, &QtObject::uiLanguageChanged);
277QtObject::Contexts QtObject::getContexts()
const
279 QQmlEngine *engine = qmlEngine();
283 QQmlRefPointer<QQmlContextData> context = v4Engine()->callingQmlContext();
285 context = QQmlContextData::get(QQmlEnginePrivate::get(engine)->rootContext);
288 QQmlRefPointer<QQmlContextData> effectiveContext
289 = context->isPragmaLibraryContext() ?
nullptr : context;
290 return {context, effectiveContext};
293QtObject *QtObject::create(QQmlEngine *, QJSEngine *jsEngine)
295 QV4::ExecutionEngine *v4 = jsEngine->handle();
296 QV4::Scope scope(v4);
297 ScopedObject globalObject(scope, v4->globalObject);
298 ScopedString qtName(scope, v4->newString(QStringLiteral(
"Qt")));
299 QV4::ScopedValue result(scope, globalObject->get(qtName->toPropertyKey()));
300 return qobject_cast<QtObject *>(result->as<QV4::QObjectWrapper>()->object());
303QJSValue QtObject::include(
const QString &url,
const QJSValue &callback)
const
305 return QV4Include::method_include(v4Engine(), v4Engine()->resolvedUrl(url), callback);
310
311
312
313
314
315bool QtObject::isQtObject(
const QJSValue &value)
const
317 return qjsvalue_cast<QObject *>(value) !=
nullptr;
321
322
323
324
325
326
327
328QVariant QtObject::color(
const QString &name)
const
331 const QVariant v = QQmlStringConverters::colorFromString(name, &ok);
335 v4Engine()->throwError(QStringLiteral(
"\"%1\" is not a valid color name").arg(name));
336 return QVariant::fromValue(
nullptr);
340
341
342
343
344
345
346
347QVariant QtObject::rgba(
double r,
double g,
double b,
double a)
const
349 r = qBound(0.0, r, 1.0);
350 g = qBound(0.0, g, 1.0);
351 b = qBound(0.0, b, 1.0);
352 a = qBound(0.0, a, 1.0);
354 return QQml_colorProvider()->fromRgbF(r, g, b, a);
358
359
360
361
362
363
364
365QVariant QtObject::hsla(
double h,
double s,
double l,
double a)
const
368 h = qBound(0.0, h, 1.0);
369 s = qBound(0.0, s, 1.0);
370 l = qBound(0.0, l, 1.0);
371 a = qBound(0.0, a, 1.0);
373 return QQml_colorProvider()->fromHslF(h, s, l, a);
377
378
379
380
381
382
383
384
385QVariant QtObject::hsva(
double h,
double s,
double v,
double a)
const
388 h = qBound(0.0, h, 1.0);
389 s = qBound(0.0, s, 1.0);
390 v = qBound(0.0, v, 1.0);
391 a = qBound(0.0, a, 1.0);
393 return QQml_colorProvider()->fromHsvF(h, s, v, a);
397
398
399
400
401
402
403
404
405
406bool QtObject::colorEqual(
const QVariant &lhs,
const QVariant &rhs)
const
410 QVariant color1 = lhs;
411 if (color1.userType() == QMetaType::QString) {
412 color1 = QQmlStringConverters::colorFromString(color1.toString(), &ok);
414 v4Engine()->throwError(QStringLiteral(
"Qt.colorEqual(): Invalid color name"));
417 }
else if (color1.userType() != QMetaType::QColor) {
418 v4Engine()->throwError(QStringLiteral(
"Qt.colorEqual(): Invalid arguments"));
422 QVariant color2 = rhs;
423 if (color2.userType() == QMetaType::QString) {
424 color2 = QQmlStringConverters::colorFromString(color2.toString(), &ok);
426 v4Engine()->throwError(QStringLiteral(
"Qt.colorEqual(): Invalid color name"));
429 }
else if (color2.userType() != QMetaType::QColor) {
430 v4Engine()->throwError(QStringLiteral(
"Qt.colorEqual(): Invalid arguments"));
434 return color1 == color2;
438
439
440
441
442QRectF QtObject::rect(
double x,
double y,
double width,
double height)
const
444 return QRectF(x, y, width, height);
448
449
450
451
452QPointF QtObject::point(
double x,
double y)
const
454 return QPointF(x, y);
458
459
460
461
462QSizeF QtObject::size(
double w,
double h)
const
468
469
470
471
472
473
474
475
476QVariant QtObject::font(
const QJSValue &fontSpecifier)
const
478 if (!fontSpecifier.isObject()) {
479 v4Engine()->throwError(QStringLiteral(
"Qt.font(): Invalid arguments"));
484 const QVariant v = QQmlValueTypeProvider::createValueType(
485 fontSpecifier, QMetaType(QMetaType::QFont));
490 v4Engine()->throwError(QStringLiteral(
"Qt.font(): Invalid argument: "
491 "no valid font subproperties specified"));
498 result.setProperty(i, e->toScriptValue(parameter));
502void addParameters<
double>(QJSEngine *, QJSValue &result,
int i,
double parameter)
504 result.setProperty(i, QJSValue(parameter));
507template<
typename T,
typename ...Others>
508void addParameters(QJSEngine *e, QJSValue &result,
int i, T parameter, Others... others)
510 addParameters<T>(e, result, i, parameter);
511 addParameters<Others...>(e, result, ++i, others...);
514template<
typename ...T>
519 QJSValue params = e->newArray(
sizeof...(parameters));
520 addParameters(e, params, 0, parameters...);
521 const QVariant variant = QQmlValueTypeProvider::createValueType(params, type);
522 return variant.isValid() ? variant : QVariant(type);
526
527
528
529
530QVariant QtObject::vector2d(
double x,
double y)
const
532 return constructFromJSValue(jsEngine(), QMetaType(QMetaType::QVector2D), x, y);
536
537
538
539
540QVariant QtObject::vector3d(
double x,
double y,
double z)
const
542 return constructFromJSValue(jsEngine(), QMetaType(QMetaType::QVector3D), x, y, z);
546
547
548
549
550QVariant QtObject::vector4d(
double x,
double y,
double z,
double w)
const
552 return constructFromJSValue(jsEngine(), QMetaType(QMetaType::QVector4D), x, y, z, w);
556
557
558
559
560QVariant QtObject::quaternion(
double scalar,
double x,
double y,
double z)
const
562 return constructFromJSValue(jsEngine(), QMetaType(QMetaType::QQuaternion), scalar, x, y, z);
566
567
568
569
570QVariant QtObject::matrix4x4()
const
572 const QMetaType metaType(QMetaType::QMatrix4x4);
573 const QVariant variant = QQmlValueTypeProvider::createValueType(QJSValue(), metaType);
574 return variant.isValid() ? variant : QVariant(metaType);
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592QVariant QtObject::matrix4x4(
const QJSValue &value)
const
594 if (value.isObject()) {
595 QVariant v = QQmlValueTypeProvider::createValueType(
596 value, QMetaType(QMetaType::QMatrix4x4));
601 v4Engine()->throwError(QStringLiteral(
"Qt.matrix4x4(): Invalid argument: "
602 "not a valid matrix4x4 values array"));
607
608
609
610
611
612
613
614
615
616
617
618
619
620QVariant QtObject::matrix4x4(
double m11,
double m12,
double m13,
double m14,
621 double m21,
double m22,
double m23,
double m24,
622 double m31,
double m32,
double m33,
double m34,
623 double m41,
double m42,
double m43,
double m44)
const
625 return constructFromJSValue(jsEngine(), QMetaType(QMetaType::QMatrix4x4),
626 m11, m12, m13, m14, m21, m22, m23, m24,
627 m31, m32, m33, m34, m41, m42, m43, m44);
633 if (color.isString()) {
634 v = QQmlStringConverters::colorFromString(color.toString(), ok);
636 return QVariant::fromValue(
nullptr);
638 v = color.toVariant();
639 if (v.userType() != QMetaType::QColor) {
641 return QVariant::fromValue(
nullptr);
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666QVariant QtObject::lighter(
const QJSValue &color,
double factor)
const
669 const QVariant v = colorVariantFromJSValue(color, &ok);
670 return ok ? QQml_colorProvider()->lighter(v, factor) : v;
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691QVariant QtObject::darker(
const QJSValue &color,
double factor)
const
694 const QVariant v = colorVariantFromJSValue(color, &ok);
695 return ok ? QQml_colorProvider()->darker(v, factor) : v;
699
700
701
702
703
704
705
706
707QVariant QtObject::alpha(
const QJSValue &baseColor,
double value)
const
710 const QVariant v = colorVariantFromJSValue(baseColor, &ok);
711 return ok ? QQml_colorProvider()->alpha(v, value) : v;
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743QVariant QtObject::tint(
const QJSValue &baseColor,
const QJSValue &tintColor)
const
748 const QVariant v1 = colorVariantFromJSValue(baseColor, &ok);
753 const QVariant v2 = colorVariantFromJSValue(tintColor, &ok);
755 return ok ? QQml_colorProvider()->tint(v1, v2) : v2;
760QString formatDateTimeObjectUsingDateFormat(T formatThis, Qt::DateFormat format) {
764 case Qt::RFC2822Date:
765 case Qt::ISODateWithMs:
766 return formatThis.toString(format);
777 return dateTime.toLocalTime().time();
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
799 const QDate date = QDate::fromString(string, Qt::ISODate);
806 const QDateTime dateTime = QDateTime::fromString(string, Qt::ISODate);
807 if (dateTime.isValid()) {
808 qCWarning(lcRootProperties())
809 << string <<
"is a date/time string being passed to formatDate()."
810 <<
"You should only pass date strings to formatDate().";
811 return dateTime.date();
817 const QDateTime dateTime = DateObject::stringToDateTime(string, engine);
818 if (dateTime.isValid())
819 return DateObject::dateTimeToDate(dateTime);
822 engine->throwError(QStringLiteral(
"Invalid argument passed to formatDate(): %1").arg(string));
826QString QtObject::formatDate(QDate date,
const QString &format)
const
828 return date.toString(format);
831QString QtObject::formatDate(QDate date, Qt::DateFormat format)
const
833 return formatDateTimeObjectUsingDateFormat(date, format);
836QString QtObject::formatDate(
const QDateTime &dateTime,
const QString &format)
const
838 return DateObject::dateTimeToDate(dateTime).toString(format);
841QString QtObject::formatDate(
const QString &string,
const QString &format)
const
843 if (
const auto qDate = dateFromString(string, v4Engine()))
844 return formatDate(qDate.value(), format);
849QString QtObject::formatDate(
const QDateTime &dateTime, Qt::DateFormat format)
const
851 return formatDateTimeObjectUsingDateFormat(DateObject::dateTimeToDate(dateTime), format);
854QString QtObject::formatDate(
const QString &string, Qt::DateFormat format)
const
856 if (
const auto qDate = dateFromString(string, v4Engine()))
857 return formatDate(qDate.value(), format);
862#if QT_CONFIG(qml_locale)
863QString QtObject::formatDate(QDate date,
const QLocale &locale,
864 QLocale::FormatType formatType)
const
866 return locale.toString(date, formatType);
869QString QtObject::formatDate(
const QDateTime &dateTime,
const QLocale &locale,
870 QLocale::FormatType formatType)
const
872 return locale.toString(DateObject::dateTimeToDate(dateTime), formatType);
875QString QtObject::formatDate(
const QString &string,
const QLocale &locale,
876 QLocale::FormatType formatType)
const
878 if (
const auto qDate = dateFromString(string, v4Engine()))
879 return locale.toString(qDate.value(), formatType);
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
904 const QTime time = QTime::fromString(string, Qt::ISODate);
911 const QDateTime dateTime = QDateTime::fromString(string, Qt::ISODate);
912 if (dateTime.isValid()) {
913 qCWarning(lcRootProperties())
914 << string <<
"is a date/time string being passed to formatTime()."
915 <<
"You should only pass time strings to formatTime().";
916 return dateTime.time();
922 const QDateTime dateTime = DateObject::stringToDateTime(string, engine);
923 if (dateTime.isValid())
924 return dateTimeToTime(dateTime);
927 engine->throwError(QStringLiteral(
"Invalid argument passed to formatTime(): %1").arg(string));
931QString QtObject::formatTime(QTime time,
const QString &format)
const
933 return time.toString(format);
936QString QtObject::formatTime(
const QDateTime &dateTime,
const QString &format)
const
938 return dateTimeToTime(dateTime).toString(format);
941QString QtObject::formatTime(
const QString &time,
const QString &format)
const
944 if (
auto qTime = timeFromString(time, v4Engine()))
945 return formatTime(qTime.value(), format);
950QString QtObject::formatTime(QTime time, Qt::DateFormat format)
const
952 return formatDateTimeObjectUsingDateFormat(time, format);
955QString QtObject::formatTime(
const QDateTime &dateTime, Qt::DateFormat format)
const
957 return formatDateTimeObjectUsingDateFormat(dateTimeToTime(dateTime), format);
960QString QtObject::formatTime(
const QString &time, Qt::DateFormat format)
const
962 if (
auto qTime = timeFromString(time, v4Engine()))
963 return formatTime(qTime.value(), format);
968#if QT_CONFIG(qml_locale)
969QString QtObject::formatTime(QTime time,
const QLocale &locale,
970 QLocale::FormatType formatType)
const
972 return locale.toString(time, formatType);
975QString QtObject::formatTime(
const QDateTime &dateTime,
const QLocale &locale,
976 QLocale::FormatType formatType)
const
978 return locale.toString(dateTimeToTime(dateTime), formatType);
981QString QtObject::formatTime(
const QString &time,
const QLocale &locale,
982 QLocale::FormatType formatType)
const
984 if (
auto qTime = timeFromString(time, v4Engine()))
985 return locale.toString(qTime.value(), formatType);
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1092 const QDateTime dateTime = QDateTime::fromString(string, Qt::ISODate);
1093 if (dateTime.isValid())
1099 const QDateTime dateTime = DateObject::stringToDateTime(string, engine);
1100 if (dateTime.isValid())
1104 engine->throwError(QStringLiteral(
"Invalid argument passed to formatDateTime(): %1").arg(string));
1105 return std::nullopt;
1108QString QtObject::formatDateTime(
const QDateTime &dateTime,
const QString &format)
const
1110 return dateTime.toString(format);
1113QString QtObject::formatDateTime(
const QString &string,
const QString &format)
const
1116 if (
const auto qDateTime = dateTimeFromString(string, v4Engine()))
1117 return formatDateTime(qDateTime.value(), format);
1122QString QtObject::formatDateTime(
const QDateTime &dateTime, Qt::DateFormat format)
const
1124 return formatDateTimeObjectUsingDateFormat(dateTime, format);
1127QString QtObject::formatDateTime(
const QString &string, Qt::DateFormat format)
const
1130 if (
const auto qDateTime = dateTimeFromString(string, v4Engine()))
1131 return formatDateTime(qDateTime.value(), format);
1136#if QT_CONFIG(qml_locale)
1137QString QtObject::formatDateTime(
const QDateTime &dateTime,
const QLocale &locale,
1138 QLocale::FormatType formatType)
const
1140 return locale.toString(dateTime, formatType);
1143QString QtObject::formatDateTime(
const QString &string,
const QLocale &locale,
1144 QLocale::FormatType formatType)
const
1147 if (
const auto qDateTime = dateTimeFromString(string, v4Engine()))
1148 return formatDateTime(qDateTime.value(), locale, formatType);
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165bool QtObject::openUrlExternally(
const QUrl &url)
const
1167 return QQml_guiProvider()->openUrlExternally(resolvedUrl(url));
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180QUrl QtObject::url(
const QUrl &url)
const
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196QUrl QtObject::resolvedUrl(
const QUrl &url)
const
1198 if (QQmlRefPointer<QQmlContextData> ctxt = v4Engine()->callingQmlContext())
1199 return ctxt->resolvedUrl(url);
1200 if (QQmlEngine *engine = qmlEngine())
1201 return engine->baseUrl().resolved(url);
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215QUrl QtObject::resolvedUrl(
const QUrl &url, QObject *context)
const
1218 QQmlData *data = QQmlData::get(context);
1219 if (data && data->outerContext)
1220 return data->outerContext->resolvedUrl(url);
1223 if (QQmlEngine *engine = qmlEngine())
1224 return engine->baseUrl().resolved(url);
1229
1230
1231
1232
1233QStringList QtObject::fontFamilies()
const
1235 return QQml_guiProvider()->fontFamilies();
1239
1240
1241
1242QString QtObject::md5(
const QString &data)
const
1244 return QLatin1String(QCryptographicHash::hash(data.toUtf8(), QCryptographicHash::Md5).toHex());
1248
1249
1250
1251
1252
1253QString QtObject::btoa(
const QString &data)
const
1255 qWarning(
"Qt.btoa(string): This method is deprecated. "
1256 "Its output differs from the common Web API. "
1257 "Use the overloads that take array-likes.");
1258 return QLatin1String(data.toUtf8().toBase64());
1262
1263
1264
1265
1266
1267
1268QString QtObject::atob(
const QString &data)
const
1270 qWarning(
"Qt.atob(string): This method is deprecated. "
1271 "Its output differs from the common Web API. "
1272 "Use the overloads that take array-likes.");
1273 return QString::fromUtf8(QByteArray::fromBase64(data.toLatin1()));
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293QByteArray QtObject::btoa(
const QByteArray &data)
const
1295 return data.toBase64();
1300 QV4::Scope scope(engine);
1301 THROW_DOM(DOMEXCEPTION_INVALID_CHARACTER_ERR,
"Invalid character");
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321QByteArray QtObject::atob(
const QByteArray &data)
const
1324 = QByteArray::fromBase64Encoding(data, QByteArray::AbortOnBase64DecodingErrors);
1325 if (result.decodingStatus == QByteArray::Base64DecodingStatus::Ok)
1326 return result.decoded;
1328 throwInvalidCharacter(v4Engine());
1329 return QByteArray();
1334 const auto fail = [&]() {
1335 throwInvalidCharacter(engine);
1336 return QByteArray();
1341 const auto append = [&](
auto value) {
1342 if (value < 0 || value >= 256)
1344 result.append(
char(value));
1348 for (
const QVariant &entry : data) {
1349 switch (entry.typeId()) {
1350 case QMetaType::Char:
1351 result.append(*
static_cast<
const char *>(entry.constData()));
1353 case QMetaType::Int: {
1354 if (!append(*
static_cast<
const int *>(entry.constData())))
1358 case QMetaType::Double: {
1359 if (!append(*
static_cast<
const double *>(entry.constData())))
1363 case QMetaType::QString: {
1364 const QString *string =
static_cast<
const QString *>(entry.constData());
1365 if (string->length() != 1)
1367 if (!append(string->at(0).unicode()))
1380
1381
1382
1383
1384
1385
1386QByteArray QtObject::btoa(
const QVariantList &data)
const
1388 return btoa(convertVariantList(data, v4Engine()));
1392
1393
1394
1395
1396
1397
1398QByteArray QtObject::atob(
const QVariantList &data)
const
1400 return atob(convertVariantList(data, v4Engine()));
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414void QtObject::quit()
const
1416 if (QQmlEngine *engine = qmlEngine())
1417 QQmlEnginePrivate::get(engine)->sendQuit();
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432void QtObject::exit(
int retCode)
const
1434 if (QQmlEngine *engine = qmlEngine())
1435 QQmlEnginePrivate::get(engine)->sendExit(retCode);
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473QObject *QtObject::createQmlObject(
const QString &qml, QObject *parent,
const QUrl &url)
const
1475 QQmlEngine *engine = qmlEngine();
1477 v4Engine()->throwError(QStringLiteral(
"Qt.createQmlObject(): "
1478 "Can only be called on a QML engine."));
1483 static ReturnedValue create(QV4::ExecutionEngine *v4,
const QList<QQmlError> &errors) {
1487 errorstr += QLatin1String(
"Qt.createQmlObject(): failed to create object: ");
1489 QV4::ScopedArrayObject qmlerrors(scope, v4->newArrayObject());
1490 QV4::ScopedObject qmlerror(scope);
1491 QV4::ScopedString s(scope);
1492 QV4::ScopedValue v(scope);
1493 for (
int ii = 0; ii < errors.size(); ++ii) {
1494 const QQmlError &error = errors.at(ii);
1495 errorstr += QLatin1String(
"\n ") + error.toString();
1496 qmlerror = v4->newObject();
1497 qmlerror->put((s = v4->newString(QStringLiteral(
"lineNumber"))), (v = QV4::Value::fromInt32(error.line())));
1498 qmlerror->put((s = v4->newString(QStringLiteral(
"columnNumber"))), (v = QV4::Value::fromInt32(error.column())));
1499 qmlerror->put((s = v4->newString(QStringLiteral(
"fileName"))), (v = v4->newString(error.url().toString())));
1500 qmlerror->put((s = v4->newString(QStringLiteral(
"message"))), (v = v4->newString(error.description())));
1501 qmlerrors->put(ii, qmlerror);
1504 v = v4->newString(errorstr);
1505 ScopedObject errorObject(scope, v4->newErrorObject(v));
1506 errorObject->put((s = v4->newString(QStringLiteral(
"qmlErrors"))), qmlerrors);
1507 return errorObject.asReturnedValue();
1511 QQmlRefPointer<QQmlContextData> context = v4Engine()->callingQmlContext();
1513 context = QQmlContextData::get(QQmlEnginePrivate::get(engine)->rootContext);
1516 QQmlContext *effectiveContext =
nullptr;
1517 if (context->isPragmaLibraryContext())
1518 effectiveContext = engine->rootContext();
1520 effectiveContext = context->asQQmlContext();
1521 Q_ASSERT(effectiveContext);
1526 QUrl resolvedUrl = url;
1527 if (url.isValid() && url.isRelative())
1528 resolvedUrl = context->resolvedUrl(url);
1531 v4Engine()->throwError(QStringLiteral(
"Qt.createQmlObject(): Missing parent object"));
1535 QQmlRefPointer<QQmlTypeData> typeData = v4Engine()->typeLoader()->getType(
1536 qml.toUtf8(), resolvedUrl, QQmlTypeLoader::Synchronous);
1538 if (!typeData->isCompleteOrError()) {
1539 v4Engine()->throwError(
1540 QStringLiteral(
"Qt.createQmlObject(): Failed to force synchronous loading "
1541 "of asynchronous URL '%1'").arg(resolvedUrl.toString()));
1545 QQmlComponent component(engine);
1546 QQmlComponentPrivate *componentPrivate = QQmlComponentPrivate::get(&component);
1547 componentPrivate->fromTypeData(typeData);
1548 componentPrivate->setProgress(1.0);
1550 Scope scope(v4Engine());
1551 if (component.isError()) {
1552 ScopedValue v(scope, Error::create(scope.engine, component.errors()));
1553 scope.engine->throwError(v);
1557 if (!component.isReady()) {
1558 v4Engine()->throwError(QStringLiteral(
"Qt.createQmlObject(): Component is not ready"));
1562 if (!effectiveContext->isValid()) {
1563 v4Engine()->throwError(QStringLiteral(
"Qt.createQmlObject(): Cannot create a component "
1564 "in an invalid context"));
1568 QObject *obj = component.beginCreate(effectiveContext);
1570 QQmlData::get(obj,
true)->explicitIndestructibleSet =
false;
1571 QQmlData::get(obj)->indestructible =
false;
1573 obj->setParent(parent);
1575 QList<QQmlPrivate::AutoParentFunction> functions = QQmlMetaType::parentFunctions();
1576 for (
int ii = 0; ii < functions.size(); ++ii) {
1577 if (QQmlPrivate::Parented == functions.at(ii)(obj, parent))
1581 component.completeCreate();
1583 v4Engine()->trimCompilationUnitsForUrl(resolvedUrl);
1584 if (component.isError()) {
1585 ScopedValue v(scope, Error::create(scope.engine, component.errors()));
1586 scope.engine->throwError(v);
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1665QQmlComponent *QtObject::createComponent(
const QUrl &url, QObject *parent)
const
1667 return createComponent(url, QQmlComponent::PreferSynchronous, parent);
1673 engine->throwError(QStringLiteral(
"Invalid compilation mode %1").arg(
int(mode)));
1677QQmlComponent *QtObject::createComponent(
const QUrl &url, QQmlComponent::CompilationMode mode,
1678 QObject *parent)
const
1680 if (mode != QQmlComponent::Asynchronous && mode != QQmlComponent::PreferSynchronous) {
1681 throw_invalid_compilation_mode(v4Engine(), mode);
1688 QQmlEngine *engine = qmlEngine();
1692 auto [context, effectiveContext] = getContexts();
1696 QQmlComponent *c =
new QQmlComponent(engine, context->resolvedUrl(url), mode, parent);
1697 QQmlComponentPrivate::get(c)->setCreationContext(std::move(effectiveContext));
1698 QQmlData::get(c,
true)->explicitIndestructibleSet =
false;
1699 QQmlData::get(c)->indestructible =
false;
1703QQmlComponent *QtObject::createComponent(
const QString &moduleUri,
const QString &typeName,
1704 QObject *parent)
const
1706 return createComponent(moduleUri, typeName, QQmlComponent::PreferSynchronous, parent);
1709QQmlComponent *QtObject::createComponent(
const QString &moduleUri,
const QString &typeName, QQmlComponent::CompilationMode mode, QObject *parent)
const
1711 if (mode != QQmlComponent::Asynchronous && mode != QQmlComponent::PreferSynchronous) {
1712 throw_invalid_compilation_mode(v4Engine(), mode);
1716 QQmlEngine *engine = qmlEngine();
1720 if (moduleUri.isEmpty() || typeName.isEmpty())
1723 auto [context, effectiveContext] = getContexts();
1727 QQmlComponent *c =
new QQmlComponent(engine, moduleUri, typeName, mode, parent);
1728 if (c->isError() && !parent && moduleUri.endsWith(u".qml")) {
1729 v4Engine()->throwTypeError(
1730 QStringLiteral(
"Invalid arguments; did you swap mode and parent"));
1732 QQmlComponentPrivate::get(c)->setCreationContext(std::move(effectiveContext));
1733 QQmlData::get(c,
true)->explicitIndestructibleSet =
false;
1734 QQmlData::get(c)->indestructible =
false;
1738#if QT_CONFIG(translation)
1739QString QtObject::uiLanguage()
const
1741 if (
const QJSEngine *e = jsEngine())
1742 return e->uiLanguage();
1746void QtObject::setUiLanguage(
const QString &uiLanguage)
1748 if (QJSEngine *e = jsEngine())
1749 e->setUiLanguage(uiLanguage);
1752QBindable<QString> QtObject::uiLanguageBindable()
1754 if (QJSEngine *e = jsEngine())
1755 return QBindable<QString>(&QJSEnginePrivate::get(e)->uiLanguage);
1756 return QBindable<QString>();
1760#if QT_CONFIG(qml_locale)
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783QLocale QtObject::locale()
const
1788QLocale QtObject::locale(
const QString &name)
const
1790 return QLocale(name);
1794void Heap::QQmlBindingFunction::init(
const QV4::JavaScriptFunctionObject *bindingFunction)
1796 Scope scope(bindingFunction->engine());
1797 ScopedContext context(scope, bindingFunction->scope());
1798 JavaScriptFunctionObject::init(context, bindingFunction->function());
1799 this->bindingFunction.set(internalClass->engine, bindingFunction->d());
1803 const FunctionObject *f,
const Value *,
const Value *,
int)
1806 return f->engine()->throwTypeError(QStringLiteral(
"Bindings must not be called directly."));
1811 QV4::CppStackFrame *frame = engine()->currentStackFrame;
1812 if (frame->v4Function)
1813 return QQmlSourceLocation(frame->source(), frame->lineNumber(), 0);
1815 return bindingFunction()->function->sourceLocation();
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861QJSValue QtObject::binding(
const QJSValue &function)
const
1863 const QV4::JavaScriptFunctionObject *f
1864 = QJSValuePrivate::asManagedType<JavaScriptFunctionObject>(&function);
1865 QV4::ExecutionEngine *e = v4Engine();
1867 return QJSValuePrivate::fromReturnedValue(
1870 "binding(): argument (binding expression) must be a function")));
1873 return QJSValuePrivate::fromReturnedValue(
1874 Encode(e->memoryManager->allocate<QQmlBindingFunction>(f)));
1877void QtObject::callLater(QQmlV4FunctionPtr args)
1879 m_engine->delayedCallQueue()->addUniquelyAndExecuteLater(m_engine, args);
1883
1884
1885
1886
1887
1888
1889double QtObject::enumStringToValue(
const QJSManagedValue &enumType,
const QString &string)
1891 return retrieveFromEnum<
double>(
1893 [&](
const QQmlType &type, QQmlTypeLoader *typeLoader,
int enumIndex,
bool *ok) {
1894 return type.scopedEnumValue(typeLoader, enumIndex, string, ok);
1895 }, [&](
const QQmlType &type, QQmlTypeLoader *typeLoader,
int enumIndex,
bool *ok) {
1896 return type.unscopedEnumValue(typeLoader, enumIndex, string, ok);
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912QString QtObject::enumValueToString(
const QJSManagedValue &enumType,
double value)
1915 if (std::isnan(value)) {
1916 m_engine->throwReferenceError(
"Invalid second argument, entry"_L1);
1920 return retrieveFromEnum<QString>(
1922 [&](
const QQmlType &type, QQmlTypeLoader *typeLoader,
int enumIndex,
bool *ok) {
1923 return type.scopedEnumKey(typeLoader, enumIndex, QtPrivate::qSaturateRound(value), ok);
1924 }, [&](
const QQmlType &type, QQmlTypeLoader *typeLoader,
int enumIndex,
bool *ok) {
1925 return type.unscopedEnumKey(typeLoader, enumIndex, QtPrivate::qSaturateRound(value), ok);
1930
1931
1932
1933
1934
1935
1936
1937QStringList QtObject::enumValueToStrings(
const QJSManagedValue &enumType,
double value)
1940 if (std::isnan(value)) {
1941 m_engine->throwReferenceError(
"Invalid second argument, entry"_L1);
1945 return retrieveFromEnum<QStringList>(
1947 [&](
const QQmlType &type, QQmlTypeLoader *typeLoader,
int enumIndex,
bool *ok) {
1948 return type.scopedEnumKeys(typeLoader, enumIndex, QtPrivate::qSaturateRound(value), ok);
1949 }, [&](
const QQmlType &type, QQmlTypeLoader *typeLoader,
int enumIndex,
bool *ok) {
1950 return type.unscopedEnumKeys(typeLoader, enumIndex, QtPrivate::qSaturateRound(value), ok);
1954QQmlPlatform *QtObject::platform()
1957 m_platform =
new QQmlPlatform(
this);
1961QQmlApplication *QtObject::application()
1965 m_application = QQml_guiProvider()->application(
this);
1967 return m_application;
1970QObject *QtObject::inputMethod()
const
1972 return QQml_guiProvider()->inputMethod();
1975QObject *QtObject::styleHints()
const
1977 return QQml_guiProvider()->styleHints();
1983 QV4::Scope scope(internalClass->engine);
1984 QV4::ScopedObject o(scope,
this);
1986 o->defineDefaultProperty(QStringLiteral(
"debug"), QV4::ConsoleObject::method_log);
1987 o->defineDefaultProperty(QStringLiteral(
"log"), QV4::ConsoleObject::method_log);
1988 o->defineDefaultProperty(QStringLiteral(
"info"), QV4::ConsoleObject::method_info);
1989 o->defineDefaultProperty(QStringLiteral(
"warn"), QV4::ConsoleObject::method_warn);
1990 o->defineDefaultProperty(QStringLiteral(
"error"), QV4::ConsoleObject::method_error);
1991 o->defineDefaultProperty(QStringLiteral(
"assert"), QV4::ConsoleObject::method_assert);
1993 o->defineDefaultProperty(QStringLiteral(
"count"), QV4::ConsoleObject::method_count);
1994 o->defineDefaultProperty(QStringLiteral(
"profile"), QV4::ConsoleObject::method_profile);
1995 o->defineDefaultProperty(QStringLiteral(
"profileEnd"), QV4::ConsoleObject::method_profileEnd);
1996 o->defineDefaultProperty(QStringLiteral(
"time"), QV4::ConsoleObject::method_time);
1997 o->defineDefaultProperty(QStringLiteral(
"timeEnd"), QV4::ConsoleObject::method_timeEnd);
1998 o->defineDefaultProperty(QStringLiteral(
"trace"), QV4::ConsoleObject::method_trace);
1999 o->defineDefaultProperty(QStringLiteral(
"exception"), QV4::ConsoleObject::method_exception);
2014 for (CppStackFrame *f = engine->currentStackFrame; f && i < 10; f = f->parentFrame(), ++i) {
2017 if (f->isJSTypesFrame() &&
static_cast<JSTypesStackFrame *>(f)->isTailCalling()) {
2018 stackFrame = QStringLiteral(
"[elided tail calls]");
2020 const int line = f->lineNumber();
2021 if (line != f->missingLineNumber()) {
2022 stackFrame = QStringLiteral(
"%1 (%2:%3)").arg(
2023 f->function(), f->source(), QString::number(qAbs(line)));
2025 stackFrame = QStringLiteral(
"%1 (%2)").arg(
2026 f->function(), f->source());
2031 stack += QLatin1Char(
'\n');
2032 stack += stackFrame;
2039 ScopedValue val(scope);
2041 alreadySeen.insert(array->d());
2043 ScopedObject detached(scope);
2044 if (Sequence *reference = array->as<Sequence>())
2045 detached = ReferenceObject::detached(reference->d());
2049 result += QLatin1Char(
'[');
2050 const uint length = detached->getLength();
2051 for (uint i = 0; i < length; ++i) {
2053 result += QLatin1Char(
',');
2054 val = detached->get(i);
2055 if (val->isManaged() && val->managed()->isArrayLike())
2056 if (!alreadySeen.contains(val->objectValue()->d()))
2057 result += serializeArray(val->objectValue(), v4, alreadySeen);
2059 result += QLatin1String(
"[Circular]");
2061 result += val->toQStringNoThrow();
2063 result += QLatin1Char(
']');
2065 alreadySeen.remove(array->d());
2072 const QLoggingCategory *loggingCategory =
nullptr;
2074 QV4::Scope scope(b);
2075 QV4::ExecutionEngine *v4 = scope.engine;
2079 if (
const QObjectWrapper* wrapper = argv[0].as<QObjectWrapper>()) {
2080 if (QQmlLoggingCategoryBase *category
2081 = qobject_cast<QQmlLoggingCategoryBase *>(wrapper->object())) {
2082 if (category->category())
2083 loggingCategory = category->category();
2085 THROW_GENERIC_ERROR(
"A QmlLoggingCatgory was provided without a valid name");
2092 for (
int i = start, ei = argc; i < ei; ++i) {
2094 result.append(QLatin1Char(
' '));
2096 QSet<QV4::Heap::Object *> alreadySeenElements;
2097 if (argv[i].isManaged() && argv[i].managed()->isArrayLike())
2098 result.append(serializeArray(argv[i].objectValue(), v4, alreadySeenElements));
2100 result.append(argv[i].toQStringNoThrow());
2104 result += QLatin1Char(
'\n') + jsStack(v4);
2106 if (!loggingCategory)
2107 loggingCategory = v4->qmlEngine() ? &lcQml() : &lcJs();
2108 QV4::CppStackFrame *frame = v4->currentStackFrame;
2109 const QByteArray baSource = frame ? frame->source().toUtf8() : QByteArray();
2110 const QByteArray baFunction = frame ? frame->function().toUtf8() : QByteArray();
2111 QMessageLogger logger(baSource.constData(), frame ? frame->lineNumber() : 0,
2112 baFunction.constData(), loggingCategory->categoryName());
2116 if (loggingCategory->isDebugEnabled())
2117 logger.debug(
"%s", result.toUtf8().constData());
2120 if (loggingCategory->isInfoEnabled())
2121 logger.info(
"%s", result.toUtf8().constData());
2124 if (loggingCategory->isWarningEnabled())
2125 logger.warning(
"%s", result.toUtf8().constData());
2128 if (loggingCategory->isCriticalEnabled())
2129 logger.critical(
"%s", result.toUtf8().constData());
2135 return Encode::undefined();
2140ReturnedValue
ConsoleObject::method_error(
const FunctionObject *b,
const Value *,
const Value *argv,
int argc)
2142 return writeToConsole(b, argv, argc, Error);
2145ReturnedValue
ConsoleObject::method_log(
const FunctionObject *b,
const Value *,
const Value *argv,
int argc)
2150 return writeToConsole(b, argv, argc, Log);
2153ReturnedValue
ConsoleObject::method_info(
const FunctionObject *b,
const Value *,
const Value *argv,
int argc)
2155 return writeToConsole(b, argv, argc, Info);
2158ReturnedValue
ConsoleObject::method_profile(
const FunctionObject *b,
const Value *,
const Value *,
int)
2160 QV4::Scope scope(b);
2161 QV4::ExecutionEngine *v4 = scope.engine;
2163 QV4::CppStackFrame *frame = v4->currentStackFrame;
2164 const QByteArray baSource = frame->source().toUtf8();
2165 const QByteArray baFunction = frame->function().toUtf8();
2166 QMessageLogger logger(baSource.constData(), frame->lineNumber(), baFunction.constData());
2167 QQmlProfilerService *service = QQmlDebugConnector::service<QQmlProfilerService>();
2169 logger.warning(
"Cannot start profiling because debug service is disabled. Start with -qmljsdebugger=port:XXXXX.");
2171 service->startProfiling(v4->jsEngine());
2172 logger.debug(
"Profiling started.");
2175 return QV4::Encode::undefined();
2178ReturnedValue
ConsoleObject::method_profileEnd(
const FunctionObject *b,
const Value *,
const Value *,
int)
2180 QV4::Scope scope(b);
2181 QV4::ExecutionEngine *v4 = scope.engine;
2183 QV4::CppStackFrame *frame = v4->currentStackFrame;
2184 const QByteArray baSource = frame->source().toUtf8();
2185 const QByteArray baFunction = frame->function().toUtf8();
2186 QMessageLogger logger(baSource.constData(), frame->lineNumber(), baFunction.constData());
2188 QQmlProfilerService *service = QQmlDebugConnector::service<QQmlProfilerService>();
2190 logger.warning(
"Ignoring console.profileEnd(): the debug service is disabled.");
2192 service->stopProfiling(v4->jsEngine());
2193 logger.debug(
"Profiling ended.");
2196 return QV4::Encode::undefined();
2199ReturnedValue
ConsoleObject::method_time(
const FunctionObject *b,
const Value *,
const Value *argv,
int argc)
2201 QV4::Scope scope(b);
2203 THROW_GENERIC_ERROR(
"console.time(): Invalid arguments");
2205 QString name = argv[0].toQStringNoThrow();
2206 scope.engine->startTimer(name);
2207 return QV4::Encode::undefined();
2210ReturnedValue
ConsoleObject::method_timeEnd(
const FunctionObject *b,
const Value *,
const Value *argv,
int argc)
2212 QV4::Scope scope(b);
2214 THROW_GENERIC_ERROR(
"console.timeEnd(): Invalid arguments");
2216 QString name = argv[0].toQStringNoThrow();
2218 qint64 elapsed = scope.engine->stopTimer(name, &wasRunning);
2220 qDebug(
"%s: %llims", qPrintable(name), elapsed);
2222 return QV4::Encode::undefined();
2225ReturnedValue
ConsoleObject::method_count(
const FunctionObject *b,
const Value *,
const Value *argv,
int argc)
2230 name = argv[0].toQStringNoThrow();
2233 QV4::ExecutionEngine *v4 = scope.engine;
2235 QV4::CppStackFrame *frame = v4->currentStackFrame;
2237 QString scriptName = frame->source();
2239 int value = v4->consoleCountHelper(scriptName, frame->lineNumber(), 0);
2240 QString message = name + QLatin1String(
": ") + QString::number(value);
2242 QMessageLogger(qPrintable(scriptName), frame->lineNumber(),
2243 qPrintable(frame->function()))
2244 .debug(
"%s", qPrintable(message));
2246 return QV4::Encode::undefined();
2249ReturnedValue
ConsoleObject::method_trace(
const FunctionObject *b,
const Value *,
const Value *,
int argc)
2251 QV4::Scope scope(b);
2253 THROW_GENERIC_ERROR(
"console.trace(): Invalid arguments");
2255 QV4::ExecutionEngine *v4 = scope.engine;
2257 QString stack = jsStack(v4);
2259 QV4::CppStackFrame *frame = v4->currentStackFrame;
2260 QMessageLogger(frame->source().toUtf8().constData(), frame->lineNumber(),
2261 frame->function().toUtf8().constData())
2262 .debug(v4->qmlEngine() ? lcQml() : lcJs(),
"%s", qPrintable(stack));
2264 return QV4::Encode::undefined();
2267ReturnedValue
ConsoleObject::method_warn(
const FunctionObject *b,
const Value *,
const Value *argv,
int argc)
2269 return writeToConsole(b, argv, argc, Warn);
2272ReturnedValue
ConsoleObject::method_assert(
const FunctionObject *b,
const Value *,
const Value *argv,
int argc)
2274 QV4::Scope scope(b);
2276 THROW_GENERIC_ERROR(
"console.assert(): Missing argument");
2278 QV4::ExecutionEngine *v4 = scope.engine;
2280 if (!argv[0].toBoolean()) {
2282 for (
int i = 1, ei = argc; i < ei; ++i) {
2284 message.append(QLatin1Char(
' '));
2286 message.append(argv[i].toQStringNoThrow());
2289 QString stack = jsStack(v4);
2291 QV4::CppStackFrame *frame = v4->currentStackFrame;
2292 QMessageLogger(frame->source().toUtf8().constData(), frame->lineNumber(),
2293 frame->function().toUtf8().constData())
2294 .critical(
"%s\n%s",qPrintable(message), qPrintable(stack));
2297 return QV4::Encode::undefined();
2300ReturnedValue
ConsoleObject::method_exception(
const FunctionObject *b,
const Value *,
const Value *argv,
int argc)
2302 QV4::Scope scope(b);
2304 THROW_GENERIC_ERROR(
"console.exception(): Missing argument");
2306 return writeToConsole(b, argv, argc, Error,
true);
2309void QV4::GlobalExtensions::init(Object *globalObject, QJSEngine::Extensions extensions)
2311 ExecutionEngine *v4 = globalObject->engine();
2314 if (extensions.testFlag(QJSEngine::TranslationExtension)) {
2315 #if QT_CONFIG(translation)
2316 globalObject->defineDefaultProperty(QStringLiteral(
"qsTranslate"), QV4::GlobalExtensions::method_qsTranslate);
2317 globalObject->defineDefaultProperty(QStringLiteral(
"QT_TRANSLATE_NOOP"), QV4::GlobalExtensions::method_qsTranslateNoOp);
2318 globalObject->defineDefaultProperty(QStringLiteral(
"qsTr"), QV4::GlobalExtensions::method_qsTr);
2319 globalObject->defineDefaultProperty(QStringLiteral(
"QT_TR_NOOP"), QV4::GlobalExtensions::method_qsTrNoOp);
2320 globalObject->defineDefaultProperty(QStringLiteral(
"qsTrId"), QV4::GlobalExtensions::method_qsTrId);
2321 globalObject->defineDefaultProperty(QStringLiteral(
"QT_TRID_NOOP"), QV4::GlobalExtensions::method_qsTrIdNoOp);
2324 ScopedString qtName(scope, v4->newString(QStringLiteral(
"Qt")));
2325 ScopedObject qt(scope, globalObject->get(qtName));
2327 v4->createQtObject();
2330 scope.engine->stringPrototype()->defineDefaultProperty(QStringLiteral(
"arg"), QV4::GlobalExtensions::method_string_arg);
2334 if (extensions.testFlag(QJSEngine::ConsoleExtension)) {
2335 globalObject->defineDefaultProperty(QStringLiteral(
"print"), QV4::ConsoleObject::method_log);
2338 QV4::ScopedObject console(scope, globalObject->engine()->memoryManager->allocate<QV4::ConsoleObject>());
2339 globalObject->defineDefaultProperty(QStringLiteral(
"console"), console);
2342 if (extensions.testFlag(QJSEngine::GarbageCollectionExtension)) {
2343 globalObject->defineDefaultProperty(QStringLiteral(
"gc"), QV4::GlobalExtensions::method_gc);
2348#if QT_CONFIG(translation)
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369ReturnedValue GlobalExtensions::method_qsTranslate(
const FunctionObject *b,
const Value *,
const Value *argv,
int argc)
2371 QV4::Scope scope(b);
2373 THROW_GENERIC_ERROR(
"qsTranslate() requires at least two arguments");
2374 if (!argv[0].isString())
2375 THROW_GENERIC_ERROR(
"qsTranslate(): first argument (context) must be a string");
2376 if (!argv[1].isString())
2377 THROW_GENERIC_ERROR(
"qsTranslate(): second argument (sourceText) must be a string");
2378 if ((argc > 2) && !argv[2].isString())
2379 THROW_GENERIC_ERROR(
"qsTranslate(): third argument (disambiguation) must be a string");
2381 QString context = argv[0].toQStringNoThrow();
2382 QString text = argv[1].toQStringNoThrow();
2384 if (argc > 2) comment = argv[2].toQStringNoThrow();
2387 if (argc > i && argv[i].isString()) {
2388 qWarning(
"qsTranslate(): specifying the encoding as fourth argument is deprecated");
2394 n = argv[i].toInt32();
2396 if (QQmlEnginePrivate *ep = (scope.engine->qmlEngine() ? QQmlEnginePrivate::get(scope.engine->qmlEngine()) :
nullptr))
2397 if (ep->propertyCapture)
2398 ep->propertyCapture->captureTranslation();
2400 QString result = QCoreApplication::translate(context.toUtf8().constData(),
2401 text.toUtf8().constData(),
2402 comment.toUtf8().constData(),
2405 return Encode(scope.engine->newString(result));
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430ReturnedValue GlobalExtensions::method_qsTranslateNoOp(
const FunctionObject *b,
const Value *,
const Value *argv,
int argc)
2432 QV4::Scope scope(b);
2434 return QV4::Encode::undefined();
2436 return argv[1].asReturnedValue();
2439QString GlobalExtensions::currentTranslationContext(ExecutionEngine *engine)
2442 CppStackFrame *frame = engine->currentStackFrame;
2445 while (frame && context.isEmpty()) {
2446 if (ExecutableCompilationUnit *unit = frame->v4Function->executableCompilationUnit()) {
2447 auto translationContextIndex = unit->unitData()->translationContextIndex();
2448 if (translationContextIndex)
2449 context = unit->stringAt(*translationContextIndex);
2450 if (!context.isEmpty())
2452 QString fileName = unit->fileName();
2453 QUrl url(unit->fileName());
2454 if (url.isValid() && url.isRelative()) {
2455 context = url.fileName();
2457 context = QQmlFile::urlToLocalFileOrQrc(fileName);
2458 if (context.isEmpty() && fileName.startsWith(QLatin1String(
":/")))
2461 context = QFileInfo(context).completeBaseName();
2463 frame = frame->parentFrame();
2466 if (context.isEmpty()) {
2467 if (QQmlRefPointer<QQmlContextData> ctxt = engine->callingQmlContext()) {
2468 QString path = ctxt->urlString();
2469 int lastSlash = path.lastIndexOf(QLatin1Char(
'/'));
2470 int lastDot = path.lastIndexOf(QLatin1Char(
'.'));
2471 int length = lastDot - (lastSlash + 1);
2472 context = (lastSlash > -1) ? path.mid(lastSlash + 1, (length > -1) ? length : -1) : QString();
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516ReturnedValue GlobalExtensions::method_qsTr(
const FunctionObject *b,
const Value *,
const Value *argv,
int argc)
2518 QV4::Scope scope(b);
2520 THROW_GENERIC_ERROR(
"qsTr() requires at least one argument");
2521 if (!argv[0].isString())
2522 THROW_GENERIC_ERROR(
"qsTr(): first argument (sourceText) must be a string");
2523 if ((argc > 1) && !argv[1].isString())
2524 THROW_GENERIC_ERROR(
"qsTr(): second argument (disambiguation) must be a string");
2525 if ((argc > 2) && !argv[2].isNumber())
2526 THROW_GENERIC_ERROR(
"qsTr(): third argument (n) must be a number");
2528 const QString context = currentTranslationContext(scope.engine);
2529 const QString text = argv[0].toQStringNoThrow();
2530 const QString comment = argc > 1 ? argv[1].toQStringNoThrow() : QString();
2531 const int n = argc > 2 ? argv[2].toInt32() : -1;
2533 if (QQmlEnginePrivate *ep = (scope.engine->qmlEngine() ? QQmlEnginePrivate::get(scope.engine->qmlEngine()) :
nullptr))
2534 if (ep->propertyCapture)
2535 ep->propertyCapture->captureTranslation();
2537 QString result = QCoreApplication::translate(context.toUtf8().constData(), text.toUtf8().constData(),
2538 comment.toUtf8().constData(), n);
2540 return Encode(scope.engine->newString(result));
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565ReturnedValue GlobalExtensions::method_qsTrNoOp(
const FunctionObject *,
const Value *,
const Value *argv,
int argc)
2568 return QV4::Encode::undefined();
2570 return argv[0].asReturnedValue();
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604ReturnedValue GlobalExtensions::method_qsTrId(
const FunctionObject *b,
const Value *,
const Value *argv,
int argc)
2606 QV4::Scope scope(b);
2608 THROW_GENERIC_ERROR(
"qsTrId() requires at least one argument");
2609 if (!argv[0].isString())
2610 THROW_TYPE_ERROR_WITH_MESSAGE(
"qsTrId(): first argument (id) must be a string");
2611 if (argc > 1 && !argv[1].isNumber())
2612 THROW_TYPE_ERROR_WITH_MESSAGE(
"qsTrId(): second argument (n) must be a number");
2616 n = argv[1].toInt32();
2618 if (QQmlEnginePrivate *ep = (scope.engine->qmlEngine() ? QQmlEnginePrivate::get(scope.engine->qmlEngine()) :
nullptr))
2619 if (ep->propertyCapture)
2620 ep->propertyCapture->captureTranslation();
2622 return Encode(scope.engine->newString(qtTrId(argv[0].toQStringNoThrow().toUtf8().constData(), n)));
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641ReturnedValue GlobalExtensions::method_qsTrIdNoOp(
const FunctionObject *,
const Value *,
const Value *argv,
int argc)
2644 return QV4::Encode::undefined();
2646 return argv[0].asReturnedValue();
2651
2652
2653
2654
2655
2656
2657
2658
2659ReturnedValue GlobalExtensions::method_gc(
const FunctionObject *b,
const Value *,
const Value *,
int)
2661 auto mm = b->engine()->memoryManager;
2664 return QV4::Encode::undefined();
2667ReturnedValue GlobalExtensions::method_string_arg(
const FunctionObject *b,
const Value *thisObject,
const Value *argv,
int argc)
2669 QV4::Scope scope(b);
2671 THROW_GENERIC_ERROR(
"String.arg(): Invalid arguments");
2673 QString value = thisObject->toQString();
2677 QV4::ScopedValue arg(scope, argv[0]);
2678 if (arg->isInteger())
2679 value = value.arg(arg->integerValue());
2680 else if (arg->isDouble())
2681 value = value.arg(arg->doubleValue());
2682 else if (arg->isBoolean())
2683 value = value.arg(arg->booleanValue());
2685 value = value.arg(arg->toQString());
2686 RETURN_RESULT(scope.engine->newString(value));
2690 constexpr int PreallocArgCount = 10;
2693 QVarLengthArray<QString, PreallocArgCount> argStrings(argc);
2694 QVarLengthArray<QtPrivate::QStringViewArg, PreallocArgCount> args(argc);
2695 QVarLengthArray<
const QtPrivate::ArgBase *, PreallocArgCount> argBases(argc);
2697 for (
int i = 0; i < argc; ++i) {
2698 QV4::ScopedValue arg(scope, argv[i]);
2700 if (arg->isInteger())
2701 argStrings[i] = QString::number(arg->integerValue());
2702 else if (arg->isDouble())
2703 argStrings[i] = QString::number(arg->doubleValue());
2704 else if (arg->isBoolean())
2705 argStrings[i] = QString::number(arg->booleanValue());
2707 argStrings[i] = arg->toQString();
2709 args[i] = QtPrivate::QStringViewArg(argStrings[i]);
2710 argBases[i] = &args[i];
2713 QString result = QtPrivate::argToQString(value, argc, argBases.data());
2714 RETURN_RESULT(scope.engine->newString(result));
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2740#include "moc_qqmlbuiltinfunctions_p.cpp"
Combined button and popup list for selecting options.
Q_LOGGING_CATEGORY(lcEventDispatcher, "qt.eventdispatcher")
DEFINE_OBJECT_VTABLE(QQmlBindingFunction)
static QByteArray convertVariantList(const QVariantList &data, QV4::ExecutionEngine *engine)
static QTime dateTimeToTime(const QDateTime &dateTime)
static QString serializeArray(Object *array, ExecutionEngine *v4, QSet< QV4::Heap::Object * > &alreadySeen)
void addParameters(QJSEngine *e, QJSValue &result, int i, T parameter, Others... others)
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 QV4::ReturnedValue throwInvalidCharacter(QV4::ExecutionEngine *engine)
DEFINE_OBJECT_VTABLE(ConsoleObject)
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 Q_DECL_COLD_FUNCTION void throw_invalid_compilation_mode(QV4::ExecutionEngine *engine, QQmlComponent::CompilationMode mode)
static QVariant colorVariantFromJSValue(const QJSValue &color, bool *ok)
Q_DECLARE_LOGGING_CATEGORY(lcQml)
Q_DECLARE_LOGGING_CATEGORY(lcJs)
QQmlSourceLocation currentLocation() const