translation_loader_po.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. /**************************************************************************/
  2. /* translation_loader_po.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #include "translation_loader_po.h"
  31. #include "core/io/file_access.h"
  32. #include "core/string/translation.h"
  33. Ref<Resource> TranslationLoaderPO::load_translation(Ref<FileAccess> f, Error *r_error) {
  34. if (r_error) {
  35. *r_error = ERR_FILE_CORRUPT;
  36. }
  37. const String path = f->get_path();
  38. Ref<Translation> translation;
  39. translation.instantiate();
  40. String config;
  41. uint32_t magic = f->get_32();
  42. if (magic == 0x950412de) {
  43. // Load binary MO file.
  44. uint16_t version_maj = f->get_16();
  45. uint16_t version_min = f->get_16();
  46. ERR_FAIL_COND_V_MSG(version_maj > 1, Ref<Resource>(), vformat("Unsupported MO file %s, version %d.%d.", path, version_maj, version_min));
  47. uint32_t num_strings = f->get_32();
  48. uint32_t id_table_offset = f->get_32();
  49. uint32_t trans_table_offset = f->get_32();
  50. // Read string tables.
  51. for (uint32_t i = 0; i < num_strings; i++) {
  52. String msg_id;
  53. String msg_id_plural;
  54. String msg_context;
  55. // Read id strings and context.
  56. {
  57. Vector<uint8_t> data;
  58. f->seek(id_table_offset + i * 8);
  59. uint32_t str_start = 0;
  60. uint32_t str_len = f->get_32();
  61. uint32_t str_offset = f->get_32();
  62. data.resize(str_len + 1);
  63. f->seek(str_offset);
  64. f->get_buffer(data.ptrw(), str_len);
  65. data.write[str_len] = 0;
  66. bool is_plural = false;
  67. for (uint32_t j = 0; j < str_len + 1; j++) {
  68. if (data[j] == 0x04) {
  69. msg_context.clear();
  70. msg_context.append_utf8((const char *)data.ptr(), j);
  71. str_start = j + 1;
  72. }
  73. if (data[j] == 0x00) {
  74. if (is_plural) {
  75. msg_id_plural.clear();
  76. msg_id_plural.append_utf8((const char *)(data.ptr() + str_start), j - str_start);
  77. } else {
  78. msg_id.clear();
  79. msg_id.append_utf8((const char *)(data.ptr() + str_start), j - str_start);
  80. is_plural = true;
  81. }
  82. str_start = j + 1;
  83. }
  84. }
  85. }
  86. // Read translated strings.
  87. {
  88. Vector<uint8_t> data;
  89. f->seek(trans_table_offset + i * 8);
  90. uint32_t str_len = f->get_32();
  91. uint32_t str_offset = f->get_32();
  92. data.resize(str_len + 1);
  93. f->seek(str_offset);
  94. f->get_buffer(data.ptrw(), str_len);
  95. data.write[str_len] = 0;
  96. if (msg_id.is_empty()) {
  97. config = String::utf8((const char *)data.ptr(), str_len);
  98. // Record plural rule.
  99. int p_start = config.find("Plural-Forms");
  100. if (p_start != -1) {
  101. int p_end = config.find_char('\n', p_start);
  102. translation->set_plural_rules_override(config.substr(p_start, p_end - p_start));
  103. }
  104. } else {
  105. uint32_t str_start = 0;
  106. Vector<String> plural_msg;
  107. for (uint32_t j = 0; j < str_len + 1; j++) {
  108. if (data[j] == 0x00) {
  109. if (msg_id_plural.is_empty()) {
  110. translation->add_message(msg_id, String::utf8((const char *)(data.ptr() + str_start), j - str_start), msg_context);
  111. } else {
  112. plural_msg.push_back(String::utf8((const char *)(data.ptr() + str_start), j - str_start));
  113. }
  114. str_start = j + 1;
  115. }
  116. }
  117. if (!plural_msg.is_empty()) {
  118. translation->add_plural_message(msg_id, plural_msg, msg_context);
  119. }
  120. }
  121. }
  122. }
  123. } else {
  124. // Try to load as text PO file.
  125. f->seek(0);
  126. enum Status {
  127. STATUS_NONE,
  128. STATUS_READING_ID,
  129. STATUS_READING_STRING,
  130. STATUS_READING_CONTEXT,
  131. STATUS_READING_PLURAL,
  132. };
  133. Status status = STATUS_NONE;
  134. String msg_id;
  135. String msg_str;
  136. String msg_context;
  137. Vector<String> msgs_plural;
  138. if (r_error) {
  139. *r_error = ERR_FILE_CORRUPT;
  140. }
  141. int line = 1;
  142. int plural_forms = 0;
  143. int plural_index = -1;
  144. bool entered_context = false;
  145. bool skip_this = false;
  146. bool skip_next = false;
  147. bool is_eof = false;
  148. while (!is_eof) {
  149. String l = f->get_line().strip_edges();
  150. is_eof = f->eof_reached();
  151. // If we reached last line and it's not a content line, break, otherwise let processing that last loop
  152. if (is_eof && l.is_empty()) {
  153. if (status == STATUS_READING_ID || status == STATUS_READING_CONTEXT || (status == STATUS_READING_PLURAL && plural_index != plural_forms - 1)) {
  154. ERR_FAIL_V_MSG(Ref<Resource>(), vformat("Unexpected EOF while reading PO file at: %s:%d.", path, line));
  155. } else {
  156. break;
  157. }
  158. }
  159. if (l.begins_with("msgctxt")) {
  160. ERR_FAIL_COND_V_MSG(status != STATUS_READING_STRING && status != STATUS_READING_PLURAL, Ref<Resource>(), vformat("Unexpected 'msgctxt', was expecting 'msgid_plural' or 'msgstr' before 'msgctxt' while parsing: %s:%d.", path, line));
  161. // In PO file, "msgctxt" appears before "msgid". If we encounter a "msgctxt", we add what we have read
  162. // and set "entered_context" to true to prevent adding twice.
  163. if (!skip_this && !msg_id.is_empty()) {
  164. if (status == STATUS_READING_STRING) {
  165. translation->add_message(msg_id, msg_str, msg_context);
  166. } else if (status == STATUS_READING_PLURAL) {
  167. ERR_FAIL_COND_V_MSG(plural_index != plural_forms - 1, Ref<Resource>(), vformat("Number of 'msgstr[]' doesn't match with number of plural forms: %s:%d.", path, line));
  168. translation->add_plural_message(msg_id, msgs_plural, msg_context);
  169. }
  170. }
  171. msg_context = "";
  172. l = l.substr(7).strip_edges();
  173. status = STATUS_READING_CONTEXT;
  174. entered_context = true;
  175. }
  176. if (l.begins_with("msgid_plural")) {
  177. if (plural_forms == 0) {
  178. ERR_FAIL_V_MSG(Ref<Resource>(), vformat("PO file uses 'msgid_plural' but 'Plural-Forms' is invalid or missing in header: %s:%d.", path, line));
  179. } else if (status != STATUS_READING_ID) {
  180. ERR_FAIL_V_MSG(Ref<Resource>(), vformat("Unexpected 'msgid_plural', was expecting 'msgid' before 'msgid_plural' while parsing: %s:%d.", path, line));
  181. }
  182. // We don't record the message in "msgid_plural" itself as tr_n(), TTRN(), RTRN() interfaces provide the plural string already.
  183. // We just have to reset variables related to plurals for "msgstr[]" later on.
  184. l = l.substr(12).strip_edges();
  185. plural_index = -1;
  186. msgs_plural.clear();
  187. msgs_plural.resize(plural_forms);
  188. status = STATUS_READING_PLURAL;
  189. } else if (l.begins_with("msgid")) {
  190. ERR_FAIL_COND_V_MSG(status == STATUS_READING_ID, Ref<Resource>(), vformat("Unexpected 'msgid', was expecting 'msgstr' while parsing: %s:%d.", path, line));
  191. if (!msg_id.is_empty()) {
  192. if (!skip_this && !entered_context) {
  193. if (status == STATUS_READING_STRING) {
  194. translation->add_message(msg_id, msg_str, msg_context);
  195. } else if (status == STATUS_READING_PLURAL) {
  196. ERR_FAIL_COND_V_MSG(plural_index != plural_forms - 1, Ref<Resource>(), vformat("Number of 'msgstr[]' doesn't match with number of plural forms: %s:%d.", path, line));
  197. translation->add_plural_message(msg_id, msgs_plural, msg_context);
  198. }
  199. }
  200. } else if (config.is_empty()) {
  201. config = msg_str;
  202. // Record plural rule.
  203. int p_start = config.find("Plural-Forms");
  204. if (p_start != -1) {
  205. int p_end = config.find_char('\n', p_start);
  206. translation->set_plural_rules_override(config.substr(p_start, p_end - p_start));
  207. plural_forms = translation->get_nplurals();
  208. }
  209. }
  210. l = l.substr(5).strip_edges();
  211. status = STATUS_READING_ID;
  212. // If we did not encounter msgctxt, we reset context to empty to reset it.
  213. if (!entered_context) {
  214. msg_context = "";
  215. }
  216. msg_id = "";
  217. msg_str = "";
  218. skip_this = skip_next;
  219. skip_next = false;
  220. entered_context = false;
  221. }
  222. if (l.begins_with("msgstr[")) {
  223. ERR_FAIL_COND_V_MSG(status != STATUS_READING_PLURAL, Ref<Resource>(), vformat("Unexpected 'msgstr[]', was expecting 'msgid_plural' before 'msgstr[]' while parsing: %s:%d.", path, line));
  224. plural_index++; // Increment to add to the next slot in vector msgs_plural.
  225. l = l.substr(9).strip_edges();
  226. } else if (l.begins_with("msgstr")) {
  227. ERR_FAIL_COND_V_MSG(status != STATUS_READING_ID, Ref<Resource>(), vformat("Unexpected 'msgstr', was expecting 'msgid' before 'msgstr' while parsing: %s:%d.", path, line));
  228. l = l.substr(6).strip_edges();
  229. status = STATUS_READING_STRING;
  230. }
  231. if (l.is_empty() || l.begins_with("#")) {
  232. if (l.contains("fuzzy")) {
  233. skip_next = true;
  234. }
  235. line++;
  236. continue; // Nothing to read or comment.
  237. }
  238. ERR_FAIL_COND_V_MSG(!l.begins_with("\"") || status == STATUS_NONE, Ref<Resource>(), vformat("Invalid line '%s' while parsing: %s:%d.", l, path, line));
  239. l = l.substr(1);
  240. // Find final quote, ignoring escaped ones (\").
  241. // The escape_next logic is necessary to properly parse things like \\"
  242. // where the backslash is the one being escaped, not the quote.
  243. int end_pos = -1;
  244. bool escape_next = false;
  245. for (int i = 0; i < l.length(); i++) {
  246. if (l[i] == '\\' && !escape_next) {
  247. escape_next = true;
  248. continue;
  249. }
  250. if (l[i] == '"' && !escape_next) {
  251. end_pos = i;
  252. break;
  253. }
  254. escape_next = false;
  255. }
  256. ERR_FAIL_COND_V_MSG(end_pos == -1, Ref<Resource>(), vformat("Expected '\"' at end of message while parsing: %s:%d.", path, line));
  257. l = l.substr(0, end_pos);
  258. l = l.c_unescape();
  259. if (status == STATUS_READING_ID) {
  260. msg_id += l;
  261. } else if (status == STATUS_READING_STRING) {
  262. msg_str += l;
  263. } else if (status == STATUS_READING_CONTEXT) {
  264. msg_context += l;
  265. } else if (status == STATUS_READING_PLURAL && plural_index >= 0) {
  266. ERR_FAIL_COND_V_MSG(plural_index >= plural_forms, Ref<Resource>(), vformat("Unexpected plural form while parsing: %s:%d.", path, line));
  267. msgs_plural.write[plural_index] = msgs_plural[plural_index] + l;
  268. }
  269. line++;
  270. }
  271. // Add the last set of data from last iteration.
  272. if (status == STATUS_READING_STRING) {
  273. if (!msg_id.is_empty()) {
  274. if (!skip_this) {
  275. translation->add_message(msg_id, msg_str, msg_context);
  276. }
  277. } else if (config.is_empty()) {
  278. config = msg_str;
  279. }
  280. } else if (status == STATUS_READING_PLURAL) {
  281. if (!skip_this && !msg_id.is_empty()) {
  282. ERR_FAIL_COND_V_MSG(plural_index != plural_forms - 1, Ref<Resource>(), vformat("Number of 'msgstr[]' doesn't match with number of plural forms: %s:%d.", path, line));
  283. translation->add_plural_message(msg_id, msgs_plural, msg_context);
  284. }
  285. }
  286. }
  287. ERR_FAIL_COND_V_MSG(config.is_empty(), Ref<Resource>(), vformat("No config found in file: '%s'.", path));
  288. Vector<String> configs = config.split("\n");
  289. for (int i = 0; i < configs.size(); i++) {
  290. String c = configs[i].strip_edges();
  291. int p = c.find_char(':');
  292. if (p == -1) {
  293. continue;
  294. }
  295. String prop = c.substr(0, p).strip_edges();
  296. String value = c.substr(p + 1).strip_edges();
  297. if (prop == "X-Language" || prop == "Language") {
  298. translation->set_locale(value);
  299. }
  300. }
  301. if (r_error) {
  302. *r_error = OK;
  303. }
  304. return translation;
  305. }
  306. Ref<Resource> TranslationLoaderPO::load(const String &p_path, const String &p_original_path, Error *r_error, bool p_use_sub_threads, float *r_progress, CacheMode p_cache_mode) {
  307. if (r_error) {
  308. *r_error = ERR_CANT_OPEN;
  309. }
  310. Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ);
  311. ERR_FAIL_COND_V_MSG(f.is_null(), Ref<Resource>(), vformat("Cannot open file '%s'.", p_path));
  312. return load_translation(f, r_error);
  313. }
  314. void TranslationLoaderPO::get_recognized_extensions(List<String> *p_extensions) const {
  315. p_extensions->push_back("po");
  316. p_extensions->push_back("mo");
  317. }
  318. bool TranslationLoaderPO::handles_type(const String &p_type) const {
  319. return p_type == "Translation";
  320. }
  321. String TranslationLoaderPO::get_resource_type(const String &p_path) const {
  322. if (p_path.has_extension("po") || p_path.has_extension("mo")) {
  323. return "Translation";
  324. }
  325. return "";
  326. }