dymokomi/luce-svg
Source of release 0.9.1
0.9.1 / src / svg / text_font_files.lucb
#==============================================================================================
#
# svg/text_font_files - FontFiles: a GlyphSource over font files, the system's by default
#
# DESCRIPTION:
# The GlyphSource `load` uses when the caller passes none: the font files under the
# platform's font directories (FontFiles.system()), or under directories the caller
# names (FontFiles.open), read and shaped by luce-fonts' opentype and shaping
# modules (HarfBuzz's default shaper). Faces are chosen as CSS chooses them: the
# first family of the list that is installed, matched without regard to case, then
# the style (italic, oblique, normal in CSS's order of preference) and the nearest
# weight; generic families (serif, sans-serif, monospace, cursive, fantasy,
# system-ui) stand for the usual faces of macOS, Windows and Linux unless set with
# `set_generic`; a list with nothing installed falls back to serif, as browsers do.
# A character a face lacks comes from the first other face that has it. Faces are
# numbered from 1 in the catalog's order (text_font_catalog.lucb).
#
#==============================================================================================
## The generic families, and the installed families each stands for, in order of preference.
let generic_names: str[6] = ["serif", "sans-serif", "monospace", "cursive", "fantasy", "system-ui"]
let generic_candidates: str[36] = [
"Times New Roman", "Times", "Noto Serif", "DejaVu Serif", "Liberation Serif", "Georgia",
"Helvetica", "Arial", "Noto Sans", "DejaVu Sans", "Liberation Sans", "Segoe UI",
"Menlo", "Consolas", "Noto Mono", "DejaVu Sans Mono", "Liberation Mono", "Courier New",
"Apple Chancery", "Comic Sans MS", "URW Chancery L", "Noto Serif", "Times New Roman", "Times",
"Papyrus", "Impact", "Noto Sans", "DejaVu Sans", "Arial", "Helvetica",
"Helvetica", "Segoe UI", "Arial", "Noto Sans", "DejaVu Sans", "Liberation Sans"]
## A glyph and the scalar it was mapped from, for kerning a pair through the shaper.
struct MappedGlyph:
var face: u32
var glyph: u32
var scalar: u32
## A GlyphSource over the font files of some directories. Make one with `system()` or
## `open(...)`, pass its address in `Options.glyphs`, and `close` it when the pictures
## loaded with it are made (they keep no reference to it). One thread at a time.
pub struct FontFiles: GlyphSource:
var faces: List[CatalogFace] = List[CatalogFace]()
## Strings the source owns: generic overrides and directory names.
var text: Arena = Arena()
## Per generic family, the family set with `set_generic` ("" for the defaults).
var generics: str[6] = ["", "", "", "", "", ""]
var mapped: MappedGlyph[1024]
## The faces of the font files under `directories` (searched recursively; missing ones
## are skipped).
pub static func open(directories: const str[]) -> FontFiles!:
var source = FontFiles()
errdefer source.close()
try catalog_directories(directories, &source.faces)
return source
## The faces of the platform's font directories: /System/Library/Fonts, /Library/Fonts
## and ~/Library/Fonts on macOS; %WINDIR%\Fonts and the user's on Windows;
## /usr/share/fonts, /usr/local/share/fonts and the user's on Linux.
pub static func system() -> FontFiles!:
var source = FontFiles()
errdefer source.close()
var directories = List[str]()
defer directories.release()
try system_font_directories(&source.text, &directories)
try catalog_directories(directories.view(), &source.faces)
return source
## Make the generic family `generic` (serif, sans-serif, monospace, cursive, fantasy or
## system-ui) stand for the installed `family`.
pub func set_generic(generic: str, family: str) -> !:
for (index, name) in generic_names.indexed():
if name == generic:
self.generics[index] = try self.text.store(family.bytes)
return
error(invalid, "not a generic font family")
## How many faces the source has.
pub func face_count() -> usize:
return self.faces.used
## The family of face `face` (numbered from 1).
pub func family(face: u32) -> str:
return self.faces.items[face - 1].probe.family_name
## Free every face and what the source holds.
pub func close():
for index in 0..<self.faces.used:
self.faces.items[index].release()
self.faces.release()
self.text.release()
# mark: Choosing faces =====================================================================
func select_face(query: FaceQuery) -> u32?:
var rest = query.families
while strings.trim(rest).length > 0:
var piece = rest
rest = ""
if let comma = strings.find(piece, ","):
rest = (str)piece.bytes[comma + 1..]
piece = (str)piece.bytes[..<comma]
var name = strings.trim(piece)
if name.length >= 2 and (name.bytes[0] == '"' or name.bytes[0] == '\''):
name = strings.trim((str)name.bytes[1..<name.length - 1])
if let generic = FontFiles.generic_index(name):
if let found = self.generic_face(generic, query):
return found
elif let found = self.best(name, query):
return found
# Nothing on the list is installed: serif, else any face.
if let found = self.generic_face(0, query):
return found
return 1 if self.faces.used > 0 else none
## The index of generic family `name`, if it is one.
static func generic_index(name: str) -> usize?:
for (index, generic) in generic_names.indexed():
if same_name(name, generic):
return index
return none
## The face generic family `generic` stands for: its override, else the first of its
## candidates that is installed.
func generic_face(generic: usize, query: FaceQuery) -> u32?:
if self.generics[generic].length > 0:
return self.best(self.generics[generic], query)
for candidate in generic_candidates[generic * 6..<generic * 6 + 6]:
if let found = self.best(candidate, query):
return found
return none
## The face of `family` that best matches the query's style and weight, by CSS's rules.
func best(family: str, query: FaceQuery) -> u32?:
var chosen: usize? = none
var chosen_score: i64 = 1 << 40
for at in 0..<self.faces.used:
let face = self.faces.items[at].probe
if not same_name(face.family_name, family):
continue
# Style: the wanted slant first, then the other slanted one, then upright.
let slope = opentype.sfnt_face_slope(face)
var style_rank: i64 = 0
if query.style == 0:
style_rank = 0 if slope == 0 else (1 if slope == 2 else 2)
elif query.style == 1:
style_rank = 0 if slope == 1 else (1 if slope == 2 else 2)
else:
style_rank = 0 if slope == 2 else (1 if slope == 1 else 2)
let score = style_rank * 100000 + weight_rank((i64)query.weight, (i64)opentype.sfnt_face_weight(face))
if score < chosen_score:
chosen_score = score
chosen = at
let index = chosen else return none
return (u32)(index + 1)
func fallback_face(face: u32, scalar: u32) -> u32?:
# A face already loaded first, then any.
for pass in 0..<(usize)2:
for at in 0..<self.faces.used:
let entry = &self.faces.items[at]
if (u32)(at + 1) == face or (pass == 0) == (entry.font == none):
continue
if opentype.sfnt_face_glyph_for_code_point(entry.probe, scalar) != 0:
return (u32)(at + 1)
return none
# mark: Metrics, glyphs and outlines ==========================================================
func face_metrics(face: u32) -> FaceMetrics:
let f = self.faces.items[face - 1].probe
let upem = (f64)f.units_per_em
var metrics = FaceMetrics(units_per_em = upem, ascent = (f64)f.ascender, descent = (f64)f.descender,
underline_position = (f64)f.underline_position, underline_thickness = (f64)f.underline_thickness)
metrics.x_height = ((f64)f.ascender - (f64)f.descender) * 0.45
metrics.strikeout_position = metrics.x_height * 0.5
metrics.subscript_offset = upem * 0.14
metrics.superscript_offset = upem * 0.48
# The sub- and superscript offsets of the OS/2 table.
if let table = opentype.sfnt_face_table(f, opentype.sfnt_tag('O', 'S', '/', '2')):
if table.length >= 28:
metrics.subscript_offset = (f64)opentype.sfnt_i16(table, 16)
metrics.superscript_offset = (f64)opentype.sfnt_i16(table, 24)
if let os2 = f.os2:
if os2.sx_height > 0:
metrics.x_height = (f64)os2.sx_height
metrics.strikeout_position = (f64)os2.y_strikeout_position
if metrics.underline_thickness <= 0.0:
metrics.underline_thickness = upem / 12.0
return metrics
func glyph_index(face: u32, scalar: u32) -> u32:
let glyph = opentype.sfnt_face_glyph_for_code_point(self.faces.items[face - 1].probe, scalar)
self.mapped[(usize)((glyph * 31 + face) % 1024)] = MappedGlyph(face = face, glyph = glyph, scalar = scalar)
return glyph
func glyph_advance(face: u32, glyph: u32) -> f64:
if not self.faces.items[face - 1].load():
return 0.0
let loaded = self.faces.items[face - 1].face() else return 0.0
return (f64)opentype.sfnt_face_advance(loaded, glyph)
func glyph_kerning(face: u32, left: u32, right: u32) -> f64:
# The pair's scalars, as glyph_index mapped them, shaped together.
let a = self.mapped[(usize)((left * 31 + face) % 1024)]
let b = self.mapped[(usize)((right * 31 + face) % 1024)]
if a.face != face or a.glyph != left or b.face != face or b.glyph != right:
return 0.0
let pair: u32[2] = [a.scalar, b.scalar]
var out: GlyphRecord[2] = [GlyphRecord(), GlyphRecord()]
let count = self.shape(face, pair, false, true, false, out) catch:
recover none
if count != 2 or out[0].glyph != left:
return 0.0
return out[0].advance - self.glyph_advance(face, left)
func shape(face: u32, scalars: const u32[], rtl: bool, kerning: bool, small_caps: bool, out: GlyphRecord[]) -> usize?!:
if not self.faces.items[face - 1].load():
return none
let font = self.faces.items[face - 1].font else return none
with memory.heap:
# UTF-16, with the index of each code unit's scalar for the clusters.
let units = try new u16[scalars.length * 2 + 1]
defer free(units)
let owner = try new usize[scalars.length * 2 + 1]
defer free(owner)
var used: usize = 0
for (index, scalar) in scalars.indexed():
if scalar >= 0x10000:
let value = scalar - 0x10000
units[used] = (u16)(0xD800 + (value >> 10))
units[used + 1] = (u16)(0xDC00 + (value & 0x3FF))
owner[used] = index
owner[used + 1] = index
used += 2
else:
units[used] = (u16)scalar
owner[used] = index
used += 1
let buffer = shaping.hb_buffer_create()
defer shaping.hb_buffer_destroy(buffer)
shaping.hb_buffer_add_utf16(buffer, units[..<used])
shaping.hb_buffer_set_direction(buffer, shaping.HbDirection.rtl if rtl else shaping.HbDirection.ltr)
shaping.hb_buffer_guess_segment_properties(buffer)
var features: shaping.HbFeature[2]
var count: usize = 0
if small_caps:
features[count] = shaping.HbFeature(tag = opentype.sfnt_tag('s', 'm', 'c', 'p'), value = 1, start = 0, end = shaping.hb_feature_global_end)
count += 1
if not kerning:
features[count] = shaping.HbFeature(tag = opentype.sfnt_tag('k', 'e', 'r', 'n'), value = 0, start = 0, end = shaping.hb_feature_global_end)
count += 1
shaping.hb_shape(font, buffer, features[..<count])
let positions = shaping.hb_buffer_get_glyph_positions(buffer)
let infos = shaping.hb_buffer_get_glyph_infos(buffer)
for at in 0..<(infos.length if infos.length < out.length else out.length):
out[at] = GlyphRecord(glyph = infos[at].codepoint, cluster = owner[(usize)infos[at].cluster], advance = (f64)positions[at].x_advance,
x_offset = (f64)positions[at].x_offset, y_offset = (f64)positions[at].y_offset)
return infos.length
func glyph_outline(face: u32, glyph: u32, path: Path*) -> bool!:
if not self.faces.items[face - 1].load():
return false
let loaded = self.faces.items[face - 1].face() else return false
var outline = with_heap_glyph_path(loaded, glyph)
defer outline.release()
let points = outline.points.view()
if outline.verbs.length() == 0:
return false
var at: usize = 0
# Font units with y up, from the path's y-down pixels at one pixel per unit.
for verb in outline.verbs.view():
match verb:
.move:
try path.move_to((f64)points[at].x, -(f64)points[at].y)
at += 1
.line:
try path.line_to((f64)points[at].x, -(f64)points[at].y)
at += 1
.quad:
try path.quad_to((f64)points[at].x, -(f64)points[at].y, (f64)points[at + 1].x, -(f64)points[at + 1].y)
at += 2
.cubic:
try path.cubic_to((f64)points[at].x, -(f64)points[at].y, (f64)points[at + 1].x, -(f64)points[at + 1].y,
(f64)points[at + 2].x, -(f64)points[at + 2].y)
at += 3
.close:
try path.close()
_:
continue
return true
## The outline of `glyph` at one pixel per font unit, in the heap.
func with_heap_glyph_path(face: const opentype.SfntFace*, glyph: u32) -> opentype.GlyphPath:
with memory.heap:
return opentype.sfnt_face_glyph_path(face, glyph, (f32)face.units_per_em)
## How far a face's `weight` is from the `wanted` one by CSS's font matching: exact first,
## then for 400..500 the weights up to 500, below, then above; below 400 the lighter ones
## first; above 500 the heavier ones first.
func weight_rank(wanted: i64, weight: i64) -> i64:
if weight == wanted:
return 0
if wanted >= 400 and wanted <= 500:
if weight > wanted and weight <= 500:
return weight - wanted
if weight < wanted:
return 1000 + (wanted - weight)
return 2000 + (weight - wanted)
if wanted < 400:
return (wanted - weight) if weight < wanted else 1000 + (weight - wanted)
return (weight - wanted) if weight > wanted else 1000 + (wanted - weight)
## Whether two family names are the same, ignoring ASCII case.
func same_name(a: str, b: str) -> bool:
if a.length != b.length:
return false
for index in 0..<a.length:
var x = a.bytes[index]
var y = b.bytes[index]
if x >= 'A' and x <= 'Z':
x += 32
if y >= 'A' and y <= 'Z':
y += 32
if x != y:
return false
return true
# mark: The system's fonts ======================================================================
## The system's fonts, which `load` sets text in when the caller passes no GlyphSource: made
## on first use and kept for the process; used by one conversion at a time.
var system_font_files: FontFiles*? = none
var system_fonts_tried: bool
var system_fonts_lock: sync.Mutex
## The system's fonts, catalogued on the first call; none when there are none. The caller
## holds system_fonts_lock.
func system_glyphs() -> FontFiles*?:
if not system_fonts_tried:
system_fonts_tried = true
with memory.heap:
let made: FontFiles? = FontFiles.system() catch:
recover none
if let catalogued = made:
if catalogued.face_count() > 0:
let boxed = new FontFiles() else return none
*boxed = catalogued
system_font_files = boxed
else:
var empty = catalogued
empty.close()
return system_font_files