translation_po.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  1. /**************************************************************************/
  2. /* translation_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_po.h"
  31. #ifdef DEBUG_TRANSLATION_PO
  32. #include "core/io/file_access.h"
  33. void TranslationPO::print_translation_map() {
  34. Error err;
  35. Ref<FileAccess> file = FileAccess::open("translation_map_print_test.txt", FileAccess::WRITE, &err);
  36. if (err != OK) {
  37. ERR_PRINT("Failed to open translation_map_print_test.txt");
  38. return;
  39. }
  40. file->store_line("NPlural : " + String::num_int64(get_plural_forms()));
  41. file->store_line("Plural rule : " + get_plural_rule());
  42. file->store_line("");
  43. List<StringName> context_l;
  44. translation_map.get_key_list(&context_l);
  45. for (const StringName &ctx : context_l) {
  46. file->store_line(" ===== Context: " + String::utf8(String(ctx).utf8()) + " ===== ");
  47. const HashMap<StringName, Vector<StringName>> &inner_map = translation_map[ctx];
  48. List<StringName> id_l;
  49. inner_map.get_key_list(&id_l);
  50. for (const StringName &id : id_l) {
  51. file->store_line("msgid: " + String::utf8(String(id).utf8()));
  52. for (int i = 0; i < inner_map[id].size(); i++) {
  53. file->store_line("msgstr[" + String::num_int64(i) + "]: " + String::utf8(String(inner_map[id][i]).utf8()));
  54. }
  55. file->store_line("");
  56. }
  57. }
  58. }
  59. #endif
  60. Dictionary TranslationPO::_get_messages() const {
  61. // Return translation_map as a Dictionary.
  62. Dictionary d;
  63. for (const KeyValue<StringName, HashMap<StringName, Vector<StringName>>> &E : translation_map) {
  64. Dictionary d2;
  65. for (const KeyValue<StringName, Vector<StringName>> &E2 : E.value) {
  66. d2[E2.key] = E2.value;
  67. }
  68. d[E.key] = d2;
  69. }
  70. return d;
  71. }
  72. void TranslationPO::_set_messages(const Dictionary &p_messages) {
  73. // Construct translation_map from a Dictionary.
  74. for (const KeyValue<Variant, Variant> &kv : p_messages) {
  75. const Dictionary &id_str_map = kv.value;
  76. HashMap<StringName, Vector<StringName>> temp_map;
  77. for (const KeyValue<Variant, Variant> &kv_id : id_str_map) {
  78. StringName id = kv_id.key;
  79. temp_map[id] = kv_id.value;
  80. }
  81. translation_map[kv.key] = temp_map;
  82. }
  83. }
  84. Vector<String> TranslationPO::get_translated_message_list() const {
  85. Vector<String> msgs;
  86. for (const KeyValue<StringName, HashMap<StringName, Vector<StringName>>> &E : translation_map) {
  87. if (E.key != StringName()) {
  88. continue;
  89. }
  90. for (const KeyValue<StringName, Vector<StringName>> &E2 : E.value) {
  91. for (const StringName &E3 : E2.value) {
  92. msgs.push_back(E3);
  93. }
  94. }
  95. }
  96. return msgs;
  97. }
  98. Vector<String> TranslationPO::_get_message_list() const {
  99. // Return all keys in translation_map.
  100. List<StringName> msgs;
  101. get_message_list(&msgs);
  102. Vector<String> v;
  103. for (const StringName &E : msgs) {
  104. v.push_back(E);
  105. }
  106. return v;
  107. }
  108. int TranslationPO::_get_plural_index(int p_n) const {
  109. // Get a number between [0;number of plural forms).
  110. input_val.clear();
  111. input_val.push_back(p_n);
  112. return _eq_test(equi_tests, 0);
  113. }
  114. int TranslationPO::_eq_test(const Ref<EQNode> &p_node, const Variant &p_result) const {
  115. if (p_node.is_valid()) {
  116. Error err = expr->parse(p_node->regex, input_name);
  117. ERR_FAIL_COND_V_MSG(err != OK, 0, vformat("Cannot parse expression \"%s\". Error: %s", p_node->regex, expr->get_error_text()));
  118. Variant result = expr->execute(input_val);
  119. ERR_FAIL_COND_V_MSG(expr->has_execute_failed(), 0, vformat("Cannot evaluate expression \"%s\".", p_node->regex));
  120. if (bool(result)) {
  121. return _eq_test(p_node->left, result);
  122. } else {
  123. return _eq_test(p_node->right, result);
  124. }
  125. } else {
  126. return p_result;
  127. }
  128. }
  129. int TranslationPO::_find_unquoted(const String &p_src, char32_t p_chr) const {
  130. const int len = p_src.length();
  131. if (len == 0) {
  132. return -1;
  133. }
  134. const char32_t *src = p_src.get_data();
  135. bool in_quote = false;
  136. for (int i = 0; i < len; i++) {
  137. if (in_quote) {
  138. if (src[i] == ')') {
  139. in_quote = false;
  140. }
  141. } else {
  142. if (src[i] == '(') {
  143. in_quote = true;
  144. } else if (src[i] == p_chr) {
  145. return i;
  146. }
  147. }
  148. }
  149. return -1;
  150. }
  151. void TranslationPO::_cache_plural_tests(const String &p_plural_rule, Ref<EQNode> &p_node) {
  152. // Some examples of p_plural_rule passed in can have the form:
  153. // "n==0 ? 0 : n==1 ? 1 : n==2 ? 2 : n%100>=3 && n%100<=10 ? 3 : n%100>=11 && n%100<=99 ? 4 : 5" (Arabic)
  154. // "n >= 2" (French) // When evaluating the last, especially careful with this one.
  155. // "n != 1" (English)
  156. String rule = p_plural_rule;
  157. if (rule.begins_with("(") && rule.ends_with(")")) {
  158. int bcount = 0;
  159. for (int i = 1; i < rule.length() - 1 && bcount >= 0; i++) {
  160. if (rule[i] == '(') {
  161. bcount++;
  162. } else if (rule[i] == ')') {
  163. bcount--;
  164. }
  165. }
  166. if (bcount == 0) {
  167. rule = rule.substr(1, rule.length() - 2);
  168. }
  169. }
  170. int first_ques_mark = _find_unquoted(rule, '?');
  171. int first_colon = _find_unquoted(rule, ':');
  172. if (first_ques_mark == -1) {
  173. p_node->regex = rule.strip_edges();
  174. return;
  175. }
  176. p_node->regex = rule.substr(0, first_ques_mark).strip_edges();
  177. p_node->left.instantiate();
  178. _cache_plural_tests(rule.substr(first_ques_mark + 1, first_colon - first_ques_mark - 1).strip_edges(), p_node->left);
  179. p_node->right.instantiate();
  180. _cache_plural_tests(rule.substr(first_colon + 1).strip_edges(), p_node->right);
  181. }
  182. void TranslationPO::set_plural_rule(const String &p_plural_rule) {
  183. // Set plural_forms and plural_rule.
  184. // p_plural_rule passed in has the form "Plural-Forms: nplurals=2; plural=(n >= 2);".
  185. int first_semi_col = p_plural_rule.find_char(';');
  186. plural_forms = p_plural_rule.substr(p_plural_rule.find_char('=') + 1, first_semi_col - (p_plural_rule.find_char('=') + 1)).to_int();
  187. int expression_start = p_plural_rule.find_char('=', first_semi_col) + 1;
  188. int second_semi_col = p_plural_rule.rfind_char(';');
  189. plural_rule = p_plural_rule.substr(expression_start, second_semi_col - expression_start).strip_edges();
  190. // Setup the cache to make evaluating plural rule faster later on.
  191. equi_tests.instantiate();
  192. _cache_plural_tests(plural_rule, equi_tests);
  193. expr.instantiate();
  194. input_name.push_back("n");
  195. }
  196. void TranslationPO::add_message(const StringName &p_src_text, const StringName &p_xlated_text, const StringName &p_context) {
  197. HashMap<StringName, Vector<StringName>> &map_id_str = translation_map[p_context];
  198. if (map_id_str.has(p_src_text)) {
  199. WARN_PRINT(vformat("Double translations for \"%s\" under the same context \"%s\" for locale \"%s\".\nThere should only be one unique translation for a given string under the same context.", String(p_src_text), String(p_context), get_locale()));
  200. map_id_str[p_src_text].set(0, p_xlated_text);
  201. } else {
  202. map_id_str[p_src_text].push_back(p_xlated_text);
  203. }
  204. }
  205. void TranslationPO::add_plural_message(const StringName &p_src_text, const Vector<String> &p_plural_xlated_texts, const StringName &p_context) {
  206. ERR_FAIL_COND_MSG(p_plural_xlated_texts.size() != plural_forms, vformat("Trying to add plural texts that don't match the required number of plural forms for locale \"%s\".", get_locale()));
  207. HashMap<StringName, Vector<StringName>> &map_id_str = translation_map[p_context];
  208. if (map_id_str.has(p_src_text)) {
  209. WARN_PRINT(vformat("Double translations for \"%s\" under the same context \"%s\" for locale %s.\nThere should only be one unique translation for a given string under the same context.", p_src_text, p_context, get_locale()));
  210. map_id_str[p_src_text].clear();
  211. }
  212. for (int i = 0; i < p_plural_xlated_texts.size(); i++) {
  213. map_id_str[p_src_text].push_back(p_plural_xlated_texts[i]);
  214. }
  215. }
  216. int TranslationPO::get_plural_forms() const {
  217. return plural_forms;
  218. }
  219. String TranslationPO::get_plural_rule() const {
  220. return plural_rule;
  221. }
  222. StringName TranslationPO::get_message(const StringName &p_src_text, const StringName &p_context) const {
  223. if (!translation_map.has(p_context) || !translation_map[p_context].has(p_src_text)) {
  224. return StringName();
  225. }
  226. ERR_FAIL_COND_V_MSG(translation_map[p_context][p_src_text].is_empty(), StringName(), vformat("Source text \"%s\" is registered but doesn't have a translation. Please report this bug.", String(p_src_text)));
  227. return translation_map[p_context][p_src_text][0];
  228. }
  229. StringName TranslationPO::get_plural_message(const StringName &p_src_text, const StringName &p_plural_text, int p_n, const StringName &p_context) const {
  230. ERR_FAIL_COND_V_MSG(p_n < 0, StringName(), "N passed into translation to get a plural message should not be negative. For negative numbers, use singular translation please. Search \"gettext PO Plural Forms\" online for the documentation on translating negative numbers.");
  231. // If the query is the same as last time, return the cached result.
  232. if (p_n == last_plural_n && p_context == last_plural_context && p_src_text == last_plural_key) {
  233. return translation_map[p_context][p_src_text][last_plural_mapped_index];
  234. }
  235. if (!translation_map.has(p_context) || !translation_map[p_context].has(p_src_text)) {
  236. return StringName();
  237. }
  238. ERR_FAIL_COND_V_MSG(translation_map[p_context][p_src_text].is_empty(), StringName(), vformat("Source text \"%s\" is registered but doesn't have a translation. Please report this bug.", String(p_src_text)));
  239. int plural_index = _get_plural_index(p_n);
  240. ERR_FAIL_COND_V_MSG(plural_index < 0 || translation_map[p_context][p_src_text].size() < plural_index + 1, StringName(), "Plural index returned or number of plural translations is not valid. Please report this bug.");
  241. // Cache result so that if the next entry is the same, we can return directly.
  242. // _get_plural_index(p_n) can get very costly, especially when evaluating long plural-rule (Arabic)
  243. last_plural_key = p_src_text;
  244. last_plural_context = p_context;
  245. last_plural_n = p_n;
  246. last_plural_mapped_index = plural_index;
  247. return translation_map[p_context][p_src_text][plural_index];
  248. }
  249. void TranslationPO::erase_message(const StringName &p_src_text, const StringName &p_context) {
  250. if (!translation_map.has(p_context)) {
  251. return;
  252. }
  253. translation_map[p_context].erase(p_src_text);
  254. }
  255. void TranslationPO::get_message_list(List<StringName> *r_messages) const {
  256. // OptimizedTranslation uses this function to get the list of msgid.
  257. // Return all the keys of translation_map under "" context.
  258. for (const KeyValue<StringName, HashMap<StringName, Vector<StringName>>> &E : translation_map) {
  259. if (E.key != StringName()) {
  260. continue;
  261. }
  262. for (const KeyValue<StringName, Vector<StringName>> &E2 : E.value) {
  263. r_messages->push_back(E2.key);
  264. }
  265. }
  266. }
  267. int TranslationPO::get_message_count() const {
  268. int count = 0;
  269. for (const KeyValue<StringName, HashMap<StringName, Vector<StringName>>> &E : translation_map) {
  270. count += E.value.size();
  271. }
  272. return count;
  273. }
  274. void TranslationPO::_bind_methods() {
  275. ClassDB::bind_method(D_METHOD("get_plural_forms"), &TranslationPO::get_plural_forms);
  276. ClassDB::bind_method(D_METHOD("get_plural_rule"), &TranslationPO::get_plural_rule);
  277. }