CGeneralTextHandler.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768
  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 <boost/locale.hpp>
  13. #include "filesystem/Filesystem.h"
  14. #include "CConfigHandler.h"
  15. #include "CModHandler.h"
  16. #include "GameConstants.h"
  17. #include "mapObjects/CQuest.h"
  18. #include "VCMI_Lib.h"
  19. VCMI_LIB_NAMESPACE_BEGIN
  20. size_t Unicode::getCharacterSize(char firstByte)
  21. {
  22. // length of utf-8 character can be determined from 1st byte by counting number of highest bits set to 1:
  23. // 0xxxxxxx -> 1 - ASCII chars
  24. // 110xxxxx -> 2
  25. // 11110xxx -> 4 - last allowed in current standard
  26. // 1111110x -> 6 - last allowed in original standard
  27. if ((ui8)firstByte < 0x80)
  28. return 1; // ASCII
  29. size_t ret = 0;
  30. for (size_t i=0; i<8; i++)
  31. {
  32. if (((ui8)firstByte & (0x80 >> i)) != 0)
  33. ret++;
  34. else
  35. break;
  36. }
  37. return ret;
  38. }
  39. bool Unicode::isValidCharacter(const char * character, size_t maxSize)
  40. {
  41. // can't be first byte in UTF8
  42. if ((ui8)character[0] >= 0x80 && (ui8)character[0] < 0xC0)
  43. return false;
  44. // first character must follow rules checked in getCharacterSize
  45. size_t size = getCharacterSize((ui8)character[0]);
  46. if ((ui8)character[0] > 0xF4)
  47. return false; // above maximum allowed in standard (UTF codepoints are capped at 0x0010FFFF)
  48. if (size > maxSize)
  49. return false;
  50. // remaining characters must have highest bit set to 1
  51. for (size_t i = 1; i < size; i++)
  52. {
  53. if (((ui8)character[i] & 0x80) == 0)
  54. return false;
  55. }
  56. return true;
  57. }
  58. bool Unicode::isValidASCII(const std::string & text)
  59. {
  60. for (const char & ch : text)
  61. if (ui8(ch) >= 0x80 )
  62. return false;
  63. return true;
  64. }
  65. bool Unicode::isValidASCII(const char * data, size_t size)
  66. {
  67. for (size_t i=0; i<size; i++)
  68. if (ui8(data[i]) >= 0x80 )
  69. return false;
  70. return true;
  71. }
  72. bool Unicode::isValidString(const std::string & text)
  73. {
  74. for (size_t i=0; i<text.size(); i += getCharacterSize(text[i]))
  75. {
  76. if (!isValidCharacter(text.data() + i, text.size() - i))
  77. return false;
  78. }
  79. return true;
  80. }
  81. bool Unicode::isValidString(const char * data, size_t size)
  82. {
  83. for (size_t i=0; i<size; i += getCharacterSize(data[i]))
  84. {
  85. if (!isValidCharacter(data + i, size - i))
  86. return false;
  87. }
  88. return true;
  89. }
  90. /// Detects language and encoding of H3 text files based on matching against pregenerated footprints of H3 file
  91. void CGeneralTextHandler::detectInstallParameters()
  92. {
  93. struct LanguageFootprint
  94. {
  95. std::string language;
  96. std::string encoding;
  97. std::array<double, 16> footprint;
  98. };
  99. static const std::vector<LanguageFootprint> knownFootprints =
  100. {
  101. { "english", "CP1252", { { 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 } } },
  102. { "french", "CP1252", { { 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 } } },
  103. { "german", "CP1252", { { 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 } } },
  104. { "polish", "CP1250", { { 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 } } },
  105. { "russian", "CP1251", { { 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 } } },
  106. { "ukrainian", "CP1251", { { 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 } } },
  107. };
  108. // load file that will be used for footprint generation
  109. // this is one of the most text-heavy files in game and consists solely from translated texts
  110. auto resource = CResourceHandler::get()->load(ResourceID("DATA/GENRLTXT.TXT", EResType::TEXT));
  111. std::array<size_t, 256> charCount{};
  112. std::array<double, 16> footprint{};
  113. std::vector<double> deviations(knownFootprints.size(), 0.0);
  114. auto data = resource->readAll();
  115. // compute how often each character occurs in input file
  116. for (si64 i = 0; i < data.second; ++i)
  117. charCount[data.first[i]] += 1;
  118. // and convert computed data into weights
  119. // to reduce amount of data, group footprint data into 16-char blocks.
  120. // While this will reduce precision, it should not affect output
  121. // since we expect only tiny differences compared to reference footprints
  122. for (size_t i = 0; i < 256; ++i)
  123. footprint[i/16] += static_cast<double>(charCount[i]) / data.second;
  124. logGlobal->debug("Language footprint: %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f",
  125. footprint[0], footprint[1], footprint[2], footprint[3], footprint[4], footprint[5], footprint[6], footprint[7],
  126. footprint[8], footprint[9], footprint[10], footprint[11], footprint[12], footprint[13], footprint[14], footprint[15]
  127. );
  128. for (size_t i = 0; i < deviations.size(); ++i)
  129. {
  130. for (size_t j = 0; j < footprint.size(); ++j)
  131. deviations[i] += std::abs((footprint[j] - knownFootprints[i].footprint[j]));
  132. }
  133. size_t bestIndex = boost::range::min_element(deviations) - deviations.begin();
  134. for (size_t i = 0; i < deviations.size(); ++i)
  135. logGlobal->debug("Comparing to %s: %f", knownFootprints[i].language, deviations[i]);
  136. Settings language = settings.write["session"]["language"];
  137. language->String() = knownFootprints[bestIndex].language;
  138. Settings encoding = settings.write["session"]["encoding"];
  139. encoding->String() = knownFootprints[bestIndex].encoding;
  140. }
  141. std::string Unicode::toUnicode(const std::string &text)
  142. {
  143. return toUnicode(text, CGeneralTextHandler::getInstalledEncoding());
  144. }
  145. std::string Unicode::toUnicode(const std::string &text, const std::string &encoding)
  146. {
  147. return boost::locale::conv::to_utf<char>(text, encoding);
  148. }
  149. std::string Unicode::fromUnicode(const std::string & text)
  150. {
  151. return fromUnicode(text, CGeneralTextHandler::getInstalledEncoding());
  152. }
  153. std::string Unicode::fromUnicode(const std::string &text, const std::string &encoding)
  154. {
  155. return boost::locale::conv::from_utf<char>(text, encoding);
  156. }
  157. void Unicode::trimRight(std::string & text, const size_t amount)
  158. {
  159. if(text.empty())
  160. return;
  161. //todo: more efficient algorithm
  162. for(int i = 0; i< amount; i++){
  163. auto b = text.begin();
  164. auto e = text.end();
  165. size_t lastLen = 0;
  166. size_t len = 0;
  167. while (b != e) {
  168. lastLen = len;
  169. size_t n = getCharacterSize(*b);
  170. if(!isValidCharacter(&(*b),e-b))
  171. {
  172. logGlobal->error("Invalid UTF8 sequence");
  173. break;//invalid sequence will be trimmed
  174. }
  175. len += n;
  176. b += n;
  177. }
  178. text.resize(lastLen);
  179. }
  180. }
  181. //Helper for string -> float conversion
  182. class LocaleWithComma: public std::numpunct<char>
  183. {
  184. protected:
  185. char do_decimal_point() const override
  186. {
  187. return ',';
  188. }
  189. };
  190. CLegacyConfigParser::CLegacyConfigParser(std::string URI):
  191. CLegacyConfigParser(CResourceHandler::get()->load(ResourceID(URI, EResType::TEXT)))
  192. {
  193. }
  194. CLegacyConfigParser::CLegacyConfigParser(const std::unique_ptr<CInputStream> & input)
  195. {
  196. data.reset(new char[input->getSize()]);
  197. input->read(reinterpret_cast<uint8_t*>(data.get()), input->getSize());
  198. curr = data.get();
  199. end = curr + input->getSize();
  200. }
  201. std::string CLegacyConfigParser::extractQuotedPart()
  202. {
  203. assert(*curr == '\"');
  204. curr++; // skip quote
  205. char * begin = curr;
  206. while (curr != end && *curr != '\"' && *curr != '\t')
  207. curr++;
  208. return std::string(begin, curr++); //increment curr to close quote
  209. }
  210. std::string CLegacyConfigParser::extractQuotedString()
  211. {
  212. assert(*curr == '\"');
  213. std::string ret;
  214. while (true)
  215. {
  216. ret += extractQuotedPart();
  217. // double quote - add it to string and continue quoted part
  218. if (curr < end && *curr == '\"')
  219. {
  220. ret += '\"';
  221. }
  222. //extract normal part
  223. else if(curr < end && *curr != '\t' && *curr != '\r')
  224. {
  225. char * begin = curr;
  226. while (curr < end && *curr != '\t' && *curr != '\r' && *curr != '\"')//find end of string or next quoted part start
  227. curr++;
  228. ret += std::string(begin, curr);
  229. if(curr>=end || *curr != '\"')
  230. return ret;
  231. }
  232. else // end of string
  233. return ret;
  234. }
  235. }
  236. std::string CLegacyConfigParser::extractNormalString()
  237. {
  238. char * begin = curr;
  239. while (curr < end && *curr != '\t' && *curr != '\r')//find end of string
  240. curr++;
  241. return std::string(begin, curr);
  242. }
  243. std::string CLegacyConfigParser::readRawString()
  244. {
  245. if (curr >= end || *curr == '\n')
  246. return "";
  247. std::string ret;
  248. if (*curr == '\"')
  249. ret = extractQuotedString();// quoted text - find closing quote
  250. else
  251. ret = extractNormalString();//string without quotes - copy till \t or \r
  252. curr++;
  253. return ret;
  254. }
  255. std::string CLegacyConfigParser::readString()
  256. {
  257. // do not convert strings that are already in ASCII - this will only slow down loading process
  258. std::string str = readRawString();
  259. if (Unicode::isValidASCII(str))
  260. return str;
  261. return Unicode::toUnicode(str);
  262. }
  263. float CLegacyConfigParser::readNumber()
  264. {
  265. std::string input = readRawString();
  266. std::istringstream stream(input);
  267. if(input.find(',') != std::string::npos) // code to handle conversion with comma as decimal separator
  268. stream.imbue(std::locale(std::locale(), new LocaleWithComma()));
  269. float result;
  270. if ( !(stream >> result) )
  271. return 0;
  272. return result;
  273. }
  274. bool CLegacyConfigParser::isNextEntryEmpty() const
  275. {
  276. char * nextSymbol = curr;
  277. while (nextSymbol < end && *nextSymbol == ' ')
  278. nextSymbol++; //find next meaningfull symbol
  279. return nextSymbol >= end || *nextSymbol == '\n' || *nextSymbol == '\r' || *nextSymbol == '\t';
  280. }
  281. bool CLegacyConfigParser::endLine()
  282. {
  283. while (curr < end && *curr != '\n')
  284. readString();
  285. curr++;
  286. return curr < end;
  287. }
  288. void CGeneralTextHandler::readToVector(std::string const & sourceID, std::string const & sourceName)
  289. {
  290. CLegacyConfigParser parser(sourceName);
  291. size_t index = 0;
  292. do
  293. {
  294. registerString( "core", {sourceID, index}, parser.readString());
  295. index += 1;
  296. }
  297. while (parser.endLine());
  298. }
  299. const std::string & CGeneralTextHandler::deserialize(const TextIdentifier & identifier) const
  300. {
  301. if(stringsLocalizations.count(identifier.get()) == 0)
  302. {
  303. logGlobal->error("Unable to find localization for string '%s'", identifier.get());
  304. return identifier.get();
  305. }
  306. auto const & entry = stringsLocalizations.at(identifier.get());
  307. if (!entry.overrideValue.empty())
  308. return entry.overrideValue;
  309. return entry.baseValue;
  310. }
  311. void CGeneralTextHandler::registerString(const std::string & modContext, const TextIdentifier & UID, const std::string & localized)
  312. {
  313. assert(UID.get().find("..") == std::string::npos); // invalid identifier - there is section that was evaluated to empty string
  314. assert(stringsLocalizations.count(UID.get()) == 0); // registering already registered string?
  315. assert(!modContext.empty());
  316. assert(!getModLanguage(modContext).empty());
  317. StringState result;
  318. result.baseLanguage = getModLanguage(modContext);
  319. result.baseValue = localized;
  320. result.modContext = modContext;
  321. stringsLocalizations[UID.get()] = result;
  322. }
  323. void CGeneralTextHandler::registerStringOverride(const std::string & modContext, const std::string & language, const TextIdentifier & UID, const std::string & localized)
  324. {
  325. assert(!modContext.empty());
  326. assert(!language.empty());
  327. // NOTE: implicitly creates entry, intended - strings added by vcmi (and potential UI mods) are not registered anywhere at the moment
  328. auto & entry = stringsLocalizations[UID.get()];
  329. entry.overrideLanguage = language;
  330. entry.overrideValue = localized;
  331. if (entry.modContext.empty())
  332. entry.modContext = modContext;
  333. }
  334. bool CGeneralTextHandler::validateTranslation(const std::string & language, const std::string & modContext, const JsonNode & config) const
  335. {
  336. bool allPresent = true;
  337. for (auto const & string : stringsLocalizations)
  338. {
  339. if (string.second.modContext != modContext)
  340. continue;
  341. if (string.second.baseLanguage == language && !string.second.baseValue.empty())
  342. continue;
  343. if (config.Struct().count(string.first) > 0)
  344. continue;
  345. if (allPresent)
  346. logMod->warn("Translation into language '%s' in mod '%s' is incomplete! Missing lines:", language, modContext);
  347. logMod->warn(R"( "%s" : "",)", string.first);
  348. allPresent = false;
  349. }
  350. bool allFound = true;
  351. for (auto const & string : config.Struct())
  352. {
  353. if (stringsLocalizations.count(string.first) > 0)
  354. continue;
  355. if (allFound)
  356. logMod->warn("Translation into language '%s' in mod '%s' has unused lines:", language, modContext);
  357. logMod->warn(R"( "%s" : "",)", string.first);
  358. allFound = false;
  359. }
  360. return allPresent && allFound;
  361. }
  362. void CGeneralTextHandler::loadTranslationOverrides(const std::string & language, const std::string & modContext, const JsonNode & config)
  363. {
  364. for ( auto const & node : config.Struct())
  365. registerStringOverride(modContext, language, node.first, node.second.String());
  366. }
  367. CGeneralTextHandler::CGeneralTextHandler():
  368. victoryConditions(*this, "core.vcdesc" ),
  369. lossCondtions (*this, "core.lcdesc" ),
  370. colors (*this, "core.plcolors" ),
  371. tcommands (*this, "core.tcommand" ),
  372. hcommands (*this, "core.hallinfo" ),
  373. fcommands (*this, "core.castinfo" ),
  374. advobtxt (*this, "core.advevent" ),
  375. restypes (*this, "core.restypes" ),
  376. randsign (*this, "core.randsign" ),
  377. overview (*this, "core.overview" ),
  378. arraytxt (*this, "core.arraytxt" ),
  379. primarySkillNames(*this, "core.priskill" ),
  380. jktexts (*this, "core.jktext" ),
  381. tavernInfo (*this, "core.tvrninfo" ),
  382. tavernRumors (*this, "core.randtvrn" ),
  383. turnDurations (*this, "core.turndur" ),
  384. heroscrn (*this, "core.heroscrn" ),
  385. tentColors (*this, "core.tentcolr" ),
  386. levels (*this, "core.skilllev" ),
  387. zelp (*this, "core.help" ),
  388. allTexts (*this, "core.genrltxt" ),
  389. // pseudo-array, that don't have H3 file with same name
  390. seerEmpty (*this, "core.seerhut.empty" ),
  391. seerNames (*this, "core.seerhut.names" ),
  392. capColors (*this, "vcmi.capitalColors" ),
  393. znpc00 (*this, "vcmi.znpc00" ), // technically - wog
  394. qeModCommands (*this, "vcmi.quickExchange" )
  395. {
  396. detectInstallParameters();
  397. readToVector("core.vcdesc", "DATA/VCDESC.TXT" );
  398. readToVector("core.lcdesc", "DATA/LCDESC.TXT" );
  399. readToVector("core.tcommand", "DATA/TCOMMAND.TXT" );
  400. readToVector("core.hallinfo", "DATA/HALLINFO.TXT" );
  401. readToVector("core.castinfo", "DATA/CASTINFO.TXT" );
  402. readToVector("core.advevent", "DATA/ADVEVENT.TXT" );
  403. readToVector("core.restypes", "DATA/RESTYPES.TXT" );
  404. readToVector("core.randsign", "DATA/RANDSIGN.TXT" );
  405. readToVector("core.overview", "DATA/OVERVIEW.TXT" );
  406. readToVector("core.arraytxt", "DATA/ARRAYTXT.TXT" );
  407. readToVector("core.priskill", "DATA/PRISKILL.TXT" );
  408. readToVector("core.jktext", "DATA/JKTEXT.TXT" );
  409. readToVector("core.tvrninfo", "DATA/TVRNINFO.TXT" );
  410. readToVector("core.turndur", "DATA/TURNDUR.TXT" );
  411. readToVector("core.heroscrn", "DATA/HEROSCRN.TXT" );
  412. readToVector("core.tentcolr", "DATA/TENTCOLR.TXT" );
  413. readToVector("core.skilllev", "DATA/SKILLLEV.TXT" );
  414. readToVector("core.cmpmusic", "DATA/CMPMUSIC.TXT" );
  415. readToVector("core.minename", "DATA/MINENAME.TXT" );
  416. readToVector("core.mineevnt", "DATA/MINEEVNT.TXT" );
  417. static const char * QE_MOD_COMMANDS = "DATA/QECOMMANDS.TXT";
  418. if (CResourceHandler::get()->existsResource(ResourceID(QE_MOD_COMMANDS, EResType::TEXT)))
  419. readToVector("vcmi.quickExchange", QE_MOD_COMMANDS);
  420. {
  421. CLegacyConfigParser parser("DATA/RANDTVRN.TXT");
  422. parser.endLine();
  423. size_t index = 0;
  424. do
  425. {
  426. std::string line = parser.readString();
  427. if(!line.empty())
  428. {
  429. registerString("core", {"core.randtvrn", index}, line);
  430. index += 1;
  431. }
  432. }
  433. while (parser.endLine());
  434. }
  435. {
  436. CLegacyConfigParser parser("DATA/GENRLTXT.TXT");
  437. parser.endLine();
  438. size_t index = 0;
  439. do
  440. {
  441. registerString("core", {"core.genrltxt", index}, parser.readString());
  442. index += 1;
  443. }
  444. while (parser.endLine());
  445. }
  446. {
  447. CLegacyConfigParser parser("DATA/HELP.TXT");
  448. size_t index = 0;
  449. do
  450. {
  451. std::string first = parser.readString();
  452. std::string second = parser.readString();
  453. registerString("core", "core.help." + std::to_string(index) + ".hover", first);
  454. registerString("core", "core.help." + std::to_string(index) + ".help", second);
  455. index += 1;
  456. }
  457. while (parser.endLine());
  458. }
  459. {
  460. CLegacyConfigParser parser("DATA/PLCOLORS.TXT");
  461. size_t index = 0;
  462. do
  463. {
  464. std::string color = parser.readString();
  465. registerString("core", {"core.plcolors", index}, color);
  466. color[0] = toupper(color[0]);
  467. registerString("core", {"vcmi.capitalColors", index}, color);
  468. index += 1;
  469. }
  470. while (parser.endLine());
  471. }
  472. {
  473. CLegacyConfigParser parser("DATA/SEERHUT.TXT");
  474. //skip header
  475. parser.endLine();
  476. for (size_t i = 0; i < 6; ++i)
  477. {
  478. registerString("core", {"core.seerhut.empty", i}, parser.readString());
  479. }
  480. parser.endLine();
  481. for (size_t i = 0; i < 9; ++i) //9 types of quests
  482. {
  483. std::string questName = CQuest::missionName(static_cast<CQuest::Emission>(1+i));
  484. for (size_t j = 0; j < 5; ++j)
  485. {
  486. std::string questState = CQuest::missionState(j);
  487. parser.readString(); //front description
  488. for (size_t k = 0; k < 6; ++k)
  489. {
  490. registerString("core", {"core.seerhut.quest", questName, questState, k}, parser.readString());
  491. }
  492. parser.endLine();
  493. }
  494. }
  495. for (size_t k = 0; k < 6; ++k) //Time limit
  496. {
  497. registerString("core", {"core.seerhut.time", k}, parser.readString());
  498. }
  499. parser.endLine();
  500. parser.endLine(); // empty line
  501. parser.endLine(); // header
  502. for (size_t i = 0; i < 48; ++i)
  503. {
  504. registerString("core", {"core.seerhut.names", i}, parser.readString());
  505. parser.endLine();
  506. }
  507. }
  508. {
  509. CLegacyConfigParser parser("DATA/CAMPTEXT.TXT");
  510. //skip header
  511. parser.endLine();
  512. std::string text;
  513. size_t campaignsCount = 0;
  514. do
  515. {
  516. text = parser.readString();
  517. if (!text.empty())
  518. {
  519. registerString("core", {"core.camptext.names", campaignsCount}, text);
  520. campaignsCount += 1;
  521. }
  522. }
  523. while (parser.endLine() && !text.empty());
  524. for (size_t campaign=0; campaign<campaignsCount; campaign++)
  525. {
  526. size_t region = 0;
  527. do // skip empty space and header
  528. {
  529. text = parser.readString();
  530. }
  531. while (parser.endLine() && text.empty());
  532. do
  533. {
  534. text = parser.readString();
  535. if (!text.empty())
  536. {
  537. registerString("core", {"core.camptext.regions", std::to_string(campaign), region}, text);
  538. region += 1;
  539. }
  540. }
  541. while (parser.endLine() && !text.empty());
  542. scenariosCountPerCampaign.push_back(region);
  543. }
  544. }
  545. if (VLC->modh->modules.COMMANDERS)
  546. {
  547. if(CResourceHandler::get()->existsResource(ResourceID("DATA/ZNPC00.TXT", EResType::TEXT)))
  548. readToVector("vcmi.znpc00", "DATA/ZNPC00.TXT" );
  549. }
  550. }
  551. int32_t CGeneralTextHandler::pluralText(int32_t textIndex, int32_t count) const
  552. {
  553. if(textIndex == 0)
  554. return 0;
  555. if(textIndex < 0)
  556. return -textIndex;
  557. if(count == 1)
  558. return textIndex;
  559. return textIndex + 1;
  560. }
  561. void CGeneralTextHandler::dumpAllTexts()
  562. {
  563. auto escapeString = [](std::string input)
  564. {
  565. boost::replace_all(input, "\\", "\\\\");
  566. boost::replace_all(input, "\n", "\\n");
  567. boost::replace_all(input, "\r", "\\r");
  568. boost::replace_all(input, "\t", "\\t");
  569. boost::replace_all(input, "\"", "\\\"");
  570. return input;
  571. };
  572. logGlobal->info("BEGIN TEXT EXPORT");
  573. for ( auto const & entry : stringsLocalizations)
  574. {
  575. if (!entry.second.overrideValue.empty())
  576. logGlobal->info(R"("%s" : "%s", // %s / %s)", entry.first, escapeString(entry.second.overrideValue), entry.second.modContext, entry.second.overrideLanguage);
  577. else
  578. logGlobal->info(R"("%s" : "%s", // %s / %s)", entry.first, escapeString(entry.second.baseValue), entry.second.modContext, entry.second.baseLanguage);
  579. }
  580. logGlobal->info("END TEXT EXPORT");
  581. }
  582. size_t CGeneralTextHandler::getCampaignLength(size_t campaignID) const
  583. {
  584. assert(campaignID < scenariosCountPerCampaign.size());
  585. if(campaignID < scenariosCountPerCampaign.size())
  586. return scenariosCountPerCampaign[campaignID];
  587. return 0;
  588. }
  589. std::string CGeneralTextHandler::getModLanguage(const std::string & modContext)
  590. {
  591. if (modContext == "core")
  592. return getInstalledLanguage();
  593. return VLC->modh->getModLanguage(modContext);
  594. }
  595. std::string CGeneralTextHandler::getPreferredLanguage()
  596. {
  597. return settings["general"]["language"].String();
  598. }
  599. std::string CGeneralTextHandler::getInstalledLanguage()
  600. {
  601. return settings["session"]["language"].String();
  602. }
  603. std::string CGeneralTextHandler::getInstalledEncoding()
  604. {
  605. auto explicitSetting = settings["general"]["encoding"].String();
  606. if (explicitSetting != "auto")
  607. return explicitSetting;
  608. return settings["session"]["encoding"].String();
  609. }
  610. std::vector<std::string> CGeneralTextHandler::findStringsWithPrefix(std::string const & prefix)
  611. {
  612. std::vector<std::string> result;
  613. for (auto const & entry : stringsLocalizations)
  614. {
  615. if(boost::algorithm::starts_with(entry.first, prefix))
  616. result.push_back(entry.first);
  617. }
  618. return result;
  619. }
  620. LegacyTextContainer::LegacyTextContainer(CGeneralTextHandler & owner, std::string const & basePath):
  621. owner(owner),
  622. basePath(basePath)
  623. {}
  624. std::string LegacyTextContainer::operator[](size_t index) const
  625. {
  626. return owner.translate(basePath, index);
  627. }
  628. LegacyHelpContainer::LegacyHelpContainer(CGeneralTextHandler & owner, std::string const & basePath):
  629. owner(owner),
  630. basePath(basePath)
  631. {}
  632. std::pair<std::string, std::string> LegacyHelpContainer::operator[](size_t index) const
  633. {
  634. return {
  635. owner.translate(basePath + "." + std::to_string(index) + ".hover"),
  636. owner.translate(basePath + "." + std::to_string(index) + ".help")
  637. };
  638. }
  639. VCMI_LIB_NAMESPACE_END