Delay server ready timing until creating cache
[platform/core/appfw/pkgmgr-info.git] / src / common / system_locale.cc
1 // Copyright (c) 2021 Samsung Electronics Co., Ltd All Rights Reserved
2 // Use of this source code is governed by an apache-2.0 license that can be
3 // found in the LICENSE file.
4
5 #include "system_locale.hh"
6
7 namespace {
8
9 constexpr const char DEFAULT_LOCALE[] = "No Locale";
10
11 }  // namespace
12
13 namespace pkgmgr_common {
14
15 SystemLocale& SystemLocale::GetInst(bool is_online) {
16   static SystemLocale inst(is_online);
17
18   return inst;
19 }
20
21 SystemLocale::SystemLocale(bool is_online) : is_online_(is_online) {
22   if (is_online_)
23     vconf_notify_key_changed(VCONFKEY_LANGSET, LanChangedCb, this);
24
25   char* lang = vconf_get_str(VCONFKEY_LANGSET);
26   lang_ = lang ? std::string(lang) : "";
27   free(lang);
28   SetLocale();
29 }
30
31 SystemLocale::~SystemLocale() {
32   if (is_online_)
33     vconf_ignore_key_changed(VCONFKEY_LANGSET, LanChangedCb);
34 }
35
36 void SystemLocale::RegisterEvent(IEvent* listener) {
37   listener_ = listener;
38 }
39
40 void SystemLocale::UnRegisterEvent() {
41   listener_ = nullptr;
42 }
43
44 const std::string& SystemLocale::Get() const {
45   return locale_;
46 }
47
48 void SystemLocale::SetLocale() {
49   std::string code = lang_.substr(0, lang_.find_first_of(".@"));
50   if (code.empty()) {
51     locale_ = DEFAULT_LOCALE;
52     return;
53   }
54
55   size_t it = code.find('_');
56   if (it == std::string::npos) {
57     locale_ = std::move(code);
58   } else {
59     code[it] = '-';
60     locale_ = std::move(code);
61
62     for (size_t i = it + 1; i < locale_.size(); ++i)
63       locale_[i] = tolower(locale_[i]);
64   }
65
66   if (listener_)
67     listener_->OnChanged(locale_);
68 }
69
70 void SystemLocale::LanChangedCb(keynode_t* node, void* user_data) {
71   char* val = vconf_keynode_get_str(node);
72
73   if (val == nullptr)
74     return;
75
76   SystemLocale* sl = reinterpret_cast<SystemLocale*>(user_data);
77   sl->lang_ = val;
78   sl->SetLocale();
79 }
80
81 }  // namespace pkgmgr_common