# misc/uifont (vanilla-engine 0.4.0)

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

UI font. (the original misc/uifont.js, all on-screen text, groups font subsets for many scripts under one name)
- Font name, list file and folder, last group, weights and wait time are set with configure_ui_font. (initially GameUI, ./assets/fonts/fonts.json, latin, 500 and 700)
- The lists are fonts.json (index { fonts: [{ group, manifest }] }) and fonts-<group>.json (subsets { faces: [{ file, weight, style, unicodeRange }] }).
- Draws all on-screen languages under one font name. Font files are not merged; a font face is made for each subset and registered with that subset's character range.
  So only the subsets containing characters used on screen are fetched. (Korean, Chinese and Japanese fonts have hundreds of subsets)
  Characters shared by several fonts, such as Han characters, are drawn by the font registered later. The selected language's group is placed right before Latin (second from the end)
  so that Japanese gets Japanese-font Han characters and Traditional Chinese gets Traditional-font ones. Latin is always last, so digits and Latin letters use the Latin font in every language.
- Every subset is registered with only the two weights in configure_ui_font's weights (initially 500, 700). Variable-weight subsets are registered twice (500 and 700), and 400-only subsets as 500.
- Subsets for the text in use are fetched in advance. (load_ui_font_text) When a subset arrives, the engine (EngineConfiguration.rebake_text_on_font_load) discards and rebakes only the text baked with that subset's characters.
  Characters not fetched in advance also get their subset fetched by update when measured or drawn with that font. (in the original, the browser fetches a registered FontFace when drawing characters in its range)
  Before it arrives, it is drawn with another font like the original canvas, and once it arrives it is rebaked (when rebake_text_on_font_load is on).
- At first only the lists for the selected language and Latin are fetched, and the remaining groups are fetched a little after play starts (remaining_delay_milliseconds).
  Initial subsets are waited for only up to wait_milliseconds. (is_ui_font_ready is true once that time passes or everything arrives)
- Differences from the original:
  The original creates FontFaces, adds them to document.fonts and waits with async. The Rust version receives the bytes of the subset files on both desktop and web
  and registers them as faces of the same name in the engine's text cache. (Engine.register_font_face_when_loaded, order by Engine.set_font_face_order)
  So on web too it draws with the engine's shaping, not browser fonts. Receiving only makes requests, and calling update(engine) every frame carries it on.
  load_ui_font returns a UiFontLoadHandle that can be awaited as in the original. (calls update while waiting, and finishes once the initial text is all registered or wait_milliseconds passes)
  load_ui_font_text returns a UiFontTextLoadHandle that finishes once the faces for that text are registered in the font list. (the original await loadUiFontText(text))
  The original readUiFontFace(FontFace) is read_ui_font_face (the registered name, None if it could not be loaded). The options object is the UiFontOptions struct.

## UiFontOptions (struct) (Clone, Debug, Default, PartialEq)

UI font settings. (the options of the original configureUiFont, fields that are None stay unchanged)
- By default every field is None. Fill only the fields to change with Some and leave the rest with ..UiFontOptions::default().

Example: Change the font name and list path

```rust
use vanilla::{uifont, UiFontOptions};

uifont::configure_ui_font(UiFontOptions {
	family: Some(String::from("MenuFont")),
	manifest_path: Some(String::from("./assets/menufonts/fonts.json")),
	directory_path: Some(String::from("./assets/menufonts/")),
	..UiFontOptions::default()
});
assert_eq!(uifont::read_ui_font_family(), "MenuFont");
assert_eq!(uifont::build_ui_font_string(700, 24.0), "700 24px \"MenuFont\", sans-serif");
```

- `pub family: Option<String>` (field, since 0.4.0): Font name to register. (initially "GameUI", the name given to the text component's set_font_family)
  - returns Option<String>
- `pub manifest_path: Option<String>` (field, since 0.4.0): Font index file path. (asset path, initially "./assets/fonts/fonts.json")
  - returns Option<String>
- `pub directory_path: Option<String>` (field, since 0.4.0): Folder holding the group lists and subset files. (file names are appended as is, so end it with /, initially "./assets/fonts/")
  - returns Option<String>
- `pub primary_group: Option<String>` (field, since 0.4.0): Group to put last. (initially "latin", digits and Latin letters are always drawn with this group)
  - returns Option<String>
- `pub weights: Option<Vec<u16>>` (field, since 0.4.0): List of weights to register subsets with. (initially 500 and 700)
  - returns Option<Vec<u16>>
- `pub wait_milliseconds: Option<f64>` (field, since 0.4.0): Time to wait for the subsets of the initial text. (milliseconds, initially 1500)
  - returns Option<f64>
- `pub remaining_delay_milliseconds: Option<f64>` (field, since 0.4.0): Time to rest after the initial load before fetching the remaining groups. (milliseconds, initially 3000)
  - returns Option<f64>

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

UI font load handle. (returned by load_ui_font. Stands in for the Promise of the original loadUiFont)
- Awaiting it waits until the initial text is all registered or wait_milliseconds passes.

Example: If there is no font list it finishes right away and carries on with the system font

```rust
use std::cell::Cell;
use std::rc::Rc;
use vanilla::{uifont, Engine, EngineConfiguration, UiFontOptions};

uifont::configure_ui_font(UiFontOptions {
	manifest_path: Some(String::from("missing-fonts/fonts.json")),
	..UiFontOptions::default()
});
let engine = Engine::new(EngineConfiguration::new());
let is_ready = Rc::new(Cell::new(false));
let is_ready_for_task = is_ready.clone();
engine.spawn_task(move |mut engine_context| async move {
	engine_context.with(|engine| uifont::load_ui_font(engine, "korean", "Start")).await;
	is_ready_for_task.set(true);
});
assert!(is_ready.get());
assert!(uifont::is_ui_font_ready());
assert_eq!(uifont::read_ui_font_face(), None);
```

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

Future that waits for the initial UI font load.
- Made by awaiting UiFontLoadHandle or returned by wait_for_load. Calls update on every poll.

Example: Finishes right away if loading has not started

```rust
use std::cell::Cell;
use std::rc::Rc;
use vanilla::{uifont, 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 {
	uifont::wait_for_load().await;
	is_finished_for_task.set(true);
});
assert!(is_finished.get());
```

## UiFontTextLoadHandle (struct) (Clone, Debug, Default, IntoFuture)

Text subset fetch handle. (returned by load_ui_font_text. Stands in for the Promise of the original loadUiFontText, finishes once all requested faces are registered)

Example: Ask whether it finished or await it as is

```rust
use vanilla::{uifont, Engine, EngineConfiguration};

let engine = Engine::new(EngineConfiguration::new());
let text_load_handle = uifont::load_ui_font_text(engine, "Ready");
if !text_load_handle.is_finished() {
	engine.spawn_task(move |_engine_context| async move {
		text_load_handle.await;
	});
}
```

- `pub fn get_font_load_handles(&self) -> &[FontLoadHandle]` (method, since 0.4.0): List of font fetch handles for the requested faces. (each one's get_load_handle when handing them to a scene)
  - returns &[FontLoadHandle]: List of font fetch handles, one per requested face. Empty list if nothing was requested.
- `pub fn is_finished(&self) -> bool` (method, since 0.4.0): Whether everything finished. (registered or failed, true if nothing was requested)
  - returns bool: true if all handles finished.

## UiFontTextLoadFuture (struct) (Clone, Debug, Future)

Future that waits for text subset fetches. (as in the original, does not end in failure even if some subsets could not be fetched)
- Awaiting UiFontTextLoadHandle gives this.

Example: Finishes on the first poll if nothing was requested

```rust
use std::cell::Cell;
use std::future::IntoFuture;
use std::rc::Rc;
use vanilla::{uifont, Engine, EngineConfiguration, UiFontTextLoadFuture};

let engine = Engine::new(EngineConfiguration::new());
let text_load_future: UiFontTextLoadFuture = uifont::load_ui_font_text(engine, "Ready").into_future();
let is_finished = Rc::new(Cell::new(false));
let is_finished_for_task = is_finished.clone();
engine.spawn_task(move |_engine_context| async move {
	text_load_future.await;
	is_finished_for_task.set(true);
});
assert!(is_finished.get());
```

## Functions and constants

- `pub fn read_target_weights(weight_descriptor: &str, weights: &[u16]) -> Vec<u16>` (method, since 0.4.0): Subset weight → weights to register. ("400 700" → [500, 700], "400" → `[500]`, "700" → `[700]`, the original readTargetWeights)
  - For a range, all weights inside it; for a single value, the closest one.
  - Treated as 400 if there is no number. If two weights are equally close, the earlier one in weights.
  - `weight_descriptor` &str: Weight text from the subset list. (a single value like "400", a range like "100 900")
  - `weights` &[u16]: List of weights to register.
  - returns Vec<u16>: List of weights to register. For a range, all weights inside it (both ends included); for a single value, the closest one. Empty list if weights is empty.

  Example: Variable-weight subsets and single-weight subsets

  ```rust
  use vanilla::uifont;
  
  let weights = [500, 700];
  assert_eq!(uifont::read_target_weights("400 700", &weights), vec![500, 700]);
  assert_eq!(uifont::read_target_weights("400", &weights), vec![500]);
  assert_eq!(uifont::read_target_weights("700", &weights), vec![700]);
  assert!(uifont::read_target_weights("100 450", &weights).is_empty());
  ```

- `pub fn load_ui_font(engine: &Engine, font_group: &str, text: &str) -> UiFontLoadHandle` (method, since 0.4.0): Loads the UI font. (registers and prioritizes the groups of the selected language and Latin, and prefetches that language's text. the original loadUiFont)
  - Call update every frame while receiving. Whether the initial text is ready is checked with is_ui_font_ready. (awaiting the returned handle waits until it is ready)
  - `engine` &Engine: Engine to receive assets with and register font faces on.
  - `font_group` &str: Font group name of the selected language. (group in the index fonts.json)
  - `text` &str: Text to prefetch. (such as all on-screen text of that language)
  - returns UiFontLoadHandle: Load handle that can be awaited.
- `pub fn update(engine: &Engine)` (method, since 0.4.0): Continues. (takes the received index and group lists, finishes the initial load, and fetches the remaining groups when the time comes. Call every frame)
  - Also fetches here the subsets for characters measured or drawn with this font that were not in the fetched subsets.
  - `engine` &Engine: Engine to receive assets with and register font faces on.
- `pub fn apply_ui_font_group(engine: &Engine, font_group: &str)` (method, since 0.4.0): Prioritizes the selected language's font group. (places that group right before Latin and reorders all faces, the original applyUiFontGroup)
  - Does nothing if no group has been received. Changing the order clears the engine's text cache.
  - `engine` &Engine: Engine to set the face order on.
  - `font_group` &str: Group name to prioritize. (the language's group when switching languages)
- `pub fn load_ui_font_text(engine: &Engine, text: &str) -> UiFontTextLoadHandle` (method, since 0.4.0): Fetches subsets for text. (only the faces that draw that text, the original loadUiFontText. Returns a handle that finishes once all requested faces are registered)
  - When the same file is registered with several weights, the bytes are fetched once and registered per weight.
  - Requests nothing if no group has been received or the text is empty. Faces already requested are not requested again.
  - `engine` &Engine: Engine to receive assets with and register font faces on.
  - `text` &str: Text to use. (finds the faces that draw each character at each weight)
  - returns UiFontTextLoadHandle: Handle that finishes once all faces requested this time are registered (or fail). A handle already finished if nothing was requested.

  Example: Nothing to request if no group has been received

  ```rust
  use vanilla::{uifont, Engine, EngineConfiguration};
  
  let engine = Engine::new(EngineConfiguration::new());
  let text_load_handle = uifont::load_ui_font_text(engine, "Player One");
  assert!(text_load_handle.get_font_load_handles().is_empty());
  assert!(text_load_handle.is_finished());
  ```

- `pub fn request_ui_font_text(engine: &Engine, text: &str)` (method, since 0.4.0): Requests subsets for text. (text that comes up on the fly like person names, only characters not seen before. the original requestUiFontText)
  - Does nothing if no group has been received. Returns no handle.
  - `engine` &Engine: Engine to receive assets with and register font faces on.
  - `text` &str: Text to use. (characters requested earlier are skipped)
- `pub fn wait_for_load() -> UiFontLoadFuture` (method, since 0.4.0): Future that waits for the initial load. (the await of the original await loadUiFont(group, text), same as awaiting the handle returned by load_ui_font)
  - Calls update every frame while waiting. As in the original, finishes once the initial text is all registered or wait_milliseconds passes. (is_ui_font_ready)
  - returns UiFontLoadFuture: Future that finishes when is_ui_font_ready becomes true.
- `pub fn is_ui_font_ready() -> bool` (method, since 0.4.0): Whether the initial load is ready. (true once the subsets of the initial text have all arrived or wait_milliseconds has passed, the wait of the original loadUiFont)
  - true if loading has not started or the list could not be read. (carries on with the system font)
  - returns bool: true if the initial load is ready.
- `pub fn read_ui_font_face() -> Option<String>` (method, since 0.4.0): Name of the loaded UI font. (given to the engine's text component with set_font_family, None if it could not be loaded. the original readUiFontFace)
  - returns Option<String>: Font name once the initial group has been received and registered. None if not yet or it could not be loaded.
- `pub fn build_ui_font_string(font_weight: u16, font_size: f64) -> String` (method, since 0.4.0): UI font string. (weight, size. the original buildUiFontString)
  - `font_weight` u16: Font weight. (a CSS weight like 500, 700)
  - `font_size` f64: Font size. (pixels)
  - returns String: Canvas2D font style text. (in the form `500 16px "GameUI", sans-serif`)
- `pub fn configure_ui_font(options: UiFontOptions)` (method, since 0.4.0): Sets the UI font. (call before loading, fields that are None stay unchanged. the original configureUiFont)
  - Giving primary_group also switches the currently selected group to it.
  - `options` UiFontOptions: Settings with only the fields to change filled with Some.
- `pub fn read_ui_font_family() -> String` (method, since 0.4.0): Returns the UI font name. (the original readUiFontFamily)
  - returns String: Font name to register. (initially "GameUI", returned even if not loaded)
