Use cache to get system locale
[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() {
16   static SystemLocale inst;
17
18   return inst;
19 }
20
21 SystemLocale::SystemLocale() {
22   vconf_notify_key_changed(VCONFKEY_LANGSET, LanChangedCb, this);
23   char* lang = vconf_get_str(VCONFKEY_LANGSET);
24   lang_ = lang ? std::string(lang) : "";
25   free(lang);
26   SetLocale();
27 }
28
29 SystemLocale::~SystemLocale() {
30   vconf_ignore_key_changed(VCONFKEY_LANGSET, LanChangedCb);
31 }
32
33 void SystemLocale::RegisterEvent(IEvent* listener) {
34   listener_ = listener;
35 }
36
37 void SystemLocale::UnRegisterEvent() {
38   listener_ = nullptr;
39 }
40
41 const std::string& SystemLocale::Get() const {
42   return locale_;
43 }
44
45 void SystemLocale::SetLocale() {
46   if (lang_.empty() || lang_.length() < 5) {
47     locale_ = DEFAULT_LOCALE;
48     return;
49   }
50
51   char local_buf[6] = {0, };
52   snprintf(local_buf, sizeof(local_buf), "%c%c-%c%c",
53       lang_[0], lang_[1], tolower(lang_[3]), tolower(lang_[4]));
54   locale_ = local_buf;
55   if (listener_)
56     listener_->OnChanged(locale_);
57 }
58
59 void SystemLocale::LanChangedCb(keynode_t* node, void* user_data) {
60   char* val = vconf_keynode_get_str(node);
61   if (val == nullptr)
62     return;
63   SystemLocale* sl = reinterpret_cast<SystemLocale*>(user_data);
64   sl->lang_ = val;
65   sl->SetLocale();
66 }
67
68 }  // namespace pkgmgr_common