-
Notifications
You must be signed in to change notification settings - Fork 3
/
mlocale.cpp
4896 lines (4457 loc) · 172 KB
/
mlocale.cpp
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
/***************************************************************************
**
** Copyright (C) 2010, 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of libmeegotouch.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** This library is free software; you can redistribute it and/or
** modify it 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.
**
****************************************************************************/
#include "mlocale.h"
#include "mlocale_p.h"
#include "debug.h"
#ifdef HAVE_ICU
#include <unicode/unistr.h>
#include <unicode/ucal.h>
#include <unicode/coll.h>
#include <unicode/fieldpos.h>
#include <unicode/datefmt.h>
#include <unicode/calendar.h>
#include <unicode/smpdtfmt.h> // SimpleDateFormat
#include <unicode/numfmt.h>
#include <unicode/uloc.h>
#include <unicode/dtfmtsym.h> // date format symbols
#include <unicode/putil.h> // u_setDataDirectory
#include <unicode/numsys.h>
using namespace icu;
#endif
#include <MDebug>
#include <QTranslator>
#include <QDir>
#include <QMetaProperty>
#include <QCoreApplication>
#include <QMutex>
#include <QDateTime>
#include <QPointer>
#ifdef HAVE_ICU
#include "mcollator.h"
#include "mcalendar.h"
#include "mcalendar_p.h"
#include "micuconversions.h"
#endif
#include "mlocaleabstractconfigitem.h"
#include "mlocaleabstractconfigitemfactory.h"
#include "mlocalenullconfigitemfactory.h"
namespace ML10N {
void MLocale::clearSystemDefault()
{
if ( MLocale::s_systemDefault )
{
delete MLocale::s_systemDefault;
MLocale::s_systemDefault = 0;
}
}
static QPointer<QTranslator> s_ltrTranslator = 0;
static QPointer<QTranslator> s_rtlTranslator = 0;
static const MLocaleAbstractConfigItemFactory* g_pConfigItemFactory = 0;
namespace
{
const char *const BackupNameFormatString = "%d%t%g%t%m%t%f";
const QString RtlLanguages("ar:fa:he:ps:ur:");
const char *const Languages = "Languages";
const char *const Countries = "Countries";
const QString SettingsLanguage("/meegotouch/i18n/language");
const QString SettingsLcTime("/meegotouch/i18n/lc_time");
const QString SettingsLcTimeFormat24h("/meegotouch/i18n/lc_timeformat24h");
const QString SettingsLcCollate("/meegotouch/i18n/lc_collate");
const QString SettingsLcNumeric("/meegotouch/i18n/lc_numeric");
const QString SettingsLcMonetary("/meegotouch/i18n/lc_monetary");
const QString SettingsLcTelephone("/meegotouch/i18n/lc_telephone");
QMap<QString, QString> gconfLanguageMap;
}
/// Helper
// Copied from Qt's QCoreApplication
static void replacePercentN(QString *result, int n)
{
if (n >= 0) {
int percentPos = 0;
int len = 0;
while ((percentPos = result->indexOf(QLatin1Char('%'), percentPos + len)) != -1) {
len = 1;
//TODO replace fmt to other type to do our own native digit conversions
QString fmt;
if (result->at(percentPos + len) == QLatin1Char('L')) {
++len;
fmt = QLatin1String("%L1");
} else {
fmt = QLatin1String("%1");
}
if (result->at(percentPos + len) == QLatin1Char('n')) {
fmt = fmt.arg(n);
++len;
result->replace(percentPos, len, fmt);
len = fmt.length();
}
}
}
}
/////////////////////////////////////////////////
//// The private Mtranslationcatalog class ////
//! \internal
class MTranslationCatalog: public QSharedData
{
public:
MTranslationCatalog(const QString &name);
virtual ~MTranslationCatalog();
// called by detach
MTranslationCatalog(const MTranslationCatalog &other);
/*!
* \brief Load the actual translation file using locale and category info
*
* As an example lets assume that
*
* - MLocale::translationPaths()
* is the list ("/usr/share/l10n/meegotouch", "/usr/share/l10n")
* - the category is MLocale::MLcMessages
* - the name of the locale (returned by mlocale->categoryName(category))
* is "en_US"
* - the base name of the translation file is "foo"
*
* then the function will try to load translation catalogs in the following order:
*
* /usr/share/l10n/meegotouch/foo_en_US.qm
* /usr/share/l10n/meegotouch/foo_en_US
* /usr/share/l10n/meegotouch/foo_en.qm
* /usr/share/l10n/meegotouch/foo_en
* /usr/share/l10n/foo_en_US.qm
* /usr/share/l10n/foo_en_US
* /usr/share/l10n/foo_en.qm
* /usr/share/l10n/foo_en
*
* and return when the first translation catalog was found.
* If no translation can be found this function returns false.
*
* The way locale specific parts are successively cut away from the
* translation file name is inherited from
* <a href="http://qt.nokia.com/doc/4.6/qtranslator.html#load">QTranslator::load()</a>
* because this is used to load the translation files.
*
* @param mlocale the locale for which the translations are loaded
* @param category this is usually MLocale::MLcMessages but it could
* also be MLocale::MLcTime, MLocale::MLcNumeric,
* etc...
*
* @return true if translations could be found, false if not.
*/
bool loadWith(MLocale *mlocale, MLocale::Category category);
// the abstract name for a translation. together with locale info and
// category a concrete path is created when the file is loaded
QString _name;
// the actual translator
QTranslator _translator;
private:
MTranslationCatalog &operator=(const MTranslationCatalog &other);
};
//! \internal_end
// //////
// MTranslationCatalog implementation
MTranslationCatalog::MTranslationCatalog(const QString &name)
: _name(name), _translator()
{
// nothing
}
MTranslationCatalog::~MTranslationCatalog()
{
// nothing
}
MTranslationCatalog::MTranslationCatalog(const MTranslationCatalog &other)
: QSharedData(), _name(other._name)
{
// nothing
}
bool MTranslationCatalog::loadWith(MLocale *mlocale, MLocale::Category category)
{
QStringList localeDirs;
QString fname;
if (QFileInfo(_name).isRelative()) {
localeDirs = MLocale::translationPaths();
fname = _name;
}
else {
localeDirs = (QStringList() << QFileInfo(_name).path());
fname = QFileInfo(_name).fileName();
}
const int size = localeDirs.size();
for (int i = 0; i < size; ++i) {
QString prefix = QDir(localeDirs.at(i)).absolutePath();
if (prefix.length() && !prefix.endsWith(QLatin1Char('/')))
prefix += QLatin1Char('/');
QString realname;
if (fname.endsWith(QLatin1String(".qm"))) {
// this is either engineering English or the locale
// specific parts of the file name have been fully
// specified already. We don’t want any fallbacks in that
// case, we try to load only the exact file name:
realname = prefix + fname;
if(QFileInfo(realname).isReadable() && _translator.load(realname))
return true;
}
else {
QString delims("_.@");
QString engineeringEnglishName = fname;
fname += '_' + mlocale->categoryName(category);
for (;;) {
realname = prefix + fname + ".qm";
if (QFileInfo(realname).isReadable() && _translator.load(realname))
return true;
realname = prefix + fname;
if (QFileInfo(realname).isReadable() && _translator.load(realname))
return true;
int rightmost = 0;
for (int i = 0; i < (int)delims.length(); i++) {
int k = fname.lastIndexOf(delims[i]);
if (k > rightmost)
rightmost = k;
}
// no truncations?
if (rightmost == 0)
break;
fname.truncate(rightmost);
if (fname == engineeringEnglishName) {
// do not fall back to engineering English when
// trying to load real translations. But if this
// point is reached, it means that no real
// translations were found for the requested
// locale. As a last fallback, try to load the
// real English translations (not the engineering
// English) here.
realname = prefix + fname + "_en.qm";
if (QFileInfo(realname).isReadable() && _translator.load(realname))
return true;
// nothing at all was found
break;
}
}
}
}
// Loading the new file into the QTranslator failed.
// Clear any old contents of the QTranslator before returning false.
// This is necessary because the QTranslator may still have old contents.
// For example, assume that an Arabic translation "foo_ar.qm" has been loaded
// into the translator before and now this loadWith() function tries to
// load "foo_de.qm" because the language has been switched to German
// but "foo_de.qm" does not exist. We do *not* want to keep the previous
// "foo_ar.qm" contents in that case.
_translator.load("", 0);
return false;
}
////////////////////////////////
//// Private stuff for MLocale
QStringList MLocalePrivate::translationPaths;
QStringList MLocalePrivate::dataPaths;
#ifdef HAVE_ICU
bool MLocalePrivate::truncateLocaleName(QString *localeName)
{
// according to http://userguide.icu-project.org/locale the separators
// that specify the parts of a locale are "_", "@", and ";", e.g.
// in sr_Latn_RS_REVISED@currency=USD;calendar=islamic-civil
// so we remove them from the end of the locale string.
int semicolonIndex = localeName->lastIndexOf(';');
if (semicolonIndex != -1)
{
// found semicolon, remove it and remaining part of string
localeName->truncate(semicolonIndex);
return true;
}
else
{
int atIndex = localeName->lastIndexOf('@');
if (atIndex != -1)
{
// found "@", remove it and remaining part of string
localeName->truncate(atIndex);
return true;
}
else
{
int underscoreIndex = localeName->lastIndexOf('_');
if (underscoreIndex != -1)
{
// found "_", remove it and remaining part of string
localeName->truncate(underscoreIndex);
return true;
}
}
}
// no truncation possible
return false;
}
#endif
#ifdef HAVE_ICU
icu::DateFormatSymbols *MLocalePrivate::createDateFormatSymbols(const icu::Locale &locale)
{
// This is a bit dirty but the only way to currently get the symbols
// is like this. Only the internal API supports directly creating DateFormatSymbols
// with an arbitrary calendar
UErrorCode status = U_ZERO_ERROR;
SimpleDateFormat dummyFormatter("", locale, status);
if (U_FAILURE(status)) {
return 0;
}
const DateFormatSymbols *dfs = dummyFormatter.getDateFormatSymbols();
return new DateFormatSymbols(*dfs);
}
#endif
#ifdef HAVE_ICU
bool MLocalePrivate::isTwelveHours(const QString &icuFormatQString) const
{
if (icuFormatQString.contains('\'')) {
bool isQuoted = false;
for (int i = 0; i < icuFormatQString.size(); ++i) {
if (icuFormatQString[i] == '\'')
isQuoted = !isQuoted;
if (!isQuoted && icuFormatQString[i] == 'a')
return true;
}
return false;
}
else {
if(icuFormatQString.contains('a'))
return true;
else
return false;
}
}
#endif
#ifdef HAVE_ICU
void MLocalePrivate::dateFormatTo24h(icu::DateFormat *df) const
{
if (df) {
icu::UnicodeString icuFormatString;
QString icuFormatQString;
static_cast<SimpleDateFormat *>(df)->toPattern(icuFormatString);
icuFormatQString = MIcuConversions::unicodeStringToQString(icuFormatString);
if (isTwelveHours(icuFormatQString)) {
// remove unquoted 'a' characters and remove space left of 'a'
// and change unquoted h -> H and K -> k
QString tmp;
bool isQuoted = false;
for (int i = 0; i < icuFormatQString.size(); ++i) {
QChar c = icuFormatQString[i];
if (c == '\'')
isQuoted = !isQuoted;
if (!isQuoted) {
if (c == 'h')
tmp.append("H");
else if (c == 'K')
tmp.append("k");
else if (c == 'a') {
if (tmp.endsWith(' ')) {
// remove space before 'a' if character
// after 'a' is space as well:
if (i < icuFormatQString.size() - 1
&& icuFormatQString[i+1] == ' ')
tmp.remove(tmp.size()-1,1);
// remove space before 'a' if 'a' is last
// character in string:
if (i == icuFormatQString.size() - 1)
tmp.remove(tmp.size()-1,1);
}
}
else
tmp.append(c);
}
else {
tmp.append(c);
}
}
icuFormatQString = tmp;
}
icuFormatString = MIcuConversions::qStringToUnicodeString(icuFormatQString);
static_cast<SimpleDateFormat *>(df)->applyPattern(icuFormatString);
}
}
#endif
#ifdef HAVE_ICU
void MLocalePrivate::dateFormatTo12h(icu::DateFormat *df) const
{
if (df) {
icu::UnicodeString icuFormatString;
QString icuFormatQString;
static_cast<SimpleDateFormat *>(df)->toPattern(icuFormatString);
icuFormatQString = MIcuConversions::unicodeStringToQString(icuFormatString);
if (!isTwelveHours(icuFormatQString)) {
// change unquoted H -> h and k -> K
// add 'a' at the right position (maybe adding a space as well)
QString tmp;
bool isQuoted = false;
bool amPmMarkerWritten = false;
QString language = categoryName(MLocale::MLcTime);
bool writeAmPmMarkerBeforeHours = false;
if (language.startsWith( QLatin1String("ja"))
|| language.startsWith( QLatin1String("zh")))
writeAmPmMarkerBeforeHours = true;
if (writeAmPmMarkerBeforeHours) {
for (int i = 0; i < icuFormatQString.size(); ++i) {
QChar c = icuFormatQString[i];
if (c == '\'')
isQuoted = !isQuoted;
if (!isQuoted) {
if (c == 'H') {
if (!amPmMarkerWritten) {
tmp.append("a");
amPmMarkerWritten = true;
}
tmp.append("h");
}
else if (c == 'k') {
if (!amPmMarkerWritten) {
tmp.append("a");
amPmMarkerWritten = true;
}
tmp.append("K");
}
else
tmp.append(c);
}
else {
tmp.append(c);
}
}
icuFormatQString = tmp;
}
else {
for (int i = 0; i < icuFormatQString.size(); ++i) {
QChar c = icuFormatQString[i];
if (c == '\'')
isQuoted = !isQuoted;
if (!isQuoted) {
if (c == 'H')
tmp.append("h");
else if (c == 'k')
tmp.append("K");
else if (c == 'z') {
if (!amPmMarkerWritten) {
if (!tmp.endsWith(' '))
tmp.append(' ');
tmp.append("a ");
amPmMarkerWritten = true;
}
tmp.append(c);
}
else
tmp.append(c);
}
else {
tmp.append(c);
}
}
if (!amPmMarkerWritten)
tmp.append(" a");
icuFormatQString = tmp;
}
}
icuFormatString = MIcuConversions::qStringToUnicodeString(icuFormatQString);
static_cast<SimpleDateFormat *>(df)->applyPattern(icuFormatString);
}
}
#endif
#ifdef HAVE_ICU
void MLocalePrivate::dateFormatToYearAndMonth(icu::DateFormat *df) const
{
if (df) {
icu::UnicodeString icuFormatString;
QString icuFormatQString;
static_cast<SimpleDateFormat *>(df)->toPattern(icuFormatString);
icuFormatQString = MIcuConversions::unicodeStringToQString(icuFormatString);
QString categoryNameTime = categoryName(MLocale::MLcTime);
QString categoryNameMessages = categoryName(MLocale::MLcMessages);
if(categoryNameTime.startsWith("zh"))
if(!mixingSymbolsWanted(categoryNameMessages, categoryNameTime))
icuFormatQString = QString::fromUtf8("yyyy年 LLLL"); // 2011年 十二月
else
icuFormatQString = QString::fromUtf8("yyyy LLLL");
else if(categoryNameTime.startsWith("ja"))
if(!mixingSymbolsWanted(categoryNameMessages, categoryNameTime))
icuFormatQString = QString::fromUtf8("yyyy年M月"); // 2011年12月
else
icuFormatQString = QString::fromUtf8("yyyy LLLL");
else if(categoryNameTime.startsWith("ko"))
if(!mixingSymbolsWanted(categoryNameMessages, categoryNameTime))
icuFormatQString = QString::fromUtf8("yyyy년 M월");
else
icuFormatQString = QString::fromUtf8("yyyy LLLL");
else if(categoryNameTime.startsWith("vi"))
icuFormatQString = QString::fromUtf8("LLLL - yyyy");
else if(categoryNameTime.startsWith("eu")
|| categoryNameTime.startsWith("hu")
|| categoryNameTime.startsWith("ms"))
icuFormatQString = QLatin1String("yyyy LLLL");
else
icuFormatQString = QLatin1String("LLLL yyyy");
icuFormatString = MIcuConversions::qStringToUnicodeString(icuFormatQString);
static_cast<SimpleDateFormat *>(df)->applyPattern(icuFormatString);
}
}
#endif
#ifdef HAVE_ICU
void MLocalePrivate::dateFormatToWeekdayAbbreviatedAndDayOfMonth(icu::DateFormat *df) const
{
if (df) {
icu::UnicodeString icuFormatString;
QString icuFormatQString;
static_cast<SimpleDateFormat *>(df)->toPattern(icuFormatString);
icuFormatQString = MIcuConversions::unicodeStringToQString(icuFormatString);
QString categoryNameTime = categoryName(MLocale::MLcTime);
QString categoryNameMessages = categoryName(MLocale::MLcMessages);
if(categoryNameTime.startsWith("zh"))
if(!mixingSymbolsWanted(categoryNameMessages, categoryNameTime))
icuFormatQString = QString::fromUtf8("d日ccc"); // 5日周一
else
icuFormatQString = QString::fromUtf8("d ccc");
else if(categoryNameTime.startsWith("ja"))
if(!mixingSymbolsWanted(categoryNameMessages, categoryNameTime))
icuFormatQString = QString::fromUtf8("d日(ccc)"); // 5日(月)
else
icuFormatQString = QString::fromUtf8("d ccc");
else if(categoryNameTime.startsWith("ko"))
if(!mixingSymbolsWanted(categoryNameMessages, categoryNameTime))
icuFormatQString = QString::fromUtf8("d일 ccc");
else
icuFormatQString = QString::fromUtf8("d ccc");
else
icuFormatQString = QLatin1String("ccc d");
icuFormatString = MIcuConversions::qStringToUnicodeString(icuFormatQString);
static_cast<SimpleDateFormat *>(df)->applyPattern(icuFormatString);
}
}
#endif
#ifdef HAVE_ICU
void MLocalePrivate::dateFormatToWeekdayWideAndDayOfMonth(icu::DateFormat *df) const
{
if (df) {
icu::UnicodeString icuFormatString;
QString icuFormatQString;
static_cast<SimpleDateFormat *>(df)->toPattern(icuFormatString);
icuFormatQString = MIcuConversions::unicodeStringToQString(icuFormatString);
QString categoryNameTime = categoryName(MLocale::MLcTime);
QString categoryNameMessages = categoryName(MLocale::MLcMessages);
if(categoryNameTime.startsWith("zh"))
if(!mixingSymbolsWanted(categoryNameMessages, categoryNameTime))
icuFormatQString = QString::fromUtf8("d日cccc"); // 5日星期一
else
icuFormatQString = QString::fromUtf8("d cccc");
else if(categoryNameTime.startsWith("ja"))
if(!mixingSymbolsWanted(categoryNameMessages, categoryNameTime))
icuFormatQString = QString::fromUtf8("d日(cccc)"); // 5日(月曜日)
else
icuFormatQString = QString::fromUtf8("d cccc");
else if(categoryNameTime.startsWith("ko"))
if(!mixingSymbolsWanted(categoryNameMessages, categoryNameTime))
icuFormatQString = QString::fromUtf8("d일 cccc");
else
icuFormatQString = QString::fromUtf8("d cccc");
else
icuFormatQString = QLatin1String("cccc d");
icuFormatString = MIcuConversions::qStringToUnicodeString(icuFormatQString);
static_cast<SimpleDateFormat *>(df)->applyPattern(icuFormatString);
}
}
#endif
#ifdef HAVE_ICU
void MLocalePrivate::simplifyDateFormatForMixing(icu::DateFormat *df) const
{
if (df) {
icu::UnicodeString icuFormatString;
QString icuFormatQString;
static_cast<SimpleDateFormat *>(df)->toPattern(icuFormatString);
icuFormatQString = MIcuConversions::unicodeStringToQString(icuFormatString);
QString categoryNameTime = categoryName(MLocale::MLcTime);
QString categoryNameMessages = categoryName(MLocale::MLcMessages);
QString categoryScriptTime = MLocale::localeScript(categoryNameTime);
QString categoryScriptMessages = MLocale::localeScript(categoryNameMessages);
// replace some known language specific stuff with something
// generic which is understandable in a all languages or remove it
// if there is no good generic replacement:
if((categoryNameTime.startsWith("zh")
|| categoryNameTime.startsWith("ja"))
&& !categoryNameMessages.startsWith("zh")
&& !categoryNameMessages.startsWith("ja")) {
// when mixing something *neither* Chinese *nor* Japanese,
// into a Chinese or Japanese date format, replace the
// Chinese characters with something understandable in the
// non-CJ language. If mixing versions of Chinese or
// Japanese, do nothing. The only difference then is
// whether the simplified 时 or the traditional character
// 時 for hour is used.
icuFormatQString.replace(QString::fromUtf8("年"), QLatin1String("-"));
icuFormatQString.replace(QString::fromUtf8("月"), QLatin1String("-"));
icuFormatQString.replace(QString::fromUtf8("日"), QLatin1String(""));
icuFormatQString.replace(QString::fromUtf8("時"), QLatin1String(":"));
icuFormatQString.replace(QString::fromUtf8("时"), QLatin1String(":"));
icuFormatQString.replace(QString::fromUtf8("分"), QLatin1String(":"));
icuFormatQString.replace(QString::fromUtf8("秒"), QLatin1String(""));
}
if(categoryNameTime.startsWith("ko")) {
icuFormatQString.replace(QString::fromUtf8("년 "), QLatin1String("-"));
icuFormatQString.replace(QString::fromUtf8("월 "), QLatin1String("-"));
icuFormatQString.replace(QString::fromUtf8("일 "), QLatin1String(" "));
icuFormatQString.replace(QString::fromUtf8("시 "), QLatin1String(":"));
icuFormatQString.replace(QString::fromUtf8("분 "), QLatin1String(":"));
icuFormatQString.replace(QString::fromUtf8("초"), QLatin1String(""));
}
// es_AR contains “hh'h'''mm:ss” or “HH'h'''mm:ss”
icuFormatQString.replace(QLatin1String("h'h'''m"), QLatin1String("h:m"));
icuFormatQString.replace(QLatin1String("H'h'''m"), QLatin1String("H:m"));
// es_PE contains “hh'H'mm''ss''” or “HH'H'mm''ss''”
icuFormatQString.replace(QLatin1String("h'H'm"), QLatin1String("h:m"));
icuFormatQString.replace(QLatin1String("H'H'm"), QLatin1String("H:m"));
icuFormatQString.replace(QLatin1String("m''s"), QLatin1String("m:s"));
icuFormatQString.replace(QLatin1String("s''"), QLatin1String("s"));
// eo contains “h-'a' 'horo' 'kaj' m:ss” or “H-'a' 'horo' 'kaj' m:ss” or “EEEE, d-'a' 'de' MMMM y”
icuFormatQString.replace(QLatin1String("H-'a' 'horo' 'kaj' m:ss"), QLatin1String("HH:mm:ss"));
icuFormatQString.replace(QLatin1String("h-'a' 'horo' 'kaj' m:ss"), QLatin1String("hh:mm:ss"));
icuFormatQString.replace(QLatin1String("d-'a'"), QLatin1String("d "));
// fa_IR may contain “ساعت” between date and time
icuFormatQString.replace(QString::fromUtf8("ساعت"), QLatin1String(""));
// pt_PT, ... contain “HH'h'mm'min'ss's' or “hh'h'mm'min'ss's'” and
// en_BE, fr_CA, ... contain “HH 'h' mm 'min' ss 's'” or “hh 'h' mm 'min' ss 's'”:
icuFormatQString.replace(QLatin1String("h'h'mm"), QLatin1String("h:mm"));
icuFormatQString.replace(QLatin1String("h 'h' mm"), QLatin1String("h:mm"));
icuFormatQString.replace(QLatin1String("H'h'mm"), QLatin1String("H:mm"));
icuFormatQString.replace(QLatin1String("H 'h' mm"), QLatin1String("H:mm"));
icuFormatQString.replace(QLatin1String("m'min's"), QLatin1String("m:s"));
icuFormatQString.replace(QLatin1String("m 'min' s"), QLatin1String("m:s"));
icuFormatQString.replace(QLatin1String("ss's'"), QLatin1String("ss"));
icuFormatQString.replace(QLatin1String("ss 's'"), QLatin1String("ss"));
// kk contains “'ж'.”
icuFormatQString.replace(QString::fromUtf8("'ж'."), QLatin1String(""));
// ru_RU contains “y 'г'.” (e.g. “2008 г.”)
// (note the U+00A0 NO-BREAK SPACE in front of the “'г'.”):
icuFormatQString.replace(QString::fromUtf8(" 'г'."), QLatin1String(""));
// sv_SE contains “d:'e'” (e.g. “18:e”):
icuFormatQString.replace(QLatin1String(":'e'"), QLatin1String(""));
// sv_SE and nb_NO contain “'kl'.”
icuFormatQString.replace(QLatin1String("'kl'."), QLatin1String(""));
// uk_UA contains “y 'р'.” (e.g. “2008 р.”):
icuFormatQString.replace(QString::fromUtf8("'р'."), QLatin1String(""));
// remove remaining quoted stuff not covered by the special
// cases above from the format strings, quoted stuff is
// hardcoded text in the language of the the time category and
// most likely not understandable in the language of the
// message locale:
icuFormatQString.replace(QRegExp("'[^']*'"), QLatin1String(""));
// use stand-alone versions of month names and weekday names only
// inflected versions will make no sense in the context of a different
// language:
icuFormatQString.replace(QLatin1String("EEEE"), QLatin1String("cccc"));
icuFormatQString.replace(QLatin1String("MMMM"), QLatin1String("LLLL"));
icuFormatQString.replace(QLatin1String("EEE"), QLatin1String("ccc"));
icuFormatQString.replace(QLatin1String("MMM"), QLatin1String("LLL"));
if(categoryNameTime.startsWith("th")) {
// th_TH contains “H นาฬิกา m นาที ss วินาที”
icuFormatQString.replace(QString::fromUtf8("H นาฬิกา m"), QLatin1String("H:m"));
icuFormatQString.replace(QString::fromUtf8("h นาฬิกา m"), QLatin1String("h:m"));
icuFormatQString.replace(QString::fromUtf8("m นาที s"), QLatin1String("m:s"));
icuFormatQString.replace(QString::fromUtf8("s วินาที"), QLatin1String("s"));
// th_TH contains “EEEEที่” or “ccccที่”
icuFormatQString.replace(QString::fromUtf8("cที่"), QLatin1String("c"));
}
if((categoryNameTime.startsWith("zh")
|| categoryNameTime.startsWith("ja"))
&& !categoryNameMessages.startsWith("zh")
&& !categoryNameMessages.startsWith("ja")) {
// when mixing a language which is *neither* Chinese *nor*
// Japanese, into a Chinese or Japanese date format, add a
// few spaces for better readability:
icuFormatQString.replace(QLatin1String("cz"), QLatin1String("c z"));
icuFormatQString.replace(QLatin1String("zH"), QLatin1String("z H"));
icuFormatQString.replace(QLatin1String("za"), QLatin1String("z a"));
icuFormatQString.replace(QLatin1String("ca"), QLatin1String("c a"));
icuFormatQString.replace(QLatin1String("cH"), QLatin1String("c H"));
icuFormatQString.replace(QLatin1String("ah"), QLatin1String("a h"));
icuFormatQString.replace(QLatin1String("da"), QLatin1String("d a"));
icuFormatQString.replace(QLatin1String("dH"), QLatin1String("d H"));
icuFormatQString.replace(QLatin1String("dz"), QLatin1String("d z"));
icuFormatQString.replace(QLatin1String("dccc"), QLatin1String("d ccc"));
}
if(categoryScriptTime == QLatin1String("Hebr")
&& categoryScriptMessages != QLatin1String("Hebr")) {
// he_IL has “בMMMM” or “בLLLL”
icuFormatQString.replace(QString::fromUtf8("בL"), QLatin1String("L"));
}
if(!categoryNameTime.startsWith("zh")
&& !categoryNameTime.startsWith("ja")
&& categoryScriptTime != QLatin1String("Arab")
&& categoryScriptTime != QLatin1String("Hebr")) {
// remove remaining non-ASCII stuff which was not yet
// specially handled above (Keep it if the time locale is
// Chinese or Japanese or has Arabic or Hebrew script).
QString tmp;
for(int i = 0; i < icuFormatQString.size(); ++i)
if(icuFormatQString.at(i) < QChar(0x0080))
tmp.append(icuFormatQString.at(i));
icuFormatQString = tmp;
}
// remove superfluous whitespace:
icuFormatQString = icuFormatQString.simplified();
icuFormatString = MIcuConversions::qStringToUnicodeString(icuFormatQString);
static_cast<SimpleDateFormat *>(df)->applyPattern(icuFormatString);
}
}
#endif
#ifdef HAVE_ICU
void MLocalePrivate::maybeEmbedDateFormat(icu::DateFormat *df, const QString &categoryNameMessages, const QString &categoryNameTime) const
{
// If the message locale and the time locale have different script directions,
// it may happen that the date format gets reordered in an unexpected way if
// it is not used on its own but together with text from the message
// locale. Protect the date format against such unexpected reordering by
// wrapping it in RLE...PDF or LRE...PDF.
if (df) {
QString categoryScriptTime = MLocale::localeScript(categoryNameTime);
QString categoryScriptMessages = MLocale::localeScript(categoryNameMessages);
bool timeIsRtl = (categoryScriptTime == QLatin1String("Arab")
|| categoryScriptTime == QLatin1String("Hebr"));
bool messagesIsRtl = (categoryScriptMessages == QLatin1String("Arab")
|| categoryScriptMessages == QLatin1String("Hebr"));
if (timeIsRtl != messagesIsRtl) {
icu::UnicodeString icuFormatString;
QString icuFormatQString;
static_cast<SimpleDateFormat *>(df)->toPattern(icuFormatString);
icuFormatQString
= MIcuConversions::unicodeStringToQString(icuFormatString);
if(!icuFormatQString.isEmpty()) {
if (timeIsRtl && !messagesIsRtl) {
icuFormatQString.prepend(QChar(0x202B)); // RIGHT-TO-LEFT EMBEDDING
icuFormatQString.append(QChar(0x202C)); // POP DIRECTIONAL FORMATTING
}
else if (!timeIsRtl && messagesIsRtl) {
icuFormatQString.prepend(QChar(0x202A)); // LEFT-TO-RIGHT EMBEDDING
icuFormatQString.append(QChar(0x202C)); // POP DIRECTIONAL FORMATTING
}
icuFormatString
= MIcuConversions::qStringToUnicodeString(icuFormatQString);
static_cast<SimpleDateFormat *>(df)->applyPattern(icuFormatString);
}
}
}
}
#endif
QString MLocalePrivate::fixCategoryNameForNumbers(const QString &categoryName) const
{
#ifdef HAVE_ICU
Q_Q(const MLocale);
QString categoryLanguage = parseLanguage(categoryName);
// do nothing for languages other than ar, fa, hi, kn, mr, ne, pa, bn:
if(categoryLanguage != "ar"
&& categoryLanguage != "fa"
&& categoryLanguage != "hi"
&& categoryLanguage != "kn"
&& categoryLanguage != "mr"
&& categoryLanguage != "ne"
&& categoryLanguage != "pa"
&& categoryLanguage != "bn")
return categoryName;
QString numericCategoryLanguage = q->categoryLanguage(MLocale::MLcNumeric);
// if @numbers=<something> is already there, don’t touch it
// and return immediately:
if(!MIcuConversions::parseOption(categoryName, "numbers").isEmpty())
return categoryName;
if(categoryLanguage == "ar" && numericCategoryLanguage == "ar")
return MIcuConversions::setOption(categoryName, "numbers", "arab");
else if(categoryLanguage == "fa" && numericCategoryLanguage == "fa")
return MIcuConversions::setOption(categoryName, "numbers", "arabext");
else if(categoryLanguage == "hi" && numericCategoryLanguage == "hi")
return MIcuConversions::setOption(categoryName, "numbers", "deva");
else if(categoryLanguage == "kn" && numericCategoryLanguage == "kn")
return MIcuConversions::setOption(categoryName, "numbers", "knda");
else if(categoryLanguage == "mr" && numericCategoryLanguage == "mr")
return MIcuConversions::setOption(categoryName, "numbers", "deva");
else if(categoryLanguage == "ne" && numericCategoryLanguage == "ne")
return MIcuConversions::setOption(categoryName, "numbers", "deva");
else if(categoryLanguage == "or" && numericCategoryLanguage == "or")
return MIcuConversions::setOption(categoryName, "numbers", "orya");
else if(categoryLanguage == "pa" && numericCategoryLanguage == "pa")
return MIcuConversions::setOption(categoryName, "numbers", "guru");
else if(categoryLanguage == "bn" && numericCategoryLanguage == "bn")
return MIcuConversions::setOption(categoryName, "numbers", "beng");
return MIcuConversions::setOption(categoryName, "numbers", "latn");
#else
// nothing to do without ICU:
return categoryName;
#endif
}
#ifdef HAVE_ICU
QString MLocalePrivate::icuFormatString(MLocale::DateType dateType,
MLocale::TimeType timeType,
MLocale::CalendarType calendarType,
MLocale::TimeFormat24h timeFormat24h) const
{
icu::DateFormat *df = createDateFormat(dateType, timeType, calendarType, timeFormat24h);
QString icuFormatQString;
if (df)
{
icu::UnicodeString icuFormatString;
static_cast<SimpleDateFormat *>(df)->toPattern(icuFormatString);
icuFormatQString = MIcuConversions::unicodeStringToQString(icuFormatString);
}
return icuFormatQString;
}
#endif
#ifdef HAVE_ICU
bool MLocalePrivate::mixingSymbolsWanted(const QString &categoryNameMessages, const QString &categoryNameTime) const
{
QString languageMessages = parseLanguage(categoryNameMessages);
QString languageTime = parseLanguage(categoryNameTime);
QString categoryScriptTime = MLocale::localeScript(categoryNameTime);
QString categoryScriptMessages = MLocale::localeScript(categoryNameMessages);
bool timeIsRtl = (categoryScriptTime == QLatin1String("Arab")
|| categoryScriptTime == QLatin1String("Hebr"));
bool messagesIsRtl = (categoryScriptMessages == QLatin1String("Arab")
|| categoryScriptMessages == QLatin1String("Hebr"));
if (categoryNameTime.contains(QRegExp("@.*mix-time-and-language=yes"))) {
return true;
}
else if(!categoryNameTime.contains(QRegExp("@.*mix-time-and-language=no"))
&& languageMessages != languageTime
&& languageMessages != "zh"
&& languageMessages != "ja"
&& languageMessages != "ko"
&& (timeIsRtl == messagesIsRtl)) {
// mixing symbols like month name and weekday name from the
// message locale into the date format of the time locale.
// Don’t do this, if the language is the same, i.e. don’t do
// it if one locale is “zh” and the other “zh_TW” or one
// locale is “pt” and the other “pt_PT”. When the locales
// share the same language, mixing should not be necessary,
// the symbols should be understandable already.
//
// Disable the mixing *always* if the language is "zh", "ja"
// or "ko", results of mixing a CJK language with a non-CJK
// language are really weird, it is just nonsense to do this.
// (See https://projects.maemo.org/bugzilla/show_bug.cgi?id=244444)
//
// Also disable mixing *always* if the message locale and the
// time locale have use scripts with different direction, i.e.
// do not attempt to do this mixing if one of the locales has
// a right-to-left script and the other a left-to-right
// script. Mixing for locales with different script
// directions almost always gives nonsensical results, trying
// to fix this for all corner cases in
// MLocalePrivate::simplifyDateFormatForMixing() is quite
// hopeless. (See also
// https://projects.maemo.org/bugzilla/show_bug.cgi?id=270020)
return true;
}
else {
return false;
}
}
#endif
#ifdef HAVE_ICU
icu::DateFormat *MLocalePrivate::createDateFormat(MLocale::DateType dateType,
MLocale::TimeType timeType,
MLocale::CalendarType calendarType,
MLocale::TimeFormat24h timeFormat24h) const
{
QString categoryNameTime = categoryName(MLocale::MLcTime);
QString categoryNameNumeric = categoryName(MLocale::MLcNumeric);
QString categoryNameMessages = categoryName(MLocale::MLcMessages);
QString key = QString("%1_%2_%3_%4_%5_%6_%7")
.arg(dateType)
.arg(timeType)
.arg(calendarType)
.arg(timeFormat24h)
.arg(categoryNameTime)
.arg(categoryNameNumeric)
.arg(categoryNameMessages);
if (_dateFormatCache.contains(key))
return _dateFormatCache.object(key);
categoryNameTime = fixCategoryNameForNumbers(
MIcuConversions::setCalendarOption(categoryNameTime, calendarType));
categoryNameMessages = fixCategoryNameForNumbers(
MIcuConversions::setCalendarOption(categoryNameMessages, calendarType));
icu::Locale calLocale = icu::Locale(qPrintable(categoryNameTime));
icu::DateFormat::EStyle dateStyle;
icu::DateFormat::EStyle timeStyle;
if (dateType == MLocale::DateYearAndMonth
|| dateType == MLocale::DateWeekdayAbbreviatedAndDayOfMonth
|| dateType == MLocale::DateWeekdayWideAndDayOfMonth) {
// doesn’t matter really will be customized anyway
dateStyle = MIcuConversions::toEStyle(MLocale::DateFull);
timeStyle = MIcuConversions::toEStyle(MLocale::TimeNone);
}
else {
dateStyle = MIcuConversions::toEStyle(dateType);
timeStyle = MIcuConversions::toEStyle(timeType);
}
icu::DateFormat *df
= icu::DateFormat::createDateTimeInstance(dateStyle, timeStyle, calLocale);
if (dateType == MLocale::DateYearAndMonth) {
MLocalePrivate::dateFormatToYearAndMonth(df);
}
else if (dateType == MLocale::DateWeekdayAbbreviatedAndDayOfMonth) {
MLocalePrivate::dateFormatToWeekdayAbbreviatedAndDayOfMonth(df);
}
else if (dateType == MLocale::DateWeekdayWideAndDayOfMonth) {
MLocalePrivate::dateFormatToWeekdayWideAndDayOfMonth(df);
}
else if (timeType != MLocale::TimeNone) {
switch (timeFormat24h) {
case(MLocale::TwelveHourTimeFormat24h):
MLocalePrivate::dateFormatTo12h(df);
break;
case(MLocale::TwentyFourHourTimeFormat24h):
MLocalePrivate::dateFormatTo24h(df);
break;
case(MLocale::LocaleDefaultTimeFormat24h):
break;
default:
break;
}
}
if(mixingSymbolsWanted(categoryNameMessages, categoryNameTime)) {
// If we are mixing really different languages, simplify the
// date format first to make the results less bad:
MLocalePrivate::simplifyDateFormatForMixing(df);
DateFormatSymbols *dfs =
MLocalePrivate::createDateFormatSymbols(
icu::Locale(qPrintable(categoryNameMessages)));
// This is not nice but seems to be the only way to set the
// symbols with the public API
static_cast<SimpleDateFormat *>(df)->adoptDateFormatSymbols(dfs);
}
MLocalePrivate::maybeEmbedDateFormat(df, categoryNameMessages, categoryNameTime);
_dateFormatCache.insert(key, df);
return df;
}
#endif
// Constructors
MLocalePrivate::MLocalePrivate()
: _valid(true),