translation.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982
  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. return _standardize_locale(p_locale, false);
  260. }
  261. String TranslationServer::_standardize_locale(const String &p_locale, bool p_add_defaults) const {
  262. // Replaces '-' with '_' for macOS style locales.
  263. String univ_locale = p_locale.replace("-", "_");
  264. // Extract locale elements.
  265. String lang_name, script_name, country_name, variant_name;
  266. Vector<String> locale_elements = univ_locale.get_slice("@", 0).split("_");
  267. lang_name = locale_elements[0];
  268. if (locale_elements.size() >= 2) {
  269. 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])) {
  270. script_name = locale_elements[1];
  271. }
  272. if (locale_elements[1].length() == 2 && is_ascii_upper_case(locale_elements[1][0]) && is_ascii_upper_case(locale_elements[1][1])) {
  273. country_name = locale_elements[1];
  274. }
  275. }
  276. if (locale_elements.size() >= 3) {
  277. if (locale_elements[2].length() == 2 && is_ascii_upper_case(locale_elements[2][0]) && is_ascii_upper_case(locale_elements[2][1])) {
  278. country_name = locale_elements[2];
  279. } else if (variant_map.has(locale_elements[2].to_lower()) && variant_map[locale_elements[2].to_lower()] == lang_name) {
  280. variant_name = locale_elements[2].to_lower();
  281. }
  282. }
  283. if (locale_elements.size() >= 4) {
  284. if (variant_map.has(locale_elements[3].to_lower()) && variant_map[locale_elements[3].to_lower()] == lang_name) {
  285. variant_name = locale_elements[3].to_lower();
  286. }
  287. }
  288. // Try extract script and variant from the extra part.
  289. Vector<String> script_extra = univ_locale.get_slice("@", 1).split(";");
  290. for (int i = 0; i < script_extra.size(); i++) {
  291. if (script_extra[i].to_lower() == "cyrillic") {
  292. script_name = "Cyrl";
  293. break;
  294. } else if (script_extra[i].to_lower() == "latin") {
  295. script_name = "Latn";
  296. break;
  297. } else if (script_extra[i].to_lower() == "devanagari") {
  298. script_name = "Deva";
  299. break;
  300. } else if (variant_map.has(script_extra[i].to_lower()) && variant_map[script_extra[i].to_lower()] == lang_name) {
  301. variant_name = script_extra[i].to_lower();
  302. }
  303. }
  304. // Handles known non-ISO language names used e.g. on Windows.
  305. if (locale_rename_map.has(lang_name)) {
  306. lang_name = locale_rename_map[lang_name];
  307. }
  308. // Handle country renames.
  309. if (country_rename_map.has(country_name)) {
  310. country_name = country_rename_map[country_name];
  311. }
  312. // Remove unsupported script codes.
  313. if (!script_map.has(script_name)) {
  314. script_name = "";
  315. }
  316. // Add script code base on language and country codes for some ambiguous cases.
  317. if (p_add_defaults) {
  318. if (script_name.is_empty()) {
  319. for (int i = 0; i < locale_script_info.size(); i++) {
  320. const LocaleScriptInfo &info = locale_script_info[i];
  321. if (info.name == lang_name) {
  322. if (country_name.is_empty() || info.supported_countries.has(country_name)) {
  323. script_name = info.script;
  324. break;
  325. }
  326. }
  327. }
  328. }
  329. if (!script_name.is_empty() && country_name.is_empty()) {
  330. // Add conntry code based on script for some ambiguous cases.
  331. for (int i = 0; i < locale_script_info.size(); i++) {
  332. const LocaleScriptInfo &info = locale_script_info[i];
  333. if (info.name == lang_name && info.script == script_name) {
  334. country_name = info.default_country;
  335. break;
  336. }
  337. }
  338. }
  339. }
  340. // Combine results.
  341. String out = lang_name;
  342. if (!script_name.is_empty()) {
  343. out = out + "_" + script_name;
  344. }
  345. if (!country_name.is_empty()) {
  346. out = out + "_" + country_name;
  347. }
  348. if (!variant_name.is_empty()) {
  349. out = out + "_" + variant_name;
  350. }
  351. return out;
  352. }
  353. int TranslationServer::compare_locales(const String &p_locale_a, const String &p_locale_b) const {
  354. String locale_a = _standardize_locale(p_locale_a, true);
  355. String locale_b = _standardize_locale(p_locale_b, true);
  356. if (locale_a == locale_b) {
  357. // Exact match.
  358. return 10;
  359. }
  360. Vector<String> locale_a_elements = locale_a.split("_");
  361. Vector<String> locale_b_elements = locale_b.split("_");
  362. if (locale_a_elements[0] == locale_b_elements[0]) {
  363. // Matching language, both locales have extra parts.
  364. // Return number of matching elements.
  365. int matching_elements = 1;
  366. for (int i = 1; i < locale_a_elements.size(); i++) {
  367. for (int j = 1; j < locale_b_elements.size(); j++) {
  368. if (locale_a_elements[i] == locale_b_elements[j]) {
  369. matching_elements++;
  370. }
  371. }
  372. }
  373. return matching_elements;
  374. } else {
  375. // No match.
  376. return 0;
  377. }
  378. }
  379. String TranslationServer::get_locale_name(const String &p_locale) const {
  380. String lang_name, script_name, country_name;
  381. Vector<String> locale_elements = standardize_locale(p_locale).split("_");
  382. lang_name = locale_elements[0];
  383. if (locale_elements.size() >= 2) {
  384. 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])) {
  385. script_name = locale_elements[1];
  386. }
  387. if (locale_elements[1].length() == 2 && is_ascii_upper_case(locale_elements[1][0]) && is_ascii_upper_case(locale_elements[1][1])) {
  388. country_name = locale_elements[1];
  389. }
  390. }
  391. if (locale_elements.size() >= 3) {
  392. if (locale_elements[2].length() == 2 && is_ascii_upper_case(locale_elements[2][0]) && is_ascii_upper_case(locale_elements[2][1])) {
  393. country_name = locale_elements[2];
  394. }
  395. }
  396. String name = language_map[lang_name];
  397. if (!script_name.is_empty()) {
  398. name = name + " (" + script_map[script_name] + ")";
  399. }
  400. if (!country_name.is_empty()) {
  401. name = name + ", " + country_name_map[country_name];
  402. }
  403. return name;
  404. }
  405. Vector<String> TranslationServer::get_all_languages() const {
  406. Vector<String> languages;
  407. for (const KeyValue<String, String> &E : language_map) {
  408. languages.push_back(E.key);
  409. }
  410. return languages;
  411. }
  412. String TranslationServer::get_language_name(const String &p_language) const {
  413. return language_map[p_language];
  414. }
  415. Vector<String> TranslationServer::get_all_scripts() const {
  416. Vector<String> scripts;
  417. for (const KeyValue<String, String> &E : script_map) {
  418. scripts.push_back(E.key);
  419. }
  420. return scripts;
  421. }
  422. String TranslationServer::get_script_name(const String &p_script) const {
  423. return script_map[p_script];
  424. }
  425. Vector<String> TranslationServer::get_all_countries() const {
  426. Vector<String> countries;
  427. for (const KeyValue<String, String> &E : country_name_map) {
  428. countries.push_back(E.key);
  429. }
  430. return countries;
  431. }
  432. String TranslationServer::get_country_name(const String &p_country) const {
  433. return country_name_map[p_country];
  434. }
  435. void TranslationServer::set_locale(const String &p_locale) {
  436. locale = standardize_locale(p_locale);
  437. if (OS::get_singleton()->get_main_loop()) {
  438. OS::get_singleton()->get_main_loop()->notification(MainLoop::NOTIFICATION_TRANSLATION_CHANGED);
  439. }
  440. ResourceLoader::reload_translation_remaps();
  441. }
  442. String TranslationServer::get_locale() const {
  443. return locale;
  444. }
  445. PackedStringArray TranslationServer::get_loaded_locales() const {
  446. PackedStringArray locales;
  447. for (const Ref<Translation> &E : translations) {
  448. const Ref<Translation> &t = E;
  449. ERR_FAIL_COND_V(t.is_null(), PackedStringArray());
  450. String l = t->get_locale();
  451. locales.push_back(l);
  452. }
  453. return locales;
  454. }
  455. void TranslationServer::add_translation(const Ref<Translation> &p_translation) {
  456. translations.insert(p_translation);
  457. }
  458. void TranslationServer::remove_translation(const Ref<Translation> &p_translation) {
  459. translations.erase(p_translation);
  460. }
  461. Ref<Translation> TranslationServer::get_translation_object(const String &p_locale) {
  462. Ref<Translation> res;
  463. int best_score = 0;
  464. for (const Ref<Translation> &E : translations) {
  465. const Ref<Translation> &t = E;
  466. ERR_FAIL_COND_V(t.is_null(), nullptr);
  467. String l = t->get_locale();
  468. int score = compare_locales(p_locale, l);
  469. if (score > 0 && score >= best_score) {
  470. res = t;
  471. best_score = score;
  472. if (score == 10) {
  473. break; // Exact match, skip the rest.
  474. }
  475. }
  476. }
  477. return res;
  478. }
  479. void TranslationServer::clear() {
  480. translations.clear();
  481. }
  482. StringName TranslationServer::translate(const StringName &p_message, const StringName &p_context) const {
  483. // Match given message against the translation catalog for the project locale.
  484. if (!enabled) {
  485. return p_message;
  486. }
  487. StringName res = _get_message_from_translations(p_message, p_context, locale, false);
  488. if (!res && fallback.length() >= 2) {
  489. res = _get_message_from_translations(p_message, p_context, fallback, false);
  490. }
  491. if (!res) {
  492. return pseudolocalization_enabled ? pseudolocalize(p_message) : p_message;
  493. }
  494. return pseudolocalization_enabled ? pseudolocalize(res) : res;
  495. }
  496. StringName TranslationServer::translate_plural(const StringName &p_message, const StringName &p_message_plural, int p_n, const StringName &p_context) const {
  497. if (!enabled) {
  498. if (p_n == 1) {
  499. return p_message;
  500. }
  501. return p_message_plural;
  502. }
  503. StringName res = _get_message_from_translations(p_message, p_context, locale, true, p_message_plural, p_n);
  504. if (!res && fallback.length() >= 2) {
  505. res = _get_message_from_translations(p_message, p_context, fallback, true, p_message_plural, p_n);
  506. }
  507. if (!res) {
  508. if (p_n == 1) {
  509. return p_message;
  510. }
  511. return p_message_plural;
  512. }
  513. return res;
  514. }
  515. 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 {
  516. StringName res;
  517. int best_score = 0;
  518. for (const Ref<Translation> &E : translations) {
  519. const Ref<Translation> &t = E;
  520. ERR_FAIL_COND_V(t.is_null(), p_message);
  521. String l = t->get_locale();
  522. int score = compare_locales(p_locale, l);
  523. if (score > 0 && score >= best_score) {
  524. StringName r;
  525. if (!plural) {
  526. r = t->get_message(p_message, p_context);
  527. } else {
  528. r = t->get_plural_message(p_message, p_message_plural, p_n, p_context);
  529. }
  530. if (!r) {
  531. continue;
  532. }
  533. res = r;
  534. best_score = score;
  535. if (score == 10) {
  536. break; // Exact match, skip the rest.
  537. }
  538. }
  539. }
  540. return res;
  541. }
  542. TranslationServer *TranslationServer::singleton = nullptr;
  543. bool TranslationServer::_load_translations(const String &p_from) {
  544. if (ProjectSettings::get_singleton()->has_setting(p_from)) {
  545. const Vector<String> &translation_names = ProjectSettings::get_singleton()->get(p_from);
  546. int tcount = translation_names.size();
  547. if (tcount) {
  548. const String *r = translation_names.ptr();
  549. for (int i = 0; i < tcount; i++) {
  550. Ref<Translation> tr = ResourceLoader::load(r[i]);
  551. if (tr.is_valid()) {
  552. add_translation(tr);
  553. }
  554. }
  555. }
  556. return true;
  557. }
  558. return false;
  559. }
  560. void TranslationServer::setup() {
  561. String test = GLOBAL_DEF("internationalization/locale/test", "");
  562. test = test.strip_edges();
  563. if (!test.is_empty()) {
  564. set_locale(test);
  565. } else {
  566. set_locale(OS::get_singleton()->get_locale());
  567. }
  568. fallback = GLOBAL_DEF("internationalization/locale/fallback", "en");
  569. pseudolocalization_enabled = GLOBAL_DEF("internationalization/pseudolocalization/use_pseudolocalization", false);
  570. pseudolocalization_accents_enabled = GLOBAL_DEF("internationalization/pseudolocalization/replace_with_accents", true);
  571. pseudolocalization_double_vowels_enabled = GLOBAL_DEF("internationalization/pseudolocalization/double_vowels", false);
  572. pseudolocalization_fake_bidi_enabled = GLOBAL_DEF("internationalization/pseudolocalization/fake_bidi", false);
  573. pseudolocalization_override_enabled = GLOBAL_DEF("internationalization/pseudolocalization/override", false);
  574. expansion_ratio = GLOBAL_DEF("internationalization/pseudolocalization/expansion_ratio", 0.0);
  575. pseudolocalization_prefix = GLOBAL_DEF("internationalization/pseudolocalization/prefix", "[");
  576. pseudolocalization_suffix = GLOBAL_DEF("internationalization/pseudolocalization/suffix", "]");
  577. pseudolocalization_skip_placeholders_enabled = GLOBAL_DEF("internationalization/pseudolocalization/skip_placeholders", true);
  578. #ifdef TOOLS_ENABLED
  579. ProjectSettings::get_singleton()->set_custom_property_info("internationalization/locale/fallback", PropertyInfo(Variant::STRING, "internationalization/locale/fallback", PROPERTY_HINT_LOCALE_ID, ""));
  580. #endif
  581. }
  582. void TranslationServer::set_tool_translation(const Ref<Translation> &p_translation) {
  583. tool_translation = p_translation;
  584. }
  585. Ref<Translation> TranslationServer::get_tool_translation() const {
  586. return tool_translation;
  587. }
  588. String TranslationServer::get_tool_locale() {
  589. #ifdef TOOLS_ENABLED
  590. if (Engine::get_singleton()->is_editor_hint() || Engine::get_singleton()->is_project_manager_hint()) {
  591. if (TranslationServer::get_singleton()->get_tool_translation().is_valid()) {
  592. return tool_translation->get_locale();
  593. } else {
  594. return "en";
  595. }
  596. } else {
  597. #else
  598. {
  599. #endif
  600. return get_locale();
  601. }
  602. }
  603. StringName TranslationServer::tool_translate(const StringName &p_message, const StringName &p_context) const {
  604. if (tool_translation.is_valid()) {
  605. StringName r = tool_translation->get_message(p_message, p_context);
  606. if (r) {
  607. return editor_pseudolocalization ? tool_pseudolocalize(r) : r;
  608. }
  609. }
  610. return editor_pseudolocalization ? tool_pseudolocalize(p_message) : p_message;
  611. }
  612. StringName TranslationServer::tool_translate_plural(const StringName &p_message, const StringName &p_message_plural, int p_n, const StringName &p_context) const {
  613. if (tool_translation.is_valid()) {
  614. StringName r = tool_translation->get_plural_message(p_message, p_message_plural, p_n, p_context);
  615. if (r) {
  616. return r;
  617. }
  618. }
  619. if (p_n == 1) {
  620. return p_message;
  621. }
  622. return p_message_plural;
  623. }
  624. void TranslationServer::set_doc_translation(const Ref<Translation> &p_translation) {
  625. doc_translation = p_translation;
  626. }
  627. StringName TranslationServer::doc_translate(const StringName &p_message, const StringName &p_context) const {
  628. if (doc_translation.is_valid()) {
  629. StringName r = doc_translation->get_message(p_message, p_context);
  630. if (r) {
  631. return r;
  632. }
  633. }
  634. return p_message;
  635. }
  636. StringName TranslationServer::doc_translate_plural(const StringName &p_message, const StringName &p_message_plural, int p_n, const StringName &p_context) const {
  637. if (doc_translation.is_valid()) {
  638. StringName r = doc_translation->get_plural_message(p_message, p_message_plural, p_n, p_context);
  639. if (r) {
  640. return r;
  641. }
  642. }
  643. if (p_n == 1) {
  644. return p_message;
  645. }
  646. return p_message_plural;
  647. }
  648. bool TranslationServer::is_pseudolocalization_enabled() const {
  649. return pseudolocalization_enabled;
  650. }
  651. void TranslationServer::set_pseudolocalization_enabled(bool p_enabled) {
  652. pseudolocalization_enabled = p_enabled;
  653. if (OS::get_singleton()->get_main_loop()) {
  654. OS::get_singleton()->get_main_loop()->notification(MainLoop::NOTIFICATION_TRANSLATION_CHANGED);
  655. }
  656. ResourceLoader::reload_translation_remaps();
  657. }
  658. void TranslationServer::set_editor_pseudolocalization(bool p_enabled) {
  659. editor_pseudolocalization = p_enabled;
  660. }
  661. void TranslationServer::reload_pseudolocalization() {
  662. pseudolocalization_accents_enabled = GLOBAL_GET("internationalization/pseudolocalization/replace_with_accents");
  663. pseudolocalization_double_vowels_enabled = GLOBAL_GET("internationalization/pseudolocalization/double_vowels");
  664. pseudolocalization_fake_bidi_enabled = GLOBAL_GET("internationalization/pseudolocalization/fake_bidi");
  665. pseudolocalization_override_enabled = GLOBAL_GET("internationalization/pseudolocalization/override");
  666. expansion_ratio = GLOBAL_GET("internationalization/pseudolocalization/expansion_ratio");
  667. pseudolocalization_prefix = GLOBAL_GET("internationalization/pseudolocalization/prefix");
  668. pseudolocalization_suffix = GLOBAL_GET("internationalization/pseudolocalization/suffix");
  669. pseudolocalization_skip_placeholders_enabled = GLOBAL_GET("internationalization/pseudolocalization/skip_placeholders");
  670. if (OS::get_singleton()->get_main_loop()) {
  671. OS::get_singleton()->get_main_loop()->notification(MainLoop::NOTIFICATION_TRANSLATION_CHANGED);
  672. }
  673. ResourceLoader::reload_translation_remaps();
  674. }
  675. StringName TranslationServer::pseudolocalize(const StringName &p_message) const {
  676. String message = p_message;
  677. int length = message.length();
  678. if (pseudolocalization_override_enabled) {
  679. message = get_override_string(message);
  680. }
  681. if (pseudolocalization_double_vowels_enabled) {
  682. message = double_vowels(message);
  683. }
  684. if (pseudolocalization_accents_enabled) {
  685. message = replace_with_accented_string(message);
  686. }
  687. if (pseudolocalization_fake_bidi_enabled) {
  688. message = wrap_with_fakebidi_characters(message);
  689. }
  690. StringName res = add_padding(message, length);
  691. return res;
  692. }
  693. StringName TranslationServer::tool_pseudolocalize(const StringName &p_message) const {
  694. String message = p_message;
  695. message = double_vowels(message);
  696. message = replace_with_accented_string(message);
  697. StringName res = "[!!! " + message + " !!!]";
  698. return res;
  699. }
  700. String TranslationServer::get_override_string(String &p_message) const {
  701. String res;
  702. for (int i = 0; i < p_message.size(); i++) {
  703. if (pseudolocalization_skip_placeholders_enabled && is_placeholder(p_message, i)) {
  704. res += p_message[i];
  705. res += p_message[i + 1];
  706. i++;
  707. continue;
  708. }
  709. res += '*';
  710. }
  711. return res;
  712. }
  713. String TranslationServer::double_vowels(String &p_message) const {
  714. String res;
  715. for (int i = 0; i < p_message.size(); i++) {
  716. if (pseudolocalization_skip_placeholders_enabled && is_placeholder(p_message, i)) {
  717. res += p_message[i];
  718. res += p_message[i + 1];
  719. i++;
  720. continue;
  721. }
  722. res += p_message[i];
  723. if (p_message[i] == 'a' || p_message[i] == 'e' || p_message[i] == 'i' || p_message[i] == 'o' || p_message[i] == 'u' ||
  724. p_message[i] == 'A' || p_message[i] == 'E' || p_message[i] == 'I' || p_message[i] == 'O' || p_message[i] == 'U') {
  725. res += p_message[i];
  726. }
  727. }
  728. return res;
  729. };
  730. String TranslationServer::replace_with_accented_string(String &p_message) const {
  731. String res;
  732. for (int i = 0; i < p_message.size(); i++) {
  733. if (pseudolocalization_skip_placeholders_enabled && is_placeholder(p_message, i)) {
  734. res += p_message[i];
  735. res += p_message[i + 1];
  736. i++;
  737. continue;
  738. }
  739. const char32_t *accented = get_accented_version(p_message[i]);
  740. if (accented) {
  741. res += accented;
  742. } else {
  743. res += p_message[i];
  744. }
  745. }
  746. return res;
  747. }
  748. String TranslationServer::wrap_with_fakebidi_characters(String &p_message) const {
  749. String res;
  750. char32_t fakebidiprefix = U'\u202e';
  751. char32_t fakebidisuffix = U'\u202c';
  752. res += fakebidiprefix;
  753. // The fake bidi unicode gets popped at every newline so pushing it back at every newline.
  754. for (int i = 0; i < p_message.size(); i++) {
  755. if (p_message[i] == '\n') {
  756. res += fakebidisuffix;
  757. res += p_message[i];
  758. res += fakebidiprefix;
  759. } else if (pseudolocalization_skip_placeholders_enabled && is_placeholder(p_message, i)) {
  760. res += fakebidisuffix;
  761. res += p_message[i];
  762. res += p_message[i + 1];
  763. res += fakebidiprefix;
  764. i++;
  765. } else {
  766. res += p_message[i];
  767. }
  768. }
  769. res += fakebidisuffix;
  770. return res;
  771. }
  772. String TranslationServer::add_padding(const String &p_message, int p_length) const {
  773. String res;
  774. String prefix = pseudolocalization_prefix;
  775. String suffix;
  776. for (int i = 0; i < p_length * expansion_ratio / 2; i++) {
  777. prefix += "_";
  778. suffix += "_";
  779. }
  780. suffix += pseudolocalization_suffix;
  781. res += prefix;
  782. res += p_message;
  783. res += suffix;
  784. return res;
  785. }
  786. const char32_t *TranslationServer::get_accented_version(char32_t p_character) const {
  787. if (!is_ascii_char(p_character)) {
  788. return nullptr;
  789. }
  790. for (unsigned int i = 0; i < sizeof(_character_to_accented) / sizeof(_character_to_accented[0]); i++) {
  791. if (_character_to_accented[i].character == p_character) {
  792. return _character_to_accented[i].accented_character;
  793. }
  794. }
  795. return nullptr;
  796. }
  797. bool TranslationServer::is_placeholder(String &p_message, int p_index) const {
  798. return p_index < p_message.size() - 1 && p_message[p_index] == '%' &&
  799. (p_message[p_index + 1] == 's' || p_message[p_index + 1] == 'c' || p_message[p_index + 1] == 'd' ||
  800. p_message[p_index + 1] == 'o' || p_message[p_index + 1] == 'x' || p_message[p_index + 1] == 'X' || p_message[p_index + 1] == 'f');
  801. }
  802. void TranslationServer::_bind_methods() {
  803. ClassDB::bind_method(D_METHOD("set_locale", "locale"), &TranslationServer::set_locale);
  804. ClassDB::bind_method(D_METHOD("get_locale"), &TranslationServer::get_locale);
  805. ClassDB::bind_method(D_METHOD("get_tool_locale"), &TranslationServer::get_tool_locale);
  806. ClassDB::bind_method(D_METHOD("compare_locales", "locale_a", "locale_b"), &TranslationServer::compare_locales);
  807. ClassDB::bind_method(D_METHOD("standardize_locale", "locale"), &TranslationServer::standardize_locale);
  808. ClassDB::bind_method(D_METHOD("get_all_languages"), &TranslationServer::get_all_languages);
  809. ClassDB::bind_method(D_METHOD("get_language_name", "language"), &TranslationServer::get_language_name);
  810. ClassDB::bind_method(D_METHOD("get_all_scripts"), &TranslationServer::get_all_scripts);
  811. ClassDB::bind_method(D_METHOD("get_script_name", "script"), &TranslationServer::get_script_name);
  812. ClassDB::bind_method(D_METHOD("get_all_countries"), &TranslationServer::get_all_countries);
  813. ClassDB::bind_method(D_METHOD("get_country_name", "country"), &TranslationServer::get_country_name);
  814. ClassDB::bind_method(D_METHOD("get_locale_name", "locale"), &TranslationServer::get_locale_name);
  815. ClassDB::bind_method(D_METHOD("translate", "message", "context"), &TranslationServer::translate, DEFVAL(""));
  816. ClassDB::bind_method(D_METHOD("translate_plural", "message", "plural_message", "n", "context"), &TranslationServer::translate_plural, DEFVAL(""));
  817. ClassDB::bind_method(D_METHOD("add_translation", "translation"), &TranslationServer::add_translation);
  818. ClassDB::bind_method(D_METHOD("remove_translation", "translation"), &TranslationServer::remove_translation);
  819. ClassDB::bind_method(D_METHOD("get_translation_object", "locale"), &TranslationServer::get_translation_object);
  820. ClassDB::bind_method(D_METHOD("clear"), &TranslationServer::clear);
  821. ClassDB::bind_method(D_METHOD("get_loaded_locales"), &TranslationServer::get_loaded_locales);
  822. ClassDB::bind_method(D_METHOD("is_pseudolocalization_enabled"), &TranslationServer::is_pseudolocalization_enabled);
  823. ClassDB::bind_method(D_METHOD("set_pseudolocalization_enabled", "enabled"), &TranslationServer::set_pseudolocalization_enabled);
  824. ClassDB::bind_method(D_METHOD("reload_pseudolocalization"), &TranslationServer::reload_pseudolocalization);
  825. ClassDB::bind_method(D_METHOD("pseudolocalize", "message"), &TranslationServer::pseudolocalize);
  826. ADD_PROPERTY(PropertyInfo(Variant::Type::BOOL, "pseudolocalization_enabled"), "set_pseudolocalization_enabled", "is_pseudolocalization_enabled");
  827. }
  828. void TranslationServer::load_translations() {
  829. _load_translations("internationalization/locale/translations"); //all
  830. _load_translations("internationalization/locale/translations_" + locale.substr(0, 2));
  831. if (locale.substr(0, 2) != locale) {
  832. _load_translations("internationalization/locale/translations_" + locale);
  833. }
  834. }
  835. TranslationServer::TranslationServer() {
  836. singleton = this;
  837. init_locale_info();
  838. }