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