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
1166bool QtObject::openUrlExternally(
const QUrl &url)
const
1168 return QQml_guiProvider()->openUrlExternally(resolvedUrl(url));
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181QUrl QtObject::url(
const QUrl &url)
const
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197QUrl QtObject::resolvedUrl(
const QUrl &url)
const
1199 if (QQmlRefPointer<QQmlContextData> ctxt = v4Engine()->callingQmlContext())
1200 return ctxt->resolvedUrl(url);
1201 if (QQmlEngine *engine = qmlEngine())
1202 return engine->baseUrl().resolved(url);
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216QUrl QtObject::resolvedUrl(
const QUrl &url, QObject *context)
const
1219 QQmlData *data = QQmlData::get(context);
1220 if (data && data->outerContext)
1221 return data->outerContext->resolvedUrl(url);
1224 if (QQmlEngine *engine = qmlEngine())
1225 return engine->baseUrl().resolved(url);
1230
1231
1232
1233
1234QStringList QtObject::fontFamilies()
const
1236 return QQml_guiProvider()->fontFamilies();
1240
1241
1242
1243QString QtObject::md5(
const QString &data)
const
1245 return QLatin1String(QCryptographicHash::hash(data.toUtf8(), QCryptographicHash::Md5).toHex());
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266QString QtObject::escapeHtml(
const QString &data)
const
1268 return data.toHtmlEscaped();
1272
1273
1274
1275
1276
1277QString QtObject::btoa(
const QString &data)
const
1279 qWarning(
"Qt.btoa(string): This method is deprecated. "
1280 "Its output differs from the common Web API. "
1281 "Use the overloads that take array-likes.");
1282 return QLatin1String(data.toUtf8().toBase64());
1286
1287
1288
1289
1290
1291
1292QString QtObject::atob(
const QString &data)
const
1294 qWarning(
"Qt.atob(string): This method is deprecated. "
1295 "Its output differs from the common Web API. "
1296 "Use the overloads that take array-likes.");
1297 return QString::fromUtf8(QByteArray::fromBase64(data.toLatin1()));
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317QByteArray QtObject::btoa(
const QByteArray &data)
const
1319 return data.toBase64();
1324 QV4::Scope scope(engine);
1325 THROW_DOM(DOMEXCEPTION_INVALID_CHARACTER_ERR,
"Invalid character");
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345QByteArray QtObject::atob(
const QByteArray &data)
const
1348 = QByteArray::fromBase64Encoding(data, QByteArray::AbortOnBase64DecodingErrors);
1349 if (result.decodingStatus == QByteArray::Base64DecodingStatus::Ok)
1350 return result.decoded;
1352 throwInvalidCharacter(v4Engine());
1353 return QByteArray();
1358 const auto fail = [&]() {
1359 throwInvalidCharacter(engine);
1360 return QByteArray();
1365 const auto append = [&](
auto value) {
1366 if (value < 0 || value >= 256)
1368 result.append(
char(value));
1372 for (
const QVariant &entry : data) {
1373 switch (entry.typeId()) {
1374 case QMetaType::Char:
1375 result.append(*
static_cast<
const char *>(entry.constData()));
1377 case QMetaType::Int: {
1378 if (!append(*
static_cast<
const int *>(entry.constData())))
1382 case QMetaType::Double: {
1383 if (!append(*
static_cast<
const double *>(entry.constData())))
1387 case QMetaType::QString: {
1388 const QString *string =
static_cast<
const QString *>(entry.constData());
1389 if (string->length() != 1)
1391 if (!append(string->at(0).unicode()))
1404
1405
1406
1407
1408
1409
1410QByteArray QtObject::btoa(
const QVariantList &data)
const
1412 return btoa(convertVariantList(data, v4Engine()));
1416
1417
1418
1419
1420
1421
1422QByteArray QtObject::atob(
const QVariantList &data)
const
1424 return atob(convertVariantList(data, v4Engine()));
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438void QtObject::quit()
const
1440 if (QQmlEngine *engine = qmlEngine())
1441 QQmlEnginePrivate::get(engine)->sendQuit();
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456void QtObject::exit(
int retCode)
const
1458 if (QQmlEngine *engine = qmlEngine())
1459 QQmlEnginePrivate::get(engine)->sendExit(retCode);
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497QObject *QtObject::createQmlObject(
const QString &qml, QObject *parent,
const QUrl &url)
const
1499 QQmlEngine *engine = qmlEngine();
1501 v4Engine()->throwError(QStringLiteral(
"Qt.createQmlObject(): "
1502 "Can only be called on a QML engine."));
1507 static ReturnedValue create(QV4::ExecutionEngine *v4,
const QList<QQmlError> &errors) {
1511 errorstr += QLatin1String(
"Qt.createQmlObject(): failed to create object: ");
1513 QV4::ScopedArrayObject qmlerrors(scope, v4->newArrayObject());
1514 QV4::ScopedObject qmlerror(scope);
1515 QV4::ScopedString s(scope);
1516 QV4::ScopedValue v(scope);
1517 for (
int ii = 0; ii < errors.size(); ++ii) {
1518 const QQmlError &error = errors.at(ii);
1519 errorstr += QLatin1String(
"\n ") + error.toString();
1520 qmlerror = v4->newObject();
1521 qmlerror->put((s = v4->newString(QStringLiteral(
"lineNumber"))), (v = QV4::Value::fromInt32(error.line())));
1522 qmlerror->put((s = v4->newString(QStringLiteral(
"columnNumber"))), (v = QV4::Value::fromInt32(error.column())));
1523 qmlerror->put((s = v4->newString(QStringLiteral(
"fileName"))), (v = v4->newString(error.url().toString())));
1524 qmlerror->put((s = v4->newString(QStringLiteral(
"message"))), (v = v4->newString(error.description())));
1525 qmlerrors->put(ii, qmlerror);
1528 v = v4->newString(errorstr);
1529 ScopedObject errorObject(scope, v4->newErrorObject(v));
1530 errorObject->put((s = v4->newString(QStringLiteral(
"qmlErrors"))), qmlerrors);
1531 return errorObject.asReturnedValue();
1535 QQmlRefPointer<QQmlContextData> context = v4Engine()->callingQmlContext();
1537 context = QQmlContextData::get(QQmlEnginePrivate::get(engine)->rootContext);
1540 QQmlContext *effectiveContext =
nullptr;
1541 if (context->isPragmaLibraryContext())
1542 effectiveContext = engine->rootContext();
1544 effectiveContext = context->asQQmlContext();
1545 Q_ASSERT(effectiveContext);
1550 QUrl resolvedUrl = url;
1551 if (url.isValid() && url.isRelative())
1552 resolvedUrl = context->resolvedUrl(url);
1555 v4Engine()->throwError(QStringLiteral(
"Qt.createQmlObject(): Missing parent object"));
1559 QQmlRefPointer<QQmlTypeData> typeData = v4Engine()->typeLoader()->getType(
1560 qml.toUtf8(), resolvedUrl, QQmlTypeLoader::Synchronous);
1562 if (!typeData->isCompleteOrError()) {
1563 v4Engine()->throwError(
1564 QStringLiteral(
"Qt.createQmlObject(): Failed to force synchronous loading "
1565 "of asynchronous URL '%1'").arg(resolvedUrl.toString()));
1569 QQmlComponent component(engine);
1570 QQmlComponentPrivate *componentPrivate = QQmlComponentPrivate::get(&component);
1571 componentPrivate->fromTypeData(typeData);
1572 componentPrivate->setProgress(1.0);
1574 Scope scope(v4Engine());
1575 if (component.isError()) {
1576 ScopedValue v(scope, Error::create(scope.engine, component.errors()));
1577 scope.engine->throwError(v);
1581 if (!component.isReady()) {
1582 v4Engine()->throwError(QStringLiteral(
"Qt.createQmlObject(): Component is not ready"));
1586 if (!effectiveContext->isValid()) {
1587 v4Engine()->throwError(QStringLiteral(
"Qt.createQmlObject(): Cannot create a component "
1588 "in an invalid context"));
1592 QObject *obj = component.beginCreate(effectiveContext);
1594 QQmlData::get(obj,
true)->explicitIndestructibleSet =
false;
1595 QQmlData::get(obj)->indestructible =
false;
1597 obj->setParent(parent);
1599 QList<QQmlPrivate::AutoParentFunction> functions = QQmlMetaType::parentFunctions();
1600 for (
int ii = 0; ii < functions.size(); ++ii) {
1601 if (QQmlPrivate::Parented == functions.at(ii)(obj, parent))
1605 component.completeCreate();
1607 v4Engine()->trimCompilationUnitsForUrl(resolvedUrl);
1608 if (component.isError()) {
1609 ScopedValue v(scope, Error::create(scope.engine, component.errors()));
1610 scope.engine->throwError(v);
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
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
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1689QQmlComponent *QtObject::createComponent(
const QUrl &url, QObject *parent)
const
1691 return createComponent(url, QQmlComponent::PreferSynchronous, parent);
1697 engine->throwError(QStringLiteral(
"Invalid compilation mode %1").arg(
int(mode)));
1701QQmlComponent *QtObject::createComponent(
const QUrl &url, QQmlComponent::CompilationMode mode,
1702 QObject *parent)
const
1704 if (mode != QQmlComponent::Asynchronous && mode != QQmlComponent::PreferSynchronous) {
1705 throw_invalid_compilation_mode(v4Engine(), mode);
1712 QQmlEngine *engine = qmlEngine();
1716 auto [context, effectiveContext] = getContexts();
1720 QQmlComponent *c =
new QQmlComponent(engine, context->resolvedUrl(url), mode, parent);
1721 QQmlComponentPrivate::get(c)->setCreationContext(std::move(effectiveContext));
1722 QQmlData::get(c,
true)->explicitIndestructibleSet =
false;
1723 QQmlData::get(c)->indestructible =
false;
1727QQmlComponent *QtObject::createComponent(
const QString &moduleUri,
const QString &typeName,
1728 QObject *parent)
const
1730 return createComponent(moduleUri, typeName, QQmlComponent::PreferSynchronous, parent);
1733QQmlComponent *QtObject::createComponent(
const QString &moduleUri,
const QString &typeName, QQmlComponent::CompilationMode mode, QObject *parent)
const
1735 if (mode != QQmlComponent::Asynchronous && mode != QQmlComponent::PreferSynchronous) {
1736 throw_invalid_compilation_mode(v4Engine(), mode);
1740 QQmlEngine *engine = qmlEngine();
1744 if (moduleUri.isEmpty() || typeName.isEmpty())
1747 auto [context, effectiveContext] = getContexts();
1751 QQmlComponent *c =
new QQmlComponent(engine, moduleUri, typeName, mode, parent);
1752 if (c->isError() && !parent && moduleUri.endsWith(u".qml")) {
1753 v4Engine()->throwTypeError(
1754 QStringLiteral(
"Invalid arguments; did you swap mode and parent"));
1756 QQmlComponentPrivate::get(c)->setCreationContext(std::move(effectiveContext));
1757 QQmlData::get(c,
true)->explicitIndestructibleSet =
false;
1758 QQmlData::get(c)->indestructible =
false;
1762#if QT_CONFIG(translation)
1763QString QtObject::uiLanguage()
const
1765 if (
const QJSEngine *e = jsEngine())
1766 return e->uiLanguage();
1770void QtObject::setUiLanguage(
const QString &uiLanguage)
1772 if (QJSEngine *e = jsEngine())
1773 e->setUiLanguage(uiLanguage);
1776QBindable<QString> QtObject::uiLanguageBindable()
1778 if (QJSEngine *e = jsEngine())
1779 return QBindable<QString>(&QJSEnginePrivate::get(e)->uiLanguage);
1780 return QBindable<QString>();
1784#if QT_CONFIG(qml_locale)
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807QLocale QtObject::locale()
const
1812QLocale QtObject::locale(
const QString &name)
const
1814 return QLocale(name);
1820 Scope scope(bindingFunction->engine());
1821 ScopedContext context(scope, bindingFunction->scope());
1822 JavaScriptFunctionObject::init(context, bindingFunction->function());
1823 this->bindingFunction.set(internalClass->engine, bindingFunction->d());
1827 const FunctionObject *f,
const Value *,
const Value *,
int)
1830 return f->engine()->throwTypeError(QStringLiteral(
"Bindings must not be called directly."));
1835 QV4::CppStackFrame *frame = engine()->currentStackFrame;
1836 if (frame->v4Function)
1837 return QQmlSourceLocation(frame->source(), frame->lineNumber(), 0);
1839 return bindingFunction()->function->sourceLocation();
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
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
1885QJSValue QtObject::binding(
const QJSValue &function)
const
1887 const QV4::JavaScriptFunctionObject *f
1888 = QJSValuePrivate::asManagedType<JavaScriptFunctionObject>(&function);
1889 QV4::ExecutionEngine *e = v4Engine();
1891 return QJSValuePrivate::fromReturnedValue(
1894 "binding(): argument (binding expression) must be a function")));
1897 return QJSValuePrivate::fromReturnedValue(
1898 Encode(e->memoryManager->allocate<QQmlBindingFunction>(f)));
1901void QtObject::callLater(QQmlV4FunctionPtr args)
1903 m_engine->delayedCallQueue()->addUniquelyAndExecuteLater(m_engine, args);
1907
1908
1909
1910
1911
1912
1913double QtObject::enumStringToValue(
const QJSManagedValue &enumType,
const QString &string)
1915 return retrieveFromEnum<
double>(
1917 [&](
const QQmlType &type, QQmlTypeLoader *typeLoader,
int enumIndex,
bool *ok) {
1918 return type.scopedEnumValue(typeLoader, enumIndex, string, ok);
1919 }, [&](
const QQmlType &type, QQmlTypeLoader *typeLoader,
int enumIndex,
bool *ok) {
1920 return type.unscopedEnumValue(typeLoader, enumIndex, string, ok);
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936QString QtObject::enumValueToString(
const QJSManagedValue &enumType,
double value)
1939 if (std::isnan(value)) {
1940 m_engine->throwReferenceError(
"Invalid second argument, entry"_L1);
1944 return retrieveFromEnum<QString>(
1946 [&](
const QQmlType &type, QQmlTypeLoader *typeLoader,
int enumIndex,
bool *ok) {
1947 return type.scopedEnumKey(typeLoader, enumIndex, QtPrivate::qSaturateRound(value), ok);
1948 }, [&](
const QQmlType &type, QQmlTypeLoader *typeLoader,
int enumIndex,
bool *ok) {
1949 return type.unscopedEnumKey(typeLoader, enumIndex, QtPrivate::qSaturateRound(value), ok);
1954
1955
1956
1957
1958
1959
1960
1961QStringList QtObject::enumValueToStrings(
const QJSManagedValue &enumType,
double value)
1964 if (std::isnan(value)) {
1965 m_engine->throwReferenceError(
"Invalid second argument, entry"_L1);
1969 return retrieveFromEnum<QStringList>(
1971 [&](
const QQmlType &type, QQmlTypeLoader *typeLoader,
int enumIndex,
bool *ok) {
1972 return type.scopedEnumKeys(typeLoader, enumIndex, QtPrivate::qSaturateRound(value), ok);
1973 }, [&](
const QQmlType &type, QQmlTypeLoader *typeLoader,
int enumIndex,
bool *ok) {
1974 return type.unscopedEnumKeys(typeLoader, enumIndex, QtPrivate::qSaturateRound(value), ok);
1978QQmlPlatform *QtObject::platform()
1981 m_platform =
new QQmlPlatform(
this);
1985QQmlApplication *QtObject::application()
1989 m_application = QQml_guiProvider()->application(
this);
1991 return m_application;
1994QObject *QtObject::inputMethod()
const
1996 return QQml_guiProvider()->inputMethod();
1999QObject *QtObject::styleHints()
const
2001 return QQml_guiProvider()->styleHints();
2007 QV4::Scope scope(internalClass->engine);
2008 QV4::ScopedObject o(scope,
this);
2010 o->defineDefaultProperty(QStringLiteral(
"debug"), QV4::ConsoleObject::method_log);
2011 o->defineDefaultProperty(QStringLiteral(
"log"), QV4::ConsoleObject::method_log);
2012 o->defineDefaultProperty(QStringLiteral(
"info"), QV4::ConsoleObject::method_info);
2013 o->defineDefaultProperty(QStringLiteral(
"warn"), QV4::ConsoleObject::method_warn);
2014 o->defineDefaultProperty(QStringLiteral(
"error"), QV4::ConsoleObject::method_error);
2015 o->defineDefaultProperty(QStringLiteral(
"assert"), QV4::ConsoleObject::method_assert);
2017 o->defineDefaultProperty(QStringLiteral(
"count"), QV4::ConsoleObject::method_count);
2018 o->defineDefaultProperty(QStringLiteral(
"profile"), QV4::ConsoleObject::method_profile);
2019 o->defineDefaultProperty(QStringLiteral(
"profileEnd"), QV4::ConsoleObject::method_profileEnd);
2020 o->defineDefaultProperty(QStringLiteral(
"time"), QV4::ConsoleObject::method_time);
2021 o->defineDefaultProperty(QStringLiteral(
"timeEnd"), QV4::ConsoleObject::method_timeEnd);
2022 o->defineDefaultProperty(QStringLiteral(
"trace"), QV4::ConsoleObject::method_trace);
2023 o->defineDefaultProperty(QStringLiteral(
"exception"), QV4::ConsoleObject::method_exception);
2038 for (CppStackFrame *f = engine->currentStackFrame; f && i < 10; f = f->parentFrame(), ++i) {
2041 if (f->isJSTypesFrame() &&
static_cast<JSTypesStackFrame *>(f)->isTailCalling()) {
2042 stackFrame = QStringLiteral(
"[elided tail calls]");
2044 const int line = f->lineNumber();
2045 if (line != f->missingLineNumber()) {
2046 stackFrame = QStringLiteral(
"%1 (%2:%3)").arg(
2047 f->function(), f->source(), QString::number(qAbs(line)));
2049 stackFrame = QStringLiteral(
"%1 (%2)").arg(
2050 f->function(), f->source());
2055 stack += QLatin1Char(
'\n');
2056 stack += stackFrame;
2063 ScopedValue val(scope);
2065 alreadySeen.insert(array->d());
2067 ScopedObject detached(scope);
2068 if (Sequence *reference = array->as<Sequence>())
2069 detached = ReferenceObject::detached(reference->d());
2073 result += QLatin1Char(
'[');
2074 const uint length = detached->getLength();
2075 for (uint i = 0; i < length; ++i) {
2077 result += QLatin1Char(
',');
2078 val = detached->get(i);
2079 if (val->isManaged() && val->managed()->isArrayLike())
2080 if (!alreadySeen.contains(val->objectValue()->d()))
2081 result += serializeArray(val->objectValue(), v4, alreadySeen);
2083 result += QLatin1String(
"[Circular]");
2085 result += val->toQStringNoThrow();
2087 result += QLatin1Char(
']');
2089 alreadySeen.remove(array->d());
2096 const QLoggingCategory *loggingCategory =
nullptr;
2098 QV4::Scope scope(b);
2099 QV4::ExecutionEngine *v4 = scope.engine;
2103 if (
const QObjectWrapper* wrapper = argv[0].as<QObjectWrapper>()) {
2104 if (QQmlLoggingCategoryBase *category
2105 = qobject_cast<QQmlLoggingCategoryBase *>(wrapper->object())) {
2106 if (category->category())
2107 loggingCategory = category->category();
2109 THROW_GENERIC_ERROR(
"A QmlLoggingCatgory was provided without a valid name");
2116 for (
int i = start, ei = argc; i < ei; ++i) {
2118 result.append(QLatin1Char(
' '));
2120 QSet<QV4::Heap::Object *> alreadySeenElements;
2121 if (argv[i].isManaged() && argv[i].managed()->isArrayLike())
2122 result.append(serializeArray(argv[i].objectValue(), v4, alreadySeenElements));
2124 result.append(argv[i].toQStringNoThrow());
2128 result += QLatin1Char(
'\n') + jsStack(v4);
2130 if (!loggingCategory)
2131 loggingCategory = v4->qmlEngine() ? &lcQml() : &lcJs();
2132 QV4::CppStackFrame *frame = v4->currentStackFrame;
2133 const QByteArray baSource = frame ? frame->source().toUtf8() : QByteArray();
2134 const QByteArray baFunction = frame ? frame->function().toUtf8() : QByteArray();
2135 QMessageLogger logger(baSource.constData(), frame ? frame->lineNumber() : 0,
2136 baFunction.constData(), loggingCategory->categoryName());
2140 if (loggingCategory->isDebugEnabled())
2141 logger.debug(
"%s", result.toUtf8().constData());
2144 if (loggingCategory->isInfoEnabled())
2145 logger.info(
"%s", result.toUtf8().constData());
2148 if (loggingCategory->isWarningEnabled())
2149 logger.warning(
"%s", result.toUtf8().constData());
2152 if (loggingCategory->isCriticalEnabled())
2153 logger.critical(
"%s", result.toUtf8().constData());
2159 return Encode::undefined();
2164ReturnedValue
ConsoleObject::method_error(
const FunctionObject *b,
const Value *,
const Value *argv,
int argc)
2166 return writeToConsole(b, argv, argc, Error);
2169ReturnedValue
ConsoleObject::method_log(
const FunctionObject *b,
const Value *,
const Value *argv,
int argc)
2174 return writeToConsole(b, argv, argc, Log);
2177ReturnedValue
ConsoleObject::method_info(
const FunctionObject *b,
const Value *,
const Value *argv,
int argc)
2179 return writeToConsole(b, argv, argc, Info);
2182ReturnedValue
ConsoleObject::method_profile(
const FunctionObject *b,
const Value *,
const Value *,
int)
2184 QV4::Scope scope(b);
2185 QV4::ExecutionEngine *v4 = scope.engine;
2187 QV4::CppStackFrame *frame = v4->currentStackFrame;
2188 const QByteArray baSource = frame->source().toUtf8();
2189 const QByteArray baFunction = frame->function().toUtf8();
2190 QMessageLogger logger(baSource.constData(), frame->lineNumber(), baFunction.constData());
2191 QQmlProfilerService *service = QQmlDebugConnector::service<QQmlProfilerService>();
2193 logger.warning(
"Cannot start profiling because debug service is disabled. Start with -qmljsdebugger=port:XXXXX.");
2195 service->startProfiling(v4->jsEngine());
2196 logger.debug(
"Profiling started.");
2199 return QV4::Encode::undefined();
2202ReturnedValue
ConsoleObject::method_profileEnd(
const FunctionObject *b,
const Value *,
const Value *,
int)
2204 QV4::Scope scope(b);
2205 QV4::ExecutionEngine *v4 = scope.engine;
2207 QV4::CppStackFrame *frame = v4->currentStackFrame;
2208 const QByteArray baSource = frame->source().toUtf8();
2209 const QByteArray baFunction = frame->function().toUtf8();
2210 QMessageLogger logger(baSource.constData(), frame->lineNumber(), baFunction.constData());
2212 QQmlProfilerService *service = QQmlDebugConnector::service<QQmlProfilerService>();
2214 logger.warning(
"Ignoring console.profileEnd(): the debug service is disabled.");
2216 service->stopProfiling(v4->jsEngine());
2217 logger.debug(
"Profiling ended.");
2220 return QV4::Encode::undefined();
2223ReturnedValue
ConsoleObject::method_time(
const FunctionObject *b,
const Value *,
const Value *argv,
int argc)
2225 QV4::Scope scope(b);
2227 THROW_GENERIC_ERROR(
"console.time(): Invalid arguments");
2229 QString name = argv[0].toQStringNoThrow();
2230 scope.engine->startTimer(name);
2231 return QV4::Encode::undefined();
2234ReturnedValue
ConsoleObject::method_timeEnd(
const FunctionObject *b,
const Value *,
const Value *argv,
int argc)
2236 QV4::Scope scope(b);
2238 THROW_GENERIC_ERROR(
"console.timeEnd(): Invalid arguments");
2240 QString name = argv[0].toQStringNoThrow();
2242 qint64 elapsed = scope.engine->stopTimer(name, &wasRunning);
2244 qDebug(
"%s: %llims", qPrintable(name), elapsed);
2246 return QV4::Encode::undefined();
2249ReturnedValue
ConsoleObject::method_count(
const FunctionObject *b,
const Value *,
const Value *argv,
int argc)
2254 name = argv[0].toQStringNoThrow();
2257 QV4::ExecutionEngine *v4 = scope.engine;
2259 QV4::CppStackFrame *frame = v4->currentStackFrame;
2261 QString scriptName = frame->source();
2263 int value = v4->consoleCountHelper(scriptName, frame->lineNumber(), 0);
2264 QString message = name + QLatin1String(
": ") + QString::number(value);
2266 QMessageLogger(qPrintable(scriptName), frame->lineNumber(),
2267 qPrintable(frame->function()))
2268 .debug(
"%s", qPrintable(message));
2270 return QV4::Encode::undefined();
2273ReturnedValue
ConsoleObject::method_trace(
const FunctionObject *b,
const Value *,
const Value *,
int argc)
2275 QV4::Scope scope(b);
2277 THROW_GENERIC_ERROR(
"console.trace(): Invalid arguments");
2279 QV4::ExecutionEngine *v4 = scope.engine;
2281 QString stack = jsStack(v4);
2283 QV4::CppStackFrame *frame = v4->currentStackFrame;
2284 QMessageLogger(frame->source().toUtf8().constData(), frame->lineNumber(),
2285 frame->function().toUtf8().constData())
2286 .debug(v4->qmlEngine() ? lcQml() : lcJs(),
"%s", qPrintable(stack));
2288 return QV4::Encode::undefined();
2291ReturnedValue
ConsoleObject::method_warn(
const FunctionObject *b,
const Value *,
const Value *argv,
int argc)
2293 return writeToConsole(b, argv, argc, Warn);
2296ReturnedValue
ConsoleObject::method_assert(
const FunctionObject *b,
const Value *,
const Value *argv,
int argc)
2298 QV4::Scope scope(b);
2300 THROW_GENERIC_ERROR(
"console.assert(): Missing argument");
2302 QV4::ExecutionEngine *v4 = scope.engine;
2304 if (!argv[0].toBoolean()) {
2306 for (
int i = 1, ei = argc; i < ei; ++i) {
2308 message.append(QLatin1Char(
' '));
2310 message.append(argv[i].toQStringNoThrow());
2313 QString stack = jsStack(v4);
2315 QV4::CppStackFrame *frame = v4->currentStackFrame;
2316 QMessageLogger(frame->source().toUtf8().constData(), frame->lineNumber(),
2317 frame->function().toUtf8().constData())
2318 .critical(
"%s\n%s",qPrintable(message), qPrintable(stack));
2321 return QV4::Encode::undefined();
2324ReturnedValue
ConsoleObject::method_exception(
const FunctionObject *b,
const Value *,
const Value *argv,
int argc)
2326 QV4::Scope scope(b);
2328 THROW_GENERIC_ERROR(
"console.exception(): Missing argument");
2330 return writeToConsole(b, argv, argc, Error,
true);
2333void QV4::GlobalExtensions::init(Object *globalObject, QJSEngine::Extensions extensions)
2335 ExecutionEngine *v4 = globalObject->engine();
2338 if (extensions.testFlag(QJSEngine::TranslationExtension)) {
2339 #if QT_CONFIG(translation)
2340 globalObject->defineDefaultProperty(QStringLiteral(
"qsTranslate"), QV4::GlobalExtensions::method_qsTranslate);
2341 globalObject->defineDefaultProperty(QStringLiteral(
"QT_TRANSLATE_NOOP"), QV4::GlobalExtensions::method_qsTranslateNoOp);
2342 globalObject->defineDefaultProperty(QStringLiteral(
"qsTr"), QV4::GlobalExtensions::method_qsTr);
2343 globalObject->defineDefaultProperty(QStringLiteral(
"QT_TR_NOOP"), QV4::GlobalExtensions::method_qsTrNoOp);
2344 globalObject->defineDefaultProperty(QStringLiteral(
"qsTrId"), QV4::GlobalExtensions::method_qsTrId);
2345 globalObject->defineDefaultProperty(QStringLiteral(
"QT_TRID_NOOP"), QV4::GlobalExtensions::method_qsTrIdNoOp);
2348 ScopedString qtName(scope, v4->newString(QStringLiteral(
"Qt")));
2349 ScopedObject qt(scope, globalObject->get(qtName));
2351 v4->createQtObject();
2354 scope.engine->stringPrototype()->defineDefaultProperty(QStringLiteral(
"arg"), QV4::GlobalExtensions::method_string_arg);
2358 if (extensions.testFlag(QJSEngine::ConsoleExtension)) {
2359 globalObject->defineDefaultProperty(QStringLiteral(
"print"), QV4::ConsoleObject::method_log);
2362 QV4::ScopedObject console(scope, globalObject->engine()->memoryManager->allocate<QV4::ConsoleObject>());
2363 globalObject->defineDefaultProperty(QStringLiteral(
"console"), console);
2366 if (extensions.testFlag(QJSEngine::GarbageCollectionExtension)) {
2367 globalObject->defineDefaultProperty(QStringLiteral(
"gc"), QV4::GlobalExtensions::method_gc);
2372#if QT_CONFIG(translation)
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393ReturnedValue GlobalExtensions::method_qsTranslate(
const FunctionObject *b,
const Value *,
const Value *argv,
int argc)
2395 QV4::Scope scope(b);
2397 THROW_GENERIC_ERROR(
"qsTranslate() requires at least two arguments");
2398 if (!argv[0].isString())
2399 THROW_GENERIC_ERROR(
"qsTranslate(): first argument (context) must be a string");
2400 if (!argv[1].isString())
2401 THROW_GENERIC_ERROR(
"qsTranslate(): second argument (sourceText) must be a string");
2402 if ((argc > 2) && !argv[2].isString())
2403 THROW_GENERIC_ERROR(
"qsTranslate(): third argument (disambiguation) must be a string");
2405 QString context = argv[0].toQStringNoThrow();
2406 QString text = argv[1].toQStringNoThrow();
2408 if (argc > 2) comment = argv[2].toQStringNoThrow();
2411 if (argc > i && argv[i].isString()) {
2412 qWarning(
"qsTranslate(): specifying the encoding as fourth argument is deprecated");
2418 n = argv[i].toInt32();
2420 if (QQmlEnginePrivate *ep = (scope.engine->qmlEngine() ? QQmlEnginePrivate::get(scope.engine->qmlEngine()) :
nullptr))
2421 if (ep->propertyCapture)
2422 ep->propertyCapture->captureTranslation();
2424 QString result = QCoreApplication::translate(context.toUtf8().constData(),
2425 text.toUtf8().constData(),
2426 comment.toUtf8().constData(),
2429 return Encode(scope.engine->newString(result));
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454ReturnedValue GlobalExtensions::method_qsTranslateNoOp(
const FunctionObject *b,
const Value *,
const Value *argv,
int argc)
2456 QV4::Scope scope(b);
2458 return QV4::Encode::undefined();
2460 return argv[1].asReturnedValue();
2463QString GlobalExtensions::currentTranslationContext(ExecutionEngine *engine)
2466 CppStackFrame *frame = engine->currentStackFrame;
2469 while (frame && context.isEmpty()) {
2470 if (ExecutableCompilationUnit *unit = frame->v4Function->executableCompilationUnit()) {
2471 auto translationContextIndex = unit->unitData()->translationContextIndex();
2472 if (translationContextIndex)
2473 context = unit->stringAt(*translationContextIndex);
2474 if (!context.isEmpty())
2476 QString fileName = unit->fileName();
2477 QUrl url(unit->fileName());
2478 if (url.isValid() && url.isRelative()) {
2479 context = url.fileName();
2481 context = QQmlFile::urlToLocalFileOrQrc(fileName);
2482 if (context.isEmpty() && fileName.startsWith(QLatin1String(
":/")))
2485 context = QFileInfo(context).completeBaseName();
2487 frame = frame->parentFrame();
2490 if (context.isEmpty()) {
2491 if (QQmlRefPointer<QQmlContextData> ctxt = engine->callingQmlContext()) {
2492 QString path = ctxt->urlString();
2493 int lastSlash = path.lastIndexOf(QLatin1Char(
'/'));
2494 int lastDot = path.lastIndexOf(QLatin1Char(
'.'));
2495 int length = lastDot - (lastSlash + 1);
2496 context = (lastSlash > -1) ? path.mid(lastSlash + 1, (length > -1) ? length : -1) : QString();
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
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
2540ReturnedValue GlobalExtensions::method_qsTr(
const FunctionObject *b,
const Value *,
const Value *argv,
int argc)
2542 QV4::Scope scope(b);
2544 THROW_GENERIC_ERROR(
"qsTr() requires at least one argument");
2545 if (!argv[0].isString())
2546 THROW_GENERIC_ERROR(
"qsTr(): first argument (sourceText) must be a string");
2547 if ((argc > 1) && !argv[1].isString())
2548 THROW_GENERIC_ERROR(
"qsTr(): second argument (disambiguation) must be a string");
2549 if ((argc > 2) && !argv[2].isNumber())
2550 THROW_GENERIC_ERROR(
"qsTr(): third argument (n) must be a number");
2552 const QString context = currentTranslationContext(scope.engine);
2553 const QString text = argv[0].toQStringNoThrow();
2554 const QString comment = argc > 1 ? argv[1].toQStringNoThrow() : QString();
2555 const int n = argc > 2 ? argv[2].toInt32() : -1;
2557 if (QQmlEnginePrivate *ep = (scope.engine->qmlEngine() ? QQmlEnginePrivate::get(scope.engine->qmlEngine()) :
nullptr))
2558 if (ep->propertyCapture)
2559 ep->propertyCapture->captureTranslation();
2561 QString result = QCoreApplication::translate(context.toUtf8().constData(), text.toUtf8().constData(),
2562 comment.toUtf8().constData(), n);
2564 return Encode(scope.engine->newString(result));
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589ReturnedValue GlobalExtensions::method_qsTrNoOp(
const FunctionObject *,
const Value *,
const Value *argv,
int argc)
2592 return QV4::Encode::undefined();
2594 return argv[0].asReturnedValue();
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628ReturnedValue GlobalExtensions::method_qsTrId(
const FunctionObject *b,
const Value *,
const Value *argv,
int argc)
2630 QV4::Scope scope(b);
2632 THROW_GENERIC_ERROR(
"qsTrId() requires at least one argument");
2633 if (!argv[0].isString())
2634 THROW_TYPE_ERROR_WITH_MESSAGE(
"qsTrId(): first argument (id) must be a string");
2635 if (argc > 1 && !argv[1].isNumber())
2636 THROW_TYPE_ERROR_WITH_MESSAGE(
"qsTrId(): second argument (n) must be a number");
2640 n = argv[1].toInt32();
2642 if (QQmlEnginePrivate *ep = (scope.engine->qmlEngine() ? QQmlEnginePrivate::get(scope.engine->qmlEngine()) :
nullptr))
2643 if (ep->propertyCapture)
2644 ep->propertyCapture->captureTranslation();
2646 return Encode(scope.engine->newString(qtTrId(argv[0].toQStringNoThrow().toUtf8().constData(), n)));
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665ReturnedValue GlobalExtensions::method_qsTrIdNoOp(
const FunctionObject *,
const Value *,
const Value *argv,
int argc)
2668 return QV4::Encode::undefined();
2670 return argv[0].asReturnedValue();
2675
2676
2677
2678
2679
2680
2681
2682
2683ReturnedValue GlobalExtensions::method_gc(
const FunctionObject *b,
const Value *,
const Value *,
int)
2685 auto mm = b->engine()->memoryManager;
2688 return QV4::Encode::undefined();
2691ReturnedValue GlobalExtensions::method_string_arg(
const FunctionObject *b,
const Value *thisObject,
const Value *argv,
int argc)
2693 QV4::Scope scope(b);
2695 THROW_GENERIC_ERROR(
"String.arg(): Invalid arguments");
2697 QString value = thisObject->toQString();
2701 QV4::ScopedValue arg(scope, argv[0]);
2702 if (arg->isInteger())
2703 value = value.arg(arg->integerValue());
2704 else if (arg->isDouble())
2705 value = value.arg(arg->doubleValue());
2706 else if (arg->isBoolean())
2707 value = value.arg(arg->booleanValue());
2709 value = value.arg(arg->toQString());
2710 RETURN_RESULT(scope.engine->newString(value));
2714 constexpr int PreallocArgCount = 10;
2717 QVarLengthArray<QString, PreallocArgCount> argStrings(argc);
2718 QVarLengthArray<QtPrivate::QStringViewArg, PreallocArgCount> args(argc);
2719 QVarLengthArray<
const QtPrivate::ArgBase *, PreallocArgCount> argBases(argc);
2721 for (
int i = 0; i < argc; ++i) {
2722 QV4::ScopedValue arg(scope, argv[i]);
2724 if (arg->isInteger())
2725 argStrings[i] = QString::number(arg->integerValue());
2726 else if (arg->isDouble())
2727 argStrings[i] = QString::number(arg->doubleValue());
2728 else if (arg->isBoolean())
2729 argStrings[i] = QString::number(arg->booleanValue());
2731 argStrings[i] = arg->toQString();
2733 args[i] = QtPrivate::QStringViewArg(argStrings[i]);
2734 argBases[i] = &args[i];
2737 QString result = QtPrivate::argToQString(value, argc, argBases.data());
2738 RETURN_RESULT(scope.engine->newString(result));
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2764#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