aboutsummaryrefslogtreecommitdiffstats
path: root/src/qml/qml/qqmllocale.cpp
blob: 8cea66c99ec34dd3e6800873c1e56cac0a53ebec (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtQml module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qqmllocale_p.h"
#include "qqmlengine_p.h"
#include <private/qqmlcontext_p.h>
#include <QtCore/qnumeric.h>
#include <QtCore/qdatetime.h>

#include <private/qlocale_p.h>
#include <private/qlocale_data_p.h>

#include <private/qv4dateobject_p.h>
#include <private/qv4numberobject_p.h>
#include <private/qv4stringobject_p.h>

QT_BEGIN_NAMESPACE

DEFINE_OBJECT_VTABLE(QQmlLocaleData);

#define GET_LOCALE_DATA_RESOURCE(OBJECT) \
    QV4::Scoped<QQmlLocaleData> r(scope, OBJECT.as<QQmlLocaleData>()); \
    if (!r) \
        V4THROW_ERROR("Not a valid Locale object")

static bool isLocaleObject(const QV4::ValueRef val)
{
    return val->as<QQmlLocaleData>();
}

//--------------
// Date extension

void QQmlDateExtension::registerExtension(QV4::ExecutionEngine *engine)
{
    engine->dateClass->prototype->defineDefaultProperty(QStringLiteral("toLocaleString"), method_toLocaleString);
    engine->dateClass->prototype->defineDefaultProperty(QStringLiteral("toLocaleTimeString"), method_toLocaleTimeString);
    engine->dateClass->prototype->defineDefaultProperty(QStringLiteral("toLocaleDateString"), method_toLocaleDateString);
    engine->dateCtor.objectValue()->defineDefaultProperty(QStringLiteral("fromLocaleString"), method_fromLocaleString);
    engine->dateCtor.objectValue()->defineDefaultProperty(QStringLiteral("fromLocaleTimeString"), method_fromLocaleTimeString);
    engine->dateCtor.objectValue()->defineDefaultProperty(QStringLiteral("fromLocaleDateString"), method_fromLocaleDateString);
    engine->dateCtor.objectValue()->defineDefaultProperty(QStringLiteral("timeZoneUpdated"), method_timeZoneUpdated);
}

QV4::ReturnedValue QQmlDateExtension::method_toLocaleString(QV4::CallContext *ctx)
{
    if (ctx->callData->argc > 2)
        return QV4::DatePrototype::method_toLocaleString(ctx);

    QV4::Scope scope(ctx);

    QV4::DateObject *date = ctx->callData->thisObject.asDateObject();
    if (!date)
        return QV4::DatePrototype::method_toLocaleString(ctx);

    QDateTime dt = date->toQDateTime();

    if (ctx->callData->argc == 0) {
        // Use QLocale for standard toLocaleString() function
        QLocale locale;
        return ctx->engine->newString(locale.toString(dt))->asReturnedValue();
    }

    if (!isLocaleObject(ctx->callData->args[0]))
        return QV4::DatePrototype::method_toLocaleString(ctx); // Use the default Date toLocaleString()

    GET_LOCALE_DATA_RESOURCE(ctx->callData->args[0]);

    QLocale::FormatType enumFormat = QLocale::LongFormat;
    QString formattedDt;
    if (ctx->callData->argc == 2) {
        if (ctx->callData->args[1].isString()) {
            QString format = ctx->callData->args[1].stringValue()->toQString();
            formattedDt = r->locale.toString(dt, format);
        } else if (ctx->callData->args[1].isNumber()) {
            quint32 intFormat = ctx->callData->args[1].toNumber();
            QLocale::FormatType format = QLocale::FormatType(intFormat);
            formattedDt = r->locale.toString(dt, format);
        } else {
            V4THROW_ERROR("Locale: Date.toLocaleString(): Invalid datetime format");
        }
    } else {
         formattedDt = r->locale.toString(dt, enumFormat);
    }

    return ctx->engine->newString(formattedDt)->asReturnedValue();
}

QV4::ReturnedValue QQmlDateExtension::method_toLocaleTimeString(QV4::CallContext *ctx)
{
    if (ctx->callData->argc > 2)
        return QV4::DatePrototype::method_toLocaleTimeString(ctx);

    QV4::Scope scope(ctx);

    QV4::DateObject *date = ctx->callData->thisObject.asDateObject();
    if (!date)
        return QV4::DatePrototype::method_toLocaleTimeString(ctx);

    QDateTime dt = date->toQDateTime();
    QTime time = dt.time();

    if (ctx->callData->argc == 0) {
        // Use QLocale for standard toLocaleString() function
        QLocale locale;
        return ctx->engine->newString(locale.toString(time))->asReturnedValue();
    }

    if (!isLocaleObject(ctx->callData->args[0]))
        return QV4::DatePrototype::method_toLocaleTimeString(ctx); // Use the default Date toLocaleTimeString()

    GET_LOCALE_DATA_RESOURCE(ctx->callData->args[0]);

    QLocale::FormatType enumFormat = QLocale::LongFormat;
    QString formattedTime;
    if (ctx->callData->argc == 2) {
        if (ctx->callData->args[1].isString()) {
            QString format = ctx->callData->args[1].stringValue()->toQString();
            formattedTime = r->locale.toString(time, format);
        } else if (ctx->callData->args[1].isNumber()) {
            quint32 intFormat = ctx->callData->args[1].toNumber();
            QLocale::FormatType format = QLocale::FormatType(intFormat);
            formattedTime = r->locale.toString(time, format);
        } else {
            V4THROW_ERROR("Locale: Date.toLocaleTimeString(): Invalid time format");
        }
    } else {
         formattedTime = r->locale.toString(time, enumFormat);
    }

    return ctx->engine->newString(formattedTime)->asReturnedValue();
}

QV4::ReturnedValue QQmlDateExtension::method_toLocaleDateString(QV4::CallContext *ctx)
{
    if (ctx->callData->argc > 2)
        return QV4::DatePrototype::method_toLocaleDateString(ctx);

    QV4::Scope scope(ctx);

    QV4::DateObject *dateObj = ctx->callData->thisObject.asDateObject();
    if (!dateObj)
        return QV4::DatePrototype::method_toLocaleDateString(ctx);

    QDateTime dt = dateObj->toQDateTime();
    QDate date = dt.date();

    if (ctx->callData->argc == 0) {
        // Use QLocale for standard toLocaleString() function
        QLocale locale;
        return ctx->engine->newString(locale.toString(date))->asReturnedValue();
    }

    if (!isLocaleObject(ctx->callData->args[0]))
        return QV4::DatePrototype::method_toLocaleDateString(ctx); // Use the default Date toLocaleDateString()

    GET_LOCALE_DATA_RESOURCE(ctx->callData->args[0]);

    QLocale::FormatType enumFormat = QLocale::LongFormat;
    QString formattedDate;
    if (ctx->callData->argc == 2) {
        if (ctx->callData->args[1].isString()) {
            QString format = ctx->callData->args[1].stringValue()->toQString();
            formattedDate = r->locale.toString(date, format);
        } else if (ctx->callData->args[1].isNumber()) {
            quint32 intFormat = ctx->callData->args[1].toNumber();
            QLocale::FormatType format = QLocale::FormatType(intFormat);
            formattedDate = r->locale.toString(date, format);
        } else {
            V4THROW_ERROR("Locale: Date.loLocaleDateString(): Invalid date format");
        }
    } else {
         formattedDate = r->locale.toString(date, enumFormat);
    }

    return ctx->engine->newString(formattedDate)->asReturnedValue();
}

QV4::ReturnedValue QQmlDateExtension::method_fromLocaleString(QV4::CallContext *ctx)
{
    QV4::ExecutionEngine * const engine = ctx->engine;
    if (ctx->callData->argc == 1 && ctx->callData->args[0].isString()) {
        QLocale locale;
        QString dateString = ctx->callData->args[0].stringValue()->toQString();
        QDateTime dt = locale.toDateTime(dateString);
        return QV4::Encode(engine->newDateObject(dt));
    }

    QV4::Scope scope(ctx);

    if (ctx->callData->argc < 1 || ctx->callData->argc > 3 || !isLocaleObject(ctx->callData->args[0]))
        V4THROW_ERROR("Locale: Date.fromLocaleString(): Invalid arguments");

    GET_LOCALE_DATA_RESOURCE(ctx->callData->args[0]);

    QLocale::FormatType enumFormat = QLocale::LongFormat;
    QDateTime dt;
    QString dateString = ctx->callData->args[1].toQStringNoThrow();
    if (ctx->callData->argc == 3) {
        if (ctx->callData->args[2].isString()) {
            QString format = ctx->callData->args[2].stringValue()->toQString();
            dt = r->locale.toDateTime(dateString, format);
        } else if (ctx->callData->args[2].isNumber()) {
            quint32 intFormat = ctx->callData->args[2].toNumber();
            QLocale::FormatType format = QLocale::FormatType(intFormat);
            dt = r->locale.toDateTime(dateString, format);
        } else {
            V4THROW_ERROR("Locale: Date.fromLocaleString(): Invalid datetime format");
        }
    } else {
        dt = r->locale.toDateTime(dateString, enumFormat);
    }

    return QV4::Encode(engine->newDateObject(dt));
}

QV4::ReturnedValue QQmlDateExtension::method_fromLocaleTimeString(QV4::CallContext *ctx)
{
    QV4::ExecutionEngine * const engine = ctx->engine;

    if (ctx->callData->argc == 1 && ctx->callData->args[0].isString()) {
        QLocale locale;
        QString timeString = ctx->callData->args[0].stringValue()->toQString();
        QTime time = locale.toTime(timeString);
        QDateTime dt = QDateTime::currentDateTime();
        dt.setTime(time);
        return QV4::Encode(engine->newDateObject(dt));
    }

    if (ctx->callData->argc < 1 || ctx->callData->argc > 3 || !isLocaleObject(ctx->callData->args[0]))
        V4THROW_ERROR("Locale: Date.fromLocaleTimeString(): Invalid arguments");

    QV4::Scope scope(ctx);

    GET_LOCALE_DATA_RESOURCE(ctx->callData->args[0]);

    QLocale::FormatType enumFormat = QLocale::LongFormat;
    QTime tm;
    QString dateString = ctx->callData->args[1].toQStringNoThrow();
    if (ctx->callData->argc == 3) {
        if (ctx->callData->args[2].isString()) {
            QString format = ctx->callData->args[2].stringValue()->toQString();
            tm = r->locale.toTime(dateString, format);
        } else if (ctx->callData->args[2].isNumber()) {
            quint32 intFormat = ctx->callData->args[2].toNumber();
            QLocale::FormatType format = QLocale::FormatType(intFormat);
            tm = r->locale.toTime(dateString, format);
        } else {
            V4THROW_ERROR("Locale: Date.fromLocaleTimeString(): Invalid datetime format");
        }
    } else {
        tm = r->locale.toTime(dateString, enumFormat);
    }

    QDateTime dt = QDateTime::currentDateTime();
    dt.setTime(tm);

    return QV4::Encode(engine->newDateObject(dt));
}

QV4::ReturnedValue QQmlDateExtension::method_fromLocaleDateString(QV4::CallContext *ctx)
{
    QV4::ExecutionEngine * const engine = ctx->engine;

    if (ctx->callData->argc == 1 && ctx->callData->args[0].isString()) {
        QLocale locale;
        QString dateString = ctx->callData->args[0].stringValue()->toQString();
        QDate date = locale.toDate(dateString);
        return QV4::Encode(engine->newDateObject(QDateTime(date)));
    }

    if (ctx->callData->argc < 1 || ctx->callData->argc > 3 || !isLocaleObject(ctx->callData->args[0]))
        V4THROW_ERROR("Locale: Date.fromLocaleDateString(): Invalid arguments");

    QV4::Scope scope(ctx);

    GET_LOCALE_DATA_RESOURCE(ctx->callData->args[0]);

    QLocale::FormatType enumFormat = QLocale::LongFormat;
    QDate dt;
    QString dateString = ctx->callData->args[1].toQStringNoThrow();
    if (ctx->callData->argc == 3) {
        if (ctx->callData->args[2].isString()) {
            QString format = ctx->callData->args[2].stringValue()->toQString();
            dt = r->locale.toDate(dateString, format);
        } else if (ctx->callData->args[2].isNumber()) {
            quint32 intFormat = ctx->callData->args[2].toNumber();
            QLocale::FormatType format = QLocale::FormatType(intFormat);
            dt = r->locale.toDate(dateString, format);
        } else {
            V4THROW_ERROR("Locale: Date.fromLocaleDateString(): Invalid datetime format");
        }
    } else {
        dt = r->locale.toDate(dateString, enumFormat);
    }

    return QV4::Encode(engine->newDateObject(QDateTime(dt)));
}

QV4::ReturnedValue QQmlDateExtension::method_timeZoneUpdated(QV4::CallContext *ctx)
{
    if (ctx->callData->argc != 0)
        V4THROW_ERROR("Locale: Date.timeZoneUpdated(): Invalid arguments");

    QV4::DatePrototype::timezoneUpdated();

    return QV4::Encode::undefined();
}

//-----------------
// Number extension

void QQmlNumberExtension::registerExtension(QV4::ExecutionEngine *engine)
{
    engine->numberClass->prototype->defineDefaultProperty(QStringLiteral("toLocaleString"), method_toLocaleString);
    engine->numberClass->prototype->defineDefaultProperty(QStringLiteral("toLocaleCurrencyString"), method_toLocaleCurrencyString);
    engine->numberCtor.objectValue()->defineDefaultProperty(QStringLiteral("fromLocaleString"), method_fromLocaleString);
}

QV4::ReturnedValue QQmlNumberExtension::method_toLocaleString(QV4::CallContext *ctx)
{
    if (ctx->callData->argc > 3)
        V4THROW_ERROR("Locale: Number.toLocaleString(): Invalid arguments");

    double number = ctx->callData->thisObject.toNumber();

    if (ctx->callData->argc == 0) {
        // Use QLocale for standard toLocaleString() function
        QLocale locale;
        return ctx->engine->newString(locale.toString(number))->asReturnedValue();
    }

    if (!isLocaleObject(ctx->callData->args[0]))
        return QV4::NumberPrototype::method_toLocaleString(ctx); // Use the default Number toLocaleString()

    QV4::Scope scope(ctx);

    GET_LOCALE_DATA_RESOURCE(ctx->callData->args[0]);

    quint16 format = 'f';
    if (ctx->callData->argc > 1) {
        if (!ctx->callData->args[1].isString())
            V4THROW_ERROR("Locale: Number.toLocaleString(): Invalid arguments");
        QV4::String *fs = ctx->callData->args[1].toString(ctx);
        if (fs->length())
            format = fs->toQString().at(0).unicode();
    }
    int prec = 2;
    if (ctx->callData->argc > 2) {
        if (!ctx->callData->args[2].isNumber())
            V4THROW_ERROR("Locale: Number.toLocaleString(): Invalid arguments");
         prec = ctx->callData->args[2].toInt32();
    }

    return ctx->engine->newString(r->locale.toString(number, (char)format, prec))->asReturnedValue();
}

QV4::ReturnedValue QQmlNumberExtension::method_toLocaleCurrencyString(QV4::CallContext *ctx)
{
    if (ctx->callData->argc > 2)
        V4THROW_ERROR("Locale: Number.toLocaleCurrencyString(): Invalid arguments");

    double number = ctx->callData->thisObject.toNumber();

    if (ctx->callData->argc == 0) {
        // Use QLocale for standard toLocaleString() function
        QLocale locale;
        return ctx->engine->newString(locale.toString(number))->asReturnedValue();
    }

    if (!isLocaleObject(ctx->callData->args[0]))
        V4THROW_ERROR("Locale: Number.toLocaleCurrencyString(): Invalid arguments");

    QV4::Scope scope(ctx);

    GET_LOCALE_DATA_RESOURCE(ctx->callData->args[0]);

    QString symbol;
    if (ctx->callData->argc > 1) {
        if (!ctx->callData->args[1].isString())
            V4THROW_ERROR("Locale: Number.toLocaleString(): Invalid arguments");
        symbol = ctx->callData->args[1].toQStringNoThrow();
    }

    return ctx->engine->newString(r->locale.toCurrencyString(number, symbol))->asReturnedValue();
}

QV4::ReturnedValue QQmlNumberExtension::method_fromLocaleString(QV4::CallContext *ctx)
{
    if (ctx->callData->argc < 1 || ctx->callData->argc > 2)
        V4THROW_ERROR("Locale: Number.fromLocaleString(): Invalid arguments");

    int numberIdx = 0;
    QLocale locale;

    QV4::Scope scope(ctx);

    if (ctx->callData->argc == 2) {
        if (!isLocaleObject(ctx->callData->args[0]))
            V4THROW_ERROR("Locale: Number.fromLocaleString(): Invalid arguments");

        GET_LOCALE_DATA_RESOURCE(ctx->callData->args[0]);
        locale = r->locale;

        numberIdx = 1;
    }

    QV4::String *ns = ctx->callData->args[numberIdx].toString(ctx);
    if (!ns->length())
        return QV4::Encode(Q_QNAN);

    bool ok = false;
    double val = locale.toDouble(ns->toQString(), &ok);

    if (!ok)
        V4THROW_ERROR("Locale: Number.fromLocaleString(): Invalid format")

    return QV4::Encode(val);
}

//--------------
// Locale object

QV4::ReturnedValue QQmlLocaleData::method_get_firstDayOfWeek(QV4::CallContext *ctx)
{
    QLocale *locale = getThisLocale(ctx);
    if (!locale)
        return QV4::Encode::undefined();
    int fdow = int(locale->firstDayOfWeek());
    if (fdow == 7)
        fdow = 0; // Qt::Sunday = 7, but Sunday is 0 in JS Date
    return QV4::Encode(fdow);
}

QV4::ReturnedValue QQmlLocaleData::method_get_measurementSystem(QV4::CallContext *ctx)
{
    QLocale *locale = getThisLocale(ctx);
    if (!locale)
        return QV4::Encode::undefined();
    return QV4::Encode(locale->measurementSystem());
}

QV4::ReturnedValue QQmlLocaleData::method_get_textDirection(QV4::CallContext *ctx)
{
    QLocale *locale = getThisLocale(ctx);
    if (!locale)
        return QV4::Encode::undefined();

    return QV4::Encode(locale->textDirection());
}

QV4::ReturnedValue QQmlLocaleData::method_get_weekDays(QV4::CallContext *ctx)
{
    QV4::Scope scope(ctx);
    QLocale *locale = getThisLocale(ctx);
    if (!locale)
        return QV4::Encode::undefined();

    QList<Qt::DayOfWeek> days = locale->weekdays();

    QV4::Scoped<QV4::ArrayObject> result(scope, ctx->engine->newArrayObject());
    result->arrayReserve(days.size());
    for (int i = 0; i < days.size(); ++i) {
        int day = days.at(i);
        if (day == 7) // JS Date days in range 0(Sunday) to 6(Saturday)
            day = 0;
        result->arrayData->put(i, QV4::Primitive::fromInt32(day));
    }
    result->setArrayLengthUnchecked(days.size());

    return result.asReturnedValue();
}

QV4::ReturnedValue QQmlLocaleData::method_get_uiLanguages(QV4::CallContext *ctx)
{
    QV4::Scope scope(ctx);
    QLocale *locale = getThisLocale(ctx);
    if (!locale)
        return QV4::Encode::undefined();

    QStringList langs = locale->uiLanguages();
    QV4::Scoped<QV4::ArrayObject> result(scope, ctx->engine->newArrayObject());
    result->arrayReserve(langs.size());
    QV4::ScopedValue v(scope);
    for (int i = 0; i < langs.size(); ++i)
        result->arrayData->put(i, (v = ctx->engine->newString(langs.at(i))));

    result->setArrayLengthUnchecked(langs.size());

    return result.asReturnedValue();
}

QV4::ReturnedValue QQmlLocaleData::method_currencySymbol(QV4::CallContext *ctx)
{
    QLocale *locale = getThisLocale(ctx);
    if (!locale)
        return QV4::Encode::undefined();

    if (ctx->callData->argc > 1)
        V4THROW_ERROR("Locale: currencySymbol(): Invalid arguments");

    QLocale::CurrencySymbolFormat format = QLocale::CurrencySymbol;
    if (ctx->callData->argc == 1) {
        quint32 intFormat = ctx->callData->args[0].toNumber();
        format = QLocale::CurrencySymbolFormat(intFormat);
    }

    return ctx->engine->newString(locale->currencySymbol(format))->asReturnedValue();
}

#define LOCALE_FORMAT(FUNC) \
QV4::ReturnedValue QQmlLocaleData::method_ ##FUNC (QV4::CallContext *ctx) { \
    QLocale *locale = getThisLocale(ctx); \
    if (!locale) \
        return QV4::Encode::undefined(); \
    if (ctx->callData->argc > 1) \
        V4THROW_ERROR("Locale: " #FUNC "(): Invalid arguments"); \
    QLocale::FormatType format = QLocale::LongFormat;\
    if (ctx->callData->argc == 1) { \
        quint32 intFormat = ctx->callData->args[0].toUInt32(); \
        format = QLocale::FormatType(intFormat); \
    } \
    return ctx->engine->newString(locale-> FUNC (format))->asReturnedValue(); \
}

LOCALE_FORMAT(dateTimeFormat)
LOCALE_FORMAT(timeFormat)
LOCALE_FORMAT(dateFormat)

// +1 added to idx because JS is 0-based, whereas QLocale months begin at 1.
#define LOCALE_FORMATTED_MONTHNAME(VARIABLE) \
QV4::ReturnedValue QQmlLocaleData::method_ ## VARIABLE (QV4::CallContext *ctx) {\
    QLocale *locale = getThisLocale(ctx); \
    if (!locale) \
        return QV4::Encode::undefined(); \
    if (ctx->callData->argc < 1 || ctx->callData->argc > 2) \
        V4THROW_ERROR("Locale: " #VARIABLE "(): Invalid arguments"); \
    QLocale::FormatType enumFormat = QLocale::LongFormat; \
    int idx = ctx->callData->args[0].toInt32() + 1; \
    if (idx < 1 || idx > 12) \
        V4THROW_ERROR("Locale: Invalid month"); \
    QString name; \
    if (ctx->callData->argc == 2) { \
        if (ctx->callData->args[1].isNumber()) { \
            quint32 intFormat = ctx->callData->args[1].toUInt32(); \
            QLocale::FormatType format = QLocale::FormatType(intFormat); \
            name = locale-> VARIABLE(idx, format); \
        } else { \
            V4THROW_ERROR("Locale: Invalid datetime format"); \
        } \
    } else { \
        name = locale-> VARIABLE(idx, enumFormat); \
    } \
    return ctx->engine->newString(name)->asReturnedValue(); \
}

// 0 -> 7 as Qt::Sunday is 7, but Sunday is 0 in JS Date
#define LOCALE_FORMATTED_DAYNAME(VARIABLE) \
QV4::ReturnedValue QQmlLocaleData::method_ ## VARIABLE (QV4::CallContext *ctx) {\
    QLocale *locale = getThisLocale(ctx); \
    if (!locale) \
        return QV4::Encode::undefined(); \
    if (ctx->callData->argc < 1 || ctx->callData->argc > 2) \
        V4THROW_ERROR("Locale: " #VARIABLE "(): Invalid arguments"); \
    QLocale::FormatType enumFormat = QLocale::LongFormat; \
    int idx = ctx->callData->args[0].toInt32(); \
    if (idx < 0 || idx > 7) \
        V4THROW_ERROR("Locale: Invalid day"); \
    if (idx == 0) idx = 7; \
    QString name; \
    if (ctx->callData->argc == 2) { \
        if (ctx->callData->args[1].isNumber()) { \
            quint32 intFormat = ctx->callData->args[1].toUInt32(); \
            QLocale::FormatType format = QLocale::FormatType(intFormat); \
            name = locale-> VARIABLE(idx, format); \
        } else { \
            V4THROW_ERROR("Locale: Invalid datetime format"); \
        } \
    } else { \
        name = locale-> VARIABLE(idx, enumFormat); \
    } \
    return ctx->engine->newString(name)->asReturnedValue(); \
}

LOCALE_FORMATTED_MONTHNAME(monthName)
LOCALE_FORMATTED_MONTHNAME(standaloneMonthName)
LOCALE_FORMATTED_DAYNAME(dayName)
LOCALE_FORMATTED_DAYNAME(standaloneDayName)

#define LOCALE_STRING_PROPERTY(VARIABLE) QV4::ReturnedValue QQmlLocaleData::method_get_ ## VARIABLE (QV4::CallContext* ctx) \
{ \
    QLocale *locale = getThisLocale(ctx); \
    if (!locale) \
        return QV4::Encode::undefined(); \
    return ctx->engine->newString(locale-> VARIABLE())->asReturnedValue();\
}

LOCALE_STRING_PROPERTY(name)
LOCALE_STRING_PROPERTY(nativeLanguageName)
LOCALE_STRING_PROPERTY(nativeCountryName)
LOCALE_STRING_PROPERTY(decimalPoint)
LOCALE_STRING_PROPERTY(groupSeparator)
LOCALE_STRING_PROPERTY(percent)
LOCALE_STRING_PROPERTY(zeroDigit)
LOCALE_STRING_PROPERTY(negativeSign)
LOCALE_STRING_PROPERTY(positiveSign)
LOCALE_STRING_PROPERTY(exponential)
LOCALE_STRING_PROPERTY(amText)
LOCALE_STRING_PROPERTY(pmText)

class QV8LocaleDataDeletable : public QV8Engine::Deletable
{
public:
    QV8LocaleDataDeletable(QV8Engine *engine);
    ~QV8LocaleDataDeletable();

    QV4::PersistentValue prototype;
};

QV8LocaleDataDeletable::QV8LocaleDataDeletable(QV8Engine *engine)
{
    QV4::ExecutionEngine *eng = QV8Engine::getV4(engine);
    QV4::Scope scope(eng);
    QV4::Scoped<QV4::Object> o(scope, eng->newObject());

    o->defineDefaultProperty(QStringLiteral("dateFormat"), QQmlLocaleData::method_dateFormat, 0);
    o->defineDefaultProperty(QStringLiteral("standaloneDayName"), QQmlLocaleData::method_standaloneDayName, 0);
    o->defineDefaultProperty(QStringLiteral("standaloneMonthName"), QQmlLocaleData::method_standaloneMonthName, 0);
    o->defineDefaultProperty(QStringLiteral("dayName"), QQmlLocaleData::method_dayName, 0);
    o->defineDefaultProperty(QStringLiteral("timeFormat"), QQmlLocaleData::method_timeFormat, 0);
    o->defineDefaultProperty(QStringLiteral("monthName"), QQmlLocaleData::method_monthName, 0);
    o->defineDefaultProperty(QStringLiteral("currencySymbol"), QQmlLocaleData::method_currencySymbol, 0);
    o->defineDefaultProperty(QStringLiteral("dateTimeFormat"), QQmlLocaleData::method_dateTimeFormat, 0);
    o->defineAccessorProperty(QStringLiteral("name"), QQmlLocaleData::method_get_name, 0);
    o->defineAccessorProperty(QStringLiteral("positiveSign"), QQmlLocaleData::method_get_positiveSign, 0);
    o->defineAccessorProperty(QStringLiteral("uiLanguages"), QQmlLocaleData::method_get_uiLanguages, 0);
    o->defineAccessorProperty(QStringLiteral("firstDayOfWeek"), QQmlLocaleData::method_get_firstDayOfWeek, 0);
    o->defineAccessorProperty(QStringLiteral("pmText"), QQmlLocaleData::method_get_pmText, 0);
    o->defineAccessorProperty(QStringLiteral("percent"), QQmlLocaleData::method_get_percent, 0);
    o->defineAccessorProperty(QStringLiteral("textDirection"), QQmlLocaleData::method_get_textDirection, 0);
    o->defineAccessorProperty(QStringLiteral("weekDays"), QQmlLocaleData::method_get_weekDays, 0);
    o->defineAccessorProperty(QStringLiteral("negativeSign"), QQmlLocaleData::method_get_negativeSign, 0);
    o->defineAccessorProperty(QStringLiteral("groupSeparator"), QQmlLocaleData::method_get_groupSeparator, 0);
    o->defineAccessorProperty(QStringLiteral("decimalPoint"), QQmlLocaleData::method_get_decimalPoint, 0);
    o->defineAccessorProperty(QStringLiteral("nativeLanguageName"), QQmlLocaleData::method_get_nativeLanguageName, 0);
    o->defineAccessorProperty(QStringLiteral("nativeCountryName"), QQmlLocaleData::method_get_nativeCountryName, 0);
    o->defineAccessorProperty(QStringLiteral("zeroDigit"), QQmlLocaleData::method_get_zeroDigit, 0);
    o->defineAccessorProperty(QStringLiteral("amText"), QQmlLocaleData::method_get_amText, 0);
    o->defineAccessorProperty(QStringLiteral("measurementSystem"), QQmlLocaleData::method_get_measurementSystem, 0);
    o->defineAccessorProperty(QStringLiteral("exponential"), QQmlLocaleData::method_get_exponential, 0);

    prototype = o;
}

QV8LocaleDataDeletable::~QV8LocaleDataDeletable()
{
}

V8_DEFINE_EXTENSION(QV8LocaleDataDeletable, localeV8Data);

/*!
    \qmltype Locale
    \instantiates QQmlLocale
    \inqmlmodule QtQml
    \brief Provides locale specific properties and formatted data

    The Locale object may only be created via the \l{QtQml::Qt::locale()}{Qt.locale()} function.
    It cannot be created directly.

    The \l{QtQml::Qt::locale()}{Qt.locale()} function returns a JS Locale object representing the
    locale with the specified name, which has the format
    "language[_territory][.codeset][@modifier]" or "C".

    Locale supports the concept of a default locale, which is
    determined from the system's locale settings at application
    startup.  If no parameter is passed to Qt.locale() the default
    locale object is returned.

    The Locale object provides a number of functions and properties
    providing data for the specified locale.

    The Locale object may also be passed to the \l Date and \l Number toLocaleString()
    and fromLocaleString() methods in order to convert to/from strings using
    the specified locale.

    This example shows the current date formatted for the German locale:

    \code
    import QtQuick 2.0

    Text {
        text: "The date is: " + Date().toLocaleString(Qt.locale("de_DE"))
    }
    \endcode

    The following example displays the specified number
    in the correct format for the default locale:

    \code
    import QtQuick 2.0

    Text {
        text: "The value is: " + Number(23443.34).toLocaleString(Qt.locale())
    }
    \endcode

    Qt Quick Locale's data is based on Common Locale Data Repository v1.8.1.


    \target FormatType
    \section2 Locale String Format Types

    The monthName(), standaloneMonthName(), dayName() and standaloneDayName()
    can use the following enumeration values to specify the formatting of
    the string representation for a Date object.

    \list
    \li Locale.LongFormat The long version of day and month names; for
    example, returning "January" as a month name.
    \li Locale.ShortFormat The short version of day and month names; for
    example, returning "Jan" as a month name.
    \li Locale.NarrowFormat A special version of day and month names for
    use when space is limited; for example, returning "J" as a month
    name. Note that the narrow format might contain the same text for
    different months and days or it can even be an empty string if the
    locale doesn't support narrow names, so you should avoid using it
    for date formatting. Also, for the system locale this format is
    the same as ShortFormat.
    \endlist


    Additionally the double-to-string and string-to-double conversion functions are
    covered by the following licenses:

    \legalese
    Copyright (c) 1991 by AT&T.

    Permission to use, copy, modify, and distribute this software for any
    purpose without fee is hereby granted, provided that this entire notice
    is included in all copies of any software which is or includes a copy
    or modification of this software and in all copies of the supporting
    documentation for such software.

    THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR IMPLIED
    WARRANTY.  IN PARTICULAR, NEITHER THE AUTHOR NOR AT&T MAKES ANY
    REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE MERCHANTABILITY
    OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR PURPOSE.

    This product includes software developed by the University of
    California, Berkeley and its contributors.

    \sa Date, Number
*/

QQmlLocale::QQmlLocale()
{
}

QQmlLocale::~QQmlLocale()
{
}

QV4::ReturnedValue QQmlLocale::locale(QV8Engine *v8engine, const QString &localeName)
{
    QLocale qlocale;
    if (!localeName.isEmpty())
        qlocale = localeName;
    return wrap(v8engine, qlocale);
}

QV4::ReturnedValue QQmlLocale::wrap(QV8Engine *engine, const QLocale &locale)
{
    QV8LocaleDataDeletable *d = localeV8Data(engine);
    QV4::ExecutionEngine *v4 = QV8Engine::getV4(engine);
    QV4::Scope scope(v4);
    QV4::Scoped<QQmlLocaleData> wrapper(scope, new (v4->memoryManager) QQmlLocaleData(v4));
    wrapper->locale = locale;
    QV4::ScopedObject p(scope, d->prototype.value());
    wrapper->setPrototype(p.getPointer());
    return wrapper.asReturnedValue();
}

void QQmlLocale::registerStringLocaleCompare(QV4::ExecutionEngine *engine)
{
    engine->stringObjectClass->prototype->defineDefaultProperty(QStringLiteral("localeCompare"), method_localeCompare);
}

QV4::ReturnedValue QQmlLocale::method_localeCompare(QV4::CallContext *ctx)
{
    if (ctx->callData->argc != 1 || (!ctx->callData->args[0].isString() && !ctx->callData->args[0].asStringObject()))
        return QV4::StringPrototype::method_localeCompare(ctx);

    if (!ctx->callData->thisObject.isString() && !ctx->callData->thisObject.asStringObject())
        return QV4::StringPrototype::method_localeCompare(ctx);

    QString thisString = ctx->callData->thisObject.toQStringNoThrow();
    QString thatString = ctx->callData->args[0].toQStringNoThrow();

    return QV4::Encode(QString::localeAwareCompare(thisString, thatString));
}

/*!
    \qmlproperty string QtQml::Locale::name

    Holds the language and country of this locale as a
    string of the form "language_country", where
    language is a lowercase, two-letter ISO 639 language code,
    and country is an uppercase, two- or three-letter ISO 3166 country code.
*/

/*!
    \qmlproperty string QtQml::Locale::decimalPoint

    Holds the decimal point character of this locale.
*/

/*!
    \qmlproperty string QtQml::Locale::groupSeparator

    Holds the group separator character of this locale.
*/

/*!
    \qmlproperty string QtQml::Locale::percent

    Holds the percent character of this locale.
*/


/*!
    \qmlproperty string QtQml::Locale::zeroDigit

    Holds Returns the zero digit character of this locale.
*/

/*!
    \qmlproperty string QtQml::Locale::negativeSign

    Holds the negative sign character of this locale.
*/

/*!
    \qmlproperty string QtQml::Locale::positiveSign

    Holds the positive sign character of this locale.
*/

/*!
    \qmlproperty string QtQml::Locale::exponential

    Holds the exponential character of this locale.
*/

/*!
    \qmlmethod string QtQml::Locale::dateTimeFormat(type)

    Returns the date time format used for the current locale.
    \a type specifies the FormatType to return.

    \sa Date
*/

/*!
    \qmlmethod string QtQml::Locale::dateFormat(type)

    Returns the date format used for the current locale.
    \a type specifies the FormatType to return.

    \sa Date
*/

/*!
    \qmlmethod string QtQml::Locale::timeFormat(type)

    Returns the time format used for the current locale.
    \a type specifies the FormatType to return.

    \sa Date
*/

/*!
    \qmlmethod string QtQml::Locale::monthName(month, type)

    Returns the localized name of \a month (0-11), in the optional
    \l FormatType specified by \a type.

    \note the QLocale C++ API expects a range of (1-12), however Locale.monthName()
    expects 0-11 as per the JS Date object.

    \sa dayName(), standaloneMonthName()
*/

/*!
    \qmlmethod string QtQml::Locale::standaloneMonthName(month, type)

    Returns the localized name of \a month (0-11) that is used as a
    standalone text, in the optional \l FormatType specified by \a type.

    If the locale information doesn't specify the standalone month
    name then return value is the same as in monthName().

    \note the QLocale C++ API expects a range of (1-12), however Locale.standaloneMonthName()
    expects 0-11 as per the JS Date object.

    \sa monthName(), standaloneDayName()
*/

/*!
    \qmlmethod string QtQml::Locale::dayName(day, type)

    Returns the localized name of the \a day (where 0 represents
    Sunday, 1 represents Monday and so on), in the optional
    \l FormatType specified by \a type.

    \sa monthName(), standaloneDayName()
*/

/*!
    \qmlmethod string QtQml::Locale::standaloneDayName(day, type)

    Returns the localized name of the \a day (where 0 represents
    Sunday, 1 represents Monday and so on) that is used as a
    standalone text, in the \l FormatType specified by \a type.

    If the locale information does not specify the standalone day
    name then return value is the same as in dayName().

    \sa dayName(), standaloneMonthName()
*/

/*!
    \qmlproperty enumeration QtQml::Locale::firstDayOfWeek

    Holds the first day of the week according to the current locale.

    \list
    \li Locale.Sunday = 0
    \li Locale.Monday = 1
    \li Locale.Tuesday = 2
    \li Locale.Wednesday = 3
    \li Locale.Thursday = 4
    \li Locale.Friday = 5
    \li Locale.Saturday = 6
    \endlist

    \note that these values match the JS Date API which is different
    from the Qt C++ API where Qt::Sunday = 7.
*/

/*!
    \qmlproperty Array<int> QtQml::Locale::weekDays

    Holds an array of days that are considered week days according to the current locale,
    where Sunday is 0 and Saturday is 6.

    \sa firstDayOfWeek
*/

/*!
    \qmlproperty Array<string> QtQml::Locale::uiLanguages

    Returns an ordered list of locale names for translation purposes in
    preference order.

    The return value represents locale names that the user expects to see the
    UI translation in.

    The first item in the list is the most preferred one.
*/

/*!
    \qmlproperty enumeration QtQml::Locale::textDirection

    Holds the text direction of the language:
    \list
    \li Qt.LeftToRight
    \li Qt.RightToLeft
    \endlist
*/

/*!
    \qmlproperty string QtQml::Locale::amText

    The localized name of the "AM" suffix for times specified using the conventions of the 12-hour clock.
*/

/*!
    \qmlproperty string QtQml::Locale::pmText

    The localized name of the "PM" suffix for times specified using the conventions of the 12-hour clock.
*/

/*!
    \qmlmethod string QtQml::Locale::currencySymbol(format)

    Returns the currency symbol for the specified \a format:
    \list
    \li Locale.CurrencyIsoCode a ISO-4217 code of the currency.
    \li Locale.CurrencySymbol a currency symbol.
    \li Locale.CurrencyDisplayName a user readable name of the currency.
    \endlist
    \sa Number::toLocaleCurrencyString()
*/

/*!
    \qmlproperty string QtQml::Locale::nativeLanguageName

    Holds a native name of the language for the locale. For example
    "Schwiizertüütsch" for Swiss-German locale.

    \sa nativeCountryName
*/

/*!
    \qmlproperty string QtQml::Locale::nativeCountryName

    Holds a native name of the country for the locale. For example
    "España" for Spanish/Spain locale.

    \sa nativeLanguageName
*/

/*!
    \qmlproperty enumeration QtQml::Locale::measurementSystem

    This property defines which units are used for measurement.

    \list
    \li Locale.MetricSystem This value indicates metric units, such as meters,
        centimeters and millimeters.
    \li Locale.ImperialSystem This value indicates imperial units, such as inches and
        miles. There are several distinct imperial systems in the world; this
        value stands for the official United States imperial units.
    \endlist
*/

QT_END_NAMESPACE