Debian Codegraph @

src/engine/translations.cpp

raw symbols SCIP
1 /***************************************************************************
2 * fheroes2: https://github.com/ihhub/fheroes2 *
3 * Copyright (C) 2019 - 2026 *
4 * *
5 * Free Heroes2 Engine: http://sourceforge.net/projects/fheroes2 *
6 * Copyright (C) 2009 by Andrey Afletdinov <[email protected]> *
7 * *
8 * This program is free software; you can redistribute it and/or modify *
9 * it under the terms of the GNU General Public License as published by *
10 * the Free Software Foundation; either version 2 of the License, or *
11 * (at your option) any later version. *
12 * *
13 * This program is distributed in the hope that it will be useful, *
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
16 * GNU General Public License for more details. *
17 * *
18 * You should have received a copy of the GNU General Public License *
19 * along with this program; if not, write to the *
20 * Free Software Foundation, Inc., *
21 * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
22 ***************************************************************************/
23
24 #include "translations.h"
25
26 #include <algorithm>
27 #include <array>
28 #include <cassert>
29 #include <cctype>
30 #include <cstddef>
31 #include <cstdint>
32 #include <cstring>
33 #include <functional>
34 #include <map>
35 #include <ostream>
36 #include <string>
37 #include <string_view>
38 #include <type_traits>
39 #include <unordered_map>
40 #include <vector>
41
42 #include "logging.h"
43 #include "serialize.h"
44 #include "tools.h"
45
46 namespace
47 {
48 const char contextSeparator = '|';
49
50 constexpr std::array<uint32_t, 256> getCRC32Table()
51 {
52 std::array<uint32_t, 256> table{ 0 };
53
54 for ( uint32_t i = 0; i < 256; ++i ) {
55 uint32_t crc = i;
56
57 for ( int bit = 0; bit < 8; ++bit ) {
58 crc = ( crc & 1 ) ? ( ( crc >> 1 ) ^ 0xEDB88320 ) : ( crc >> 1 );
59 }
60
61 table[i] = crc;
62 }
63
64 return table;
65 }
66
67 const std::array<uint32_t, 256> crc32Table = getCRC32Table();
68
69 // Character lookup table for custom tolower
70 // Compatible with ASCII, custom French encoding, CP1250 and CP1251
71 const std::array<unsigned char, 256> tolowerLUT
72 = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, // Non-printable characters
73 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F,
74
75 // SP ! " # $ % & ' ( ) * + , - . / (ASCII)
76 // SP ! " ô û % ù ' ( ) â + , - . / (French, #$&* are ôûùâ)
77 ' ', '!', '"', '#', '$', '%', '&', '\'', '(', ')', '*', '+', ',', '-', '.', '/',
78
79 // 0 1 2 3 4 5 6 7 8 9 : ; < = > ? (ASCII)
80 // 0 1 2 3 4 5 6 7 8 9 : ; ï = î ? (French, <> are ïî)
81 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ':', ';', '<', '=', '>', '?',
82
83 // @ A→a B→b C→c D→d E→e F→f G→g H→h I→i J→j K→k L→l M→m N→n O→o (ASCII)
84 // à A→a B→b C→c D→d E→e F→f G→g H→h I→i J→j K→k L→l M→m N→n O→o (French, @ is à)
85 '@', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',
86
87 // P→p Q→q R→r S→s T→t U→u V→v W→w X→x Y→y Z→z [ \ ] ^ _ (ASCII)
88 // P→p Q→q R→r S→s T→t U→u V→v W→w X→x Y→y Z→z [ \ ] ç _ (French, ^ is ç)
89 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '[', '\\', ']', '^', '_',
90
91 // ` a b c d e f g h i j k l m n o (ASCII)
92 // è a b c d e f g h i j k l m n o (French, ` is è)
93 '`', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',
94
95 // p q r s t u v w x y z { | } ~ DEL (ASCII)
96 // p q r s t u v w x y z { ê } é DEL (French, |~ are êé)
97 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '{', '|', '}', '~', 0x7F,
98
99 // € ‚ „ … † ‡ ‰ Š→š ‹ Ś→ś Ť→ť Ž→ž Ź→ź (1250, except €)
100 // Ђ→ђ Ѓ→ѓ ‚ ѓ „ … † ‡ € ‰ Љ→љ ‹ Њ→њ Ќ→ќ Ћ→ћ Џ→џ (1251)
101 0x90, 0x83, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x9A, 0x8B, 0x9C, 0x9D, 0x9E, 0x9F,
102
103 // ‘ ’ “ ” • – — ™ š › ś ť ž ź (1250)
104 // ђ ‘ ’ “ ” • – — ™ љ › њ ќ ћ џ (1251)
105 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9A, 0x9B, 0x9C, 0x9D, 0x9E, 0x9F,
106
107 // NBS ˇ ˘ Ł→ł ¤ Ą→ą ¦ § ¨ © Ş→ş « ¬ SHY ® Ż→ż (1250 except ˇ¨)
108 // NBP Ў→ў ў Ј ¤ Ґ ¦ § Ё→ё © Є→є « ¬ SHY ® Ї→ї (1251 except ЈҐ)
109 0xA0, 0xA2, 0xA2, 0xB3, 0xA4, 0xB9, 0xA6, 0xA7, 0xB8, 0xA9, 0xBA, 0xAB, 0xAC, 0xAD, 0xAE, 0xBF,
110
111 // ° ± ˛ ł ´ µ ¶ · ¸ ą ş » Ľ→ľ ˝ ľ ż (1250 except ˛˝)
112 // ° ± І→і і ґ µ ¶ · ё № є » ј Ѕ→ѕ ѕ ї (1251 except ј)
113 0xB0, 0xB1, 0xB3, 0xB3, 0xB4, 0xB5, 0xB6, 0xB7, 0xB8, 0xB9, 0xBA, 0xBB, 0xBE, 0xBE, 0xBE, 0xBF,
114
115 // Ŕ→ŕ Á→á Â→â Ă→ă Ä→ä Ĺ→ĺ Ć→ć Ç→ç Č→č É→é Ę→ę Ë→ë Ě→ě Í→í Î→î Ď→ď (1250)
116 // А→а Б→б В→в Г→г Д→д Е→е Ж→ж З→з И→и Й→й К→к Л→л М→м Н→н О→о П→п (1251)
117 0xE0, 0xE1, 0xE2, 0xE3, 0xE4, 0xE5, 0xE6, 0xE7, 0xE8, 0xE9, 0xEA, 0xEB, 0xEC, 0xED, 0xEE, 0xEF,
118
119 // Đ→đ Ń→ń Ň→ň Ó→ó Ô→ô Ő→ő Ö→ö × Ř→ř Ů→ů Ú→ú Ű→ű Ü→ü Ý→ý Ţ→ţ ß (1250, except ×ß)
120 // Р→р С→с Т→т У→у Ф→ф Х→х Ц→ц Ч→ч Ш→ш Щ→щ Ъ→ъ Ы→ы Ь→ь Э→э Ю→ю Я→я (1251)
121 0xF0, 0xF1, 0xF2, 0xF3, 0xF4, 0xF5, 0xF6, 0xF7, 0xF8, 0xF9, 0xFA, 0xFB, 0xFC, 0xFD, 0xFE, 0xFF,
122
123 // ŕ á â ă ä ĺ ć ç č é ę ë ě í î ď (1250)
124 // а б в г д е ж з и й к л м н о п (1251)
125 0xE0, 0xE1, 0xE2, 0xE3, 0xE4, 0xE5, 0xE6, 0xE7, 0xE8, 0xE9, 0xEA, 0xEB, 0xEC, 0xED, 0xEE, 0xEF,
126
127 // đ ń ň ó ô ő ö ÷ ř ů ú ű ü ý ţ ˙ (1250)
128 // р с т у ф х ц ч ш щ ъ ы ь э ю я (1251)
129 0xF0, 0xF1, 0xF2, 0xF3, 0xF4, 0xF5, 0xF6, 0xF7, 0xF8, 0xF9, 0xFA, 0xFB, 0xFC, 0xFD, 0xFE, 0xFF };
130
131 enum class LocaleType : int
132 {
133 LOCALE_EN,
134 LOCALE_AF,
135 LOCALE_AR,
136 LOCALE_BE,
137 LOCALE_BG,
138 LOCALE_CA,
139 LOCALE_CS,
140 LOCALE_DA,
141 LOCALE_DE,
142 LOCALE_EL,
143 LOCALE_EO,
144 LOCALE_ES,
145 LOCALE_ET,
146 LOCALE_EU,
147 LOCALE_FI,
148 LOCALE_FR,
149 LOCALE_GL,
150 LOCALE_HE,
151 LOCALE_HR,
152 LOCALE_HU,
153 LOCALE_ID,
154 LOCALE_IT,
155 LOCALE_LA,
156 LOCALE_LT,
157 LOCALE_LV,
158 LOCALE_MK,
159 LOCALE_NB,
160 LOCALE_NL,
161 LOCALE_PL,
162 LOCALE_PT,
163 LOCALE_RO,
164 LOCALE_RU,
165 LOCALE_SK,
166 LOCALE_SL,
167 LOCALE_SR,
168 LOCALE_SV,
169 LOCALE_TR,
170 LOCALE_UK,
171 LOCALE_VI
172 };
173
174 LocaleType langToLocale( const std::string_view langName )
175 {
176 static const std::unordered_map<std::string_view, LocaleType> langLocale{ // Afrikaans
177 { "af", LocaleType::LOCALE_AF },
178 { "afrikaans", LocaleType::LOCALE_AF },
179 // Arabic
180 { "ar", LocaleType::LOCALE_AR },
181 { "arabic", LocaleType::LOCALE_AR },
182 // Belarusian
183 { "be", LocaleType::LOCALE_BE },
184 { "belarusian", LocaleType::LOCALE_BE },
185 // Bulgarian
186 { "bg", LocaleType::LOCALE_BG },
187 { "bulgarian", LocaleType::LOCALE_BG },
188 // Catalan
189 { "ca", LocaleType::LOCALE_CA },
190 { "catalan", LocaleType::LOCALE_CA },
191 // Czech
192 { "cs", LocaleType::LOCALE_CS },
193 { "czech", LocaleType::LOCALE_CS },
194 // Danish
195 { "da", LocaleType::LOCALE_DA },
196 { "danish", LocaleType::LOCALE_DA },
197 // German
198 { "de", LocaleType::LOCALE_DE },
199 { "german", LocaleType::LOCALE_DE },
200 // Greek
201 { "el", LocaleType::LOCALE_EL },
202 { "greek", LocaleType::LOCALE_EL },
203 // Esperanto
204 { "eo", LocaleType::LOCALE_EO },
205 { "esperanto", LocaleType::LOCALE_EO },
206 // Spanish
207 { "es", LocaleType::LOCALE_ES },
208 { "spanish", LocaleType::LOCALE_ES },
209 // Estonian
210 { "et", LocaleType::LOCALE_ET },
211 { "estonian", LocaleType::LOCALE_ET },
212 // Basque
213 { "eu", LocaleType::LOCALE_EU },
214 { "basque", LocaleType::LOCALE_EU },
215 // Finnish
216 { "fi", LocaleType::LOCALE_FI },
217 { "finnish", LocaleType::LOCALE_FI },
218 // French
219 { "fr", LocaleType::LOCALE_FR },
220 { "french", LocaleType::LOCALE_FR },
221 // Galician
222 { "gl", LocaleType::LOCALE_GL },
223 { "galician", LocaleType::LOCALE_GL },
224 // Hebrew
225 { "he", LocaleType::LOCALE_HE },
226 { "hebrew", LocaleType::LOCALE_HE },
227 // Croatian
228 { "hr", LocaleType::LOCALE_HR },
229 { "croatian", LocaleType::LOCALE_HR },
230 // Hungarian
231 { "hu", LocaleType::LOCALE_HU },
232 { "hungarian", LocaleType::LOCALE_HU },
233 // Indonesian
234 { "id", LocaleType::LOCALE_ID },
235 { "indonesian", LocaleType::LOCALE_ID },
236 // Italian
237 { "it", LocaleType::LOCALE_IT },
238 { "italian", LocaleType::LOCALE_IT },
239 // Latin
240 { "la", LocaleType::LOCALE_LA },
241 { "latin", LocaleType::LOCALE_LA },
242 // Lithuanian
243 { "lt", LocaleType::LOCALE_LT },
244 { "lithuanian", LocaleType::LOCALE_LT },
245 // Latvian
246 { "lv", LocaleType::LOCALE_LV },
247 { "latvian", LocaleType::LOCALE_LV },
248 // Macedonian
249 { "mk", LocaleType::LOCALE_MK },
250 { "macedonian", LocaleType::LOCALE_MK },
251 // Norwegian
252 { "nb", LocaleType::LOCALE_NB },
253 { "norwegian", LocaleType::LOCALE_NB },
254 // Dutch
255 { "nl", LocaleType::LOCALE_NL },
256 { "dutch", LocaleType::LOCALE_NL },
257 // Polish
258 { "pl", LocaleType::LOCALE_PL },
259 { "polish", LocaleType::LOCALE_PL },
260 // Portuguese
261 { "pt", LocaleType::LOCALE_PT },
262 { "portuguese", LocaleType::LOCALE_PT },
263 // Romanian
264 { "ro", LocaleType::LOCALE_RO },
265 { "romanian", LocaleType::LOCALE_RO },
266 // Russian
267 { "ru", LocaleType::LOCALE_RU },
268 { "russian", LocaleType::LOCALE_RU },
269 // Slovak
270 { "sk", LocaleType::LOCALE_SK },
271 { "slovak", LocaleType::LOCALE_SK },
272 // Slovenian
273 { "sl", LocaleType::LOCALE_SL },
274 { "slovenian", LocaleType::LOCALE_SL },
275 // Serbian
276 { "sr", LocaleType::LOCALE_SR },
277 { "serbian", LocaleType::LOCALE_SR },
278 // Swedish
279 { "sv", LocaleType::LOCALE_SV },
280 { "swedish", LocaleType::LOCALE_SV },
281 // Turkish
282 { "tr", LocaleType::LOCALE_TR },
283 { "turkish", LocaleType::LOCALE_TR },
284 // Ukrainian
285 { "uk", LocaleType::LOCALE_UK },
286 { "ukrainian", LocaleType::LOCALE_UK },
287 // Vietnamese
288 { "vi", LocaleType::LOCALE_VI },
289 { "vietnamese", LocaleType::LOCALE_VI } };
290
291 const auto iter = langLocale.find( langName );
292 if ( iter == langLocale.end() ) {
293 assert( 0 );
294 return LocaleType::LOCALE_EN;
295 }
296
297 return iter->second;
298 }
299
300 uint32_t crc32b( const std::string_view str )
301 {
302 uint32_t crc = 0xFFFFFFFF;
303
304 for ( const char ch : str ) {
305 crc = ( crc >> 8 ) ^ crc32Table[( crc ^ static_cast<uint32_t>( ch ) ) & 0xFF];
306 }
307
308 return ~crc;
309 }
310
311 bool getCharsetFromHeader( const std::string & hdr, std::string & charset )
312 {
313 constexpr std::string_view hdrEntry{ "Content-Type:" };
314 constexpr std::string_view charsetDirective{ "charset=" };
315
316 if ( hdr.size() <= hdrEntry.size() + charsetDirective.size() ) {
317 return false;
318 }
319
320 if ( hdr.rfind( hdrEntry, 0 ) != 0 ) {
321 return false;
322 }
323
324 const size_t pos = hdr.find( charsetDirective );
325 if ( pos == std::string::npos ) {
326 return false;
327 }
328
329 charset = hdr.substr( pos + charsetDirective.size() );
330
331 return true;
332 }
333
334 const char * stripContext( const char * str )
335 {
336 const char * pos = std::strchr( str, contextSeparator );
337
338 return pos ? ++pos : str;
339 }
340
341 class MOFile final
342 {
343 public:
344 MOFile() = default;
345
346 const char * ngettext( const char * str, const size_t plural ) const
347 {
348 if ( !_isValid ) {
349 assert( 0 );
350
351 return stripContext( str );
352 }
353
354 const auto iter = std::as_const( _translations ).find( crc32b( str ) );
355 if ( iter == _translations.cend() ) {
356 return stripContext( str );
357 }
358
359 const auto & [dummy, pluralFormTranslations] = *iter;
360 if ( plural >= pluralFormTranslations.size() ) {
361 return stripContext( str );
362 }
363
364 const std::string & translatedStr = pluralFormTranslations[plural];
365 if ( translatedStr.empty() ) {
366 return stripContext( str );
367 }
368
369 return translatedStr.c_str();
370 }
371
372 bool load( const std::string_view langName, const std::string & fileName )
373 {
374 *this = {};
375
376 StreamFile sf;
377 if ( !sf.open( fileName, "rb" ) ) {
378 return false;
379 }
380
381 ROStreamBuf sb = sf.getStreamBuf();
382 if ( sf.fail() ) {
383 ERROR_LOG( "I/O error when reading " << fileName )
384 return false;
385 }
386
387 sf.close();
388
389 {
390 const uint32_t magicNumber = sb.getLE32();
391 if ( sb.fail() ) {
392 ERROR_LOG( "I/O error when parsing " << fileName )
393 return false;
394 }
395
396 switch ( magicNumber ) {
397 case 0xde120495:
398 sb.setBigendian( true );
399
400 DEBUG_LOG( DBG_ENGINE, DBG_TRACE, "Setting big-endian mode for " << fileName )
401 break;
402 case 0x950412de:
403 sb.setBigendian( false );
404
405 DEBUG_LOG( DBG_ENGINE, DBG_TRACE, "Setting little-endian mode for " << fileName )
406 break;
407 default:
408 ERROR_LOG( "Incorrect magic number " << GetHexString( magicNumber ) << " for " << fileName )
409 return false;
410 }
411 }
412
413 {
414 const uint16_t majorVersion = sb.get16();
415 if ( sb.fail() ) {
416 ERROR_LOG( "I/O error when parsing " << fileName )
417 return false;
418 }
419
420 if ( majorVersion != 0 ) {
421 ERROR_LOG( "Incorrect major version " << GetHexString( majorVersion, 4 ) << " for " << fileName )
422 return false;
423 }
424 }
425
426 // Skip the minor version
427 sb.skip( 2 );
428
429 const uint32_t stringsCount = sb.get32();
430 if ( stringsCount == 0 ) {
431 ERROR_LOG( "There are no translated strings in " << fileName )
432 return false;
433 }
434
435 const uint32_t originalStringsTableOffset = sb.get32();
436 const uint32_t translationsTableOffset = sb.get32();
437 if ( sb.fail() ) {
438 ERROR_LOG( "I/O error when parsing " << fileName )
439 return false;
440 }
441
442 // The hash table is optional and may be missing, and even if it is present, the actual hashing algorithm depends on the
443 // specific implementation and is not documented. See https://www.gnu.org/software/gettext/manual/html_node/MO-Files.html
444 // for details.
445
446 for ( uint32_t i = 0; i < stringsCount; ++i ) {
447 sb.seek( originalStringsTableOffset + i * 8 );
448
449 const uint32_t origStrLen = sb.get32();
450 const uint32_t origStrOff = sb.get32();
451 if ( sb.fail() ) {
452 ERROR_LOG( "I/O error when parsing " << fileName )
453 return false;
454 }
455
456 if ( origStrLen == 0 ) {
457 // This is an empty original string. Skip it.
458 continue;
459 }
460
461 sb.seek( origStrOff );
462
463 const std::string_view origStr = sb.getStringView( origStrLen );
464 if ( sb.fail() ) {
465 ERROR_LOG( "I/O error when parsing " << fileName )
466 return false;
467 }
468
469 sb.seek( translationsTableOffset + i * 8 );
470
471 const uint32_t tranStrLen = sb.get32();
472 const uint32_t tranStrOff = sb.get32();
473 if ( sb.fail() ) {
474 ERROR_LOG( "I/O error when parsing " << fileName )
475 return false;
476 }
477
478 if ( tranStrLen == 0 ) {
479 // This is an empty translation. Skip it.
480 continue;
481 }
482
483 sb.seek( tranStrOff );
484
485 const auto [tranBufPtr, tranBufLen] = sb.getRawView( tranStrLen );
486 if ( sb.fail() ) {
487 ERROR_LOG( "I/O error when parsing " << fileName )
488 return false;
489 }
490
491 static_assert( std::is_same_v<std::remove_const_t<std::remove_reference_t<decltype( *tranBufPtr )>>, unsigned char> );
492
493 if ( const auto [dummy, inserted]
494 = _translations.try_emplace( crc32b( origStr ), StringSplit( { reinterpret_cast<const char *>( tranBufPtr ), tranBufLen }, '\0' ) );
495 !inserted ) {
496 ERROR_LOG( "Hash collision detected for string \"" << origStr << "\"" )
497 }
498 }
499
500 if ( _translations.empty() ) {
501 ERROR_LOG( "There are no translated strings in " << fileName )
502 return false;
503 }
504
505 _locale = langToLocale( langName );
506
507 // The empty line in the MO file goes first (since the original lines in it are sorted in increasing lexicographical order),
508 // and its "translation" contains service information such as the encoding used and information about the plural form. See
509 // https://www.gnu.org/software/gettext/manual/html_node/MO-Files.html for details.
510 //
511 // TODO: parse the plural form information and use it in the code.
512 {
513 sb.seek( translationsTableOffset );
514
515 const uint32_t len = sb.get32();
516 const uint32_t off = sb.get32();
517 if ( sb.fail() ) {
518 ERROR_LOG( "I/O error when parsing " << fileName )
519 return false;
520 }
521
522 sb.seek( off );
523
524 const std::string_view str = sb.getStringView( len );
525 if ( sb.fail() ) {
526 ERROR_LOG( "I/O error when parsing " << fileName )
527 return false;
528 }
529
530 for ( const std::string & hdr : StringSplit( str, '\n' ) ) {
531 if ( getCharsetFromHeader( hdr, _encoding ) ) {
532 break;
533 }
534 }
535 }
536
537 _isValid = true;
538
539 return true;
540 }
541
542 LocaleType getLocale() const
543 {
544 return _locale;
545 }
546
547 bool isEncoding( const std::string_view encoding ) const
548 {
549 return ( _encoding == encoding );
550 }
551
552 bool isValid() const
553 {
554 return _isValid;
555 }
556
557 private:
558 LocaleType _locale{ LocaleType::LOCALE_EN };
559 std::unordered_map<uint32_t, std::vector<std::string>> _translations;
560 std::string _encoding;
561 bool _isValid{ false };
562 };
563
564 MOFile * current = nullptr;
565 std::map<std::string, MOFile, std::less<>> cache;
566 }
567
568 std::pair<bool, bool> Translation::setLanguage( const std::string_view langName )
569 {
570 assert( !langName.empty() );
571
572 if ( const auto iter = cache.find( langName ); iter != cache.end() ) {
573 MOFile & item = iter->second;
574
575 if ( item.isValid() ) {
576 current = &item;
577 }
578
579 return { true, item.isValid() };
580 }
581
582 return { false, false };
583 }
584
585 bool Translation::setLanguage( const std::string & langName, const std::string_view fileName )
586 {
587 assert( !langName.empty() );
588
589 const auto [cacheIter, inserted] = cache.try_emplace( langName );
590 MOFile & item = cacheIter->second;
591
592 if ( !inserted ) {
593 if ( item.isValid() ) {
594 current = &item;
595 }
596
597 return item.isValid();
598 }
599
600 if ( fileName.empty() || !item.load( langName, std::string{ fileName } ) ) {
601 assert( !item.isValid() );
602
603 return false;
604 }
605
606 assert( item.isValid() );
607
608 current = &item;
609
610 return true;
611 }
612
613 void Translation::reset()
614 {
615 current = nullptr;
616 }
617
618 const char * Translation::gettext( const std::string & str )
619 {
620 return current ? current->ngettext( str.c_str(), 0 ) : stripContext( str.c_str() );
621 }
622
623 const char * Translation::gettext( const char * str )
624 {
625 return current ? current->ngettext( str, 0 ) : stripContext( str );
626 }
627
628 const char * Translation::getNonTranslated( const char * str )
629 {
630 return stripContext( str );
631 }
632
633 const char * Translation::ngettext( const char * str, const char * plural, const size_t n )
634 {
635 if ( current ) {
636 switch ( current->getLocale() ) {
637 case LocaleType::LOCALE_AF:
638 case LocaleType::LOCALE_BG:
639 case LocaleType::LOCALE_DA:
640 case LocaleType::LOCALE_DE:
641 case LocaleType::LOCALE_EO:
642 case LocaleType::LOCALE_ES:
643 case LocaleType::LOCALE_ET:
644 case LocaleType::LOCALE_EU:
645 case LocaleType::LOCALE_FI:
646 case LocaleType::LOCALE_GL:
647 case LocaleType::LOCALE_HE:
648 case LocaleType::LOCALE_HU:
649 case LocaleType::LOCALE_ID:
650 case LocaleType::LOCALE_IT:
651 case LocaleType::LOCALE_LA:
652 case LocaleType::LOCALE_NB:
653 case LocaleType::LOCALE_NL:
654 case LocaleType::LOCALE_SV:
655 case LocaleType::LOCALE_TR:
656 return current->ngettext( str, ( n != 1 ) );
657 case LocaleType::LOCALE_EL:
658 case LocaleType::LOCALE_FR:
659 case LocaleType::LOCALE_PT:
660 return current->ngettext( str, ( n > 1 ) );
661 case LocaleType::LOCALE_AR:
662 return current->ngettext( str, ( n == 0 ? 0 : n == 1 ? 1 : n == 2 ? 2 : n % 100 >= 3 && n % 100 <= 10 ? 3 : n % 100 >= 11 && n % 100 <= 99 ? 4 : 5 ) );
663 case LocaleType::LOCALE_RO:
664 return current->ngettext( str, ( n == 1 ? 0 : n == 0 || ( n != 1 && n % 100 >= 1 && n % 100 <= 19 ) ? 1 : 2 ) );
665 case LocaleType::LOCALE_SL:
666 return current->ngettext( str, ( n % 100 == 1 ? 0 : n % 100 == 2 ? 1 : n % 100 == 3 || n % 100 == 4 ? 2 : 3 ) );
667 case LocaleType::LOCALE_SR:
668 return current->ngettext( str, ( n == 1 ? 3 : n % 10 == 1 && n % 100 != 11 ? 0 : n % 10 >= 2 && n % 10 <= 4 && ( n % 100 < 10 || n % 100 >= 20 ) ? 1 : 2 ) );
669 case LocaleType::LOCALE_CS:
670 case LocaleType::LOCALE_SK:
671 return current->ngettext( str, ( ( n == 1 ) ? 0 : ( n >= 2 && n <= 4 ) ? 1 : 2 ) );
672 case LocaleType::LOCALE_HR:
673 case LocaleType::LOCALE_LV:
674 case LocaleType::LOCALE_RU:
675 return current->ngettext( str, ( n % 10 == 1 && n % 100 != 11 ? 0 : n % 10 >= 2 && n % 10 <= 4 && ( n % 100 < 10 || n % 100 >= 20 ) ? 1 : 2 ) );
676 case LocaleType::LOCALE_LT:
677 return current->ngettext( str, ( n % 10 == 1 && n % 100 != 11 ? 0 : n % 10 >= 2 && ( n % 100 < 10 || n % 100 >= 20 ) ? 1 : 2 ) );
678 case LocaleType::LOCALE_MK:
679 return current->ngettext( str, ( n == 1 || n % 10 == 1 ? 0 : 1 ) );
680 case LocaleType::LOCALE_PL:
681 return current->ngettext( str, ( n == 1 ? 0 : n % 10 >= 2 && n % 10 <= 4 && ( n % 100 < 10 || n % 100 >= 20 ) ? 1 : 2 ) );
682 case LocaleType::LOCALE_BE:
683 case LocaleType::LOCALE_UK:
684 return current->ngettext( str, ( n % 10 == 1 && n % 100 != 11 ? 0 : n % 10 >= 2 && n % 10 <= 4 && ( n % 100 < 12 || n % 100 > 14 ) ? 1 : 2 ) );
685 default:
686 break;
687 }
688 }
689
690 return stripContext( n == 1 ? str : plural );
691 }
692
693 std::string Translation::StringLower( std::string str )
694 {
695 if ( current ) {
696 // With German, lowercasing strings does more harm than good
697 if ( current->getLocale() == LocaleType::LOCALE_DE ) {
698 return str;
699 }
700
701 // For CP1250/1251 codepages a custom lowercase LUT is implemented
702 if ( current->isEncoding( "CP1250" ) || current->isEncoding( "CP1251" ) ) {
703 std::transform( str.begin(), str.end(), str.begin(), []( const unsigned char c ) { return tolowerLUT[c]; } );
704 return str;
705 }
706 }
707
708 return ::StringLower( str );
709 }
710
711 void StringReplaceWithLowercase( std::string & workString, const char * pattern, const std::string & patternReplacement )
712 {
713 if ( pattern == nullptr ) {
714 return;
715 }
716
717 for ( size_t position = workString.find( pattern ); position != std::string::npos; position = workString.find( pattern ) ) {
718 // To determine if the end of a sentence was before this word we parse the character before it
719 // for the presence of full stop, question mark, or exclamation mark, skipping whitespace characters.
720 const char prevWordEnd = [&workString, position]() {
721 assert( position < workString.size() );
722
723 const auto iter = std::find_if_not( workString.rbegin() + static_cast<int32_t>( workString.size() - position ), workString.rend(),
724 []( const unsigned char c ) { return std::isspace( c ); } );
725 if ( iter != workString.rend() ) {
726 return *iter;
727 }
728
729 // Before 'position' there is nothing, or there are only spaces.
730 return '\0';
731 }();
732
733 // Also if the insert 'position' equals zero, then it is the first word in a sentence.
734 if ( position == 0 || prevWordEnd == '.' || prevWordEnd == '?' || prevWordEnd == '!' ) {
735 // Also, 'patternReplacement' can consist of two words (for example, "Power Liches") and if
736 // it is placed as the first word in sentence, then we have to lowercase only the second word.
737 // To detect this, we look for a space mark in 'patternReplacement'.
738 const size_t spacePosition = patternReplacement.find( ' ' );
739
740 // The first (and possibly only) word of 'patternReplacement' replaces 'pattern' in 'workString'.
741 workString.replace( position, std::strlen( pattern ), patternReplacement.substr( 0, spacePosition ) );
742
743 // Check if a space mark was found to insert the rest part of 'patternReplacement' with lowercase applied.
744 if ( spacePosition != std::string::npos ) {
745 workString.insert( position + spacePosition, Translation::StringLower( patternReplacement.substr( spacePosition ) ) );
746 }
747 }
748 else {
749 // For all other cases lowercase the 'patternReplacement' and replace the 'pattern' with it in 'workString'.
750 workString.replace( position, std::strlen( pattern ), Translation::StringLower( patternReplacement ) );
751 }
752 }
753 }