1/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */
2/* If you are missing that file, acquire a complete release at teeworlds.com. */
3
4#include "localization.h"
5
6#include <base/io.h>
7#include <base/log.h>
8#include <base/os.h>
9#include <base/str.h>
10
11#include <engine/console.h>
12#include <engine/shared/linereader.h>
13#include <engine/shared/protocol.h>
14#include <engine/storage.h>
15
16const char *Localize(const char *pStr, const char *pContext)
17{
18 const char *pNewStr = g_Localization.FindString(Hash: str_quickhash(str: pStr), ContextHash: str_quickhash(str: pContext));
19 return pNewStr ? pNewStr : pStr;
20}
21
22void CLocalizationDatabase::LoadIndexfile(IStorage *pStorage, IConsole *pConsole)
23{
24 m_vLanguages.clear();
25
26 const std::vector<std::string> vEnglishLanguageCodes = {"en"};
27 m_vLanguages.emplace_back(args: "English", args: "", args: 826, args: vEnglishLanguageCodes);
28
29 const char *pFilename = "languages/index.txt";
30 CLineReader LineReader;
31 if(!LineReader.OpenFile(File: pStorage->OpenFile(pFilename, Flags: IOFLAG_READ, Type: IStorage::TYPE_ALL)))
32 {
33 log_error("localization", "Couldn't open index file '%s'", pFilename);
34 return;
35 }
36
37 while(const char *pLine = LineReader.Get())
38 {
39 if(!str_length(str: pLine) || pLine[0] == '#') // skip empty lines and comments
40 continue;
41
42 char aEnglishName[128];
43 str_copy(dst&: aEnglishName, src: pLine);
44
45 pLine = LineReader.Get();
46 if(!pLine)
47 {
48 log_error("localization", "Unexpected end of index file after language '%s'", aEnglishName);
49 break;
50 }
51 if(!str_startswith(str: pLine, prefix: "== "))
52 {
53 log_error("localization", "Missing native name for language '%s'", aEnglishName);
54 (void)LineReader.Get();
55 (void)LineReader.Get();
56 continue;
57 }
58 char aNativeName[128];
59 str_copy(dst&: aNativeName, src: pLine + 3);
60
61 pLine = LineReader.Get();
62 if(!pLine)
63 {
64 log_error("localization", "Unexpected end of index file after language '%s'", aEnglishName);
65 break;
66 }
67 if(!str_startswith(str: pLine, prefix: "== "))
68 {
69 log_error("localization", "Missing country code for language '%s'", aEnglishName);
70 (void)LineReader.Get();
71 continue;
72 }
73 char aCountryCode[128];
74 str_copy(dst&: aCountryCode, src: pLine + 3);
75 int CountryCode;
76 if(!str_toint(str: aCountryCode, out: &CountryCode))
77 {
78 log_error("localization", "Country code '%s' for language '%s' is not a number", aCountryCode, aEnglishName);
79 (void)LineReader.Get();
80 continue;
81 }
82 if(!in_range(a: CountryCode, lower: CountryCode::MINIMUM, upper: CountryCode::MAXIMUM))
83 {
84 log_error("localization", "Country code '%d' for language '%s' is not within valid code range [%d..%d]", CountryCode, aEnglishName, CountryCode::MINIMUM, CountryCode::MAXIMUM);
85 (void)LineReader.Get();
86 continue;
87 }
88
89 pLine = LineReader.Get();
90 if(!pLine)
91 {
92 log_error("localization", "Unexpected end of index file after language '%s'", aEnglishName);
93 break;
94 }
95 if(!str_startswith(str: pLine, prefix: "== "))
96 {
97 log_error("localization", "Missing language codes for language '%s'", aEnglishName);
98 continue;
99 }
100 const char *pLanguageCodes = pLine + 3;
101 char aLanguageCode[256];
102 std::vector<std::string> vLanguageCodes;
103 while((pLanguageCodes = str_next_token(str: pLanguageCodes, delim: ";", buffer: aLanguageCode, buffer_size: sizeof(aLanguageCode))))
104 {
105 if(aLanguageCode[0])
106 {
107 vLanguageCodes.emplace_back(args&: aLanguageCode);
108 }
109 }
110 if(vLanguageCodes.empty())
111 {
112 log_error("localization", "At least one language code required for language '%s'", aEnglishName);
113 continue;
114 }
115
116 char aFilename[IO_MAX_PATH_LENGTH];
117 str_format(buffer: aFilename, buffer_size: sizeof(aFilename), format: "languages/%s.txt", aEnglishName);
118 m_vLanguages.emplace_back(args&: aNativeName, args&: aFilename, args&: CountryCode, args&: vLanguageCodes);
119 }
120
121 std::sort(first: m_vLanguages.begin(), last: m_vLanguages.end());
122}
123
124void CLocalizationDatabase::SelectDefaultLanguage(IConsole *pConsole, char *pFilename, size_t Length) const
125{
126 if(Languages().empty())
127 return;
128 if(Languages().size() == 1)
129 {
130 str_copy(dst: pFilename, src: Languages()[0].m_Filename.c_str(), dst_size: Length);
131 return;
132 }
133
134 char aLocaleStr[128];
135 os_locale_str(locale: aLocaleStr, length: sizeof(aLocaleStr));
136
137 log_info("localization", "Choosing default language based on user locale '%s'", aLocaleStr);
138
139 while(true)
140 {
141 const CLanguage *pPrefixMatch = nullptr;
142 for(const auto &Language : Languages())
143 {
144 for(const auto &LanguageCode : Language.m_vLanguageCodes)
145 {
146 if(LanguageCode == aLocaleStr)
147 {
148 // Exact match found, use it immediately
149 str_copy(dst: pFilename, src: Language.m_Filename.c_str(), dst_size: Length);
150 return;
151 }
152 else if(LanguageCode.starts_with(x: aLocaleStr))
153 {
154 // Locale is prefix of language code, e.g. locale is "en" and current language is "en-US"
155 pPrefixMatch = &Language;
156 }
157 }
158 }
159 // Use prefix match if no exact match was found
160 if(pPrefixMatch)
161 {
162 str_copy(dst: pFilename, src: pPrefixMatch->m_Filename.c_str(), dst_size: Length);
163 return;
164 }
165
166 // Remove last segment of locale string and try again with more generic locale, e.g. "en-US" -> "en"
167 int i = str_length(str: aLocaleStr) - 1;
168 for(; i >= 0; --i)
169 {
170 if(aLocaleStr[i] == '-')
171 {
172 aLocaleStr[i] = '\0';
173 break;
174 }
175 }
176
177 // Stop if no more locale segments are left
178 if(i <= 0)
179 break;
180 }
181}
182
183bool CLocalizationDatabase::Load(const char *pFilename, IStorage *pStorage, IConsole *pConsole)
184{
185 // empty string means unload
186 if(pFilename[0] == 0)
187 {
188 m_vStrings.clear();
189 m_StringsHeap.Reset();
190 return true;
191 }
192
193 CLineReader LineReader;
194 if(!LineReader.OpenFile(File: pStorage->OpenFile(pFilename, Flags: IOFLAG_READ, Type: IStorage::TYPE_ALL)))
195 return false;
196
197 log_info("localization", "loaded '%s'", pFilename);
198 m_vStrings.clear();
199 m_StringsHeap.Reset();
200
201 std::string Context;
202 std::string Origin;
203 std::string Replacement;
204 int Line = 0;
205 while(const char *pLine = LineReader.Get())
206 {
207 Line++;
208 if(pLine[0] == '\0')
209 continue;
210
211 if(pLine[0] == '#') // skip comments
212 continue;
213
214 if(pLine[0] == '[') // context
215 {
216 const size_t Len = str_length(str: pLine);
217 if(Len <= 2 || pLine[Len - 1] != ']')
218 {
219 log_error("localization", "malformed context '%s' on line %d", pLine, Line);
220 continue;
221 }
222 Context = pLine + 1;
223 Context.erase(pos: Len - 2); // remove ']'
224 pLine = LineReader.Get();
225 if(!pLine)
226 {
227 log_error("localization", "unexpected end of file after context line '%s' on line %d", Context.c_str(), Line);
228 break;
229 }
230 Line++;
231 }
232 else
233 {
234 Context = "";
235 }
236
237 Origin = pLine;
238 str_unescape_newlines(str: Origin.data());
239
240 const char *pReplacement = LineReader.Get();
241 if(!pReplacement)
242 {
243 log_error("localization", "unexpected end of file after original '%s' on line %d", Origin.c_str(), Line);
244 break;
245 }
246 Line++;
247
248 if(pReplacement[0] != '=' || pReplacement[1] != '=' || pReplacement[2] != ' ')
249 {
250 log_error("localization", "malformed replacement '%s' for original '%s' on line %d", pReplacement, Origin.c_str(), Line);
251 continue;
252 }
253
254 Replacement = pReplacement + 3;
255 str_unescape_newlines(str: Replacement.data());
256
257 AddString(pOrgStr: Origin.c_str(), pNewStr: Replacement.c_str(), pContext: Context.c_str());
258 }
259 std::sort(first: m_vStrings.begin(), last: m_vStrings.end());
260 return true;
261}
262
263void CLocalizationDatabase::AddString(const char *pOrgStr, const char *pNewStr, const char *pContext)
264{
265 m_vStrings.emplace_back(args: str_quickhash(str: pOrgStr), args: str_quickhash(str: pContext), args: m_StringsHeap.StoreString(pSrc: *pNewStr ? pNewStr : pOrgStr));
266}
267
268const char *CLocalizationDatabase::FindString(unsigned Hash, unsigned ContextHash) const
269{
270 CString String;
271 String.m_Hash = Hash;
272 String.m_ContextHash = ContextHash;
273 String.m_pReplacement = nullptr;
274 auto Range1 = std::equal_range(first: m_vStrings.begin(), last: m_vStrings.end(), val: String);
275 if(std::distance(first: Range1.first, last: Range1.second) == 1)
276 return Range1.first->m_pReplacement;
277
278 const unsigned DefaultHash = str_quickhash(str: "");
279 if(ContextHash != DefaultHash)
280 {
281 // Do another lookup with the default context hash
282 String.m_ContextHash = DefaultHash;
283 auto Range2 = std::equal_range(first: m_vStrings.begin(), last: m_vStrings.end(), val: String);
284 if(std::distance(first: Range2.first, last: Range2.second) == 1)
285 return Range2.first->m_pReplacement;
286 }
287
288 return nullptr;
289}
290
291CLocalizationDatabase g_Localization;
292