vanilladocs
vanillapunch.com
API / misc/languagepack

misc/languagepack

언어 묶음. (원본 misc/languagepack.js 의 LanguagePack, 자산의 표로 두는 화면 글자의 언어)

  • Localization(코드 안의 표)과 달리 글자를 자산의 JSON 파일로 둔다. 언어가 많고 번역가가 파일을 따로 고치는 게임에 쓴다.
  • 경로는 set_language_paths 로 정한다. (처음은 ./assets/localization/languages.json 과 그 폴더)
  • 언어의 목록은 languages.json({ fallbackLanguage, languages: [{ code, name, englishName, fontGroup, direction, aliases, countries, file }] })이고, 언어마다 한 파일(열쇠 → 글자)이다. 설정의 언어가 비어 있으면 플랫폼이 알려 준 언어(set_preferred_language_tag), 그다음 기기의 언어를 따르고, 목록에 없으면 기본 언어(영어)이다. 고른 언어의 표에 없는 열쇠는 기본 언어의 글자로, 거기에도 없으면 열쇠 그대로 쓴다.
  • 언어를 불러오면 페이지의 언어(html lang)와 제목(set_document_title_key 의 열쇠, 처음은 game.title)을 그 언어로 바꾼다. 언어는 Document::set_language 로 쓴다. (웹은 html 의 lang, 데스크탑은 엔진이 든 문서 언어. Document::get_language 로 읽는다) 제목은 창 제목이다.
  • 원본과 다른 것: 원본은 async 함수로 기다린다. 러스트 판은 엔진의 "요청 → 나중에 다 읽힘" 꼴이라 load_language_list, load_language, apply_language_setting 이 읽기를 요청하고, 프레임마다 update(engine) 를 불러야 이어 간다. (데스크탑은 그 자리에서 읽혀 요청한 함수 안에서 끝난다) is_loading 으로 기다린다. load_language_list, load_language, apply_language_setting 은 원본처럼 await 할 수 있는 LanguageLoadHandle 을 돌려준다. (엔진 작업 안에서 scene_context.with(|_, 엔진| languagepack::load_language(엔진, 코드)).await, 기다리는 동안 프레임마다 update 를 불러 준다) 원본 applyLanguageSetting 은 불러온 뒤 함수가 돌려준 Promise 까지 기다린다. 퓨처를 돌려주는 함수는 set_language_loaded_async_handler 로 걸고, 엔진이 그 퓨처를 엔진 작업으로 돌려 끝날 때까지 불러오는 중으로 친다. (손잡이의 await 도 그때까지 기다린다) 전역 상태는 스레드 하나의 thread_local 이다. (원본 모듈 변수) 언어 한 줄은 LanguageEntry 구조체다. 불러온 뒤 부를 함수(set_language_loaded_handler)는 (엔진, 언어 한 줄, 모든 글자) 를 받는다. (원본 (언어, 모든 글자), 엔진은 글꼴 받기에 쓴다)

Language pack. (LanguagePack of the original misc/languagepack.js, languages for on-screen text kept as asset tables)

  • Unlike Localization (tables in code), the text is kept in asset JSON files. Use it for games with many languages where translators edit the files separately.
  • Paths are set with set_language_paths. (initially ./assets/localization/languages.json and its folder)
  • The language list is languages.json ({ fallbackLanguage, languages: [{ code, name, englishName, fontGroup, direction, aliases, countries, file }] }), with one file per language (key → text). If the language setting is empty, it follows the language reported by the platform (set_preferred_language_tag), then the device language, and if not in the list, the default language (English). Keys missing from the chosen language's table use the default language's text, and if missing there too, the key as is.
  • Loading a language changes the page language (html lang) and title (the key from set_document_title_key, initially game.title) to that language. The language is written with Document::set_language. (the html lang on the web, the language of the document held by the engine on desktop. Read with Document::get_language) The title is the window title.
  • Differences from the original:
The original waits with async functions. The Rust version follows the engine's "request → fully loaded later" pattern, so load_language_list, load_language, apply_language_setting
request the read, and update(engine) must be called every frame to continue. (on desktop it is read on the spot and finishes inside the requesting function) Wait with is_loading.
load_language_list, load_language, apply_language_setting return a LanguageLoadHandle that can be awaited, as in the original.
(inside an engine task, scene_context.with(|_, engine| languagepack::load_language(engine, code)).await, and update is called every frame while waiting)
The original applyLanguageSetting also waits for the Promise returned by the function after loading. A function returning a future is set with set_language_loaded_async_handler,
and the engine runs that future as an engine task and counts it as loading until it finishes. (awaiting the handle also waits until then)
The global state is a thread_local on one thread. (original module variables) One language row is the LanguageEntry struct.
The function to call after loading (set_language_loaded_handler) receives (engine, language row, all text). (original (language, all text), the engine is used for fetching fonts)
예제Example파일 없이 목록과 표를 바로 넣고 번역하기Put the list and tables in directly without files and translate
use vanilla::languagepack;

let language_list_json = r#"{ "fallbackLanguage": "en", "languages": [
	{ "code": "en", "name": "English", "direction": "ltr", "file": "en.json" },
	{ "code": "ar", "name": "Arabic", "direction": "rtl", "file": "ar.json" }
] }"#;
assert!(languagepack::set_language_list_from_json(language_list_json));
assert!(languagepack::set_language_texts_from_json("en", r#"{ "game.title": "Mine" }"#, r#"{ "game.title": "Mine", "menu.start": "Start" }"#));
assert_eq!(languagepack::read_language_code(), "en");
assert_eq!(languagepack::translate("game.title"), "Mine");
assert_eq!(languagepack::translate("menu.start"), "Start");
assert_eq!(languagepack::translate("menu.unknown"), "menu.unknown");

LanguageEntrystruct traits Clone, Debug, Default, PartialEq, Eq

소스source

언어 목록의 한 줄. (원본 { code, name, englishName, fontGroup, direction, aliases, countries, file })

One row of the language list. (the original { code, name, englishName, fontGroup, direction, aliases, countries, file })

예제ExampleJSON 한 줄에서 읽기Read from one JSON row
use vanilla::LanguageEntry;

let language_json = serde_json::json!({ "code": "zh-Hant", "name": "Chinese", "englishName": "Chinese (Traditional)", "aliases": ["zh-TW", "zh-HK"], "file": "zh-Hant.json" });
let language = LanguageEntry::create_from_json(&language_json).unwrap();
assert_eq!(language.code, "zh-Hant");
assert_eq!(language.english_name, "Chinese (Traditional)");
assert_eq!(language.aliases, vec![String::from("zh-tw"), String::from("zh-hk")]);
assert_eq!(language.direction, "");
assert!(LanguageEntry::create_from_json(&serde_json::json!({ "name": "No code" })).is_none());
정적staticpub fn create_from_json(value: &serde_json::Value) -> Option<LanguageEntry>#0.4.0 부터since 0.4.0소스source

JSON 한 줄 읽기. (code 가 없으면 None, 나머지 칸은 없으면 빈 값)

  • aliases 와 countries 는 글만 골라 소문자로 바꾼다.

Reads one JSON row. (None if there is no code, other fields are empty values if missing)

  • aliases and countries keep only strings and are lowercased.
value&serde_json::Value
languages 배열의 한 칸. (JSON 객체)One entry of the languages array. (JSON object)

반환ReturnsOption<LanguageEntry> 읽은 한 줄. code 가 없거나 글이 아니면 None.The row read. None if code is missing or not a string.

필드fieldpub code: String#0.4.0 부터since 0.4.0소스source

언어 코드. (원본 code, 언어 파일과 html lang 에 쓰는 이름, 찾을 때는 대소문자를 가리지 않는다)

Language code. (the original code, the name used for the language file and html lang, case-insensitive when searching)

반환ReturnsString

필드fieldpub name: String#0.4.0 부터since 0.4.0소스source

그 언어로 쓴 언어 이름. (원본 name)

Language name written in that language. (the original name)

반환ReturnsString

필드fieldpub english_name: String#0.4.0 부터since 0.4.0소스source

영어로 쓴 언어 이름. (원본 englishName)

Language name written in English. (the original englishName)

반환ReturnsString

필드fieldpub font_group: String#0.4.0 부터since 0.4.0소스source

글꼴 무리 이름. (원본 fontGroup, 게임이 언어에 맞는 글꼴을 고를 때 쓴다)

Font group name. (the original fontGroup, used when the game picks a font that fits the language)

반환ReturnsString

필드fieldpub direction: String#0.4.0 부터since 0.4.0소스source

글자 방향. (원본 direction, "rtl" 이면 오른쪽에서 왼쪽, 그 밖은 왼쪽에서 오른쪽)

Text direction. (the original direction, right to left if "rtl", otherwise left to right)

반환ReturnsString

필드fieldpub aliases: Vec<String>#0.4.0 부터since 0.4.0소스source

이 언어로 볼 다른 태그. (원본 aliases, 소문자로 든다)

Other tags treated as this language. (the original aliases, held in lowercase)

반환ReturnsVec<String>

필드fieldpub countries: Vec<String>#0.4.0 부터since 0.4.0소스source

이 언어를 쓰는 나라 코드. (원본 countries, 소문자로 든다)

Codes of the countries that use this language. (the original countries, held in lowercase)

반환ReturnsVec<String>

필드fieldpub file: String#0.4.0 부터since 0.4.0소스source

언어 파일 이름. (원본 file, 언어 폴더 경로 뒤에 붙여 받는다)

Language file name. (the original file, appended to the language folder path to fetch)

반환ReturnsString

LanguageLoadedHandlertype

소스source

언어를 불러온 뒤 부르는 함수. (엔진, 언어 한 줄, 그 언어의 모든 글자)

Function called after a language is loaded. (engine, language row, all text of that language)

pub type LanguageLoadedHandler = Box<dyn FnMut(&Engine, &LanguageEntry, &str)>

LanguageLoadedAsyncHandlertype

소스source

언어를 불러온 뒤 부르는 async 함수. (원본처럼 돌려준 퓨처가 끝날 때까지 apply_language_setting 이 끝나지 않는다)

Async function called after a language is loaded. (as in the original, apply_language_setting does not finish until the returned future finishes)

pub type LanguageLoadedAsyncHandler = Box<dyn FnMut(&Engine, &LanguageEntry, &str) -> Pin<Box<dyn Future<Output = ()>>>>

LanguageLoadHandlestruct traits Clone, Copy, Debug, Default, IntoFuture

소스source

언어 불러오기 손잡이. (load_language_list, load_language, apply_language_setting 이 돌려준다. 원본 async 함수의 Promise 자리)

  • await 하면 불러오기(와 async 로 건 불러온 뒤 함수)가 끝날 때까지 기다린다. 기다리는 동안 프레임마다 update 를 불러 준다.

Language load handle. (returned by load_language_list, load_language, apply_language_setting. Stands in for the Promise of the original async functions)

  • Awaiting it waits until the load (and the after-load function hooked as async) finishes. Calls update every frame while waiting.
예제Example엔진 작업에서 언어를 불러오고 기다리기Load a language and wait in an engine task
use std::cell::Cell;
use std::rc::Rc;
use vanilla::{languagepack, Engine, EngineConfiguration};

let asset_directory_path = std::env::temp_dir().join(format!("vanillaLanguageLoadHandleDoc-{}", std::process::id()));
std::fs::create_dir_all(asset_directory_path.join("localization")).unwrap();
std::fs::write(asset_directory_path.join("localization/languages.json"), r#"{ "fallbackLanguage": "en", "languages": [{ "code": "en", "name": "English", "file": "en.json" }] }"#).unwrap();
std::fs::write(asset_directory_path.join("localization/en.json"), r#"{ "greeting": "Hello" }"#).unwrap();
let mut engine_configuration = EngineConfiguration::new();
engine_configuration.asset_directory_paths = vec![asset_directory_path.clone()];
let engine = Engine::new(engine_configuration);
languagepack::set_language_paths("localization/languages.json", "localization/");

let is_loaded = Rc::new(Cell::new(false));
let is_loaded_for_task = is_loaded.clone();
engine.spawn_task(move |mut engine_context| async move {
	engine_context.with(|engine| languagepack::load_language(engine, "en")).await;
	is_loaded_for_task.set(true);
});
assert!(is_loaded.get());
assert_eq!(languagepack::translate("greeting"), "Hello");
std::fs::remove_dir_all(&asset_directory_path).unwrap();

LanguageLoadFuturestruct traits Clone, Copy, Debug, Default, Future

소스source

언어 불러오기를 기다리는 퓨처. (LanguageLoadHandle 을 await 하거나 wait_for_load 가 돌려준다)

  • 폴링할 때마다 update 를 부르고, is_loading 이 거짓이면 끝난다.

Future that waits for a language load. (made by awaiting LanguageLoadHandle or returned by wait_for_load)

  • Calls update on every poll, and finishes when is_loading is false.
예제Example불러오는 것이 없으면 바로 끝난다Finishes right away if nothing is loading
use std::cell::Cell;
use std::rc::Rc;
use vanilla::{languagepack, Engine, EngineConfiguration};

let engine = Engine::new(EngineConfiguration::new());
let is_finished = Rc::new(Cell::new(false));
let is_finished_for_task = is_finished.clone();
engine.spawn_task(move |_engine_context| async move {
	languagepack::wait_for_load().await;
	is_finished_for_task.set(true);
});
assert!(!languagepack::is_loading());
assert!(is_finished.get());

함수Functions

함수functionpub fn set_language_list_from_json(json_text: &str) -> bool#0.4.0 부터since 0.4.0소스source

언어의 목록 JSON 넣기. (load_language_list 가 받은 것을 넣는다. 파일 없이 바로 줄 때도 쓴다, 읽었으면 true)

  • code 가 없는 줄은 뺀다. fallbackLanguage 가 없으면 기본 언어는 "en" 이다.

Sets the language list JSON. (puts in what load_language_list received. Also used to give it directly without a file, true if read)

  • Rows without code are dropped. If fallbackLanguage is missing, the default language is "en".
json_text&str
languages.json 의 글. ({ fallbackLanguage, languages: [...] })Text of languages.json. ({ fallbackLanguage, languages: [...] })

반환Returnsbool 읽어 들였으면 true. JSON 객체가 아니거나 languages 배열이 없으면 false 이고 앞의 목록을 그대로 둔다.true if read. false if it is not a JSON object or has no languages array, and the previous list is kept.

함수functionpub fn load_language_list(engine: &Engine) -> LanguageLoadHandle#0.4.0 부터since 0.4.0소스source

언어의 목록 불러오기. (한 번만, 원본 loadLanguageList. 받은 뒤 update 가 든다)

  • 이미 목록이 있거나 받는 중이면 다시 요청하지 않는다. 경로는 set_language_paths 의 목록 파일이다.

Loads the language list. (once only, the original loadLanguageList. Arrives in update after being received)

  • Does not request again if the list already exists or is being received. The path is the list file of set_language_paths.
engine&Engine
애셋을 받을 엔진. (데스크탑은 그 자리에서 읽혀 이 함수 안의 update 에서 든다)Engine to receive assets with. (on desktop it is read on the spot and arrives in the update inside this function)

반환ReturnsLanguageLoadHandle await 할 수 있는 불러오기 손잡이.Load handle that can be awaited.

짝Counterpart: vanilla.js loadLanguageList

함수functionpub fn is_loading() -> bool#0.4.0 부터since 0.4.0소스source

언어의 목록을 받는 중이거나 언어를 불러오는 중인지. (async 로 건 불러온 뒤 함수가 도는 중도 든다)

Whether the language list is being received or a language is loading. (includes while an after-load function hooked as async is running)

반환Returnsbool 목록을 받는 중이거나, 언어 표를 불러오는 중이거나, async 로 건 불러온 뒤 함수의 작업이 끝나지 않았으면 true.true if the list is being received, a language table is loading, or the task of an after-load function hooked as async has not finished.

함수functionpub fn wait_for_load() -> LanguageLoadFuture#0.4.0 부터since 0.4.0소스source

불러오기를 마치기를 기다리는 퓨처. (원본 await loadLanguageList(), await loadLanguage(코드), await applyLanguageSetting(코드) 의 await 자리)

  • 요청 함수가 돌려준 손잡이를 await 하는 것과 같다. 기다리는 동안 프레임마다 update 를 부른다.

Future that waits for loading to finish. (the await of the original await loadLanguageList(), await loadLanguage(code), await applyLanguageSetting(code))

  • Same as awaiting the handle returned by a request function. Calls update every frame while waiting.

반환ReturnsLanguageLoadFuture 불러오기가 끝나면 끝나는 퓨처. 불러오는 것이 없으면 첫 폴링에 끝난다.Future that finishes when loading finishes. Finishes on the first poll if nothing is loading.

함수functionpub fn read_languages() -> Vec<LanguageEntry>#0.4.0 부터since 0.4.0소스source

언어의 목록 반환. (못 읽었으면 빈 목록, 원본 readLanguages)

Returns the language list. (empty list if it could not be read, the original readLanguages)

반환ReturnsVec<LanguageEntry> 언어 목록의 복사본. 아직 읽지 않았거나 못 읽었으면 빈 목록.Copy of the language list. Empty list if not read yet or could not be read.

짝Counterpart: vanilla.js readLanguages

함수functionpub fn find_language(language_code: &str) -> Option<LanguageEntry>#0.4.0 부터since 0.4.0소스source

언어 찾기. (코드는 대소문자를 가리지 않는다, 없으면 None. 원본 findLanguage)

Finds a language. (the code is case-insensitive, None if not found. the original findLanguage)

language_code&str
찾을 언어 코드. (빈 글이면 None)Language code to find. (None if empty)

반환ReturnsOption<LanguageEntry> 코드가 같은 언어 한 줄의 복사본. 목록이 없거나 없는 코드면 None.Copy of the language row with the same code. None if there is no list or the code is not in it.

짝Counterpart: vanilla.js findLanguage

함수functionpub fn match_language_tag(language_tag: &str) -> Option<LanguageEntry>#0.4.0 부터since 0.4.0소스source

언어 태그에 맞는 언어. ("pt-BR" → pt, "zh-Hant-TW" → zh-Hant, 뒤의 조각을 하나씩 떼며 코드와 별칭을 본다, 없으면 None. 원본 matchLanguageTag)

  • 밑줄은 하이픈으로 바꾸고 대소문자를 가리지 않는다.

Language matching a language tag. ("pt-BR" → pt, "zh-Hant-TW" → zh-Hant, drops trailing subtags one at a time and checks codes and aliases, None if not found. the original matchLanguageTag)

  • Underscores become hyphens and case is ignored.
language_tag&str
언어 태그. (빈 글이면 None)Language tag. (None if empty)

반환ReturnsOption<LanguageEntry> 처음 맞은 언어 한 줄의 복사본. 없으면 None.Copy of the first matching language row. None if not found.

짝Counterpart: vanilla.js matchLanguageTag

예제Example지역 태그와 별칭으로 맞추기Match by region tag and alias
use vanilla::languagepack;

languagepack::set_language_list_from_json(r#"{ "fallbackLanguage": "en", "languages": [
	{ "code": "en", "file": "en.json" },
	{ "code": "zh-Hant", "aliases": ["zh-tw", "zh-hk"], "file": "zh-Hant.json" }
] }"#);
assert_eq!(languagepack::match_language_tag("en-US").unwrap().code, "en");
assert_eq!(languagepack::match_language_tag("zh_Hant_TW").unwrap().code, "zh-Hant");
assert_eq!(languagepack::match_language_tag("zh-HK").unwrap().code, "zh-Hant");
assert!(languagepack::match_language_tag("fr").is_none());
함수functionpub fn set_preferred_language_tag(language_tag: &str)#0.4.0 부터since 0.4.0소스source

앞세울 언어 태그 넣기. (플랫폼이 알려 준 사용자의 언어, 기기의 언어보다 먼저 본다, 없으면 "". 원본 setPreferredLanguageTag)

Sets the preferred language tag. (the user's language reported by the platform, checked before the device language, "" if none. the original setPreferredLanguageTag)

language_tag&str
앞세울 언어 태그. (빈 글이면 앞세우지 않는다)Language tag to prefer. (does not prefer anything if empty)

짝Counterpart: vanilla.js setPreferredLanguageTag

함수functionpub fn resolve_device_language_code() -> String#0.4.0 부터since 0.4.0소스source

기기의 언어. (앞세울 태그, 기기가 앞세우는 언어 차례대로 목록에 있는 첫 언어, 없으면 기본 언어. 원본 resolveDeviceLanguageCode)

  • 웹은 navigator.languages, 데스크탑은 sys-locale 로 시스템의 선호 언어 차례를 읽는다. (Localization.detect_language 와 같다)

Device language. (the first language in the list from the preferred tag and then the languages the device prefers in order, otherwise the default language. the original resolveDeviceLanguageCode)

  • On web reads the system's preferred language order from navigator.languages, on desktop from sys-locale. (same as Localization.detect_language)

반환ReturnsString 목록에서 맞은 언어 코드. (목록에 적힌 대로) 맞는 것이 없으면 기본 언어의 코드.Matched language code from the list. (as written in the list) The default language's code if nothing matches.

짝Counterpart: vanilla.js resolveDeviceLanguageCode

함수functionpub fn read_fallback_language_code() -> String#0.4.0 부터since 0.4.0소스source

기본 언어의 코드. (목록의 fallbackLanguage, 없으면 "en". 원본 readFallbackLanguageCode)

Code of the default language. (the list's fallbackLanguage, "en" if missing. the original readFallbackLanguageCode)

반환ReturnsString 기본 언어의 코드.Default language code.

짝Counterpart: vanilla.js readFallbackLanguageCode

함수functionpub fn resolve_language_code(setting_language_code: &str) -> String#0.4.0 부터since 0.4.0소스source

설정의 언어 → 쓸 언어의 코드. (비었거나 목록에 없으면 기기의 언어, 원본 resolveLanguageCode)

Language setting → code of the language to use. (device language if empty or not in the list, the original resolveLanguageCode)

setting_language_code&str
설정에 적힌 언어 코드. (대소문자를 가리지 않는다)Language code written in the settings. (case-insensitive)

반환ReturnsString 쓸 언어 코드. (목록에 적힌 대로)Language code to use. (as written in the list)

짝Counterpart: vanilla.js resolveLanguageCode

함수functionpub fn load_language(engine: &Engine, language_code: &str) -> LanguageLoadHandle#0.4.0 부터since 0.4.0소스source

언어 불러오기. (그 언어의 표와 기본 언어의 표, 목록에 없는 코드면 기본 언어. 원본 loadLanguage)

  • 목록이 없으면 먼저 받는다. 불러온 뒤 함수는 부르지 않는다. (apply_language_setting 만 부른다)

Loads a language. (that language's table and the default language's table, the default language if the code is not in the list. the original loadLanguage)

  • Receives the list first if there is none. Does not call the after-load function. (only apply_language_setting calls it)
engine&Engine
애셋을 받을 엔진.Engine to load the asset with.
language_code&str
불러올 언어 코드.Language code to load.

반환ReturnsLanguageLoadHandle await 할 수 있는 불러오기 손잡이.Load handle that can be awaited.

짝Counterpart: vanilla.js loadLanguage

함수functionpub fn apply_language_setting(engine: &Engine, setting_language_code: &str) -> LanguageLoadHandle#0.4.0 부터since 0.4.0소스source

설정의 언어 적용하기. (쓸 언어를 정해 그 표를 불러오고, set_language_loaded_handler 로 건 함수를 부른다. "" 이면 기기의 언어. 원본 applyLanguageSetting)

Applies the language setting. (decides the language to use, loads its table, and calls the function hooked with set_language_loaded_handler. Device language if "". the original applyLanguageSetting)

engine&Engine
애셋을 받을 엔진.Engine to load the asset with.
setting_language_code&str
설정에 적힌 언어 코드. (빈 글이거나 목록에 없으면 기기의 언어)Language code written in the settings. (device language if empty or not in the list)

반환ReturnsLanguageLoadHandle await 할 수 있는 불러오기 손잡이. (async 로 건 불러온 뒤 함수가 끝날 때까지 기다린다)Load handle that can be awaited. (waits until the after-load function hooked as async finishes)

짝Counterpart: vanilla.js applyLanguageSetting

예제Example불러온 뒤 함수로 언어와 글자 받기Receive the language and text in the after-load function
use std::cell::RefCell;
use std::rc::Rc;
use vanilla::{languagepack, Engine, EngineConfiguration, LanguageEntry};

let asset_directory_path = std::env::temp_dir().join(format!("vanillaApplyLanguageDoc-{}", std::process::id()));
std::fs::create_dir_all(asset_directory_path.join("localization")).unwrap();
std::fs::write(asset_directory_path.join("localization/languages.json"), r#"{ "fallbackLanguage": "en", "languages": [{ "code": "en", "file": "en.json" }] }"#).unwrap();
std::fs::write(asset_directory_path.join("localization/en.json"), r#"{ "greeting": "Hello" }"#).unwrap();
let mut engine_configuration = EngineConfiguration::new();
engine_configuration.asset_directory_paths = vec![asset_directory_path.clone()];
let engine = Engine::new(engine_configuration);
languagepack::set_language_paths("localization/languages.json", "localization/");

let loaded_text = Rc::new(RefCell::new(String::new()));
let loaded_text_for_handler = loaded_text.clone();
languagepack::set_language_loaded_handler(Some(Box::new(move |_engine: &Engine, language: &LanguageEntry, all_texts: &str| {
	*loaded_text_for_handler.borrow_mut() = format!("{} {}", language.code, all_texts);
})));
languagepack::apply_language_setting(engine, "en");
assert!(!languagepack::is_loading());
assert_eq!(*loaded_text.borrow(), "en Hello");
std::fs::remove_dir_all(&asset_directory_path).unwrap();
함수functionpub fn update(engine: &Engine)#0.4.0 부터since 0.4.0소스source

이어 가기. (받은 목록과 표를 들고, 다 받으면 언어를 바꾸고 불러온 뒤 함수를 부른다. 프레임마다 부른다)

  • 언어를 바꾸면 문서 언어를 그 코드로, 창 제목을 제목 열쇠의 글자로 바꾼다.

Continues. (takes the received list and tables, and once everything arrives switches the language and calls the after-load function. Call every frame)

  • Switching the language changes the document language to that code and the window title to the text of the title key.
engine&Engine
애셋 손잡이를 받고 불러온 뒤 함수에 넘길 엔진.Engine to receive asset handles with and pass to the after-load function.
함수functionpub fn read_language() -> Option<LanguageEntry>#0.4.0 부터since 0.4.0소스source

지금 언어. (목록의 한 줄, 아직 없으면 None. 원본 readLanguage)

Current language. (a row of the list, None if not yet. the original readLanguage)

반환ReturnsOption<LanguageEntry> 지금 언어 한 줄의 복사본. 아직 불러오지 않았으면 None.Copy of the current language row. None if not loaded yet.

짝Counterpart: vanilla.js readLanguage

함수functionpub fn read_language_code() -> String#0.4.0 부터since 0.4.0소스source

지금 언어의 코드. (아직 없으면 기본 언어, 원본 readLanguageCode)

Code of the current language. (the default language if not yet, the original readLanguageCode)

반환ReturnsString 지금 언어 코드. 아직 없으면 기본 언어의 코드.Current language code. The default language's code if not yet.

짝Counterpart: vanilla.js readLanguageCode

함수functionpub fn read_text_direction() -> &'static str#0.4.0 부터since 0.4.0소스source

지금 언어의 글자 방향. ("ltr" 또는 "rtl", 언어 목록의 direction, 아직 없으면 "ltr". 원본 readTextDirection)

Text direction of the current language. ("ltr" or "rtl", direction from the language list, "ltr" if not yet. the original readTextDirection)

반환Returns&'static str direction 이 "rtl" 이면 "rtl", 그 밖은 "ltr"."rtl" if direction is "rtl", otherwise "ltr".

짝Counterpart: vanilla.js readTextDirection

함수functionpub fn is_right_to_left() -> bool#0.4.0 부터since 0.4.0소스source

지금 언어가 오른쪽에서 왼쪽으로 쓰는지. (원본 isRightToLeft)

Whether the current language is written right to left. (the original isRightToLeft)

반환Returnsbool 지금 언어의 direction 이 "rtl" 이면 true.true if the current language's direction is "rtl".

짝Counterpart: vanilla.js isRightToLeft

함수functionpub fn mirror_layout_x(x: f64, width: f64, parent_width: f64) -> f64#0.4.0 부터since 0.4.0소스source

배치의 가로 자리. (오른쪽에서 왼쪽 언어면 부모 너비 안에서 좌우를 뒤집은 왼쪽, 아니면 그대로. 원본 mirrorLayoutX)

Horizontal position for layout. (for right-to-left languages the left mirrored within the parent width, otherwise unchanged. the original mirrorLayoutX)

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 mirrorLayoutX

예제Example아랍어 표를 넣으면 좌우를 뒤집는다Put in an Arabic table and mirror left and right
use vanilla::{languagepack, TextAlign};

languagepack::set_language_list_from_json(r#"{ "fallbackLanguage": "en", "languages": [
	{ "code": "en", "direction": "ltr", "file": "en.json" },
	{ "code": "ar", "direction": "rtl", "file": "ar.json" }
] }"#);
languagepack::set_language_texts_from_json("ar", "{}", "{}");
assert!(languagepack::is_right_to_left());
assert_eq!(languagepack::mirror_layout_x(10.0, 20.0, 100.0), 70.0);
assert_eq!(languagepack::read_layout_text_align(TextAlign::Left), TextAlign::Right);
함수functionpub fn read_layout_text_align(text_align: TextAlign) -> TextAlign#0.4.0 부터since 0.4.0소스source

배치의 글자 정렬. (오른쪽에서 왼쪽 언어면 Left 와 Right 를 바꾸고, 나머지는 그대로. 원본 readLayoutTextAlign)

Text alignment for layout. (for right-to-left languages swaps Left and Right, the rest unchanged. the original readLayoutTextAlign)

text_alignTextAlign
왼쪽에서 오른쪽 언어일 때의 정렬.Alignment for left-to-right languages.

반환ReturnsTextAlign 지금 언어 방향에 맞춘 정렬.Alignment matching the current language direction.

짝Counterpart: vanilla.js readLayoutTextAlign

함수functionpub fn isolate_text(text: &str) -> String#0.4.0 부터since 0.4.0소스source

글 사이에 끼우는 값 묶기. (오른쪽에서 왼쪽 언어면 방향 격리 문자 FSI ... PDI 로 묶고, 아니면 그대로. 원본 isolateText)

Wraps a value inserted into text. (for right-to-left languages wraps it with the directional isolate characters FSI ... PDI, otherwise unchanged. the original isolateText)

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 isolateText

함수functionpub fn translate(key: &str) -> String#0.4.0 부터since 0.4.0소스source

열쇠의 글자. (지금 언어 → 기본 언어 → 열쇠 그대로, 원본 translate)

Text for a key. (current language → default language → the key itself, the original translate)

key&str
글자의 열쇠. (값이 글이 아닌 칸은 없는 것으로 본다)Key of the text. (entries whose value is not a string are treated as missing)

반환ReturnsString 찾은 글자. 두 표에 모두 없으면 열쇠 그대로.Text found. The key itself if missing from both tables.

짝Counterpart: vanilla.js translate

함수functionpub fn format_text(key: &str, values: &[(&str, &dyn std::fmt::Display)]) -> String#0.4.0 부터since 0.4.0소스source

열쇠의 글자에 값 넣기. ("Restart {seconds}" + [("seconds", "3")] → "Restart 3", 원본 formatText)

  • 오른쪽에서 왼쪽 언어면 넣는 값을 방향 격리 문자로 묶는다. 빗금으로만 이은 값들("{count}/{limit}")은 통째로 한 번 묶는다.
  • 이름이 values 에 없는 자리는 그대로 둔다. 이름은 영문과 숫자만 된다.

Inserts values into a key's text. ("Restart {seconds}" + [("seconds", "3")] → "Restart 3", the original formatText)

  • For right-to-left languages, inserted values are wrapped with directional isolate characters. Values joined only by slashes ("{count}/{limit}") are wrapped once as a whole.
  • Placeholders whose name is not in values are left as is. Names may only be Latin letters and digits.
key&str
글자의 열쇠. (translate 로 찾는다)Key of the text. (looked up with translate)
values&[(&str, &dyn std::fmt::Display)]
(이름, 값) 목록. 같은 이름이 여럿이면 처음 것을 쓴다.List of (name, value). If a name appears more than once, the first is used.

반환ReturnsString 자리를 채운 글자.Text with placeholders filled.

짝Counterpart: vanilla.js formatText

예제Example이름 자리 채우기Fill named placeholders
use vanilla::languagepack;

languagepack::set_language_list_from_json(r#"{ "fallbackLanguage": "en", "languages": [{ "code": "en", "file": "en.json" }] }"#);
languagepack::set_language_texts_from_json("en", r#"{ "restart": "Restart {seconds}", "count": "{count}/{limit} workers" }"#, "{}");
assert_eq!(languagepack::format_text("restart", &[("seconds", &3)]), "Restart 3");
assert_eq!(languagepack::format_text("count", &[("count", &1), ("limit", &40)]), "1/40 workers");
함수functionpub fn read_all_texts() -> String#0.4.0 부터since 0.4.0소스source

지금 언어의 글자 모두. (글꼴의 조각을 미리 받을 때 쓴다, 원본 readAllTexts)

All text of the current language. (used to prefetch font subsets, the original readAllTexts)

반환ReturnsString 지금 언어 표의 글 값을 모두 이은 글. (기본 언어 표는 넣지 않는다)Text joining all string values of the current language's table. (the default language's table is not included)

짝Counterpart: vanilla.js readAllTexts

함수functionpub fn set_language_texts_from_json(language_code: &str, language_json_text: &str, fallback_json_text: &str) -> bool#0.4.0 부터since 0.4.0소스source

지금 언어의 표 넣기. (파일 없이 바로 줄 때, 기본 언어 표도 함께. 언어가 목록에 없으면 false)

  • 문서 언어, 창 제목, 불러온 뒤 함수는 건드리지 않는다.

Sets the current language's table. (when given directly without a file, together with the default language's table. false if the language is not in the list)

  • Does not touch the document language, window title or after-load function.
language_code&str
지금 언어로 할 코드. (목록에 있어야 한다)Code to make the current language. (must be in the list)
language_json_text&str
그 언어의 표 JSON. (열쇠 → 글자, 객체가 아니면 빈 표)Table JSON of that language. (key → text, an empty table if not an object)
fallback_json_text&str
기본 언어의 표 JSON. (객체가 아니면 빈 표)Table JSON of the default language. (an empty table if not an object)

반환Returnsbool 넣었으면 true. 언어가 목록에 없으면 false 이고 아무것도 바꾸지 않는다.true if set. false if the language is not in the list, and nothing is changed.

함수functionpub fn set_language_paths(list_path: &str, directory_path: &str)#0.4.0 부터since 0.4.0소스source

경로 정하기. (언어 목록 파일, 언어 파일들이 있는 폴더, 불러오기 전에 부른다. 원본 setLanguagePaths)

Sets the paths. (the language list file and the folder holding the language files, call before loading. the original setLanguagePaths)

list_path&str
언어 목록 파일 경로. (애셋 경로, 처음은 "./assets/localization/languages.json")Language list file path. (asset path, initially "./assets/localization/languages.json")
directory_path&str
언어 파일 폴더 경로. (뒤에 언어의 file 을 그대로 붙이므로 / 로 끝낸다, 처음은 "./assets/localization/")Language file folder path. (the language's file is appended as is, so end it with /, initially "./assets/localization/")

짝Counterpart: vanilla.js setLanguagePaths

함수functionpub fn set_document_title_key(title_key: &str)#0.4.0 부터since 0.4.0소스source

제목이 될 글자의 열쇠 정하기. ("" 이면 제목을 바꾸지 않는다, 원본 setDocumentTitleKey. 웹은 탭 제목, 데스크탑은 창 제목)

  • 불러온 언어의 표에서 찾은 글자가 열쇠와 같으면(없으면) 제목을 바꾸지 않는다.

Sets the key of the text used as the title. (does not change the title if "", the original setDocumentTitleKey. The tab title on web, the window title on desktop)

  • Does not change the title if the text found in the loaded language's table equals the key (is missing).
title_key&str
제목 글자의 열쇠. (처음은 "game.title")Key of the title text. (initially "game.title")

짝Counterpart: vanilla.js setDocumentTitleKey

함수functionpub fn set_language_loaded_handler(handler: Option<LanguageLoadedHandler>)#0.4.0 부터since 0.4.0소스source

언어를 불러온 뒤 부를 함수 정하기. (apply_language_setting 이 다 불러온 뒤 부른다, None 이면 없음. 원본 setLanguageLoadedHandler)

Sets the function to call after a language is loaded. (called by apply_language_setting after everything is loaded, none if None. the original setLanguageLoadedHandler)

handlerOption<LanguageLoadedHandler>
(엔진, 언어 한 줄, 그 언어의 모든 글자) 를 받는 함수. None 이면 지운다.Function that takes (engine, language row, all text of that language). Clears it if None.

짝Counterpart: vanilla.js setLanguageLoadedHandler

함수functionpub fn set_language_loaded_async_handler(handler: Option<LanguageLoadedAsyncHandler>)#0.4.0 부터since 0.4.0소스source

언어를 불러온 뒤 부를 async 함수 정하기. (원본 setLanguageLoadedHandler 에 Promise 를 돌려주는 함수를 건 자리, None 이면 없음)

  • apply_language_setting 이 다 불러온 뒤 부르고, 돌려준 퓨처를 엔진 작업으로 돌려 끝날 때까지 불러오는 중으로 친다.

Sets the async function to call after a language is loaded. (stands in for hooking a Promise-returning function on the original setLanguageLoadedHandler, none if None)

  • Called by apply_language_setting after everything is loaded, the returned future runs as an engine task and counts as loading until it finishes.
handlerOption<LanguageLoadedAsyncHandler>
(엔진, 언어 한 줄, 그 언어의 모든 글자) 를 받아 고정한 퓨처(Pin<Box<dyn Future>>)를 돌려주는 함수. None 이면 지운다.Function that takes (engine, language row, all text of that language) and returns a pinned future (Pin<Box<dyn Future>>). Clears it if None.
예제Example불러온 뒤 0.5 초 쉬는 async 일 걸기Hook async work that rests 0.5 seconds after loading
use vanilla::{languagepack, wait, Engine, LanguageEntry};

languagepack::set_language_loaded_async_handler(Some(Box::new(|_engine: &Engine, _language: &LanguageEntry, _all_texts: &str| {
	Box::pin(async move {
		wait::seconds(0.5).await;
	})
})));
assert!(!languagepack::is_loading());