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
185
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
211
212
213
214
215
216
217
218
219
222
223
224
225
226
227
228
229
230
231
232
233
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
269QtObject::QtObject(ExecutionEngine *engine)
272#if QT_CONFIG(translation)
273 connect(m_engine->jsEngine(), &QJSEngine::uiLanguageChanged,
274 this, &QtObject::uiLanguageChanged);
278QtObject::Contexts QtObject::getContexts()
const
280 QQmlEngine *engine = qmlEngine();
284 QQmlRefPointer<QQmlContextData> context = v4Engine()->callingQmlContext();
286 context = QQmlContextData::get(QQmlEnginePrivate::get(engine)->rootContext);
289 QQmlRefPointer<QQmlContextData> effectiveContext
290 = context->isPragmaLibraryContext() ?
nullptr : context;
291 return {context, effectiveContext};
294QtObject *QtObject::create(QQmlEngine *, QJSEngine *jsEngine)
296 QV4::ExecutionEngine *v4 = jsEngine->handle();
297 QV4::Scope scope(v4);
298 ScopedObject globalObject(scope, v4->globalObject);
299 ScopedString qtName(scope, v4->newString(QStringLiteral(
"Qt")));
300 QV4::ScopedValue result(scope, globalObject->get(qtName->toPropertyKey()));
301 return qobject_cast<QtObject *>(result->as<QV4::QObjectWrapper>()->object());
304QJSValue QtObject::include(
const QString &url,
const QJSValue &callback)
const
306 return QV4Include::method_include(v4Engine(), v4Engine()->resolvedUrl(url), callback);
311
312
313
314
315
316bool QtObject::isQtObject(
const QJSValue &value)
const
318 return qjsvalue_cast<QObject *>(value) !=
nullptr;
322
323
324
325
326
327
328
329QVariant QtObject::color(
const QString &name)
const
332 const QVariant v = QQmlStringConverters::colorFromString(name, &ok);
336 v4Engine()->throwError(QStringLiteral(
"\"%1\" is not a valid color name").arg(name));
337 return QVariant::fromValue(
nullptr);
341
342
343
344
345
346
347
348QVariant QtObject::rgba(
double r,
double g,
double b,
double a)
const
350 r = qBound(0.0, r, 1.0);
351 g = qBound(0.0, g, 1.0);
352 b = qBound(0.0, b, 1.0);
353 a = qBound(0.0, a, 1.0);
355 return QQml_colorProvider()->fromRgbF(r, g, b, a);
359
360
361
362
363
364
365
366QVariant QtObject::hsla(
double h,
double s,
double l,
double a)
const
369 h = qBound(0.0, h, 1.0);
370 s = qBound(0.0, s, 1.0);
371 l = qBound(0.0, l, 1.0);
372 a = qBound(0.0, a, 1.0);
374 return QQml_colorProvider()->fromHslF(h, s, l, a);
378
379
380
381
382
383
384
385
386QVariant QtObject::hsva(
double h,
double s,
double v,
double a)
const
389 h = qBound(0.0, h, 1.0);
390 s = qBound(0.0, s, 1.0);
391 v = qBound(0.0, v, 1.0);
392 a = qBound(0.0, a, 1.0);
394 return QQml_colorProvider()->fromHsvF(h, s, v, a);
398
399
400
401
402
403
404
405
406
407bool QtObject::colorEqual(
const QVariant &lhs,
const QVariant &rhs)
const
411 QVariant color1 = lhs;
412 if (color1.userType() == QMetaType::QString) {
413 color1 = QQmlStringConverters::colorFromString(color1.toString(), &ok);
415 v4Engine()->throwError(QStringLiteral(
"Qt.colorEqual(): Invalid color name"));
418 }
else if (color1.userType() != QMetaType::QColor) {
419 v4Engine()->throwError(QStringLiteral(
"Qt.colorEqual(): Invalid arguments"));
423 QVariant color2 = rhs;
424 if (color2.userType() == QMetaType::QString) {
425 color2 = QQmlStringConverters::colorFromString(color2.toString(), &ok);
427 v4Engine()->throwError(QStringLiteral(
"Qt.colorEqual(): Invalid color name"));
430 }
else if (color2.userType() != QMetaType::QColor) {
431 v4Engine()->throwError(QStringLiteral(
"Qt.colorEqual(): Invalid arguments"));
435 return color1 == color2;
439
440
441
442
443QRectF QtObject::rect(
double x,
double y,
double width,
double height)
const
445 return QRectF(x, y, width, height);
449
450
451
452
453QPointF QtObject::point(
double x,
double y)
const
455 return QPointF(x, y);
459
460
461
462
463QSizeF QtObject::size(
double w,
double h)
const
469
470
471
472
473
474
475
476
477QVariant QtObject::font(
const QJSValue &fontSpecifier)
const
479 if (!fontSpecifier.isObject()) {
480 v4Engine()->throwError(QStringLiteral(
"Qt.font(): Invalid arguments"));
485 const QVariant v = QQmlValueTypeProvider::createValueType(
486 fontSpecifier, QMetaType(QMetaType::QFont));
491 v4Engine()->throwError(QStringLiteral(
"Qt.font(): Invalid argument: "
492 "no valid font subproperties specified"));
499 result.setProperty(i, e->toScriptValue(parameter));
503void addParameters<
double>(QJSEngine *, QJSValue &result,
int i,
double parameter)
505 result.setProperty(i, QJSValue(parameter));
508template<
typename T,
typename ...Others>
509void addParameters(QJSEngine *e, QJSValue &result,
int i, T parameter, Others... others)
511 addParameters<T>(e, result, i, parameter);
512 addParameters<Others...>(e, result, ++i, others...);
515template<
typename ...T>
520 QJSValue params = e->newArray(
sizeof...(parameters));
521 addParameters(e, params, 0, parameters...);
522 const QVariant variant = QQmlValueTypeProvider::createValueType(params, type);
523 return variant.isValid() ? variant : QVariant(type);
527
528
529
530
531QVariant QtObject::vector2d(
double x,
double y)
const
533 return constructFromJSValue(jsEngine(), QMetaType(QMetaType::QVector2D), x, y);
537
538
539
540
541QVariant QtObject::vector3d(
double x,
double y,
double z)
const
543 return constructFromJSValue(jsEngine(), QMetaType(QMetaType::QVector3D), x, y, z);
547
548
549
550
551QVariant QtObject::vector4d(
double x,
double y,
double z,
double w)
const
553 return constructFromJSValue(jsEngine(), QMetaType(QMetaType::QVector4D), x, y, z, w);
557
558
559
560
561QVariant QtObject::quaternion(
double scalar,
double x,
double y,
double z)
const
563 return constructFromJSValue(jsEngine(), QMetaType(QMetaType::QQuaternion), scalar, x, y, z);
567
568
569
570
571QVariant QtObject::matrix4x4()
const
573 const QMetaType metaType(QMetaType::QMatrix4x4);
574 const QVariant variant = QQmlValueTypeProvider::createValueType(QJSValue(), metaType);
575 return variant.isValid() ? variant : QVariant(metaType);
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593QVariant QtObject::matrix4x4(
const QJSValue &value)
const
595 if (value.isObject()) {
596 QVariant v = QQmlValueTypeProvider::createValueType(
597 value, QMetaType(QMetaType::QMatrix4x4));
602 v4Engine()->throwError(QStringLiteral(
"Qt.matrix4x4(): Invalid argument: "
603 "not a valid matrix4x4 values array"));
608
609
610
611
612
613
614
615
616
617
618
619
620
621QVariant QtObject::matrix4x4(
double m11,
double m12,
double m13,
double m14,
622 double m21,
double m22,
double m23,
double m24,
623 double m31,
double m32,
double m33,
double m34,
624 double m41,
double m42,
double m43,
double m44)
const
626 return constructFromJSValue(jsEngine(), QMetaType(QMetaType::QMatrix4x4),
627 m11, m12, m13, m14, m21, m22, m23, m24,
628 m31, m32, m33, m34, m41, m42, m43, m44);
634 if (color.isString()) {
635 v = QQmlStringConverters::colorFromString(color.toString(), ok);
637 return QVariant::fromValue(
nullptr);
639 v = color.toVariant();
640 if (v.userType() != QMetaType::QColor) {
642 return QVariant::fromValue(
nullptr);
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667QVariant QtObject::lighter(
const QJSValue &color,
double factor)
const
670 const QVariant v = colorVariantFromJSValue(color, &ok);
671 return ok ? QQml_colorProvider()->lighter(v, factor) : v;
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692QVariant QtObject::darker(
const QJSValue &color,
double factor)
const
695 const QVariant v = colorVariantFromJSValue(color, &ok);
696 return ok ? QQml_colorProvider()->darker(v, factor) : v;
700
701
702
703
704
705
706
707
708QVariant QtObject::alpha(
const QJSValue &baseColor,
double value)
const
711 const QVariant v = colorVariantFromJSValue(baseColor, &ok);
712 return ok ? QQml_colorProvider()->alpha(v, value) : v;
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744QVariant QtObject::tint(
const QJSValue &baseColor,
const QJSValue &tintColor)
const
749 const QVariant v1 = colorVariantFromJSValue(baseColor, &ok);
754 const QVariant v2 = colorVariantFromJSValue(tintColor, &ok);
756 return ok ? QQml_colorProvider()->tint(v1, v2) : v2;
761QString formatDateTimeObjectUsingDateFormat(T formatThis, Qt::DateFormat format) {
765 case Qt::RFC2822Date:
766 case Qt::ISODateWithMs:
767 return formatThis.toString(format);
778 return dateTime.toLocalTime().time();
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
800 const QDate date = QDate::fromString(string, Qt::ISODate);
807 const QDateTime dateTime = QDateTime::fromString(string, Qt::ISODate);
808 if (dateTime.isValid()) {
809 qCWarning(lcRootProperties())
810 << string <<
"is a date/time string being passed to formatDate()."
811 <<
"You should only pass date strings to formatDate().";
812 return dateTime.date();
818 const QDateTime dateTime = DateObject::stringToDateTime(string, engine);
819 if (dateTime.isValid())
820 return DateObject::dateTimeToDate(dateTime);
823 engine->throwError(QStringLiteral(
"Invalid argument passed to formatDate(): %1").arg(string));
827QString QtObject::formatDate(QDate date,
const QString &format)
const
829 return date.toString(format);
832QString QtObject::formatDate(QDate date, Qt::DateFormat format)
const
834 return formatDateTimeObjectUsingDateFormat(date, format);
837QString QtObject::formatDate(
const QDateTime &dateTime,
const QString &format)
const
839 return DateObject::dateTimeToDate(dateTime).toString(format);
842QString QtObject::formatDate(
const QString &string,
const QString &format)
const
844 if (
const auto qDate = dateFromString(string, v4Engine()))
845 return formatDate(qDate.value(), format);
850QString QtObject::formatDate(
const QDateTime &dateTime, Qt::DateFormat format)
const
852 return formatDateTimeObjectUsingDateFormat(DateObject::dateTimeToDate(dateTime), format);
855QString QtObject::formatDate(
const QString &string, Qt::DateFormat format)
const
857 if (
const auto qDate = dateFromString(string, v4Engine()))
858 return formatDate(qDate.value(), format);
863#if QT_CONFIG(qml_locale)
864QString QtObject::formatDate(QDate date,
const QLocale &locale,
865 QLocale::FormatType formatType)
const
867 return locale.toString(date, formatType);
870QString QtObject::formatDate(
const QDateTime &dateTime,
const QLocale &locale,
871 QLocale::FormatType formatType)
const
873 return locale.toString(DateObject::dateTimeToDate(dateTime), formatType);
876QString QtObject::formatDate(
const QString &string,
const QLocale &locale,
877 QLocale::FormatType formatType)
const
879 if (
const auto qDate = dateFromString(string, v4Engine()))
880 return locale.toString(qDate.value(), formatType);
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
905 const QTime time = QTime::fromString(string, Qt::ISODate);
912 const QDateTime dateTime = QDateTime::fromString(string, Qt::ISODate);
913 if (dateTime.isValid()) {
914 qCWarning(lcRootProperties())
915 << string <<
"is a date/time string being passed to formatTime()."
916 <<
"You should only pass time strings to formatTime().";
917 return dateTime.time();
923 const QDateTime dateTime = DateObject::stringToDateTime(string, engine);
924 if (dateTime.isValid())
925 return dateTimeToTime(dateTime);
928 engine->throwError(QStringLiteral(
"Invalid argument passed to formatTime(): %1").arg(string));
932QString QtObject::formatTime(QTime time,
const QString &format)
const
934 return time.toString(format);
937QString QtObject::formatTime(
const QDateTime &dateTime,
const QString &format)
const
939 return dateTimeToTime(dateTime).toString(format);
942QString QtObject::formatTime(
const QString &time,
const QString &format)
const
945 if (
auto qTime = timeFromString(time, v4Engine()))
946 return formatTime(qTime.value(), format);
951QString QtObject::formatTime(QTime time, Qt::DateFormat format)
const
953 return formatDateTimeObjectUsingDateFormat(time, format);
956QString QtObject::formatTime(
const QDateTime &dateTime, Qt::DateFormat format)
const
958 return formatDateTimeObjectUsingDateFormat(dateTimeToTime(dateTime), format);
961QString QtObject::formatTime(
const QString &time, Qt::DateFormat format)
const
963 if (
auto qTime = timeFromString(time, v4Engine()))
964 return formatTime(qTime.value(), format);
969#if QT_CONFIG(qml_locale)
970QString QtObject::formatTime(QTime time,
const QLocale &locale,
971 QLocale::FormatType formatType)
const
973 return locale.toString(time, formatType);
976QString QtObject::formatTime(
const QDateTime &dateTime,
const QLocale &locale,
977 QLocale::FormatType formatType)
const
979 return locale.toString(dateTimeToTime(dateTime), formatType);
982QString QtObject::formatTime(
const QString &time,
const QLocale &locale,
983 QLocale::FormatType formatType)
const
985 if (
auto qTime = timeFromString(time, v4Engine()))
986 return locale.toString(qTime.value(), formatType);
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
1089
1093 const QDateTime dateTime = QDateTime::fromString(string, Qt::ISODate);
1094 if (dateTime.isValid())
1100 const QDateTime dateTime = DateObject::stringToDateTime(string, engine);
1101 if (dateTime.isValid())
1105 engine->throwError(QStringLiteral(
"Invalid argument passed to formatDateTime(): %1").arg(string));
1106 return std::nullopt;
1109QString QtObject::formatDateTime(
const QDateTime &dateTime,
const QString &format)
const
1111 return dateTime.toString(format);
1114QString QtObject::formatDateTime(
const QString &string,
const QString &format)
const
1117 if (
const auto qDateTime = dateTimeFromString(string, v4Engine()))
1118 return formatDateTime(qDateTime.value(), format);
1123QString QtObject::formatDateTime(
const QDateTime &dateTime, Qt::DateFormat format)
const
1125 return formatDateTimeObjectUsingDateFormat(dateTime, format);
1128QString QtObject::formatDateTime(
const QString &string, Qt::DateFormat format)
const
1131 if (
const auto qDateTime = dateTimeFromString(string, v4Engine()))
1132 return formatDateTime(qDateTime.value(), format);
1137#if QT_CONFIG(qml_locale)
1138QString QtObject::formatDateTime(
const QDateTime &dateTime,
const QLocale &locale,
1139 QLocale::FormatType formatType)
const
1141 return locale.toString(dateTime, formatType);
1144QString QtObject::formatDateTime(
const QString &string,
const QLocale &locale,
1145 QLocale::FormatType formatType)
const
1148 if (
const auto qDateTime = dateTimeFromString(string, v4Engine()))
1149 return formatDateTime(qDateTime.value(), locale, formatType);
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1177bool QtObject::openUrlExternally(
const QUrl &url)
const
1179 return QQml_guiProvider()->openUrlExternally(resolvedUrl(url));
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192QUrl QtObject::url(
const QUrl &url)
const
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208QUrl QtObject::resolvedUrl(
const QUrl &url)
const
1210 if (QQmlRefPointer<QQmlContextData> ctxt = v4Engine()->callingQmlContext())
1211 return ctxt->resolvedUrl(url);
1212 if (QQmlEngine *engine = qmlEngine())
1213 return engine->baseUrl().resolved(url);
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227QUrl QtObject::resolvedUrl(
const QUrl &url, QObject *context)
const
1230 QQmlData *data = QQmlData::get(context);
1231 if (data && data->outerContext)
1232 return data->outerContext->resolvedUrl(url);
1235 if (QQmlEngine *engine = qmlEngine())
1236 return engine->baseUrl().resolved(url);
1241
1242
1243
1244
1245QStringList QtObject::fontFamilies()
const
1247 return QQml_guiProvider()->fontFamilies();
1251
1252
1253
1254QString QtObject::md5(
const QString &data)
const
1256 return QLatin1String(QCryptographicHash::hash(data.toUtf8(), QCryptographicHash::Md5).toHex());
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277QString QtObject::escapeHtml(
const QString &data)
const
1279 return data.toHtmlEscaped();
1283
1284
1285
1286
1287
1288QString QtObject::btoa(
const QString &data)
const
1290 qWarning(
"Qt.btoa(string): This method is deprecated. "
1291 "Its output differs from the common Web API. "
1292 "Use the overloads that take array-likes.");
1293 return QLatin1String(data.toUtf8().toBase64());
1297
1298
1299
1300
1301
1302
1303QString QtObject::atob(
const QString &data)
const
1305 qWarning(
"Qt.atob(string): This method is deprecated. "
1306 "Its output differs from the common Web API. "
1307 "Use the overloads that take array-likes.");
1308 return QString::fromUtf8(QByteArray::fromBase64(data.toLatin1()));
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328QByteArray QtObject::btoa(
const QByteArray &data)
const
1330 return data.toBase64();
1335 QV4::Scope scope(engine);
1336 THROW_DOM(DOMEXCEPTION_INVALID_CHARACTER_ERR,
"Invalid character");
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356QByteArray QtObject::atob(
const QByteArray &data)
const
1359 = QByteArray::fromBase64Encoding(data, QByteArray::AbortOnBase64DecodingErrors);
1360 if (result.decodingStatus == QByteArray::Base64DecodingStatus::Ok)
1361 return result.decoded;
1363 throwInvalidCharacter(v4Engine());
1364 return QByteArray();
1369 const auto fail = [&]() {
1370 throwInvalidCharacter(engine);
1371 return QByteArray();
1376 const auto append = [&](
auto value) {
1377 if (value < 0 || value >= 256)
1379 result.append(
char(value));
1383 for (
const QVariant &entry : data) {
1384 switch (entry.typeId()) {
1385 case QMetaType::Char:
1386 result.append(*
static_cast<
const char *>(entry.constData()));
1388 case QMetaType::Int: {
1389 if (!append(*
static_cast<
const int *>(entry.constData())))
1393 case QMetaType::Double: {
1394 if (!append(*
static_cast<
const double *>(entry.constData())))
1398 case QMetaType::QString: {
1399 const QString *string =
static_cast<
const QString *>(entry.constData());
1400 if (string->length() != 1)
1402 if (!append(string->at(0).unicode()))
1415
1416
1417
1418
1419
1420
1421QByteArray QtObject::btoa(
const QVariantList &data)
const
1423 return btoa(convertVariantList(data, v4Engine()));
1427
1428
1429
1430
1431
1432
1433QByteArray QtObject::atob(
const QVariantList &data)
const
1435 return atob(convertVariantList(data, v4Engine()));
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449void QtObject::quit()
const
1451 if (QQmlEngine *engine = qmlEngine())
1452 QQmlEnginePrivate::get(engine)->sendQuit();
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467void QtObject::exit(
int retCode)
const
1469 if (QQmlEngine *engine = qmlEngine())
1470 QQmlEnginePrivate::get(engine)->sendExit(retCode);
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508QObject *QtObject::createQmlObject(
const QString &qml, QObject *parent,
const QUrl &url)
const
1510 QQmlEngine *engine = qmlEngine();
1512 v4Engine()->throwError(QStringLiteral(
"Qt.createQmlObject(): "
1513 "Can only be called on a QML engine."));
1518 static ReturnedValue create(QV4::ExecutionEngine *v4,
const QList<QQmlError> &errors) {
1522 errorstr += QLatin1String(
"Qt.createQmlObject(): failed to create object: ");
1524 QV4::ScopedArrayObject qmlerrors(scope, v4->newArrayObject());
1525 QV4::ScopedObject qmlerror(scope);
1526 QV4::ScopedString s(scope);
1527 QV4::ScopedValue v(scope);
1528 for (
int ii = 0; ii < errors.size(); ++ii) {
1529 const QQmlError &error = errors.at(ii);
1530 errorstr += QLatin1String(
"\n ") + error.toString();
1531 qmlerror = v4->newObject();
1532 qmlerror->put((s = v4->newString(QStringLiteral(
"lineNumber"))), (v = QV4::Value::fromInt32(error.line())));
1533 qmlerror->put((s = v4->newString(QStringLiteral(
"columnNumber"))), (v = QV4::Value::fromInt32(error.column())));
1534 qmlerror->put((s = v4->newString(QStringLiteral(
"fileName"))), (v = v4->newString(error.url().toString())));
1535 qmlerror->put((s = v4->newString(QStringLiteral(
"message"))), (v = v4->newString(error.description())));
1536 qmlerrors->put(ii, qmlerror);
1539 v = v4->newString(errorstr);
1540 ScopedObject errorObject(scope, v4->newErrorObject(v));
1541 errorObject->put((s = v4->newString(QStringLiteral(
"qmlErrors"))), qmlerrors);
1542 return errorObject.asReturnedValue();
1546 QQmlRefPointer<QQmlContextData> context = v4Engine()->callingQmlContext();
1548 context = QQmlContextData::get(QQmlEnginePrivate::get(engine)->rootContext);
1551 QQmlContext *effectiveContext =
nullptr;
1552 if (context->isPragmaLibraryContext())
1553 effectiveContext = engine->rootContext();
1555 effectiveContext = context->asQQmlContext();
1556 Q_ASSERT(effectiveContext);
1561 QUrl resolvedUrl = url;
1562 if (url.isValid() && url.isRelative())
1563 resolvedUrl = context->resolvedUrl(url);
1566 v4Engine()->throwError(QStringLiteral(
"Qt.createQmlObject(): Missing parent object"));
1570 QQmlRefPointer<QQmlTypeData> typeData = v4Engine()->typeLoader()->getType(
1571 qml.toUtf8(), resolvedUrl, QQmlTypeLoader::Synchronous);
1573 if (!typeData->isCompleteOrError()) {
1574 v4Engine()->throwError(
1575 QStringLiteral(
"Qt.createQmlObject(): Failed to force synchronous loading "
1576 "of asynchronous URL '%1'").arg(resolvedUrl.toString()));
1580 QQmlComponent component(engine);
1581 QQmlComponentPrivate *componentPrivate = QQmlComponentPrivate::get(&component);
1582 componentPrivate->fromTypeData(typeData);
1583 componentPrivate->setProgress(1.0);
1585 Scope scope(v4Engine());
1586 if (component.isError()) {
1587 ScopedValue v(scope, Error::create(scope.engine, component.errors()));
1588 scope.engine->throwError(v);
1592 if (!component.isReady()) {
1593 v4Engine()->throwError(QStringLiteral(
"Qt.createQmlObject(): Component is not ready"));
1597 if (!effectiveContext->isValid()) {
1598 v4Engine()->throwError(QStringLiteral(
"Qt.createQmlObject(): Cannot create a component "
1599 "in an invalid context"));
1603 QObject *obj = component.beginCreate(effectiveContext);
1605 QQmlData::get(obj,
true)->explicitIndestructibleSet =
false;
1606 QQmlData::get(obj)->indestructible =
false;
1608 obj->setParent(parent);
1610 QList<QQmlPrivate::AutoParentFunction> functions = QQmlMetaType::parentFunctions();
1611 for (
int ii = 0; ii < functions.size(); ++ii) {
1612 if (QQmlPrivate::Parented == functions.at(ii)(obj, parent))
1616 component.completeCreate();
1618 v4Engine()->trimCompilationUnitsForUrl(resolvedUrl);
1619 if (component.isError()) {
1620 ScopedValue v(scope, Error::create(scope.engine, component.errors()));
1621 scope.engine->throwError(v);
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1700QQmlComponent *QtObject::createComponent(
const QUrl &url, QObject *parent)
const
1702 return createComponent(url, QQmlComponent::PreferSynchronous, parent);
1708 engine->throwError(QStringLiteral(
"Invalid compilation mode %1").arg(
int(mode)));
1712QQmlComponent *QtObject::createComponent(
const QUrl &url, QQmlComponent::CompilationMode mode,
1713 QObject *parent)
const
1715 if (mode != QQmlComponent::Asynchronous && mode != QQmlComponent::PreferSynchronous) {
1716 throw_invalid_compilation_mode(v4Engine(), mode);
1723 QQmlEngine *engine = qmlEngine();
1727 auto [context, effectiveContext] = getContexts();
1731 QQmlComponent *c =
new QQmlComponent(engine, context->resolvedUrl(url), mode, parent);
1732 QQmlComponentPrivate::get(c)->setCreationContext(std::move(effectiveContext));
1733 QQmlData::get(c,
true)->explicitIndestructibleSet =
false;
1734 QQmlData::get(c)->indestructible =
false;
1738QQmlComponent *QtObject::createComponent(
const QString &moduleUri,
const QString &typeName,
1739 QObject *parent)
const
1741 return createComponent(moduleUri, typeName, QQmlComponent::PreferSynchronous, parent);
1744QQmlComponent *QtObject::createComponent(
const QString &moduleUri,
const QString &typeName, QQmlComponent::CompilationMode mode, QObject *parent)
const
1746 if (mode != QQmlComponent::Asynchronous && mode != QQmlComponent::PreferSynchronous) {
1747 throw_invalid_compilation_mode(v4Engine(), mode);
1751 QQmlEngine *engine = qmlEngine();
1755 if (moduleUri.isEmpty() || typeName.isEmpty())
1758 auto [context, effectiveContext] = getContexts();
1762 QQmlComponent *c =
new QQmlComponent(engine, moduleUri, typeName, mode, parent);
1763 if (c->isError() && !parent && moduleUri.endsWith(u".qml")) {
1764 v4Engine()->throwTypeError(
1765 QStringLiteral(
"Invalid arguments; did you swap mode and parent"));
1767 QQmlComponentPrivate::get(c)->setCreationContext(std::move(effectiveContext));
1768 QQmlData::get(c,
true)->explicitIndestructibleSet =
false;
1769 QQmlData::get(c)->indestructible =
false;
1773#if QT_CONFIG(translation)
1774QString QtObject::uiLanguage()
const
1776 if (
const QJSEngine *e = jsEngine())
1777 return e->uiLanguage();
1781void QtObject::setUiLanguage(
const QString &uiLanguage)
1783 if (QJSEngine *e = jsEngine())
1784 e->setUiLanguage(uiLanguage);
1787QBindable<QString> QtObject::uiLanguageBindable()
1789 if (QJSEngine *e = jsEngine())
1790 return QBindable<QString>(&QJSEnginePrivate::get(e)->uiLanguage);
1791 return QBindable<QString>();
1795#if QT_CONFIG(qml_locale)
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818QLocale QtObject::locale()
const
1823QLocale QtObject::locale(
const QString &name)
const
1825 return QLocale(name);
1831 Scope scope(bindingFunction->engine());
1832 ScopedContext context(scope, bindingFunction->scope());
1833 JavaScriptFunctionObject::init(context, bindingFunction->function());
1834 this->bindingFunction.set(internalClass->engine, bindingFunction->d());
1838 const FunctionObject *f,
const Value *,
const Value *,
int)
1841 return f->engine()->throwTypeError(QStringLiteral(
"Bindings must not be called directly."));
1846 QV4::CppStackFrame *frame = engine()->currentStackFrame;
1847 if (frame->v4Function)
1848 return QQmlSourceLocation(frame->source(), frame->lineNumber(), 0);
1850 return bindingFunction()->function->sourceLocation();
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896QJSValue QtObject::binding(
const QJSValue &function)
const
1898 const QV4::JavaScriptFunctionObject *f
1899 = QJSValuePrivate::asManagedType<JavaScriptFunctionObject>(&function);
1900 QV4::ExecutionEngine *e = v4Engine();
1902 return QJSValuePrivate::fromReturnedValue(
1905 "binding(): argument (binding expression) must be a function")));
1908 return QJSValuePrivate::fromReturnedValue(
1909 Encode(e->memoryManager->allocate<QQmlBindingFunction>(f)));
1912void QtObject::callLater(QQmlV4FunctionPtr args)
1914 m_engine->delayedCallQueue()->addUniquelyAndExecuteLater(m_engine, args);
1918
1919
1920
1921
1922
1923
1924double QtObject::enumStringToValue(
const QJSManagedValue &enumType,
const QString &string)
1926 return retrieveFromEnum<
double>(
1928 [&](
const QQmlType &type, QQmlTypeLoader *typeLoader,
int enumIndex,
bool *ok) {
1929 return type.scopedEnumValue(typeLoader, enumIndex, string, ok);
1930 }, [&](
const QQmlType &type, QQmlTypeLoader *typeLoader,
int enumIndex,
bool *ok) {
1931 return type.unscopedEnumValue(typeLoader, enumIndex, string, ok);
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947QString QtObject::enumValueToString(
const QJSManagedValue &enumType,
double value)
1950 if (std::isnan(value)) {
1951 m_engine->throwReferenceError(
"Invalid second argument, entry"_L1);
1955 return retrieveFromEnum<QString>(
1957 [&](
const QQmlType &type, QQmlTypeLoader *typeLoader,
int enumIndex,
bool *ok) {
1958 return type.scopedEnumKey(typeLoader, enumIndex, QtPrivate::qSaturateRound(value), ok);
1959 }, [&](
const QQmlType &type, QQmlTypeLoader *typeLoader,
int enumIndex,
bool *ok) {
1960 return type.unscopedEnumKey(typeLoader, enumIndex, QtPrivate::qSaturateRound(value), ok);
1965
1966
1967
1968
1969
1970
1971
1972QStringList QtObject::enumValueToStrings(
const QJSManagedValue &enumType,
double value)
1975 if (std::isnan(value)) {
1976 m_engine->throwReferenceError(
"Invalid second argument, entry"_L1);
1980 return retrieveFromEnum<QStringList>(
1982 [&](
const QQmlType &type, QQmlTypeLoader *typeLoader,
int enumIndex,
bool *ok) {
1983 return type.scopedEnumKeys(typeLoader, enumIndex, QtPrivate::qSaturateRound(value), ok);
1984 }, [&](
const QQmlType &type, QQmlTypeLoader *typeLoader,
int enumIndex,
bool *ok) {
1985 return type.unscopedEnumKeys(typeLoader, enumIndex, QtPrivate::qSaturateRound(value), ok);
1989QQmlPlatform *QtObject::platform()
1992 m_platform =
new QQmlPlatform(
this);
1996QQmlApplication *QtObject::application()
2000 m_application = QQml_guiProvider()->application(
this);
2002 return m_application;
2005QObject *QtObject::inputMethod()
const
2007 return QQml_guiProvider()->inputMethod();
2010QObject *QtObject::styleHints()
const
2012 return QQml_guiProvider()->styleHints();
2018 QV4::Scope scope(internalClass->engine);
2019 QV4::ScopedObject o(scope,
this);
2021 o->defineDefaultProperty(QStringLiteral(
"debug"), QV4::ConsoleObject::method_log);
2022 o->defineDefaultProperty(QStringLiteral(
"log"), QV4::ConsoleObject::method_log);
2023 o->defineDefaultProperty(QStringLiteral(
"info"), QV4::ConsoleObject::method_info);
2024 o->defineDefaultProperty(QStringLiteral(
"warn"), QV4::ConsoleObject::method_warn);
2025 o->defineDefaultProperty(QStringLiteral(
"error"), QV4::ConsoleObject::method_error);
2026 o->defineDefaultProperty(QStringLiteral(
"assert"), QV4::ConsoleObject::method_assert);
2028 o->defineDefaultProperty(QStringLiteral(
"count"), QV4::ConsoleObject::method_count);
2029 o->defineDefaultProperty(QStringLiteral(
"profile"), QV4::ConsoleObject::method_profile);
2030 o->defineDefaultProperty(QStringLiteral(
"profileEnd"), QV4::ConsoleObject::method_profileEnd);
2031 o->defineDefaultProperty(QStringLiteral(
"time"), QV4::ConsoleObject::method_time);
2032 o->defineDefaultProperty(QStringLiteral(
"timeEnd"), QV4::ConsoleObject::method_timeEnd);
2033 o->defineDefaultProperty(QStringLiteral(
"trace"), QV4::ConsoleObject::method_trace);
2034 o->defineDefaultProperty(QStringLiteral(
"exception"), QV4::ConsoleObject::method_exception);
2049 for (CppStackFrame *f = engine->currentStackFrame; f && i < 10; f = f->parentFrame(), ++i) {
2052 if (f->isJSTypesFrame() &&
static_cast<JSTypesStackFrame *>(f)->isTailCalling()) {
2053 stackFrame = QStringLiteral(
"[elided tail calls]");
2055 const int line = f->lineNumber();
2056 if (line != f->missingLineNumber()) {
2057 stackFrame = QStringLiteral(
"%1 (%2:%3)").arg(
2058 f->function(), f->source(), QString::number(qAbs(line)));
2060 stackFrame = QStringLiteral(
"%1 (%2)").arg(
2061 f->function(), f->source());
2066 stack += QLatin1Char(
'\n');
2067 stack += stackFrame;
2074 ScopedValue val(scope);
2076 alreadySeen.insert(array->d());
2078 ScopedObject detached(scope);
2079 if (Sequence *reference = array->as<Sequence>())
2080 detached = ReferenceObject::detached(reference->d());
2084 result += QLatin1Char(
'[');
2085 const uint length = detached->getLength();
2086 for (uint i = 0; i < length; ++i) {
2088 result += QLatin1Char(
',');
2089 val = detached->get(i);
2090 if (val->isManaged() && val->managed()->isArrayLike())
2091 if (!alreadySeen.contains(val->objectValue()->d()))
2092 result += serializeArray(val->objectValue(), v4, alreadySeen);
2094 result += QLatin1String(
"[Circular]");
2096 result += val->toQStringNoThrow();
2098 result += QLatin1Char(
']');
2100 alreadySeen.remove(array->d());
2107 const QLoggingCategory *loggingCategory =
nullptr;
2109 QV4::Scope scope(b);
2110 QV4::ExecutionEngine *v4 = scope.engine;
2114 if (
const QObjectWrapper* wrapper = argv[0].as<QObjectWrapper>()) {
2115 if (QQmlLoggingCategoryBase *category
2116 = qobject_cast<QQmlLoggingCategoryBase *>(wrapper->object())) {
2117 if (category->category())
2118 loggingCategory = category->category();
2120 THROW_GENERIC_ERROR(
"A QmlLoggingCatgory was provided without a valid name");
2127 for (
int i = start, ei = argc; i < ei; ++i) {
2129 result.append(QLatin1Char(
' '));
2131 QSet<QV4::Heap::Object *> alreadySeenElements;
2132 if (argv[i].isManaged() && argv[i].managed()->isArrayLike())
2133 result.append(serializeArray(argv[i].objectValue(), v4, alreadySeenElements));
2135 result.append(argv[i].toQStringNoThrow());
2139 result += QLatin1Char(
'\n') + jsStack(v4);
2141 if (!loggingCategory)
2142 loggingCategory = v4->qmlEngine() ? &lcQml() : &lcJs();
2143 QV4::CppStackFrame *frame = v4->currentStackFrame;
2144 const QByteArray baSource = frame ? frame->source().toUtf8() : QByteArray();
2145 const QByteArray baFunction = frame ? frame->function().toUtf8() : QByteArray();
2146 QMessageLogger logger(baSource.constData(), frame ? frame->lineNumber() : 0,
2147 baFunction.constData(), loggingCategory->categoryName());
2151 if (loggingCategory->isDebugEnabled())
2152 logger.debug(
"%s", result.toUtf8().constData());
2155 if (loggingCategory->isInfoEnabled())
2156 logger.info(
"%s", result.toUtf8().constData());
2159 if (loggingCategory->isWarningEnabled())
2160 logger.warning(
"%s", result.toUtf8().constData());
2163 if (loggingCategory->isCriticalEnabled())
2164 logger.critical(
"%s", result.toUtf8().constData());
2170 return Encode::undefined();
2175ReturnedValue
ConsoleObject::method_error(
const FunctionObject *b,
const Value *,
const Value *argv,
int argc)
2177 return writeToConsole(b, argv, argc, Error);
2180ReturnedValue
ConsoleObject::method_log(
const FunctionObject *b,
const Value *,
const Value *argv,
int argc)
2185 return writeToConsole(b, argv, argc, Log);
2188ReturnedValue
ConsoleObject::method_info(
const FunctionObject *b,
const Value *,
const Value *argv,
int argc)
2190 return writeToConsole(b, argv, argc, Info);
2193ReturnedValue
ConsoleObject::method_profile(
const FunctionObject *b,
const Value *,
const Value *,
int)
2195 QV4::Scope scope(b);
2196 QV4::ExecutionEngine *v4 = scope.engine;
2198 QV4::CppStackFrame *frame = v4->currentStackFrame;
2199 const QByteArray baSource = frame->source().toUtf8();
2200 const QByteArray baFunction = frame->function().toUtf8();
2201 QMessageLogger logger(baSource.constData(), frame->lineNumber(), baFunction.constData());
2202 QQmlProfilerService *service = QQmlDebugConnector::service<QQmlProfilerService>();
2204 logger.warning(
"Cannot start profiling because debug service is disabled. Start with -qmljsdebugger=port:XXXXX.");
2206 service->startProfiling(v4->jsEngine());
2207 logger.debug(
"Profiling started.");
2210 return QV4::Encode::undefined();
2213ReturnedValue
ConsoleObject::method_profileEnd(
const FunctionObject *b,
const Value *,
const Value *,
int)
2215 QV4::Scope scope(b);
2216 QV4::ExecutionEngine *v4 = scope.engine;
2218 QV4::CppStackFrame *frame = v4->currentStackFrame;
2219 const QByteArray baSource = frame->source().toUtf8();
2220 const QByteArray baFunction = frame->function().toUtf8();
2221 QMessageLogger logger(baSource.constData(), frame->lineNumber(), baFunction.constData());
2223 QQmlProfilerService *service = QQmlDebugConnector::service<QQmlProfilerService>();
2225 logger.warning(
"Ignoring console.profileEnd(): the debug service is disabled.");
2227 service->stopProfiling(v4->jsEngine());
2228 logger.debug(
"Profiling ended.");
2231 return QV4::Encode::undefined();
2234ReturnedValue
ConsoleObject::method_time(
const FunctionObject *b,
const Value *,
const Value *argv,
int argc)
2236 QV4::Scope scope(b);
2238 THROW_GENERIC_ERROR(
"console.time(): Invalid arguments");
2240 QString name = argv[0].toQStringNoThrow();
2241 scope.engine->startTimer(name);
2242 return QV4::Encode::undefined();
2245ReturnedValue
ConsoleObject::method_timeEnd(
const FunctionObject *b,
const Value *,
const Value *argv,
int argc)
2247 QV4::Scope scope(b);
2249 THROW_GENERIC_ERROR(
"console.timeEnd(): Invalid arguments");
2251 QString name = argv[0].toQStringNoThrow();
2253 qint64 elapsed = scope.engine->stopTimer(name, &wasRunning);
2255 qDebug(
"%s: %llims", qPrintable(name), elapsed);
2257 return QV4::Encode::undefined();
2260ReturnedValue
ConsoleObject::method_count(
const FunctionObject *b,
const Value *,
const Value *argv,
int argc)
2265 name = argv[0].toQStringNoThrow();
2268 QV4::ExecutionEngine *v4 = scope.engine;
2270 QV4::CppStackFrame *frame = v4->currentStackFrame;
2272 QString scriptName = frame->source();
2274 int value = v4->consoleCountHelper(scriptName, frame->lineNumber(), 0);
2275 QString message = name + QLatin1String(
": ") + QString::number(value);
2277 QMessageLogger(qPrintable(scriptName), frame->lineNumber(),
2278 qPrintable(frame->function()))
2279 .debug(
"%s", qPrintable(message));
2281 return QV4::Encode::undefined();
2284ReturnedValue
ConsoleObject::method_trace(
const FunctionObject *b,
const Value *,
const Value *,
int argc)
2286 QV4::Scope scope(b);
2288 THROW_GENERIC_ERROR(
"console.trace(): Invalid arguments");
2290 QV4::ExecutionEngine *v4 = scope.engine;
2292 QString stack = jsStack(v4);
2294 QV4::CppStackFrame *frame = v4->currentStackFrame;
2295 QMessageLogger(frame->source().toUtf8().constData(), frame->lineNumber(),
2296 frame->function().toUtf8().constData())
2297 .debug(v4->qmlEngine() ? lcQml() : lcJs(),
"%s", qPrintable(stack));
2299 return QV4::Encode::undefined();
2302ReturnedValue
ConsoleObject::method_warn(
const FunctionObject *b,
const Value *,
const Value *argv,
int argc)
2304 return writeToConsole(b, argv, argc, Warn);
2307ReturnedValue
ConsoleObject::method_assert(
const FunctionObject *b,
const Value *,
const Value *argv,
int argc)
2309 QV4::Scope scope(b);
2311 THROW_GENERIC_ERROR(
"console.assert(): Missing argument");
2313 QV4::ExecutionEngine *v4 = scope.engine;
2315 if (!argv[0].toBoolean()) {
2317 for (
int i = 1, ei = argc; i < ei; ++i) {
2319 message.append(QLatin1Char(
' '));
2321 message.append(argv[i].toQStringNoThrow());
2324 QString stack = jsStack(v4);
2326 QV4::CppStackFrame *frame = v4->currentStackFrame;
2327 QMessageLogger(frame->source().toUtf8().constData(), frame->lineNumber(),
2328 frame->function().toUtf8().constData())
2329 .critical(
"%s\n%s",qPrintable(message), qPrintable(stack));
2332 return QV4::Encode::undefined();
2335ReturnedValue
ConsoleObject::method_exception(
const FunctionObject *b,
const Value *,
const Value *argv,
int argc)
2337 QV4::Scope scope(b);
2339 THROW_GENERIC_ERROR(
"console.exception(): Missing argument");
2341 return writeToConsole(b, argv, argc, Error,
true);
2344void QV4::GlobalExtensions::init(Object *globalObject, QJSEngine::Extensions extensions)
2346 ExecutionEngine *v4 = globalObject->engine();
2349 if (extensions.testFlag(QJSEngine::TranslationExtension)) {
2350 #if QT_CONFIG(translation)
2351 globalObject->defineDefaultProperty(QStringLiteral(
"qsTranslate"), QV4::GlobalExtensions::method_qsTranslate);
2352 globalObject->defineDefaultProperty(QStringLiteral(
"QT_TRANSLATE_NOOP"), QV4::GlobalExtensions::method_qsTranslateNoOp);
2353 globalObject->defineDefaultProperty(QStringLiteral(
"qsTr"), QV4::GlobalExtensions::method_qsTr);
2354 globalObject->defineDefaultProperty(QStringLiteral(
"QT_TR_NOOP"), QV4::GlobalExtensions::method_qsTrNoOp);
2355 globalObject->defineDefaultProperty(QStringLiteral(
"qsTrId"), QV4::GlobalExtensions::method_qsTrId);
2356 globalObject->defineDefaultProperty(QStringLiteral(
"QT_TRID_NOOP"), QV4::GlobalExtensions::method_qsTrIdNoOp);
2359 ScopedString qtName(scope, v4->newString(QStringLiteral(
"Qt")));
2360 ScopedObject qt(scope, globalObject->get(qtName));
2362 v4->createQtObject();
2365 scope.engine->stringPrototype()->defineDefaultProperty(QStringLiteral(
"arg"), QV4::GlobalExtensions::method_string_arg);
2369 if (extensions.testFlag(QJSEngine::ConsoleExtension)) {
2370 globalObject->defineDefaultProperty(QStringLiteral(
"print"), QV4::ConsoleObject::method_log);
2373 QV4::ScopedObject console(scope, globalObject->engine()->memoryManager->allocate<QV4::ConsoleObject>());
2374 globalObject->defineDefaultProperty(QStringLiteral(
"console"), console);
2377 if (extensions.testFlag(QJSEngine::GarbageCollectionExtension)) {
2378 globalObject->defineDefaultProperty(QStringLiteral(
"gc"), QV4::GlobalExtensions::method_gc);
2383#if QT_CONFIG(translation)
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404ReturnedValue GlobalExtensions::method_qsTranslate(
const FunctionObject *b,
const Value *,
const Value *argv,
int argc)
2406 QV4::Scope scope(b);
2408 THROW_GENERIC_ERROR(
"qsTranslate() requires at least two arguments");
2409 if (!argv[0].isString())
2410 THROW_GENERIC_ERROR(
"qsTranslate(): first argument (context) must be a string");
2411 if (!argv[1].isString())
2412 THROW_GENERIC_ERROR(
"qsTranslate(): second argument (sourceText) must be a string");
2413 if ((argc > 2) && !argv[2].isString())
2414 THROW_GENERIC_ERROR(
"qsTranslate(): third argument (disambiguation) must be a string");
2416 QString context = argv[0].toQStringNoThrow();
2417 QString text = argv[1].toQStringNoThrow();
2419 if (argc > 2) comment = argv[2].toQStringNoThrow();
2422 if (argc > i && argv[i].isString()) {
2423 qWarning(
"qsTranslate(): specifying the encoding as fourth argument is deprecated");
2429 n = argv[i].toInt32();
2431 if (QQmlEnginePrivate *ep = (scope.engine->qmlEngine() ? QQmlEnginePrivate::get(scope.engine->qmlEngine()) :
nullptr))
2432 if (ep->propertyCapture)
2433 ep->propertyCapture->captureTranslation();
2435 QString result = QCoreApplication::translate(context.toUtf8().constData(),
2436 text.toUtf8().constData(),
2437 comment.toUtf8().constData(),
2440 return Encode(scope.engine->newString(result));
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465ReturnedValue GlobalExtensions::method_qsTranslateNoOp(
const FunctionObject *b,
const Value *,
const Value *argv,
int argc)
2467 QV4::Scope scope(b);
2469 return QV4::Encode::undefined();
2471 return argv[1].asReturnedValue();
2474QString GlobalExtensions::currentTranslationContext(ExecutionEngine *engine)
2477 CppStackFrame *frame = engine->currentStackFrame;
2480 while (frame && context.isEmpty()) {
2481 if (ExecutableCompilationUnit *unit = frame->v4Function->executableCompilationUnit()) {
2482 auto translationContextIndex = unit->unitData()->translationContextIndex();
2483 if (translationContextIndex)
2484 context = unit->stringAt(*translationContextIndex);
2485 if (!context.isEmpty())
2487 QString fileName = unit->fileName();
2488 QUrl url(unit->fileName());
2489 if (url.isValid() && url.isRelative()) {
2490 context = url.fileName();
2492 context = QQmlFile::urlToLocalFileOrQrc(fileName);
2493 if (context.isEmpty() && fileName.startsWith(QLatin1String(
":/")))
2496 context = QFileInfo(context).completeBaseName();
2498 frame = frame->parentFrame();
2501 if (context.isEmpty()) {
2502 if (QQmlRefPointer<QQmlContextData> ctxt = engine->callingQmlContext()) {
2503 QString path = ctxt->urlString();
2504 int lastSlash = path.lastIndexOf(QLatin1Char(
'/'));
2505 int lastDot = path.lastIndexOf(QLatin1Char(
'.'));
2506 int length = lastDot - (lastSlash + 1);
2507 context = (lastSlash > -1) ? path.mid(lastSlash + 1, (length > -1) ? length : -1) : QString();
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551ReturnedValue GlobalExtensions::method_qsTr(
const FunctionObject *b,
const Value *,
const Value *argv,
int argc)
2553 QV4::Scope scope(b);
2555 THROW_GENERIC_ERROR(
"qsTr() requires at least one argument");
2556 if (!argv[0].isString())
2557 THROW_GENERIC_ERROR(
"qsTr(): first argument (sourceText) must be a string");
2558 if ((argc > 1) && !argv[1].isString())
2559 THROW_GENERIC_ERROR(
"qsTr(): second argument (disambiguation) must be a string");
2560 if ((argc > 2) && !argv[2].isNumber())
2561 THROW_GENERIC_ERROR(
"qsTr(): third argument (n) must be a number");
2563 const QString context = currentTranslationContext(scope.engine);
2564 const QString text = argv[0].toQStringNoThrow();
2565 const QString comment = argc > 1 ? argv[1].toQStringNoThrow() : QString();
2566 const int n = argc > 2 ? argv[2].toInt32() : -1;
2568 if (QQmlEnginePrivate *ep = (scope.engine->qmlEngine() ? QQmlEnginePrivate::get(scope.engine->qmlEngine()) :
nullptr))
2569 if (ep->propertyCapture)
2570 ep->propertyCapture->captureTranslation();
2572 QString result = QCoreApplication::translate(context.toUtf8().constData(), text.toUtf8().constData(),
2573 comment.toUtf8().constData(), n);
2575 return Encode(scope.engine->newString(result));
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600ReturnedValue GlobalExtensions::method_qsTrNoOp(
const FunctionObject *,
const Value *,
const Value *argv,
int argc)
2603 return QV4::Encode::undefined();
2605 return argv[0].asReturnedValue();
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639ReturnedValue GlobalExtensions::method_qsTrId(
const FunctionObject *b,
const Value *,
const Value *argv,
int argc)
2641 QV4::Scope scope(b);
2643 THROW_GENERIC_ERROR(
"qsTrId() requires at least one argument");
2644 if (!argv[0].isString())
2645 THROW_TYPE_ERROR_WITH_MESSAGE(
"qsTrId(): first argument (id) must be a string");
2646 if (argc > 1 && !argv[1].isNumber())
2647 THROW_TYPE_ERROR_WITH_MESSAGE(
"qsTrId(): second argument (n) must be a number");
2651 n = argv[1].toInt32();
2653 if (QQmlEnginePrivate *ep = (scope.engine->qmlEngine() ? QQmlEnginePrivate::get(scope.engine->qmlEngine()) :
nullptr))
2654 if (ep->propertyCapture)
2655 ep->propertyCapture->captureTranslation();
2657 return Encode(scope.engine->newString(qtTrId(argv[0].toQStringNoThrow().toUtf8().constData(), n)));
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676ReturnedValue GlobalExtensions::method_qsTrIdNoOp(
const FunctionObject *,
const Value *,
const Value *argv,
int argc)
2679 return QV4::Encode::undefined();
2681 return argv[0].asReturnedValue();
2686
2687
2688
2689
2690
2691
2692
2693
2694ReturnedValue GlobalExtensions::method_gc(
const FunctionObject *b,
const Value *,
const Value *,
int)
2696 auto mm = b->engine()->memoryManager;
2699 return QV4::Encode::undefined();
2702ReturnedValue GlobalExtensions::method_string_arg(
const FunctionObject *b,
const Value *thisObject,
const Value *argv,
int argc)
2704 QV4::Scope scope(b);
2706 THROW_GENERIC_ERROR(
"String.arg(): Invalid arguments");
2708 QString value = thisObject->toQString();
2712 QV4::ScopedValue arg(scope, argv[0]);
2713 if (arg->isInteger())
2714 value = value.arg(arg->integerValue());
2715 else if (arg->isDouble())
2716 value = value.arg(arg->doubleValue());
2717 else if (arg->isBoolean())
2718 value = value.arg(arg->booleanValue());
2720 value = value.arg(arg->toQString());
2721 RETURN_RESULT(scope.engine->newString(value));
2725 constexpr int PreallocArgCount = 10;
2728 QVarLengthArray<QString, PreallocArgCount> argStrings(argc);
2729 QVarLengthArray<QtPrivate::QStringViewArg, PreallocArgCount> args(argc);
2730 QVarLengthArray<
const QtPrivate::ArgBase *, PreallocArgCount> argBases(argc);
2732 for (
int i = 0; i < argc; ++i) {
2733 QV4::ScopedValue arg(scope, argv[i]);
2735 if (arg->isInteger())
2736 argStrings[i] = QString::number(arg->integerValue());
2737 else if (arg->isDouble())
2738 argStrings[i] = QString::number(arg->doubleValue());
2739 else if (arg->isBoolean())
2740 argStrings[i] = QString::number(arg->booleanValue());
2742 argStrings[i] = arg->toQString();
2744 args[i] = QtPrivate::QStringViewArg(argStrings[i]);
2745 argBases[i] = &args[i];
2748 QString result = QtPrivate::argToQString(value, argc, argBases.data());
2749 RETURN_RESULT(scope.engine->newString(result));
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2775#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