translation.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976
  1. /*************************************************************************/
  2. /* translation.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2022 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.h"
  31. #include "core/config/project_settings.h"
  32. #include "core/io/resource_loader.h"
  33. #include "core/os/os.h"
  34. #include "core/string/locales.h"
  35. #ifdef TOOLS_ENABLED
  36. #include "main/main.h"
  37. #endif
  38. Dictionary Translation::_get_messages() const {
  39. Dictionary d;
  40. for (const KeyValue<StringName, StringName> &E : translation_map) {
  41. d[E.key] = E.value;
  42. }
  43. return d;
  44. }
  45. Vector<String> Translation::_get_message_list() const {
  46. Vector<String> msgs;
  47. msgs.resize(translation_map.size());
  48. int idx = 0;
  49. for (const KeyValue<StringName, StringName> &E : translation_map) {
  50. msgs.set(idx, E.key);
  51. idx += 1;
  52. }
  53. return msgs;
  54. }
  55. void Translation::_set_messages(const Dictionary &p_messages) {
  56. List<Variant> keys;
  57. p_messages.get_key_list(&keys);
  58. for (const Variant &E : keys) {
  59. translation_map[E] = p_messages[E];
  60. }
  61. }
  62. void Translation::set_locale(const String &p_locale) {
  63. locale = TranslationServer::get_singleton()->standardize_locale(p_locale);
  64. if (OS::get_singleton()->get_main_loop() && TranslationServer::get_singleton()->get_loaded_locales().has(get_locale())) {
  65. OS::get_singleton()->get_main_loop()->notification(MainLoop::NOTIFICATION_TRANSLATION_CHANGED);
  66. }
  67. }
  68. void Translation::add_message(const StringName &p_src_text, const StringName &p_xlated_text, const StringName &p_context) {
  69. translation_map[p_src_text] = p_xlated_text;
  70. }
  71. void Translation::add_plural_message(const StringName &p_src_text, const Vector<String> &p_plural_xlated_texts, const StringName &p_context) {
  72. WARN_PRINT("Translation class doesn't handle plural messages. Calling add_plural_message() on a Translation instance is probably a mistake. \nUse a derived Translation class that handles plurals, such as TranslationPO class");
  73. ERR_FAIL_COND_MSG(p_plural_xlated_texts.is_empty(), "Parameter vector p_plural_xlated_texts passed in is empty.");
  74. translation_map[p_src_text] = p_plural_xlated_texts[0];
  75. }
  76. StringName Translation::get_message(const StringName &p_src_text, const StringName &p_context) const {
  77. StringName ret;
  78. if (GDVIRTUAL_CALL(_get_message, p_src_text, p_context, ret)) {
  79. return ret;
  80. }
  81. if (p_context != StringName()) {
  82. WARN_PRINT("Translation class doesn't handle context. Using context in get_message() on a Translation instance is probably a mistake. \nUse a derived Translation class that handles context, such as TranslationPO class");
  83. }
  84. HashMap<StringName, StringName>::ConstIterator E = translation_map.find(p_src_text);
  85. if (!E) {
  86. return StringName();
  87. }
  88. return E->value;
  89. }
  90. StringName Translation::get_plural_message(const StringName &p_src_text, const StringName &p_plural_text, int p_n, const StringName &p_context) const {
  91. StringName ret;
  92. if (GDVIRTUAL_CALL(_get_plural_message, p_src_text, p_plural_text, p_n, p_context, ret)) {
  93. return ret;
  94. }
  95. WARN_PRINT("Translation class doesn't handle plural messages. Calling get_plural_message() on a Translation instance is probably a mistake. \nUse a derived Translation class that handles plurals, such as TranslationPO class");
  96. return get_message(p_src_text);
  97. }
  98. void Translation::erase_message(const StringName &p_src_text, const StringName &p_context) {
  99. if (p_context != StringName()) {
  100. WARN_PRINT("Translation class doesn't handle context. Using context in erase_message() on a Translation instance is probably a mistake. \nUse a derived Translation class that handles context, such as TranslationPO class");
  101. }
  102. translation_map.erase(p_src_text);
  103. }
  104. void Translation::get_message_list(List<StringName> *r_messages) const {
  105. for (const KeyValue<StringName, StringName> &E : translation_map) {
  106. r_messages->push_back(E.key);
  107. }
  108. }
  109. int Translation::get_message_count() const {
  110. return translation_map.size();
  111. }
  112. void Translation::_bind_methods() {
  113. ClassDB::bind_method(D_METHOD("set_locale", "locale"), &Translation::set_locale);
  114. ClassDB::bind_method(D_METHOD("get_locale"), &Translation::get_locale);
  115. ClassDB::bind_method(D_METHOD("add_message", "src_message", "xlated_message", "context"), &Translation::add_message, DEFVAL(""));
  116. ClassDB::bind_method(D_METHOD("add_plural_message", "src_message", "xlated_messages", "context"), &Translation::add_plural_message, DEFVAL(""));
  117. ClassDB::bind_method(D_METHOD("get_message", "src_message", "context"), &Translation::get_message, DEFVAL(""));
  118. ClassDB::bind_method(D_METHOD("get_plural_message", "src_message", "src_plural_message", "n", "context"), &Translation::get_plural_message, DEFVAL(""));
  119. ClassDB::bind_method(D_METHOD("erase_message", "src_message", "context"), &Translation::erase_message, DEFVAL(""));
  120. ClassDB::bind_method(D_METHOD("get_message_list"), &Translation::_get_message_list);
  121. ClassDB::bind_method(D_METHOD("get_message_count"), &Translation::get_message_count);
  122. ClassDB::bind_method(D_METHOD("_set_messages", "messages"), &Translation::_set_messages);
  123. ClassDB::bind_method(D_METHOD("_get_messages"), &Translation::_get_messages);
  124. GDVIRTUAL_BIND(_get_plural_message, "src_message", "src_plural_message", "n", "context");
  125. GDVIRTUAL_BIND(_get_message, "src_message", "context");
  126. ADD_PROPERTY(PropertyInfo(Variant::DICTIONARY, "messages", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL), "_set_messages", "_get_messages");
  127. ADD_PROPERTY(PropertyInfo(Variant::STRING, "locale"), "set_locale", "get_locale");
  128. }
  129. ///////////////////////////////////////////////
  130. struct _character_accent_pair {
  131. const char32_t character;
  132. const char32_t *accented_character;
  133. };
  134. static _character_accent_pair _character_to_accented[] = {
  135. { 'A', U"Å" },
  136. { 'B', U"ß" },
  137. { 'C', U"Ç" },
  138. { 'D', U"Ð" },
  139. { 'E', U"É" },
  140. { 'F', U"F́" },
  141. { 'G', U"Ĝ" },
  142. { 'H', U"Ĥ" },
  143. { 'I', U"Ĩ" },
  144. { 'J', U"Ĵ" },
  145. { 'K', U"ĸ" },
  146. { 'L', U"Ł" },
  147. { 'M', U"Ḿ" },
  148. { 'N', U"й" },
  149. { 'O', U"Ö" },
  150. { 'P', U"Ṕ" },
  151. { 'Q', U"Q́" },
  152. { 'R', U"Ř" },
  153. { 'S', U"Ŝ" },
  154. { 'T', U"Ŧ" },
  155. { 'U', U"Ũ" },
  156. { 'V', U"Ṽ" },
  157. { 'W', U"Ŵ" },
  158. { 'X', U"X́" },
  159. { 'Y', U"Ÿ" },
  160. { 'Z', U"Ž" },
  161. { 'a', U"á" },
  162. { 'b', U"ḅ" },
  163. { 'c', U"ć" },
  164. { 'd', U"d́" },
  165. { 'e', U"é" },
  166. { 'f', U"f́" },
  167. { 'g', U"ǵ" },
  168. { 'h', U"h̀" },
  169. { 'i', U"í" },
  170. { 'j', U"ǰ" },
  171. { 'k', U"ḱ" },
  172. { 'l', U"ł" },
  173. { 'm', U"m̀" },
  174. { 'n', U"ή" },
  175. { 'o', U"ô" },
  176. { 'p', U"ṕ" },
  177. { 'q', U"q́" },
  178. { 'r', U"ŕ" },
  179. { 's', U"š" },
  180. { 't', U"ŧ" },
  181. { 'u', U"ü" },
  182. { 'v', U"ṽ" },
  183. { 'w', U"ŵ" },
  184. { 'x', U"x́" },
  185. { 'y', U"ý" },
  186. { 'z', U"ź" },
  187. };
  188. Vector<TranslationServer::LocaleScriptInfo> TranslationServer::locale_script_info;
  189. HashMap<String, String> TranslationServer::language_map;
  190. HashMap<String, String> TranslationServer::script_map;
  191. HashMap<String, String> TranslationServer::locale_rename_map;
  192. HashMap<String, String> TranslationServer::country_name_map;
  193. HashMap<String, String> TranslationServer::variant_map;
  194. HashMap<String, String> TranslationServer::country_rename_map;
  195. void TranslationServer::init_locale_info() {
  196. // Init locale info.
  197. language_map.clear();
  198. int idx = 0;
  199. while (language_list[idx][0] != nullptr) {
  200. language_map[language_list[idx][0]] = String::utf8(language_list[idx][1]);
  201. idx++;
  202. }
  203. // Init locale-script map.
  204. locale_script_info.clear();
  205. idx = 0;
  206. while (locale_scripts[idx][0] != nullptr) {
  207. LocaleScriptInfo info;
  208. info.name = locale_scripts[idx][0];
  209. info.script = locale_scripts[idx][1];
  210. info.default_country = locale_scripts[idx][2];
  211. Vector<String> supported_countries = String(locale_scripts[idx][3]).split(",", false);
  212. for (int i = 0; i < supported_countries.size(); i++) {
  213. info.supported_countries.insert(supported_countries[i]);
  214. }
  215. locale_script_info.push_back(info);
  216. idx++;
  217. }
  218. // Init supported script list.
  219. script_map.clear();
  220. idx = 0;
  221. while (script_list[idx][0] != nullptr) {
  222. script_map[script_list[idx][1]] = String::utf8(script_list[idx][0]);
  223. idx++;
  224. }
  225. // Init regional variant map.
  226. variant_map.clear();
  227. idx = 0;
  228. while (locale_variants[idx][0] != nullptr) {
  229. variant_map[locale_variants[idx][0]] = locale_variants[idx][1];
  230. idx++;
  231. }
  232. // Init locale renames.
  233. locale_rename_map.clear();
  234. idx = 0;
  235. while (locale_renames[idx][0] != nullptr) {
  236. if (!String(locale_renames[idx][1]).is_empty()) {
  237. locale_rename_map[locale_renames[idx][0]] = locale_renames[idx][1];
  238. }
  239. idx++;
  240. }
  241. // Init country names.
  242. country_name_map.clear();
  243. idx = 0;
  244. while (country_names[idx][0] != nullptr) {
  245. country_name_map[String(country_names[idx][0])] = String::utf8(country_names[idx][1]);
  246. idx++;
  247. }
  248. // Init country renames.
  249. country_rename_map.clear();
  250. idx = 0;
  251. while (country_renames[idx][0] != nullptr) {
  252. if (!String(country_renames[idx][1]).is_empty()) {
  253. country_rename_map[country_renames[idx][0]] = country_renames[idx][1];
  254. }
  255. idx++;
  256. }
  257. }
  258. String TranslationServer::standardize_locale(const String &p_locale) const {
  259. // Replaces '-' with '_' for macOS style locales.
  260. String univ_locale = p_locale.replace("-", "_");
  261. // Extract locale elements.
  262. String lang_name, script_name, country_name, variant_name;
  263. Vector<String> locale_elements = univ_locale.get_slice("@", 0).split("_");
  264. lang_name = locale_elements[0];
  265. if (locale_elements.size() >= 2) {
  266. if (locale_elements[1].length() == 4 && is_ascii_upper_case(locale_elements[1][0]) && is_ascii_lower_case(locale_elements[1][1]) && is_ascii_lower_case(locale_elements[1][2]) && is_ascii_lower_case(locale_elements[1][3])) {
  267. script_name = locale_elements[1];
  268. }
  269. if (locale_elements[1].length() == 2 && is_ascii_upper_case(locale_elements[1][0]) && is_ascii_upper_case(locale_elements[1][1])) {
  270. country_name = locale_elements[1];
  271. }
  272. }
  273. if (locale_elements.size() >= 3) {
  274. if (locale_elements[2].length() == 2 && is_ascii_upper_case(locale_elements[2][0]) && is_ascii_upper_case(locale_elements[2][1])) {
  275. country_name = locale_elements[2];
  276. } else if (variant_map.has(locale_elements[2].to_lower()) && variant_map[locale_elements[2].to_lower()] == lang_name) {
  277. variant_name = locale_elements[2].to_lower();
  278. }
  279. }
  280. if (locale_elements.size() >= 4) {
  281. if (variant_map.has(locale_elements[3].to_lower()) && variant_map[locale_elements[3].to_lower()] == lang_name) {
  282. variant_name = locale_elements[3].to_lower();
  283. }
  284. }
  285. // Try extract script and variant from the extra part.
  286. Vector<String> script_extra = univ_locale.get_slice("@", 1).split(";");
  287. for (int i = 0; i < script_extra.size(); i++) {
  288. if (script_extra[i].to_lower() == "cyrillic") {
  289. script_name = "Cyrl";
  290. break;
  291. } else if (script_extra[i].to_lower() == "latin") {
  292. script_name = "Latn";
  293. break;
  294. } else if (script_extra[i].to_lower() == "devanagari") {
  295. script_name = "Deva";
  296. break;
  297. } else if (variant_map.has(script_extra[i].to_lower()) && variant_map[script_extra[i].to_lower()] == lang_name) {
  298. variant_name = script_extra[i].to_lower();
  299. }
  300. }
  301. // Handles known non-ISO language names used e.g. on Windows.
  302. if (locale_rename_map.has(lang_name)) {
  303. lang_name = locale_rename_map[lang_name];
  304. }
  305. // Handle country renames.
  306. if (country_rename_map.has(country_name)) {
  307. country_name = country_rename_map[country_name];
  308. }
  309. // Remove unsupported script codes.
  310. if (!script_map.has(script_name)) {
  311. script_name = "";
  312. }
  313. // Add script code base on language and country codes for some ambiguous cases.
  314. if (script_name.is_empty()) {
  315. for (int i = 0; i < locale_script_info.size(); i++) {
  316. const LocaleScriptInfo &info = locale_script_info[i];
  317. if (info.name == lang_name) {
  318. if (country_name.is_empty() || info.supported_countries.has(country_name)) {
  319. script_name = info.script;
  320. break;
  321. }
  322. }
  323. }
  324. }
  325. if (!script_name.is_empty() && country_name.is_empty()) {
  326. // Add conntry code based on script for some ambiguous cases.
  327. for (int i = 0; i < locale_script_info.size(); i++) {
  328. const LocaleScriptInfo &info = locale_script_info[i];
  329. if (info.name == lang_name && info.script == script_name) {
  330. country_name = info.default_country;
  331. break;
  332. }
  333. }
  334. }
  335. // Combine results.
  336. String out = lang_name;
  337. if (!script_name.is_empty()) {
  338. out = out + "_" + script_name;
  339. }
  340. if (!country_name.is_empty()) {
  341. out = out + "_" + country_name;
  342. }
  343. if (!variant_name.is_empty()) {
  344. out = out + "_" + variant_name;
  345. }
  346. return out;
  347. }
  348. int TranslationServer::compare_locales(const String &p_locale_a, const String &p_locale_b) const {
  349. String locale_a = standardize_locale(p_locale_a);
  350. String locale_b = standardize_locale(p_locale_b);
  351. if (locale_a == locale_b) {
  352. // Exact match.
  353. return 10;
  354. }
  355. Vector<String> locale_a_elements = locale_a.split("_");
  356. Vector<String> locale_b_elements = locale_b.split("_");
  357. if (locale_a_elements[0] == locale_b_elements[0]) {
  358. // Matching language, both locales have extra parts.
  359. // Return number of matching elements.
  360. int matching_elements = 1;
  361. for (int i = 1; i < locale_a_elements.size(); i++) {
  362. for (int j = 1; j < locale_b_elements.size(); j++) {
  363. if (locale_a_elements[i] == locale_b_elements[j]) {
  364. matching_elements++;
  365. }
  366. }
  367. }
  368. return matching_elements;
  369. } else {
  370. // No match.
  371. return 0;
  372. }
  373. }
  374. String TranslationServer::get_locale_name(const String &p_locale) const {
  375. String lang_name, script_name, country_name;
  376. Vector<String> locale_elements = standardize_locale(p_locale).split("_");
  377. lang_name = locale_elements[0];
  378. if (locale_elements.size() >= 2) {
  379. if (locale_elements[1].length() == 4 && is_ascii_upper_case(locale_elements[1][0]) && is_ascii_lower_case(locale_elements[1][1]) && is_ascii_lower_case(locale_elements[1][2]) && is_ascii_lower_case(locale_elements[1][3])) {
  380. script_name = locale_elements[1];
  381. }
  382. if (locale_elements[1].length() == 2 && is_ascii_upper_case(locale_elements[1][0]) && is_ascii_upper_case(locale_elements[1][1])) {
  383. country_name = locale_elements[1];
  384. }
  385. }
  386. if (locale_elements.size() >= 3) {
  387. if (locale_elements[2].length() == 2 && is_ascii_upper_case(locale_elements[2][0]) && is_ascii_upper_case(locale_elements[2][1])) {
  388. country_name = locale_elements[2];
  389. }
  390. }
  391. String name = language_map[lang_name];
  392. if (!script_name.is_empty()) {
  393. name = name + " (" + script_map[script_name] + ")";
  394. }
  395. if (!country_name.is_empty()) {
  396. name = name + ", " + country_name_map[country_name];
  397. }
  398. return name;
  399. }
  400. Vector<String> TranslationServer::get_all_languages() const {
  401. Vector<String> languages;
  402. for (const KeyValue<String, String> &E : language_map) {
  403. languages.push_back(E.key);
  404. }
  405. return languages;
  406. }
  407. String TranslationServer::get_language_name(const String &p_language) const {
  408. return language_map[p_language];
  409. }
  410. Vector<String> TranslationServer::get_all_scripts() const {
  411. Vector<String> scripts;
  412. for (const KeyValue<String, String> &E : script_map) {
  413. scripts.push_back(E.key);
  414. }
  415. return scripts;
  416. }
  417. String TranslationServer::get_script_name(const String &p_script) const {
  418. return script_map[p_script];
  419. }
  420. Vector<String> TranslationServer::get_all_countries() const {
  421. Vector<String> countries;
  422. for (const KeyValue<String, String> &E : country_name_map) {
  423. countries.push_back(E.key);
  424. }
  425. return countries;
  426. }
  427. String TranslationServer::get_country_name(const String &p_country) const {
  428. return country_name_map[p_country];
  429. }
  430. void TranslationServer::set_locale(const String &p_locale) {
  431. locale = standardize_locale(p_locale);
  432. if (OS::get_singleton()->get_main_loop()) {
  433. OS::get_singleton()->get_main_loop()->notification(MainLoop::NOTIFICATION_TRANSLATION_CHANGED);
  434. }
  435. ResourceLoader::reload_translation_remaps();
  436. }
  437. String TranslationServer::get_locale() const {
  438. return locale;
  439. }
  440. PackedStringArray TranslationServer::get_loaded_locales() const {
  441. PackedStringArray locales;
  442. for (const Ref<Translation> &E : translations) {
  443. const Ref<Translation> &t = E;
  444. ERR_FAIL_COND_V(t.is_null(), PackedStringArray());
  445. String l = t->get_locale();
  446. locales.push_back(l);
  447. }
  448. return locales;
  449. }
  450. void TranslationServer::add_translation(const Ref<Translation> &p_translation) {
  451. translations.insert(p_translation);
  452. }
  453. void TranslationServer::remove_translation(const Ref<Translation> &p_translation) {
  454. translations.erase(p_translation);
  455. }
  456. Ref<Translation> TranslationServer::get_translation_object(const String &p_locale) {
  457. Ref<Translation> res;
  458. int best_score = 0;
  459. for (const Ref<Translation> &E : translations) {
  460. const Ref<Translation> &t = E;
  461. ERR_FAIL_COND_V(t.is_null(), nullptr);
  462. String l = t->get_locale();
  463. int score = compare_locales(p_locale, l);
  464. if (score > 0 && score >= best_score) {
  465. res = t;
  466. best_score = score;
  467. if (score == 10) {
  468. break; // Exact match, skip the rest.
  469. }
  470. }
  471. }
  472. return res;
  473. }
  474. void TranslationServer::clear() {
  475. translations.clear();
  476. }
  477. StringName TranslationServer::translate(const StringName &p_message, const StringName &p_context) const {
  478. // Match given message against the translation catalog for the project locale.
  479. if (!enabled) {
  480. return p_message;
  481. }
  482. StringName res = _get_message_from_translations(p_message, p_context, locale, false);
  483. if (!res && fallback.length() >= 2) {
  484. res = _get_message_from_translations(p_message, p_context, fallback, false);
  485. }
  486. if (!res) {
  487. return pseudolocalization_enabled ? pseudolocalize(p_message) : p_message;
  488. }
  489. return pseudolocalization_enabled ? pseudolocalize(res) : res;
  490. }
  491. StringName TranslationServer::translate_plural(const StringName &p_message, const StringName &p_message_plural, int p_n, const StringName &p_context) const {
  492. if (!enabled) {
  493. if (p_n == 1) {
  494. return p_message;
  495. }
  496. return p_message_plural;
  497. }
  498. StringName res = _get_message_from_translations(p_message, p_context, locale, true, p_message_plural, p_n);
  499. if (!res && fallback.length() >= 2) {
  500. res = _get_message_from_translations(p_message, p_context, fallback, true, p_message_plural, p_n);
  501. }
  502. if (!res) {
  503. if (p_n == 1) {
  504. return p_message;
  505. }
  506. return p_message_plural;
  507. }
  508. return res;
  509. }
  510. StringName TranslationServer::_get_message_from_translations(const StringName &p_message, const StringName &p_context, const String &p_locale, bool plural, const String &p_message_plural, int p_n) const {
  511. StringName res;
  512. int best_score = 0;
  513. for (const Ref<Translation> &E : translations) {
  514. const Ref<Translation> &t = E;
  515. ERR_FAIL_COND_V(t.is_null(), p_message);
  516. String l = t->get_locale();
  517. int score = compare_locales(p_locale, l);
  518. if (score > 0 && score >= best_score) {
  519. StringName r;
  520. if (!plural) {
  521. r = t->get_message(p_message, p_context);
  522. } else {
  523. r = t->get_plural_message(p_message, p_message_plural, p_n, p_context);
  524. }
  525. if (!r) {
  526. continue;
  527. }
  528. res = r;
  529. best_score = score;
  530. if (score == 10) {
  531. break; // Exact match, skip the rest.
  532. }
  533. }
  534. }
  535. return res;
  536. }
  537. TranslationServer *TranslationServer::singleton = nullptr;
  538. bool TranslationServer::_load_translations(const String &p_from) {
  539. if (ProjectSettings::get_singleton()->has_setting(p_from)) {
  540. const Vector<String> &translation_names = GLOBAL_GET(p_from);
  541. int tcount = translation_names.size();
  542. if (tcount) {
  543. const String *r = translation_names.ptr();
  544. for (int i = 0; i < tcount; i++) {
  545. Ref<Translation> tr = ResourceLoader::load(r[i]);
  546. if (tr.is_valid()) {
  547. add_translation(tr);
  548. }
  549. }
  550. }
  551. return true;
  552. }
  553. return false;
  554. }
  555. void TranslationServer::setup() {
  556. String test = GLOBAL_DEF("internationalization/locale/test", "");
  557. test = test.strip_edges();
  558. if (!test.is_empty()) {
  559. set_locale(test);
  560. } else {
  561. set_locale(OS::get_singleton()->get_locale());
  562. }
  563. fallback = GLOBAL_DEF("internationalization/locale/fallback", "en");
  564. pseudolocalization_enabled = GLOBAL_DEF("internationalization/pseudolocalization/use_pseudolocalization", false);
  565. pseudolocalization_accents_enabled = GLOBAL_DEF("internationalization/pseudolocalization/replace_with_accents", true);
  566. pseudolocalization_double_vowels_enabled = GLOBAL_DEF("internationalization/pseudolocalization/double_vowels", false);
  567. pseudolocalization_fake_bidi_enabled = GLOBAL_DEF("internationalization/pseudolocalization/fake_bidi", false);
  568. pseudolocalization_override_enabled = GLOBAL_DEF("internationalization/pseudolocalization/override", false);
  569. expansion_ratio = GLOBAL_DEF("internationalization/pseudolocalization/expansion_ratio", 0.0);
  570. pseudolocalization_prefix = GLOBAL_DEF("internationalization/pseudolocalization/prefix", "[");
  571. pseudolocalization_suffix = GLOBAL_DEF("internationalization/pseudolocalization/suffix", "]");
  572. pseudolocalization_skip_placeholders_enabled = GLOBAL_DEF("internationalization/pseudolocalization/skip_placeholders", true);
  573. #ifdef TOOLS_ENABLED
  574. ProjectSettings::get_singleton()->set_custom_property_info("internationalization/locale/fallback", PropertyInfo(Variant::STRING, "internationalization/locale/fallback", PROPERTY_HINT_LOCALE_ID, ""));
  575. #endif
  576. }
  577. void TranslationServer::set_tool_translation(const Ref<Translation> &p_translation) {
  578. tool_translation = p_translation;
  579. }
  580. Ref<Translation> TranslationServer::get_tool_translation() const {
  581. return tool_translation;
  582. }
  583. String TranslationServer::get_tool_locale() {
  584. #ifdef TOOLS_ENABLED
  585. if (Engine::get_singleton()->is_editor_hint() || Engine::get_singleton()->is_project_manager_hint()) {
  586. if (TranslationServer::get_singleton()->get_tool_translation().is_valid()) {
  587. return tool_translation->get_locale();
  588. } else {
  589. return "en";
  590. }
  591. } else {
  592. #else
  593. {
  594. #endif
  595. return get_locale();
  596. }
  597. }
  598. StringName TranslationServer::tool_translate(const StringName &p_message, const StringName &p_context) const {
  599. if (tool_translation.is_valid()) {
  600. StringName r = tool_translation->get_message(p_message, p_context);
  601. if (r) {
  602. return editor_pseudolocalization ? tool_pseudolocalize(r) : r;
  603. }
  604. }
  605. return editor_pseudolocalization ? tool_pseudolocalize(p_message) : p_message;
  606. }
  607. StringName TranslationServer::tool_translate_plural(const StringName &p_message, const StringName &p_message_plural, int p_n, const StringName &p_context) const {
  608. if (tool_translation.is_valid()) {
  609. StringName r = tool_translation->get_plural_message(p_message, p_message_plural, p_n, p_context);
  610. if (r) {
  611. return r;
  612. }
  613. }
  614. if (p_n == 1) {
  615. return p_message;
  616. }
  617. return p_message_plural;
  618. }
  619. void TranslationServer::set_doc_translation(const Ref<Translation> &p_translation) {
  620. doc_translation = p_translation;
  621. }
  622. StringName TranslationServer::doc_translate(const StringName &p_message, const StringName &p_context) const {
  623. if (doc_translation.is_valid()) {
  624. StringName r = doc_translation->get_message(p_message, p_context);
  625. if (r) {
  626. return r;
  627. }
  628. }
  629. return p_message;
  630. }
  631. StringName TranslationServer::doc_translate_plural(const StringName &p_message, const StringName &p_message_plural, int p_n, const StringName &p_context) const {
  632. if (doc_translation.is_valid()) {
  633. StringName r = doc_translation->get_plural_message(p_message, p_message_plural, p_n, p_context);
  634. if (r) {
  635. return r;
  636. }
  637. }
  638. if (p_n == 1) {
  639. return p_message;
  640. }
  641. return p_message_plural;
  642. }
  643. bool TranslationServer::is_pseudolocalization_enabled() const {
  644. return pseudolocalization_enabled;
  645. }
  646. void TranslationServer::set_pseudolocalization_enabled(bool p_enabled) {
  647. pseudolocalization_enabled = p_enabled;
  648. if (OS::get_singleton()->get_main_loop()) {
  649. OS::get_singleton()->get_main_loop()->notification(MainLoop::NOTIFICATION_TRANSLATION_CHANGED);
  650. }
  651. ResourceLoader::reload_translation_remaps();
  652. }
  653. void TranslationServer::set_editor_pseudolocalization(bool p_enabled) {
  654. editor_pseudolocalization = p_enabled;
  655. }
  656. void TranslationServer::reload_pseudolocalization() {
  657. pseudolocalization_accents_enabled = GLOBAL_GET("internationalization/pseudolocalization/replace_with_accents");
  658. pseudolocalization_double_vowels_enabled = GLOBAL_GET("internationalization/pseudolocalization/double_vowels");
  659. pseudolocalization_fake_bidi_enabled = GLOBAL_GET("internationalization/pseudolocalization/fake_bidi");
  660. pseudolocalization_override_enabled = GLOBAL_GET("internationalization/pseudolocalization/override");
  661. expansion_ratio = GLOBAL_GET("internationalization/pseudolocalization/expansion_ratio");
  662. pseudolocalization_prefix = GLOBAL_GET("internationalization/pseudolocalization/prefix");
  663. pseudolocalization_suffix = GLOBAL_GET("internationalization/pseudolocalization/suffix");
  664. pseudolocalization_skip_placeholders_enabled = GLOBAL_GET("internationalization/pseudolocalization/skip_placeholders");
  665. if (OS::get_singleton()->get_main_loop()) {
  666. OS::get_singleton()->get_main_loop()->notification(MainLoop::NOTIFICATION_TRANSLATION_CHANGED);
  667. }
  668. ResourceLoader::reload_translation_remaps();
  669. }
  670. StringName TranslationServer::pseudolocalize(const StringName &p_message) const {
  671. String message = p_message;
  672. int length = message.length();
  673. if (pseudolocalization_override_enabled) {
  674. message = get_override_string(message);
  675. }
  676. if (pseudolocalization_double_vowels_enabled) {
  677. message = double_vowels(message);
  678. }
  679. if (pseudolocalization_accents_enabled) {
  680. message = replace_with_accented_string(message);
  681. }
  682. if (pseudolocalization_fake_bidi_enabled) {
  683. message = wrap_with_fakebidi_characters(message);
  684. }
  685. StringName res = add_padding(message, length);
  686. return res;
  687. }
  688. StringName TranslationServer::tool_pseudolocalize(const StringName &p_message) const {
  689. String message = p_message;
  690. message = double_vowels(message);
  691. message = replace_with_accented_string(message);
  692. StringName res = "[!!! " + message + " !!!]";
  693. return res;
  694. }
  695. String TranslationServer::get_override_string(String &p_message) const {
  696. String res;
  697. for (int i = 0; i < p_message.size(); i++) {
  698. if (pseudolocalization_skip_placeholders_enabled && is_placeholder(p_message, i)) {
  699. res += p_message[i];
  700. res += p_message[i + 1];
  701. i++;
  702. continue;
  703. }
  704. res += '*';
  705. }
  706. return res;
  707. }
  708. String TranslationServer::double_vowels(String &p_message) const {
  709. String res;
  710. for (int i = 0; i < p_message.size(); i++) {
  711. if (pseudolocalization_skip_placeholders_enabled && is_placeholder(p_message, i)) {
  712. res += p_message[i];
  713. res += p_message[i + 1];
  714. i++;
  715. continue;
  716. }
  717. res += p_message[i];
  718. if (p_message[i] == 'a' || p_message[i] == 'e' || p_message[i] == 'i' || p_message[i] == 'o' || p_message[i] == 'u' ||
  719. p_message[i] == 'A' || p_message[i] == 'E' || p_message[i] == 'I' || p_message[i] == 'O' || p_message[i] == 'U') {
  720. res += p_message[i];
  721. }
  722. }
  723. return res;
  724. };
  725. String TranslationServer::replace_with_accented_string(String &p_message) const {
  726. String res;
  727. for (int i = 0; i < p_message.size(); i++) {
  728. if (pseudolocalization_skip_placeholders_enabled && is_placeholder(p_message, i)) {
  729. res += p_message[i];
  730. res += p_message[i + 1];
  731. i++;
  732. continue;
  733. }
  734. const char32_t *accented = get_accented_version(p_message[i]);
  735. if (accented) {
  736. res += accented;
  737. } else {
  738. res += p_message[i];
  739. }
  740. }
  741. return res;
  742. }
  743. String TranslationServer::wrap_with_fakebidi_characters(String &p_message) const {
  744. String res;
  745. char32_t fakebidiprefix = U'\u202e';
  746. char32_t fakebidisuffix = U'\u202c';
  747. res += fakebidiprefix;
  748. // The fake bidi unicode gets popped at every newline so pushing it back at every newline.
  749. for (int i = 0; i < p_message.size(); i++) {
  750. if (p_message[i] == '\n') {
  751. res += fakebidisuffix;
  752. res += p_message[i];
  753. res += fakebidiprefix;
  754. } else if (pseudolocalization_skip_placeholders_enabled && is_placeholder(p_message, i)) {
  755. res += fakebidisuffix;
  756. res += p_message[i];
  757. res += p_message[i + 1];
  758. res += fakebidiprefix;
  759. i++;
  760. } else {
  761. res += p_message[i];
  762. }
  763. }
  764. res += fakebidisuffix;
  765. return res;
  766. }
  767. String TranslationServer::add_padding(const String &p_message, int p_length) const {
  768. String res;
  769. String prefix = pseudolocalization_prefix;
  770. String suffix;
  771. for (int i = 0; i < p_length * expansion_ratio / 2; i++) {
  772. prefix += "_";
  773. suffix += "_";
  774. }
  775. suffix += pseudolocalization_suffix;
  776. res += prefix;
  777. res += p_message;
  778. res += suffix;
  779. return res;
  780. }
  781. const char32_t *TranslationServer::get_accented_version(char32_t p_character) const {
  782. if (!is_ascii_char(p_character)) {
  783. return nullptr;
  784. }
  785. for (unsigned int i = 0; i < sizeof(_character_to_accented) / sizeof(_character_to_accented[0]); i++) {
  786. if (_character_to_accented[i].character == p_character) {
  787. return _character_to_accented[i].accented_character;
  788. }
  789. }
  790. return nullptr;
  791. }
  792. bool TranslationServer::is_placeholder(String &p_message, int p_index) const {
  793. return p_index < p_message.size() - 1 && p_message[p_index] == '%' &&
  794. (p_message[p_index + 1] == 's' || p_message[p_index + 1] == 'c' || p_message[p_index + 1] == 'd' ||
  795. p_message[p_index + 1] == 'o' || p_message[p_index + 1] == 'x' || p_message[p_index + 1] == 'X' || p_message[p_index + 1] == 'f');
  796. }
  797. void TranslationServer::_bind_methods() {
  798. ClassDB::bind_method(D_METHOD("set_locale", "locale"), &TranslationServer::set_locale);
  799. ClassDB::bind_method(D_METHOD("get_locale"), &TranslationServer::get_locale);
  800. ClassDB::bind_method(D_METHOD("get_tool_locale"), &TranslationServer::get_tool_locale);
  801. ClassDB::bind_method(D_METHOD("compare_locales", "locale_a", "locale_b"), &TranslationServer::compare_locales);
  802. ClassDB::bind_method(D_METHOD("standardize_locale", "locale"), &TranslationServer::standardize_locale);
  803. ClassDB::bind_method(D_METHOD("get_all_languages"), &TranslationServer::get_all_languages);
  804. ClassDB::bind_method(D_METHOD("get_language_name", "language"), &TranslationServer::get_language_name);
  805. ClassDB::bind_method(D_METHOD("get_all_scripts"), &TranslationServer::get_all_scripts);
  806. ClassDB::bind_method(D_METHOD("get_script_name", "script"), &TranslationServer::get_script_name);
  807. ClassDB::bind_method(D_METHOD("get_all_countries"), &TranslationServer::get_all_countries);
  808. ClassDB::bind_method(D_METHOD("get_country_name", "country"), &TranslationServer::get_country_name);
  809. ClassDB::bind_method(D_METHOD("get_locale_name", "locale"), &TranslationServer::get_locale_name);
  810. ClassDB::bind_method(D_METHOD("translate", "message", "context"), &TranslationServer::translate, DEFVAL(""));
  811. ClassDB::bind_method(D_METHOD("translate_plural", "message", "plural_message", "n", "context"), &TranslationServer::translate_plural, DEFVAL(""));
  812. ClassDB::bind_method(D_METHOD("add_translation", "translation"), &TranslationServer::add_translation);
  813. ClassDB::bind_method(D_METHOD("remove_translation", "translation"), &TranslationServer::remove_translation);
  814. ClassDB::bind_method(D_METHOD("get_translation_object", "locale"), &TranslationServer::get_translation_object);
  815. ClassDB::bind_method(D_METHOD("clear"), &TranslationServer::clear);
  816. ClassDB::bind_method(D_METHOD("get_loaded_locales"), &TranslationServer::get_loaded_locales);
  817. ClassDB::bind_method(D_METHOD("is_pseudolocalization_enabled"), &TranslationServer::is_pseudolocalization_enabled);
  818. ClassDB::bind_method(D_METHOD("set_pseudolocalization_enabled", "enabled"), &TranslationServer::set_pseudolocalization_enabled);
  819. ClassDB::bind_method(D_METHOD("reload_pseudolocalization"), &TranslationServer::reload_pseudolocalization);
  820. ClassDB::bind_method(D_METHOD("pseudolocalize", "message"), &TranslationServer::pseudolocalize);
  821. ADD_PROPERTY(PropertyInfo(Variant::Type::BOOL, "pseudolocalization_enabled"), "set_pseudolocalization_enabled", "is_pseudolocalization_enabled");
  822. }
  823. void TranslationServer::load_translations() {
  824. _load_translations("internationalization/locale/translations"); //all
  825. _load_translations("internationalization/locale/translations_" + locale.substr(0, 2));
  826. if (locale.substr(0, 2) != locale) {
  827. _load_translations("internationalization/locale/translations_" + locale);
  828. }
  829. }
  830. TranslationServer::TranslationServer() {
  831. singleton = this;
  832. init_locale_info();
  833. }