Open-source Android PDF and document toolkit with PDF tools, Office viewing, XLSX editing, scanning, and image editing. Built with Kotlin and Jetpack Compose.
Rust androiddocument-scannerdocximage-editorjetpack-composekotlinliquid-glassofflineopen-sourcepdfpdf-compressorpdf-editorpdf-mergerpdf-readerpdf-splitterpdf-toolspdf-viewerpptxspreadsheet-editorxlsx
Open PowerPoint presentations, and give Quick Preview Apple's continuous corners
chethan6162ab2f8841d4c
diff --git a/ATTRIBUTION.md b/ATTRIBUTION.mdindex f46972f..2d2143b 100644--- a/ATTRIBUTION.md+++ b/ATTRIBUTION.md@@ -267,10 +267,11 @@ Every asset Artefact's engine includes, bundles or uses to build its published m| `engine/assets/icons/pilcrow.svg` | Lucide icon "pilcrow" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/pilcrow.svg) | UI icon, embedded via engine/crates/ui-egui/src/icon_data.rs || `engine/assets/icons/move-horizontal.svg` | Lucide icon "move-horizontal" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/move-horizontal.svg) | UI icon, embedded via engine/crates/ui-egui/src/icon_data.rs |-## Compiled in through dependencies (5)+## Compiled in through dependencies (6)| Crate | File | Title | Author | Licence | Source | Used for ||---|---|---|---|---|---|---|+| `epaint_default_fonts` 0.37.0 | `fonts/Ubuntu-Light.ttf` | Ubuntu Light | Canonical Ltd. / Dalton Maag | Ubuntu-font-1.0 | https://design.ubuntu.com/font | Presentations: the last-resort face of deckcraft-fonts (engine/vendor/deckcraft-fonts) || `epaint_default_fonts` 0.36.2 | `fonts/Ubuntu-Light.ttf` | Ubuntu Light | Canonical Ltd. / Dalton Maag | Ubuntu-font-1.0 | https://design.ubuntu.com/font | egui fallback fonts (eframe feature default_fonts) || `epaint_default_fonts` 0.36.2 | `fonts/Hack-Regular.ttf` | Hack Regular | Source Foundry Authors (derived from Bitstream Vera / DejaVu) | MIT AND Bitstream-Vera | https://github.com/source-foundry/Hack | egui fallback fonts (eframe feature default_fonts) || `epaint_default_fonts` 0.36.2 | `fonts/NotoEmoji-Regular.ttf` | Noto Emoji (monochrome) | Google Inc. | OFL-1.1 | https://github.com/googlefonts/noto-emoji | egui fallback fonts (eframe feature default_fonts) |diff --git a/HANDOFF.md b/HANDOFF.mdindex e427251..d864bff 100644--- a/HANDOFF.md+++ b/HANDOFF.md@@ -22,7 +22,7 @@ Read this first after a `/clear`. The roadmap is `PLAN.md`.`adb shell cmd package compile -f -m speed-profile com.chethan616.clearpdf.debug` to compile theprofile at once. A debuggable build runs Compose several times slower.-## Office documents (Word in; PowerPoint and Excel next)+## Office documents (Word and PowerPoint in; Excel next)Plan and status: PLAN.md "Office documents". How the Word bridge works:@@ -34,7 +34,14 @@ Plan and status: PLAN.md "Office documents". How the Word bridge works:Source Sans 3 / Source Serif 4 live there). `[patch.crates-io] krilla` = craft-libs `c5a1cbf`(Word's PDF export needs the suite's krilla, and Cargo ignores a dependency's own patches).Upstream draft (not filed, don't file without the owner): `docs/upstream/wordcraft-android.md`.-- **Bridge** (`engine/mobile/src/word.rs`): `MobileSession.open(path)` sniffs the bytes+- **Bridge**: `engine/mobile/src/office.rs` is the shared part: the `OfficeDoc` trait (info, render,+ text layer, links, thumbnail, release_memory), `sniff` (zip part names / CFB streams / `{ tf`),+ `text_glyph` (a glyph box through an `Affine`), ids from `OFFICE_IDS` = 2^40. `word.rs` and+ `slides.rs` implement it; `MobileSession` keeps `office: HashMap<u64, Arc<dyn OfficeDoc>>`.+ Slides: `deckcraft_pptx::import`, `deckcraft_render::render_slide` (tiles via `RenderOpts.offset`+ and `size`, 2 threads), text from `place_slide(..).texts` (runs' glyphs + `cells` chars, through+ `PlacedText.transform`), links from `place_slide(..).links` (URL actions).+- **Word** (`engine/mobile/src/word.rs`): `MobileSession.open(path)` sniffs the bytes(`word_extension`: zip with `word/document.xml`, ODF text, CFB `WordDocument`, `{tf`; an encryptedCFB only when the name says .docx) and opens a `WordDocument` (wordcraft `Session`) under an id@@ -48,8 +55,8 @@ tf`; an encrypted(`session.view.proofing = false`: no spelling squiggles in a reader). `DocumentInfo.kind` tells theapp; `read_only_reason` is set (no editing yet). Errors reuse `MobileError` (NeedsPassword /WrongPassword for protected .docx).-- **Android**: `engine/DocumentTypes.kt` (types, Word extensions, `title`, `mimeOf`);- `OpenDocument.isWord`; `QuickTool.WORD` (Read Aloud only) on the bar, empty More tools, More sheet+- **Android**: `engine/DocumentTypes.kt` (PDF/Word/slides types and extensions, `title`, `mimeOf`);+ `OpenDocument.isOffice` / `isSlides`; `QuickTool.WORD` (Read Aloud only) on the bar, empty More tools, More sheetwithout Edit/Print/comments/signatures/PDF tools; `safeName` keeps Word extensions (the engineneeds .docx for encrypted files); manifest SEND and Quick Preview VIEW filters list the Word types.- Tests: `cargo test -p artefact-mobile` (Word tests write a .docx with wordcraft, open, render,@@ -190,6 +197,12 @@ tf`; an encryptedattached): check them first when it is. Fast APK: `android/app/build/outputs/apk/fast/app-fast.apk`.If gradle complains a backdrop class is "outside the root directory", run `./gradlew :backdrop:clean`.+## Quick Preview corners (2026-11-07)++The card is a `Squircle` (new in `ui/glass/Shapes.kt`: kyant's continuous corners, allowed only for+content clipped inside its own moving layer) with a radius concentric with the screen's corners+(`RoundedCorner` bottom-left radius minus the 10 dp inset, 24..48 dp; 34 dp without it).+## Desk flicker (2026-11-06, fix built, not yet seen on the phone)The owner saw the desk's cards "appear again for a second" after tapping a card. Cause found in@@ -204,5 +217,5 @@ still sees a flash on the Files/Pdf collection cards (a route change, not a docu## Next upSee PLAN.md "Office documents" and "Next". Immediate: when Artefact is in front on the phone,-check Word viewing (Files, Recent, Quick Preview with the sample above) and the desk flicker fix,-then PowerPoint viewing (deckcraft).+check Word and slides viewing (Files, Recent, Quick Preview with the samples), the desk flicker fix+and the squircle Quick Preview card; then slides present mode, then Excel viewing (gridcraft).diff --git a/NOTICE b/NOTICEindex 43689e8..840849a 100644--- a/NOTICE+++ b/NOTICE@@ -17,6 +17,11 @@ network code; engine/vendor/wordcraft-fonts: Android's font folders), keeping thIts bundled faces Source Sans 3 and Source Serif 4 (Adobe, SIL Open Font License 1.1) are inengine/assets/fonts with their licences.+Presentations: the slide reader and renderer of DeckCraft (https://github.com/storytold/deckcraft)+by storytold and the DeckCraft contributors, MIT OR Apache-2.0, pinned by commit; its fonts crate is+vendored with Artefact's Android patch (engine/vendor/deckcraft-fonts). Its last-resort face is+Ubuntu Light (Canonical Ltd. / Dalton Maag, Ubuntu Font Licence 1.0), from epaint_default_fonts.+Liquid glass: the backdrop library from AndroidLiquidGlass by Kyant0(https://github.com/Kyant0/AndroidLiquidGlass), Apache-2.0, adapted. The velocity squash-and-stretchof glass thumbs follows LiquidTracker from AndroidLiquidGlassView by Donny Yalediff --git a/PLAN.md b/PLAN.mdindex 4998ac8..7d29778 100644--- a/PLAN.md+++ b/PLAN.md@@ -128,8 +128,13 @@ all three → editing, one format at a time, each built and run on the phone befcomments/signatures/PDF tools); names keep their Word extension.- Installed on the phone (fast build, 2026-11-06); [ ] seen there: open the sample .docx fromFiles, Recent and Quick Preview (the owner was using the phone).-- [ ] PowerPoint viewing (deckcraft): slides in the viewer, present mode; vendor deckcraft-fonts- with the same Android font-folder patch (drafted in the upstream doc).+- [x] **PowerPoint viewing** (deckcraft `159ed07`), built and host-tested (2026-11-07): `slides.rs`+ opens .pptx with `deckcraft-pptx` and draws slides with `deckcraft-render` (no deckcraft engine,+ so no video codecs or krilla); slides are pages (`DocumentKind.Slides`), with text layer and links;+ `deckcraft-fonts` vendored with the Android font folders. App: pptx types in pickers, folder+ lists and filters; same reading-only viewer as Word. [ ] seen on the phone; [ ] present mode+ (full-screen slides, tap/swipe to advance; transitions from `deckcraft-render::render_transition`).+ Password-protected decks are refused with a message (deckcraft can't decrypt).- [ ] Excel viewing (gridcraft): pannable Compose grid with frozen headers from cell text, styles,column widths and row heights; charts rendered by gridcraft-chart.- [ ] Export to PDF for all three (wordcraft-pdf / deckcraft-pdf through craft-pdf + krilla, alreadydiff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xmlindex aa992b3..ba434b6 100644--- a/android/app/src/main/AndroidManifest.xml+++ b/android/app/src/main/AndroidManifest.xml@@ -54,6 +54,10 @@<data android:mimeType="application/vnd.oasis.opendocument.text" /><data android:mimeType="application/rtf" /><data android:mimeType="text/rtf" />+ <data android:mimeType="application/vnd.openxmlformats-officedocument.presentationml.presentation" />+ <data android:mimeType="application/vnd.openxmlformats-officedocument.presentationml.slideshow" />+ <data android:mimeType="application/vnd.openxmlformats-officedocument.presentationml.template" />+ <data android:mimeType="application/vnd.ms-powerpoint.presentation.macroEnabled.12" /></intent-filter></activity>@@ -89,6 +93,10 @@<data android:mimeType="application/vnd.oasis.opendocument.text" /><data android:mimeType="application/rtf" /><data android:mimeType="text/rtf" />+ <data android:mimeType="application/vnd.openxmlformats-officedocument.presentationml.presentation" />+ <data android:mimeType="application/vnd.openxmlformats-officedocument.presentationml.slideshow" />+ <data android:mimeType="application/vnd.openxmlformats-officedocument.presentationml.template" />+ <data android:mimeType="application/vnd.ms-powerpoint.presentation.macroEnabled.12" /></intent-filter></activity>diff --git a/android/app/src/main/java/com/chethan616/clearpdf/engine/DocumentFiles.kt b/android/app/src/main/java/com/chethan616/clearpdf/engine/DocumentFiles.ktindex 68e7887..4e93275 100644--- a/android/app/src/main/java/com/chethan616/clearpdf/engine/DocumentFiles.kt+++ b/android/app/src/main/java/com/chethan616/clearpdf/engine/DocumentFiles.kt@@ -243,7 +243,7 @@ class DocumentFiles(private val context: Context) {*/fun safeName(name: String): String {val clean = name.replace(Regex("[\\\\/:*?\"<>|\\p{Cntrl}]"), "_").trim().trimStart('.').ifEmpty { "Document" }- return if (clean.lowercase().endsWith(".pdf") || DocumentTypes.isWordName(clean)) clean else "$clean.pdf"+ return if (clean.lowercase().endsWith(".pdf") || DocumentTypes.isOfficeName(clean)) clean else "$clean.pdf"}private fun sha(s: String): String =diff --git a/android/app/src/main/java/com/chethan616/clearpdf/engine/DocumentTypes.kt b/android/app/src/main/java/com/chethan616/clearpdf/engine/DocumentTypes.ktindex d5ae050..b204cac 100644--- a/android/app/src/main/java/com/chethan616/clearpdf/engine/DocumentTypes.kt+++ b/android/app/src/main/java/com/chethan616/clearpdf/engine/DocumentTypes.kt@@ -1,8 +1,8 @@package com.chethan616.clearpdf.engine/**- * The kinds of file Artefact opens: PDFs, and word-processor documents read by the Word engine- * (.docx, .doc, .odt, .rtf). The engine tells them apart by their bytes; these lists are for the+ * The kinds of file Artefact opens: PDFs, word-processor documents read by the Word engine+ * (.docx, .doc, .odt, .rtf) and presentations read by the slides engine (.pptx). The engine tells them apart by their bytes; these lists are for the* system's pickers, file lists and names, which go by type and extension.*/object DocumentTypes {@@ -19,22 +19,34 @@ object DocumentTypes {"text/rtf",)+ /** Presentations. */+ val SLIDES = arrayOf(+ "application/vnd.openxmlformats-officedocument.presentationml.presentation",+ "application/vnd.openxmlformats-officedocument.presentationml.slideshow",+ "application/vnd.openxmlformats-officedocument.presentationml.template",+ "application/vnd.ms-powerpoint.presentation.macroEnabled.12",+ )+/** Everything the viewer opens. */- val OPENABLE = arrayOf(PDF) + WORD+ val OPENABLE = arrayOf(PDF) + WORD + SLIDESprivate val WORD_EXTENSIONS = setOf("docx", "docm", "dotx", "dotm", "doc", "dot", "odt", "ott", "rtf")+ private val SLIDE_EXTENSIONS = setOf("pptx", "pptm", "ppsx", "ppsm", "potx", "potm")private fun extension(name: String) = name.substringAfterLast('.', "").lowercase()fun isWordName(name: String) = extension(name) in WORD_EXTENSIONS+ /** An office document's name (Word or slides): it keeps its own extension. */+ fun isOfficeName(name: String) = extension(name) in WORD_EXTENSIONS || extension(name) in SLIDE_EXTENSIONS+/** Whether a file of type [mime] named [name] is one the viewer opens. */fun isOpenable(mime: String?, name: String) =- mime == PDF || mime in WORD || extension(name) == "pdf" || isWordName(name)+ mime == PDF || mime in WORD || mime in SLIDES || extension(name) == "pdf" || isOfficeName(name)/** A file name without its extension, as documents are titled (`Report.docx` → `Report`). */fun title(name: String): String =- if (isWordName(name)) name.substringBeforeLast('.') else name.removeSuffix(".pdf").removeSuffix(".PDF")+ if (isOfficeName(name)) name.substringBeforeLast('.') else name.removeSuffix(".pdf").removeSuffix(".PDF")/** The type to hand another app a file named [name] as. */fun mimeOf(name: String): String = when (extension(name)) {@@ -44,6 +56,9 @@ object DocumentTypes {"doc", "dot" -> "application/msword""odt", "ott" -> "application/vnd.oasis.opendocument.text""rtf" -> "application/rtf"+ "pptx", "pptm" -> SLIDES[0]+ "ppsx", "ppsm" -> SLIDES[1]+ "potx", "potm" -> SLIDES[2]else -> PDF}}diff --git a/android/app/src/main/java/com/chethan616/clearpdf/preview/QuickPreview.kt b/android/app/src/main/java/com/chethan616/clearpdf/preview/QuickPreview.ktindex 5d2a6fc..b81634d 100644--- a/android/app/src/main/java/com/chethan616/clearpdf/preview/QuickPreview.kt+++ b/android/app/src/main/java/com/chethan616/clearpdf/preview/QuickPreview.kt@@ -85,7 +85,6 @@ import com.chethan616.clearpdf.ui.viewer.CanvasLookimport com.chethan616.clearpdf.ui.viewer.PageCanvasimport com.chethan616.clearpdf.ui.viewer.formatSizeimport com.chethan616.clearpdf.ui.glass.Capsule-import com.chethan616.clearpdf.ui.glass.RoundedRectangleimport kotlinx.coroutines.delayimport kotlinx.coroutines.launch@@ -195,6 +194,15 @@ private fun Preview()val margin = with(density) { 10.dp.toPx() }val cardH = fullH * CardHeight - navPx+ // Apple's way: continuous corners, concentric with the screen's own (its corner radius less+ // the card's inset), the same on all four corners; 34 dp where the screen doesn't say+ val view = androidx.compose.ui.platform.LocalView.current+ val corner = remember(view, density) {+ val screen = if (android.os.Build.VERSION.SDK_INT >= 31) {+ view.rootWindowInsets?.getRoundedCorner(android.view.RoundedCorner.POSITION_BOTTOM_LEFT)?.radius ?: 0+ } else 0+ with(density) { if (screen > 0) (screen.toDp() - 10.dp).coerceIn(24.dp, 48.dp) else 34.dp }+ }Box(Modifier.align(Alignment.BottomCenter)@@ -208,7 +216,7 @@ private fun Preview(.padding(start = 10.dp, end = 10.dp, bottom = with(density) { (margin + navPx).toDp() }).fillMaxWidth().height(with(density) { cardH.toDp() })- .clip(RoundedRectangle(34.dp))+ .clip(com.chethan616.clearpdf.ui.glass.Squircle(corner)).background(paper).clickable(remember { MutableInteractionSource() }, null) {},) {diff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/AppViewModel.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/AppViewModel.ktindex ad17cfe..e4368ae 100644--- a/android/app/src/main/java/com/chethan616/clearpdf/ui/AppViewModel.kt+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/AppViewModel.kt@@ -2766,10 +2766,10 @@ class AppViewModel(app: Application, private val saved: SavedStateHandle) : Andrfun renameFile(row: com.chethan616.clearpdf.ui.home.FileRow, newName: String) {viewModelScope.launch {- // a Word document keeps its extension when the new name leaves it out+ // an office document keeps its extension when the new name leaves it outval typed = newName.trim()- val wordExt = row.name.substringAfterLast('.', "").takeIf { DocumentTypes.isWordName(row.name) }- val name = DocumentFiles.safeName(if (wordExt != null && !DocumentTypes.isWordName(typed)) "$typed.$wordExt" else typed)+ val wordExt = row.name.substringAfterLast('.', "").takeIf { DocumentTypes.isOfficeName(row.name) }+ val name = DocumentFiles.safeName(if (wordExt != null && !DocumentTypes.isOfficeName(typed)) "$typed.$wordExt" else typed)val u = Uri.parse(row.key)val ok = withContext(Dispatchers.IO) {runCatching {diff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/OpenDocument.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/OpenDocument.ktindex cc92c77..f3c8430 100644--- a/android/app/src/main/java/com/chethan616/clearpdf/ui/OpenDocument.kt+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/OpenDocument.kt@@ -77,8 +77,11 @@ class OpenDocument(*/var localUndo by mutableStateOf<LocalUndo?>(null)- /** A Word document (read by the Word engine): it opens for reading, the PDF tools don't apply. */- val isWord: Boolean get() = info.kind == DocumentKind.WORD+ /** A Word document or a presentation: it opens for reading, the PDF tools don't apply. */+ val isOffice: Boolean get() = info.kind != DocumentKind.PDF++ /** A presentation: each page is a slide. */+ val isSlides: Boolean get() = info.kind == DocumentKind.SLIDES/** The file name without its extension, as the reference titles documents. */val title: String get() = com.chethan616.clearpdf.engine.DocumentTypes.title(info.name)diff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/desk/SettingsScreen.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/desk/SettingsScreen.ktindex 07e6a60..45d0595 100644--- a/android/app/src/main/java/com/chethan616/clearpdf/ui/desk/SettingsScreen.kt+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/desk/SettingsScreen.kt@@ -446,6 +446,8 @@ private fun LicencesPage(onBack: () -> Unit) {val credits = listOf(Credit(stringResource(R.string.root_licence_pdfcraft), stringResource(R.string.root_licence_pdfcraft_terms)),Credit(stringResource(R.string.root_licence_wordcraft), stringResource(R.string.root_licence_wordcraft_terms)),+ Credit(stringResource(R.string.root_licence_deckcraft), stringResource(R.string.root_licence_wordcraft_terms)),+ Credit("Ubuntu Light", "Ubuntu Font Licence 1.0, Canonical Ltd. / Dalton Maag"),Credit("AndroidLiquidGlass (backdrop)", "Apache-2.0, Kyant0"),Credit("AndroidLiquidGlassView (LiquidTracker)", "MIT, Donny Yale (QmDeve)"),Credit("UniFFI", "MPL-2.0, Mozilla"),diff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/glass/Shapes.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/glass/Shapes.ktindex 5057ffb..53740af 100644--- a/android/app/src/main/java/com/chethan616/clearpdf/ui/glass/Shapes.kt+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/glass/Shapes.kt@@ -12,3 +12,10 @@ val Capsule = com.kyant.shapes.Capsule(RoundedCornerStyle.Circular)/** A rounded rectangle with circular corners of [radius]. */fun RoundedRectangle(radius: Dp) = com.kyant.shapes.RoundedRectangle(radius, RoundedCornerStyle.Circular)++/**+ * A rounded rectangle with Apple's continuous ("squircle") corners of [radius]. Only for content+ * clipped inside a layer of its own that moves by its layer's transform (a card in a+ * `graphicsLayer`): there the mask is recorded once. Never on content that scrolls or resizes.+ */+fun Squircle(radius: Dp) = com.kyant.shapes.RoundedRectangle(radius, RoundedCornerStyle.Continuous)diff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/QuickTools.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/QuickTools.ktindex 012e6a5..0f33d45 100644--- a/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/QuickTools.kt+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/QuickTools.kt@@ -93,7 +93,7 @@ enum class QuickTool(val id: String, @StringRes val label: Int, @StringRes val t/** The bar as it comes: the reference's default tools and order. */val DEFAULT_BAR = listOf(Edit, Comment, Highlight, Draw, FillSign, Export)- /** The tools that work on a Word document (it opens for reading: the PDF tools don't apply). */+ /** The tools that work on a Word document or a presentation (they open for reading: the PDF tools don't apply). */val WORD = listOf(ReadAloud)fun of(id: String): QuickTool? = entries.firstOrNull { it.id == id }@@ -139,7 +139,7 @@ class QuickToolbarPrefs(context: Context) {/** Do what [tool] does on the bar or in More tools. */fun AppViewModel.runQuickTool(doc: OpenDocument, tool: QuickTool) {- if (doc.isWord && tool !in QuickTool.WORD) {+ if (doc.isOffice && tool !in QuickTool.WORD) {tell(com.chethan616.clearpdf.text(com.chethan616.clearpdf.R.string.msg_word_reading_only))return}diff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/ViewerScreen.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/ViewerScreen.ktindex 2507e34..8a16681 100644--- a/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/ViewerScreen.kt+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/ViewerScreen.kt@@ -439,7 +439,7 @@ fun ViewerScreen(vm: AppViewModel, doc: OpenDocument) {Column(barSides) {if (ctl.tool == ViewerTool.None) {QuickToolbar(- tools = if (doc.isWord) QuickTool.WORD else vm.quickToolbar.bar,+ tools = if (doc.isOffice) QuickTool.WORD else vm.quickToolbar.bar,onTool = { vm.runQuickTool(doc, it) },onMoreTools = { ctl.sheet = if (ctl.sheet == ViewerSheet.MoreTools) ViewerSheet.None else ViewerSheet.MoreTools },moreToolsOpen = ctl.sheet == ViewerSheet.MoreTools,diff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/ViewerSheets.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/ViewerSheets.ktindex 8352b78..6dd6d84 100644--- a/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/ViewerSheets.kt+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/ViewerSheets.kt@@ -112,7 +112,7 @@ fun MoreSheet(vm: AppViewModel, doc: OpenDocument) {Text(doc.title, style = ClearType.Title.copy(fontSize = 17.sp), color = clear.ink, maxLines = 1, overflow = TextOverflow.Ellipsis)Spacer(Modifier.height(2.dp))Text(- (if (doc.isWord) stringResource(R.string.sheet_kind_word) else "PDF") + " · ${modifiedLabel(doc.file.lastModified(), stringResource(R.string.common_yesterday))}" + if (!doc.writable) " · " + stringResource(R.string.sheet_read_only) else "",+ (if (doc.isSlides) stringResource(R.string.sheet_kind_slides) else if (doc.isOffice) stringResource(R.string.sheet_kind_word) else "PDF") + " · ${modifiedLabel(doc.file.lastModified(), stringResource(R.string.common_yesterday))}" + if (!doc.writable) " · " + stringResource(R.string.sheet_read_only) else "",style = ClearType.Caption.copy(fontSize = 12.sp), color = clear.inkSoft, maxLines = 1, overflow = TextOverflow.Ellipsis,)}@@ -133,7 +133,7 @@ fun MoreSheet(vm: AppViewModel, doc: OpenDocument) {) { close(); vm.toggleBookmark(doc) }ActionTile(LucideIcons.Volume2, stringResource(R.string.common_tool_read_aloud), Candy.Sky) { close(); vm.startReadAloud(doc) }// a Word document opens for reading: editing and printing it come later- if (!doc.isWord) {+ if (!doc.isOffice) {ActionTile(LucideIcons.FilePenLine, stringResource(R.string.common_tool_edit_pdf), Candy.Bubblegum) { close(); vm.enterTool(doc, ViewerTool.Edit) }ActionTile(LucideIcons.Printer, stringResource(R.string.sheet_print), Candy.Grape) { close(); vm.print(doc) }}@@ -144,12 +144,12 @@ fun MoreSheet(vm: AppViewModel, doc: OpenDocument) {SheetRow(LucideIcons.LayoutGrid, stringResource(R.string.sheet_pages), { close(); ctl.pagesOpen = true }, chevron = true, tint = Candy.Mint)SheetRow(LucideIcons.Bookmark, stringResource(R.string.sheet_bookmarks_contents), { ctl.sheet = ViewerSheet.Bookmarks }, chevron = true, tint = Candy.Tangerine)if (doc.info.attachments > 0u) SheetRow(LucideIcons.Paperclip, stringResource(R.string.sheet_attachments), { ctl.sheet = ViewerSheet.Attachments }, chevron = true, tint = Candy.Grape)- if (!doc.isWord) {+ if (!doc.isOffice) {SheetRow(LucideIcons.MessagesSquare, stringResource(R.string.sheet_comment_list), { ctl.sheet = ViewerSheet.Comments }, chevron = true, tint = Candy.Bubblegum)SheetRow(LucideIcons.ShieldCheck, stringResource(R.string.sign_signatures), { ctl.sheet = ViewerSheet.Signatures }, chevron = true, tint = Candy.Lime)}}- if (!doc.isWord) SheetSection {+ if (!doc.isOffice) SheetSection {SheetRow(LucideIcons.FileOutput, stringResource(R.string.sheet_export_as), { close(); vm.openExport(doc) }, tint = Candy.Tangerine)SheetRow(LucideIcons.FileArchive, stringResource(R.string.common_tool_compress), { close(); vm.openCompress(doc) }, tint = Candy.Mint)SheetRow(LucideIcons.Combine, stringResource(R.string.common_tool_combine), { close(); vm.openCombine(doc) }, tint = Candy.Grape)@@ -548,7 +548,7 @@ fun MoreToolsSheet(vm: AppViewModel, doc: OpenDocument) {SheetTitle(stringResource(R.string.common_tool_more_tools))val slots = toolbarSlots(androidx.compose.ui.platform.LocalConfiguration.current.screenWidthDp)val prefs = vm.quickToolbar- val tools = if (doc.isWord) emptyList() else prefs.bar.drop(slots) + prefs.grid+ val tools = if (doc.isOffice) emptyList() else prefs.bar.drop(slots) + prefs.grid// a grid of app-icon tiles: four to a row on a phone, more on wider screensandroidx.compose.foundation.layout.BoxWithConstraints(Modifier.fillMaxWidth().padding(horizontal = 10.dp, vertical = 2.dp)) {val perRow = if (maxWidth >= 560.dp) 6 else if (maxWidth >= 400.dp) 5 else 4diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xmlindex 54de26a..193d4c4 100644--- a/android/app/src/main/res/values/strings.xml+++ b/android/app/src/main/res/values/strings.xml@@ -336,6 +336,7 @@<string name="root_licence_pdfcraft">PdfCraft (engine and app)</string><string name="root_licence_pdfcraft_terms">MIT OR Apache-2.0, by storytold, the ArtCraft Team and contributors</string><string name="root_licence_wordcraft">WordCraft (Word engine)</string>+ <string name="root_licence_deckcraft">DeckCraft (slides engine)</string><string name="root_licence_wordcraft_terms">MIT OR Apache-2.0, by storytold and contributors</string><string name="root_licence_lucide">Lucide icons</string><string name="root_licence_dancing_script">Dancing Script typeface (typed signatures)</string>@@ -952,8 +953,9 @@<!-- Messages: viewer tools --><string name="msg_tool_blocked_security">This tool is not available due to the document\'s security settings.</string>- <string name="msg_word_reading_only">Word documents open for reading for now. Editing them is coming.</string>+ <string name="msg_word_reading_only">Word documents and presentations open for reading for now. Editing them is coming.</string><string name="sheet_kind_word">Word</string>+ <string name="sheet_kind_slides">Slides</string><!-- Draw tool: lines drawn are turned into neat shapes. --><string name="msg_snap_to_shape_on">Snap to shape on</string>diff --git a/engine/Cargo.lock b/engine/Cargo.lockindex c4b229e..7603674 100644--- a/engine/Cargo.lock+++ b/engine/Cargo.lock@@ -128,6 +128,9 @@ name = "artefact-mobile"version = "0.14.0"dependencies = ["android_logger",+ "deckcraft-model",+ "deckcraft-pptx",+ "deckcraft-render","kurbo","log","pdfcraft-automation",@@ -1208,6 +1211,117 @@ dependencies = ["parking_lot_core",]+[[package]]+name = "deckcraft-anim"+version = "0.15.0"+source = "git+https://github.com/storytold/deckcraft?rev=159ed07eb3f0522a5dc97d7cf1858242a6638659#159ed07eb3f0522a5dc97d7cf1858242a6638659"+dependencies = [+ "deckcraft-geom",+ "deckcraft-model",+ "serde",+]++[[package]]+name = "deckcraft-color"+version = "0.15.0"+source = "git+https://github.com/storytold/deckcraft?rev=159ed07eb3f0522a5dc97d7cf1858242a6638659#159ed07eb3f0522a5dc97d7cf1858242a6638659"+dependencies = [+ "serde",+]++[[package]]+name = "deckcraft-fonts"+version = "0.15.0"+dependencies = [+ "epaint_default_fonts",+ "harfrust 0.13.3",+ "kurbo",+ "log",+ "skrifa 0.47.0",+ "unicode-bidi",+]++[[package]]+name = "deckcraft-geom"+version = "0.15.0"+source = "git+https://github.com/storytold/deckcraft?rev=159ed07eb3f0522a5dc97d7cf1858242a6638659#159ed07eb3f0522a5dc97d7cf1858242a6638659"+dependencies = [+ "kurbo",+ "serde",+]++[[package]]+name = "deckcraft-metafile"+version = "0.15.0"+source = "git+https://github.com/storytold/deckcraft?rev=159ed07eb3f0522a5dc97d7cf1858242a6638659#159ed07eb3f0522a5dc97d7cf1858242a6638659"+dependencies = [+ "image",+ "kurbo",+ "thiserror",+]++[[package]]+name = "deckcraft-model"+version = "0.15.0"+source = "git+https://github.com/storytold/deckcraft?rev=159ed07eb3f0522a5dc97d7cf1858242a6638659#159ed07eb3f0522a5dc97d7cf1858242a6638659"+dependencies = [+ "deckcraft-color",+ "deckcraft-geom",+ "serde",+ "serde_json",+ "thiserror",+ "unicode-segmentation",+]++[[package]]+name = "deckcraft-pptx"+version = "0.15.0"+source = "git+https://github.com/storytold/deckcraft?rev=159ed07eb3f0522a5dc97d7cf1858242a6638659#159ed07eb3f0522a5dc97d7cf1858242a6638659"+dependencies = [+ "deckcraft-color",+ "deckcraft-geom",+ "deckcraft-model",+ "log",+ "quick-xml",+ "thiserror",+ "zip",+]++[[package]]+name = "deckcraft-render"+version = "0.15.0"+source = "git+https://github.com/storytold/deckcraft?rev=159ed07eb3f0522a5dc97d7cf1858242a6638659#159ed07eb3f0522a5dc97d7cf1858242a6638659"+dependencies = [+ "deckcraft-anim",+ "deckcraft-color",+ "deckcraft-fonts",+ "deckcraft-geom",+ "deckcraft-metafile",+ "deckcraft-model",+ "deckcraft-text",+ "image",+ "kurbo",+ "log",+ "skrifa 0.47.0",+ "vello_common 0.2.0",+ "vello_cpu 0.2.0",+]++[[package]]+name = "deckcraft-text"+version = "0.15.0"+source = "git+https://github.com/storytold/deckcraft?rev=159ed07eb3f0522a5dc97d7cf1858242a6638659#159ed07eb3f0522a5dc97d7cf1858242a6638659"+dependencies = [+ "chrono",+ "deckcraft-color",+ "deckcraft-fonts",+ "deckcraft-geom",+ "deckcraft-model",+ "unicode-bidi",+ "unicode-linebreak",+ "unicode-segmentation",+]+[[package]]name = "der"version = "0.7.10"@@ -1450,6 +1564,12 @@ dependencies = ["log",]+[[package]]+name = "epaint_default_fonts"+version = "0.37.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cfc1cc505827f4c23eedc297975a0fd038268d41293f389dd8ff3b574aefab19"+[[package]]name = "equator"version = "0.4.2"diff --git a/engine/Cargo.toml b/engine/Cargo.tomlindex 8f70aa1..647985d 100644--- a/engine/Cargo.toml+++ b/engine/Cargo.toml@@ -60,6 +60,12 @@ pdfcraft-automation = { path = "crates/automation", version = "0.14.0", default-# code, out: `default-features = false` turns off its `font-store` feature.wordcraft-engine = { path = "vendor/wordcraft-engine", version = "0.15.1", default-features = false }+# PowerPoint (.pptx): storytold/deckcraft's reader, model and slide renderer, pinned to one revision.+# Viewing needs no deckcraft-engine (and so none of its video codecs).+deckcraft-model = { git = "https://github.com/storytold/deckcraft", rev = "159ed07eb3f0522a5dc97d7cf1858242a6638659", version = "0.15.0" }+deckcraft-pptx = { git = "https://github.com/storytold/deckcraft", rev = "159ed07eb3f0522a5dc97d7cf1858242a6638659", version = "0.15.0" }+deckcraft-render = { git = "https://github.com/storytold/deckcraft", rev = "159ed07eb3f0522a5dc97d7cf1858242a6638659", version = "0.15.0" }+hayro = "0.7.1"hayro-syntax = "0.7.2"@@ -131,3 +137,7 @@ krilla = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f904# wordcraft crates we carry a patch for (see vendor/README.md).[patch."https://github.com/storytold/wordcraft"]wordcraft-fonts = { path = "vendor/wordcraft-fonts" }++# deckcraft crates we carry a patch for (see vendor/README.md).+[patch."https://github.com/storytold/deckcraft"]+deckcraft-fonts = { path = "vendor/deckcraft-fonts" }diff --git a/engine/mobile/Cargo.toml b/engine/mobile/Cargo.tomlindex 8bdd2fd..58eb9b4 100644--- a/engine/mobile/Cargo.toml+++ b/engine/mobile/Cargo.toml@@ -22,6 +22,10 @@ pdfcraft-automation = { workspace = true }serde_json = { workspace = true }# Word documents (src/word.rs): WordCraft's engine, which re-exports its model, layout and rendererwordcraft-engine = { workspace = true }+# PowerPoint presentations (src/slides.rs): DeckCraft's reader, model and slide renderer+deckcraft-model = { workspace = true }+deckcraft-pptx = { workspace = true }+deckcraft-render = { workspace = true }kurbo = { workspace = true }thiserror = { workspace = true }log = { workspace = true }diff --git a/engine/mobile/src/lib.rs b/engine/mobile/src/lib.rsindex 892cc72..3012203 100644--- a/engine/mobile/src/lib.rs+++ b/engine/mobile/src/lib.rs@@ -25,11 +25,13 @@ use serde_json::{Value, json};uniffi::setup_scaffolding!();+mod office;+mod slides;#[cfg(test)]mod tests;mod word;-use word::WordDocument;+use office::OfficeDoc;/// What went wrong, as a message the user can act on.#[derive(Debug, thiserror::Error, uniffi::Error)]@@ -72,6 +74,8 @@ pub enum DocumentKind {Pdf,/// A word-processor document (.docx, .doc, .odt, .rtf), read by WordCraft's engine.Word,+ /// A presentation (.pptx), read by DeckCraft: each slide is a page.+ Slides,}/// An open document as the viewer's title, menus and properties show it.@@ -156,14 +160,13 @@ pub struct ToolInfo {pub read_only: bool,}-/// Page 1 of the document (a PDF or a Word document) at absolute path `path` drawn to fit+/// Page 1 of the document (a PDF, a Word document or a presentation) at absolute path `path` drawn to fit/// `max_side` pixels, for file lists. The file is read but not opened in any session; a protected/// or unreadable file is an error.#[uniffi::export]pub fn file_thumbnail(path: String, max_side: u32) -> Result<RenderedImage, MobileError> {- if let Some(ext) = word_file(&path)? {- let bytes = WordDocument::read(&path)?;- return WordDocument::open(&path, ext, &bytes, None, None)?.thumbnail(max_side);+ if let Some((kind, bytes)) = office::file_at(&path)? {+ return office::open(&path, kind, &bytes, None, None)?.thumbnail(max_side);}let bytes = std::fs::read(&path).map_err(|e| MobileError::Open(format!("{path}: {e}")))?;let mut r = PageRenderer::new(Arc::new(bytes), RenderConfig::default());@@ -440,29 +443,15 @@ struct TextCache {pages: Vec<Option<Arc<PageText>>>,}-/// The Word document at `path`, if it is one: the extension WordCraft reads it by. Only the-/// first bytes are read of a file that can't be one (a PDF).-fn word_file(path: &str) -> Result<Option<&'static str>, MobileError> {- use std::io::Read;- let mut head = [0u8; 8];- let n = std::fs::File::open(path).and_then(|mut f| f.read(&mut head)).map_err(|e| MobileError::Open(format!("{path}: {e}")))?;- let head = head.get(..n).unwrap_or_default();- let maybe = head.starts_with(b"PK\x03\x04") || head.starts_with(&[0xD0, 0xCF, 0x11, 0xE0]) || head.starts_with(b"{\\rtf");- if !maybe {- return Ok(None);- }- Ok(word::word_extension(&WordDocument::read(path)?, path))-}-/// The engine's session: the open documents, their edit history and the tools that act on them.-/// PDFs are the PDF engine's; Word documents are kept beside them under ids of their own.+/// PDFs are the PDF engine's; office documents are kept beside them under ids of their own.#[derive(uniffi::Object)]pub struct MobileSession {auto: Mutex<Automation>,renderers: Mutex<RendererCache>,texts: Mutex<HashMap<u64, TextCache>>,- words: Mutex<HashMap<u64, Arc<WordDocument>>>,- next_word: AtomicU64,+ office: Mutex<HashMap<u64, Arc<dyn OfficeDoc>>>,+ next_office: AtomicU64,/// The reader's language (BCP 47), for the paper of documents that give none.locale: Mutex<Option<String>>,}@@ -505,9 +494,9 @@ impl MobileSession {}}- /// The Word document `doc`, if it is one.- fn word(&self, doc: u64) -> Option<Arc<WordDocument>> {- self.words.lock().unwrap_or_else(PoisonError::into_inner).get(&doc).cloned()+ /// The office document `doc`, if it is one.+ fn office(&self, doc: u64) -> Option<Arc<dyn OfficeDoc>> {+ self.office.lock().unwrap_or_else(PoisonError::into_inner).get(&doc).cloned()}fn with_doc<T>(&self, doc: u64, f: impl FnOnce(&Document) -> T) -> Result<T, MobileError> {@@ -518,7 +507,7 @@ impl MobileSession {/// The text layer of page `page` of `doc` as it is now (extracted once per document version).fn page_text(&self, doc: u64, page: u32) -> Result<Arc<PageText>, MobileError> {- if let Some(w) = self.word(doc) {+ if let Some(w) = self.office(doc) {return w.page_text(page);}let (bytes, password, pages) = self.with_doc(doc, |d| (d.bytes.clone(), d.password.clone(), d.info.pages.len()))?;@@ -574,8 +563,8 @@ impl MobileSession {auto: Mutex::new(Automation::new()),renderers: Mutex::new(HashMap::new()),texts: Mutex::new(HashMap::new()),- words: Mutex::new(HashMap::new()),- next_word: AtomicU64::new(word::WORD_IDS),+ office: Mutex::new(HashMap::new()),+ next_office: AtomicU64::new(office::OFFICE_IDS),locale: Mutex::new(None),})}@@ -586,19 +575,18 @@ impl MobileSession {*self.locale.lock().unwrap_or_else(PoisonError::into_inner) = Some(tag);}- /// Open the document at absolute path `path` (with `password` if it needs one): a PDF, or a- /// Word document (.docx, .doc, .odt, .rtf), told apart by its bytes.+ /// Open the document at absolute path `path` (with `password` if it needs one): a PDF, a Word+ /// document (.docx, .doc, .odt, .rtf) or a presentation (.pptx), told apart by its bytes.pub fn open(&self, path: String, password: Option<String>) -> Result<DocumentInfo, MobileError> {if !std::path::Path::new(&path).is_absolute() {return Err(MobileError::Open(format!("the path must be absolute, not `{path}`")));}- if let Some(ext) = word_file(&path)? {- let bytes = WordDocument::read(&path)?;+ if let Some((kind, bytes)) = office::file_at(&path)? {let locale = self.locale.lock().unwrap_or_else(PoisonError::into_inner).clone();- let w = Arc::new(WordDocument::open(&path, ext, &bytes, password.as_deref(), locale.as_deref())?);- let id = self.next_word.fetch_add(1, Ordering::Relaxed);- self.words.lock().unwrap_or_else(PoisonError::into_inner).insert(id, w.clone());- return Ok(w.info(id));+ let d = office::open(&path, kind, &bytes, password.as_deref(), locale.as_deref())?;+ let id = self.next_office.fetch_add(1, Ordering::Relaxed);+ self.office.lock().unwrap_or_else(PoisonError::into_inner).insert(id, d.clone());+ return Ok(d.info(id));}let mut args = json!({ "path": path });if let (Some(p), Some(o)) = (password, args.as_object_mut()) {@@ -611,7 +599,7 @@ impl MobileSession {/// Close document `doc`. Unsaved edits are refused unless `discard_changes` is set.pub fn close(&self, doc: u64, discard_changes: bool) -> Result<(), MobileError> {- if self.words.lock().unwrap_or_else(PoisonError::into_inner).remove(&doc).is_some() {+ if self.office.lock().unwrap_or_else(PoisonError::into_inner).remove(&doc).is_some() {return Ok(());}self.call("doc_close", &json!({ "doc": doc, "discard_changes": discard_changes }))?;@@ -623,15 +611,15 @@ impl MobileSession {/// The ids of the open documents.pub fn documents(&self) -> Vec<u64> {let mut ids: Vec<u64> = self.lock().session().docs().iter().map(|d| d.id.0).collect();- let mut words: Vec<u64> = self.words.lock().unwrap_or_else(PoisonError::into_inner).keys().copied().collect();- words.sort_unstable();- ids.extend(words);+ let mut office: Vec<u64> = self.office.lock().unwrap_or_else(PoisonError::into_inner).keys().copied().collect();+ office.sort_unstable();+ ids.extend(office);ids}/// Document `doc` as it is now.pub fn document(&self, doc: u64) -> Result<DocumentInfo, MobileError> {- if let Some(w) = self.word(doc) {+ if let Some(w) = self.office(doc) {return Ok(w.info(doc));}self.with_doc(doc, document_info)@@ -639,7 +627,7 @@ impl MobileSession {/// Document `doc`'s bookmarks, flattened in reading order (at most as many as the engine reads).pub fn outline(&self, doc: u64) -> Result<Vec<OutlineEntry>, MobileError> {- if self.word(doc).is_some() {+ if self.office(doc).is_some() {return Ok(Vec::new());}self.with_doc(doc, |d| {@@ -657,7 +645,7 @@ impl MobileSession {if !(scale.is_finite() && scale > 0.0) {return Err(MobileError::Render(format!("the scale must be a positive number, not {scale}")));}- if let Some(w) = self.word(doc) {+ if let Some(w) = self.office(doc) {return w.render_page(page, scale, tile);}let (bytes, config, pages) = self.with_doc(doc, |d| {@@ -711,7 +699,7 @@ impl MobileSession {/// The links on page `page`.pub fn links(&self, doc: u64, page: u32) -> Result<Vec<LinkInfo>, MobileError> {- if let Some(w) = self.word(doc) {+ if let Some(w) = self.office(doc) {return w.links(page);}self.with_doc(doc, |d| {@@ -742,7 +730,7 @@ impl MobileSession {/// Every comment of the document, page by page (replies included; see `reply_to`).pub fn comments(&self, doc: u64) -> Result<Vec<CommentInfo>, MobileError> {- if self.word(doc).is_some() {+ if self.office(doc).is_some() {return Ok(Vec::new());}self.with_doc(doc, |d| {@@ -774,7 +762,7 @@ impl MobileSession {/// The files embedded in the document.pub fn attachments(&self, doc: u64) -> Result<Vec<AttachmentInfo>, MobileError> {- if self.word(doc).is_some() {+ if self.office(doc).is_some() {return Ok(Vec::new());}self.with_doc(doc, |d| {@@ -819,7 +807,7 @@ impl MobileSession {/// The certificate (DER) that signed signature field `field`, if it is signed: what the app/// saves when the reader chooses to trust that signer.pub fn signer_certificate(&self, doc: u64, field: String) -> Result<Option<Vec<u8>>, MobileError> {- if self.word(doc).is_some() {+ if self.office(doc).is_some() {return Ok(None);}self.with_doc(doc, |d| d.signatures.iter().find(|s| s.signed && s.field == field).and_then(|s| s.certificate.as_ref()).map(|c| c.raw.clone()))@@ -827,7 +815,7 @@ impl MobileSession {/// Every visible widget of the document's form fields, page by page.pub fn widgets(&self, doc: u64) -> Result<Vec<WidgetInfo>, MobileError> {- if self.word(doc).is_some() {+ if self.office(doc).is_some() {return Ok(Vec::new());}use pdfcraft_engine::{FormFieldKind as K, field_flags as fl};@@ -881,7 +869,7 @@ impl MobileSession {pub fn release_memory(&self) {self.cache().clear();self.texts.lock().unwrap_or_else(PoisonError::into_inner).clear();- for w in self.words.lock().unwrap_or_else(PoisonError::into_inner).values() {+ for w in self.office.lock().unwrap_or_else(PoisonError::into_inner).values() {w.release_memory();}}diff --git a/engine/mobile/src/office.rs b/engine/mobile/src/office.rsnew file mode 100644index 0000000..aaac883--- /dev/null+++ b/engine/mobile/src/office.rs@@ -0,0 +1,211 @@+//! Office documents beside the PDFs: Word documents ([`crate::word`], WordCraft's engine) and+//! PowerPoint presentations ([`crate::slides`], DeckCraft's).+//!+//! Each lives in the same [`MobileSession`](crate::MobileSession) as the PDFs, under a document id+//! of its own ([`OFFICE_IDS`] and up), so the viewer's page, thumbnail, search, selection and Read+//! Aloud paths work unchanged: the session sends each call for such an id to the document's+//! [`OfficeDoc`]. Their text layers are built from the engines' positioned glyphs into the PDF+//! engine's [`PageText`], whose search, word and line logic is then shared.++use std::sync::Arc;++use pdfcraft_render::{PageText, TextGlyph};++use crate::{DocumentInfo, LinkInfo, MobileError, RenderedImage, TileRect};++/// The first document id given to an office document: far above the PDF engine's ids (which count+/// up from 1), so the two never meet.+pub(crate) const OFFICE_IDS: u64 = 1 << 40;++/// The largest file opened (the PDF side has the same 2 GB bound in its reader).+const MAX_FILE: u64 = 2 << 30;++/// An open office document, as the session uses it: pages (Word's pages, a deck's slides) drawn and+/// read like a PDF's.+pub(crate) trait OfficeDoc: Send + Sync {+ /// The document as the viewer's title, menus and properties show it, under id `id`.+ fn info(&self, id: u64) -> DocumentInfo;+ /// Page `page` at `scale` pixels per point: all of it, or `tile` of it (pixels at that scale).+ fn render_page(&self, page: u32, scale: f32, tile: Option<TileRect>) -> Result<RenderedImage, MobileError>;+ /// Page `page`'s text layer.+ fn page_text(&self, page: u32) -> Result<Arc<PageText>, MobileError>;+ /// The web and mail links on page `page`.+ fn links(&self, page: u32) -> Result<Vec<LinkInfo>, MobileError>;+ /// Drop what can be built again (the system is short of memory).+ fn release_memory(&self);++ /// Page 1 drawn to fit `max_side` pixels, for file lists.+ fn thumbnail(&self, max_side: u32) -> Result<RenderedImage, MobileError> {+ let page = self.info(0).pages.into_iter().next().ok_or_else(|| MobileError::Open("the document has no pages".into()))?;+ let scale = (max_side.clamp(16, 2048) as f32 / page.width.max(page.height).max(1.0)).max(0.01);+ self.render_page(0, scale, None)+ }+}++/// What kind of office document a file is, and the extension its engine reads it by.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub(crate) enum OfficeFile {+ Word(&'static str),+ Slides,+}++const WORD_EXTENSIONS: &[&str] = &["docx", "docm", "dotx", "dotm", "doc", "dot", "odt", "ott", "rtf"];+const SLIDE_EXTENSIONS: &[&str] = &["pptx", "pptm", "ppsx", "ppsm", "potx", "potm"];++/// What the bytes of a file are, as far as office documents go, or `None` when it is not one (a+/// PDF, or anything else). An encrypted package is a compound file whatever the application: its+/// name decides.+pub(crate) fn sniff(bytes: &[u8], path: &str) -> Option<OfficeFile> {+ let head = bytes.get(..bytes.len().min(1024)).unwrap_or_default();+ if head.windows(5).any(|w| w == b"%PDF-") {+ return None;+ }+ let ext = std::path::Path::new(path).extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase);+ let word_named = ext.as_deref().and_then(|e| WORD_EXTENSIONS.iter().find(|w| **w == e).copied());+ let slides_named = ext.as_deref().is_some_and(|e| SLIDE_EXTENSIONS.contains(&e));+ let contains = |needle: &[u8]| bytes.windows(needle.len()).any(|w| w == needle);+ if bytes.starts_with(b"PK\x03\x04") {+ // a zip package: its part names are plain text in the local headers and the directory+ if contains(b"word/document.xml") {+ return Some(OfficeFile::Word(match word_named {+ Some(e @ ("docm" | "dotx" | "dotm")) => e,+ _ => "docx",+ }));+ }+ if contains(b"ppt/presentation.xml") {+ return Some(OfficeFile::Slides);+ }+ if contains(b"application/vnd.oasis.opendocument.text") {+ return Some(OfficeFile::Word(if word_named == Some("ott") { "ott" } else { "odt" }));+ }+ return None;+ }+ if bytes.starts_with(&[0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1]) {+ // a compound file: a Word 97-2003 document, or a password-protected package+ let utf16 = |s: &str| s.encode_utf16().flat_map(u16::to_le_bytes).collect::<Vec<u8>>();+ if contains(&utf16("WordDocument")) {+ return Some(OfficeFile::Word(if word_named == Some("dot") { "dot" } else { "doc" }));+ }+ if contains(&utf16("EncryptedPackage")) {+ if slides_named {+ return Some(OfficeFile::Slides);+ }+ return word_named.filter(|e| matches!(*e, "docx" | "docm" | "dotx" | "dotm")).map(OfficeFile::Word);+ }+ return None;+ }+ if head.starts_with(b"{\\rtf") {+ return Some(OfficeFile::Word("rtf"));+ }+ None+}++/// Read the file at `path` within the size bound.+pub(crate) fn read(path: &str) -> Result<Vec<u8>, MobileError> {+ let size = std::fs::metadata(path).map_err(|e| MobileError::Open(format!("{path}: {e}")))?.len();+ if size > MAX_FILE {+ return Err(MobileError::Open(format!("{path}: the file is larger than 2 GB")));+ }+ std::fs::read(path).map_err(|e| MobileError::Open(format!("{path}: {e}")))+}++/// The office document at `path`, if it is one, with its bytes. Only the first bytes are read of a+/// file that can't be one (a PDF).+pub(crate) fn file_at(path: &str) -> Result<Option<(OfficeFile, Vec<u8>)>, MobileError> {+ use std::io::Read;+ let mut head = [0u8; 8];+ let n = std::fs::File::open(path).and_then(|mut f| f.read(&mut head)).map_err(|e| MobileError::Open(format!("{path}: {e}")))?;+ let head = head.get(..n).unwrap_or_default();+ if !(head.starts_with(b"PK\x03\x04") || head.starts_with(&[0xD0, 0xCF, 0x11, 0xE0]) || head.starts_with(b"{\\rtf")) {+ return Ok(None);+ }+ let bytes = read(path)?;+ Ok(sniff(&bytes, path).map(|kind| (kind, bytes)))+}++/// Open the office document `kind` from `bytes` (read from `path`).+pub(crate) fn open(+ path: &str,+ kind: OfficeFile,+ bytes: &[u8],+ password: Option<&str>,+ locale: Option<&str>,+) -> Result<Arc<dyn OfficeDoc>, MobileError> {+ Ok(match kind {+ OfficeFile::Word(ext) => Arc::new(crate::word::WordDocument::open(path, ext, bytes, password, locale)?),+ OfficeFile::Slides => Arc::new(crate::slides::SlideDeck::open(path, bytes)?),+ })+}++/// The file name of `path`.+pub(crate) fn file_name(path: &str) -> String {+ std::path::Path::new(path).file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| path.to_string())+}++/// How far above its baseline a glyph's box reaches, and how far below, in ems: the usual ascent+/// and descent of text faces (the box is for highlighting and hit testing, not drawing).+pub(crate) const ASCENT: f32 = 0.8;+pub(crate) const DESCENT: f32 = 0.22;++/// A text glyph showing `text` whose em box runs from `x0` to `x1` along a baseline at `baseline`+/// at `size`, in its own space, which `to_page` maps to page points (a shape's rotation, say).+pub(crate) fn text_glyph(text: String, x0: f64, x1: f64, baseline: f64, size: f64, to_page: kurbo::Affine) -> TextGlyph {+ let (top, bottom) = (baseline - size * f64::from(ASCENT), baseline + size * f64::from(DESCENT));+ let p = |x: f64, y: f64| {+ let q = to_page * kurbo::Point::new(x, y);+ [q.x as f32, q.y as f32]+ };+ // the edge towards the next line (the bottom) first, in the writing direction, then the top back+ let quad = [p(x0, bottom), p(x1, bottom), p(x1, top), p(x0, top)];+ let xs = quad.map(|c| c[0]);+ let ys = quad.map(|c| c[1]);+ let min = |v: [f32; 4]| v.into_iter().fold(f32::INFINITY, f32::min);+ let max = |v: [f32; 4]| v.into_iter().fold(f32::NEG_INFINITY, f32::max);+ let [a, b] = [quad[0], quad[1]];+ let (dx, dy) = (b[0] - a[0], b[1] - a[1]);+ let len = (dx * dx + dy * dy).sqrt();+ let direction = if len > 0.0 { [dx / len, dy / len] } else { [1.0, 0.0] };+ TextGlyph { text, rect: [min(xs), min(ys), max(xs), max(ys)], quad, direction }+}++/// Whether a link goes to the web or to a mail address (the only links the viewer opens).+pub(crate) fn is_web_link(uri: &str) -> bool {+ let lower = uri.trim_start().to_ascii_lowercase();+ lower.starts_with("http://") || lower.starts_with("https://") || lower.starts_with("mailto:")+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn office_documents_are_told_from_pdfs_by_their_bytes() {+ assert_eq!(sniff(b"%PDF-1.7\n", "/a/Report.docx"), None);+ assert_eq!(sniff(b"PK\x03\x04....word/document.xml....", "/a/Report.pdf"), Some(OfficeFile::Word("docx")));+ assert_eq!(sniff(b"PK\x03\x04....word/document.xml....", "/a/Letter.dotx"), Some(OfficeFile::Word("dotx")));+ assert_eq!(sniff(b"PK\x03\x04mimetypeapplication/vnd.oasis.opendocument.text", "/a/x"), Some(OfficeFile::Word("odt")));+ assert_eq!(sniff(b"PK\x03\x04....ppt/presentation.xml....", "/a/Deck.pdf"), Some(OfficeFile::Slides));+ assert_eq!(sniff(b"PK\x03\x04xl/workbook.xml", "/a/Book.xlsx"), None);+ assert_eq!(sniff(b"{\\rtf1\\ansi hello}", "/a/x.txt"), Some(OfficeFile::Word("rtf")));+ assert_eq!(sniff(b"plain words", "/a/notes.docx"), None);+ }++ #[test]+ fn an_encrypted_package_is_what_its_name_says() {+ let mut cfb = vec![0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1];+ cfb.extend("EncryptedPackage".encode_utf16().flat_map(u16::to_le_bytes));+ assert_eq!(sniff(&cfb, "/a/Locked.docx"), Some(OfficeFile::Word("docx")));+ assert_eq!(sniff(&cfb, "/a/Locked.pptx"), Some(OfficeFile::Slides));+ assert_eq!(sniff(&cfb, "/a/Locked.xlsx"), None);+ }++ #[test]+ fn a_glyph_box_follows_its_transform() {+ let g = text_glyph("a".into(), 0.0, 10.0, 20.0, 10.0, kurbo::Affine::IDENTITY);+ assert_eq!(g.rect, [0.0, 12.0, 10.0, 22.2]);+ assert_eq!(g.direction, [1.0, 0.0]);+ // turned a quarter clockwise, the text runs down the page+ let g = text_glyph("a".into(), 0.0, 10.0, 0.0, 10.0, kurbo::Affine::rotate(std::f64::consts::FRAC_PI_2));+ assert!((g.direction[1] - 1.0).abs() < 1e-5 && g.direction[0].abs() < 1e-5, "{:?}", g.direction);+ }+}diff --git a/engine/mobile/src/slides.rs b/engine/mobile/src/slides.rsnew file mode 100644index 0000000..3da9f68--- /dev/null+++ b/engine/mobile/src/slides.rs@@ -0,0 +1,156 @@+//! PowerPoint presentations (.pptx) through storytold/deckcraft's reader and slide renderer: each+//! slide is a page of the viewer (see [`crate::office`]). Viewing needs no deckcraft engine.++use std::sync::{Arc, Mutex, PoisonError};++use deckcraft_model::Presentation;+use deckcraft_model::text::Action;+use deckcraft_render::RenderOpts;+use pdfcraft_render::PageText;++use crate::office::{OfficeDoc, is_web_link, text_glyph};+use crate::{DocumentInfo, DocumentKind, LinkInfo, MobileError, PageInfo, RenderedImage, TileRect};++/// One open presentation and its slides' text layers.+pub(crate) struct SlideDeck {+ pres: Arc<Presentation>,+ name: String,+ path: String,+ file_size: u64,+ texts: Mutex<Vec<Option<Arc<PageText>>>>,+}++/// Worker threads a slide renders on (effects that blur need some).+const THREADS: u16 = 2;++impl SlideDeck {+ pub(crate) fn open(path: &str, bytes: &[u8]) -> Result<SlideDeck, MobileError> {+ if deckcraft_pptx::is_encrypted(bytes) {+ return Err(MobileError::Open("password-protected presentations can't be opened yet".into()));+ }+ let pres = deckcraft_pptx::import(bytes).map_err(|e| MobileError::Open(e.to_string()))?;+ let n = pres.slides.len();+ Ok(SlideDeck {+ pres: Arc::new(pres),+ name: crate::office::file_name(path),+ path: path.to_string(),+ file_size: bytes.len() as u64,+ texts: Mutex::new(vec![None; n]),+ })+ }++ fn slide(&self, page: u32) -> Result<usize, MobileError> {+ let n = self.pres.slides.len();+ let i = page as usize;+ if i < n {+ Ok(i)+ } else {+ Err(MobileError::Render(format!("slide {} is out of range: the presentation has {n} slides", u64::from(page) + 1)))+ }+ }+}++impl OfficeDoc for SlideDeck {+ fn info(&self, id: u64) -> DocumentInfo {+ let p = &self.pres;+ let (w, h) = (p.slide_size.width as f32, p.slide_size.height as f32);+ let some = |v: &str| (!v.trim().is_empty()).then(|| v.to_string());+ DocumentInfo {+ id,+ kind: DocumentKind::Slides,+ name: self.name.clone(),+ path: Some(self.path.clone()),+ pages: (0..p.slides.len()).map(|i| PageInfo { width: w, height: h, label: (i + 1).to_string(), rotation: 0 }).collect(),+ title: some(&p.props.title),+ author: some(&p.props.author),+ subject: some(&p.props.subject),+ keywords: some(&p.props.keywords),+ creator: None,+ producer: None,+ pdf_version: String::new(),+ file_size: self.file_size,+ encrypted: false,+ tagged: false,+ read_only_reason: Some("Presentations open for viewing in this version".into()),+ allows_printing: true,+ allows_copying: true,+ allows_annotation: false,+ allows_form_filling: false,+ allows_assembly: false,+ dirty: false,+ undo: None,+ redo: None,+ fields: 0,+ has_outline: false,+ attachments: 0,+ signed: false,+ comments_hidden: false,+ generation: 0,+ }+ }++ fn render_page(&self, page: u32, scale: f32, tile: Option<TileRect>) -> Result<RenderedImage, MobileError> {+ let i = self.slide(page)?;+ let mut opts = RenderOpts { scale: f64::from(scale), threads: THREADS, ..RenderOpts::default() };+ if let Some(t) = tile {+ opts.offset = (-f64::from(t.x), -f64::from(t.y));+ opts.size = Some((t.width.max(1), t.height.max(1)));+ }+ let img = deckcraft_render::render_slide(&self.pres, i, &opts);+ if img.width == 0 || img.height == 0 {+ return Err(MobileError::Render(format!("slide {} could not be drawn", i + 1)));+ }+ Ok(RenderedImage { width: img.width, height: img.height, rgba: img.pixels })+ }++ fn page_text(&self, page: u32) -> Result<Arc<PageText>, MobileError> {+ let i = self.slide(page)?;+ let mut texts = self.texts.lock().unwrap_or_else(PoisonError::into_inner);+ if let Some(Some(t)) = texts.get(i) {+ return Ok(t.clone());+ }+ let mut glyphs = Vec::new();+ for pt in deckcraft_render::place_slide(&self.pres, i).texts {+ for run in &pt.layout.runs {+ if run.size <= 0.0 {+ continue;+ }+ for (gi, (gid, x, y)) in run.glyphs.iter().enumerate() {+ // bullets draw no paragraph character+ let Some((_, ch)) = run.cells.get(gi) else { continue };+ if ch.is_whitespace() {+ continue;+ }+ let next = run.glyphs.get(gi + 1).map(|g| g.1).filter(|n| n > x);+ let x1 = next.unwrap_or(x + run.face.advance(*gid) * run.size / run.face.upem.max(1.0));+ glyphs.push(text_glyph(ch.to_string(), *x, x1, *y, run.size, pt.transform));+ }+ }+ }+ let text = Arc::new(pdfcraft_render::text::layout(glyphs));+ if let Some(slot) = texts.get_mut(i) {+ *slot = Some(text.clone());+ }+ Ok(text)+ }++ fn links(&self, page: u32) -> Result<Vec<LinkInfo>, MobileError> {+ let i = self.slide(page)?;+ Ok(deckcraft_render::place_slide(&self.pres, i)+ .links+ .into_iter()+ .filter_map(|l| match &l.link.action {+ Action::Url { url } if is_web_link(url) => {+ let r = l.rect;+ Some(LinkInfo { rect: vec![r.x0 as f32, r.y0 as f32, r.x1 as f32, r.y1 as f32], uri: Some(url.clone()), page: None, top: None })+ }+ _ => None,+ })+ .collect())+ }++ fn release_memory(&self) {+ let mut texts = self.texts.lock().unwrap_or_else(PoisonError::into_inner);+ texts.iter_mut().for_each(|t| *t = None);+ }+}diff --git a/engine/mobile/src/tests.rs b/engine/mobile/src/tests.rsindex 4af04b5..6c3a101 100644--- a/engine/mobile/src/tests.rs+++ b/engine/mobile/src/tests.rs@@ -537,3 +537,32 @@ fn render_sample() {eprintln!("links {:?}", s.links(info.id, p).unwrap());}}++/// A presentation (.pptx) whose title slide reads `title`, written by DeckCraft into a fresh folder.+fn deck_file(title: &str, name: &str) -> String {+ let mut p = deckcraft_model::defaults::new_presentation(None);+ let slide = std::sync::Arc::make_mut(p.slides.first_mut().unwrap());+ let shape = slide.shapes.iter_mut().find(|s| s.ph.is_some()).unwrap();+ shape.text = Some(deckcraft_model::text::TextBody::from_text(title));+ let path = scratch().join(name);+ std::fs::write(&path, deckcraft_pptx::export(&p).unwrap()).unwrap();+ path.to_string_lossy().into_owned()+}++#[test]+fn opens_a_presentation_as_slides() {+ let s = MobileSession::new();+ let info = s.open(deck_file("Quarterly results", "Deck.pptx"), None).unwrap();+ assert_eq!(info.kind, DocumentKind::Slides);+ assert_eq!(info.pages.len(), 1);+ assert!(info.pages[0].width > info.pages[0].height, "a slide is wide: {:?}", info.pages[0]);+ let page = s.render_page(info.id, 0, 0.5, None).unwrap();+ assert_eq!(page.rgba.len() as u32, page.width * page.height * 4);+ let tile = s.render_page(info.id, 0, 1.0, Some(TileRect { x: 10, y: 10, width: 40, height: 20 })).unwrap();+ assert_eq!((tile.width, tile.height), (40, 20));+ assert!(s.render_page(info.id, 1, 1.0, None).is_err());+ let hits = s.find_in_page(info.id, 0, "results".into(), false, false).unwrap();+ assert_eq!(hits.len(), 1);+ assert_eq!(s.text_of(info.id, hits[0].range).unwrap(), "results");+ assert_eq!(file_thumbnail(deck_file("Thumb", "T.pptx"), 100).unwrap().width, 100);+}diff --git a/engine/mobile/src/word.rs b/engine/mobile/src/word.rsindex e761a1f..3bb09ff 100644--- a/engine/mobile/src/word.rs+++ b/engine/mobile/src/word.rs@@ -1,75 +1,21 @@//! Word documents (.docx and the other word-processor formats) through storytold/wordcraft's-//! engine: opened, laid out into pages, drawn and read the way the viewer reads a PDF.-//!-//! A Word document lives in the same [`MobileSession`](crate::MobileSession) as the PDFs, under a-//! document id of its own ([`WORD_IDS`] and up), so the viewer's page, thumbnail, search,-//! selection and Read Aloud paths work unchanged: the session sends each call for a Word id here.-//! Its text layer is built from the layout's glyph runs into the PDF engine's [`PageText`], whose-//! search, word and line logic is then shared.+//! engine: opened, laid out into pages, drawn and read the way the viewer reads a PDF (see+//! [`crate::office`]).use std::sync::{Arc, Mutex, MutexGuard, PoisonError};use kurbo::Affine;use pdfcraft_render::{PageText, TextGlyph};+use wordcraft_engine::Session;use wordcraft_engine::doc::Document;use wordcraft_engine::layout::display::{DisplayOptions, Draw, page_display};use wordcraft_engine::layout::{DocLayout, Page};use wordcraft_engine::render::RenderOptions;+use crate::office::{ASCENT, DESCENT, OfficeDoc, is_web_link, text_glyph};use crate::{DocumentInfo, DocumentKind, LinkInfo, MobileError, PageInfo, RenderedImage, TileRect};-/// The first document id given to a Word document: far above the PDF engine's ids (which count up-/// from 1), so the two never meet.-pub(crate) const WORD_IDS: u64 = 1 << 40;--/// The extensions read as Word documents when the bytes alone don't say (an encrypted package is-/// a compound file whatever the application).-const WORD_EXTENSIONS: &[&str] = &["docx", "docm", "dotx", "dotm", "doc", "dot", "odt", "ott", "rtf"];--/// The largest file opened (the PDF side has the same 2 GB bound in its reader).-const MAX_FILE: u64 = 2 << 30;--/// What the bytes of a file are, as far as Word documents go: the extension wordcraft reads it-/// by, or `None` when it is not a Word document (a PDF, or anything else).-pub(crate) fn word_extension(bytes: &[u8], path: &str) -> Option<&'static str> {- let head = bytes.get(..bytes.len().min(1024)).unwrap_or_default();- if head.windows(5).any(|w| w == b"%PDF-") {- return None;- }- let ext = std::path::Path::new(path).extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase);- let named = ext.as_deref().and_then(|e| WORD_EXTENSIONS.iter().find(|w| **w == e).copied());- let contains = |needle: &[u8]| bytes.windows(needle.len()).any(|w| w == needle);- if bytes.starts_with(b"PK\x03\x04") {- // a zip package: its part names are plain text in the local headers and the directory- if contains(b"word/document.xml") {- return Some(match named {- Some(e @ ("docm" | "dotx" | "dotm")) => e,- _ => "docx",- });- }- if contains(b"application/vnd.oasis.opendocument.text") {- return Some(if named == Some("ott") { "ott" } else { "odt" });- }- return None;- }- if bytes.starts_with(&[0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1]) {- // a compound file: a Word 97-2003 document, or a password-protected package- let utf16 = |s: &str| s.encode_utf16().flat_map(u16::to_le_bytes).collect::<Vec<u8>>();- if contains(&utf16("WordDocument")) {- return Some(if named == Some("dot") { "dot" } else { "doc" });- }- if contains(&utf16("EncryptedPackage")) {- return named.filter(|e| matches!(*e, "docx" | "docm" | "dotx" | "dotm"));- }- return None;- }- if head.starts_with(b"{\\rtf") {- return Some("rtf");- }- None-}-/// One open Word document: the engine's session (document, layout, history) and its text layers.pub(crate) struct WordDocument {state: Mutex<WordState>,@@ -108,11 +54,11 @@ fn display_options() -> DisplayOptions {}impl WordDocument {- /// Open the Word document at absolute path `path` (`ext` is what [`word_extension`] found),+ /// Open the Word document at absolute path `path` (`ext` is what [`crate::office::sniff`] found),/// with `password` if it needs one. `locale` (a BCP 47 tag) picks the paper of formats that/// give none.pub(crate) fn open(path: &str, ext: &str, bytes: &[u8], password: Option<&str>, locale: Option<&str>) -> Result<WordDocument, MobileError> {- let name = std::path::Path::new(path).file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| path.to_string());+ let name = crate::office::file_name(path);let region = wordcraft_engine::Region::from_locale_vars(|_| None, || locale.map(str::to_string));// wordcraft picks its reader by the name's extensionlet stem = std::path::Path::new(&name).file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default();@@ -129,15 +75,6 @@ impl WordDocument {Ok(WordDocument { state: Mutex::new(state), texts: Mutex::new((0, Vec::new())) })}- /// Read the file at `path` within the size bound.- pub(crate) fn read(path: &str) -> Result<Vec<u8>, MobileError> {- let size = std::fs::metadata(path).map_err(|e| MobileError::Open(format!("{path}: {e}")))?.len();- if size > MAX_FILE {- return Err(MobileError::Open(format!("{path}: the file is larger than 2 GB")));- }- std::fs::read(path).map_err(|e| MobileError::Open(format!("{path}: {e}")))- }-fn lock(&self) -> MutexGuard<'_, WordState> {self.state.lock().unwrap_or_else(PoisonError::into_inner)}@@ -149,9 +86,10 @@ impl WordDocument {let layout = s.session.layout();(s.session.doc.clone(), layout, s.generation)}+}- /// The document as the viewer's title, menus and properties show it.- pub(crate) fn info(&self, id: u64) -> DocumentInfo {+impl OfficeDoc for WordDocument {+ fn info(&self, id: u64) -> DocumentInfo {let (doc, layout, generation) = self.snapshot();let s = self.lock();let some = |v: &str| (!v.trim().is_empty()).then(|| v.to_string());@@ -189,8 +127,7 @@ impl WordDocument {}}- /// Draw page `page` at `scale` pixels per point: all of it, or `tile` of it (pixels at that scale).- pub(crate) fn render_page(&self, page: u32, scale: f32, tile: Option<TileRect>) -> Result<RenderedImage, MobileError> {+ fn render_page(&self, page: u32, scale: f32, tile: Option<TileRect>) -> Result<RenderedImage, MobileError> {let (doc, layout, _) = self.snapshot();let p = page_of(&layout, page)?;let opts = render_options();@@ -204,8 +141,8 @@ impl WordDocument {Ok(RenderedImage { width: out.width, height: out.height, rgba: out.pixels })}- /// Page `page`'s text layer (built once per document version).- pub(crate) fn page_text(&self, page: u32) -> Result<Arc<PageText>, MobileError> {+ /// Built once per document version.+ fn page_text(&self, page: u32) -> Result<Arc<PageText>, MobileError> {let (doc, layout, generation) = self.snapshot();let p = page_of(&layout, page)?;let mut texts = self.texts.lock().unwrap_or_else(PoisonError::into_inner);@@ -224,8 +161,8 @@ impl WordDocument {Ok(text)}- /// The web and mail links on page `page`: one rectangle per run of linked text.- pub(crate) fn links(&self, page: u32) -> Result<Vec<LinkInfo>, MobileError> {+ /// One rectangle per run of linked text.+ fn links(&self, page: u32) -> Result<Vec<LinkInfo>, MobileError> {let (doc, layout, _) = self.snapshot();let p = page_of(&layout, page)?;let mut out = Vec::new();@@ -233,18 +170,10 @@ impl WordDocument {Ok(out)}- /// Drop the text layers (the system is short of memory); they are built again when needed.- pub(crate) fn release_memory(&self) {+ /// The text layers go; they are built again when needed.+ fn release_memory(&self) {*self.texts.lock().unwrap_or_else(PoisonError::into_inner) = (0, Vec::new());}-- /// Page 1 drawn to fit `max_side` pixels, for file lists.- pub(crate) fn thumbnail(&self, max_side: u32) -> Result<RenderedImage, MobileError> {- let (_, layout, _) = self.snapshot();- let p = layout.pages.first().ok_or_else(|| MobileError::Open("the document has no pages".into()))?;- let scale = (max_side.clamp(16, 2048) as f32 / p.w.max(p.h).max(1.0)).max(0.01);- self.render_page(0, scale, None)- }}fn page_of(layout: &DocLayout, page: u32) -> Result<&Page, MobileError> {@@ -255,11 +184,6 @@ fn page_of(layout: &DocLayout, page: u32) -> Result<&Page, MobileError> {.ok_or_else(|| MobileError::Render(format!("page {} is out of range: the document has {n} pages", u64::from(page) + 1)))}-/// How far above its baseline a glyph's box reaches, and how far below, in ems: the usual-/// ascent and descent of text faces (the box is for highlighting and hit testing, not drawing).-const ASCENT: f32 = 0.8;-const DESCENT: f32 = 0.22;-/// The glyphs of `draws` (and of the groups in them) as text glyphs, in page points. Glyphs that/// show only white space are left out: the text layer puts word spaces back from the gaps./// Known limit: text in turned or rotated boxes is left out of the text layer.@@ -312,8 +236,7 @@ fn run_glyphs(size: f32, glyphs: &[(u32, f32, f32)], text: &str, ranges: &[std::}let next = glyphs.get(i + 1).map(|g| g.1).filter(|n| *n > *x);let x1 = next.unwrap_or(x + average.min(size));- let (y0, y1) = (baseline - size * ASCENT, baseline + size * DESCENT);- out.push(TextGlyph { text: t, rect: [*x, y0, x1, y1], quad: [[*x, y1], [x1, y1], [x1, y0], [*x, y0]], direction: [1.0, 0.0] });+ out.push(text_glyph(t, f64::from(*x), f64::from(x1), f64::from(*baseline), f64::from(size), Affine::IDENTITY));}}@@ -336,34 +259,10 @@ fn collect_links(draws: &[Draw], out: &mut Vec<LinkInfo>) {}}-fn is_web_link(uri: &str) -> bool {- let lower = uri.trim_start().to_ascii_lowercase();- lower.starts_with("http://") || lower.starts_with("https://") || lower.starts_with("mailto:")-}-#[cfg(test)]mod tests {use super::*;- #[test]- fn word_documents_are_told_from_pdfs_by_their_bytes() {- assert_eq!(word_extension(b"%PDF-1.7\n", "/a/Report.docx"), None);- assert_eq!(word_extension(b"PK\x03\x04....word/document.xml....", "/a/Report.pdf"), Some("docx"));- assert_eq!(word_extension(b"PK\x03\x04....word/document.xml....", "/a/Letter.dotx"), Some("dotx"));- assert_eq!(word_extension(b"PK\x03\x04mimetypeapplication/vnd.oasis.opendocument.text", "/a/x"), Some("odt"));- assert_eq!(word_extension(b"PK\x03\x04xl/workbook.xml", "/a/Book.xlsx"), None);- assert_eq!(word_extension(b"{\\rtf1\\ansi hello}", "/a/x.txt"), Some("rtf"));- assert_eq!(word_extension(b"plain words", "/a/notes.docx"), None);- }-- #[test]- fn an_encrypted_package_is_word_only_when_named_so() {- let mut cfb = vec![0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1];- cfb.extend("EncryptedPackage".encode_utf16().flat_map(u16::to_le_bytes));- assert_eq!(word_extension(&cfb, "/a/Locked.docx"), Some("docx"));- assert_eq!(word_extension(&cfb, "/a/Locked.xlsx"), None);- }-#[test]fn glyph_texts_follow_the_byte_ranges() {assert_eq!(glyph_texts(3, "abc", &[0..1, 1..2, 2..3]), ["a", "b", "c"]);diff --git a/engine/vendor/README.md b/engine/vendor/README.mdindex f246641..35a89e5 100644--- a/engine/vendor/README.md+++ b/engine/vendor/README.md@@ -123,3 +123,12 @@ is pinned to (`engine/Cargo.toml`). Their upstream manifests are kept as `Cargo.code. Without it `packs::Cancel` is the flag the web build already used and `use_font_store` isgone. Covered by the dependency tree: `cargo tree -p artefact-mobile --target aarch64-linux-android`lists no `ureq`, `rustls` or `ring`.++## DeckCraft (presentations)++`deckcraft-fonts` is storytold/deckcraft's `crates/fonts` at+`159ed07eb3f0522a5dc97d7cf1858242a6638659` (the revision `deckcraft-model`, `-pptx` and `-render` are+pinned to), with the same Android font-folder patch as `wordcraft-fonts` in `system_font_dirs()`+(marked `Artefact patch:`; drafted in `docs/upstream/wordcraft-android.md`). It is a+`[patch."https://github.com/storytold/deckcraft"]` entry. Its last-resort face is Ubuntu Light from+`epaint_default_fonts` 0.37 (crates.io). No deckcraft engine, media or PDF crate is in the build.diff --git a/engine/vendor/deckcraft-fonts/Cargo.toml b/engine/vendor/deckcraft-fonts/Cargo.tomlnew file mode 100644index 0000000..a2305b3--- /dev/null+++ b/engine/vendor/deckcraft-fonts/Cargo.toml@@ -0,0 +1,19 @@+# Vendored from storytold/deckcraft crates/fonts at 159ed07eb3f0522a5dc97d7cf1858242a6638659+# (Cargo.toml.orig is its manifest; the workspace inheritance is written out here).+# Artefact patch: system_font_dirs() also lists Android's font folders (see ../README.md).+[package]+name = "deckcraft-fonts"+version = "0.15.0"+edition = "2024"+license = "MIT OR Apache-2.0"+repository = "https://github.com/storytold/deckcraft"+description = "DeckCraft fonts: font database (craft-fonts + system), substitutes for Office fonts, metrics, outlines, shaping"++[dependencies]+kurbo = { version = "0.13", features = ["serde"] }+skrifa = "0.47"+harfrust = "0.13"+unicode-bidi = "0.3"+log = "0.4"+# Last-resort face only (Ubuntu Light); no UI code.+epaint_default_fonts = "0.37"diff --git a/engine/vendor/deckcraft-fonts/Cargo.toml.orig b/engine/vendor/deckcraft-fonts/Cargo.toml.orignew file mode 100644index 0000000..c4a5a32--- /dev/null+++ b/engine/vendor/deckcraft-fonts/Cargo.toml.orig@@ -0,0 +1,18 @@+[package]+name = "deckcraft-fonts"+version.workspace = true+edition.workspace = true+license.workspace = true+description = "DeckCraft fonts: font database (craft-fonts + system), substitutes for Office fonts, metrics, outlines, shaping"++[lints]+workspace = true++[dependencies]+kurbo = { workspace = true }+skrifa = { workspace = true }+harfrust = { workspace = true }+unicode-bidi = { workspace = true }+log = { workspace = true }+# Last-resort face only (Ubuntu Light); no UI code.+epaint_default_fonts = "0.37"diff --git a/engine/vendor/deckcraft-fonts/LICENSE-APACHE b/engine/vendor/deckcraft-fonts/LICENSE-APACHEnew file mode 100644index 0000000..ade750b--- /dev/null+++ b/engine/vendor/deckcraft-fonts/LICENSE-APACHE@@ -0,0 +1,177 @@++ Apache License+ Version 2.0, January 2004+ http://www.apache.org/licenses/++ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION++ 1. Definitions.++ "License" shall mean the terms and conditions for use, reproduction,+ and distribution as defined by Sections 1 through 9 of this document.++ "Licensor" shall mean the copyright owner or entity authorized by+ the copyright owner that is granting the License.++ "Legal Entity" shall mean the union of the acting entity and all+ other entities that control, are controlled by, or are under common+ control with that entity. For the purposes of this definition,+ "control" means (i) the power, direct or indirect, to cause the+ direction or management of such entity, whether by contract or+ otherwise, or (ii) ownership of fifty percent (50%) or more of the+ outstanding shares, or (iii) beneficial ownership of such entity.++ "You" (or "Your") shall mean an individual or Legal Entity+ exercising permissions granted by this License.++ "Source" form shall mean the preferred form for making modifications,+ including but not limited to software source code, documentation+ source, and configuration files.++ "Object" form shall mean any form resulting from mechanical+ transformation or translation of a Source form, including but+ not limited to compiled object code, generated documentation,+ and conversions to other media types.++ "Work" shall mean the work of authorship, whether in Source or+ Object form, made available under the License, as indicated by a+ copyright notice that is included in or attached to the work+ (an example is provided in the Appendix below).++ "Derivative Works" shall mean any work, whether in Source or Object+ form, that is based on (or derived from) the Work and for which the+ editorial revisions, annotations, elaborations, or other modifications+ represent, as a whole, an original work of authorship. For the purposes+ of this License, Derivative Works shall not include works that remain+ separable from, or merely link (or bind by name) to the interfaces of,+ the Work and Derivative Works thereof.++ "Contribution" shall mean any work of authorship, including+ the original version of the Work and any modifications or additions+ to that Work or Derivative Works thereof, that is intentionally+ submitted to Licensor for inclusion in the Work by the copyright owner+ or by an individual or Legal Entity authorized to submit on behalf of+ the copyright owner. For the purposes of this definition, "submitted"+ means any form of electronic, verbal, or written communication sent+ to the Licensor or its representatives, including but not limited to+ communication on electronic mailing lists, source code control systems,+ and issue tracking systems that are managed by, or on behalf of, the+ Licensor for the purpose of discussing and improving the Work, but+ excluding communication that is conspicuously marked or otherwise+ designated in writing by the copyright owner as "Not a Contribution."++ "Contributor" shall mean Licensor and any individual or Legal Entity+ on behalf of whom a Contribution has been received by Licensor and+ subsequently incorporated within the Work.++ 2. Grant of Copyright License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ copyright license to reproduce, prepare Derivative Works of,+ publicly display, publicly perform, sublicense, and distribute the+ Work and such Derivative Works in Source or Object form.++ 3. Grant of Patent License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ (except as stated in this section) patent license to make, have made,+ use, offer to sell, sell, import, and otherwise transfer the Work,+ where such license applies only to those patent claims licensable+ by such Contributor that are necessarily infringed by their+ Contribution(s) alone or by combination of their Contribution(s)+ with the Work to which such Contribution(s) was submitted. If You+ institute patent litigation against any entity (including a+ cross-claim or counterclaim in a lawsuit) alleging that the Work+ or a Contribution incorporated within the Work constitutes direct+ or contributory patent infringement, then any patent licenses+ granted to You under this License for that Work shall terminate+ as of the date such litigation is filed.++ 4. Redistribution. You may reproduce and distribute copies of the+ Work or Derivative Works thereof in any medium, with or without+ modifications, and in Source or Object form, provided that You+ meet the following conditions:++ (a) You must give any other recipients of the Work or+ Derivative Works a copy of this License; and++ (b) You must cause any modified files to carry prominent notices+ stating that You changed the files; and++ (c) You must retain, in the Source form of any Derivative Works+ that You distribute, all copyright, patent, trademark, and+ attribution notices from the Source form of the Work,+ excluding those notices that do not pertain to any part of+ the Derivative Works; and++ (d) If the Work includes a "NOTICE" text file as part of its+ distribution, then any Derivative Works that You distribute must+ include a readable copy of the attribution notices contained+ within such NOTICE file, excluding those notices that do not+ pertain to any part of the Derivative Works, in at least one+ of the following places: within a NOTICE text file distributed+ as part of the Derivative Works; within the Source form or+ documentation, if provided along with the Derivative Works; or,+ within a display generated by the Derivative Works, if and+ wherever such third-party notices normally appear. The contents+ of the NOTICE file are for informational purposes only and+ do not modify the License. You may add Your own attribution+ notices within Derivative Works that You distribute, alongside+ or as an addendum to the NOTICE text from the Work, provided+ that such additional attribution notices cannot be construed+ as modifying the License.++ You may add Your own copyright statement to Your modifications and+ may provide additional or different license terms and conditions+ for use, reproduction, or distribution of Your modifications, or+ for any such Derivative Works as a whole, provided Your use,+ reproduction, and distribution of the Work otherwise complies with+ the conditions stated in this License.++ 5. Submission of Contributions. Unless You explicitly state otherwise,+ any Contribution intentionally submitted for inclusion in the Work+ by You to the Licensor shall be under the terms and conditions of+ this License, without any additional terms or conditions.+ Notwithstanding the above, nothing herein shall supersede or modify+ the terms of any separate license agreement you may have executed+ with Licensor regarding such Contributions.++ 6. Trademarks. This License does not grant permission to use the trade+ names, trademarks, service marks, or product names of the Licensor,+ except as required for reasonable and customary use in describing the+ origin of the Work and reproducing the content of the NOTICE file.++ 7. Disclaimer of Warranty. Unless required by applicable law or+ agreed to in writing, Licensor provides the Work (and each+ Contributor provides its Contributions) on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or+ implied, including, without limitation, any warranties or conditions+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A+ PARTICULAR PURPOSE. You are solely responsible for determining the+ appropriateness of using or redistributing the Work and assume any+ risks associated with Your exercise of permissions under this License.++ 8. Limitation of Liability. In no event and under no legal theory,+ whether in tort (including negligence), contract, or otherwise,+ unless required by applicable law (such as deliberate and grossly+ negligent acts) or agreed to in writing, shall any Contributor be+ liable to You for damages, including any direct, indirect, special,+ incidental, or consequential damages of any character arising as a+ result of this License or out of the use or inability to use the+ Work (including but not limited to damages for loss of goodwill,+ work stoppage, computer failure or malfunction, or any and all+ other commercial damages or losses), even if such Contributor+ has been advised of the possibility of such damages.++ 9. Accepting Warranty or Additional Liability. While redistributing+ the Work or Derivative Works thereof, You may choose to offer,+ and charge a fee for, acceptance of support, warranty, indemnity,+ or other liability obligations and/or rights consistent with this+ License. However, in accepting such obligations, You may act only+ on Your own behalf and on Your sole responsibility, not on behalf+ of any other Contributor, and only if You agree to indemnify,+ defend, and hold each Contributor harmless for any liability+ incurred by, or claims asserted against, such Contributor by reason+ of your accepting any such warranty or additional liability.++ END OF TERMS AND CONDITIONSdiff --git a/engine/vendor/deckcraft-fonts/LICENSE-MIT b/engine/vendor/deckcraft-fonts/LICENSE-MITnew file mode 100644index 0000000..e503840--- /dev/null+++ b/engine/vendor/deckcraft-fonts/LICENSE-MIT@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2026 ArtCraft Team and the DeckCraft contributors++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/engine/vendor/deckcraft-fonts/NOTICE b/engine/vendor/deckcraft-fonts/NOTICEnew file mode 100644index 0000000..d7fae34--- /dev/null+++ b/engine/vendor/deckcraft-fonts/NOTICE@@ -0,0 +1,105 @@+DeckCraft+Copyright (c) 2026 ArtCraft Team and the DeckCraft contributors.+Licensed under the MIT License or the Apache License, Version 2.0, at your option+(LICENSE-MIT, LICENSE-APACHE).++The ArtCraft name, wordmark and logos in docs/brand/ are trademarks of the ArtCraft Team. They are+not open source and are not covered by the license above; their terms are in+docs/brand/LICENSE-brand.txt.++Third-party material++This product bundles third-party material under its own licenses, listed below. The per-file+list (author, source, license) is in ATTRIBUTION.md.++- Ubuntu Light (via the epaint_default_fonts crate) — Ubuntu Font Licence 1.0.+- Hack, Noto Emoji and the egui emoji icon font (via epaint_default_fonts) — MIT, Bitstream Vera,+ OFL-1.1.+- Builds made with craft-fonts (CRAFT_FONTS_DIR; all official releases) embed the fonts listed in+ ATTRIBUTION.md (Inter, Carlito, Caladea, Liberation, Montserrat, Lato, Open Sans, Roboto,+ Merriweather, Playfair Display, Poppins, Nunito Sans, BIZ UD, Shippori Mincho, Noto Sans+ Arabic, Noto Sans Thai, Noto Sans Georgian, NanumGothic, Noto Sans Symbols, Noto Sans Symbols 2,+ Noto Sans Hebrew) under the SIL Open Font License 1.1; their licence texts ship with release+ packages (the exact font files and OFL texts are retained in craft-fonts releases). Native+ builds may additionally read craft-fonts' separate Simplified Chinese manifest and embed LXGW+ WenKai Lite 1.530 under OFL-1.1; its OFL text ships with release packages, and the exact font+ and licence files are retained in craft-fonts with the LXGW Reserved Font Names. That face is+ not in the web payload.+- Lucide icon paths embedded in crates/engine/src/icon_data.rs (Insert › Icons), release 1.56.0,+ commit 440a1e1dfb1e712505308da46bead3c28b1f1398, https://github.com/lucide-icons/lucide.+ ISC License, Copyright (c) 2026 Lucide Icons and Contributors. Icons Lucide derives from Feather+ are MIT, Copyright (c) 2013-present Cole Bemis; which names those are is the list in Lucide's+ LICENSE at that commit. Among the paths embedded here, the Feather-derived names are arrow-down,+ arrow-left, arrow-right, arrow-up, at-sign, calendar, check, chevron-right, clipboard, clock,+ compass, download, info, key, link, lock, minus, moon, move, music, plus, search, target and x.++ ISC License++ Copyright (c) 2026 Lucide Icons and Contributors++ Permission to use, copy, modify, and/or distribute this software for any+ purpose with or without fee is hereby granted, provided that the above+ copyright notice and this permission notice appear in all copies.++ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES+ WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF+ MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR+ ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES+ WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN+ ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF+ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.++ The MIT License (MIT) (for the Feather-derived icons)++ Copyright (c) 2013-present Cole Bemis++ Permission is hereby granted, free of charge, to any person obtaining a copy+ of this software and associated documentation files (the "Software"), to deal+ in the Software without restriction, including without limitation the rights+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+ copies of the Software, and to permit persons to whom the Software is+ furnished to do so, subject to the following conditions:++ The above copyright notice and this permission notice shall be included in all+ copies or substantial portions of the Software.++ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+ SOFTWARE.++Code dependencies++- symphonia (audio decoding for MP3, AAC, ALAC, FLAC, Vorbis, WAV, AIFF, CAF) is used unmodified+ under the Mozilla Public License 2.0; its source is available at+ https://github.com/pdeljanov/Symphonia.+- The H.264, HEVC, VP9, AV1, Opus, MP4, Matroska and Ogg crates under crates/ are ported from+ FilmCraft (same owner, MIT OR Apache-2.0).++- Krilla 0.8.2 (https://github.com/LaurenzV/krilla) is used through craft-pdf under+ MIT OR Apache-2.0. craft-libs vendors that version with page/surface unwind recovery+ and rejection of serialization after failed cleanup. Its upstream licence files are+ retained in craft-libs/licenses/pdf-writer. Its bundled Compact ICC Profiles by Clinton Ingram+ (https://github.com/saucecontrol/Compact-ICC-Profiles) are CC0-1.0; the profile+ licence is retained in licenses/pdf-writer/LICENSE-ICC.txt and exact files, sources+ and hashes are in ATTRIBUTION.md.+++egui icon font subset (dependency asset)+----------------------------------------+epaint_default_fonts 0.37 embeds egui-icons.ttf, a five-glyph subset of+emoji-icon-font by John Slegers. The full monochrome emoji-icon-font fallback+uses the same MIT license. Upstream license text follows unchanged.++MIT License++Copyright (c) 2014 John Slegers++Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.diff --git a/engine/vendor/deckcraft-fonts/build.rs b/engine/vendor/deckcraft-fonts/build.rsnew file mode 100644index 0000000..a6db31c--- /dev/null+++ b/engine/vendor/deckcraft-fonts/build.rs@@ -0,0 +1,511 @@+//! Optional craft-fonts build input (https://github.com/storytold/craft-fonts, recipe from its+//! `docs/integration.md`). With `CRAFT_FONTS_DIR=<checkout>` the fonts in its+//! `fonts/latin-manifest.txt` (presentation fonts) and `fonts/manifest.txt` are embedded as+//! `CRAFT_FONTS`, Latin first. Native builds additionally read+//! `fonts/simplified-chinese-manifest.txt`; it is optional for ordinary local builds but a required+//! native input (`CRAFT_FONTS_REQUIRED`) fails without it. Unset, `CRAFT_FONTS` is empty. Web+//! (wasm32) builds embed only Inter Regular/Bold (or a supported Variable face) and BIZ UDPGothic+//! Regular, to stay within the web size budget; native builds also carry BIZ UDPGothic Bold.+//! Required builds verify the faces they promise survive exclusion (and, on wasm, the web filter),+//! so a pin without the Latin manifest or the native bold face fails instead of silently dropping+//! them. It only reads the local checkout: no network.+use std::fmt::Write as _;+use std::path::PathBuf;++/// Families DeckCraft never embeds (AGENTS.md §1: no Adobe-authored visual design, and no Noto+/// CJK rebrand of Source Han on any platform).+const EXCLUDED_FAMILIES: &[&str] = &["Source Sans 3", "Source Serif 4", "Source Han Sans", "Source Han Serif"];++/// Reject source families prohibited by the asset policy, including Source Han and every+/// Noto CJK/Serif/Mono CJK variant.+fn is_excluded_family(family: &str) -> bool {+ EXCLUDED_FAMILIES.contains(&family)+ || family.starts_with("Source Han Sans")+ || family.starts_with("Source Han Serif")+ || family.starts_with("Noto Sans CJK")+ || family.starts_with("Noto Serif CJK")+ || family.starts_with("Noto Sans Mono CJK")+}++/// The generated initialisers plus the faces that were actually embedded after exclusion and web+/// filtering. Validation must use the latter, not the raw manifest text.+#[derive(Default)]+struct FontInput {+ source: String,+ faces: Vec<(String, String)>,+}++impl FontInput {+ /// Concatenate another input's generated source and embedded-face list into this one.+ fn append(&mut self, other: Self) {+ self.source.push_str(&other.source);+ self.faces.extend(other.faces);+ }+}++/// Read font-input environment and target architecture, write `craft_fonts.rs`, report font-input+/// failures as warnings unless required, and always fail when the generated file cannot be written.+fn main() {+ println!("cargo::rerun-if-env-changed=CRAFT_FONTS_DIR");+ println!("cargo::rerun-if-env-changed=CRAFT_FONTS_REQUIRED");+ let mut src = String::from("pub static CRAFT_FONTS: &[CraftFont] = &[\n");+ let dir = std::env::var_os("CRAFT_FONTS_DIR").map(PathBuf::from);+ let required = std::env::var_os("CRAFT_FONTS_REQUIRED").is_some();+ let wasm = std::env::var("CARGO_CFG_TARGET_ARCH").is_ok_and(|a| a == "wasm32");+ match input_fonts(dir.as_deref(), wasm, required) {+ Ok(entries) => src.push_str(&entries),+ Err(e) if required => println!("cargo::error={e}"),+ Err(e) => println!("cargo::warning=building without craft-fonts: {e}"),+ }+ src.push_str("];\n");+ let out = PathBuf::from(std::env::var_os("OUT_DIR").unwrap_or_default()).join("craft_fonts.rs");+ if let Err(e) = std::fs::write(&out, src) {+ println!("cargo::error=writing {}: {e}", out.display());+ }+}++/// One `CraftFont { .. }` initialiser per manifest line.+fn input_fonts(dir: Option<&std::path::Path>, wasm: bool, required: bool) -> Result<String, String> {+ load_fonts(dir, wasm, required).map(|input| input.source)+}++/// Use no fonts when the directory is absent unless required; otherwise load the manifests.+fn load_fonts(dir: Option<&std::path::Path>, wasm: bool, required: bool) -> Result<FontInput, String> {+ match dir {+ Some(dir) => craft_fonts(dir, wasm, required),+ None if required => Err("CRAFT_FONTS_REQUIRED is set but CRAFT_FONTS_DIR is missing".into()),+ None => Ok(FontInput::default()),+ }+}++/// Load optional Latin input, required main input, and native-only Chinese input, then validate+/// the promised required faces after filtering.+fn craft_fonts(dir: &std::path::Path, wasm: bool, required: bool) -> Result<FontInput, String> {+ let mut input = FontInput::default();+ // The Latin presentation fonts are optional within craft-fonts (older checkouts lack them).+ // A malformed or incomplete optional manifest is skipped as a unit: the main Japanese/symbol/RTL+ // faces and the native Chinese addition stay usable, and required builds still fail validation.+ let latin = dir.join("fonts/latin-manifest.txt");+ println!("cargo::rerun-if-changed={}", latin.display());+ let latin_exists = match latin.try_exists() {+ Ok(exists) => exists,+ Err(e) if required => return Err(format!("{}: {e}", latin.display())),+ Err(e) => {+ println!("cargo::warning=skipping optional Latin fonts: {}: {e}", latin.display());+ false+ }+ };+ if latin_exists {+ match manifest(dir, &latin, wasm) {+ Ok(entries) => input.append(entries),+ Err(e) if required => return Err(e),+ Err(e) => println!("cargo::warning=skipping optional Latin fonts: {e}"),+ }+ }+ input.append(manifest(dir, &dir.join("fonts/manifest.txt"), wasm)?);+ // Native consumers opt in; older craft-fonts checkouts need not carry this manifest.+ // An invalid optional addition must never discard the main Japanese/symbol/RTL faces.+ if !wasm {+ let chinese = dir.join("fonts/simplified-chinese-manifest.txt");+ println!("cargo::rerun-if-changed={}", chinese.display());+ let exists = match chinese.try_exists() {+ Ok(exists) => exists,+ Err(e) if required => return Err(format!("{}: {e}", chinese.display())),+ Err(e) => {+ println!("cargo::warning=skipping optional Chinese fonts: {}: {e}", chinese.display());+ false+ }+ };+ if exists {+ match manifest(dir, &chinese, false) {+ Ok(entries) => input.append(entries),+ Err(e) if required => return Err(e),+ Err(e) => println!("cargo::warning=skipping optional Chinese fonts: {e}"),+ }+ } else if required {+ // A required native font input that silently lacks the reviewed Chinese manifest+ // would make the Chinese UI/canvas test pass only by skipping.+ return Err(format!("{}: CRAFT_FONTS_REQUIRED is set but the simplified-Chinese font manifest is missing", chinese.display()));+ }+ }+ if required {+ validate_required_faces(&input.faces, wasm)?;+ }+ Ok(input)+}++/// Parse one manifest, reject malformed rows, exclude banned families, apply the wasm filter,+/// canonicalise assets, and emit initialisers.+fn manifest(dir: &std::path::Path, manifest: &std::path::Path, wasm: bool) -> Result<FontInput, String> {+ println!("cargo::rerun-if-changed={}", manifest.display());+ let text = std::fs::read_to_string(manifest).map_err(|e| format!("{}: {e}", manifest.display()))?;+ let mut input = FontInput::default();+ for line in text.lines().map(str::trim).filter(|l| !l.is_empty() && !l.starts_with('#')) {+ let f: Vec<&str> = line.split(" | ").map(str::trim).collect();+ let [family, style, file, scripts, ..] = f.as_slice() else {+ return Err(format!("malformed manifest line: {line}"));+ };+ // DeckCraft's asset policy: no Adobe-authored typefaces, even openly licensed ones.+ if is_excluded_family(family) {+ continue;+ }+ if wasm && !matches!((*family, *style), ("BIZ UDPGothic", "Regular") | ("Inter", "Regular" | "Bold" | "Variable")) {+ continue;+ }+ let path = dir.join(file).canonicalize().map_err(|e| format!("{file}: {e}"))?;+ println!("cargo::rerun-if-changed={}", path.display());+ let scripts: Vec<String> = scripts.split(',').map(|s| format!("{:?}", s.trim())).collect();+ input.faces.push(((*family).to_owned(), (*style).to_owned()));+ let _ = writeln!(+ input.source,+ " CraftFont {{ family: {family:?}, style: {style:?}, scripts: &[{}], bytes: include_bytes!({:?}) }},",+ scripts.join(", "),+ path.display().to_string(),+ );+ }+ Ok(input)+}++/// Required builds must actually carry the faces the platform promises: Inter Regular and Bold+/// (or one Variable face) and BIZ UDPGothic Regular everywhere, BIZ UDPGothic Bold natively (the+/// weight-pair metric test relies on it), plus LXGW WenKai Lite Regular for native builds. This+/// runs after exclusion and, on wasm, the web filter, so an absent manifest, empty/all-excluded+/// rows, a wrong-family row or a partial catalog cannot satisfy the gate. Wasm deliberately+/// embeds only BIZ Regular to stay within the web size budget.+fn validate_required_faces(faces: &[(String, String)], wasm: bool) -> Result<(), String> {+ let has = |family: &str, style: &str| faces.iter().any(|(f, s)| f == family && s == style);+ let inter = has("Inter", "Variable") || (has("Inter", "Regular") && has("Inter", "Bold"));+ let biz_regular = has("BIZ UDPGothic", "Regular");+ let biz_bold = wasm || has("BIZ UDPGothic", "Bold");+ let chinese = wasm || has("LXGW WenKai Lite", "Regular");+ let mut missing = Vec::new();+ if !inter {+ missing.push("Inter Regular/Bold (or Inter Variable)");+ }+ if !biz_regular {+ missing.push("BIZ UDPGothic Regular");+ }+ if !biz_bold {+ missing.push("BIZ UDPGothic Bold");+ }+ if !chinese {+ missing.push("LXGW WenKai Lite Regular");+ }+ if missing.is_empty() {+ Ok(())+ } else {+ Err(format!("CRAFT_FONTS_REQUIRED is set but the embedded font set after filtering lacks {}", missing.join(" and ")))+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use std::sync::atomic::{AtomicU64, Ordering};++ static NEXT_FIXTURE: AtomicU64 = AtomicU64::new(0);+ const CHINESE_ROW: &str = "LXGW WenKai Lite | Regular | fonts/fixture.ttf | Hani,Hans | OFL-1.1 | OFL.txt | fixture | https://example.invalid\n";++ struct InputFixture(PathBuf);++ impl InputFixture {+ /// Test helper: create a unique temporary fixture with a main manifest and asset file.+ fn new() -> Self {+ let path = std::env::temp_dir().join(format!("deck-font-input-{}-{}", std::process::id(), NEXT_FIXTURE.fetch_add(1, Ordering::Relaxed)));+ std::fs::create_dir(&path).unwrap();+ std::fs::create_dir(path.join("fonts")).unwrap();+ std::fs::write(path.join("fonts/fixture.ttf"), b"build-input path fixture").unwrap();+ std::fs::write(+ path.join("fonts/manifest.txt"),+ "BIZ UDPGothic | Regular | fonts/fixture.ttf | Jpan,Latn | OFL-1.1 | OFL.txt | fixture | https://example.invalid\n\+ BIZ UDPGothic | Bold | fonts/fixture.ttf | Jpan,Latn | OFL-1.1 | OFL.txt | fixture | https://example.invalid\n",+ )+ .unwrap();+ Self(path)+ }++ /// Test helper: replace the fixture's main manifest contents.+ fn main(&self, text: &str) {+ std::fs::write(self.0.join("fonts/manifest.txt"), text).unwrap();+ }++ /// Test helper: write the fixture's optional Latin manifest.+ fn latin(&self, text: &str) {+ std::fs::write(self.0.join("fonts/latin-manifest.txt"), text).unwrap();+ }++ /// Test helper: remove the optional Latin manifest.+ fn no_latin(&self) {+ let _ = std::fs::remove_file(self.0.join("fonts/latin-manifest.txt"));+ }++ /// Test helper: install a valid Inter Regular/Bold Latin manifest.+ fn valid_latin(&self) {+ self.latin(+ "Inter | Regular | fonts/fixture.ttf | Latn | OFL-1.1 | OFL.txt | fixture | https://example.invalid\n\+ Inter | Bold | fonts/fixture.ttf | Latn | OFL-1.1 | OFL.txt | fixture | https://example.invalid\n",+ );+ }++ /// Test helper: write the optional native Chinese manifest with the supplied rows.+ fn optional(&self, text: &str) {+ std::fs::write(self.0.join("fonts/simplified-chinese-manifest.txt"), text).unwrap();+ }+ }++ impl Drop for InputFixture {+ /// Test helper: best-effort removal of the temporary fixture directory.+ fn drop(&mut self) {+ let _ = std::fs::remove_dir_all(&self.0);+ }+ }++ /// A required build without a font directory fails; an optional build embeds no fonts.+ #[test]+ fn required_input_cannot_silently_disappear() {+ assert!(input_fonts(None, false, true).unwrap_err().contains("CRAFT_FONTS_DIR"));+ assert_eq!(input_fonts(None, false, false).unwrap(), "");+ }++ /// A malformed optional Chinese manifest, or one naming a missing asset, leaves the main catalog+ /// unchanged in optional builds, while a required build fails.+ #[test]+ fn broken_optional_manifest_preserves_the_main_fonts() {+ let fixture = InputFixture::new();+ let main = input_fonts(Some(&fixture.0), false, false).unwrap();+ fixture.optional("malformed row");+ assert_eq!(input_fonts(Some(&fixture.0), false, false).unwrap(), main);+ assert!(input_fonts(Some(&fixture.0), false, true).is_err());+ fixture.optional("LXGW WenKai Lite | Regular | missing.ttf | Hani,Hans | OFL-1.1 | OFL.txt | fixture | https://example.invalid");+ assert_eq!(input_fonts(Some(&fixture.0), false, false).unwrap(), main);+ assert!(input_fonts(Some(&fixture.0), false, true).is_err());+ }++ /// Adding or breaking native Chinese input must not change the wasm font initialiser bytes.+ #[test]+ fn native_opt_in_does_not_change_wasm_embedded_bytes() {+ let fixture = InputFixture::new();+ fixture.valid_latin();+ let before = input_fonts(Some(&fixture.0), true, true).unwrap();+ fixture.optional(CHINESE_ROW);+ let native = input_fonts(Some(&fixture.0), false, true).unwrap();+ assert!(native.contains("LXGW WenKai Lite"));+ assert_eq!(input_fonts(Some(&fixture.0), true, true).unwrap(), before);+ fixture.optional("malformed row");+ assert_eq!(input_fonts(Some(&fixture.0), true, true).unwrap(), before);+ }++ /// Required native builds fail without the Chinese manifest; optional native and wasm builds+ /// stay valid.+ #[test]+ fn required_native_input_requires_the_chinese_manifest() {+ let fixture = InputFixture::new();+ fixture.valid_latin();+ assert!(input_fonts(Some(&fixture.0), false, true).unwrap_err().contains("simplified-Chinese"));+ // Optional native builds and wasm keep working without it.+ assert!(input_fonts(Some(&fixture.0), false, false).is_ok());+ assert!(input_fonts(Some(&fixture.0), true, true).is_ok());+ }++ /// Every prohibited Source Han/Noto CJK family is excluded while permitted CJK, Latin, and+ /// Hebrew faces survive.+ #[test]+ fn all_noto_cjk_families_are_excluded_from_every_platform() {+ for family in [+ "Noto Sans CJK SC",+ "Noto Sans CJK TC",+ "Noto Sans CJK JP",+ "Noto Sans CJK KR",+ "Noto Sans CJK HK",+ "Noto Serif CJK SC",+ "Noto Serif CJK JP",+ "Noto Sans Mono CJK SC",+ "Source Han Sans SC",+ "Source Han Serif JP",+ ] {+ assert!(is_excluded_family(family), "{family} would be embedded");+ }+ for family in ["LXGW WenKai Lite", "Noto Sans Hebrew", "Inter", "Noto Sans Symbols 2"] {+ assert!(!is_excluded_family(family), "{family} is an allowed input");+ }+ let fixture = InputFixture::new();+ fixture.valid_latin();+ let mut rows = String::from(CHINESE_ROW);+ for family in ["Noto Sans CJK SC", "Noto Serif CJK JP", "Noto Sans Mono CJK KR"] {+ rows.push_str(&format!("{family} | Regular | fonts/fixture.ttf | Hani | OFL-1.1 | OFL.txt | fixture | https://example.invalid\n"));+ }+ fixture.optional(&rows);+ let native = input_fonts(Some(&fixture.0), false, true).unwrap();+ assert!(!native.contains("Noto Sans CJK") && !native.contains("Noto Serif CJK") && !native.contains("Noto Sans Mono CJK"));+ assert!(native.contains("BIZ UDPGothic"), "the allowed main manifest is retained");+ assert!(native.contains("LXGW WenKai Lite"), "the valid Chinese row is retained");+ }++ /// A required native Chinese manifest must embed LXGW WenKai Lite Regular, not merely list a+ /// nonempty manifest.+ #[test]+ fn required_native_chinese_manifest_must_emit_the_reviewed_face() {+ let fixture = InputFixture::new();+ fixture.valid_latin();+ let excluded = "Noto Sans CJK SC | Regular | fonts/fixture.ttf | Hani | OFL-1.1 | OFL.txt | fixture | https://example.invalid\n\+ Noto Serif CJK JP | Regular | fonts/fixture.ttf | Hani | OFL-1.1 | OFL.txt | fixture | https://example.invalid\n";+ let wrong_family = "LXGW WenKai | Regular | fonts/fixture.ttf | Hani,Hans | OFL-1.1 | OFL.txt | fixture | https://example.invalid\n";+ for rows in ["", excluded, wrong_family] {+ fixture.optional(rows);+ let e = input_fonts(Some(&fixture.0), false, true).unwrap_err();+ assert!(e.contains("LXGW WenKai Lite Regular"), "rows={rows:?}: {e}");+ assert!(input_fonts(Some(&fixture.0), false, false).is_ok(), "optional builds still preserve the valid core");+ }+ fixture.optional(CHINESE_ROW);+ let native = input_fonts(Some(&fixture.0), false, true).unwrap();+ assert!(native.contains("CraftFont { family: \"LXGW WenKai Lite\", style: \"Regular\""), "{native}");+ assert!(native.contains("BIZ UDPGothic") && native.contains("Inter"), "the rest of the required catalog is retained");+ }++ /// A broken optional Latin manifest is skipped as a unit, preserving main and valid Chinese+ /// faces; required builds still fail.+ #[test]+ fn optional_broken_latin_manifest_is_skipped_without_losing_core_or_chinese() {+ let fixture = InputFixture::new();+ fixture.optional(CHINESE_ROW);+ let missing_asset = "Inter | Regular | fonts/missing.ttf | Latn | OFL-1.1 | OFL.txt | fixture | https://example.invalid\n";+ for latin in [None, Some("malformed row"), Some(missing_asset)] {+ match latin {+ Some(text) => fixture.latin(text),+ None => fixture.no_latin(),+ }+ for wasm in [false, true] {+ let catalog = input_fonts(Some(&fixture.0), wasm, false).unwrap();+ assert!(catalog.contains("BIZ UDPGothic"), "wasm={wasm}: the main manifest is retained");+ assert!(!catalog.contains("Inter"), "wasm={wasm}: the broken Latin manifest is skipped as a unit");+ if !wasm {+ assert!(catalog.contains("LXGW WenKai Lite"), "the valid Chinese addition is retained");+ }+ }+ assert!(input_fonts(Some(&fixture.0), false, true).is_err(), "required builds must not skip the missing required faces");+ }+ }++ /// The reviewed Latin catalog keeps 43 permitted faces plus BIZ and LXGW natively, while wasm+ /// remains a three-face subset.+ #[test]+ fn full_prior_latin_catalog_keeps_permitted_native_families() {+ let fixture = InputFixture::new();+ fixture.latin(include_str!("tests/fixtures/latin-families.txt"));+ fixture.optional(CHINESE_ROW);+ let native = input_fonts(Some(&fixture.0), false, true).unwrap();+ assert_eq!(native.matches("CraftFont {").count(), 46, "43 permitted Latin faces plus BIZ Regular/Bold and LXGW");+ for family in [+ "Carlito",+ "Caladea",+ "Liberation Serif",+ "Montserrat",+ "Lato",+ "Open Sans",+ "Roboto",+ "Merriweather",+ "Playfair Display",+ "Poppins",+ "Nunito Sans",+ ] {+ assert!(native.contains(family), "missing prior presentation family {family}");+ }+ let web = input_fonts(Some(&fixture.0), true, true).unwrap();+ assert_eq!(web.matches("CraftFont {").count(), 3, "Inter Regular/Bold and BIZ only");+ for catalog in [&native, &web] {+ assert!(!catalog.contains("Source Sans 3"));+ assert!(!catalog.contains("Source Serif 4"));+ }+ }++ /// Required builds without the Latin catalog fail because Inter Regular/Bold (or Variable) is+ /// mandatory.+ #[test]+ fn required_builds_need_the_latin_catalog_for_inter() {+ let fixture = InputFixture::new();+ fixture.optional(CHINESE_ROW);+ for wasm in [true, false] {+ let e = input_fonts(Some(&fixture.0), wasm, true).unwrap_err();+ assert!(e.contains("Inter Regular/Bold"), "wasm={wasm}: {e}");+ assert!(input_fonts(Some(&fixture.0), wasm, false).is_ok(), "optional builds still work");+ }+ }++ /// A single Inter weight, non-Inter substitutes, or excluded faces cannot satisfy the required+ /// Inter contract.+ #[test]+ fn required_builds_reject_partial_or_unrelated_faces() {+ let fixture = InputFixture::new();+ fixture.optional(CHINESE_ROW);+ for latin in [+ "Inter | Regular | fonts/fixture.ttf | Latn | OFL-1.1 | OFL.txt | fixture | https://example.invalid\n",+ "Inter | Bold | fonts/fixture.ttf | Latn | OFL-1.1 | OFL.txt | fixture | https://example.invalid\n",+ "Inter | Italic | fonts/fixture.ttf | Latn | OFL-1.1 | OFL.txt | fixture | https://example.invalid\n\+ Inter | SemiBold | fonts/fixture.ttf | Latn | OFL-1.1 | OFL.txt | fixture | https://example.invalid\n",+ "Carlito | Regular | fonts/fixture.ttf | Latn | OFL-1.1 | OFL.txt | fixture | https://example.invalid\n",+ "Source Sans 3 | Regular | fonts/fixture.ttf | Latn | OFL-1.1 | OFL.txt | fixture | https://example.invalid\n\+ Source Sans 3 | Bold | fonts/fixture.ttf | Latn | OFL-1.1 | OFL.txt | fixture | https://example.invalid\n",+ ] {+ fixture.latin(latin);+ for wasm in [true, false] {+ let e = input_fonts(Some(&fixture.0), wasm, true).unwrap_err();+ assert!(e.contains("Inter Regular/Bold"), "wasm={wasm}: {e}");+ assert!(input_fonts(Some(&fixture.0), wasm, false).is_ok(), "optional builds still work");+ }+ }+ }++ /// BIZ UDPGothic Regular is required on every platform; required native builds additionally+ /// need Bold.+ #[test]+ fn required_builds_need_biz_udpgothic_regular() {+ let fixture = InputFixture::new();+ fixture.valid_latin();+ fixture.main(+ "Inter | Regular | fonts/fixture.ttf | Latn | OFL-1.1 | OFL.txt | fixture | https://example.invalid\n\+ Inter | Bold | fonts/fixture.ttf | Latn | OFL-1.1 | OFL.txt | fixture | https://example.invalid\n",+ );+ fixture.optional(CHINESE_ROW);+ for wasm in [true, false] {+ let e = input_fonts(Some(&fixture.0), wasm, true).unwrap_err();+ assert!(e.contains("BIZ UDPGothic Regular"), "wasm={wasm}: {e}");+ if !wasm {+ assert!(e.contains("BIZ UDPGothic Bold"), "native builds need the weight pair: {e}");+ }+ assert!(input_fonts(Some(&fixture.0), wasm, false).is_ok(), "optional builds still work");+ }+ }++ /// Native required builds need the real BIZ Bold face for weight metrics; wasm deliberately+ /// embeds only Regular to stay within its size budget. This pins the contract the engine's+ /// required-build metric pair assertion relies on.+ #[test]+ fn required_native_builds_need_biz_bold_but_wasm_does_not() {+ let fixture = InputFixture::new();+ fixture.valid_latin();+ fixture.optional(CHINESE_ROW);+ fixture.main("BIZ UDPGothic | Regular | fonts/fixture.ttf | Jpan,Latn | OFL-1.1 | OFL.txt | fixture | https://example.invalid\n");+ let e = input_fonts(Some(&fixture.0), false, true).unwrap_err();+ assert!(e.contains("BIZ UDPGothic Bold"), "required native build accepted a Regular-only catalog: {e}");+ let web = input_fonts(Some(&fixture.0), true, true).unwrap();+ assert_eq!(web.matches("CraftFont {").count(), 3, "wasm keeps Inter Regular/Bold and BIZ Regular only");+ }++ /// Required checks accept either static Inter Regular+Bold or a single Variable face, together+ /// with BIZ.+ #[test]+ fn required_builds_accept_static_or_variable_inter_with_biz() {+ let fixture = InputFixture::new();+ fixture.valid_latin();+ fixture.optional(CHINESE_ROW);+ for wasm in [true, false] {+ let static_catalog = input_fonts(Some(&fixture.0), wasm, true).unwrap();+ assert!(static_catalog.contains("Inter") && static_catalog.contains("BIZ UDPGothic"));+ }+ fixture.latin("Inter | Variable | fonts/fixture.ttf | Latn | OFL-1.1 | OFL.txt | fixture | https://example.invalid\n");+ for wasm in [true, false] {+ let variable_catalog = input_fonts(Some(&fixture.0), wasm, true).unwrap();+ assert!(variable_catalog.contains("Inter") && variable_catalog.contains("BIZ UDPGothic"));+ }+ }+}diff --git a/engine/vendor/deckcraft-fonts/src/fallback.rs b/engine/vendor/deckcraft-fonts/src/fallback.rsnew file mode 100644index 0000000..1b67a3f--- /dev/null+++ b/engine/vendor/deckcraft-fonts/src/fallback.rs@@ -0,0 +1,314 @@+//! Font fallback per grapheme cluster, and ligature caret positions.+//!+//! The cascade for a cluster (a base character with its marks, never split across faces) is:+//! 1. the faces the document asks for, in order (the run's slot typeface, then the theme's script+//! font, `a:font[@script="Arab"]`);+//! 2. for scripts with a platform cascade (Arabic, Hebrew, Thai, Devanagari): the craft-fonts face+//! bundled for the script (Noto Naskh Arabic for Arabic), so every machine draws the same; then+//! openly licensed or OS-native families found by name among the installed fonts (no platform+//! API is called); then any installed face covering the cluster;+//! 3. any loaded face (bundled first: Japanese keeps its craft-fonts faces), then the first+//! requested face (drawn as .notdef).++use std::sync::Arc;++use skrifa::raw::TableProvider;++use crate::script::{ScriptTag, script_of};+use crate::{CRAFT_FONTS, FontDb, FontFace};++/// Variation selector 15: text presentation.+const TEXT_SELECTOR: char = '\u{FE0E}';+/// Combining enclosing keycap.+const KEYCAP: char = '\u{20E3}';++/// Characters that never decide a face: they're drawn by whatever face the cluster gets.+fn ignorable(c: char) -> bool {+ c.is_whitespace()+ || c.is_control()+ || matches!(c as u32, 0x200B..=0x200F | 0x202A..=0x202E | 0x2060..=0x2069 | 0xFE00..=0xFE0F | 0xFEFF | 0xE0100..=0xE01EF)+}++/// Is the cluster an emoji drawn in colour: a pictograph that defaults to emoji presentation+/// (Unicode's Emoji_Presentation, including BMP ones such as ⭐ ✅ ☔ ⌚ ⏩), or a sequence with an+/// emoji presentation selector (U+FE0F), a zero-width joiner between pictographs, a skin tone+/// modifier or regional indicators (flags)? Keycaps ("1️⃣") are not: PowerPoint draws them as text+/// (an outlined key), as it draws ♥ ✔ ☎ ⬆ ▶ without a selector.+pub fn is_emoji_cluster(cluster: &[char]) -> bool {+ if cluster.contains(&'\u{FE0E}') || cluster.contains(&'\u{20E3}') {+ return false;+ }+ let pictographic = |c: char| matches!(c as u32, 0x1F000..=0x1FAFF | 0x2600..=0x27BF | 0x2B00..=0x2BFF | 0x2190..=0x21FF | 0x2300..=0x23FF);+ let default_emoji = |c: char| {+ matches!(+ c as u32,+ 0x1F300..=0x1F64F+ | 0x1F680..=0x1F6FF+ | 0x1F900..=0x1F9FF+ | 0x1FA70..=0x1FAFF+ | 0x1F1E6..=0x1F1FF+ | 0x1F004+ | 0x1F0CF+ | 0x1F18E+ | 0x1F191..=0x1F19A+ | 0x1F201+ | 0x1F21A+ | 0x1F22F+ | 0x1F232..=0x1F236+ | 0x1F238..=0x1F23A+ | 0x1F250..=0x1F251+ | 0x231A..=0x231B+ | 0x23E9..=0x23EC+ | 0x23F0+ | 0x23F3+ | 0x25FD..=0x25FE+ | 0x2614..=0x2615+ | 0x2648..=0x2653+ | 0x267F+ | 0x2693+ | 0x26A1+ | 0x26AA..=0x26AB+ | 0x26BD..=0x26BE+ | 0x26C4..=0x26C5+ | 0x26CE+ | 0x26D4+ | 0x26EA+ | 0x26F2..=0x26F3+ | 0x26F5+ | 0x26FA+ | 0x26FD+ | 0x2705+ | 0x270A..=0x270B+ | 0x2728+ | 0x274C+ | 0x274E+ | 0x2753..=0x2755+ | 0x2757+ | 0x2795..=0x2797+ | 0x27B0+ | 0x27BF+ | 0x2B1B..=0x2B1C+ | 0x2B50+ | 0x2B55+ )+ };+ cluster.iter().any(|&c| default_emoji(c))+ || (cluster.contains(&'\u{FE0F}') && cluster.iter().any(|&c| pictographic(c)))+ || (cluster.contains(&'\u{200D}') && cluster.iter().any(|&c| pictographic(c)))+}++/// Does `face` draw every character of the cluster?+pub fn covers_cluster(face: &FontFace, cluster: &[char]) -> bool {+ cluster.iter().all(|c| ignorable(*c) || face.covers(*c))+}++/// Installed families tried by name for a script after the bundled face, before scanning every+/// installed font. Microsoft font names are not listed (AGENTS.md §1.1); an installed one is+/// still used by the scan when nothing earlier covers the cluster.+fn os_families(script: ScriptTag) -> &'static [&'static str] {+ match &script {+ b"Arab" => &["Noto Naskh Arabic", "Noto Sans Arabic", "Geeza Pro", "SF Arabic", "DejaVu Sans"],+ b"Hebr" => &["Noto Sans Hebrew", "Arial Hebrew", "SF Hebrew", "DejaVu Sans"],+ b"Thai" => &["Noto Sans Thai", "Thonburi"],+ b"Deva" => &["Noto Sans Devanagari", "Kohinoor Devanagari", "Devanagari Sangam MN"],+ _ => &[],+ }+}++/// The craft-fonts families for a script (manifest order), e.g. Noto Naskh Arabic for `Arab`.+pub fn bundled_families(script: ScriptTag) -> Vec<&'static str> {+ let tag = std::str::from_utf8(&script).unwrap_or("");+ let mut v: Vec<&'static str> = CRAFT_FONTS.iter().filter(|f| f.scripts.contains(&tag)).map(|f| f.family).collect();+ v.dedup();+ v+}++impl FontDb {+ /// The face for one grapheme cluster: the first of `chain` that draws all of it, else the+ /// bundled face for its script, else an installed face for the script, else any loaded+ /// face that draws it, else `chain[0]` (or the default face if `chain` is empty).+ pub fn cascade(&self, cluster: &[char], chain: &[Arc<FontFace>], style: &str) -> Arc<FontFace> {+ // Emoji take a colour face (with its ZWJ sequences, skin tones and flags) before the+ // document's fonts, as PowerPoint draws them, even when a text font has a plain glyph.+ if is_emoji_cluster(cluster) {+ if let Some(f) = chain.iter().find(|f| f.is_color() && covers_cluster(f, cluster)) {+ return f.clone();+ }+ if let Some(key) = cluster.iter().copied().find(|c| !ignorable(*c))+ && let Some(f) = self.color_face_for(key, cluster)+ {+ return f;+ }+ }+ if let Some(f) = chain.iter().find(|f| covers_cluster(f, cluster)) {+ return f.clone();+ }+ // Text presentation (U+FE0E) and keycaps: a plain face, not a colour emoji one.+ let text_style = cluster.contains(&TEXT_SELECTOR) || cluster.contains(&KEYCAP);+ if text_style+ && let Some(key) = cluster.iter().copied().find(|c| !ignorable(*c))+ && let Some(f) = self.plain_face_for(key, cluster)+ {+ return f;+ }+ let first = || chain.first().cloned().unwrap_or_else(|| self.face(crate::DEFAULT_FAMILY, style));+ let Some(key) = cluster.iter().copied().find(|c| !ignorable(*c)) else { return first() };+ let script = cluster.iter().find_map(|c| script_of(*c));+ // Scripts with a platform cascade (Arabic, Hebrew, Thai, Devanagari): the bundled face,+ // then installed ones; the others keep the loaded-faces-first order (Japanese documents+ // prefer the bundled craft-fonts faces).+ if let Some(s) = script.filter(|s| !os_families(*s).is_empty()) {+ let bundled = bundled_families(s);+ for fam in &bundled {+ let f = self.face(fam, style);+ if f.family.eq_ignore_ascii_case(fam) && covers_cluster(&f, cluster) {+ return f;+ }+ }+ for fam in os_families(s) {+ if bundled.contains(fam) {+ continue;+ }+ if self.is_loaded(fam) || self.has_family(fam) {+ let f = self.face(fam, style);+ if f.family.eq_ignore_ascii_case(fam) && covers_cluster(&f, cluster) {+ return f;+ }+ }+ }+ #[cfg(not(target_arch = "wasm32"))]+ if let Some(f) = self.system_face_for(key, cluster, &bundled) {+ return f;+ }+ }+ let exclude = chain.first().map(|f| f.id()).unwrap_or(u32::MAX);+ let f = match self.fallback_for(key, exclude) {+ Some(f) if covers_cluster(&f, cluster) => f,+ Some(f) if chain.iter().all(|c| !c.covers(key)) => f,+ // A letter with marks the run's font lacks (stacked combining marks): a loaded plain+ // face that draws the whole cluster, as PowerPoint draws the marks, before the run's+ // font with missing-glyph boxes.+ _ => {+ // Searched before `first` runs: it may load the default family, which needs the+ // faces' write lock, so the read lock must not be held across it.+ let found = self.read_faces().iter().find(|f| !f.is_color() && covers_cluster(f, cluster)).cloned();+ found.unwrap_or_else(first)+ }+ };+ // A pictograph that defaults to text presentation (⚠ ♥ ⬆ ▶) whose first fallback is the+ // colour emoji font: PowerPoint draws it from a plain symbol font.+ if f.is_color()+ && !is_emoji_cluster(cluster)+ && let Some(plain) = self.plain_face_for(key, cluster)+ {+ return plain;+ }+ f+ }++ /// An installed (non-bundled) face covering the cluster, loading one from the system catalog+ /// if no loaded face does.+ #[cfg(not(target_arch = "wasm32"))]+ fn system_face_for(&self, key: char, cluster: &[char], bundled: &[&str]) -> Option<Arc<FontFace>> {+ let pick = |db: &FontDb| {+ let faces = db.read_faces();+ let mut v: Vec<&Arc<FontFace>> = faces+ .iter()+ .filter(|f| !bundled.iter().any(|b| f.family.eq_ignore_ascii_case(b)) && !CRAFT_FONTS.iter().any(|c| c.family == f.family))+ .filter(|f| covers_cluster(f, cluster))+ .collect();+ v.sort_by_key(|f| (f.italic, (f.weight - 400.0).abs() as i32));+ v.first().map(|f| (*f).clone())+ };+ if let Some(f) = pick(self) {+ return Some(f);+ }+ if self.system_fallback(key) { pick(self) } else { None }+ }+}++/// Most caret records read for one ligature glyph.+const MAX_LIGATURE_CARETS: usize = 64;++/// Caret positions inside a ligature glyph from GDEF `LigCaretList`, in font units from the+/// glyph's origin (sorted ascending). Empty when the font has none for `gid`.+pub fn ligature_carets(face: &FontFace, gid: u32) -> Vec<i32> {+ let Some(font) = face.skrifa() else { return Vec::new() };+ let Ok(gdef) = font.gdef() else { return Vec::new() };+ let Some(Ok(list)) = gdef.lig_caret_list() else { return Vec::new() };+ let Ok(cov) = list.coverage() else { return Vec::new() };+ let Some(idx) = cov.get(skrifa::GlyphId::new(gid)) else { return Vec::new() };+ let Ok(lig) = list.lig_glyphs().get(idx as usize) else { return Vec::new() };+ // The limit applies to the records read, not to the carets kept: a font can list thousands of+ // records it then has to be read through for every ligature laid out.+ let mut out: Vec<i32> = lig+ .caret_values()+ .iter()+ .take(MAX_LIGATURE_CARETS)+ .filter_map(|cv| cv.ok())+ .filter_map(|cv| match cv {+ skrifa::raw::tables::gdef::CaretValue::Format1(f) => Some(f.coordinate() as i32),+ skrifa::raw::tables::gdef::CaretValue::Format3(f) => Some(f.coordinate() as i32),+ // Format 2 is a contour point index; outlines aren't consulted here.+ skrifa::raw::tables::gdef::CaretValue::Format2(_) => None,+ })+ .collect();+ out.sort_unstable();+ out+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn requested_face_wins_when_it_covers() {+ let db = FontDb::global();+ let inter = db.face(crate::DEFAULT_FAMILY, "Regular");+ let f = db.cascade(&['a'], std::slice::from_ref(&inter), "Regular");+ assert!(Arc::ptr_eq(&f, &inter));+ // Spaces and joiners never force a fallback.+ let f = db.cascade(&[' ', '\u{200D}'], std::slice::from_ref(&inter), "Regular");+ assert!(Arc::ptr_eq(&f, &inter));+ // Nothing to go on: the default face.+ assert!(!db.cascade(&[], &[], "Regular").family.is_empty());+ }++ #[test]+ fn arabic_cluster_falls_back_to_an_arabic_face() {+ let db = FontDb::global();+ let inter = db.face(crate::DEFAULT_FAMILY, "Regular");+ let cluster = ['\u{0628}', '\u{064E}']; // beh + fatha: one cluster, one face.+ let f = db.cascade(&cluster, std::slice::from_ref(&inter), "Regular");+ if covers_cluster(&f, &cluster) {+ assert!(f.covers('\u{0628}'));+ } else {+ eprintln!("skipped: no installed or bundled face covers Arabic");+ }+ }++ #[cfg(not(target_arch = "wasm32"))]+ #[test]+ fn falling_back_to_the_default_face_does_not_deadlock() {+ // An empty chain and a character no loaded face draws: the loaded faces are searched,+ // then the default family is looked up, which loads it (taking the faces' write lock).+ // Holding the search's read lock across that lookup hung the thread.+ let (tx, rx) = std::sync::mpsc::channel();+ std::thread::spawn(move || {+ let db = FontDb::with_font_dirs(Vec::new());+ db.set_system_fallback(false);+ let _ = tx.send(db.cascade(&['\u{10FFFD}'], &[], "Regular").family.clone());+ });+ let family = rx.recv_timeout(std::time::Duration::from_secs(30)).expect("cascade did not return");+ assert!(!family.is_empty());+ }++ #[test]+ fn ligature_carets_never_fail() {+ let face = FontDb::global().face(crate::DEFAULT_FAMILY, "Regular");+ for gid in [0, 1, 100, u32::MAX] {+ let c = ligature_carets(&face, gid);+ assert!(c.windows(2).all(|w| w[0] <= w[1]));+ }+ }+}diff --git a/engine/vendor/deckcraft-fonts/src/fontdb.rs b/engine/vendor/deckcraft-fonts/src/fontdb.rsnew file mode 100644index 0000000..3c5aeb0--- /dev/null+++ b/engine/vendor/deckcraft-fonts/src/fontdb.rs@@ -0,0 +1,1753 @@+//! Font database: bundled OFL fonts, user fonts, the installed system fonts (cataloged the first+//! time a lookup needs them, native only), outline cache.++use std::collections::HashMap;+use std::sync::atomic::{AtomicU32, Ordering};+use std::sync::{Arc, Mutex, RwLock};++use kurbo::BezPath;+use skrifa::instance::{Location, LocationRef, Size};+use skrifa::outline::{DrawSettings, OutlinePen};+use skrifa::raw::FileRef;+use skrifa::string::StringId;+use skrifa::{GlyphId, MetadataProvider};++/// The family used when a requested family is unknown and has no substitute.+pub const FALLBACK_FAMILY: &str = "Inter";++/// The always-available last-resort face (Ubuntu Light, compiled in through+/// `epaint_default_fonts`; licence in ATTRIBUTION.md).+pub const LAST_RESORT_FAMILY: &str = "Ubuntu";++/// Compiled-in font files: the craft-fonts faces (Latin presentation fonts, then Japanese;+/// empty without `CRAFT_FONTS_DIR`), then the last-resort face.+pub fn bundled() -> Vec<&'static [u8]> {+ let mut v: Vec<&'static [u8]> = crate::CRAFT_FONTS.iter().map(|f| f.bytes).collect();+ v.push(epaint_default_fonts::UBUNTU_LIGHT);+ v+}++/// Open substitutes for families documents often ask for but we can't ship (metric-compatible+/// where one exists), tried in order after the family itself.+pub fn substitutes(family: &str) -> &'static [&'static str] {+ let f = family.to_ascii_lowercase();+ if is_monospace_family(&f) {+ return &["Liberation Mono", "Courier New", "Menlo", "Courier", "DejaVu Sans Mono"];+ }+ match f.as_str() {+ "calibri" | "calibri light" => &["Carlito", "Liberation Sans", "Arial", "Inter"],+ "cambria" | "cambria math" => &["Caladea", "Liberation Serif", "Times New Roman", "Merriweather"],+ "arial" | "helvetica" | "helvetica neue" | "arial nova" => &["Liberation Sans", "Arial", "Helvetica Neue", "Helvetica", "Inter"],+ "times new roman" | "times" => &["Liberation Serif", "Times New Roman", "Times", "Merriweather"],+ "aptos" | "aptos display" | "aptos narrow" | "segoe ui" | "segoe ui light" | "segoe ui semibold" | "tahoma" | "verdana" => {+ &["Inter", "Helvetica Neue", "Arial", "Liberation Sans"]+ }+ "georgia" | "garamond" | "book antiqua" | "palatino" | "palatino linotype" | "constantia" => &["Merriweather", "Liberation Serif", "Georgia"],+ "century gothic" | "avenir" | "avenir next" | "futura" | "gill sans" | "gill sans mt" | "trebuchet ms" | "corbel" | "candara" => {+ &["Montserrat", "Poppins", "Avenir Next", "Inter"]+ }+ "franklin gothic" | "franklin gothic book" | "franklin gothic medium" | "univers" => &["Open Sans", "Inter"],+ "open sans" | "lato" | "roboto" | "montserrat" | "poppins" | "nunito sans" => &["Inter"],+ "playfair display" | "merriweather" | "source serif 4" | "source serif pro" => &["Merriweather", "Liberation Serif", "Georgia"],+ "source sans 3" | "source sans pro" => &["Open Sans", "Inter"],+ "impact" | "arial black" => &["Montserrat", "Inter"],+ _ => &[],+ }+}++/// Families that are monospaced: when not installed, documents keep a monospaced substitute+/// ([`substitutes`]) so code blocks and columns stay aligned instead of falling back to+/// proportional Calibri.+pub fn is_monospace_family(family: &str) -> bool {+ let f = family.to_ascii_lowercase();+ let s = f.trim();+ if matches!(+ s,+ "courier new"+ | "courier"+ | "cousine"+ | "consolas"+ | "menlo"+ | "monaco"+ | "source code pro"+ | "jetbrains mono"+ | "cascadia code"+ | "cascadia code pl"+ | "cascadia mono"+ | "cascadia mono pl"+ | "fira code"+ | "fira mono"+ | "inconsolata"+ | "dejavu sans mono"+ | "sf mono"+ | "roboto mono"+ | "hack"+ | "ubuntu mono"+ | "pt mono"+ | "liberation mono"+ | "andale mono"+ | "lucida console"+ | "lucida sans typewriter"+ | "fixedsys"+ | "terminal"+ | "monospace"+ | "iosevka"+ | "monolisa"+ | "envy code r"+ | "hasklig"+ ) {+ return true;+ }+ s.starts_with("courier")+ || s.starts_with("consolas")+ || s.starts_with("inconsolata")+ || s.starts_with("iosevka")+ || s.ends_with(" mono")+ || s.ends_with(" code")+ || s.ends_with(" console")+ || s.ends_with(" typewriter")+ || s.ends_with(" monospace")+ || s.split_whitespace().any(|w| w == "mono" || w == "terminal" || w == "monospace")+}++/// Families whose open substitutes ([`substitutes`]) keep their metrics, so text drawn with+/// them breaks into the same lines.+fn has_metric_twin(family: &str) -> bool {+ matches!(+ family.to_ascii_lowercase().as_str(),+ "calibri"+ | "calibri light"+ | "cambria"+ | "cambria math"+ | "arial"+ | "helvetica"+ | "times new roman"+ | "times"+ | "courier new"+ | "courier"+ | "cousine"+ )+}++/// The installed family PowerPoint draws a missing `family` with instead of Calibri: Liberation+/// Sans and Serif as Arial and Times New Roman (observed in PowerPoint; Liberation Mono, Carlito,+/// Caladea, Arimo and Tinos are not mapped and draw in Calibri), and Windows' standard font+/// substitutes (Arial CE, Times New Roman CYR…).+fn office_twin(family: &str) -> Option<&'static str> {+ let f = family.to_ascii_lowercase();+ Some(match f.as_str() {+ "liberation sans" | "helvetica" | "helv" => "Arial",+ "liberation serif" | "times" | "tms rmn" => "Times New Roman",+ _ => {+ let base = f+ .strip_suffix(" baltic")+ .or(f.strip_suffix(" ce"))+ .or(f.strip_suffix(" cyr"))+ .or(f.strip_suffix(" greek"))+ .or(f.strip_suffix(" tur"))?;+ match base {+ "arial" => "Arial",+ "courier new" => "Courier New",+ "times new roman" => "Times New Roman",+ _ => return None,+ }+ }+ })+}++/// Office's downloadable (cloud) families: PowerPoint fetches them when a document uses them, so+/// they draw as themselves there, not as Calibri. Without them DeckCraft keeps their closest open+/// substitute ([`substitutes`]; Aptos as Inter).+fn is_office_cloud_font(family: &str) -> bool {+ let f = family.to_ascii_lowercase();+ f.starts_with("aptos") || ["bierstadt", "grandview", "seaford", "skeena", "tenorite"].iter().any(|c| f.starts_with(c))+}++/// The family PowerPoint draws a document's Latin text in when the font it names isn't installed,+/// whatever the theme, `panose` or `pitchFamily` say.+pub const MISSING_FONT_FAMILY: &str = "Calibri";++#[derive(Clone)]+enum FontBytes {+ Static(&'static [u8]),+ Owned(Arc<Vec<u8>>),+}++/// One loaded font face.+pub struct FontFace {+ id: u32,+ /// Typographic family name (e.g. "Source Sans 3").+ pub family: String,+ /// Typographic style name (e.g. "Semibold", "Italic").+ pub style: String,+ /// The Windows (GDI) family and style names (`name` IDs 1 and 2) when the family differs from+ /// the typographic one: "Segoe UI Semibold" / "Regular" for Segoe UI Semibold. Documents name+ /// fonts this way.+ pub legacy: Option<(String, String)>,+ /// usWeightClass-style weight (400 = regular).+ pub weight: f32,+ pub italic: bool,+ bytes: FontBytes,+ index: u32,+ pub upem: f64,+ /// Ascender in font units (positive = up).+ pub ascent: f64,+ /// Descender in font units (positive = down).+ pub descent: f64,+ /// Cap height and x height in font units (estimated from the ascent when the font has no OS/2+ /// values).+ pub cap_height: f64,+ pub x_height: f64,+ /// Where the baseline sits in a line, as a share of the line's height from its top: the+ /// Windows ascent over the Windows ascent plus descent (OS/2 `usWinAscent`/`usWinDescent`),+ /// the split PowerPoint uses (computed by `line_split`).+ pub line_split: f64,+ /// Underline position (top edge, below the baseline) and thickness in font units (`post`+ /// table; 0.1 and 0.05 em when the font has none). PowerPoint draws single underlines there.+ pub underline: (f64, f64),+ /// Strikethrough position (top edge, above the baseline) and thickness in font units (OS/2;+ /// 0.26 and 0.05 em when the font has none). PowerPoint draws single strikethroughs there.+ pub strikeout: (f64, f64),+ pub shaper: harfrust::ShaperData,+ /// Variable fonts: the named instance's axis settings (user units; empty = default instance),+ /// the normalised location and the shaper's view of it.+ pub coords: Vec<([u8; 4], f32)>,+ location: Location,+ pub instance: Option<harfrust::ShaperInstance>,+ /// Basic Multilingual Plane coverage bitset, built on first use.+ bmp: std::sync::OnceLock<Box<[u64]>>,+ /// Colour glyph tables present (`is_color`), looked up on first use.+ color: std::sync::OnceLock<bool>,+}++/// A cheap `Copy` handle to a face. Faces are never unloaded, so the handle lives for the rest of+/// the process; unlike cloning an `Arc`, copying it touches no shared reference count (which made+/// parallel composition scale negatively).+#[derive(Clone, Copy)]+pub struct FaceRef(&'static FontFace);++impl FaceRef {+ /// The handle for a loaded face (memoised per face).+ pub fn of(face: &Arc<FontFace>) -> FaceRef {+ static LEAKED: RwLock<Vec<Option<&FontFace>>> = RwLock::new(Vec::new());+ let id = face.id as usize;+ if let Some(Some(f)) = LEAKED.read().unwrap_or_else(std::sync::PoisonError::into_inner).get(id) {+ return FaceRef(f);+ }+ let mut w = LEAKED.write().unwrap_or_else(std::sync::PoisonError::into_inner);+ if w.len() <= id {+ w.resize(id + 1, None);+ }+ let f: &'static FontFace = w[id].unwrap_or_else(|| {+ let keep: &'static Arc<FontFace> = Box::leak(Box::new(face.clone()));+ keep+ });+ w[id] = Some(f);+ FaceRef(f)+ }+ pub fn get(self) -> &'static FontFace {+ self.0+ }+}++impl std::ops::Deref for FaceRef {+ type Target = FontFace;+ fn deref(&self) -> &FontFace {+ self.0+ }+}++impl std::fmt::Debug for FaceRef {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ self.0.fmt(f)+ }+}++impl PartialEq for FaceRef {+ fn eq(&self, o: &FaceRef) -> bool {+ self.0.id == o.0.id+ }+}++impl std::fmt::Debug for FontFace {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ write!(f, "FontFace({} {})", self.family, self.style)+ }+}++impl FontFace {+ pub fn data(&self) -> &[u8] {+ match &self.bytes {+ FontBytes::Static(b) => b,+ FontBytes::Owned(v) => v.as_slice(),+ }+ }+ pub fn skrifa(&self) -> Option<skrifa::FontRef<'_>> {+ skrifa::FontRef::from_index(self.data(), self.index).ok()+ }+ /// Does the face draw colour glyphs (a `COLR`, `CBDT`, `sbix` or `SVG ` table, as colour emoji+ /// fonts have)?+ pub fn is_color(&self) -> bool {+ *self.color.get_or_init(|| has_color_tables(self.data(), self.index))+ }+ pub fn hb(&self) -> Option<harfrust::FontRef<'_>> {+ harfrust::FontRef::from_index(self.data(), self.index).ok()+ }+ /// Where in the design space glyphs, metrics and outlines come from.+ pub fn location(&self) -> LocationRef<'_> {+ (&self.location).into()+ }+ /// Is this a named instance of a variable font?+ pub fn is_variable(&self) -> bool {+ !self.coords.is_empty()+ }+ /// Face index within the font file (collections); 0 for plain fonts.+ pub fn index(&self) -> u32 {+ self.index+ }+ /// Unique id of this face within the process.+ pub fn id(&self) -> u32 {+ self.id+ }+ /// Does the face map `c` to a glyph?+ pub fn covers(&self, c: char) -> bool {+ let cp = c as u32;+ if cp < 0x1_0000 {+ let bits = self.bmp.get_or_init(|| {+ let mut b = vec![0u64; 1024].into_boxed_slice();+ if let Some(f) = self.skrifa() {+ for (cp, _) in f.charmap().mappings() {+ if cp < 0x1_0000 {+ b[(cp / 64) as usize] |= 1 << (cp % 64);+ }+ }+ }+ b+ });+ return bits[(cp / 64) as usize] & (1 << (cp % 64)) != 0;+ }+ self.skrifa().is_some_and(|f| f.charmap().map(c).is_some())+ }+ /// Units per em.+ pub fn units_per_em(&self) -> f64 {+ self.upem+ }+ /// (ascent, descent) in font units, both positive.+ pub fn vertical_metrics(&self) -> (f64, f64) {+ (self.ascent, self.descent)+ }+ /// Every mapped character and its glyph id, sorted by code point (the Glyphs panel).+ pub fn chars(&self) -> Vec<(char, u32)> {+ let Some(f) = self.skrifa() else { return vec![] };+ let mut v: Vec<(char, u32)> = f.charmap().mappings().filter_map(|(cp, g)| char::from_u32(cp).map(|c| (c, g.to_u32()))).collect();+ v.sort_unstable_by_key(|x| x.0);+ v.dedup_by_key(|x| x.0);+ v+ }+ /// Advance width of glyph `gid` in font units.+ pub fn advance(&self, gid: u32) -> f64 {+ self.skrifa()+ .and_then(|f| f.glyph_metrics(Size::unscaled(), self.location()).advance_width(GlyphId::new(gid)))+ .map(|a| a as f64)+ .unwrap_or(self.upem * 0.5)+ }+ /// Glyph id for `c` (0 = .notdef).+ pub fn glyph_for(&self, c: char) -> u32 {+ self.skrifa().and_then(|f| f.charmap().map(c)).map(|g| g.to_u32()).unwrap_or(0)+ }+}++#[cfg(not(target_arch = "wasm32"))]+#[derive(Clone, Debug)]+struct CatalogEntry {+ family: String,+ style: String,+ path: std::path::PathBuf,+}++/// Process-wide font database.+pub struct FontDb {+ faces: RwLock<Vec<Arc<FontFace>>>,+ outlines: Mutex<OutlineCache>,+ #[cfg(not(target_arch = "wasm32"))]+ catalog: RwLock<Vec<CatalogEntry>>,+ /// The folders the system font scan reads (the platform's font folders for [`FontDb::global`]).+ #[cfg_attr(target_arch = "wasm32", allow(dead_code))]+ font_dirs: Vec<std::path::PathBuf>,+ /// Set once the font folders have been scanned. Lookups by family name wait for the first+ /// scan, so what they find doesn't depend on what ran before them.+ #[cfg(not(target_arch = "wasm32"))]+ cataloged: std::sync::OnceLock<()>,+ /// Families (lower case) whose cataloged files have all been loaded: a family's files load+ /// together, so a lookup never settles for the one face another name loaded ("Segoe UI+ /// Semibold" loads a face of the family "Segoe UI").+ #[cfg(not(target_arch = "wasm32"))]+ loaded_families: Mutex<std::collections::HashSet<String>>,+ /// System fallback state: enabled, and characters no system font covers.+ #[cfg(not(target_arch = "wasm32"))]+ sys: Mutex<SysFallback>,+ /// Held while installed fonts are loaded, so threads that need the same family wait for one+ /// load instead of racing it: what a lookup finds doesn't depend on which thread got there+ /// first.+ #[cfg(not(target_arch = "wasm32"))]+ loading: Mutex<()>,+}++#[cfg(not(target_arch = "wasm32"))]+#[derive(Default)]+struct SysFallback {+ enabled: bool,+ misses: std::collections::HashSet<char>,+}++/// Does face `index` of `data` carry colour glyph tables?+fn has_color_tables(data: &[u8], index: u32) -> bool {+ use skrifa::raw::types::Tag;+ let Ok(f) = skrifa::FontRef::from_index(data, index) else { return false };+ [b"COLR", b"CBDT", b"sbix", b"SVG "].iter().any(|t| f.table_data(Tag::new(t)).is_some())+}++/// Families tried (when installed) for characters the loaded fonts lack: CJK, symbols, emoji.+#[cfg(not(target_arch = "wasm32"))]+const SYSTEM_FALLBACKS: &[&str] = &[+ "Helvetica Neue",+ "Arial",+ "Segoe UI",+ "Noto Sans",+ "DejaVu Sans",+ "PingFang SC",+ "Hiragino Sans",+ "Hiragino Kaku Gothic ProN",+ "Apple SD Gothic Neo",+ "Heiti SC",+ "STHeiti",+ "Microsoft YaHei",+ "Yu Gothic",+ "Malgun Gothic",+ "Noto Sans CJK SC",+ "Noto Sans CJK JP",+ "Arial Unicode MS",+ "Apple Symbols",+ "Segoe UI Symbol",+ "Noto Sans Symbols",+ "Noto Sans Symbols2",+ "Noto Emoji",+ "Segoe UI Emoji",+ "Apple Color Emoji",+ "Noto Color Emoji",+];++static NEXT_ID: AtomicU32 = AtomicU32::new(1);+const OUTLINE_CACHE_MAX: usize = 50_000;+/// Most path elements one glyph outline may expand to. Composite and `VARC` glyphs can draw a+/// shared outline many times over; a glyph past this draws nothing rather than holding megabytes.+const MAX_OUTLINE_ELEMENTS: usize = 1 << 15;+/// Most path elements the outline cache holds across all glyphs (about 230 MB at most) before it+/// starts over: distinct glyph ids can each expand one dense outline.+const OUTLINE_CACHE_MAX_ELEMENTS: usize = 1 << 22;++/// Glyph outlines by (face, glyph), with the path elements they hold.+#[derive(Default)]+struct OutlineCache {+ paths: HashMap<(u32, u32), Arc<BezPath>>,+ elements: usize,+}++impl OutlineCache {+ fn get(&self, key: &(u32, u32)) -> Option<Arc<BezPath>> {+ self.paths.get(key).cloned()+ }++ fn insert(&mut self, key: (u32, u32), path: Arc<BezPath>) {+ let n = path.elements().len();+ if let Some(old) = self.paths.remove(&key) {+ self.elements = self.elements.saturating_sub(old.elements().len());+ }+ if self.paths.len() >= OUTLINE_CACHE_MAX || self.elements.saturating_add(n) > OUTLINE_CACHE_MAX_ELEMENTS {+ self.paths.clear();+ self.elements = 0;+ }+ self.paths.insert(key, path);+ self.elements = self.elements.saturating_add(n);+ }+}++fn name(font: &skrifa::FontRef<'_>, ids: &[StringId]) -> Option<String> {+ ids.iter().find_map(|id| font.localized_strings(*id).english_or_first().map(|s| s.to_string()).filter(|s| !s.is_empty()))+}++/// A face's family and style names (the default instance's style for a variable font).+fn face_names(f: &skrifa::FontRef<'_>) -> Option<(String, String)> {+ let family = name(f, &[StringId::TYPOGRAPHIC_FAMILY_NAME, StringId::FAMILY_NAME])?;+ let style = name(f, &[StringId::TYPOGRAPHIC_SUBFAMILY_NAME, StringId::SUBFAMILY_NAME]).unwrap_or_else(|| "Regular".into());+ Some((family, style))+}++/// A face's Windows (GDI) family and style (`name` IDs 1 and 2) when that family differs from the+/// typographic `family`.+fn legacy_names(f: &skrifa::FontRef<'_>, family: &str) -> Option<(String, String)> {+ let legacy = name(f, &[StringId::FAMILY_NAME])?;+ if legacy.eq_ignore_ascii_case(family) {+ return None;+ }+ Some((legacy, name(f, &[StringId::SUBFAMILY_NAME]).unwrap_or_else(|| "Regular".into())))+}++/// The Windows family and style a variable font's named instance answers to. Windows lists each+/// instance other than Regular, Italic, Bold and Bold Italic as a family of its own, as the+/// family's static files name themselves: "Montserrat ExtraBold" / "Regular" for the ExtraBold+/// instance, "Montserrat ExtraBold" / "Italic" for ExtraBold Italic.+fn instance_legacy_names(family: &str, style: &str) -> Option<(String, String)> {+ if style.contains('{') {+ return None;+ }+ let weight: Vec<&str> = style.split_whitespace().filter(|w| !matches!(norm(w).as_str(), "italic" | "oblique")).collect();+ let weight = weight.join(" ");+ if matches!(norm(&weight).as_str(), "" | "regular" | "bold") {+ return None;+ }+ Some((format!("{family} {weight}"), if style_italic(style) { "Italic" } else { "Regular" }.into()))+}++/// The tables skrifa reads glyph outlines from: `glyf` (TrueType), `CFF `, `CFF2` and `VARC`. For a+/// face with none of them (bitmaps only, or outlines in Apple's `hvgl` table), [`FontDb::outline`]+/// returns an empty path for every glyph.+#[cfg(not(target_arch = "wasm32"))]+const OUTLINE_TABLES: [&[u8; 4]; 4] = [b"glyf", b"CFF ", b"CFF2", b"VARC"];++/// (family, style) of every face in the font file at `path`, reading only its table directories+/// and `name` tables: a scan opens hundreds of font files, many of them megabytes long. A+/// variable font is cataloged under its default style; its named instances appear once it loads.+/// Faces with none of the [`OUTLINE_TABLES`] are left out.+#[cfg(not(target_arch = "wasm32"))]+fn file_face_names(path: &std::path::Path) -> Vec<(String, String)> {+ use std::io::{Read, Seek, SeekFrom};+ /// Caps on what a (possibly damaged) file can make the scan read.+ const MAX_FACES: u32 = 256;+ const MAX_NAME_TABLE: u32 = 1 << 20;+ let Ok(mut file) = std::fs::File::open(path) else { return vec![] };+ let mut read_at = |offset: u64, len: usize| -> Option<Vec<u8>> {+ let mut buf = vec![0; len];+ file.seek(SeekFrom::Start(offset)).ok()?;+ file.read_exact(&mut buf).ok()?;+ Some(buf)+ };+ let be32 = |b: &[u8], at: usize| b.get(at..at + 4).and_then(|s| s.try_into().ok()).map(u32::from_be_bytes);+ let Some(head) = read_at(0, 12) else { return vec![] };+ // A collection lists where each face's table directory starts.+ let starts: Vec<u32> = if head.starts_with(b"ttcf") {+ let n = be32(&head, 8).unwrap_or(0).min(MAX_FACES) as usize;+ read_at(12, n * 4).map(|b| b.as_chunks::<4>().0.iter().map(|c| u32::from_be_bytes(*c)).collect()).unwrap_or_default()+ } else {+ vec![0]+ };+ starts+ .into_iter()+ .filter_map(|start| {+ let dir = read_at(start.into(), 12)?;+ let tables = u16::from_be_bytes(dir.get(4..6)?.try_into().ok()?) as usize;+ let records = read_at(u64::from(start) + 12, tables * 16)?;+ if !records.as_chunks::<16>().0.iter().any(|r| OUTLINE_TABLES.iter().any(|t| r.starts_with(*t))) {+ return None;+ }+ let rec = records.as_chunks::<16>().0.iter().find(|r| r.starts_with(b"name"))?;+ let (offset, len) = (be32(rec, 8)?, be32(rec, 12)?);+ if len > MAX_NAME_TABLE {+ return None;+ }+ let table = read_at(offset.into(), len as usize)?;+ // A one-table font holding just the `name` table, to read it as the font itself would.+ let mut font = Vec::with_capacity(28 + table.len());+ font.extend_from_slice(&0x0001_0000_u32.to_be_bytes());+ font.extend_from_slice(&[0, 1, 0, 16, 0, 0, 0, 0]);+ font.extend_from_slice(b"name");+ for v in [0, 28, len] {+ font.extend_from_slice(&u32::to_be_bytes(v));+ }+ font.extend_from_slice(&table);+ let f = skrifa::FontRef::new(&font).ok()?;+ let (family, style) = face_names(&f)?;+ // Cataloged under its Windows family too, so "Segoe UI Semibold" finds the file.+ let legacy = legacy_names(&f, &family);+ Some(std::iter::once((family, style)).chain(legacy))+ })+ .flatten()+ .collect()+}++/// Folder depth below a font folder that the system scan descends.+#[cfg(not(target_arch = "wasm32"))]+const MAX_SCAN_DEPTH: usize = 12;+/// Directory entries the system scan looks at in all.+#[cfg(not(target_arch = "wasm32"))]+const MAX_SCAN_ENTRIES: usize = 200_000;+/// The largest font file read (the biggest CJK collections are a few hundred MB).+#[cfg(not(target_arch = "wasm32"))]+pub const MAX_FONT_FILE: u64 = 512 << 20;++/// A regular file of a size a font can have.+#[cfg(not(target_arch = "wasm32"))]+fn font_file_ok(meta: &std::fs::Metadata) -> bool {+ meta.is_file() && meta.len() > 12 && meta.len() <= MAX_FONT_FILE+}++/// The platform's font folders (the system's and the user's), scanned by [`FontDb::global`].+/// Empty on wasm.+pub fn system_font_dirs() -> Vec<std::path::PathBuf> {+ let mut dirs: Vec<std::path::PathBuf> = Vec::new();+ if cfg!(target_arch = "wasm32") {+ return dirs;+ }+ let home = std::env::var_os("HOME").map(std::path::PathBuf::from);+ if cfg!(target_os = "macos") {+ dirs.extend(["/System/Library/Fonts", "/Library/Fonts"].map(Into::into));+ if let Some(h) = &home {+ dirs.push(h.join("Library/Fonts"));+ // Fonts Microsoft Office downloads on demand (Aptos…), used where Office put them.+ dirs.push(h.join("Library/Group Containers/UBF8T346G9.Office/FontCache/4/CloudFonts"));+ }+ // Fonts Office installs inside its apps.+ for app in ["Microsoft PowerPoint", "Microsoft Word", "Microsoft Excel"] {+ dirs.push(std::path::PathBuf::from(format!("/Applications/{app}.app/Contents/Resources/DFonts")));+ }+ // Fonts macOS ships as assets (PingFang, Yu Mincho, …): com_apple_MobileAsset_Font<N>.+ for parent in ["/System/Library/AssetsV2", "/System/Library/AssetsV2/PreinstalledAssetsV2/InstallWithOs"] {+ let Ok(entries) = std::fs::read_dir(parent) else { continue };+ for e in entries.flatten() {+ if e.file_name().to_string_lossy().starts_with("com_apple_MobileAsset_Font") {+ dirs.push(e.path());+ }+ }+ }+ } else if cfg!(windows) {+ let root = std::env::var_os("WINDIR").map(std::path::PathBuf::from).unwrap_or_else(|| "C:\\Windows".into());+ dirs.push(root.join("Fonts"));+ if let Some(l) = std::env::var_os("LOCALAPPDATA") {+ let l = std::path::PathBuf::from(l);+ dirs.push(l.join("Microsoft\\Windows\\Fonts"));+ // Fonts Microsoft Office downloads on demand (Aptos…), used where Office put them;+ // DeckCraft never ships or needs them.+ dirs.push(l.join("Microsoft\\FontCache\\4\\CloudFonts"));+ }+ } else if cfg!(target_os = "android") {+ // Artefact patch: Android's font folders (the system's, and the product partition's that+ // some phones add fonts to). The Linux folders, XDG and fontconfig below don't exist there.+ dirs.extend(["/system/fonts", "/product/fonts", "/system/product/fonts"].map(Into::into));+ } else {+ dirs.extend(["/usr/share/fonts", "/usr/local/share/fonts"].map(Into::into));+ if let Some(h) = &home {+ dirs.push(h.join(".fonts"));+ dirs.push(h.join(".local/share/fonts"));+ }+ let env = |k: &str| std::env::var_os(k).map(|v| v.to_string_lossy().into_owned());+ dirs.extend(xdg_font_dirs(env("XDG_DATA_HOME").as_deref(), env("XDG_DATA_DIRS").as_deref(), home.as_deref()));+ // Inside Flatpak the host's fonts are mounted here.+ dirs.extend(["/run/host/fonts", "/run/host/local-fonts", "/run/host/user-fonts"].map(Into::into));+ // Folders fontconfig is configured with (NixOS, Guix, custom setups).+ for conf in fontconfig_files() {+ if let Ok(text) = std::fs::read_to_string(&conf) {+ dirs.extend(fontconfig_dirs(&text, env("XDG_DATA_HOME").as_deref(), home.as_deref()));+ }+ }+ }+ let mut seen = std::collections::HashSet::new();+ dirs.retain(|d| seen.insert(d.clone()));+ dirs+}++/// `<data dir>/fonts` for `XDG_DATA_HOME` (default `~/.local/share`) and each `XDG_DATA_DIRS`+/// entry (default `/usr/local/share:/usr/share`).+fn xdg_font_dirs(data_home: Option<&str>, data_dirs: Option<&str>, home: Option<&std::path::Path>) -> Vec<std::path::PathBuf> {+ let mut v = vec![];+ match data_home.filter(|d| !d.is_empty()) {+ Some(d) => v.push(std::path::Path::new(d).join("fonts")),+ None => {+ if let Some(h) = home {+ v.push(h.join(".local/share/fonts"));+ }+ }+ }+ let dirs = data_dirs.filter(|d| !d.is_empty()).unwrap_or("/usr/local/share:/usr/share");+ v.extend(dirs.split(':').filter(|d| d.starts_with('/')).take(64).map(|d| std::path::Path::new(d).join("fonts")));+ v+}++/// The fontconfig configuration files: `/etc/fonts/fonts.conf` and `/etc/fonts/conf.d/*.conf`.+fn fontconfig_files() -> Vec<std::path::PathBuf> {+ let mut v = vec![std::path::PathBuf::from("/etc/fonts/fonts.conf"), std::path::PathBuf::from("/etc/fonts/local.conf")];+ if let Ok(entries) = std::fs::read_dir("/etc/fonts/conf.d") {+ let mut files: Vec<_> = entries.flatten().map(|e| e.path()).filter(|p| p.extension().is_some_and(|x| x == "conf")).collect();+ files.sort();+ files.truncate(512);+ v.extend(files);+ }+ v+}++/// The `<dir>` folders of a fontconfig file (`prefix="xdg"` is under `XDG_DATA_HOME`, a leading+/// `~` under home; relative and `cachedir` entries are skipped).+fn fontconfig_dirs(text: &str, data_home: Option<&str>, home: Option<&std::path::Path>) -> Vec<std::path::PathBuf> {+ let mut v = vec![];+ let mut rest = text;+ while let Some(start) = rest.find("<dir") {+ let after = &rest[start + 4..];+ // `<dir>` or `<dir …>`, not `<dirname>`.+ if !(after.starts_with('>') || after.starts_with(' ')) {+ rest = after;+ continue;+ }+ let Some(gt) = after.find('>') else { break };+ let attrs = &after[..gt];+ let body = &after[gt + 1..];+ let Some(end) = body.find("</dir>") else { break };+ let path = body[..end].trim();+ rest = &body[end..];+ if attrs.trim_end().ends_with('/') || path.is_empty() || v.len() >= 64 {+ continue;+ }+ let p = if attrs.contains("prefix=\"xdg\"") {+ let base = data_home.filter(|d| !d.is_empty()).map(std::path::PathBuf::from).or_else(|| home.map(|h| h.join(".local/share")));+ base.map(|b| b.join(path))+ } else if let Some(r) = path.strip_prefix("~/") {+ home.map(|h| h.join(r))+ } else if path.starts_with('/') {+ Some(std::path::PathBuf::from(path))+ } else {+ None+ };+ v.extend(p);+ }+ v+}++/// One face found in a font file: index, family, style and (variable fonts) the named instance's+/// axis settings.+type Found = (u32, String, String, Vec<([u8; 4], f32)>);++/// Maximum number of faces we enumerate from a single font collection.+const MAX_COLLECTION_FACES: u32 = 256;+/// Maximum collection entries inspected while looking for distinct table directories.+const MAX_COLLECTION_ENTRIES_SCANNED: u32 = 16_384;+/// Maximum named instances read from a single face.+const MAX_NAMED_INSTANCES_PER_FACE: usize = 1024;+/// Maximum faces (named instances counted separately) enumerated from one font file, across all+/// of a collection's faces: the per-collection and per-face limits multiply, and each face found+/// is then built with its own shaper.+const MAX_ENUMERATED_FACES: usize = 4096;++fn distinct_face_indices(entries: impl IntoIterator<Item = (u32, u32)>) -> Vec<u32> {+ let mut offsets = std::collections::HashSet::new();+ let mut indices = Vec::with_capacity(MAX_COLLECTION_FACES as usize);+ for (index, offset) in entries.into_iter().take(MAX_COLLECTION_ENTRIES_SCANNED as usize) {+ if offsets.insert(offset) {+ indices.push(index);+ if indices.len() == MAX_COLLECTION_FACES as usize {+ break;+ }+ }+ }+ indices+}++fn capped_named_instance_count(count: usize) -> usize {+ count.min(MAX_NAMED_INSTANCES_PER_FACE)+}++/// Parse every face in `data` (a font file or collection); a variable font yields one face per+/// named instance (InDesign lists them as styles).+fn enumerate_faces(data: &[u8]) -> Vec<Found> {+ let indices = match FileRef::new(data) {+ Ok(FileRef::Font(_)) => vec![0],+ Ok(FileRef::Collection(c)) => {+ let entries = (0..c.len().min(MAX_COLLECTION_ENTRIES_SCANNED)).filter_map(|i| {+ let start = 12usize.checked_add((i as usize).checked_mul(4)?)?;+ let end = start.checked_add(4)?;+ let offset = u32::from_be_bytes(data.get(start..end)?.try_into().ok()?);+ Some((i, offset))+ });+ distinct_face_indices(entries)+ }+ Err(_) => Vec::new(),+ };+ let mut out = Vec::new();+ // Named instances read and plain faces kept, across the whole file.+ let mut budget = MAX_ENUMERATED_FACES;+ for i in indices {+ if budget == 0 {+ break;+ }+ let Ok(f) = skrifa::FontRef::from_index(data, i) else { continue };+ let Some((family, style)) = face_names(&f) else { continue };+ let axes = f.axes();+ let mut named = Vec::new();+ let mut seen = std::collections::HashSet::new();+ let instances = f.named_instances();+ for ni in instances.iter().take(capped_named_instance_count(instances.len())) {+ let Some(left) = budget.checked_sub(1) else { break };+ budget = left;+ let Some(style) = name(&f, &[ni.subfamily_name_id()]) else { continue };+ if !seen.insert(style.to_ascii_lowercase()) {+ continue;+ }+ let coords: Vec<([u8; 4], f32)> = axes.iter().zip(ni.user_coords()).map(|(a, v)| (a.tag().to_be_bytes(), v)).collect();+ named.push((i, style, coords));+ }+ if named.is_empty() {+ budget = budget.saturating_sub(1);+ out.push((i, family, style, Vec::new()));+ } else {+ out.extend(named.into_iter().map(|(i, s, c)| (i, family.clone(), s, c)));+ }+ }+ out+}++/// The compiled-in last-resort face, for a database that somehow has no usable faces at all.+pub(crate) fn last_resort_face() -> Arc<FontFace> {+ static FACE: std::sync::OnceLock<Arc<FontFace>> = std::sync::OnceLock::new();+ FACE.get_or_init(|| {+ // The font is compiled in (`include_bytes!`), so parsing it can't depend on input; the+ // `last_resort_face_parses` test proves it on every run.+ #[allow(clippy::expect_used)]+ let face = make_face(FontBytes::Static(epaint_default_fonts::UBUNTU_LIGHT), 0, LAST_RESORT_FAMILY.into(), "Regular".into(), Vec::new())+ .expect("the compiled-in last-resort face parses");+ Arc::new(face)+ })+ .clone()+}++/// The share of a line above the baseline (`FontFace::line_split`): OS/2 `usWinAscent` over+/// `usWinAscent + usWinDescent`, else the ascent over ascent plus descent. Fonts whose Windows+/// extent is huge (Gabriola, Cambria Math: over 1.5 em) get 0.81, where PowerPoint puts their+/// baseline (observed).+fn line_split(f: &skrifa::FontRef, ascent: f64, descent: f64, upem: f64) -> f64 {+ use skrifa::raw::TableProvider;+ let (a, d) = match f.os2() {+ Ok(os2) if os2.us_win_ascent() > 0 => (os2.us_win_ascent() as f64, os2.us_win_descent() as f64),+ _ => (ascent, descent),+ };+ let total = a + d;+ if !total.is_finite() || total <= 0.0 || a < 0.0 || d < 0.0 {+ return 0.8;+ }+ if total > upem * 1.5 { 0.81 } else { (a / total).clamp(0.5, 1.0) }+}++fn make_face(bytes: FontBytes, index: u32, family: String, style: String, coords: Vec<([u8; 4], f32)>) -> Option<FontFace> {+ let data: &[u8] = match &bytes {+ FontBytes::Static(b) => b,+ FontBytes::Owned(v) => v.as_slice(),+ };+ let f = skrifa::FontRef::from_index(data, index).ok()?;+ let settings: Vec<(skrifa::Tag, f32)> = coords.iter().map(|(t, v)| (skrifa::Tag::new(t), *v)).collect();+ let location = if coords.is_empty() { Location::default() } else { f.axes().location(settings.iter().copied()) };+ let m = f.metrics(Size::unscaled(), &location);+ let a = f.attributes();+ let hb = harfrust::FontRef::from_index(data, index).ok()?;+ let shaper = harfrust::ShaperData::new(&hb);+ let instance = (!coords.is_empty())+ .then(|| harfrust::ShaperInstance::from_variations(&hb, settings.iter().map(|(t, v)| harfrust::Variation { tag: *t, value: *v })));+ let axis = |tag: &[u8; 4]| coords.iter().find(|(t, _)| t == tag).map(|(_, v)| *v);+ let weight = axis(b"wght").unwrap_or(if coords.is_empty() { a.weight.value() } else { style_weight(&style) });+ let italic = axis(b"ital")+ .map(|v| v >= 0.5)+ .or(axis(b"slnt").map(|v| v.abs() > 0.1))+ .unwrap_or(!matches!(a.style, skrifa::attribute::Style::Normal) || style_italic(&style));+ let legacy = if coords.is_empty() { legacy_names(&f, &family) } else { instance_legacy_names(&family, &style) };+ Some(FontFace {+ id: NEXT_ID.fetch_add(1, Ordering::Relaxed),+ family,+ style,+ legacy,+ weight,+ italic,+ upem: m.units_per_em.max(1) as f64,+ ascent: m.ascent as f64,+ descent: -(m.descent as f64),+ cap_height: m.cap_height.map(|v| v as f64).filter(|v| *v > 0.0).unwrap_or(m.ascent as f64 * 0.72),+ x_height: m.x_height.map(|v| v as f64).filter(|v| *v > 0.0).unwrap_or(m.ascent as f64 * 0.5),+ line_split: line_split(&f, m.ascent as f64, -(m.descent as f64), m.units_per_em.max(1) as f64),+ underline: underline_metrics(m.underline, m.units_per_em.max(1) as f64),+ strikeout: strikeout_metrics(m.strikeout, m.units_per_em.max(1) as f64),+ shaper,+ coords,+ location,+ instance,+ bytes,+ index,+ bmp: std::sync::OnceLock::new(),+ color: std::sync::OnceLock::new(),+ })+}++/// The underline's top edge below the baseline and its thickness, font units, from the `post`+/// table (its position is the top edge: Arial's -217/2048 is where PowerPoint's underline starts,+/// 10 px below the baseline at 96 pt); fonts without a usable one get 0.1 em and 0.05 em.+fn underline_metrics(d: Option<skrifa::metrics::Decoration>, upem: f64) -> (f64, f64) {+ match d {+ Some(d) if d.thickness > 0.0 && (d.thickness as f64) < upem * 0.3 && (d.offset as f64).abs() < upem * 0.5 => {+ (-(d.offset as f64), d.thickness as f64)+ }+ _ => (upem * 0.1, upem * 0.05),+ }+}++/// The strikethrough's top edge above the baseline and its thickness, font units, from OS/2 (its+/// position is the top edge: Arial's 530/2048 is where PowerPoint's strikethrough starts, 25 px+/// above the baseline at 96 pt); fonts without a usable one get 0.26 em and 0.05 em.+fn strikeout_metrics(d: Option<skrifa::metrics::Decoration>, upem: f64) -> (f64, f64) {+ match d {+ Some(d) if d.thickness > 0.0 && (d.thickness as f64) < upem * 0.3 && d.offset > 0.0 && (d.offset as f64) < upem => {+ (d.offset as f64, d.thickness as f64)+ }+ _ => (upem * 0.26, upem * 0.05),+ }+}++/// The named style part of a style with axis settings (`Bold {wght:650}` → `Bold`).+pub fn base_style(style: &str) -> &str {+ style.split('{').next().unwrap_or(style).trim()+}++fn norm(s: &str) -> String {+ s.chars().filter(|c| c.is_alphanumeric()).flat_map(char::to_lowercase).collect()+}++/// Weight implied by a style name.+fn style_weight(style: &str) -> f32 {+ let s = norm(style);+ const TABLE: &[(&str, f32)] = &[+ ("extralight", 200.0),+ ("ultralight", 200.0),+ ("semibold", 600.0),+ ("demibold", 600.0),+ ("extrabold", 800.0),+ ("ultrabold", 800.0),+ ("hairline", 100.0),+ ("thin", 100.0),+ ("light", 300.0),+ ("medium", 500.0),+ ("bold", 700.0),+ ("black", 900.0),+ ("heavy", 900.0),+ ];+ TABLE.iter().find(|(k, _)| s.contains(k)).map(|(_, w)| *w).unwrap_or(400.0)+}++fn style_italic(style: &str) -> bool {+ let s = norm(style);+ s.contains("italic") || s.contains("oblique") || s == "it"+}++impl FontDb {+ /// A database holding the bundled fonts, then the craft-fonts Japanese faces (Mincho first,+ /// so they are the fallback for Japanese text after the requested and bundled fonts; empty+ /// without `CRAFT_FONTS_DIR`), whose system font scan reads `font_dirs`.+ pub fn with_font_dirs(font_dirs: Vec<std::path::PathBuf>) -> Self {+ let mut faces = Vec::new();+ for data in bundled() {+ for (i, family, style, coords) in enumerate_faces(data) {+ if let Some(f) = make_face(FontBytes::Static(data), i, family, style, coords) {+ faces.push(Arc::new(f));+ }+ }+ }+ Self {+ faces: RwLock::new(faces),+ outlines: Mutex::new(OutlineCache::default()),+ #[cfg(not(target_arch = "wasm32"))]+ catalog: RwLock::new(Vec::new()),+ font_dirs,+ #[cfg(not(target_arch = "wasm32"))]+ cataloged: std::sync::OnceLock::new(),+ #[cfg(not(target_arch = "wasm32"))]+ loaded_families: Mutex::new(std::collections::HashSet::new()),+ #[cfg(not(target_arch = "wasm32"))]+ sys: Mutex::new(SysFallback { enabled: true, ..Default::default() }),+ #[cfg(not(target_arch = "wasm32"))]+ loading: Mutex::new(()),+ }+ }++ /// Enable or disable the lazy system-font fallback for characters the loaded fonts lack+ /// (native only; on by default).+ pub fn set_system_fallback(&self, on: bool) {+ #[cfg(not(target_arch = "wasm32"))]+ {+ self.sys.lock().unwrap_or_else(std::sync::PoisonError::into_inner).enabled = on;+ }+ #[cfg(target_arch = "wasm32")]+ let _ = on;+ }++ /// Process-wide database: the bundled fonts, then the installed system fonts, cataloged the+ /// first time a lookup by family name needs them (or ahead of time by+ /// [`FontDb::scan_in_background`]).+ pub fn global() -> &'static FontDb {+ static DB: std::sync::OnceLock<FontDb> = std::sync::OnceLock::new();+ DB.get_or_init(|| FontDb::with_font_dirs(system_font_dirs()))+ }++ pub(crate) fn read_faces(&self) -> std::sync::RwLockReadGuard<'_, Vec<Arc<FontFace>>> {+ self.faces.read().unwrap_or_else(std::sync::PoisonError::into_inner)+ }++ /// The system font catalog, scanned first if it hasn't been yet.+ #[cfg(not(target_arch = "wasm32"))]+ fn read_catalog(&self) -> std::sync::RwLockReadGuard<'_, Vec<CatalogEntry>> {+ self.ensure_catalog();+ self.catalog.read().unwrap_or_else(std::sync::PoisonError::into_inner)+ }++ /// Family names available (loaded plus cataloged system fonts), sorted and deduplicated.+ pub fn families(&self) -> Vec<String> {+ let mut v: Vec<String> = self.read_faces().iter().map(|f| f.family.clone()).collect();+ #[cfg(not(target_arch = "wasm32"))]+ v.extend(self.read_catalog().iter().map(|c| c.family.clone()));+ v.sort_by_key(|a| a.to_lowercase());+ v.dedup_by(|a, b| a.eq_ignore_ascii_case(b));+ v+ }++ /// Style names available for `family` (Regular first, then by weight).+ pub fn styles(&self, family: &str) -> Vec<String> {+ let mut v: Vec<(bool, f32, String)> = self+ .read_faces()+ .iter()+ .filter(|f| f.family.eq_ignore_ascii_case(family) && !f.style.contains('{'))+ .map(|f| (f.italic, f.weight, f.style.clone()))+ .collect();+ #[cfg(not(target_arch = "wasm32"))]+ for c in self.read_catalog().iter() {+ if c.family.eq_ignore_ascii_case(family) && !v.iter().any(|(_, _, s)| s.eq_ignore_ascii_case(&c.style)) {+ v.push((style_italic(&c.style), style_weight(&c.style), c.style.clone()));+ }+ }+ v.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.total_cmp(&b.1)).then(a.2.cmp(&b.2)));+ v.dedup_by(|a, b| a.2 == b.2);+ v.into_iter().map(|t| t.2).collect()+ }++ /// Add a user font (TTF/OTF/TTC bytes). Returns the number of faces added (0 if unparseable or+ /// every face was already present).+ pub fn add_font(&self, bytes: Vec<u8>) -> usize {+ self.add_fonts(vec![bytes])+ }++ /// Add font files together: lookups see all of their faces or none, never part of a family.+ /// Returns the number of faces added.+ fn add_fonts(&self, files: Vec<Vec<u8>>) -> usize {+ let present = |faces: &[Arc<FontFace>], family: &str, style: &str| {+ faces.iter().any(|f| f.family.eq_ignore_ascii_case(family) && f.style.eq_ignore_ascii_case(style))+ };+ let mut new = Vec::new();+ for bytes in files {+ let data = Arc::new(bytes);+ for (i, family, style, coords) in enumerate_faces(&data) {+ if present(&self.read_faces(), &family, &style) {+ continue;+ }+ if let Some(f) = make_face(FontBytes::Owned(data.clone()), i, family, style, coords) {+ new.push(Arc::new(f));+ }+ }+ }+ let mut faces = self.faces.write().unwrap_or_else(std::sync::PoisonError::into_inner);+ let mut added = 0;+ for f in new {+ // Checked again under the lock: another thread may have added the same face.+ if !present(&faces, &f.family, &f.style) {+ faces.push(f);+ added += 1;+ }+ }+ added+ }++ /// Catalog the installed fonts unless that has been done: the first caller scans the font+ /// folders, any other waits for that scan to finish.+ #[cfg(not(target_arch = "wasm32"))]+ fn ensure_catalog(&self) {+ self.cataloged.get_or_init(|| {+ self.scan_font_dirs();+ });+ }++ /// Catalog the installed fonts on a background thread, so the first lookup by family name+ /// (opening a file, the font menus) doesn't wait for the scan. A no-op once they are+ /// cataloged, and on wasm.+ pub fn scan_in_background(&'static self) {+ #[cfg(not(target_arch = "wasm32"))]+ if self.cataloged.get().is_none() {+ // A failed spawn leaves the scan to the first lookup that needs it.+ let _ = std::thread::Builder::new().name("font-scan".into()).spawn(move || self.ensure_catalog());+ }+ }++ /// Scan the font folders again (fonts installed or removed since), cataloging the faces+ /// found (native only). Font data is loaded when a cataloged family is first resolved.+ /// Returns the number of faces cataloged.+ #[cfg(not(target_arch = "wasm32"))]+ pub fn load_system_fonts(&self) -> usize {+ // Families load again from the new catalog when next looked up.+ self.loaded_families.lock().unwrap_or_else(std::sync::PoisonError::into_inner).clear();+ // The first scan, or a rescan once it is done (never both at once).+ let mut first = None;+ self.cataloged.get_or_init(|| first = Some(self.scan_font_dirs()));+ first.unwrap_or_else(|| self.scan_font_dirs())+ }++ #[cfg(not(target_arch = "wasm32"))]+ fn scan_font_dirs(&self) -> usize {+ let mut found = Vec::new();+ let mut stack: Vec<(std::path::PathBuf, usize)> = self.font_dirs.iter().map(|d| (d.clone(), 0)).collect();+ // Each folder once, however links lead back to it.+ let mut visited = std::collections::HashSet::new();+ let mut entries = 0usize;+ while let Some((d, depth)) = stack.pop() {+ if !visited.insert(std::fs::canonicalize(&d).unwrap_or_else(|_| d.clone())) {+ continue;+ }+ let Ok(rd) = std::fs::read_dir(&d) else { continue };+ for e in rd.flatten() {+ // A link to `/` or a vast tree mustn't turn start-up into a disk crawl.+ entries += 1;+ if entries > MAX_SCAN_ENTRIES {+ log::warn!("font scan stopped after {MAX_SCAN_ENTRIES} entries");+ stack.clear();+ break;+ }+ let p = e.path();+ // Follows links: what matters is what the entry leads to.+ let Ok(meta) = std::fs::metadata(&p) else { continue };+ if meta.is_dir() {+ if depth < MAX_SCAN_DEPTH {+ stack.push((p, depth + 1));+ }+ continue;+ }+ let ext = p.extension().and_then(std::ffi::OsStr::to_str).map(str::to_ascii_lowercase);+ if !matches!(ext.as_deref(), Some("ttf" | "otf" | "ttc" | "otc")) {+ continue;+ }+ // Only regular files: opening a FIFO named like a font blocks until something+ // writes to it (start-up hung), and a device never ends.+ if !font_file_ok(&meta) {+ continue;+ }+ for (family, style) in file_face_names(&p) {+ found.push(CatalogEntry { family, style, path: p.clone() });+ }+ }+ }+ let n = found.len();+ log::debug!("cataloged {n} system font faces");+ *self.catalog.write().unwrap_or_else(std::sync::PoisonError::into_inner) = found;+ n+ }++ /// Load the files of the installed `family` (faces already loaded are kept). Returns whether+ /// it is loaded.+ #[cfg(not(target_arch = "wasm32"))]+ fn load_cataloged(&self, family: &str) -> bool {+ let loading = self.loading.lock().unwrap_or_else(std::sync::PoisonError::into_inner);+ self.load_family(family, &loading)+ }++ /// [`FontDb::load_cataloged`] for a caller already holding `loading`.+ #[cfg(not(target_arch = "wasm32"))]+ fn load_family(&self, family: &str, _loading: &std::sync::MutexGuard<'_, ()>) -> bool {+ // Not skipped when some face of the family is loaded: a lookup by a Windows family name+ // loads only that style's file, and the family's other files must still load later.+ let paths: Vec<std::path::PathBuf> = {+ let cat = self.read_catalog();+ let mut p: Vec<_> = cat.iter().filter(|c| c.family.eq_ignore_ascii_case(family)).map(|c| c.path.clone()).collect();+ p.sort();+ p.dedup();+ p+ };+ self.add_fonts(paths.iter().filter(|p| std::fs::metadata(p).is_ok_and(|m| font_file_ok(&m))).filter_map(|p| std::fs::read(p).ok()).collect());+ self.is_loaded(family)+ }++ /// Resolve a family + style to a face, falling back to the closest style of the family, then to+ /// an open substitute ([`substitutes`]), then to Inter. Installed system fonts are found by name+ /// whatever ran before.+ pub fn face(&self, family: &str, style: &str) -> Arc<FontFace> {+ if let Some(f) = self.try_family(family, style) {+ return f;+ }+ for sub in substitutes(family) {+ if let Some(f) = self.try_family(sub, style) {+ return f;+ }+ }+ for sub in [FALLBACK_FAMILY, "Helvetica Neue", "Arial", "Liberation Sans", "DejaVu Sans", "Segoe UI"] {+ if let Some(f) = self.try_family(sub, style) {+ return f;+ }+ }+ self.find(LAST_RESORT_FAMILY, "Regular")+ .or_else(|| self.find(FALLBACK_FAMILY, "Regular"))+ .or_else(|| self.read_faces().first().cloned())+ .unwrap_or_else(last_resort_face)+ }++ /// The face a document's text in `family` is drawn with, as PowerPoint draws it: the family+ /// when it is installed or bundled, or a metric-compatible stand-in (Carlito for Calibri,+ /// Liberation Sans for Arial…), or the family PowerPoint maps it to (Liberation Sans as Arial,+ /// see `office_twin`); any other missing family is drawn in Calibri (or Carlito).+ /// Monospaced families keep a monospaced substitute instead of falling back to Calibri.+ /// DeckCraft's own default family keeps [`FontDb::face`]'s fallbacks.+ pub fn document_face(&self, family: &str, style: &str) -> Arc<FontFace> {+ if family.eq_ignore_ascii_case(FALLBACK_FAMILY) || has_metric_twin(family) || is_office_cloud_font(family) || self.has_family(family) {+ return self.face(family, style);+ }+ if let Some(twin) = office_twin(family) {+ return self.face(twin, style);+ }+ if is_monospace_family(family) {+ return self.face(family, style);+ }+ self.face(MISSING_FONT_FAMILY, style)+ }++ fn try_family(&self, family: &str, style: &str) -> Option<Arc<FontFace>> {+ // Every installed file of the family first, so the best style is among the candidates. The+ // lock is held while the files load, so another thread looking up the family waits for+ // them rather than finding none and falling back to another family.+ #[cfg(not(target_arch = "wasm32"))]+ {+ let mut loaded = self.loaded_families.lock().unwrap_or_else(std::sync::PoisonError::into_inner);+ let key = family.to_lowercase();+ if !loaded.contains(&key) {+ self.load_cataloged(family);+ loaded.insert(key);+ }+ }+ self.find(family, style)+ }++ /// Is `family` available (loaded, or installed on the system)?+ pub fn has_family(&self, family: &str) -> bool {+ if self.is_loaded(family) {+ return true;+ }+ #[cfg(not(target_arch = "wasm32"))]+ if self.read_catalog().iter().any(|c| c.family.eq_ignore_ascii_case(family)) {+ return true;+ }+ false+ }++ pub(crate) fn is_loaded(&self, family: &str) -> bool {+ self.read_faces()+ .iter()+ .any(|f| f.family.eq_ignore_ascii_case(family) || f.legacy.as_ref().is_some_and(|(lf, _)| lf.eq_ignore_ascii_case(family)))+ }++ /// A variable font's axes: (tag, name, min, default, max), empty for static fonts.+ pub fn axes(&self, family: &str, style: &str) -> Vec<(String, String, f32, f32, f32)> {+ let face = self.face(family, base_style(style));+ let Some(f) = face.skrifa() else { return vec![] };+ f.axes()+ .iter()+ .map(|a| {+ let tag = String::from_utf8_lossy(&a.tag().to_be_bytes()).to_string();+ let name = f.localized_strings(a.name_id()).english_or_first().map(|s| s.to_string()).unwrap_or_else(|| tag.clone());+ (tag, name, a.min_value(), a.default_value(), a.max_value())+ })+ .collect()+ }++ /// `Style {wght:650,wdth:90}`: the named style's font at those axis values, made on first use.+ fn instance(&self, family: &str, style: &str) -> Option<Arc<FontFace>> {+ let open = style.find('{')?;+ let base = self.find(family, style[..open].trim())?;+ let Some(font) = base.skrifa().filter(|f| !f.axes().is_empty()) else { return Some(base) };+ let axis_tags: Vec<[u8; 4]> = font.axes().iter().map(|a| a.tag().to_be_bytes()).collect();+ let mut coords = base.coords.clone();+ for kv in style[open + 1..].trim_end_matches('}').split(',') {+ let (k, v) = kv.split_once(':')?;+ let k = k.trim().as_bytes();+ let v: f32 = v.trim().parse().ok()?;+ if k.len() != 4 {+ return None;+ }+ let tag = [k[0], k[1], k[2], k[3]];+ // A tag the font has no axis for changes nothing; keeping it would grow the list with+ // every distinct tag in the style text.+ if !axis_tags.contains(&tag) {+ continue;+ }+ match coords.iter_mut().find(|(t, _)| *t == tag) {+ Some(c) => c.1 = v,+ None => coords.push((tag, v)),+ }+ }+ let f = make_face(base.bytes.clone(), base.index, base.family.clone(), style.to_string(), coords)?;+ let f = Arc::new(f);+ self.faces.write().unwrap_or_else(std::sync::PoisonError::into_inner).push(f.clone());+ Some(f)+ }++ fn find(&self, family: &str, style: &str) -> Option<Arc<FontFace>> {+ if style.contains('{') {+ {+ let faces = self.read_faces();+ if let Some(f) = faces.iter().find(|f| f.family.eq_ignore_ascii_case(family) && f.style == style) {+ return Some(f.clone());+ }+ }+ return self.instance(family, style);+ }+ let faces = self.read_faces();+ let mut cands: Vec<&Arc<FontFace>> = faces.iter().filter(|f| f.family.eq_ignore_ascii_case(family)).collect();+ let ns = norm(style);+ if cands.is_empty() {+ // A Windows family name ("Segoe UI Semibold", "Arial Black"): its faces, matched by+ // their Windows style ("Regular", "Bold"…).+ cands = faces.iter().filter(|f| f.legacy.as_ref().is_some_and(|(lf, _)| lf.eq_ignore_ascii_case(family))).collect();+ if let Some(f) = cands.iter().find(|f| f.legacy.as_ref().is_some_and(|(_, ls)| norm(ls) == ns)) {+ return Some((*f).clone());+ }+ // Bold of a family that is itself a weight (Semibold, Light): the face, made bolder+ // by the caller, as Windows does, rather than a face of another weight.+ if let Some(f) = cands+ .iter()+ .find(|f| f.legacy.as_ref().is_some_and(|(_, ls)| norm(ls) == norm(if style_italic(style) { "Italic" } else { "Regular" })))+ {+ return Some((*f).clone());+ }+ }+ if cands.is_empty() {+ return None;+ }+ if let Some(f) = cands.iter().find(|f| norm(&f.style) == ns) {+ return Some((*f).clone());+ }+ let (tw, ti) = (style_weight(style), style_italic(style));+ cands+ .iter()+ .min_by(|a, b| {+ let sa = (a.weight - tw).abs() + if a.italic != ti { 1000.0 } else { 0.0 };+ let sb = (b.weight - tw).abs() + if b.italic != ti { 1000.0 } else { 0.0 };+ sa.total_cmp(&sb)+ })+ .map(|f| (*f).clone())+ }++ /// First face (fallback family first, then load order) that covers `c`; on native, system+ /// fonts are cataloged and loaded lazily the first time no loaded face covers a character.+ pub fn fallback_for(&self, c: char, exclude: u32) -> Option<Arc<FontFace>> {+ if let Some(f) = self.loaded_fallback(c, exclude) {+ return Some(f);+ }+ #[cfg(not(target_arch = "wasm32"))]+ if self.system_fallback(c) {+ return self.loaded_fallback(c, exclude);+ }+ None+ }++ /// A covering fallback accepted by the caller (for example, an interface that cannot use+ /// colour or very large faces). Rejected faces do not stop the search for another face.+ /// A policy-specific miss is not stored as a general document-font miss.+ pub fn fallback_for_filtered(&self, c: char, exclude: u32, accept: impl Fn(&FontFace) -> bool) -> Option<Arc<FontFace>> {+ if let Some(f) = self.loaded_fallback_filtered(c, exclude, &accept) {+ return Some(f);+ }+ #[cfg(not(target_arch = "wasm32"))]+ if self.system_fallback_filtered(c, &|f| f.id != exclude && accept(f), false) {+ return self.loaded_fallback_filtered(c, exclude, &accept);+ }+ None+ }++ fn loaded_fallback(&self, c: char, exclude: u32) -> Option<Arc<FontFace>> {+ self.loaded_fallback_filtered(c, exclude, &|_| true)+ }++ fn loaded_fallback_filtered(&self, c: char, exclude: u32, accept: &impl Fn(&FontFace) -> bool) -> Option<Arc<FontFace>> {+ let faces = self.read_faces();+ let mut order: Vec<&Arc<FontFace>> = faces.iter().filter(|f| f.id != exclude).collect();+ order.sort_by_key(|f| (!f.family.eq_ignore_ascii_case(FALLBACK_FAMILY), f.italic, (f.weight - 400.0).abs() as i32));+ order.into_iter().find(|f| f.covers(c) && accept(f)).cloned()+ }++ /// Load a system font covering `c` (preferred fallback families first, then any cataloged+ /// file under 40 MB). Returns true if one was loaded. Misses are remembered.+ #[cfg(not(target_arch = "wasm32"))]+ pub(crate) fn system_fallback(&self, c: char) -> bool {+ self.system_fallback_filtered(c, &|_| true, true)+ }++ #[cfg(not(target_arch = "wasm32"))]+ fn system_fallback_filtered(&self, c: char, accept: &impl Fn(&FontFace) -> bool, remember_miss: bool) -> bool {+ if c.is_control() || c.is_whitespace() {+ return false;+ }+ let seen = self.read_faces().len();+ {+ let sys = self.sys.lock().unwrap_or_else(std::sync::PoisonError::into_inner);+ if !sys.enabled || sys.misses.contains(&c) {+ return false;+ }+ }+ let covered = |db: &FontDb| db.read_faces().iter().any(|f| f.covers(c) && accept(f));+ let cataloged: Vec<String> = self.read_catalog().iter().map(|e| e.family.clone()).collect();+ let loading = self.loading.lock().unwrap_or_else(std::sync::PoisonError::into_inner);+ // Another thread may have loaded a face for `c` (faces are only ever added), or found+ // there is none, while this one waited.+ if self.read_faces().len() != seen && covered(self) {+ return true;+ }+ if self.sys.lock().unwrap_or_else(std::sync::PoisonError::into_inner).misses.contains(&c) {+ return false;+ }+ for fam in SYSTEM_FALLBACKS {+ if !self.is_loaded(fam) && cataloged.iter().any(|f| f.eq_ignore_ascii_case(fam)) {+ self.load_family(fam, &loading);+ if covered(self) {+ return true;+ }+ }+ }+ let mut paths: Vec<std::path::PathBuf> =+ self.catalog.read().unwrap_or_else(std::sync::PoisonError::into_inner).iter().map(|e| e.path.clone()).collect();+ paths.sort();+ paths.dedup();+ for p in paths {+ if std::fs::metadata(&p).map(|m| m.len() > 40 << 20).unwrap_or(true) {+ continue;+ }+ let Ok(data) = std::fs::read(&p) else { continue };+ let hit =+ enumerate_faces(&data).iter().any(|(i, _, _, _)| skrifa::FontRef::from_index(&data, *i).is_ok_and(|f| f.charmap().map(c).is_some()));+ if hit && self.add_font(data) > 0 && covered(self) {+ return true;+ }+ }+ if remember_miss {+ self.sys.lock().unwrap_or_else(std::sync::PoisonError::into_inner).misses.insert(c);+ }+ false+ }++ /// A loaded colour face drawing all of `cluster`, loading an installed colour font that covers+ /// `key` if none is loaded yet. Misses are remembered.+ pub(crate) fn color_face_for(&self, key: char, cluster: &[char]) -> Option<Arc<FontFace>> {+ let pick = |db: &FontDb| {+ let faces = db.read_faces();+ let mut v: Vec<&Arc<FontFace>> = faces.iter().filter(|f| crate::covers_cluster(f, cluster) && f.is_color()).collect();+ v.sort_by_key(|f| (f.italic, (f.weight - 400.0).abs() as i32));+ v.first().map(|f| (*f).clone())+ };+ if let Some(f) = pick(self) {+ return Some(f);+ }+ #[cfg(not(target_arch = "wasm32"))]+ if self.system_color_fallback(key) {+ return pick(self);+ }+ let _ = key;+ None+ }++ /// A loaded plain (not colour) face drawing all of `cluster`, loading an installed plain font+ /// that covers `key` if none is loaded yet. Misses are remembered.+ pub(crate) fn plain_face_for(&self, key: char, cluster: &[char]) -> Option<Arc<FontFace>> {+ // Symbol fonts first (PowerPoint draws ⚠ ♥ ⬆ from the system's symbol font), then the+ // usual fallback families in order, then any other.+ let rank = |f: &FontFace| {+ if f.family.contains("Symbol") {+ return 0;+ }+ #[cfg(not(target_arch = "wasm32"))]+ if let Some(i) = SYSTEM_FALLBACKS.iter().position(|s| s.eq_ignore_ascii_case(&f.family)) {+ return i + 1;+ }+ 1000+ };+ let pick = |db: &FontDb| {+ let faces = db.read_faces();+ let mut v: Vec<&Arc<FontFace>> = faces.iter().filter(|f| !f.is_color() && crate::covers_cluster(f, cluster)).collect();+ v.sort_by_key(|f| (rank(f), f.italic, (f.weight - 400.0).abs() as i32));+ v.first().map(|f| (*f).clone())+ };+ #[cfg(not(target_arch = "wasm32"))]+ {+ let cataloged: Vec<String> = self.read_catalog().iter().map(|e| e.family.clone()).collect();+ for fam in SYSTEM_FALLBACKS.iter().filter(|f| f.contains("Symbol")) {+ if !self.is_loaded(fam) && cataloged.iter().any(|f| f.eq_ignore_ascii_case(fam)) {+ self.load_cataloged(fam);+ }+ }+ }+ if let Some(f) = pick(self) {+ return Some(f);+ }+ #[cfg(not(target_arch = "wasm32"))]+ if self.system_plain_fallback(key) {+ return pick(self);+ }+ let _ = key;+ None+ }++ /// Load an installed font without colour tables covering `c`. True if one was loaded.+ #[cfg(not(target_arch = "wasm32"))]+ fn system_plain_fallback(&self, c: char) -> bool {+ static MISSES: Mutex<Option<std::collections::HashSet<char>>> = Mutex::new(None);+ if c.is_control() || c.is_whitespace() {+ return false;+ }+ if !self.sys.lock().unwrap_or_else(std::sync::PoisonError::into_inner).enabled {+ return false;+ }+ if MISSES.lock().unwrap_or_else(std::sync::PoisonError::into_inner).get_or_insert_with(Default::default).contains(&c) {+ return false;+ }+ let mut paths: Vec<std::path::PathBuf> = self.read_catalog().iter().map(|e| e.path.clone()).collect();+ paths.sort();+ paths.dedup();+ for p in paths {+ if std::fs::metadata(&p).map(|m| m.len() > 40 << 20).unwrap_or(true) {+ continue;+ }+ let Ok(data) = std::fs::read(&p) else { continue };+ let hit = enumerate_faces(&data).iter().any(|(i, _, _, _)| {+ !has_color_tables(&data, *i) && skrifa::FontRef::from_index(&data, *i).is_ok_and(|f| f.charmap().map(c).is_some())+ });+ if hit && self.add_font(data) > 0 {+ return true;+ }+ }+ MISSES.lock().unwrap_or_else(std::sync::PoisonError::into_inner).get_or_insert_with(Default::default).insert(c);+ false+ }++ /// Load an installed colour font covering `c`. True if one was loaded.+ #[cfg(not(target_arch = "wasm32"))]+ fn system_color_fallback(&self, c: char) -> bool {+ static MISSES: Mutex<Option<std::collections::HashSet<char>>> = Mutex::new(None);+ if c.is_control() || c.is_whitespace() {+ return false;+ }+ {+ let sys = self.sys.lock().unwrap_or_else(std::sync::PoisonError::into_inner);+ if !sys.enabled {+ return false;+ }+ }+ if MISSES.lock().unwrap_or_else(std::sync::PoisonError::into_inner).get_or_insert_with(Default::default).contains(&c) {+ return false;+ }+ let mut paths: Vec<std::path::PathBuf> = self.read_catalog().iter().map(|e| e.path.clone()).collect();+ paths.sort();+ paths.dedup();+ for p in paths {+ if std::fs::metadata(&p).map(|m| m.len() > 64 << 20).unwrap_or(true) {+ continue;+ }+ let Ok(data) = std::fs::read(&p) else { continue };+ let hit = enumerate_faces(&data).iter().any(|(i, _, _, _)| {+ has_color_tables(&data, *i) && skrifa::FontRef::from_index(&data, *i).is_ok_and(|f| f.charmap().map(c).is_some())+ });+ if hit && self.add_font(data) > 0 {+ return true;+ }+ }+ MISSES.lock().unwrap_or_else(std::sync::PoisonError::into_inner).get_or_insert_with(Default::default).insert(c);+ false+ }++ /// Glyph outline in font units, y-down (flipped), cached per (face, glyph).+ pub fn outline(&self, face: &FontFace, gid: u32) -> Arc<BezPath> {+ let key = (face.id, gid);+ if let Some(p) = self.outlines.lock().unwrap_or_else(std::sync::PoisonError::into_inner).get(&key) {+ return p;+ }+ let mut pen = FlipPen::new(MAX_OUTLINE_ELEMENTS);+ if let Some(f) = face.skrifa()+ && let Some(g) = f.outline_glyphs().get(GlyphId::new(gid))+ {+ let _ = g.draw(DrawSettings::unhinted(Size::unscaled(), face.location()), &mut pen);+ }+ let p = Arc::new(pen.finish());+ self.outlines.lock().unwrap_or_else(std::sync::PoisonError::into_inner).insert(key, p.clone());+ p+ }+}++/// Collects a glyph outline, y flipped, up to `limit` path elements. Past the limit it ignores+/// what follows and [`FlipPen::finish`] gives an empty path: a cut-off outline would fill wrongly.+struct FlipPen {+ path: BezPath,+ limit: usize,+ over: bool,+}++impl FlipPen {+ fn new(limit: usize) -> Self {+ FlipPen { path: BezPath::new(), limit, over: false }+ }++ /// Room for one more element?+ fn room(&mut self) -> bool {+ if !self.over && self.path.elements().len() >= self.limit {+ self.over = true;+ self.path = BezPath::new();+ }+ !self.over+ }++ fn finish(self) -> BezPath {+ if self.over { BezPath::new() } else { self.path }+ }+}++impl OutlinePen for FlipPen {+ fn move_to(&mut self, x: f32, y: f32) {+ if self.room() {+ self.path.move_to((x as f64, -y as f64));+ }+ }+ fn line_to(&mut self, x: f32, y: f32) {+ if self.room() {+ self.path.line_to((x as f64, -y as f64));+ }+ }+ fn quad_to(&mut self, cx0: f32, cy0: f32, x: f32, y: f32) {+ if self.room() {+ self.path.quad_to((cx0 as f64, -cy0 as f64), (x as f64, -y as f64));+ }+ }+ fn curve_to(&mut self, cx0: f32, cy0: f32, cx1: f32, cy1: f32, x: f32, y: f32) {+ if self.room() {+ self.path.curve_to((cx0 as f64, -cy0 as f64), (cx1 as f64, -cy1 as f64), (x as f64, -y as f64));+ }+ }+ fn close(&mut self) {+ if self.room() {+ self.path.close_path();+ }+ }+}++#[cfg(test)]+mod font_dir_tests {+ use std::path::{Path, PathBuf};++ use super::*;++ #[test]+ fn duplicate_collection_offsets_do_not_consume_face_cap() {+ let mut entries = vec![(0, 7); MAX_COLLECTION_FACES as usize];+ entries.extend((0..MAX_COLLECTION_FACES).map(|i| (i + MAX_COLLECTION_FACES, i + 8)));+ let faces = distinct_face_indices(entries);+ assert_eq!(faces.len(), MAX_COLLECTION_FACES as usize);+ assert_eq!(faces.first(), Some(&0));+ assert_eq!(faces.get(1), Some(&MAX_COLLECTION_FACES));+ assert_eq!(faces.last(), Some(&(MAX_COLLECTION_FACES * 2 - 2)));+ }++ #[test]+ fn named_instance_limit_is_bounded_per_face() {+ assert_eq!(capped_named_instance_count(0), 0);+ assert_eq!(capped_named_instance_count(MAX_NAMED_INSTANCES_PER_FACE), MAX_NAMED_INSTANCES_PER_FACE);+ assert_eq!(capped_named_instance_count(MAX_NAMED_INSTANCES_PER_FACE + 1), MAX_NAMED_INSTANCES_PER_FACE);+ }++ #[test]+ fn faces_of_one_file_are_bounded_across_the_collection() {+ // The per-collection and per-face limits together would allow far more.+ assert!((MAX_COLLECTION_FACES as usize) * MAX_NAMED_INSTANCES_PER_FACE > 16 * MAX_ENUMERATED_FACES);+ for data in bundled() {+ assert!(enumerate_faces(data).len() <= MAX_ENUMERATED_FACES);+ }+ }++ #[test]+ fn an_outline_past_the_element_limit_draws_nothing() {+ let mut pen = FlipPen::new(8);+ pen.move_to(0.0, 0.0);+ pen.line_to(1.0, 1.0);+ pen.close();+ assert_eq!(pen.finish().elements().len(), 3);+ // A shared outline drawn over and over (composite and VARC glyphs).+ let mut pen = FlipPen::new(8);+ for i in 0..1_000_000 {+ pen.move_to(0.0, 0.0);+ pen.line_to(i as f32, 1.0);+ pen.close();+ }+ assert_eq!(pen.path.elements().len(), 0);+ assert!(pen.finish().elements().is_empty());+ }++ #[test]+ fn outline_cache_is_bounded_by_elements() {+ let mut path = BezPath::new();+ path.move_to((0.0, 0.0));+ for i in 1..MAX_OUTLINE_ELEMENTS {+ path.line_to((i as f64, 0.0));+ }+ let path = Arc::new(path);+ let mut cache = OutlineCache::default();+ let glyphs = 4 * OUTLINE_CACHE_MAX_ELEMENTS / MAX_OUTLINE_ELEMENTS;+ for gid in 0..glyphs as u32 {+ cache.insert((1, gid), path.clone());+ assert!(cache.elements <= OUTLINE_CACHE_MAX_ELEMENTS);+ assert_eq!(cache.elements, cache.paths.values().map(|p| p.elements().len()).sum::<usize>());+ }+ assert!(cache.get(&(1, glyphs as u32 - 1)).is_some());+ // Replacing an entry does not count it twice.+ let before = cache.elements;+ cache.insert((1, glyphs as u32 - 1), path.clone());+ assert_eq!(cache.elements, before);+ }++ #[test]+ fn xdg_data_dirs_contribute_their_fonts_folders() {+ let home = Path::new("/home/ann");+ assert_eq!(+ xdg_font_dirs(None, None, Some(home)),+ [home.join(".local/share/fonts"), "/usr/local/share/fonts".into(), "/usr/share/fonts".into()]+ );+ let v = xdg_font_dirs(Some("/data/ann"), Some("/nix/profile/share:relative:/var/lib/flatpak/exports/share"), Some(home));+ assert_eq!(v, [PathBuf::from("/data/ann/fonts"), "/nix/profile/share/fonts".into(), "/var/lib/flatpak/exports/share/fonts".into()]);+ }++ #[test]+ fn fontconfig_dir_entries_are_read() {+ let conf = r#"<?xml version="1.0"?>+<fontconfig>+ <dir>/usr/share/fonts</dir>+ <dir prefix="xdg">fonts</dir>+ <dir>~/.fonts</dir>+ <dir>relative/fonts</dir>+ <cachedir>/var/cache/fontconfig</cachedir>+ <dirname>ignored</dirname>+ <dir>/nix/store/abc-fonts/share/fonts</dir>+</fontconfig>"#;+ let home = Path::new("/home/ann");+ let v = fontconfig_dirs(conf, None, Some(home));+ assert_eq!(+ v,+ [PathBuf::from("/usr/share/fonts"), home.join(".local/share/fonts"), home.join(".fonts"), "/nix/store/abc-fonts/share/fonts".into()]+ );+ assert!(fontconfig_dirs("<dir>/never closed", None, Some(home)).is_empty());+ }++ #[test]+ #[cfg(target_os = "linux")]+ fn linux_dirs_include_flatpak_host_fonts_without_duplicates() {+ let d = system_font_dirs();+ assert!(d.contains(&PathBuf::from("/run/host/user-fonts")));+ let mut u = d.clone();+ u.sort();+ u.dedup();+ assert_eq!(u.len(), d.len());+ }+}diff --git a/engine/vendor/deckcraft-fonts/src/lib.rs b/engine/vendor/deckcraft-fonts/src/lib.rsnew file mode 100644index 0000000..5e2ecc6--- /dev/null+++ b/engine/vendor/deckcraft-fonts/src/lib.rs@@ -0,0 +1,172 @@+//! DeckCraft fonts: the font database (craft-fonts families, user and system fonts, and open+//! substitutes for the Office fonts presentations ask for), vertical metrics, glyph outlines and+//! OpenType shaping, script/slot classification and per-cluster fallback.+//!+//! Shaping here is style-agnostic: [`shape`] and [`shape_range`] turn text in one face into glyph+//! ids, clusters and advances in font units. `deckcraft-text` applies sizes, tracking, scaling and+//! justification on top.+#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]+#![forbid(unsafe_code)]++mod fallback;+mod fontdb;+pub mod script;+mod shape;++pub use fallback::{bundled_families, covers_cluster, is_emoji_cluster, ligature_carets};+pub use fontdb::{+ FALLBACK_FAMILY, FaceRef, FontDb, FontFace, LAST_RESORT_FAMILY, MISSING_FONT_FAMILY, base_style, bundled, is_monospace_family, substitutes,+ system_font_dirs,+};+pub use harfrust::Feature;+use harfrust::Tag;+pub use kurbo::BezPath;+pub use script::{FontSlot, ScriptTag};+pub use shape::{ShapeParams, ShapedGlyph, shape_range};++/// A font from the optional craft-fonts build input (https://github.com/storytold/craft-fonts;+/// empty unless built with `CRAFT_FONTS_DIR`, see `build.rs`).+pub struct CraftFont {+ pub family: &'static str,+ pub style: &'static str,+ /// ISO 15924 scripts the font is for, e.g. `"Jpan"`.+ pub scripts: &'static [&'static str],+ pub bytes: &'static [u8],+}++include!(concat!(env!("OUT_DIR"), "/craft_fonts.rs"));++/// The craft-fonts faces for Japanese (`"Jpan"`), in manifest order. Empty without craft-fonts.+pub fn japanese_fonts() -> impl Iterator<Item = &'static CraftFont> {+ CRAFT_FONTS.iter().filter(|f| f.scripts.contains(&"Jpan"))+}++/// The TrueType or OpenType font inside a PresentationML embedded-font part+/// (`application/x-fontdata`).+///+/// The part is the font itself, or an Embedded OpenType wrapper around it (the `0x504C` magic+/// at byte 34, from the W3C Embedded OpenType submission). A MicroType Express subset is neither,+/// so this returns none; the original part stays in the file for the round trip.+pub fn embedded_sfnt(part: &[u8]) -> Option<&[u8]> {+ eot_payload(part).or_else(|| sfnt_or_collection(part).then_some(part))+}++fn sfnt_or_collection(b: &[u8]) -> bool {+ b.len() >= 12+ && (b.starts_with(&[0x00, 0x01, 0x00, 0x00])+ || b.starts_with(b"OTTO")+ || b.starts_with(b"true")+ || b.starts_with(b"typ1")+ || b.starts_with(b"ttcf"))+}++/// Font data at the end of an Embedded OpenType blob, when the header is one.+fn eot_payload(b: &[u8]) -> Option<&[u8]> {+ if b.len() < 82 || u16::from_le_bytes([b[34], b[35]]) != 0x504C {+ return None;+ }+ let version = u32::from_le_bytes(b.get(8..12)?.try_into().ok()?);+ if !matches!(version, 0x0001_0000 | 0x0002_0001 | 0x0002_0002) {+ return None;+ }+ let eot_size = u32::from_le_bytes(b.get(0..4)?.try_into().ok()?) as usize;+ let font_size = u32::from_le_bytes(b.get(4..8)?.try_into().ok()?) as usize;+ if font_size < 12 || eot_size < font_size.saturating_add(82) || eot_size > b.len() {+ return None;+ }+ let font = b.get(eot_size - font_size..eot_size)?;+ sfnt_or_collection(font).then_some(font)+}++/// Japanese faces in document-fallback order: Mincho (serif) families first, matching the+/// serif default text font, then the others; Regular before other styles.+pub fn japanese_document_fonts() -> Vec<&'static CraftFont> {+ let mut v: Vec<_> = japanese_fonts().collect();+ v.sort_by_key(|f| (!f.family.contains("Mincho"), f.style != "Regular"));+ v+}++/// Japanese faces in UI order: BIZ UDPGothic first (the UI face), then the others; `bold` puts+/// bold styles before regular ones.+pub fn japanese_ui_fonts(bold: bool) -> Vec<&'static CraftFont> {+ let mut v: Vec<_> = japanese_fonts().collect();+ v.sort_by_key(|f| (f.family != "BIZ UDPGothic", (f.style == "Bold") != bold));+ v+}++/// The default theme's font.+pub const DEFAULT_FAMILY: &str = "Inter";++/// An OpenType feature setting: `"liga"`, `"-kern"`, `"ss01"`.+pub fn feature(tag: &str) -> Option<Feature> {+ let (on, t) = match tag.strip_prefix('-') {+ Some(r) => (false, r),+ None => (true, tag.strip_prefix('+').unwrap_or(tag)),+ };+ let b = t.as_bytes();+ if b.len() != 4 {+ return None;+ }+ Some(Feature::new(Tag::new(&[b[0], b[1], b[2], b[3]]), on as u32, ..))+}++/// A strong right-to-left character (Hebrew, Arabic, …)?+pub fn is_rtl(c: char) -> bool {+ use unicode_bidi::BidiClass::{AL, R};+ matches!(unicode_bidi::bidi_class(c), R | AL)+}++/// Shape `text` with `face`. `chars` lets callers substitute characters (e.g. uppercase for All+/// Caps) while keeping clusters pointing into the original string. Glyphs come in logical+/// order: each direction run is shaped with [`shape_range`] (right-to-left runs right to left,+/// with the whole string as context), then its clusters put back in text order (each cluster's+/// glyphs keep the shaper's order). Paragraph layout uses [`shape_range`] directly and keeps the+/// visual order.+pub fn shape(face: &FontFace, text: &str, features: &[Feature], map: impl Fn(char) -> char) -> Vec<ShapedGlyph> {+ let mut out = Vec::with_capacity(text.len());+ for (r, rtl) in direction_runs(text) {+ let mut g = shape_range(face, text, r, &ShapeParams { features, rtl, ..Default::default() }, &map);+ if rtl {+ // Visual (clusters descending) → logical; the sort is stable, so each cluster's+ // glyphs keep the shaper's order.+ g.sort_by_key(|x| x.cluster);+ }+ out.extend(g);+ }+ out+}++/// Maximal runs of one direction (neutrals join the run they're in): (byte range, right-to-left).+fn direction_runs(text: &str) -> Vec<(std::ops::Range<usize>, bool)> {+ let mut runs: Vec<(std::ops::Range<usize>, bool)> = Vec::new();+ let mut cur: Option<bool> = None;+ let mut start = 0;+ for (i, c) in text.char_indices() {+ let strong = if is_rtl(c) {+ Some(true)+ } else if unicode_bidi::bidi_class(c) == unicode_bidi::BidiClass::L {+ Some(false)+ } else {+ None+ };+ match (cur, strong) {+ (None, Some(d)) => cur = Some(d),+ (Some(a), Some(d)) if a != d => {+ runs.push((start..i, a));+ start = i;+ cur = Some(d);+ }+ _ => {}+ }+ }+ runs.push((start..text.len(), cur.unwrap_or(false)));+ runs+}++/// Glyph id of the first of `chars` the face has (0 = .notdef).+pub fn first_glyph(face: &FontFace, chars: &[char]) -> u32 {+ chars.iter().map(|c| face.glyph_for(*c)).find(|g| *g != 0).unwrap_or(0)+}++#[cfg(test)]+mod tests;diff --git a/engine/vendor/deckcraft-fonts/src/script.rs b/engine/vendor/deckcraft-fonts/src/script.rsnew file mode 100644index 0000000..e6a86fe--- /dev/null+++ b/engine/vendor/deckcraft-fonts/src/script.rs@@ -0,0 +1,246 @@+//! Script and font-slot classification.+//!+//! DrawingML gives every run three typefaces: `a:latin`, `a:ea` (East Asian) and `a:cs` (complex+//! script: Arabic, Hebrew, Thai, Indic…). Which one a character uses follows its Unicode script+//! (UAX #24). Characters with no script of their own (Common and Inherited: spaces, digits,+//! punctuation, combining marks) take the script and slot of the text around them, so a space or+//! a parenthesis between two Arabic words is shaped with them.++/// An ISO 15924 script tag, e.g. `*b"Arab"`.+pub type ScriptTag = [u8; 4];++pub const ARABIC: ScriptTag = *b"Arab";+pub const HEBREW: ScriptTag = *b"Hebr";+pub const LATIN: ScriptTag = *b"Latn";++/// The DrawingML typeface slot a character is drawn with.+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]+pub enum FontSlot {+ /// `a:latin`.+ #[default]+ Latin,+ /// `a:ea`.+ EastAsian,+ /// `a:cs`.+ ComplexScript,+}++/// Inclusive code point ranges and their script (a subset of `Scripts.txt` covering the scripts+/// the slot decision and shaping need; everything else is Latin-slot or Common).+const RANGES: &[(u32, u32, ScriptTag)] = &[+ (0x0041, 0x005A, *b"Latn"),+ (0x0061, 0x007A, *b"Latn"),+ (0x00AA, 0x00AA, *b"Latn"),+ (0x00BA, 0x00BA, *b"Latn"),+ (0x00C0, 0x00D6, *b"Latn"),+ (0x00D8, 0x00F6, *b"Latn"),+ (0x00F8, 0x024F, *b"Latn"),+ (0x0370, 0x03FF, *b"Grek"),+ (0x0400, 0x052F, *b"Cyrl"),+ (0x0530, 0x058F, *b"Armn"),+ (0x0591, 0x05F4, *b"Hebr"),+ // Arabic block, minus the Common/Inherited code points handled in `script_of`.+ (0x0600, 0x06FF, *b"Arab"),+ (0x0700, 0x074F, *b"Syrc"),+ (0x0750, 0x077F, *b"Arab"),+ (0x0780, 0x07BF, *b"Thaa"),+ (0x07C0, 0x07FF, *b"Nkoo"),+ (0x0870, 0x08FF, *b"Arab"),+ (0x0900, 0x097F, *b"Deva"),+ (0x0980, 0x09FF, *b"Beng"),+ (0x0A00, 0x0A7F, *b"Guru"),+ (0x0A80, 0x0AFF, *b"Gujr"),+ (0x0B00, 0x0B7F, *b"Orya"),+ (0x0B80, 0x0BFF, *b"Taml"),+ (0x0C00, 0x0C7F, *b"Telu"),+ (0x0C80, 0x0CFF, *b"Knda"),+ (0x0D00, 0x0D7F, *b"Mlym"),+ (0x0D80, 0x0DFF, *b"Sinh"),+ (0x0E00, 0x0E7F, *b"Thai"),+ (0x0E80, 0x0EFF, *b"Laoo"),+ (0x0F00, 0x0FFF, *b"Tibt"),+ (0x1000, 0x109F, *b"Mymr"),+ (0x10A0, 0x10FF, *b"Geor"),+ (0x1100, 0x11FF, *b"Hang"),+ (0x1200, 0x139F, *b"Ethi"),+ (0x1780, 0x17FF, *b"Khmr"),+ (0x1E00, 0x1EFF, *b"Latn"),+ (0x1F00, 0x1FFF, *b"Grek"),+ (0x2C60, 0x2C7F, *b"Latn"),+ (0x2E80, 0x2FDF, *b"Hani"),+ (0x3040, 0x309F, *b"Hira"),+ (0x30A0, 0x30FF, *b"Kana"),+ (0x3100, 0x312F, *b"Bopo"),+ (0x3130, 0x318F, *b"Hang"),+ (0x31F0, 0x31FF, *b"Kana"),+ (0x3400, 0x4DBF, *b"Hani"),+ (0x4E00, 0x9FFF, *b"Hani"),+ (0xA720, 0xA7FF, *b"Latn"),+ (0xAC00, 0xD7AF, *b"Hang"),+ (0xF900, 0xFAFF, *b"Hani"),+ (0xFB00, 0xFB06, *b"Latn"),+ (0xFB1D, 0xFB4F, *b"Hebr"),+ (0xFB50, 0xFDFF, *b"Arab"),+ (0xFE70, 0xFEFF, *b"Arab"),+ (0xFF21, 0xFF3A, *b"Latn"),+ (0xFF41, 0xFF5A, *b"Latn"),+ (0xFF66, 0xFF9F, *b"Kana"),+ (0x10E60, 0x10E7F, *b"Arab"),+ (0x1EE00, 0x1EEFF, *b"Arab"),+ (0x20000, 0x323AF, *b"Hani"),+];++/// Code points inside the Arabic blocks whose script is Common or Inherited: the Arabic comma,+/// semicolon and question mark, tatweel, the harakat (combining vowel marks) and the BOM-like+/// U+FEFF. They take the script of the text around them.+fn arabic_common(cp: u32) -> bool {+ matches!(cp, 0x060C | 0x061B | 0x061F | 0x0640 | 0x064B..=0x0655 | 0x0670 | 0xFEFF | 0xFD3E | 0xFD3F)+}++/// The script of `c`, or `None` for Common and Inherited characters (spaces, digits,+/// punctuation, combining marks), which take the script of their neighbours.+pub fn script_of(c: char) -> Option<ScriptTag> {+ let cp = c as u32;+ if arabic_common(cp) {+ return None;+ }+ // Ranges are sorted and disjoint: binary search on the start.+ let i = RANGES.partition_point(|(lo, _, _)| *lo <= cp);+ let (lo, hi, tag) = RANGES.get(i.checked_sub(1)?)?;+ (cp >= *lo && cp <= *hi).then_some(*tag)+}++/// The slot a script is drawn with.+pub fn slot_of_script(s: ScriptTag) -> FontSlot {+ match &s {+ b"Hani" | b"Hira" | b"Kana" | b"Hang" | b"Bopo" => FontSlot::EastAsian,+ b"Arab" | b"Hebr" | b"Syrc" | b"Thaa" | b"Nkoo" | b"Deva" | b"Beng" | b"Guru" | b"Gujr" | b"Orya" | b"Taml" | b"Telu" | b"Knda" | b"Mlym"+ | b"Sinh" | b"Thai" | b"Laoo" | b"Tibt" | b"Mymr" | b"Khmr" => FontSlot::ComplexScript,+ _ => FontSlot::Latin,+ }+}++/// The slot of `c` on its own: `None` for characters that take their neighbours' slot. CJK+/// punctuation and full-width forms are East Asian although their script is Common.+pub fn slot_of(c: char) -> Option<FontSlot> {+ if let Some(s) = script_of(c) {+ return Some(slot_of_script(s));+ }+ let cp = c as u32;+ if (0x3000..=0x303F).contains(&cp) || (0xFF00..=0xFFEF).contains(&cp) || (0x3200..=0x33FF).contains(&cp) {+ return Some(FontSlot::EastAsian);+ }+ None+}++/// A default BCP 47 language for a script (shaping picks `locl` forms by language).+pub fn default_language(s: ScriptTag) -> Option<&'static str> {+ Some(match &s {+ b"Arab" => "ar",+ b"Hebr" => "he",+ b"Syrc" => "syr",+ b"Thaa" => "dv",+ b"Thai" => "th",+ b"Deva" => "hi",+ _ => return None,+ })+}++/// Resolve every character's script and slot, giving Common/Inherited characters the value of the+/// preceding character with one (or, at the start, the following one; Latin when there is none).+pub fn resolve(chars: &[char]) -> Vec<(Option<ScriptTag>, FontSlot)> {+ let own: Vec<(Option<ScriptTag>, Option<FontSlot>)> = chars.iter().map(|c| (script_of(*c), slot_of(*c))).collect();+ let first = own.iter().find_map(|(s, sl)| sl.map(|sl| (*s, sl))).unwrap_or((None, FontSlot::Latin));+ let mut prev = first;+ own.into_iter()+ .map(|(s, sl)| {+ if let Some(sl) = sl {+ prev = (s, sl);+ }+ prev+ })+ .collect()+}++/// Arabic letters that join to the following letter (joining type D, dual-joining): a kashida+/// (tatweel) may be inserted after them. Right-joining (alef, dal, reh, waw…) and non-joining+/// (hamza) letters are excluded.+pub fn joins_following(c: char) -> bool {+ let cp = c as u32;+ let letter = matches!(cp, 0x0620..=0x064A | 0x066E..=0x06D3 | 0x06FA..=0x06FC | 0x06FF | 0x0750..=0x077F | 0x08A0..=0x08C9);+ letter+ && !matches!(+ cp,+ 0x0621..=0x0625 | 0x0627 | 0x0629 | 0x062F..=0x0632 | 0x0648 | 0x0671..=0x0673 | 0x0675..=0x0677 | 0x0688..=0x0699 | 0x06C0+ | 0x06C3..=0x06CB | 0x06CD | 0x06CF | 0x06D2 | 0x06D3 | 0x0759..=0x075B | 0x076B | 0x076C | 0x0771 | 0x0773 | 0x0774+ | 0x0778 | 0x0779 | 0x08AA..=0x08AC | 0x08AE | 0x08B1 | 0x08B2 | 0x08B9+ )+}++/// An Arabic letter that joins to the preceding letter (joining type D or R).+pub fn joins_preceding(c: char) -> bool {+ let cp = c as u32;+ matches!(cp, 0x0622..=0x064A | 0x066E..=0x06D3 | 0x06FA..=0x06FC | 0x06FF | 0x0750..=0x077F | 0x08A0..=0x08C9) && cp != 0x0621+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn scripts_and_slots() {+ assert_eq!(script_of('س'), Some(ARABIC));+ assert_eq!(script_of('ש'), Some(HEBREW));+ assert_eq!(script_of('R'), Some(LATIN));+ assert_eq!(script_of('2'), None);+ assert_eq!(script_of('('), None);+ // Harakat and tatweel are Inherited/Common.+ assert_eq!(script_of('\u{064E}'), None);+ assert_eq!(script_of('\u{0640}'), None);+ assert_eq!(slot_of('س'), Some(FontSlot::ComplexScript));+ assert_eq!(slot_of('日'), Some(FontSlot::EastAsian));+ assert_eq!(slot_of('、'), Some(FontSlot::EastAsian));+ assert_eq!(slot_of('a'), Some(FontSlot::Latin));+ assert_eq!(slot_of(' '), None);+ assert_eq!(script_of('\u{10FFFF}'), None);+ assert_eq!(script_of('\0'), None);+ }++ #[test]+ fn neutrals_take_the_surrounding_slot() {+ let chars: Vec<char> = "سنة 2024 (Retrait) فقط".chars().collect();+ let r = resolve(&chars);+ // "سنة 2024 (" follows Arabic: complex script.+ for (i, c) in chars.iter().enumerate().take(10) {+ assert_eq!(r[i].1, FontSlot::ComplexScript, "{c:?}");+ }+ // "Retrait)" is Latin; the space after ")" stays Latin; "فقط" is complex script.+ assert_eq!(r[10].1, FontSlot::Latin);+ assert_eq!(r[17].1, FontSlot::Latin);+ assert_eq!(r[19], (Some(ARABIC), FontSlot::ComplexScript));+ // Leading neutrals take the first strong character's slot.+ let r = resolve(&['(', 'س']);+ assert_eq!(r[0].1, FontSlot::ComplexScript);+ assert!(resolve(&[]).is_empty());+ assert_eq!(resolve(&['1'])[0], (None, FontSlot::Latin));+ }++ #[test]+ fn joining_classes() {+ assert!(joins_following('س'));+ assert!(joins_following('ن'));+ assert!(!joins_following('ا'));+ assert!(!joins_following('د'));+ assert!(!joins_following('ء'));+ assert!(joins_preceding('ا'));+ assert!(!joins_preceding('ء'));+ assert!(!joins_following('a'));+ }++ #[test]+ fn ranges_are_sorted_and_disjoint() {+ for w in RANGES.windows(2) {+ assert!(w[0].1 < w[1].0, "{:x?} {:x?}", w[0], w[1]);+ }+ }+}diff --git a/engine/vendor/deckcraft-fonts/src/shape.rs b/engine/vendor/deckcraft-fonts/src/shape.rsnew file mode 100644index 0000000..e3e7ab2--- /dev/null+++ b/engine/vendor/deckcraft-fonts/src/shape.rs@@ -0,0 +1,247 @@+//! OpenType shaping with HarfRust.+//!+//! [`shape_range`] shapes one item of a paragraph (one face, one direction, one script) with the+//! rest of the paragraph as pre/post context, so Arabic letters at an item boundary (a colour+//! change inside a word, a bold letter) still take their joining forms. Glyphs come back in+//! visual order, exactly as the shaper produced them: right-to-left items are not reversed.++use std::ops::Range;++use harfrust::{Direction, Feature, Language, Script, ShapeOptions, Tag, UnicodeBuffer};+use skrifa::MetadataProvider;+use skrifa::instance::Size;++use crate::FontFace;+use crate::script::ScriptTag;++/// One shaped glyph, in font units.+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct ShapedGlyph {+ pub gid: u32,+ /// Byte offset (in the shaped string) of the cluster this glyph belongs to.+ pub cluster: usize,+ pub x_advance: i32,+ pub x_offset: i32,+ pub y_offset: i32,+}++/// How to shape an item.+#[derive(Clone, Copy, Debug, Default)]+pub struct ShapeParams<'a> {+ pub features: &'a [Feature],+ /// Right-to-left (odd bidi level). Mirrored characters (brackets) take their mirrored glyphs.+ pub rtl: bool,+ /// ISO 15924 script (`*b"Arab"`); `None` lets the shaper guess from the text.+ pub script: Option<ScriptTag>,+ /// BCP 47 language (`"ar"`, `"ar-MA"`); `None` = the script's default.+ pub language: Option<&'a str>,+}++/// Most bytes of text given to the shaper at once. The shaper lets one call grow its buffers to+/// 256 glyphs per character (a font's substitutions decide how many), so a long item is shaped in+/// pieces of this size, each with the rest of the paragraph as context.+const MAX_SHAPE_CHUNK: usize = 1024;+/// Most glyphs kept per character of a piece: a piece the font expands further is laid out one+/// glyph per character from the cmap instead.+const MAX_GLYPHS_PER_CHAR: usize = 32;++/// Shape `para[range]` with `face`, the rest of `para` as context. Glyphs are in visual order+/// (left to right) and clusters are byte offsets into `para`. `map` substitutes characters (All+/// Caps) without moving clusters. An empty or out-of-bounds range shapes nothing.+pub fn shape_range(face: &FontFace, para: &str, range: Range<usize>, params: &ShapeParams, map: impl Fn(char) -> char) -> Vec<ShapedGlyph> {+ let (Some(_), Some(text), Some(_)) = (para.get(..range.start), para.get(range.clone()), para.get(range.end..)) else {+ return Vec::new();+ };+ let chunks = chunks(text, MAX_SHAPE_CHUNK);+ let mut pieces: Vec<Vec<ShapedGlyph>> = Vec::with_capacity(chunks.len());+ let shaped = face.hb().map(|hb| {+ let shaper = face.shaper.shaper(&hb).instance(face.instance.as_ref()).build();+ // Pieces of one item share the script the whole item would be guessed to have.+ let item_script = (chunks.len() > 1 && params.script.is_none()).then(|| {+ let mut probe = UnicodeBuffer::new();+ for c in text.chars() {+ probe.add(map(c), 0);+ }+ probe.guess_segment_properties();+ probe.script()+ });+ for c in &chunks {+ let r = (range.start + c.start)..(range.start + c.end);+ let (Some(pre), Some(piece), Some(post)) = (para.get(..r.start), para.get(r.clone()), para.get(r.end..)) else { continue };+ let mut buf = UnicodeBuffer::new();+ buf.set_pre_context(pre);+ buf.set_post_context(post);+ for (i, c) in piece.char_indices() {+ buf.add(map(c), (r.start + i) as u32);+ }+ buf.guess_segment_properties();+ if let Some(s) = params.script.and_then(|t| Script::from_iso15924_tag(Tag::new(&t))) {+ buf.set_script(s);+ } else if let Some(s) = item_script {+ buf.set_script(s);+ }+ if let Some(l) =+ params.language.or_else(|| params.script.and_then(crate::script::default_language)).and_then(|l| l.parse::<Language>().ok())+ {+ buf.set_language(l);+ }+ buf.set_direction(if params.rtl { Direction::RightToLeft } else { Direction::LeftToRight });+ let gb = shaper.shape(buf, ShapeOptions::new().features(params.features));+ let budget = piece.chars().count().saturating_mul(MAX_GLYPHS_PER_CHAR);+ if gb.len() > budget {+ // Font-controlled expansion past anything real text needs: keep it bounded.+ pieces.push(cmap_glyphs(face, para, r, params.rtl, &map));+ continue;+ }+ pieces.push(+ gb.glyph_infos()+ .iter()+ .zip(gb.glyph_positions())+ .map(|(info, pos)| ShapedGlyph {+ gid: info.glyph_id,+ cluster: info.cluster as usize,+ x_advance: pos.x_advance,+ x_offset: pos.x_offset,+ y_offset: pos.y_offset,+ })+ .collect(),+ );+ }+ });+ if shaped.is_none() {+ // No shaper for this face: one glyph per character from the cmap, in visual order.+ return cmap_glyphs(face, para, range, params.rtl, &map);+ }+ // Each piece is in visual order; right to left, the later pieces come first.+ if params.rtl {+ pieces.reverse();+ }+ let mut out = Vec::with_capacity(pieces.iter().map(Vec::len).sum());+ for p in pieces {+ out.extend(p);+ }+ out+}++/// One glyph per character of `para[range]` from the cmap, in visual order.+fn cmap_glyphs(face: &FontFace, para: &str, range: Range<usize>, rtl: bool, map: &impl Fn(char) -> char) -> Vec<ShapedGlyph> {+ let (Some(text), Some(f)) = (para.get(range.clone()), face.skrifa()) else { return Vec::new() };+ let cmap = f.charmap();+ let gm = f.glyph_metrics(Size::unscaled(), face.location());+ let mut out = Vec::with_capacity(text.len());+ for (i, c) in text.char_indices() {+ let g = cmap.map(map(c)).unwrap_or_default();+ let adv = gm.advance_width(g).unwrap_or(face.upem as f32 * 0.5);+ out.push(ShapedGlyph { gid: g.to_u32(), cluster: range.start + i, x_advance: adv.round() as i32, x_offset: 0, y_offset: 0 });+ }+ if rtl {+ out.reverse();+ }+ out+}++/// `text` cut into byte ranges of at most `max` bytes (or one character, if longer), at the last+/// space of a piece where there is one, else before a character that starts a cluster (not a+/// combining mark or joiner, not after a joiner). Text that fits is one piece.+fn chunks(text: &str, max: usize) -> Vec<Range<usize>> {+ use unicode_bidi::BidiClass::{BN, NSM};+ let mut out = Vec::new();+ let mut start = 0;+ while text.len() - start > max {+ let window = text.get(start..).unwrap_or_default();+ let mut space = None;+ let mut boundary = None;+ let mut any = None;+ let mut prev: Option<char> = None;+ for (i, c) in window.char_indices() {+ if i > max {+ break;+ }+ if i > 0 {+ any = Some(i);+ let joined = prev.is_some_and(|p| matches!(unicode_bidi::bidi_class(p), BN));+ if !joined && !matches!(unicode_bidi::bidi_class(c), NSM | BN) {+ boundary = Some(i);+ if prev.is_some_and(char::is_whitespace) {+ space = Some(i);+ }+ }+ }+ prev = Some(c);+ }+ // A piece always moves forward by at least one character.+ let first = window.chars().next().map_or(window.len(), char::len_utf8);+ let cut = space.filter(|&i| i >= max / 2).or(boundary).or(any).unwrap_or(first).max(first);+ out.push(start..start + cut);+ start += cut;+ }+ if start < text.len() || out.is_empty() {+ out.push(start..text.len());+ }+ out+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::{DEFAULT_FAMILY, FontDb};++ #[test]+ fn rtl_items_come_in_visual_order_and_mirror() {+ let face = FontDb::global().face(DEFAULT_FAMILY, "Regular");+ let text = "(ab)";+ let p = ShapeParams { rtl: true, ..Default::default() };+ let g = shape_range(&face, text, 0..text.len(), &p, |c| c);+ // Visual order: last cluster first.+ assert_eq!(g.iter().map(|g| g.cluster).collect::<Vec<_>>(), vec![3, 2, 1, 0]);+ // L4: in a right-to-left run "(" is drawn with the ")" glyph and vice versa.+ if face.covers('(') && face.covers(')') {+ assert_eq!(g[3].gid, face.glyph_for(')'));+ assert_eq!(g[0].gid, face.glyph_for('('));+ }+ }++ #[test]+ fn clusters_point_into_the_whole_paragraph() {+ let face = FontDb::global().face(DEFAULT_FAMILY, "Regular");+ let para = "Hello world";+ let g = shape_range(&face, para, 6..11, &ShapeParams::default(), |c| c);+ assert_eq!(g.first().map(|g| g.cluster), Some(6));+ assert!(shape_range(&face, para, 6..99, &ShapeParams::default(), |c| c).is_empty());+ // Not a char boundary.+ assert!(shape_range(&face, "سنة", 1..2, &ShapeParams::default(), |c| c).is_empty());+ }++ #[test]+ fn long_items_are_shaped_in_bounded_pieces() {+ for text in ["word ".repeat(2_000), "e\u{301}".repeat(2_000), "x".repeat(5_000), "\u{1f469}\u{200d}\u{1f4bb} ".repeat(500)] {+ let pieces = chunks(&text, MAX_SHAPE_CHUNK);+ assert_eq!(pieces.first().map(|r| r.start), Some(0));+ assert_eq!(pieces.last().map(|r| r.end), Some(text.len()));+ for w in pieces.windows(2) {+ assert_eq!(w[0].end, w[1].start);+ }+ for r in &pieces {+ assert!(!r.is_empty() && r.len() <= MAX_SHAPE_CHUNK);+ // Never before a combining mark, never after a joiner.+ let rest = &text[r.end..];+ assert!(!rest.starts_with('\u{301}'));+ assert!(!text[..r.end].ends_with('\u{200d}') || rest.is_empty());+ }+ }+ assert_eq!(chunks("short", MAX_SHAPE_CHUNK), vec![0..5]);+ assert_eq!(chunks("", MAX_SHAPE_CHUNK), vec![0..0]);+ }++ #[test]+ fn long_items_keep_every_cluster_in_visual_order() {+ let face = FontDb::global().face(DEFAULT_FAMILY, "Regular");+ let text = "ab cd ".repeat(1_000);+ let g = shape_range(&face, &text, 0..text.len(), &ShapeParams::default(), |c| c);+ assert_eq!(g.len(), text.len());+ assert!(g.windows(2).all(|w| w[0].cluster < w[1].cluster));+ let rtl = shape_range(&face, &text, 0..text.len(), &ShapeParams { rtl: true, ..Default::default() }, |c| c);+ assert_eq!(rtl.len(), text.len());+ assert!(rtl.windows(2).all(|w| w[0].cluster > w[1].cluster));+ }+}diff --git a/engine/vendor/deckcraft-fonts/src/tests.rs b/engine/vendor/deckcraft-fonts/src/tests.rsnew file mode 100644index 0000000..8d47dd3--- /dev/null+++ b/engine/vendor/deckcraft-fonts/src/tests.rs@@ -0,0 +1,427 @@+use super::*;++fn any_face() -> std::sync::Arc<FontFace> {+ FontDb::global().face(DEFAULT_FAMILY, "Regular")+}++#[test]+fn emoji_clusters_are_recognised() {+ let c = |s: &str| s.chars().collect::<Vec<char>>();+ // As PowerPoint draws them: emoji-presentation characters (⭐ ✅ ☔ ⌚ ⏩) in colour even+ // without a selector, text-presentation ones (♥ ✔ ☎ ⬆ ▶) as text unless U+FE0F asks, and+ // keycaps always as text.+ for yes in ["😀", "👍🏽", "❤\u{FE0F}", "👨\u{200D}👩\u{200D}👧", "🇯🇵", "🏳\u{FE0F}\u{200D}🌈", "⭐", "✅", "☔", "⌚", "⏩", "🀄"]+ {+ assert!(is_emoji_cluster(&c(yes)), "{yes:?}");+ }+ for no in ["a", "1", "❤", "☺\u{FE0E}", "😀\u{FE0E}", "字", "→", "♥", "✔", "☎", "⬆", "▶", "1\u{FE0F}\u{20E3}", "#\u{20E3}"] {+ assert!(!is_emoji_cluster(&c(no)), "{no:?}");+ }+}++#[test]+fn colour_fonts_are_recognised() {+ let db = FontDb::with_font_dirs(Vec::new());+ assert!(db.add_font(include_bytes!("../../render/tests/fixtures/colr-squares.ttf").to_vec()) > 0);+ assert!(db.face("DeckCraft Colr Squares", "Regular").is_color());+ assert!(!fontdb::last_resort_face().is_color());+}++#[test]+fn last_resort_face_parses() {+ let f = fontdb::last_resort_face();+ assert_eq!(f.family, fontdb::LAST_RESORT_FAMILY);+ assert!(f.upem > 0.0);+}++#[test]+fn line_split_follows_the_windows_ascent_and_descent() {+ use skrifa::raw::TableProvider;+ let f = fontdb::last_resort_face();+ let font = skrifa::FontRef::new(f.data()).unwrap();+ let os2 = font.os2().unwrap();+ let (a, d) = (os2.us_win_ascent() as f64, os2.us_win_descent() as f64);+ assert!((f.line_split - a / (a + d)).abs() < 1e-9, "{} vs {}", f.line_split, a / (a + d));+ assert!(f.line_split > 0.5 && f.line_split < 1.0);+}++#[test]+fn some_face_always_resolves() {+ let db = FontDb::with_font_dirs(Vec::new());+ db.set_system_fallback(false);+ let f = db.face("No Such Font Anywhere", "Regular");+ assert!(!f.family.is_empty());+ assert!(!shape(&f, "Hello", &[], |c| c).is_empty());+}++#[test]+fn filtered_fallback_continues_after_a_rejected_loaded_face() {+ let db = FontDb::with_font_dirs(Vec::new());+ db.set_system_fallback(false);+ assert_eq!(db.add_font(include_bytes!("../tests/fixtures/legacy-regular.ttf").to_vec()), 1);+ let first = db.fallback_for('A', u32::MAX).unwrap();+ let accepted_family = if first.family == LAST_RESORT_FAMILY { "DeckCraft Legacy" } else { LAST_RESORT_FAMILY };+ let fallback = db.fallback_for_filtered('A', u32::MAX, |f| f.family == accepted_family).unwrap();+ assert_eq!(fallback.family, accepted_family);+ assert!(fallback.covers('A'));+ assert_ne!(fallback.id(), first.id());+ assert_eq!(db.fallback_for('A', u32::MAX).unwrap().id(), first.id(), "document fallback order is unchanged");+ assert!(db.fallback_for_filtered('A', fallback.id(), |f| f.family == accepted_family).is_none(), "the excluded face stays excluded");+}++#[cfg(not(target_arch = "wasm32"))]+#[test]+fn filtered_fallback_loads_an_eligible_system_face_and_does_not_cache_policy_misses() {+ let dir = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures");+ let db = FontDb::with_font_dirs(vec![dir]);+ let first = db.fallback_for('A', u32::MAX).unwrap();+ assert_ne!(first.family, "DeckCraft Legacy");+ assert!(db.fallback_for_filtered('A', u32::MAX, |_| false).is_none());+ assert!(db.fallback_for('A', u32::MAX).is_some(), "an interface policy miss does not hide document glyphs");+ let accepted = db.fallback_for_filtered('A', u32::MAX, |f| f.family == "DeckCraft Legacy").unwrap();+ assert_eq!(accepted.family, "DeckCraft Legacy");+ assert!(accepted.covers('A'));+}++#[test]+fn concurrent_lookups_all_find_an_installed_family() {+ // Threads resolving an installed family nobody had loaded yet used to fall back to+ // another face when a different thread finished loading it first, so the same text was+ // laid out in different fonts depending on timing.+ let dir = std::env::temp_dir().join(format!("deckcraft-fonts-concurrent-{}", std::process::id()));+ std::fs::create_dir_all(&dir).unwrap();+ std::fs::write(dir.join("Hack-Regular.ttf"), epaint_default_fonts::HACK_REGULAR).unwrap();+ for _ in 0..20 {+ let db = FontDb::with_font_dirs(vec![dir.clone()]);+ db.set_system_fallback(false);+ let start = std::sync::Barrier::new(8);+ let got: Vec<String> = std::thread::scope(|s| {+ let threads: Vec<_> = (0..8)+ .map(|_| {+ s.spawn(|| {+ start.wait();+ db.face("Hack", "Regular").family.clone()+ })+ })+ .collect();+ threads.into_iter().map(|t| t.join().unwrap()).collect()+ });+ assert!(got.iter().all(|f| f == "Hack"), "{got:?}");+ }+ let _ = std::fs::remove_dir_all(&dir);+}++#[test]+fn windows_family_names_find_their_faces() {+ // Documents name fonts by their Windows family ("Segoe UI Semibold"); the font's+ // typographic family is "Segoe UI" with a "Semibold" style. The fixture is named the same way.+ let check = |db: &FontDb| {+ assert!(db.has_family("DeckCraft Legacy Semibold"));+ for style in ["Regular", "Bold"] {+ let f = db.face("DeckCraft Legacy Semibold", style);+ assert_eq!((f.family.as_str(), f.style.as_str()), ("DeckCraft Legacy", "Semibold"), "{style}");+ }+ assert_eq!(db.document_face("DeckCraft Legacy Semibold", "Regular").family, "DeckCraft Legacy", "installed, so not Calibri");+ // The typographic name still works.+ assert_eq!(db.face("DeckCraft Legacy", "Semibold").style, "Semibold");+ };+ // Loaded directly…+ let db = FontDb::with_font_dirs(Vec::new());+ db.set_system_fallback(false);+ assert_eq!(db.add_font(include_bytes!("../tests/fixtures/legacy-semibold.ttf").to_vec()), 1);+ check(&db);+ // …and found by the system font scan under its Windows name, then loaded.+ #[cfg(not(target_arch = "wasm32"))]+ {+ let dir = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures");+ let db = FontDb::with_font_dirs(vec![dir.clone()]);+ db.set_system_fallback(false);+ check(&db);+ // Looking up the Windows name loads the Semibold file only; a later lookup of the+ // family's Regular must still load and pick the Regular file, not settle for Semibold.+ let db = FontDb::with_font_dirs(vec![dir]);+ db.set_system_fallback(false);+ assert_eq!(db.face("DeckCraft Legacy Semibold", "Regular").style, "Semibold");+ let regular = db.face("DeckCraft Legacy", "Regular");+ assert_eq!((regular.style.as_str(), regular.weight), ("Regular", 400.0));+ }+}++#[test]+fn variable_font_instances_answer_to_their_windows_names() {+ // Windows lists a variable font's named instances other than Regular, Italic, Bold and+ // Bold Italic as families of their own, and documents name them that way ("Montserrat+ // ExtraBold"). The bundled Montserrat is variable, so these names found no face and drew+ // in Inter Regular, even with the family's static files installed (their faces are+ // skipped as already present).+ let db = FontDb::with_font_dirs(Vec::new());+ db.set_system_fallback(false);+ if !db.is_loaded("Montserrat") {+ return; // built without craft-fonts+ }+ for (name, style, weight, italic) in [+ ("Montserrat ExtraBold", "Regular", 800.0, false),+ ("Montserrat SemiBold", "Regular", 600.0, false),+ ("Montserrat Medium", "Regular", 500.0, false),+ ("Montserrat Medium", "Italic", 500.0, true),+ ("Montserrat Thin", "Bold", 100.0, false),+ ] {+ assert!(db.has_family(name), "{name}");+ let f = db.face(name, style);+ assert_eq!((f.family.as_str(), f.weight, f.italic), ("Montserrat", weight, italic), "{name} {style}");+ assert_eq!(db.document_face(name, style).family, "Montserrat", "{name}: installed, so not Calibri");+ }+ // Regular and Bold are the family itself, not families of their own.+ assert!(!db.has_family("Montserrat Regular"));+ assert!(!db.has_family("Montserrat Bold"));+ assert_eq!(db.face("Montserrat", "Bold").weight, 700.0);+}++#[test]+fn faces_without_outlines_are_not_cataloged() {+ // Rename the Semibold's `glyf` table, as in fonts whose glyphs are bitmaps or are stored in+ // Apple's `hvgl` table. The face still maps "A", but its outline is empty. The new tag+ // keeps the table directory sorted.+ let mut semibold = include_bytes!("../tests/fixtures/legacy-semibold.ttf").to_vec();+ let tables = u16::from_be_bytes([semibold[4], semibold[5]]) as usize;+ let glyf = (0..tables).map(|i| 12 + 16 * i).find(|&r| &semibold[r..r + 4] == b"glyf").unwrap();+ semibold[glyf..glyf + 4].copy_from_slice(b"gxyz");+ let loaded = FontDb::with_font_dirs(Vec::new());+ assert_eq!(loaded.add_font(semibold.clone()), 1);+ let face = loaded.face("DeckCraft Legacy", "Semibold");+ assert!(face.covers('A'));+ assert!(loaded.outline(&face, face.glyph_for('A')).elements().is_empty());+ // The system font scan lists the Regular, which has outlines, and leaves out the Semibold+ // under both of its names.+ #[cfg(not(target_arch = "wasm32"))]+ {+ let dir = std::env::temp_dir().join(format!("deckcraft-fonts-outlines-{}", std::process::id()));+ std::fs::create_dir_all(&dir).unwrap();+ std::fs::write(dir.join("legacy-semibold.ttf"), &semibold).unwrap();+ std::fs::write(dir.join("legacy-regular.ttf"), include_bytes!("../tests/fixtures/legacy-regular.ttf")).unwrap();+ let db = FontDb::with_font_dirs(vec![dir.clone()]);+ db.set_system_fallback(false);+ assert_eq!(db.styles("DeckCraft Legacy"), ["Regular"]);+ assert!(!db.has_family("DeckCraft Legacy Semibold"));+ let _ = std::fs::remove_dir_all(&dir);+ }+}++#[test]+fn missing_document_fonts_are_drawn_in_calibri() {+ // PowerPoint draws a missing family in Calibri, whatever its panose or the theme says.+ let db = FontDb::global();+ for missing in ["Qqq Nonexistent", "Avenir Next Qqq", "", "Arimo Qqq"] {+ let f = db.document_face(missing, "Bold");+ assert_eq!(f.family, db.face(MISSING_FONT_FAMILY, "Bold").family, "{missing:?}");+ }+ // PowerPoint's own twins and Windows' substitutes, when the font itself is missing.+ for (missing, twin) in [+ ("Liberation Sans", "Arial"),+ ("Liberation Serif", "Times New Roman"),+ ("Arial CE", "Arial"),+ ("Times New Roman CYR", "Times New Roman"),+ ("Courier New CE", "Courier New"),+ ] {+ if !db.has_family(missing) {+ assert_eq!(db.document_face(missing, "Regular").family, db.face(twin, "Regular").family, "{missing}");+ }+ }+ // Metric-compatible stand-ins and DeckCraft's default keep their own fallbacks.+ // So do Office's cloud fonts, which PowerPoint downloads and draws as themselves.+ for kept in ["Arial", "Times New Roman", "Cambria", "Courier New", FALLBACK_FAMILY, "Aptos", "Aptos Display", "Grandview"] {+ assert_eq!(db.document_face(kept, "Regular").family, db.face(kept, "Regular").family, "{kept}");+ }+}++#[test]+fn office_fonts_have_substitutes() {+ assert!(substitutes("Calibri").contains(&"Carlito"));+ assert!(substitutes("Cambria").contains(&"Caladea"));+ assert!(substitutes("Times New Roman").contains(&"Liberation Serif"));+ assert!(substitutes("Aptos").contains(&"Inter"));+ assert!(substitutes("zzz").is_empty());++ for mono in [+ "Courier New",+ "Cousine",+ "Consolas",+ "Menlo",+ "Monaco",+ "Source Code Pro",+ "JetBrains Mono",+ "Cascadia Code",+ "Cascadia Code PL",+ "Cascadia Mono",+ "Fira Code",+ "Inconsolata",+ "DejaVu Sans Mono",+ "Roboto Mono",+ "Hack",+ "Ubuntu Mono",+ "Custom Monospace",+ "Fantasque Sans Mono",+ ] {+ assert!(substitutes(mono).contains(&"Liberation Mono"), "{mono} should have Liberation Mono substitute");+ assert!(is_monospace_family(mono), "{mono} should be recognized as monospace");+ }++ for prop in ["Calibri", "Arial", "Times New Roman", "Inter", "Monotype Corsiva", "Monoton", "Monotype Baskerville", "Code Pro", "zzz"] {+ assert!(!is_monospace_family(prop), "{prop} should not be recognized as monospace");+ }++ // Explicit checks requested in review: Consolas, Courier New, Fira Code, Monotype Corsiva, Monoton,+ // and ensuring proportional families maintain their unchanged substitutes.+ assert!(is_monospace_family("Consolas"));+ assert!(is_monospace_family("Courier New"));+ assert!(is_monospace_family("Fira Code"));+ assert!(!is_monospace_family("Monotype Corsiva"));+ assert!(!is_monospace_family("Monoton"));++ assert_eq!(substitutes("Calibri"), &["Carlito", "Liberation Sans", "Arial", "Inter"]);+ assert_eq!(substitutes("Arial"), &["Liberation Sans", "Arial", "Helvetica Neue", "Helvetica", "Inter"]);+ assert_eq!(substitutes("Times New Roman"), &["Liberation Serif", "Times New Roman", "Times", "Merriweather"]);+ assert_eq!(substitutes("Georgia"), &["Merriweather", "Liberation Serif", "Georgia"]);+ assert!(substitutes("Monotype Corsiva").is_empty());+ assert!(substitutes("Monoton").is_empty());+}++#[test]+fn missing_monospace_fonts_keep_monospace_fallback() {+ let db = FontDb::global();+ let mono_sub = db.face("Unavailable JetBrains Mono", "Regular").family.clone();+ let calibri_target = db.face(MISSING_FONT_FAMILY, "Regular").family.clone();++ assert!(is_monospace_family(&mono_sub), "substitute {mono_sub} must be monospace");++ // Cousine is metric-compatible with Courier New / Liberation Mono and must not fall back to Calibri.+ if !db.has_family("Cousine") {+ assert_eq!(db.document_face("Cousine", "Regular").family, mono_sub);+ }++ // Monospace fonts missing from the system must resolve to a monospace substitute.+ for mono in ["Unavailable JetBrains Mono", "Custom App Code", "Unknown Space Mono", "Mock Terminal Font"] {+ let f = db.document_face(mono, "Regular");+ assert_eq!(f.family, mono_sub, "{mono}");+ assert!(is_monospace_family(&f.family), "{mono} must resolve to a monospace family");+ if mono_sub != calibri_target {+ assert_ne!(f.family, calibri_target, "{mono} must not fall back to Calibri");+ }+ }+}++#[test]+fn shaping_produces_clusters_and_advances() {+ let face = any_face();+ let g = shape(&face, "Hello", &[], |c| c);+ assert_eq!(g.len(), 5);+ assert_eq!(g.iter().map(|g| g.cluster).collect::<Vec<_>>(), vec![0, 1, 2, 3, 4]);+ assert!(g.iter().all(|g| g.x_advance > 0 && g.gid != 0));+}++#[test]+fn mapping_keeps_clusters() {+ let face = any_face();+ let g = shape(&face, "ab", &[], |c| c.to_ascii_uppercase());+ assert_eq!(g[0].gid, face.glyph_for('A'));+ assert_eq!(g[1].cluster, 1);+}++#[test]+fn outlines_and_metrics() {+ let db = FontDb::global();+ let face = any_face();+ let o = db.outline(&face, face.glyph_for('O'));+ assert!(!o.elements().is_empty());+ assert!(face.ascent > 0.0 && face.descent > 0.0);+ assert!(feature("abc").is_none());+ assert!(feature("liga").is_some());+}++/// When the Latin build input exists, the runtime catalogue carries the expected Latin faces;+/// required builds also assert their presence.+#[test]+fn craft_fonts_latin_when_present() {+ let required = option_env!("CRAFT_FONTS_REQUIRED").is_some();+ if !CRAFT_FONTS.iter().any(|f| f.family == "Inter") {+ assert!(!required, "CRAFT_FONTS_REQUIRED must embed Inter rather than skip the optional Latin manifest");+ eprintln!("skipped: built without craft-fonts' Latin manifest (set CRAFT_FONTS_DIR)");+ return;+ }+ let inter = |style: &str| CRAFT_FONTS.iter().find(|f| f.family == "Inter" && f.style == style);+ let (regular, bold, variable) = (inter("Regular"), inter("Bold"), inter("Variable"));+ if required {+ assert!(+ variable.is_some() || (regular.is_some() && bold.is_some()),+ "CRAFT_FONTS_REQUIRED must embed Inter Regular and Bold (or a Variable face)"+ );+ }+ let db = FontDb::with_font_dirs(Vec::new());+ db.set_system_fallback(false);+ assert_eq!(db.face("Inter", "Regular").family, "Inter");+ assert_eq!(db.face("Aptos", "Regular").family, "Inter");+ if let (Some(regular), Some(bold)) = (regular, bold) {+ // The build input carries one entry per face; real static Bold must not be the Regular+ // file relabelled in the manifest.+ assert_ne!(regular.bytes, bold.bytes, "Inter Bold must be a distinct face file from Regular");+ let (r, b) = (db.face("Inter", "Regular"), db.face("Inter", "Bold"));+ assert_eq!((r.family.as_str(), r.style.as_str()), ("Inter", "Regular"));+ assert_eq!((b.family.as_str(), b.style.as_str()), ("Inter", "Bold"));+ assert_ne!(r.id(), b.id(), "Inter Bold must load as its own face");+ assert!(b.weight > r.weight, "Inter Bold weight {} is not above Regular {}", b.weight, r.weight);+ }+ if CRAFT_FONTS.iter().any(|f| f.family == "Carlito") {+ assert_eq!(db.face("Calibri", "Bold").family, "Carlito");+ }+}++/// An Embedded OpenType header of `version` around `font`, with the font at the end.+fn wrap_eot(font: &[u8], version: u32) -> Vec<u8> {+ let mut h = vec![0u8; 82];+ let total = 82 + font.len();+ h[0..4].copy_from_slice(&(total as u32).to_le_bytes());+ h[4..8].copy_from_slice(&(font.len() as u32).to_le_bytes());+ h[8..12].copy_from_slice(&version.to_le_bytes());+ h[34..36].copy_from_slice(&0x504Cu16.to_le_bytes());+ h.extend_from_slice(font);+ h+}++#[test]+fn embedded_open_type_yields_the_font() {+ let font = epaint_default_fonts::UBUNTU_LIGHT;+ assert_eq!(embedded_sfnt(font), Some(font));+ assert_eq!(embedded_sfnt(&wrap_eot(font, 0x0002_0001)), Some(font));+ assert_eq!(embedded_sfnt(&wrap_eot(font, 0x0001_0000)), Some(font));+ assert!(embedded_sfnt(b"not a font file").is_none());+ assert!(embedded_sfnt(&wrap_eot(b"hello world!!", 0x0002_0002)).is_none());+ let mut truncated = wrap_eot(font, 0x0002_0001);+ truncated.truncate(40);+ assert!(embedded_sfnt(&truncated).is_none());+}++/// A FIFO, a folder and a link loop dressed up as font files: the system scan skips them+/// instead of blocking forever on the FIFO (start-up hung when one sat in `~/.fonts`), and+/// still finds the real font beside them.+#[cfg(unix)]+#[test]+fn the_font_scan_skips_fifos_folders_and_link_loops() {+ let dir = std::env::temp_dir().join(format!("deckcraft-fontscan-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&dir);+ std::fs::create_dir_all(dir.join("sub")).unwrap();+ std::fs::copy(std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/legacy-semibold.ttf"), dir.join("sub/real.ttf")).unwrap();+ let fifo = std::process::Command::new("mkfifo").arg(dir.join("trap.ttf")).status().is_ok_and(|s| s.success());+ std::fs::create_dir(dir.join("folder.ttf")).unwrap();+ std::fs::write(dir.join("empty.otf"), b"").unwrap();+ std::os::unix::fs::symlink(&dir, dir.join("sub/loop")).unwrap();+ let (tx, rx) = std::sync::mpsc::channel();+ let scan_dir = dir.clone();+ std::thread::spawn(move || {+ let db = FontDb::with_font_dirs(vec![scan_dir]);+ let _ = tx.send(db.load_system_fonts());+ });+ let n = rx.recv_timeout(std::time::Duration::from_secs(30)).expect("the font scan hung");+ assert!(n >= 1, "the real font was found");+ assert!(fifo || n >= 1);+ let _ = std::fs::remove_dir_all(&dir);+}