translation_loader_po.cpp 14 KB

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