# core/textshaping (vanilla-engine 0.4.0)

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

Text shaping. (picking font faces, bidirectional ordering, joining glyph shapes, glyph rasterization)
- In the original the browser's Canvas2D does all of this. (CSS font selection, the bidirectional algorithm, HarfBuzz shaping, Skia rasterization)
  The Rust version follows the same sequence with crates:
  - Font faces (FontFaceDescriptors): like CSS @font-face, several faces with different weights, slants and character ranges (unicode-range) sit under one name.
    Selection follows the CSS Fonts order (slant, then weight), and faces with the same weight and slant are split by character range when drawing. A face added later wins.
  - Bidirectional ordering: unicode-bidi (UAX #9). The paragraph direction is given by the baking side. (original canvas.direction)
  - Shaping: rustybuzz (a port of HarfBuzz). Arabic joining, ligatures, kerning and combining mark placement come out like the browser.
    Like Chrome's HarfBuzzFace::GetScaledFont, the position scale is set to the font size as a 16.16 fixed-point number. rustybuzz 0.20.1 has no scale,
    so the repository carries a build of third_party/rustybuzz with hb_font_set_scale (Face::set_scale) added. Font-unit values are rounded from that scale with em_scale, variable GPOS deltas with em_scalef,
    and axis values are normalized like HarfBuzz hb_ot_var_normalize_coords. The bundled third_party/ttf-parser is a build with the device table base of pair kerning (PairPos format 1) corrected.
  - Rasterization: fontdue's glyph-index rasterization. Faces with no bold get a fake bold, and faces with no italic get a fake italic, applied per glyph.
    Color glyphs (sbix, CBDT, COLR) are drawn in their own colors by colorglyph.rs. Like Chrome, fake italic is applied and fake bold is not.
- Emoji presentation: a face in the name list is used first if it has the glyph, regardless of color. In the operating system fallback step, VS16 (FE0F), Emoji_Presentation characters, skin tone modifiers, flags, keycaps and tag sequences
  pick a face with color glyphs first, and everything else (including VS15) picks a non-color face first. A sequence carrying a variation selector accepts only the face matching that presentation even in the name list.
  Chrome draws ❤️ (FE0F) with the color emoji font and a bare ❤ with the specified font, even if the specified font has a monochrome ❤. (checked with Canvas2D on Mac Chrome)
  Linux Chrome 157 draws a bare 😀 in "16px DejaVu Sans" with DejaVu Sans's monochrome glyph. (measureText on CI)
- Fake italic and fake bold are the same values Chromium gives Skia:
  slant 1/4 (setSkewX(-SK_Scalar1 / 4) in font_platform_data.cc), and bold widens the outline by painting a stroke of 1/24 (9px and below) to 1/32 (36px and above) of the font size.
  (kStdFakeBoldInterpKeys / Values in Skia SkTextFormatParams.h) Both leave the advance unchanged.
  Fake bold applies when the requested weight is 600 or more and the chosen face is below 600. (Blink kBoldThreshold)
- Font bytes are held by LoadedFont together with the rustybuzz face. (self_cell, the face borrows the bytes) When the registration is removed and nothing uses it, the bytes are given back too.
  Several faces of the same file (the weights of a TTC, the weight instances of a variable font) share the bytes (Rc).
- Font collections like TTC are read by choosing a face index (face_index). (find_collection_face_index picks it by weight and slant)
- Variable fonts (the wght axis of fvar) make weight instances from axis values. (variation_list of create_from_shared_bytes) Shaping reads the axis values in rustybuzz,
  but fontdue cannot read axis values and cannot draw the outlines of variable fonts like Mac SFNS, so variable fonts take outlines with axis values applied from skrifa and are drawn with colorglyph's area-accumulation raster.
  (Chrome also draws the weight of a variable font from axis values)
- Optical size (opsz axis) and the tracking table (trak): Chrome sets the font's opsz axis to the font size. (initial value auto of font-optical-sizing, FontPlatformDataFromCTFont in Mac font_platform_data_mac.mm,
  font_custom_platform_data.cc for web fonts on every operating system. It is not applied to Windows and Linux system fonts)
  Shaping gives HarfBuzz the font size as ptem and adds the tracking of the AAT trak table. (GetScaledFont in harfbuzz_face.cc, on Mac the advances of a font that has trak and no sbix
  are computed by HarfBuzz instead of CoreText) The Rust version also sets opsz with the baking size (the original grows the px of the font string by the baking scale) and adds trak.
  trak is added here like HarfBuzz 15 (hb-aat-layout-trak-table.hh), not by rustybuzz. Between sizes it joins straight without rounding, outside the start and end of the table
  it is the end value, and it is added only to the advance of the first glyph of a cluster. It is not applied to fonts with no STAT table.
  (rustybuzz 0.20 rounds to integer font units, extends past the table, adds half to x_offset too, and does not look at STAT)
  The Mac system UI font (SFNS, opsz 17 to 96, initial 28) matches Chrome at 16px with opsz 17 and trak -40 units. (color emoji keep CoreText's advance as is)
- Per-word shaping: the Chrome canvas (SegmentWord in platform/fonts/plain_text_node.cc) splits text into words and shapes each separately. There is no kerning or ligature across a space.
  Space (U+0020), tab and ZWSP stand alone, and CJK characters and emoji are separate per character. (find_chrome_word_end) Tab, line feed, form feed and carriage return in the canvas are turned into spaces.
- Mac: glyphs are drawn with CoreText like the original Chrome on Mac. (platform/desktop/coretextglyph.rs) Non-color glyphs are an A8 mask with the same settings as Chrome Canvas2D (font smoothing,
  undoing CoreGraphics gamma, gamma precorrection by text color luminance, quarter-pixel subpixel positions), and color emoji fonts read from files (sbix) are CoreText color pictures. (rasterize_glyph_at)
  The advance of color emoji is multiplied by the ratio at which CoreText enlarges them at small sizes and rounded to whole pixels. (20 at 16px, 16 at 13px, same as Chrome measureText)
- Windows: non-color glyphs are drawn with DirectWrite like Chrome on Windows. (platform/desktop/directwriteglyph.rs, grayscale A8 and gamma precorrection of Skia SkScalerContext_DW, quarter-pixel subpixel positions)
- Linux: Chrome 158 on Linux draws fonts with Skia Fontations (skrifa), not FreeType. The Rust version also hints skrifa outlines with fontconfig's hinting level,
  precorrects with gamma 1.2 and contrast 0.2, and uses quarter-pixel subpixel positions. (rasterize_hinted_outline_mask)

Example: Tell emoji presentation from text presentation

```rust
use vanilla::core::textshaping::is_emoji_presentation;

assert!(is_emoji_presentation("\u{1F600}"));
assert!(is_emoji_presentation("\u{2764}\u{FE0F}"));
assert!(!is_emoji_presentation("\u{2764}"));
assert!(!is_emoji_presentation("\u{1F600}\u{FE0E}"));
assert!(is_emoji_presentation("\u{1F1F0}\u{1F1F7}"));
assert!(!is_emoji_presentation("A"));
```

## SystemFontMeasure (type)

Measures a system font segment. (segment text, whether right to left → advance in pixels)

```rust
pub type SystemFontMeasure<'a> = &'a dyn Fn(&str, bool) -> f32
```

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

Font face descriptors. (the original FontFace descriptors: weight, style, unicodeRange)
- Weight is held as a range. (like a variable font's "100 900", a single value has the same start and end)
- An empty character range means all characters.
- source_key is the key that identifies a face under the same name. (usually the file path, used for ordering and removal)

Example: Create from CSS descriptor text and check the character range

```rust
use vanilla::FontFaceDescriptors;

let font_face_descriptors = FontFaceDescriptors::create_from_css("100 900", "italic", "U+AC00-D7A3");
assert_eq!((font_face_descriptors.minimum_weight, font_face_descriptors.maximum_weight), (100, 900));
assert!(font_face_descriptors.is_italic);
assert!(font_face_descriptors.contains_character('\u{AC00}'));
assert!(!font_face_descriptors.contains_character('A'));
assert!(FontFaceDescriptors::new().contains_character('A'));
assert_eq!(FontFaceDescriptors::create_with_bold(true).minimum_weight, 700);
```

- `pub minimum_weight: u16` (field, since 0.4.0): Start of the weight range. (CSS weight 1 ~ 1000, default 400)
  - returns u16
- `pub maximum_weight: u16` (field, since 0.4.0): End of the weight range. (same as minimum_weight for a single value)
  - returns u16
- `pub is_italic: bool` (field, since 0.4.0): Whether it is an italic face.
  - returns bool
- `pub unicode_range_list: Vec<(u32, u32)>` (field, since 0.4.0): List of character ranges. ((start, end) code points, end inclusive. Empty means all characters)
  - returns Vec<(u32, u32)>
- `pub source_key: String` (field, since 0.4.0): Face key. (empty text by default)
  - returns String
- `pub is_system_fallback: bool` (field, since 0.4.0): Whether this is a face of a fallback font chosen by the operating system. (also fallback fonts and the last resort font; the fallback stage looked at after all faces of the name list for each character, where emoji presentation picks a color glyph face first. Default false)
  - returns bool
- `pub fn new() -> FontFaceDescriptors` (constructor, since 0.4.0): Creates. (weight 400, not italic, all characters. Same as the original FontFace with no descriptors given)
  - returns FontFaceDescriptors: Descriptors with weight 400, not italic, all characters, and an empty key.
- `pub fn create_with_bold(is_bold: bool) -> FontFaceDescriptors` (static, since 0.4.0): Creates from whether the face is bold. (700 if bold, otherwise 400)
  - `is_bold` bool: Weight 700 if true, 400 if false.
  - returns FontFaceDescriptors: Descriptors. (everything other than weight is the same as new)
- `pub fn create_from_css(weight: &str, style: &str, unicode_range: &str) -> FontFaceDescriptors` (static, since 0.4.0): Creates from CSS descriptor text. (the original { weight, style, unicodeRange }, empty text means the default)
  - weight: "400", "bold", "100 900". style: "normal", "italic", "oblique". unicode_range: "U+0000-00FF, U+0131, U+4??"
  - `weight` &str: CSS font-weight text. (400 for empty or unknown text)
  - `style` &str: CSS font-style text. (italic if it starts with italic or oblique, case-insensitive)
  - `unicode_range` &str: CSS unicode-range text. (all characters for empty text)
  - returns FontFaceDescriptors: Descriptors. (source_key is empty text)
- `pub fn set_weight(&mut self, weight: u16)` (method, since 0.4.0): Sets a single weight value.
  - `weight` u16: Weight. (sets both start and end to this value)
- `pub fn set_weight_from_css(&mut self, weight: &str)` (method, since 0.4.0): Sets from CSS weight text. ("normal", "bold", "500", "100 900", unknown text leaves it unchanged)
  - `weight` &str: CSS weight text. (one value if splitting by spaces gives one, a range from the first two if two or more)
- `pub fn contains_character(&self, character: char) -> bool` (method, since 0.4.0): Whether a character is in the character range. (always in if the range is empty)
  - `character` char: Character to check.
  - returns bool: true if in the range.
- `pub fn contains_any_character(&self, text: &str) -> bool` (method, since 0.4.0): Whether the text has a character in the character range.
  - `text` &str: Text to check.
  - returns bool: true if at least one character is in the range. (false for empty text)

## LoadedFont (struct)

One loaded font. (fontdue for rasterization, the rustybuzz face for shaping and its bytes, whether it has color glyph tables)

Example: Read font bytes

```rust
use vanilla::core::textshaping::LoadedFont;
use vanilla::platform::find_fallback_font_file;

assert!(LoadedFont::create_from_bytes(vec![0, 1, 2, 3]).is_err());
if let Some(source) = find_fallback_font_file("A", 400, false, false) {
	let font = LoadedFont::create_from_bytes(std::fs::read(&source.path).expect("font file")).expect("font");
	assert!(font.has_character('A'));
	assert!(font.units_per_em > 0.0);
	assert_eq!(font.get_face_index(), 0);
	assert!(!font.is_variation_applied());
}
```

- `pub raster_font: fontdue::Font` (field, since 0.4.0): fontdue font for rasterization.
  - returns fontdue::Font
- `pub units_per_em: f32` (field, since 0.4.0): Em size in font units. (unitsPerEm of the head table)
  - returns f32
- `pub has_color_tables: bool` (field, since 0.4.0): Whether it has color glyph tables (sbix, CBDT, COLR).
  - returns bool
- `pub fn create_from_bytes(font_bytes: Vec<u8>) -> Result<LoadedFont, String>` (static, since 0.4.0): Reads from decompressed font bytes (ttf, otf, ttc). (face 0 for a collection)
  - `font_bytes` Vec<u8>: Font bytes. (WOFF and WOFF2 must be decompressed first)
  - returns Result<LoadedFont, String>: The loaded font. Err(reason) if it cannot be read.
- `pub fn create_from_shared_bytes(font_bytes: Rc<[u8]>, face_index: u32, variation_list: &[rustybuzz::Variation]) -> Result<LoadedFont, String>` (static, since 0.4.0): Reads one face from shared bytes. (face index inside a collection, axis values of a variable font)
  - `font_bytes` Rc<[u8]>: Shared font bytes.
  - `face_index` u32: Face index inside the collection. (0 if not a collection)
  - `variation_list` &[rustybuzz::Variation]: Axis values to apply. (the default instance if empty)
  - returns Result<LoadedFont, String>: The loaded font. Err(reason) if it cannot be read or there is no face with that index.
- `pub fn read_horizontal_tracking(&self, ptem: f32) -> f32` (method, since 0.4.0): Horizontal tracking from the trak table. (font units, ptem is the font size in pixels. 0 if there is no table or STAT table, or for Mac color emoji. track 0 of TrackData::get_tracking in HarfBuzz 15)
  - Size: interpolated linearly between the table's sizes, the first value if smaller than the first, the last value if larger than the last.
  - track: the row equal to 0 if there is one, otherwise linear interpolation between the two rows around 0.
  - `ptem` f32: Font size. (pixels)
  - returns f32: Tracking. (font units)
- `pub fn with_optical_sizing_auto(mut self, is_optical_sizing_auto: bool) -> LoadedFont` (method, since 0.4.0): Sets whether to apply the opsz axis from the font size. (applied initially. Chrome does not apply it to system fonts on Windows and Linux)
  - `is_optical_sizing_auto` bool: true to apply it.
  - returns LoadedFont: The changed font.
- `pub fn read_optical_size(&self, pixel_size: f32) -> Option<f32>` (method, since 0.4.0): opsz axis value applied for the font size. (the size clamped to the axis range if the axis exists and the font applies it, otherwise None)
  - `pixel_size` f32: Font size. (pixels)
  - returns Option<f32>: Axis value. None if there is no opsz axis or the font is set not to apply it.
- `pub fn create_sized_shaping_face(&self, pixel_size: f32) -> rustybuzz::Face<'_>` (method, since 0.4.0): Shaping face for the font size. (applies the opsz axis. trak tracking is added separately by shape_text, so rustybuzz's ptem is not set)
  - `pixel_size` f32: Font size. (pixels)
  - returns rustybuzz::Face<'_>: Copy of the shaping face. (unchanged for a font that does not apply opsz)
- `pub fn with_source_path(mut self, source_path: std::path::PathBuf) -> LoadedFont` (method, since 0.4.0): Records the font file path. (a font read from a file. On Mac, color emoji and fonts without outline tables are drawn with CoreText)
  - `source_path` std::path::PathBuf: Font file path.
  - returns LoadedFont: The font with the path recorded.
- `pub fn is_core_text_raster(&self) -> bool` (method, since 0.4.0): Whether it is drawn with Mac CoreText.
  - returns bool: true if drawn with CoreText. (always false outside Mac)
- `pub fn read_advance_scale(&self, pixel_size: f32) -> f32` (method, since 0.4.0): Ratio to multiply the shaping advance by. (for Mac color emoji, the ratio CoreText enlarges drawing at small sizes, otherwise 1)
  - `pixel_size` f32: Font size. (pixels)
  - returns f32: Ratio. (1 except for Mac color emoji)
- `pub fn is_bitmap_only_font(&self) -> bool` (method, since 0.4.0): Whether this is a color font with only bitmap images. (a font with CBDT or sbix and no outline table (glyf, CFF, CFF2), not drawn with CoreText on Mac)
  - Like Chrome on Linux (FreeType and Skia), the advance and pixel box come from the strike's glyph metrics and image box. (colorglyph::read_bitmap_glyph_advance, read_bitmap_glyph_bounds)
  - returns bool: true if it has only bitmaps.
- `pub fn is_integer_advance(&self) -> bool` (method, since 0.4.0): Whether the advance is rounded to integer pixels. (Mac color emoji, Chrome measureText gives integers like 16 at 13px and 21 at 17px)
  - returns bool: true if rounded. (only Mac color emoji drawn with CoreText)
- `pub fn get_shaping_face(&self) -> &rustybuzz::Face<'_>` (method, since 0.4.0): Shaping face. (the face with axis values applied, font tables are also read through it)
  - returns &rustybuzz::Face<'_>: rustybuzz face.
- `pub fn calculate_normal_line_height(&self, pixel_size: f32) -> f32` (method, since 0.4.0): Line height of CSS line-height normal. (LineSpacing of Chrome SimpleFontData::PlatformInit)
  - Chrome rounds the ascent and descent from Skia (fAscent, fDescent) separately (FontMetrics::AscentDescentWithHacks), and the line height is lroundf(ascent) + lroundf(descent) + lroundf(line gap fLeading).
  - The tables Skia reads differ by operating system.
    - Linux (SkFontHost_FreeType.cpp): the typo values if USE_TYPO_METRICS in OS/2 is set, otherwise FreeType's hhea values (typo if hhea is 0, the win values if that is also 0).
      ttf-parser's ascender, descender, line_gap read them in this order.
    - macOS (CoreText): the hhea values, ignoring USE_TYPO_METRICS. (confirmed in headless Chrome on macOS: a font with that bit set keeps the same line height)
    - Windows (DirectWrite's DWRITE_FONT_METRICS): the typo values if USE_TYPO_METRICS, otherwise the win values with a line gap equal to how much the hhea line height exceeds the win height.
      (DirectWrite does not disclose which table it picks, so the calculation known from font vertical metrics guides is used)
  - Chrome on macOS adds 15% of (ascent + descent), rounded, to the ascent of Times, Helvetica and Courier. (a value matched to Safari's SimpleFontDataMac)
  - `pixel_size` f32: Font size. (px)
  - returns f32: Line height. (px, integer)
- `pub fn calculate_font_bounding_box(&self, pixel_size: f32) -> (f32, f32)` (method, since 0.4.0): Font ascent and descent for the canvas. (Chrome's FontMetrics::AscentDescentWithHacks with the subpixel_ascent_descent the canvas turns on; TextMetrics fontBoundingBoxAscent, fontBoundingBoxDescent)
  - The table read on each operating system is the same as calculate_normal_line_height.
  - Ascent and descent are each rounded. Tiny fonts whose ascent is below 3px or whose ascent + descent is below 2px are not rounded. (crbug.com/338908, so that baselines of different kinds do not coincide)
  - On Mac, 15% of (ascent + descent), rounded, is added to the ascent of Times, Helvetica and Courier.
  - Linux's VDMX table and borrowing descent for subpixel positioning apply only with FreeType bytecode hinting (full, normal) and subpixel positioning, so like Chrome's Linux default (slight hinting, subpixel positioning off) they are not used.
  - `pixel_size` f32: Font size. (px)
  - returns (f32, f32): (ascent, descent). (px, both positive, both 0 if the font size is 0)
- `pub fn get_font_bytes(&self) -> &Rc<[u8]>` (method, since 0.4.0): Font bytes. (shared with other faces from the same file)
  - returns &Rc<[u8]>: Font bytes.
- `pub fn get_face_index(&self) -> u32` (method, since 0.4.0): Face index inside the font collection.
  - returns u32: Face index. (0 if not a collection)
- `pub fn is_variation_applied(&self) -> bool` (method, since 0.4.0): Whether it is a variable font instance with axis values applied.
  - returns bool: true if axis values are applied.
- `pub fn is_outline_raster(&self) -> bool` (method, since 0.4.0): Whether glyphs are drawn directly from outlines. (variable fonts. fontdue cannot read axis values and cannot draw the outlines of variable fonts like Mac SFNS)
  - returns bool: true if it is a variable font or axis values are applied.
- `pub fn read_glyph_metrics(&self, glyph_index: u16, pixel_size: f32) -> (i32, i32, i32, i32)` (method, since 0.4.0): Pixel box a glyph covers. (left, bottom, width, height from the pen origin. Same meaning as xmin, ymin, width, height in fontdue Metrics, width and height 0 if empty)
  - `glyph_index` u16: Glyph ID.
  - `pixel_size` f32: Font size. (pixels)
  - returns (i32, i32, i32, i32): (left, bottom, width, height). (pixels, up is positive)
- `pub fn read_glyph_path_bounds(&self, glyph_index: u16, pixel_size: f32, skew: f32) -> Option<(f32, f32, f32, f32)>` (method, since 0.4.0): Glyph bounds used for the measureText bounding box. (the outline path bounds like Mac Chrome: GetPathBoundsForGlyph, which Blink skia_text_metrics.cc SkFontGetBoundsForGlyph calls on Mac.
  The path is the CoreText outline (CTFontCreatePathForGlyph) and the bounds are SkPath::getBounds including curve control points)
  - Reads the points of the outline table (glyf, CFF, CFF2), including curve control points, with the axis values for that size, and scales the bounds to pixels. No rounding.
  - Fonts whose outlines the engine cannot read (color emoji sbix, hvgl without an outline table, and the like) and glyphs with an empty outline are None. (Chrome also uses the integer getBounds when there is no path)
  - `glyph_index` u16: Glyph ID.
  - `pixel_size` f32: Font size. (pixels)
  - `skew` f32: Horizontal skew. (adds y x skew to x; SYNTHETIC_ITALIC_SKEW for fake italic, otherwise 0. Like Chrome, the bounds are measured after skewing the path points)
  - returns Option<(f32, f32, f32, f32)>: (left, bottom, right, top). (pixels from the pen origin, up is positive)
- `pub fn read_glyph_skia_bounds(&self, glyph_index: u16, pixel_size: f32, skew: f32) -> Option<(f32, f32, f32, f32)>` (method, since 0.4.0): Integer bounds of a glyph without a path (a CoreText raster font such as Mac color emoji) used for the measureText bounding box. (the same calculation as Skia getBounds; None when not on Mac or not a CoreText raster font)
  - Skia SkScalerContext_Mac::generateMetrics: expands the bounds of the CTFont Skia builds outward to integers and then by 1 pixel on every side (outset(1, 1)). For fake italic, the bounds are skewed before expanding.
  - `glyph_index` u16: Glyph ID.
  - `pixel_size` f32: Font size. (pixels)
  - `skew` f32: Horizontal skew. (adds y x skew to x; 0 unless fake italic)
  - returns Option<(f32, f32, f32, f32)>: (left, bottom, right, top). (pixels from the pen origin, up is positive)
- `pub fn draw_glyph_outline(&self, glyph_index: u16, pixel_size: f32, outline_builder: &mut dyn rustybuzz::ttf_parser::OutlineBuilder) -> bool` (method, since 0.4.0): Draws a glyph outline. (font units, the outline with the axis values (including opsz) for that font size. Variable fonts through skrifa, otherwise through ttf-parser. false if there is no outline)
  - ttf-parser cannot read the outlines of variable fonts with more than 32 variations per glyph (like Mac SFNS).
  - `glyph_index` u16: Glyph ID.
  - `pixel_size` f32: Font size. (pixels, used only to pick the opsz axis value of a variable font)
  - `outline_builder` &mut dyn rustybuzz::ttf_parser::OutlineBuilder: Receiver of the outline.
  - returns bool: true if the outline was drawn.
- `pub fn has_character(&self, character: char) -> bool` (method, since 0.4.0): Whether it has the character.
  - `character` char: Character to check.
  - returns bool: true if there is a glyph.
- `pub fn has_color_character(&self, character: char) -> bool` (method, since 0.4.0): Whether it has the character as a color glyph. (sbix, CBDT, COLR)
  - `character` char: Character to check.
  - returns bool: true if there is a color glyph. (always false for fonts without color glyph tables)

## RegisteredFontFace (struct) (Clone)

One registered font face.

Example: Pick bold between a regular and a bold face

```rust
use std::rc::Rc;
use vanilla::core::textshaping::{select_font_faces, LoadedFont, RegisteredFontFace};
use vanilla::platform::find_fallback_font_file;
use vanilla::FontFaceDescriptors;

if let Some(source) = find_fallback_font_file("A", 400, false, false) {
	let font = Rc::new(LoadedFont::create_from_bytes(std::fs::read(&source.path).expect("font file")).expect("font"));
	let regular_face = RegisteredFontFace {
		descriptors: FontFaceDescriptors::create_with_bold(false),
		font: font.clone(),
		order_number: 1,
	};
	let bold_face = RegisteredFontFace {
		descriptors: FontFaceDescriptors::create_with_bold(true),
		font,
		order_number: 2,
	};
	let mut resolved_face_list = Vec::new();
	select_font_faces(&[&regular_face, &bold_face], 700, false, &mut resolved_face_list);
	assert_eq!(resolved_face_list.len(), 1);
	assert_eq!(resolved_face_list[0].descriptors.minimum_weight, 700);
	assert!(!resolved_face_list[0].is_synthetic_bold);
}
```

- `pub descriptors: FontFaceDescriptors` (field, since 0.4.0): Face descriptors.
  - returns FontFaceDescriptors
- `pub font: Rc<LoadedFont>` (field, since 0.4.0): The loaded font. (several faces can share the same font)
  - returns Rc<LoadedFont>
- `pub order_number: u64` (field, since 0.4.0): Load order. (larger is later, later ones draw first)
  - returns u64

## ResolvedFontFace (struct) (Clone)

One face chosen for drawing. (also holds whether to apply fake bold and fake italic)

Example: Fake italic does not change the advance

```rust
use std::rc::Rc;
use vanilla::core::textshaping::{shape_text, LoadedFont, ResolvedFontFace};
use vanilla::platform::find_fallback_font_file;
use vanilla::{FontFaceDescriptors, ShapingDirection};

if let Some(source) = find_fallback_font_file("A", 400, false, false) {
	let font = Rc::new(LoadedFont::create_from_bytes(std::fs::read(&source.path).expect("font file")).expect("font"));
	let upright_face = ResolvedFontFace {
		font: font.clone(),
		descriptors: FontFaceDescriptors::new(),
		is_synthetic_bold: false,
		is_synthetic_italic: false,
	};
	let italic_face = ResolvedFontFace {
		is_synthetic_italic: true,
		..upright_face.clone()
	};
	let upright_text = shape_text(&[upright_face], "Hello", 20.0, ShapingDirection::LeftToRight, None);
	let italic_text = shape_text(&[italic_face], "Hello", 20.0, ShapingDirection::LeftToRight, None);
	assert_eq!(upright_text.advance_width, italic_text.advance_width);
}
```

- `pub font: Rc<LoadedFont>` (field, since 0.4.0): The loaded font.
  - returns Rc<LoadedFont>
- `pub descriptors: FontFaceDescriptors` (field, since 0.4.0): Face descriptors.
  - returns FontFaceDescriptors
- `pub is_synthetic_bold: bool` (field, since 0.4.0): Whether to apply fake bold. (the requested weight is 600 or more and the face weight is below 600)
  - returns bool
- `pub is_synthetic_italic: bool` (field, since 0.4.0): Whether to apply fake italic. (italic was requested but the face is upright)
  - returns bool

## ShapedGlyph (struct) (Clone, Copy, Debug)

One shaped glyph. (length unit is pixels, y up is positive)

Example: Glyphs are placed from the left

```rust
use std::rc::Rc;
use vanilla::core::textshaping::{shape_text, LoadedFont, ResolvedFontFace};
use vanilla::platform::find_fallback_font_file;
use vanilla::{FontFaceDescriptors, ShapingDirection};

if let Some(source) = find_fallback_font_file("A", 400, false, false) {
	let face_list = vec![ResolvedFontFace {
		font: Rc::new(LoadedFont::create_from_bytes(std::fs::read(&source.path).expect("font file")).expect("font")),
		descriptors: FontFaceDescriptors::new(),
		is_synthetic_bold: false,
		is_synthetic_italic: false,
	}];
	let shaped_text = shape_text(&face_list, "ab", 20.0, ShapingDirection::LeftToRight, None);
	let first_glyph = shaped_text.glyph_list[0];
	let second_glyph = shaped_text.glyph_list[1];
	assert_eq!(first_glyph.face_index, 0);
	assert!(second_glyph.position_x > first_glyph.position_x);
	assert!(!second_glyph.is_right_to_left);
}
```

- `pub face_index: usize` (field, since 0.4.0): Position in the face list. (a browser system font segment if SYSTEM_FACE_INDEX)
  - returns usize
- `pub glyph_index: u16` (field, since 0.4.0): Glyph index. (0 for a system font segment)
  - returns u16
- `pub position_x: f32` (field, since 0.4.0): Glyph origin x. (from the left end of the text, including the shaping x offset)
  - returns f32
- `pub position_y: f32` (field, since 0.4.0): Glyph origin y. (from the baseline, the shaping y offset)
  - returns f32
- `pub text_start: usize` (field, since 0.4.0): For a system font segment, the text position of that segment. (bytes, only when face_index is SYSTEM_FACE_INDEX)
  - returns usize
- `pub text_end: usize` (field, since 0.4.0): Text end position of a system font segment. (bytes, end exclusive. 0 if not a segment)
  - returns usize
- `pub is_right_to_left: bool` (field, since 0.4.0): Whether the run it belongs to is right to left.
  - returns bool
- `pub cluster_start: usize` (field, since 0.4.0): Text start position of the grapheme cluster (HarfBuzz cluster) that holds the glyph. (bytes, the segment start for a system font segment; the glyph atlas uses it to split text chunks)
  - returns usize

## ShapedText (struct)

Shaped text. (glyphs in left to right drawing order)

Example: Advance of the whole text

```rust
use std::rc::Rc;
use vanilla::core::textshaping::{shape_text, LoadedFont, ResolvedFontFace};
use vanilla::platform::find_fallback_font_file;
use vanilla::{FontFaceDescriptors, ShapingDirection};

if let Some(source) = find_fallback_font_file("A", 400, false, false) {
	let face_list = vec![ResolvedFontFace {
		font: Rc::new(LoadedFont::create_from_bytes(std::fs::read(&source.path).expect("font file")).expect("font")),
		descriptors: FontFaceDescriptors::new(),
		is_synthetic_bold: false,
		is_synthetic_italic: false,
	}];
	let shaped_text = shape_text(&face_list, "abc", 20.0, ShapingDirection::LeftToRight, None);
	assert_eq!(shaped_text.glyph_list.len(), 3);
	let last_glyph = shaped_text.glyph_list[2];
	assert!(shaped_text.advance_width > last_glyph.position_x);
}
```

- `pub glyph_list: Vec<ShapedGlyph>` (field, since 0.4.0): Glyph list. (drawing order from the left)
  - returns Vec<ShapedGlyph>
- `pub advance_width: f32` (field, since 0.4.0): Advance of the whole text. (pixels)
  - returns f32

## GlyphRaster (struct)

One glyph raster. (coverage, the top left position is xmin to the right of the pen origin and top up from the baseline)
- coverage is the coverage of non-color text. The color glyph part is held in its own colors in color_pixels. (premultiplied RGBA, same size, None if absent)

Example: Rasterize one glyph

```rust
use std::rc::Rc;
use vanilla::core::textshaping::{rasterize_glyph, shape_text, LoadedFont, ResolvedFontFace};
use vanilla::platform::find_fallback_font_file;
use vanilla::{FontFaceDescriptors, ShapingDirection};

if let Some(source) = find_fallback_font_file("A", 400, false, false) {
	let face = ResolvedFontFace {
		font: Rc::new(LoadedFont::create_from_bytes(std::fs::read(&source.path).expect("font file")).expect("font")),
		descriptors: FontFaceDescriptors::new(),
		is_synthetic_bold: false,
		is_synthetic_italic: false,
	};
	let shaped_text = shape_text(&[face.clone()], "A", 32.0, ShapingDirection::LeftToRight, None);
	let glyph_raster = rasterize_glyph(&face, shaped_text.glyph_list[0].glyph_index, 32.0);
	assert!(glyph_raster.width > 0 && glyph_raster.height > 0);
	assert_eq!(glyph_raster.coverage.len(), (glyph_raster.width * glyph_raster.height) as usize);
	assert!(glyph_raster.top_y > 0);
	assert!(glyph_raster.color_pixels.is_none());
}
```

- `pub coverage: Vec<u8>` (field, since 0.4.0): Coverage. (0 ~ 255, width * height values, from the top row)
  - returns Vec<u8>
- `pub width: i32` (field, since 0.4.0): Width. (pixels)
  - returns i32
- `pub height: i32` (field, since 0.4.0): Height. (pixels)
  - returns i32
- `pub left_x: i32` (field, since 0.4.0): From the pen origin to the left of the raster. (pixels, right is positive)
  - returns i32
- `pub top_y: i32` (field, since 0.4.0): From the baseline to the top of the raster. (pixels, up is positive)
  - returns i32
- `pub color_pixels: Option<Vec<u8>>` (field, since 0.4.0): Color glyph layer. (premultiplied RGBA, width * height * 4 bytes, None if not a color glyph)
  - returns Option<Vec<u8>>

## Functions and constants

- `pub const SYNTHETIC_ITALIC_SKEW: f32 = 0.25` (field, since 0.4.0): Slant of fake italic. (pixels pushed right for every 1 pixel up from the baseline, Chromium setSkewX(-1/4))
  - returns f32
- `pub const BOLD_WEIGHT_THRESHOLD: u16 = 600` (field, since 0.4.0): Weight threshold that counts as bold. (Blink kBoldThreshold)
  - returns u16
- `pub const SYSTEM_FACE_INDEX: usize = usize::MAX` (field, since 0.4.0): Face position for segments drawn with the browser system font. (characters not in any font loaded on the web, ShapedGlyph.face_index)
  - returns usize
- `pub fn parse_css_weight(weight_text: &str) -> Option<u16>` (method, since 0.4.0): Reads one CSS weight value. ("normal" 400, "bold" 700, numbers 1 ~ 1000)
  - `weight_text` &str: One CSS weight value. (leading and trailing spaces are trimmed, case-insensitive)
  - returns Option<u16>: Weight. (decimals are rounded) None if outside 1 ~ 1000 or unreadable.

  Example: Words, numbers, out of range

  ```rust
  use vanilla::core::textshaping::parse_css_weight;
  
  assert_eq!(parse_css_weight("normal"), Some(400));
  assert_eq!(parse_css_weight(" BOLD "), Some(700));
  assert_eq!(parse_css_weight("450.6"), Some(451));
  assert_eq!(parse_css_weight("1001"), None);
  assert_eq!(parse_css_weight("heavy"), None);
  ```

- `pub fn parse_unicode_range(unicode_range: &str) -> Vec<(u32, u32)>` (method, since 0.4.0): unicode-range text → list of code point ranges. ("U+0-FF, U+4??" → [(0, 255), (1024, 1279)], an empty list if empty = all characters)
  - Same as parseUnicodeRange in the original textstringtexturecache.js and uifont.js.
  - `unicode_range` &str: Comma separated range text. (pieces that do not start with U+ or u+ or are not hexadecimal are skipped)
  - returns Vec<(u32, u32)>: List of (start, end) code points. (end inclusive)

  Example: Range, single character, ? wildcard

  ```rust
  use vanilla::core::textshaping::parse_unicode_range;
  
  assert_eq!(parse_unicode_range("U+0-FF, U+4??"), vec![(0, 255), (0x400, 0x4FF)]);
  assert_eq!(parse_unicode_range("U+0131"), vec![(0x131, 0x131)]);
  assert!(parse_unicode_range("").is_empty());
  ```

- `pub fn is_emoji_presentation(grapheme: &str) -> bool` (method, since 0.4.0): Whether a grapheme cluster has emoji presentation. (UTS #51, otherwise text presentation)
  - Text presentation if it has VS15 (FE0E), emoji presentation if it has VS16 (FE0F) or a keycap (20E3).
  - Emoji presentation if the first character is Emoji_Presentation (including the regional indicators of flags), a skin tone modifier or tag characters are attached, or it is an emoji sequence joined with a joiner.
    A single character like ❤ that is Emoji but not Emoji_Presentation is text presentation. (Chrome also draws a plain ❤ with the text font)
  - `grapheme` &str: One grapheme cluster.
  - returns bool: true for emoji presentation. (false for empty text)
- `pub fn calculate_weight_score(face_minimum_weight: u16, face_maximum_weight: u16, desired_weight: u16) -> (u32, u32)` (method, since 0.4.0): Weight selection score. (smaller comes first, the CSS Fonts 4 order. (0, 0) if the weight range contains the requested weight)
  - If the requested value is 400 ~ 500, ascending from that value up to 500, then descending below it, then ascending above 500. Below 400, descending below then ascending above. Above 500, ascending above then descending below.
  - `face_minimum_weight` u16: Start of the face's weight range.
  - `face_maximum_weight` u16: End of the face's weight range.
  - `desired_weight` u16: Requested weight.
  - returns (u32, u32): (group, weight difference). (compared as a tuple, smaller comes first)

  Example: Requesting 400 gives the order 500, 300, 600

  ```rust
  use vanilla::core::textshaping::calculate_weight_score;
  
  assert_eq!(calculate_weight_score(100, 900, 700), (0, 0));
  assert!(calculate_weight_score(500, 500, 400) < calculate_weight_score(300, 300, 400));
  assert!(calculate_weight_score(300, 300, 400) < calculate_weight_score(600, 600, 400));
  ```

- `pub fn find_collection_face_index(font_bytes: &[u8], desired_weight: u16, is_italic_desired: bool) -> u32` (method, since 0.4.0): Face index in a font collection (TTC) that best matches the requested weight and style. (0 if not a collection)
  - Weight comes from usWeightClass in OS/2, and style from the italic flags in OS/2 and head. Style is chosen first, then weight in the same order as select_font_faces.
  - Faces whose PostScript name starts with a dot (faces the Mac system font uses only internally) are chosen only when there is no other face. On a tie, the lower index.
  - `font_bytes` &[u8]: Font bytes. (a collection or a single font)
  - `desired_weight` u16: Requested weight.
  - `is_italic_desired` bool: Whether italic is requested.
  - returns u32: Face index. (0 if there is no readable face)
- `pub fn read_weight_variation(font_bytes: &[u8], face_index: u32, desired_weight: u16) -> Vec<rustybuzz::Variation>` (method, since 0.4.0): Weight axis values of a variable font. (one value clamped to the axis range if there is a wght axis and the requested weight differs from the default, otherwise an empty list)
  - `font_bytes` &[u8]: Font bytes.
  - `face_index` u32: Face index inside the collection. (0 if not a collection)
  - `desired_weight` u16: Requested weight.
  - returns Vec<rustybuzz::Variation>: A list of one wght axis value. An empty list if there is no axis, the clamped value is within 0.5 of the default, or the font cannot be read.
- `pub fn read_weight_axis_range(font_bytes: &[u8], face_index: u32) -> Option<(u16, u16)>` (method, since 0.4.0): Weight range of a variable font. (start and end of the wght axis, None if there is no axis)
  - `font_bytes` &[u8]: Font bytes.
  - `face_index` u32: Face index inside the collection. (0 if not a collection)
  - returns Option<(u16, u16)>: (start, end) weight. (rounded) None if there is no axis or the font cannot be read.
- `pub fn select_font_faces(face_list: &[&RegisteredFontFace], desired_weight: u16, is_italic_desired: bool, output_list: &mut Vec<ResolvedFontFace>)` (method, since 0.4.0): Chooses the faces matching the requested weight and style from the faces under one name. (the CSS Fonts 4 font matching order)
  - Style is chosen first. If italic is requested, an italic face, or an upright face if none (fake italic). If upright is requested, an upright face, or an italic face if none.
  - Weight: if the requested value is 400 ~ 500, ascending from that value up to 500, then descending below it, then ascending above 500. Below 400, descending below then ascending above. Above 500, ascending above then descending below.
  - Returns all faces with the chosen weight and style, latest first. (drawing is split by character range)
  - `face_list` &[&RegisteredFontFace]: Faces under one name. (adds nothing if empty)
  - `desired_weight` u16: Requested weight.
  - `is_italic_desired` bool: Whether italic is requested.
  - `output_list` &mut Vec<ResolvedFontFace>: List to append the chosen faces to. (existing items are kept)

  Example: Requesting bold italic with only one upright regular face applies them as fakes

  ```rust
  use std::rc::Rc;
  use vanilla::core::textshaping::{select_font_faces, LoadedFont, RegisteredFontFace};
  use vanilla::platform::find_fallback_font_file;
  use vanilla::FontFaceDescriptors;
  
  if let Some(source) = find_fallback_font_file("A", 400, false, false) {
  	let regular_face = RegisteredFontFace {
  		descriptors: FontFaceDescriptors::new(),
  		font: Rc::new(LoadedFont::create_from_bytes(std::fs::read(&source.path).expect("font file")).expect("font")),
  		order_number: 1,
  	};
  	let mut resolved_face_list = Vec::new();
  	select_font_faces(&[&regular_face], 700, true, &mut resolved_face_list);
  	assert!(resolved_face_list[0].is_synthetic_bold);
  	assert!(resolved_face_list[0].is_synthetic_italic);
  }
  ```

- `pub fn find_chrome_word_end(text: &str, start: usize, is_latin1: bool) -> usize` (method, since 0.4.0): Word end of Chrome's canvas. (NextWordEndIndex in platform/fonts/plain_text_node.cc. The end byte position of the word starting at byte position start of text)
  - Spaces (U+0020), tabs and ZWSP are separate words, one each. If is_latin1 (Chrome's 8 bit text, every character U+00FF or below), it breaks only at spaces and tabs.
  - Otherwise: if it starts with a character that is not a CJK character or symbol, it breaks before a space or a CJK character (one that is not a combining mark or the like).
    If it starts with CJK or emoji, it breaks at every character but attaches combining marks, modifier letters, ZWJ, emoji components and pictographs, CJK symbols whose script is Common or Inherited,
    and, when the first character is Common, the next character too.
  - `text` &str: Text.
  - `start` usize: Byte position where the word starts. (must be a character boundary, otherwise it panics)
  - `is_latin1` bool: Whether every character in the text is U+00FF or below.
  - returns usize: Word end byte position. (end exclusive) start if start is at the end of the text.

  Example: Spaces are separate, Han characters are per character

  ```rust
  use vanilla::core::textshaping::find_chrome_word_end;
  
  let text = "ab cd";
  assert_eq!(find_chrome_word_end(text, 0, true), 2);
  assert_eq!(find_chrome_word_end(text, 2, true), 3);
  assert_eq!(find_chrome_word_end(text, 3, true), 5);
  let ideograph_text = "\u{4E00}\u{4E8C}";
  assert_eq!(find_chrome_word_end(ideograph_text, 0, false), 3);
  assert_eq!(find_chrome_word_end(ideograph_text, 3, false), 6);
  ```

- `pub fn shape_text(face_list: &[ResolvedFontFace], text: &str, pixel_size: f32, direction: ShapingDirection, system_font_measure: Option<SystemFontMeasure>) -> ShapedText` (method, since 0.4.0): Shapes text. (bidirectional ordering → shapes the per-face segments with rustybuzz → places them from the left)
  - direction is the paragraph direction. (the original canvas.direction) The character order inside the paragraph is decided by the bidirectional algorithm.
  - Line break characters are treated as one line and shaped as they are. (the original fillText does not break lines either)
  - If system_font_measure is given (web), grapheme clusters not in any loaded face become browser system font segments (SYSTEM_FACE_INDEX). Same as the browser font fallback in the original.
    If a cluster has emoji presentation and the loaded faces have no color glyph, it becomes a browser segment (color emoji) even if a monochrome glyph exists. (Chrome also draws ❤️ with a color emoji font)
    If not given, it is drawn with the first face's empty glyph.
  - `face_list` &[ResolvedFontFace]: Chosen faces. (searched from the first face for each grapheme cluster)
  - `text` &str: Text to shape.
  - `pixel_size` f32: Font size. (pixels)
  - `direction` ShapingDirection: Paragraph direction.
  - `system_font_measure` Option<SystemFontMeasure>: Measures a system font segment. (web, no segments are made if None)
  - returns ShapedText: The shaped text. No glyphs and advance 0 if there are no faces or the text is empty.

  Example: A larger size gives a larger advance

  ```rust
  use std::rc::Rc;
  use vanilla::core::textshaping::{shape_text, LoadedFont, ResolvedFontFace};
  use vanilla::platform::find_fallback_font_file;
  use vanilla::{FontFaceDescriptors, ShapingDirection};
  
  if let Some(source) = find_fallback_font_file("A", 400, false, false) {
  	let face_list = vec![ResolvedFontFace {
  		font: Rc::new(LoadedFont::create_from_bytes(std::fs::read(&source.path).expect("font file")).expect("font")),
  		descriptors: FontFaceDescriptors::new(),
  		is_synthetic_bold: false,
  		is_synthetic_italic: false,
  	}];
  	let small_text = shape_text(&face_list, "Hello", 16.0, ShapingDirection::LeftToRight, None);
  	let large_text = shape_text(&face_list, "Hello", 32.0, ShapingDirection::LeftToRight, None);
  	assert!(large_text.advance_width > small_text.advance_width);
  	let empty_text = shape_text(&face_list, "", 16.0, ShapingDirection::LeftToRight, None);
  	assert!(empty_text.glyph_list.is_empty());
  	assert_eq!(empty_text.advance_width, 0.0);
  }
  ```

- `pub fn calculate_synthetic_bold_radius(pixel_size: f32) -> f32` (method, since 0.4.0): Widening radius of fake bold. (pixels, half of Skia's stroke thickness)
  - `pixel_size` f32: Font size. (pixels)
  - returns f32: Radius. (pixels, 1/48 of the size at 9px or less, 1/64 at 36px or more, linearly interpolated in between)

  Example: 1/64 of the size at 36px or more

  ```rust
  use vanilla::core::textshaping::calculate_synthetic_bold_radius;
  
  assert_eq!(calculate_synthetic_bold_radius(48.0), 0.75);
  assert!((calculate_synthetic_bold_radius(6.0) - 0.125).abs() < 0.00001);
  ```

- `pub fn rasterize_glyph(face: &ResolvedFontFace, glyph_index: u16, pixel_size: f32) -> GlyphRaster` (method, since 0.4.0): Rasterizes a glyph. (fake bold widens, fake italic shears around the baseline. Color glyphs in their own colors, without fake bold)
  - `face` &ResolvedFontFace: Face to draw with. (together with whether to apply fake bold and fake italic)
  - `glyph_index` u16: Glyph ID.
  - `pixel_size` f32: Font size. (pixels)
  - returns GlyphRaster: The raster. A glyph without an outline (space) has width and height 0.

  Example: Fake bold widens the raster

  ```rust
  use std::rc::Rc;
  use vanilla::core::textshaping::{rasterize_glyph, shape_text, LoadedFont, ResolvedFontFace};
  use vanilla::platform::find_fallback_font_file;
  use vanilla::{FontFaceDescriptors, ShapingDirection};
  
  if let Some(source) = find_fallback_font_file("A", 400, false, false) {
  	let face = ResolvedFontFace {
  		font: Rc::new(LoadedFont::create_from_bytes(std::fs::read(&source.path).expect("font file")).expect("font")),
  		descriptors: FontFaceDescriptors::new(),
  		is_synthetic_bold: false,
  		is_synthetic_italic: false,
  	};
  	let bold_face = ResolvedFontFace {
  		is_synthetic_bold: true,
  		..face.clone()
  	};
  	let glyph_index = shape_text(&[face.clone()], "H", 32.0, ShapingDirection::LeftToRight, None).glyph_list[0].glyph_index;
  	let glyph_raster = rasterize_glyph(&face, glyph_index, 32.0);
  	let bold_glyph_raster = rasterize_glyph(&bold_face, glyph_index, 32.0);
  	assert!(bold_glyph_raster.width > glyph_raster.width);
  	assert!(bold_glyph_raster.left_x < glyph_raster.left_x);
  }
  ```

- `pub fn is_subpixel_positioned(face: &ResolvedFontFace, pixel_size: f32) -> bool` (method, since 0.4.0): Whether to split glyph positions into 1/4 pixel subpixels. (the value Chrome Blink gives SkFont::setSubpixel)
  - Mac, Windows: always on. (antialiased text)
  - Linux: off when fontconfig hinting is full (hintfull), otherwise on. (In WebFontRenderStyle::ApplyToSkFont, force_subpixel_positioning is true when hinting is not kFull,
    and use_subpixel_positioning is true only when the device scale is greater than 1. For fonts with antialiasing off, Chrome GetFontRenderParams changes hinting to full)
    Queried by the face's family name, size, weight, and slant. (the same query as the hinting in rasterize_glyph_at)
  - Otherwise (web): off. (the browser canvas decides)
  - `face` &ResolvedFontFace: Face to draw.
  - `pixel_size` f32: Font size. (pixels)
  - returns bool: true when on. When off, the glyph is placed at the rounded integer position and the subpixel part is 0.

  Example: Mac and Windows are always on

  ```rust
  use std::rc::Rc;
  use vanilla::core::textshaping::{is_subpixel_positioned, LoadedFont, ResolvedFontFace};
  use vanilla::platform::find_fallback_font_file;
  use vanilla::FontFaceDescriptors;
  
  if let Some(source) = find_fallback_font_file("A", 400, false, false) {
  	let face = ResolvedFontFace {
  		font: Rc::new(LoadedFont::create_from_bytes(std::fs::read(&source.path).expect("font file")).expect("font")),
  		descriptors: FontFaceDescriptors::new(),
  		is_synthetic_bold: false,
  		is_synthetic_italic: false,
  	};
  	let is_subpixel = is_subpixel_positioned(&face, 16.0);
  	if cfg!(any(target_os = "macos", target_os = "windows")) {
  		assert!(is_subpixel);
  	}
  }
  ```

- `pub fn rasterize_glyph_at(face: &ResolvedFontFace, glyph_index: u16, pixel_size: f32, subpixel_x: f32, luminance_color: [u8; 3]) -> GlyphRaster` (method, since 0.4.0): Glyph raster by subpixel position and text color luminance. (Mac uses CoreText, Windows uses DirectWrite, Linux draws like Chrome with hinted skrifa outlines)
  - Mac: non-color glyphs are drawn the same way as Chrome Mac Canvas2D. (the A8 mask of Skia SkScalerContext_Mac: font smoothing, undoing CoreGraphics gamma, gamma precorrection by text color luminance)
    As in Mac Skia, the text color luminance is a 3-bit step of the color multiplied by 1/2 when font smoothing is gray, the gamma is Chrome Mac's sRGB, and the contrast is 0. (SkTypeface_Mac::onFilterRec, Chromium skia/BUILD.gn)
    Fake italic is drawn with the slant of the CoreText text matrix. Color glyphs are the same as rasterize_glyph.
  - Windows: non-color glyphs are drawn by DirectWrite the same way as Chrome Windows Canvas2D. (the A8 of Skia SkScalerContext_DW: grid fitting, the rendering mode picked by gasp, when ClearType is on the average of the three channels of a 3x1 texture like Chrome, otherwise grayscale)
    Gamma precorrection uses a table by text color luminance step, and contrast and gamma are the system values if the Avalon.Graphics key exists, otherwise contrast 1 and sRGB, like Chrome. Fake italic is the slant of the DirectWrite text matrix.
  - Linux: non-color glyphs are painted like Chrome Linux by hinting skrifa outlines with fontconfig's hinting level, filled with the same analytic AA as Skia, and precorrected with gamma 1.2 and contrast 0.2. (Skia SkTypeface_Fontations, SkScan_AAAPath)
    Fonts whose fontconfig hinting is full (hintfull) turn off subpixel positioning. (is_subpixel_positioned; the caller passes 0 for subpixel_x)
  - Otherwise subpixel position and luminance are not used.
  - `face` &ResolvedFontFace: Face to draw with. (together with whether to apply fake bold and fake italic)
  - `glyph_index` u16: Glyph ID.
  - `pixel_size` f32: Font size. (pixels)
  - `subpixel_x` f32: Horizontal subpixel position. (0, 0.25, 0.5, 0.75; like Skia, the remainder of the integer position obtained by adding 1/8 to the glyph position and flooring, floored to 1/4 steps)
  - `luminance_color` [u8; 3]: Text color. (red, green, blue in sRGB; [255, 255, 255] for text baked white like the original)
  - returns GlyphRaster: The raster. A glyph without an outline (a space) has width and height 0. left_x is measured from the integer position without the subpixel part.

  Example: Moving the subpixel position keeps the coverage sum almost the same

  ```rust
  use std::rc::Rc;
  use vanilla::core::textshaping::{rasterize_glyph_at, shape_text, LoadedFont, ResolvedFontFace};
  use vanilla::platform::find_fallback_font_file;
  use vanilla::{FontFaceDescriptors, ShapingDirection};
  
  if let Some(source) = find_fallback_font_file("H", 400, false, false) {
  	let face = ResolvedFontFace {
  		font: Rc::new(LoadedFont::create_from_bytes(std::fs::read(&source.path).expect("font file")).expect("font")),
  		descriptors: FontFaceDescriptors::new(),
  		is_synthetic_bold: false,
  		is_synthetic_italic: false,
  	};
  	let glyph_index = shape_text(&[face.clone()], "H", 24.0, ShapingDirection::LeftToRight, None).glyph_list[0].glyph_index;
  	let glyph_raster = rasterize_glyph_at(&face, glyph_index, 24.0, 0.0, [255, 255, 255]);
  	let shifted_glyph_raster = rasterize_glyph_at(&face, glyph_index, 24.0, 0.5, [255, 255, 255]);
  	let sum = |coverage: &[u8]| coverage.iter().map(|value| *value as u32).sum::<u32>() as f32;
  	assert!(glyph_raster.width > 0 && shifted_glyph_raster.width > 0);
  	assert!((sum(&glyph_raster.coverage) / sum(&shifted_glyph_raster.coverage) - 1.0).abs() < 0.1);
  }
  ```

- `pub fn dilate_coverage(coverage: &[u8], width: i32, height: i32, radius: f32) -> Vec<u8>` (method, since 0.4.0): Widens coverage in a circular shape. (fake bold, the outline pushed outward by radius pixels)
  - Treats coverage as the distance from the pixel center to the outline. (coverage - 0.5, inside is positive)
    Takes the largest of the neighbor pixels' distances minus the distance to that neighbor, adds radius and converts it back to coverage. A straight outline is pushed by exactly radius.
  - `coverage` &[u8]: Coverage. (0 ~ 255, width * height values)
  - `width` i32: Width. (pixels)
  - `height` i32: Height. (pixels)
  - `radius` f32: Radius to widen by. (pixels, copied as is if 0 or less)
  - returns Vec<u8>: Widened coverage. (same size, never smaller than the original values)

  Example: Widen a two-column bar by half a pixel

  ```rust
  use vanilla::core::textshaping::dilate_coverage;
  
  let width = 8;
  let height = 3;
  let mut coverage = vec![0u8; (width * height) as usize];
  for position_y in 0..height {
  	coverage[(position_y * width + 3) as usize] = 255;
  	coverage[(position_y * width + 4) as usize] = 255;
  }
  let dilated_coverage = dilate_coverage(&coverage, width, height, 0.5);
  assert_eq!(dilated_coverage[(width + 3) as usize], 255);
  assert!((dilated_coverage[(width + 2) as usize] as i32 - 128).abs() <= 2);
  assert_eq!(dilated_coverage[width as usize], 0);
  ```

- `pub fn shear_coverage(coverage: &[u8], bitmap_width: i32, bitmap_height: i32, baseline_y: f32, shear: f32) -> Vec<u8>` (method, since 0.4.0): Shears coverage horizontally. (rows above the baseline move right and rows below move left by row height × slant, blending between two pixels)
  - `coverage` &[u8]: Coverage. (0 ~ 255, bitmap_width * bitmap_height values)
  - `bitmap_width` i32: Width. (pixels)
  - `bitmap_height` i32: Height. (pixels)
  - `baseline_y` f32: Baseline position. (pixels from the top)
  - `shear` f32: Slant. (pixels pushed right for every 1 pixel up)
  - returns Vec<u8>: Sheared coverage. (same size, parts pushed outside are cut off)

  Example: A vertical bar above the baseline moves right

  ```rust
  use vanilla::core::textshaping::shear_coverage;
  
  let width = 12;
  let height = 12;
  let mut coverage = vec![0u8; (width * height) as usize];
  for position_y in 0..10 {
  	coverage[(position_y * width + 5) as usize] = 255;
  }
  let sheared_coverage = shear_coverage(&coverage, width, height, 10.0, 0.5);
  let top_row = &sheared_coverage[0..width as usize];
  assert_eq!(top_row[5], 0);
  assert!(top_row[9] > 0 && top_row[10] > 0);
  ```

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

Text direction. (the actual value "ltr" / "rtl" of the original Canvas2D direction)

- `LeftToRight`: Left to right. (the original "ltr")
- `RightToLeft`: Right to left. (the original "rtl")
