# misc/languagepack (vanilla-engine 0.4.0)

> https://vanillapunch.com/docs/vanilla-engine/0.4.0/api/misc/languagepack/

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

```rust
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");
```

## LanguageEntry (struct) (Clone, Debug, Default, PartialEq, Eq)

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

Example: Read from one JSON row

```rust
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());
```

- `pub code: String` (field, since 0.4.0): Language code. (the original code, the name used for the language file and html lang, case-insensitive when searching)
  - returns String
- `pub name: String` (field, since 0.4.0): Language name written in that language. (the original name)
  - returns String
- `pub english_name: String` (field, since 0.4.0): Language name written in English. (the original englishName)
  - returns String
- `pub font_group: String` (field, since 0.4.0): Font group name. (the original fontGroup, used when the game picks a font that fits the language)
  - returns String
- `pub direction: String` (field, since 0.4.0): Text direction. (the original direction, right to left if "rtl", otherwise left to right)
  - returns String
- `pub aliases: Vec<String>` (field, since 0.4.0): Other tags treated as this language. (the original aliases, held in lowercase)
  - returns Vec<String>
- `pub countries: Vec<String>` (field, since 0.4.0): Codes of the countries that use this language. (the original countries, held in lowercase)
  - returns Vec<String>
- `pub file: String` (field, since 0.4.0): Language file name. (the original file, appended to the language folder path to fetch)
  - returns String
- `pub fn create_from_json(value: &serde_json::Value) -> Option<LanguageEntry>` (static, since 0.4.0): 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: One entry of the languages array. (JSON object)
  - returns Option<LanguageEntry>: The row read. None if code is missing or not a string.

## LanguageLoadedHandler (type)

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

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

## LanguageLoadedAsyncHandler (type)

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

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

## LanguageLoadHandle (struct) (Clone, Copy, Debug, Default, IntoFuture)

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

```rust
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();
```

## LanguageLoadFuture (struct) (Clone, Copy, Debug, Default, Future)

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

```rust
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 and constants

- `pub fn set_language_list_from_json(json_text: &str) -> bool` (method, since 0.4.0): 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: Text of languages.json. ({ fallbackLanguage, languages: [...] })
  - returns bool: true if read. false if it is not a JSON object or has no languages array, and the previous list is kept.
- `pub fn load_language_list(engine: &Engine) -> LanguageLoadHandle` (method, since 0.4.0): 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: Engine to receive assets with. (on desktop it is read on the spot and arrives in the update inside this function)
  - returns LanguageLoadHandle: Load handle that can be awaited.
- `pub fn is_loading() -> bool` (method, since 0.4.0): Whether the language list is being received or a language is loading. (includes while an after-load function hooked as async is running)
  - returns bool: 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.
- `pub fn wait_for_load() -> LanguageLoadFuture` (method, since 0.4.0): 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.
  - returns LanguageLoadFuture: Future that finishes when loading finishes. Finishes on the first poll if nothing is loading.
- `pub fn read_languages() -> Vec<LanguageEntry>` (method, since 0.4.0): Returns the language list. (empty list if it could not be read, the original readLanguages)
  - returns Vec<LanguageEntry>: Copy of the language list. Empty list if not read yet or could not be read.
- `pub fn find_language(language_code: &str) -> Option<LanguageEntry>` (method, since 0.4.0): Finds a language. (the code is case-insensitive, None if not found. the original findLanguage)
  - `language_code` &str: Language code to find. (None if empty)
  - returns Option<LanguageEntry>: Copy of the language row with the same code. None if there is no list or the code is not in it.
- `pub fn match_language_tag(language_tag: &str) -> Option<LanguageEntry>` (method, since 0.4.0): 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: Language tag. (None if empty)
  - returns Option<LanguageEntry>: Copy of the first matching language row. None if not found.

  Example: Match by region tag and alias

  ```rust
  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());
  ```

- `pub fn set_preferred_language_tag(language_tag: &str)` (method, since 0.4.0): 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)
- `pub fn resolve_device_language_code() -> String` (method, since 0.4.0): 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)
  - returns String: Matched language code from the list. (as written in the list) The default language's code if nothing matches.
- `pub fn read_fallback_language_code() -> String` (method, since 0.4.0): Code of the default language. (the list's fallbackLanguage, "en" if missing. the original readFallbackLanguageCode)
  - returns String: Default language code.
- `pub fn resolve_language_code(setting_language_code: &str) -> String` (method, since 0.4.0): 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)
  - returns String: Language code to use. (as written in the list)
- `pub fn load_language(engine: &Engine, language_code: &str) -> LanguageLoadHandle` (method, since 0.4.0): 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.
  - returns LanguageLoadHandle: Load handle that can be awaited.
- `pub fn apply_language_setting(engine: &Engine, setting_language_code: &str) -> LanguageLoadHandle` (method, since 0.4.0): 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)
  - returns LanguageLoadHandle: Load handle that can be awaited. (waits until the after-load function hooked as async finishes)

  Example: Receive the language and text in the after-load function

  ```rust
  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();
  ```

- `pub fn update(engine: &Engine)` (method, since 0.4.0): 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.
- `pub fn read_language() -> Option<LanguageEntry>` (method, since 0.4.0): Current language. (a row of the list, None if not yet. the original readLanguage)
  - returns Option<LanguageEntry>: Copy of the current language row. None if not loaded yet.
- `pub fn read_language_code() -> String` (method, since 0.4.0): Code of the current language. (the default language if not yet, the original readLanguageCode)
  - returns String: Current language code. The default language's code if not yet.
- `pub fn read_text_direction() -> &'static str` (method, since 0.4.0): Text direction of the current language. ("ltr" or "rtl", direction from the language list, "ltr" if not yet. the original readTextDirection)
  - returns &'static str: "rtl" if direction is "rtl", otherwise "ltr".
- `pub fn is_right_to_left() -> bool` (method, since 0.4.0): Whether the current language is written right to left. (the original isRightToLeft)
  - returns bool: true if the current language's direction is "rtl".
- `pub fn mirror_layout_x(x: f64, width: f64, parent_width: f64) -> f64` (method, since 0.4.0): Horizontal position for layout. (for right-to-left languages the left mirrored within the parent width, otherwise unchanged. the original mirrorLayoutX)
  - `x` f64: Left position for left-to-right languages. (pixels, relative to the parent's left)
  - `width` f64: Width of the thing being placed. (pixels)
  - `parent_width` f64: Parent width. (pixels)
  - returns f64: parent_width - x - width for right-to-left languages, otherwise x.

  Example: Put in an Arabic table and mirror left and right

  ```rust
  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);
  ```

- `pub fn read_layout_text_align(text_align: TextAlign) -> TextAlign` (method, since 0.4.0): Text alignment for layout. (for right-to-left languages swaps Left and Right, the rest unchanged. the original readLayoutTextAlign)
  - `text_align` TextAlign: Alignment for left-to-right languages.
  - returns TextAlign: Alignment matching the current language direction.
- `pub fn isolate_text(text: &str) -> String` (method, since 0.4.0): 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.
  - returns String: Text wrapped in U+2068 and U+2069 for right-to-left languages. Unchanged otherwise or if empty.
- `pub fn translate(key: &str) -> String` (method, since 0.4.0): 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)
  - returns String: Text found. The key itself if missing from both tables.
- `pub fn format_text(key: &str, values: &[(&str, &dyn std::fmt::Display)]) -> String` (method, since 0.4.0): 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: 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.
  - returns String: Text with placeholders filled.

  Example: Fill named placeholders

  ```rust
  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");
  ```

- `pub fn read_all_texts() -> String` (method, since 0.4.0): All text of the current language. (used to prefetch font subsets, the original readAllTexts)
  - returns String: Text joining all string values of the current language's table. (the default language's table is not included)
- `pub fn set_language_texts_from_json(language_code: &str, language_json_text: &str, fallback_json_text: &str) -> bool` (method, since 0.4.0): 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: Table JSON of that language. (key → text, an empty table if not an object)
  - `fallback_json_text` &str: Table JSON of the default language. (an empty table if not an object)
  - returns bool: true if set. false if the language is not in the list, and nothing is changed.
- `pub fn set_language_paths(list_path: &str, directory_path: &str)` (method, since 0.4.0): Sets the paths. (the language list file and the folder holding the language files, call before loading. the original setLanguagePaths)
  - `list_path` &str: Language list file path. (asset path, initially "./assets/localization/languages.json")
  - `directory_path` &str: Language file folder path. (the language's file is appended as is, so end it with /, initially "./assets/localization/")
- `pub fn set_document_title_key(title_key: &str)` (method, since 0.4.0): 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: Key of the title text. (initially "game.title")
- `pub fn set_language_loaded_handler(handler: Option<LanguageLoadedHandler>)` (method, since 0.4.0): 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)
  - `handler` Option<LanguageLoadedHandler>: Function that takes (engine, language row, all text of that language). Clears it if None.
- `pub fn set_language_loaded_async_handler(handler: Option<LanguageLoadedAsyncHandler>)` (method, since 0.4.0): 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.
  - `handler` Option<LanguageLoadedAsyncHandler>: 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: Hook async work that rests 0.5 seconds after loading

  ```rust
  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());
  ```

