-
-
Notifications
You must be signed in to change notification settings - Fork 708
/
calendar.cpp
4305 lines (3811 loc) · 146 KB
/
calendar.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
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http:https://www.unicode.org/copyright.html
/*
*******************************************************************************
* Copyright (C) 1997-2016, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*
* File CALENDAR.CPP
*
* Modification History:
*
* Date Name Description
* 02/03/97 clhuang Creation.
* 04/22/97 aliu Cleaned up, fixed memory leak, made
* setWeekCountData() more robust.
* Moved platform code to TPlatformUtilities.
* 05/01/97 aliu Made equals(), before(), after() arguments const.
* 05/20/97 aliu Changed logic of when to compute fields and time
* to fix bugs.
* 08/12/97 aliu Added equivalentTo. Misc other fixes.
* 07/28/98 stephen Sync up with JDK 1.2
* 09/02/98 stephen Sync with JDK 1.2 8/31 build (getActualMin/Max)
* 03/17/99 stephen Changed adoptTimeZone() - now fAreFieldsSet is
* set to false to force update of time.
*******************************************************************************
*/
#include "utypeinfo.h" // for 'typeid' to work
#include "unicode/utypes.h"
#if !UCONFIG_NO_FORMATTING
#include "unicode/gregocal.h"
#include "unicode/basictz.h"
#include "unicode/simpletz.h"
#include "unicode/rbtz.h"
#include "unicode/vtzone.h"
#include "gregoimp.h"
#include "buddhcal.h"
#include "taiwncal.h"
#include "japancal.h"
#include "islamcal.h"
#include "hebrwcal.h"
#include "persncal.h"
#include "indiancal.h"
#include "iso8601cal.h"
#include "chnsecal.h"
#include "coptccal.h"
#include "dangical.h"
#include "ethpccal.h"
#include "unicode/calendar.h"
#include "cpputils.h"
#include "servloc.h"
#include "ucln_in.h"
#include "cstring.h"
#include "locbased.h"
#include "uresimp.h"
#include "ustrenum.h"
#include "uassert.h"
#include "olsontz.h"
#include "sharedcalendar.h"
#include "unifiedcache.h"
#include "ulocimp.h"
#include "charstr.h"
#if !UCONFIG_NO_SERVICE
static icu::ICULocaleService* gService = nullptr;
static icu::UInitOnce gServiceInitOnce {};
// INTERNAL - for cleanup
U_CDECL_BEGIN
static UBool calendar_cleanup() {
#if !UCONFIG_NO_SERVICE
if (gService) {
delete gService;
gService = nullptr;
}
gServiceInitOnce.reset();
#endif
return true;
}
U_CDECL_END
#endif
// ------------------------------------------
//
// Registration
//
//-------------------------------------------
//#define U_DEBUG_CALSVC 1
//
#if defined( U_DEBUG_CALSVC ) || defined (U_DEBUG_CAL)
/**
* fldName was removed as a duplicate implementation.
* use udbg_ services instead,
* which depend on include files and library from ../tools/toolutil, the following circular link:
* CPPFLAGS+=-I$(top_srcdir)/tools/toolutil
* LIBS+=$(LIBICUTOOLUTIL)
*/
#include "udbgutil.h"
#include <stdio.h>
/**
* convert a UCalendarDateFields into a string - for debugging
* @param f field enum
* @return static string to the field name
* @internal
*/
const char* fldName(UCalendarDateFields f) {
return udbg_enumName(UDBG_UCalendarDateFields, (int32_t)f);
}
#if UCAL_DEBUG_DUMP
// from CalendarTest::calToStr - but doesn't modify contents.
void ucal_dump(const Calendar &cal) {
cal.dump();
}
void Calendar::dump() const {
int i;
fprintf(stderr, "@calendar=%s, timeset=%c, fieldset=%c, allfields=%c, virtualset=%c, t=%.2f",
getType(), fIsTimeSet?'y':'n', fAreFieldsSet?'y':'n', fAreAllFieldsSet?'y':'n',
fAreFieldsVirtuallySet?'y':'n',
fTime);
// can add more things here: DST, zone, etc.
fprintf(stderr, "\n");
for(i = 0;i<UCAL_FIELD_COUNT;i++) {
int n;
const char *f = fldName((UCalendarDateFields)i);
fprintf(stderr, " %25s: %-11ld", f, fFields[i]);
if(fStamp[i] == kUnset) {
fprintf(stderr, " (unset) ");
} else if(fStamp[i] == kInternallySet) {
fprintf(stderr, " (internally set) ");
//} else if(fStamp[i] == kInternalDefault) {
// fprintf(stderr, " (internal default) ");
} else {
fprintf(stderr, " %%%d ", fStamp[i]);
}
fprintf(stderr, "\n");
}
}
U_CFUNC void ucal_dump(UCalendar* cal) {
ucal_dump( *((Calendar*)cal) );
}
#endif
#endif
/* Max value for stamp allowable before recalculation */
#define STAMP_MAX 10000
static const char * const gCalTypes[] = {
"gregorian",
"japanese",
"buddhist",
"roc",
"persian",
"islamic-civil",
"islamic",
"hebrew",
"chinese",
"indian",
"coptic",
"ethiopic",
"ethiopic-amete-alem",
"iso8601",
"dangi",
"islamic-umalqura",
"islamic-tbla",
"islamic-rgsa",
nullptr
};
// Must be in the order of gCalTypes above
typedef enum ECalType {
CALTYPE_UNKNOWN = -1,
CALTYPE_GREGORIAN = 0,
CALTYPE_JAPANESE,
CALTYPE_BUDDHIST,
CALTYPE_ROC,
CALTYPE_PERSIAN,
CALTYPE_ISLAMIC_CIVIL,
CALTYPE_ISLAMIC,
CALTYPE_HEBREW,
CALTYPE_CHINESE,
CALTYPE_INDIAN,
CALTYPE_COPTIC,
CALTYPE_ETHIOPIC,
CALTYPE_ETHIOPIC_AMETE_ALEM,
CALTYPE_ISO8601,
CALTYPE_DANGI,
CALTYPE_ISLAMIC_UMALQURA,
CALTYPE_ISLAMIC_TBLA,
CALTYPE_ISLAMIC_RGSA
} ECalType;
U_NAMESPACE_BEGIN
SharedCalendar::~SharedCalendar() {
delete ptr;
}
template<> U_I18N_API
const SharedCalendar *LocaleCacheKey<SharedCalendar>::createObject(
const void * /*unusedCreationContext*/, UErrorCode &status) const {
if (U_FAILURE(status)) {
return nullptr;
}
Calendar *calendar = Calendar::makeInstance(fLoc, status);
if (U_FAILURE(status)) {
return nullptr;
}
SharedCalendar *shared = new SharedCalendar(calendar);
if (shared == nullptr) {
delete calendar;
status = U_MEMORY_ALLOCATION_ERROR;
return nullptr;
}
shared->addRef();
return shared;
}
static ECalType getCalendarType(const char *s) {
for (int i = 0; gCalTypes[i] != nullptr; i++) {
if (uprv_stricmp(s, gCalTypes[i]) == 0) {
return (ECalType)i;
}
}
return CALTYPE_UNKNOWN;
}
#if !UCONFIG_NO_SERVICE
// Only used with service registration.
static UBool isStandardSupportedKeyword(const char *keyword, UErrorCode& status) {
if(U_FAILURE(status)) {
return false;
}
ECalType calType = getCalendarType(keyword);
return (calType != CALTYPE_UNKNOWN);
}
#endif
static ECalType getCalendarTypeForLocale(const char *locid) {
UErrorCode status = U_ZERO_ERROR;
ECalType calType = CALTYPE_UNKNOWN;
// Canonicalize, so that an old-style variant will be transformed to keywords.
// e.g ja_JP_TRADITIONAL -> ja_JP@calendar=japanese
// NOTE: Since ICU-20187, ja_JP_TRADITIONAL no longer canonicalizes, and
// the Gregorian calendar is returned instead.
CharString canonicalName = ulocimp_canonicalize(locid, status);
if (U_FAILURE(status)) {
return CALTYPE_GREGORIAN;
}
CharString calTypeBuf = ulocimp_getKeywordValue(canonicalName.data(), "calendar", status);
if (U_SUCCESS(status)) {
calType = getCalendarType(calTypeBuf.data());
if (calType != CALTYPE_UNKNOWN) {
return calType;
}
}
status = U_ZERO_ERROR;
// when calendar keyword is not available or not supported, read supplementalData
// to get the default calendar type for the locale's region
CharString region = ulocimp_getRegionForSupplementalData(canonicalName.data(), true, status);
if (U_FAILURE(status)) {
return CALTYPE_GREGORIAN;
}
// Read preferred calendar values from supplementalData calendarPreference
UResourceBundle *rb = ures_openDirect(nullptr, "supplementalData", &status);
ures_getByKey(rb, "calendarPreferenceData", rb, &status);
UResourceBundle *order = ures_getByKey(rb, region.data(), nullptr, &status);
if (status == U_MISSING_RESOURCE_ERROR && rb != nullptr) {
status = U_ZERO_ERROR;
order = ures_getByKey(rb, "001", nullptr, &status);
}
calTypeBuf.clear();
if (U_SUCCESS(status) && order != nullptr) {
// the first calendar type is the default for the region
int32_t len = 0;
const char16_t *uCalType = ures_getStringByIndex(order, 0, &len, &status);
calTypeBuf.appendInvariantChars(uCalType, len, status);
calType = getCalendarType(calTypeBuf.data());
}
ures_close(order);
ures_close(rb);
if (calType == CALTYPE_UNKNOWN) {
// final fallback
calType = CALTYPE_GREGORIAN;
}
return calType;
}
static Calendar *createStandardCalendar(ECalType calType, const Locale &loc, UErrorCode& status) {
if (U_FAILURE(status)) {
return nullptr;
}
LocalPointer<Calendar> cal;
switch (calType) {
case CALTYPE_GREGORIAN:
cal.adoptInsteadAndCheckErrorCode(new GregorianCalendar(loc, status), status);
break;
case CALTYPE_JAPANESE:
cal.adoptInsteadAndCheckErrorCode(new JapaneseCalendar(loc, status), status);
break;
case CALTYPE_BUDDHIST:
cal.adoptInsteadAndCheckErrorCode(new BuddhistCalendar(loc, status), status);
break;
case CALTYPE_ROC:
cal.adoptInsteadAndCheckErrorCode(new TaiwanCalendar(loc, status), status);
break;
case CALTYPE_PERSIAN:
cal.adoptInsteadAndCheckErrorCode(new PersianCalendar(loc, status), status);
break;
case CALTYPE_ISLAMIC_TBLA:
cal.adoptInsteadAndCheckErrorCode(new IslamicTBLACalendar(loc, status), status);
break;
case CALTYPE_ISLAMIC_CIVIL:
cal.adoptInsteadAndCheckErrorCode(new IslamicCivilCalendar(loc, status), status);
break;
case CALTYPE_ISLAMIC_RGSA:
cal.adoptInsteadAndCheckErrorCode(new IslamicRGSACalendar(loc, status), status);
break;
case CALTYPE_ISLAMIC:
cal.adoptInsteadAndCheckErrorCode(new IslamicCalendar(loc, status), status);
break;
case CALTYPE_ISLAMIC_UMALQURA:
cal.adoptInsteadAndCheckErrorCode(new IslamicUmalquraCalendar(loc, status), status);
break;
case CALTYPE_HEBREW:
cal.adoptInsteadAndCheckErrorCode(new HebrewCalendar(loc, status), status);
break;
case CALTYPE_CHINESE:
cal.adoptInsteadAndCheckErrorCode(new ChineseCalendar(loc, status), status);
break;
case CALTYPE_INDIAN:
cal.adoptInsteadAndCheckErrorCode(new IndianCalendar(loc, status), status);
break;
case CALTYPE_COPTIC:
cal.adoptInsteadAndCheckErrorCode(new CopticCalendar(loc, status), status);
break;
case CALTYPE_ETHIOPIC:
cal.adoptInsteadAndCheckErrorCode(new EthiopicCalendar(loc, status), status);
break;
case CALTYPE_ETHIOPIC_AMETE_ALEM:
cal.adoptInsteadAndCheckErrorCode(new EthiopicAmeteAlemCalendar(loc, status), status);
break;
case CALTYPE_ISO8601:
cal.adoptInsteadAndCheckErrorCode(new ISO8601Calendar(loc, status), status);
break;
case CALTYPE_DANGI:
cal.adoptInsteadAndCheckErrorCode(new DangiCalendar(loc, status), status);
break;
default:
status = U_UNSUPPORTED_ERROR;
}
return cal.orphan();
}
#if !UCONFIG_NO_SERVICE
// -------------------------------------
/**
* a Calendar Factory which creates the "basic" calendar types, that is, those
* shipped with ICU.
*/
class BasicCalendarFactory : public LocaleKeyFactory {
public:
/**
* @param calendarType static const string (caller owns storage - will be aliased) to calendar type
*/
BasicCalendarFactory()
: LocaleKeyFactory(LocaleKeyFactory::INVISIBLE) { }
virtual ~BasicCalendarFactory();
protected:
//virtual UBool isSupportedID( const UnicodeString& id, UErrorCode& status) const {
// if(U_FAILURE(status)) {
// return false;
// }
// char keyword[ULOC_FULLNAME_CAPACITY];
// getCalendarKeyword(id, keyword, (int32_t)sizeof(keyword));
// return isStandardSupportedKeyword(keyword, status);
//}
virtual void updateVisibleIDs(Hashtable& result, UErrorCode& status) const override
{
if (U_SUCCESS(status)) {
for(int32_t i=0;gCalTypes[i] != nullptr;i++) {
UnicodeString id((char16_t)0x40); /* '@' a variant character */
id.append(UNICODE_STRING_SIMPLE("calendar="));
id.append(UnicodeString(gCalTypes[i], -1, US_INV));
result.put(id, (void*)this, status);
}
}
}
virtual UObject* create(const ICUServiceKey& key, const ICUService* /*service*/, UErrorCode& status) const override {
if (U_FAILURE(status)) {
return nullptr;
}
#ifdef U_DEBUG_CALSVC
if(dynamic_cast<const LocaleKey*>(&key) == nullptr) {
fprintf(stderr, "::create - not a LocaleKey!\n");
}
#endif
const LocaleKey* lkey = dynamic_cast<const LocaleKey*>(&key);
U_ASSERT(lkey != nullptr);
Locale curLoc; // current locale
Locale canLoc; // Canonical locale
lkey->currentLocale(curLoc);
lkey->canonicalLocale(canLoc);
char keyword[ULOC_FULLNAME_CAPACITY];
curLoc.getKeywordValue("calendar", keyword, (int32_t) sizeof(keyword), status);
#ifdef U_DEBUG_CALSVC
fprintf(stderr, "BasicCalendarFactory::create() - cur %s, can %s\n", (const char*)curLoc.getName(), (const char*)canLoc.getName());
#endif
if(!isStandardSupportedKeyword(keyword,status)) { // Do we handle this type?
#ifdef U_DEBUG_CALSVC
fprintf(stderr, "BasicCalendarFactory - not handling %s.[%s]\n", (const char*) curLoc.getName(), tmp );
#endif
return nullptr;
}
return createStandardCalendar(getCalendarType(keyword), canLoc, status);
}
};
BasicCalendarFactory::~BasicCalendarFactory() {}
/**
* A factory which looks up the DefaultCalendar resource to determine which class of calendar to use
*/
class DefaultCalendarFactory : public ICUResourceBundleFactory {
public:
DefaultCalendarFactory() : ICUResourceBundleFactory() { }
virtual ~DefaultCalendarFactory();
protected:
virtual UObject* create(const ICUServiceKey& key, const ICUService* /*service*/, UErrorCode& status) const override {
if (U_FAILURE(status)) {
return nullptr;
}
const LocaleKey *lkey = dynamic_cast<const LocaleKey*>(&key);
U_ASSERT(lkey != nullptr);
Locale loc;
lkey->currentLocale(loc);
UnicodeString *ret = new UnicodeString();
if (ret == nullptr) {
status = U_MEMORY_ALLOCATION_ERROR;
} else {
ret->append((char16_t)0x40); // '@' is a variant character
ret->append(UNICODE_STRING("calendar=", 9));
ret->append(UnicodeString(gCalTypes[getCalendarTypeForLocale(loc.getName())], -1, US_INV));
}
return ret;
}
};
DefaultCalendarFactory::~DefaultCalendarFactory() {}
// -------------------------------------
class CalendarService : public ICULocaleService {
public:
CalendarService()
: ICULocaleService(UNICODE_STRING_SIMPLE("Calendar"))
{
UErrorCode status = U_ZERO_ERROR;
registerFactory(new DefaultCalendarFactory(), status);
}
virtual ~CalendarService();
virtual UObject* cloneInstance(UObject* instance) const override {
UnicodeString *s = dynamic_cast<UnicodeString *>(instance);
if(s != nullptr) {
return s->clone();
} else {
#ifdef U_DEBUG_CALSVC_F
UErrorCode status2 = U_ZERO_ERROR;
fprintf(stderr, "Cloning a %s calendar with tz=%ld\n", ((Calendar*)instance)->getType(), ((Calendar*)instance)->get(UCAL_ZONE_OFFSET, status2));
#endif
return ((Calendar*)instance)->clone();
}
}
virtual UObject* handleDefault(const ICUServiceKey& key, UnicodeString* /*actualID*/, UErrorCode& status) const override {
if (U_FAILURE(status)) {
return nullptr;
}
LocaleKey& lkey = static_cast<LocaleKey&>(const_cast<ICUServiceKey&>(key));
//int32_t kind = lkey.kind();
Locale loc;
lkey.canonicalLocale(loc);
#ifdef U_DEBUG_CALSVC
Locale loc2;
lkey.currentLocale(loc2);
fprintf(stderr, "CalSvc:handleDefault for currentLoc %s, canloc %s\n", (const char*)loc.getName(), (const char*)loc2.getName());
#endif
Calendar *nc = new GregorianCalendar(loc, status);
if (nc == nullptr) {
status = U_MEMORY_ALLOCATION_ERROR;
return nc;
}
#ifdef U_DEBUG_CALSVC
UErrorCode status2 = U_ZERO_ERROR;
fprintf(stderr, "New default calendar has tz=%d\n", ((Calendar*)nc)->get(UCAL_ZONE_OFFSET, status2));
#endif
return nc;
}
virtual UBool isDefault() const override {
return countFactories() == 1;
}
};
CalendarService::~CalendarService() {}
// -------------------------------------
static inline UBool
isCalendarServiceUsed() {
return !gServiceInitOnce.isReset();
}
// -------------------------------------
static void U_CALLCONV
initCalendarService(UErrorCode &status)
{
#ifdef U_DEBUG_CALSVC
fprintf(stderr, "Spinning up Calendar Service\n");
#endif
if (U_FAILURE(status)) {
return;
}
ucln_i18n_registerCleanup(UCLN_I18N_CALENDAR, calendar_cleanup);
gService = new CalendarService();
if (gService == nullptr) {
status = U_MEMORY_ALLOCATION_ERROR;
return;
}
#ifdef U_DEBUG_CALSVC
fprintf(stderr, "Registering classes..\n");
#endif
// Register all basic instances.
gService->registerFactory(new BasicCalendarFactory(),status);
#ifdef U_DEBUG_CALSVC
fprintf(stderr, "Done..\n");
#endif
if(U_FAILURE(status)) {
#ifdef U_DEBUG_CALSVC
fprintf(stderr, "err (%s) registering classes, deleting service.....\n", u_errorName(status));
#endif
delete gService;
gService = nullptr;
}
}
static ICULocaleService*
getCalendarService(UErrorCode &status)
{
umtx_initOnce(gServiceInitOnce, &initCalendarService, status);
return gService;
}
URegistryKey Calendar::registerFactory(ICUServiceFactory* toAdopt, UErrorCode& status)
{
return getCalendarService(status)->registerFactory(toAdopt, status);
}
UBool Calendar::unregister(URegistryKey key, UErrorCode& status) {
return getCalendarService(status)->unregister(key, status);
}
#endif /* UCONFIG_NO_SERVICE */
// -------------------------------------
static const int32_t kCalendarLimits[UCAL_FIELD_COUNT][4] = {
// Minimum Greatest min Least max Greatest max
{/*N/A*/-1, /*N/A*/-1, /*N/A*/-1, /*N/A*/-1}, // ERA
{/*N/A*/-1, /*N/A*/-1, /*N/A*/-1, /*N/A*/-1}, // YEAR
{/*N/A*/-1, /*N/A*/-1, /*N/A*/-1, /*N/A*/-1}, // MONTH
{/*N/A*/-1, /*N/A*/-1, /*N/A*/-1, /*N/A*/-1}, // WEEK_OF_YEAR
{/*N/A*/-1, /*N/A*/-1, /*N/A*/-1, /*N/A*/-1}, // WEEK_OF_MONTH
{/*N/A*/-1, /*N/A*/-1, /*N/A*/-1, /*N/A*/-1}, // DAY_OF_MONTH
{/*N/A*/-1, /*N/A*/-1, /*N/A*/-1, /*N/A*/-1}, // DAY_OF_YEAR
{ 1, 1, 7, 7 }, // DAY_OF_WEEK
{/*N/A*/-1, /*N/A*/-1, /*N/A*/-1, /*N/A*/-1}, // DAY_OF_WEEK_IN_MONTH
{ 0, 0, 1, 1 }, // AM_PM
{ 0, 0, 11, 11 }, // HOUR
{ 0, 0, 23, 23 }, // HOUR_OF_DAY
{ 0, 0, 59, 59 }, // MINUTE
{ 0, 0, 59, 59 }, // SECOND
{ 0, 0, 999, 999 }, // MILLISECOND
{-24*kOneHour, -16*kOneHour, 12*kOneHour, 30*kOneHour }, // ZONE_OFFSET
{ -1*kOneHour, -1*kOneHour, 2*kOneHour, 2*kOneHour }, // DST_OFFSET
{/*N/A*/-1, /*N/A*/-1, /*N/A*/-1, /*N/A*/-1}, // YEAR_WOY
{ 1, 1, 7, 7 }, // DOW_LOCAL
{/*N/A*/-1, /*N/A*/-1, /*N/A*/-1, /*N/A*/-1}, // EXTENDED_YEAR
{ -0x7F000000, -0x7F000000, 0x7F000000, 0x7F000000 }, // JULIAN_DAY
{ 0, 0, 24*kOneHour-1, 24*kOneHour-1 }, // MILLISECONDS_IN_DAY
{ 0, 0, 1, 1 }, // IS_LEAP_MONTH
{ 0, 0, 11, 11 } // ORDINAL_MONTH
};
// Resource bundle tags read by this class
static const char gCalendar[] = "calendar";
static const char gMonthNames[] = "monthNames";
static const char gGregorian[] = "gregorian";
// Data flow in Calendar
// ---------------------
// The current time is represented in two ways by Calendar: as UTC
// milliseconds from the epoch start (1 January 1970 0:00 UTC), and as local
// fields such as MONTH, HOUR, AM_PM, etc. It is possible to compute the
// millis from the fields, and vice versa. The data needed to do this
// conversion is encapsulated by a TimeZone object owned by the Calendar.
// The data provided by the TimeZone object may also be overridden if the
// user sets the ZONE_OFFSET and/or DST_OFFSET fields directly. The class
// keeps track of what information was most recently set by the caller, and
// uses that to compute any other information as needed.
// If the user sets the fields using set(), the data flow is as follows.
// This is implemented by the Calendar subclass's computeTime() method.
// During this process, certain fields may be ignored. The disambiguation
// algorithm for resolving which fields to pay attention to is described
// above.
// local fields (YEAR, MONTH, DATE, HOUR, MINUTE, etc.)
// |
// | Using Calendar-specific algorithm
// V
// local standard millis
// |
// | Using TimeZone or user-set ZONE_OFFSET / DST_OFFSET
// V
// UTC millis (in time data member)
// If the user sets the UTC millis using setTime(), the data flow is as
// follows. This is implemented by the Calendar subclass's computeFields()
// method.
// UTC millis (in time data member)
// |
// | Using TimeZone getOffset()
// V
// local standard millis
// |
// | Using Calendar-specific algorithm
// V
// local fields (YEAR, MONTH, DATE, HOUR, MINUTE, etc.)
// In general, a round trip from fields, through local and UTC millis, and
// back out to fields is made when necessary. This is implemented by the
// complete() method. Resolving a partial set of fields into a UTC millis
// value allows all remaining fields to be generated from that value. If
// the Calendar is lenient, the fields are also renormalized to standard
// ranges when they are regenerated.
// -------------------------------------
Calendar::Calendar(UErrorCode& success)
: UObject(),
fIsTimeSet(false),
fAreFieldsSet(false),
fAreAllFieldsSet(false),
fAreFieldsVirtuallySet(false),
fNextStamp((int32_t)kMinimumUserStamp),
fTime(0),
fLenient(true),
fZone(nullptr),
fRepeatedWallTime(UCAL_WALLTIME_LAST),
fSkippedWallTime(UCAL_WALLTIME_LAST)
{
validLocale[0] = 0;
actualLocale[0] = 0;
clear();
if (U_FAILURE(success)) {
return;
}
fZone = TimeZone::createDefault();
if (fZone == nullptr) {
success = U_MEMORY_ALLOCATION_ERROR;
}
setWeekData(Locale::getDefault(), nullptr, success);
}
// -------------------------------------
Calendar::Calendar(TimeZone* zone, const Locale& aLocale, UErrorCode& success)
: UObject(),
fIsTimeSet(false),
fAreFieldsSet(false),
fAreAllFieldsSet(false),
fAreFieldsVirtuallySet(false),
fNextStamp((int32_t)kMinimumUserStamp),
fTime(0),
fLenient(true),
fZone(nullptr),
fRepeatedWallTime(UCAL_WALLTIME_LAST),
fSkippedWallTime(UCAL_WALLTIME_LAST)
{
validLocale[0] = 0;
actualLocale[0] = 0;
if (U_FAILURE(success)) {
delete zone;
return;
}
if (zone == nullptr) {
#if defined (U_DEBUG_CAL)
fprintf(stderr, "%s:%d: ILLEGAL ARG because timezone cannot be 0\n",
__FILE__, __LINE__);
#endif
success = U_ILLEGAL_ARGUMENT_ERROR;
return;
}
clear();
fZone = zone;
setWeekData(aLocale, nullptr, success);
}
// -------------------------------------
Calendar::Calendar(const TimeZone& zone, const Locale& aLocale, UErrorCode& success)
: UObject(),
fIsTimeSet(false),
fAreFieldsSet(false),
fAreAllFieldsSet(false),
fAreFieldsVirtuallySet(false),
fNextStamp((int32_t)kMinimumUserStamp),
fTime(0),
fLenient(true),
fZone(nullptr),
fRepeatedWallTime(UCAL_WALLTIME_LAST),
fSkippedWallTime(UCAL_WALLTIME_LAST)
{
validLocale[0] = 0;
actualLocale[0] = 0;
if (U_FAILURE(success)) {
return;
}
clear();
fZone = zone.clone();
if (fZone == nullptr) {
success = U_MEMORY_ALLOCATION_ERROR;
}
setWeekData(aLocale, nullptr, success);
}
// -------------------------------------
Calendar::~Calendar()
{
delete fZone;
}
// -------------------------------------
Calendar::Calendar(const Calendar &source)
: UObject(source)
{
fZone = nullptr;
*this = source;
}
// -------------------------------------
Calendar &
Calendar::operator=(const Calendar &right)
{
if (this != &right) {
uprv_arrayCopy(right.fFields, fFields, UCAL_FIELD_COUNT);
uprv_arrayCopy(right.fIsSet, fIsSet, UCAL_FIELD_COUNT);
uprv_arrayCopy(right.fStamp, fStamp, UCAL_FIELD_COUNT);
fTime = right.fTime;
fIsTimeSet = right.fIsTimeSet;
fAreAllFieldsSet = right.fAreAllFieldsSet;
fAreFieldsSet = right.fAreFieldsSet;
fAreFieldsVirtuallySet = right.fAreFieldsVirtuallySet;
fLenient = right.fLenient;
fRepeatedWallTime = right.fRepeatedWallTime;
fSkippedWallTime = right.fSkippedWallTime;
delete fZone;
fZone = nullptr;
if (right.fZone != nullptr) {
fZone = right.fZone->clone();
}
fFirstDayOfWeek = right.fFirstDayOfWeek;
fMinimalDaysInFirstWeek = right.fMinimalDaysInFirstWeek;
fWeekendOnset = right.fWeekendOnset;
fWeekendOnsetMillis = right.fWeekendOnsetMillis;
fWeekendCease = right.fWeekendCease;
fWeekendCeaseMillis = right.fWeekendCeaseMillis;
fNextStamp = right.fNextStamp;
uprv_strncpy(validLocale, right.validLocale, sizeof(validLocale));
uprv_strncpy(actualLocale, right.actualLocale, sizeof(actualLocale));
validLocale[sizeof(validLocale)-1] = 0;
actualLocale[sizeof(validLocale)-1] = 0;
}
return *this;
}
// -------------------------------------
Calendar* U_EXPORT2
Calendar::createInstance(UErrorCode& success)
{
return createInstance(TimeZone::createDefault(), Locale::getDefault(), success);
}
// -------------------------------------
Calendar* U_EXPORT2
Calendar::createInstance(const TimeZone& zone, UErrorCode& success)
{
return createInstance(zone, Locale::getDefault(), success);
}
// -------------------------------------
Calendar* U_EXPORT2
Calendar::createInstance(const Locale& aLocale, UErrorCode& success)
{
return createInstance(TimeZone::forLocaleOrDefault(aLocale), aLocale, success);
}
// ------------------------------------- Adopting
// Note: this is the bottleneck that actually calls the service routines.
Calendar * U_EXPORT2
Calendar::makeInstance(const Locale& aLocale, UErrorCode& success) {
if (U_FAILURE(success)) {
return nullptr;
}
Locale actualLoc;
UObject* u = nullptr;
#if !UCONFIG_NO_SERVICE
if (isCalendarServiceUsed()) {
u = getCalendarService(success)->get(aLocale, LocaleKey::KIND_ANY, &actualLoc, success);
}
else
#endif
{
u = createStandardCalendar(getCalendarTypeForLocale(aLocale.getName()), aLocale, success);
}
Calendar* c = nullptr;
if(U_FAILURE(success) || !u) {
if(U_SUCCESS(success)) { // Propagate some kind of err
success = U_INTERNAL_PROGRAM_ERROR;
}
return nullptr;
}
#if !UCONFIG_NO_SERVICE
const UnicodeString* str = dynamic_cast<const UnicodeString*>(u);
if(str != nullptr) {
// It's a unicode string telling us what type of calendar to load ("gregorian", etc)
// Create a Locale over this string
Locale l("");
LocaleUtility::initLocaleFromName(*str, l);
#ifdef U_DEBUG_CALSVC
fprintf(stderr, "Calendar::createInstance(%s), looking up [%s]\n", aLocale.getName(), l.getName());
#endif
Locale actualLoc2;
delete u;
u = nullptr;
// Don't overwrite actualLoc, since the actual loc from this call
// may be something like "@calendar=gregorian" -- TODO investigate
// further...
c = (Calendar*)getCalendarService(success)->get(l, LocaleKey::KIND_ANY, &actualLoc2, success);
if(U_FAILURE(success) || !c) {
if(U_SUCCESS(success)) {
success = U_INTERNAL_PROGRAM_ERROR; // Propagate some err
}
return nullptr;
}
str = dynamic_cast<const UnicodeString*>(c);
if(str != nullptr) {
// recursed! Second lookup returned a UnicodeString.
// Perhaps DefaultCalendar{} was set to another locale.
#ifdef U_DEBUG_CALSVC
char tmp[200];
// Extract a char* out of it..
int32_t len = str->length();
int32_t actLen = sizeof(tmp)-1;
if(len > actLen) {
len = actLen;
}
str->extract(0,len,tmp);
tmp[len]=0;
fprintf(stderr, "err - recursed, 2nd lookup was unistring %s\n", tmp);
#endif
success = U_MISSING_RESOURCE_ERROR; // requested a calendar type which could NOT be found.
delete c;
return nullptr;
}
#ifdef U_DEBUG_CALSVC
fprintf(stderr, "%p: setting week count data to locale %s, actual locale %s\n", c, (const char*)aLocale.getName(), (const char *)actualLoc.getName());
#endif
c->setWeekData(aLocale, c->getType(), success); // set the correct locale (this was an indirect calendar)
char keyword[ULOC_FULLNAME_CAPACITY] = "";
UErrorCode tmpStatus = U_ZERO_ERROR;
l.getKeywordValue("calendar", keyword, ULOC_FULLNAME_CAPACITY, tmpStatus);
if (U_SUCCESS(tmpStatus) && uprv_strcmp(keyword, "iso8601") == 0) {
c->setFirstDayOfWeek(UCAL_MONDAY);
c->setMinimalDaysInFirstWeek(4);
}
}
else
#endif /* UCONFIG_NO_SERVICE */
{
// a calendar was returned - we assume the factory did the right thing.
c = (Calendar*)u;
}
return c;
}
Calendar* U_EXPORT2
Calendar::createInstance(TimeZone* zone, const Locale& aLocale, UErrorCode& success)
{
LocalPointer<TimeZone> zonePtr(zone);
const SharedCalendar *shared = nullptr;
UnifiedCache::getByLocale(aLocale, shared, success);
if (U_FAILURE(success)) {
return nullptr;
}
Calendar *c = (*shared)->clone();
shared->removeRef();
if (c == nullptr) {
success = U_MEMORY_ALLOCATION_ERROR;
return nullptr;
}
// Now, reset calendar to default state:
c->adoptTimeZone(zonePtr.orphan()); // Set the correct time zone
c->setTimeInMillis(getNow(), success); // let the new calendar have the current time.
return c;
}
// -------------------------------------
Calendar* U_EXPORT2
Calendar::createInstance(const TimeZone& zone, const Locale& aLocale, UErrorCode& success)
{
Calendar* c = createInstance(aLocale, success);
if(U_SUCCESS(success) && c) {
c->setTimeZone(zone);
}
return c;
}