CGeneralTextHandler.h 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. /*
  2. * CGeneralTextHandler.h, 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. #pragma once
  11. #include "filesystem/ResourcePath.h"
  12. VCMI_LIB_NAMESPACE_BEGIN
  13. class CInputStream;
  14. class JsonNode;
  15. class JsonSerializeFormat;
  16. /// Parser for any text files from H3
  17. class DLL_LINKAGE CLegacyConfigParser
  18. {
  19. std::string fileEncoding;
  20. std::unique_ptr<char[]> data;
  21. char * curr;
  22. char * end;
  23. /// extracts part of quoted string.
  24. std::string extractQuotedPart();
  25. /// extracts quoted string. Any end of lines are ignored, double-quote is considered as "escaping"
  26. std::string extractQuotedString();
  27. /// extracts non-quoted string
  28. std::string extractNormalString();
  29. /// reads "raw" string without encoding conversion
  30. std::string readRawString();
  31. public:
  32. /// read one entry from current line. Return ""/0 if end of line reached
  33. std::string readString();
  34. float readNumber();
  35. template <typename numeric>
  36. std::vector<numeric> readNumArray(size_t size)
  37. {
  38. std::vector<numeric> ret;
  39. ret.reserve(size);
  40. while (size--)
  41. ret.push_back((numeric)readNumber());
  42. return ret;
  43. }
  44. /// returns true if next entry is empty
  45. bool isNextEntryEmpty() const;
  46. /// end current line
  47. bool endLine();
  48. explicit CLegacyConfigParser(const TextPath & URI);
  49. };
  50. class CGeneralTextHandler;
  51. /// Small wrapper that provides text access API compatible with old code
  52. class DLL_LINKAGE LegacyTextContainer
  53. {
  54. CGeneralTextHandler & owner;
  55. std::string basePath;
  56. public:
  57. LegacyTextContainer(CGeneralTextHandler & owner, std::string basePath);
  58. std::string operator [](size_t index) const;
  59. };
  60. /// Small wrapper that provides help text access API compatible with old code
  61. class DLL_LINKAGE LegacyHelpContainer
  62. {
  63. CGeneralTextHandler & owner;
  64. std::string basePath;
  65. public:
  66. LegacyHelpContainer(CGeneralTextHandler & owner, std::string basePath);
  67. std::pair<std::string, std::string> operator[](size_t index) const;
  68. };
  69. class TextIdentifier
  70. {
  71. std::string identifier;
  72. public:
  73. const std::string & get() const
  74. {
  75. return identifier;
  76. }
  77. TextIdentifier(const char * id):
  78. identifier(id)
  79. {}
  80. TextIdentifier(const std::string & id):
  81. identifier(id)
  82. {}
  83. template<typename... T>
  84. TextIdentifier(const std::string & id, size_t index, T... rest):
  85. TextIdentifier(id + '.' + std::to_string(index), rest...)
  86. {}
  87. template<typename... T>
  88. TextIdentifier(const std::string & id, const std::string & id2, T... rest):
  89. TextIdentifier(id + '.' + id2, rest...)
  90. {}
  91. };
  92. class DLL_LINKAGE TextLocalizationContainer
  93. {
  94. protected:
  95. static std::recursive_mutex globalTextMutex;
  96. struct StringState
  97. {
  98. /// Human-readable string that was added on registration
  99. std::string baseValue;
  100. /// Language of base string
  101. std::string baseLanguage;
  102. /// Translated human-readable string
  103. std::string overrideValue;
  104. /// Language of the override string
  105. std::string overrideLanguage;
  106. /// ID of mod that created this string
  107. std::string modContext;
  108. template <typename Handler>
  109. void serialize(Handler & h)
  110. {
  111. h & baseValue;
  112. h & baseLanguage;
  113. h & modContext;
  114. }
  115. };
  116. /// map identifier -> localization
  117. std::unordered_map<std::string, StringState> stringsLocalizations;
  118. std::vector<const TextLocalizationContainer *> subContainers;
  119. /// add selected string to internal storage as high-priority strings
  120. void registerStringOverride(const std::string & modContext, const std::string & language, const TextIdentifier & UID, const std::string & localized);
  121. std::string getModLanguage(const std::string & modContext);
  122. // returns true if identifier with such name was registered, even if not translated to current language
  123. bool identifierExists(const TextIdentifier & UID) const;
  124. public:
  125. /// validates translation of specified language for specified mod
  126. /// returns true if localization is valid and complete
  127. /// any error messages will be written to log file
  128. bool validateTranslation(const std::string & language, const std::string & modContext, JsonNode const & file) const;
  129. /// Loads translation from provided json
  130. /// Any entries loaded by this will have priority over texts registered normally
  131. void loadTranslationOverrides(const std::string & language, const std::string & modContext, JsonNode const & file);
  132. /// add selected string to internal storage
  133. void registerString(const std::string & modContext, const TextIdentifier & UID, const std::string & localized);
  134. void registerString(const std::string & modContext, const TextIdentifier & UID, const std::string & localized, const std::string & language);
  135. /// returns translated version of a string that can be displayed to user
  136. template<typename ... Args>
  137. std::string translate(std::string arg1, Args ... args) const
  138. {
  139. TextIdentifier id(arg1, args ...);
  140. return deserialize(id);
  141. }
  142. /// converts identifier into user-readable string
  143. const std::string & deserialize(const TextIdentifier & identifier) const;
  144. /// Debug method, returns all currently stored texts
  145. /// Format: [mod ID][string ID] -> human-readable text
  146. void exportAllTexts(std::map<std::string, std::map<std::string, std::string>> & storage) const;
  147. /// Add or override subcontainer which can store identifiers
  148. void addSubContainer(const TextLocalizationContainer & container);
  149. /// Remove subcontainer with give name
  150. void removeSubContainer(const TextLocalizationContainer & container);
  151. void jsonSerialize(JsonNode & dest) const;
  152. template <typename Handler>
  153. void serialize(Handler & h)
  154. {
  155. std::lock_guard<std::recursive_mutex> globalLock(globalTextMutex);
  156. std::string key;
  157. auto sz = stringsLocalizations.size();
  158. h & sz;
  159. if(h.saving)
  160. {
  161. for(auto s : stringsLocalizations)
  162. {
  163. key = s.first;
  164. h & key;
  165. h & s.second;
  166. }
  167. }
  168. else
  169. {
  170. for(size_t i = 0; i < sz; ++i)
  171. {
  172. h & key;
  173. h & stringsLocalizations[key];
  174. }
  175. }
  176. }
  177. };
  178. class DLL_LINKAGE TextContainerRegistrable : public TextLocalizationContainer
  179. {
  180. public:
  181. TextContainerRegistrable();
  182. ~TextContainerRegistrable();
  183. TextContainerRegistrable(const TextContainerRegistrable & other);
  184. TextContainerRegistrable(TextContainerRegistrable && other) noexcept;
  185. TextContainerRegistrable& operator=(const TextContainerRegistrable & b) = default;
  186. };
  187. /// Handles all text-related data in game
  188. class DLL_LINKAGE CGeneralTextHandler: public TextLocalizationContainer
  189. {
  190. void readToVector(const std::string & sourceID, const std::string & sourceName);
  191. /// number of scenarios in specific campaign. TODO: move to a better location
  192. std::vector<size_t> scenariosCountPerCampaign;
  193. public:
  194. LegacyTextContainer allTexts;
  195. LegacyTextContainer arraytxt;
  196. LegacyTextContainer primarySkillNames;
  197. LegacyTextContainer jktexts;
  198. LegacyTextContainer heroscrn;
  199. LegacyTextContainer overview;//text for Kingdom Overview window
  200. LegacyTextContainer colors; //names of player colors ("red",...)
  201. LegacyTextContainer capColors; //names of player colors with first letter capitalized ("Red",...)
  202. LegacyTextContainer turnDurations; //turn durations for pregame (1 Minute ... Unlimited)
  203. //towns
  204. LegacyTextContainer tcommands, hcommands, fcommands; //texts for town screen, town hall screen and fort screen
  205. LegacyTextContainer tavernInfo;
  206. LegacyTextContainer tavernRumors;
  207. LegacyTextContainer qeModCommands;
  208. LegacyHelpContainer zelp;
  209. LegacyTextContainer lossCondtions;
  210. LegacyTextContainer victoryConditions;
  211. //objects
  212. LegacyTextContainer advobtxt;
  213. LegacyTextContainer restypes; //names of resources
  214. LegacyTextContainer randsign;
  215. LegacyTextContainer seerEmpty;
  216. LegacyTextContainer seerNames;
  217. LegacyTextContainer tentColors;
  218. //sec skills
  219. LegacyTextContainer levels;
  220. //commanders
  221. LegacyTextContainer znpc00; //more or less useful content of that file
  222. std::vector<std::string> findStringsWithPrefix(const std::string & prefix);
  223. int32_t pluralText(int32_t textIndex, int32_t count) const;
  224. size_t getCampaignLength(size_t campaignID) const;
  225. CGeneralTextHandler();
  226. CGeneralTextHandler(const CGeneralTextHandler&) = delete;
  227. CGeneralTextHandler operator=(const CGeneralTextHandler&) = delete;
  228. /// Attempts to detect encoding & language of H3 files
  229. static void detectInstallParameters();
  230. /// Returns name of language preferred by user
  231. static std::string getPreferredLanguage();
  232. /// Returns name of language of Heroes III text files
  233. static std::string getInstalledLanguage();
  234. /// Returns name of encoding of Heroes III text files
  235. static std::string getInstalledEncoding();
  236. };
  237. VCMI_LIB_NAMESPACE_END