Refactoring common class
[platform/framework/web/nwrt.git] / src / common / locale_manager.cc
1 // Copyright 2015 Samsung Electronics Co, Ltd. 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.
4
5 #include "common/locale_manager.h"
6
7 #include <runtime_info.h>
8 #include <memory>
9 #include <algorithm>
10
11 #include "common/logger.h"
12 #include "common/file_utils.h"
13
14 namespace wrt {
15
16 namespace {
17
18 std::string localeToBCP47LangTag(
19     const std::string locale) {
20   // Cut off codepage information from given string (if any exists)
21   // i.e. change en_US.UTF-8 into en_US */
22   std::string lang = locale.substr(0, locale.find_first_of("."));
23
24   // Replace all '_' with '-'
25   std::replace(lang.begin(), lang.end(), '_', '-');
26   return lang;
27 }
28
29 }  // namespace
30
31
32 LocaleManager::LocaleManager() {
33   UpdateSystemLocale();
34 }
35
36 LocaleManager::~LocaleManager() {
37 }
38
39 void LocaleManager::SetDefaultLocale(const std::string& locale) {
40   if (!default_locale_.empty() && system_locales_.size() > 0 &&
41        system_locales_.back() == default_locale_) {
42     system_locales_.pop_back();
43   }
44   default_locale_ = locale;
45   if (!default_locale_.empty()) {
46     system_locales_.push_back(locale);
47   }
48 }
49
50 void LocaleManager::UpdateSystemLocale() {
51   char* str = NULL;
52   if (RUNTIME_INFO_ERROR_NONE !=
53       runtime_info_get_value_string(RUNTIME_INFO_KEY_LANGUAGE, &str)
54      || str == NULL) {
55     return;
56   }
57   std::string lang = localeToBCP47LangTag(str);
58
59   if (lang.length() == 0) {
60     LoggerE("Language tag was invalid");
61     return;
62   }
63
64   system_locales_.clear();
65   while (true) {
66     LoggerD("Processing language description: %s", lang.c_str());
67     system_locales_.push_back(lang);
68
69     // compatibility with lower language Tag by SDK
70     std::string lower = lang;
71     std::transform(lower.begin(), lower.end(), lower.begin(), ::tolower);
72     if (lower != lang) {
73       system_locales_.push_back(lower);
74     }
75     size_t position = lang.find_last_of("-");
76     if (position == std::string::npos) {
77       break;
78     }
79     lang = lang.substr(0, position);
80   }
81   if (!default_locale_.empty()) {
82     system_locales_.push_back(default_locale_);
83   }
84 }
85
86 }  // namespace wrt