CGeneralTextHandler.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525
  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 "VCMI_Lib.h"
  18. #include "Terrain.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 sourceName, std::vector<std::string> &dest)
  246. {
  247. CLegacyConfigParser parser(sourceName);
  248. do
  249. {
  250. dest.push_back(parser.readString());
  251. }
  252. while (parser.endLine());
  253. }
  254. CGeneralTextHandler::CGeneralTextHandler()
  255. {
  256. std::vector<std::string> h3mTerrainNames;
  257. readToVector("DATA/VCDESC.TXT", victoryConditions);
  258. readToVector("DATA/LCDESC.TXT", lossCondtions);
  259. readToVector("DATA/TCOMMAND.TXT", tcommands);
  260. readToVector("DATA/HALLINFO.TXT", hcommands);
  261. readToVector("DATA/CASTINFO.TXT", fcommands);
  262. readToVector("DATA/ADVEVENT.TXT", advobtxt);
  263. readToVector("DATA/XTRAINFO.TXT", xtrainfo);
  264. readToVector("DATA/RESTYPES.TXT", restypes);
  265. readToVector("DATA/TERRNAME.TXT", h3mTerrainNames);
  266. readToVector("DATA/RANDSIGN.TXT", randsign);
  267. readToVector("DATA/CRGEN1.TXT", creGens);
  268. readToVector("DATA/CRGEN4.TXT", creGens4);
  269. readToVector("DATA/OVERVIEW.TXT", overview);
  270. readToVector("DATA/ARRAYTXT.TXT", arraytxt);
  271. readToVector("DATA/PRISKILL.TXT", primarySkillNames);
  272. readToVector("DATA/JKTEXT.TXT", jktexts);
  273. readToVector("DATA/TVRNINFO.TXT", tavernInfo);
  274. readToVector("DATA/RANDTVRN.TXT", tavernRumors);
  275. readToVector("DATA/TURNDUR.TXT", turnDurations);
  276. readToVector("DATA/HEROSCRN.TXT", heroscrn);
  277. readToVector("DATA/TENTCOLR.TXT", tentColors);
  278. readToVector("DATA/SKILLLEV.TXT", levels);
  279. for(int i = 0; i < h3mTerrainNames.size(); ++i)
  280. {
  281. terrainNames[i] = h3mTerrainNames[i];
  282. }
  283. for(const auto & terrain : VLC->terrainTypeHandler->terrains())
  284. {
  285. if(!terrain.terrainText.empty())
  286. terrainNames[terrain.id] = terrain.terrainText;
  287. }
  288. static const char * QE_MOD_COMMANDS = "DATA/QECOMMANDS.TXT";
  289. if (CResourceHandler::get()->existsResource(ResourceID(QE_MOD_COMMANDS, EResType::TEXT)))
  290. readToVector(QE_MOD_COMMANDS, qeModCommands);
  291. localizedTexts = JsonNode(ResourceID("config/translate.json", EResType::TEXT));
  292. {
  293. CLegacyConfigParser parser("DATA/GENRLTXT.TXT");
  294. parser.endLine();
  295. do
  296. {
  297. allTexts.push_back(parser.readString());
  298. }
  299. while (parser.endLine());
  300. }
  301. {
  302. CLegacyConfigParser parser("DATA/HELP.TXT");
  303. do
  304. {
  305. std::string first = parser.readString();
  306. std::string second = parser.readString();
  307. zelp.push_back(std::make_pair(first, second));
  308. }
  309. while (parser.endLine());
  310. }
  311. {
  312. CLegacyConfigParser nameParser("DATA/MINENAME.TXT");
  313. CLegacyConfigParser eventParser("DATA/MINEEVNT.TXT");
  314. do
  315. {
  316. std::string name = nameParser.readString();
  317. std::string event = eventParser.readString();
  318. mines.push_back(std::make_pair(name, event));
  319. }
  320. while (nameParser.endLine() && eventParser.endLine());
  321. }
  322. {
  323. CLegacyConfigParser parser("DATA/PLCOLORS.TXT");
  324. do
  325. {
  326. std::string color = parser.readString();
  327. colors.push_back(color);
  328. color[0] = toupper(color[0]);
  329. capColors.push_back(color);
  330. }
  331. while (parser.endLine());
  332. }
  333. {
  334. CLegacyConfigParser parser("DATA/SEERHUT.TXT");
  335. //skip header
  336. parser.endLine();
  337. for (int i = 0; i < 6; ++i)
  338. seerEmpty.push_back(parser.readString());
  339. parser.endLine();
  340. quests.resize(10);
  341. for (int i = 0; i < 9; ++i) //9 types of quests
  342. {
  343. quests[i].resize(5);
  344. for (int j = 0; j < 5; ++j)
  345. {
  346. parser.readString(); //front description
  347. for (int k = 0; k < 6; ++k)
  348. quests[i][j].push_back(parser.readString());
  349. parser.endLine();
  350. }
  351. }
  352. quests[9].resize(1);
  353. for (int k = 0; k < 6; ++k) //Time limit
  354. {
  355. quests[9][0].push_back(parser.readString());
  356. }
  357. parser.endLine();
  358. parser.endLine(); // empty line
  359. parser.endLine(); // header
  360. for (int i = 0; i < 48; ++i)
  361. {
  362. seerNames.push_back(parser.readString());
  363. parser.endLine();
  364. }
  365. }
  366. {
  367. CLegacyConfigParser parser("DATA/CAMPTEXT.TXT");
  368. //skip header
  369. parser.endLine();
  370. std::string text;
  371. do
  372. {
  373. text = parser.readString();
  374. if (!text.empty())
  375. campaignMapNames.push_back(text);
  376. }
  377. while (parser.endLine() && !text.empty());
  378. for (size_t i=0; i<campaignMapNames.size(); i++)
  379. {
  380. do // skip empty space and header
  381. {
  382. text = parser.readString();
  383. }
  384. while (parser.endLine() && text.empty());
  385. campaignRegionNames.push_back(std::vector<std::string>());
  386. do
  387. {
  388. text = parser.readString();
  389. if (!text.empty())
  390. campaignRegionNames.back().push_back(text);
  391. }
  392. while (parser.endLine() && !text.empty());
  393. }
  394. }
  395. if (VLC->modh->modules.STACK_EXP)
  396. {
  397. CLegacyConfigParser parser("DATA/ZCREXP.TXT");
  398. parser.endLine();//header
  399. for (size_t iter=0; iter<325; iter++)
  400. {
  401. parser.readString(); //ignore 1st column with description
  402. zcrexp.push_back(parser.readString());
  403. parser.endLine();
  404. }
  405. // line 325 - some weird formatting here
  406. zcrexp.push_back(parser.readString());
  407. parser.readString();
  408. parser.endLine();
  409. do // rest of file can be read normally
  410. {
  411. parser.readString(); //ignore 1st column with description
  412. zcrexp.push_back(parser.readString());
  413. }
  414. while (parser.endLine());
  415. }
  416. if (VLC->modh->modules.COMMANDERS)
  417. {
  418. try
  419. {
  420. CLegacyConfigParser parser("DATA/ZNPC00.TXT");
  421. parser.endLine();//header
  422. do
  423. {
  424. znpc00.push_back(parser.readString());
  425. } while (parser.endLine());
  426. }
  427. catch (const std::runtime_error &)
  428. {
  429. logGlobal->warn("WoG file ZNPC00.TXT containing commander texts was not found");
  430. }
  431. }
  432. }
  433. int32_t CGeneralTextHandler::pluralText(const int32_t textIndex, const int32_t count) const
  434. {
  435. if(textIndex == 0)
  436. return 0;
  437. else if(textIndex < 0)
  438. return -textIndex;
  439. else if(count == 1)
  440. return textIndex;
  441. else
  442. return textIndex + 1;
  443. }
  444. VCMI_LIB_NAMESPACE_END