translation.cpp 34 KB

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