Debian Codegraph @

src/Main/locale.cxx

raw symbols SCIP
1 // locale.cxx -- FlightGear Localization Support
2 //
3 // Written by Thorsten Brehm, started April 2012.
4 //
5 // Copyright (C) 2012 Thorsten Brehm - brehmt (at) gmail com
6 //
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License as
9 // published by the Free Software Foundation; either version 2 of the
10 // License, or (at your option) any later version.
11 //
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 // General Public License for more details.
16 //
17 // You should have received a copy of the GNU General Public License
18 // along with this program; if not, write to the Free Software
19 // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.
20
21 #include <config.h>
22
23 #ifdef HAVE_WINDOWS_H
24 #include <windows.h>
25 #endif
26
27 #include <cstdio>
28 #include <cstring> // std::strlen()
29 #include <cstddef> // std::size_t
30 #include <cassert>
31
32 #include <simgear/misc/strutils.hxx>
33 #include <simgear/props/props.hxx>
34 #include <simgear/props/props_io.hxx>
35 #include <simgear/structure/exception.hxx>
36
37 #include "fg_props.hxx"
38 #include "locale.hxx"
39 #include "XLIFFParser.hxx"
40
41 #include <Add-ons/AddonMetadataParser.hxx>
42
43 using std::vector;
44 using std::string;
45 namespace strutils = simgear::strutils;
46
47 FGLocale::FGLocale(SGPropertyNode* root) :
48 _intl(root->getNode("/sim/intl", 0, true)),
49 _defaultLocale(_intl->getChild("locale", 0, true))
50 {
51 }
52
53 FGLocale::~FGLocale()
54 {
55 }
56
57 // Static method
58 string FGLocale::removeEncodingPart(const string& locale)
59 {
60 string res;
61 std::size_t pos = locale.find('.');
62
63 if (pos != string::npos)
64 {
65 assert(pos > 0);
66 res = locale.substr(0, pos);
67 } else {
68 res = locale;
69 }
70
71 return res;
72 }
73
74 string removeLocalePart(const string& locale)
75 {
76 std::size_t pos = locale.find('_');
77 if (pos == string::npos) {
78 pos = locale.find('-');
79 }
80
81 if (pos == string::npos)
82 return {};
83
84 return locale.substr(0, pos);
85 }
86
87 #ifdef _WIN32
88
89
90 string_list
91 FGLocale::getUserLanguages()
92 {
93 unsigned long bufSize = 128;
94 wchar_t* localeNameBuf = reinterpret_cast<wchar_t*>(alloca(bufSize));
95 unsigned long numLanguages = 0;
96
97 bool ok = GetUserPreferredUILanguages(MUI_LANGUAGE_NAME, &numLanguages,
98 localeNameBuf, &bufSize);
99 if (!ok) {
100 // if we have a lot of languages, can fail, allocate a bigger
101 // buffer
102 if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
103 bufSize = 0;
104 GetUserPreferredUILanguages(MUI_LANGUAGE_NAME, &numLanguages,
105 nullptr, &bufSize);
106 localeNameBuf = reinterpret_cast<wchar_t*>(alloca(bufSize));
107 ok = GetUserPreferredUILanguages(MUI_LANGUAGE_NAME, &numLanguages,
108 localeNameBuf, &bufSize);
109 }
110 }
111
112 if (!ok) {
113 SG_LOG(SG_GENERAL, SG_WARN, "Failed to detected user locale via GetUserPreferredUILanguages");
114 return{};
115 }
116
117 string_list result;
118 result.reserve(numLanguages);
119 for (unsigned int l = 0; l < numLanguages; ++l) {
120 std::wstring ws(localeNameBuf);
121 if (ws.empty())
122 break;
123
124 // skip to next string, past this string and trailing NULL
125 localeNameBuf += (ws.size() + 1);
126 result.push_back(simgear::strutils::convertWStringToUtf8(ws));
127 SG_LOG(SG_GENERAL, SG_INFO, "User langauge " << l << ":" << result.back());
128 }
129
130 return result;
131 }
132 #elif __APPLE__
133 // implemented in CocoaHelpers.mm
134 #else
135 /**
136 * Determine locale/language settings on Linux/Unix.
137 */
138 string_list
139 FGLocale::getUserLanguages()
140 {
141 string_list result;
142 const char* langEnv = ::getenv("LANG");
143
144 if (langEnv) {
145 // Remove character encoding from the locale spec, i.e. "de_DE.UTF-8"
146 // becomes "de_DE". This is for consistency with the Windows and MacOS
147 // implementations of this method.
148 result.push_back(removeEncodingPart(langEnv));
149 }
150
151 return result;
152 }
153 #endif
154
155 // Search property tree for matching locale description
156 SGPropertyNode*
157 FGLocale::findLocaleNode(const string& localeSpec)
158 {
159 SGPropertyNode* node = nullptr;
160 // Remove the character encoding part of the locale spec, i.e.,
161 // "de_DE.utf8" => "de_DE"
162 string language = removeEncodingPart(localeSpec);
163
164 SG_LOG(SG_GENERAL, SG_DEBUG,
165 "Searching language resource for locale: '" << language << "'");
166 // search locale using full string
167 vector<SGPropertyNode_ptr> localeList = _intl->getChildren("locale");
168
169 for (size_t i = 0; i < localeList.size(); i++)
170 {
171 vector<SGPropertyNode_ptr> langList = localeList[i]->getChildren("lang");
172
173 for (size_t j = 0; j < langList.size(); j++)
174 {
175 if (!language.compare(langList[j]->getStringValue()))
176 {
177 SG_LOG(SG_GENERAL, SG_INFO, "Found language resource for: " << language);
178 return localeList[i];
179 }
180 }
181 }
182
183 // try country's default resource, i.e. "de_DE" => "de"
184 const auto justTheLanguage = removeLocalePart(language);
185 if (!justTheLanguage.empty()) {
186 node = findLocaleNode(justTheLanguage);
187 if (node)
188 return node;
189 }
190
191 return nullptr;
192 }
193
194 // Select the language. When no language is given (nullptr),
195 // a default is determined matching the system locale.
196 bool FGLocale::selectLanguage(const std::string& language)
197 {
198 _languages = getUserLanguages();
199 if (_languages.empty()) {
200 // Use plain C locale if nothing is available.
201 SG_LOG(SG_GENERAL, SG_WARN, "Unable to detect system language" );
202 _languages.push_back("C");
203 }
204
205 // if we were passed a language option, try it first
206 if (!language.empty()) {
207 const auto normalizedLang = strutils::replace(language, "-", "_");
208 _languages.insert(_languages.begin(), normalizedLang);
209 }
210
211 _currentLocaleString = removeEncodingPart(_languages.front());
212 if (_currentLocaleString == "C") {
213 _currentLocaleString.clear();
214 }
215 // Record the current locale at /sim/intl/current-locale
216 _intl->getChild("current-locale", 0, true)
217 ->setStringValue(_currentLocaleString);
218
219 _currentLocale = nullptr;
220
221 for (const string& lang : _languages) {
222 SG_LOG(SG_GENERAL, SG_DEBUG,
223 "Trying to find locale for '" << lang << "'");
224 _currentLocale = findLocaleNode(lang);
225
226 if (_currentLocale) {
227 SG_LOG(SG_GENERAL, SG_DEBUG,
228 "Found locale for '" << lang << "' at '" <<
229 _currentLocale->getPath() << "'");
230 break;
231 }
232 }
233
234 if (_currentLocale && _currentLocale->hasChild("xliff")) {
235 parseXLIFF(_currentLocale);
236 }
237
238
239 // load resource for system messages (translations for fgfs internal messages)
240 loadResource("sys");
241 loadResource("atc");
242 loadResource("tips");
243 loadResource("weather-scenarios");
244
245 _inited = true;
246 if (!_currentLocale && !_currentLocaleString.empty()) {
247 SG_LOG(SG_GENERAL, SG_WARN,
248 "System locale not found or no internationalization settings specified in defaults.xml. Using default (en).");
249 return false;
250 }
251
252 return true;
253 }
254
255 void FGLocale::clear()
256 {
257 _inited = false;
258 _currentLocaleString.clear();
259 _languages.clear();
260
261 if (_currentLocale && (_currentLocale != _defaultLocale)) {
262 // remove loaded strings, so we don't duplicate
263 _currentLocale->removeChild("strings");
264 }
265
266 _currentLocale.clear();
267 }
268
269 // Return the preferred language according to user choice and/or settings
270 // (e.g., 'fr_FR', or the empty string if nothing could be found).
271 std::string
272 FGLocale::getPreferredLanguage() const
273 {
274 return _currentLocaleString;
275 }
276
277 void FGLocale::parseXLIFF(SGPropertyNode* localeNode)
278 {
279 SGPath path(globals->get_fg_root());
280 SGPath xliffPath = path / localeNode->getStringValue("xliff");
281 if (!xliffPath.exists()) {
282 SG_LOG(SG_GENERAL, SG_ALERT, "No XLIFF file at " << xliffPath);
283 } else {
284 SG_LOG(SG_GENERAL, SG_INFO, "Loading XLIFF file at " << xliffPath);
285 SGPropertyNode_ptr stringNode = localeNode->getNode("strings", 0, true);
286 try {
287 flightgear::XLIFFParser visitor(stringNode);
288 readXML(xliffPath, visitor);
289 } catch (sg_io_exception& ex) {
290 SG_LOG(SG_GENERAL, SG_WARN, "failure parsing XLIFF: " << path <<
291 "\n\t" << ex.getMessage() << "\n\tat:" << ex.getLocation().asString());
292 } catch (sg_exception& ex) {
293 SG_LOG(SG_GENERAL, SG_WARN, "failure parsing XLIFF: " << path <<
294 "\n\t" << ex.getMessage());
295 }
296 }
297 }
298
299 // Load strings for requested resource and locale.
300 // Result is stored below "strings" in the property tree of the given locale.
301 bool
302 FGLocale::loadResource(SGPropertyNode* localeNode, const char* resource)
303 {
304 SGPath path( globals->get_fg_root() );
305
306 // already loaded
307 if (localeNode->hasChild("xliff")) {
308 return true;
309 }
310
311 SGPropertyNode* stringNode = localeNode->getNode("strings", 0, true);
312 SGPropertyNode* resourceNode = stringNode->getNode(resource);
313
314 if (!resourceNode)
315 return false;
316
317 if (resourceNode->getBoolValue("__loaded")) {
318 // already loaded previously
319 return true;
320 }
321
322 string path_str = resourceNode->getStringValue();
323 if (path_str.empty())
324 {
325 SG_LOG(SG_GENERAL, SG_WARN, "No path in " << stringNode->getPath() << "/" << resource << ".");
326 return false;
327 }
328
329 path.append(path_str);
330 SG_LOG(SG_GENERAL, SG_INFO, "Reading localized strings for '" <<
331 localeNode->getStringValue("lang", "<none>")
332 <<"' from " << path);
333
334 // load the actual file
335 try
336 {
337 readProperties(path, resourceNode);
338 } catch (const sg_exception &e)
339 {
340 SG_LOG(SG_GENERAL, SG_ALERT, "Unable to read the localized strings from " << path <<
341 ". Error: " << e.getFormattedMessage());
342 return false;
343 }
344
345 // set marker to indicate the data has been loaded
346 resourceNode->setBoolValue("__loaded", true);
347 return true;
348 }
349
350 // Load strings for requested resource (for current and default locale).
351 // Result is stored below "strings" in the property tree of the locales.
352 bool
353 FGLocale::loadResource(const char* resource)
354 {
355 // load defaults first
356 bool Ok = loadResource(_defaultLocale, resource);
357
358 // also load language specific resource, unless identical
359 if ((_currentLocale != nullptr) && (_defaultLocale != _currentLocale))
360 {
361 Ok &= loadResource(_currentLocale, resource);
362 }
363
364 return Ok;
365 }
366
367 std::string
368 FGLocale::innerGetLocalizedString(SGPropertyNode* localeNode, const char* id, const char* context, int index) const
369 {
370 SGPropertyNode *n = localeNode->getNode("strings",0, true)->getNode(context);
371 if (!n) {
372 return std::string();
373 }
374
375 n = n->getNode(id, index);
376 if (n && n->hasValue()) {
377 return std::string(n->getStringValue());
378 }
379
380 return std::string();
381 }
382
383 std::string
384 FGLocale::getLocalizedString(const std::string& id, const char* resource, const std::string& defaultValue)
385 {
386 return getLocalizedString(id.c_str(), resource, defaultValue.c_str());
387 }
388
389 std::string
390 FGLocale::getLocalizedString(const char* id, const char* resource, const char* Default)
391 {
392 assert(_inited);
393 if (id && resource)
394 {
395 std::string s;
396 if (_currentLocale) {
397 s = innerGetLocalizedString(_currentLocale, id, resource, 0);
398 if (!s.empty()) {
399 return s;
400 }
401 }
402
403 if (_defaultLocale) {
404 s = innerGetLocalizedString(_defaultLocale, id, resource, 0);
405 if (!s.empty()) {
406 return s;
407 }
408 }
409 }
410
411 return (Default == nullptr) ? std::string() : std::string(Default);
412 }
413
414 std::string
415 FGLocale::getLocalizedStringWithIndex(const char* id, const char* resource, unsigned int index) const
416 {
417 assert(_inited);
418 if (id && resource) {
419 std::string s;
420 if (_currentLocale) {
421 s = innerGetLocalizedString(_currentLocale, id, resource, index);
422 if (!s.empty()) {
423 return s;
424 }
425 }
426
427 if (_defaultLocale) {
428 s = innerGetLocalizedString(_defaultLocale, id, resource, index);
429 if (!s.empty()) {
430 return s;
431 }
432 }
433 }
434
435 return std::string();
436 }
437
438 simgear::PropertyList
439 FGLocale::getLocalizedStrings(SGPropertyNode *localeNode, const char* id, const char* context)
440 {
441 SGPropertyNode *n = localeNode->getNode("strings",0, true)->getNode(context);
442 if (n)
443 {
444 return n->getChildren(id);
445 }
446 return simgear::PropertyList();
447 }
448
449 size_t FGLocale::getLocalizedStringCount(const char* id, const char* resource) const
450 {
451 assert(_inited);
452 if (_currentLocale) {
453 SGPropertyNode* resourceNode = _currentLocale->getNode("strings",0, true)->getNode(resource);
454 if (resourceNode) {
455 const size_t count = resourceNode->getChildren(id).size();
456 if (count > 0) {
457 return count;
458 }
459 }
460 }
461
462 if (_defaultLocale) {
463 auto resourceNode = _defaultLocale->getNode("strings", 0, true)->getNode(resource);
464 if (!resourceNode)
465 return 0;
466
467 size_t count = resourceNode->getChildren(id).size();
468 if (count > 0) {
469 return count;
470 }
471 }
472
473 return 0;
474 }
475
476 simgear::PropertyList
477 FGLocale::getLocalizedStrings(const char* id, const char* resource)
478 {
479 assert(_inited);
480 if (id && resource)
481 {
482 if (_currentLocale)
483 {
484 simgear::PropertyList s = getLocalizedStrings(_currentLocale, id, resource);
485 if (! s.empty())
486 return s;
487 }
488
489 if (_defaultLocale)
490 {
491 simgear::PropertyList s = getLocalizedStrings(_defaultLocale, id, resource);
492 if (! s.empty())
493 return s;
494 }
495 }
496 return simgear::PropertyList();
497 }
498
499 // Check for localized font
500 std::string
501 FGLocale::getDefaultFont(const char* fallbackFont)
502 {
503 assert(_inited);
504 std::string font;
505 if (_currentLocale)
506 {
507 font = _currentLocale->getStringValue("font", "");
508 if (!font.empty())
509 return font;
510 }
511 if (_defaultLocale)
512 {
513 font = _defaultLocale->getStringValue("font", "");
514 if (!font.empty())
515 return font;
516 }
517
518 return fallbackFont;
519 }
520
521 std::string FGLocale::localizedPrintf(const char* id, const char* resource, ... )
522 {
523 va_list args;
524 va_start(args, resource);
525 string r = vlocalizedPrintf(id, resource, args);
526 va_end(args);
527 return r;
528 }
529
530 std::string FGLocale::vlocalizedPrintf(const char* id, const char* resource, va_list args)
531 {
532 assert(_inited);
533 std::string format = getLocalizedString(id, resource);
534 int len = ::vsnprintf(nullptr, 0, format.c_str(), args);
535 char* buf = (char*) alloca(len);
536 ::vsnprintf(buf, len, format.c_str(), args);
537 return std::string(buf);
538 }
539
540 // Simple UTF8 to Latin1 encoder.
541 void FGLocale::utf8toLatin1(string& s)
542 {
543 size_t pos = 0;
544
545 // map '0xc3..' utf8 characters to Latin1
546 while ((string::npos != (pos = s.find('\xc3',pos)))&&
547 (pos+1 < s.size()))
548 {
549 char c='*';
550 unsigned char p = s[pos+1];
551 if ((p>=0x80)&&(p<0xc0))
552 c = 0x40 + p;
553 char v[2];
554 v[0]=c;
555 v[1]=0;
556 s.replace(pos, 2, v);
557 pos++;
558 }
559
560 #ifdef DEBUG_ENCODING
561 printf("'%s': ", s.c_str());
562 for (pos = 0;pos<s.size();pos++)
563 printf("%02x ", (unsigned char) s[pos]);
564 printf("\n");
565 #endif
566
567 // hack: also map some Latin2 characters to plain-text ASCII
568 pos = 0;
569 while ((string::npos != (pos = s.find('\xc5',pos)))&&
570 (pos+1 < s.size()))
571 {
572 char c='*';
573 unsigned char p = s[pos+1];
574 switch(p)
575 {
576 case 0x82:c='l';break;
577 case 0x9a:c='S';break;
578 case 0x9b:c='s';break;
579 case 0xba:c='z';break;
580 case 0xbc:c='z';break;
581 }
582 char v[2];
583 v[0]=c;
584 v[1]=0;
585 s.replace(pos, 2, v);
586 pos++;
587 }
588 }
589
590 std::string fgTrMsg(const char* key)
591 {
592 return globals->get_locale()->getLocalizedString(key, "message");
593 }
594
595 std::string fgTrPrintfMsg(const char* key, ...)
596 {
597 va_list args;
598 va_start(args, key);
599 string r = globals->get_locale()->vlocalizedPrintf(key, "message", args);
600 va_end(args);
601 return r;
602 }
603
604 SGPropertyNode_ptr FGLocale::selectLanguageNode(SGPropertyNode* langs) const
605 {
606 if (!langs)
607 return {};
608
609 for (auto l : _languages) {
610 // Only accept the hyphen separator in PropertyList node names between
611 // language and territory
612 const auto langNoEncoding = strutils::replace(removeEncodingPart(l),
613 "_", "-");
614 if (langs->hasChild(langNoEncoding)) {
615 return langs->getChild(langNoEncoding);
616 }
617
618 const auto justLang = removeLocalePart(langNoEncoding);
619 if (langs->hasChild(justLang)) {
620 return langs->getChild(justLang);
621 }
622 }
623
624 return {};
625 }