AI-native design editor. Open-source Figma alternative.
refactor: read font tables through HarfBuzz, TextDecoder, and read-fonts (#1719)
Danila Poyarkov7c46064c2fa7
diff --git a/desktop/src/fonts/sfnt.rs b/desktop/src/fonts/sfnt.rsindex 20cbf9c63..9258d338e 100644--- a/desktop/src/fonts/sfnt.rs+++ b/desktop/src/fonts/sfnt.rs@@ -1,5 +1,6 @@//! Byte-level knowledge of OpenType font files, independent of how fonts are discovered.+use read_fonts::FontRef;use std::io::{Read, Seek, SeekFrom};const TTC_TAG: &[u8; 4] = b"ttcf";@@ -13,41 +14,27 @@ fn read_array<const N: usize>(reader: &mut impl Read) -> Option<[u8; N]> {Some(bytes)}-fn read_u16(data: &[u8], offset: usize) -> Option<u16> {- Some(u16::from_be_bytes(- data.get(offset..offset + 2)?.try_into().ok()?,- ))-}--fn read_u32(data: &[u8], offset: usize) -> Option<u32> {- Some(u32::from_be_bytes(- data.get(offset..offset + 4)?.try_into().ok()?,- ))-}-/// Returns font data whose first table directory is face `index`, which renderers that read only/// the first face of a collection (CanvasKit) accept. Table offsets in a collection are absolute,/// so the tables themselves stay where they are.pub fn standalone_face(data: &[u8], index: u32) -> Option<Vec<u8>> {- if data.get(0..4)? != TTC_TAG {- return (index == 0).then(|| data.to_vec());- }- let count = read_u32(data, 8)?;- if index >= count {- return None;+ let face = FontRef::from_index(data, index).ok()?;+ if face.ttc_index().is_none() {+ return Some(data.to_vec());}- let face = read_u32(data, OFFSET_TABLE_SIZE + 4 * index as usize)? as usize;- let num_tables = read_u16(data, face + 4)? as usize;- let directory = OFFSET_TABLE_SIZE + num_tables * TABLE_RECORD_SIZE;+ let directory = face.table_directory();+ let size = OFFSET_TABLE_SIZE + directory.num_tables() as usize * TABLE_RECORD_SIZE;let mut standalone = data.to_vec();standalone- .get_mut(..directory)?- .copy_from_slice(data.get(face..face + directory)?);+ .get_mut(..size)?+ .copy_from_slice(directory.offset_data().as_bytes().get(..size)?);Some(standalone)}/// Returns whether every face in a font file stores outlines only in a table the renderer cannot-/// draw, such as Apple's `hvgl` (PingFang on macOS 15 and later). Reads only the table directories.+/// draw, such as Apple's `hvgl` (PingFang on macOS 15 and later). Reads only the table directories+/// from the stream, as it runs on every failed load of such a family: read-fonts would need the+/// whole file, tens of megabytes for PingFang, in memory.pub fn has_only_unsupported_outlines(reader: &mut (impl Read + Seek)) -> Option<bool> {let header: [u8; 12] = read_array(reader)?;let face_offsets = if &header[0..4] == TTC_TAG {diff --git a/packages/core/src/text/font/glyphs.ts b/packages/core/src/text/font/glyphs.tsindex e855073bd..e44c873b3 100644--- a/packages/core/src/text/font/glyphs.ts+++ b/packages/core/src/text/font/glyphs.ts@@ -6,6 +6,7 @@ import {fontInstance,glyphCommands,harfBuzzFont,+ harfBuzzTable,isHarfBuzzLoaded,loadHarfBuzz,shapeText,@@ -13,7 +14,6 @@ import {type OutlineCommand,type ShapingOptions} from './harfbuzz'-import { fontTableView } from './variation'export type { OutlineCommand } from './harfbuzz'@@ -113,8 +113,8 @@ const lineMetricsCache = new WeakMap<HarfBuzzFont, LineMetrics>()function lineMetrics(parsed: HarfBuzzFont): LineMetrics {const cached = lineMetricsCache.get(parsed)if (cached) return cached- const hhea = fontTableView(parsed.bytes, 'hhea')- const os2 = fontTableView(parsed.bytes, 'OS/2')+ const hhea = harfBuzzTable(parsed.face, 'hhea')+ const os2 = harfBuzzTable(parsed.face, 'OS/2')const hasHhea = hhea !== null && hhea.byteLength >= 8const metrics = {ascender: hasHhea ? hhea.getInt16(4) : 0,diff --git a/packages/core/src/text/font/harfbuzz.ts b/packages/core/src/text/font/harfbuzz.tsindex d30a97e07..e4a9689ea 100644--- a/packages/core/src/text/font/harfbuzz.ts+++ b/packages/core/src/text/font/harfbuzz.ts@@ -6,8 +6,6 @@ import { ResourceCache } from '#core/cache/resource'import { IS_BROWSER } from '#core/constants'import { servesRuntimeAsset, unservedRuntimeAssetMessage } from '#core/runtime-assets/served'-import { fontTableView } from './variation'-export interface OutlineCommand {type: stringx?: number@@ -168,13 +166,25 @@ const outlineCache = new ResourceCache<number, readonly OutlineCommand[]>({})let nextInstanceId = 0+/**+ * A copy of one of the face's tables as HarfBuzz finds it, in a file or a collection. HarfBuzz+ * hands back a view of its memory, which the next call can move; the tables read this way are a+ * few dozen bytes.+ */+export function harfBuzzTable(face: HarfBuzzModule.Face, tag: string): DataView | null {+ const table = face.referenceTable(tag)+ return table ? new DataView(table.slice().buffer) : null+}+/** A font file read by HarfBuzz, or `null` when HarfBuzz is not loaded or the file has no glyphs. */export function harfBuzzFont(bytes: ArrayBuffer): HarfBuzzFont | null {const hb = harfBuzz- const maxp = fontTableView(bytes, 'maxp')- const glyphCount = maxp && maxp.byteLength >= 6 ? maxp.getUint16(4) : 0- if (!hb || glyphCount === 0) return null+ if (!hb) return null+ // The first face of a collection, the one CanvasKit draws.const face = new hb.Face(new hb.Blob(bytes))+ const maxp = harfBuzzTable(face, 'maxp')+ const glyphCount = maxp && maxp.byteLength >= 6 ? maxp.getUint16(4) : 0+ if (glyphCount === 0) return nullreturn {hb,face,diff --git a/packages/core/src/text/font/variation.ts b/packages/core/src/text/font/variation.tsindex e2ec0202a..01fa12181 100644--- a/packages/core/src/text/font/variation.ts+++ b/packages/core/src/text/font/variation.ts@@ -9,6 +9,10 @@ interface TableRange {const WINDOWS_PLATFORM = 3const MAC_PLATFORM = 1const ENGLISH_US = 0x409+/** Windows names are UTF-16; Mac names are read in the Roman script, the one with a decoder. */+const WINDOWS_NAMES = new TextDecoder('utf-16be')+const MAC_ROMAN_NAMES = new TextDecoder('macintosh')+const MAC_ROMAN = 0const NAME_HEADER_SIZE = 6const NAME_RECORD_SIZE = 12const FVAR_HEADER_SIZE = 16@@ -69,13 +73,11 @@ function fontName(view: DataView, name: TableRange, nameId: number): string | nuif (start + length > end) continueconst bytes = new Uint8Array(view.buffer, view.byteOffset + start, length)if (platform === WINDOWS_PLATFORM) {- let value = ''- for (let c = 0; c + 1 < length; c += 2)- value += String.fromCharCode((bytes[c] << 8) | bytes[c + 1])+ const value = WINDOWS_NAMES.decode(bytes)if (language === ENGLISH_US) return valuefallback ??= value- } else if (platform === MAC_PLATFORM) {- fallback ??= String.fromCharCode(...bytes)+ } else if (platform === MAC_PLATFORM && view.getUint16(record + 2) === MAC_ROMAN) {+ fallback ??= MAC_ROMAN_NAMES.decode(bytes)}}return fallbackdiff --git a/packages/core/src/text/web-font/resolver.ts b/packages/core/src/text/web-font/resolver.tsindex cc5db3991..c8071938f 100644--- a/packages/core/src/text/web-font/resolver.ts+++ b/packages/core/src/text/web-font/resolver.ts@@ -68,7 +68,7 @@ const DEFAULT_WEB_FONT_SUBSETS = []export function normalizedCoverageText(text: string): string {- return Array.from(new Set(text)).sort().join('')+ return uniq(Array.from(text)).sort().join('')}export function webFontSubsetsForText(text: string): string[] {diff --git a/packages/core/tests/text/font/glyphs.test.ts b/packages/core/tests/text/font/glyphs.test.tsindex c24355000..44fb8bc4e 100644--- a/packages/core/tests/text/font/glyphs.test.ts+++ b/packages/core/tests/text/font/glyphs.test.ts@@ -8,9 +8,44 @@ import { fontManager } from '@open-pencil/core/text'import {getGlyphOutlineMetricsSync,glyphAdvanceSync,- glyphOutlineSourceSync+ glyphOutlineSourceSync,+ measureTextWithFont} from '#core/text/font/glyphs'+/** `faces` as one collection, as system CJK fonts ship: each face's table offsets move with it. */+function collectionOf(...faces: ArrayBuffer[]): ArrayBuffer {+ const header = 12 + faces.length * 4+ const bytes = new Uint8Array(header + faces.reduce((size, face) => size + face.byteLength, 0))+ const view = new DataView(bytes.buffer)+ view.setUint32(0, 0x74746366)+ view.setUint32(4, 0x00010000)+ view.setUint32(8, faces.length)+ let start = header+ faces.forEach((face, index) => {+ bytes.set(new Uint8Array(face), start)+ view.setUint32(12 + index * 4, start)+ for (let table = 0; table < view.getUint16(start + 4); table++) {+ const offset = start + 12 + table * 16 + 8+ view.setUint32(offset, view.getUint32(offset) + start)+ }+ start += face.byteLength+ })+ return bytes.buffer+}++test('reads a font collection as its first face, as CanvasKit draws it', async () => {+ const fonts = join(FIXTURES, 'fonts')+ const chinese = await Bun.file(join(fonts, 'NotoSansSC-Regular.ttf')).arrayBuffer()+ const latin = await Bun.file(join(fonts, 'InterVariable-Latin.ttf')).arrayBuffer()+ await fontManager.markLoaded('Collection Test', 'Regular', collectionOf(chinese, latin))+ await fontManager.markLoaded('Collection Test Single', 'Regular', chinese)++ expect(glyphOutlineSourceSync('Collection Test', 'Regular')?.covers('中文')).toBe(true)+ const measured = measureTextWithFont('中文', 16, 'Collection Test', 'Regular')+ expect(measured).toEqual(measureTextWithFont('中文', 16, 'Collection Test Single', 'Regular'))+ expect(measured?.height).toBeGreaterThan(0)+})+test('measures default advances whatever instance of a variable font was last outlined', async () => {const family = 'OpenType Test Variable'await fontManager.markLoaded(