translation.cpp 35 KB

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