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
qqmllocale.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
5#include "qqmllocale_p.h"
6#include <private/qqmlcontext_p.h>
7#include <QtCore/qnumeric.h>
8#include <QtCore/qdatetime.h>
9#include <QtCore/qtimezone.h>
10
11#include <private/qlocale_p.h>
12
13#include <private/qv4dateobject_p.h>
14#include <private/qv4numberobject_p.h>
15#include <private/qv4stringobject_p.h>
16#include <private/qqmlvaluetypewrapper_p.h>
17
19
20using namespace QV4;
21
22#define THROW_ERROR(string)
23 do {
24 return scope.engine->throwError(QString::fromUtf8(string));
25 } while (false)
26
27
28#define GET_LOCALE_DATA_RESOURCE(OBJECT)
29 QLocale *r = [&]() {
30 QV4::Scoped<QQmlValueTypeWrapper> r(scope, OBJECT.as<QQmlValueTypeWrapper>());
31 return r ? r->cast<QLocale>() : nullptr;
32 }();
33 if (!r)
34 THROW_ERROR("Not a valid Locale object")
35
36static bool isLocaleObject(const QV4::Value &val)
37{
38 if (const QV4::QQmlValueTypeWrapper *wrapper = val.as<QQmlValueTypeWrapper>())
39 return wrapper->type() == QMetaType::fromType<QLocale>();
40 return false;
41}
42
43//--------------
44// Date extension
45
46void QQmlDateExtension::registerExtension(QV4::ExecutionEngine *engine)
47{
48 engine->datePrototype()->defineDefaultProperty(engine->id_toLocaleString(), method_toLocaleString);
49 engine->datePrototype()->defineDefaultProperty(QStringLiteral("toLocaleTimeString"), method_toLocaleTimeString);
50 engine->datePrototype()->defineDefaultProperty(QStringLiteral("toLocaleDateString"), method_toLocaleDateString);
51 engine->dateCtor()->defineDefaultProperty(QStringLiteral("fromLocaleString"), method_fromLocaleString);
52 engine->dateCtor()->defineDefaultProperty(QStringLiteral("fromLocaleTimeString"), method_fromLocaleTimeString);
53 engine->dateCtor()->defineDefaultProperty(QStringLiteral("fromLocaleDateString"), method_fromLocaleDateString);
54 engine->dateCtor()->defineDefaultProperty(QStringLiteral("timeZoneUpdated"), method_timeZoneUpdated);
55}
56
57ReturnedValue QQmlDateExtension::method_toLocaleString(const QV4::FunctionObject *b, const QV4::Value *thisObject, const QV4::Value *argv, int argc)
58{
59 Scope scope(b);
60 if (argc > 2)
61 return QV4::DatePrototype::method_toLocaleString(b, thisObject, argv, argc);
62
63 const QV4::DateObject *date = thisObject->as<DateObject>();
64 if (!date)
65 return QV4::DatePrototype::method_toLocaleString(b, thisObject, argv, argc);
66
67 QDateTime dt = date->toQDateTime();
68
69 if (argc == 0) {
70 // Use QLocale for standard toLocaleString() function
71 QLocale locale;
72 RETURN_RESULT(scope.engine->newString(locale.toString(dt)));
73 }
74
75 if (!isLocaleObject(argv[0]))
76 return QV4::DatePrototype::method_toLocaleString(b, thisObject, argv, argc); // Use the default Date toLocaleString()
77
79
80 QLocale::FormatType enumFormat = QLocale::LongFormat;
81 QString formattedDt;
82 if (argc == 2) {
83 if (String *s = argv[1].stringValue()) {
84 QString format = s->toQString();
85 formattedDt = r->toString(dt, format);
86 } else if (argv[1].isNumber()) {
87 quint32 intFormat = argv[1].toNumber();
88 QLocale::FormatType format = QLocale::FormatType(intFormat);
89 formattedDt = r->toString(dt, format);
90 } else {
91 THROW_ERROR("Locale: Date.toLocaleString(): Invalid datetime format");
92 }
93 } else {
94 formattedDt = r->toString(dt, enumFormat);
95 }
96
97 RETURN_RESULT(scope.engine->newString(formattedDt));
98}
99
100ReturnedValue QQmlDateExtension::method_toLocaleTimeString(const QV4::FunctionObject *b, const QV4::Value *thisObject, const QV4::Value *argv, int argc)
101{
102 Scope scope(b);
103 if (argc > 2)
104 return QV4::DatePrototype::method_toLocaleTimeString(b, thisObject, argv, argc);
105
106 const QV4::DateObject *date = thisObject->as<DateObject>();
107 if (!date)
108 return QV4::DatePrototype::method_toLocaleTimeString(b, thisObject, argv, argc);
109
110 QDateTime dt = date->toQDateTime();
111 QTime time = dt.time();
112
113 if (argc == 0) {
114 // Use QLocale for standard toLocaleString() function
115 QLocale locale;
116 RETURN_RESULT(scope.engine->newString(locale.toString(time)));
117 }
118
119 if (!isLocaleObject(argv[0]))
120 return QV4::DatePrototype::method_toLocaleTimeString(b, thisObject, argv, argc); // Use the default Date toLocaleTimeString()
121
123
124 QLocale::FormatType enumFormat = QLocale::LongFormat;
125 QString formattedTime;
126 if (argc == 2) {
127 if (String *s = argv[1].stringValue()) {
128 QString format = s->toQString();
129 formattedTime = r->toString(time, format);
130 } else if (argv[1].isNumber()) {
131 quint32 intFormat = argv[1].toNumber();
132 QLocale::FormatType format = QLocale::FormatType(intFormat);
133 formattedTime = r->toString(time, format);
134 } else {
135 THROW_ERROR("Locale: Date.toLocaleTimeString(): Invalid time format");
136 }
137 } else {
138 formattedTime = r->toString(time, enumFormat);
139 }
140
141 RETURN_RESULT(scope.engine->newString(formattedTime));
142}
143
144ReturnedValue QQmlDateExtension::method_toLocaleDateString(const QV4::FunctionObject *b, const QV4::Value *thisObject, const QV4::Value *argv, int argc)
145{
146 Scope scope(b);
147 if (argc > 2)
148 return QV4::DatePrototype::method_toLocaleDateString(b, thisObject, argv, argc);
149
150 const QV4::DateObject *dateObj = thisObject->as<DateObject>();
151 if (!dateObj)
152 return QV4::DatePrototype::method_toLocaleDateString(b, thisObject, argv, argc);
153
154 QDateTime dt = dateObj->toQDateTime();
155 QDate date = dt.date();
156
157 if (argc == 0) {
158 // Use QLocale for standard toLocaleString() function
159 QLocale locale;
160 RETURN_RESULT(scope.engine->newString(locale.toString(date)));
161 }
162
163 if (!isLocaleObject(argv[0]))
164 return QV4::DatePrototype::method_toLocaleDateString(b, thisObject, argv, argc); // Use the default Date toLocaleDateString()
165
167
168 QLocale::FormatType enumFormat = QLocale::LongFormat;
169 QString formattedDate;
170 if (argc == 2) {
171 if (String *s = argv[1].stringValue()) {
172 QString format = s->toQString();
173 formattedDate = r->toString(date, format);
174 } else if (argv[1].isNumber()) {
175 quint32 intFormat = argv[1].toNumber();
176 QLocale::FormatType format = QLocale::FormatType(intFormat);
177 formattedDate = r->toString(date, format);
178 } else {
179 THROW_ERROR("Locale: Date.loLocaleDateString(): Invalid date format");
180 }
181 } else {
182 formattedDate = r->toString(date, enumFormat);
183 }
184
185 RETURN_RESULT(scope.engine->newString(formattedDate));
186}
187
188ReturnedValue QQmlDateExtension::method_fromLocaleString(const QV4::FunctionObject *b, const QV4::Value *, const QV4::Value *argv, int argc)
189{
190 QV4::Scope scope(b);
191 QV4::ExecutionEngine * const engine = scope.engine;
192 if (argc == 1) {
193 if (String *s = argv[0].stringValue()) {
194 QLocale locale;
195 QString dateString = s->toQString();
196 QDateTime dt = locale.toDateTime(dateString);
197 RETURN_RESULT(engine->newDateObject(dt));
198 }
199 }
200
201 if (argc < 1 || argc > 3 || !isLocaleObject(argv[0]))
202 THROW_ERROR("Locale: Date.fromLocaleString(): Invalid arguments");
203
205
206 QLocale::FormatType enumFormat = QLocale::LongFormat;
207 QDateTime dt;
208 QString dateString = argv[1].toQStringNoThrow();
209 if (argc == 3) {
210 if (String *s = argv[2].stringValue()) {
211 QString format = s->toQString();
212 dt = r->toDateTime(dateString, format);
213 } else if (argv[2].isNumber()) {
214 quint32 intFormat = argv[2].toNumber();
215 QLocale::FormatType format = QLocale::FormatType(intFormat);
216 dt = r->toDateTime(dateString, format);
217 } else {
218 THROW_ERROR("Locale: Date.fromLocaleString(): Invalid datetime format");
219 }
220 } else {
221 dt = r->toDateTime(dateString, enumFormat);
222 }
223
224 RETURN_RESULT(engine->newDateObject(dt));
225}
226
227ReturnedValue QQmlDateExtension::method_fromLocaleTimeString(const QV4::FunctionObject *b, const QV4::Value *, const QV4::Value *argv, int argc)
228{
229 QV4::Scope scope(b);
230 QV4::ExecutionEngine * const engine = scope.engine;
231
232 if (argc == 1) {
233 if (String *s = argv[0].stringValue()) {
234 QLocale locale;
235 QString timeString = s->toQString();
236 QTime time = locale.toTime(timeString);
237 QDateTime dt = QDateTime::currentDateTime();
238 dt.setTime(time);
239 RETURN_RESULT(engine->newDateObject(dt));
240 }
241 }
242
243 if (argc < 1 || argc > 3 || !isLocaleObject(argv[0]))
244 THROW_ERROR("Locale: Date.fromLocaleTimeString(): Invalid arguments");
245
247
248 QLocale::FormatType enumFormat = QLocale::LongFormat;
249 QTime tm;
250 QString dateString = argv[1].toQStringNoThrow();
251 if (argc == 3) {
252 if (String *s = argv[2].stringValue()) {
253 QString format = s->toQString();
254 tm = r->toTime(dateString, format);
255 } else if (argv[2].isNumber()) {
256 quint32 intFormat = argv[2].toNumber();
257 QLocale::FormatType format = QLocale::FormatType(intFormat);
258 tm = r->toTime(dateString, format);
259 } else {
260 THROW_ERROR("Locale: Date.fromLocaleTimeString(): Invalid datetime format");
261 }
262 } else {
263 tm = r->toTime(dateString, enumFormat);
264 }
265
266 QDateTime dt;
267 if (tm.isValid()) {
268 dt = QDateTime::currentDateTime();
269 dt.setTime(tm);
270 }
271
272 RETURN_RESULT(engine->newDateObject(dt));
273}
274
275ReturnedValue QQmlDateExtension::method_fromLocaleDateString(const QV4::FunctionObject *b, const QV4::Value *, const QV4::Value *argv, int argc)
276{
277 QV4::Scope scope(b);
278 QV4::ExecutionEngine * const engine = scope.engine;
279
280 if (argc == 1) {
281 if (String *s = argv[0].stringValue()) {
282 QLocale locale;
283 QString dateString = s->toQString();
284 QDate date = locale.toDate(dateString);
285 RETURN_RESULT(engine->newDateObject(date.startOfDay(QTimeZone::UTC)));
286 }
287 }
288
289 if (argc < 1 || argc > 3 || !isLocaleObject(argv[0]))
290 THROW_ERROR("Locale: Date.fromLocaleDateString(): Invalid arguments");
291
293
294 QLocale::FormatType enumFormat = QLocale::LongFormat;
295 QDate dt;
296 QString dateString = argv[1].toQStringNoThrow();
297 if (argc == 3) {
298 if (String *s = argv[2].stringValue()) {
299 QString format = s->toQString();
300 dt = r->toDate(dateString, format);
301 } else if (argv[2].isNumber()) {
302 quint32 intFormat = argv[2].toNumber();
303 QLocale::FormatType format = QLocale::FormatType(intFormat);
304 dt = r->toDate(dateString, format);
305 } else {
306 THROW_ERROR("Locale: Date.fromLocaleDateString(): Invalid datetime format");
307 }
308 } else {
309 dt = r->toDate(dateString, enumFormat);
310 }
311
312 RETURN_RESULT(engine->newDateObject(dt.startOfDay(QTimeZone::UTC)));
313}
314
315ReturnedValue QQmlDateExtension::method_timeZoneUpdated(const QV4::FunctionObject *b, const QV4::Value *, const QV4::Value *, int argc)
316{
317 QV4::Scope scope(b);
318 if (argc != 0)
319 THROW_ERROR("Locale: Date.timeZoneUpdated(): Invalid arguments");
320
321 QV4::DatePrototype::timezoneUpdated(scope.engine);
322
323 RETURN_UNDEFINED();
324}
325
326//-----------------
327// Number extension
328
329void QQmlNumberExtension::registerExtension(QV4::ExecutionEngine *engine)
330{
331 engine->numberPrototype()->defineDefaultProperty(engine->id_toLocaleString(), method_toLocaleString);
332 engine->numberPrototype()->defineDefaultProperty(QStringLiteral("toLocaleCurrencyString"), method_toLocaleCurrencyString);
333 engine->numberCtor()->defineDefaultProperty(QStringLiteral("fromLocaleString"), method_fromLocaleString);
334}
335
336QV4::ReturnedValue QQmlNumberExtension::method_toLocaleString(const QV4::FunctionObject *b, const QV4::Value *thisObject, const QV4::Value *argv, int argc)
337{
338 QV4::Scope scope(b);
339 if (argc > 3)
340 THROW_ERROR("Locale: Number.toLocaleString(): Invalid arguments");
341
342 double number = thisObject->toNumber();
343
344 if (argc == 0) {
345 // Use QLocale for standard toLocaleString() function
346 QLocale locale;
347 RETURN_RESULT(scope.engine->newString(locale.toString(number)));
348 }
349
350 if (!isLocaleObject(argv[0]))
351 return QV4::NumberPrototype::method_toLocaleString(b, thisObject, argv, argc); // Use the default Number toLocaleString()
352
354
355 quint16 format = 'f';
356 if (argc > 1) {
357 if (!argv[1].isString())
358 THROW_ERROR("Locale: Number.toLocaleString(): Invalid arguments");
359 QString fs = argv[1].toQString();
360 if (fs.size())
361 format = fs.at(0).unicode();
362 }
363 int prec = 2;
364 if (argc > 2) {
365 if (!argv[2].isNumber())
366 THROW_ERROR("Locale: Number.toLocaleString(): Invalid arguments");
367 prec = argv[2].toInt32();
368 }
369
370 RETURN_RESULT(scope.engine->newString(r->toString(number, (char)format, prec)));
371}
372
373ReturnedValue QQmlNumberExtension::method_toLocaleCurrencyString(const QV4::FunctionObject *b, const QV4::Value *thisObject, const QV4::Value *argv, int argc)
374{
375 QV4::Scope scope(b);
376 if (argc > 2)
377 THROW_ERROR("Locale: Number.toLocaleCurrencyString(): Invalid arguments");
378
379 double number = thisObject->toNumber();
380
381 if (argc == 0) {
382 // Use QLocale for standard toLocaleString() function
383 QLocale locale;
384 RETURN_RESULT(scope.engine->newString(locale.toString(number)));
385 }
386
387 if (!isLocaleObject(argv[0]))
388 THROW_ERROR("Locale: Number.toLocaleCurrencyString(): Invalid arguments");
389
391
392 QString symbol;
393 if (argc > 1) {
394 if (!argv[1].isString())
395 THROW_ERROR("Locale: Number.toLocaleString(): Invalid arguments");
396 symbol = argv[1].toQStringNoThrow();
397 }
398
399 RETURN_RESULT(scope.engine->newString(r->toCurrencyString(number, symbol)));
400}
401
402ReturnedValue QQmlNumberExtension::method_fromLocaleString(const QV4::FunctionObject *b, const QV4::Value *, const QV4::Value *argv, int argc)
403{
404 QV4::Scope scope(b);
405 if (argc < 1 || argc > 2)
406 THROW_ERROR("Locale: Number.fromLocaleString(): Invalid arguments");
407
408 int numberIdx = 0;
409 QLocale locale;
410
411 if (argc == 2) {
412 if (!isLocaleObject(argv[0]))
413 THROW_ERROR("Locale: Number.fromLocaleString(): Invalid arguments");
414
416 locale = *r;
417
418 numberIdx = 1;
419 }
420
421 QString ns = argv[numberIdx].toQString();
422 if (!ns.size())
423 RETURN_RESULT(QV4::Encode(Q_QNAN));
424
425 bool ok = false;
426 double val = locale.toDouble(ns, &ok);
427
428 if (!ok)
429 THROW_ERROR("Locale: Number.fromLocaleString(): Invalid format");
430
431 RETURN_RESULT(QV4::Encode(val));
432}
433
434//--------------
435// Locale object
436
437void QQmlLocaleValueType::formattedDataSize(QQmlV4FunctionPtr args) const
438{
439 QV4::Scope scope(args->v4engine());
440 const auto doThrow = [&](const QString &message) {
441 args->setReturnValue(scope.engine->throwError(message));
442 };
443
444 const int argc = args->length();
445
446 if (argc < 1 || argc > 3) {
447 doThrow(QString::fromLatin1(
448 "Locale: formattedDataSize(): Expected 1-3 arguments, but received %1")
449 .arg(argc));
450 return;
451 }
452
453 QV4::ScopedValue arg0(scope, (*args)[0]);
454 bool mismatched0 = false;
455 if (!arg0->isNumber()) {
456 // ### Qt7: Throw an exception here, so that we don't have to handle mismatched0 below.
457 qWarning() << "Locale: formattedDataSize(): Invalid argument ('bytes' should be a number)";
458 if (argc == 1) {
459 args->setReturnValue(
460 scope.engine->newString(locale.formattedDataSize(qint64(arg0->toInteger())))
461 ->asReturnedValue());
462 return;
463 }
464
465 mismatched0 = true;
466 }
467
468 // Anything can be coerced to a number, for better or worse ...
469 Q_ASSERT(argc >= 2);
470
471 QV4::ScopedValue arg1(scope, (*args)[1]);
472 if (!arg1->isInteger()) {
473 doThrow(QLatin1String(
474 "Locale: formattedDataSize(): Invalid argument ('precision' must be an int)"));
475 return;
476 }
477
478 if (mismatched0) {
479 if (argc == 2) {
480 const QString result = locale.formattedDataSize(
481 qint64(arg0->toInteger()), arg1->integerValue());
482 args->setReturnValue(scope.engine->newString(result)->asReturnedValue());
483 return;
484 }
485
486 QV4::ScopedValue arg2(scope, (*args)[2]);
487 if (arg2->isNumber()) {
488 const QString result = locale.formattedDataSize(
489 qint64(arg0->toInteger()), arg1->integerValue(),
490 QLocale::DataSizeFormats(arg2->integerValue()));
491 args->setReturnValue(scope.engine->newString(result)->asReturnedValue());
492 return;
493 }
494 }
495
496 Q_ASSERT(argc == 3);
497 Q_ASSERT(!QV4::ScopedValue(scope, (*args)[2])->isNumber());
498
499 doThrow(QLatin1String(
500 "Locale: formattedDataSize(): Invalid argument ('format' must be DataSizeFormat)"));
501}
502
503static QQmlLocale::DayOfWeek qtDayToQmlDay(Qt::DayOfWeek day)
504{
505 return day == Qt::Sunday ? QQmlLocale::DayOfWeek::Sunday : QQmlLocale::DayOfWeek(day);
506}
507
508QQmlLocale::DayOfWeek QQmlLocaleValueType::firstDayOfWeek() const
509{
510 return qtDayToQmlDay(locale.firstDayOfWeek());
511}
512
514{
515 const QList<Qt::DayOfWeek> days = locale.weekdays();
516 QList<QQmlLocale::DayOfWeek> result;
517 result.reserve(days.size());
518 for (Qt::DayOfWeek day : days)
519 result.append(qtDayToQmlDay(day));
520 return result;
521}
522
523void QQmlLocaleValueType::toString(QQmlV4FunctionPtr args) const
524{
525 Scope scope(args->v4engine());
526 const auto doThrow = [&](const QString &message) {
527 args->setReturnValue(scope.engine->throwError(message));
528 };
529
530 const int argc = args->length();
531
532 // toString()
533 Q_ASSERT(argc > 0);
534
535 if (argc > 3) {
536 doThrow(QString::fromLatin1("Locale: toString(): Expected 1-3 arguments, but received %1")
537 .arg(argc));
538 return;
539 }
540
541 QV4::ScopedValue arg0(scope, (*args)[0]);
542 if (arg0->isNumber()) {
543
544 // toString(int)
545 // toString(double)
546 Q_ASSERT(argc != 1);
547
548 QV4::ScopedValue arg1(scope, (*args)[1]);
549 if (!arg1->isString()) {
550 doThrow(QLatin1String("Locale: the second argument to the toString overload "
551 "whose first argument is a double should be a char"));
552 return;
553 }
554
555 // toString(double, const QString &)
556 // toString(double, const QString &, int)
557 Q_ASSERT(argc == 3);
558 Q_ASSERT(!QV4::ScopedValue(scope, (*args)[2])->isInteger());
559
560 doThrow(QLatin1String("Locale: the third argument to the toString overload "
561 "whose first argument is a double should be an int"));
562 return;
563 }
564
565 if (arg0->as<DateObject>()) {
566 if (argc > 2) {
567 doThrow(QString::fromLatin1(
568 "Locale: the toString() overload that takes a Date as its first "
569 "argument expects 1 or 2 arguments, but received %1").arg(argc));
570 return;
571 }
572
573 // toString(QDateTime)
574 Q_ASSERT(argc == 2);
575 QV4::ScopedValue arg1(scope, (*args)[1]);
576
577 // toString(QDateTime, QString)
578 Q_ASSERT(!arg1->isString());
579
580 // toString(QDateTime, QLocale::FormatType)
581 Q_ASSERT(!arg1->isNumber());
582
583 doThrow(QLatin1String("Locale: the second argument to the toString overloads whose "
584 "first argument is a Date should be a string or FormatType"));
585 return;
586 }
587
588 doThrow(QLatin1String("Locale: toString() expects either an int, double, "
589 "or Date as its first argument"));
590}
591
592/*!
593 \qmltype Locale
594 //! \nativetype QQmlLocale
595 \inqmlmodule QtQml
596 \brief Provides locale specific properties and formatted data.
597
598 The Locale object may only be created via the \l{QtQml::Qt::locale()}{Qt.locale()} function.
599 It cannot be created directly.
600
601 The \l{QtQml::Qt::locale()}{Qt.locale()} function returns a JS Locale object representing the
602 locale with the specified name, which has the format
603 "language[_territory][.codeset][@modifier]" or "C".
604
605 Locale supports the concept of a default locale, which is
606 determined from the system's locale settings at application
607 startup. If no parameter is passed to Qt.locale() the default
608 locale object is returned.
609
610 The Locale object provides a number of functions and properties
611 providing data for the specified locale.
612
613 The Locale object may also be passed to the \l{The Date JavaScript Object}{Date} and \l{The Number JavaScript Object}{Number} toLocaleString()
614 and fromLocaleString() methods in order to convert to/from strings using
615 the specified locale.
616
617 This example shows the current date formatted for the German locale:
618
619 \code
620 import QtQuick 2.0
621
622 Text {
623 text: "The date is: " + Date().toLocaleString(Qt.locale("de_DE"))
624 }
625 \endcode
626
627 The following example displays the specified number
628 in the correct format for the default locale:
629
630 \code
631 import QtQuick 2.0
632
633 Text {
634 text: "The value is: " + Number(23443.34).toLocaleString(Qt.locale())
635 }
636 \endcode
637
638 Qt Quick Locale's data is based on Common Locale Data Repository v1.8.1.
639
640
641 \target FormatType
642 \section2 Locale String Format Types
643
644 The monthName(), standaloneMonthName(), dayName() and standaloneDayName()
645 can use the following enumeration values to specify the formatting of
646 the string representation for a Date object.
647
648 \value Locale.LongFormat The long version of day and month names; for
649 example, returning "January" as a month name.
650 \value Locale.ShortFormat The short version of day and month names; for
651 example, returning "Jan" as a month name.
652 \value Locale.NarrowFormat A special version of day and month names for
653 use when space is limited; for example, returning "J" as a month
654 name. Note that the narrow format might contain the same text for
655 different months and days or it can even be an empty string if the
656 locale doesn't support narrow names, so you should avoid using it
657 for date formatting. Also, for the system locale this format is
658 the same as ShortFormat.
659
660
661 Additionally the double-to-string and string-to-double conversion functions are
662 covered by the following licenses:
663
664 \legalese
665 Copyright (c) 1991 by AT&T.
666
667 Permission to use, copy, modify, and distribute this software for any
668 purpose without fee is hereby granted, provided that this entire notice
669 is included in all copies of any software which is or includes a copy
670 or modification of this software and in all copies of the supporting
671 documentation for such software.
672
673 THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR IMPLIED
674 WARRANTY. IN PARTICULAR, NEITHER THE AUTHOR NOR AT&T MAKES ANY
675 REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE MERCHANTABILITY
676 OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR PURPOSE.
677
678 This product includes software developed by the University of
679 California, Berkeley and its contributors.
680
681 \sa {The Date JavaScript Object}, {The Number JavaScript Object}
682*/
683
684QV4::ReturnedValue QQmlLocale::locale(ExecutionEngine *engine, const QString &localeName)
685{
686 if (localeName.isEmpty()) {
687 return QQmlValueTypeWrapper::create(
688 engine, nullptr, &QQmlLocaleValueType::staticMetaObject,
689 QMetaType::fromType<QLocale>());
690 }
691
692 QLocale qlocale(localeName);
693 return QQmlValueTypeWrapper::create(
694 engine, &qlocale, &QQmlLocaleValueType::staticMetaObject,
695 QMetaType::fromType<QLocale>());
696}
697
698void QQmlLocale::registerStringLocaleCompare(QV4::ExecutionEngine *engine)
699{
700 engine->stringPrototype()->defineDefaultProperty(QStringLiteral("localeCompare"), method_localeCompare);
701}
702
703ReturnedValue QQmlLocale::method_localeCompare(const QV4::FunctionObject *b, const QV4::Value *thisObject, const QV4::Value *argv, int argc)
704{
705 if (argc != 1 || (!argv[0].isString() && !argv[0].as<StringObject>()))
706 return QV4::StringPrototype::method_localeCompare(b, thisObject, argv, argc);
707
708 if (!thisObject->isString() && !thisObject->as<StringObject>())
709 return QV4::StringPrototype::method_localeCompare(b, thisObject, argv, argc);
710
711 QString thisString = thisObject->toQStringNoThrow();
712 QString thatString = argv[0].toQStringNoThrow();
713
714 return QV4::Encode(QString::localeAwareCompare(thisString, thatString));
715}
716
717/*!
718 \qmlproperty string QtQml::Locale::name
719
720 Holds the language and territory of this locale as a
721 string of the form "language_territory", where
722 language is a lowercase, two-letter ISO 639 language code,
723 and territory is an uppercase, two- or three-letter ISO 3166 territory code.
724*/
725
726/*!
727 \qmlproperty string QtQml::Locale::decimalPoint
728
729 Holds the decimal point character of this locale.
730*/
731
732/*!
733 \qmlproperty string QtQml::Locale::groupSeparator
734
735 Holds the group separator character of this locale.
736*/
737
738/*!
739 \qmlproperty enumeration QtQml::Locale::numberOptions
740
741 Holds a set of options for number-to-string and
742 string-to-number conversions.
743
744 \sa {string Number::toLocaleString(locale, format, precision)}
745 \sa {string Number::fromLocaleString(locale, number)}
746*/
747
748/*!
749 \qmlproperty string QtQml::Locale::percent
750
751 Holds the percent character of this locale.
752*/
753
754
755/*!
756 \qmlproperty string QtQml::Locale::zeroDigit
757
758 Holds Returns the zero digit character of this locale.
759*/
760
761/*!
762 \qmlproperty string QtQml::Locale::negativeSign
763
764 Holds the negative sign character of this locale.
765*/
766
767/*!
768 \qmlproperty string QtQml::Locale::positiveSign
769
770 Holds the positive sign character of this locale.
771*/
772
773/*!
774 \qmlproperty string QtQml::Locale::exponential
775
776 Holds the exponential character of this locale.
777*/
778
779/*!
780 \qmlmethod string QtQml::Locale::dateTimeFormat(type)
781
782 Returns the date time format used for the current locale.
783 \a type specifies the FormatType to return.
784
785 \sa {The Date JavaScript Object}
786*/
787
788/*!
789 \qmlmethod string QtQml::Locale::dateFormat(type)
790
791 Returns the date format used for the current locale.
792 \a type specifies the FormatType to return.
793
794 \sa {The Date JavaScript Object}
795*/
796
797/*!
798 \qmlmethod string QtQml::Locale::timeFormat(type)
799
800 Returns the time format used for the current locale.
801 \a type specifies the FormatType to return.
802
803 \sa {The Date JavaScript Object}
804*/
805
806/*!
807 \qmlmethod string QtQml::Locale::formattedDataSize(int bytes, int precision, DataSizeFormat format)
808 \since 6.2
809
810 Converts a size in \a bytes to a human-readable localized string, comprising a
811 number and a quantified unit.
812
813 The \a precision and \a format arguments are optional.
814
815 For more information, see \l QLocale::formattedDataSize().
816
817 \sa QLocale::DataSizeFormats
818*/
819
820/*!
821 \qmlmethod string QtQml::Locale::monthName(month, type)
822
823 Returns the localized name of \a month (0-11), in the optional
824 \l FormatType specified by \a type.
825
826 \note the QLocale C++ API expects a range of (1-12), however Locale.monthName()
827 expects 0-11 as per the JS Date object.
828
829 \sa dayName(), standaloneMonthName()
830*/
831
832/*!
833 \qmlmethod string QtQml::Locale::standaloneMonthName(month, type)
834
835 Returns the localized name of \a month (0-11) that is used as a
836 standalone text, in the optional \l FormatType specified by \a type.
837
838 If the locale information doesn't specify the standalone month
839 name then return value is the same as in monthName().
840
841 \note the QLocale C++ API expects a range of (1-12), however Locale.standaloneMonthName()
842 expects 0-11 as per the JS Date object.
843
844 \sa monthName(), standaloneDayName()
845*/
846
847/*!
848 \qmlmethod string QtQml::Locale::dayName(day, type)
849
850 Returns the localized name of the \a day (where 0 represents
851 Sunday, 1 represents Monday and so on), in the optional
852 \l FormatType specified by \a type.
853
854 \sa monthName(), standaloneDayName()
855*/
856
857/*!
858 \qmlmethod string QtQml::Locale::standaloneDayName(day, type)
859
860 Returns the localized name of the \a day (where 0 represents
861 Sunday, 1 represents Monday and so on) that is used as a
862 standalone text, in the \l FormatType specified by \a type.
863
864 If the locale information does not specify the standalone day
865 name then return value is the same as in dayName().
866
867 \sa dayName(), standaloneMonthName()
868*/
869
870/*!
871 \qmlproperty enumeration QtQml::Locale::firstDayOfWeek
872
873 Holds the first day of the week according to the current locale.
874
875 \value Locale.Sunday 0
876 \value Locale.Monday 1
877 \value Locale.Tuesday 2
878 \value Locale.Wednesday 3
879 \value Locale.Thursday 4
880 \value Locale.Friday 5
881 \value Locale.Saturday 6
882
883 \note that these values match the JS Date API which is different
884 from the Qt C++ API where Qt::Sunday = 7.
885*/
886
887/*!
888 \qmlproperty Array<int> QtQml::Locale::weekDays
889
890 Holds an array of days that are considered week days according to the current locale,
891 where Sunday is 0 and Saturday is 6.
892
893 \sa firstDayOfWeek
894*/
895
896/*!
897 \qmlmethod string QtQml::Locale::toString(int i)
898 \since 6.5
899
900 Returns a localized string representation of \a i.
901
902 \sa QLocale::toString(int)
903*/
904
905/*!
906 \qmlmethod string QtQml::Locale::toString(double f, char format = 'g', int precision = 6)
907 \overload
908 \since 6.5
909
910 Returns a string representing the floating-point number \a f.
911
912 The form of the representation is controlled by the optional \a format and
913 \a precision parameters.
914
915 See \l {QLocale::toString(double, char, int)} for more information.
916*/
917
918/*!
919 \qmlmethod string QtQml::Locale::toString(Date date, string format)
920 \overload
921 \since 6.5
922
923 Returns a localized string representation of the given \a date in the
924 specified \a format. If \c format is an empty string, an empty string is
925 returned.
926
927 \sa QLocale::toString(QDate, QStringView)
928*/
929
930/*!
931 \qmlmethod string QtQml::Locale::toString(Date date, FormatType format = LongFormat)
932 \overload
933 \since 6.5
934
935 Returns a localized string representation of the given \a date in the
936 specified \a format. If \c format is omitted, \c Locale.LongFormat is used.
937
938 \sa QLocale::toString(QDate, QLocale::FormatType)
939*/
940
941/*!
942 \qmlmethod string QtQml::Locale::createSeparatedList(list<string> list)
943 \since 6.10
944
945 Returns a string that represents a join of a given \a list of strings with a
946 separator defined by the locale.
947
948 \sa QLocale::createSeparatedList()
949*/
950
951/*!
952 \qmlproperty Array<string> QtQml::Locale::uiLanguages
953
954 Returns an ordered list of locale names for translation purposes in
955 preference order.
956
957 The return value represents locale names that the user expects to see the
958 UI translation in.
959
960 The first item in the list is the most preferred one.
961*/
962
963/*!
964 \qmlproperty enumeration QtQml::Locale::textDirection
965
966 Holds the text direction of the language:
967
968 \value Qt.LeftToRight Text normally begins at the left side.
969 \value Qt.RightToLeft Text normally begins at the right side.
970*/
971
972/*!
973 \qmlproperty string QtQml::Locale::amText
974
975 The localized name of the "AM" suffix for times specified using the conventions of the 12-hour clock.
976*/
977
978/*!
979 \qmlproperty string QtQml::Locale::pmText
980
981 The localized name of the "PM" suffix for times specified using the conventions of the 12-hour clock.
982*/
983
984/*!
985 \qmlmethod string QtQml::Locale::currencySymbol(format)
986
987 Returns the currency symbol for the specified \a format:
988
989 \value Locale.CurrencyIsoCode a ISO-4217 code of the currency.
990 \value Locale.CurrencySymbol a currency symbol.
991 \value Locale.CurrencyDisplayName a user readable name of the currency.
992
993 \sa {string Number::toLocaleCurrencyString(locale, symbol)}
994*/
995
996/*!
997 \qmlproperty string QtQml::Locale::nativeLanguageName
998
999 Holds a native name of the language for the locale. For example
1000 "Schwiizertüütsch" for Swiss-German locale.
1001
1002 \sa nativeTerritoryName
1003*/
1004
1005/*!
1006 \qmlproperty string QtQml::Locale::nativeCountryName
1007 \deprecated [6.4] Use nativeTerritoryName instead.
1008
1009 Holds a native name of the country for the locale. For example
1010 "España" for Spanish/Spain locale.
1011
1012 \sa nativeLanguageName
1013*/
1014
1015/*!
1016 \qmlproperty string QtQml::Locale::nativeTerritoryName
1017
1018 Holds a native name of the territory for the locale. For example
1019 "España" for Spanish/Spain locale.
1020
1021 \sa nativeLanguageName
1022*/
1023
1024/*!
1025 \qmlproperty enumeration QtQml::Locale::measurementSystem
1026
1027 This property defines which units are used for measurement.
1028
1029 \value Locale.MetricSystem This value indicates metric units, such as meters,
1030 centimeters and millimeters.
1031 \value Locale.ImperialUSSystem This value indicates imperial units, such as
1032 inches and miles as they are used in the United States.
1033 \value Locale.ImperialUKSystem This value indicates imperial units, such as
1034 inches and miles as they are used in the United Kingdom.
1035 \value Locale.ImperialSystem Provided for compatibility. The same as Locale.ImperialUSSystem.
1036*/
1037
1038QT_END_NAMESPACE
1039
1040#include "moc_qqmllocale_p.cpp"
QList< QQmlLocale::DayOfWeek > weekDays() const
Combined button and popup list for selecting options.
#define GET_LOCALE_DATA_RESOURCE(OBJECT)
static bool isLocaleObject(const QV4::Value &val)
#define THROW_ERROR(string)
static QQmlLocale::DayOfWeek qtDayToQmlDay(Qt::DayOfWeek day)