CGeneralTextHandler.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618
  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. static std::string getSelectedEncoding()
  91. {
  92. return settings["general"]["encoding"].String();
  93. }
  94. std::string Unicode::toUnicode(const std::string &text)
  95. {
  96. return toUnicode(text, getSelectedEncoding());
  97. }
  98. std::string Unicode::toUnicode(const std::string &text, const std::string &encoding)
  99. {
  100. return boost::locale::conv::to_utf<char>(text, encoding);
  101. }
  102. std::string Unicode::fromUnicode(const std::string & text)
  103. {
  104. return fromUnicode(text, getSelectedEncoding());
  105. }
  106. std::string Unicode::fromUnicode(const std::string &text, const std::string &encoding)
  107. {
  108. return boost::locale::conv::from_utf<char>(text, encoding);
  109. }
  110. void Unicode::trimRight(std::string & text, const size_t amount)
  111. {
  112. if(text.empty())
  113. return;
  114. //todo: more efficient algorithm
  115. for(int i = 0; i< amount; i++){
  116. auto b = text.begin();
  117. auto e = text.end();
  118. size_t lastLen = 0;
  119. size_t len = 0;
  120. while (b != e) {
  121. lastLen = len;
  122. size_t n = getCharacterSize(*b);
  123. if(!isValidCharacter(&(*b),e-b))
  124. {
  125. logGlobal->error("Invalid UTF8 sequence");
  126. break;//invalid sequence will be trimmed
  127. }
  128. len += n;
  129. b += n;
  130. }
  131. text.resize(lastLen);
  132. }
  133. }
  134. //Helper for string -> float conversion
  135. class LocaleWithComma: public std::numpunct<char>
  136. {
  137. protected:
  138. char do_decimal_point() const override
  139. {
  140. return ',';
  141. }
  142. };
  143. CLegacyConfigParser::CLegacyConfigParser(std::string URI)
  144. {
  145. init(CResourceHandler::get()->load(ResourceID(URI, EResType::TEXT)));
  146. }
  147. CLegacyConfigParser::CLegacyConfigParser(const std::unique_ptr<CInputStream> & input)
  148. {
  149. init(input);
  150. }
  151. void CLegacyConfigParser::init(const std::unique_ptr<CInputStream> & input)
  152. {
  153. data.reset(new char[input->getSize()]);
  154. input->read((ui8*)data.get(), input->getSize());
  155. curr = data.get();
  156. end = curr + input->getSize();
  157. }
  158. std::string CLegacyConfigParser::extractQuotedPart()
  159. {
  160. assert(*curr == '\"');
  161. curr++; // skip quote
  162. char * begin = curr;
  163. while (curr != end && *curr != '\"' && *curr != '\t')
  164. curr++;
  165. return std::string(begin, curr++); //increment curr to close quote
  166. }
  167. std::string CLegacyConfigParser::extractQuotedString()
  168. {
  169. assert(*curr == '\"');
  170. std::string ret;
  171. while (true)
  172. {
  173. ret += extractQuotedPart();
  174. // double quote - add it to string and continue quoted part
  175. if (curr < end && *curr == '\"')
  176. {
  177. ret += '\"';
  178. }
  179. //extract normal part
  180. else if(curr < end && *curr != '\t' && *curr != '\r')
  181. {
  182. char * begin = curr;
  183. while (curr < end && *curr != '\t' && *curr != '\r' && *curr != '\"')//find end of string or next quoted part start
  184. curr++;
  185. ret += std::string(begin, curr);
  186. if(curr>=end || *curr != '\"')
  187. return ret;
  188. }
  189. else // end of string
  190. return ret;
  191. }
  192. }
  193. std::string CLegacyConfigParser::extractNormalString()
  194. {
  195. char * begin = curr;
  196. while (curr < end && *curr != '\t' && *curr != '\r')//find end of string
  197. curr++;
  198. return std::string(begin, curr);
  199. }
  200. std::string CLegacyConfigParser::readRawString()
  201. {
  202. if (curr >= end || *curr == '\n')
  203. return "";
  204. std::string ret;
  205. if (*curr == '\"')
  206. ret = extractQuotedString();// quoted text - find closing quote
  207. else
  208. ret = extractNormalString();//string without quotes - copy till \t or \r
  209. curr++;
  210. return ret;
  211. }
  212. std::string CLegacyConfigParser::readString()
  213. {
  214. // do not convert strings that are already in ASCII - this will only slow down loading process
  215. std::string str = readRawString();
  216. if (Unicode::isValidASCII(str))
  217. return str;
  218. return Unicode::toUnicode(str);
  219. }
  220. float CLegacyConfigParser::readNumber()
  221. {
  222. std::string input = readRawString();
  223. std::istringstream stream(input);
  224. if(input.find(',') != std::string::npos) // code to handle conversion with comma as decimal separator
  225. stream.imbue(std::locale(std::locale(), new LocaleWithComma()));
  226. float result;
  227. if ( !(stream >> result) )
  228. return 0;
  229. return result;
  230. }
  231. bool CLegacyConfigParser::isNextEntryEmpty() const
  232. {
  233. char * nextSymbol = curr;
  234. while (nextSymbol < end && *nextSymbol == ' ')
  235. nextSymbol++; //find next meaningfull symbol
  236. return nextSymbol >= end || *nextSymbol == '\n' || *nextSymbol == '\r' || *nextSymbol == '\t';
  237. }
  238. bool CLegacyConfigParser::endLine()
  239. {
  240. while (curr < end && *curr != '\n')
  241. readString();
  242. curr++;
  243. return curr < end;
  244. }
  245. void CGeneralTextHandler::readToVector(std::string const & sourceID, std::string const & sourceName)
  246. {
  247. CLegacyConfigParser parser(sourceName);
  248. size_t index = 0;
  249. do
  250. {
  251. registerString({sourceID, index}, parser.readString());
  252. index += 1;
  253. }
  254. while (parser.endLine());
  255. }
  256. const std::string & CGeneralTextHandler::serialize(const std::string & identifier) const
  257. {
  258. assert(stringsIdentifiers.count(identifier));
  259. return stringsIdentifiers.at(identifier);
  260. }
  261. const std::string & CGeneralTextHandler::deserialize(const TextIdentifier & identifier) const
  262. {
  263. if(stringsLocalizations.count(identifier.get()))
  264. return stringsLocalizations.at(identifier.get());
  265. logGlobal->error("Unable to find localization for string '%s'", identifier.get());
  266. return identifier.get();
  267. }
  268. void CGeneralTextHandler::registerString(const TextIdentifier & UID, const std::string & localized)
  269. {
  270. stringsIdentifiers[localized] = UID.get();
  271. stringsLocalizations[UID.get()] = localized;
  272. }
  273. CGeneralTextHandler::CGeneralTextHandler():
  274. victoryConditions(*this, "core.vcdesc" ),
  275. lossCondtions (*this, "core.lcdesc" ),
  276. colors (*this, "core.plcolors" ),
  277. tcommands (*this, "core.tcommand" ),
  278. hcommands (*this, "core.hallinfo" ),
  279. fcommands (*this, "core.castinfo" ),
  280. advobtxt (*this, "core.advevent" ),
  281. xtrainfo (*this, "core.xtrainfo" ),
  282. restypes (*this, "core.restypes" ),
  283. randsign (*this, "core.randsign" ),
  284. overview (*this, "core.overview" ),
  285. arraytxt (*this, "core.arraytxt" ),
  286. primarySkillNames(*this, "core.priskill" ),
  287. jktexts (*this, "core.jktext" ),
  288. tavernInfo (*this, "core.tvrninfo" ),
  289. tavernRumors (*this, "core.randtvrn" ),
  290. turnDurations (*this, "core.turndur" ),
  291. heroscrn (*this, "core.heroscrn" ),
  292. tentColors (*this, "core.tentcolr" ),
  293. levels (*this, "core.skilllev" ),
  294. zelp (*this, "core.help" ),
  295. allTexts (*this, "core.genrltxt" ),
  296. // pseudo-array, that don't have H3 file with same name
  297. seerEmpty (*this, "core.seerhut.empty" ),
  298. seerNames (*this, "core.seerhut.names" ),
  299. capColors (*this, "vcmi.capitalColors" ),
  300. znpc00 (*this, "vcmi.znpc00" ), // technically - wog
  301. qeModCommands (*this, "vcmi.quickExchange" )
  302. {
  303. readToVector("core.vcdesc", "DATA/VCDESC.TXT" );
  304. readToVector("core.lcdesc", "DATA/LCDESC.TXT" );
  305. readToVector("core.tcommand", "DATA/TCOMMAND.TXT" );
  306. readToVector("core.hallinfo", "DATA/HALLINFO.TXT" );
  307. readToVector("core.castinfo", "DATA/CASTINFO.TXT" );
  308. readToVector("core.advevent", "DATA/ADVEVENT.TXT" );
  309. readToVector("core.xtrainfo", "DATA/XTRAINFO.TXT" );
  310. readToVector("core.restypes", "DATA/RESTYPES.TXT" );
  311. readToVector("core.randsign", "DATA/RANDSIGN.TXT" );
  312. readToVector("core.overview", "DATA/OVERVIEW.TXT" );
  313. readToVector("core.arraytxt", "DATA/ARRAYTXT.TXT" );
  314. readToVector("core.priskill", "DATA/PRISKILL.TXT" );
  315. readToVector("core.jktext", "DATA/JKTEXT.TXT" );
  316. readToVector("core.tvrninfo", "DATA/TVRNINFO.TXT" );
  317. readToVector("core.turndur", "DATA/TURNDUR.TXT" );
  318. readToVector("core.heroscrn", "DATA/HEROSCRN.TXT" );
  319. readToVector("core.tentcolr", "DATA/TENTCOLR.TXT" );
  320. readToVector("core.skilllev", "DATA/SKILLLEV.TXT" );
  321. readToVector("core.cmpmusic", "DATA/CMPMUSIC.TXT" );
  322. readToVector("core.minename", "DATA/MINENAME.TXT" );
  323. readToVector("core.mineevnt", "DATA/MINEEVNT.TXT" );
  324. static const char * QE_MOD_COMMANDS = "DATA/QECOMMANDS.TXT";
  325. if (CResourceHandler::get()->existsResource(ResourceID(QE_MOD_COMMANDS, EResType::TEXT)))
  326. readToVector("vcmi.quickExchange", QE_MOD_COMMANDS);
  327. auto vcmiTexts = JsonNode(ResourceID("config/translate.json", EResType::TEXT));
  328. for ( auto const & node : vcmiTexts.Struct())
  329. registerString(node.first, node.second.String());
  330. {
  331. CLegacyConfigParser parser("DATA/RANDTVRN.TXT");
  332. parser.endLine();
  333. size_t index = 0;
  334. do
  335. {
  336. std::string line = parser.readString();
  337. if(!line.empty())
  338. {
  339. registerString({"core.randtvrn", index}, line);
  340. index += 1;
  341. }
  342. }
  343. while (parser.endLine());
  344. }
  345. {
  346. CLegacyConfigParser parser("DATA/GENRLTXT.TXT");
  347. parser.endLine();
  348. size_t index = 0;
  349. do
  350. {
  351. registerString({"core.genrltxt", index}, parser.readString());
  352. index += 1;
  353. }
  354. while (parser.endLine());
  355. }
  356. {
  357. CLegacyConfigParser parser("DATA/HELP.TXT");
  358. size_t index = 0;
  359. do
  360. {
  361. std::string first = parser.readString();
  362. std::string second = parser.readString();
  363. registerString("core.help." + std::to_string(index) + ".hover", first);
  364. registerString("core.help." + std::to_string(index) + ".help", second);
  365. index += 1;
  366. }
  367. while (parser.endLine());
  368. }
  369. {
  370. CLegacyConfigParser parser("DATA/PLCOLORS.TXT");
  371. size_t index = 0;
  372. do
  373. {
  374. std::string color = parser.readString();
  375. registerString({"core.plcolors", index}, color);
  376. color[0] = toupper(color[0]);
  377. registerString({"vcmi.capitalColors", index}, color);
  378. index += 1;
  379. }
  380. while (parser.endLine());
  381. }
  382. {
  383. CLegacyConfigParser parser("DATA/SEERHUT.TXT");
  384. //skip header
  385. parser.endLine();
  386. for (size_t i = 0; i < 6; ++i)
  387. {
  388. registerString({"core.seerhut.empty", i}, parser.readString());
  389. }
  390. parser.endLine();
  391. for (size_t i = 0; i < 9; ++i) //9 types of quests
  392. {
  393. std::string questName = CQuest::missionName(CQuest::Emission(1+i));
  394. for (size_t j = 0; j < 5; ++j)
  395. {
  396. std::string questState = CQuest::missionState(j);
  397. parser.readString(); //front description
  398. for (size_t k = 0; k < 6; ++k)
  399. {
  400. registerString({"core.seerhut.quest", questName, questState, k}, parser.readString());
  401. }
  402. parser.endLine();
  403. }
  404. }
  405. for (size_t k = 0; k < 6; ++k) //Time limit
  406. {
  407. registerString({"core.seerhut.time", k}, parser.readString());
  408. }
  409. parser.endLine();
  410. parser.endLine(); // empty line
  411. parser.endLine(); // header
  412. for (size_t i = 0; i < 48; ++i)
  413. {
  414. registerString({"core.seerhut.names", i}, parser.readString());
  415. parser.endLine();
  416. }
  417. }
  418. {
  419. CLegacyConfigParser parser("DATA/CAMPTEXT.TXT");
  420. //skip header
  421. parser.endLine();
  422. std::string text;
  423. size_t campaignsCount = 0;
  424. do
  425. {
  426. text = parser.readString();
  427. if (!text.empty())
  428. {
  429. registerString({"core.camptext.names", campaignsCount}, text);
  430. campaignsCount += 1;
  431. }
  432. }
  433. while (parser.endLine() && !text.empty());
  434. for (size_t campaign=0; campaign<campaignsCount; campaign++)
  435. {
  436. size_t region = 0;
  437. do // skip empty space and header
  438. {
  439. text = parser.readString();
  440. }
  441. while (parser.endLine() && text.empty());
  442. do
  443. {
  444. text = parser.readString();
  445. if (!text.empty())
  446. {
  447. registerString({"core.camptext.regions", std::to_string(campaign), region}, text);
  448. region += 1;
  449. }
  450. }
  451. while (parser.endLine() && !text.empty());
  452. scenariosCountPerCampaign.push_back(region);
  453. }
  454. }
  455. if (VLC->modh->modules.COMMANDERS)
  456. {
  457. if(CResourceHandler::get()->existsResource(ResourceID("DATA/ZNPC00.TXT", EResType::TEXT)))
  458. readToVector("vcmi.znpc00", "DATA/ZNPC00.TXT" );
  459. }
  460. }
  461. int32_t CGeneralTextHandler::pluralText(const int32_t textIndex, const int32_t count) const
  462. {
  463. if(textIndex == 0)
  464. return 0;
  465. else if(textIndex < 0)
  466. return -textIndex;
  467. else if(count == 1)
  468. return textIndex;
  469. else
  470. return textIndex + 1;
  471. }
  472. void CGeneralTextHandler::dumpAllTexts()
  473. {
  474. logGlobal->info("BEGIN TEXT EXPORT");
  475. for ( auto const & entry : stringsLocalizations)
  476. {
  477. auto cleanString = entry.second;
  478. boost::replace_all(cleanString, "\\", "\\\\");
  479. boost::replace_all(cleanString, "\n", "\\n");
  480. boost::replace_all(cleanString, "\r", "\\r");
  481. boost::replace_all(cleanString, "\t", "\\t");
  482. boost::replace_all(cleanString, "\"", "\\\"");
  483. logGlobal->info("\"%s\" : \"%s\",", entry.first, cleanString);
  484. }
  485. logGlobal->info("END TEXT EXPORT");
  486. }
  487. size_t CGeneralTextHandler::getCampaignLength(size_t campaignID) const
  488. {
  489. assert(campaignID < scenariosCountPerCampaign.size());
  490. if(campaignID < scenariosCountPerCampaign.size())
  491. return scenariosCountPerCampaign[campaignID];
  492. return 0;
  493. }
  494. std::vector<std::string> CGeneralTextHandler::findStringsWithPrefix(std::string const & prefix)
  495. {
  496. std::vector<std::string> result;
  497. for (auto const & entry : stringsLocalizations)
  498. {
  499. if(boost::algorithm::starts_with(entry.first, prefix))
  500. result.push_back(entry.first);
  501. }
  502. return result;
  503. }
  504. LegacyTextContainer::LegacyTextContainer(CGeneralTextHandler & owner, std::string const & basePath):
  505. owner(owner),
  506. basePath(basePath)
  507. {}
  508. std::string LegacyTextContainer::operator[](size_t index) const
  509. {
  510. return owner.translate(basePath, index);
  511. }
  512. LegacyHelpContainer::LegacyHelpContainer(CGeneralTextHandler & owner, std::string const & basePath):
  513. owner(owner),
  514. basePath(basePath)
  515. {}
  516. std::pair<std::string, std::string> LegacyHelpContainer::operator[](size_t index) const
  517. {
  518. return {
  519. owner.translate(basePath + "." + std::to_string(index) + ".hover"),
  520. owner.translate(basePath + "." + std::to_string(index) + ".help")
  521. };
  522. }
  523. VCMI_LIB_NAMESPACE_END