1 // © 2016 and later: Unicode, Inc. and others.
2 // License & terms of use: http://www.unicode.org/copyright.html
3 /*
4 **********************************************************************
5 * Copyright (c) 2004-2016, International Business Machines
6 * Corporation and others. All Rights Reserved.
7 **********************************************************************
8 * Author: Alan Liu
9 * Created: April 20, 2004
10 * Since: ICU 3.0
11 **********************************************************************
12 */
13 #include "utypeinfo.h" // for 'typeid' to work
14 #include "unicode/utypes.h"
15
16 #if !UCONFIG_NO_FORMATTING
17
18 #include "unicode/measfmt.h"
19 #include "unicode/numfmt.h"
20 #include "currfmt.h"
21 #include "unicode/localpointer.h"
22 #include "resource.h"
23 #include "unicode/simpleformatter.h"
24 #include "quantityformatter.h"
25 #include "unicode/plurrule.h"
26 #include "unicode/decimfmt.h"
27 #include "uresimp.h"
28 #include "unicode/ures.h"
29 #include "unicode/ustring.h"
30 #include "ureslocs.h"
31 #include "cstring.h"
32 #include "mutex.h"
33 #include "ucln_in.h"
34 #include "unicode/listformatter.h"
35 #include "charstr.h"
36 #include "unicode/putil.h"
37 #include "unicode/smpdtfmt.h"
38 #include "uassert.h"
39 #include "unicode/numberformatter.h"
40 #include "number_longnames.h"
41 #include "number_utypes.h"
42
43 #include "sharednumberformat.h"
44 #include "sharedpluralrules.h"
45 #include "standardplural.h"
46 #include "unifiedcache.h"
47
48
49 U_NAMESPACE_BEGIN
50
51 using number::impl::UFormattedNumberData;
52
53 static constexpr int32_t WIDTH_INDEX_COUNT = UMEASFMT_WIDTH_NARROW + 1;
54
55 UOBJECT_DEFINE_RTTI_IMPLEMENTATION(MeasureFormat)
56
57 // Used to format durations like 5:47 or 21:35:42.
58 class NumericDateFormatters : public UMemory {
59 public:
60 // Formats like H:mm
61 UnicodeString hourMinute;
62
63 // formats like M:ss
64 UnicodeString minuteSecond;
65
66 // formats like H:mm:ss
67 UnicodeString hourMinuteSecond;
68
69 // Constructor that takes the actual patterns for hour-minute,
70 // minute-second, and hour-minute-second respectively.
NumericDateFormatters(const UnicodeString & hm,const UnicodeString & ms,const UnicodeString & hms)71 NumericDateFormatters(
72 const UnicodeString &hm,
73 const UnicodeString &ms,
74 const UnicodeString &hms) :
75 hourMinute(hm),
76 minuteSecond(ms),
77 hourMinuteSecond(hms) {
78 }
79 private:
80 NumericDateFormatters(const NumericDateFormatters &other);
81 NumericDateFormatters &operator=(const NumericDateFormatters &other);
82 };
83
getRegularWidth(UMeasureFormatWidth width)84 static UMeasureFormatWidth getRegularWidth(UMeasureFormatWidth width) {
85 if (width >= WIDTH_INDEX_COUNT) {
86 return UMEASFMT_WIDTH_NARROW;
87 }
88 return width;
89 }
90
getUnitWidth(UMeasureFormatWidth width)91 static UNumberUnitWidth getUnitWidth(UMeasureFormatWidth width) {
92 switch (width) {
93 case UMEASFMT_WIDTH_WIDE:
94 return UNUM_UNIT_WIDTH_FULL_NAME;
95 case UMEASFMT_WIDTH_NARROW:
96 case UMEASFMT_WIDTH_NUMERIC:
97 return UNUM_UNIT_WIDTH_NARROW;
98 case UMEASFMT_WIDTH_SHORT:
99 default:
100 return UNUM_UNIT_WIDTH_SHORT;
101 }
102 }
103
104 /**
105 * Instances contain all MeasureFormat specific data for a particular locale.
106 * This data is cached. It is never copied, but is shared via shared pointers.
107 *
108 * Note: We might change the cache data to have an array[WIDTH_INDEX_COUNT] of
109 * complete sets of unit & per patterns,
110 * to correspond to the resource data and its aliases.
111 *
112 * TODO: Maybe store more sparsely in general, with pointers rather than potentially-empty objects.
113 */
114 class MeasureFormatCacheData : public SharedObject {
115 public:
116
117 /**
118 * Redirection data from root-bundle, top-level sideways aliases.
119 * - UMEASFMT_WIDTH_COUNT: initial value, just fall back to root
120 * - UMEASFMT_WIDTH_WIDE/SHORT/NARROW: sideways alias for missing data
121 */
122 UMeasureFormatWidth widthFallback[WIDTH_INDEX_COUNT];
123
124 MeasureFormatCacheData();
125 virtual ~MeasureFormatCacheData();
126
adoptCurrencyFormat(int32_t widthIndex,NumberFormat * nfToAdopt)127 void adoptCurrencyFormat(int32_t widthIndex, NumberFormat *nfToAdopt) {
128 delete currencyFormats[widthIndex];
129 currencyFormats[widthIndex] = nfToAdopt;
130 }
getCurrencyFormat(UMeasureFormatWidth width) const131 const NumberFormat *getCurrencyFormat(UMeasureFormatWidth width) const {
132 return currencyFormats[getRegularWidth(width)];
133 }
adoptIntegerFormat(NumberFormat * nfToAdopt)134 void adoptIntegerFormat(NumberFormat *nfToAdopt) {
135 delete integerFormat;
136 integerFormat = nfToAdopt;
137 }
getIntegerFormat() const138 const NumberFormat *getIntegerFormat() const {
139 return integerFormat;
140 }
adoptNumericDateFormatters(NumericDateFormatters * formattersToAdopt)141 void adoptNumericDateFormatters(NumericDateFormatters *formattersToAdopt) {
142 delete numericDateFormatters;
143 numericDateFormatters = formattersToAdopt;
144 }
getNumericDateFormatters() const145 const NumericDateFormatters *getNumericDateFormatters() const {
146 return numericDateFormatters;
147 }
148
149 private:
150 NumberFormat* currencyFormats[WIDTH_INDEX_COUNT];
151 NumberFormat* integerFormat;
152 NumericDateFormatters* numericDateFormatters;
153
154 MeasureFormatCacheData(const MeasureFormatCacheData &other);
155 MeasureFormatCacheData &operator=(const MeasureFormatCacheData &other);
156 };
157
MeasureFormatCacheData()158 MeasureFormatCacheData::MeasureFormatCacheData()
159 : integerFormat(nullptr), numericDateFormatters(nullptr) {
160 for (int32_t i = 0; i < WIDTH_INDEX_COUNT; ++i) {
161 widthFallback[i] = UMEASFMT_WIDTH_COUNT;
162 }
163 memset(currencyFormats, 0, sizeof(currencyFormats));
164 }
165
~MeasureFormatCacheData()166 MeasureFormatCacheData::~MeasureFormatCacheData() {
167 for (int32_t i = 0; i < UPRV_LENGTHOF(currencyFormats); ++i) {
168 delete currencyFormats[i];
169 }
170 // Note: the contents of 'dnams' are pointers into the resource bundle
171 delete integerFormat;
172 delete numericDateFormatters;
173 }
174
isCurrency(const MeasureUnit & unit)175 static UBool isCurrency(const MeasureUnit &unit) {
176 return (uprv_strcmp(unit.getType(), "currency") == 0);
177 }
178
getString(const UResourceBundle * resource,UnicodeString & result,UErrorCode & status)179 static UBool getString(
180 const UResourceBundle *resource,
181 UnicodeString &result,
182 UErrorCode &status) {
183 int32_t len = 0;
184 const UChar *resStr = ures_getString(resource, &len, &status);
185 if (U_FAILURE(status)) {
186 return FALSE;
187 }
188 result.setTo(TRUE, resStr, len);
189 return TRUE;
190 }
191
loadNumericDateFormatterPattern(const UResourceBundle * resource,const char * pattern,UErrorCode & status)192 static UnicodeString loadNumericDateFormatterPattern(
193 const UResourceBundle *resource,
194 const char *pattern,
195 UErrorCode &status) {
196 UnicodeString result;
197 if (U_FAILURE(status)) {
198 return result;
199 }
200 CharString chs;
201 chs.append("durationUnits", status)
202 .append("/", status).append(pattern, status);
203 LocalUResourceBundlePointer patternBundle(
204 ures_getByKeyWithFallback(
205 resource,
206 chs.data(),
207 NULL,
208 &status));
209 if (U_FAILURE(status)) {
210 return result;
211 }
212 getString(patternBundle.getAlias(), result, status);
213 // Replace 'h' with 'H'
214 int32_t len = result.length();
215 UChar *buffer = result.getBuffer(len);
216 for (int32_t i = 0; i < len; ++i) {
217 if (buffer[i] == 0x68) { // 'h'
218 buffer[i] = 0x48; // 'H'
219 }
220 }
221 result.releaseBuffer(len);
222 return result;
223 }
224
loadNumericDateFormatters(const UResourceBundle * resource,UErrorCode & status)225 static NumericDateFormatters *loadNumericDateFormatters(
226 const UResourceBundle *resource,
227 UErrorCode &status) {
228 if (U_FAILURE(status)) {
229 return NULL;
230 }
231 NumericDateFormatters *result = new NumericDateFormatters(
232 loadNumericDateFormatterPattern(resource, "hm", status),
233 loadNumericDateFormatterPattern(resource, "ms", status),
234 loadNumericDateFormatterPattern(resource, "hms", status));
235 if (U_FAILURE(status)) {
236 delete result;
237 return NULL;
238 }
239 return result;
240 }
241
242 template<> U_I18N_API
createObject(const void *,UErrorCode & status) const243 const MeasureFormatCacheData *LocaleCacheKey<MeasureFormatCacheData>::createObject(
244 const void * /*unused*/, UErrorCode &status) const {
245 const char *localeId = fLoc.getName();
246 LocalUResourceBundlePointer unitsBundle(ures_open(U_ICUDATA_UNIT, localeId, &status));
247 static UNumberFormatStyle currencyStyles[] = {
248 UNUM_CURRENCY_PLURAL, UNUM_CURRENCY_ISO, UNUM_CURRENCY};
249 LocalPointer<MeasureFormatCacheData> result(new MeasureFormatCacheData(), status);
250 if (U_FAILURE(status)) {
251 return NULL;
252 }
253 result->adoptNumericDateFormatters(loadNumericDateFormatters(
254 unitsBundle.getAlias(), status));
255 if (U_FAILURE(status)) {
256 return NULL;
257 }
258
259 for (int32_t i = 0; i < WIDTH_INDEX_COUNT; ++i) {
260 // NumberFormat::createInstance can erase warning codes from status, so pass it
261 // a separate status instance
262 UErrorCode localStatus = U_ZERO_ERROR;
263 result->adoptCurrencyFormat(i, NumberFormat::createInstance(
264 localeId, currencyStyles[i], localStatus));
265 if (localStatus != U_ZERO_ERROR) {
266 status = localStatus;
267 }
268 if (U_FAILURE(status)) {
269 return NULL;
270 }
271 }
272 NumberFormat *inf = NumberFormat::createInstance(
273 localeId, UNUM_DECIMAL, status);
274 if (U_FAILURE(status)) {
275 return NULL;
276 }
277 inf->setMaximumFractionDigits(0);
278 DecimalFormat *decfmt = dynamic_cast<DecimalFormat *>(inf);
279 if (decfmt != NULL) {
280 decfmt->setRoundingMode(DecimalFormat::kRoundDown);
281 }
282 result->adoptIntegerFormat(inf);
283 result->addRef();
284 return result.orphan();
285 }
286
isTimeUnit(const MeasureUnit & mu,const char * tu)287 static UBool isTimeUnit(const MeasureUnit &mu, const char *tu) {
288 return uprv_strcmp(mu.getType(), "duration") == 0 &&
289 uprv_strcmp(mu.getSubtype(), tu) == 0;
290 }
291
292 // Converts a composite measure into hours-minutes-seconds and stores at hms
293 // array. [0] is hours; [1] is minutes; [2] is seconds. Returns a bit map of
294 // units found: 1=hours, 2=minutes, 4=seconds. For example, if measures
295 // contains hours-minutes, this function would return 3.
296 //
297 // If measures cannot be converted into hours, minutes, seconds or if amounts
298 // are negative, or if hours, minutes, seconds are out of order, returns 0.
toHMS(const Measure * measures,int32_t measureCount,Formattable * hms,UErrorCode & status)299 static int32_t toHMS(
300 const Measure *measures,
301 int32_t measureCount,
302 Formattable *hms,
303 UErrorCode &status) {
304 if (U_FAILURE(status)) {
305 return 0;
306 }
307 int32_t result = 0;
308 if (U_FAILURE(status)) {
309 return 0;
310 }
311 // We use copy constructor to ensure that both sides of equality operator
312 // are instances of MeasureUnit base class and not a subclass. Otherwise,
313 // operator== will immediately return false.
314 for (int32_t i = 0; i < measureCount; ++i) {
315 if (isTimeUnit(measures[i].getUnit(), "hour")) {
316 // hour must come first
317 if (result >= 1) {
318 return 0;
319 }
320 hms[0] = measures[i].getNumber();
321 if (hms[0].getDouble() < 0.0) {
322 return 0;
323 }
324 result |= 1;
325 } else if (isTimeUnit(measures[i].getUnit(), "minute")) {
326 // minute must come after hour
327 if (result >= 2) {
328 return 0;
329 }
330 hms[1] = measures[i].getNumber();
331 if (hms[1].getDouble() < 0.0) {
332 return 0;
333 }
334 result |= 2;
335 } else if (isTimeUnit(measures[i].getUnit(), "second")) {
336 // second must come after hour and minute
337 if (result >= 4) {
338 return 0;
339 }
340 hms[2] = measures[i].getNumber();
341 if (hms[2].getDouble() < 0.0) {
342 return 0;
343 }
344 result |= 4;
345 } else {
346 return 0;
347 }
348 }
349 return result;
350 }
351
352
MeasureFormat(const Locale & locale,UMeasureFormatWidth w,UErrorCode & status)353 MeasureFormat::MeasureFormat(
354 const Locale &locale, UMeasureFormatWidth w, UErrorCode &status)
355 : cache(NULL),
356 numberFormat(NULL),
357 pluralRules(NULL),
358 fWidth(w),
359 listFormatter(NULL) {
360 initMeasureFormat(locale, w, NULL, status);
361 }
362
MeasureFormat(const Locale & locale,UMeasureFormatWidth w,NumberFormat * nfToAdopt,UErrorCode & status)363 MeasureFormat::MeasureFormat(
364 const Locale &locale,
365 UMeasureFormatWidth w,
366 NumberFormat *nfToAdopt,
367 UErrorCode &status)
368 : cache(NULL),
369 numberFormat(NULL),
370 pluralRules(NULL),
371 fWidth(w),
372 listFormatter(NULL) {
373 initMeasureFormat(locale, w, nfToAdopt, status);
374 }
375
MeasureFormat(const MeasureFormat & other)376 MeasureFormat::MeasureFormat(const MeasureFormat &other) :
377 Format(other),
378 cache(other.cache),
379 numberFormat(other.numberFormat),
380 pluralRules(other.pluralRules),
381 fWidth(other.fWidth),
382 listFormatter(NULL) {
383 cache->addRef();
384 numberFormat->addRef();
385 pluralRules->addRef();
386 if (other.listFormatter != NULL) {
387 listFormatter = new ListFormatter(*other.listFormatter);
388 }
389 }
390
operator =(const MeasureFormat & other)391 MeasureFormat &MeasureFormat::operator=(const MeasureFormat &other) {
392 if (this == &other) {
393 return *this;
394 }
395 Format::operator=(other);
396 SharedObject::copyPtr(other.cache, cache);
397 SharedObject::copyPtr(other.numberFormat, numberFormat);
398 SharedObject::copyPtr(other.pluralRules, pluralRules);
399 fWidth = other.fWidth;
400 delete listFormatter;
401 if (other.listFormatter != NULL) {
402 listFormatter = new ListFormatter(*other.listFormatter);
403 } else {
404 listFormatter = NULL;
405 }
406 return *this;
407 }
408
MeasureFormat()409 MeasureFormat::MeasureFormat() :
410 cache(NULL),
411 numberFormat(NULL),
412 pluralRules(NULL),
413 fWidth(UMEASFMT_WIDTH_SHORT),
414 listFormatter(NULL) {
415 }
416
~MeasureFormat()417 MeasureFormat::~MeasureFormat() {
418 if (cache != NULL) {
419 cache->removeRef();
420 }
421 if (numberFormat != NULL) {
422 numberFormat->removeRef();
423 }
424 if (pluralRules != NULL) {
425 pluralRules->removeRef();
426 }
427 delete listFormatter;
428 }
429
operator ==(const Format & other) const430 UBool MeasureFormat::operator==(const Format &other) const {
431 if (this == &other) { // Same object, equal
432 return TRUE;
433 }
434 if (!Format::operator==(other)) {
435 return FALSE;
436 }
437 const MeasureFormat &rhs = static_cast<const MeasureFormat &>(other);
438
439 // Note: Since the ListFormatter depends only on Locale and width, we
440 // don't have to check it here.
441
442 // differing widths aren't equivalent
443 if (fWidth != rhs.fWidth) {
444 return FALSE;
445 }
446 // Width the same check locales.
447 // We don't need to check locales if both objects have same cache.
448 if (cache != rhs.cache) {
449 UErrorCode status = U_ZERO_ERROR;
450 const char *localeId = getLocaleID(status);
451 const char *rhsLocaleId = rhs.getLocaleID(status);
452 if (U_FAILURE(status)) {
453 // On failure, assume not equal
454 return FALSE;
455 }
456 if (uprv_strcmp(localeId, rhsLocaleId) != 0) {
457 return FALSE;
458 }
459 }
460 // Locales same, check NumberFormat if shared data differs.
461 return (
462 numberFormat == rhs.numberFormat ||
463 **numberFormat == **rhs.numberFormat);
464 }
465
clone() const466 MeasureFormat *MeasureFormat::clone() const {
467 return new MeasureFormat(*this);
468 }
469
format(const Formattable & obj,UnicodeString & appendTo,FieldPosition & pos,UErrorCode & status) const470 UnicodeString &MeasureFormat::format(
471 const Formattable &obj,
472 UnicodeString &appendTo,
473 FieldPosition &pos,
474 UErrorCode &status) const {
475 if (U_FAILURE(status)) return appendTo;
476 if (obj.getType() == Formattable::kObject) {
477 const UObject* formatObj = obj.getObject();
478 const Measure* amount = dynamic_cast<const Measure*>(formatObj);
479 if (amount != NULL) {
480 return formatMeasure(
481 *amount, **numberFormat, appendTo, pos, status);
482 }
483 }
484 status = U_ILLEGAL_ARGUMENT_ERROR;
485 return appendTo;
486 }
487
parseObject(const UnicodeString &,Formattable &,ParsePosition &) const488 void MeasureFormat::parseObject(
489 const UnicodeString & /*source*/,
490 Formattable & /*result*/,
491 ParsePosition& /*pos*/) const {
492 return;
493 }
494
formatMeasurePerUnit(const Measure & measure,const MeasureUnit & perUnit,UnicodeString & appendTo,FieldPosition & pos,UErrorCode & status) const495 UnicodeString &MeasureFormat::formatMeasurePerUnit(
496 const Measure &measure,
497 const MeasureUnit &perUnit,
498 UnicodeString &appendTo,
499 FieldPosition &pos,
500 UErrorCode &status) const {
501 if (U_FAILURE(status)) {
502 return appendTo;
503 }
504 auto* df = dynamic_cast<const DecimalFormat*>(&getNumberFormatInternal());
505 if (df == nullptr) {
506 // Don't know how to handle other types of NumberFormat
507 status = U_UNSUPPORTED_ERROR;
508 return appendTo;
509 }
510 UFormattedNumberData result;
511 if (auto* lnf = df->toNumberFormatter(status)) {
512 result.quantity.setToDouble(measure.getNumber().getDouble(status));
513 lnf->unit(measure.getUnit())
514 .perUnit(perUnit)
515 .unitWidth(getUnitWidth(fWidth))
516 .formatImpl(&result, status);
517 }
518 DecimalFormat::fieldPositionHelper(result, pos, appendTo.length(), status);
519 appendTo.append(result.toTempString(status));
520 return appendTo;
521 }
522
formatMeasures(const Measure * measures,int32_t measureCount,UnicodeString & appendTo,FieldPosition & pos,UErrorCode & status) const523 UnicodeString &MeasureFormat::formatMeasures(
524 const Measure *measures,
525 int32_t measureCount,
526 UnicodeString &appendTo,
527 FieldPosition &pos,
528 UErrorCode &status) const {
529 if (U_FAILURE(status)) {
530 return appendTo;
531 }
532 if (measureCount == 0) {
533 return appendTo;
534 }
535 if (measureCount == 1) {
536 return formatMeasure(measures[0], **numberFormat, appendTo, pos, status);
537 }
538 if (fWidth == UMEASFMT_WIDTH_NUMERIC) {
539 Formattable hms[3];
540 int32_t bitMap = toHMS(measures, measureCount, hms, status);
541 if (bitMap > 0) {
542 return formatNumeric(hms, bitMap, appendTo, status);
543 }
544 }
545 if (pos.getField() != FieldPosition::DONT_CARE) {
546 return formatMeasuresSlowTrack(
547 measures, measureCount, appendTo, pos, status);
548 }
549 UnicodeString *results = new UnicodeString[measureCount];
550 if (results == NULL) {
551 status = U_MEMORY_ALLOCATION_ERROR;
552 return appendTo;
553 }
554 for (int32_t i = 0; i < measureCount; ++i) {
555 const NumberFormat *nf = cache->getIntegerFormat();
556 if (i == measureCount - 1) {
557 nf = numberFormat->get();
558 }
559 formatMeasure(
560 measures[i],
561 *nf,
562 results[i],
563 pos,
564 status);
565 }
566 listFormatter->format(results, measureCount, appendTo, status);
567 delete [] results;
568 return appendTo;
569 }
570
getUnitDisplayName(const MeasureUnit & unit,UErrorCode & status) const571 UnicodeString MeasureFormat::getUnitDisplayName(const MeasureUnit& unit, UErrorCode& status) const {
572 return number::impl::LongNameHandler::getUnitDisplayName(
573 getLocale(status),
574 unit,
575 getUnitWidth(fWidth),
576 status);
577 }
578
initMeasureFormat(const Locale & locale,UMeasureFormatWidth w,NumberFormat * nfToAdopt,UErrorCode & status)579 void MeasureFormat::initMeasureFormat(
580 const Locale &locale,
581 UMeasureFormatWidth w,
582 NumberFormat *nfToAdopt,
583 UErrorCode &status) {
584 static const char *listStyles[] = {"unit", "unit-short", "unit-narrow"};
585 LocalPointer<NumberFormat> nf(nfToAdopt);
586 if (U_FAILURE(status)) {
587 return;
588 }
589 const char *name = locale.getName();
590 setLocaleIDs(name, name);
591
592 UnifiedCache::getByLocale(locale, cache, status);
593 if (U_FAILURE(status)) {
594 return;
595 }
596
597 const SharedPluralRules *pr = PluralRules::createSharedInstance(
598 locale, UPLURAL_TYPE_CARDINAL, status);
599 if (U_FAILURE(status)) {
600 return;
601 }
602 SharedObject::copyPtr(pr, pluralRules);
603 pr->removeRef();
604 if (nf.isNull()) {
605 // TODO: Clean this up
606 const SharedNumberFormat *shared = NumberFormat::createSharedInstance(
607 locale, UNUM_DECIMAL, status);
608 if (U_FAILURE(status)) {
609 return;
610 }
611 SharedObject::copyPtr(shared, numberFormat);
612 shared->removeRef();
613 } else {
614 adoptNumberFormat(nf.orphan(), status);
615 if (U_FAILURE(status)) {
616 return;
617 }
618 }
619 fWidth = w;
620 delete listFormatter;
621 listFormatter = ListFormatter::createInstance(
622 locale,
623 listStyles[getRegularWidth(fWidth)],
624 status);
625 }
626
adoptNumberFormat(NumberFormat * nfToAdopt,UErrorCode & status)627 void MeasureFormat::adoptNumberFormat(
628 NumberFormat *nfToAdopt, UErrorCode &status) {
629 LocalPointer<NumberFormat> nf(nfToAdopt);
630 if (U_FAILURE(status)) {
631 return;
632 }
633 SharedNumberFormat *shared = new SharedNumberFormat(nf.getAlias());
634 if (shared == NULL) {
635 status = U_MEMORY_ALLOCATION_ERROR;
636 return;
637 }
638 nf.orphan();
639 SharedObject::copyPtr(shared, numberFormat);
640 }
641
setMeasureFormatLocale(const Locale & locale,UErrorCode & status)642 UBool MeasureFormat::setMeasureFormatLocale(const Locale &locale, UErrorCode &status) {
643 if (U_FAILURE(status) || locale == getLocale(status)) {
644 return FALSE;
645 }
646 initMeasureFormat(locale, fWidth, NULL, status);
647 return U_SUCCESS(status);
648 }
649
getNumberFormatInternal() const650 const NumberFormat &MeasureFormat::getNumberFormatInternal() const {
651 return **numberFormat;
652 }
653
getCurrencyFormatInternal() const654 const NumberFormat &MeasureFormat::getCurrencyFormatInternal() const {
655 return *cache->getCurrencyFormat(UMEASFMT_WIDTH_NARROW);
656 }
657
getPluralRules() const658 const PluralRules &MeasureFormat::getPluralRules() const {
659 return **pluralRules;
660 }
661
getLocale(UErrorCode & status) const662 Locale MeasureFormat::getLocale(UErrorCode &status) const {
663 return Format::getLocale(ULOC_VALID_LOCALE, status);
664 }
665
getLocaleID(UErrorCode & status) const666 const char *MeasureFormat::getLocaleID(UErrorCode &status) const {
667 return Format::getLocaleID(ULOC_VALID_LOCALE, status);
668 }
669
formatMeasure(const Measure & measure,const NumberFormat & nf,UnicodeString & appendTo,FieldPosition & pos,UErrorCode & status) const670 UnicodeString &MeasureFormat::formatMeasure(
671 const Measure &measure,
672 const NumberFormat &nf,
673 UnicodeString &appendTo,
674 FieldPosition &pos,
675 UErrorCode &status) const {
676 if (U_FAILURE(status)) {
677 return appendTo;
678 }
679 const Formattable& amtNumber = measure.getNumber();
680 const MeasureUnit& amtUnit = measure.getUnit();
681 if (isCurrency(amtUnit)) {
682 UChar isoCode[4];
683 u_charsToUChars(amtUnit.getSubtype(), isoCode, 4);
684 return cache->getCurrencyFormat(fWidth)->format(
685 new CurrencyAmount(amtNumber, isoCode, status),
686 appendTo,
687 pos,
688 status);
689 }
690 auto* df = dynamic_cast<const DecimalFormat*>(&nf);
691 if (df == nullptr) {
692 // Handle other types of NumberFormat using the ICU 63 code, modified to
693 // get the unitPattern from LongNameHandler and handle fallback to OTHER.
694 UnicodeString formattedNumber;
695 StandardPlural::Form pluralForm = QuantityFormatter::selectPlural(
696 amtNumber, nf, **pluralRules, formattedNumber, pos, status);
697 UnicodeString pattern = number::impl::LongNameHandler::getUnitPattern(getLocale(status),
698 amtUnit, getUnitWidth(fWidth), pluralForm, status);
699 // The above handles fallback from other widths to short, and from other plural forms to OTHER
700 if (U_FAILURE(status)) {
701 return appendTo;
702 }
703 SimpleFormatter formatter(pattern, 0, 1, status);
704 return QuantityFormatter::format(formatter, formattedNumber, appendTo, pos, status);
705 }
706 UFormattedNumberData result;
707 if (auto* lnf = df->toNumberFormatter(status)) {
708 result.quantity.setToDouble(amtNumber.getDouble(status));
709 lnf->unit(amtUnit)
710 .unitWidth(getUnitWidth(fWidth))
711 .formatImpl(&result, status);
712 }
713 DecimalFormat::fieldPositionHelper(result, pos, appendTo.length(), status);
714 appendTo.append(result.toTempString(status));
715 return appendTo;
716 }
717
718
719 // Formats numeric time duration as 5:00:47 or 3:54.
formatNumeric(const Formattable * hms,int32_t bitMap,UnicodeString & appendTo,UErrorCode & status) const720 UnicodeString &MeasureFormat::formatNumeric(
721 const Formattable *hms, // always length 3
722 int32_t bitMap, // 1=hour set, 2=minute set, 4=second set
723 UnicodeString &appendTo,
724 UErrorCode &status) const {
725 if (U_FAILURE(status)) {
726 return appendTo;
727 }
728
729 UnicodeString pattern;
730
731 double hours = hms[0].getDouble(status);
732 double minutes = hms[1].getDouble(status);
733 double seconds = hms[2].getDouble(status);
734 if (U_FAILURE(status)) {
735 return appendTo;
736 }
737
738 // All possible combinations: "h", "m", "s", "hm", "hs", "ms", "hms"
739 if (bitMap == 5 || bitMap == 7) { // "hms" & "hs" (we add minutes if "hs")
740 pattern = cache->getNumericDateFormatters()->hourMinuteSecond;
741 hours = uprv_trunc(hours);
742 minutes = uprv_trunc(minutes);
743 } else if (bitMap == 3) { // "hm"
744 pattern = cache->getNumericDateFormatters()->hourMinute;
745 hours = uprv_trunc(hours);
746 } else if (bitMap == 6) { // "ms"
747 pattern = cache->getNumericDateFormatters()->minuteSecond;
748 minutes = uprv_trunc(minutes);
749 } else { // h m s, handled outside formatNumeric. No value is also an error.
750 status = U_INTERNAL_PROGRAM_ERROR;
751 return appendTo;
752 }
753
754 const DecimalFormat *numberFormatter = dynamic_cast<const DecimalFormat*>(numberFormat->get());
755 if (!numberFormatter) {
756 status = U_INTERNAL_PROGRAM_ERROR;
757 return appendTo;
758 }
759 number::LocalizedNumberFormatter numberFormatter2;
760 if (auto* lnf = numberFormatter->toNumberFormatter(status)) {
761 numberFormatter2 = lnf->integerWidth(number::IntegerWidth::zeroFillTo(2));
762 } else {
763 return appendTo;
764 }
765
766 FormattedStringBuilder fsb;
767
768 UBool protect = FALSE;
769 const int32_t patternLength = pattern.length();
770 for (int32_t i = 0; i < patternLength; i++) {
771 char16_t c = pattern[i];
772
773 // Also set the proper field in this switch
774 // We don't use DateFormat.Field because this is not a date / time, is a duration.
775 double value = 0;
776 switch (c) {
777 case u'H': value = hours; break;
778 case u'm': value = minutes; break;
779 case u's': value = seconds; break;
780 }
781
782 // There is not enough info to add Field(s) for the unit because all we have are plain
783 // text patterns. For example in "21:51" there is no text for something like "hour",
784 // while in something like "21h51" there is ("h"). But we can't really tell...
785 switch (c) {
786 case u'H':
787 case u'm':
788 case u's':
789 if (protect) {
790 fsb.appendChar16(c, kUndefinedField, status);
791 } else {
792 UnicodeString tmp;
793 if ((i + 1 < patternLength) && pattern[i + 1] == c) { // doubled
794 tmp = numberFormatter2.formatDouble(value, status).toString(status);
795 i++;
796 } else {
797 numberFormatter->format(value, tmp, status);
798 }
799 // TODO: Use proper Field
800 fsb.append(tmp, kUndefinedField, status);
801 }
802 break;
803 case u'\'':
804 // '' is escaped apostrophe
805 if ((i + 1 < patternLength) && pattern[i + 1] == c) {
806 fsb.appendChar16(c, kUndefinedField, status);
807 i++;
808 } else {
809 protect = !protect;
810 }
811 break;
812 default:
813 fsb.appendChar16(c, kUndefinedField, status);
814 }
815 }
816
817 appendTo.append(fsb.toTempUnicodeString());
818
819 return appendTo;
820 }
821
formatMeasuresSlowTrack(const Measure * measures,int32_t measureCount,UnicodeString & appendTo,FieldPosition & pos,UErrorCode & status) const822 UnicodeString &MeasureFormat::formatMeasuresSlowTrack(
823 const Measure *measures,
824 int32_t measureCount,
825 UnicodeString& appendTo,
826 FieldPosition& pos,
827 UErrorCode& status) const {
828 if (U_FAILURE(status)) {
829 return appendTo;
830 }
831 FieldPosition dontCare(FieldPosition::DONT_CARE);
832 FieldPosition fpos(pos.getField());
833 LocalArray<UnicodeString> results(new UnicodeString[measureCount], status);
834 int32_t fieldPositionFoundIndex = -1;
835 for (int32_t i = 0; i < measureCount; ++i) {
836 const NumberFormat *nf = cache->getIntegerFormat();
837 if (i == measureCount - 1) {
838 nf = numberFormat->get();
839 }
840 if (fieldPositionFoundIndex == -1) {
841 formatMeasure(measures[i], *nf, results[i], fpos, status);
842 if (U_FAILURE(status)) {
843 return appendTo;
844 }
845 if (fpos.getBeginIndex() != 0 || fpos.getEndIndex() != 0) {
846 fieldPositionFoundIndex = i;
847 }
848 } else {
849 formatMeasure(measures[i], *nf, results[i], dontCare, status);
850 }
851 }
852 int32_t offset;
853 listFormatter->format(
854 results.getAlias(),
855 measureCount,
856 appendTo,
857 fieldPositionFoundIndex,
858 offset,
859 status);
860 if (U_FAILURE(status)) {
861 return appendTo;
862 }
863 // Fix up FieldPosition indexes if our field is found.
864 if (fieldPositionFoundIndex != -1 && offset != -1) {
865 pos.setBeginIndex(fpos.getBeginIndex() + offset);
866 pos.setEndIndex(fpos.getEndIndex() + offset);
867 }
868 return appendTo;
869 }
870
createCurrencyFormat(const Locale & locale,UErrorCode & ec)871 MeasureFormat* U_EXPORT2 MeasureFormat::createCurrencyFormat(const Locale& locale,
872 UErrorCode& ec) {
873 if (U_FAILURE(ec)) {
874 return nullptr;
875 }
876 LocalPointer<CurrencyFormat> fmt(new CurrencyFormat(locale, ec), ec);
877 return fmt.orphan();
878 }
879
createCurrencyFormat(UErrorCode & ec)880 MeasureFormat* U_EXPORT2 MeasureFormat::createCurrencyFormat(UErrorCode& ec) {
881 if (U_FAILURE(ec)) {
882 return nullptr;
883 }
884 return MeasureFormat::createCurrencyFormat(Locale::getDefault(), ec);
885 }
886
887 U_NAMESPACE_END
888
889 #endif /* #if !UCONFIG_NO_FORMATTING */
890