AI-native design editor. Open-source Figma alternative.
fix(fonts): explain PingFang substitution and draw its CJK text (#781)
Danila Poyarkovd4f34abdb256
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex acfc09005..f22405072 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -22,6 +22,8 @@- Show what to update instead of a blank window when the browser or system WebView is too old, naming the detected macOS, Safari, Chrome, Edge, Firefox, WebKitGTK, or WebView2 version and linking a prefilled bug report, and explain a failed start the same way (#744).- Start on macOS 13 with WebKit older than Safari 17.4, which previously failed with `Promise.withResolvers is not a function` (#744).- Evaluate the `**` operator in the AI and MCP `calc` tool, which its own description advertised but which the tool rejected. `calc` now accepts exactly the arithmetic it documents — `+ - * / % **`, parentheses and `min max floor ceil round abs sqrt pow` — and no longer evaluates undocumented expressions such as `random()`, factorials, trigonometry, strings, arrays, or property access.+- Show Chinese, Japanese, Korean, and Arabic characters in a fallback font when the text's own font is unavailable and another font substitutes for it, instead of drawing missing-glyph boxes (#746).+- Explain in the font issues banner when an installed font, such as PingFang on macOS 15 and later, stores outlines in a format OpenPencil cannot draw yet, instead of spending over a second trying to load each of its styles (#746).### Securitydiff --git a/desktop/Cargo.lock b/desktop/Cargo.lockindex 22ef2cfe8..9e1c3cba2 100644--- a/desktop/Cargo.lock+++ b/desktop/Cargo.lock@@ -3306,6 +3306,8 @@ dependencies = [name = "open_pencil"version = "0.15.1"dependencies = [+ "core-foundation 0.9.4",+ "core-text","fix-path-env","font-kit","keyring",diff --git a/desktop/Cargo.toml b/desktop/Cargo.tomlindex 9faa471cd..5d82f7093 100644--- a/desktop/Cargo.toml+++ b/desktop/Cargo.toml@@ -47,6 +47,8 @@ tauri-plugin-wdio-webdriver = { version = "1.3.0", optional = true }[target.'cfg(target_os = "macos")'.dependencies]security-framework = "3"+core-foundation = "0.9"+core-text = "20.1"[target.'cfg(any(target_os = "macos", windows, target_os = "linux"))'.dependencies]tauri-plugin-single-instance = { version = "2", features = ["deep-link"] }diff --git a/desktop/src/fonts.rs b/desktop/src/fonts.rsindex e4aed3c8f..17358c460 100644--- a/desktop/src/fonts.rs+++ b/desktop/src/fonts.rs@@ -1,5 +1,6 @@use font_kit::source::SystemSource;use serde::Serialize;+use std::io::{Read, Seek, SeekFrom};use std::sync::OnceLock;#[derive(Serialize, Clone)]@@ -70,11 +71,44 @@ pub async fn list_system_fonts() -> Vec<FontFamily> {families}-fn load_system_font_blocking(family: String, style: String) -> Result<Vec<u8>, String> {+#[derive(Debug, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct FontLoadError {+ code: FontLoadErrorCode,+ message: String,+}++#[derive(Clone, Copy, Debug, PartialEq, Serialize)]+#[serde(rename_all = "kebab-case")]+enum FontLoadErrorCode {+ NotFound,+ UnsupportedFormat,+ Failed,+}++impl FontLoadError {+ fn new(code: FontLoadErrorCode, message: String) -> Self {+ Self { code, message }+ }+}++fn load_system_font_blocking(family: String, style: String) -> Result<Vec<u8>, FontLoadError> {+ // Checked before font-kit, which would read every face of a large collection only to fail.+ #[cfg(target_os = "macos")]+ if macos::family_has_only_unsupported_outlines(&family) {+ return Err(FontLoadError::new(+ FontLoadErrorCode::UnsupportedFormat,+ format!("Font outlines are in an unsupported format: {family}"),+ ));+ }+let source = SystemSource::new();- let family_handle = source- .select_family_by_name(&family)- .map_err(|e| format!("Font family not found: {e}"))?;+ let family_handle = source.select_family_by_name(&family).map_err(|e| {+ FontLoadError::new(+ FontLoadErrorCode::NotFound,+ format!("Font family not found: {e}"),+ )+ })?;let is_italic = style.contains("Italic");let weight_str = style.replace(" Italic", "");@@ -108,17 +142,151 @@ fn load_system_font_blocking(family: String, style: String) -> Result<Vec<u8>, S}}- Err(format!("Font face not found: {family} {style}"))+ Err(FontLoadError::new(+ FontLoadErrorCode::NotFound,+ format!("Font face not found: {family} {style}"),+ ))}#[tauri::command]pub async fn load_system_font(family: String,style: String,-) -> Result<tauri::ipc::Response, String> {+) -> Result<tauri::ipc::Response, FontLoadError> {let data =tauri::async_runtime::spawn_blocking(move || load_system_font_blocking(family, style)).await- .map_err(|e| format!("Font load task failed: {e}"))??;+ .map_err(|e| {+ FontLoadError::new(+ FontLoadErrorCode::Failed,+ format!("Font load task failed: {e}"),+ )+ })??;Ok(tauri::ipc::Response::new(data))}++const TTC_TAG: &[u8; 4] = b"ttcf";+const OUTLINE_TABLES: [&[u8; 4]; 3] = [b"glyf", b"CFF ", b"CFF2"];++fn read_array<const N: usize>(reader: &mut impl Read) -> Option<[u8; N]> {+ let mut bytes = [0; N];+ reader.read_exact(&mut bytes).ok()?;+ Some(bytes)+}++/// 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.+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 {+ let count = u32::from_be_bytes(header[8..12].try_into().ok()?);+ (0..count)+ .map(|_| read_array::<4>(reader).map(|offset| u32::from_be_bytes(offset) as u64))+ .collect::<Option<Vec<_>>>()?+ } else {+ vec![0]+ };+ for offset in face_offsets {+ reader.seek(SeekFrom::Start(offset + 4)).ok()?;+ let num_tables = u16::from_be_bytes(read_array(reader)?);+ reader.seek(SeekFrom::Current(6)).ok()?;+ let mut tags = Vec::with_capacity(num_tables as usize);+ for _ in 0..num_tables {+ let record: [u8; 16] = read_array(reader)?;+ tags.push([record[0], record[1], record[2], record[3]]);+ }+ let drawable = tags.iter().any(|tag| OUTLINE_TABLES.contains(&tag));+ if drawable || !tags.contains(b"hvgl") {+ return Some(false);+ }+ }+ Some(true)+}++#[cfg(target_os = "macos")]+mod macos {+ use core_foundation::array::CFArray;+ use core_foundation::base::{CFType, TCFType};+ use core_foundation::dictionary::CFDictionary;+ use core_foundation::string::CFString;+ use core_text::{font_collection, font_descriptor};+ use std::collections::HashSet;+ use std::fs::File;++ pub fn family_has_only_unsupported_outlines(family: &str) -> bool {+ let attributes: CFDictionary<CFString, CFType> = CFDictionary::from_CFType_pairs(&[(+ CFString::new("NSFontFamilyAttribute"),+ CFString::new(family).as_CFType(),+ )]);+ let descriptor = font_descriptor::new_from_attributes(&attributes);+ let collection =+ font_collection::new_from_descriptors(&CFArray::from_CFTypes(&[descriptor]));+ let Some(descriptors) = collection.get_descriptors() else {+ return false;+ };+ let paths: HashSet<_> = descriptors.iter().filter_map(|d| d.font_path()).collect();+ !paths.is_empty()+ && paths.iter().all(|path| {+ File::open(path)+ .ok()+ .and_then(|mut file| super::has_only_unsupported_outlines(&mut file))+ .unwrap_or(false)+ })+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use std::io::Cursor;++ fn face(tags: &[&[u8; 4]]) -> Vec<u8> {+ let mut data = 0x0001_0000u32.to_be_bytes().to_vec();+ data.extend((tags.len() as u16).to_be_bytes());+ data.extend([0; 6]);+ for tag in tags {+ data.extend(*tag);+ data.extend([0; 12]);+ }+ data+ }++ fn collection(faces: &[Vec<u8>]) -> Vec<u8> {+ let mut data = TTC_TAG.to_vec();+ data.extend(0x0001_0000u32.to_be_bytes());+ data.extend((faces.len() as u32).to_be_bytes());+ let mut offset = 12 + faces.len() * 4;+ for face in faces {+ data.extend((offset as u32).to_be_bytes());+ offset += face.len();+ }+ faces.iter().for_each(|face| data.extend(face));+ data+ }++ fn check(data: Vec<u8>) -> Option<bool> {+ has_only_unsupported_outlines(&mut Cursor::new(data))+ }++ #[test]+ fn detects_collections_with_only_hvgl_outlines() {+ let hvgl = face(&[b"cmap", b"fvar", b"hvgl", b"name"]);+ assert_eq!(check(collection(&[hvgl.clone(), hvgl])), Some(true));+ }++ #[test]+ fn accepts_fonts_with_drawable_outlines() {+ assert_eq!(check(face(&[b"cmap", b"glyf", b"loca"])), Some(false));+ assert_eq!(check(face(&[b"CFF ", b"cmap"])), Some(false));+ let mixed = collection(&[face(&[b"hvgl"]), face(&[b"CFF2"])]);+ assert_eq!(check(mixed), Some(false));+ }++ #[test]+ fn ignores_truncated_data() {+ assert_eq!(check(vec![0; 6]), None);+ let mut truncated = face(&[b"hvgl", b"cmap"]);+ truncated.truncate(20);+ assert_eq!(check(truncated), None);+ }+}diff --git a/packages/core/src/canvas/text/index.ts b/packages/core/src/canvas/text/index.tsindex a21635793..7319b049e 100644--- a/packages/core/src/canvas/text/index.ts+++ b/packages/core/src/canvas/text/index.ts@@ -203,9 +203,13 @@ function canObserveGlyphCoverage(r: FontReadinessRenderer): r is TextRenderer {export function nodeFontReadiness(r: FontReadinessRenderer, node: SceneNode): NodeFontReadiness {if (node.type !== 'TEXT') return 'ready'const faces = requiredFacesReadiness(r, node)- if (faces !== 'ready') return faces- if (!node.text || !canObserveGlyphCoverage(r)) return 'ready'- return observedGlyphReadiness(r, node)+ if (faces === 'pending' || faces === 'exhausted') return faces+ if (!node.text || !canObserveGlyphCoverage(r)) return faces+ const glyphs = observedGlyphReadiness(r, node)+ // Substituted text still needs script fallbacks (for example CJK) for glyphs the substitute+ // lacks, but stays visible when none can be found.+ if (faces === 'substituted') return glyphs === 'pending' ? 'pending' : 'substituted'+ return glyphs}export function isNodeFontLoaded(r: FontReadinessRenderer, node: SceneNode): boolean {diff --git a/packages/core/src/text/font/sources.ts b/packages/core/src/text/font/sources.tsindex f3bd53bca..d9c1ff62d 100644--- a/packages/core/src/text/font/sources.ts+++ b/packages/core/src/text/font/sources.ts@@ -22,3 +22,16 @@ export interface DownloadedFontCache {}export type HostFontLoader = (family: string, style: string) => Promise<ArrayBuffer | null>++/** Why an installed face could not be loaded, when the host can tell. */+export type FontUnavailableReason = 'unsupported-format'++/** Thrown by a {@link HostFontLoader} for an installed face whose outlines cannot be drawn. */+export class UnsupportedFontFormatError extends Error {+ readonly reason: FontUnavailableReason = 'unsupported-format'++ constructor(family: string, style: string) {+ super(`Font outlines are in an unsupported format: ${family} ${style}`)+ this.name = 'UnsupportedFontFormatError'+ }+}diff --git a/packages/core/src/text/font/status.ts b/packages/core/src/text/font/status.tsindex da365d5d1..276dd54b4 100644--- a/packages/core/src/text/font/status.ts+++ b/packages/core/src/text/font/status.ts@@ -1,7 +1,7 @@import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'import { DEFAULT_FONT_FAMILY } from '#core/constants'-import type { FontLoadedSource } from '#core/text/font/sources'+import type { FontLoadedSource, FontUnavailableReason } from '#core/text/font/sources'import { fontManager, type FontManager } from '#core/text/fonts'import { collectNodeFontFaces } from '#core/text/requirements'@@ -13,6 +13,8 @@ export interface DocumentFontFaceStatus {status: FontFaceStatussource: FontLoadedSource | nullsubstituteFamily: string | null+ /** Why the requested face could not be loaded, when the host reported a reason. */+ reason: FontUnavailableReason | nullnodeIds: string[]nodeNames: string[]}@@ -68,6 +70,7 @@ function faceStatus(use: MutableFontFaceUse, manager: FontManager): DocumentFontstatus: 'available',source: exactSource,substituteFamily: null,+ reason: null,nodeIds: [...use.nodeIds],nodeNames: [...use.nodeNames]}@@ -80,6 +83,7 @@ function faceStatus(use: MutableFontFaceUse, manager: FontManager): DocumentFontstatus: 'substituted',source: null,substituteFamily: use.family,+ reason: manager.unavailableReason(use.family, use.style),nodeIds: [...use.nodeIds],nodeNames: [...use.nodeNames]}@@ -92,6 +96,7 @@ function faceStatus(use: MutableFontFaceUse, manager: FontManager): DocumentFontstatus: defaultSource ? 'substituted' : 'unresolved',source: null,substituteFamily: defaultSource ? DEFAULT_FONT_FAMILY : null,+ reason: manager.unavailableReason(use.family, use.style),nodeIds: [...use.nodeIds],nodeNames: [...use.nodeNames]}diff --git a/packages/core/src/text/fonts.ts b/packages/core/src/text/fonts.tsindex 91c30518b..09b5fb185 100644--- a/packages/core/src/text/fonts.ts+++ b/packages/core/src/text/fonts.ts@@ -17,11 +17,13 @@ export * from '#core/text/font/sources'export * from '#core/text/font/style'import { fontFallbackEntry } from '#core/text/fallbacks'import type { FontFallbackScript } from '#core/text/fallbacks'+import { UnsupportedFontFormatError } from '#core/text/font/sources'import type {DownloadedFontCache,FontFamilyOption,FontInfo,FontLoadedSource,+ FontUnavailableReason,HostFontLoader,LocalFontAccessState} from '#core/text/font/sources'@@ -43,6 +45,7 @@ const BUNDLED_FONTS: Record<string, string> = {export class FontManager {private loadedFamilies = new Map<string, ArrayBuffer>()private loadedFamilySources = new Map<string, FontLoadedSource>()+ private unavailableFaces = new Map<string, FontUnavailableReason>()private supplementalFamilyData = new Map<string, ArrayBuffer[]>()private remoteCoverage = new Map<string, Set<string>>()private blockedNodeIds = new Set<string>()@@ -342,6 +345,11 @@ export class FontManager {return this.loadedFamilySources.get(`${family}|${style}`) ?? null}+ /** Why the host could not load an installed face, when it reported a reason. */+ unavailableReason(family: string, style: string): FontUnavailableReason | null {+ return this.unavailableFaces.get(`${family}|${style}`) ?? null+ }+isLoaded(family: string): boolean {return [...this.loadedFamilies.keys()].some((k) => k.startsWith(`${family}|`))}@@ -491,9 +499,16 @@ export class FontManager {private async loadHostFont(family: string, style: string): Promise<ArrayBuffer | null> {if (!this.hostFontLoader) return null+ const key = `${family}|${style}`try {- return await this.hostFontLoader(family, style)+ const data = await this.hostFontLoader(family, style)+ if (data) this.unavailableFaces.delete(key)+ return data} catch (e) {+ if (e instanceof UnsupportedFontFormatError) {+ this.unavailableFaces.set(key, e.reason)+ return null+ }console.warn(`Host fallback font load failed for "${family}" ${style}:`, e)return null}diff --git a/packages/core/src/text/resolver/resolver.ts b/packages/core/src/text/resolver/resolver.tsindex 9ea174ca8..9c397bad8 100644--- a/packages/core/src/text/resolver/resolver.ts+++ b/packages/core/src/text/resolver/resolver.ts@@ -157,6 +157,7 @@ export class FontResolver {error})}+ this.notify('progressed', entry.snapshot)}return this.settle(entry, { key: entry.demand.key, state: 'exhausted' })diff --git a/packages/core/src/text/resolver/types.ts b/packages/core/src/text/resolver/types.tsindex 07acf0948..e4b032125 100644--- a/packages/core/src/text/resolver/types.ts+++ b/packages/core/src/text/resolver/types.ts@@ -1,6 +1,7 @@export type FontResolutionState = 'idle' | 'loading' | 'loaded' | 'failed' | 'exhausted'-export type FontResolutionEvent = 'started' | 'settled' | 'reset'+/** `progressed` follows each candidate that did not load while later candidates are still tried. */+export type FontResolutionEvent = 'started' | 'progressed' | 'settled' | 'reset'export type FontResolutionListener = (event: FontResolutionEvent,diff --git a/packages/core/src/tools/read/fonts.ts b/packages/core/src/tools/read/fonts.tsindex 1014d1aa1..fa17baafa 100644--- a/packages/core/src/tools/read/fonts.ts+++ b/packages/core/src/tools/read/fonts.ts@@ -7,7 +7,8 @@ export const getFontStatus = defineTool({name: 'get_font_status',description:'Report whether fonts used on the current page are faithfully available. Returns requested ' +- 'faces, their loaded source, active substitutions, and affected nodes.',+ 'faces, their loaded source, active substitutions, why an installed face could not be ' ++ 'loaded, and affected nodes.',execution: { kind: 'sync', mutation: 'none' },exposure: { webmcp: false },input: v.object({}),diff --git a/packages/docs/programmable/mcp-server.md b/packages/docs/programmable/mcp-server.mdindex 305317425..1fb6d017e 100644--- a/packages/docs/programmable/mcp-server.md+++ b/packages/docs/programmable/mcp-server.md@@ -192,7 +192,7 @@ OpenPencil currently registers 100+ shared design tools, plus MCP-only document| `list_collections` | List variable collections || `list_fonts` | List fonts used in the current page || `list_available_fonts` | List font families the current host can render |-| `get_font_status` | Report requested faces, loaded sources, active substitutions, and affected nodes |+| `get_font_status` | Report requested faces, loaded sources, active substitutions, why an installed face could not be loaded, and affected nodes || `page_bounds` | Get bounding box of all objects on the current page || `node_bounds` | Get bounding box of a node || `node_ancestors` | Get ancestor chain of a node |diff --git a/packages/vue/src/i18n/locales/de/fonts.json b/packages/vue/src/i18n/locales/de/fonts.jsonindex 553585663..7743e76c7 100644--- a/packages/vue/src/i18n/locales/de/fonts.json+++ b/packages/vue/src/i18n/locales/de/fonts.json@@ -27,6 +27,8 @@"expandIssues": "Schriftprobleme anzeigen","collapseIssues": "Schriftprobleme ausblenden","noSubstitute": "kein Ersatz verfügbar",+ "unsupportedFormatShort": "nicht unterstütztes Format",+ "unsupportedFormat": "Installiert, aber in einem Format, das OpenPencil noch nicht darstellen kann","settingsDesktopDescription": "Auf Systemschriften, Online-Anbieter, Fallback-Pakete und zwischengespeicherte Downloads zugreifen.","settingsBrowserDescription": "Browserzugriff auf lokale Schriften erlauben und Online-Schriftanbieter verwalten.","providerEnabled": "{provider} aktiviert.",diff --git a/packages/vue/src/i18n/locales/es/fonts.json b/packages/vue/src/i18n/locales/es/fonts.jsonindex ae8ce3e28..f057b7d87 100644--- a/packages/vue/src/i18n/locales/es/fonts.json+++ b/packages/vue/src/i18n/locales/es/fonts.json@@ -27,6 +27,8 @@"expandIssues": "Mostrar problemas de fuentes","collapseIssues": "Ocultar problemas de fuentes","noSubstitute": "sin sustituto disponible",+ "unsupportedFormatShort": "formato no compatible",+ "unsupportedFormat": "Instalada, pero en un formato que OpenPencil aún no puede dibujar","settingsDesktopDescription": "Accede a fuentes del sistema, proveedores en línea, paquetes de respaldo y descargas en caché.","settingsBrowserDescription": "Permite al navegador acceder a fuentes locales y gestiona proveedores de fuentes en línea.","providerEnabled": "{provider} activado.",diff --git a/packages/vue/src/i18n/locales/fr/fonts.json b/packages/vue/src/i18n/locales/fr/fonts.jsonindex 54b8f8219..d3e513102 100644--- a/packages/vue/src/i18n/locales/fr/fonts.json+++ b/packages/vue/src/i18n/locales/fr/fonts.json@@ -27,6 +27,8 @@"expandIssues": "Afficher les problèmes de police","collapseIssues": "Masquer les problèmes de police","noSubstitute": "aucun remplacement disponible",+ "unsupportedFormatShort": "format non pris en charge",+ "unsupportedFormat": "Installée, mais dans un format qu’OpenPencil ne peut pas encore afficher","settingsDesktopDescription": "Accédez aux polices système, aux fournisseurs en ligne, aux packs de secours et aux téléchargements en cache.","settingsBrowserDescription": "Autorisez l’accès du navigateur aux polices locales et gérez les fournisseurs de polices en ligne.","providerEnabled": "{provider} activé.",diff --git a/packages/vue/src/i18n/locales/it/fonts.json b/packages/vue/src/i18n/locales/it/fonts.jsonindex 7b82658bd..f2e6ed073 100644--- a/packages/vue/src/i18n/locales/it/fonts.json+++ b/packages/vue/src/i18n/locales/it/fonts.json@@ -27,6 +27,8 @@"expandIssues": "Mostra problemi dei font","collapseIssues": "Nascondi problemi dei font","noSubstitute": "nessun sostituto disponibile",+ "unsupportedFormatShort": "formato non supportato",+ "unsupportedFormat": "Installato, ma in un formato che OpenPencil non può ancora disegnare","settingsDesktopDescription": "Accedi ai font di sistema, ai provider online, ai pacchetti di fallback e ai download nella cache.","settingsBrowserDescription": "Consenti al browser di accedere ai font locali e gestisci i provider di font online.","providerEnabled": "{provider} abilitato.",diff --git a/packages/vue/src/i18n/locales/ja/fonts.json b/packages/vue/src/i18n/locales/ja/fonts.jsonindex 7ee1ab5ac..e20abcdf5 100644--- a/packages/vue/src/i18n/locales/ja/fonts.json+++ b/packages/vue/src/i18n/locales/ja/fonts.json@@ -27,6 +27,8 @@"expandIssues": "フォントの問題を表示","collapseIssues": "フォントの問題を隠す","noSubstitute": "代替フォントなし",+ "unsupportedFormatShort": "未対応の形式",+ "unsupportedFormat": "インストール済みですが、OpenPencil がまだ描画できない形式です","settingsDesktopDescription": "システムフォント、オンラインプロバイダー、フォールバックパック、キャッシュ済みダウンロードにアクセスします。","settingsBrowserDescription": "ローカルフォントへのブラウザーアクセスを許可し、オンラインフォントプロバイダーを管理します。","providerEnabled": "{provider} を有効にしました。",diff --git a/packages/vue/src/i18n/locales/pl/fonts.json b/packages/vue/src/i18n/locales/pl/fonts.jsonindex faccfb048..a9161ba9c 100644--- a/packages/vue/src/i18n/locales/pl/fonts.json+++ b/packages/vue/src/i18n/locales/pl/fonts.json@@ -27,6 +27,8 @@"expandIssues": "Pokaż problemy z czcionkami","collapseIssues": "Ukryj problemy z czcionkami","noSubstitute": "brak dostępnego zamiennika",+ "unsupportedFormatShort": "nieobsługiwany format",+ "unsupportedFormat": "Zainstalowany, ale w formacie, którego OpenPencil jeszcze nie obsługuje","settingsDesktopDescription": "Uzyskaj dostęp do czcionek systemowych, dostawców online, pakietów zapasowych i pobranych plików w pamięci podręcznej.","settingsBrowserDescription": "Zezwól przeglądarce na dostęp do lokalnych czcionek i zarządzaj dostawcami czcionek online.","providerEnabled": "Włączono {provider}.",diff --git a/packages/vue/src/i18n/locales/ru/fonts.json b/packages/vue/src/i18n/locales/ru/fonts.jsonindex 08eba7cf6..40225170f 100644--- a/packages/vue/src/i18n/locales/ru/fonts.json+++ b/packages/vue/src/i18n/locales/ru/fonts.json@@ -27,6 +27,8 @@"expandIssues": "Показать проблемы со шрифтами","collapseIssues": "Скрыть проблемы со шрифтами","noSubstitute": "замена недоступна",+ "unsupportedFormatShort": "неподдерживаемый формат",+ "unsupportedFormat": "Установлен, но в формате, который OpenPencil пока не умеет отображать","settingsDesktopDescription": "Доступ к системным шрифтам, онлайн-провайдерам, резервным наборам и кэшу загрузок.","settingsBrowserDescription": "Разрешите браузеру доступ к локальным шрифтам и управляйте онлайн-провайдерами шрифтов.","providerEnabled": "{provider} включён.",diff --git a/packages/vue/src/i18n/locales/zh-cn/fonts.json b/packages/vue/src/i18n/locales/zh-cn/fonts.jsonindex 7238622f1..af5fa0010 100644--- a/packages/vue/src/i18n/locales/zh-cn/fonts.json+++ b/packages/vue/src/i18n/locales/zh-cn/fonts.json@@ -27,6 +27,8 @@"expandIssues": "显示字体问题","collapseIssues": "隐藏字体问题","noSubstitute": "没有可用的替代字体",+ "unsupportedFormatShort": "不支持的格式",+ "unsupportedFormat": "已安装,但 OpenPencil 暂时无法绘制这种字体格式","settingsDesktopDescription": "访问系统字体、在线提供商、后备字体包和缓存下载。","settingsBrowserDescription": "允许浏览器访问本地字体,并管理在线字体提供商。","providerEnabled": "已启用 {provider}。",diff --git a/packages/vue/src/i18n/messages/fonts.ts b/packages/vue/src/i18n/messages/fonts.tsindex 5cd485429..654a47aa3 100644--- a/packages/vue/src/i18n/messages/fonts.ts+++ b/packages/vue/src/i18n/messages/fonts.ts@@ -12,6 +12,8 @@ export const fontsMessageDefaults = {expandIssues: 'Show font issues',collapseIssues: 'Hide font issues',noSubstitute: 'no substitute available',+ unsupportedFormatShort: 'unsupported format',+ unsupportedFormat: 'Installed, but in a format OpenPencil can’t draw yet',affectedLayer: '1 affected layer',affectedLayerCount: params('{count} affected layers'),settingsDesktopDescription:diff --git a/src/app/editor/fonts/index.ts b/src/app/editor/fonts/index.tsindex 1c7382146..302bb91cd 100644--- a/src/app/editor/fonts/index.ts+++ b/src/app/editor/fonts/index.ts@@ -9,7 +9,8 @@ import {missingGraphFontScripts,type FontFamilyOption,type LocalFontAccessState,- type WebFontProviderId+ type WebFontProviderId,+ UnsupportedFontFormatError} from '@open-pencil/core/text'import type { SceneGraph } from '@open-pencil/scene-graph'@@ -197,6 +198,8 @@ function clearTextPictures(graph: SceneGraph, nodeIds: string[]): void {for (const id of nodeIds) clear(id)}+type NativeFontLoadError = { code?: 'not-found' | 'unsupported-format' | 'failed' }+async function loadSystemFont(family: string, style = 'Regular'): Promise<ArrayBuffer | null> {if (!isTauri()) return nulltry {@@ -204,7 +207,10 @@ async function loadSystemFont(family: string, style = 'Regular'): Promise<ArrayBconst data = await invoke<ArrayBuffer>('load_system_font', { family, style })if (data.byteLength === 0) return nullreturn data- } catch {+ } catch (error) {+ if ((error as NativeFontLoadError | null)?.code === 'unsupported-format') {+ throw new UnsupportedFontFormatError(family, style)+ }return null}}diff --git a/src/components/font-status/FontStatusBanner.vue b/src/components/font-status/FontStatusBanner.vueindex 22a5fbcc8..669331b69 100644--- a/src/components/font-status/FontStatusBanner.vue+++ b/src/components/font-status/FontStatusBanner.vue@@ -4,6 +4,7 @@ import { computed, ref } from 'vue'import { useI18n } from '@open-pencil/vue'import { useDocumentFontStatus } from '@/app/editor/fonts/status'+import Tip from '@/components/ui/overlay/Tip.vue'const { fonts } = useI18n()const expanded = ref(false)@@ -66,6 +67,9 @@ const issues = computed(() => status.value.issues)<strong>{{ issue.family }} {{ issue.style }}</strong><template v-if="issue.substituteFamily"> → {{ issue.substituteFamily }} </template><template v-else>— {{ fonts.noSubstitute }}</template>+ <Tip v-if="issue.reason === 'unsupported-format'" :label="fonts.unsupportedFormat">+ <span class="ms-1 opacity-75">· {{ fonts.unsupportedFormatShort }}</span>+ </Tip></span><span class="shrink-0 text-[10px] opacity-75">{{diff --git a/tests/e2e/fonts/cjk-rendering-visual.spec.ts b/tests/e2e/fonts/cjk-rendering-visual.spec.tsindex 5d28beef1..1dc06794e 100644--- a/tests/e2e/fonts/cjk-rendering-visual.spec.ts+++ b/tests/e2e/fonts/cjk-rendering-visual.spec.ts@@ -361,3 +361,83 @@ test('typed and tool-created text repaint with the same resolved fallbacks', asyexpect(state).toEqual({ textsMatch: true, toolReady: true, typedReady: true, unblocked: true })expect(Buffer.from(image)).toMatchSnapshot('interactive-font-fallback-resolved.png')})++test('substituted fonts still request fallbacks for CJK text', async ({ page }) => {+ await openEditor(page)++ const result = await page.evaluate(async () => {+ const store = window.openPencil?.getStore?.()+ if (!store?.renderer) throw new Error('OpenPencil renderer not initialized')+ const fontModuleURL = performance+ .getEntriesByType('resource')+ .map((entry) => entry.name)+ .find((url) => url.includes('/packages/core/src/text/fonts.ts'))+ if (!fontModuleURL) throw new Error('Active font manager module not found')+ const { fontManager } = (await import(/* @vite-ignore */ fontModuleURL)) as {+ fontManager: FontManager+ }+ const cjk = await fetch('/tests/fixtures/fonts/NotoSansCJK-Test.otf').then((response) =>+ response.arrayBuffer()+ )+ // Supply the fixture only when the renderer requests a CJK fallback for the substituted text.+ const requestedScripts: string[] = []+ fontManager.ensureFallbackPack = async (scripts = ['cjk', 'arabic']) => {+ requestedScripts.push(...scripts)+ fontManager.markLoaded('Noto Sans CJK SC', 'Regular', cjk, 'fallback')+ fontManager.setCJKFallbackFamily('Noto Sans CJK SC')+ return { cjk: ['Noto Sans CJK SC'] }+ }++ const node = store.graph.createNode('TEXT', store.state.currentPageId, {+ name: 'Substituted CJK text',+ x: 40,+ y: 40,+ width: 520,+ height: 48,+ text: 'Buttons 你好世界',+ textLanguage: 'zh-Hans',+ fontFamily: 'Unavailable Visual Test Face',+ fontSize: 32,+ textAutoResize: 'NONE',+ fills: [+ { type: 'SOLID', color: { r: 0.04, g: 0.06, b: 0.12, a: 1 }, visible: true, opacity: 1 }+ ]+ })++ const deadline = performance.now() + 10_000+ while (performance.now() < deadline) {+ store.renderer.invalidateAllPictures()+ store.requestRender()+ store.renderer.renderFromEditorState(+ store.state,+ store.graph,+ store.textEditor,+ window.innerWidth,+ window.innerHeight,+ false,+ 'full'+ )+ if (+ store.renderer.nodeFontReadiness(node) === 'substituted' &&+ fontManager.getCJKFallbackFamilies().includes('Noto Sans CJK SC')+ ) {+ break+ }+ await new Promise<void>((resolve) => {+ setTimeout(resolve, 50)+ })+ }++ const image = await store.renderExportImage([node.id], 2, 'PNG')+ if (!image) throw new Error('Export failed')+ return {+ image: Array.from(image),+ readiness: store.renderer.nodeFontReadiness(node),+ requestedCJK: requestedScripts.some((script) => script.startsWith('cjk'))+ }+ })++ const { image, ...state } = result+ expect(state).toEqual({ readiness: 'substituted', requestedCJK: true })+ expect(Buffer.from(image)).toMatchSnapshot('substituted-font-cjk-fallback.png')+})diff --git a/tests/e2e/fonts/cjk-rendering-visual.spec.ts-snapshots/substituted-font-cjk-fallback-openpencil-darwin.png b/tests/e2e/fonts/cjk-rendering-visual.spec.ts-snapshots/substituted-font-cjk-fallback-openpencil-darwin.pngnew file mode 100644index 000000000..77fb23aa2Binary files /dev/null and b/tests/e2e/fonts/cjk-rendering-visual.spec.ts-snapshots/substituted-font-cjk-fallback-openpencil-darwin.png differdiff --git a/tests/engine/render/canvas/text.test.ts b/tests/engine/render/canvas/text.test.tsindex 454c12400..a6591e2fc 100644--- a/tests/engine/render/canvas/text.test.ts+++ b/tests/engine/render/canvas/text.test.ts@@ -1,6 +1,6 @@/* eslint-disable max-lines -- text rendering scenarios share CanvasKit setup and fixtures */-import { describe, test, expect, mock } from 'bun:test'+import { describe, test, expect, mock, spyOn } from 'bun:test'import {detectTextDirection,@@ -14,7 +14,7 @@ import { createDefaultSourceMetadata } from '@open-pencil/scene-graph/node-defauimport { initCanvasKit } from '#cli/headless'import type { SkiaRenderer } from '#core/canvas/renderer'import { renderText, textVerticalOffset } from '#core/canvas/scene'-import { buildParagraph, isNodeFontLoaded } from '#core/canvas/text'+import { buildParagraph, isNodeFontLoaded, nodeFontReadiness } from '#core/canvas/text'import { transformTextCase } from '#core/text/case'import { fontManager } from '#core/text/fonts'import { fontFaceDemand, fontResolver, missingGlyphCharacters } from '#core/text/resolver'@@ -390,6 +390,38 @@ describe('renderText headless visual', () => {}})+ test('requests a CJK fallback for text whose face is substituted', async () => {+ const ck = await initCanvasKit()+ const fontProvider = ck.TypefaceFontProvider.Make()+ fontManager.attachProvider(ck, fontProvider)+ const interData = await Bun.file('public/Inter-Regular.ttf').arrayBuffer()+ fontManager.markLoaded('Inter', 'Regular', interData)+ const manager = fontManager as typeof fontManager & { cjkFallbackFamilies: string[] }+ const originalFallbacks = [...manager.cjkFallbackFamilies]+ manager.cjkFallbackFamilies = []+ const fallbackPack = spyOn(fontManager, 'ensureFallbackPack').mockResolvedValue({})+ const face = fontFaceDemand('Undrawable Sans', 'Regular')+ fontResolver.exhaust(face)+ const surface = expectDefined(ck.MakeSurface(200, 50), 'CanvasKit surface')++ try {+ const renderer = new SkiaRendererClass(ck, surface)+ renderer.fontsLoaded = true+ renderer.fontProvider = fontProvider+ const node = textNode({ text: '按钮', fontFamily: 'Undrawable Sans', fontWeight: 400 })++ expect(nodeFontReadiness(renderer, node)).toBe('pending')+ await Promise.resolve()+ expect(fallbackPack).toHaveBeenCalled()+ expect(fallbackPack.mock.calls[0]?.[0]?.some((script) => script.startsWith('cjk'))).toBe(true)+ } finally {+ fallbackPack.mockRestore()+ fontResolver.reset(face)+ manager.cjkFallbackFamilies = originalFallbacks+ surface.delete()+ }+ })+test('does not require fallback families when the primary font covers CJK glyphs', async () => {const notoPath = repoPath('tests/fixtures/fonts/NotoSansSC-Regular.ttf')const notoData = await Bun.file(notoPath).arrayBuffer()diff --git a/tests/engine/tauri/fonts.test.ts b/tests/engine/tauri/fonts.test.tsindex a2837675d..9bf3c1fa5 100644--- a/tests/engine/tauri/fonts.test.ts+++ b/tests/engine/tauri/fonts.test.ts@@ -39,6 +39,18 @@ describe('Tauri font helpers', () => {expect(fontManager.isLoaded('System UI', 'Bold Italic')).toBe(true)})+ test('records installed faces whose outlines cannot be drawn', async () => {+ await mockTauriIPC((cmd) => {+ expect(cmd).toBe('load_system_font')+ throw { code: 'unsupported-format', message: 'Font outlines are in an unsupported format' }+ })+ await import('@/app/editor/fonts')++ await expect(fontManager.loadLocalFont('Undrawable Sans', 'Regular')).resolves.toBeNull()+ expect(fontManager.unavailableReason('Undrawable Sans', 'Regular')).toBe('unsupported-format')+ expect(fontManager.unavailableReason('Undrawable Sans', 'Bold')).toBeNull()+ })+test('falls back to font manager loading when the system font command fails', async () => {await mockTauriIPC((cmd) => {expect(cmd).toBe('load_system_font')diff --git a/tests/engine/text/fonts/status.test.ts b/tests/engine/text/fonts/status.test.tsindex f020c39ca..62852ae5a 100644--- a/tests/engine/text/fonts/status.test.ts+++ b/tests/engine/text/fonts/status.test.ts@@ -1,6 +1,7 @@import { describe, expect, test } from 'bun:test'import { FontManager, SceneGraph, documentFontStatus } from '@open-pencil/core'+import { UnsupportedFontFormatError } from '@open-pencil/core/text'function pageId(graph: SceneGraph): string {return graph.getPages()[0].id@@ -27,6 +28,7 @@ describe('documentFontStatus', () => {status: 'available',source: 'bundled',substituteFamily: null,+ reason: null,nodeIds: [expect.any(String)],nodeNames: ['Title']}@@ -56,6 +58,7 @@ describe('documentFontStatus', () => {status: 'substituted',source: null,substituteFamily: 'Inter',+ reason: null,nodeIds: [node.id],nodeNames: ['Unavailable label']}@@ -89,6 +92,7 @@ describe('documentFontStatus', () => {status: 'substituted',source: null,substituteFamily: 'Example Sans',+ reason: null,nodeIds: [node.id],nodeNames: ['Mixed text']},@@ -98,9 +102,49 @@ describe('documentFontStatus', () => {status: 'unresolved',source: null,substituteFamily: null,+ reason: null,nodeIds: [node.id],nodeNames: ['Mixed text']}])})++ test('reports why the host could not load an installed face until it loads', async () => {+ const graph = new SceneGraph()+ const manager = new FontManager()+ manager.markLoaded('Inter', 'Regular', new ArrayBuffer(8), 'bundled')+ let host: 'unsupported' | 'failed' | 'drawable' = 'unsupported'+ manager.setHostFontLoader(async (family, style) => {+ if (host === 'unsupported') throw new UnsupportedFontFormatError(family, style)+ return host === 'drawable' ? new ArrayBuffer(8) : null+ })+ const node = graph.createNode('TEXT', pageId(graph), {+ name: 'Chinese label',+ text: '按钮',+ fontFamily: 'PingFang SC',+ fontWeight: 400+ })++ expect(await manager.loadLocalFont('PingFang SC', 'Regular')).toBeNull()+ expect(documentFontStatus(graph, pageId(graph), manager).issues).toEqual([+ {+ family: 'PingFang SC',+ style: 'Regular',+ status: 'substituted',+ source: null,+ substituteFamily: 'Inter',+ reason: 'unsupported-format',+ nodeIds: [node.id],+ nodeNames: ['Chinese label']+ }+ ])++ host = 'failed'+ expect(await manager.loadLocalFont('PingFang SC', 'Regular')).toBeNull()+ expect(manager.unavailableReason('PingFang SC', 'Regular')).toBe('unsupported-format')++ host = 'drawable'+ expect(await manager.loadLocalFont('PingFang SC', 'Regular')).not.toBeNull()+ expect(documentFontStatus(graph, pageId(graph), manager).faithful).toBe(true)+ })})diff --git a/tests/engine/text/resolver.test.ts b/tests/engine/text/resolver.test.tsindex e6c92b625..008deb4cb 100644--- a/tests/engine/text/resolver.test.ts+++ b/tests/engine/text/resolver.test.ts@@ -114,6 +114,23 @@ describe('FontResolver', () => {expect(events).toEqual(['started:loading', 'settled:loaded', 'reset:idle'])})+ test('notifies subscribers after each candidate that does not load', async () => {+ const resolver = new FontResolver(async (item) => item.source === 'cache')+ const events: string[] = []+ resolver.subscribe((event, snapshot) => {+ events.push(`${event}:${snapshot.state}:${snapshot.candidate?.source ?? ''}`)+ })++ await resolver.demand(faceDemand())++ expect(events).toEqual([+ 'started:loading:',+ 'progressed:loading:registered',+ 'progressed:loading:local',+ 'settled:loaded:cache'+ ])+ })+test('exhausts after every candidate is unavailable', async () => {const resolver = new FontResolver(async () => false)const demand = faceDemand()diff --git a/tools/i18n/mixed-script-baseline.txt b/tools/i18n/mixed-script-baseline.txtindex 4bd4899c9..67362e475 100644--- a/tools/i18n/mixed-script-baseline.txt+++ b/tools/i18n/mixed-script-baseline.txt@@ -88,6 +88,7 @@ ja:files.importFailedja:files.importHTMLCSSja:files.importHTMLCSSDescriptionja:fonts.downloadFallbackPacksDescription+ja:fonts.unsupportedFormatja:media.getPexelsAPIKeyja:media.getUnsplashAccessKeyja:media.pexelsAPIKey@@ -222,6 +223,7 @@ zh-cn:files.importFailedzh-cn:files.importHTMLCSSzh-cn:files.importHTMLCSSDescriptionzh-cn:fonts.downloadFallbackPacksDescription+zh-cn:fonts.unsupportedFormatzh-cn:media.getPexelsAPIKeyzh-cn:media.getUnsplashAccessKeyzh-cn:media.pexelsAPIKey