# platform/desktop/systemfont (vanilla-engine 0.4.0)

> https://vanillapunch.com/docs/vanilla-engine/0.4.0/api/platform/desktop/systemfont/

Desktop system font lookup. (the file for a font name, fallback fonts to draw characters missing from the fonts)
- A file not in the original. In the original the browser finds CSS font names among OS fonts, and draws characters not in the font list with the OS fallback font.
  Chrome finds them with CoreText on Mac, DirectWrite on Windows and fontconfig on Linux. The Rust version on desktop also finds files with the same APIs and registers them in the text cache.
- find_family_font_file: finds the file and face by font name, weight and italic. None if there is no font with that name. (does not substitute another font like CSS)
  - Mac: system-ui, BlinkMacSystemFont are the system UI font (CTFontCreateUIFontForLanguage, the italic trait of CTFontCreateCopyWithSymbolicTraits when italic, MatchSystemUIFont in Chrome's font_matcher_mac.mm),
    others a font descriptor built from the name and weight traits. -apple-system and ui-serif, ui-sans-serif, ui-monospace, ui-rounded are names Chrome does not know, so None.
    (only Safari knows them. In Canvas2D of Chrome 158 on Mac, "16px -apple-system" is drawn with the default font)
  - Windows: system-ui is the menu font like Chrome (lfMenuFont of NONCLIENTMETRICS, Segoe UI if it cannot be read), others the name in the system font collection (FindFamilyName) and GetFirstMatchingFont.
  - Linux: fontconfig's FcFontMatch. Like Chrome (isAcceptableMatch in Skia SkFontConfigInterface_direct.cpp), accepts only if the found font's name equals the requested name or the name after configuration,
    or it is a metric-compatible substitute (a table like Arial and Liberation Sans), or the requested name is sans, serif, monospace.
- Generic names (serif, sans-serif, monospace, cursive, fantasy, math, and -webkit-body as the standard font) are turned into font names by Chrome's default font table before searching. (resolve_generic_family_name)
  A name wrapped in double quotes ("\"monospace\"") is not converted, like Chrome, and the font spelled that way is looked up. (Mac and Windows have no font of that name, Linux fontconfig accepts monospace)
  The table is IDS_*_FONT_FAMILY of Chromium chrome/app/resources/`locale_settings_<os>`.grd and its translations per language (platform_locale_settings/*.xtb).
  Chrome sets the Common (Zyyy) script value by the browser language (UI language), and a canvas without a document lang picks fonts by the script of the default locale (browser language).
  The separately set value for that script is not registered because it is the browser language's script (RegisterProfilePrefs in prefs_tab_helper.cc), so in the end the Common value is used.
  The canvas the original bakes text on is not attached to the document, so changing the document's lang leaves it as is. (checked with Chrome 158 on Mac)
  The Rust version finds the UI language Chrome would pick from the system preferred languages (read_browser_locale) and uses the same table.
  Example: Mac Korean is serif AppleMyungjo, sans-serif Apple SD Gothic Neo, monospace Menlo, English is Times, Helvetica, Menlo. Windows Korean is serif Batang, sans-serif Malgun Gothic.
- find_fallback_font_file: lets the OS pick a fallback font to draw text (one grapheme cluster).
  - Mac: CTFontCreateForString on the system UI font. (the same API as Chrome Mac's font fallback) If color emoji is wanted, checks Apple Color Emoji first.
  - Windows: IDWriteFontFallback.MapCharacters (base name Segoe UI, user language)
  - Linux: the first font with that character from FcFontSort with a charset containing it. If color emoji is wanted, sets the color property.
- The face index of the returned FontFileSource is included when the OS reports it (Windows, Linux), and on Mac the PostScript name is included to find the right face when reading the font.
  The weight of variable fonts (such as SFNS, the Mac system UI font) is made by the text cache from axis values.

Example: Find the bold font file for the generic name sans-serif

```rust
use vanilla::platform::desktop::systemfont::{find_family_font_file, resolve_generic_family_name, GenericFamily};

assert_eq!(GenericFamily::from_family_name("Sans-Serif"), Some(GenericFamily::SansSerif));
assert_eq!(GenericFamily::from_family_name("Helvetica"), None);
if let Some(family_name) = resolve_generic_family_name(GenericFamily::SansSerif) {
	if let Some(source) = find_family_font_file(&family_name, 700, false) {
		assert!(source.path.exists());
	}
}
```

## Functions and constants

- `pub fn read_double_click_seconds() -> f32` (method, since 0.4.0): Time within which presses count as repeated (double clicks). (seconds, for double and triple clicks in input fields)
  - macOS: Chrome uses NSEvent clickCount, and the time is NSEvent.doubleClickInterval, the double-click speed in System Settings.
  - Windows, Linux: Chrome aura does not read the OS value and uses kDoubleClickTimeMs 500 from ui/events/event_constants.h.
  - returns f32: Time within which presses count as repeated. (seconds, the System Settings value on macOS, 0.5 if it cannot be read or on other operating systems)
- `pub fn is_overlay_scrollbar_preferred() -> bool` (method, since 0.4.0): Whether the system prefers overlay scroll bars. (Show scroll bars in macOS System Settings, PrefersOverlayScrollbars in Chrome's os_settings_provider_mac.mm)
  - macOS: true if NSScroller.preferredScrollerStyle is NSScrollerStyleOverlay (1). (when automatic, the system decides based on the mouse and trackpad)
  - Windows, Linux: always false because Chrome's overlay scroll bar feature (kOverlayScrollbar) is off.
  - returns bool: true if overlay scroll bars are preferred. (always false on Windows and Linux)
- `pub fn find_family_font_file(family_name: &str, weight: u16, is_italic: bool) -> Option<FontFileSource>` (method, since 0.4.0): Finds a file by font name. (one CSS font name, generic names are converted to names from Chrome's default font table before searching. None if not found)
  - A name wrapped in double quotes is not converted even when spelled like a generic name, and the font of that name is looked up. (Chrome's FontSelector::FamilyNameFromSettings does not convert quoted names through the default font table, and FontCache looks up that spelling)
  - `family_name` &str: One font name. (leading and trailing spaces are trimmed, wrapped in double quotes like "\"monospace\"" it is a font name)
  - `weight` u16: Weight. (CSS font-weight, 100 ~ 900, 400 is normal)
  - `is_italic` bool: true to find the italic face.
  - returns Option<FontFileSource>: The found file and face. None if the name is empty, there is no font with that name, or no font matches the generic name.

  Example: Find by name, and fall back to a fallback font if missing

  ```rust
  use vanilla::platform::{find_fallback_font_file, find_family_font_file};
  
  let source = find_family_font_file("NoSuchFamily", 400, false).or_else(|| find_fallback_font_file("A", 400, false, false));
  if let Some(source) = source {
  	assert!(source.path.exists());
  }
  assert!(find_family_font_file("  ", 400, false).is_none());
  assert!(find_family_font_file("\"monospace\"", 400, false).is_none() || find_family_font_file("monospace", 400, false).is_some());
  ```

- `pub fn list_family_font_faces(family_name: &str) -> Vec<FamilyFontFace>` (method, since 0.4.0): Lists every weight and slant face of a font name. (candidates for picking a face with the CSS weight rule: the family faces of Mac CoreText, the family fonts of Windows DirectWrite, the weights of Linux fontconfig)
  - `family_name` &str: One font name. (same as find_family_font_file)
  - returns Vec<FamilyFontFace>: Face list. Empty if the named font does not exist or the name cannot list faces (Mac system-ui).

  Example: Weight and slant faces

  ```rust
  use vanilla::platform::list_family_font_faces;
  
  for face in list_family_font_faces("Helvetica Neue") {
  	assert!((100..=900).contains(&face.weight));
  	assert!(face.source.path.exists());
  }
  assert!(list_family_font_faces("NoSuchFamily").is_empty());
  ```

- `pub fn find_fallback_font_file(text: &str, weight: u16, is_italic: bool, is_color_wanted: bool) -> Option<FontFileSource>` (method, since 0.4.0): Finds a fallback font file to draw text. (picked by the OS, color emoji fonts first if is_color_wanted)
  - `text` &str: Text to draw. (one grapheme cluster)
  - `weight` u16: Weight. (CSS font-weight)
  - `is_italic` bool: true if an italic face is wanted.
  - `is_color_wanted` bool: true to check color emoji fonts first.
  - returns Option<FontFileSource>: File and face picked by the OS. None if the text is empty or nothing was picked.
- `pub fn find_last_resort_font_file() -> Option<(FontFileSource, String)>` (method, since 0.4.0): Last resort fallback font file. (Chrome FontCache::GetLastResortFallbackFont, also returns the font name. None if not found)
  - It becomes the parent font when computing font-relative units (ex, ch, cap, ic, lh besides em) in the font string of a canvas not attached to a document. (checked with Times metrics in Chrome 158 on Mac)
  - Mac: Times, or Lucida Grande if missing. (font_cache_mac.mm)
  - Windows, Linux: no name (OS default), Sans, Arial, and on Windows then MS UI Gothic, Microsoft Sans Serif, Segoe UI, Calibri, Times New Roman, Courier New. (font_cache_skia.cc)
  - returns Option<(FontFileSource, String)>: (found file and face, font name from the list). None if no name in the list could be found.
- `pub fn read_last_resort_family_name() -> Option<String>` (method, since 0.4.0): Name of the last resort fallback font. (the first installed name, skipping no name (OS default). Looked up once at first, None if not found)
  - The text cache places this font after the system fallback font. (the last step of Chrome's FontFallbackIterator)
  - returns Option<String>: The first installed name. None if no name in the list is installed. (each thread keeps using the value found first)
- `pub fn read_browser_locale() -> String` (method, since 0.4.0): UI language Chrome picks. (the first language in the system preferred language order that Chrome has a translation for, "en" if none)
  - Matches by the language part. Chinese is zh-TW if Traditional (Hant) or Taiwan, Hong Kong, Macau, otherwise zh-CN. The old names iw is he, tl is fil, in is id, nb is no. (aliases of l10n_util)
  - The only languages whose font tables differ are Mac ar, fa, he, ja, ko, zh-CN, zh-TW, Windows bn, ja, ko, th, zh-CN, zh-TW, Linux bn, ja, ko, th.
  - returns String: Chrome UI language name. (such as "ko", "en", "zh-TW", "en" if nothing matches)
- `pub fn resolve_generic_family_name(generic_family: GenericFamily) -> Option<String>` (method, since 0.4.0): Generic name → font name. (the same value as Chrome GenericFontFamilySettings::Get, None on OSes without a table)
  - A comma-separated list gives the first installed font, or the first name if none is installed. (gfx::FontList::FirstAvailableOrFirst)
  - Mac: if monospace is Osaka, Osaka-Mono. (generic_font_family_settings.cc)
  - Windows: if monospace starts with Courier and ClearType is on, Consolas. (ShouldUseAlternateDefaultFixedFont in prefs_tab_helper.cc)
  - `generic_family` GenericFamily: Kind of generic name.
  - returns Option<String>: Picked font name. None on an OS without a table or if that entry's value is empty. (each thread keeps using the value picked first)

## GenericFamily (enum) (Clone, Copy, Debug, PartialEq, Eq)

Kind of CSS generic font name. (the kinds of Chrome GenericFontFamilySettings, in the same order as the table columns)

- `Standard`: Standard font. (the first column of the table, the generic name -webkit-body is this one. Chrome's FontBuilder::GenericFontFamilyName gives the standard font name)
- `Serif`: serif.
- `SansSerif`: sans-serif.
- `Monospace`: monospace.
- `Cursive`: cursive.
- `Fantasy`: fantasy.
- `Math`: math.

- `pub fn from_family_name(family_name: &str) -> Option<GenericFamily>` (static, since 0.4.0): Generic name → kind. (serif, sans-serif, monospace, cursive, fantasy, math, -webkit-body is Standard, case-insensitive. Only names Chrome's font_selector.cc knows, otherwise None)
  - `family_name` &str: One CSS font name. (leading and trailing spaces are trimmed)
  - returns Option<GenericFamily>: Kind of that generic name. None if it is not a generic name. (names like system-ui are None too)
