translation_loader_po.cpp 14 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_po.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<TranslationPO> translation = Ref<TranslationPO>(memnew(TranslationPO));
  39. String config;
  40. uint32_t magic = f->get_32();
  41. if (magic == 0x950412de) {
  42. // Load binary MO file.
  43. uint16_t version_maj = f->get_16();
  44. uint16_t version_min = f->get_16();
  45. ERR_FAIL_COND_V_MSG(version_maj > 1, Ref<Resource>(), vformat("Unsupported MO file %s, version %d.%d.", path, version_maj, version_min));
  46. uint32_t num_strings = f->get_32();
  47. uint32_t id_table_offset = f->get_32();
  48. uint32_t trans_table_offset = f->get_32();
  49. // Read string tables.
  50. for (uint32_t i = 0; i < num_strings; i++) {
  51. String msg_id;
  52. String msg_id_plural;
  53. String msg_context;
  54. // Read id strings and context.
  55. {
  56. Vector<uint8_t> data;
  57. f->seek(id_table_offset + i * 8);
  58. uint32_t str_start = 0;
  59. uint32_t str_len = f->get_32();
  60. uint32_t str_offset = f->get_32();
  61. data.resize(str_len + 1);
  62. f->seek(str_offset);
  63. f->get_buffer(data.ptrw(), str_len);
  64. data.write[str_len] = 0;
  65. bool is_plural = false;
  66. for (uint32_t j = 0; j < str_len + 1; j++) {
  67. if (data[j] == 0x04) {
  68. msg_context.clear();
  69. msg_context.append_utf8((const char *)data.ptr(), j);
  70. str_start = j + 1;
  71. }
  72. if (data[j] == 0x00) {
  73. if (is_plural) {
  74. msg_id_plural.clear();
  75. msg_id_plural.append_utf8((const char *)(data.ptr() + str_start), j - str_start);
  76. } else {
  77. msg_id.clear();
  78. msg_id.append_utf8((const char *)(data.ptr() + str_start), j - str_start);
  79. is_plural = true;
  80. }
  81. str_start = j + 1;
  82. }
  83. }
  84. }
  85. // Read translated strings.
  86. {
  87. Vector<uint8_t> data;
  88. f->seek(trans_table_offset + i * 8);
  89. uint32_t str_len = f->get_32();
  90. uint32_t str_offset = f->get_32();
  91. data.resize(str_len + 1);
  92. f->seek(str_offset);
  93. f->get_buffer(data.ptrw(), str_len);
  94. data.write[str_len] = 0;
  95. if (msg_id.is_empty()) {
  96. config = String::utf8((const char *)data.ptr(), str_len);
  97. // Record plural rule.
  98. int p_start = config.find("Plural-Forms");
  99. if (p_start != -1) {
  100. int p_end = config.find_char('\n', p_start);
  101. translation->set_plural_rule(config.substr(p_start, p_end - p_start));
  102. }
  103. } else {
  104. uint32_t str_start = 0;
  105. Vector<String> plural_msg;
  106. for (uint32_t j = 0; j < str_len + 1; j++) {
  107. if (data[j] == 0x00) {
  108. if (msg_id_plural.is_empty()) {
  109. translation->add_message(msg_id, String::utf8((const char *)(data.ptr() + str_start), j - str_start), msg_context);
  110. } else {
  111. plural_msg.push_back(String::utf8((const char *)(data.ptr() + str_start), j - str_start));
  112. }
  113. str_start = j + 1;
  114. }
  115. }
  116. if (!plural_msg.is_empty()) {
  117. translation->add_plural_message(msg_id, plural_msg, msg_context);
  118. }
  119. }
  120. }
  121. }
  122. } else {
  123. // Try to load as text PO file.
  124. f->seek(0);
  125. enum Status {
  126. STATUS_NONE,
  127. STATUS_READING_ID,
  128. STATUS_READING_STRING,
  129. STATUS_READING_CONTEXT,
  130. STATUS_READING_PLURAL,
  131. };
  132. Status status = STATUS_NONE;
  133. String msg_id;
  134. String msg_str;
  135. String msg_context;
  136. Vector<String> msgs_plural;
  137. if (r_error) {
  138. *r_error = ERR_FILE_CORRUPT;
  139. }
  140. int line = 1;
  141. int plural_forms = 0;
  142. int plural_index = -1;
  143. bool entered_context = false;
  144. bool skip_this = false;
  145. bool skip_next = false;
  146. bool is_eof = false;
  147. while (!is_eof) {
  148. String l = f->get_line().strip_edges();
  149. is_eof = f->eof_reached();
  150. // If we reached last line and it's not a content line, break, otherwise let processing that last loop
  151. if (is_eof && l.is_empty()) {
  152. if (status == STATUS_READING_ID || status == STATUS_READING_CONTEXT || (status == STATUS_READING_PLURAL && plural_index != plural_forms - 1)) {
  153. ERR_FAIL_V_MSG(Ref<Resource>(), vformat("Unexpected EOF while reading PO file at: %s:%d.", path, line));
  154. } else {
  155. break;
  156. }
  157. }
  158. if (l.begins_with("msgctxt")) {
  159. 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));
  160. // In PO file, "msgctxt" appears before "msgid". If we encounter a "msgctxt", we add what we have read
  161. // and set "entered_context" to true to prevent adding twice.
  162. if (!skip_this && !msg_id.is_empty()) {
  163. if (status == STATUS_READING_STRING) {
  164. translation->add_message(msg_id, msg_str, msg_context);
  165. } else if (status == STATUS_READING_PLURAL) {
  166. 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));
  167. translation->add_plural_message(msg_id, msgs_plural, msg_context);
  168. }
  169. }
  170. msg_context = "";
  171. l = l.substr(7).strip_edges();
  172. status = STATUS_READING_CONTEXT;
  173. entered_context = true;
  174. }
  175. if (l.begins_with("msgid_plural")) {
  176. if (plural_forms == 0) {
  177. 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));
  178. } else if (status != STATUS_READING_ID) {
  179. ERR_FAIL_V_MSG(Ref<Resource>(), vformat("Unexpected 'msgid_plural', was expecting 'msgid' before 'msgid_plural' while parsing: %s:%d.", path, line));
  180. }
  181. // We don't record the message in "msgid_plural" itself as tr_n(), TTRN(), RTRN() interfaces provide the plural string already.
  182. // We just have to reset variables related to plurals for "msgstr[]" later on.
  183. l = l.substr(12).strip_edges();
  184. plural_index = -1;
  185. msgs_plural.clear();
  186. msgs_plural.resize(plural_forms);
  187. status = STATUS_READING_PLURAL;
  188. } else if (l.begins_with("msgid")) {
  189. ERR_FAIL_COND_V_MSG(status == STATUS_READING_ID, Ref<Resource>(), vformat("Unexpected 'msgid', was expecting 'msgstr' while parsing: %s:%d.", path, line));
  190. if (!msg_id.is_empty()) {
  191. if (!skip_this && !entered_context) {
  192. if (status == STATUS_READING_STRING) {
  193. translation->add_message(msg_id, msg_str, msg_context);
  194. } else if (status == STATUS_READING_PLURAL) {
  195. 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));
  196. translation->add_plural_message(msg_id, msgs_plural, msg_context);
  197. }
  198. }
  199. } else if (config.is_empty()) {
  200. config = msg_str;
  201. // Record plural rule.
  202. int p_start = config.find("Plural-Forms");
  203. if (p_start != -1) {
  204. int p_end = config.find_char('\n', p_start);
  205. translation->set_plural_rule(config.substr(p_start, p_end - p_start));
  206. plural_forms = translation->get_plural_forms();
  207. }
  208. }
  209. l = l.substr(5).strip_edges();
  210. status = STATUS_READING_ID;
  211. // If we did not encounter msgctxt, we reset context to empty to reset it.
  212. if (!entered_context) {
  213. msg_context = "";
  214. }
  215. msg_id = "";
  216. msg_str = "";
  217. skip_this = skip_next;
  218. skip_next = false;
  219. entered_context = false;
  220. }
  221. if (l.begins_with("msgstr[")) {
  222. 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));
  223. plural_index++; // Increment to add to the next slot in vector msgs_plural.
  224. l = l.substr(9).strip_edges();
  225. } else if (l.begins_with("msgstr")) {
  226. 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));
  227. l = l.substr(6).strip_edges();
  228. status = STATUS_READING_STRING;
  229. }
  230. if (l.is_empty() || l.begins_with("#")) {
  231. if (l.contains("fuzzy")) {
  232. skip_next = true;
  233. }
  234. line++;
  235. continue; // Nothing to read or comment.
  236. }
  237. ERR_FAIL_COND_V_MSG(!l.begins_with("\"") || status == STATUS_NONE, Ref<Resource>(), vformat("Invalid line '%s' while parsing: %s:%d.", l, path, line));
  238. l = l.substr(1);
  239. // Find final quote, ignoring escaped ones (\").
  240. // The escape_next logic is necessary to properly parse things like \\"
  241. // where the backslash is the one being escaped, not the quote.
  242. int end_pos = -1;
  243. bool escape_next = false;
  244. for (int i = 0; i < l.length(); i++) {
  245. if (l[i] == '\\' && !escape_next) {
  246. escape_next = true;
  247. continue;
  248. }
  249. if (l[i] == '"' && !escape_next) {
  250. end_pos = i;
  251. break;
  252. }
  253. escape_next = false;
  254. }
  255. ERR_FAIL_COND_V_MSG(end_pos == -1, Ref<Resource>(), vformat("Expected '\"' at end of message while parsing: %s:%d.", path, line));
  256. l = l.substr(0, end_pos);
  257. l = l.c_unescape();
  258. if (status == STATUS_READING_ID) {
  259. msg_id += l;
  260. } else if (status == STATUS_READING_STRING) {
  261. msg_str += l;
  262. } else if (status == STATUS_READING_CONTEXT) {
  263. msg_context += l;
  264. } else if (status == STATUS_READING_PLURAL && plural_index >= 0) {
  265. ERR_FAIL_COND_V_MSG(plural_index >= plural_forms, Ref<Resource>(), vformat("Unexpected plural form while parsing: %s:%d.", path, line));
  266. msgs_plural.write[plural_index] = msgs_plural[plural_index] + l;
  267. }
  268. line++;
  269. }
  270. // Add the last set of data from last iteration.
  271. if (status == STATUS_READING_STRING) {
  272. if (!msg_id.is_empty()) {
  273. if (!skip_this) {
  274. translation->add_message(msg_id, msg_str, msg_context);
  275. }
  276. } else if (config.is_empty()) {
  277. config = msg_str;
  278. }
  279. } else if (status == STATUS_READING_PLURAL) {
  280. if (!skip_this && !msg_id.is_empty()) {
  281. 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));
  282. translation->add_plural_message(msg_id, msgs_plural, msg_context);
  283. }
  284. }
  285. }
  286. ERR_FAIL_COND_V_MSG(config.is_empty(), Ref<Resource>(), vformat("No config found in file: '%s'.", path));
  287. Vector<String> configs = config.split("\n");
  288. for (int i = 0; i < configs.size(); i++) {
  289. String c = configs[i].strip_edges();
  290. int p = c.find_char(':');
  291. if (p == -1) {
  292. continue;
  293. }
  294. String prop = c.substr(0, p).strip_edges();
  295. String value = c.substr(p + 1).strip_edges();
  296. if (prop == "X-Language" || prop == "Language") {
  297. translation->set_locale(value);
  298. }
  299. }
  300. if (r_error) {
  301. *r_error = OK;
  302. }
  303. return translation;
  304. }
  305. 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) {
  306. if (r_error) {
  307. *r_error = ERR_CANT_OPEN;
  308. }
  309. Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ);
  310. ERR_FAIL_COND_V_MSG(f.is_null(), Ref<Resource>(), vformat("Cannot open file '%s'.", p_path));
  311. return load_translation(f, r_error);
  312. }
  313. void TranslationLoaderPO::get_recognized_extensions(List<String> *p_extensions) const {
  314. p_extensions->push_back("po");
  315. p_extensions->push_back("mo");
  316. }
  317. bool TranslationLoaderPO::handles_type(const String &p_type) const {
  318. return (p_type == "Translation") || (p_type == "TranslationPO");
  319. }
  320. String TranslationLoaderPO::get_resource_type(const String &p_path) const {
  321. if (p_path.get_extension().to_lower() == "po" || p_path.get_extension().to_lower() == "mo") {
  322. return "Translation";
  323. }
  324. return "";
  325. }