translation_po.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. /*************************************************************************/
  2. /* translation_po.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
  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. #include "core/os/file_access.h"
  32. #ifdef DEBUG_TRANSLATION_PO
  33. void TranslationPO::print_translation_map() {
  34. Error err;
  35. 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(this->get_plural_forms()));
  41. file->store_line("Plural rule : " + this->get_plural_rule());
  42. file->store_line("");
  43. List<StringName> context_l;
  44. translation_map.get_key_list(&context_l);
  45. for (auto E = context_l.front(); E; E = E->next()) {
  46. StringName ctx = E->get();
  47. file->store_line(" ===== Context: " + String::utf8(String(ctx).utf8()) + " ===== ");
  48. const HashMap<StringName, Vector<StringName>> &inner_map = translation_map[ctx];
  49. List<StringName> id_l;
  50. inner_map.get_key_list(&id_l);
  51. for (auto E2 = id_l.front(); E2; E2 = E2->next()) {
  52. StringName id = E2->get();
  53. file->store_line("msgid: " + String::utf8(String(id).utf8()));
  54. for (int i = 0; i < inner_map[id].size(); i++) {
  55. file->store_line("msgstr[" + String::num_int64(i) + "]: " + String::utf8(String(inner_map[id][i]).utf8()));
  56. }
  57. file->store_line("");
  58. }
  59. }
  60. file->close();
  61. }
  62. #endif
  63. Dictionary TranslationPO::_get_messages() const {
  64. // Return translation_map as a Dictionary.
  65. Dictionary d;
  66. List<StringName> context_l;
  67. translation_map.get_key_list(&context_l);
  68. for (auto E = context_l.front(); E; E = E->next()) {
  69. StringName ctx = E->get();
  70. const HashMap<StringName, Vector<StringName>> &id_str_map = translation_map[ctx];
  71. Dictionary d2;
  72. List<StringName> id_l;
  73. id_str_map.get_key_list(&id_l);
  74. // Save list of id and strs associated with a context in a temporary dictionary.
  75. for (auto E2 = id_l.front(); E2; E2 = E2->next()) {
  76. StringName id = E2->get();
  77. d2[id] = id_str_map[id];
  78. }
  79. d[ctx] = d2;
  80. }
  81. return d;
  82. }
  83. void TranslationPO::_set_messages(const Dictionary &p_messages) {
  84. // Construct translation_map from a Dictionary.
  85. List<Variant> context_l;
  86. p_messages.get_key_list(&context_l);
  87. for (auto E = context_l.front(); E; E = E->next()) {
  88. StringName ctx = E->get();
  89. const Dictionary &id_str_map = p_messages[ctx];
  90. HashMap<StringName, Vector<StringName>> temp_map;
  91. List<Variant> id_l;
  92. id_str_map.get_key_list(&id_l);
  93. for (auto E2 = id_l.front(); E2; E2 = E2->next()) {
  94. StringName id = E2->get();
  95. temp_map[id] = id_str_map[id];
  96. }
  97. translation_map[ctx] = temp_map;
  98. }
  99. }
  100. Vector<String> TranslationPO::_get_message_list() const {
  101. // Return all keys in translation_map.
  102. List<StringName> msgs;
  103. get_message_list(&msgs);
  104. Vector<String> v;
  105. for (auto E = msgs.front(); E; E = E->next()) {
  106. v.push_back(E->get());
  107. }
  108. return v;
  109. }
  110. int TranslationPO::_get_plural_index(int p_n) const {
  111. // Get a number between [0;number of plural forms).
  112. input_val.clear();
  113. input_val.push_back(p_n);
  114. Variant result;
  115. for (int i = 0; i < equi_tests.size(); i++) {
  116. Error err = expr->parse(equi_tests[i], input_name);
  117. ERR_FAIL_COND_V_MSG(err != OK, 0, "Cannot parse expression. Error: " + expr->get_error_text());
  118. result = expr->execute(input_val);
  119. ERR_FAIL_COND_V_MSG(expr->has_execute_failed(), 0, "Cannot evaluate expression.");
  120. // Last expression. Variant result will either map to a bool or an integer, in both cases returning it will give the correct plural index.
  121. if (i + 1 == equi_tests.size()) {
  122. return result;
  123. }
  124. if (bool(result)) {
  125. return i;
  126. }
  127. }
  128. ERR_FAIL_V_MSG(0, "Unexpected. Function should have returned. Please report this bug.");
  129. }
  130. void TranslationPO::_cache_plural_tests(const String &p_plural_rule) {
  131. // Some examples of p_plural_rule passed in can have the form:
  132. // "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)
  133. // "n >= 2" (French) // When evaluating the last, esp careful with this one.
  134. // "n != 1" (English)
  135. int first_ques_mark = p_plural_rule.find("?");
  136. if (first_ques_mark == -1) {
  137. equi_tests.push_back(p_plural_rule.strip_edges());
  138. return;
  139. }
  140. String equi_test = p_plural_rule.substr(0, first_ques_mark).strip_edges();
  141. equi_tests.push_back(equi_test);
  142. String after_colon = p_plural_rule.substr(p_plural_rule.find(":") + 1, p_plural_rule.length());
  143. _cache_plural_tests(after_colon);
  144. }
  145. void TranslationPO::set_plural_rule(const String &p_plural_rule) {
  146. // Set plural_forms and plural_rule.
  147. // p_plural_rule passed in has the form "Plural-Forms: nplurals=2; plural=(n >= 2);".
  148. int first_semi_col = p_plural_rule.find(";");
  149. plural_forms = p_plural_rule.substr(p_plural_rule.find("=") + 1, first_semi_col - (p_plural_rule.find("=") + 1)).to_int();
  150. int expression_start = p_plural_rule.find("=", first_semi_col) + 1;
  151. int second_semi_col = p_plural_rule.rfind(";");
  152. plural_rule = p_plural_rule.substr(expression_start, second_semi_col - expression_start);
  153. // Setup the cache to make evaluating plural rule faster later on.
  154. plural_rule = plural_rule.replacen("(", "");
  155. plural_rule = plural_rule.replacen(")", "");
  156. _cache_plural_tests(plural_rule);
  157. expr.instance();
  158. input_name.push_back("n");
  159. }
  160. void TranslationPO::add_message(const StringName &p_src_text, const StringName &p_xlated_text, const StringName &p_context) {
  161. HashMap<StringName, Vector<StringName>> &map_id_str = translation_map[p_context];
  162. if (map_id_str.has(p_src_text)) {
  163. WARN_PRINT("Double translations for \"" + String(p_src_text) + "\" under the same context \"" + String(p_context) + "\" for locale \"" + get_locale() + "\".\nThere should only be one unique translation for a given string under the same context.");
  164. map_id_str[p_src_text].set(0, p_xlated_text);
  165. } else {
  166. map_id_str[p_src_text].push_back(p_xlated_text);
  167. }
  168. }
  169. void TranslationPO::add_plural_message(const StringName &p_src_text, const Vector<String> &p_plural_xlated_texts, const StringName &p_context) {
  170. ERR_FAIL_COND_MSG(p_plural_xlated_texts.size() != plural_forms, "Trying to add plural texts that don't match the required number of plural forms for locale \"" + get_locale() + "\"");
  171. HashMap<StringName, Vector<StringName>> &map_id_str = translation_map[p_context];
  172. if (map_id_str.has(p_src_text)) {
  173. WARN_PRINT("Double translations for \"" + p_src_text + "\" under the same context \"" + p_context + "\" for locale " + get_locale() + ".\nThere should only be one unique translation for a given string under the same context.");
  174. map_id_str[p_src_text].clear();
  175. }
  176. for (int i = 0; i < p_plural_xlated_texts.size(); i++) {
  177. map_id_str[p_src_text].push_back(p_plural_xlated_texts[i]);
  178. }
  179. }
  180. int TranslationPO::get_plural_forms() const {
  181. return plural_forms;
  182. }
  183. String TranslationPO::get_plural_rule() const {
  184. return plural_rule;
  185. }
  186. StringName TranslationPO::get_message(const StringName &p_src_text, const StringName &p_context) const {
  187. if (!translation_map.has(p_context) || !translation_map[p_context].has(p_src_text)) {
  188. return StringName();
  189. }
  190. ERR_FAIL_COND_V_MSG(translation_map[p_context][p_src_text].is_empty(), StringName(), "Source text \"" + String(p_src_text) + "\" is registered but doesn't have a translation. Please report this bug.");
  191. return translation_map[p_context][p_src_text][0];
  192. }
  193. StringName TranslationPO::get_plural_message(const StringName &p_src_text, const StringName &p_plural_text, int p_n, const StringName &p_context) const {
  194. 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.");
  195. // If the query is the same as last time, return the cached result.
  196. if (p_n == last_plural_n && p_context == last_plural_context && p_src_text == last_plural_key) {
  197. return translation_map[p_context][p_src_text][last_plural_mapped_index];
  198. }
  199. if (!translation_map.has(p_context) || !translation_map[p_context].has(p_src_text)) {
  200. return StringName();
  201. }
  202. ERR_FAIL_COND_V_MSG(translation_map[p_context][p_src_text].is_empty(), StringName(), "Source text \"" + String(p_src_text) + "\" is registered but doesn't have a translation. Please report this bug.");
  203. if (translation_map[p_context][p_src_text].size() == 1) {
  204. WARN_PRINT("Source string \"" + String(p_src_text) + "\" doesn't have plural translations. Use singular translation API for such as tr(), TTR() to translate \"" + String(p_src_text) + "\"");
  205. return translation_map[p_context][p_src_text][0];
  206. }
  207. int plural_index = _get_plural_index(p_n);
  208. 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.");
  209. // Cache result so that if the next entry is the same, we can return directly.
  210. // _get_plural_index(p_n) can get very costly, especially when evaluating long plural-rule (Arabic)
  211. last_plural_key = p_src_text;
  212. last_plural_context = p_context;
  213. last_plural_n = p_n;
  214. last_plural_mapped_index = plural_index;
  215. return translation_map[p_context][p_src_text][plural_index];
  216. }
  217. void TranslationPO::erase_message(const StringName &p_src_text, const StringName &p_context) {
  218. if (!translation_map.has(p_context)) {
  219. return;
  220. }
  221. translation_map[p_context].erase(p_src_text);
  222. }
  223. void TranslationPO::get_message_list(List<StringName> *r_messages) const {
  224. // PHashTranslation uses this function to get the list of msgid.
  225. // Return all the keys of translation_map under "" context.
  226. List<StringName> context_l;
  227. translation_map.get_key_list(&context_l);
  228. for (auto E = context_l.front(); E; E = E->next()) {
  229. if (String(E->get()) != "") {
  230. continue;
  231. }
  232. List<StringName> msgid_l;
  233. translation_map[E->get()].get_key_list(&msgid_l);
  234. for (auto E2 = msgid_l.front(); E2; E2 = E2->next()) {
  235. r_messages->push_back(E2->get());
  236. }
  237. }
  238. }
  239. int TranslationPO::get_message_count() const {
  240. List<StringName> context_l;
  241. translation_map.get_key_list(&context_l);
  242. int count = 0;
  243. for (auto E = context_l.front(); E; E = E->next()) {
  244. count += translation_map[E->get()].size();
  245. }
  246. return count;
  247. }
  248. void TranslationPO::_bind_methods() {
  249. ClassDB::bind_method(D_METHOD("get_plural_forms"), &TranslationPO::get_plural_forms);
  250. ClassDB::bind_method(D_METHOD("get_plural_rule"), &TranslationPO::get_plural_rule);
  251. }