1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "ui/base/l10n/l10n_util_android.h"
7 #include "base/android/jni_android.h"
8 #include "base/android/jni_string.h"
9 #include "base/android/scoped_java_ref.h"
10 #include "base/i18n/rtl.h"
11 #include "base/logging.h"
12 #include "base/strings/string_util.h"
13 #include "jni/LocalizationUtils_jni.h"
14 #include "third_party/icu/source/common/unicode/uloc.h"
18 jboolean IsRTL(JNIEnv* env, jclass clazz) {
19 return base::i18n::IsRTL();
22 jint GetFirstStrongCharacterDirection(JNIEnv* env, jclass clazz,
24 return base::i18n::GetFirstStrongCharacterDirection(
25 base::android::ConvertJavaStringToUTF16(env, string));
28 std::string GetDefaultLocale() {
29 JNIEnv* env = base::android::AttachCurrentThread();
30 ScopedJavaLocalRef<jstring> locale = Java_LocalizationUtils_getDefaultLocale(
32 return ConvertJavaStringToUTF8(locale);
37 // Common prototype of ICU uloc_getXXX() functions.
38 typedef int32_t (*UlocGetComponentFunc)(const char*, char*, int32_t,
41 std::string GetLocaleComponent(const std::string& locale,
42 UlocGetComponentFunc uloc_func,
43 int32_t max_capacity) {
45 UErrorCode error = U_ZERO_ERROR;
46 int32_t actual_length = uloc_func(locale.c_str(),
47 WriteInto(&result, max_capacity),
50 DCHECK(U_SUCCESS(error));
51 DCHECK(actual_length < max_capacity);
52 result.resize(actual_length);
56 ScopedJavaLocalRef<jobject> NewJavaLocale(
58 const std::string& locale) {
59 // TODO(wangxianzhu): Use new Locale API once Android supports scripts.
60 std::string language = GetLocaleComponent(
61 locale, uloc_getLanguage, ULOC_LANG_CAPACITY);
62 std::string country = GetLocaleComponent(
63 locale, uloc_getCountry, ULOC_COUNTRY_CAPACITY);
64 std::string variant = GetLocaleComponent(
65 locale, uloc_getVariant, ULOC_FULLNAME_CAPACITY);
66 return Java_LocalizationUtils_getJavaLocale(env,
67 base::android::ConvertUTF8ToJavaString(env, language).obj(),
68 base::android::ConvertUTF8ToJavaString(env, country).obj(),
69 base::android::ConvertUTF8ToJavaString(env, variant).obj());
74 string16 GetDisplayNameForLocale(const std::string& locale,
75 const std::string& display_locale) {
76 JNIEnv* env = base::android::AttachCurrentThread();
77 ScopedJavaLocalRef<jobject> java_locale =
78 NewJavaLocale(env, locale);
79 ScopedJavaLocalRef<jobject> java_display_locale =
80 NewJavaLocale(env, display_locale);
82 ScopedJavaLocalRef<jstring> java_result(
83 Java_LocalizationUtils_getDisplayNameForLocale(
86 java_display_locale.obj()));
87 return ConvertJavaStringToUTF16(java_result);
90 bool RegisterLocalizationUtil(JNIEnv* env) {
91 return RegisterNativesImpl(env);
94 } // namespace l10n_util