1 /* 2 * Copyright (C) 2008 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 #define LOG_TAG "ICU" 18 19 #include "IcuUtilities.h" 20 #include "JNIHelp.h" 21 #include "JniConstants.h" 22 #include "JniException.h" 23 #include "ScopedFd.h" 24 #include "ScopedJavaUnicodeString.h" 25 #include "ScopedLocalRef.h" 26 #include "ScopedUtfChars.h" 27 #include "UniquePtr.h" 28 #include "cutils/log.h" 29 #include "toStringArray.h" 30 #include "unicode/calendar.h" 31 #include "unicode/datefmt.h" 32 #include "unicode/dcfmtsym.h" 33 #include "unicode/decimfmt.h" 34 #include "unicode/dtfmtsym.h" 35 #include "unicode/dtptngen.h" 36 #include "unicode/gregocal.h" 37 #include "unicode/locid.h" 38 #include "unicode/numfmt.h" 39 #include "unicode/strenum.h" 40 #include "unicode/ubrk.h" 41 #include "unicode/ucal.h" 42 #include "unicode/uclean.h" 43 #include "unicode/ucol.h" 44 #include "unicode/ucurr.h" 45 #include "unicode/udat.h" 46 #include "unicode/uloc.h" 47 #include "unicode/ulocdata.h" 48 #include "unicode/ustring.h" 49 #include "ureslocs.h" 50 #include "valueOf.h" 51 52 #include <errno.h> 53 #include <fcntl.h> 54 #include <stdlib.h> 55 #include <string.h> 56 #include <string> 57 #include <sys/mman.h> 58 #include <sys/stat.h> 59 #include <sys/time.h> 60 #include <sys/types.h> 61 #include <time.h> 62 #include <unistd.h> 63 64 // TODO: put this in a header file and use it everywhere! 65 // DISALLOW_COPY_AND_ASSIGN disallows the copy and operator= functions. 66 // It goes in the private: declarations in a class. 67 #define DISALLOW_COPY_AND_ASSIGN(TypeName) \ 68 TypeName(const TypeName&); \ 69 void operator=(const TypeName&) 70 71 class ScopedResourceBundle { 72 public: 73 ScopedResourceBundle(UResourceBundle* bundle) : bundle_(bundle) { 74 } 75 76 ~ScopedResourceBundle() { 77 if (bundle_ != NULL) { 78 ures_close(bundle_); 79 } 80 } 81 82 UResourceBundle* get() { 83 return bundle_; 84 } 85 86 bool hasKey(const char* key) { 87 UErrorCode status = U_ZERO_ERROR; 88 ures_getStringByKey(bundle_, key, NULL, &status); 89 return U_SUCCESS(status); 90 } 91 92 private: 93 UResourceBundle* bundle_; 94 DISALLOW_COPY_AND_ASSIGN(ScopedResourceBundle); 95 }; 96 97 static jstring ICU_addLikelySubtags(JNIEnv* env, jclass, jstring javaLocale) { 98 UErrorCode status = U_ZERO_ERROR; 99 ScopedUtfChars localeID(env, javaLocale); 100 char maximizedLocaleID[ULOC_FULLNAME_CAPACITY]; 101 uloc_addLikelySubtags(localeID.c_str(), maximizedLocaleID, sizeof(maximizedLocaleID), &status); 102 if (U_FAILURE(status)) { 103 return javaLocale; 104 } 105 return env->NewStringUTF(maximizedLocaleID); 106 } 107 108 static jstring ICU_getScript(JNIEnv* env, jclass, jstring javaLocale) { 109 UErrorCode status = U_ZERO_ERROR; 110 ScopedUtfChars localeID(env, javaLocale); 111 char script[ULOC_SCRIPT_CAPACITY]; 112 uloc_getScript(localeID.c_str(), script, sizeof(script), &status); 113 if (U_FAILURE(status)) { 114 return NULL; 115 } 116 return env->NewStringUTF(script); 117 } 118 119 static jint ICU_getCurrencyFractionDigits(JNIEnv* env, jclass, jstring javaCurrencyCode) { 120 ScopedJavaUnicodeString currencyCode(env, javaCurrencyCode); 121 if (!currencyCode.valid()) { 122 return 0; 123 } 124 UnicodeString icuCurrencyCode(currencyCode.unicodeString()); 125 UErrorCode status = U_ZERO_ERROR; 126 return ucurr_getDefaultFractionDigits(icuCurrencyCode.getTerminatedBuffer(), &status); 127 } 128 129 // TODO: rewrite this with int32_t ucurr_forLocale(const char* locale, UChar* buff, int32_t buffCapacity, UErrorCode* ec)... 130 static jstring ICU_getCurrencyCode(JNIEnv* env, jclass, jstring javaCountryCode) { 131 UErrorCode status = U_ZERO_ERROR; 132 ScopedResourceBundle supplData(ures_openDirect(U_ICUDATA_CURR, "supplementalData", &status)); 133 if (U_FAILURE(status)) { 134 return NULL; 135 } 136 137 ScopedResourceBundle currencyMap(ures_getByKey(supplData.get(), "CurrencyMap", NULL, &status)); 138 if (U_FAILURE(status)) { 139 return NULL; 140 } 141 142 ScopedUtfChars countryCode(env, javaCountryCode); 143 ScopedResourceBundle currency(ures_getByKey(currencyMap.get(), countryCode.c_str(), NULL, &status)); 144 if (U_FAILURE(status)) { 145 return NULL; 146 } 147 148 ScopedResourceBundle currencyElem(ures_getByIndex(currency.get(), 0, NULL, &status)); 149 if (U_FAILURE(status)) { 150 return env->NewStringUTF("XXX"); 151 } 152 153 // Check if there's a 'to' date. If there is, the currency isn't used anymore. 154 ScopedResourceBundle currencyTo(ures_getByKey(currencyElem.get(), "to", NULL, &status)); 155 if (!U_FAILURE(status)) { 156 return NULL; 157 } 158 // Ignore the failure to find a 'to' date. 159 status = U_ZERO_ERROR; 160 161 ScopedResourceBundle currencyId(ures_getByKey(currencyElem.get(), "id", NULL, &status)); 162 if (U_FAILURE(status)) { 163 // No id defined for this country 164 return env->NewStringUTF("XXX"); 165 } 166 167 int32_t charCount; 168 const jchar* chars = ures_getString(currencyId.get(), &charCount, &status); 169 return (charCount == 0) ? env->NewStringUTF("XXX") : env->NewString(chars, charCount); 170 } 171 172 static jstring getCurrencyName(JNIEnv* env, jstring javaLocaleName, jstring javaCurrencyCode, UCurrNameStyle nameStyle) { 173 ScopedUtfChars localeName(env, javaLocaleName); 174 if (localeName.c_str() == NULL) { 175 return NULL; 176 } 177 ScopedJavaUnicodeString currencyCode(env, javaCurrencyCode); 178 if (!currencyCode.valid()) { 179 return NULL; 180 } 181 UnicodeString icuCurrencyCode(currencyCode.unicodeString()); 182 UErrorCode status = U_ZERO_ERROR; 183 UBool isChoiceFormat = false; 184 int32_t charCount; 185 const UChar* chars = ucurr_getName(icuCurrencyCode.getTerminatedBuffer(), localeName.c_str(), 186 nameStyle, &isChoiceFormat, &charCount, &status); 187 if (status == U_USING_DEFAULT_WARNING) { 188 if (nameStyle == UCURR_SYMBOL_NAME) { 189 // ICU doesn't distinguish between falling back to the root locale and meeting a genuinely 190 // unknown currency. The Currency class does. 191 if (!ucurr_isAvailable(icuCurrencyCode.getTerminatedBuffer(), U_DATE_MIN, U_DATE_MAX, &status)) { 192 return NULL; 193 } 194 } 195 if (nameStyle == UCURR_LONG_NAME) { 196 // ICU's default is English. We want the ISO 4217 currency code instead. 197 chars = icuCurrencyCode.getBuffer(); 198 charCount = icuCurrencyCode.length(); 199 } 200 } 201 return (charCount == 0) ? NULL : env->NewString(chars, charCount); 202 } 203 204 static jstring ICU_getCurrencyDisplayName(JNIEnv* env, jclass, jstring javaLocaleName, jstring javaCurrencyCode) { 205 return getCurrencyName(env, javaLocaleName, javaCurrencyCode, UCURR_LONG_NAME); 206 } 207 208 static jstring ICU_getCurrencySymbol(JNIEnv* env, jclass, jstring javaLocaleName, jstring javaCurrencyCode) { 209 return getCurrencyName(env, javaLocaleName, javaCurrencyCode, UCURR_SYMBOL_NAME); 210 } 211 212 static jstring ICU_getDisplayCountryNative(JNIEnv* env, jclass, jstring targetLocale, jstring locale) { 213 Locale loc = getLocale(env, locale); 214 Locale targetLoc = getLocale(env, targetLocale); 215 UnicodeString str; 216 targetLoc.getDisplayCountry(loc, str); 217 return env->NewString(str.getBuffer(), str.length()); 218 } 219 220 static jstring ICU_getDisplayLanguageNative(JNIEnv* env, jclass, jstring targetLocale, jstring locale) { 221 Locale loc = getLocale(env, locale); 222 Locale targetLoc = getLocale(env, targetLocale); 223 UnicodeString str; 224 targetLoc.getDisplayLanguage(loc, str); 225 return env->NewString(str.getBuffer(), str.length()); 226 } 227 228 static jstring ICU_getDisplayVariantNative(JNIEnv* env, jclass, jstring targetLocale, jstring locale) { 229 Locale loc = getLocale(env, locale); 230 Locale targetLoc = getLocale(env, targetLocale); 231 UnicodeString str; 232 targetLoc.getDisplayVariant(loc, str); 233 return env->NewString(str.getBuffer(), str.length()); 234 } 235 236 static jstring ICU_getISO3CountryNative(JNIEnv* env, jclass, jstring locale) { 237 Locale loc = getLocale(env, locale); 238 return env->NewStringUTF(loc.getISO3Country()); 239 } 240 241 static jstring ICU_getISO3LanguageNative(JNIEnv* env, jclass, jstring locale) { 242 Locale loc = getLocale(env, locale); 243 return env->NewStringUTF(loc.getISO3Language()); 244 } 245 246 static jobjectArray ICU_getISOCountriesNative(JNIEnv* env, jclass) { 247 return toStringArray(env, Locale::getISOCountries()); 248 } 249 250 static jobjectArray ICU_getISOLanguagesNative(JNIEnv* env, jclass) { 251 return toStringArray(env, Locale::getISOLanguages()); 252 } 253 254 static jobjectArray ICU_getAvailableLocalesNative(JNIEnv* env, jclass) { 255 return toStringArray(env, uloc_countAvailable, uloc_getAvailable); 256 } 257 258 static jobjectArray ICU_getAvailableBreakIteratorLocalesNative(JNIEnv* env, jclass) { 259 return toStringArray(env, ubrk_countAvailable, ubrk_getAvailable); 260 } 261 262 static jobjectArray ICU_getAvailableCalendarLocalesNative(JNIEnv* env, jclass) { 263 return toStringArray(env, ucal_countAvailable, ucal_getAvailable); 264 } 265 266 static jobjectArray ICU_getAvailableCollatorLocalesNative(JNIEnv* env, jclass) { 267 return toStringArray(env, ucol_countAvailable, ucol_getAvailable); 268 } 269 270 static jobjectArray ICU_getAvailableDateFormatLocalesNative(JNIEnv* env, jclass) { 271 return toStringArray(env, udat_countAvailable, udat_getAvailable); 272 } 273 274 static jobjectArray ICU_getAvailableNumberFormatLocalesNative(JNIEnv* env, jclass) { 275 return toStringArray(env, unum_countAvailable, unum_getAvailable); 276 } 277 278 static void setIntegerField(JNIEnv* env, jobject obj, const char* fieldName, int value) { 279 ScopedLocalRef<jobject> integerValue(env, integerValueOf(env, value)); 280 jfieldID fid = env->GetFieldID(JniConstants::localeDataClass, fieldName, "Ljava/lang/Integer;"); 281 env->SetObjectField(obj, fid, integerValue.get()); 282 } 283 284 static void setStringField(JNIEnv* env, jobject obj, const char* fieldName, jstring value) { 285 jfieldID fid = env->GetFieldID(JniConstants::localeDataClass, fieldName, "Ljava/lang/String;"); 286 env->SetObjectField(obj, fid, value); 287 env->DeleteLocalRef(value); 288 } 289 290 static void setStringArrayField(JNIEnv* env, jobject obj, const char* fieldName, jobjectArray value) { 291 jfieldID fid = env->GetFieldID(JniConstants::localeDataClass, fieldName, "[Ljava/lang/String;"); 292 env->SetObjectField(obj, fid, value); 293 } 294 295 static void setStringArrayField(JNIEnv* env, jobject obj, const char* fieldName, const UnicodeString* valueArray, int32_t size) { 296 ScopedLocalRef<jobjectArray> result(env, env->NewObjectArray(size, JniConstants::stringClass, NULL)); 297 for (int32_t i = 0; i < size ; i++) { 298 ScopedLocalRef<jstring> s(env, env->NewString(valueArray[i].getBuffer(),valueArray[i].length())); 299 if (env->ExceptionCheck()) { 300 return; 301 } 302 env->SetObjectArrayElement(result.get(), i, s.get()); 303 if (env->ExceptionCheck()) { 304 return; 305 } 306 } 307 setStringArrayField(env, obj, fieldName, result.get()); 308 } 309 310 static void setStringField(JNIEnv* env, jobject obj, const char* fieldName, UResourceBundle* bundle, int index) { 311 UErrorCode status = U_ZERO_ERROR; 312 int charCount; 313 const UChar* chars = ures_getStringByIndex(bundle, index, &charCount, &status); 314 if (U_SUCCESS(status)) { 315 setStringField(env, obj, fieldName, env->NewString(chars, charCount)); 316 } else { 317 ALOGE("Error setting String field %s from ICU resource (index %d): %s", fieldName, index, u_errorName(status)); 318 } 319 } 320 321 static void setStringField(JNIEnv* env, jobject obj, const char* fieldName, UResourceBundle* bundle, const char* key) { 322 UErrorCode status = U_ZERO_ERROR; 323 int charCount; 324 const UChar* chars = ures_getStringByKey(bundle, key, &charCount, &status); 325 if (U_SUCCESS(status)) { 326 setStringField(env, obj, fieldName, env->NewString(chars, charCount)); 327 } else { 328 ALOGE("Error setting String field %s from ICU resource (key %s): %s", fieldName, key, u_errorName(status)); 329 } 330 } 331 332 static void setCharField(JNIEnv* env, jobject obj, const char* fieldName, const UnicodeString& value) { 333 if (value.length() == 0) { 334 return; 335 } 336 jfieldID fid = env->GetFieldID(JniConstants::localeDataClass, fieldName, "C"); 337 env->SetCharField(obj, fid, value.charAt(0)); 338 } 339 340 static void setStringField(JNIEnv* env, jobject obj, const char* fieldName, const UnicodeString& value) { 341 const UChar* chars = value.getBuffer(); 342 setStringField(env, obj, fieldName, env->NewString(chars, value.length())); 343 } 344 345 static void setNumberPatterns(JNIEnv* env, jobject obj, Locale& locale) { 346 UErrorCode status = U_ZERO_ERROR; 347 348 UnicodeString pattern; 349 UniquePtr<DecimalFormat> fmt(static_cast<DecimalFormat*>(NumberFormat::createInstance(locale, UNUM_CURRENCY, status))); 350 pattern = fmt->toPattern(pattern.remove()); 351 setStringField(env, obj, "currencyPattern", pattern); 352 353 fmt.reset(static_cast<DecimalFormat*>(NumberFormat::createInstance(locale, UNUM_DECIMAL, status))); 354 pattern = fmt->toPattern(pattern.remove()); 355 setStringField(env, obj, "numberPattern", pattern); 356 357 fmt.reset(static_cast<DecimalFormat*>(NumberFormat::createInstance(locale, UNUM_PERCENT, status))); 358 pattern = fmt->toPattern(pattern.remove()); 359 setStringField(env, obj, "percentPattern", pattern); 360 } 361 362 static void setDecimalFormatSymbolsData(JNIEnv* env, jobject obj, Locale& locale) { 363 UErrorCode status = U_ZERO_ERROR; 364 DecimalFormatSymbols dfs(locale, status); 365 366 setCharField(env, obj, "decimalSeparator", dfs.getSymbol(DecimalFormatSymbols::kDecimalSeparatorSymbol)); 367 setCharField(env, obj, "groupingSeparator", dfs.getSymbol(DecimalFormatSymbols::kGroupingSeparatorSymbol)); 368 setCharField(env, obj, "patternSeparator", dfs.getSymbol(DecimalFormatSymbols::kPatternSeparatorSymbol)); 369 setCharField(env, obj, "percent", dfs.getSymbol(DecimalFormatSymbols::kPercentSymbol)); 370 setCharField(env, obj, "perMill", dfs.getSymbol(DecimalFormatSymbols::kPerMillSymbol)); 371 setCharField(env, obj, "monetarySeparator", dfs.getSymbol(DecimalFormatSymbols::kMonetarySeparatorSymbol)); 372 setCharField(env, obj, "minusSign", dfs.getSymbol(DecimalFormatSymbols:: kMinusSignSymbol)); 373 setStringField(env, obj, "exponentSeparator", dfs.getSymbol(DecimalFormatSymbols::kExponentialSymbol)); 374 setStringField(env, obj, "infinity", dfs.getSymbol(DecimalFormatSymbols::kInfinitySymbol)); 375 setStringField(env, obj, "NaN", dfs.getSymbol(DecimalFormatSymbols::kNaNSymbol)); 376 setCharField(env, obj, "zeroDigit", dfs.getSymbol(DecimalFormatSymbols::kZeroDigitSymbol)); 377 } 378 379 380 // Iterates up through the locale hierarchy. So "en_US" would return "en_US", "en", "". 381 class LocaleNameIterator { 382 public: 383 LocaleNameIterator(const char* locale_name, UErrorCode& status) : status_(status), has_next_(true) { 384 strcpy(locale_name_, locale_name); 385 locale_name_length_ = strlen(locale_name_); 386 } 387 388 const char* Get() { 389 return locale_name_; 390 } 391 392 bool HasNext() { 393 return has_next_; 394 } 395 396 void Up() { 397 if (locale_name_length_ == 0) { 398 has_next_ = false; 399 } else { 400 locale_name_length_ = uloc_getParent(locale_name_, locale_name_, sizeof(locale_name_), &status_); 401 } 402 } 403 404 private: 405 UErrorCode& status_; 406 bool has_next_; 407 char locale_name_[ULOC_FULLNAME_CAPACITY]; 408 int32_t locale_name_length_; 409 410 DISALLOW_COPY_AND_ASSIGN(LocaleNameIterator); 411 }; 412 413 static bool getDateTimePatterns(JNIEnv* env, jobject localeData, const char* locale_name) { 414 UErrorCode status = U_ZERO_ERROR; 415 ScopedResourceBundle root(ures_open(NULL, locale_name, &status)); 416 if (U_FAILURE(status)) { 417 return false; 418 } 419 ScopedResourceBundle calendar(ures_getByKey(root.get(), "calendar", NULL, &status)); 420 if (U_FAILURE(status)) { 421 return false; 422 } 423 ScopedResourceBundle gregorian(ures_getByKey(calendar.get(), "gregorian", NULL, &status)); 424 if (U_FAILURE(status)) { 425 return false; 426 } 427 ScopedResourceBundle dateTimePatterns(ures_getByKey(gregorian.get(), "DateTimePatterns", NULL, &status)); 428 if (U_FAILURE(status)) { 429 return false; 430 } 431 setStringField(env, localeData, "fullTimeFormat", dateTimePatterns.get(), 0); 432 setStringField(env, localeData, "longTimeFormat", dateTimePatterns.get(), 1); 433 setStringField(env, localeData, "mediumTimeFormat", dateTimePatterns.get(), 2); 434 setStringField(env, localeData, "shortTimeFormat", dateTimePatterns.get(), 3); 435 setStringField(env, localeData, "fullDateFormat", dateTimePatterns.get(), 4); 436 setStringField(env, localeData, "longDateFormat", dateTimePatterns.get(), 5); 437 setStringField(env, localeData, "mediumDateFormat", dateTimePatterns.get(), 6); 438 setStringField(env, localeData, "shortDateFormat", dateTimePatterns.get(), 7); 439 return true; 440 } 441 442 static bool getYesterdayTodayAndTomorrow(JNIEnv* env, jobject localeData, const char* locale_name) { 443 UErrorCode status = U_ZERO_ERROR; 444 ScopedResourceBundle root(ures_open(NULL, locale_name, &status)); 445 if (U_FAILURE(status)) { 446 return false; 447 } 448 ScopedResourceBundle fields(ures_getByKey(root.get(), "fields", NULL, &status)); 449 if (U_FAILURE(status)) { 450 return false; 451 } 452 ScopedResourceBundle day(ures_getByKey(fields.get(), "day", NULL, &status)); 453 if (U_FAILURE(status)) { 454 return false; 455 } 456 ScopedResourceBundle relative(ures_getByKey(day.get(), "relative", NULL, &status)); 457 if (U_FAILURE(status)) { 458 return false; 459 } 460 // bn_BD only has a "-2" entry. 461 if (relative.hasKey("-1") && relative.hasKey("0") && relative.hasKey("1")) { 462 setStringField(env, localeData, "yesterday", relative.get(), "-1"); 463 setStringField(env, localeData, "today", relative.get(), "0"); 464 setStringField(env, localeData, "tomorrow", relative.get(), "1"); 465 return true; 466 } 467 return false; 468 } 469 470 static jboolean ICU_initLocaleDataImpl(JNIEnv* env, jclass, jstring javaLocaleName, jobject localeData) { 471 ScopedUtfChars localeName(env, javaLocaleName); 472 if (localeName.c_str() == NULL) { 473 return JNI_FALSE; 474 } 475 if (localeName.size() >= ULOC_FULLNAME_CAPACITY) { 476 return JNI_FALSE; // ICU has a fixed-length limit. 477 } 478 479 // Get the DateTimePatterns. 480 UErrorCode status = U_ZERO_ERROR; 481 bool foundDateTimePatterns = false; 482 for (LocaleNameIterator it(localeName.c_str(), status); it.HasNext(); it.Up()) { 483 if (getDateTimePatterns(env, localeData, it.Get())) { 484 foundDateTimePatterns = true; 485 break; 486 } 487 } 488 if (!foundDateTimePatterns) { 489 ALOGE("Couldn't find ICU DateTimePatterns for %s", localeName.c_str()); 490 return JNI_FALSE; 491 } 492 493 // Get the "Yesterday", "Today", and "Tomorrow" strings. 494 bool foundYesterdayTodayAndTomorrow = false; 495 for (LocaleNameIterator it(localeName.c_str(), status); it.HasNext(); it.Up()) { 496 if (getYesterdayTodayAndTomorrow(env, localeData, it.Get())) { 497 foundYesterdayTodayAndTomorrow = true; 498 break; 499 } 500 } 501 if (!foundYesterdayTodayAndTomorrow) { 502 ALOGE("Couldn't find ICU yesterday/today/tomorrow for %s", localeName.c_str()); 503 return JNI_FALSE; 504 } 505 506 status = U_ZERO_ERROR; 507 Locale locale = getLocale(env, javaLocaleName); 508 UniquePtr<Calendar> cal(Calendar::createInstance(locale, status)); 509 if (U_FAILURE(status)) { 510 return JNI_FALSE; 511 } 512 513 setIntegerField(env, localeData, "firstDayOfWeek", cal->getFirstDayOfWeek()); 514 setIntegerField(env, localeData, "minimalDaysInFirstWeek", cal->getMinimalDaysInFirstWeek()); 515 516 // Get DateFormatSymbols. 517 status = U_ZERO_ERROR; 518 DateFormatSymbols dateFormatSym(locale, status); 519 if (U_FAILURE(status)) { 520 return JNI_FALSE; 521 } 522 523 // Get AM/PM and BC/AD. 524 int32_t count = 0; 525 const UnicodeString* amPmStrs = dateFormatSym.getAmPmStrings(count); 526 setStringArrayField(env, localeData, "amPm", amPmStrs, count); 527 const UnicodeString* erasStrs = dateFormatSym.getEras(count); 528 setStringArrayField(env, localeData, "eras", erasStrs, count); 529 530 const UnicodeString* longMonthNames = 531 dateFormatSym.getMonths(count, DateFormatSymbols::FORMAT, DateFormatSymbols::WIDE); 532 setStringArrayField(env, localeData, "longMonthNames", longMonthNames, count); 533 const UnicodeString* shortMonthNames = 534 dateFormatSym.getMonths(count, DateFormatSymbols::FORMAT, DateFormatSymbols::ABBREVIATED); 535 setStringArrayField(env, localeData, "shortMonthNames", shortMonthNames, count); 536 const UnicodeString* tinyMonthNames = 537 dateFormatSym.getMonths(count, DateFormatSymbols::FORMAT, DateFormatSymbols::NARROW); 538 setStringArrayField(env, localeData, "tinyMonthNames", tinyMonthNames, count); 539 const UnicodeString* longWeekdayNames = 540 dateFormatSym.getWeekdays(count, DateFormatSymbols::FORMAT, DateFormatSymbols::WIDE); 541 setStringArrayField(env, localeData, "longWeekdayNames", longWeekdayNames, count); 542 const UnicodeString* shortWeekdayNames = 543 dateFormatSym.getWeekdays(count, DateFormatSymbols::FORMAT, DateFormatSymbols::ABBREVIATED); 544 setStringArrayField(env, localeData, "shortWeekdayNames", shortWeekdayNames, count); 545 const UnicodeString* tinyWeekdayNames = 546 dateFormatSym.getWeekdays(count, DateFormatSymbols::FORMAT, DateFormatSymbols::NARROW); 547 setStringArrayField(env, localeData, "tinyWeekdayNames", tinyWeekdayNames, count); 548 549 const UnicodeString* longStandAloneMonthNames = 550 dateFormatSym.getMonths(count, DateFormatSymbols::STANDALONE, DateFormatSymbols::WIDE); 551 setStringArrayField(env, localeData, "longStandAloneMonthNames", longStandAloneMonthNames, count); 552 const UnicodeString* shortStandAloneMonthNames = 553 dateFormatSym.getMonths(count, DateFormatSymbols::STANDALONE, DateFormatSymbols::ABBREVIATED); 554 setStringArrayField(env, localeData, "shortStandAloneMonthNames", shortStandAloneMonthNames, count); 555 const UnicodeString* tinyStandAloneMonthNames = 556 dateFormatSym.getMonths(count, DateFormatSymbols::STANDALONE, DateFormatSymbols::NARROW); 557 setStringArrayField(env, localeData, "tinyStandAloneMonthNames", tinyStandAloneMonthNames, count); 558 const UnicodeString* longStandAloneWeekdayNames = 559 dateFormatSym.getWeekdays(count, DateFormatSymbols::STANDALONE, DateFormatSymbols::WIDE); 560 setStringArrayField(env, localeData, "longStandAloneWeekdayNames", longStandAloneWeekdayNames, count); 561 const UnicodeString* shortStandAloneWeekdayNames = 562 dateFormatSym.getWeekdays(count, DateFormatSymbols::STANDALONE, DateFormatSymbols::ABBREVIATED); 563 setStringArrayField(env, localeData, "shortStandAloneWeekdayNames", shortStandAloneWeekdayNames, count); 564 const UnicodeString* tinyStandAloneWeekdayNames = 565 dateFormatSym.getWeekdays(count, DateFormatSymbols::STANDALONE, DateFormatSymbols::NARROW); 566 setStringArrayField(env, localeData, "tinyStandAloneWeekdayNames", tinyStandAloneWeekdayNames, count); 567 568 status = U_ZERO_ERROR; 569 570 // For numberPatterns and symbols. 571 setNumberPatterns(env, localeData, locale); 572 setDecimalFormatSymbolsData(env, localeData, locale); 573 574 jstring countryCode = env->NewStringUTF(Locale::createFromName(localeName.c_str()).getCountry()); 575 jstring internationalCurrencySymbol = ICU_getCurrencyCode(env, NULL, countryCode); 576 env->DeleteLocalRef(countryCode); 577 countryCode = NULL; 578 579 jstring currencySymbol = NULL; 580 if (internationalCurrencySymbol != NULL) { 581 currencySymbol = ICU_getCurrencySymbol(env, NULL, javaLocaleName, internationalCurrencySymbol); 582 } else { 583 internationalCurrencySymbol = env->NewStringUTF("XXX"); 584 } 585 if (currencySymbol == NULL) { 586 // This is the UTF-8 encoding of U+00A4 (CURRENCY SIGN). 587 currencySymbol = env->NewStringUTF("\xc2\xa4"); 588 } 589 setStringField(env, localeData, "currencySymbol", currencySymbol); 590 setStringField(env, localeData, "internationalCurrencySymbol", internationalCurrencySymbol); 591 592 return JNI_TRUE; 593 } 594 595 static jstring ICU_toLowerCase(JNIEnv* env, jclass, jstring javaString, jstring localeName) { 596 ScopedJavaUnicodeString scopedString(env, javaString); 597 if (!scopedString.valid()) { 598 return NULL; 599 } 600 UnicodeString& s(scopedString.unicodeString()); 601 UnicodeString original(s); 602 s.toLower(Locale::createFromName(ScopedUtfChars(env, localeName).c_str())); 603 return s == original ? javaString : env->NewString(s.getBuffer(), s.length()); 604 } 605 606 static jstring ICU_toUpperCase(JNIEnv* env, jclass, jstring javaString, jstring localeName) { 607 ScopedJavaUnicodeString scopedString(env, javaString); 608 if (!scopedString.valid()) { 609 return NULL; 610 } 611 UnicodeString& s(scopedString.unicodeString()); 612 UnicodeString original(s); 613 s.toUpper(Locale::createFromName(ScopedUtfChars(env, localeName).c_str())); 614 return s == original ? javaString : env->NewString(s.getBuffer(), s.length()); 615 } 616 617 static jstring versionString(JNIEnv* env, const UVersionInfo& version) { 618 char versionString[U_MAX_VERSION_STRING_LENGTH]; 619 u_versionToString(const_cast<UVersionInfo&>(version), &versionString[0]); 620 return env->NewStringUTF(versionString); 621 } 622 623 static jstring ICU_getCldrVersion(JNIEnv* env, jclass) { 624 UErrorCode status = U_ZERO_ERROR; 625 UVersionInfo cldrVersion; 626 ulocdata_getCLDRVersion(cldrVersion, &status); 627 return versionString(env, cldrVersion); 628 } 629 630 static jstring ICU_getIcuVersion(JNIEnv* env, jclass) { 631 UVersionInfo icuVersion; 632 u_getVersion(icuVersion); 633 return versionString(env, icuVersion); 634 } 635 636 static jstring ICU_getUnicodeVersion(JNIEnv* env, jclass) { 637 UVersionInfo unicodeVersion; 638 u_getUnicodeVersion(unicodeVersion); 639 return versionString(env, unicodeVersion); 640 } 641 642 static jobject ICU_getAvailableCurrencyCodes(JNIEnv* env, jclass) { 643 UErrorCode status = U_ZERO_ERROR; 644 UStringEnumeration e(ucurr_openISOCurrencies(UCURR_COMMON|UCURR_NON_DEPRECATED, &status)); 645 return fromStringEnumeration(env, status, "ucurr_openISOCurrencies", &e); 646 } 647 648 static jstring ICU_getBestDateTimePattern(JNIEnv* env, jclass, jstring javaSkeleton, jstring javaLocaleName) { 649 Locale locale = getLocale(env, javaLocaleName); 650 UErrorCode status = U_ZERO_ERROR; 651 UniquePtr<DateTimePatternGenerator> generator(DateTimePatternGenerator::createInstance(locale, status)); 652 if (maybeThrowIcuException(env, "DateTimePatternGenerator::createInstance", status)) { 653 return NULL; 654 } 655 656 ScopedJavaUnicodeString skeletonHolder(env, javaSkeleton); 657 if (!skeletonHolder.valid()) { 658 return NULL; 659 } 660 UnicodeString result(generator->getBestPattern(skeletonHolder.unicodeString(), status)); 661 if (maybeThrowIcuException(env, "DateTimePatternGenerator::getBestPattern", status)) { 662 return NULL; 663 } 664 665 return env->NewString(result.getBuffer(), result.length()); 666 } 667 668 static JNINativeMethod gMethods[] = { 669 NATIVE_METHOD(ICU, addLikelySubtags, "(Ljava/lang/String;)Ljava/lang/String;"), 670 NATIVE_METHOD(ICU, getAvailableBreakIteratorLocalesNative, "()[Ljava/lang/String;"), 671 NATIVE_METHOD(ICU, getAvailableCalendarLocalesNative, "()[Ljava/lang/String;"), 672 NATIVE_METHOD(ICU, getAvailableCollatorLocalesNative, "()[Ljava/lang/String;"), 673 NATIVE_METHOD(ICU, getAvailableCurrencyCodes, "()[Ljava/lang/String;"), 674 NATIVE_METHOD(ICU, getAvailableDateFormatLocalesNative, "()[Ljava/lang/String;"), 675 NATIVE_METHOD(ICU, getAvailableLocalesNative, "()[Ljava/lang/String;"), 676 NATIVE_METHOD(ICU, getAvailableNumberFormatLocalesNative, "()[Ljava/lang/String;"), 677 NATIVE_METHOD(ICU, getBestDateTimePattern, "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;"), 678 NATIVE_METHOD(ICU, getCldrVersion, "()Ljava/lang/String;"), 679 NATIVE_METHOD(ICU, getCurrencyCode, "(Ljava/lang/String;)Ljava/lang/String;"), 680 NATIVE_METHOD(ICU, getCurrencyDisplayName, "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;"), 681 NATIVE_METHOD(ICU, getCurrencyFractionDigits, "(Ljava/lang/String;)I"), 682 NATIVE_METHOD(ICU, getCurrencySymbol, "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;"), 683 NATIVE_METHOD(ICU, getDisplayCountryNative, "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;"), 684 NATIVE_METHOD(ICU, getDisplayLanguageNative, "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;"), 685 NATIVE_METHOD(ICU, getDisplayVariantNative, "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;"), 686 NATIVE_METHOD(ICU, getISO3CountryNative, "(Ljava/lang/String;)Ljava/lang/String;"), 687 NATIVE_METHOD(ICU, getISO3LanguageNative, "(Ljava/lang/String;)Ljava/lang/String;"), 688 NATIVE_METHOD(ICU, getISOCountriesNative, "()[Ljava/lang/String;"), 689 NATIVE_METHOD(ICU, getISOLanguagesNative, "()[Ljava/lang/String;"), 690 NATIVE_METHOD(ICU, getIcuVersion, "()Ljava/lang/String;"), 691 NATIVE_METHOD(ICU, getScript, "(Ljava/lang/String;)Ljava/lang/String;"), 692 NATIVE_METHOD(ICU, getUnicodeVersion, "()Ljava/lang/String;"), 693 NATIVE_METHOD(ICU, initLocaleDataImpl, "(Ljava/lang/String;Llibcore/icu/LocaleData;)Z"), 694 NATIVE_METHOD(ICU, toLowerCase, "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;"), 695 NATIVE_METHOD(ICU, toUpperCase, "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;"), 696 }; 697 void register_libcore_icu_ICU(JNIEnv* env) { 698 std::string path; 699 path = u_getDataDirectory(); 700 path += "/"; 701 path += U_ICUDATA_NAME; 702 path += ".dat"; 703 704 #define FAIL_WITH_STRERROR(s) \ 705 ALOGE("Couldn't " s " '%s': %s", path.c_str(), strerror(errno)); \ 706 abort(); 707 #define MAYBE_FAIL_WITH_ICU_ERROR(s) \ 708 if (status != U_ZERO_ERROR) {\ 709 ALOGE("Couldn't initialize ICU (" s "): %s (%s)", u_errorName(status), path.c_str()); \ 710 abort(); \ 711 } 712 713 // Open the file and get its length. 714 ScopedFd fd(open(path.c_str(), O_RDONLY)); 715 if (fd.get() == -1) { 716 FAIL_WITH_STRERROR("open"); 717 } 718 struct stat sb; 719 if (fstat(fd.get(), &sb) == -1) { 720 FAIL_WITH_STRERROR("stat"); 721 } 722 723 // Map it. 724 void* data = mmap(NULL, sb.st_size, PROT_READ, MAP_SHARED, fd.get(), 0); 725 if (data == MAP_FAILED) { 726 FAIL_WITH_STRERROR("mmap"); 727 } 728 729 // Tell the kernel that accesses are likely to be random rather than sequential. 730 if (madvise(data, sb.st_size, MADV_RANDOM) == -1) { 731 FAIL_WITH_STRERROR("madvise(MADV_RANDOM)"); 732 } 733 734 // Tell ICU to use our memory-mapped data. 735 UErrorCode status = U_ZERO_ERROR; 736 udata_setCommonData(data, &status); 737 MAYBE_FAIL_WITH_ICU_ERROR("udata_setCommonData"); 738 // Tell ICU it can *only* use our memory-mapped data. 739 udata_setFileAccess(UDATA_NO_FILES, &status); 740 MAYBE_FAIL_WITH_ICU_ERROR("udata_setFileAccess"); 741 742 // Failures to find the ICU data tend to be somewhat obscure because ICU loads its data on first 743 // use, which can be anywhere. Force initialization up front so we can report a nice clear error 744 // and bail. 745 u_init(&status); 746 MAYBE_FAIL_WITH_ICU_ERROR("u_init"); 747 jniRegisterNativeMethods(env, "libcore/icu/ICU", gMethods, NELEM(gMethods)); 748 } 749