misc/localization
로컬라이제이션.
- 원본 misc/localization.js 를 옮긴 것이다. 언어 자동 감지, 번역 테이블, {0}{1} 자리 표시자 바꾸기, 폴백을 한 곳에 모았다.
- 키는 원문 그대로 써도 된다. 표에 없으면 원문(키)을 그대로 돌려주므로 조금씩 번역해 나갈 수 있다.
- 사용:
Localization::set_table("en", [("확인", "OK"), ("{0}점 획득", "Got {0} points")]);
Localization::set_language(&Localization::detect_language(&["ko", "en"], "ko"));
Localization::text("{0}점 획득", &[&120]);- 원본과 다른 점: 원본은 클래스의 정적 필드에 표를 든다. 러스트 판은 스레드 하나의 전역 상태로 든다. (엔진은 한 스레드에서 돈다) 표의 값은 글 하나 또는 글 목록(LocalizationValue)이다. JSON 표(JsonAsset 으로 읽은 것)는 set_table_from_json 으로 넣는다. text 의 가변 인자는 Display 참조 목록(&[&dyn Display])이다.
- 외계행성 광부 키우기에서 엔진으로 옮긴 것: 언어 태그를 뒤 조각부터 하나씩 떼며 맞추기와 별칭(set_language_aliases), 오른쪽에서 왼쪽으로 쓰는 언어(is_right_to_left, set_right_to_left)와 넣는 값을 방향 격리 문자로 묶기(isolate_text), 이름 자리 채우기(text_named, "{seconds}" 꼴, 빗금으로만 이은 값들은 통째로 한 번 묶는다). 배치 뒤집기(mirror_layout_x, read_layout_text_align, 원본 LanguagePack 의 mirrorLayoutX, readLayoutTextAlign). detect_language 는 웹에서 원본처럼 navigator.languages 를 읽고, 데스크탑에서는 sys-locale 로 시스템의 선호 언어 차례를 읽는다. (윈도우 GetUserPreferredUILanguages, 맥 CFLocaleCopyPreferredLanguages, 리눅스 LANGUAGE / LC_ALL / LC_MESSAGES / LANG 환경 변수)
Localization.
- A port of the original misc/localization.js. Gathers automatic language detection, translation tables, {0}{1} placeholder substitution, and fallback in one place.
- Keys can be the source text as is. If a key is not in the table, the source text (the key) is returned as is, so you can translate bit by bit.
- Usage:
Localization::set_table("en", [("Confirm", "OK"), ("{0} points earned", "Got {0} points")]);
Localization::set_language(&Localization::detect_language(&["ko", "en"], "ko"));
Localization::text("{0} points earned", &[&120]);- Differences from the original: The original holds the tables in static fields of the class. The Rust version holds them in thread-local global state. (the engine runs on one thread) A table value is one string or a list of strings (LocalizationValue). A JSON table (read with JsonAsset) is put in with set_table_from_json. The variadic arguments of text are a list of Display references (&[&dyn Display]).
- Brought into the engine from Exoplanet Miner: matching language tags by dropping trailing parts one by one, and aliases (set_language_aliases), right-to-left languages (is_right_to_left, set_right_to_left) and wrapping inserted values in directional isolate characters (isolate_text), filling named placeholders (text_named, "{seconds}" style, values joined only by slashes are wrapped once as a whole). Layout mirroring (mirror_layout_x, read_layout_text_align, mirrorLayoutX, readLayoutTextAlign of the original LanguagePack). On the web detect_language reads navigator.languages as in the original, and on desktop it reads the system's preferred language order with sys-locale. (Windows GetUserPreferredUILanguages, Mac CFLocaleCopyPreferredLanguages, Linux LANGUAGE / LC_ALL / LC_MESSAGES / LANG environment variables)
LocalizationTabletype
번역 표. (키(원문) → 번역 값)
Translation table. (key (source text) → translated value)
pub type LocalizationTable = HashMap<String, LocalizationValue>Localizationstruct
로컬라이제이션. (정적 함수 묶음)
- 상태는 스레드 하나의 전역이다. 처음 쓸 때 지금 언어와 폴백 언어가 "ko" 다.
Localization. (a set of static functions)
- The state is thread-local global. On first use, the current language and the fallback language are "ko".
use vanilla::Localization;
Localization::set_table("fr", [("OK", "D'accord"), ("Got {0} points", "{0} points gagnes")]);
Localization::set_language(&Localization::detect_language(&["fr"], "fr"));
assert_eq!(Localization::get_language(), "fr");
assert_eq!(Localization::text("OK", &[]), "D'accord");
assert_eq!(Localization::text("Got {0} points", &[&120]), "120 points gagnes");
assert_eq!(Localization::text("Not translated yet", &[]), "Not translated yet");pub fn detect_language(supported_language_codes: &[&str], default_language_code: &str) -> String#사용자 언어 감지. (선호 언어 순서대로 지원 목록에 있는 첫 언어, 없으면 기본 언어)
- "zh-TW" 같은 지역 표기는 "zh-tw" → "zh" 순으로 대조한다.
- 선호 언어는 웹이면 navigator.languages, 데스크탑이면 시스템 선호 언어 차례다.
Detects the user language. (the first language in preferred order that is in the supported list, otherwise the default language)
- Regional forms like "zh-TW" are matched in the order "zh-tw" → "zh".
- Preferred languages are navigator.languages on the web, and the system preferred language order on desktop.
- supported_language_codes&[&str]
- 게임이 지원하는 언어 코드 목록. (대소문자 상관없다)List of language codes the game supports. (case insensitive)
- default_language_code&str
- 맞는 것이 없을 때 쓸 언어 코드.Language code to use when nothing matches.
반환ReturnsString 맞은 언어 코드. (소문자) 없으면 default_language_code 그대로.The matched language code. (lowercase) default_language_code as is if none.
짝Counterpart: vanilla.js Localization.detectLanguage
pub fn select_language(candidate_list: &[String], supported_language_codes: &[&str], default_language_code: &str) -> String#선호 언어 목록에서 지원하는 첫 언어 고르기. (detect_language 의 대조 부분)
- 태그의 뒤 조각부터 하나씩 떼며 지원 목록의 코드와 별칭을 본다. ("zh-Hant-TW" → "zh-hant-tw", "zh-hant", "zh", 밑줄은 하이픈으로)
Picks the first supported language from a preferred language list. (the matching part of detect_language)
- Drops trailing parts of the tag one by one and checks the codes and aliases of the supported list. ("zh-Hant-TW" → "zh-hant-tw", "zh-hant", "zh", underscores become hyphens)
- candidate_list&[String]
- 선호 언어 태그 목록. (앞이 먼저)List of preferred language tags. (earlier first)
- supported_language_codes&[&str]
- 지원하는 언어 코드 목록. (대소문자 상관없다)List of supported language codes. (case insensitive)
- default_language_code&str
- 맞는 것이 없을 때 쓸 언어 코드.Language code to use when nothing matches.
반환ReturnsString 처음 맞은 지원 언어 코드. (소문자, 별칭으로 맞았으면 그 별칭의 언어) 없으면 default_language_code 그대로.The first matched supported language code. (lowercase, the alias's language if matched by an alias) default_language_code as is if none.
짝Counterpart: vanilla.js Localization.selectLanguage
use vanilla::Localization;
let candidate_list = vec![String::from("zh-TW"), String::from("en-US")];
assert_eq!(Localization::select_language(&candidate_list, &["ko", "zh-tw", "en"], "ko"), "zh-tw");
assert_eq!(Localization::select_language(&candidate_list, &["ko", "en"], "ko"), "en");
assert_eq!(Localization::select_language(&candidate_list, &["ko"], "ko"), "ko");언어의 별칭 설정. (예: "zh-hant" 에 "zh-tw", "zh-hk", 태그를 맞출 때 별칭도 그 언어로 본다)
Sets aliases for a language. (e.g. "zh-tw", "zh-hk" for "zh-hant", aliases are treated as that language when matching tags)
- language_code&str
- 별칭이 가리킬 언어 코드. (소문자로 바꿔 든다)Language code the aliases point to. (stored lowercased)
- alias_list&[&str]
- 별칭 목록. (소문자로, 밑줄은 하이픈으로 바꿔 든다. 같은 별칭이 있으면 바꾼다)List of aliases. (stored lowercased with underscores turned into hyphens. An existing identical alias is replaced)
짝Counterpart: vanilla.js Localization.setLanguageAliases
use vanilla::Localization;
Localization::set_language_aliases("zh-hant", &["zh-tw", "zh_HK"]);
assert_eq!(Localization::select_language(&[String::from("zh_HK")], &["en", "zh-hant"], "en"), "zh-hant");오른쪽에서 왼쪽으로 쓰는 언어로 정하거나 풀기. (처음은 ar, fa, he, ur, ps, yi, dv)
Marks or unmarks a language as right-to-left. (initially ar, fa, he, ur, ps, yi, dv)
- language_code&str
- 언어 코드. (첫 조각만 쓴다, "ar-EG" 는 "ar")Language code. (only the first part is used, "ar-EG" is "ar")
- is_right_to_leftbool
- true 면 넣고, false 면 뺀다.Adds if true, removes if false.
짝Counterpart: vanilla.js Localization.setRightToLeft
지금 언어가 오른쪽에서 왼쪽으로 쓰는 언어인지. (글자를 그 방향으로 굽고 배치를 좌우로 뒤집을 때)
- set_right_to_left 처럼 소문자로, 밑줄은 하이픈으로 읽은 첫 조각을 본다. ("ar_EG" 도 ar)
Whether the current language is written right to left. (when baking text in that direction and mirroring the layout left to right)
- Like set_right_to_left, looks at the first segment read in lowercase with underscores as hyphens. ("ar_EG" is also ar)
반환Returnsbool 지금 언어 코드의 첫 조각이 오른쪽에서 왼쪽 언어 목록에 있으면 true.true if the first part of the current language code is in the right-to-left language list.
짝Counterpart: vanilla.js Localization.isRightToLeft
배치의 가로 자리. (오른쪽에서 왼쪽 언어면 부모 너비 안에서 좌우를 뒤집은 왼쪽, 아니면 그대로)
- 창과 표의 왼쪽, 오른쪽 배치를 언어 방향에 맞춰 뒤집을 때 쓴다. 화면 구석의 자리나 슬라이더의 방향처럼 뒤집지 않을 것은 부르지 않는다.
Horizontal layout position. (the left position mirrored within the parent width for right-to-left languages, otherwise unchanged)
- Used to mirror the left and right placement of windows and tables to match the language direction. Do not call it for things that should not be mirrored, like screen corner positions or slider directions.
- xf64
- 왼쪽에서 오른쪽 언어일 때의 왼쪽 자리. (픽셀, 부모 왼쪽 기준)Left position for left-to-right languages. (pixels, relative to the parent's left)
- widthf64
- 배치할 것의 너비. (픽셀)Width of the thing being placed. (pixels)
- parent_widthf64
- 부모 너비. (픽셀)Parent width. (pixels)
반환Returnsf64 오른쪽에서 왼쪽 언어면 parent_width - x - width, 아니면 x.parent_width - x - width for right-to-left languages, otherwise x.
짝Counterpart: vanilla.js Localization.mirrorLayoutX
use vanilla::{Localization, TextAlign};
Localization::set_language("en");
assert_eq!(Localization::mirror_layout_x(10.0, 20.0, 100.0), 10.0);
Localization::set_language("ar");
assert_eq!(Localization::mirror_layout_x(10.0, 20.0, 100.0), 70.0);
assert_eq!(Localization::read_layout_text_align(TextAlign::Left), TextAlign::Right);배치의 글자 정렬. (오른쪽에서 왼쪽 언어면 Left 와 Right 를 바꾸고, 나머지는 그대로)
Text alignment of the layout. (swaps Left and Right for right-to-left languages, others unchanged)
- text_alignTextAlign
- 왼쪽에서 오른쪽 언어일 때의 정렬.Alignment for left-to-right languages.
반환ReturnsTextAlign 지금 언어 방향에 맞춘 정렬.Alignment matching the current language direction.
짝Counterpart: vanilla.js Localization.readLayoutTextAlign
글 사이에 끼우는 값 묶기. (오른쪽에서 왼쪽 언어면 방향 격리 문자로 묶고, 아니면 그대로)
- 숫자와 단위(123°/s, +60%)나 사람 이름이 앞뒤 글과 섞여 흩어지지 않고 제 방향으로 한 덩어리로 놓이게 한다.
Wraps a value inserted into text. (wraps it in directional isolate characters for right-to-left languages, otherwise unchanged)
- Keeps numbers and units (123°/s, +60%) or people's names in one piece in their own direction instead of scattering among the surrounding text.
- text&str
- 끼울 값의 글.Text of the value to insert.
반환ReturnsString 오른쪽에서 왼쪽 언어면 U+2068 과 U+2069 로 묶은 글. 아니거나 빈 글이면 그대로.Text wrapped in U+2068 and U+2069 for right-to-left languages. Unchanged otherwise or if empty.
짝Counterpart: vanilla.js Localization.isolateText
use vanilla::Localization;
Localization::set_language("en");
assert_eq!(Localization::isolate_text("+60%"), "+60%");
Localization::set_language("ar");
assert_eq!(Localization::isolate_text("+60%"), "\u{2068}+60%\u{2069}");이름 자리 채우기. ("Restart {seconds}" + [("seconds", &3)] → "Restart 3")
- 오른쪽에서 왼쪽 언어면 넣은 값을 방향 격리 문자로 묶는다.
- 빗금으로만 이은 값들("{count}/{limit}")은 값마다가 아니라 통째로 한 번 묶는다. (값마다 묶으면 1/40 이 40/1 로 보인다)
- 이름이 없는 자리는 그대로 둔다.
- 키는 text 처럼 지금 언어, 폴백 언어, 키 원문 차례로 찾는다. 이름은 영문과 숫자만 된다.
Fills named placeholders. ("Restart {seconds}" + [("seconds", &3)] → "Restart 3")
- For right-to-left languages, wraps inserted values in directional isolate characters.
- Values joined only by slashes ("{count}/{limit}") are wrapped once as a whole, not per value. (wrapping per value shows 1/40 as 40/1)
- Placeholders with no matching name are left as is.
- Like text, the key is looked up in the current language, the fallback language, then the key source text. Names may only contain letters and digits.
- key&str
- 번역 키. (원문)Translation key. (source text)
- values&[(&str, &dyn Display)]
- (이름, 값) 목록. 같은 이름이 여럿이면 처음 것을 쓴다.List of (name, value). If a name appears more than once, the first is used.
반환ReturnsString 이름 자리를 채운 번역문.Translated text with named placeholders filled.
짝Counterpart: vanilla.js Localization.textNamed
use vanilla::Localization;
Localization::set_language("en");
Localization::set_table("en", [("restart", "Restart {seconds}"), ("count", "{count}/{limit} workers")]);
assert_eq!(Localization::text_named("restart", &[("seconds", &3)]), "Restart 3");
assert_eq!(Localization::text_named("count", &[("count", &1), ("limit", &40)]), "1/40 workers");
assert_eq!(Localization::text_named("{who} and {other}", &[("who", &"Ann")]), "Ann and {other}");pub fn set_table<K, V>(language_code: &str, table: impl IntoIterator<Item = (K, V)>) where K: Into<String>, V: Into<LocalizationValue>,#번역 표 설정. (언어 코드는 소문자로 바꿔 든다. 같은 언어 표가 있으면 바꾼다)
Sets a translation table. (the language code is stored lowercased. An existing table for the same language is replaced)
- language_code&str
- 언어 코드.Language code.
- tableimpl IntoIterator<Item = (K, V)>
- (키, 값) 목록. 키는 String 으로, 값은 글이나 글 목록(LocalizationValue)으로 바꿀 수 있는 것.List of (key, value). Keys convertible to String, values convertible to a string or a list of strings (LocalizationValue).
짝Counterpart: vanilla.js Localization.setTable
use vanilla::{Localization, LocalizationValue};
Localization::set_table("en", [
("title", LocalizationValue::from("Mine")),
("intro", LocalizationValue::from(vec!["First line", "Second line"])),
]);
Localization::set_language("en");
assert_eq!(Localization::text("title", &[]), "Mine");
assert_eq!(Localization::text_list("intro"), vec!["First line", "Second line"]);JSON 객체로 번역 표 설정. (값이 글이면 글, 글 배열이면 목록. 그 밖의 값은 건너뛴다)
- 배열 안의 글이 아닌 값은 뺀다. 객체가 아니면 빈 표가 된다.
Sets a translation table from a JSON object. (string values become strings, string arrays become lists. Other values are skipped)
- Non-string values inside arrays are dropped. If it is not an object, the table is empty.
- language_code&str
- 언어 코드.Language code.
- table_json&serde_json::Value
- { 키: 글 또는 글 배열 } 꼴의 JSON 객체.A JSON object of the form { key: string or string array }.
짝Counterpart: vanilla.js Localization.setTableFromJson
use vanilla::Localization;
Localization::set_table_from_json("fr", &serde_json::json!({ "OK": "D'accord", "lines": ["a", "b"], "number": 3 }));
Localization::set_language("fr");
assert_eq!(Localization::text("OK", &[]), "D'accord");
assert_eq!(Localization::text_list("lines"), vec!["a", "b"]);
assert_eq!(Localization::text("number", &[]), "number");지금 언어 설정. (소문자로)
Sets the current language. (lowercased)
- language_code&str
- 언어 코드. (표의 언어 코드와 같아야 그 표를 쓴다)Language code. (must equal a table's language code to use that table)
짝Counterpart: vanilla.js Localization.setLanguage
지금 언어 반환.
Returns the current language.
반환ReturnsString 지금 언어 코드. (소문자, 처음은 "ko")The current language code. (lowercase, "ko" at first)
짝Counterpart: vanilla.js Localization.getLanguage
폴백 언어 설정. (지금 언어 표에 없으면 이 언어 표를 본다)
Sets the fallback language. (this language's table is checked when the current language's table lacks the key)
- language_code&str
- 폴백 언어 코드. (소문자로 바꿔 든다, 처음은 "ko")Fallback language code. (stored lowercased, initially "ko")
짝Counterpart: vanilla.js Localization.setFallbackLanguage
번역문 찾기. (지금 언어 → 폴백 언어 → 키 원문 순, {0} {1} ... 을 인자로 바꾼다)
- 값이 목록이면 원본처럼 키를 쓴다.
Looks up a translation. (in order: current language → fallback language → key source text, replacing {0} {1} ... with the arguments)
- If the value is a list, the key is used, as in the original.
- key&str
- 번역 키. (원문)Translation key. (source text)
- substitutions&[&dyn Display]
- {0}, {1} ... 자리에 차례로 넣을 값 목록. (Display 로 글이 된다)List of values to put into {0}, {1} ... in order. (turned into text with Display)
반환ReturnsString 자리를 바꾼 번역문. 표에 없으면 키 원문에서 자리를 바꾼 것.Translated text with placeholders replaced. If not in the table, the key source text with placeholders replaced.
짝Counterpart: vanilla.js Localization.text
use vanilla::Localization;
Localization::set_table("en", [("{0}/{1}", "{1} of {0}")]);
Localization::set_language("en");
assert_eq!(Localization::text("{0}/{1}", &[&3, &"ten"]), "ten of 3");
assert_eq!(Localization::text("Missing {0}", &[&1.5]), "Missing 1.5");목록형 번역 찾기. (대사 목록처럼 여러 줄인 항목. 글 하나면 한 줄짜리 목록, 없으면 [키])
Looks up a list translation. (an entry with several lines, like a dialogue list. A single string gives a one-line list, none gives [key])
- key&str
- 번역 키.Translation key.
반환ReturnsVec<String> 찾은 글 목록. 자리 표시자는 바꾸지 않는다.The found list of strings. Placeholders are not replaced.
짝Counterpart: vanilla.js Localization.textList
값 그대로 찾기. (지금 언어 → 폴백 언어, 없으면 None)
Looks up the raw value. (current language → fallback language, None if none)
- key&str
- 번역 키.Translation key.
반환ReturnsOption<LocalizationValue> 찾은 값의 복사본. 두 표 모두에 없으면 None.A copy of the found value. None if in neither table.
짝Counterpart: vanilla.js Localization.lookup
모든 표 비우기. (시험용, 언어 설정은 그대로)
Clears all tables. (for tests, the language settings stay)
짝Counterpart: vanilla.js Localization.clear
LocalizationValueenum traits Clone, Debug, PartialEq, Eq, From<&str>, From<String>, From<Vec<String>>, From<Vec<&str>>
번역 값. (원본 표의 값: 문자열 또는 문자열 배열)
Translation value. (a value of the original table: a string or an array of strings)
| 이름Name | 값Value | 설명Description |
|---|---|---|
Text | Text(String) | 글 하나. (text 로 읽는다)One string. (read with text) |
TextList | TextList(Vec<String>) | 글 목록. (대사처럼 여러 줄인 항목, text_list 로 읽는다)List of strings. (an entry with several lines, like dialogue, read with text_list) |