translation.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. /**************************************************************************/
  2. /* translation.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.h"
  31. #include "core/os/thread.h"
  32. #include "core/string/plural_rules.h"
  33. #include "core/string/translation_server.h"
  34. void _check_for_incompatibility(const String &p_msgctxt, const String &p_msgid) {
  35. // Gettext PO and MO files use an empty untranslated string without context
  36. // to store metadata.
  37. if (p_msgctxt.is_empty() && p_msgid.is_empty()) {
  38. WARN_PRINT("Both context and the untranslated string are empty. This may cause issues with the translation system and external tools.");
  39. }
  40. // The EOT character (0x04) is used as a separator between context and
  41. // untranslated string in the MO file format. This convention is also used
  42. // by `get_message_list()`.
  43. //
  44. // It's unusual to have this character in the context or untranslated
  45. // string. But it doesn't do any harm as long as you are aware of this when
  46. // using the relevant APIs and tools.
  47. if (p_msgctxt.contains_char(0x04)) {
  48. WARN_PRINT(vformat("Found EOT character (0x04) within context '%s'. This may cause issues with the translation system and external tools.", p_msgctxt));
  49. }
  50. if (p_msgid.contains_char(0x04)) {
  51. WARN_PRINT(vformat("Found EOT character (0x04) within untranslated string '%s'. This may cause issues with the translation system and external tools.", p_msgid));
  52. }
  53. }
  54. Dictionary Translation::_get_messages() const {
  55. Dictionary d;
  56. for (const KeyValue<MessageKey, Vector<StringName>> &E : translation_map) {
  57. const Array &storage_key = { E.key.msgctxt, E.key.msgid };
  58. Array storage_value;
  59. storage_value.resize(E.value.size());
  60. for (int i = 0; i < E.value.size(); i++) {
  61. storage_value[i] = E.value[i];
  62. }
  63. d[storage_key] = storage_value;
  64. }
  65. return d;
  66. }
  67. void Translation::_set_messages(const Dictionary &p_messages) {
  68. translation_map.clear();
  69. for (const KeyValue<Variant, Variant> &kv : p_messages) {
  70. switch (kv.key.get_type()) {
  71. // Old version, no context or plural support.
  72. case Variant::STRING:
  73. case Variant::STRING_NAME: {
  74. const MessageKey msg_key = { StringName(), kv.key };
  75. _check_for_incompatibility(msg_key.msgctxt, msg_key.msgid);
  76. translation_map[msg_key] = { kv.value };
  77. } break;
  78. // Current version.
  79. case Variant::ARRAY: {
  80. const Array &storage_key = kv.key;
  81. const MessageKey msg_key = { storage_key[0], storage_key[1] };
  82. const Array &storage_value = kv.value;
  83. ERR_CONTINUE_MSG(storage_value.is_empty(), vformat("No translated strings for untranslated string '%s' with context '%s'.", msg_key.msgid, msg_key.msgctxt));
  84. Vector<StringName> msgstrs;
  85. msgstrs.resize(storage_value.size());
  86. for (int i = 0; i < storage_value.size(); i++) {
  87. msgstrs.write[i] = storage_value[i];
  88. }
  89. _check_for_incompatibility(msg_key.msgctxt, msg_key.msgid);
  90. translation_map[msg_key] = msgstrs;
  91. } break;
  92. default: {
  93. WARN_PRINT(vformat("Invalid key type in messages dictionary: %s.", Variant::get_type_name(kv.key.get_type())));
  94. continue;
  95. }
  96. }
  97. }
  98. }
  99. Vector<String> Translation::_get_message_list() const {
  100. List<StringName> msgstrs;
  101. get_message_list(&msgstrs);
  102. Vector<String> keys;
  103. keys.resize(msgstrs.size());
  104. int idx = 0;
  105. for (const StringName &msgstr : msgstrs) {
  106. keys.write[idx++] = msgstr;
  107. }
  108. return keys;
  109. }
  110. Vector<String> Translation::get_translated_message_list() const {
  111. Vector<String> msgstrs;
  112. for (const KeyValue<MessageKey, Vector<StringName>> &E : translation_map) {
  113. for (const StringName &msgstr : E.value) {
  114. msgstrs.push_back(msgstr);
  115. }
  116. }
  117. return msgstrs;
  118. }
  119. void Translation::set_locale(const String &p_locale) {
  120. locale = TranslationServer::get_singleton()->standardize_locale(p_locale);
  121. if (plural_rules_cache && plural_rules_override.is_empty()) {
  122. memdelete(plural_rules_cache);
  123. plural_rules_cache = nullptr;
  124. }
  125. }
  126. void Translation::add_message(const StringName &p_src_text, const StringName &p_xlated_text, const StringName &p_context) {
  127. _check_for_incompatibility(p_context, p_src_text);
  128. translation_map[{ p_context, p_src_text }] = { p_xlated_text };
  129. }
  130. void Translation::add_plural_message(const StringName &p_src_text, const Vector<String> &p_plural_xlated_texts, const StringName &p_context) {
  131. ERR_FAIL_COND_MSG(p_plural_xlated_texts.is_empty(), "Parameter vector p_plural_xlated_texts passed in is empty.");
  132. Vector<StringName> msgstrs;
  133. msgstrs.resize(p_plural_xlated_texts.size());
  134. for (int i = 0; i < p_plural_xlated_texts.size(); i++) {
  135. msgstrs.write[i] = p_plural_xlated_texts[i];
  136. }
  137. _check_for_incompatibility(p_context, p_src_text);
  138. translation_map[{ p_context, p_src_text }] = msgstrs;
  139. }
  140. StringName Translation::get_message(const StringName &p_src_text, const StringName &p_context) const {
  141. StringName ret;
  142. if (GDVIRTUAL_CALL(_get_message, p_src_text, p_context, ret)) {
  143. return ret;
  144. }
  145. const Vector<StringName> *msgstrs = translation_map.getptr({ p_context, p_src_text });
  146. if (msgstrs == nullptr) {
  147. return StringName();
  148. }
  149. DEV_ASSERT(!msgstrs->is_empty()); // Should be prevented when adding messages.
  150. return msgstrs->get(0);
  151. }
  152. StringName Translation::get_plural_message(const StringName &p_src_text, const StringName &p_plural_text, int p_n, const StringName &p_context) const {
  153. StringName ret;
  154. if (GDVIRTUAL_CALL(_get_plural_message, p_src_text, p_plural_text, p_n, p_context, ret)) {
  155. return ret;
  156. }
  157. 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 details on translating negative numbers.");
  158. const Vector<StringName> *msgstrs = translation_map.getptr({ p_context, p_src_text });
  159. if (msgstrs == nullptr) {
  160. return StringName();
  161. }
  162. const int index = _get_plural_rules()->evaluate(p_n);
  163. ERR_FAIL_INDEX_V_MSG(index, msgstrs->size(), StringName(), "Plural index returned or number of plural translations is not valid.");
  164. return msgstrs->get(index);
  165. }
  166. void Translation::erase_message(const StringName &p_src_text, const StringName &p_context) {
  167. translation_map.erase({ p_context, p_src_text });
  168. }
  169. void Translation::get_message_list(List<StringName> *r_messages) const {
  170. for (const KeyValue<MessageKey, Vector<StringName>> &E : translation_map) {
  171. if (E.key.msgctxt.is_empty()) {
  172. r_messages->push_back(E.key.msgid);
  173. } else {
  174. // Separated by the EOT character. Compatible with the MO file format.
  175. r_messages->push_back(vformat("%s\x04%s", E.key.msgctxt, E.key.msgid));
  176. }
  177. }
  178. }
  179. int Translation::get_message_count() const {
  180. return translation_map.size();
  181. }
  182. PluralRules *Translation::_get_plural_rules() const {
  183. if (plural_rules_cache) {
  184. return plural_rules_cache;
  185. }
  186. if (!plural_rules_override.is_empty()) {
  187. plural_rules_cache = PluralRules::parse(plural_rules_override);
  188. }
  189. if (!plural_rules_cache) {
  190. // Locale's default plural rules.
  191. const String &default_rule = TranslationServer::get_singleton()->get_plural_rules(locale);
  192. if (!default_rule.is_empty()) {
  193. plural_rules_cache = PluralRules::parse(default_rule);
  194. }
  195. // Use English plural rules as a fallback.
  196. if (!plural_rules_cache) {
  197. plural_rules_cache = PluralRules::parse("nplurals=2; plural=(n != 1);");
  198. }
  199. }
  200. DEV_ASSERT(plural_rules_cache != nullptr);
  201. return plural_rules_cache;
  202. }
  203. void Translation::set_plural_rules_override(const String &p_rules) {
  204. plural_rules_override = p_rules;
  205. if (plural_rules_cache) {
  206. memdelete(plural_rules_cache);
  207. plural_rules_cache = nullptr;
  208. }
  209. }
  210. String Translation::get_plural_rules_override() const {
  211. return plural_rules_override;
  212. }
  213. int Translation::get_nplurals() const {
  214. return _get_plural_rules()->get_nplurals();
  215. }
  216. void Translation::_bind_methods() {
  217. ClassDB::bind_method(D_METHOD("set_locale", "locale"), &Translation::set_locale);
  218. ClassDB::bind_method(D_METHOD("get_locale"), &Translation::get_locale);
  219. ClassDB::bind_method(D_METHOD("add_message", "src_message", "xlated_message", "context"), &Translation::add_message, DEFVAL(StringName()));
  220. ClassDB::bind_method(D_METHOD("add_plural_message", "src_message", "xlated_messages", "context"), &Translation::add_plural_message, DEFVAL(StringName()));
  221. ClassDB::bind_method(D_METHOD("get_message", "src_message", "context"), &Translation::get_message, DEFVAL(StringName()));
  222. ClassDB::bind_method(D_METHOD("get_plural_message", "src_message", "src_plural_message", "n", "context"), &Translation::get_plural_message, DEFVAL(StringName()));
  223. ClassDB::bind_method(D_METHOD("erase_message", "src_message", "context"), &Translation::erase_message, DEFVAL(StringName()));
  224. ClassDB::bind_method(D_METHOD("get_message_list"), &Translation::_get_message_list);
  225. ClassDB::bind_method(D_METHOD("get_translated_message_list"), &Translation::get_translated_message_list);
  226. ClassDB::bind_method(D_METHOD("get_message_count"), &Translation::get_message_count);
  227. ClassDB::bind_method(D_METHOD("_set_messages", "messages"), &Translation::_set_messages);
  228. ClassDB::bind_method(D_METHOD("_get_messages"), &Translation::_get_messages);
  229. ClassDB::bind_method(D_METHOD("set_plural_rules_override", "rules"), &Translation::set_plural_rules_override);
  230. ClassDB::bind_method(D_METHOD("get_plural_rules_override"), &Translation::get_plural_rules_override);
  231. GDVIRTUAL_BIND(_get_plural_message, "src_message", "src_plural_message", "n", "context");
  232. GDVIRTUAL_BIND(_get_message, "src_message", "context");
  233. ADD_PROPERTY(PropertyInfo(Variant::DICTIONARY, "messages", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL), "_set_messages", "_get_messages");
  234. ADD_PROPERTY(PropertyInfo(Variant::STRING, "locale", PROPERTY_HINT_LOCALE_ID), "set_locale", "get_locale");
  235. ADD_PROPERTY(PropertyInfo(Variant::STRING, "plural_rules_override"), "set_plural_rules_override", "get_plural_rules_override");
  236. }
  237. Translation::~Translation() {
  238. if (plural_rules_cache) {
  239. memdelete(plural_rules_cache);
  240. plural_rules_cache = nullptr;
  241. }
  242. }