Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qqmlbuiltinfunctions.cpp
Go to the documentation of this file.
1// Copyright (C) 2021 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3// Qt-Security score:significant
4
6
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>
15
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>
25
26#include <QtQml/qqmlfile.h>
27
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>
39
41
42Q_STATIC_LOGGING_CATEGORY(lcRootProperties, "qt.qml.rootObjectProperties");
45
46using namespace QV4;
47
48#define THROW_TYPE_ERROR_WITH_MESSAGE(msg)
49 do {
50 return scope.engine->throwTypeError(QString::fromUtf8(msg));
51 } while (false)
52
53/*!
54\qmltype Qt
55\inqmlmodule QtQml
56//! \nativetype QQmlEnginePrivate
57\ingroup qml-utility-elements
58\keyword QmlGlobalQtObject
59\brief Provides a global object with useful enums and functions from Qt.
60
61\c Qt is a singleton type that provides utility functions, properties, and
62enums. Here is an example showing how to use this type:
63
64\qml
65import QtQuick 2.0
66
67Text {
68 color: Qt.rgba(1, 0, 0, 1)
69 text: Qt.md5("hello, world")
70}
71\endqml
72
73
74\section1 Enums
75
76The Qt object contains the enums available in the \l [QtCore]{Qt}{Qt Namespace}. For example, you can access
77the \l Qt::LeftButton and \l Qt::RightButton enumeration values as \c Qt.LeftButton and \c Qt.RightButton.
78
79
80\section1 Types
81\target globalqtobjecttypes
82
83The Qt object also contains helper functions for creating objects of specific
84data types. This is primarily useful when setting the properties of an item
85when the property has one of the following types:
86\list
87\li \c rect - use \l{Qt::rect()}{Qt.rect()}
88\li \c point - use \l{Qt::point()}{Qt.point()}
89\li \c size - use \l{Qt::size()}{Qt.size()}
90\endlist
91
92If the \c QtQuick module has been imported, the following helper functions for
93creating objects of specific data types are also available for clients to use:
94\list
95\li \c color - use \l{Qt::rgba()}{Qt.rgba()}, \l{Qt::hsla()}{Qt.hsla()}, \l{Qt::darker()}{Qt.darker()}, \l{Qt::lighter()}{Qt.lighter()} or \l{Qt::tint()}{Qt.tint()}
96\li \c font - use \l{Qt::font()}{Qt.font()}
97\li \c vector2d - use \l{Qt::vector2d()}{Qt.vector2d()}
98\li \c vector3d - use \l{Qt::vector3d()}{Qt.vector3d()}
99\li \c vector4d - use \l{Qt::vector4d()}{Qt.vector4d()}
100\li \c quaternion - use \l{Qt::quaternion()}{Qt.quaternion()}
101\li \c matrix4x4 - use \l{Qt::matrix4x4()}{Qt.matrix4x4()}
102\endlist
103
104\section1 Date/Time Formatters
105
106The Qt object contains several functions for formatting QDateTime, QDate and QTime values.
107
108\list
109 \li \l{Qt::formatDateTime}{string Qt.formatDateTime(datetime date, variant format)}
110 \li \l{Qt::formatDate}{string Qt.formatDate(datetime date, variant format)}
111 \li \l{Qt::formatTime}{string Qt.formatTime(datetime date, variant format)}
112\endlist
113
114The format specification is described at \l{Qt::formatDateTime}{Qt.formatDateTime}.
115
116
117\section1 Dynamic Object Creation
118The following functions on the global object allow you to dynamically create QML
119items from files or strings. See \l{Dynamic QML Object Creation from JavaScript} for an overview
120of their use.
121
122\list
123 \li \l{Qt::createComponent()}{object Qt.createComponent(url)}
124 \li \l{Qt::createQmlObject()}{object Qt.createQmlObject(string qml, object parent, url url)}
125\endlist
126
127
128\section1 Other Functions
129
130The following functions are also on the Qt object.
131
132\list
133 \li \l{Qt::quit()}{Qt.quit()}
134 \li \l{Qt::md5()}{Qt.md5(string)}
135 \li \l{Qt::btoa()}{string Qt.btoa(string)}
136 \li \l{Qt::atob()}{string Qt.atob(string)}
137 \li \l{Qt::binding()}{object Qt.binding(function)}
138 \li \l{Qt::locale()}{object Qt.locale()}
139 \li \l{Qt::resolvedUrl()}{string Qt.resolvedUrl(string)}
140 \li \l{Qt::openUrlExternally()}{Qt.openUrlExternally(string)}
141 \li \l{Qt::fontFamilies()}{list<string> Qt.fontFamilies()}
142\endlist
143*/
144
145/*!
146 \qmlproperty var Qt::platform
147 \since 5.1
148
149 The \c platform object provides info about the underlying platform.
150
151 Its properties are:
152
153 \table
154 \row
155 \li \c platform.os
156 \li
157
158 This read-only property contains the name of the operating system.
159
160 Possible values are:
161
162 \list
163 \li \c "android" - Android
164 \li \c "ios" - iOS
165 \li \c "tvos" - tvOS
166 \li \c "visionos" - visionOS
167 \li \c "linux" - Linux
168 \li \c "osx" - \macos
169 \li \c "qnx" - QNX (since Qt 5.9.3)
170 \li \c "unix" - Other Unix-based OS
171 \li \c "windows" - Windows
172 \li \c "wasm" - WebAssembly
173 \li \c "harmonyos" - HarmonyOS
174 \endlist
175
176 \note The property's value on \macos is "osx", regardless of Apple naming convention.
177 The returned value will be updated to "macos" for Qt 7.
178
179 \row
180 \li \c platform.pluginName
181 \li This is the name of the platform set on the QGuiApplication instance
182 as returned by \l QGuiApplication::platformName()
183
184 \endtable
185*/
186
187/*!
188 \qmlproperty Application Qt::application
189 \since 5.1
190
191 The \c application object provides access to global application state
192 properties shared by many QML components.
193
194 It is the same as the \l Application singleton.
195
196 The following example uses the \c application object to indicate
197 whether the application is currently active:
198
199 \snippet qml/application.qml document
200
201 \note When using QML without a QGuiApplication, the following properties will be undefined:
202 \list
203 \li application.active
204 \li application.state
205 \li application.layoutDirection
206 \li application.font
207 \endlist
208*/
209
210/*!
211 \qmlproperty InputMethod Qt::inputMethod
212 \since 5.0
213
214 It is the same as the \l InputMethod singleton.
215
216 The \c inputMethod object allows access to application's QInputMethod object
217 and all its properties and slots. See the QInputMethod documentation for
218 further details.
219*/
220
221/*!
222 \qmlproperty QtObject Qt::styleHints
223 \since 5.5
224
225 The \c styleHints object provides platform-specific style hints and settings.
226 See the \l QStyleHints documentation for further details.
227
228 You should access StyleHints via \l Application::styleHints instead, as
229 this provides better type information for tooling such as the
230 \l {Qt Quick Compiler}.
231
232 \note The \c styleHints object is only available when using the Qt Quick module.
233*/
234
235/*!
236\qmlmethod var Qt::include(string url, jsobject callback)
237\deprecated
238
239This method should not be used. Use ECMAScript modules, and the native
240JavaScript \c import and \c export statements instead.
241
242Includes another JavaScript file. This method can only be used from within JavaScript files,
243and not regular QML files.
244
245This imports all functions from \a url into the current script's namespace.
246
247Qt.include() returns an object that describes the status of the operation. The object has
248a single property, \c {status}, that is set to one of the following values:
249
250\table
251\header \li Symbol \li Value \li Description
252\row \li result.OK \li 0 \li The include completed successfully.
253\row \li result.LOADING \li 1 \li Data is being loaded from the network.
254\row \li result.NETWORK_ERROR \li 2 \li A network error occurred while fetching the url.
255\row \li result.EXCEPTION \li 3 \li A JavaScript exception occurred while executing the included code.
256An additional \c exception property will be set in this case.
257\endtable
258
259The \c status property will be updated as the operation progresses.
260
261If provided, \a callback is invoked when the operation completes. The callback is passed
262the same object as is returned from the Qt.include() call.
263
264\warning Using this function is strict mode does not actually put identifier into the
265current context.
266*/
267// Qt.include() is implemented in qv4include.cpp
268
269QtObject::QtObject(ExecutionEngine *engine)
270 : m_engine(engine)
271{
272#if QT_CONFIG(translation)
273 // Worker script engines have no QJSEngine.
274 // We can't report the uiLanguage from their Qt object.
275 if (QJSEngine *jsEngine = m_engine->jsEngine()) {
276 connect(jsEngine, &QJSEngine::uiLanguageChanged,
277 this, &QtObject::uiLanguageChanged);
278 }
279#endif
280}
281
282QtObject::Contexts QtObject::getContexts() const
283{
284 QQmlEngine *engine = qmlEngine();
285 if (!engine)
286 return {};
287
288 QQmlRefPointer<QQmlContextData> context = v4Engine()->callingQmlContext();
289 if (!context)
290 context = QQmlContextData::get(QQmlEnginePrivate::get(engine)->rootContext);
291
292 Q_ASSERT(context);
293 QQmlRefPointer<QQmlContextData> effectiveContext
294 = context->isPragmaLibraryContext() ? nullptr : context;
295 return {context, effectiveContext};
296}
297
298QtObject *QtObject::create(QQmlEngine *, QJSEngine *jsEngine)
299{
300 QV4::ExecutionEngine *v4 = jsEngine->handle();
301 QV4::Scope scope(v4);
302 ScopedObject globalObject(scope, v4->globalObject);
303 ScopedString qtName(scope, v4->newString(QStringLiteral("Qt")));
304 QV4::ScopedValue result(scope, globalObject->get(qtName->toPropertyKey()));
305 return qobject_cast<QtObject *>(result->as<QV4::QObjectWrapper>()->object());
306}
307
308QJSValue QtObject::include(const QString &url, const QJSValue &callback) const
309{
310 return QV4Include::method_include(v4Engine(), v4Engine()->resolvedUrl(url), callback);
311}
312
313
314/*!
315 \qmlmethod bool Qt::isQtObject(object)
316
317 Returns \c true if \a object is a valid reference to a Qt or QML object,
318 \c false otherwise.
319*/
320bool QtObject::isQtObject(const QJSValue &value) const
321{
322 return qjsvalue_cast<QObject *>(value) != nullptr;
323}
324
325/*!
326 \qmlmethod color Qt::color(string name)
327
328 Returns the color corresponding to the given \a name (i.e. red or #ff0000).
329 If there is no such color, \c null is returned.
330
331 \note Prefer using the typed \l{Color::fromString}
332*/
333QVariant QtObject::color(const QString &name) const
334{
335 bool ok = false;
336 const QVariant v = QQmlStringConverters::colorFromString(name, &ok);
337 if (ok)
338 return v;
339
340 v4Engine()->throwError(QStringLiteral("\"%1\" is not a valid color name").arg(name));
341 return QVariant::fromValue(nullptr);
342}
343
344/*!
345 \qmlmethod color Qt::rgba(real red, real green, real blue, real alpha)
346
347 Returns a color with the specified \a red, \a green, \a blue, and \a alpha
348 components. All components should be in the range 0-1 (inclusive).
349
350 \note Prefer using the typed \l{Color::rgba}
351*/
352QVariant QtObject::rgba(double r, double g, double b, double a) const
353{
354 r = qBound(0.0, r, 1.0);
355 g = qBound(0.0, g, 1.0);
356 b = qBound(0.0, b, 1.0);
357 a = qBound(0.0, a, 1.0);
358
359 return QQml_colorProvider()->fromRgbF(r, g, b, a);
360}
361
362/*!
363 \qmlmethod color Qt::hsla(real hue, real saturation, real lightness, real alpha)
364
365 Returns a color with the specified \a hue, \a saturation, \a lightness, and \a alpha
366 components. All components should be in the range 0-1 (inclusive).
367
368 \note Prefer using the typed \l{Color::hsla}
369*/
370QVariant QtObject::hsla(double h, double s, double l, double a) const
371{
372 if (h != -1)
373 h = qBound(0.0, h, 1.0);
374 s = qBound(0.0, s, 1.0);
375 l = qBound(0.0, l, 1.0);
376 a = qBound(0.0, a, 1.0);
377
378 return QQml_colorProvider()->fromHslF(h, s, l, a);
379}
380
381/*!
382 \since 5.5
383 \qmlmethod color Qt::hsva(real hue, real saturation, real value, real alpha)
384
385 Returns a color with the specified \a hue, \a saturation, \a value and \a alpha
386 components. All components should be in the range 0-1 (inclusive).
387
388 \note Prefer using the typed \l{Color::hsva}
389*/
390QVariant QtObject::hsva(double h, double s, double v, double a) const
391{
392 if (h != -1)
393 h = qBound(0.0, h, 1.0);
394 s = qBound(0.0, s, 1.0);
395 v = qBound(0.0, v, 1.0);
396 a = qBound(0.0, a, 1.0);
397
398 return QQml_colorProvider()->fromHsvF(h, s, v, a);
399}
400
401/*!
402 \qmlmethod color Qt::colorEqual(color lhs, string rhs)
403
404 Returns \c true if both \a lhs and \a rhs yield equal color values. Both
405 arguments may be either color values or string values. If a string value
406 is supplied it must be convertible to a color, as described for the
407 \l{colorvaluetypedocs}{color} value type.
408
409 \note Prefer using the typed \l{Color::equal}
410*/
411bool QtObject::colorEqual(const QVariant &lhs, const QVariant &rhs) const
412{
413 bool ok = false;
414
415 QVariant color1 = lhs;
416 if (color1.userType() == QMetaType::QString) {
417 color1 = QQmlStringConverters::colorFromString(color1.toString(), &ok);
418 if (!ok) {
419 v4Engine()->throwError(QStringLiteral("Qt.colorEqual(): Invalid color name"));
420 return false;
421 }
422 } else if (color1.userType() != QMetaType::QColor) {
423 v4Engine()->throwError(QStringLiteral("Qt.colorEqual(): Invalid arguments"));
424 return false;
425 }
426
427 QVariant color2 = rhs;
428 if (color2.userType() == QMetaType::QString) {
429 color2 = QQmlStringConverters::colorFromString(color2.toString(), &ok);
430 if (!ok) {
431 v4Engine()->throwError(QStringLiteral("Qt.colorEqual(): Invalid color name"));
432 return false;
433 }
434 } else if (color2.userType() != QMetaType::QColor) {
435 v4Engine()->throwError(QStringLiteral("Qt.colorEqual(): Invalid arguments"));
436 return false;
437 }
438
439 return color1 == color2;
440}
441
442/*!
443 \qmlmethod rect Qt::rect(real x, real y, real width, real height)
444
445 Returns a rect with the top-left corner at \a x, \a y and the specified \a width and \a height.
446*/
447QRectF QtObject::rect(double x, double y, double width, double height) const
448{
449 return QRectF(x, y, width, height);
450}
451
452/*!
453 \qmlmethod point Qt::point(real x, real y)
454
455 Returns a point with the specified \a x and \a y coordinates.
456*/
457QPointF QtObject::point(double x, double y) const
458{
459 return QPointF(x, y);
460}
461
462/*!
463 \qmlmethod size Qt::size(real width, real height)
464
465 Returns a size with the specified \a width and \a height.
466*/
467QSizeF QtObject::size(double w, double h) const
468{
469 return QSizeF(w, h);
470}
471
472/*!
473 \qmlmethod font Qt::font(var fontSpecifier)
474
475 Returns a font with the properties specified in the \a fontSpecifier object
476 or the nearest matching font. The \a fontSpecifier object should contain
477 key-value pairs where valid keys are the \l{fontvaluetypedocs}{font} type's
478 subproperty names, and the values are valid values for each subproperty.
479 Invalid keys will be ignored.
480*/
481QVariant QtObject::font(const QJSValue &fontSpecifier) const
482{
483 if (!fontSpecifier.isObject()) {
484 v4Engine()->throwError(QStringLiteral("Qt.font(): Invalid arguments"));
485 return QVariant();
486 }
487
488 {
489 const QVariant v = QQmlValueTypeProvider::createValueType(
490 fontSpecifier, QMetaType(QMetaType::QFont));
491 if (v.isValid())
492 return v;
493 }
494
495 v4Engine()->throwError(QStringLiteral("Qt.font(): Invalid argument: "
496 "no valid font subproperties specified"));
497 return QVariant();
498}
499
500template<typename T>
501void addParameters(QJSEngine *e, QJSValue &result, int i, T parameter)
502{
503 result.setProperty(i, e->toScriptValue(parameter));
504}
505
506template<>
507void addParameters<double>(QJSEngine *, QJSValue &result, int i, double parameter)
508{
509 result.setProperty(i, QJSValue(parameter));
510}
511
512template<typename T, typename ...Others>
513void addParameters(QJSEngine *e, QJSValue &result, int i, T parameter, Others... others)
514{
515 addParameters<T>(e, result, i, parameter);
516 addParameters<Others...>(e, result, ++i, others...);
517}
518
519template<typename ...T>
520static QVariant constructFromJSValue(QJSEngine *e, QMetaType type, T... parameters)
521{
522 if (!e)
523 return QVariant();
524 QJSValue params = e->newArray(sizeof...(parameters));
525 addParameters(e, params, 0, parameters...);
526 const QVariant variant = QQmlValueTypeProvider::createValueType(params, type);
527 return variant.isValid() ? variant : QVariant(type);
528}
529
530/*!
531 \qmlmethod vector2d Qt::vector2d(real x, real y)
532
533 Returns a vector2d with the specified \a x and \a y values.
534*/
535QVariant QtObject::vector2d(double x, double y) const
536{
537 return constructFromJSValue(jsEngine(), QMetaType(QMetaType::QVector2D), x, y);
538}
539
540/*!
541 \qmlmethod vector3d Qt::vector3d(real x, real y, real z)
542
543 Returns a vector3d with the specified \a x, \a y, and \a z values.
544*/
545QVariant QtObject::vector3d(double x, double y, double z) const
546{
547 return constructFromJSValue(jsEngine(), QMetaType(QMetaType::QVector3D), x, y, z);
548}
549
550/*!
551 \qmlmethod vector4d Qt::vector4d(real x, real y, real z, real w)
552
553 Returns a vector4d with the specified \a x, \a y, \a z, and \a w values.
554*/
555QVariant QtObject::vector4d(double x, double y, double z, double w) const
556{
557 return constructFromJSValue(jsEngine(), QMetaType(QMetaType::QVector4D), x, y, z, w);
558}
559
560/*!
561 \qmlmethod quaternion Qt::quaternion(real scalar, real x, real y, real z)
562
563 Returns a quaternion with the specified \a scalar, \a x, \a y, and \a z values.
564*/
565QVariant QtObject::quaternion(double scalar, double x, double y, double z) const
566{
567 return constructFromJSValue(jsEngine(), QMetaType(QMetaType::QQuaternion), scalar, x, y, z);
568}
569
570/*!
571 \qmlmethod matrix4x4 Qt::matrix4x4()
572
573 Returns an identity matrix4x4.
574 */
575QVariant QtObject::matrix4x4() const
576{
577 const QMetaType metaType(QMetaType::QMatrix4x4);
578 const QVariant variant = QQmlValueTypeProvider::createValueType(QJSValue(), metaType);
579 return variant.isValid() ? variant : QVariant(metaType);
580}
581
582/*!
583 \qmlmethod matrix4x4 Qt::matrix4x4(var values)
584
585 Returns a matrix4x4 with the specified \a values. \a values is expected to
586 be a JavaScript array with 16 entries.
587
588 The array indices correspond to positions in the matrix as follows:
589
590 \table
591 \row \li 0 \li 1 \li 2 \li 3
592 \row \li 4 \li 5 \li 6 \li 7
593 \row \li 8 \li 9 \li 10 \li 11
594 \row \li 12 \li 13 \li 14 \li 15
595 \endtable
596*/
597QVariant QtObject::matrix4x4(const QJSValue &value) const
598{
599 if (value.isObject()) {
600 QVariant v = QQmlValueTypeProvider::createValueType(
601 value, QMetaType(QMetaType::QMatrix4x4));
602 if (v.isValid())
603 return v;
604 }
605
606 v4Engine()->throwError(QStringLiteral("Qt.matrix4x4(): Invalid argument: "
607 "not a valid matrix4x4 values array"));
608 return QVariant();
609}
610
611/*!
612 \qmlmethod matrix4x4 Qt::matrix4x4(real m11, real m12, real m13, real m14, real m21, real m22, real m23, real m24, real m31, real m32, real m33, real m34, real m41, real m42, real m43, real m44)
613
614 Returns a matrix4x4 with the specified values.
615
616 The arguments correspond to their positions in the matrix:
617
618 \table
619 \row \li \a m11 \li \a m12 \li \a m13 \li \a m14
620 \row \li \a m21 \li \a m22 \li \a m23 \li \a m24
621 \row \li \a m31 \li \a m32 \li \a m33 \li \a m34
622 \row \li \a m41 \li \a m42 \li \a m43 \li \a m44
623 \endtable
624*/
625QVariant QtObject::matrix4x4(double m11, double m12, double m13, double m14,
626 double m21, double m22, double m23, double m24,
627 double m31, double m32, double m33, double m34,
628 double m41, double m42, double m43, double m44) const
629{
630 return constructFromJSValue(jsEngine(), QMetaType(QMetaType::QMatrix4x4),
631 m11, m12, m13, m14, m21, m22, m23, m24,
632 m31, m32, m33, m34, m41, m42, m43, m44);
633}
634
635static QVariant colorVariantFromJSValue(const QJSValue &color, bool *ok)
636{
637 QVariant v;
638 if (color.isString()) {
639 v = QQmlStringConverters::colorFromString(color.toString(), ok);
640 if (!(*ok))
641 return QVariant::fromValue(nullptr);
642 } else {
643 v = color.toVariant();
644 if (v.userType() != QMetaType::QColor) {
645 *ok = false;
646 return QVariant::fromValue(nullptr);
647 }
648 }
649
650 *ok = true;
651 return v;
652}
653
654/*!
655 \qmlmethod color Qt::lighter(color baseColor, real factor)
656
657 Returns a color lighter than \a baseColor by the \a factor provided.
658
659 If the factor is greater than 1.0, this functions returns a lighter color.
660 Setting factor to 1.5 returns a color that is 50% brighter. If the factor is less than 1.0,
661 the return color is darker, but we recommend using the Qt.darker() function for this purpose.
662 If the factor is 0 or negative, the return value is unspecified.
663
664 The function converts the current RGB color to HSV, multiplies the value (V) component
665 by factor and converts the color back to RGB.
666
667 If \a factor is not supplied, returns a color that is 50% lighter than \a baseColor (factor 1.5).
668
669 \note Prefer using the typed \l{Color::lighter}
670*/
671QVariant QtObject::lighter(const QJSValue &color, double factor) const
672{
673 bool ok;
674 const QVariant v = colorVariantFromJSValue(color, &ok);
675 return ok ? QQml_colorProvider()->lighter(v, factor) : v;
676}
677
678/*!
679 \qmlmethod color Qt::darker(color baseColor, real factor)
680
681 Returns a color darker than \a baseColor by the \a factor provided.
682
683 If the factor is greater than 1.0, this function returns a darker color.
684 Setting factor to 3.0 returns a color that has one-third the brightness.
685 If the factor is less than 1.0, the return color is lighter, but we recommend using
686 the Qt.lighter() function for this purpose. If the factor is 0 or negative, the return
687 value is unspecified.
688
689 The function converts the current RGB color to HSV, divides the value (V) component
690 by factor and converts the color back to RGB.
691
692 If \a factor is not supplied, returns a color that is 50% darker than \a baseColor (factor 2.0).
693
694 \note Prefer using the typed \l{Color::darker}
695*/
696QVariant QtObject::darker(const QJSValue &color, double factor) const
697{
698 bool ok;
699 const QVariant v = colorVariantFromJSValue(color, &ok);
700 return ok ? QQml_colorProvider()->darker(v, factor) : v;
701}
702
703/*!
704 \qmlmethod color Qt::alpha(color baseColor, real value)
705
706 Returns \a baseColor with an alpha value of \a value.
707
708 \a value is a real ranging from 0 (completely transparent) to 1 (completely opaque).
709
710 \note Prefer using the typed \l{Color::transparent}
711*/
712QVariant QtObject::alpha(const QJSValue &baseColor, double value) const
713{
714 bool ok;
715 const QVariant v = colorVariantFromJSValue(baseColor, &ok);
716 return ok ? QQml_colorProvider()->alpha(v, value) : v;
717}
718
719/*!
720 \qmlmethod color Qt::tint(color baseColor, color tintColor)
721
722 This function allows tinting one color (\a baseColor) with another (\a tintColor).
723
724 The tint color should usually be mostly transparent, or you will not be
725 able to see the underlying color. The below example provides a slight red
726 tint by having the tint color be pure red which is only 1/16th opaque.
727
728 \qml
729 Item {
730 Rectangle {
731 x: 0; width: 80; height: 80
732 color: "lightsteelblue"
733 }
734 Rectangle {
735 x: 100; width: 80; height: 80
736 color: Qt.tint("lightsteelblue", "#10FF0000")
737 }
738 }
739 \endqml
740 \image declarative-rect_tint.png {Side-by-side representation of a light
741 steel blue square and a light steel blue square with a tint applied}
742
743 Tint is most useful when a subtle change is intended to be conveyed due to some event;
744 you can then use tinting to more effectively tune the visible color.
745
746 \note Prefer using the typed \l{Color::tint}
747*/
748QVariant QtObject::tint(const QJSValue &baseColor, const QJSValue &tintColor) const
749{
750 bool ok;
751
752 // base color
753 const QVariant v1 = colorVariantFromJSValue(baseColor, &ok);
754 if (!ok)
755 return v1;
756
757 // tint color
758 const QVariant v2 = colorVariantFromJSValue(tintColor, &ok);
759
760 return ok ? QQml_colorProvider()->tint(v1, v2) : v2;
761}
762
763namespace {
764template <typename T>
765QString formatDateTimeObjectUsingDateFormat(T formatThis, Qt::DateFormat format) {
766 switch (format) {
767 case Qt::TextDate:
768 case Qt::ISODate:
769 case Qt::RFC2822Date:
770 case Qt::ISODateWithMs:
771 return formatThis.toString(format);
772 default: // ### Qt 6: remove once qtbase has removed the rest of the enum !
773 break;
774 }
775 // Q_UNREACHABLE(); // ### Qt 6: restore once the default is gone
776 return QString();
777}
778}
779
780static QTime dateTimeToTime(const QDateTime &dateTime)
781{
782 return dateTime.toLocalTime().time();
783}
784
785/*!
786\qmlmethod string Qt::formatDate(datetime date, variant format, variant localeFormatOption)
787
788Returns a string representation of \a date, optionally formatted using \a format.
789
790The \a date parameter may be a JavaScript \c Date object, a \l{date}{date}
791property, a QDate, or QDateTime value. The \a format and \a localeFormatOption
792parameter may be any of the possible format values as described for
793\l{QtQml::Qt::formatDateTime()}{Qt.formatDateTime()}.
794
795If \a format is not specified, \a date is formatted using
796\l {QLocale::FormatType}{Locale.ShortFormat} using the
797default locale.
798
799\sa Locale
800*/
801static std::optional<QDate> dateFromString(const QString &string, QV4::ExecutionEngine *engine)
802{
803 {
804 const QDate date = QDate::fromString(string, Qt::ISODate);
805 if (date.isValid())
806 return date;
807 }
808
809 {
810 // For historical reasons, the string argument is parsed as datetime, not as only date
811 const QDateTime dateTime = QDateTime::fromString(string, Qt::ISODate);
812 if (dateTime.isValid()) {
813 qCWarning(lcRootProperties())
814 << string << "is a date/time string being passed to formatDate()."
815 << "You should only pass date strings to formatDate().";
816 return dateTime.date();
817 }
818 }
819
820 {
821 // Since we can coerce QDate to QString, allow the resulting string format here.
822 const QDateTime dateTime = DateObject::stringToDateTime(string, engine);
823 if (dateTime.isValid())
824 return DateObject::dateTimeToDate(dateTime);
825 }
826
827 engine->throwError(QStringLiteral("Invalid argument passed to formatDate(): %1").arg(string));
828 return std::nullopt;
829}
830
831QString QtObject::formatDate(QDate date, const QString &format) const
832{
833 return date.toString(format);
834}
835
836QString QtObject::formatDate(QDate date, Qt::DateFormat format) const
837{
838 return formatDateTimeObjectUsingDateFormat(date, format);
839}
840
841QString QtObject::formatDate(const QDateTime &dateTime, const QString &format) const
842{
843 return DateObject::dateTimeToDate(dateTime).toString(format);
844}
845
846QString QtObject::formatDate(const QString &string, const QString &format) const
847{
848 if (const auto qDate = dateFromString(string, v4Engine()))
849 return formatDate(qDate.value(), format);
850
851 return QString();
852}
853
854QString QtObject::formatDate(const QDateTime &dateTime, Qt::DateFormat format) const
855{
856 return formatDateTimeObjectUsingDateFormat(DateObject::dateTimeToDate(dateTime), format);
857}
858
859QString QtObject::formatDate(const QString &string, Qt::DateFormat format) const
860{
861 if (const auto qDate = dateFromString(string, v4Engine()))
862 return formatDate(qDate.value(), format);
863
864 return QString();
865}
866
867#if QT_CONFIG(qml_locale)
868QString QtObject::formatDate(QDate date, const QLocale &locale,
869 QLocale::FormatType formatType) const
870{
871 return locale.toString(date, formatType);
872}
873
874QString QtObject::formatDate(const QDateTime &dateTime, const QLocale &locale,
875 QLocale::FormatType formatType) const
876{
877 return locale.toString(DateObject::dateTimeToDate(dateTime), formatType);
878}
879
880QString QtObject::formatDate(const QString &string, const QLocale &locale,
881 QLocale::FormatType formatType) const
882{
883 if (const auto qDate = dateFromString(string, v4Engine()))
884 return locale.toString(qDate.value(), formatType);
885
886 return QString();
887}
888#endif
889
890/*!
891\qmlmethod string Qt::formatTime(datetime time, variant format, variant localeFormatOption)
892
893Returns a string representation of \a time, optionally formatted using
894\a format, and, if provided, \a localeFormatOption.
895
896The \a time parameter may be a JavaScript \c Date object, a QTime, or QDateTime
897value. The \a format and \a localeFormatOption parameter may be any of the
898possible format values as described for
899\l{QtQml::Qt::formatDateTime()}{Qt.formatDateTime()}.
900
901If \a format is not specified, \a time is formatted using
902\l {QLocale::FormatType}{Locale.ShortFormat} using the default locale.
903
904\sa Locale
905*/
906static std::optional<QTime> timeFromString(const QString &string, QV4::ExecutionEngine *engine)
907{
908 {
909 const QTime time = QTime::fromString(string, Qt::ISODate);
910 if (time.isValid())
911 return time;
912 }
913
914 {
915 // For historical reasons, the string argument is parsed as datetime, not as only time
916 const QDateTime dateTime = QDateTime::fromString(string, Qt::ISODate);
917 if (dateTime.isValid()) {
918 qCWarning(lcRootProperties())
919 << string << "is a date/time string being passed to formatTime()."
920 << "You should only pass time strings to formatTime().";
921 return dateTime.time();
922 }
923 }
924
925 {
926 // Since we can coerce QTime to QString, allow the resulting string format here.
927 const QDateTime dateTime = DateObject::stringToDateTime(string, engine);
928 if (dateTime.isValid())
929 return dateTimeToTime(dateTime);
930 }
931
932 engine->throwError(QStringLiteral("Invalid argument passed to formatTime(): %1").arg(string));
933 return std::nullopt;
934}
935
936QString QtObject::formatTime(QTime time, const QString &format) const
937{
938 return time.toString(format);
939}
940
941QString QtObject::formatTime(const QDateTime &dateTime, const QString &format) const
942{
943 return dateTimeToTime(dateTime).toString(format);
944}
945
946QString QtObject::formatTime(const QString &time, const QString &format) const
947{
948
949 if (auto qTime = timeFromString(time, v4Engine()))
950 return formatTime(qTime.value(), format);
951
952 return QString();
953}
954
955QString QtObject::formatTime(QTime time, Qt::DateFormat format) const
956{
957 return formatDateTimeObjectUsingDateFormat(time, format);
958}
959
960QString QtObject::formatTime(const QDateTime &dateTime, Qt::DateFormat format) const
961{
962 return formatDateTimeObjectUsingDateFormat(dateTimeToTime(dateTime), format);
963}
964
965QString QtObject::formatTime(const QString &time, Qt::DateFormat format) const
966{
967 if (auto qTime = timeFromString(time, v4Engine()))
968 return formatTime(qTime.value(), format);
969
970 return QString();
971}
972
973#if QT_CONFIG(qml_locale)
974QString QtObject::formatTime(QTime time, const QLocale &locale,
975 QLocale::FormatType formatType) const
976{
977 return locale.toString(time, formatType);
978}
979
980QString QtObject::formatTime(const QDateTime &dateTime, const QLocale &locale,
981 QLocale::FormatType formatType) const
982{
983 return locale.toString(dateTimeToTime(dateTime), formatType);
984}
985
986QString QtObject::formatTime(const QString &time, const QLocale &locale,
987 QLocale::FormatType formatType) const
988{
989 if (auto qTime = timeFromString(time, v4Engine()))
990 return locale.toString(qTime.value(), formatType);
991
992 return QString();
993}
994#endif
995
996/*!
997\qmlmethod string Qt::formatDateTime(datetime dateTime, variant format, variant localeFormatOption)
998
999Returns a string representation of \a dateTime, optionally formatted using
1000\a format and \a localeFormatOption.
1001
1002The \a dateTime parameter may be a JavaScript \c Date object, a \l{date}{date}
1003property, a QDate, QTime, or QDateTime value.
1004
1005If \a format is not provided, \a dateTime is formatted using
1006\l {QLocale::FormatType}{Locale.ShortFormat} using the
1007default locale. Otherwise, \a format should be either:
1008
1009\list
1010\li One of the Qt::DateFormat enumeration values, such as
1011 \c Qt.RFC2822Date or \c Qt.ISODate.
1012\li A string that specifies the format of the returned string, as detailed below.
1013\li A \c locale object.
1014\endlist
1015
1016If \a format specifies a locale object, \a dateTime is formatted
1017with \l{QLocale::toString}. In this case, \a localeFormatOption can hold a value
1018of type \l {QLocale::FormatType} to further tune the formatting. If none is
1019provided, \l {QLocale::FormatType}{Locale.ShortFormat} is used.
1020
1021If \a format specifies a format string, it should use the following expressions
1022to specify the date:
1023
1024 \table
1025 \header \li Expression \li Output
1026 \row \li d \li the day as number without a leading zero (1 to 31)
1027 \row \li dd \li the day as number with a leading zero (01 to 31)
1028 \row \li ddd
1029 \li the abbreviated localized day name (e.g. 'Mon' to 'Sun').
1030 Uses QDate::shortDayName().
1031 \row \li dddd
1032 \li the long localized day name (e.g. 'Monday' to 'Qt::Sunday').
1033 Uses QDate::longDayName().
1034 \row \li M \li the month as number without a leading zero (1-12)
1035 \row \li MM \li the month as number with a leading zero (01-12)
1036 \row \li MMM
1037 \li the abbreviated localized month name (e.g. 'Jan' to 'Dec').
1038 Uses QDate::shortMonthName().
1039 \row \li MMMM
1040 \li the long localized month name (e.g. 'January' to 'December').
1041 Uses QDate::longMonthName().
1042 \row \li yy \li the year as two digit number (00-99)
1043 \row \li yyyy \li the year as four digit number
1044 \endtable
1045
1046In addition the following expressions can be used to specify the time:
1047
1048 \table
1049 \header \li Expression \li Output
1050 \row \li h
1051 \li the hour without a leading zero (0 to 23 or 1 to 12 if AM/PM display)
1052 \row \li hh
1053 \li the hour with a leading zero (00 to 23 or 01 to 12 if AM/PM display)
1054 \row \li m \li the minute without a leading zero (0 to 59)
1055 \row \li mm \li the minute with a leading zero (00 to 59)
1056 \row \li s \li the second without a leading zero (0 to 59)
1057 \row \li ss \li the second with a leading zero (00 to 59)
1058 \row \li z \li the milliseconds without leading zeroes (0 to 999)
1059 \row \li zzz \li the milliseconds with leading zeroes (000 to 999)
1060 \row \li AP
1061 \li use AM/PM display. \e AP will be replaced by either "AM" or "PM".
1062 \row \li ap
1063 \li use am/pm display. \e ap will be replaced by either "am" or "pm".
1064 \row \li t
1065 \li include a time-zone indicator.
1066 \endtable
1067
1068 All other input characters will be ignored. Any sequence of characters that
1069 are enclosed in single quotes will be treated as text and not be used as an
1070 expression. Two consecutive single quotes ("''") are replaced by a single quote
1071 in the output.
1072
1073For example, if the following date/time value was specified:
1074
1075 \code
1076 // 21 May 2001 14:13:09
1077 var dateTime = new Date(2001, 5, 21, 14, 13, 09)
1078 \endcode
1079
1080This \a dateTime value could be passed to \c Qt.formatDateTime(),
1081\l {QtQml::Qt::formatDate()}{Qt.formatDate()} or \l {QtQml::Qt::formatTime()}{Qt.formatTime()}
1082with the \a format values below to produce the following results:
1083
1084 \table
1085 \header \li Format \li Result
1086 \row \li "dd.MM.yyyy" \li 21.05.2001
1087 \row \li "ddd MMMM d yy" \li Tue May 21 01
1088 \row \li "hh:mm:ss.zzz" \li 14:13:09.042
1089 \row \li "h:m:s ap" \li 2:13:9 pm
1090 \endtable
1091
1092 \sa Locale
1093*/
1094static std::optional<QDateTime> dateTimeFromString(const QString &string, QV4::ExecutionEngine *engine)
1095{
1096 {
1097 const QDateTime dateTime = QDateTime::fromString(string, Qt::ISODate);
1098 if (dateTime.isValid())
1099 return dateTime;
1100 }
1101
1102 {
1103 // Since we can coerce QDateTime to QString, allow the resulting string format here.
1104 const QDateTime dateTime = DateObject::stringToDateTime(string, engine);
1105 if (dateTime.isValid())
1106 return dateTime;
1107 }
1108
1109 engine->throwError(QStringLiteral("Invalid argument passed to formatDateTime(): %1").arg(string));
1110 return std::nullopt;
1111}
1112
1113QString QtObject::formatDateTime(const QDateTime &dateTime, const QString &format) const
1114{
1115 return dateTime.toString(format);
1116}
1117
1118QString QtObject::formatDateTime(const QString &string, const QString &format) const
1119{
1120
1121 if (const auto qDateTime = dateTimeFromString(string, v4Engine()))
1122 return formatDateTime(qDateTime.value(), format);
1123
1124 return QString();
1125}
1126
1127QString QtObject::formatDateTime(const QDateTime &dateTime, Qt::DateFormat format) const
1128{
1129 return formatDateTimeObjectUsingDateFormat(dateTime, format);
1130}
1131
1132QString QtObject::formatDateTime(const QString &string, Qt::DateFormat format) const
1133{
1134
1135 if (const auto qDateTime = dateTimeFromString(string, v4Engine()))
1136 return formatDateTime(qDateTime.value(), format);
1137
1138 return QString();
1139}
1140
1141#if QT_CONFIG(qml_locale)
1142QString QtObject::formatDateTime(const QDateTime &dateTime, const QLocale &locale,
1143 QLocale::FormatType formatType) const
1144{
1145 return locale.toString(dateTime, formatType);
1146}
1147
1148QString QtObject::formatDateTime(const QString &string, const QLocale &locale,
1149 QLocale::FormatType formatType) const
1150{
1151
1152 if (const auto qDateTime = dateTimeFromString(string, v4Engine()))
1153 return formatDateTime(qDateTime.value(), locale, formatType);
1154
1155 return QString();
1156}
1157#endif
1158
1159/*!
1160 \qmlmethod bool Qt::openUrlExternally(url target)
1161
1162 Attempts to open the specified \a target url in an external application, based on the user's
1163 desktop preferences. Returns \c true if it succeeds, \c false otherwise.
1164
1165 If \a target is a relative URL, it will be resolved. Afterwards, the URL will be forwarded
1166 to \l{QDesktopServices::openUrl}.
1167
1168 \warning A return value of \c true indicates that the application has successfully requested
1169 the operating system to open the URL in an external application. The external application may
1170 still fail to launch or fail to open the requested URL. This result will not be reported back
1171 to the application.
1172
1173 \warning Passing untrusted URLs to openUrlExternally can result in unexpected behaviour.
1174 If untrusted URLs are to be passed to this function, create a JavaScript URL object
1175 and check its \c{protocol} property against a list of allowed protocols. You can also do
1176 further filtering based on other properties like \c{host}.
1177*/
1178// TODO: \l{QDesktopServices::setUrlHandler} doesn't help, as it doesn't allow a catch-all
1179// handler. If it would, that could be used for global rejection of undesired schemes.
1180// Amend documentation if this should change.
1181bool QtObject::openUrlExternally(const QUrl &url) const
1182{
1183 return QQml_guiProvider()->openUrlExternally(resolvedUrl(url));
1184}
1185
1186/*!
1187 \qmlmethod url Qt::url(url url)
1188
1189 Returns \a url verbatim. This can be used to force a type coercion to \c url.
1190 In contrast to Qt.resolvedUrl() this retains any relative URLs. As strings
1191 are implicitly converted to urls, the function can be called with a string
1192 as argument, and will then return a url.
1193
1194 \sa resolvedUrl()
1195*/
1196QUrl QtObject::url(const QUrl &url) const
1197{
1198 return url;
1199}
1200
1201/*!
1202 \qmlmethod url Qt::resolvedUrl(url url)
1203
1204 Returns \a url resolved relative to the URL of the caller.
1205
1206 If there is no caller or the caller is not associated with a QML context,
1207 returns \a url resolved relative to the QML engine's base URL. If the QML
1208 engine has no base URL, just returns \a url.
1209
1210 \sa url()
1211*/
1212QUrl QtObject::resolvedUrl(const QUrl &url) const
1213{
1214 if (QQmlRefPointer<QQmlContextData> ctxt = v4Engine()->callingQmlContext())
1215 return ctxt->resolvedUrl(url);
1216 if (QQmlEngine *engine = qmlEngine())
1217 return engine->baseUrl().resolved(url);
1218 return url;
1219}
1220
1221/*!
1222 \qmlmethod url Qt::resolvedUrl(url url, object context)
1223
1224 Returns \a url resolved relative to the URL of the QML context of
1225 \a context. If \a context is not associated with a QML context,
1226 returns \a url resolved relative to the QML engine's base URL. If
1227 the QML engine has no base URL, just returns \a url.
1228
1229 \sa url()
1230*/
1231QUrl QtObject::resolvedUrl(const QUrl &url, QObject *context) const
1232{
1233 if (context) {
1234 QQmlData *data = QQmlData::get(context);
1235 if (data && data->outerContext)
1236 return data->outerContext->resolvedUrl(url);
1237 }
1238
1239 if (QQmlEngine *engine = qmlEngine())
1240 return engine->baseUrl().resolved(url);
1241 return url;
1242}
1243
1244/*!
1245\qmlmethod list<string> Qt::fontFamilies()
1246
1247Returns a list of the font families available to the application.
1248*/
1249QStringList QtObject::fontFamilies() const
1250{
1251 return QQml_guiProvider()->fontFamilies();
1252}
1253
1254/*!
1255\qmlmethod string Qt::md5(data)
1256Returns a hex string of the md5 hash of \a data.
1257*/
1258QString QtObject::md5(const QString &data) const
1259{
1260 return QLatin1String(QCryptographicHash::hash(data.toUtf8(), QCryptographicHash::Md5).toHex());
1261}
1262
1263/*!
1264\qmlmethod string Qt::escapeHtml(string data)
1265\since 6.12
1266
1267Returns \a data with HTML special characters escaped.
1268
1269This function converts the plain text string \a data to an HTML string with
1270HTML metacharacters \c{<}, \c{>}, \c{&}, and \c{"} replaced by HTML entities.
1271
1272Example:
1273\qml
1274var plain = "<script>alert('XSS')</script>";
1275var escaped = Qt.escapeHtml(plain);
1276// escaped is now "&lt;script&gt;alert('XSS')&lt;/script&gt;"
1277\endqml
1278
1279\sa QString::toHtmlEscaped()
1280*/
1281QString QtObject::escapeHtml(const QString &data) const
1282{
1283 return data.toHtmlEscaped();
1284}
1285
1286/*!
1287\qmlmethod string Qt::btoa(string data)
1288\deprecated [6.11] This method performs a UTF-8 conversion of the string before encoding it.
1289
1290Binary to ASCII --- this function returns a base64 encoding of \a data.
1291*/
1292QString QtObject::btoa(const QString &data) const
1293{
1294 qWarning("Qt.btoa(string): This method is deprecated. "
1295 "Its output differs from the common Web API. "
1296 "Use the overloads that take array-likes.");
1297 return QLatin1String(data.toUtf8().toBase64());
1298}
1299
1300/*!
1301\qmlmethod string Qt::atob(string data)
1302\deprecated [6.11] This method performs a Latin-1 conversion of the string before decoding it
1303 and then interprets the result as UTF-8.
1304
1305ASCII to binary --- this function decodes the base64 encoded \a data string and returns it.
1306*/
1307QString QtObject::atob(const QString &data) const
1308{
1309 qWarning("Qt.atob(string): This method is deprecated. "
1310 "Its output differs from the common Web API. "
1311 "Use the overloads that take array-likes.");
1312 return QString::fromUtf8(QByteArray::fromBase64(data.toLatin1()));
1313}
1314
1315/*!
1316\qmlmethod ArrayBuffer Qt::btoa(ArrayBuffer data)
1317\since 6.11
1318
1319Binary to ASCII --- this function returns a base64 encoding of \a data.
1320
1321You can pass any array-like as \a data, and it will try to convert
1322it into a byte array. In particular this works with a list of numbers
1323and a list of one-character strings. The most efficient way to do this,
1324however, is passing either a QByteArray or a JavaScript ArrayBuffer
1325object.
1326
1327If the conversion fails and it turns out that the \a data is not of
1328the expected form, an \c{Invalid Character} exception is thrown and an
1329empty array is returned.
1330
1331*/
1332QByteArray QtObject::btoa(const QByteArray &data) const
1333{
1334 return data.toBase64();
1335}
1336
1337static QV4::ReturnedValue throwInvalidCharacter(QV4::ExecutionEngine *engine)
1338{
1339 QV4::Scope scope(engine);
1340 THROW_DOM(DOMEXCEPTION_INVALID_CHARACTER_ERR, "Invalid character");
1341}
1342
1343/*!
1344\qmlmethod ArrayBuffer Qt::atob(ArrayBuffer data)
1345\since 6.11
1346
1347ASCII to binary --- this function decodes the base64 encoded \a data and returns it.
1348
1349You can pass any array-like as \a data, and it will try to convert
1350it into a byte array. In particular this works with a list of numbers
1351and a list of one-character strings. The most efficient way to do this,
1352however, is passing either a QByteArray or a JavaScript ArrayBuffer
1353object.
1354
1355If the conversion fails and it turns out that the \a data is not of
1356the expected form, an \c{Invalid Character} exception is thrown and an
1357empty array is returned.
1358
1359*/
1360QByteArray QtObject::atob(const QByteArray &data) const
1361{
1362 const auto result
1363 = QByteArray::fromBase64Encoding(data, QByteArray::AbortOnBase64DecodingErrors);
1364 if (result.decodingStatus == QByteArray::Base64DecodingStatus::Ok)
1365 return result.decoded;
1366
1367 throwInvalidCharacter(v4Engine());
1368 return QByteArray();
1369}
1370
1371static QByteArray convertVariantList(const QVariantList &data, QV4::ExecutionEngine *engine)
1372{
1373 const auto fail = [&]() {
1374 throwInvalidCharacter(engine);
1375 return QByteArray();
1376 };
1377
1378 QByteArray result;
1379
1380 const auto append = [&](auto value) {
1381 if (value < 0 || value >= 256)
1382 return false;
1383 result.append(char(value));
1384 return true;
1385 };
1386
1387 for (const QVariant &entry : data) {
1388 switch (entry.typeId()) {
1389 case QMetaType::Char:
1390 result.append(*static_cast<const char *>(entry.constData()));
1391 break;
1392 case QMetaType::Int: {
1393 if (!append(*static_cast<const int *>(entry.constData())))
1394 return fail();
1395 break;
1396 }
1397 case QMetaType::Double: {
1398 if (!append(*static_cast<const double *>(entry.constData())))
1399 return fail();
1400 break;
1401 }
1402 case QMetaType::QString: {
1403 const QString *string = static_cast<const QString *>(entry.constData());
1404 if (string->length() != 1)
1405 return fail();
1406 if (!append(string->at(0).unicode()))
1407 return fail();
1408 break;
1409 }
1410 default:
1411 return fail();
1412 }
1413 }
1414
1415 return result;
1416}
1417
1418/*!
1419\qmlmethod var Qt::btoa(var data)
1420\overload
1421\since 6.11
1422
1423Binary to ASCII --- this function returns a base64 encoding of \a data.
1424*/
1425QByteArray QtObject::btoa(const QVariantList &data) const
1426{
1427 return btoa(convertVariantList(data, v4Engine()));
1428}
1429
1430/*!
1431\qmlmethod var Qt::atob(var data)
1432\overload
1433\since 6.11
1434
1435ASCII to binary --- this function decodes the base64 encoded \a data and returns it.
1436*/
1437QByteArray QtObject::atob(const QVariantList &data) const
1438{
1439 return atob(convertVariantList(data, v4Engine()));
1440}
1441
1442/*!
1443 \qmlmethod void Qt::quit()
1444
1445 This function causes the QQmlEngine::quit() signal to be emitted.
1446 Within the \l {Prototyping with the QML Runtime Tool}{qml tool},
1447 this causes the launcher application to exit; to quit a C++ application
1448 when this method is called, connect the QQmlEngine::quit() signal to the
1449 QCoreApplication::quit() slot.
1450
1451 \sa exit()
1452*/
1453void QtObject::quit() const
1454{
1455 if (QQmlEngine *engine = qmlEngine())
1456 QQmlEnginePrivate::get(engine)->sendQuit();
1457}
1458
1459/*!
1460 \qmlmethod void Qt::exit(int retCode)
1461
1462 This function causes the QQmlEngine::exit(int) signal to be emitted.
1463 Within the \l {Prototyping with the QML Runtime Tool}{qml tool},
1464 this causes the launcher application to exit with
1465 the specified return code (\a retCode). To exit from the event loop with a specified
1466 return code when this method is called, a C++ application can connect the
1467 QQmlEngine::exit(int) signal to the QCoreApplication::exit(int) slot.
1468
1469 \sa quit()
1470*/
1471void QtObject::exit(int retCode) const
1472{
1473 if (QQmlEngine *engine = qmlEngine())
1474 QQmlEnginePrivate::get(engine)->sendExit(retCode);
1475}
1476
1477/*!
1478\qmlmethod QtObject Qt::createQmlObject(string qml, QtObject parent, url url)
1479
1480Compiles the given \a qml string into a component and then returns a new object created from
1481that component. The new object will have the specified \a parent. Returns \c null if there was
1482an error in creating the component or the object.
1483
1484If \a url is specified, it will be used as URL of the component. This is useful for error
1485reporting.
1486
1487\warning The new component will shadow any existing component of the same URL. You should not
1488pass a URL of an existing component. In particular, by passing the URL of the surrounding QML
1489file, you prevent access to the surrounding component from the new one.
1490
1491Example (where \c parentItem is the id of an existing QML item):
1492
1493\snippet qml/createQmlObject.qml 0
1494
1495In the case of an error, a QQmlError object is thrown. This object has an additional property,
1496\c qmlErrors, which is an array of the errors encountered.
1497Each object in this array has the members \c lineNumber, \c columnNumber, \c fileName and \c message.
1498For example, if the above snippet had misspelled color as 'colro' then the array would contain an object like the following:
1499{ "lineNumber" : 1, "columnNumber" : 32, "fileName" : "dynamicSnippet1", "message" : "Cannot assign to non-existent property \"colro\""}.
1500
1501\note This function returns immediately, and therefore may not work if
1502the \a qml string loads new components (that is, external QML files that have not yet been loaded).
1503If this is the case, consider using \l{QtQml::Qt::createComponent()}{Qt.createComponent()} instead.
1504
1505\warning This function is extremely slow since it has to compile the passed QML string every time
1506it is invoked. Furthermore, it's very easy to produce invalid QML when programmatically constructing
1507QML code. It's much better to keep your QML components as separate files and add properties and
1508methods to customize their behavior than to produce new components by string manipulation.
1509
1510See \l {Dynamic QML Object Creation from JavaScript} for more information on using this function.
1511*/
1512QObject *QtObject::createQmlObject(const QString &qml, QObject *parent, const QUrl &url) const
1513{
1514 QQmlEngine *engine = qmlEngine();
1515 if (!engine) {
1516 v4Engine()->throwError(QStringLiteral("Qt.createQmlObject(): "
1517 "Can only be called on a QML engine."));
1518 return nullptr;
1519 }
1520
1521 struct Error {
1522 static ReturnedValue create(QV4::ExecutionEngine *v4, const QList<QQmlError> &errors) {
1523 Scope scope(v4);
1524 QString errorstr;
1525 // '+=' reserves extra capacity. Follow-up appending will be probably free.
1526 errorstr += QLatin1String("Qt.createQmlObject(): failed to create object: ");
1527
1528 QV4::ScopedArrayObject qmlerrors(scope, v4->newArrayObject());
1529 QV4::ScopedObject qmlerror(scope);
1530 QV4::ScopedString s(scope);
1531 QV4::ScopedValue v(scope);
1532 for (int ii = 0; ii < errors.size(); ++ii) {
1533 const QQmlError &error = errors.at(ii);
1534 errorstr += QLatin1String("\n ") + error.toString();
1535 qmlerror = v4->newObject();
1536 qmlerror->put((s = v4->newString(QStringLiteral("lineNumber"))), (v = QV4::Value::fromInt32(error.line())));
1537 qmlerror->put((s = v4->newString(QStringLiteral("columnNumber"))), (v = QV4::Value::fromInt32(error.column())));
1538 qmlerror->put((s = v4->newString(QStringLiteral("fileName"))), (v = v4->newString(error.url().toString())));
1539 qmlerror->put((s = v4->newString(QStringLiteral("message"))), (v = v4->newString(error.description())));
1540 qmlerrors->put(ii, qmlerror);
1541 }
1542
1543 v = v4->newString(errorstr);
1544 ScopedObject errorObject(scope, v4->newErrorObject(v));
1545 errorObject->put((s = v4->newString(QStringLiteral("qmlErrors"))), qmlerrors);
1546 return errorObject.asReturnedValue();
1547 }
1548 };
1549
1550 QQmlRefPointer<QQmlContextData> context = v4Engine()->callingQmlContext();
1551 if (!context)
1552 context = QQmlContextData::get(QQmlEnginePrivate::get(engine)->rootContext);
1553
1554 Q_ASSERT(context);
1555 QQmlContext *effectiveContext = nullptr;
1556 if (context->isPragmaLibraryContext())
1557 effectiveContext = engine->rootContext();
1558 else
1559 effectiveContext = context->asQQmlContext();
1560 Q_ASSERT(effectiveContext);
1561
1562 if (qml.isEmpty())
1563 return nullptr;
1564
1565 QUrl resolvedUrl = url;
1566 if (url.isValid() && url.isRelative())
1567 resolvedUrl = context->resolvedUrl(url);
1568
1569 if (!parent) {
1570 v4Engine()->throwError(QStringLiteral("Qt.createQmlObject(): Missing parent object"));
1571 return nullptr;
1572 }
1573
1574 QQmlRefPointer<QQmlTypeData> typeData = v4Engine()->typeLoader()->getType(
1575 qml.toUtf8(), resolvedUrl, QQmlTypeLoader::Synchronous);
1576
1577 if (!typeData->isCompleteOrError()) {
1578 v4Engine()->throwError(
1579 QStringLiteral("Qt.createQmlObject(): Failed to force synchronous loading "
1580 "of asynchronous URL '%1'").arg(resolvedUrl.toString()));
1581 return nullptr;
1582 }
1583
1584 QQmlComponent component(engine);
1585 QQmlComponentPrivate *componentPrivate = QQmlComponentPrivate::get(&component);
1586 componentPrivate->fromTypeData(typeData);
1587 componentPrivate->setProgress(1.0);
1588
1589 Scope scope(v4Engine());
1590 if (component.isError()) {
1591 ScopedValue v(scope, Error::create(scope.engine, component.errors()));
1592 scope.engine->throwError(v);
1593 return nullptr;
1594 }
1595
1596 if (!component.isReady()) {
1597 v4Engine()->throwError(QStringLiteral("Qt.createQmlObject(): Component is not ready"));
1598 return nullptr;
1599 }
1600
1601 if (!effectiveContext->isValid()) {
1602 v4Engine()->throwError(QStringLiteral("Qt.createQmlObject(): Cannot create a component "
1603 "in an invalid context"));
1604 return nullptr;
1605 }
1606
1607 QObject *obj = component.beginCreate(effectiveContext);
1608 if (obj) {
1609 QQmlData::get(obj, true)->explicitIndestructibleSet = false;
1610 QQmlData::get(obj)->indestructible = false;
1611
1612 obj->setParent(parent);
1613
1614 QList<QQmlPrivate::AutoParentFunction> functions = QQmlMetaType::parentFunctions();
1615 for (int ii = 0; ii < functions.size(); ++ii) {
1616 if (QQmlPrivate::Parented == functions.at(ii)(obj, parent))
1617 break;
1618 }
1619 }
1620 component.completeCreate();
1621
1622 v4Engine()->trimCompilationUnitsForUrl(resolvedUrl);
1623 if (component.isError()) {
1624 ScopedValue v(scope, Error::create(scope.engine, component.errors()));
1625 scope.engine->throwError(v);
1626 return nullptr;
1627 }
1628
1629 Q_ASSERT(obj);
1630 return obj;
1631}
1632
1633/*!
1634\qmlmethod Component Qt::createComponent(url url, enumeration mode, QtObject parent)
1635
1636Returns a \l Component object created using the QML file at the specified \a url,
1637or \c null if an empty string was given.
1638
1639The returned component's \l Component::status property indicates whether the
1640component was successfully created. If the status is \c Component.Error,
1641see \l Component::errorString() for an error description.
1642
1643If the optional \a mode parameter is set to \c Component.Asynchronous, the
1644component will be loaded in a background thread. The Component::status property
1645will be \c Component.Loading while it is loading. The status will change to
1646\c Component.Ready if the component loads successfully, or \c Component.Error
1647if loading fails. This parameter defaults to \c Component.PreferSynchronous
1648if omitted.
1649
1650If \a mode is set to \c Component.PreferSynchronous, Qt will attempt to load
1651the component synchronously, but may end up loading it asynchronously if
1652necessary. Scenarios that may cause asynchronous loading include, but are not
1653limited to, the following:
1654
1655\list
1656\li The URL refers to a network resource
1657\li The component is being created as a result of another component that is
1658being loaded asynchronously
1659\endlist
1660
1661If the optional \a parent parameter is given, it should refer to the object
1662that will become the parent for the created \l Component object. If no mode
1663was passed, this can be the second argument.
1664
1665Call \l {Component::createObject()}{Component.createObject()} on the returned
1666component to create an object instance of the component.
1667
1668For example:
1669
1670\snippet qml/createComponent-simple.qml 0
1671
1672See \l {Dynamic QML Object Creation from JavaScript} for more information on using this function.
1673
1674To create a QML object from an arbitrary string of QML (instead of a file),
1675use \l{QtQml::Qt::createQmlObject()}{Qt.createQmlObject()}.
1676*/
1677
1678/*!
1679\since 6.5
1680\qmlmethod Component Qt::createComponent(string moduleUri, string typeName, enumeration mode, QtObject parent)
1681\overload
1682Returns a \l Component object created for the type specified by \a moduleUri and \a typeName.
1683\qml
1684import QtQml
1685QtObject {
1686 id: root
1687 property Component myComponent: Qt.createComponent("QtQuick", "Rectangle", Component.Asynchronous, root)
1688}
1689\endqml
1690This overload mostly behaves as the \c url based version, but can be used
1691to instantiate types which do not have an URL (e.g. C++ types registered
1692via \l {QML_ELEMENT}).
1693\note In some cases, passing \c Component.Asynchronous won't have any
1694effect:
1695\list
1696\li The type is implemented in C++
1697\li The type is an inline component.
1698\endlist
1699If the optional \a parent parameter is given, it should refer to the object
1700that will become the parent for the created \l Component object. If no mode
1701was passed, this can be the second argument.
1702*/
1703
1704QQmlComponent *QtObject::createComponent(const QUrl &url, QObject *parent) const
1705{
1706 return createComponent(url, QQmlComponent::PreferSynchronous, parent);
1707}
1708
1710static void throw_invalid_compilation_mode(QV4::ExecutionEngine *engine, QQmlComponent::CompilationMode mode)
1711{
1712 engine->throwError(QStringLiteral("Invalid compilation mode %1").arg(int(mode)));
1713 // ^ QTBUG-131906
1714}
1715
1716QQmlComponent *QtObject::createComponent(const QUrl &url, QQmlComponent::CompilationMode mode,
1717 QObject *parent) const
1718{
1719 if (mode != QQmlComponent::Asynchronous && mode != QQmlComponent::PreferSynchronous) {
1720 throw_invalid_compilation_mode(v4Engine(), mode);
1721 return nullptr;
1722 }
1723
1724 if (url.isEmpty())
1725 return nullptr;
1726
1727 QQmlEngine *engine = qmlEngine();
1728 if (!engine)
1729 return nullptr;
1730
1731 auto [context, effectiveContext] = getContexts();
1732 if (!context)
1733 return nullptr;
1734
1735 QQmlComponent *c = new QQmlComponent(engine, context->resolvedUrl(url), mode, parent);
1736 QQmlComponentPrivate::get(c)->setCreationContext(std::move(effectiveContext));
1737 QQmlData::get(c, true)->explicitIndestructibleSet = false;
1738 QQmlData::get(c)->indestructible = false;
1739 return c;
1740}
1741
1742QQmlComponent *QtObject::createComponent(const QString &moduleUri, const QString &typeName,
1743 QObject *parent) const
1744{
1745 return createComponent(moduleUri, typeName, QQmlComponent::PreferSynchronous, parent);
1746}
1747
1748QQmlComponent *QtObject::createComponent(const QString &moduleUri, const QString &typeName, QQmlComponent::CompilationMode mode, QObject *parent) const
1749{
1750 if (mode != QQmlComponent::Asynchronous && mode != QQmlComponent::PreferSynchronous) {
1751 throw_invalid_compilation_mode(v4Engine(), mode);
1752 return nullptr;
1753 }
1754
1755 QQmlEngine *engine = qmlEngine();
1756 if (!engine)
1757 return nullptr;
1758
1759 if (moduleUri.isEmpty() || typeName.isEmpty())
1760 return nullptr;
1761
1762 auto [context, effectiveContext] = getContexts();
1763 if (!context)
1764 return nullptr;
1765
1766 QQmlComponent *c = new QQmlComponent(engine, moduleUri, typeName, mode, parent);
1767 if (c->isError() && !parent && moduleUri.endsWith(u".qml")) {
1768 v4Engine()->throwTypeError(
1769 QStringLiteral("Invalid arguments; did you swap mode and parent"));
1770 }
1771 QQmlComponentPrivate::get(c)->setCreationContext(std::move(effectiveContext));
1772 QQmlData::get(c, true)->explicitIndestructibleSet = false;
1773 QQmlData::get(c)->indestructible = false;
1774 return c;
1775}
1776
1777#if QT_CONFIG(translation)
1778QString QtObject::uiLanguage() const
1779{
1780 if (const QJSEngine *e = jsEngine())
1781 return e->uiLanguage();
1782 return QString();
1783}
1784
1785void QtObject::setUiLanguage(const QString &uiLanguage)
1786{
1787 if (QJSEngine *e = jsEngine())
1788 e->setUiLanguage(uiLanguage);
1789}
1790
1791QBindable<QString> QtObject::uiLanguageBindable()
1792{
1793 if (QJSEngine *e = jsEngine())
1794 return QBindable<QString>(&QJSEnginePrivate::get(e)->uiLanguage);
1795 return QBindable<QString>();
1796}
1797#endif
1798
1799#if QT_CONFIG(qml_locale)
1800/*!
1801 \qmlmethod locale Qt::locale(name)
1802
1803 Returns a JS object representing the locale with the specified
1804 \a name, which has the format "language[_territory][.codeset][@modifier]"
1805 or "C", where:
1806
1807 \list
1808 \li \c language is a lowercase, two-letter, ISO 639 language code,
1809 \li \c territory is an uppercase, two-letter, ISO 3166 country code, and
1810 \li \c codeset and \c modifier are ignored.
1811 \endlist
1812
1813 If the string violates the locale format, or language is not a
1814 valid ISO 369 code, the "C" locale is used instead. If country
1815 is not present, or is not a valid ISO 3166 code, the most
1816 appropriate country is chosen for the specified language.
1817
1818 The returned object is of an anonymous QML type backed by \l QLocale.
1819
1820 \sa Locale
1821*/
1822QLocale QtObject::locale() const
1823{
1824 return QLocale();
1825}
1826
1827QLocale QtObject::locale(const QString &name) const
1828{
1829 return QLocale(name);
1830}
1831#endif
1832
1833void Heap::QQmlBindingFunction::init(const QV4::JavaScriptFunctionObject *bindingFunction)
1834{
1835 Scope scope(bindingFunction->engine());
1836 ScopedContext context(scope, bindingFunction->scope());
1837 JavaScriptFunctionObject::init(context, bindingFunction->function());
1838 this->bindingFunction.set(internalClass->engine, bindingFunction->d());
1839}
1840
1841ReturnedValue QQmlBindingFunction::virtualCall(
1842 const FunctionObject *f, const Value *, const Value *, int)
1843{
1844 // Mark this as a callable object, so that we can perform the binding magic on it.
1845 return f->engine()->throwTypeError(QStringLiteral("Bindings must not be called directly."));
1846}
1847
1849{
1850 QV4::CppStackFrame *frame = engine()->currentStackFrame;
1851 if (frame->v4Function) // synchronous loading:
1852 return QQmlSourceLocation(frame->source(), frame->lineNumber(), 0);
1853 else // async loading:
1854 return bindingFunction()->function->sourceLocation();
1855}
1856
1858
1859/*!
1860 \qmlmethod var Qt::binding(var function)
1861
1862 Returns a JavaScript object representing a \l{Property Binding}{property binding},
1863 with a \a function that evaluates the binding.
1864
1865 There are two main use-cases for the function: firstly, to apply a
1866 property binding imperatively from JavaScript code:
1867
1868 \snippet qml/qtBinding.1.qml 0
1869
1870 and secondly, to apply a property binding when initializing property values
1871 of dynamically constructed objects (via \l{Component::createObject()}
1872 {Component.createObject()} or \l{Loader::setSource()}{Loader.setSource()}).
1873
1874 For example, assuming the existence of a DynamicText component:
1875 \snippet qml/DynamicText.qml 0
1876
1877 the output from:
1878 \snippet qml/qtBinding.2.qml 0
1879
1880 and from:
1881 \snippet qml/qtBinding.3.qml 0
1882
1883 should both be:
1884 \code
1885 Root text extra text
1886 Modified root text extra text
1887 Dynamic text extra text
1888 Modified dynamic text extra text
1889 \endcode
1890
1891 This function cannot be used in property binding declarations
1892 (see the documentation on \l{qml-javascript-assignment}{binding
1893 declarations and binding assignments}) except when the result is
1894 stored in an array bound to a var property.
1895
1896 \snippet qml/qtBinding.4.qml 0
1897
1898 \since 5.0
1899*/
1900QJSValue QtObject::binding(const QJSValue &function) const
1901{
1902 const QV4::JavaScriptFunctionObject *f
1903 = QJSValuePrivate::asManagedType<JavaScriptFunctionObject>(&function);
1904 QV4::ExecutionEngine *e = v4Engine();
1905 if (!f) {
1906 return QJSValuePrivate::fromReturnedValue(
1907 e->throwError(
1908 QStringLiteral(
1909 "binding(): argument (binding expression) must be a function")));
1910 }
1911
1912 return QJSValuePrivate::fromReturnedValue(
1913 Encode(e->memoryManager->allocate<QQmlBindingFunction>(f)));
1914}
1915
1916void QtObject::callLater(QQmlV4FunctionPtr args)
1917{
1918 m_engine->delayedCallQueue()->addUniquelyAndExecuteLater(m_engine, args);
1919}
1920
1921/*!
1922 \qmlmethod real Qt::enumStringToValue(enumType, keyName)
1923
1924 Returns the numeric value of key \a keyName in enum \a enumType. If the
1925 enum could not be found, a \c TypeError is thrown. If the key is not an
1926 entry of the enum, a \c ReferenceError is thrown.
1927 */
1928double QtObject::enumStringToValue(const QJSManagedValue &enumType, const QString &string)
1929{
1930 return retrieveFromEnum<double>(
1931 enumType,
1932 [&](const QQmlType &type, QQmlTypeLoader *typeLoader, int enumIndex, bool *ok) {
1933 return type.scopedEnumValue(typeLoader, enumIndex, string, ok);
1934 }, [&](const QQmlType &type, QQmlTypeLoader *typeLoader, int enumIndex, bool *ok) {
1935 return type.unscopedEnumValue(typeLoader, enumIndex, string, ok);
1936 }, m_engine);
1937}
1938
1939/*!
1940 \qmlmethod string Qt::enumValueToString(enumType, keyValue)
1941
1942 Returns the string representation of a key of enum \a enumType that has the
1943 value \a keyValue. If the enum could not be found, a \c TypeError is
1944 thrown. If the value does not match any key of the enum, a
1945 \c ReferenceError is thrown.
1946
1947 \note If multiple keys match the value of \a keyValue, which of the
1948 matching keys will be returned is unspecified. Use enumValueToStrings in
1949 that case.
1950 */
1951QString QtObject::enumValueToString(const QJSManagedValue &enumType, double value)
1952{
1953 // Undefined -> double = NaN
1954 if (std::isnan(value)) {
1955 m_engine->throwReferenceError("Invalid second argument, entry"_L1);
1956 return {};
1957 }
1958
1959 return retrieveFromEnum<QString>(
1960 enumType,
1961 [&](const QQmlType &type, QQmlTypeLoader *typeLoader, int enumIndex, bool *ok) {
1962 return type.scopedEnumKey(typeLoader, enumIndex, QtPrivate::qSaturateRound(value), ok);
1963 }, [&](const QQmlType &type, QQmlTypeLoader *typeLoader, int enumIndex, bool *ok) {
1964 return type.unscopedEnumKey(typeLoader, enumIndex, QtPrivate::qSaturateRound(value), ok);
1965 }, m_engine);
1966}
1967
1968/*!
1969 \qmlmethod list<string> Qt::enumValueToStrings(enumType, keyValue)
1970
1971 Returns a list of the string representation of all the keys of enum
1972 \a enumType that have the value \a keyValue. If the enum could not be
1973 found, a \c TypeError is thrown. If no key in the enum has value
1974 \a keyValue, a \c ReferenceError is thrown.
1975 */
1976QStringList QtObject::enumValueToStrings(const QJSManagedValue &enumType, double value)
1977{
1978 // Undefined -> double = NaN
1979 if (std::isnan(value)) {
1980 m_engine->throwReferenceError("Invalid second argument, entry"_L1);
1981 return {};
1982 }
1983
1984 return retrieveFromEnum<QStringList>(
1985 enumType,
1986 [&](const QQmlType &type, QQmlTypeLoader *typeLoader, int enumIndex, bool *ok) {
1987 return type.scopedEnumKeys(typeLoader, enumIndex, QtPrivate::qSaturateRound(value), ok);
1988 }, [&](const QQmlType &type, QQmlTypeLoader *typeLoader, int enumIndex, bool *ok) {
1989 return type.unscopedEnumKeys(typeLoader, enumIndex, QtPrivate::qSaturateRound(value), ok);
1990 }, m_engine);
1991}
1992
1993QQmlPlatform *QtObject::platform()
1994{
1995 if (!m_platform)
1996 m_platform = new QQmlPlatform(this);
1997 return m_platform;
1998}
1999
2000QQmlApplication *QtObject::application()
2001{
2002 if (!m_application)
2003 // Only allocate an application object once
2004 m_application = QQml_guiProvider()->application(this);
2005
2006 return m_application;
2007}
2008
2009QObject *QtObject::inputMethod() const
2010{
2011 return QQml_guiProvider()->inputMethod();
2012}
2013
2014QObject *QtObject::styleHints() const
2015{
2016 return QQml_guiProvider()->styleHints();
2017}
2018
2020{
2021 Object::init();
2022 QV4::Scope scope(internalClass->engine);
2023 QV4::ScopedObject o(scope, this);
2024
2025 o->defineDefaultProperty(QStringLiteral("debug"), QV4::ConsoleObject::method_log);
2026 o->defineDefaultProperty(QStringLiteral("log"), QV4::ConsoleObject::method_log);
2027 o->defineDefaultProperty(QStringLiteral("info"), QV4::ConsoleObject::method_info);
2028 o->defineDefaultProperty(QStringLiteral("warn"), QV4::ConsoleObject::method_warn);
2029 o->defineDefaultProperty(QStringLiteral("error"), QV4::ConsoleObject::method_error);
2030 o->defineDefaultProperty(QStringLiteral("assert"), QV4::ConsoleObject::method_assert);
2031
2032 o->defineDefaultProperty(QStringLiteral("count"), QV4::ConsoleObject::method_count);
2033 o->defineDefaultProperty(QStringLiteral("profile"), QV4::ConsoleObject::method_profile);
2034 o->defineDefaultProperty(QStringLiteral("profileEnd"), QV4::ConsoleObject::method_profileEnd);
2035 o->defineDefaultProperty(QStringLiteral("time"), QV4::ConsoleObject::method_time);
2036 o->defineDefaultProperty(QStringLiteral("timeEnd"), QV4::ConsoleObject::method_timeEnd);
2037 o->defineDefaultProperty(QStringLiteral("trace"), QV4::ConsoleObject::method_trace);
2038 o->defineDefaultProperty(QStringLiteral("exception"), QV4::ConsoleObject::method_exception);
2039}
2040
2041
2048
2049static QString jsStack(QV4::ExecutionEngine *engine) {
2050 QString stack;
2051
2052 int i = 0;
2053 for (CppStackFrame *f = engine->currentStackFrame; f && i < 10; f = f->parentFrame(), ++i) {
2054 QString stackFrame;
2055
2056 if (f->isJSTypesFrame() && static_cast<JSTypesStackFrame *>(f)->isTailCalling()) {
2057 stackFrame = QStringLiteral("[elided tail calls]");
2058 } else {
2059 const int line = f->lineNumber();
2060 if (line != f->missingLineNumber()) {
2061 stackFrame = QStringLiteral("%1 (%2:%3)").arg(
2062 f->function(), f->source(), QString::number(qAbs(line)));
2063 } else {
2064 stackFrame = QStringLiteral("%1 (%2)").arg(
2065 f->function(), f->source());
2066 }
2067 }
2068
2069 if (i)
2070 stack += QLatin1Char('\n');
2071 stack += stackFrame;
2072 }
2073 return stack;
2074}
2075
2076static QString serializeArray(Object *array, ExecutionEngine *v4, QSet<QV4::Heap::Object *> &alreadySeen) {
2077 Scope scope(v4);
2078 ScopedValue val(scope);
2079 QString result;
2080 alreadySeen.insert(array->d());
2081
2082 ScopedObject detached(scope);
2083 if (Sequence *reference = array->as<Sequence>())
2084 detached = ReferenceObject::detached(reference->d());
2085 else
2086 detached = array;
2087
2088 result += QLatin1Char('[');
2089 const uint length = detached->getLength();
2090 for (uint i = 0; i < length; ++i) {
2091 if (i != 0)
2092 result += QLatin1Char(',');
2093 val = detached->get(i);
2094 if (val->isManaged() && val->managed()->isArrayLike())
2095 if (!alreadySeen.contains(val->objectValue()->d()))
2096 result += serializeArray(val->objectValue(), v4, alreadySeen);
2097 else
2098 result += QLatin1String("[Circular]");
2099 else
2100 result += val->toQStringNoThrow();
2101 }
2102 result += QLatin1Char(']');
2103
2104 alreadySeen.remove(array->d());
2105 return result;
2106};
2107
2108static ReturnedValue writeToConsole(const FunctionObject *b, const Value *argv, int argc,
2109 ConsoleLogTypes logType, bool printStack = false)
2110{
2111 const QLoggingCategory *loggingCategory = nullptr;
2112 QString result;
2113 QV4::Scope scope(b);
2114 QV4::ExecutionEngine *v4 = scope.engine;
2115
2116 int start = 0;
2117 if (argc > 0) {
2118 if (const QObjectWrapper* wrapper = argv[0].as<QObjectWrapper>()) {
2119 if (QQmlLoggingCategoryBase *category
2120 = qobject_cast<QQmlLoggingCategoryBase *>(wrapper->object())) {
2121 if (category->category())
2122 loggingCategory = category->category();
2123 else
2124 THROW_GENERIC_ERROR("A QmlLoggingCatgory was provided without a valid name");
2125 start = 1;
2126 }
2127 }
2128 }
2129
2130
2131 for (int i = start, ei = argc; i < ei; ++i) {
2132 if (i != start)
2133 result.append(QLatin1Char(' '));
2134
2135 QSet<QV4::Heap::Object *> alreadySeenElements;
2136 if (argv[i].isManaged() && argv[i].managed()->isArrayLike())
2137 result.append(serializeArray(argv[i].objectValue(), v4, alreadySeenElements));
2138 else
2139 result.append(argv[i].toQStringNoThrow());
2140 }
2141
2142 if (printStack)
2143 result += QLatin1Char('\n') + jsStack(v4);
2144
2145 if (!loggingCategory)
2146 loggingCategory = v4->qmlEngine() ? &lcQml() : &lcJs();
2147 QV4::CppStackFrame *frame = v4->currentStackFrame;
2148 const QByteArray baSource = frame ? frame->source().toUtf8() : QByteArray();
2149 const QByteArray baFunction = frame ? frame->function().toUtf8() : QByteArray();
2150 QMessageLogger logger(baSource.constData(), frame ? frame->lineNumber() : 0,
2151 baFunction.constData(), loggingCategory->categoryName());
2152
2153 switch (logType) {
2154 case Log:
2155 if (loggingCategory->isDebugEnabled())
2156 logger.debug("%s", result.toUtf8().constData());
2157 break;
2158 case Info:
2159 if (loggingCategory->isInfoEnabled())
2160 logger.info("%s", result.toUtf8().constData());
2161 break;
2162 case Warn:
2163 if (loggingCategory->isWarningEnabled())
2164 logger.warning("%s", result.toUtf8().constData());
2165 break;
2166 case Error:
2167 if (loggingCategory->isCriticalEnabled())
2168 logger.critical("%s", result.toUtf8().constData());
2169 break;
2170 default:
2171 break;
2172 }
2173
2174 return Encode::undefined();
2175}
2176
2178
2179ReturnedValue ConsoleObject::method_error(const FunctionObject *b, const Value *, const Value *argv, int argc)
2180{
2181 return writeToConsole(b, argv, argc, Error);
2182}
2183
2184ReturnedValue ConsoleObject::method_log(const FunctionObject *b, const Value *, const Value *argv, int argc)
2185{
2186 //console.log
2187 //console.debug
2188 //print
2189 return writeToConsole(b, argv, argc, Log);
2190}
2191
2192ReturnedValue ConsoleObject::method_info(const FunctionObject *b, const Value *, const Value *argv, int argc)
2193{
2194 return writeToConsole(b, argv, argc, Info);
2195}
2196
2197ReturnedValue ConsoleObject::method_profile(const FunctionObject *b, const Value *, const Value *, int)
2198{
2199 QV4::Scope scope(b);
2200 QV4::ExecutionEngine *v4 = scope.engine;
2201
2202 QV4::CppStackFrame *frame = v4->currentStackFrame;
2203 const QByteArray baSource = frame->source().toUtf8();
2204 const QByteArray baFunction = frame->function().toUtf8();
2205 QMessageLogger logger(baSource.constData(), frame->lineNumber(), baFunction.constData());
2206 QQmlProfilerService *service = QQmlDebugConnector::service<QQmlProfilerService>();
2207 if (!service) {
2208 logger.warning("Cannot start profiling because debug service is disabled. Start with -qmljsdebugger=port:XXXXX.");
2209 } else {
2210 service->startProfiling(v4->jsEngine());
2211 logger.debug("Profiling started.");
2212 }
2213
2214 return QV4::Encode::undefined();
2215}
2216
2217ReturnedValue ConsoleObject::method_profileEnd(const FunctionObject *b, const Value *, const Value *, int)
2218{
2219 QV4::Scope scope(b);
2220 QV4::ExecutionEngine *v4 = scope.engine;
2221
2222 QV4::CppStackFrame *frame = v4->currentStackFrame;
2223 const QByteArray baSource = frame->source().toUtf8();
2224 const QByteArray baFunction = frame->function().toUtf8();
2225 QMessageLogger logger(baSource.constData(), frame->lineNumber(), baFunction.constData());
2226
2227 QQmlProfilerService *service = QQmlDebugConnector::service<QQmlProfilerService>();
2228 if (!service) {
2229 logger.warning("Ignoring console.profileEnd(): the debug service is disabled.");
2230 } else {
2231 service->stopProfiling(v4->jsEngine());
2232 logger.debug("Profiling ended.");
2233 }
2234
2235 return QV4::Encode::undefined();
2236}
2237
2238ReturnedValue ConsoleObject::method_time(const FunctionObject *b, const Value *, const Value *argv, int argc)
2239{
2240 QV4::Scope scope(b);
2241 if (argc != 1)
2242 THROW_GENERIC_ERROR("console.time(): Invalid arguments");
2243
2244 QString name = argv[0].toQStringNoThrow();
2245 scope.engine->startTimer(name);
2246 return QV4::Encode::undefined();
2247}
2248
2249ReturnedValue ConsoleObject::method_timeEnd(const FunctionObject *b, const Value *, const Value *argv, int argc)
2250{
2251 QV4::Scope scope(b);
2252 if (argc != 1)
2253 THROW_GENERIC_ERROR("console.timeEnd(): Invalid arguments");
2254
2255 QString name = argv[0].toQStringNoThrow();
2256 bool wasRunning;
2257 qint64 elapsed = scope.engine->stopTimer(name, &wasRunning);
2258 if (wasRunning) {
2259 qDebug("%s: %llims", qPrintable(name), elapsed);
2260 }
2261 return QV4::Encode::undefined();
2262}
2263
2264ReturnedValue ConsoleObject::method_count(const FunctionObject *b, const Value *, const Value *argv, int argc)
2265{
2266 // first argument: name to print. Ignore any additional arguments
2267 QString name;
2268 if (argc > 0)
2269 name = argv[0].toQStringNoThrow();
2270
2271 Scope scope(b);
2272 QV4::ExecutionEngine *v4 = scope.engine;
2273
2274 QV4::CppStackFrame *frame = v4->currentStackFrame;
2275
2276 QString scriptName = frame->source();
2277
2278 int value = v4->consoleCountHelper(scriptName, frame->lineNumber(), 0);
2279 QString message = name + QLatin1String(": ") + QString::number(value);
2280
2281 QMessageLogger(qPrintable(scriptName), frame->lineNumber(),
2282 qPrintable(frame->function()))
2283 .debug("%s", qPrintable(message));
2284
2285 return QV4::Encode::undefined();
2286}
2287
2288ReturnedValue ConsoleObject::method_trace(const FunctionObject *b, const Value *, const Value *, int argc)
2289{
2290 QV4::Scope scope(b);
2291 if (argc != 0)
2292 THROW_GENERIC_ERROR("console.trace(): Invalid arguments");
2293
2294 QV4::ExecutionEngine *v4 = scope.engine;
2295
2296 QString stack = jsStack(v4);
2297
2298 QV4::CppStackFrame *frame = v4->currentStackFrame;
2299 QMessageLogger(frame->source().toUtf8().constData(), frame->lineNumber(),
2300 frame->function().toUtf8().constData())
2301 .debug(v4->qmlEngine() ? lcQml() : lcJs(), "%s", qPrintable(stack));
2302
2303 return QV4::Encode::undefined();
2304}
2305
2306ReturnedValue ConsoleObject::method_warn(const FunctionObject *b, const Value *, const Value *argv, int argc)
2307{
2308 return writeToConsole(b, argv, argc, Warn);
2309}
2310
2311ReturnedValue ConsoleObject::method_assert(const FunctionObject *b, const Value *, const Value *argv, int argc)
2312{
2313 QV4::Scope scope(b);
2314 if (argc == 0)
2315 THROW_GENERIC_ERROR("console.assert(): Missing argument");
2316
2317 QV4::ExecutionEngine *v4 = scope.engine;
2318
2319 if (!argv[0].toBoolean()) {
2320 QString message;
2321 for (int i = 1, ei = argc; i < ei; ++i) {
2322 if (i != 1)
2323 message.append(QLatin1Char(' '));
2324
2325 message.append(argv[i].toQStringNoThrow());
2326 }
2327
2328 QString stack = jsStack(v4);
2329
2330 QV4::CppStackFrame *frame = v4->currentStackFrame;
2331 QMessageLogger(frame->source().toUtf8().constData(), frame->lineNumber(),
2332 frame->function().toUtf8().constData())
2333 .critical("%s\n%s",qPrintable(message), qPrintable(stack));
2334
2335 }
2336 return QV4::Encode::undefined();
2337}
2338
2339ReturnedValue ConsoleObject::method_exception(const FunctionObject *b, const Value *, const Value *argv, int argc)
2340{
2341 QV4::Scope scope(b);
2342 if (argc == 0)
2343 THROW_GENERIC_ERROR("console.exception(): Missing argument");
2344
2345 return writeToConsole(b, argv, argc, Error, true);
2346}
2347
2348void QV4::GlobalExtensions::init(Object *globalObject, QJSEngine::Extensions extensions)
2349{
2350 ExecutionEngine *v4 = globalObject->engine();
2351 Scope scope(v4);
2352
2353 if (extensions.testFlag(QJSEngine::TranslationExtension)) {
2354 #if QT_CONFIG(translation)
2355 globalObject->defineDefaultProperty(QStringLiteral("qsTranslate"), QV4::GlobalExtensions::method_qsTranslate);
2356 globalObject->defineDefaultProperty(QStringLiteral("QT_TRANSLATE_NOOP"), QV4::GlobalExtensions::method_qsTranslateNoOp);
2357 globalObject->defineDefaultProperty(QStringLiteral("qsTr"), QV4::GlobalExtensions::method_qsTr);
2358 globalObject->defineDefaultProperty(QStringLiteral("QT_TR_NOOP"), QV4::GlobalExtensions::method_qsTrNoOp);
2359 globalObject->defineDefaultProperty(QStringLiteral("qsTrId"), QV4::GlobalExtensions::method_qsTrId);
2360 globalObject->defineDefaultProperty(QStringLiteral("QT_TRID_NOOP"), QV4::GlobalExtensions::method_qsTrIdNoOp);
2361
2362 // Initialize the Qt global object for the uiLanguage property
2363 ScopedString qtName(scope, v4->newString(QStringLiteral("Qt")));
2364 ScopedObject qt(scope, globalObject->get(qtName));
2365 if (!qt)
2366 v4->createQtObject();
2367
2368 // string prototype extension
2369 scope.engine->stringPrototype()->defineDefaultProperty(QStringLiteral("arg"), QV4::GlobalExtensions::method_string_arg);
2370 #endif
2371 }
2372
2373 if (extensions.testFlag(QJSEngine::ConsoleExtension)) {
2374 globalObject->defineDefaultProperty(QStringLiteral("print"), QV4::ConsoleObject::method_log);
2375
2376
2377 QV4::ScopedObject console(scope, globalObject->engine()->memoryManager->allocate<QV4::ConsoleObject>());
2378 globalObject->defineDefaultProperty(QStringLiteral("console"), console);
2379 }
2380
2381 if (extensions.testFlag(QJSEngine::GarbageCollectionExtension)) {
2382 globalObject->defineDefaultProperty(QStringLiteral("gc"), QV4::GlobalExtensions::method_gc);
2383 }
2384}
2385
2386
2387#if QT_CONFIG(translation)
2388/*!
2389 \qmlmethod string Qt::qsTranslate(string context, string sourceText, string disambiguation, int n)
2390
2391 Returns a translated version of \a sourceText within the given \a context, optionally based on a
2392 \a disambiguation string and value of \a n for strings containing plurals;
2393 otherwise returns \a sourceText itself if no appropriate translated string
2394 is available.
2395
2396 If the same \a sourceText is used in different roles within the
2397 same translation \a context, an additional identifying string may be passed in
2398 for \a disambiguation.
2399
2400 Example:
2401 \snippet qml/qsTranslate.qml 0
2402
2403 Use if you have a translation \a context that differs from the file \a context.
2404
2405 \sa {Internationalization with Qt}
2406 \sa qsTr()
2407*/
2408ReturnedValue GlobalExtensions::method_qsTranslate(const FunctionObject *b, const Value *, const Value *argv, int argc)
2409{
2410 QV4::Scope scope(b);
2411 if (argc < 2)
2412 THROW_GENERIC_ERROR("qsTranslate() requires at least two arguments");
2413 if (!argv[0].isString())
2414 THROW_GENERIC_ERROR("qsTranslate(): first argument (context) must be a string");
2415 if (!argv[1].isString())
2416 THROW_GENERIC_ERROR("qsTranslate(): second argument (sourceText) must be a string");
2417 if ((argc > 2) && !argv[2].isString())
2418 THROW_GENERIC_ERROR("qsTranslate(): third argument (disambiguation) must be a string");
2419
2420 QString context = argv[0].toQStringNoThrow();
2421 QString text = argv[1].toQStringNoThrow();
2422 QString comment;
2423 if (argc > 2) comment = argv[2].toQStringNoThrow();
2424
2425 int i = 3;
2426 if (argc > i && argv[i].isString()) {
2427 qWarning("qsTranslate(): specifying the encoding as fourth argument is deprecated");
2428 ++i;
2429 }
2430
2431 int n = -1;
2432 if (argc > i)
2433 n = argv[i].toInt32();
2434
2435 if (QQmlEnginePrivate *ep = (scope.engine->qmlEngine() ? QQmlEnginePrivate::get(scope.engine->qmlEngine()) : nullptr))
2436 if (ep->propertyCapture)
2437 ep->propertyCapture->captureTranslation();
2438
2439 QString result = QCoreApplication::translate(context.toUtf8().constData(),
2440 text.toUtf8().constData(),
2441 comment.toUtf8().constData(),
2442 n);
2443
2444 return Encode(scope.engine->newString(result));
2445}
2446
2447/*!
2448 \qmlmethod string Qt::QT_TRANSLATE_NOOP(string context, string sourceText, string disambiguation)
2449
2450 Marks \a sourceText for dynamic translation in the given \a context; i.e, the stored \a sourceText
2451 will not be altered.
2452
2453 If the same \a sourceText is used in different roles within the
2454 same translation context, an additional identifying string may be passed in
2455 for \a disambiguation.
2456
2457 Returns the \a sourceText.
2458
2459 QT_TRANSLATE_NOOP is used in conjunction with the dynamic translation functions
2460 qsTr() and qsTranslate(). It identifies a string as requiring
2461 translation (so it can be identified by \c lupdate), but leaves the actual
2462 translation to the dynamic functions.
2463
2464 Example:
2465 \snippet qml/qtTranslateNoOp.qml 0
2466
2467 \sa {Internationalization with Qt}
2468*/
2469ReturnedValue GlobalExtensions::method_qsTranslateNoOp(const FunctionObject *b, const Value *, const Value *argv, int argc)
2470{
2471 QV4::Scope scope(b);
2472 if (argc < 2)
2473 return QV4::Encode::undefined();
2474 else
2475 return argv[1].asReturnedValue();
2476}
2477
2478QString GlobalExtensions::currentTranslationContext(ExecutionEngine *engine)
2479{
2480 QString context;
2481 CppStackFrame *frame = engine->currentStackFrame;
2482
2483 // The first non-empty source URL in the call stack determines the translation context.
2484 while (frame && context.isEmpty()) {
2485 if (ExecutableCompilationUnit *unit = frame->v4Function->executableCompilationUnit()) {
2486 auto translationContextIndex = unit->unitData()->translationContextIndex();
2487 if (translationContextIndex)
2488 context = unit->stringAt(*translationContextIndex);
2489 if (!context.isEmpty())
2490 break;
2491 QString fileName = unit->fileName();
2492 QUrl url(unit->fileName());
2493 if (url.isValid() && url.isRelative()) {
2494 context = url.fileName();
2495 } else {
2496 context = QQmlFile::urlToLocalFileOrQrc(fileName);
2497 if (context.isEmpty() && fileName.startsWith(QLatin1String(":/")))
2498 context = fileName;
2499 }
2500 context = QFileInfo(context).completeBaseName();
2501 }
2502 frame = frame->parentFrame();
2503 }
2504
2505 if (context.isEmpty()) {
2506 if (QQmlRefPointer<QQmlContextData> ctxt = engine->callingQmlContext()) {
2507 QString path = ctxt->urlString();
2508 int lastSlash = path.lastIndexOf(QLatin1Char('/'));
2509 int lastDot = path.lastIndexOf(QLatin1Char('.'));
2510 int length = lastDot - (lastSlash + 1);
2511 context = (lastSlash > -1) ? path.mid(lastSlash + 1, (length > -1) ? length : -1) : QString();
2512 }
2513 }
2514
2515 return context;
2516}
2517
2518/*!
2519 \qmlmethod string Qt::qsTr(string sourceText, string disambiguation, int n)
2520
2521 Returns a translated version of \a sourceText, optionally based on a
2522 \a disambiguation string and value of \a n for strings containing plurals;
2523 otherwise returns \a sourceText itself if no appropriate translated string
2524 is available.
2525
2526 Examples with \a sourceText and \a {n}:
2527
2528 \if defined(onlinedocs)
2529 \tab {qstr}{qstr-1}{sourceText}{checked}
2530 \tab {qstr}{qstr-2}{sourceText and n}{}
2531 \tabcontent {qstr-1}
2532 \else
2533 \section1 Only sourceText
2534 \endif
2535 \snippet qml/qsTr.qml 0
2536 \if defined(onlinedocs)
2537 \endtabcontent
2538 \tabcontent {qstr-2}
2539 \else
2540 \section1 SourceText and n
2541 \endif
2542 \snippet qml/qsTr.qml 1
2543 \if defined(onlinedocs)
2544 \endtabcontent
2545 \endif
2546
2547 If the same \a sourceText is used in different roles within the
2548 same translation context, an additional identifying string may be passed in
2549 for \a disambiguation. For more information and examples, refer to
2550 \l{Disambiguate Identical Text}.
2551
2552 \sa qsTranslate()
2553 \sa {Internationalization with Qt},{Writing Source Code for Translation}
2554*/
2555ReturnedValue GlobalExtensions::method_qsTr(const FunctionObject *b, const Value *, const Value *argv, int argc)
2556{
2557 QV4::Scope scope(b);
2558 if (argc < 1)
2559 THROW_GENERIC_ERROR("qsTr() requires at least one argument");
2560 if (!argv[0].isString())
2561 THROW_GENERIC_ERROR("qsTr(): first argument (sourceText) must be a string");
2562 if ((argc > 1) && !argv[1].isString())
2563 THROW_GENERIC_ERROR("qsTr(): second argument (disambiguation) must be a string");
2564 if ((argc > 2) && !argv[2].isNumber())
2565 THROW_GENERIC_ERROR("qsTr(): third argument (n) must be a number");
2566
2567 const QString context = currentTranslationContext(scope.engine);
2568 const QString text = argv[0].toQStringNoThrow();
2569 const QString comment = argc > 1 ? argv[1].toQStringNoThrow() : QString();
2570 const int n = argc > 2 ? argv[2].toInt32() : -1;
2571
2572 if (QQmlEnginePrivate *ep = (scope.engine->qmlEngine() ? QQmlEnginePrivate::get(scope.engine->qmlEngine()) : nullptr))
2573 if (ep->propertyCapture)
2574 ep->propertyCapture->captureTranslation();
2575
2576 QString result = QCoreApplication::translate(context.toUtf8().constData(), text.toUtf8().constData(),
2577 comment.toUtf8().constData(), n);
2578
2579 return Encode(scope.engine->newString(result));
2580}
2581
2582/*!
2583 \qmlmethod string Qt::QT_TR_NOOP(string sourceText, string disambiguation)
2584
2585 Marks \a sourceText for dynamic translation; i.e, the stored \a sourceText
2586 will not be altered.
2587
2588 If the same \a sourceText is used in different roles within the
2589 same translation context, an additional identifying string may be passed in
2590 for \a disambiguation.
2591
2592 Returns the \a sourceText.
2593
2594 QT_TR_NOOP is used in conjunction with the dynamic translation functions
2595 qsTr() and qsTranslate(). It identifies a string as requiring
2596 translation (so it can be identified by \c lupdate), but leaves the actual
2597 translation to the dynamic functions.
2598
2599 Example:
2600 \snippet qml/qtTrNoOp.qml 0
2601
2602 \sa {Internationalization with Qt}
2603*/
2604ReturnedValue GlobalExtensions::method_qsTrNoOp(const FunctionObject *, const Value *, const Value *argv, int argc)
2605{
2606 if (argc < 1)
2607 return QV4::Encode::undefined();
2608 else
2609 return argv[0].asReturnedValue();
2610}
2611
2612/*!
2613 \qmlmethod string Qt::qsTrId(string id, int n)
2614
2615 Returns a translated string identified by \a id.
2616 If no matching string is found, the id itself is returned. This
2617 should not happen under normal conditions.
2618
2619 If \a n >= 0, all occurrences of \c %n in the resulting string
2620 are replaced with a decimal representation of \a n. In addition,
2621 depending on \a n's value, the translation text may vary.
2622
2623 Example:
2624 \snippet qml/qsTrId.qml 0
2625
2626 It is possible to supply a source string template like:
2627
2628 \tt{//% <string>}
2629
2630 \snippet qml/qsTrId.1.qml 0
2631
2632 or
2633
2634 \tt{\begincomment% <string> \endcomment}
2635
2636 \snippet qml/qsTrId.1.qml 1
2637
2638 Creating binary translation (QM) files suitable for use with this function requires passing
2639 the \c -idbased option to the \c lrelease tool.
2640
2641 \sa QT_TRID_NOOP(), {Internationalization with Qt}
2642*/
2643ReturnedValue GlobalExtensions::method_qsTrId(const FunctionObject *b, const Value *, const Value *argv, int argc)
2644{
2645 QV4::Scope scope(b);
2646 if (argc < 1)
2647 THROW_GENERIC_ERROR("qsTrId() requires at least one argument");
2648 if (!argv[0].isString())
2649 THROW_TYPE_ERROR_WITH_MESSAGE("qsTrId(): first argument (id) must be a string");
2650 if (argc > 1 && !argv[1].isNumber())
2651 THROW_TYPE_ERROR_WITH_MESSAGE("qsTrId(): second argument (n) must be a number");
2652
2653 int n = -1;
2654 if (argc > 1)
2655 n = argv[1].toInt32();
2656
2657 if (QQmlEnginePrivate *ep = (scope.engine->qmlEngine() ? QQmlEnginePrivate::get(scope.engine->qmlEngine()) : nullptr))
2658 if (ep->propertyCapture)
2659 ep->propertyCapture->captureTranslation();
2660
2661 return Encode(scope.engine->newString(qtTrId(argv[0].toQStringNoThrow().toUtf8().constData(), n)));
2662}
2663
2664/*!
2665 \qmlmethod string Qt::QT_TRID_NOOP(string id)
2666
2667 Marks \a id for dynamic translation.
2668
2669 Returns the \a id.
2670
2671 QT_TRID_NOOP is used in conjunction with the dynamic translation function
2672 qsTrId(). It identifies a string as requiring translation (so it can be identified
2673 by \c lupdate), but leaves the actual translation to qsTrId().
2674
2675 Example:
2676 \snippet qml/qtTrIdNoOp.qml 0
2677
2678 \sa qsTrId(), {Internationalization with Qt}
2679*/
2680ReturnedValue GlobalExtensions::method_qsTrIdNoOp(const FunctionObject *, const Value *, const Value *argv, int argc)
2681{
2682 if (argc < 1)
2683 return QV4::Encode::undefined();
2684 else
2685 return argv[0].asReturnedValue();
2686}
2687#endif // translation
2688
2689/*!
2690 \qmlmethod void Qt::gc()
2691
2692 Runs the garbage collector.
2693
2694 This is equivalent to calling QJSEngine::collectGarbage().
2695
2696 \sa {Garbage Collection}
2697*/
2698ReturnedValue GlobalExtensions::method_gc(const FunctionObject *b, const Value *, const Value *, int)
2699{
2700 auto mm = b->engine()->memoryManager;
2701 mm->runFullGC();
2702
2703 return QV4::Encode::undefined();
2704}
2705
2706ReturnedValue GlobalExtensions::method_string_arg(const FunctionObject *b, const Value *thisObject, const Value *argv, int argc)
2707{
2708 QV4::Scope scope(b);
2709 if (argc < 1)
2710 THROW_GENERIC_ERROR("String.arg(): Invalid arguments");
2711
2712 QString value = thisObject->toQString();
2713
2714 // Fast path for single argument
2715 if (argc == 1) {
2716 QV4::ScopedValue arg(scope, argv[0]);
2717 if (arg->isInteger())
2718 value = value.arg(arg->integerValue());
2719 else if (arg->isDouble())
2720 value = value.arg(arg->doubleValue());
2721 else if (arg->isBoolean())
2722 value = value.arg(arg->booleanValue());
2723 else
2724 value = value.arg(arg->toQString());
2725 RETURN_RESULT(scope.engine->newString(value));
2726 }
2727
2728 // Preallocate for up to 10 arguments on the stack
2729 constexpr int PreallocArgCount = 10;
2730
2731 // Convert QV4 values to QStringViewArg for QtPrivate::argToQString
2732 QVarLengthArray<QString, PreallocArgCount> argStrings(argc);
2733 QVarLengthArray<QtPrivate::QStringViewArg, PreallocArgCount> args(argc);
2734 QVarLengthArray<const QtPrivate::ArgBase *, PreallocArgCount> argBases(argc);
2735
2736 for (int i = 0; i < argc; ++i) {
2737 QV4::ScopedValue arg(scope, argv[i]);
2738
2739 if (arg->isInteger())
2740 argStrings[i] = QString::number(arg->integerValue());
2741 else if (arg->isDouble())
2742 argStrings[i] = QString::number(arg->doubleValue());
2743 else if (arg->isBoolean())
2744 argStrings[i] = QString::number(arg->booleanValue());
2745 else
2746 argStrings[i] = arg->toQString();
2747
2748 args[i] = QtPrivate::QStringViewArg(argStrings[i]);
2749 argBases[i] = &args[i];
2750 }
2751
2752 QString result = QtPrivate::argToQString(value, argc, argBases.data());
2753 RETURN_RESULT(scope.engine->newString(result));
2754}
2755
2756/*!
2757\qmlmethod void Qt::callLater(function)
2758\qmlmethod void Qt::callLater(function, argument1, argument2, ...)
2759\since 5.8
2760Use this function to eliminate redundant calls to a function or signal.
2761
2762The function passed as the first argument to Qt.callLater()
2763will be called later, once the QML engine returns to the event loop.
2764
2765When this function is called multiple times in quick succession with the
2766same function as its first argument, that function will be called only once.
2767
2768For example:
2769\snippet qml/qtLater.qml 0
2770
2771Any additional arguments passed to Qt.callLater() will
2772be passed on to the function invoked. Note that if redundant calls
2773are eliminated, then only the last set of arguments will be passed to the
2774function.
2775*/
2776
2777/*!
2778\qmlmethod void Qt::callLater(object, function)
2779\qmlmethod void Qt::callLater(object, function, argument1, argument2, ...)
2780\since 6.13
2781\overload
2782
2783Use this overload to tie a delayed call to the lifetime of \a object, for
2784example when \a function belongs to another object.
2785
2786Like Qt.callLater(function), this calls \a function later, once the QML engine
2787returns to the event loop, and passes on any additional arguments. The call is
2788skipped if, by then, \a object has been deleted or scheduled for deletion, for
2789example with \c destroy(), or if the QML context of \a object has been
2790invalidated, as when a \l Loader unloads it. If \a object has no
2791QML context, only its lifetime is checked. \a object guards \a function
2792whatever kind of function it is, including a JavaScript closure or a method of
2793a C++ object.
2794
2795When this overload is called multiple times in quick succession with the same
2796\a object, \a function, and arguments, that function is called only once,
2797after any calls scheduled in between. Arguments are compared with \c ===, so
2798calls with different arguments, or with distinct but equal objects, are all
2799made. Functions are compared the same way: a function defined inside a signal
2800handler, such as an arrow function, is a new function each time the handler
2801runs. The same function scheduled with two different objects is called once
2802for each object. In this example, each delegate gets its own call, which is
2803skipped once the delegate is destroyed:
2804
2805\qml
2806ListView {
2807 id: view
2808 function relayout(row) { console.log("relayout", row.width) }
2809 delegate: Item {
2810 id: row
2811 onWidthChanged: Qt.callLater(row, view.relayout, row)
2812 }
2813}
2814\endqml
2815
2816Calls scheduled with and without an object are never combined.
2817
2818Throws an error if \a object is not a QObject, for example \c null or
2819\c undefined, or if \a function is not a function or signal.
2820*/
2821
2822QT_END_NAMESPACE
2823
2824#include "moc_qqmlbuiltinfunctions_p.cpp"
Combined button and popup list for selecting options.
Definition qjsvalue.h:24
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