translation.cpp 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028
  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. // Look for best matching loaded translation.
  612. String best_locale = "en";
  613. int best_score = 0;
  614. for (const Ref<Translation> &E : translations) {
  615. const Ref<Translation> &t = E;
  616. ERR_FAIL_COND_V(t.is_null(), best_locale);
  617. String l = t->get_locale();
  618. int score = compare_locales(locale, l);
  619. if (score > 0 && score >= best_score) {
  620. best_locale = l;
  621. best_score = score;
  622. if (score == 10) {
  623. break; // Exact match, skip the rest.
  624. }
  625. }
  626. }
  627. return best_locale;
  628. }
  629. }
  630. StringName TranslationServer::tool_translate(const StringName &p_message, const StringName &p_context) const {
  631. if (tool_translation.is_valid()) {
  632. StringName r = tool_translation->get_message(p_message, p_context);
  633. if (r) {
  634. return editor_pseudolocalization ? tool_pseudolocalize(r) : r;
  635. }
  636. }
  637. return editor_pseudolocalization ? tool_pseudolocalize(p_message) : p_message;
  638. }
  639. StringName TranslationServer::tool_translate_plural(const StringName &p_message, const StringName &p_message_plural, int p_n, const StringName &p_context) const {
  640. if (tool_translation.is_valid()) {
  641. StringName r = tool_translation->get_plural_message(p_message, p_message_plural, p_n, p_context);
  642. if (r) {
  643. return r;
  644. }
  645. }
  646. if (p_n == 1) {
  647. return p_message;
  648. }
  649. return p_message_plural;
  650. }
  651. void TranslationServer::set_doc_translation(const Ref<Translation> &p_translation) {
  652. doc_translation = p_translation;
  653. }
  654. StringName TranslationServer::doc_translate(const StringName &p_message, const StringName &p_context) const {
  655. if (doc_translation.is_valid()) {
  656. StringName r = doc_translation->get_message(p_message, p_context);
  657. if (r) {
  658. return r;
  659. }
  660. }
  661. return p_message;
  662. }
  663. StringName TranslationServer::doc_translate_plural(const StringName &p_message, const StringName &p_message_plural, int p_n, const StringName &p_context) const {
  664. if (doc_translation.is_valid()) {
  665. StringName r = doc_translation->get_plural_message(p_message, p_message_plural, p_n, p_context);
  666. if (r) {
  667. return r;
  668. }
  669. }
  670. if (p_n == 1) {
  671. return p_message;
  672. }
  673. return p_message_plural;
  674. }
  675. void TranslationServer::set_property_translation(const Ref<Translation> &p_translation) {
  676. property_translation = p_translation;
  677. }
  678. StringName TranslationServer::property_translate(const StringName &p_message) const {
  679. if (property_translation.is_valid()) {
  680. StringName r = property_translation->get_message(p_message);
  681. if (r) {
  682. return r;
  683. }
  684. }
  685. return p_message;
  686. }
  687. bool TranslationServer::is_pseudolocalization_enabled() const {
  688. return pseudolocalization_enabled;
  689. }
  690. void TranslationServer::set_pseudolocalization_enabled(bool p_enabled) {
  691. pseudolocalization_enabled = p_enabled;
  692. if (OS::get_singleton()->get_main_loop()) {
  693. OS::get_singleton()->get_main_loop()->notification(MainLoop::NOTIFICATION_TRANSLATION_CHANGED);
  694. }
  695. ResourceLoader::reload_translation_remaps();
  696. }
  697. void TranslationServer::set_editor_pseudolocalization(bool p_enabled) {
  698. editor_pseudolocalization = p_enabled;
  699. }
  700. void TranslationServer::reload_pseudolocalization() {
  701. pseudolocalization_accents_enabled = GLOBAL_GET("internationalization/pseudolocalization/replace_with_accents");
  702. pseudolocalization_double_vowels_enabled = GLOBAL_GET("internationalization/pseudolocalization/double_vowels");
  703. pseudolocalization_fake_bidi_enabled = GLOBAL_GET("internationalization/pseudolocalization/fake_bidi");
  704. pseudolocalization_override_enabled = GLOBAL_GET("internationalization/pseudolocalization/override");
  705. expansion_ratio = GLOBAL_GET("internationalization/pseudolocalization/expansion_ratio");
  706. pseudolocalization_prefix = GLOBAL_GET("internationalization/pseudolocalization/prefix");
  707. pseudolocalization_suffix = GLOBAL_GET("internationalization/pseudolocalization/suffix");
  708. pseudolocalization_skip_placeholders_enabled = GLOBAL_GET("internationalization/pseudolocalization/skip_placeholders");
  709. if (OS::get_singleton()->get_main_loop()) {
  710. OS::get_singleton()->get_main_loop()->notification(MainLoop::NOTIFICATION_TRANSLATION_CHANGED);
  711. }
  712. ResourceLoader::reload_translation_remaps();
  713. }
  714. StringName TranslationServer::pseudolocalize(const StringName &p_message) const {
  715. String message = p_message;
  716. int length = message.length();
  717. if (pseudolocalization_override_enabled) {
  718. message = get_override_string(message);
  719. }
  720. if (pseudolocalization_double_vowels_enabled) {
  721. message = double_vowels(message);
  722. }
  723. if (pseudolocalization_accents_enabled) {
  724. message = replace_with_accented_string(message);
  725. }
  726. if (pseudolocalization_fake_bidi_enabled) {
  727. message = wrap_with_fakebidi_characters(message);
  728. }
  729. StringName res = add_padding(message, length);
  730. return res;
  731. }
  732. StringName TranslationServer::tool_pseudolocalize(const StringName &p_message) const {
  733. String message = p_message;
  734. message = double_vowels(message);
  735. message = replace_with_accented_string(message);
  736. StringName res = "[!!! " + message + " !!!]";
  737. return res;
  738. }
  739. String TranslationServer::get_override_string(String &p_message) const {
  740. String res;
  741. for (int i = 0; i < p_message.size(); i++) {
  742. if (pseudolocalization_skip_placeholders_enabled && is_placeholder(p_message, i)) {
  743. res += p_message[i];
  744. res += p_message[i + 1];
  745. i++;
  746. continue;
  747. }
  748. res += '*';
  749. }
  750. return res;
  751. }
  752. String TranslationServer::double_vowels(String &p_message) const {
  753. String res;
  754. for (int i = 0; i < p_message.size(); i++) {
  755. if (pseudolocalization_skip_placeholders_enabled && is_placeholder(p_message, i)) {
  756. res += p_message[i];
  757. res += p_message[i + 1];
  758. i++;
  759. continue;
  760. }
  761. res += p_message[i];
  762. if (p_message[i] == 'a' || p_message[i] == 'e' || p_message[i] == 'i' || p_message[i] == 'o' || p_message[i] == 'u' ||
  763. p_message[i] == 'A' || p_message[i] == 'E' || p_message[i] == 'I' || p_message[i] == 'O' || p_message[i] == 'U') {
  764. res += p_message[i];
  765. }
  766. }
  767. return res;
  768. };
  769. String TranslationServer::replace_with_accented_string(String &p_message) const {
  770. String res;
  771. for (int i = 0; i < p_message.size(); i++) {
  772. if (pseudolocalization_skip_placeholders_enabled && is_placeholder(p_message, i)) {
  773. res += p_message[i];
  774. res += p_message[i + 1];
  775. i++;
  776. continue;
  777. }
  778. const char32_t *accented = get_accented_version(p_message[i]);
  779. if (accented) {
  780. res += accented;
  781. } else {
  782. res += p_message[i];
  783. }
  784. }
  785. return res;
  786. }
  787. String TranslationServer::wrap_with_fakebidi_characters(String &p_message) const {
  788. String res;
  789. char32_t fakebidiprefix = U'\u202e';
  790. char32_t fakebidisuffix = U'\u202c';
  791. res += fakebidiprefix;
  792. // The fake bidi unicode gets popped at every newline so pushing it back at every newline.
  793. for (int i = 0; i < p_message.size(); i++) {
  794. if (p_message[i] == '\n') {
  795. res += fakebidisuffix;
  796. res += p_message[i];
  797. res += fakebidiprefix;
  798. } else if (pseudolocalization_skip_placeholders_enabled && is_placeholder(p_message, i)) {
  799. res += fakebidisuffix;
  800. res += p_message[i];
  801. res += p_message[i + 1];
  802. res += fakebidiprefix;
  803. i++;
  804. } else {
  805. res += p_message[i];
  806. }
  807. }
  808. res += fakebidisuffix;
  809. return res;
  810. }
  811. String TranslationServer::add_padding(const String &p_message, int p_length) const {
  812. String res;
  813. String prefix = pseudolocalization_prefix;
  814. String suffix;
  815. for (int i = 0; i < p_length * expansion_ratio / 2; i++) {
  816. prefix += "_";
  817. suffix += "_";
  818. }
  819. suffix += pseudolocalization_suffix;
  820. res += prefix;
  821. res += p_message;
  822. res += suffix;
  823. return res;
  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. }