CGeneralTextHandler.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705
  1. /*
  2. * CGeneralTextHandler.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include "CGeneralTextHandler.h"
  12. #include "filesystem/Filesystem.h"
  13. #include "serializer/JsonSerializeFormat.h"
  14. #include "CConfigHandler.h"
  15. #include "GameSettings.h"
  16. #include "mapObjects/CQuest.h"
  17. #include "modding/CModHandler.h"
  18. #include "VCMI_Lib.h"
  19. #include "Languages.h"
  20. #include "TextOperations.h"
  21. VCMI_LIB_NAMESPACE_BEGIN
  22. /// Detects language and encoding of H3 text files based on matching against pregenerated footprints of H3 file
  23. void CGeneralTextHandler::detectInstallParameters()
  24. {
  25. using LanguageFootprint = std::array<double, 16>;
  26. static const std::array<LanguageFootprint, 7> knownFootprints =
  27. { {
  28. { { 0.1602, 0.0000, 0.0357, 0.0054, 0.0038, 0.0017, 0.0077, 0.0214, 0.0000, 0.0000, 0.1264, 0.1947, 0.2012, 0.1406, 0.0480, 0.0532 } },
  29. { { 0.0559, 0.0000, 0.1983, 0.0051, 0.0222, 0.0183, 0.4596, 0.2405, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000 } },
  30. { { 0.0493, 0.0000, 0.1926, 0.0047, 0.0230, 0.0121, 0.4133, 0.2780, 0.0002, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0259, 0.0008 } },
  31. { { 0.0534, 0.0000, 0.1705, 0.0047, 0.0418, 0.0208, 0.4775, 0.2191, 0.0001, 0.0000, 0.0000, 0.0000, 0.0000, 0.0005, 0.0036, 0.0080 } },
  32. { { 0.0534, 0.0000, 0.1701, 0.0067, 0.0157, 0.0133, 0.4328, 0.2540, 0.0001, 0.0043, 0.0000, 0.0244, 0.0000, 0.0000, 0.0181, 0.0071 } },
  33. { { 0.0548, 0.0000, 0.1744, 0.0061, 0.0031, 0.0009, 0.0046, 0.0136, 0.0000, 0.0004, 0.0000, 0.0000, 0.0227, 0.0061, 0.4882, 0.2252 } },
  34. { { 0.0559, 0.0000, 0.1807, 0.0059, 0.0036, 0.0013, 0.0046, 0.0134, 0.0000, 0.0004, 0.0000, 0.0487, 0.0209, 0.0060, 0.4615, 0.1972 } },
  35. } };
  36. static const std::array<std::string, 7> knownLanguages =
  37. { {
  38. "chinese",
  39. "english",
  40. "french",
  41. "german",
  42. "polish",
  43. "russian",
  44. "ukrainian"
  45. } };
  46. if(!CResourceHandler::get("core")->existsResource(TextPath::builtin("DATA/GENRLTXT.TXT")))
  47. {
  48. Settings language = settings.write["session"]["language"];
  49. language->String() = "english";
  50. Settings confidence = settings.write["session"]["languageDeviation"];
  51. confidence->Float() = 1.0;
  52. Settings encoding = settings.write["session"]["encoding"];
  53. encoding->String() = Languages::getLanguageOptions("english").encoding;
  54. return;
  55. }
  56. // load file that will be used for footprint generation
  57. // this is one of the most text-heavy files in game and consists solely from translated texts
  58. auto resource = CResourceHandler::get("core")->load(TextPath::builtin("DATA/GENRLTXT.TXT"));
  59. std::array<size_t, 256> charCount{};
  60. std::array<double, 16> footprint{};
  61. std::array<double, 6> deviations{};
  62. auto data = resource->readAll();
  63. // compute how often each character occurs in input file
  64. for (si64 i = 0; i < data.second; ++i)
  65. charCount[data.first[i]] += 1;
  66. // and convert computed data into weights
  67. // to reduce amount of data, group footprint data into 16-char blocks.
  68. // While this will reduce precision, it should not affect output
  69. // since we expect only tiny differences compared to reference footprints
  70. for (size_t i = 0; i < 256; ++i)
  71. footprint[i/16] += static_cast<double>(charCount[i]) / data.second;
  72. logGlobal->debug("Language footprint: %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f",
  73. footprint[0], footprint[1], footprint[2], footprint[3], footprint[4], footprint[5], footprint[6], footprint[7],
  74. footprint[8], footprint[9], footprint[10], footprint[11], footprint[12], footprint[13], footprint[14], footprint[15]
  75. );
  76. for (size_t i = 0; i < deviations.size(); ++i)
  77. {
  78. for (size_t j = 0; j < footprint.size(); ++j)
  79. deviations[i] += std::abs((footprint[j] - knownFootprints[i][j]));
  80. }
  81. size_t bestIndex = boost::range::min_element(deviations) - deviations.begin();
  82. for (size_t i = 0; i < deviations.size(); ++i)
  83. logGlobal->debug("Comparing to %s: %f", knownLanguages[i], deviations[i]);
  84. Settings language = settings.write["session"]["language"];
  85. language->String() = knownLanguages[bestIndex];
  86. Settings confidence = settings.write["session"]["languageDeviation"];
  87. confidence->Float() = deviations[bestIndex];
  88. Settings encoding = settings.write["session"]["encoding"];
  89. encoding->String() = Languages::getLanguageOptions(knownLanguages[bestIndex]).encoding;
  90. }
  91. //Helper for string -> float conversion
  92. class LocaleWithComma: public std::numpunct<char>
  93. {
  94. protected:
  95. char do_decimal_point() const override
  96. {
  97. return ',';
  98. }
  99. };
  100. CLegacyConfigParser::CLegacyConfigParser(const TextPath & resource)
  101. {
  102. auto input = CResourceHandler::get()->load(resource);
  103. std::string modName = VLC->modh->findResourceOrigin(resource);
  104. std::string language = VLC->modh->getModLanguage(modName);
  105. fileEncoding = Languages::getLanguageOptions(language).encoding;
  106. data.reset(new char[input->getSize()]);
  107. input->read(reinterpret_cast<uint8_t*>(data.get()), input->getSize());
  108. curr = data.get();
  109. end = curr + input->getSize();
  110. }
  111. std::string CLegacyConfigParser::extractQuotedPart()
  112. {
  113. assert(*curr == '\"');
  114. curr++; // skip quote
  115. char * begin = curr;
  116. while (curr != end && *curr != '\"' && *curr != '\t')
  117. curr++;
  118. return std::string(begin, curr++); //increment curr to close quote
  119. }
  120. std::string CLegacyConfigParser::extractQuotedString()
  121. {
  122. assert(*curr == '\"');
  123. std::string ret;
  124. while (true)
  125. {
  126. ret += extractQuotedPart();
  127. // double quote - add it to string and continue quoted part
  128. if (curr < end && *curr == '\"')
  129. {
  130. ret += '\"';
  131. }
  132. //extract normal part
  133. else if(curr < end && *curr != '\t' && *curr != '\r')
  134. {
  135. char * begin = curr;
  136. while (curr < end && *curr != '\t' && *curr != '\r' && *curr != '\"')//find end of string or next quoted part start
  137. curr++;
  138. ret += std::string(begin, curr);
  139. if(curr>=end || *curr != '\"')
  140. return ret;
  141. }
  142. else // end of string
  143. return ret;
  144. }
  145. }
  146. std::string CLegacyConfigParser::extractNormalString()
  147. {
  148. char * begin = curr;
  149. while (curr < end && *curr != '\t' && *curr != '\r')//find end of string
  150. curr++;
  151. return std::string(begin, curr);
  152. }
  153. std::string CLegacyConfigParser::readRawString()
  154. {
  155. if (curr >= end || *curr == '\n')
  156. return "";
  157. std::string ret;
  158. if (*curr == '\"')
  159. ret = extractQuotedString();// quoted text - find closing quote
  160. else
  161. ret = extractNormalString();//string without quotes - copy till \t or \r
  162. curr++;
  163. return ret;
  164. }
  165. std::string CLegacyConfigParser::readString()
  166. {
  167. // do not convert strings that are already in ASCII - this will only slow down loading process
  168. std::string str = readRawString();
  169. if (TextOperations::isValidASCII(str))
  170. return str;
  171. return TextOperations::toUnicode(str, fileEncoding);
  172. }
  173. float CLegacyConfigParser::readNumber()
  174. {
  175. std::string input = readRawString();
  176. std::istringstream stream(input);
  177. if(input.find(',') != std::string::npos) // code to handle conversion with comma as decimal separator
  178. stream.imbue(std::locale(std::locale(), new LocaleWithComma()));
  179. float result;
  180. if ( !(stream >> result) )
  181. return 0;
  182. return result;
  183. }
  184. bool CLegacyConfigParser::isNextEntryEmpty() const
  185. {
  186. char * nextSymbol = curr;
  187. while (nextSymbol < end && *nextSymbol == ' ')
  188. nextSymbol++; //find next meaningfull symbol
  189. return nextSymbol >= end || *nextSymbol == '\n' || *nextSymbol == '\r' || *nextSymbol == '\t';
  190. }
  191. bool CLegacyConfigParser::endLine()
  192. {
  193. while (curr < end && *curr != '\n')
  194. readString();
  195. curr++;
  196. return curr < end;
  197. }
  198. void TextLocalizationContainer::registerStringOverride(const std::string & modContext, const std::string & language, const TextIdentifier & UID, const std::string & localized)
  199. {
  200. assert(!modContext.empty());
  201. assert(!language.empty());
  202. // NOTE: implicitly creates entry, intended - strings added by maps, campaigns, vcmi and potentially - UI mods are not registered anywhere at the moment
  203. auto & entry = stringsLocalizations[UID.get()];
  204. entry.overrideLanguage = language;
  205. entry.overrideValue = localized;
  206. if (entry.modContext.empty())
  207. entry.modContext = modContext;
  208. }
  209. void TextLocalizationContainer::addSubContainer(const TextLocalizationContainer & container)
  210. {
  211. subContainers.insert(&container);
  212. }
  213. void TextLocalizationContainer::removeSubContainer(const TextLocalizationContainer & container)
  214. {
  215. subContainers.erase(&container);
  216. }
  217. const std::string & TextLocalizationContainer::deserialize(const TextIdentifier & identifier) const
  218. {
  219. if(stringsLocalizations.count(identifier.get()) == 0)
  220. {
  221. for(const auto * container : subContainers)
  222. if(container->identifierExists(identifier))
  223. return container->deserialize(identifier);
  224. logGlobal->error("Unable to find localization for string '%s'", identifier.get());
  225. return identifier.get();
  226. }
  227. const auto & entry = stringsLocalizations.at(identifier.get());
  228. if (!entry.overrideValue.empty())
  229. return entry.overrideValue;
  230. return entry.baseValue;
  231. }
  232. void TextLocalizationContainer::registerString(const std::string & modContext, const TextIdentifier & UID, const std::string & localized, const std::string & language)
  233. {
  234. assert(!modContext.empty());
  235. assert(!Languages::getLanguageOptions(language).identifier.empty());
  236. assert(UID.get().find("..") == std::string::npos); // invalid identifier - there is section that was evaluated to empty string
  237. //assert(stringsLocalizations.count(UID.get()) == 0); // registering already registered string?
  238. if(stringsLocalizations.count(UID.get()) > 0)
  239. {
  240. auto & value = stringsLocalizations[UID.get()];
  241. value.baseLanguage = language;
  242. value.baseValue = localized;
  243. }
  244. else
  245. {
  246. StringState value;
  247. value.baseLanguage = language;
  248. value.baseValue = localized;
  249. value.modContext = modContext;
  250. stringsLocalizations[UID.get()] = value;
  251. }
  252. }
  253. void TextLocalizationContainer::registerString(const std::string & modContext, const TextIdentifier & UID, const std::string & localized)
  254. {
  255. assert(!getModLanguage(modContext).empty());
  256. registerString(modContext, UID, localized, getModLanguage(modContext));
  257. }
  258. bool TextLocalizationContainer::validateTranslation(const std::string & language, const std::string & modContext, const JsonNode & config) const
  259. {
  260. bool allPresent = true;
  261. for(const auto & string : stringsLocalizations)
  262. {
  263. if (string.second.modContext != modContext)
  264. continue; // Not our mod
  265. if (string.second.overrideLanguage == language)
  266. continue; // Already translated
  267. if (string.second.baseLanguage == language && !string.second.baseValue.empty())
  268. continue; // Base string already uses our language
  269. if (string.second.baseLanguage.empty())
  270. continue; // String added in localization, not present in base language (e.g. maps/campaigns)
  271. if (config.Struct().count(string.first) > 0)
  272. continue;
  273. if (allPresent)
  274. logMod->warn("Translation into language '%s' in mod '%s' is incomplete! Missing lines:", language, modContext);
  275. std::string currentText;
  276. if (string.second.overrideValue.empty())
  277. currentText = string.second.baseValue;
  278. else
  279. currentText = string.second.overrideValue;
  280. logMod->warn(R"( "%s" : "%s",)", string.first, TextOperations::escapeString(currentText));
  281. allPresent = false;
  282. }
  283. bool allFound = true;
  284. // for(const auto & string : config.Struct())
  285. // {
  286. // if (stringsLocalizations.count(string.first) > 0)
  287. // continue;
  288. //
  289. // if (allFound)
  290. // logMod->warn("Translation into language '%s' in mod '%s' has unused lines:", language, modContext);
  291. //
  292. // logMod->warn(R"( "%s" : "%s",)", string.first, TextOperations::escapeString(string.second.String()));
  293. // allFound = false;
  294. // }
  295. return allPresent && allFound;
  296. }
  297. void TextLocalizationContainer::loadTranslationOverrides(const std::string & language, const std::string & modContext, const JsonNode & config)
  298. {
  299. for(const auto & node : config.Struct())
  300. registerStringOverride(modContext, language, node.first, node.second.String());
  301. }
  302. bool TextLocalizationContainer::identifierExists(const TextIdentifier & UID) const
  303. {
  304. return stringsLocalizations.count(UID.get());
  305. }
  306. void TextLocalizationContainer::dumpAllTexts()
  307. {
  308. logGlobal->info("BEGIN TEXT EXPORT");
  309. for(const auto & entry : stringsLocalizations)
  310. {
  311. if (!entry.second.overrideValue.empty())
  312. logGlobal->info(R"("%s" : "%s",)", entry.first, TextOperations::escapeString(entry.second.overrideValue));
  313. else
  314. logGlobal->info(R"("%s" : "%s",)", entry.first, TextOperations::escapeString(entry.second.baseValue));
  315. }
  316. logGlobal->info("END TEXT EXPORT");
  317. }
  318. std::string TextLocalizationContainer::getModLanguage(const std::string & modContext)
  319. {
  320. if (modContext == "core")
  321. return CGeneralTextHandler::getInstalledLanguage();
  322. return VLC->modh->getModLanguage(modContext);
  323. }
  324. void TextLocalizationContainer::jsonSerialize(JsonNode & dest) const
  325. {
  326. for(auto & s : stringsLocalizations)
  327. {
  328. dest.Struct()[s.first].String() = s.second.baseValue;
  329. if(!s.second.overrideValue.empty())
  330. dest.Struct()[s.first].String() = s.second.overrideValue;
  331. }
  332. }
  333. void CGeneralTextHandler::readToVector(const std::string & sourceID, const std::string & sourceName)
  334. {
  335. CLegacyConfigParser parser(TextPath::builtin(sourceName));
  336. size_t index = 0;
  337. do
  338. {
  339. registerString( "core", {sourceID, index}, parser.readString());
  340. index += 1;
  341. }
  342. while (parser.endLine());
  343. }
  344. CGeneralTextHandler::CGeneralTextHandler():
  345. victoryConditions(*this, "core.vcdesc" ),
  346. lossCondtions (*this, "core.lcdesc" ),
  347. colors (*this, "core.plcolors" ),
  348. tcommands (*this, "core.tcommand" ),
  349. hcommands (*this, "core.hallinfo" ),
  350. fcommands (*this, "core.castinfo" ),
  351. advobtxt (*this, "core.advevent" ),
  352. restypes (*this, "core.restypes" ),
  353. randsign (*this, "core.randsign" ),
  354. overview (*this, "core.overview" ),
  355. arraytxt (*this, "core.arraytxt" ),
  356. primarySkillNames(*this, "core.priskill" ),
  357. jktexts (*this, "core.jktext" ),
  358. tavernInfo (*this, "core.tvrninfo" ),
  359. tavernRumors (*this, "core.randtvrn" ),
  360. turnDurations (*this, "core.turndur" ),
  361. heroscrn (*this, "core.heroscrn" ),
  362. tentColors (*this, "core.tentcolr" ),
  363. levels (*this, "core.skilllev" ),
  364. zelp (*this, "core.help" ),
  365. allTexts (*this, "core.genrltxt" ),
  366. // pseudo-array, that don't have H3 file with same name
  367. seerEmpty (*this, "core.seerhut.empty" ),
  368. seerNames (*this, "core.seerhut.names" ),
  369. capColors (*this, "vcmi.capitalColors" ),
  370. znpc00 (*this, "vcmi.znpc00" ), // technically - wog
  371. qeModCommands (*this, "vcmi.quickExchange" )
  372. {
  373. readToVector("core.vcdesc", "DATA/VCDESC.TXT" );
  374. readToVector("core.lcdesc", "DATA/LCDESC.TXT" );
  375. readToVector("core.tcommand", "DATA/TCOMMAND.TXT" );
  376. readToVector("core.hallinfo", "DATA/HALLINFO.TXT" );
  377. readToVector("core.castinfo", "DATA/CASTINFO.TXT" );
  378. readToVector("core.advevent", "DATA/ADVEVENT.TXT" );
  379. readToVector("core.restypes", "DATA/RESTYPES.TXT" );
  380. readToVector("core.randsign", "DATA/RANDSIGN.TXT" );
  381. readToVector("core.overview", "DATA/OVERVIEW.TXT" );
  382. readToVector("core.arraytxt", "DATA/ARRAYTXT.TXT" );
  383. readToVector("core.priskill", "DATA/PRISKILL.TXT" );
  384. readToVector("core.jktext", "DATA/JKTEXT.TXT" );
  385. readToVector("core.tvrninfo", "DATA/TVRNINFO.TXT" );
  386. readToVector("core.turndur", "DATA/TURNDUR.TXT" );
  387. readToVector("core.heroscrn", "DATA/HEROSCRN.TXT" );
  388. readToVector("core.tentcolr", "DATA/TENTCOLR.TXT" );
  389. readToVector("core.skilllev", "DATA/SKILLLEV.TXT" );
  390. readToVector("core.cmpmusic", "DATA/CMPMUSIC.TXT" );
  391. readToVector("core.minename", "DATA/MINENAME.TXT" );
  392. readToVector("core.mineevnt", "DATA/MINEEVNT.TXT" );
  393. static const char * QE_MOD_COMMANDS = "DATA/QECOMMANDS.TXT";
  394. if (CResourceHandler::get()->existsResource(TextPath::builtin(QE_MOD_COMMANDS)))
  395. readToVector("vcmi.quickExchange", QE_MOD_COMMANDS);
  396. {
  397. CLegacyConfigParser parser(TextPath::builtin("DATA/RANDTVRN.TXT"));
  398. parser.endLine();
  399. size_t index = 0;
  400. do
  401. {
  402. std::string line = parser.readString();
  403. if(!line.empty())
  404. {
  405. registerString("core", {"core.randtvrn", index}, line);
  406. index += 1;
  407. }
  408. }
  409. while (parser.endLine());
  410. }
  411. {
  412. CLegacyConfigParser parser(TextPath::builtin("DATA/GENRLTXT.TXT"));
  413. parser.endLine();
  414. size_t index = 0;
  415. do
  416. {
  417. registerString("core", {"core.genrltxt", index}, parser.readString());
  418. index += 1;
  419. }
  420. while (parser.endLine());
  421. }
  422. {
  423. CLegacyConfigParser parser(TextPath::builtin("DATA/HELP.TXT"));
  424. size_t index = 0;
  425. do
  426. {
  427. std::string first = parser.readString();
  428. std::string second = parser.readString();
  429. registerString("core", "core.help." + std::to_string(index) + ".hover", first);
  430. registerString("core", "core.help." + std::to_string(index) + ".help", second);
  431. index += 1;
  432. }
  433. while (parser.endLine());
  434. }
  435. {
  436. CLegacyConfigParser parser(TextPath::builtin("DATA/PLCOLORS.TXT"));
  437. size_t index = 0;
  438. do
  439. {
  440. std::string color = parser.readString();
  441. registerString("core", {"core.plcolors", index}, color);
  442. color[0] = toupper(color[0]);
  443. registerString("core", {"vcmi.capitalColors", index}, color);
  444. index += 1;
  445. }
  446. while (parser.endLine());
  447. }
  448. {
  449. CLegacyConfigParser parser(TextPath::builtin("DATA/SEERHUT.TXT"));
  450. //skip header
  451. parser.endLine();
  452. for (size_t i = 0; i < 6; ++i)
  453. {
  454. registerString("core", {"core.seerhut.empty", i}, parser.readString());
  455. }
  456. parser.endLine();
  457. for (size_t i = 0; i < 9; ++i) //9 types of quests
  458. {
  459. std::string questName = CQuest::missionName(static_cast<CQuest::Emission>(1+i));
  460. for (size_t j = 0; j < 5; ++j)
  461. {
  462. std::string questState = CQuest::missionState(j);
  463. parser.readString(); //front description
  464. for (size_t k = 0; k < 6; ++k)
  465. {
  466. registerString("core", {"core.seerhut.quest", questName, questState, k}, parser.readString());
  467. }
  468. parser.endLine();
  469. }
  470. }
  471. for (size_t k = 0; k < 6; ++k) //Time limit
  472. {
  473. registerString("core", {"core.seerhut.time", k}, parser.readString());
  474. }
  475. parser.endLine();
  476. parser.endLine(); // empty line
  477. parser.endLine(); // header
  478. for (size_t i = 0; i < 48; ++i)
  479. {
  480. registerString("core", {"core.seerhut.names", i}, parser.readString());
  481. parser.endLine();
  482. }
  483. }
  484. {
  485. CLegacyConfigParser parser(TextPath::builtin("DATA/CAMPTEXT.TXT"));
  486. //skip header
  487. parser.endLine();
  488. std::string text;
  489. size_t campaignsCount = 0;
  490. do
  491. {
  492. text = parser.readString();
  493. if (!text.empty())
  494. {
  495. registerString("core", {"core.camptext.names", campaignsCount}, text);
  496. campaignsCount += 1;
  497. }
  498. }
  499. while (parser.endLine() && !text.empty());
  500. for (size_t campaign=0; campaign<campaignsCount; campaign++)
  501. {
  502. size_t region = 0;
  503. do // skip empty space and header
  504. {
  505. text = parser.readString();
  506. }
  507. while (parser.endLine() && text.empty());
  508. do
  509. {
  510. text = parser.readString();
  511. if (!text.empty())
  512. {
  513. registerString("core", {"core.camptext.regions", std::to_string(campaign), region}, text);
  514. region += 1;
  515. }
  516. }
  517. while (parser.endLine() && !text.empty());
  518. scenariosCountPerCampaign.push_back(region);
  519. }
  520. }
  521. if (VLC->settings()->getBoolean(EGameSettings::MODULE_COMMANDERS))
  522. {
  523. if(CResourceHandler::get()->existsResource(TextPath::builtin("DATA/ZNPC00.TXT")))
  524. readToVector("vcmi.znpc00", "DATA/ZNPC00.TXT" );
  525. }
  526. }
  527. int32_t CGeneralTextHandler::pluralText(const int32_t textIndex, const int32_t count) const
  528. {
  529. if(textIndex == 0)
  530. return 0;
  531. if(textIndex < 0)
  532. return -textIndex;
  533. if(count == 1)
  534. return textIndex;
  535. return textIndex + 1;
  536. }
  537. size_t CGeneralTextHandler::getCampaignLength(size_t campaignID) const
  538. {
  539. assert(campaignID < scenariosCountPerCampaign.size());
  540. if(campaignID < scenariosCountPerCampaign.size())
  541. return scenariosCountPerCampaign[campaignID];
  542. return 0;
  543. }
  544. std::string CGeneralTextHandler::getPreferredLanguage()
  545. {
  546. assert(!settings["general"]["language"].String().empty());
  547. return settings["general"]["language"].String();
  548. }
  549. std::string CGeneralTextHandler::getInstalledLanguage()
  550. {
  551. assert(!settings["session"]["language"].String().empty());
  552. return settings["session"]["language"].String();
  553. }
  554. std::string CGeneralTextHandler::getInstalledEncoding()
  555. {
  556. assert(!settings["session"]["encoding"].String().empty());
  557. return settings["session"]["encoding"].String();
  558. }
  559. std::vector<std::string> CGeneralTextHandler::findStringsWithPrefix(const std::string & prefix)
  560. {
  561. std::vector<std::string> result;
  562. for(const auto & entry : stringsLocalizations)
  563. {
  564. if(boost::algorithm::starts_with(entry.first, prefix))
  565. result.push_back(entry.first);
  566. }
  567. return result;
  568. }
  569. LegacyTextContainer::LegacyTextContainer(CGeneralTextHandler & owner, std::string basePath):
  570. owner(owner),
  571. basePath(std::move(basePath))
  572. {}
  573. std::string LegacyTextContainer::operator[](size_t index) const
  574. {
  575. return owner.translate(basePath, index);
  576. }
  577. LegacyHelpContainer::LegacyHelpContainer(CGeneralTextHandler & owner, std::string basePath):
  578. owner(owner),
  579. basePath(std::move(basePath))
  580. {}
  581. std::pair<std::string, std::string> LegacyHelpContainer::operator[](size_t index) const
  582. {
  583. return {
  584. owner.translate(basePath + "." + std::to_string(index) + ".hover"),
  585. owner.translate(basePath + "." + std::to_string(index) + ".help")
  586. };
  587. }
  588. VCMI_LIB_NAMESPACE_END