# core/textstringtexturecache (vanilla-engine 0.4.0)

> https://vanillapunch.com/docs/vanilla-engine/0.4.0/api/core/textstringtexturecache/

String texture cache.
- The original bakes text chunks once per font (mode, font string, bake scale, line width) into a glyph atlas (1024 x 1024 pages, up to 8 pages), and text is drawn as a list of glyph rectangles (entries, LRU limit 1024).
- Desktop places glyphs with text shaping (textshaping.rs: bidirectional ordering, rustybuzz shaping), rasterizes only glyphs seen for the first time (CoreText on Mac, DirectWrite on Windows, skrifa on Linux) and bakes them into atlas cells.
  There is one cell per text chunk, the same chunks as the original. Hangul, Han, kana, digits, punctuation and emoji get one cell per grapheme cluster, and letters such as Latin and Cyrillic get one cell per word.
  The cell key is, for every glyph in the chunk, (face, glyph index, size, Skia 1/4 subpixel slot) and its integer offset from the first glyph, plus mode and line width and antialiasing.
  (The original keys by a 1/8 position slot that holds every Skia slot boundary. Rust knows the slot Skia itself uses, so it bakes fewer copies of the same raster)
  Where the ink of neighboring chunks touches, each cell is drawn separately, so linear filtering at fractional positions and blending of overlapping ink can differ slightly from the whole string. (Same as the original, the shape of the Skia glyph cache and TextMeshPro)
  One row above and below each cell is baked as a repeat of the edge row. (Sampling past the cell edge at a fractional vertical position returns the edge row like the old CLAMP_TO_EDGE instead of another row of the atlas)
  Fonts above 256px, right-to-left text and the web (baked with the browser Canvas2D) are baked as a whole string into one cell like the original.
  The page policy (append only to the most recently opened page, a new page when it is full, clear the least recently used page beyond 8 pages), the entry limit and the entry key fields (mode, paragraph direction, font string, line width, scale, text) are the same as the original.
  The original joins the key into a string. Here, to avoid building a string on every lookup, the key is looked up by its hash and the keys inside the same hash are compared one by one.
- Text is baked in white and the color is multiplied when drawing. (A color change does not rebake)
  Color glyphs (emoji) are baked in their own color on top of the white text. The original also uploads a canvas filled with fillText in white, so emoji are baked in their own color and the same color is multiplied when drawing.
  When baking as an outline (Stroke), color glyphs are not stroked and are laid down in their own color. (Same as Chrome strokeText)
- The font string is read in the same form as Canvas2D font (the CSS font shorthand). Examples: "16px DOSGothic", "bold 24px default", "italic 500 16px default", "12pt 'A B', C, sans-serif"
  CSS units other than px (ex, ch, cap, ic, lh, rem, including viewport units), named sizes and calc() are read like the Chrome canvas does, and "/line-height" is skipped.
  For a comma separated name list, each character is looked up starting from the face of the first name. (Same as the browser font list, parse_font_string)
- As with the original document.fonts, several faces (weight, slant, character range) are registered under one name. (register_font_face)
  Selection follows the CSS order. When there is no slanted face a fake slant (slope 1/4) is applied per glyph, and when there is no bold face a fake bold is applied per glyph. (textshaping.rs)
- Characters missing from the faces of the name are looked up in the default font, the system font chain, the standard font (desktop, Chrome's -webkit-standard) and the fallback font, in that order. (The same place as browser font fallback)
  When no face is found at all in the name list (only unknown names other than default), the standard font is placed before the default font, as Chrome does.
  The desktop system font chain (set_system_font_chain) is the names of the original SYSTEM_FONT_STRING looked up in the operating system fonts, and it follows the default font only when the default font name default is requested.
  When enabled, names in the font string that were not uploaded are also looked up in the operating system fonts. A face is read the first time a character of that weight and slant is used. (platform/desktop/systemfont.rs)
  The fallback font is chosen by the operating system. (set_system_font_fallback_enabled, asking for bold asks for the bold face separately) As in Chrome, it asks separately for the first font (the first face that has the blank) and for each font string,
  and the fallback face draws only the characters the operating system chose that face for. Characters the face in the name list draws by canonical decomposition (ï as i and U+0308) are not asked. When candidate files are given (add_fallback_font_candidate) they are used first.
  Candidate files are read when used. For emoji presentation characters a candidate with a color glyph table is read first, and for other characters a candidate without one. (Only the table list is peeked first)
- When a font face is newly uploaded, only the strings baked with a font string that uses that name and that have a character in the face's character range are discarded. (The original invalidateFontFaces)
  As in the original this happens only when turned on with set_rebake_text_on_font_load. (The engine turns it on with EngineConfiguration.rebake_text_on_font_load, off by default)
  When off, text baked with another font before the download stays until it is evicted from the cache. Removing a face and reordering are discarded regardless.
  Changing the default font or the fallback font discards everything.
- As in the original, web always bakes and measures with the browser Canvas2D. (platform/web/systemfont.rs) The uploaded font bytes are uploaded to document.fonts as a FontFace and the browser selects and draws.
  When an uploaded font finishes loading (loadingdone) the baked text is discarded at the start of the frame. Desktop bakes with the shaping and rasterization above.
- Text anti-aliasing (set_text_antialias_enabled, the original setTextAntialiasEnabled): when off, the alpha of baked text is split into 0 and 255 at the threshold 128 and the texture is sampled with NEAREST.
  Projects that draw a pixel font at integer multiples of its design size turn it off. The original keeps it as a module global and leaves already baked text alone.
  Here the cache holds it and puts the on/off state in the key, so text drawn after the change is baked that way right away. (rasterize_text does not take it, like the original ShadowText)
- Text measuring (measure_text) is not redone when the font string and the text are the same. (The cache of the original measureTextMetrics, 2048 entries)
  The original discards the least recently used one on each overflow. Here, on overflow the least recently used half is discarded at once. (Searching one by one would scan 2048 entries on every measure after overflow)
  Registering a font clears it. (The original clears it when a web font finishes loading) Since measure_text takes &self the cache lives in a RefCell.
- Getting faces on demand (watch_unresolved_family_characters, take_unresolved_family_characters): the original browser downloads an uploaded FontFace when a character in its character range is drawn.
  The Rust edition collects characters, in measured or baked text of a watched name, that fall outside the range of the uploaded faces, and UIFont takes them out in update and downloads the pieces for those characters.
- Measuring without a Graphic (measure_text_without_graphic): the original measures text anywhere with a shared 2D canvas. The Rust edition tells a thread-wide global
  the font list (Rc) every time a font is registered and measures with that list. Used when UI layout needs the number of text lines before drawing. (UIConfirmWindow)

## TextEntry (struct) (Clone, Debug)

One text layout entry. (The entry of the original getEntry; all lengths are logical pixels, divided by the bake scale)
- Gives the rectangle of the string as if baked whole (quad_width, quad_height, pen_offset_x, baseline_offset_y) and
  the glyph rectangles relative to the top-left of that rectangle (glyph_textures, glyph_rects). Glyphs are baked once into the glyph atlas and shared by many strings.
- Place the top-left of the rectangle at (pen x - pen_offset_x, baseline y - baseline_offset_y) and draw each glyph by adding glyph_rects to that position. (Graphic::draw_text_entry)

Example: Placing the entry's glyph rectangles at the pen position and baseline

```rust
use vanilla::core::textstringtexturecache::{TextDrawKind, TextStringTextureCache};
use vanilla::{Rect, ShapingDirection};

fn calculate_glyph_quads(text_string_texture_cache: &mut TextStringTextureCache, gl: &vanilla::GlContext, pen_x: f64, baseline_y: f64) -> Vec<Rect> {
	let Some(entry) = text_string_texture_cache.get_entry(gl, TextDrawKind::Fill, "Score", "24px default", 0.0, 2.0, ShapingDirection::LeftToRight) else {
		return Vec::new();
	};
	let quad_x = pen_x - entry.pen_offset_x;
	let quad_y = baseline_y - entry.baseline_offset_y;
	entry.glyph_rects.iter().map(|glyph_rect| Rect::create(quad_x + glyph_rect[0], quad_y + glyph_rect[1], glyph_rect[2] - glyph_rect[0], glyph_rect[3] - glyph_rect[1])).collect()
}
```

- `pub glyph_textures: Rc<[crate::core::graphic::GlTexture]>` (field, since 0.4.0): Atlas page texture of each glyph. (Same order as glyph_rects, premultiplied RGBA of white text, color glyphs in their own color)
  - returns Rc<[crate::core::graphic::GlTexture]>
- `pub glyph_rects: Rc<[[f64; 8]]>` (field, since 0.4.0): Glyph rectangles. (Left, top, right, bottom in logical coordinates relative to the top-left of the string rectangle, and atlas texture coordinates u0, v0, u1, v1)
  - returns Rc<[[f64; 8]]>
- `pub advance_width: f64` (field, since 0.3.2): Advance width.
  - returns f64
- `pub font_ascent: f64` (field, since 0.3.2): Font ascent above the baseline. (positive)
  - returns f64
- `pub font_descent: f64` (field, since 0.3.2): Font descent below the baseline. (positive)
  - returns f64
- `pub pen_offset_x: f64` (field, since 0.3.2): Distance from the left of the string rectangle to the pen origin.
  - returns f64
- `pub baseline_offset_y: f64` (field, since 0.3.2): Distance from the top of the string rectangle to the baseline.
  - returns f64
- `pub quad_width: f64` (field, since 0.3.2): String rectangle width. (The texture width when baked whole divided by the bake scale)
  - returns f64
- `pub quad_height: f64` (field, since 0.3.2): String rectangle height. (The texture height when baked whole divided by the bake scale)
  - returns f64

## TextAtlasStatistics (struct) (Clone, Copy, Debug, Default, PartialEq, Eq)

Glyph atlas statistics. (The value returned by the original readAtlasStatistics, for tests and statistics)

Example: Statistics of a cache that has baked nothing

```rust
use vanilla::core::textstringtexturecache::TextStringTextureCache;

let text_string_texture_cache = TextStringTextureCache::new();
let text_atlas_statistics = text_string_texture_cache.read_atlas_statistics();
assert_eq!(text_atlas_statistics.atlas_page_count, 0);
assert_eq!(text_atlas_statistics.entry_count, 0);
```

- `pub atlas_page_count: usize` (field, since 0.4.0): Number of atlas pages.
  - returns usize
- `pub glyph_count: usize` (field, since 0.4.0): Number of glyphs held.
  - returns usize
- `pub baked_glyph_count: u64` (field, since 0.4.0): Number of glyphs baked so far.
  - returns u64
- `pub upload_count: u64` (field, since 0.4.0): Number of uploads to the atlas so far. (Several new glyphs placed next to each other count as one)
  - returns u64
- `pub entry_count: usize` (field, since 0.4.0): Number of text layout entries.
  - returns usize

## TextRaster (struct) (Clone, Debug)

Text shape raster. (coverage 0 ~ 255, lengths in pixels multiplied by the bake scale)
- coverage is the coverage of the text excluding color glyphs. If there are color glyphs (emoji), they are in color_pixels in their own colors. (premultiplied RGBA, same size)

Example: Get a text shape raster

```rust
use vanilla::core::textstringtexturecache::TextStringTextureCache;
use vanilla::platform::find_fallback_font_file;
use vanilla::ShapingDirection;

if let Some(source) = find_fallback_font_file("A", 400, false, false) {
	let font_bytes = std::fs::read(&source.path).expect("font file");
	let mut text_string_texture_cache = TextStringTextureCache::new();
	text_string_texture_cache.set_default_font(false, font_bytes).expect("font");
	let text_raster = text_string_texture_cache.rasterize_text("Hi", "20px default", 2.0, 2, ShapingDirection::LeftToRight).expect("raster");
	assert_eq!(text_raster.coverage.len(), (text_raster.width * text_raster.height) as usize);
	assert!(text_raster.origin_x >= 2.0);
	assert!(text_raster.baseline_y > 0.0);
}
```

- `pub coverage: Vec<u8>` (field, since 0.4.0): Coverage. (0 ~ 255, width * height values, from the top row)
  - returns Vec<u8>
- `pub color_pixels: Option<Vec<u8>>` (field, since 0.4.0): Color glyph layer. (premultiplied RGBA, width * height * 4 bytes, None if there are no color glyphs)
  - returns Option<Vec<u8>>
- `pub width: i32` (field, since 0.4.0): Raster width. (pixels)
  - returns i32
- `pub height: i32` (field, since 0.4.0): Raster height. (pixels)
  - returns i32
- `pub origin_x: f64` (field, since 0.4.0): Distance from the left of the raster to the pen origin. (pixels)
  - returns f64
- `pub baseline_y: f64` (field, since 0.4.0): Distance from the top of the raster to the baseline. (pixels)
  - returns f64
- `pub advance_width: f64` (field, since 0.4.0): Advance width. (pixels)
  - returns f64
- `pub font_ascent: f64` (field, since 0.4.0): Font ascent above the baseline. (pixels, positive)
  - returns f64
- `pub font_descent: f64` (field, since 0.4.0): Font descent below the baseline. (pixels, positive)
  - returns f64

## TextMetrics (struct) (Clone, Copy, Debug, Default)

String measurement result. (Canvas2D TextMetrics)
- actual_bounding_box_* is the distance glyphs actually reach from the pen origin (left alignment, alphabetic baseline). (left, up and down are positive in their direction)

Example: Measure text and check how far it actually reaches

```rust
use vanilla::core::textstringtexturecache::TextStringTextureCache;
use vanilla::platform::find_fallback_font_file;

if let Some(source) = find_fallback_font_file("A", 400, false, false) {
	let font_bytes = std::fs::read(&source.path).expect("font file");
	let mut text_string_texture_cache = TextStringTextureCache::new();
	text_string_texture_cache.set_default_font(false, font_bytes).expect("font");
	let text_metrics = text_string_texture_cache.measure_text("20px default", "Hg");
	assert!(text_metrics.width > 0.0);
	assert!(text_metrics.font_ascent > 0.0);
	assert!(text_metrics.actual_bounding_box_ascent > 0.0);
	assert!(text_metrics.actual_bounding_box_descent > 0.0);
}
```

- `pub width: f64` (field, since 0.3.2): Advance width. (pixels)
  - returns f64
- `pub font_ascent: f64` (field, since 0.3.2): Font ascent above the baseline. (line height value of the first face, positive)
  - returns f64
- `pub font_descent: f64` (field, since 0.3.2): Font descent below the baseline. (line height value of the first face, positive)
  - returns f64
- `pub actual_bounding_box_left: f64` (field, since 0.4.0): From the pen origin to the left edge of the glyphs. (positive to the left)
  - returns f64
- `pub actual_bounding_box_right: f64` (field, since 0.4.0): From the pen origin to the right edge of the glyphs. (positive to the right)
  - returns f64
- `pub actual_bounding_box_ascent: f64` (field, since 0.4.0): From the baseline to the top edge of the glyphs. (positive upward)
  - returns f64
- `pub actual_bounding_box_descent: f64` (field, since 0.4.0): From the baseline to the bottom edge of the glyphs. (positive downward)
  - returns f64

## FontDescription (struct) (Clone, Debug)

Font string parse result.
- font_weight is the CSS weight. ("bold" 700, a number, 400 if none) is_bold is whether the weight is 600 or more.

Example: Parse a font string

```rust
use vanilla::core::textstringtexturecache::parse_font_string;

let font_description = parse_font_string("italic bold 20px \"My Font\", sans-serif");
assert_eq!(font_description.font_size, 20.0);
assert_eq!(font_description.font_weight, 700);
assert!(font_description.is_bold);
assert!(font_description.is_italic);
assert_eq!(font_description.family_name, "My Font");
assert_eq!(font_description.family_name_list, vec!["My Font", "sans-serif"]);
```

- `pub font_size: f32` (field, since 0.3.2): Font size. (pixels)
  - returns f32
- `pub font_weight: u16` (field, since 0.4.0): CSS weight. (1 ~ 1000, 400 if none)
  - returns u16
- `pub is_bold: bool` (field, since 0.3.2): Whether the weight is 600 or more.
  - returns bool
- `pub is_italic: bool` (field, since 0.4.0): Whether it is italic or oblique.
  - returns bool
- `pub family_name: String` (field, since 0.3.2): First name in the list.
  - returns String
- `pub family_name_list: Vec<String>` (field, since 0.4.0): Comma-separated name list. (looked up from the first name)
  - A quoted name spelled like a generic name (serif, sans-serif, cursive, fantasy, monospace, system-ui, -webkit-body, math) keeps its quotes. ("'monospace'" → "\"monospace\"")
    Like Chrome, a quoted one is looked up as a font of that name and an unquoted one as the generic name.
  - returns Vec<String>

## FontFileSource (struct) (Clone, Debug, PartialEq, Eq)

Face of one font file. (desktop system font, found by the platform)
- If face_index is unknown (Mac), the face in the collection is found by post_script_name, and if that is missing too, chosen by weight and style.

Example: Add a font file chosen by the operating system as a face candidate for a system font name

```rust
use vanilla::core::textstringtexturecache::TextStringTextureCache;
use vanilla::platform::find_fallback_font_file;

let mut text_string_texture_cache = TextStringTextureCache::new();
assert!(!text_string_texture_cache.has_system_font());
if let Some(source) = find_fallback_font_file("A", 400, false, false) {
	assert!(source.path.exists());
	text_string_texture_cache.add_system_font_candidate("GameSans", 400, false, source);
	assert!(text_string_texture_cache.has_system_font());
}
```

- `pub path: std::path::PathBuf` (field, since 0.4.0): Font file path.
  - returns std::path::PathBuf
- `pub face_index: Option<u32>` (field, since 0.4.0): Face index within a font collection (TTC). (None if unknown)
  - returns Option<u32>
- `pub post_script_name: Option<String>` (field, since 0.4.0): PostScript name of the face. (None if unknown)
  - returns Option<String>

## FamilyFontFace (struct) (Clone, Debug, PartialEq, Eq)

One face of a system font name. (the weight and slant the operating system reports, a candidate for the CSS font-weight matching rule that picks a face)

Example: Build one bold face

```rust
use vanilla::core::textstringtexturecache::{FamilyFontFace, FontFileSource};

let face = FamilyFontFace {
	source: FontFileSource { path: std::path::PathBuf::from("GameSans-Bold.ttf"), face_index: None, post_script_name: None },
	weight: 700,
	is_italic: false,
};
assert_eq!(face.weight, 700);
```

- `pub source: FontFileSource` (field, since 0.4.0): Font file and face.
  - returns FontFileSource
- `pub weight: u16` (field, since 0.4.0): CSS weight of the face. (100 to 900)
  - returns u16
- `pub is_italic: bool` (field, since 0.4.0): True if the face is slanted.
  - returns bool

## TextStringTextureCache (struct) (Default)

String texture cache. (the original TextStringTextureCache, font face registration, text measuring, baking strings into textures)
- Graphic holds one. (get_text_string_texture_cache) Baking (get_entry) needs GL, while font registration, measuring and rasterizing work without GL.

Example: Register a font and measure text

```rust
use vanilla::core::textstringtexturecache::TextStringTextureCache;
use vanilla::platform::find_fallback_font_file;

let mut text_string_texture_cache = TextStringTextureCache::new();
assert!(text_string_texture_cache.register_font("GameFont", false, vec![0, 1, 2, 3]).is_err());
if let Some(source) = find_fallback_font_file("A", 400, false, false) {
	let font_bytes = std::fs::read(&source.path).expect("font file");
	text_string_texture_cache.register_font("GameFont", false, font_bytes).expect("font");
	assert_eq!(text_string_texture_cache.get_font_face_count("gamefont"), 1);
	let text_metrics = text_string_texture_cache.measure_text("20px GameFont", "Hello");
	assert!(text_metrics.width > 0.0);
}
```

- `pub fn new() -> TextStringTextureCache` (constructor, since 0.3.2): Constructor.
  - returns TextStringTextureCache: A cache with no fonts and no baked strings. (antialiasing on, rebaking off, the web bakes with the browser)
- `pub fn begin_frame(&mut self)` (method, since 0.3.2): Frame start. (counts the LRU order by frame number)
- `pub fn is_browser_raster(&self) -> bool` (method, since 0.4.0): Whether it bakes and measures with the browser Canvas2D. (always true on the web as in the original, false on desktop)
  - returns bool: True on the web, false on desktop.
- `pub fn register_font(&mut self, family_name: &str, is_bold: bool, font_bytes: Vec<u8>) -> Result<(), String>` (method, since 0.3.2): Registers a font. (looked up by the name in the font string. Case insensitive, a weight 700 face if bold, otherwise 400)
  - `family_name` &str: Name to use in font strings. (leading and trailing spaces and quotes are removed)
  - `is_bold` bool: True for a weight 700 face, false for a 400 face.
  - `font_bytes` Vec<u8>: Font file bytes. (ttf, otf, ttc use face 0, woff, woff2 are decompressed and read)
  - returns Result<(), String>: Ok if registered. Err(reason) if the font cannot be read, and nothing changes.
- `pub fn register_font_face(&mut self, family_name: &str, font_face_descriptors: FontFaceDescriptors, font_bytes: Vec<u8>) -> Result<(), String>` (method, since 0.4.0): Registers a font face. (the original adding new FontFace(family, url, descriptors) to document.fonts)
  - If the same name has a face with the same key (source_key), weight and style, it is replaced. Otherwise it goes at the end (the slot drawn first).
    For a name whose order was set with set_font_face_order, it is placed according to that order.
  - If turned on with set_rebake_text_on_font_load, strings baked with font strings using that name and containing characters in this face's character range are dropped. (rebaked with this face on the next draw)
  - `family_name` &str: Name. (leading and trailing spaces and quotes are removed and case is ignored)
  - `font_face_descriptors` FontFaceDescriptors: Weight, style, character range and key of the face.
  - `font_bytes` Vec<u8>: Font file bytes. (ttf, otf, ttc use face 0, woff, woff2 are decompressed and read)
  - returns Result<(), String>: Ok if registered. Err(reason) if the font cannot be read, and nothing changes.

  Example: Register and remove a Latin character range face

  ```rust
  use vanilla::core::textstringtexturecache::TextStringTextureCache;
  use vanilla::platform::find_fallback_font_file;
  use vanilla::FontFaceDescriptors;
  
  if let Some(source) = find_fallback_font_file("A", 400, false, false) {
  	let font_bytes = std::fs::read(&source.path).expect("font file");
  	let mut text_string_texture_cache = TextStringTextureCache::new();
  	let mut font_face_descriptors = FontFaceDescriptors::create_from_css("400", "normal", "U+0000-00FF");
  	font_face_descriptors.source_key = String::from("latin");
  	text_string_texture_cache.register_font_face("GameFont", font_face_descriptors, font_bytes).expect("font");
  	assert_eq!(text_string_texture_cache.get_font_face_count("GameFont"), 1);
  	assert!(text_string_texture_cache.unregister_font_face("GameFont", "latin"));
  	assert_eq!(text_string_texture_cache.get_font_face_count("GameFont"), 0);
  }
  ```

- `pub fn unregister_font_face(&mut self, family_name: &str, source_key: &str) -> bool` (method, since 0.4.0): Removes a font face. (the original document.fonts.delete, all faces with the same key, true if any were removed)
  - `family_name` &str: Name. (leading and trailing spaces are removed and case is ignored)
  - `source_key` &str: Key of the face to remove. (source_key of FontFaceDescriptors)
  - returns bool: True if any face was removed.
- `pub fn set_font_face_order(&mut self, family_name: &str, source_key_list: &[String])` (method, since 0.4.0): Sets the face order of one name. (a list of face keys, later ones draw first. What the original uifont does by removing them from document.fonts and adding them back in order)
  - Faces not in the list are not pushed behind the listed faces (to draw later) and stay in front. Keys of faces not loaded yet can be included too. (placed there once loaded)
  - When the order changes, all strings baked with that name are dropped.
  - `family_name` &str: Name. (leading and trailing spaces are removed and case is ignored)
  - `source_key_list` &[String]: Face key list. (later ones draw first)
- `pub fn clear(&mut self)` (method, since 0.4.0): Discards all entries and glyphs. (The original clear; atlas page textures are deleted at the next bake)
- `pub fn set_default_font(&mut self, is_bold: bool, font_bytes: Vec<u8>) -> Result<(), String>` (method, since 0.3.2): Sets the default font. (used for font strings whose name is not found and for character fallback, a weight 700 face if bold)
  - `is_bold` bool: True for a weight 700 face, false for a 400 face. (replaces the non-italic face of the same weight)
  - `font_bytes` Vec<u8>: Font file bytes. (ttf, otf, ttc use face 0, woff, woff2 are decompressed and read)
  - returns Result<(), String>: Ok if set. (all baked strings are dropped) Err(reason) if the font cannot be read.
- `pub fn add_fallback_font(&mut self, font_bytes: Vec<u8>) -> Result<(), String>` (method, since 0.3.2): Adds a fallback font. (looks up characters missing from the earlier fonts)
  - `font_bytes` Vec<u8>: Font file bytes. (ttf, otf, ttc use face 0, woff, woff2 are decompressed and read)
  - returns Result<(), String>: Ok if added. (all baked strings are dropped) Err(reason) if the font cannot be read.
- `pub fn set_text_antialias_enabled(&mut self, value: bool)` (method, since 0.4.0): Turns text antialiasing on / off. (the original setTextAntialiasEnabled, text drawn after the change is baked that way)
  - `value` bool: True to turn it on. (on by default)
- `pub fn is_text_antialias_on(&self) -> bool` (method, since 0.4.0): Whether text antialiasing is on. (the original isTextAntialiasOn)
  - returns bool: true if enabled.
- `pub fn set_rebake_text_on_font_load(&mut self, is_rebake_text_on_font_load: bool)` (method, since 0.4.0): Sets whether to drop strings baked with a face's characters when a new font face is registered. (the original EngineConfiguration.rebakeTextOnFontLoad, set when the engine takes over the graphic)
  - `is_rebake_text_on_font_load` bool: True to drop them. (off by default)
- `pub fn get_font_registration_count(&self) -> u64` (method, since 0.4.0): Number of times fonts were registered. (registration, removal, order, default font, fallback font. Decides whether cached text widths are measured again)
  - returns u64: Registration count. (only increases from 0 after new)
- `pub fn set_system_font_chain(&mut self, family_name_list: Vec<String>)` (method, since 0.4.0): Sets the system font chain. (Desktop, like the original SYSTEM_FONT_STRING, looked up in name order after the default font for a font string that requests the default font name default)
  - When on, names in the font string that were not uploaded are also looked up in the operating system fonts. ("16px Arial" is drawn with the system Arial, same as the browser)
  - A face is read the first time a character of that weight and slant is drawn or measured.
  - `family_name_list` Vec<String>: Order of names to look up after the default font. (case is ignored)
- `pub fn add_system_font_candidate(&mut self, family_name: &str, weight: u16, is_italic: bool, source: FontFileSource)` (method, since 0.4.0): Adds a face candidate file to a system font name. (desktop, puts that name at the end of the chain. For when a file is given instead of searching the operating system)
  - Without a face index, the face in the collection is chosen by PostScript name, and without that, by the requested weight and style. For variable fonts the weight is made from an axis value.
  - `family_name` &str: System font name. (leading and trailing spaces are removed and case is ignored)
  - `weight` u16: Weight of this candidate. (CSS weight 1 ~ 1000)
  - `is_italic` bool: Whether it is an italic face.
  - `source` FontFileSource: Font file and face. (a candidate with the same file, weight and style is held only once)
- `pub fn set_system_font_fallback_enabled(&mut self, value: bool)` (method, since 0.4.0): Turns operating system fallback fonts on / off. (desktop, when on, characters missing from every font are drawn with a font chosen by the operating system. Fallback font candidate files come first if any)
  - `value` bool: True to turn it on. (off by default)
- `pub fn has_system_font(&self) -> bool` (method, since 0.4.0): Whether there is a system font chain or candidate. (desktop)
  - returns bool: True if the chain has a found name or a name with candidates, or the chain is enabled and has at least one name.
- `pub fn add_fallback_font_candidate(&mut self, font_path: std::path::PathBuf)` (method, since 0.4.0): Adds a fallback font candidate file. (desktop, where the original browser draws characters missing from fonts with system fonts)
  - Not read right away. When measuring or baking characters missing from every registered font, candidates are read from the front and added as fallback fonts. (so large CJK fonts are not read at startup)
  - Missing or unreadable files are skipped.
  - `font_path` std::path::PathBuf: Font file path. (only peeks whether it has a color glyph table when added)
- `pub fn has_default_font(&self) -> bool` (method, since 0.3.2): Whether there is a default font.
  - returns bool: True if there is at least one default font face.
- `pub fn get_font_face_count(&self, family_name: &str) -> usize` (method, since 0.4.0): Number of faces registered under the name. (0 if the name does not exist)
  - `family_name` &str: Name. (leading and trailing spaces are removed and case is ignored)
  - returns usize: Face count.
- `pub fn measure_text(&self, font_string: &str, text: &str) -> TextMetrics` (method, since 0.3.2): Measures a string. (paragraph direction left to right, the original measureTextMetrics does not take a direction either)
  - `font_string` &str: Font string. (Canvas2D font form, parse_font_string)
  - `text` &str: Text to measure.
  - returns TextMetrics: Measured values. (pixels) All 0 if there is no face to draw with on desktop.

  Example: The same text is measured only once

  ```rust
  use vanilla::core::textstringtexturecache::TextStringTextureCache;
  use vanilla::platform::find_fallback_font_file;
  
  if let Some(source) = find_fallback_font_file("A", 400, false, false) {
  	let font_bytes = std::fs::read(&source.path).expect("font file");
  	let mut text_string_texture_cache = TextStringTextureCache::new();
  	text_string_texture_cache.set_default_font(false, font_bytes).expect("font");
  	let small_metrics = text_string_texture_cache.measure_text("20px default", "abc");
  	text_string_texture_cache.measure_text("20px default", "abc");
  	assert_eq!(text_string_texture_cache.get_measure_count(), 1);
  	let large_metrics = text_string_texture_cache.measure_text("40px default", "abc");
  	assert!(large_metrics.width > small_metrics.width);
  	assert_eq!(text_string_texture_cache.get_measure_count(), 2);
  }
  ```

- `pub fn get_measure_count(&self) -> usize` (method, since 0.4.0): Number of measured texts. (those in the cache, for tests and statistics)
  - returns usize: Number of measured texts in the cache. (half is dropped on overflow, limit 2048)
- `pub fn get_entry(&mut self, gl: &GlContext, text_draw_kind: TextDrawKind, text: &str, font_string: &str, line_width: f64, bake_scale: f64, direction: ShapingDirection) -> Option<TextEntry>` (method, since 0.3.2): Returns a text layout entry. (If missing, lays it out and bakes only glyphs seen for the first time into the atlas; direction is the paragraph direction, textDirection of the original getEntry)
  - Glyph atlas: glyphs are baked once into 1024 x 1024 pages. They are appended only to the most recently opened page, a new page is opened when it is full, and the least recently used page is cleared beyond 8 pages.
    The texture of a cleared page goes to a discard list and is deleted at the next get_entry. (Graphic flushes the pending batch first and deletes it right away)
  - Glyph positions from the shaper are split into an integer position and 4 subpixel slots like Chrome Skia. Each text chunk (one per character for Hangul, digits and similar, one per word for Latin words) is baked into one cell. Fonts above 256px and right-to-left text are baked as a whole string.
  - `gl` &GlContext: GL context to create the texture with.
  - `text_draw_kind` TextDrawKind: Bake mode.
  - `text` &str: Text to bake.
  - `font_string` &str: Font string. (Canvas2D font form, parse_font_string)
  - `line_width` f64: Outline width. (logical pixels, used only when baking as Stroke but always part of the key)
  - `bake_scale` f64: Bake scale. (bakes at the text size multiplied by this, and TextEntry lengths are divided by it)
  - `direction` ShapingDirection: Paragraph direction.
  - returns Option<TextEntry>: Text layout entry. (The cached one for the same key) None if the text is empty, there is no face to draw with on desktop, or the texture cannot be created.

  Example: Calling again with the same key neither bakes nor uploads

  ```rust
  use vanilla::core::textstringtexturecache::{TextDrawKind, TextStringTextureCache};
  use vanilla::ShapingDirection;
  
  fn bake_outline(text_string_texture_cache: &mut TextStringTextureCache, gl: &vanilla::GlContext) {
  	text_string_texture_cache.get_entry(gl, TextDrawKind::Stroke, "Hello", "bold 20px default", 3.0, 1.5, ShapingDirection::LeftToRight);
  	let first_statistics = text_string_texture_cache.read_atlas_statistics();
  	text_string_texture_cache.get_entry(gl, TextDrawKind::Stroke, "Hello", "bold 20px default", 3.0, 1.5, ShapingDirection::LeftToRight);
  	assert_eq!(text_string_texture_cache.read_atlas_statistics(), first_statistics);
  }
  ```

- `pub fn rasterize_text(&self, text: &str, font_string: &str, bake_scale: f64, padding: i32, direction: ShapingDirection) -> Option<TextRaster>` (method, since 0.4.0): Gets only the text shape as a raster. (not uploaded as a texture, used by those that bake separately, like text with a drop shadow)
  - The web gets it with the browser Canvas2D as in the original. None if there are no fonts at all on desktop.
  - `text` &str: Text.
  - `font_string` &str: Font string. (Canvas2D font form, parse_font_string)
  - `bake_scale` f64: Bake scale. (multiplied by the text size)
  - `padding` i32: Edge padding. (pixels, 1 if less than 1)
  - `direction` ShapingDirection: Paragraph direction.
  - returns Option<TextRaster>: Raster. None if the text is empty or there is no face to draw with on desktop.
- `pub fn rasterize_text_with_color(&self, text: &str, font_string: &str, bake_scale: f64, padding: i32, direction: ShapingDirection, color: Color) -> Option<TextRaster>` (method, since 0.4.0): Get only the shape of the text as a raster, telling the text color. (same as rasterize_text, and the Mac desktop gamma-corrects the coverage by the text color luminance like Chrome)
  - Used by the side the original bakes in the text color into Canvas2D as is (text with a shadow underneath, fillText of the 2D canvas). Text baked white and multiplied by color is the same as rasterize_text.
  - `text` &str: Text.
  - `font_string` &str: Font string. (Canvas2D font form, parse_font_string)
  - `bake_scale` f64: Bake scale. (multiplied by the text size)
  - `padding` i32: Edge padding. (pixels, 1 if less than 1)
  - `direction` ShapingDirection: Paragraph direction.
  - `color` Color: Text color. (alpha is not used; when painting with a gradient or pattern, gray 0.5 like the original Skia)
  - returns Option<TextRaster>: Raster. None if the text is empty or there is no face to draw with on desktop.

  Example: Get the coverage of black text

  ```rust
  use vanilla::core::textstringtexturecache::TextStringTextureCache;
  use vanilla::platform::find_fallback_font_file;
  use vanilla::{Color, ShapingDirection};
  
  if let Some(source) = find_fallback_font_file("A", 400, false, false) {
  	let mut text_string_texture_cache = TextStringTextureCache::new();
  	text_string_texture_cache.set_default_font(false, std::fs::read(&source.path).expect("font file")).expect("font");
  	let text_raster = text_string_texture_cache.rasterize_text_with_color("Ag", "24px default", 1.0, 2, ShapingDirection::LeftToRight, Color::black()).expect("raster");
  	assert_eq!(text_raster.coverage.len(), (text_raster.width * text_raster.height) as usize);
  	assert!(text_raster.coverage.iter().any(|value| *value == 255));
  }
  ```

- `pub fn rasterize_character(&self, character: &str, font_string: &str) -> Option<(textshaping::GlyphRaster, f32, f32, f32)>` (method, since 0.4.0): Rasterizes one glyph. (used by the glyph atlas, the glyph index is found by character. The web uses the browser Canvas2D, None if there are no fonts at all on desktop)
  - Returns: (raster, advance width, font ascent, font descent) lengths in pixels.
  - `character` &str: One grapheme cluster. (gathered into one image even if combining marks make it several glyphs)
  - `font_string` &str: Font string. (Canvas2D font form, parse_font_string)
  - returns Option<(textshaping::GlyphRaster, f32, f32, f32)>: (raster, advance width, font ascent, font descent). An empty raster if there are no glyphs to draw (space). None if there is no face to draw with on desktop.

  Example: Raster and advance width of one character

  ```rust
  use vanilla::core::textstringtexturecache::TextStringTextureCache;
  use vanilla::platform::find_fallback_font_file;
  
  if let Some(source) = find_fallback_font_file("A", 400, false, false) {
  	let font_bytes = std::fs::read(&source.path).expect("font file");
  	let mut text_string_texture_cache = TextStringTextureCache::new();
  	text_string_texture_cache.set_default_font(false, font_bytes).expect("font");
  	let (glyph_raster, advance_width, font_ascent, _) = text_string_texture_cache.rasterize_character("A", "32px default").expect("glyph");
  	assert!(glyph_raster.width > 0 && glyph_raster.height > 0);
  	assert!(advance_width > 0.0 && font_ascent > 0.0);
  	let (space_raster, space_advance_width, _, _) = text_string_texture_cache.rasterize_character(" ", "32px default").expect("space");
  	assert_eq!(space_raster.width, 0);
  	assert!(space_advance_width > 0.0);
  }
  ```

- `pub fn get_entry_count(&self) -> usize` (method, since 0.3.2): Number of text layout entries.
  - returns usize: Number of text layout entries in the cache. (Limit 1024)
- `pub fn read_atlas_statistics(&self) -> TextAtlasStatistics` (method, since 0.4.0): Glyph atlas statistics. (The original readAtlasStatistics, for tests and statistics: page count, glyph count, glyphs baked so far, uploads so far, entry count)
  - returns TextAtlasStatistics: The current statistics.

  Example: Text baked for the first time opens an atlas page and adds one entry

  ```rust
  use vanilla::core::textstringtexturecache::{TextDrawKind, TextStringTextureCache};
  use vanilla::ShapingDirection;
  
  fn bake_once(text_string_texture_cache: &mut TextStringTextureCache, gl: &vanilla::GlContext) {
  	let entry_count = text_string_texture_cache.read_atlas_statistics().entry_count;
  	text_string_texture_cache.get_entry(gl, TextDrawKind::Fill, "Score 100", "20px default", 0.0, 1.0, ShapingDirection::LeftToRight);
  	let text_atlas_statistics = text_string_texture_cache.read_atlas_statistics();
  	assert!(text_atlas_statistics.atlas_page_count >= 1);
  	assert!(text_atlas_statistics.baked_glyph_count >= 1);
  	assert_eq!(text_atlas_statistics.entry_count, entry_count + 1);
  }
  ```

## Functions and constants

- `pub fn watch_unresolved_family_characters(family_name: &str)` (method, since 0.4.0): Starts watching characters with no face for a name. (in the original browser, once a FontFace is added to document.fonts, the canvas starts loading the face whose range contains the characters when drawing text with that font)
  - The Rust version registers faces after loading, so it collects characters not in the character ranges of registered faces from text measured or baked with watched names, and the loader (UIFont) takes them out and loads them.
  - `family_name` &str: Name to watch. (leading and trailing spaces are removed and case is ignored)
- `pub fn take_unresolved_family_characters(family_name: &str) -> String` (method, since 0.4.0): Takes out characters that had no face in watched names. (cleared when taken, empty text if the name is not watched)
  - `family_name` &str: Watched name. (leading and trailing spaces are removed and case is ignored)
  - returns String: Text joining the collected characters in code point order. (spaces and control characters are not collected)

  Example: Collect characters measured with a name that has no registered face

  ```rust
  use vanilla::core::textstringtexturecache::{take_unresolved_family_characters, watch_unresolved_family_characters, TextStringTextureCache};
  
  watch_unresolved_family_characters("GameFont");
  let text_string_texture_cache = TextStringTextureCache::new();
  text_string_texture_cache.measure_text("16px GameFont", "b a");
  assert_eq!(take_unresolved_family_characters("gamefont"), "ab");
  assert_eq!(take_unresolved_family_characters("GameFont"), "");
  assert_eq!(take_unresolved_family_characters("OtherFont"), "");
  ```

- `pub fn measure_normal_line_height_without_graphic(font_string: &str) -> Option<f64>` (method, since 0.4.0): Measures the line height of CSS line-height normal without a Graphic. (font string, in Chrome the LineSpacing of the first usable font (primary font))
  - On desktop, computed with the first face of the same face selection as drawing. (LoadedFont::calculate_normal_line_height) None if there are no fonts at all.
  - On the web, reads the line height the browser lays out. (platform/web/systemfont.rs)
  - `font_string` &str: Text in Canvas2D font form. (like "bold 16px sans-serif")
  - returns Option<f64>: Line height. (CSS pixels) None on desktop if there is no glyph cache with registered fonts or no face to choose, and on the web if there is no document or the measured height is 0 or less.
- `pub fn measure_text_without_graphic(font_string: &str, text: &str) -> Option<TextMetrics>` (method, since 0.4.0): Measures text without a Graphic. (font string and text, in place of the original shared canvas measureText)
  - Measures with the same face selection and shaping as drawing.
  - The web measures with the browser Canvas2D. Desktop returns None if there are no fonts at all. (a state where no text appears when drawing either)
  - `font_string` &str: Font string. (Canvas2D font form, parse_font_string)
  - `text` &str: Text to measure.
  - returns Option<TextMetrics>: Measured values. (pixels) None on desktop if there is no cache with fonts registered on this thread yet, or no face to choose for that font string.

  Example: Measure without a Graphic after registering a font

  ```rust
  use vanilla::core::textstringtexturecache::{measure_text_without_graphic, TextStringTextureCache};
  use vanilla::platform::find_fallback_font_file;
  
  assert!(measure_text_without_graphic("16px default", "Hello").is_none());
  if let Some(source) = find_fallback_font_file("A", 400, false, false) {
  	let font_bytes = std::fs::read(&source.path).expect("font file");
  	let mut text_string_texture_cache = TextStringTextureCache::new();
  	text_string_texture_cache.set_default_font(false, font_bytes).expect("font");
  	let text_metrics = measure_text_without_graphic("16px default", "Hello").expect("metrics");
  	assert!(text_metrics.width > 0.0);
  }
  ```

- `pub fn parse_font_string(font_string: &str) -> FontDescription` (method, since 0.3.2): Parses a font string. (the CSS font shorthand of Canvas2D font, "bold 16px DOSGothic" → size 16, weight 700, name DOSGothic)
  - Words before the size: normal, italic / oblique (a following angle is skipped) set italic, small-caps and stretch words (condensed etc.) are skipped.
    bold / bolder is 700, lighter is 100, numbers are the weight (1 ~ 1000). Any other word makes it an invalid string.
  - Size: absolute lengths (px, pt, pc, in, cm, mm, q), font-relative lengths (em, ex, ch, cap, ic, lh, rem, rex, rch, rcap, ric, rlh), %, viewport units, named sizes, larger, smaller,
    CSS math functions like calc(). A following "/line-height" is read and skipped. (the canvas does not use line height) parse_css_font_size computes it the same as Chrome.
    The canvas the original bakes and measures text on is not attached to the document, so the parent font is Chrome's last fallback font (Times on Mac) at 10px, and the root is the document's standard font at 16px.
    The web gets sizes other than absolute lengths by putting them into a browser canvas and reading them back. (resolve_font_size in platform/web/systemfont.rs)
  - After the size is a comma-separated name list. Quoted names have their quotes removed, unquoted names have their words joined with a single space. The drawing side looks up from the first name in the list.
  - An invalid string (no size or name, negative size, unknown word) is treated as the canvas initial value "10px sans-serif".
  - `font_string` &str: Font string.
  - returns FontDescription: Parse result. Size 10, weight 400, name sans-serif if the string is invalid.

  Example: CSS units, line height, invalid strings

  ```rust
  use vanilla::core::textstringtexturecache::parse_font_string;
  
  assert_eq!(parse_font_string("12pt a").font_size, 16.0);
  assert_eq!(parse_font_string("1in a").font_size, 96.0);
  let line_height_description = parse_font_string("bold 16px/20px a, b");
  assert_eq!(line_height_description.font_size, 16.0);
  assert_eq!(line_height_description.family_name_list, vec!["a", "b"]);
  let invalid_description = parse_font_string("16px");
  assert_eq!(invalid_description.font_size, 10.0);
  assert_eq!(invalid_description.family_name, "sans-serif");
  ```

- `pub fn set_font_viewport_size(width: f32, height: f32)` (method, since 0.4.0): Sets the window size that viewport units (vw, vh and such) in font strings refer to. (logical pixels, in place of the original window.innerWidth / innerHeight. The desktop platform calls it when the window size changes)
  - `width` f32: Window width. (logical pixels)
  - `height` f32: Window height. (logical pixels)

## TextDrawKind (enum) (Clone, Copy, Debug, PartialEq, Eq, Hash)

Bake mode.

- `Fill`: Bake filled. (the original fillText)
- `Stroke`: Bake as an outline. (the original strokeText, width is line_width)
