Skip to content
FontDatabase

FontDatabase

Mojo struct 🡭

FontDatabase

@memory_only
struct FontDatabase

Every installed face on this machine, scanned once.

Construct one and reuse it: building it walks the font directories and reads a few tables out of every font file found, which is the whole cost of a lookup – matching against an already-built database is arithmetic over a list. resolve_font_file builds a throwaway one per call, so a caller resolving more than a handful of fonts wants a FontCache (which holds one of these) instead.

Fields

  • faces (List[FontFace])

Implemented traits

AnyType, Deinitable, Movable

Methods

__init__

fn def __init__(out self)

Scan the platform’s font directories.

Reads the cache file when it holds a table recorded for these directories at these modification times, and writes one after a scan; see this module’s docstring for the file and how to disable it.

Never raises on a bad font file, an unreadable directory or an unusable cache – those are skipped – so a machine with no fonts installed at all yields an empty database, and it is resolve that reports that.

Args:

  • self (Self)

Returns:

Self

fn def __init__(out self, var faces: List[FontFace])

A database over faces alone, with no scan of the installed fonts: what FontCache holds until its first lookup, and a way to build a database over known faces.

Args:

  • faces (List[FontFace]): The faces the database resolves against.
  • self (Self)

Returns:

Self

resolve

fn def resolve(self, family: String, slant: FontSlant = FontSlant.NORMAL, weight: FontWeight = FontWeight.NORMAL, codepoint: Int = Int(-1)) -> String

Best-matching font file for this request.

With codepoint set, a face that maps that character outranks every other term: candidates are ranked normally, then walked best-first until one covers it. If none does, the plain best match is returned rather than raising, so a missing glyph degrades to a .notdef box.

Args:

  • self (Self)
  • family (String): Font family name or generic alias (e.g. “sans-serif”).
  • slant (FontSlant): Requested upright/italic/oblique style.
  • weight (FontWeight): Requested normal/bold weight.
  • codepoint (Int): Unicode codepoint the matched font should contain, or -1 for no constraint.

Returns:

String: The matched font’s absolute file path.

Raises:

Error: no font files were found on this machine.