2 * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 * @file localization_utils.cpp
18 * @author Bartosz Janiak (b.janiak@samsung.com)
22 #include <dpl/localization/localization_utils.h>
24 #include <dpl/foreach.h>
25 #include <dpl/mutex.h>
27 namespace LocalizationUtils {
28 static LanguageTagsList m_systemLanguageTags;
29 static LanguageTagsList m_languageTags;
30 static DPL::ReadWriteMutex m_readWriteMutex;
32 template<typename StringType>
33 void FindAndReplace(StringType& source,
34 const StringType& find,
35 const StringType& replace)
38 while ((pos = source.find(find, pos)) != StringType::npos) {
39 source.replace(pos, find.length(), replace);
40 pos += replace.length();
44 DPL::String BCP47LanguageTagToLocale(const DPL::String& inLanguageTag)
46 DPL::String languageTag(inLanguageTag);
47 FindAndReplace(languageTag, DPL::String(L"-"), DPL::String(L"_"));
51 DPL::String LocaleToBCP47LanguageTag(const DPL::String& inLocaleString)
53 DPL::String localeString = inLocaleString.substr(
57 FindAndReplace(localeString, DPL::String(L"_"), DPL::String(L"-"));
61 void UpdateUserAgentLanguageTags()
63 // WARNING!!!!! This function shall be called
64 // only when mutex is locked in readWriteMode!
66 m_languageTags.clear();
68 FOREACH(i, m_systemLanguageTags) {
69 DPL::String tag = LocaleToBCP47LanguageTag(*i);
70 while (true) { //W3C Packaging 9. Step 5. 2. D
71 if (tag.empty()) { continue; }
73 LogDebug("Adding user locale '" << tag << "'");
74 m_languageTags.push_back(tag);
76 size_t subtagPos = tag.find_last_of(L"-");
77 if (subtagPos == DPL::String::npos) {
80 tag = tag.substr(0, subtagPos);
84 m_languageTags.push_back(L"en");
85 m_languageTags.push_back(L"");
88 void SetSystemLanguageTags(const LanguageTagsList& tags)
90 DPL::ReadWriteMutex::ScopedWriteLock lock(&m_readWriteMutex);
91 if (m_systemLanguageTags != tags) {
92 m_systemLanguageTags = tags;
93 UpdateUserAgentLanguageTags();
97 LanguageTagsList GetUserAgentLanguageTags()
99 DPL::ReadWriteMutex::ScopedReadLock lock(&m_readWriteMutex);
100 return m_languageTags;