#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere
TypeScript dockerhacktoberfestjavapdfpdf-converterpdf-editorpdf-manipulationpdf-mergerpdf-ocrpdf-toolspdf-web-appspdfmergerself-hosted
Match scanned text, installed fonts and subset fonts to the right typeface in the PDF text editor (#8798)
Anthony Stirling20f102306949
diff --git a/app/core/src/main/resources/static/fonts/Caladea-Bold.ttf b/app/core/src/main/resources/static/fonts/Caladea-Bold.ttfnew file mode 100644index 0000000000..a41e29a6f8Binary files /dev/null and b/app/core/src/main/resources/static/fonts/Caladea-Bold.ttf differdiff --git a/app/core/src/main/resources/static/fonts/Caladea-LICENSE.txt b/app/core/src/main/resources/static/fonts/Caladea-LICENSE.txtnew file mode 100644index 0000000000..f6c716248d--- /dev/null+++ b/app/core/src/main/resources/static/fonts/Caladea-LICENSE.txt@@ -0,0 +1,178 @@+Caladea: Copyright (c) 2012 Huerta Tipografia. Licensed under the Apache License, Version 2.0.++ 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/app/core/src/main/resources/static/fonts/Caladea-Regular.ttf b/app/core/src/main/resources/static/fonts/Caladea-Regular.ttfnew file mode 100644index 0000000000..a0802530deBinary files /dev/null and b/app/core/src/main/resources/static/fonts/Caladea-Regular.ttf differdiff --git a/app/core/src/main/resources/static/fonts/Carlito-Bold.ttf b/app/core/src/main/resources/static/fonts/Carlito-Bold.ttfnew file mode 100644index 0000000000..b29a590511Binary files /dev/null and b/app/core/src/main/resources/static/fonts/Carlito-Bold.ttf differdiff --git a/app/core/src/main/resources/static/fonts/Carlito-OFL.txt b/app/core/src/main/resources/static/fonts/Carlito-OFL.txtnew file mode 100644index 0000000000..78279eac42--- /dev/null+++ b/app/core/src/main/resources/static/fonts/Carlito-OFL.txt@@ -0,0 +1,93 @@+Copyright (c) 2010-2013 by tyPoland Lukasz Dziedzic (http://www.typoland.com/) with Reserved Font Name "Carlito".++This Font Software is licensed under the SIL Open Font License, Version 1.1.+This license is copied below, and is also available with a FAQ at:+http://scripts.sil.org/OFL+++-----------------------------------------------------------+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007+-----------------------------------------------------------++PREAMBLE+The goals of the Open Font License (OFL) are to stimulate worldwide+development of collaborative font projects, to support the font creation+efforts of academic and linguistic communities, and to provide a free and+open framework in which fonts may be shared and improved in partnership+with others.++The OFL allows the licensed fonts to be used, studied, modified and+redistributed freely as long as they are not sold by themselves. The+fonts, including any derivative works, can be bundled, embedded,+redistributed and/or sold with any software provided that any reserved+names are not used by derivative works. The fonts and derivatives,+however, cannot be released under any other type of license. The+requirement for fonts to remain under this license does not apply+to any document created using the fonts or their derivatives.++DEFINITIONS+"Font Software" refers to the set of files released by the Copyright+Holder(s) under this license and clearly marked as such. This may+include source files, build scripts and documentation.++"Reserved Font Name" refers to any names specified as such after the+copyright statement(s).++"Original Version" refers to the collection of Font Software components as+distributed by the Copyright Holder(s).++"Modified Version" refers to any derivative made by adding to, deleting,+or substituting -- in part or in whole -- any of the components of the+Original Version, by changing formats or by porting the Font Software to a+new environment.++"Author" refers to any designer, engineer, programmer, technical+writer or other person who contributed to the Font Software.++PERMISSION & CONDITIONS+Permission is hereby granted, free of charge, to any person obtaining+a copy of the Font Software, to use, study, copy, merge, embed, modify,+redistribute, and sell modified and unmodified copies of the Font+Software, subject to the following conditions:++1) Neither the Font Software nor any of its individual components,+in Original or Modified Versions, may be sold by itself.++2) Original or Modified Versions of the Font Software may be bundled,+redistributed and/or sold with any software, provided that each copy+contains the above copyright notice and this license. These can be+included either as stand-alone text files, human-readable headers or+in the appropriate machine-readable metadata fields within text or+binary files as long as those fields can be easily viewed by the user.++3) No Modified Version of the Font Software may use the Reserved Font+Name(s) unless explicit written permission is granted by the corresponding+Copyright Holder. This restriction only applies to the primary font name as+presented to the users.++4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font+Software shall not be used to promote, endorse or advertise any+Modified Version, except to acknowledge the contribution(s) of the+Copyright Holder(s) and the Author(s) or with their explicit written+permission.++5) The Font Software, modified or unmodified, in part or in whole,+must be distributed entirely under this license, and must not be+distributed under any other license. The requirement for fonts to+remain under this license does not apply to any document created+using the Font Software.++TERMINATION+This license becomes null and void if any of the above conditions are+not met.++DISCLAIMER+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM+OTHER DEALINGS IN THE FONT SOFTWARE.diff --git a/app/core/src/main/resources/static/fonts/Carlito-Regular.ttf b/app/core/src/main/resources/static/fonts/Carlito-Regular.ttfnew file mode 100644index 0000000000..6b7e0e38e9Binary files /dev/null and b/app/core/src/main/resources/static/fonts/Carlito-Regular.ttf differdiff --git a/frontend/public/locales/en-US/translation.toml b/frontend/public/locales/en-US/translation.tomlindex 8f90263ffd..268a09d61d 100644--- a/frontend/public/locales/en-US/translation.toml+++ b/frontend/public/locales/en-US/translation.toml@@ -7576,6 +7576,7 @@ widget = "Form field - not page text, so it can't be edited here"[pdfTextEditor.commands]edit = "Edit"markTagged = "Mark as fully tagged"+matchScanFont = "Match scanned text to {{face}}"mergeRuns_one = "Merge {{count}} run into a paragraph"mergeRuns_other = "Merge {{count}} runs into a paragraph"setColour = "Set colour on {{run}}"@@ -7601,6 +7602,7 @@ title = "Drop a PDF to open"[pdfTextEditor.error]decodeImage = "Could not decode the selected image."insertImage = "Could not insert the selected image."+scanOffInk = "Can't edit this text: its recognised words don't line up with the scan. Run OCR again."[pdfTextEditor.externalEdit]pngFileType = "PNG image"@@ -7626,12 +7628,16 @@ deviceFontsNone = "No extra device fonts were found."deviceFontsUnavailable = "Device fonts are unavailable. The built-in fonts still work."deviceGroup = "Device fonts"documentGroup = "Document font"+embeddingForbidden = "This font's licence does not allow embedding it in a PDF. The text was left unchanged."embedFailed = "This font could not be embedded in the PDF. The text was left unchanged."+includedGroup = "Included fonts"label = "Font family"+matchedGroup = "Matched font"mixed = "Mixed"noGlyphs = "This font has no characters for the selected text. The text was left unchanged."noMatch = "No matching font"placeholder = "Font family"+scannedText = "Scanned text"serverFontFailed = "That server font could not be downloaded. The text was left unchanged."serverGroup = "Server fonts"useDeviceFonts = "Use device fonts"@@ -7702,6 +7708,8 @@ zoomDesc = "Zoom in / out"[pdfTextEditor.inspector]document = "Document"+fontCompletedClosest = "Embedded font · characters it lacks are drawn in {{name}}, the closest match available."+fontCompletedOriginal = "Embedded font · characters it lacks are drawn in {{name}}, the same font."fontEmbedded = "Embedded font · a character it lacks falls back to Helvetica."fontGap = "{{name}} · missing {{glyphs}} - typing those falls back to {{fallback}}."fontUnknownCoverage = "{{name}} · a character it lacks falls back to {{fallback}}."@@ -7731,6 +7739,9 @@ runOcr = "Run OCR"scanHint_one = "This page is a scanned image with no text to edit. Run OCR first to make its text editable."scanHint_other = "{{count}} pages are scanned images with no text to edit. Run OCR first to make their text editable."scannedText = "Scanned text · changed words are covered and redrawn in a matching font."+scannedTextMisaligned = "Scanned text · its recognised words do not line up with the scan, so this block cannot be edited or deleted."+scannedTextNoFont = "Scanned text · typed words in this script cannot be drawn yet, so they are not kept. Deleting words still works."+scannedTextOffInk = "Scanned text · its recognised words sit off the scanned words, so this block cannot be edited. Run OCR again."tabDocument = "Document"tabSelected = "Selected"textBoxes = "Text boxes"@@ -7915,6 +7926,35 @@ note = "Your edits are kept. The changes listed above are unavoidable when savinsaveAnyway = "Save anyway"title = "Saving will change this PDF"+[pdfTextEditor.scanFont]+approximate = "Approximate match"+approximateHint = "The closest font found may not match the scan."+change = "Font not looking right?"+choose = "Choose a font"+chooseMissing = "Choose a font for this text…"+compare = "Compare fonts…"+deviceAllow = "Allow font access for better matching"+deviceBlocked = "Your browser won't ask again. To allow it, click the icon left of the address bar, turn on Fonts, then try again."+deviceBlockedTitle = "Font access is blocked"+deviceNone = "None of the usual document fonts are installed on this computer."+deviceNote = "Your browser asks first. Fonts stay on this device."+deviceOn_one = "Also compared with {{count}} font on this computer."+deviceOn_other = "Also compared with {{count}} fonts on this computer."+deviceReading = "Reading fonts on this computer…"+deviceRetry = "Try again"+done = "Done"+hint = "Your typing is drawn in the closest font found. Pick another if it looks more like the scan."+hintFromScan = "Your typing is built from letters found in the scan. Pick a font to draw it in that font instead."+hintOthers = "Your pick is also used for scanned text you have not edited yet."+matching = "Matching fonts…"+noFont = "None of the available fonts can draw this script, so typed text cannot be redrawn yet."+scan = "Original scan"+scanAlt = "The scanned line"+scanNote = "Scans often look blurrier or bolder than the font really is. Compare letter shapes rather than thickness."+score = "{{match}}% alike"+title = "Match the scanned font"+unmeasurable = "This scan is too faint or small to match a font to."+[pdfTextEditor.settings]advanced = "Advanced"find = "Find in document"diff --git a/frontend/src-tauri/Cargo.lock b/frontend/src-tauri/Cargo.lockindex 5601347588..867cbc14fa 100644--- a/frontend/src-tauri/Cargo.lock+++ b/frontend/src-tauri/Cargo.lock@@ -1342,6 +1342,28 @@ version = "0.2.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"+[[package]]+name = "fontconfig-parser"+version = "0.5.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bbc773e24e02d4ddd8395fd30dc147524273a83e54e0f312d986ea30de5f5646"+dependencies = [+ "roxmltree",+]++[[package]]+name = "fontdb"+version = "0.24.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2660c5e9157bf76d2db1294e4a9feba604ef610819a3b591088d0d8392a3290f"+dependencies = [+ "fontconfig-parser",+ "log",+ "memmap2",+ "slotmap",+ "tinyvec",+]+[[package]]name = "foreign-types"version = "0.5.0"@@ -2548,6 +2570,15 @@ version = "2.8.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79"+[[package]]+name = "memmap2"+version = "0.9.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6b0ca1155a9ecc25aa12e8313a119f32edf0255fea2f44839c4ac0a12b2ac157"+dependencies = [+ "libc",+]+[[package]]name = "memoffset"version = "0.9.1"@@ -3972,6 +4003,12 @@ dependencies = ["syn 1.0.109",]+[[package]]+name = "roxmltree"+version = "0.20.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6c20b6793b5c2fa6553b250154b78d6d0db37e72700ae35fad9387a46f487c97"+[[package]]name = "rust-ini"version = "0.21.3"@@ -4556,6 +4593,15 @@ version = "0.4.12"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"+[[package]]+name = "slotmap"+version = "1.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bdd58c3c93c3d278ca835519292445cb4b0d4dc59ccfdf7ceadaab3f8aeb4038"+dependencies = [+ "version_check",+]+[[package]]name = "smallvec"version = "1.15.1"@@ -4633,6 +4679,7 @@ dependencies = ["base64 0.23.1","core-foundation 0.10.1","core-services",+ "fontdb","keyring","log","notify",@@ -4662,6 +4709,7 @@ dependencies = ["tempfile","tiny_http","tokio",+ "ttf-parser","url","urlencoding","webview2-com",@@ -5797,6 +5845,12 @@ version = "0.2.5"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"+[[package]]+name = "ttf-parser"+version = "0.25.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d2df906b07856748fa3f6e0ad0cbaa047052d4a7dd609e231c4f72cee8c36f31"+[[package]]name = "typeid"version = "1.0.3"diff --git a/frontend/src-tauri/Cargo.toml b/frontend/src-tauri/Cargo.tomlindex 4513132f77..9cf3c88fdf 100644--- a/frontend/src-tauri/Cargo.toml+++ b/frontend/src-tauri/Cargo.toml@@ -51,6 +51,8 @@ sha2 = "0.11"base64 = "0.23"rand = "0.10"tempfile = "3.27"+fontdb = "0.24"+ttf-parser = "0.25"[target.'cfg(target_os = "macos")'.dependencies]core-foundation = "0.10"diff --git a/frontend/src-tauri/src/commands/fonts.rs b/frontend/src-tauri/src/commands/fonts.rsnew file mode 100644index 0000000000..1df2db73d4--- /dev/null+++ b/frontend/src-tauri/src/commands/fonts.rs@@ -0,0 +1,411 @@+use std::path::{Path, PathBuf};+use std::sync::OnceLock;++use serde::Serialize;+use tauri::ipc::Response;+use ttf_parser::{name_id, Face, Language, Permissions, Tag};++#[derive(Clone, Debug, PartialEq, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct SystemFontFace {+ id: usize,+ family: String,+ full_name: String,+ style: String,+ postscript_name: String,+ weight: u16,+ bold: bool,+ italic: bool,+}++struct CatalogEntry {+ face: SystemFontFace,+ path: PathBuf,+}++struct FaceNames {+ style: Option<String>,+ full_name: Option<String>,+}++static CATALOG: OnceLock<Vec<CatalogEntry>> = OnceLock::new();++const SEMIBOLD_WEIGHT: u16 = 600;++/// Must stay equal to the server's `EditorFontRegistry.MAX_FONT_BYTES`: picking a face sends its whole file to the webview.+const MAX_FONT_BYTES: u64 = 64 * 1024 * 1024;++fn has_table(face: &Face, tag: &[u8; 4]) -> bool {+ face.raw_face().table(Tag::from_bytes(tag)).is_some()+}++/// A face with no OS/2 table records no restriction, which is how the server reads it too. One that is present but unreadable is refused.+fn embedding_allowed(face: &Face) -> bool {+ !has_table(face, b"OS/2")+ || (face.permissions() != Some(Permissions::Restricted)+ && face.is_outline_embedding_allowed())+}++/// A PDF embeds only a variable face's default instance. The table's presence decides, as on the server.+fn is_variable(face: &Face) -> bool {+ has_table(face, b"fvar")+}++/// A leading dot on either name marks an OS-private UI face: ".Keyboard", or "System Font" whose PostScript name is ".SFNS-Regular".+fn is_os_private(family: &str, post_script_name: &str) -> bool {+ family.starts_with('.') || post_script_name.starts_with('.')+}++fn fits_size_limit(size: std::io::Result<u64>) -> bool {+ size.is_ok_and(|bytes| bytes <= MAX_FONT_BYTES)+}++fn file_fits_size_limit(path: &Path) -> bool {+ fits_size_limit(std::fs::metadata(path).map(|file| file.len()))+}++/// The editor embeds device fonts as TrueType; a CFF face would save as a broken font resource.+fn has_truetype_outlines(face: &Face) -> bool {+ let tables = face.tables();+ tables.glyf.is_some() && tables.cff.is_none() && tables.cff2.is_none()+}++fn english_name(face: &Face, id: u16) -> Option<String> {+ let mut fallback = None;+ for name in face.names() {+ if name.name_id != id {+ continue;+ }+ let Some(text) = name.to_string().filter(|text| !text.trim().is_empty()) else {+ continue;+ };+ if name.language() == Language::English_UnitedStates {+ return Some(text);+ }+ fallback.get_or_insert(text);+ }+ fallback+}++/// The face's display names, or `None` when it is unparseable, variable, not licensed for embedding, or not TrueType.+fn embeddable_face_names(data: &[u8], index: u32) -> Option<FaceNames> {+ let face = Face::parse(data, index).ok()?;+ if is_variable(&face) || !embedding_allowed(&face) || !has_truetype_outlines(&face) {+ return None;+ }+ Some(FaceNames {+ style: english_name(&face, name_id::TYPOGRAPHIC_SUBFAMILY)+ .or_else(|| english_name(&face, name_id::SUBFAMILY)),+ full_name: english_name(&face, name_id::FULL_NAME),+ })+}++fn is_bold(info: &fontdb::FaceInfo) -> bool {+ info.weight.0 >= SEMIBOLD_WEIGHT+}++fn is_italic(info: &fontdb::FaceInfo) -> bool {+ info.style != fontdb::Style::Normal+}++fn style_from_axes(info: &fontdb::FaceInfo) -> String {+ match (is_bold(info), is_italic(info)) {+ (true, true) => "Bold Italic",+ (true, false) => "Bold",+ (false, true) => "Italic",+ (false, false) => "Regular",+ }+ .to_string()+}++fn source_path(source: &fontdb::Source) -> Option<PathBuf> {+ match source {+ fontdb::Source::File(path) | fontdb::Source::SharedFile(path, _) => Some(path.clone()),+ fontdb::Source::Binary(_) => None,+ }+}++fn build_catalog(db: &fontdb::Database) -> Vec<CatalogEntry> {+ let mut entries = Vec::new();+ for info in db.faces() {+ let Some(path) = source_path(&info.source) else {+ continue;+ };+ let Some((family, _)) = info.families.first() else {+ continue;+ };+ if info.post_script_name.is_empty()+ || is_os_private(family, &info.post_script_name)+ || !file_fits_size_limit(&path)+ {+ continue;+ }+ let Some(names) = db.with_face_data(info.id, embeddable_face_names).flatten() else {+ continue;+ };+ entries.push(CatalogEntry {+ face: SystemFontFace {+ id: entries.len(),+ family: family.clone(),+ full_name: names.full_name.unwrap_or_else(|| family.clone()),+ style: names.style.unwrap_or_else(|| style_from_axes(info)),+ postscript_name: info.post_script_name.clone(),+ weight: info.weight.0,+ bold: is_bold(info),+ italic: is_italic(info),+ },+ path,+ });+ }+ entries+}++fn catalog() -> &'static [CatalogEntry] {+ CATALOG.get_or_init(|| {+ let mut db = fontdb::Database::new();+ db.load_system_fonts();+ let entries = build_catalog(&db);+ log::info!(+ "System fonts: {} of {} installed faces can be embedded",+ entries.len(),+ db.len()+ );+ entries+ })+}++/// The installed faces the editor can embed: static TrueType outlines, a licence that allows embedding, and a file no larger than the server accepts.+#[tauri::command]+pub async fn list_system_fonts() -> Result<Vec<SystemFontFace>, String> {+ tauri::async_runtime::spawn_blocking(|| {+ catalog().iter().map(|entry| entry.face.clone()).collect()+ })+ .await+ .map_err(|e| e.to_string())+}++/// The font file behind an id from [`list_system_fonts`]; an id, not a path, so the webview reads only catalogued files.+#[tauri::command]+pub async fn read_system_font(id: usize) -> Result<Response, String> {+ let path = CATALOG+ .get()+ .and_then(|entries| entries.get(id))+ .map(|entry| entry.path.clone())+ .ok_or_else(|| "Unknown system font".to_string())?;+ tauri::async_runtime::spawn_blocking(move || std::fs::read(path))+ .await+ .map_err(|e| e.to_string())?+ .map(Response::new)+ .map_err(|e| e.to_string())+}++#[cfg(test)]+mod tests {+ use super::*;++ const FS_TYPE_OFFSET: usize = 8;+ const TABLE_DIRECTORY_OFFSET: usize = 12;+ const TABLE_RECORD_SIZE: usize = 16;++ fn bundled(name: &str) -> Vec<u8> {+ let dir = concat!(+ env!("CARGO_MANIFEST_DIR"),+ "/../../app/core/src/main/resources/static/fonts/"+ );+ std::fs::read(format!("{dir}{name}")).expect("bundled font is readable")+ }++ fn bundled_font() -> Vec<u8> {+ bundled("Carlito-Regular.ttf")+ }++ fn os2_offset(data: &[u8]) -> usize {+ ttf_parser::RawFace::parse(data, 0)+ .expect("font parses")+ .table(ttf_parser::Tag::from_bytes(b"OS/2"))+ .expect("font has an OS/2 table")+ .as_ptr() as usize+ - data.as_ptr() as usize+ }++ fn with_fs_type(mut data: Vec<u8>, fs_type: u16) -> Vec<u8> {+ let os2 = os2_offset(&data);+ data[os2 + FS_TYPE_OFFSET..os2 + FS_TYPE_OFFSET + 2]+ .copy_from_slice(&fs_type.to_be_bytes());+ data+ }++ fn with_os2_version(mut data: Vec<u8>, version: u16) -> Vec<u8> {+ let os2 = os2_offset(&data);+ data[os2..os2 + 2].copy_from_slice(&version.to_be_bytes());+ data+ }++ /// The parser binary-searches the table directory, so `to` must sort where `from` did.+ fn with_table_renamed(mut data: Vec<u8>, from: &[u8; 4], to: &[u8; 4]) -> Vec<u8> {+ let tables = usize::from(u16::from_be_bytes([data[4], data[5]]));+ let record = (0..tables)+ .map(|table| TABLE_DIRECTORY_OFFSET + table * TABLE_RECORD_SIZE)+ .find(|&record| data[record..record + 4] == from[..])+ .expect("font has the table");+ data[record..record + 4].copy_from_slice(to);+ data+ }++ fn catalog_of(data: Vec<u8>) -> Vec<CatalogEntry> {+ let size = data.len() as u64;+ catalog_of_file_sized(data, size)+ }++ /// Extends the file without writing the tail, so one at the size limit stays cheap to make.+ fn catalog_of_file_sized(data: Vec<u8>, size: u64) -> Vec<CatalogEntry> {+ let dir = tempfile::tempdir().expect("temp dir");+ let path = dir.path().join("font.ttf");+ std::fs::write(&path, data).expect("font written");+ std::fs::OpenOptions::new()+ .write(true)+ .open(&path)+ .and_then(|file| file.set_len(size))+ .expect("font resized");+ let mut db = fontdb::Database::new();+ db.load_fonts_dir(dir.path());+ build_catalog(&db)+ }++ #[test]+ fn lists_an_embeddable_face_with_its_names() {+ let entries = catalog_of(with_fs_type(bundled_font(), 0x0000));+ assert_eq!(entries.len(), 1);+ let face = &entries[0].face;+ assert_eq!(face.family, "Carlito");+ assert_eq!(face.style, "Regular");+ assert_eq!(face.postscript_name, "Carlito");+ assert_eq!(face.id, 0);+ }++ fn with_name_text(mut data: Vec<u8>, from: &str, to: &str) -> Vec<u8> {+ let name = ttf_parser::RawFace::parse(&data, 0)+ .expect("font parses")+ .table(ttf_parser::Tag::from_bytes(b"name"))+ .expect("font has a name table");+ let start = name.as_ptr() as usize - data.as_ptr() as usize;+ let end = start + name.len();+ let encodings = [+ (from.as_bytes().to_vec(), to.as_bytes().to_vec()),+ (+ from.encode_utf16().flat_map(u16::to_be_bytes).collect(),+ to.encode_utf16().flat_map(u16::to_be_bytes).collect(),+ ),+ ];+ for (needle, replacement) in encodings {+ let mut at = start;+ while at + needle.len() <= end {+ if data[at..at + needle.len()] == needle[..] {+ data[at..at + needle.len()].copy_from_slice(&replacement);+ at += needle.len();+ } else {+ at += 1;+ }+ }+ }+ data+ }++ #[test]+ fn reports_the_style_axes_whatever_language_the_style_name_is_in() {+ let entries = catalog_of(with_name_text(bundled("Carlito-Bold.ttf"), "Bold", "Fett"));+ assert_eq!(entries.len(), 1);+ let face = serde_json::to_value(&entries[0].face).expect("face serialises");+ assert_eq!(face["style"], "Fett");+ assert_eq!(face["bold"], true);+ assert_eq!(face["italic"], false);+ assert_eq!(face["weight"], 700);+ }++ #[test]+ fn reports_an_italic_face_as_italic() {+ let entries = catalog_of(bundled("LiberationSans-Italic.ttf"));+ let face = serde_json::to_value(&entries[0].face).expect("face serialises");+ assert_eq!(face["bold"], false);+ assert_eq!(face["italic"], true);+ assert_eq!(face["weight"], 400);+ }++ #[test]+ fn keeps_preview_and_editable_embedding() {+ assert_eq!(catalog_of(with_fs_type(bundled_font(), 0x0004)).len(), 1);+ assert_eq!(catalog_of(with_fs_type(bundled_font(), 0x0008)).len(), 1);+ assert_eq!(catalog_of(with_fs_type(bundled_font(), 0x0108)).len(), 1);+ }++ #[test]+ fn drops_a_face_whose_licence_forbids_embedding() {+ assert!(catalog_of(with_fs_type(bundled_font(), 0x0002)).is_empty());+ }++ #[test]+ fn drops_a_bitmap_only_face() {+ assert!(catalog_of(with_fs_type(bundled_font(), 0x0208)).is_empty());+ }++ #[test]+ fn lists_a_face_with_no_os2_table() {+ let entries = catalog_of(with_table_renamed(bundled_font(), b"OS/2", b"OS/1"));+ assert_eq!(entries.len(), 1);+ assert_eq!(entries[0].face.family, "Carlito");+ }++ #[test]+ fn drops_a_face_whose_os2_table_cannot_be_read() {+ let unreadable = with_os2_version(with_fs_type(bundled_font(), 0x0002), 0xFFFF);+ assert!(catalog_of(unreadable).is_empty());+ }++ #[test]+ fn drops_a_face_with_an_fvar_table() {+ assert!(catalog_of(with_table_renamed(bundled_font(), b"fpgm", b"fvar")).is_empty());+ }++ #[test]+ fn a_leading_dot_on_either_name_is_os_private() {+ assert!(is_os_private(".Keyboard", "Keyboard"));+ assert!(is_os_private("System Font", ".SFNS-Regular"));+ assert!(!is_os_private("Carlito", "Carlito-Bold"));+ }++ #[test]+ fn drops_a_face_whose_postscript_name_is_os_private() {+ let entries = catalog_of(with_name_text(+ bundled("Carlito-Bold.ttf"),+ "Carlito-Bold",+ ".arlito-Bold",+ ));+ assert!(entries.is_empty());+ }++ #[test]+ fn a_size_that_is_too_large_or_unreadable_does_not_fit() {+ assert!(fits_size_limit(Ok(MAX_FONT_BYTES)));+ assert!(!fits_size_limit(Ok(MAX_FONT_BYTES + 1)));+ assert!(!fits_size_limit(Err(std::io::ErrorKind::NotFound.into())));+ }++ #[test]+ fn drops_a_file_over_the_size_limit() {+ assert_eq!(+ catalog_of_file_sized(bundled_font(), MAX_FONT_BYTES).len(),+ 1+ );+ assert!(catalog_of_file_sized(bundled_font(), MAX_FONT_BYTES + 1).is_empty());+ }++ #[test]+ fn drops_a_face_with_postscript_outlines() {+ assert!(catalog_of(bundled("NotoSansTC-Regular.ttf")).is_empty());+ }++ #[test]+ fn drops_an_unparseable_face() {+ assert!(embeddable_face_names(b"not a font", 0).is_none());+ }+}diff --git a/frontend/src-tauri/src/commands/mod.rs b/frontend/src-tauri/src/commands/mod.rsindex 48bb1dc0d6..f447cb28cf 100644--- a/frontend/src-tauri/src/commands/mod.rs+++ b/frontend/src-tauri/src/commands/mod.rs@@ -4,6 +4,7 @@ pub mod connection;pub mod default_app;pub mod file_drop;pub mod files;+pub mod fonts;pub mod local_proxy;pub mod platform;pub mod print;diff --git a/frontend/src-tauri/src/lib.rs b/frontend/src-tauri/src/lib.rsindex 8a48fe4c4e..d2d134084f 100644--- a/frontend/src-tauri/src/lib.rs+++ b/frontend/src-tauri/src/lib.rs@@ -236,6 +236,8 @@ pub fn run() {get_update_mode,set_update_mode,restart_app,+ commands::fonts::list_system_fonts,+ commands::fonts::read_system_font,]).build(tauri::generate_context!()).expect("error while building tauri application")diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-clip-path.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-clip-path.spec.tsindex 407280e012..32e6a54c7f 100644--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-clip-path.spec.ts+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-clip-path.spec.ts@@ -27,18 +27,33 @@ test.describe("PDF text editor - clip paths follow their object", () => {await page.evaluate(() => {/* eslint-disable @typescript-eslint/no-explicit-any */const w = window as any;- const m = (w.__editor_store.doc ?? w.__editor_store.document).module;- w.__clipProbe = [] as Array<{ kind: string; args: number[] }>;+ const doc = w.__editor_store.doc ?? w.__editor_store.document;+ const m = doc.module;+ const livePages = new Set(+ doc.loadedPages().map((p: { pagePtr: number }) => p.pagePtr),+ );+ const offPage = new Set<number>();+ const calls: Array<{ kind: string; obj: number; args: number[] }> = [];+ w.__clipProbe = () =>+ calls+ .filter((c) => !offPage.has(c.obj))+ .map(({ kind, args }) => ({ kind, args }));const realObj = m.FPDFPageObj_Transform.bind(m);const realClip = m.FPDFPageObj_TransformClipPath.bind(m);+ const realInsert = m.FPDFPage_InsertObject.bind(m);m.FPDFPageObj_Transform = (...args: number[]) => {- w.__clipProbe.push({ kind: "object", args: args.slice(1) });+ calls.push({ kind: "object", obj: args[0], args: args.slice(1) });return realObj(...args);};m.FPDFPageObj_TransformClipPath = (...args: number[]) => {- w.__clipProbe.push({ kind: "clip", args: args.slice(1) });+ calls.push({ kind: "clip", obj: args[0], args: args.slice(1) });return realClip(...args);};+ // Background font matching draws trial text on scratch pages through the same module.+ m.FPDFPage_InsertObject = (pagePtr: number, obj: number) => {+ if (!livePages.has(pagePtr)) offPage.add(obj);+ return realInsert(pagePtr, obj);+ };/* eslint-enable @typescript-eslint/no-explicit-any */});@@ -62,13 +77,12 @@ test.describe("PDF text editor - clip paths follow their object", () => {});const read = () =>- page.evaluate(- () =>- (- window as unknown as {- __clipProbe: Array<{ kind: string; args: number[] }>;- }- ).__clipProbe,+ page.evaluate(() =>+ (+ window as unknown as {+ __clipProbe: () => Array<{ kind: string; args: number[] }>;+ }+ ).__clipProbe(),);const afterMove = await read();diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-font-recognition.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-font-recognition.spec.tsindex 19b8f26a96..1ae71ea502 100644--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-font-recognition.spec.ts+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-font-recognition.spec.ts@@ -117,4 +117,100 @@ test.describe("PDF text editor - document font recognition", () => {`picking the recognised font rewrote ${before} to ${after}`,).toBe(before);});++ // Without the original installed, a character the subset lacks is drawn in the closest available face.+ test("draws a character the subset lacks in the closest face, and names it", async ({+ page,+ }) => {+ await openEditor(page, SUBSET_PDF);++ const run = await embeddedRun(page);+ expect(run).toBeTruthy();+ await page.locator(`[data-testid="pdf-editor-run-${run!.id}"]`).click();++ const note = page.getByText(/closest match available/);+ await expect(+ note,+ "no lookalike was found for the embedded subset",+ ).toBeVisible({ timeout: 30_000 });+ const face = /drawn in (.+), the closest match/.exec(+ (await note.textContent()) ?? "",+ )?.[1];+ expect(face, "the note did not name the face").toBeTruthy();++ await page.keyboard.press("ControlOrMeta+ArrowRight");+ await page.keyboard.type(" Q", { delay: 60 });+ await page.keyboard.press("Escape");++ await expect+ .poll(+ () =>+ page.evaluate((rid) => {+ const w = window as unknown as {+ __editor_store: {+ state: {+ pages: { runs: { id: string; text: string }[] }[];+ };+ };+ };+ return w.__editor_store.state.pages+ .flatMap((p) => p.runs)+ .find((r) => r.id === rid)?.text;+ }, run!.id),+ { message: "the typed character was not kept" },+ )+ .toContain("Q");++ const drawnIn = await page.evaluate(async () => {+ const w = window as unknown as {+ __editor_store: {+ document: {+ docPtr: number;+ module: {+ FPDF_GetPageCount: (doc: number) => number;+ FPDF_LoadPage: (doc: number, index: number) => number;+ FPDF_ClosePage: (page: number) => void;+ FPDFPage_CountObjects: (page: number) => number;+ FPDFPage_GetObject: (page: number, index: number) => number;+ FPDFPageObj_GetType: (obj: number) => number;+ FPDFTextObj_GetFont: (obj: number) => number;+ FPDFFont_GetBaseFontName: (+ font: number,+ buffer: number,+ length: number,+ ) => number;+ pdfium: {+ wasmExports: {+ malloc: (size: number) => number;+ free: (at: number) => void;+ };+ UTF8ToString: (at: number) => string;+ };+ };+ page: (index: number) => { pagePtr: number };+ };+ };+ };+ const doc = w.__editor_store.document;+ const m = doc.module;+ const pagePtr = doc.page(0).pagePtr;+ const names = new Set<string>();+ for (let i = 0; i < m.FPDFPage_CountObjects(pagePtr); i++) {+ const obj = m.FPDFPage_GetObject(pagePtr, i);+ if (m.FPDFPageObj_GetType(obj) !== 1) continue;+ const font = m.FPDFTextObj_GetFont(obj);+ const length = m.FPDFFont_GetBaseFontName(font, 0, 0);+ const buffer = m.pdfium.wasmExports.malloc(length);+ m.FPDFFont_GetBaseFontName(font, buffer, length);+ names.add(m.pdfium.UTF8ToString(buffer));+ m.pdfium.wasmExports.free(buffer);+ }+ return [...names];+ });+ const squashed = (name: string) => name.replace(/[^a-z0-9]/gi, "");+ expect(+ drawnIn.map(squashed),+ `the typed character was not drawn in ${face}`,+ ).toContain(squashed(face!));+ });});diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-scanned-ocr.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-scanned-ocr.spec.tsindex 773ab5b92d..aa4eb70ab1 100644--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-scanned-ocr.spec.ts+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-scanned-ocr.spec.ts@@ -1,5 +1,5 @@import { test, expect } from "@editor/tests/helpers/stub-test-base";-import type { Page } from "@playwright/test";+import type { Locator, Page } from "@playwright/test";import path from "path";import { readFile } from "node:fs/promises";import { waitForEditorReady } from "@editor/tests/stubbed/editorReady";@@ -128,6 +128,22 @@ async function bitmapSig(page: Page): Promise<string> {}, PAGE_TESTID);}+// The picker slides in for ~150ms; a click aimed while it moves can land beside the button.+async function untilStill(target: Locator): Promise<void> {+ let prev = "";+ await expect+ .poll(+ async () => {+ const box = JSON.stringify(await target.boundingBox());+ const still = box !== "null" && box === prev;+ prev = box;+ return still;+ },+ { message: "control never stopped moving", intervals: [100] },+ )+ .toBe(true);+}+// Wait until the bitmap differs from `from` (when given), then holds still.async function settle(page: Page, from?: string): Promise<void> {let prev = "";@@ -774,3 +790,54 @@ test("only blurry scans get softened edits", async ({ page }) => {await replaceRunText(page, south.id, south.text.replace("SOUTH", "EAST"));expect(await blockSoftness(page, south.id)).toBeGreaterThan(0);});++test("a scanned edit applies the best font, the picker swaps it, and undo puts it back", async ({+ page,+}) => {+ test.setTimeout(150_000);+ await openForm(page);+ const line = (await runs(page)).find((r) => r.renderMode === 3)!;+ const runBox = page.getByTestId(`pdf-editor-run-${line.id}`);+ const choices = page.getByTestId("pdf-editor-scan-font-choice");+ const applied = choices.and(page.locator('[aria-pressed="true"]'));+ const open = page.getByTestId("pdf-editor-scan-font-open");+ const label = (i: number) => choices.nth(i).locator("p").first().innerText();+ await runBox.click();+ await expect(open).toHaveCount(0);++ await replaceRunText(page, line.id, `${line.text}X`);+ await expect(choices).toHaveCount(0);+ await runBox.click();+ await open.click();+ await expect(choices.first()).toBeVisible({ timeout: 30_000 });+ expect(await choices.count()).toBeGreaterThan(1);+ await expect(choices.first()).toHaveAttribute("aria-pressed", "true");+ const best = await label(0);+ const runnerUp = await label(1);++ await snap(page, "edited");+ const edited = await bitmapSig(page);+ await untilStill(choices.nth(1));+ await choices.nth(1).click();+ await expect(choices).toHaveCount(0);+ await settle(page, edited);++ await open.click();+ await expect(applied).toHaveCount(1, { timeout: 30_000 });+ await expect(applied).toContainText(runnerUp);+ const done = page.getByTestId("pdf-editor-scan-font-done");+ await untilStill(done);+ await done.click();+ await expect(choices).toHaveCount(0);++ const picked = await bitmapSig(page);+ await page.getByTestId("pdf-editor-undo").click();+ await settle(page, picked);+ await snap(page, "undone");+ expect(await diff(page, "edited", "undone")).toBeLessThan(20);++ await runBox.click();+ await open.click();+ await expect(applied).toHaveCount(1, { timeout: 30_000 });+ await expect(applied).toContainText(best);+});diff --git a/frontend/src/editor/core/tools/pdfTextEditor/PdfTextEditor.tsx b/frontend/src/editor/core/tools/pdfTextEditor/PdfTextEditor.tsxindex c15e21a422..40baaca861 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/PdfTextEditor.tsx+++ b/frontend/src/editor/core/tools/pdfTextEditor/PdfTextEditor.tsx@@ -59,6 +59,7 @@ import {type SaveRisks,} from "@editor/tools/pdfTextEditor/util/documentRisks";import { preloadFallbackFontBytes } from "@editor/tools/pdfTextEditor/util/fallbackFont";+import { useScanPrefit } from "@editor/tools/pdfTextEditor/hooks/useScanPrefit";import { visiblePageNumber } from "@editor/tools/pdfTextEditor/util/dom";import type {GroupingMode,@@ -148,6 +149,8 @@ export default function PdfTextEditor(_props: BaseToolProps) {void preloadFallbackFontBytes();}, []);+ useScanPrefit(store, state);+const sel = useSelectionActions(store);// Guards against re-entrant saves while a (synchronous) serialize runs.diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/LineGrouperSpacing.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/LineGrouperSpacing.test.tsindex 350a5b7ee9..ee2d6e7243 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/LineGrouperSpacing.test.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/LineGrouperSpacing.test.ts@@ -3,6 +3,7 @@ import { describe, it, expect } from "vitest";import { Page } from "@editor/tools/pdfTextEditor/model/Page";import { TextRun } from "@editor/tools/pdfTextEditor/model/TextRun";import { LineGrouper } from "@editor/tools/pdfTextEditor/pdfium/LineGrouper";+import { RENDER_MODE_INVISIBLE } from "@editor/tools/pdfTextEditor/types";let ptr = 5000;function mkRun(opts: {@@ -169,3 +170,58 @@ describe("LineGrouper inter-run space synthesis", () => {expect(text).toBe("Water");});});++describe("LineGrouper text layers", () => {+ it("keeps visible text out of a line of invisible OCR words", () => {+ const [typed, ...ocr] = lineOf(+ [+ { text: "Receipt", width: 35, gapAfter: 3.2 },+ { text: "4471", width: 20, gapAfter: 3.2 },+ { text: "for", width: 14 },+ ],+ 10,+ );+ for (const run of ocr) run.renderMode = 3;+ const page = new Page({ index: 0, pagePtr: 1, width: 600, height: 800 });+ page.setRuns([typed, ...ocr]);+ page.loaded = true;+ const groups = LineGrouper.apply(page);+ expect(+ groups.map((g) => [g.representative.text, g.representative.renderMode]),+ ).toEqual([+ ["Receipt", 0],+ ["4471 for", 3],+ ]);+ });+});++describe("LineGrouper text layers", () => {+ it("keeps a whole line in each layer when OCR words sit over the printed ones", () => {+ const printed = lineOf(+ [+ { text: "Hello", width: 25, gapAfter: 3.2 },+ { text: "world", width: 27 },+ ],+ 10,+ );+ const ocr = printed.map((r) => {+ const copy = mkRun({+ x: r.bounds.x + 1,+ width: r.bounds.width,+ f: 500,+ fs: 10,+ text: r.text,+ });+ copy.renderMode = RENDER_MODE_INVISIBLE;+ return copy;+ });+ const page = new Page({ index: 0, pagePtr: 1, width: 600, height: 800 });+ page.setRuns([...printed, ...ocr]);+ page.loaded = true;+ const groups = LineGrouper.apply(page);+ expect(groups.map((g) => g.representative.text).sort()).toEqual([+ "Hello world",+ "Hello world",+ ]);+ });+});diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/base14Text.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/base14Text.test.tsnew file mode 100644index 0000000000..6e1979c43e--- /dev/null+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/base14Text.test.ts@@ -0,0 +1,97 @@+// @vitest-environment node+import { readFile } from "node:fs/promises";+import { createRequire } from "node:module";+import { afterAll, beforeAll, expect, test, vi } from "vitest";+import { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";+import { uniformTags } from "@editor/tools/pdfTextEditor/model/TextTags";+import { PdfiumTextReader } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTextReader";+import { exportToBlob } from "@editor/tools/pdfTextEditor/util/exportPdf";+import {+ emitTextLine,+ getDroppedBase14Chars,+ resetDroppedBase14Chars,+ sanitizeForBase14,+} from "@editor/tools/pdfTextEditor/commands/editTextHelpers";+import {+ buildClassicPdf,+ streamBody,+} from "@editor/tools/pdfTextEditor/__tests__/pdfFixtures";++const PUNCTUATION = "don’t “quote” – — … € ™";++beforeAll(async () => {+ const wasmBytes = await readFile(+ createRequire(import.meta.url).resolve("@embedpdf/pdfium/pdfium.wasm"),+ );+ vi.stubGlobal(+ "fetch",+ vi.fn(async () =>+ Promise.resolve(+ new Response(wasmBytes, {+ headers: { "Content-Type": "application/wasm" },+ }),+ ),+ ),+ );+});++afterAll(() => {+ vi.unstubAllGlobals();+});++function blankPdf(): Uint8Array {+ return buildClassicPdf(+ [+ { num: 1, body: "<< /Type /Catalog /Pages 2 0 R >>" },+ { num: 2, body: "<< /Type /Pages /Kids [3 0 R] /Count 1 >>" },+ {+ num: 3,+ body: "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << >> /Contents 4 0 R >>",+ },+ { num: 4, body: streamBody("", "") },+ ],+ 1,+ );+}++test("base-14 keeps WinAnsi punctuation", () => {+ expect(sanitizeForBase14(PUNCTUATION)).toBe(PUNCTUATION);+ expect(sanitizeForBase14("a\u0007b\u0085c")).toBe("abc");+});++test("a base-14 emit writes WinAnsi punctuation in the base-14 font", async () => {+ resetDroppedBase14Chars();+ const doc = await EditorDocument.open(blankPdf());+ try {+ const page = doc.page(0);+ emitTextLine({+ doc,+ page,+ text: PUNCTUATION,+ x: 72,+ y: 700,+ fontSize: 12,+ fill: { r: 0, g: 0, b: 0, a: 255 },+ originalFontPtr: 0,+ fallbackFamily: "Times-Roman",+ tags: uniformTags([]),+ });+ expect(getDroppedBase14Chars()).toEqual([]);+ page.markDirty();+ page.markNeedsGenerate();+ const blob = await exportToBlob(doc);+ const back = await EditorDocument.open(+ new Uint8Array(await blob.arrayBuffer()),+ );+ try {+ const saved = back.page(0);+ PdfiumTextReader.populate(back, saved);+ expect(saved.runs.map((r) => r.text)).toEqual([PUNCTUATION]);+ expect(saved.runs[0].fontId).not.toMatch(/noto/i);+ } finally {+ back.dispose();+ }+ } finally {+ doc.dispose();+ }+});diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/deviceFontEmbed.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/deviceFontEmbed.test.tsindex d1b6c92ea8..a9e24d029e 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/deviceFontEmbed.test.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/deviceFontEmbed.test.ts@@ -17,6 +17,7 @@ import type { LocalFont } from "@editor/tools/pdfTextEditor/util/localFonts";import type { FontRef } from "@editor/tools/pdfTextEditor/model/FontRef";import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";import { Page } from "@editor/tools/pdfTextEditor/model/Page";+import { assembleSfnt } from "@editor/tools/pdfTextEditor/util/sfnt";type QueryStub = () => Promise<unknown[]>;@@ -61,8 +62,11 @@ function plainFont(family: string, style: string): LocalFont {};}-/** Not a real font file: parseTrueTypeCmap gives up, so coverage fails open. */-const FAKE_FONT_BYTES = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]);+/** TrueType outlines but no cmap, so coverage fails open. */+const FAKE_FONT_BYTES = assembleSfnt(+ 0x00010000,+ new Map([["glyf", new Uint8Array(4)]]),+);interface FakeModuleOptions {loadFont?: (@@ -237,6 +241,24 @@ describe("pickLocalFontFace", () => {);});+ it("finds the cuts of a family whose own name contains a style word", () => {+ const named = [+ plainFont("Times New Roman", "Regular"),+ plainFont("Times New Roman", "Bold"),+ plainFont("Times New Roman", "Italic"),+ plainFont("Book Antiqua", "Regular"),+ plainFont("Book Antiqua", "Bold"),+ ];+ expect(pickLocalFontFace(named, "Times New Roman Bold")?.style).toBe(+ "Bold",+ );+ expect(pickLocalFontFace(named, "Times New Roman Italic")?.style).toBe(+ "Italic",+ );+ expect(pickLocalFontFace(named, "Book Antiqua Bold")?.style).toBe("Bold");+ expect(pickLocalFontFace(named, "Book Antiqua")?.style).toBe("Regular");+ });+it("returns null when nothing matches", () => {expect(pickLocalFontFace(faces, "Comic Sans MS")).toBeNull();expect(pickLocalFontFace([], "Segoe UI")).toBeNull();diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/documentFontCompletion.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/documentFontCompletion.test.tsnew file mode 100644index 0000000000..030d73be7c--- /dev/null+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/documentFontCompletion.test.ts@@ -0,0 +1,396 @@+import { readFile } from "node:fs/promises";+import path from "node:path";+import { beforeEach, describe, expect, it, vi } from "vitest";+import type { WrappedPdfiumModule } from "@embedpdf/pdfium";+import {+ fontCanBeCompleted,+ fontCompletionFor,+ fontNameRefused,+ resetFontCompletions,+ resolveOriginalFonts,+ setClosestFont,+} from "@editor/tools/pdfTextEditor/util/documentFontCompletion";+import { resetFontHelperCaches } from "@editor/tools/pdfTextEditor/charcode/FontHelpers";+import { fallbackFamilyFor } from "@editor/tools/pdfTextEditor/util/fontCapability";+import { embeddedFontProgram } from "@editor/tools/pdfTextEditor/util/embeddedFace";+import { getExternalFontBytes } from "@editor/tools/pdfTextEditor/util/externalFonts";+import {+ listLocalFonts,+ registerFontBytes,+ resetLocalFontsCache,+ type LocalFont,+} from "@editor/tools/pdfTextEditor/util/localFonts";++vi.mock("@editor/tools/pdfTextEditor/util/embeddedFace", () => ({+ embeddedFontProgram: vi.fn(() => null),+}));++const FONTS = path.join(+ import.meta.dirname,+ "../../../../../../../app/core/src/main/resources/static/fonts",+);+const fontFile = async (name: string) =>+ new Uint8Array(await readFile(path.join(FONTS, name)));++interface Installed extends LocalFont {+ file: string;+}++const face = (+ family: string,+ style: string,+ postscriptName: string,+ file: string,+): Installed => ({+ family,+ fullName: style === "Regular" ? family : `${family} ${style}`,+ style,+ postscriptName,+ file,+});++async function install(fonts: Installed[]): Promise<void> {+ const files = new Map<string, Uint8Array>();+ for (const font of fonts) files.set(font.file, await fontFile(font.file));+ (window as unknown as { queryLocalFonts: unknown }).queryLocalFonts = vi.fn(+ async () =>+ fonts.map((font) => ({+ ...font,+ blob: async () => ({+ arrayBuffer: async () => files.get(font.file)!.slice().buffer,+ }),+ })),+ );+ await listLocalFonts();+}++// A document font whose /BaseFont reads `baseFont`.+function documentNaming(baseFont: string): WrappedPdfiumModule {+ return {+ FPDFFont_GetBaseFontName: () => baseFont.length + 1,+ pdfium: {+ wasmExports: { malloc: () => 8, free: () => undefined },+ UTF8ToString: () => baseFont,+ },+ } as unknown as WrappedPdfiumModule;+}++const stillOpen = () => true;++beforeEach(() => {+ resetLocalFontsCache();+ resetFontCompletions();+ resetFontHelperCaches();+ vi.mocked(embeddedFontProgram).mockReturnValue(null);+ delete (window as unknown as { queryLocalFonts?: unknown }).queryLocalFonts;+});++describe("resolveOriginalFonts", () => {+ it("completes a subset from the installed font its glyphs agree with", async () => {+ await install([+ face(+ "Liberation Sans",+ "Regular",+ "LiberationSans",+ "LiberationSans-Regular.ttf",+ ),+ ]);+ vi.mocked(embeddedFontProgram).mockReturnValue(+ await fontFile("LiberationSans-Regular.ttf"),+ );+ const id = "pdf:11:Liberation Sans";++ await resolveOriginalFonts(+ documentNaming("ABCDEF+LiberationSans"),+ [id],+ stillOpen,+ );++ expect(fontCompletionFor(id)).toEqual({+ family: "Liberation Sans",+ source: "original",+ });+ expect(fallbackFamilyFor(id)).toBe("Liberation Sans");+ });++ it("refuses an installed font that only shares the name", async () => {+ await install([+ face("Liberation Sans", "Regular", "LiberationSans", "DejaVuSans.ttf"),+ ]);+ vi.mocked(embeddedFontProgram).mockReturnValue(+ await fontFile("LiberationSans-Regular.ttf"),+ );+ const id = "pdf:12:Liberation Sans";++ await resolveOriginalFonts(+ documentNaming("ABCDEF+LiberationSans"),+ [id],+ stillOpen,+ );++ expect(fontCompletionFor(id)).toBeNull();+ expect(fontNameRefused(id)).toBe(true);+ expect(fallbackFamilyFor(id)).toBe("Helvetica");+ });++ it("finds the cut the PostScript name asks for, not the family's regular", async () => {+ await install([+ face(+ "Liberation Sans",+ "Regular",+ "LiberationSans",+ "LiberationSans-Regular.ttf",+ ),+ face(+ "Liberation Sans",+ "Bold",+ "LiberationSans-Bold",+ "LiberationSans-Bold.ttf",+ ),+ ]);+ vi.mocked(embeddedFontProgram).mockReturnValue(+ await fontFile("LiberationSans-Bold.ttf"),+ );+ const id = "pdf:13:Liberation Sans";++ await resolveOriginalFonts(+ documentNaming("EAAAAA+LiberationSans-Bold"),+ [id],+ stillOpen,+ );++ expect(fontCompletionFor(id)).toEqual({+ family: "Liberation Sans Bold",+ source: "original",+ });+ });++ it("finds a cut no bold or italic flag can name, and draws with that cut", async () => {+ await install([+ face(+ "Liberation Sans",+ "Regular",+ "LiberationSans",+ "LiberationSans-Regular.ttf",+ ),+ face(+ "Liberation Sans",+ "Light",+ "LiberationSans-Light",+ "DejaVuSans.ttf",+ ),+ ]);+ const light = await fontFile("DejaVuSans.ttf");+ vi.mocked(embeddedFontProgram).mockReturnValue(light);+ const id = "pdf:18:Liberation Sans";++ await resolveOriginalFonts(+ documentNaming("EAAAAA+LiberationSans-Light"),+ [id],+ stillOpen,+ );++ const completion = fontCompletionFor(id);+ expect(completion?.source).toBe("original");+ // toEqual walks a 750 KB array element by element, seconds on a CI runner.+ expect(+ Buffer.compare(getExternalFontBytes(completion!.family)!, light),+ ).toBe(0);+ expect(fontNameRefused(id)).toBe(false);+ });++ it("trusts the name when the embedded font cannot be read", async () => {+ await install([+ face(+ "Liberation Sans",+ "Regular",+ "LiberationSans",+ "LiberationSans-Regular.ttf",+ ),+ ]);+ const id = "pdf:14:Liberation Sans";++ await resolveOriginalFonts(+ documentNaming("LiberationSans"),+ [id],+ stillOpen,+ );++ expect(fontCompletionFor(id)?.source).toBe("original");+ });++ it("leaves a font nobody has installed without a completion", async () => {+ await install([+ face(+ "Liberation Sans",+ "Regular",+ "LiberationSans",+ "LiberationSans-Regular.ttf",+ ),+ ]);+ const id = "pdf:15:Frobnicate";++ await resolveOriginalFonts(+ documentNaming("QWERTY+Frobnicate"),+ [id],+ stillOpen,+ );++ expect(fontCompletionFor(id)).toBeNull();+ expect(fontNameRefused(id)).toBe(false);+ expect(fallbackFamilyFor(id)).toBe("Helvetica");+ });++ it("looks again when the font list changes while a lookup is reading a file", async () => {+ const regular = face(+ "Liberation Sans",+ "Regular",+ "LiberationSans",+ "LiberationSans-Regular.ttf",+ );+ const regularBytes = await fontFile(regular.file);+ let release: () => void = () => {};+ const held = new Promise<void>((resolve) => (release = resolve));+ const blob = vi.fn(async () => {+ await held;+ return { arrayBuffer: async () => regularBytes.slice().buffer };+ });+ (window as unknown as { queryLocalFonts: unknown }).queryLocalFonts = vi.fn(+ async () => [{ ...regular, blob }],+ );+ await listLocalFonts();+ vi.mocked(embeddedFontProgram).mockReturnValue(+ await fontFile("LiberationSans-Bold.ttf"),+ );+ const id = "pdf:19:Liberation Sans";+ const m = documentNaming("EAAAAA+LiberationSans-Bold");++ const first = resolveOriginalFonts(m, [id], stillOpen);+ await vi.waitFor(() => expect(blob).toHaveBeenCalled());+ resetLocalFontsCache();+ await install([+ regular,+ face(+ "Liberation Sans",+ "Bold",+ "LiberationSans-Bold",+ "LiberationSans-Bold.ttf",+ ),+ ]);+ await resolveOriginalFonts(m, [id], stillOpen);+ release();+ await first;++ expect(fontCompletionFor(id)).toEqual({+ family: "Liberation Sans Bold",+ source: "original",+ });+ });++ it("records nothing once the document has been closed", async () => {+ await install([+ face(+ "Liberation Sans",+ "Regular",+ "LiberationSans",+ "LiberationSans-Regular.ttf",+ ),+ ]);+ const id = "pdf:16:Liberation Sans";++ await resolveOriginalFonts(+ documentNaming("LiberationSans"),+ [id],+ () => false,+ );++ expect(fontCompletionFor(id)).toBeNull();+ });++ it("does nothing before any font list has loaded", async () => {+ const id = "pdf:17:Liberation Sans";+ await resolveOriginalFonts(+ documentNaming("LiberationSans"),+ [id],+ stillOpen,+ );+ expect(fontCompletionFor(id)).toBeNull();+ });+});++describe("fontCanBeCompleted", () => {+ it("leaves alone a standard font the file only names", () => {+ // PDFium draws a non-embedded Helvetica in a stand-in face whose family name is all the font id carries.+ expect(+ fontCanBeCompleted(documentNaming("Helvetica"), "pdf:31:Chrom Sans OTF"),+ ).toBe(false);+ expect(+ fontCanBeCompleted(+ documentNaming("Times-Bold"),+ "pdf:32:Chrom Serif OTF",+ ),+ ).toBe(false);+ });++ it("takes an embedded subset, tagged or not", () => {+ expect(+ fontCanBeCompleted(documentNaming("ABCDEF+Georgia"), "pdf:33:Georgia"),+ ).toBe(true);+ expect(fontCanBeCompleted(documentNaming("ArialMT"), "pdf:34:Arial")).toBe(+ true,+ );+ });++ it("is never true for a font that is not the document's own", () => {+ expect(+ fontCanBeCompleted(documentNaming("Georgia"), "device:Georgia"),+ ).toBe(false);+ expect(+ fontCanBeCompleted(documentNaming("Helvetica"), "base14:Helvetica"),+ ).toBe(false);+ });+});++describe("the closest font", () => {+ it("stands in until the original turns up, and never replaces it", async () => {+ const id = "pdf:21:Liberation Sans";+ registerFontBytes("DejaVu Sans", await fontFile("DejaVuSans.ttf"));++ setClosestFont(id, "DejaVu Sans");+ expect(fontCompletionFor(id)).toEqual({+ family: "DejaVu Sans",+ source: "closest",+ });+ expect(fallbackFamilyFor(id)).toBe("DejaVu Sans");++ await install([+ face(+ "Liberation Sans",+ "Regular",+ "LiberationSans",+ "LiberationSans-Regular.ttf",+ ),+ ]);+ await resolveOriginalFonts(+ documentNaming("LiberationSans"),+ [id],+ stillOpen,+ );+ setClosestFont(id, "DejaVu Sans");++ expect(fontCompletionFor(id)?.source).toBe("original");+ });++ it("is ignored while its font cannot be drawn", () => {+ setClosestFont("pdf:22:Whatever", "A Font With No Bytes");+ expect(fontCompletionFor("pdf:22:Whatever")).toBeNull();+ expect(fallbackFamilyFor("pdf:22:Whatever")).toBe("Helvetica");+ });++ it("is forgotten with the document", () => {+ setClosestFont("pdf:23:Whatever", "Times-Roman");+ expect(fontCompletionFor("pdf:23:Whatever")?.family).toBe("Times-Roman");+ resetFontCompletions();+ expect(fontCompletionFor("pdf:23:Whatever")).toBeNull();+ });+});diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/fontCapability.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/fontCapability.test.tsindex c7f9e610e1..6958fe7512 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/fontCapability.test.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/fontCapability.test.ts@@ -4,15 +4,18 @@ import {fallbackFamilyFor,fallbackFontIdFor,italicCapability,- resetDocumentFontMatchCache,- warmDocumentDeviceFonts,} from "@editor/tools/pdfTextEditor/util/fontCapability";+import {+ resetFontCompletions,+ resolveOriginalFonts,+} from "@editor/tools/pdfTextEditor/util/documentFontCompletion";import {listLocalFonts,- loadLocalFontBytes,resetLocalFontsCache,} from "@editor/tools/pdfTextEditor/util/localFonts";+import type { WrappedPdfiumModule } from "@embedpdf/pdfium";import type { LocalFont } from "@editor/tools/pdfTextEditor/util/localFonts";+import { assembleSfnt } from "@editor/tools/pdfTextEditor/util/sfnt";// The editor used to answer "make this italic" for ANY font by swapping the run// wholesale to Helvetica-Oblique. For a document set in Calibri that is not@@ -38,6 +41,9 @@ const CALIBRI: LocalFont[] = [},];+// PDFium gives no name or program for these fonts, so only the family in the font id is left.+const NO_FONT_DATA = {} as WrappedPdfiumModule;+/** An installed family with no italic cut at all. */const STENCIL: LocalFont[] = [{@@ -58,7 +64,9 @@ function stubQueryLocalFonts(fonts: LocalFont[] | null): void {fonts.map((font) => ({...font,blob: async () => ({- arrayBuffer: async () => new Uint8Array([1]).buffer,+ arrayBuffer: async () =>+ assembleSfnt(0x00010000, new Map([["glyf", new Uint8Array(4)]]))+ .buffer,}),})),);@@ -66,7 +74,7 @@ function stubQueryLocalFonts(fonts: LocalFont[] | null): void {beforeEach(() => {resetLocalFontsCache();- resetDocumentFontMatchCache();+ resetFontCompletions();stubQueryLocalFonts(null);});@@ -131,7 +139,7 @@ describe("fallbackFamilyFor", () => {it("keeps a subset family whose real face is loaded", async () => {stubQueryLocalFonts(CALIBRI);await listLocalFonts();- await warmDocumentDeviceFonts(["pdf:4242:Calibri"]);+ await resolveOriginalFonts(NO_FONT_DATA, ["pdf:4242:Calibri"], () => true);// Completing the subset now costs the document nothing: the edit re-emits// in Calibri's real bytes rather than Helvetica.@@ -142,28 +150,10 @@ describe("fallbackFamilyFor", () => {it("does not forget the face on the NEXT edit", async () => {stubQueryLocalFonts(CALIBRI);await listLocalFonts();- await warmDocumentDeviceFonts(["pdf:4242:Calibri"]);+ await resolveOriginalFonts(NO_FONT_DATA, ["pdf:4242:Calibri"], () => true);// The id an edit leaves behind must still resolve to the same real family.const nextId = fallbackFontIdFor(fallbackFamilyFor("pdf:4242:Calibri"));expect(fallbackFamilyFor(nextId)).toBe("Calibri");});});--describe("warmDocumentDeviceFonts", () => {- it("matches only the document's own families, exactly", async () => {- stubQueryLocalFonts(CALIBRI);- await listLocalFonts();- const matched = await warmDocumentDeviceFonts([- "base14:Helvetica",- "pdf:1:Calibri",- "pdf:2:SomeFontNobodyHas",- ]);- expect(matched).toEqual(["Calibri"]);- expect(await loadLocalFontBytes("SomeFontNobodyHas")).toBeNull();- });-- it("is a no-op before the user loads their device fonts", async () => {- expect(await warmDocumentDeviceFonts(["pdf:1:Calibri"])).toEqual([]);- });-});diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/fontCollection.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/fontCollection.test.tsnew file mode 100644index 0000000000..22e430ca24--- /dev/null+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/fontCollection.test.ts@@ -0,0 +1,150 @@+// @vitest-environment node+import { readFile } from "node:fs/promises";+import path from "node:path";+import { afterEach, describe, expect, test } from "vitest";+import {+ facePostscriptNames,+ fontFace,+} from "@editor/tools/pdfTextEditor/util/fontCollection";+import {+ embeddingForbidden,+ hasTrueTypeOutlines,+ parseFontMetrics,+} from "@editor/tools/pdfTextEditor/util/fontMetrics";+import {+ loadLocalFont,+ resetLocalFontsCache,+} from "@editor/tools/pdfTextEditor/util/localFonts";+import { readTableDirectory } from "@editor/tools/pdfTextEditor/util/sfnt";++const FONTS = path.join(+ import.meta.dirname,+ "../../../../../../../app/core/src/main/resources/static/fonts",+);++function collect(fonts: Uint8Array[]): Uint8Array {+ const header = 12 + fonts.length * 4;+ const size = fonts.reduce((s, f) => s + f.length, header);+ const out = new Uint8Array(size);+ const dv = new DataView(out.buffer);+ dv.setUint32(0, 0x74746366);+ dv.setUint32(4, 0x00010000);+ dv.setUint32(8, fonts.length);+ let at = header;+ fonts.forEach((font, i) => {+ dv.setUint32(12 + i * 4, at);+ out.set(font, at);+ const count = dv.getUint16(at + 4);+ for (let t = 0; t < count; t++) {+ const rec = at + 12 + t * 16 + 8;+ dv.setUint32(rec, dv.getUint32(rec) + at);+ }+ at += font.length;+ });+ return out;+}++const read = async (file: string) =>+ new Uint8Array(await readFile(path.join(FONTS, file)));++describe("fontFace", () => {+ test("returns a plain font file unchanged", async () => {+ const regular = await read("Carlito-Regular.ttf");+ expect(fontFace(regular)).toBe(regular);+ });++ test("pulls the named face out of a collection as a usable font", async () => {+ const regular = await read("Carlito-Regular.ttf");+ const bold = await read("Carlito-Bold.ttf");+ const ttc = collect([regular, bold]);+ expect(facePostscriptNames(ttc)).toEqual(["Carlito", "Carlito-Bold"]);+ expect(parseFontMetrics(ttc)).toBeNull();++ const face = fontFace(ttc, "Carlito-Bold")!;+ expect(facePostscriptNames(face)).toEqual(["Carlito-Bold"]);+ expect(parseFontMetrics(face)).toEqual(parseFontMetrics(bold));+ });++ test("gives up on a name the collection does not hold", async () => {+ const ttc = collect([await read("Carlito-Regular.ttf")]);+ expect(fontFace(ttc, "Calibri")).toBeNull();+ });+});++function withFsType(font: Uint8Array, fsType: number): Uint8Array {+ const out = font.slice();+ const dv = new DataView(out.buffer);+ dv.setUint16(readTableDirectory(dv)!.get("OS/2")!.offset + 8, fsType);+ return out;+}++describe("embeddingForbidden", () => {+ test.each([+ ["installable", 0x0000, false],+ ["preview and print", 0x0004, false],+ ["editable", 0x0008, false],+ ["editable, no subsetting", 0x0108, false],+ ["restricted licence", 0x0002, true],+ ["bitmap only", 0x0208, true],+ ])("%s", async (_label, fsType, forbidden) => {+ const font = withFsType(await read("Carlito-Regular.ttf"), fsType);+ expect(embeddingForbidden(font)).toBe(forbidden);+ });++ test("a file with no OS/2 table declares no restriction", () => {+ expect(embeddingForbidden(new Uint8Array([0, 1, 0, 0, 0, 0]))).toBe(false);+ });+});++describe("hasTrueTypeOutlines", () => {+ test("accepts glyf outlines", async () => {+ expect(hasTrueTypeOutlines(await read("Carlito-Regular.ttf"))).toBe(true);+ });++ test("rejects CFF outlines", async () => {+ expect(hasTrueTypeOutlines(await read("NotoSansTC-Regular.ttf"))).toBe(+ false,+ );+ });+});++describe("loadLocalFont", () => {+ type Query = () => Promise<unknown[]>;+ const scope = globalThis as unknown as {+ window?: { queryLocalFonts?: Query };+ };++ function installFont(bytes: Uint8Array): void {+ scope.window = {+ queryLocalFonts: async () => [+ {+ family: "Carlito",+ fullName: "Carlito",+ style: "Regular",+ postscriptName: "Carlito",+ blob: async () => new Blob([bytes.slice()]),+ },+ ],+ };+ }++ afterEach(() => {+ resetLocalFontsCache();+ delete scope.window;+ });++ test("hands over a font whose licence allows embedding", async () => {+ installFont(withFsType(await read("Carlito-Regular.ttf"), 0x0008));+ expect(await loadLocalFont("Carlito")).toHaveProperty("bytes");+ });++ test("refuses a font whose licence forbids embedding", async () => {+ installFont(withFsType(await read("Carlito-Regular.ttf"), 0x0002));+ expect(await loadLocalFont("Carlito")).toEqual({ refused: "licence" });+ });++ test("refuses a font with CFF outlines as unavailable", async () => {+ installFont(await read("NotoSansTC-Regular.ttf"));+ expect(await loadLocalFont("Carlito")).toEqual({ refused: "unavailable" });+ });+});diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/fontProgramMatch.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/fontProgramMatch.test.tsnew file mode 100644index 0000000000..35c89e67a6--- /dev/null+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/fontProgramMatch.test.ts@@ -0,0 +1,63 @@+// @vitest-environment node+import { readFile } from "node:fs/promises";+import path from "node:path";+import { describe, expect, test } from "vitest";+import { compareFontPrograms } from "@editor/tools/pdfTextEditor/util/fontProgramMatch";++const FONTS = path.join(+ import.meta.dirname,+ "../../../../../../../app/core/src/main/resources/static/fonts",+);+const font = async (name: string) =>+ new Uint8Array(await readFile(path.join(FONTS, name)));++function tableOffset(bytes: Uint8Array, tag: string): number {+ const dv = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);+ for (let i = 0; i < dv.getUint16(4); i++) {+ const rec = 12 + i * 16;+ const name = String.fromCharCode(...bytes.subarray(rec, rec + 4));+ if (name === tag) return dv.getUint32(rec + 8);+ }+ throw new Error(`no ${tag} table`);+}++// Same widths, every outline redrawn: how another version of a font, or a metric-compatible clone, compares.+function withOtherOutlines(bytes: Uint8Array): Uint8Array {+ const out = bytes.slice();+ const glyf = tableOffset(out, "glyf");+ for (let at = glyf + 64; at < glyf + 40_000; at += 7) out[at] ^= 0x55;+ return out;+}++describe("compareFontPrograms", () => {+ test("recognises the same font by its outlines", async () => {+ const liberation = await font("LiberationSans-Regular.ttf");+ expect(compareFontPrograms(liberation, liberation.slice())).toBe("same");+ });++ test("accepts different outlines when every shared width agrees", async () => {+ const liberation = await font("LiberationSans-Regular.ttf");+ expect(compareFontPrograms(liberation, withOtherOutlines(liberation))).toBe(+ "same",+ );+ });++ test.each([+ ["another typeface", "DejaVuSans.ttf"],+ ["another weight of the same family", "LiberationSans-Bold.ttf"],+ ["a serif of the same foundry", "LiberationSerif-Regular.ttf"],+ ])("tells %s apart", async (_label, other) => {+ const liberation = await font("LiberationSans-Regular.ttf");+ expect(compareFontPrograms(liberation, await font(other))).toBe(+ "different",+ );+ });++ test("gives no verdict on something that is not a font", async () => {+ const liberation = await font("LiberationSans-Regular.ttf");+ const noise = new Uint8Array(512).fill(7);+ expect(compareFontPrograms(noise, liberation)).toBe("unknown");+ expect(compareFontPrograms(liberation, noise)).toBe("unknown");+ expect(compareFontPrograms(new Uint8Array(0), liberation)).toBe("unknown");+ });+});diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/glyphReadingOrder.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/glyphReadingOrder.test.tsnew file mode 100644index 0000000000..db845cca0c--- /dev/null+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/glyphReadingOrder.test.ts@@ -0,0 +1,38 @@+// @vitest-environment node+import { describe, expect, test } from "vitest";+import {+ inReadingOrder,+ type PlacedGlyph,+} from "@editor/tools/pdfTextEditor/pdfium/PdfiumTextReader";++const glyph = (ch: string, x: number, bottom: number): PlacedGlyph => ({+ cp: ch.codePointAt(0)!,+ x,+ end: x + 5,+ bottom,+});++const read = (glyphs: PlacedGlyph[]) =>+ inReadingOrder(glyphs, 10)+ .map((g) => String.fromCodePoint(g.cp))+ .join("");++describe("inReadingOrder", () => {+ test("moves redrawn glyphs listed last back into their line", () => {+ // Lines keep "ab" and "ef"; "cd", redrawn onto line one, comes last in the page content.+ const listed = [+ glyph("a", 0, 700),+ glyph("b", 6, 700),+ glyph("e", 0, 688),+ glyph("f", 6, 688),+ glyph("c", 12, 700.6),+ glyph("d", 18, 699.4),+ ];+ expect(read(listed)).toBe("abcdef");+ });++ test("keeps separate lines apart", () => {+ const listed = [glyph("b", 0, 688), glyph("a", 40, 700)];+ expect(read(listed)).toBe("ab");+ });+});diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/localFonts.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/localFonts.test.tsindex f1bcbf5997..17575b5860 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/localFonts.test.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/localFonts.test.ts@@ -3,6 +3,7 @@ import {groupByFamily,isLocalFontAccessSupported,listLocalFonts,+ listLocalFontsIfGranted,resetLocalFontsCache,} from "@editor/tools/pdfTextEditor/util/localFonts";import type { LocalFont } from "@editor/tools/pdfTextEditor/util/localFonts";@@ -160,6 +161,52 @@ describe("listLocalFonts", () => {});});+describe("listLocalFontsIfGranted", () => {+ function setPermission(state: PermissionState): void {+ Object.defineProperty(navigator, "permissions", {+ configurable: true,+ value: { query: vi.fn().mockResolvedValue({ state }) },+ });+ }++ afterEach(() => {+ Reflect.deleteProperty(navigator, "permissions");+ });++ it("lists the fonts when access was already granted", async () => {+ setPermission("granted");+ setQuery(+ vi.fn<QueryStub>().mockResolvedValue([face("Acme", "Regular", "Acme")]),+ );+ const fonts = await listLocalFontsIfGranted();+ expect(fonts?.map((f) => f.family)).toEqual(["Acme"]);+ });++ it("lists the fonts once access is granted after an earlier query failed", async () => {+ setQuery(vi.fn<QueryStub>().mockRejectedValue(new Error("dismissed")));+ await expect(listLocalFonts()).resolves.toBeNull();+ setPermission("granted");+ setQuery(+ vi.fn<QueryStub>().mockResolvedValue([face("Acme", "Regular", "Acme")]),+ );+ const fonts = await listLocalFontsIfGranted();+ expect(fonts?.map((f) => f.family)).toEqual(["Acme"]);+ });++ it("never asks when access would have to be requested", async () => {+ setPermission("prompt");+ const query = vi.fn<QueryStub>().mockResolvedValue([]);+ setQuery(query);+ await expect(listLocalFontsIfGranted()).resolves.toBeNull();+ expect(query).not.toHaveBeenCalled();+ });++ it("returns null in a browser without the API", async () => {+ setPermission("granted");+ await expect(listLocalFontsIfGranted()).resolves.toBeNull();+ });+});+describe("groupByFamily", () => {it("collapses faces into families sorted case-insensitively", () => {const grouped = groupByFamily([diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/matchableSample.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/matchableSample.test.tsnew file mode 100644index 0000000000..7bbca82fe4--- /dev/null+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/matchableSample.test.ts@@ -0,0 +1,60 @@+import { describe, expect, it, vi } from "vitest";+import { matchableSample } from "@editor/tools/pdfTextEditor/util/matchableSample";+import { captureScanEdit } from "@editor/tools/pdfTextEditor/commands/scanTextEdit";+import { scanFrameFor } from "@editor/tools/pdfTextEditor/commands/scanFrame";+import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";++vi.mock("@editor/tools/pdfTextEditor/commands/scanTextEdit", async () => {+ const { scanFrameFor } =+ await import("@editor/tools/pdfTextEditor/commands/scanFrame");+ return {+ isScanRun: () => false,+ captureScanEdit: vi.fn(+ (_m: unknown, run: { matrix: never; bounds: never }, page: never) => ({+ frame: scanFrameFor(page, run.matrix, run.bounds),+ }),+ ),+ };+});++const UPRIGHT = { a: 10, b: 0, c: 0, d: 10, e: 0, f: 0 };+const TURNED = { a: 0, b: 10, c: -10, d: 0, e: 0, f: 0 };++function run(id: string, text: string, matrix: typeof UPRIGHT) {+ return {+ id,+ fontId: "F1",+ text,+ matrix,+ bounds: { x: 10, y: 10, width: 100, height: 12 },+ };+}++describe("matchableSample", () => {+ it("finds an upright run behind more turned runs than it captures", () => {+ const page = {+ display: {+ cropLeft: 0,+ cropBottom: 0,+ cropWidth: 600,+ cropHeight: 800,+ },+ runs: [+ ...Array.from({ length: 5 }, (_, i) =>+ run(`t${i}`, "Turned margin label text", TURNED),+ ),+ run("u", "Invoice total", UPRIGHT),+ ],+ };+ const doc = {+ module: {},+ loadedPages: () => [page],+ } as unknown as EditorDocument;+ expect(scanFrameFor(page as never, TURNED, page.runs[0].bounds)).not.toBe(+ null,+ );++ expect(matchableSample(doc, "F1")?.text).toBe("Invoice total");+ expect(captureScanEdit).toHaveBeenCalledTimes(1);+ });+});diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/scanEditHistory.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/scanEditHistory.test.tsnew file mode 100644index 0000000000..280096d5e4--- /dev/null+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/scanEditHistory.test.ts@@ -0,0 +1,116 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { Page } from "@editor/tools/pdfTextEditor/model/Page";+import { TextRun } from "@editor/tools/pdfTextEditor/model/TextRun";+import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";+import type { ScanEditState } from "@editor/tools/pdfTextEditor/commands/scanTextEdit";+import { EditTextCommand } from "@editor/tools/pdfTextEditor/commands/EditTextCommand";+import { ReflowWrapCommand } from "@editor/tools/pdfTextEditor/commands/ReflowWrapCommand";+import { HistoryStack } from "@editor/tools/pdfTextEditor/store/HistoryStack";++const { renderScanEdit } = vi.hoisted(() => ({+ renderScanEdit: vi.fn(+ (+ _doc: unknown,+ _page: unknown,+ run: TextRun,+ _s: unknown,+ text: string,+ ) => {+ run.text = text;+ return true;+ },+ ),+}));+vi.mock("@editor/tools/pdfTextEditor/commands/scanTextEdit", () => ({+ isScanRun: (run: { renderMode?: number }) => run.renderMode === 3,+ captureScanEdit: () => ({}) as ScanEditState,+ renderScanEdit,+}));++function fixture() {+ const page = new Page({ index: 0, pagePtr: 1, width: 600, height: 800 });+ const run = new TextRun({+ id: "ocr",+ pageIndex: 0,+ pdfiumObjPtr: 11,+ text: "Jane",+ bounds: { x: 100, y: 690, width: 40, height: 10 },+ matrix: { a: 1, b: 0, c: 0, d: 1, e: 100, f: 690 },+ fontId: "Helvetica",+ fontSize: 12,+ fontSubset: false,+ fill: { r: 0, g: 0, b: 0, a: 255 },+ renderMode: 3,+ });+ page.setRuns([run]);+ const flushGenerate = vi.fn();+ page.flushGenerate = flushGenerate;+ const doc = { module: {}, page: () => page } as unknown as EditorDocument;+ return { doc, run, flushGenerate };+}++beforeEach(() => {+ vi.useFakeTimers();+ renderScanEdit.mockReset();+});++afterEach(() => {+ vi.useRealTimers();+});++describe("undoing typing in scanned text", () => {+ it("redraws the block once for a whole burst, each way", () => {+ const { doc, run } = fixture();+ const history = new HistoryStack();+ for (const nextText of ["Jan", "Ja", "Jo", "Joe"])+ history.execute(+ new EditTextCommand({ pageIndex: 0, runId: run.id, nextText }),+ doc,+ );+ renderScanEdit.mockClear();++ history.undo(doc);+ expect(renderScanEdit.mock.calls.map((c) => c[4])).toEqual(["Jane"]);+ expect(run.text).toBe("Jane");++ renderScanEdit.mockClear();+ history.redo(doc);+ expect(renderScanEdit.mock.calls.map((c) => c[4])).toEqual(["Joe"]);+ expect(run.text).toBe("Joe");+ });++ it("redoes a burst to its last drawn text when its last step was refused", () => {+ const { doc, run } = fixture();+ renderScanEdit.mockImplementation((_d, _p, r, _s, text) => {+ if (/\p{Script=Hebrew}/u.test(text)) return false;+ r.text = text;+ return true;+ });+ const history = new HistoryStack();+ for (const nextText of ["Janet", "Janetש"])+ history.execute(+ new EditTextCommand({ pageIndex: 0, runId: run.id, nextText }),+ doc,+ );+ expect(run.text).toBe("Janet");++ history.undo(doc);+ expect(run.text).toBe("Jane");+ history.redo(doc);+ expect(run.text).toBe("Janet");+ });+});++describe("wrapping scanned text", () => {+ it("leaves the block alone, since its words are pixels in the scan", () => {+ const { doc, run, flushGenerate } = fixture();+ new ReflowWrapCommand({+ pageIndex: 0,+ runId: run.id,+ maxWidthPt: 10,+ explicit: true,+ }).apply(doc);+ expect(flushGenerate).not.toHaveBeenCalled();+ expect(run.text).toBe("Jane");+ });+});diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/scanFitSlices.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/scanFitSlices.test.tsnew file mode 100644index 0000000000..e2e7cbc6ad--- /dev/null+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/scanFitSlices.test.ts@@ -0,0 +1,27 @@+import { describe, expect, it, vi } from "vitest";++const { prefitScanRun } = vi.hoisted(() => ({ prefitScanRun: vi.fn() }));+vi.mock("@editor/tools/pdfTextEditor/commands/scanTextEdit", () => ({+ prefitScanRun,+ scanRunNeedsFit: () => true,+}));++import { prefitInSlices } from "@editor/tools/pdfTextEditor/commands/scanFitSlices";+import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";+import type { Page } from "@editor/tools/pdfTextEditor/model/Page";+import type { TextRun } from "@editor/tools/pdfTextEditor/model/TextRun";++describe("prefitInSlices", () => {+ it("stops fitting once the document is closed between slices", async () => {+ const doc = { disposed: false };+ prefitScanRun.mockReturnValue(true).mockImplementationOnce(() => {+ doc.disposed = true;+ return false;+ });+ const target = { page: {} as Page, run: {} as TextRun };++ await prefitInSlices(doc as unknown as EditorDocument, [target, target]);++ expect(prefitScanRun).toHaveBeenCalledTimes(1);+ });+});diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/scanFixtures.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/scanFixtures.tsnew file mode 100644index 0000000000..ef9e00cd2e--- /dev/null+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/scanFixtures.ts@@ -0,0 +1,317 @@+import { readFile } from "node:fs/promises";+import path from "node:path";+import { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";+import type { Page } from "@editor/tools/pdfTextEditor/model/Page";+import { PdfiumTextReader } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTextReader";+import {+ INK_SCALE,+ capturePatch,+} from "@editor/tools/pdfTextEditor/pdfium/BackgroundSampler";+import {+ base14SpaceAdvance,+ emitTextLine,+ measureObjSpanPt,+} from "@editor/tools/pdfTextEditor/commands/editTextHelpers";+import {+ opaqueStroke,+ spanOf,+} from "@editor/tools/pdfTextEditor/commands/scanStyle";+import { transformObject } from "@editor/tools/pdfTextEditor/util/objectTransform";+import { moveAllObjects } from "@editor/tools/pdfTextEditor/commands/scanFrame";+import { createBitmapImageObject } from "@editor/utils/pdfiumBitmapUtils";+import { exportToBlob } from "@editor/tools/pdfTextEditor/util/exportPdf";+import {+ getLocalFontBytes,+ registerFontBytes,+} from "@editor/tools/pdfTextEditor/util/localFonts";+import { parseFontMetrics } from "@editor/tools/pdfTextEditor/util/fontMetrics";+import {+ BUNDLED_SCAN_FONTS,+ faceFromBytes,+ type Face,+} from "@editor/tools/pdfTextEditor/util/scanFontLibrary";+import {+ buildClassicPdf,+ streamBody,+} from "@editor/tools/pdfTextEditor/__tests__/pdfFixtures";+import { uniformTags } from "@editor/tools/pdfTextEditor/model/TextTags";++const BLACK = { r: 0, g: 0, b: 0, a: 255 };+export const PAGE_W = 560;++export interface ScanLineSpec {+ family: string;+ text: string;+ size: number;+ ocrFamily?: string;+}++export interface ScanOptions {+ dpi: number;+ blur: number;+ noise: number;+ sideways?: boolean;+ rotate?: number;+ reversed?: boolean;+ skew?: number;+ ocrShift?: number;+}++export const FONT_DIR = path.join(+ import.meta.dirname,+ "../../../../../../../app/core/src/main/resources/static/fonts",+);++export async function readBundledFaces(): Promise<Face[]> {+ const faces: Face[] = [];+ for (const spec of BUNDLED_SCAN_FONTS) {+ const [regularFile, boldFile] = spec.files;+ const regular = new Uint8Array(+ await readFile(path.join(FONT_DIR, regularFile)),+ );+ const boldBytes = new Uint8Array(+ await readFile(path.join(FONT_DIR, boldFile)),+ );+ registerFontBytes(spec.family, regular);+ registerFontBytes(spec.bold, boldBytes);+ const face = faceFromBytes(+ {+ label: spec.label,+ family: spec.family,+ bold: spec.bold,+ source: "bundled",+ },+ regular,+ boldBytes,+ );+ if (face) faces.push(face);+ }+ return faces;+}++function blankPdf(width: number, height: number): Uint8Array {+ return buildClassicPdf(+ [+ { num: 1, body: "<< /Type /Catalog /Pages 2 0 R >>" },+ { num: 2, body: "<< /Type /Pages /Kids [3 0 R] /Count 1 >>" },+ {+ num: 3,+ body: `<< /Type /Page /Parent 2 0 R /MediaBox [0 0 ${width} ${height}] /Resources << >> /Contents 4 0 R >>`,+ },+ { num: 4, body: streamBody("", "") },+ ],+ 1,+ );+}++interface WordBox {+ text: string;+ left: number;+ right: number;+ baseline: number;+ size: number;+ ocrFamily: string;+}++function spaceAdvance(family: string): number {+ const bytes = getLocalFontBytes(family);+ const own = bytes ? parseFontMetrics(bytes)?.advances.get(0x20) : undefined;+ return own ?? base14SpaceAdvance(family) ?? 278;+}++function typeset(+ doc: EditorDocument,+ page: Page,+ lines: ScanLineSpec[],+ pitch: number,+ height: number,+ skew = 0,+): WordBox[] {+ const boxes: WordBox[] = [];+ lines.forEach((line, i) => {+ const baseline = height - pitch * (i + 0.7);+ const hh = spanOf(doc, page, "HH", line.family, line.size);+ const space = (spaceAdvance(line.family) * line.size) / 1000;+ let x = 30;+ for (const word of line.text.split(" ")) {+ const wordBaseline = baseline + skew * (x - 30);+ const ptrs = emitTextLine({+ doc,+ page,+ text: word,+ x,+ y: wordBaseline,+ fontSize: line.size,+ fill: BLACK,+ originalFontPtr: 0,+ fallbackFamily: line.family,+ tags: uniformTags([]),+ });+ const span = measureObjSpanPt(doc.module, ptrs);+ if (!span) throw new Error(`could not set "${word}" in ${line.family}`);+ boxes.push({+ text: word,+ left: span.left,+ right: span.right,+ baseline: wordBaseline,+ size: line.size,+ ocrFamily: line.ocrFamily ?? "Helvetica",+ });+ x += spanOf(doc, page, `H${word}H`, line.family, line.size) - hh + space;+ }+ });+ return boxes;+}++function degrade(+ src: { rgba: Uint8Array; width: number; height: number },+ opts: ScanOptions,+ seed: number,+): { rgba: Uint8Array; width: number; height: number } {+ const f = (INK_SCALE * 72) / opts.dpi;+ const width = Math.max(1, Math.round(src.width / f));+ const height = Math.max(1, Math.round(src.height / f));+ let grey = new Float32Array(width * height);+ for (let y = 0; y < height; y++)+ for (let x = 0; x < width; x++) {+ let sum = 0;+ let n = 0;+ for (+ let sy = Math.floor(y * f);+ sy < Math.min(src.height, Math.ceil((y + 1) * f));+ sy+++ )+ for (+ let sx = Math.floor(x * f);+ sx < Math.min(src.width, Math.ceil((x + 1) * f));+ sx+++ ) {+ const i = (sy * src.width + sx) * 4;+ sum +=+ 0.299 * src.rgba[i] ++ 0.587 * src.rgba[i + 1] ++ 0.114 * src.rgba[i + 2];+ n++;+ }+ grey[y * width + x] = n ? sum / n : 255;+ }+ if (opts.blur > 0) {+ const r = Math.ceil(opts.blur);+ const weights = Array.from({ length: 2 * r + 1 }, (_, k) =>+ Math.exp(-((k - r) ** 2) / (2 * opts.blur * opts.blur)),+ );+ const total = weights.reduce((a, b) => a + b, 0);+ for (const [dx, dy] of [+ [1, 0],+ [0, 1],+ ]) {+ const out = new Float32Array(grey.length);+ for (let y = 0; y < height; y++)+ for (let x = 0; x < width; x++) {+ let sum = 0;+ for (let k = -r; k <= r; k++) {+ const xx = Math.min(width - 1, Math.max(0, x + k * dx));+ const yy = Math.min(height - 1, Math.max(0, y + k * dy));+ sum += grey[yy * width + xx] * weights[k + r];+ }+ out[y * width + x] = sum / total;+ }+ grey = out;+ }+ }+ let state = seed >>> 0 || 1;+ const rand = () => {+ state = (state * 1664525 + 1013904223) >>> 0;+ return state / 0x100000000;+ };+ const rgba = new Uint8Array(width * height * 4);+ for (let i = 0; i < grey.length; i++) {+ const tone = grey[i] * 0.93 + 4;+ const paper = opts.reversed ? 255 - tone : tone;+ const v = Math.max(+ 0,+ Math.min(255, paper + (rand() - 0.5) * 2 * opts.noise),+ );+ rgba[i * 4] = rgba[i * 4 + 1] = rgba[i * 4 + 2] = Math.round(v);+ rgba[i * 4 + 3] = 255;+ }+ return { rgba, width, height };+}++export async function buildScan(+ lines: ScanLineSpec[],+ opts: ScanOptions,+ pitch = 48,+): Promise<{ doc: EditorDocument; page: Page }> {+ const height = Math.ceil(pitch * lines.length + 20);+ const clean = await EditorDocument.open(blankPdf(PAGE_W, height));+ const scanned = await EditorDocument.open(+ opts.sideways ? blankPdf(height, PAGE_W) : blankPdf(PAGE_W, height),+ );+ try {+ const cleanPage = clean.page(0);+ PdfiumTextReader.populate(clean, cleanPage);+ const boxes = typeset(clean, cleanPage, lines, pitch, height, opts.skew);+ const render = capturePatch(clean.module, cleanPage, {+ x: 0,+ y: 0,+ width: PAGE_W,+ height,+ });+ if (!render) throw new Error("could not render the clean page");+ const image = degrade(render, opts, lines.length * 7919 + opts.dpi);++ const page = scanned.page(0);+ PdfiumTextReader.populate(scanned, page);+ const m = scanned.module;+ const img = createBitmapImageObject(+ m,+ scanned.docPtr,+ page.pagePtr,+ image,+ 0,+ 0,+ PAGE_W,+ height,+ );+ if (!img) throw new Error("could not place the scan image");+ m.FPDFPage_InsertObject(page.pagePtr, img);+ for (const box of boxes) {+ const ptrs = emitTextLine({+ doc: scanned,+ page,+ text: box.text,+ x: box.left,+ y: box.baseline + (opts.ocrShift ?? 0),+ fontSize: box.size,+ fill: BLACK,+ originalFontPtr: 0,+ fallbackFamily: box.ocrFamily,+ renderMode: 3,+ tags: uniformTags([]),+ });+ opaqueStroke(m, ptrs);+ const span = measureObjSpanPt(m, ptrs);+ if (!span) continue;+ const sx =+ (box.right - box.left) / Math.max(1e-3, span.right - span.left);+ for (const p of ptrs)+ transformObject(m, p, sx, 0, 0, 1, box.left * (1 - sx), 0);+ }+ if (opts.sideways)+ moveAllObjects(m, page, { a: 0, b: 1, c: -1, d: 0, e: height, f: 0 });+ if (opts.rotate) m.FPDFPage_SetRotation(page.pagePtr, opts.rotate);+ page.markDirty();+ page.markNeedsGenerate();+ const blob = await exportToBlob(scanned);+ const doc = await EditorDocument.open(+ new Uint8Array(await blob.arrayBuffer()),+ );+ const out = doc.page(0);+ PdfiumTextReader.populate(doc, out);+ return { doc, page: out };+ } finally {+ clean.dispose();+ scanned.dispose();+ }+}diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/scanFontLibrary.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/scanFontLibrary.test.tsnew file mode 100644index 0000000000..87910ef6dc--- /dev/null+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/scanFontLibrary.test.ts@@ -0,0 +1,453 @@+import { readFileSync } from "node:fs";+import path from "node:path";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++const { get } = vi.hoisted(() => ({ get: vi.fn() }));+vi.mock("@editor/services/apiClient", () => ({ default: { get } }));++import {+ SERVER_FONTS_URL,+ forgetServerFontList,+} from "@editor/tools/pdfTextEditor/util/serverFonts";+import { resetLocalFontsCache } from "@editor/tools/pdfTextEditor/util/localFonts";+import { getExternalFontBytes } from "@editor/tools/pdfTextEditor/util/externalFonts";+import {+ BUNDLED_SCAN_FONTS,+ candidateFaces,+ deviceFontsCouldCover,+ loadBundledScanFaces,+ loadDeviceScanFaces,+ loadScriptScanFaces,+ _resetScanFacesForTests,+ scanFaceCssFamily,+ scanFaces,+ scanFacesGeneration,+ scanScriptsOf,+} from "@editor/tools/pdfTextEditor/util/scanFontLibrary";+import { FONT_DIR } from "@editor/tools/pdfTextEditor/__tests__/scanFixtures";++const SERVED: Array<[family: string, style: string, file: string]> = [+ ["Carlito", "Regular", "Carlito-Regular.ttf"],+ ["Carlito", "Bold", "Carlito-Bold.ttf"],+ ["Caladea", "Regular", "Caladea-Regular.ttf"],+ ["Caladea", "Bold", "Caladea-Bold.ttf"],+ ["DejaVu Sans", "Book", "DejaVuSans.ttf"],+ ["DejaVu Sans", "Bold", "DejaVuSans-Bold.ttf"],+ ["DejaVu Sans", "Oblique", "DejaVuSans-Oblique.ttf"],+ ["DejaVu Serif", "Book", "DejaVuSerif.ttf"],+ ["DejaVu Serif", "Bold", "DejaVuSerif-Bold.ttf"],+ ["Liberation Sans", "Regular", "LiberationSans-Regular.ttf"],+ ["Liberation Sans", "Bold", "LiberationSans-Bold.ttf"],+ ["Liberation Serif", "Regular", "LiberationSerif-Regular.ttf"],+ ["Liberation Mono", "Regular", "LiberationMono-Regular.ttf"],+ ["Noto Sans JP", "Regular", "NotoSansJP-Regular.ttf"],+ ["Noto Sans SC", "Regular", "NotoSansSC-Regular.ttf"],+];++const fileBytes = new Map<string, ArrayBuffer>();++function bytesOf(file: string): ArrayBuffer {+ let bytes = fileBytes.get(file);+ if (!bytes) {+ bytes = new Uint8Array(readFileSync(path.join(FONT_DIR, file))).buffer;+ fileBytes.set(file, bytes);+ }+ return bytes;+}++const idOf = (file: string) =>+ (SERVED.findIndex(([, , f]) => f === file) + 1)+ .toString(16)+ .padStart(64, "0");++function manifest(families: string[]) {+ return {+ families: families.map((family) => ({+ family,+ faces: SERVED.filter(([f]) => f === family).map(([, style, file]) => ({+ id: idOf(file),+ style,+ bold: style === "Bold",+ italic: style === "Oblique",+ weight: style === "Bold" ? 700 : 400,+ postscriptName: file.replace(".ttf", ""),+ format: "ttf",+ size: bytesOf(file).byteLength,+ })),+ })),+ };+}++const ALL_FAMILIES = [...new Set(SERVED.map(([family]) => family))];++function serve(families = ALL_FAMILIES, failing = new Set<string>()): void {+ get.mockImplementation(async (url: string) => {+ if (url === SERVER_FONTS_URL) return { data: manifest(families) };+ const served = SERVED.find(([, , file]) => url.endsWith(idOf(file)));+ if (!served || failing.has(served[2])) throw new Error("unavailable");+ return { data: bytesOf(served[2]) };+ });+}++function downloads(file: string): number {+ return get.mock.calls.filter(([url]) => url.endsWith(idOf(file))).length;+}++const jarFetch = vi.fn(async (url: string) => {+ const file = url.slice(url.lastIndexOf("/") + 1);+ return SERVED.some(([, , f]) => f === file)+ ? new Response(bytesOf(file))+ : new Response(null, { status: 404 });+});++function labels(): string[] {+ return scanFaces().map((face) => face.label);+}++beforeEach(() => {+ get.mockReset();+ jarFetch.mockClear();+ vi.stubGlobal("fetch", jarFetch);+ forgetServerFontList();+ resetLocalFontsCache();+ _resetScanFacesForTests();+});++afterEach(() => {+ vi.unstubAllGlobals();+ delete (window as unknown as { queryLocalFonts?: unknown }).queryLocalFonts;+});++describe("bundled scan faces", () => {+ it("builds the four bundled faces, each with its bold cut, from the server", async () => {+ serve();+ const before = scanFacesGeneration();+ await loadBundledScanFaces();++ const bundled = scanFaces().filter((face) => face.source === "bundled");+ expect(bundled.map((face) => face.label)).toEqual(+ BUNDLED_SCAN_FONTS.map((spec) => spec.label),+ );+ for (const face of bundled) {+ expect(face.bold).not.toBe(face.family);+ expect(face.metrics?.size).toBe(2);+ }+ expect(scanFacesGeneration()).toBeGreaterThan(before);+ expect(jarFetch).not.toHaveBeenCalled();+ });++ it("loads a face again after its download failed", async () => {+ jarFetch.mockImplementationOnce(+ async () => new Response(null, { status: 404 }),+ );+ serve(ALL_FAMILIES, new Set(["Caladea-Regular.ttf"]));+ await loadBundledScanFaces();+ expect(labels()).not.toContain("Cambria (Caladea)");++ serve();+ await loadBundledScanFaces();+ expect(labels()).toContain("Cambria (Caladea)");+ });++ it("falls back to the app's own copy when the server has no font list", async () => {+ get.mockRejectedValue(new Error("not found"));+ await loadBundledScanFaces();++ expect(labels()).toEqual(+ expect.arrayContaining(BUNDLED_SCAN_FONTS.map((spec) => spec.label)),+ );+ expect(getExternalFontBytes("Carlito Bold")?.byteLength).toBe(+ bytesOf("Carlito-Bold.ttf").byteLength,+ );+ });++ it("falls back to the app's own copy for the fonts an older server lacks", async () => {+ serve(["DejaVu Sans", "DejaVu Serif"]);+ await loadBundledScanFaces();++ expect(labels()).toEqual(+ expect.arrayContaining(BUNDLED_SCAN_FONTS.map((spec) => spec.label)),+ );+ expect(jarFetch.mock.calls.map(([url]) => url.split("/").pop())).toEqual(+ expect.arrayContaining(["Carlito-Regular.ttf", "Caladea-Bold.ttf"]),+ );+ expect(downloads("DejaVuSans.ttf")).toBe(1);+ });++ it("lets the page draw the app's own copy, its bold cut under the regular family", async () => {+ const added: Array<[string, string]> = [];+ vi.stubGlobal(+ "FontFace",+ class {+ constructor(+ readonly family: string,+ _bytes: ArrayBuffer,+ readonly descriptors: { weight: string },+ ) {}+ load() {+ return Promise.resolve(this);+ }+ },+ );+ Object.defineProperty(document, "fonts", {+ configurable: true,+ value: {+ add: (f: { family: string; descriptors: { weight: string } }) =>+ added.push([f.family, f.descriptors.weight]),+ },+ });+ try {+ get.mockRejectedValue(new Error("not found"));+ await loadBundledScanFaces();+ await vi.waitFor(() =>+ expect(added).toEqual(+ expect.arrayContaining([+ ["Carlito", "400"],+ ["Carlito", "700"],+ ]),+ ),+ );+ expect(scanFaceCssFamily("Carlito Bold")).toMatch(+ /^"Carlito Bold", "Carlito", /,+ );+ } finally {+ Reflect.deleteProperty(document, "fonts");+ }+ });++ it("loads the font bytes again after the server font list was reset", async () => {+ serve();+ await loadBundledScanFaces();+ expect(getExternalFontBytes("Carlito")).not.toBeNull();++ forgetServerFontList();+ await loadBundledScanFaces();+ expect(getExternalFontBytes("Carlito")?.byteLength).toBe(+ bytesOf("Carlito-Regular.ttf").byteLength,+ );+ });+});++describe("bundled scan faces across a server reset", () => {+ it("keeps the faces of the load that started after the reset", async () => {+ jarFetch.mockImplementation(+ async () => new Response(null, { status: 404 }),+ );+ let answer: (value: { data: unknown }) => void = () => {};+ get.mockImplementationOnce(+ () => new Promise((resolve) => (answer = resolve)),+ );+ const first = loadBundledScanFaces();+ forgetServerFontList();+ serve();+ await loadBundledScanFaces();+ answer({ data: manifest(ALL_FAMILIES) });+ await first;+ expect(labels()).toEqual(+ expect.arrayContaining(BUNDLED_SCAN_FONTS.map((spec) => spec.label)),+ );+ });+});++describe("script scan faces", () => {+ it("loads a Chinese font for Japanese text when the server has no Japanese one", async () => {+ serve(ALL_FAMILIES.filter((family) => family !== "Noto Sans JP"));+ await loadScriptScanFaces(scanScriptsOf("請求書 お支払い"));++ expect(labels()).toContain("Noto Sans SC");+ });++ it("loads the server's Japanese font once for Japanese text", async () => {+ serve();+ await loadScriptScanFaces(scanScriptsOf("請求書 お支払い ください"));+ await loadScriptScanFaces(scanScriptsOf("請求書 お支払い"));++ expect(labels().filter((label) => label === "Noto Sans JP")).toHaveLength(+ 1,+ );+ expect(downloads("NotoSansJP-Regular.ttf")).toBe(1);+ expect(downloads("NotoSansSC-Regular.ttf")).toBe(0);+ });++ it("loads one Chinese font for Chinese text", async () => {+ serve();+ await loadScriptScanFaces(scanScriptsOf("发票 请于六月三十日前付款"));++ expect(labels()).toContain("Noto Sans SC");+ expect(downloads("NotoSansJP-Regular.ttf")).toBe(0);+ });++ it("tries again after the font list failed to load", async () => {+ get.mockRejectedValue(new Error("restarting"));+ await loadScriptScanFaces(scanScriptsOf("請求書 お支払い"));+ expect(labels()).not.toContain("Noto Sans JP");++ serve();+ await loadScriptScanFaces(scanScriptsOf("請求書 お支払い"));+ expect(labels()).toContain("Noto Sans JP");+ });++ it("tries again after the font download failed", async () => {+ serve(ALL_FAMILIES, new Set(["NotoSansJP-Regular.ttf"]));+ await loadScriptScanFaces(scanScriptsOf("請求書 お支払い"));+ expect(labels()).not.toContain("Noto Sans JP");++ serve();+ await loadScriptScanFaces(scanScriptsOf("請求書 お支払い"));+ expect(labels()).toContain("Noto Sans JP");+ });++ it("loads the server's Japanese font again after the server font list was reset", async () => {+ serve();+ await loadScriptScanFaces(scanScriptsOf("請求書 お支払い"));++ forgetServerFontList();+ await loadScriptScanFaces(scanScriptsOf("請求書 お支払い"));+ expect(labels().filter((label) => label === "Noto Sans JP")).toHaveLength(+ 1,+ );+ expect(getExternalFontBytes("Noto Sans JP")).not.toBeNull();+ });++ it("offers the Liberation clones for Cyrillic but not where base-14 can draw", async () => {+ serve();+ await loadScriptScanFaces(scanScriptsOf("Счёт для Ивана"));++ expect(labels()).toEqual(+ expect.arrayContaining([+ "Arial (Liberation Sans)",+ "Times New Roman (Liberation Serif)",+ "Courier New (Liberation Mono)",+ ]),+ );+ const cyrillic = candidateFaces("Счёт для Ивана").map((f) => f.label);+ expect(cyrillic).toContain("Arial (Liberation Sans)");+ expect(cyrillic).not.toContain("Helvetica / Arial");+ const latin = candidateFaces("Invoice for Jane").map((f) => f.label);+ expect(latin).toContain("Helvetica / Arial");+ expect(latin).not.toContain("Arial (Liberation Sans)");+ });+});++interface StubFace {+ family: string;+ style: string;+ file: string;+}++function stubDeviceFonts(faces: StubFace[]): void {+ (window as unknown as { queryLocalFonts: unknown }).queryLocalFonts =+ async () =>+ faces.map(({ family, style, file }) => ({+ family,+ style,+ fullName: `${family} ${style}`,+ postscriptName: `${family.replace(/ /g, "")}-${style}`,+ blob: async () => ({ arrayBuffer: async () => bytesOf(file) }),+ }));+}++describe("which scripts device fonts are tried for", () => {+ it("tries device fonts for Latin, Cyrillic and listed scripts", () => {+ expect(deviceFontsCouldCover("Invoice 4471 for Jane")).toBe(true);+ expect(deviceFontsCouldCover("Счёт для Ивана")).toBe(true);+ expect(deviceFontsCouldCover("청구서 4471")).toBe(true);+ });++ it("does not for a script no listed device font draws", () => {+ expect(deviceFontsCouldCover("ინვოისი 4471")).toBe(false);+ });+});++describe("device scan faces", () => {+ it("loads the bold cut of a family whose name contains a style word", async () => {+ stubDeviceFonts([+ {+ family: "Times New Roman",+ style: "Regular",+ file: "LiberationSerif-Regular.ttf",+ },+ { family: "Times New Roman", style: "Bold", file: "Carlito-Bold.ttf" },+ ]);+ expect(await loadDeviceScanFaces()).toBe(1);++ const times = scanFaces().find((face) => face.label === "Times New Roman");+ expect(times?.bold).toBe("Times New Roman Bold");+ expect(times?.metrics?.size).toBe(2);+ });++ it("asks again after the user declined", async () => {+ (window as unknown as { queryLocalFonts: unknown }).queryLocalFonts =+ async () => {+ throw new DOMException("denied", "NotAllowedError");+ };+ expect(await loadDeviceScanFaces()).toBe(0);++ stubDeviceFonts([+ { family: "Georgia", style: "Regular", file: "DejaVuSerif.ttf" },+ ]);+ expect(await loadDeviceScanFaces()).toBe(1);+ });++ it("reads a family again after reading its file failed", async () => {+ let failing = true;+ (window as unknown as { queryLocalFonts: unknown }).queryLocalFonts =+ async () => [+ {+ family: "Georgia",+ style: "Regular",+ fullName: "Georgia Regular",+ postscriptName: "Georgia-Regular",+ blob: async () => {+ if (failing) throw new Error("busy");+ return { arrayBuffer: async () => bytesOf("DejaVuSerif.ttf") };+ },+ },+ ];+ expect(await loadDeviceScanFaces()).toBe(0);++ failing = false;+ expect(await loadDeviceScanFaces()).toBe(1);+ });++ it("skips families the server or base-14 already provide", async () => {+ serve();+ await loadScriptScanFaces(scanScriptsOf("請求書 お支払い"));+ stubDeviceFonts([+ { family: "Noto Sans JP", style: "Regular", file: "Caladea-Regular.ttf" },+ { family: "Helvetica", style: "Regular", file: "Carlito-Regular.ttf" },+ { family: "Georgia", style: "Regular", file: "DejaVuSerif.ttf" },+ ]);+ expect(await loadDeviceScanFaces()).toBe(1);++ expect(labels().filter((label) => label === "Noto Sans JP")).toHaveLength(+ 1,+ );+ expect(scanFaces().filter((face) => face.family === "Helvetica")).toEqual([+ expect.objectContaining({ source: "base14" }),+ ]);+ });++ it("reads a script's installed fonts once that script turns up after Latin", async () => {+ serve([]);+ stubDeviceFonts([+ { family: "Georgia", style: "Regular", file: "DejaVuSerif.ttf" },+ { family: "Yu Gothic", style: "Regular", file: "NotoSansJP-Regular.ttf" },+ ]);+ expect(await loadDeviceScanFaces()).toBe(1);++ await loadScriptScanFaces(scanScriptsOf("請求書 お支払い"));+ expect(await loadDeviceScanFaces()).toBe(2);+ expect(labels()).toEqual(expect.arrayContaining(["Georgia", "Yu Gothic"]));+ });++ it("keeps one face when two families share the same outlines", async () => {+ serve([]);+ await loadScriptScanFaces(scanScriptsOf("发票"));+ stubDeviceFonts([+ { family: "Heiti SC", style: "Regular", file: "DejaVuSans.ttf" },+ { family: "Heiti TC", style: "Regular", file: "DejaVuSans.ttf" },+ ]);+ expect(await loadDeviceScanFaces()).toBe(1);+ });+});diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/scanFontMatch.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/scanFontMatch.test.tsnew file mode 100644index 0000000000..bc8c32e645--- /dev/null+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/scanFontMatch.test.ts@@ -0,0 +1,1646 @@+// @vitest-environment node+import { readFile } from "node:fs/promises";+import { createRequire } from "node:module";+import path from "node:path";+import {+ afterAll,+ beforeAll,+ beforeEach,+ describe,+ expect,+ test,+ vi,+} from "vitest";++const { get } = vi.hoisted(() => ({ get: vi.fn() }));+vi.mock("@editor/services/apiClient", () => ({ default: { get } }));++import { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";+import { PdfiumTextReader } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTextReader";+import { exportToBlob } from "@editor/tools/pdfTextEditor/util/exportPdf";+import {+ emitFillRect,+ getDroppedBase14Chars,+ resetDroppedBase14Chars,+} from "@editor/tools/pdfTextEditor/commands/editTextHelpers";+import type { Page } from "@editor/tools/pdfTextEditor/model/Page";+import type { TextRun } from "@editor/tools/pdfTextEditor/model/TextRun";+import { renderLuma } from "@editor/tools/pdfTextEditor/pdfium/BackgroundSampler";+import { readMatrix } from "@editor/tools/pdfTextEditor/commands/textPieces";+import {+ drawnBlockStyle,+ isScanRun,+ scanBlockMisaligned,+ scanBlockOffInk,+ scanDrawnFont,+ prefitScanRun,+ renderScanEdit,+ scanDrawnSize,+ scanEditOf,+ wrapScanText,+ scanRunNeedsFit,+ scanTypingDropped,+} from "@editor/tools/pdfTextEditor/commands/scanTextEdit";+import {+ CLOSE_CALL,+ preferredScanFace,+ preferredStyle,+ setPreferredScanFace,+ type RankedStyle,+ type ScanStyle,+} from "@editor/tools/pdfTextEditor/commands/scanFit";+import { isEvenlySpaced } from "@editor/tools/pdfTextEditor/commands/scanStyle";+import { SetScanStyleCommand } from "@editor/tools/pdfTextEditor/commands/SetScanStyleCommand";+import { DeleteObjectCommand } from "@editor/tools/pdfTextEditor/commands/DeleteObjectCommand";+import {+ SERVER_FONTS_URL,+ forgetServerFontList,+} from "@editor/tools/pdfTextEditor/util/serverFonts";+import {+ COURIER,+ HELVETICA,+ TIMES,+ faceCovers,+ faceFromBytes,+ loadScriptScanFaces,+ _resetScanFacesForTests,+ scanScriptsOf,+ _setBundledScanFacesForTests,+ type Face,+} from "@editor/tools/pdfTextEditor/util/scanFontLibrary";+import { registerFontBytes } from "@editor/tools/pdfTextEditor/util/localFonts";+import {+ buildClassicPdf,+ streamBody,+} from "@editor/tools/pdfTextEditor/__tests__/pdfFixtures";+import {+ FONT_DIR,+ buildScan,+ readBundledFaces,+ type ScanLineSpec,+ type ScanOptions,+} from "@editor/tools/pdfTextEditor/__tests__/scanFixtures";++const SENTENCES = [+ "Invoice 4471 for Jane Example is due on 30 June",+ "Please return the signed copy to our Leeds office",+];++let bundled: Face[] = [];++beforeAll(async () => {+ const wasmPath = createRequire(import.meta.url).resolve(+ "@embedpdf/pdfium/pdfium.wasm",+ );+ const wasmBytes = await readFile(wasmPath);+ vi.stubGlobal(+ "fetch",+ vi.fn(async () =>+ Promise.resolve(+ new Response(wasmBytes, {+ headers: { "Content-Type": "application/wasm" },+ }),+ ),+ ),+ );+ bundled = await readBundledFaces();+});++beforeEach(() => {+ _setBundledScanFacesForTests(bundled);+});++afterAll(() => {+ _resetScanFacesForTests();+ vi.unstubAllGlobals();+});++interface Sample extends ScanLineSpec {+ accept: string;+ bold: boolean;+}++const nextTick = () => new Promise((resolve) => setTimeout(resolve, 0));++async function choicesFor(+ doc: EditorDocument,+ page: Page,+ run: TextRun,+): Promise<RankedStyle[]> {+ while (!prefitScanRun(doc, page, run, performance.now() + 50))+ await nextTick();+ return scanEditOf(doc, run)?.block?.ranked ?? [];+}++async function choicesByLine(+ doc: EditorDocument,+ page: Page,+ samples: Sample[],+): Promise<Array<RankedStyle[]>> {+ const runs = page.runs.filter(isScanRun);+ const out: Array<RankedStyle[]> = [];+ for (const [i] of samples.entries()) {+ const baseline = page.height - 48 * (i + 0.7);+ const run = runs.find((r) => Math.abs(r.matrix.f - baseline) < 6);+ out.push(run ? await choicesFor(doc, page, run) : []);+ }+ return out;+}++// Saving subsets embedded fonts, which tags their names (ABCDEF+Carlito).+const SUBSET_TAG = /^[A-Z]{6}\+/;++function drawnFontNames(doc: EditorDocument, ptrs: number[]): string[] {+ const m = doc.module;+ return ptrs.map((p) => {+ const font = m.FPDFTextObj_GetFont(p);+ const len = m.FPDFFont_GetBaseFontName(font, 0, 0);+ const buf = m.pdfium.wasmExports.malloc(len);+ try {+ m.FPDFFont_GetBaseFontName(font, buf, len);+ return m.pdfium.UTF8ToString(buf).replace(SUBSET_TAG, "");+ } finally {+ m.pdfium.wasmExports.free(buf);+ }+ });+}++function boldCut(choice: RankedStyle | undefined): boolean {+ if (!choice) return false;+ const { face, style } = choice;+ return style.family === face.bold && face.bold !== face.family;+}++const line = (+ family: string,+ accept: string,+ i: number,+ bold = false,+): Sample => ({+ family,+ text: SENTENCES[i % SENTENCES.length],+ size: 12,+ accept,+ bold,+});++describe("spotting typewriter spacing", () => {+ const PITCH = 7.2;+ const centresOn = (text: string, cell: number) =>+ [...text].flatMap((ch, i) => (/\s/.test(ch) ? [] : [i * cell]));++ test("reads a monospaced line with spaces as typewriter text", () => {+ for (const text of [+ "Invoice 4471 for Jane Example is due on 30 June",+ "DATE OF BIRTH 12 MAY 1987",+ ])+ expect(isEvenlySpaced(centresOn(text, PITCH), text)).toBe(true);+ });++ test("does not read proportional glyph steps as typewriter text", () => {+ const text = "Invoice for Jane Example";+ let x = 0;+ const centres = [...text].flatMap((ch, i) => {+ x += PITCH * (0.5 + ((i * 7) % 5) * 0.17);+ return /\s/.test(ch) ? [] : [x];+ });+ expect(isEvenlySpaced(centres, text)).toBe(false);+ });+});++describe("letting a picked face win close calls", () => {+ const doc = {} as EditorDocument;+ const style = (family: string): ScanStyle => ({+ family,+ fontSize: 12,+ stretch: 1,+ ink: { r: 0, g: 0, b: 0, a: 255 },+ weight: 0,+ hollow: 0,+ softness: 0,+ });+ const ranked: RankedStyle[] = [+ { face: HELVETICA, style: style("Helvetica"), score: 0.9 },+ { face: TIMES, style: style("Times-Roman"), score: 0.9 - CLOSE_CALL / 2 },+ { face: COURIER, style: style("Courier"), score: 0.9 - CLOSE_CALL * 2 },+ ];+ const drawnWith = (label: string | null) => {+ setPreferredScanFace(doc, label);+ return preferredStyle(doc, ranked)?.family ?? null;+ };++ test("draws a pick that is a close call", () => {+ expect(drawnWith(TIMES.label)).toBe("Times-Roman");+ });++ test("keeps the best fit when the pick is well behind it", () => {+ expect(drawnWith(COURIER.label)).toBeNull();+ });++ test("keeps the best fit when the pick is not among the choices", () => {+ expect(drawnWith("Calibri (Carlito)")).toBeNull();+ expect(drawnWith(null)).toBeNull();+ });++ test("still draws the pick once it is the best fit", () => {+ expect(drawnWith(HELVETICA.label)).toBe("Helvetica");+ });+});++describe("matching a face to scanned text", () => {+ const SCAN: ScanOptions = { dpi: 200, blur: 0.5, noise: 6 };+ const samples: Sample[] = [+ line("Carlito", "Calibri (Carlito)", 0),+ line("Caladea Bold", "Cambria (Caladea)", 1, true),+ line("Helvetica-Bold", "Helvetica / Arial", 0, true),+ line("Times-Roman", "Times", 1),+ line("Courier", "Courier", 0),+ line("DejaVu Sans", "DejaVu Sans", 1),+ ];++ test(+ "names the face each line was typeset in",+ { timeout: 240_000 },+ async () => {+ const { doc, page } = await buildScan(samples, SCAN);+ try {+ const picked = await choicesByLine(doc, page, samples);+ const report = samples.map((s, i) => ({+ set: s.family,+ picked: picked[i][0]?.face.label ?? null,+ bold: boldCut(picked[i][0]),+ }));+ expect(report).toEqual(+ samples.map((s) => ({+ set: s.family,+ picked: s.accept,+ bold: s.bold,+ })),+ );+ const scores = picked[0].map((c) => c.score);+ expect([...scores].sort((a, b) => b - a)).toEqual(scores);+ expect(new Set(picked[0].map((c) => c.face.label)).size).toBe(3);+ } finally {+ doc.dispose();+ }+ },+ );++ test(+ "fits a block in short slices and reaches the same face",+ { timeout: 120_000 },+ async () => {+ const { doc, page } = await buildScan([samples[0]], SCAN);+ try {+ const run = page.runs.find(isScanRun)!;+ let slices = 0;+ while (!prefitScanRun(doc, page, run, 0)) {+ slices++;+ await nextTick();+ }+ expect(slices).toBeGreaterThan(1);+ expect(scanEditOf(doc, run)!.block?.style.family).toBe("Carlito");+ } finally {+ doc.dispose();+ }+ },+ );++ test(+ "a picked face wins a close call and stays once the block is drawn",+ { timeout: 120_000 },+ async () => {+ const { doc, page } = await buildScan(+ [{ ...samples[0], text: "Quarterly review" }],+ SCAN,+ );+ try {+ const run = page.runs.find(isScanRun)!;+ const [best, runnerUp] = await choicesFor(doc, page, run);+ expect(runnerUp.score).toBeGreaterThanOrEqual(best.score - CLOSE_CALL);+ setPreferredScanFace(doc, runnerUp.face.label);+ const state = scanEditOf(doc, run)!;+ const drawnFamily = () =>+ drawnFontNames(doc, state.textPtrs).map((n) => n.replace(/ /g, ""));+ renderScanEdit(doc, page, run, state, "Quiz");+ expect(drawnFamily()).toContain(+ runnerUp.style.family.replace(/ /g, ""),+ );+ expect(drawnBlockStyle(doc, state)).toBe(runnerUp.style);+ setPreferredScanFace(doc, null);+ renderScanEdit(doc, page, run, state, "Quizzes");+ expect(drawnFamily()).toContain(+ runnerUp.style.family.replace(/ /g, ""),+ );+ expect(drawnBlockStyle(doc, state)).toBe(runnerUp.style);+ } finally {+ doc.dispose();+ }+ },+ );++ test(+ "a picked face still wins when the block's first edit only deleted words",+ { timeout: 120_000 },+ async () => {+ const sample = { ...samples[0], text: "Quarterly review" };+ const probe = await buildScan([sample], SCAN);+ let runnerUp: RankedStyle;+ try {+ const run = probe.page.runs.find(isScanRun)!;+ runnerUp = (await choicesFor(probe.doc, probe.page, run))[1];+ } finally {+ probe.doc.dispose();+ }+ const { doc, page } = await buildScan([sample], SCAN);+ try {+ const run = page.runs.find(isScanRun)!;+ setPreferredScanFace(doc, runnerUp.face.label);+ const state = scanEditOf(doc, run)!;+ expect(renderScanEdit(doc, page, run, state, "Quarterly")).toBe(true);+ expect(state.block).toBeUndefined();+ renderScanEdit(doc, page, run, state, "Quarterly reviews");+ expect(drawnBlockStyle(doc, state)?.family).toBe(runnerUp.style.family);+ } finally {+ doc.dispose();+ }+ },+ );++ test(+ "undoing a pick redraws the block in its own best face",+ { timeout: 120_000 },+ async () => {+ const lines = [samples[0], { ...samples[0], text: "Quarterly review" }];+ const { doc, page } = await buildScan(lines, SCAN);+ try {+ const run = page.runs.filter(isScanRun)[1];+ const ranked = await choicesFor(doc, page, run);+ const runnerUp = ranked[1];+ expect(runnerUp.score).toBeGreaterThanOrEqual(+ ranked[0].score - CLOSE_CALL,+ );+ const state = scanEditOf(doc, run)!;+ renderScanEdit(doc, page, run, state, "Quiz");+ const band = {+ x: run.bounds.x - 4,+ y: run.bounds.y,+ width: run.bounds.width + 8,+ height: run.bounds.height,+ };+ const best = renderLuma(doc.module, page, band, 0)!.data;+ const pick = new SetScanStyleCommand({+ pageIndex: 0,+ runId: run.id,+ choice: runnerUp,+ });+ pick.apply(doc);+ expect(preferredScanFace(doc)).toBe(runnerUp.face.label);+ expect(renderLuma(doc.module, page, band, 0)!.data).not.toEqual(best);+ pick.revert(doc);+ expect(preferredScanFace(doc)).toBeNull();+ expect(renderLuma(doc.module, page, band, 0)!.data).toEqual(best);+ } finally {+ doc.dispose();+ }+ },+ );++ test(+ "scores the picked font in an untouched block that did not offer it",+ { timeout: 120_000 },+ async () => {+ const { doc, page } = await buildScan([samples[0]], SCAN);+ try {+ const run = page.runs.find(isScanRun)!;+ const before = await choicesFor(doc, page, run);+ expect(before.map((c) => c.face.label)).not.toContain("Courier");+ setPreferredScanFace(doc, "Courier");+ expect(scanRunNeedsFit(doc, run)).toBe(true);+ const after = await choicesFor(doc, page, run);+ expect(scanRunNeedsFit(doc, run)).toBe(false);+ expect(scanEditOf(doc, run)!.block!.preferred).toBe("Courier");+ expect(+ after.every((c) => before.includes(c) || c.face.label === "Courier"),+ ).toBe(true);+ } finally {+ doc.dispose();+ }+ },+ );+});++function inkProfile(+ page: Page,+ doc: EditorDocument,+ x: number,+ width: number,+ baseline: number,+) {+ return renderLuma(+ doc.module,+ page,+ { x, y: baseline - 4, width, height: 16 },+ 0,+ )!;+}++function likeness(+ a: { data: Float32Array; width: number; height: number },+ b: { data: Float32Array; width: number; height: number },+): number {+ const firstInk = (img: typeof a) => {+ for (let x = 0; x < img.width; x++)+ for (let y = 0; y < img.height; y++)+ if (img.data[y * img.width + x] < 128) return x;+ return 0;+ };+ const ax = firstInk(a);+ const bx = firstInk(b);+ const w = Math.min(a.width - ax, b.width - bx);+ const h = Math.min(a.height, b.height);+ const pa: number[] = [];+ const pb: number[] = [];+ for (let y = 0; y < h; y++)+ for (let x = 0; x < w; x++) {+ pa.push(a.data[y * a.width + ax + x]);+ pb.push(b.data[y * b.width + bx + x]);+ }+ const mean = (v: number[]) => v.reduce((p, q) => p + q, 0) / v.length;+ const ma = mean(pa);+ const mb = mean(pb);+ let ab = 0;+ let aa = 0;+ let bb = 0;+ for (let i = 0; i < pa.length; i++) {+ ab += (pa[i] - ma) * (pb[i] - mb);+ aa += (pa[i] - ma) ** 2;+ bb += (pb[i] - mb) ** 2;+ }+ return ab / Math.sqrt(aa * bb);+}++async function staticFace(family: string, file: string): Promise<Face | null> {+ const bytes = new Uint8Array(await readFile(path.join(FONT_DIR, file)));+ registerFontBytes(family, bytes);+ return faceFromBytes(+ { label: family, family, bold: `${family} Bold`, source: "bundled" },+ bytes,+ null,+ );+}++async function savedText(doc: EditorDocument): Promise<string> {+ const blob = await exportToBlob(doc);+ const back = await EditorDocument.open(+ new Uint8Array(await blob.arrayBuffer()),+ );+ try {+ const page = back.page(0);+ PdfiumTextReader.populate(back, page);+ return page.runs.map((r) => r.text).join(" ");+ } finally {+ back.dispose();+ }+}++async function savedFonts(doc: EditorDocument) {+ const blob = await exportToBlob(doc);+ const text = new TextDecoder("latin1").decode(await blob.arrayBuffer());+ return {+ names: [+ ...new Set(+ [...text.matchAll(/\/BaseFont\s*\/([^\s/<>[\]()]+)/g)].map((m) =>+ m[1].replace(SUBSET_TAG, ""),+ ),+ ),+ ],+ embedded: text.split("/FontFile2").length - 1,+ };+}++describe("what an edit leaves in the saved file", () => {+ test("keeps only the face the edit draws", { timeout: 120_000 }, async () => {+ const { doc, page } = await buildScan(+ [+ {+ family: "Carlito",+ text: SENTENCES[0],+ size: 12,+ },+ ],+ {+ dpi: 300,+ blur: 0.3,+ noise: 4,+ },+ );+ try {+ const run = page.runs.find(isScanRun)!;+ const [top] = await choicesFor(doc, page, run);+ expect(top.style.family).toBe("Carlito");+ const state = scanEditOf(doc, run)!;+ state.override.style = { ...top.style, softness: 0 };+ renderScanEdit(doc, page, run, state, run.text.replace("Jane", "Quiz"));+ expect(drawnFontNames(doc, state.textPtrs)).toContain("Carlito");+ const saved = await savedFonts(doc);+ expect(saved.embedded).toBe(1);+ expect(saved.names.filter((n) => !n.startsWith("Helvetica"))).toEqual([+ "Carlito",+ ]);+ } finally {+ doc.dispose();+ }+ });+});++describe("softening typed words to the scan", () => {+ test(+ "keeps the ascenders and descenders the replaced word did not have",+ { timeout: 120_000 },+ async () => {+ const { doc, page } = await buildScan(+ [{ family: "Carlito", text: SENTENCES[0], size: 12 }],+ { dpi: 200, blur: 0.5, noise: 6 },+ );+ try {+ const run = page.runs.find(isScanRun)!;+ const [top] = await choicesFor(doc, page, run);+ expect(top.style.softness).toBeGreaterThan(0);+ const state = scanEditOf(doc, run)!;+ const on = state.lines[0].words.find((w) => w.text.trim() === "on")!;+ const baseline = state.lines[0].baseline;+ const inked = (bottom: number, top: number) => {+ const img = renderLuma(+ doc.module,+ page,+ {+ x: on.x,+ y: baseline + bottom,+ width: on.right - on.x,+ height: top - bottom,+ },+ 0,+ )!;+ return img.data.filter((l) => l < 128).length;+ };+ renderScanEdit(doc, page, run, state, run.text.replace(" on ", " by "));+ expect(state.classes).toEqual([]);+ expect(inked(7, 9)).toBeGreaterThan(0);+ expect(inked(-2.5, -1)).toBeGreaterThan(0);+ } finally {+ doc.dispose();+ }+ },+ );+});++describe("editing sideways scanned text", () => {+ const SCAN: ScanOptions = { dpi: 200, blur: 0.5, noise: 6 };+ const line: ScanLineSpec = {+ family: "Carlito",+ text: "Invoice 4471 for Jane Example is due on 30 June",+ size: 12,+ };++ test(+ "fits the face upright and draws the edit turned back",+ { timeout: 120_000 },+ async () => {+ const { doc, page } = await buildScan([line], {+ ...SCAN,+ sideways: true,+ });+ try {+ const run = page.runs.find(+ (r) => isScanRun(r) && r.text.includes("Jane"),+ )!;+ expect((await choicesFor(doc, page, run))[0]?.face.label).toBe(+ "Calibri (Carlito)",+ );+ const band = {+ x: run.bounds.x - 4,+ y: run.bounds.y,+ width: run.bounds.width + 8,+ height: run.bounds.height,+ };+ const before = renderLuma(doc.module, page, band, 0)!.data;+ renderScanEdit(+ doc,+ page,+ run,+ scanEditOf(doc, run)!,+ run.text.replace("Jane", "Mary"),+ );+ const after = renderLuma(doc.module, page, band, 0)!.data;+ let changed = 0;+ for (let i = 0; i < before.length; i++)+ if (Math.abs(before[i] - after[i]) > 40) changed++;+ expect(changed).toBeGreaterThan(50);+ expect(await savedText(doc)).toContain("Mary");+ } finally {+ doc.dispose();+ }+ },+ );+});++describe("the font a scanned block is drawn in", () => {+ test(+ "is the family the user picked, even before the block is fitted",+ { timeout: 120_000 },+ async () => {+ const { doc, page } = await buildScan(+ [{ family: "Carlito", text: SENTENCES[0], size: 12 }],+ { dpi: 200, blur: 0.5, noise: 6 },+ );+ try {+ const run = page.runs.find(isScanRun)!;+ const state = scanEditOf(doc, run)!;+ state.override = { ...state.override, family: "Courier" };+ expect(scanDrawnFont(doc, run)?.family).toBe("Courier");+ } finally {+ doc.dispose();+ }+ },+ );+});++describe("wrapping scanned text to a width", () => {+ test(+ "moves the overflow to a new line and still draws the edit",+ { timeout: 120_000 },+ async () => {+ const { doc, page } = await buildScan(+ [{ family: "Carlito", text: SENTENCES[0], size: 12 }],+ { dpi: 200, blur: 0.5, noise: 6 },+ );+ try {+ const run = page.runs.find(isScanRun)!;+ const state = scanEditOf(doc, run)!;+ const words = state.lines[0].words;+ const full = words[words.length - 1].right - words[0].x;+ expect(wrapScanText(doc, page, run, full * 2)).toBe(run.text);+ const wrapped = wrapScanText(doc, page, run, full * 0.6)!;+ expect(wrapped.split("\n").length).toBeGreaterThan(1);+ expect(wrapped.replace(/\n/g, " ")).toBe(run.text);+ expect(renderScanEdit(doc, page, run, state, wrapped)).toBe(true);+ expect(run.text).toBe(wrapped);+ } finally {+ doc.dispose();+ }+ },+ );++ test(+ "measures at the size the user picked",+ { timeout: 120_000 },+ async () => {+ const { doc, page } = await buildScan(+ [{ family: "Carlito", text: SENTENCES[0], size: 12 }],+ { dpi: 200, blur: 0.5, noise: 6 },+ );+ try {+ const run = page.runs.find(isScanRun)!;+ const state = scanEditOf(doc, run)!;+ const words = state.lines[0].words;+ const full = words[words.length - 1].right - words[0].x;+ state.override = { ...state.override, fontSize: 24 };+ const wrapped = wrapScanText(doc, page, run, full * 1.2)!;+ expect(wrapped.split("\n").length).toBeGreaterThan(1);+ } finally {+ doc.dispose();+ }+ },+ );++ test(+ "does not wrap onto text further down the page",+ { timeout: 120_000 },+ async () => {+ const { doc, page } = await buildScan(+ SENTENCES.map((text) => ({ family: "Carlito", text, size: 12 })),+ { dpi: 200, blur: 0.5, noise: 6 },+ );+ try {+ const run = page.runs.filter(isScanRun)[0];+ const state = scanEditOf(doc, run)!;+ const words = state.lines[0].words;+ const full = words[words.length - 1].right - words[0].x;+ expect(+ wrapScanText(doc, page, run, full * 0.6)!.split("\n").length,+ ).toBeGreaterThan(1);+ expect(wrapScanText(doc, page, run, full * 0.25)).toBe(run.text);+ } finally {+ doc.dispose();+ }+ },+ );+});++describe("editing scanned text on a page turned with /Rotate", () => {+ test("fits the face and draws the edit", { timeout: 120_000 }, async () => {+ const { doc, page } = await buildScan(+ [{ family: "Carlito", text: SENTENCES[0], size: 12 }],+ { dpi: 200, blur: 0.5, noise: 6, rotate: 1 },+ );+ try {+ const run = page.runs.find(isScanRun)!;+ expect((await choicesFor(doc, page, run))[0]?.face.label).toBe(+ "Calibri (Carlito)",+ );+ const state = scanEditOf(doc, run)!;+ const jane = state.lines[0].words.find((w) => w.text.trim() === "Jane")!;+ const band = {+ x: jane.x - 1,+ y: state.lines[0].baseline - 3,+ width: jane.right - jane.x + 2,+ height: 13,+ };+ const before = renderLuma(doc.module, page, band, 0)!.data;+ renderScanEdit(doc, page, run, state, run.text.replace("Jane", "Mary"));+ const after = renderLuma(doc.module, page, band, 0)!.data;+ let changed = 0;+ for (let i = 0; i < before.length; i++)+ if (Math.abs(before[i] - after[i]) > 40) changed++;+ expect(changed).toBeGreaterThan(50);+ expect(state.textPtrs.length).toBeGreaterThan(0);+ } finally {+ doc.dispose();+ }+ });++ test(+ "fits the face of a sideways scan on a turned page",+ { timeout: 120_000 },+ async () => {+ const { doc, page } = await buildScan(+ [{ family: "Carlito", text: SENTENCES[0], size: 12 }],+ { dpi: 200, blur: 0.5, noise: 6, sideways: true, rotate: 1 },+ );+ try {+ const run = page.runs.find(isScanRun)!;+ expect((await choicesFor(doc, page, run))[0]?.face.label).toBe(+ "Calibri (Carlito)",+ );+ } finally {+ doc.dispose();+ }+ },+ );+});++describe("fitting a long block in slices", () => {+ test(+ "measures one line in a slice that is already over",+ { timeout: 120_000 },+ async () => {+ const { doc, page } = await buildScan(+ Array.from({ length: 10 }, () => ({+ family: "Carlito",+ text: SENTENCES[0],+ size: 12,+ })),+ { dpi: 150, blur: 0.5, noise: 6 },+ 18,+ );+ try {+ const run = page.runs.find(+ (r) => isScanRun(r) && r.text.split("\n").length >= 6,+ )!;+ const state = scanEditOf(doc, run)!;+ expect(prefitScanRun(doc, page, run, performance.now() - 1)).toBe(+ false,+ );+ expect(state.inks.size).toBe(1);+ } finally {+ doc.dispose();+ }+ },+ );+});++describe("editing a skewed scan", () => {+ const SKEWED: ScanOptions = { dpi: 200, blur: 0.5, noise: 6, skew: 0.018 };+ const baselineOf = (doc: EditorDocument, ptr: number) =>+ readMatrix(doc.module, ptr)![5];++ test(+ "draws a replaced word on that word's own baseline",+ { timeout: 120_000 },+ async () => {+ const { doc, page } = await buildScan(+ [{ family: "Carlito", text: SENTENCES[0], size: 12 }],+ SKEWED,+ );+ try {+ const run = page.runs.find(isScanRun)!;+ const state = scanEditOf(doc, run)!;+ const words = state.lines[0].words;+ const june = words.find((w) => w.text.trim() === "June")!;+ const truth = baselineOf(doc, june.ptr);+ expect(truth - baselineOf(doc, words[0].ptr)).toBeGreaterThan(3);+ renderScanEdit(doc, page, run, state, run.text.replace("June", "Mary"));+ expect(state.textPtrs.length).toBeGreaterThan(0);+ for (const ptr of state.textPtrs)+ expect(Math.abs(baselineOf(doc, ptr) - truth)).toBeLessThan(0.6);+ const own = words.indexOf(june);+ expect(+ Math.abs(state.inks.get(`0:${own}:${own}`)!.baseline - truth),+ ).toBeLessThan(0.6);+ } finally {+ doc.dispose();+ }+ },+ );++ test(+ "draws an inserted word on the line's baseline where it lands",+ { timeout: 120_000 },+ async () => {+ const { doc, page } = await buildScan(+ [{ family: "Carlito", text: SENTENCES[0], size: 12 }],+ SKEWED,+ );+ try {+ const run = page.runs.find(isScanRun)!;+ const state = scanEditOf(doc, run)!;+ const words = state.lines[0].words;+ const thirty = words.find((w) => w.text.trim() === "30")!;+ const june = words.find((w) => w.text.trim() === "June")!;+ const truth =+ (baselineOf(doc, thirty.ptr) + baselineOf(doc, june.ptr)) / 2;+ renderScanEdit(+ doc,+ page,+ run,+ state,+ run.text.replace("30 June", "30 late June"),+ );+ expect(state.textPtrs.length).toBeGreaterThan(0);+ for (const ptr of state.textPtrs)+ expect(Math.abs(baselineOf(doc, ptr) - truth)).toBeLessThan(0.8);+ } finally {+ doc.dispose();+ }+ },+ );+});++describe("editing light text on a dark fill", () => {+ test(+ "fits the face and redraws the edit light",+ { timeout: 120_000 },+ async () => {+ const { doc, page } = await buildScan(+ [{ family: "Carlito", text: SENTENCES[0], size: 12 }],+ { dpi: 200, blur: 0.5, noise: 6, reversed: true },+ );+ try {+ const run = page.runs.find(isScanRun)!;+ expect((await choicesFor(doc, page, run))[0]?.face.label).toBe(+ "Calibri (Carlito)",+ );+ const state = scanEditOf(doc, run)!;+ const jane = state.lines[0].words.find(+ (w) => w.text.trim() === "Jane",+ )!;+ renderScanEdit(doc, page, run, state, run.text.replace("Jane", "Mary"));+ const band = renderLuma(+ doc.module,+ page,+ {+ x: jane.x - 1,+ y: state.lines[0].baseline - 3,+ width: jane.right - jane.x + 2,+ height: 13,+ },+ 0,+ )!;+ expect(band.data.filter((l) => l > 160).length).toBeGreaterThan(50);+ } finally {+ doc.dispose();+ }+ },+ );+});++describe("matching scanned text in other scripts", () => {+ const SCAN: ScanOptions = { dpi: 200, blur: 0.6, noise: 8 };+ const russian: ScanLineSpec = {+ family: "DejaVu Sans",+ text: "Счёт 4471 для Ивана Петрова к оплате до 30 июня",+ size: 14,+ ocrFamily: "DejaVu Sans",+ };++ test(+ "picks a face that can draw Cyrillic and the edit survives a save",+ { timeout: 120_000 },+ async () => {+ const { doc, page } = await buildScan([russian], SCAN);+ try {+ const run = page.runs.find(isScanRun)!;+ const [top] = await choicesFor(doc, page, run);+ expect(top.face.label).toBe("DejaVu Sans");+ renderScanEdit(+ doc,+ page,+ run,+ scanEditOf(doc, run)!,+ run.text.replace("Ивана", "Марии"),+ );+ expect(await savedText(doc)).toContain("Марии");+ } finally {+ doc.dispose();+ }+ },+ );++ test(+ "picks the script's own face when the server has one",+ { timeout: 120_000 },+ async () => {+ const id = "a".repeat(64);+ const bytes = await readFile(+ path.join(FONT_DIR, "NotoSansJP-Regular.ttf"),+ );+ get.mockImplementation(async (url: string) =>+ url === SERVER_FONTS_URL+ ? {+ data: {+ families: [+ {+ family: "Noto Sans JP",+ faces: [{ id, style: "Regular", weight: 400 }],+ },+ ],+ },+ }+ : { data: new Uint8Array(bytes).buffer },+ );+ const text = "請求書 4471 六月 三十日 までに お支払い ください";+ await loadScriptScanFaces(scanScriptsOf(text));+ const { doc, page } = await buildScan(+ [{ family: "Noto Sans JP", text, size: 14, ocrFamily: "Noto Sans JP" }],+ SCAN,+ );+ try {+ const run = page.runs.find(isScanRun)!;+ expect((await choicesFor(doc, page, run))[0]?.face.label).toBe(+ "Noto Sans JP",+ );+ } finally {+ doc.dispose();+ _resetScanFacesForTests();+ forgetServerFontList();+ }+ },+ );++ test("the bundled Chinese and Korean fonts can be matched", async () => {+ const chinese = await staticFace("Noto Sans SC", "NotoSansSC-Regular.ttf");+ const korean = await staticFace("Noto Sans KR", "NotoSansKR-Regular.ttf");+ expect(chinese && faceCovers(chinese, "华级们这说话东车书门关进")).toBe(+ true,+ );+ expect(korean && faceCovers(korean, "청구서 김민준 님 납부")).toBe(true);+ });++ test(+ "sizes caps-only Cyrillic and a Japanese line without digits by their own glyph height",+ { timeout: 120_000 },+ async () => {+ const japanese = await staticFace(+ "Noto Sans JP",+ "NotoSansJP-Regular.ttf",+ );+ _setBundledScanFacesForTests([...bundled, japanese!]);+ const lines: ScanLineSpec[] = [+ {+ family: "DejaVu Sans",+ text: "СЧЕТ НА ОПЛАТУ ДЛЯ ИВАНА ПЕТРОВА",+ size: 14,+ ocrFamily: "DejaVu Sans",+ },+ {+ family: "Noto Sans JP",+ text: "請求書 六月 三十日 までに お支払い ください",+ size: 14,+ ocrFamily: "Noto Sans JP",+ },+ ];+ const { doc, page } = await buildScan(lines, SCAN);+ try {+ for (const spec of lines) {+ const run = page.runs.find(+ (r) => isScanRun(r) && r.text.startsWith(spec.text.slice(0, 3)),+ )!;+ await choicesFor(doc, page, run);+ const size = scanEditOf(doc, run)!.block!.style.fontSize;+ expect(Math.abs(size / spec.size - 1)).toBeLessThan(0.1);+ }+ } finally {+ doc.dispose();+ }+ },+ );++ test(+ "offers nothing it cannot draw and leaves the scan alone when an edit cannot be drawn",+ { timeout: 120_000 },+ async () => {+ await staticFace("Noto Sans KR", "NotoSansKR-Regular.ttf");+ resetDroppedBase14Chars();+ const { doc, page } = await buildScan(+ [+ {+ family: "Noto Sans KR",+ text: "청구서 4471 김민준 님 6월 30일까지 납부",+ size: 14,+ ocrFamily: "Noto Sans KR",+ },+ ],+ SCAN,+ );+ try {+ const run = page.runs.find(isScanRun)!;+ expect(await choicesFor(doc, page, run)).toEqual([]);+ const line = scanEditOf(doc, run)!.lines[0];+ const region = {+ x: 20,+ y: line.baseline - 6,+ width: 500,+ height: line.height + 8,+ };+ const before = renderLuma(doc.module, page, region, 0)!.data;+ renderScanEdit(+ doc,+ page,+ run,+ scanEditOf(doc, run)!,+ run.text.replace("김민준", "이서연"),+ );+ expect(getDroppedBase14Chars()).toEqual(+ expect.arrayContaining(["이", "서", "연"]),+ );+ expect(renderLuma(doc.module, page, region, 0)!.data).toEqual(before);+ } finally {+ doc.dispose();+ }+ },+ );++ test(+ "refits a block no face could draw once a face for it arrives",+ { timeout: 120_000 },+ async () => {+ const japanese = await staticFace(+ "Noto Sans JP",+ "NotoSansJP-Regular.ttf",+ );+ const text = "請求書 六月 三十日 までに お支払い ください";+ const { doc, page } = await buildScan(+ [{ family: "Noto Sans JP", text, size: 14, ocrFamily: "Noto Sans JP" }],+ SCAN,+ );+ try {+ const run = page.runs.find(isScanRun)!;+ expect(await choicesFor(doc, page, run)).toEqual([]);+ expect(scanRunNeedsFit(doc, run)).toBe(false);+ _setBundledScanFacesForTests([...bundled, japanese!]);+ expect(scanRunNeedsFit(doc, run)).toBe(true);+ const state = scanEditOf(doc, run)!;+ renderScanEdit(doc, page, run, state, run.text.replace("六月", "七月"));+ expect(state.block?.ranked[0]?.face.label).toBe("Noto Sans JP");+ expect(drawnFontNames(doc, state.textPtrs)).toEqual([+ expect.stringMatching(/^NotoSansJP/),+ ]);+ } finally {+ doc.dispose();+ }+ },+ );+});++describe("drawing typed words from the scan's own letters", () => {+ const SCAN: ScanOptions = { dpi: 200, blur: 0.5, noise: 6 };+ const spec: ScanLineSpec = {+ family: "DejaVu Sans",+ text: "Invoice 4471 for Jane Example is due on 30 June",+ size: 12,+ };++ test(+ "looks more like the scan than the best-fitting font does",+ { timeout: 60_000 },+ async () => {+ _setBundledScanFacesForTests(+ bundled.filter((f) => f.family !== spec.family),+ );+ const { doc, page } = await buildScan([spec], SCAN);+ try {+ const run = page.runs.find(isScanRun)!;+ const state = scanEditOf(doc, run)!;+ const words = state.lines[0].words;+ const jane = words.find((w) => w.text.trim() === "Jane")!;+ const june = words.find((w) => w.text.trim() === "June")!;+ const baseline = state.lines[0].baseline;+ const width = jane.right - jane.x + 3;+ const scanned = inkProfile(page, doc, jane.x - 2, width, baseline);+ const [best] = await choicesFor(doc, page, run);+ const retyped = () => {+ renderScanEdit(+ doc,+ page,+ run,+ state,+ run.text.replace("June", "Jane"),+ );+ return likeness(+ scanned,+ inkProfile(page, doc, june.x - 2, width, baseline),+ );+ };+ const fromScan = retyped();+ expect(state.typedFromScan).toBe(true);+ const measuredAlone = (text: string) => {+ const i = words.findIndex((w) => w.text.trim() === text);+ return state.inks.has(`0:${i}:${i}`);+ };+ expect(["4471", "for", "is"].filter(measuredAlone)).toEqual([]);+ state.override.style = best.style;+ const fromFont = retyped();+ expect(state.typedFromScan).toBe(false);+ expect(fromScan).toBeGreaterThan(0.75);+ expect(fromScan).toBeGreaterThan(fromFont + 0.2);+ } finally {+ doc.dispose();+ }+ },+ );+});++describe("edits that need no font, and text no font can draw", () => {+ const SCAN: ScanOptions = { dpi: 200, blur: 0.5, noise: 6 };++ test(+ "deletes words from a block no font can draw, and a refused edit leaves the deletion as it was",+ { timeout: 120_000 },+ async () => {+ await staticFace("Noto Sans KR", "NotoSansKR-Regular.ttf");+ const { doc, page } = await buildScan(+ [+ {+ family: "Noto Sans KR",+ text: "청구서 4471 김민준 님 6월 30일까지 납부",+ size: 14,+ ocrFamily: "Noto Sans KR",+ },+ ],+ SCAN,+ );+ try {+ const run = page.runs.find(isScanRun)!;+ const state = scanEditOf(doc, run)!;+ const original = run.text;+ const line = state.lines[0];+ const region = {+ x: 20,+ y: line.baseline - 6,+ width: 500,+ height: line.height + 8,+ };+ expect(scanTypingDropped(run)).toBe(true);+ const deleted = original.replace("김민준 ", "");+ expect(renderScanEdit(doc, page, run, state, deleted)).toBe(true);+ expect(run.text).toBe(deleted);+ expect(state.lifted.size).toBeGreaterThan(0);+ expect(scanRunNeedsFit(doc, run)).toBe(true);+ const afterDelete = renderLuma(doc.module, page, region, 0)!.data;+ const leaves = [...run.paragraphLeafPtrs];++ expect(+ renderScanEdit(+ doc,+ page,+ run,+ state,+ deleted.replace("님", "이서연"),+ ),+ ).toBe(false);+ expect(run.text).toBe(deleted);+ expect(run.paragraphLeafPtrs).toEqual(leaves);+ expect(renderLuma(doc.module, page, region, 0)!.data).toEqual(+ afterDelete,+ );++ expect(renderScanEdit(doc, page, run, state, original)).toBe(true);+ expect(state.lifted.size).toBe(0);+ expect(await savedText(doc)).toContain("김민준");+ } finally {+ doc.dispose();+ }+ },+ );++ test(+ "refuses typed Hebrew in a block whose face covers it, rather than drawing it backwards",+ { timeout: 120_000 },+ async () => {+ resetDroppedBase14Chars();+ const { doc, page } = await buildScan(+ [{ family: "DejaVu Sans", text: SENTENCES[0], size: 12 }],+ SCAN,+ );+ try {+ const run = page.runs.find(isScanRun)!;+ const state = scanEditOf(doc, run)!;+ expect(scanTypingDropped(run)).toBe(false);+ expect(+ renderScanEdit(+ doc,+ page,+ run,+ state,+ run.text.replace("Jane", "שרה"),+ ),+ ).toBe(false);+ expect(state.created).toEqual([]);+ expect(getDroppedBase14Chars()).toEqual(+ expect.arrayContaining(["ש", "ר", "ה"]),+ );+ } finally {+ doc.dispose();+ }+ },+ );++ test(+ "keeps a word's scan pixels when its replacement is in a script the block's font cannot draw",+ { timeout: 120_000 },+ async () => {+ resetDroppedBase14Chars();+ _setBundledScanFacesForTests([]);+ const { doc, page } = await buildScan(+ [{ family: "Carlito", text: SENTENCES[0], size: 12 }],+ SCAN,+ );+ try {+ const run = page.runs.find(isScanRun)!;+ const state = scanEditOf(doc, run)!;+ const line = state.lines[0];+ const jane = line.words.find((w) => w.text.trim() === "Jane")!;+ const band = {+ x: jane.x - 1,+ y: line.baseline - 3,+ width: jane.right - jane.x + 2,+ height: 13,+ };+ const before = renderLuma(doc.module, page, band, 0)!.data;+ renderScanEdit(doc, page, run, state, run.text.replace("Jane", "Иван"));+ const after = renderLuma(doc.module, page, band, 0)!.data;+ let changed = 0;+ for (let i = 0; i < before.length; i++)+ if (Math.abs(before[i] - after[i]) > 40) changed++;+ expect(changed).toBeLessThan(10);+ expect(getDroppedBase14Chars()).toEqual(+ expect.arrayContaining(["И", "в"]),+ );+ } finally {+ doc.dispose();+ }+ },+ );++ test(+ "keeps the pixels of every word one undrawable replacement stands for",+ { timeout: 120_000 },+ async () => {+ _setBundledScanFacesForTests([]);+ const { doc, page } = await buildScan(+ [{ family: "Carlito", text: SENTENCES[0], size: 12 }],+ SCAN,+ );+ try {+ const run = page.runs.find(isScanRun)!;+ const state = scanEditOf(doc, run)!;+ const line = state.lines[0];+ const jane = line.words.find((w) => w.text.trim() === "Jane")!;+ const is = line.words.find((w) => w.text.trim() === "is")!;+ const band = {+ x: jane.x - 1,+ y: line.baseline - 3,+ width: is.right - jane.x + 2,+ height: 13,+ };+ const before = renderLuma(doc.module, page, band, 0)!.data;+ renderScanEdit(+ doc,+ page,+ run,+ state,+ run.text.replace("Jane Example", "Иван"),+ );+ const after = renderLuma(doc.module, page, band, 0)!.data;+ let changed = 0;+ for (let i = 0; i < before.length; i++)+ if (Math.abs(before[i] - after[i]) > 40) changed++;+ expect(changed).toBeLessThan(10);+ } finally {+ doc.dispose();+ }+ },+ );++ test(+ "draws typing in a face that covers it when the scan is too faint to fit one",+ { timeout: 120_000 },+ async () => {+ const { doc, page } = await buildScan(+ [{ family: "Carlito", text: SENTENCES[0], size: 12 }],+ SCAN,+ );+ try {+ const run = page.runs.find(isScanRun)!;+ const state = scanEditOf(doc, run)!;+ const blank = emitFillRect(+ doc.module,+ page,+ { x: 0, y: 0, width: page.width, height: page.height },+ { r: 255, g: 255, b: 255 },+ 0,+ );+ expect(blank).not.toBe(0);+ expect(+ renderScanEdit(+ doc,+ page,+ run,+ state,+ run.text.replace("Jane", "Иван"),+ ),+ ).toBe(true);+ expect(state.block).toBeNull();+ expect(state.textPtrs.length).toBeGreaterThan(0);+ expect(drawnFontNames(doc, state.textPtrs)).not.toContain("Helvetica");+ } finally {+ doc.dispose();+ }+ },+ );++ test(+ "keeps the spaces between words whose hidden copies were redrawn",+ { timeout: 120_000 },+ async () => {+ const { doc, page } = await buildScan(+ [{ family: "Carlito", text: SENTENCES[0], size: 12 }],+ SCAN,+ );+ try {+ const run = page.runs.find(isScanRun)!;+ const state = scanEditOf(doc, run)!;+ const original = run.text;+ renderScanEdit(+ doc,+ page,+ run,+ state,+ original+ .replace("Invoice", "Invoices issued")+ .replace("Jane", "Mary"),+ );+ const edited = await savedText(doc);+ expect(edited).toContain("issued 4471 for Mary Example is due");+ renderScanEdit(doc, page, run, state, original);+ expect(await savedText(doc)).toContain(SENTENCES[0]);+ } finally {+ doc.dispose();+ }+ },+ );++ test(+ "fits a block on the scan alone after a deletion has covered words",+ { timeout: 120_000 },+ async () => {+ const fitAfter = async (deleteFirst: boolean) => {+ const { doc, page } = await buildScan(+ [{ family: "Carlito", text: SENTENCES[0], size: 12 }],+ SCAN,+ );+ try {+ const run = page.runs.find(isScanRun)!;+ const state = scanEditOf(doc, run)!;+ const deleted = run.text.replace("Invoice ", "");+ if (deleteFirst) {+ expect(renderScanEdit(doc, page, run, state, deleted)).toBe(true);+ expect(state.created.length).toBeGreaterThan(0);+ expect(state.block).toBeUndefined();+ }+ const size = scanDrawnSize(doc, page, run);+ state.block = undefined;+ while (!prefitScanRun(doc, page, run, Infinity));+ const style = state.block!.style;+ return {+ size: size?.toFixed(2),+ family: style.family,+ fontSize: style.fontSize.toFixed(2),+ };+ } finally {+ doc.dispose();+ }+ };+ expect(await fitAfter(true)).toEqual(await fitAfter(false));+ },+ );+});++describe("reading scanned words inside a form", () => {+ test("puts each word on its baseline on the page, not in the form", async () => {+ const form =+ "BT /F1 12 Tf 3 Tr 1 0 0 1 50 100 Tm (Hello) Tj 1 0 0 1 82 100.5 Tm (world) Tj ET";+ const bytes = buildClassicPdf(+ [+ { num: 1, body: "<< /Type /Catalog /Pages 2 0 R >>" },+ { num: 2, body: "<< /Type /Pages /Kids [3 0 R] /Count 1 >>" },+ {+ num: 3,+ body: "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << /XObject << /Fx 6 0 R >> >> /Contents 4 0 R >>",+ },+ { num: 4, body: streamBody("", "q 1 0 0 1 0 300 cm /Fx Do Q") },+ {+ num: 5,+ body: "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>",+ },+ {+ num: 6,+ body: streamBody(+ "/Type /XObject /Subtype /Form /BBox [0 0 612 792] /Resources << /Font << /F1 5 0 R >> >>",+ form,+ ),+ },+ ],+ 1,+ );+ const doc = await EditorDocument.open(bytes);+ try {+ const page = doc.page(0);+ PdfiumTextReader.populate(doc, page);+ const run = page.runs.find(isScanRun)!;+ expect(run.containerPtr).not.toBe(0);+ const state = scanEditOf(doc, run)!;+ expect(+ state.lines.flatMap((l) => l.words.map((w) => w.baseline)),+ ).toEqual([400, 400.5]);+ } finally {+ doc.dispose();+ }+ });+});++describe("scanned text whose OCR words do not line up with the scan", () => {+ const ocrPage = async (scale: number) => {+ const bytes = buildClassicPdf(+ [+ { num: 1, body: "<< /Type /Catalog /Pages 2 0 R >>" },+ { num: 2, body: "<< /Type /Pages /Kids [3 0 R] /Count 1 >>" },+ {+ num: 3,+ body: "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << /Font << /F1 5 0 R >> >> /Contents 4 0 R >>",+ },+ {+ num: 4,+ body: streamBody(+ "",+ `BT /F1 12 Tf 3 Tr ${scale} Tz 1 0 0 1 50 700 Tm (Invoice for Jane Example) Tj ET`,+ ),+ },+ {+ num: 5,+ body: "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>",+ },+ ],+ 1,+ );+ const doc = await EditorDocument.open(bytes);+ const page = doc.page(0);+ PdfiumTextReader.populate(doc, page);+ return { doc, page, run: page.runs.find(isScanRun)! };+ };++ test("flags the block so the inspector can say it cannot be edited", async () => {+ const plausible = await ocrPage(100);+ const squeezed = await ocrPage(5);+ try {+ expect(scanBlockMisaligned(plausible.doc, plausible.run)).toBe(false);+ expect(scanBlockMisaligned(squeezed.doc, squeezed.run)).toBe(true);+ new DeleteObjectCommand({+ pageIndex: 0,+ runId: squeezed.run.id,+ }).apply(squeezed.doc);+ expect(squeezed.page.findRun(squeezed.run.id)).toBe(squeezed.run);+ } finally {+ plausible.doc.dispose();+ squeezed.doc.dispose();+ }+ });+});++describe("scanned text whose OCR layer sits off the scanned words", () => {+ const scan = (ocrShift: number) =>+ buildScan(+ SENTENCES.map((text) => ({ family: "Helvetica", text, size: 12 })),+ { dpi: 150, blur: 0.5, noise: 4, ocrShift },+ );++ test("refuses the edit when no ink sits under the OCR words but sits beside them", async () => {+ const { doc, page } = await scan(-14);+ try {+ const run = page.runs.find(isScanRun)!;+ expect(scanBlockOffInk(doc, run)).toBe(true);+ const state = scanEditOf(doc, run)!;+ const before = state.created.length;+ expect(renderScanEdit(doc, page, run, state, `${run.text} extra`)).toBe(+ false,+ );+ expect(state.created.length).toBe(before);+ } finally {+ doc.dispose();+ }+ });++ test("leaves the picked font unapplied when the block cannot be redrawn", async () => {+ const { doc, page } = await scan(-14);+ try {+ const run = page.runs.find(isScanRun)!;+ const state = scanEditOf(doc, run)!;+ const before = state.override;+ new SetScanStyleCommand({+ pageIndex: 0,+ runId: run.id,+ choice: {+ face: COURIER,+ style: {+ family: COURIER.family,+ fontSize: 12,+ stretch: 1,+ ink: { r: 0, g: 0, b: 0, a: 255 },+ weight: 0,+ hollow: 0,+ softness: 0,+ },+ score: 1,+ },+ }).apply(doc);+ expect(state.override).toBe(before);+ expect(preferredScanFace(doc)).toBeNull();+ } finally {+ doc.dispose();+ }+ });++ test("leaves a scan whose OCR words sit on the ink editable", async () => {+ const { doc, page } = await scan(0);+ try {+ const run = page.runs.find(isScanRun)!;+ expect(scanBlockOffInk(doc, run)).toBe(false);+ } finally {+ doc.dispose();+ }+ });++ test("does not blame the OCR layer when the page has no ink at all", async () => {+ const bytes = buildClassicPdf(+ [+ { num: 1, body: "<< /Type /Catalog /Pages 2 0 R >>" },+ { num: 2, body: "<< /Type /Pages /Kids [3 0 R] /Count 1 >>" },+ {+ num: 3,+ body: "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << /Font << /F1 5 0 R >> >> /Contents 4 0 R >>",+ },+ {+ num: 4,+ body: streamBody(+ "",+ "BT /F1 12 Tf 3 Tr 1 0 0 1 50 700 Tm (Invoice for Jane Example) Tj ET",+ ),+ },+ {+ num: 5,+ body: "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>",+ },+ ],+ 1,+ );+ const doc = await EditorDocument.open(bytes);+ try {+ const page = doc.page(0);+ PdfiumTextReader.populate(doc, page);+ expect(scanBlockOffInk(doc, page.runs.find(isScanRun)!)).toBe(false);+ } finally {+ doc.dispose();+ }+ });+});diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/scanGlyphs.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/scanGlyphs.test.tsnew file mode 100644index 0000000000..ed6e97ae56--- /dev/null+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/scanGlyphs.test.ts@@ -0,0 +1,169 @@+import { describe, expect, test } from "vitest";+import {+ buildGlyphAtlas,+ composeText,+ type ScannedWord,+} from "@editor/tools/pdfTextEditor/commands/scanGlyphs";++const SCALE = 4;+const HEIGHT = 40;+const DESCENT = 2;+const BASE_ROW = HEIGHT - DESCENT * SCALE;++interface Letter {+ width: number;+ top: number;+ bottom: number;+}++const X: Letter = { width: 8, top: 12, bottom: 0 };++const widthOf = (ch: string) =>+ /[il]/.test(ch) ? 3 : /[mw]/.test(ch) ? 14 : /[A-Z]/.test(ch) ? 12 : 8;++const letterOf = (ch: string): Letter => ({+ width: widthOf(ch),+ top: /[A-Z0-9]/.test(ch) ? 17 : /[bdfhijkl]/.test(ch) ? 18 : 12,+ bottom: 0,+});++function scanned(+ text: string,+ place: (i: number, letter: Letter) => number,+ overrides: Record<number, Letter> = {},+): ScannedWord {+ const letters = [...text].map((ch, i) => overrides[i] ?? letterOf(ch));+ const lefts = letters.map((l, i) => place(i, l));+ const width = Math.max(...letters.map((l, i) => lefts[i] + l.width)) + 4;+ const rgba = new Uint8Array(width * HEIGHT * 4);+ letters.forEach((l, i) => {+ for (let y = BASE_ROW - l.top; y < BASE_ROW - l.bottom; y++)+ for (let x = lefts[i]; x < lefts[i] + l.width; x++)+ rgba[(y * width + x) * 4 + 3] = 255;+ });+ return {+ text,+ rgba,+ width,+ height: HEIGHT,+ left: 0,+ scale: SCALE,+ spans: letters.map((l, i) => ({+ left: lefts[i] / SCALE,+ right: (lefts[i] + l.width) / SCALE,+ })),+ };+}++const proportional = (text: string, overrides: Record<number, Letter> = {}) => {+ const widths = [...text].map((ch, i) => (overrides[i] ?? letterOf(ch)).width);+ return scanned(+ text,+ (i) => 3 + widths.slice(0, i).reduce((p, q) => p + q + 3, 0),+ overrides,+ );+};++const CELL = 20;+const typewritten = (text: string) =>+ scanned(text, (i, l) => 3 + i * CELL + Math.round((CELL - l.width) / 2));++const inkWidth = (glyphs: { inkLeft: number; inkRight: number } | null) =>+ glyphs ? glyphs.inkRight - glyphs.inkLeft : null;++describe("building the atlas from the scan's letters", () => {+ test("drops a letter whose ink is taller than the OCR's reading allows", () => {+ const atlas = buildGlyphAtlas(+ [+ proportional("nonce"),+ proportional("ce", { 1: { width: 8, top: 18, bottom: 0 } }),+ ],+ DESCENT,+ )!;+ expect(composeText(atlas, "e", 0)).not.toBeNull();+ const accentOnly = buildGlyphAtlas(+ [+ proportional("noun"),+ proportional("ce", { 1: { width: 8, top: 18, bottom: 0 } }),+ ],+ DESCENT,+ )!;+ expect(composeText(accentOnly, "e", 0)).toBeNull();+ expect(composeText(accentOnly, "on", 0)).not.toBeNull();+ });++ test("leaves out a word with right-to-left letters, whose ink runs the other way", () => {+ const atlas = buildGlyphAtlas(+ [proportional("nonce"), proportional("mאב")],+ DESCENT,+ )!;+ expect([...atlas.glyphs.keys()].sort()).toEqual(["c", "e", "n", "o"]);+ });++ test("keeps both words intact across a gap that is not a whole pixel", () => {+ const atlas = buildGlyphAtlas([proportional("noun")], DESCENT)!;+ const composed = composeText(atlas, "no un", 9.4)!;++ expect(Number.isInteger(composed.width)).toBe(true);+ expect(composed.rgba.length).toBe(composed.width * composed.height * 4);+ const inkPerRow = (row: number) => {+ let ink = 0;+ for (let x = 0; x < composed.width; x++)+ if (composed.rgba[(row * composed.width + x) * 4 + 3] > 0) ink++;+ return ink;+ };+ // Four x-height letters, each a solid block as wide as it is.+ const row = BASE_ROW - 4;+ expect(inkPerRow(row)).toBe(4 * X.width);+ expect(inkPerRow(BASE_ROW - X.top - 2)).toBe(0);+ });++ test("never pastes a capital the OCR read as lowercase", () => {+ const atlas = buildGlyphAtlas(+ [+ proportional("moon"),+ proportional("oxford", { 0: { width: 12, top: 17, bottom: 0 } }),+ ],+ DESCENT,+ )!;+ expect(inkWidth(composeText(atlas, "o", 0))).toBe(X.width);+ });++ test("drops a letter whose ink hangs below the baseline it should sit on", () => {+ const atlas = buildGlyphAtlas(+ [+ proportional("noun"),+ proportional("aca", { 1: { width: 8, top: 12, bottom: -6 } }),+ ],+ DESCENT,+ )!;+ expect(composeText(atlas, "c", 0)).toBeNull();+ expect(composeText(atlas, "a", 0)).not.toBeNull();+ });+});++describe("spacing letters taken from the scan", () => {+ test("keeps typewriter letters on the scan's character pitch", () => {+ const atlas = buildGlyphAtlas(+ [typewritten("illicit"), typewritten("minimum")],+ DESCENT,+ )!;+ expect(atlas.pitch).toBe(CELL);+ const halves = (widthOf("i") + widthOf("m")) / 2;+ const near = (text: string, cells: number) =>+ Math.abs(+ inkWidth(composeText(atlas, text, 0))! - (cells * CELL + halves),+ );+ expect(near("im", 1)).toBeLessThanOrEqual(1);+ expect(near("i m", 2)).toBeLessThanOrEqual(1);+ });++ test("packs proportional letters a letter gap apart", () => {+ const atlas = buildGlyphAtlas(+ [proportional("Invoice"), proportional("Example")],+ DESCENT,+ )!;+ expect(atlas.pitch).toBeNull();+ expect(inkWidth(composeText(atlas, "ce", 0))).toBe(2 * X.width + 3);+ });+});diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/scanInkDots.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/scanInkDots.test.tsnew file mode 100644index 0000000000..1c8e3a75a3--- /dev/null+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/scanInkDots.test.ts@@ -0,0 +1,65 @@+// @vitest-environment node+import { readFile } from "node:fs/promises";+import { createRequire } from "node:module";+import { afterAll, beforeAll, expect, test, vi } from "vitest";++const { get } = vi.hoisted(() => ({ get: vi.fn() }));+vi.mock("@editor/services/apiClient", () => ({ default: { get } }));++import { measureScanInk } from "@editor/tools/pdfTextEditor/pdfium/BackgroundSampler";+import { isScanRun } from "@editor/tools/pdfTextEditor/commands/scanTextEdit";+import { buildScan } from "@editor/tools/pdfTextEditor/__tests__/scanFixtures";++beforeAll(async () => {+ const wasmPath = createRequire(import.meta.url).resolve(+ "@embedpdf/pdfium/pdfium.wasm",+ );+ const wasmBytes = await readFile(wasmPath);+ vi.stubGlobal(+ "fetch",+ vi.fn(async () =>+ Promise.resolve(+ new Response(wasmBytes, {+ headers: { "Content-Type": "application/wasm" },+ }),+ ),+ ),+ );+});++afterAll(() => {+ vi.unstubAllGlobals();+});++test("a word with no ascender still takes its i-dots into the cover box", async () => {+ const size = 12;+ const { doc, page } = await buildScan(+ [{ family: "Times-Roman", text: "mice in vain", size }],+ { dpi: 200, blur: 0.5, noise: 6 },+ );+ try {+ const run = page.runs.find(isScanRun)!;+ const baseline = run.matrix.f;+ const span = { x0: run.bounds.x, x1: run.bounds.x + run.bounds.width };+ // An OCR box that stops at the x-height, as it does for such a word.+ const tight = measureScanInk(doc.module, page, {+ ...span,+ bottom: baseline - 0.5,+ top: baseline + size * 0.47,+ })!;+ const tall = measureScanInk(doc.module, page, {+ ...span,+ bottom: baseline - 0.5,+ top: baseline + size * 0.8,+ })!;+ const top = (ink: typeof tight) => ink.rect.y + ink.rect.height;++ // The dots sit about a fifth of the size above the x-height.+ expect(top(tall) - baseline).toBeGreaterThan(size * 0.6);+ expect(top(tight)).toBeCloseTo(top(tall), 0);+ // What the letters measure is unchanged by the taller cover.+ expect(tight.body.height).toBeLessThan(size * 0.55);+ } finally {+ doc.dispose();+ }+});diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/scanLayout.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/scanLayout.test.tsindex e0eafc4d33..d39a0b6a69 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/scanLayout.test.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/scanLayout.test.ts@@ -2,6 +2,7 @@import { describe, expect, it } from "vitest";import {layoutScanEdit,+ rewrapLines,type LayoutInput,type LayoutLine,} from "@editor/tools/pdfTextEditor/commands/scanLayout";@@ -39,6 +40,68 @@ function run(}describe("layoutScanEdit", () => {+ it("opens a gap for every extra space typed between kept words", () => {+ const l = run(block("NORTH HARBOUR CO"), "NORTH HARBOUR CO");+ expect(l.kept.map((k) => k.x)).toEqual([10, 39 + 8, 78 + 8]);+ });++ it("keeps the extra spaces inside and before typed text", () => {+ const l = run(block("NORTH HARBOUR CO"), "NORTH OLD PIER HARBOUR CO");+ expect(l.typed.map((t) => [t.text, t.x])).toEqual([["OLD PIER", 39 + 4]]);+ });++ it("does not move a word for spaces the scan's text already had", () => {+ const lines = block("NORTH HARBOUR CO");+ lines[0].words[1].lead = 2;+ const l = run(lines, "NORTH HARBOUR CO");+ expect(l.kept.every((k) => !k.moved)).toBe(true);+ });++ it("draws a replaced word where it was when the scan already had its spaces", () => {+ const lines = block("NORTH HARBOUR CO");+ lines[0].words[1].lead = 2;+ lines[0].words[1].x += 8;+ const l = run(lines, "NORTH BAY CO");+ expect(l.typed).toEqual([+ expect.objectContaining({ text: "BAY", x: lines[0].words[1].x }),+ ]);+ });++ it("starts a replaced first word where the scan's indented line starts", () => {+ const lines = block("NORTH HARBOUR");+ lines[0].words[0].lead = 2;+ const l = run(lines, " SOUTH HARBOUR");+ expect(l.typed).toEqual([+ expect.objectContaining({ text: "SOUTH", x: lines[0].words[0].x }),+ ]);+ });++ it("keeps every word a typed word replaces", () => {+ const l = run(block("NORTH HARBOUR CO"), "NORTH BAY");+ expect(l.typed).toEqual([+ expect.objectContaining({+ text: "BAY",+ replaced: [+ expect.objectContaining({ text: "HARBOUR" }),+ expect.objectContaining({ text: "CO" }),+ ],+ }),+ ]);+ });++ it("measures no word on a line the edit left alone", () => {+ const measured: string[] = [];+ run(block("NORTH HARBOUR CO", "TEL 123"), "NORTH HARBOUR CO\nFAX 123", {+ wordWidth: (w) => {+ measured.push(w.text);+ return w.text.length * 5;+ },+ });+ expect(+ measured.filter((t) => ["NORTH", "HARBOUR", "CO"].includes(t)),+ ).toEqual([]);+ });+it("leaves an unchanged block exactly as scanned", () => {const l = run(block("NORTH HARBOUR CO", "TEL 123"),@@ -102,3 +165,44 @@ describe("layoutScanEdit", () => {expect(l.typed.map((t) => t.text)).toEqual(["NORTH CO", "TEL 1"]);});});++describe("rewrapLines", () => {+ const upTo = (n: number) => (line: string) => line.length <= n;++ it("moves the words that overflow to the front of the next line", () => {+ expect(rewrapLines("one two three four\nfive", upTo(13), false)).toBe(+ "one two three\nfour five",+ );+ });++ it("keeps every character at its offset", () => {+ const text = "one two three four\nfive six seven\neight";+ const wrapped = rewrapLines(text, upTo(13), true);+ expect(wrapped.replace(/\n/g, " ")).toBe(text.replace(/\n/g, " "));+ expect(wrapped.split("\n").every((l) => l.trim().length <= 13)).toBe(true);+ });++ it("adds a line under the last one only when there is room", () => {+ expect(rewrapLines("one two three four", upTo(13), true)).toBe(+ "one two three\nfour",+ );+ expect(rewrapLines("one two three four", upTo(13), false)).toBe(+ "one two three four",+ );+ });++ it("does not pull a paragraph break into the line above", () => {+ expect(rewrapLines("one two three four\n\nfive", upTo(13), true)).toBe(+ "one two three\nfour\n\nfive",+ );+ });++ it("leaves a single word that cannot fit, and text that already fits", () => {+ expect(rewrapLines("incomprehensibilities", upTo(5), true)).toBe(+ "incomprehensibilities",+ );+ expect(rewrapLines("one two\nthree", upTo(13), true)).toBe(+ "one two\nthree",+ );+ });+});diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/scanPaint.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/scanPaint.test.tsnew file mode 100644index 0000000000..9f268d3d8e--- /dev/null+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/scanPaint.test.ts@@ -0,0 +1,61 @@+// @vitest-environment node+import { describe, expect, test, vi } from "vitest";++vi.mock(+ "@editor/tools/pdfTextEditor/commands/scanStyle",+ async (importOriginal) => ({+ ...(await importOriginal<object>()),+ placeText: vi.fn(() => [11, 12]),+ }),+);++import {+ drawInFont,+ type Canvas,+} from "@editor/tools/pdfTextEditor/commands/scanPaint";+import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";+import type { Page } from "@editor/tools/pdfTextEditor/model/Page";++describe("drawing typed scan text in a font", () => {+ test("tags the drawn text with the block's tags, as it replaces the tagged OCR words", () => {+ const marked: Array<[number, string]> = [];+ const module = {+ FPDFPageObj_CountMarks: () => 0,+ FPDFPageObj_AddMark: (ptr: number, name: string) => {+ marked.push([ptr, name]);+ return 1;+ },+ FPDFPageObjMark_SetIntParam: () => true,+ };+ const canvas: Canvas = {+ doc: { module, docPtr: 1 } as unknown as EditorDocument,+ page: { pagePtr: 2 } as unknown as Page,+ tagMarks: [{ name: "P", mcid: 3 }],+ created: [],+ textPtrs: [],+ searchableFontPtr: 0,+ };+ drawInFont(+ canvas,+ "Mary",+ 10,+ 10,+ 100,+ {+ family: "Helvetica",+ fontSize: 12,+ stretch: 1,+ ink: { r: 0, g: 0, b: 0, a: 255 },+ weight: 0,+ hollow: 0,+ softness: 0,+ },+ Infinity,+ );+ expect(marked).toEqual([+ [11, "P"],+ [12, "P"],+ ]);+ expect(canvas.textPtrs).toEqual([11, 12]);+ });+});diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/scanTextEdit.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/scanTextEdit.test.tsindex 5ce484903f..eb471f93bd 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/scanTextEdit.test.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/scanTextEdit.test.ts@@ -21,6 +21,7 @@ vi.mock("@editor/tools/pdfTextEditor/commands/editTextHelpers", () => ({}));vi.mock("@editor/tools/pdfTextEditor/pdfium/BackgroundSampler", () => ({INK_SCALE: 1,+ measureScanInk: () => null,sampleBackground: () => ({ fill: { r: 255, g: 255, b: 255, a: 255 } }),}));@@ -55,6 +56,7 @@ function fixture() {ptr: 11,container: 90,fontSize: 12,+ baseline: 690,},],},diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/selectedFontNote.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/selectedFontNote.test.tsindex 5dee23ca08..a4c9a2ea92 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/selectedFontNote.test.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/selectedFontNote.test.ts@@ -2,8 +2,29 @@ import { readFileSync } from "node:fs";import path from "node:path";import { beforeAll, describe, expect, it, vi } from "vitest";-const { get } = vi.hoisted(() => ({ get: vi.fn() }));+const { get, originals } = vi.hoisted(() => ({+ get: vi.fn(),+ originals: new Map<string, string>(),+}));vi.mock("@editor/services/apiClient", () => ({ default: { get } }));+vi.mock(+ "@editor/tools/pdfTextEditor/util/documentFontCompletion",+ async (importOriginal) => {+ const real =+ await importOriginal<+ typeof import("@editor/tools/pdfTextEditor/util/documentFontCompletion")+ >();+ return {+ ...real,+ fontCompletionFor: (fontId: string) => {+ const family = originals.get(fontId);+ return family+ ? { family, source: "original" as const }+ : real.fontCompletionFor(fontId);+ },+ };+ },+);import { selectedFontNote } from "@editor/tools/pdfTextEditor/util/selectedFontNote";import {@@ -12,6 +33,10 @@ import {forgetServerFontList,} from "@editor/tools/pdfTextEditor/util/serverFonts";import { resetDeviceFontEmbedCache } from "@editor/tools/pdfTextEditor/util/deviceFontEmbed";+import {+ resetFontCompletions,+ setClosestFont,+} from "@editor/tools/pdfTextEditor/util/documentFontCompletion";import type { PageSnapshot } from "@editor/tools/pdfTextEditor/types";const SERIF_BOLD = "1".repeat(64);@@ -143,6 +168,40 @@ describe("selectedFontNote", () => {).toEqual({ kind: "embeddedUnknown" });});+ it("names the font that completes an embedded one, and how sure it is", () => {+ const pages = page([run("a", "pdf:41:Acme Sans", "Hi")]);++ setClosestFont("pdf:41:Acme Sans", "Times-Roman");++ expect(selectedFontNote(pages, ["a"])).toEqual({+ kind: "completed",+ name: "Times-Roman",+ source: "closest",+ });+ resetFontCompletions();+ expect(selectedFontNote(pages, ["a"])).toEqual({ kind: "embeddedUnknown" });+ });++ it("claims the same font only when every selected font is completed by it", () => {+ const pages = page([+ { ...run("a", "pdf:42:Acme Sans", "Hi"), fontSubset: true },+ { ...run("b", "pdf:43:Acme Sans Bold", "Hi"), fontSubset: true },+ ]);+ originals.set("pdf:42:Acme Sans", "Times-Roman");+ setClosestFont("pdf:43:Acme Sans Bold", "Times-Roman");++ try {+ expect(selectedFontNote(pages, ["a", "b"])).toEqual({+ kind: "completed",+ name: "Times-Roman",+ source: "closest",+ });+ } finally {+ originals.clear();+ resetFontCompletions();+ }+ });+it("judges a document font by its own coverage, not a device face of the same name", () => {const pages = page([run("a", "device:DejaVu Serif Bold", "Hi"),diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/serverFonts.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/serverFonts.test.tsindex 2ef2e37f2d..426c0716c7 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/serverFonts.test.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/serverFonts.test.ts@@ -26,10 +26,8 @@ import {resetLocalFontsCache,} from "@editor/tools/pdfTextEditor/util/localFonts";import { deviceFontIdFor } from "@editor/tools/pdfTextEditor/util/deviceFontEmbed";-import {- italicCapability,- resetDocumentFontMatchCache,-} from "@editor/tools/pdfTextEditor/util/fontCapability";+import { italicCapability } from "@editor/tools/pdfTextEditor/util/fontCapability";+import { resetFontCompletions } from "@editor/tools/pdfTextEditor/util/documentFontCompletion";const requestsAtImport = get.mock.calls.length;@@ -94,7 +92,7 @@ describe("server fonts", () => {get.mockReset();forgetServerFontList();resetLocalFontsCache();- resetDocumentFontMatchCache();+ resetFontCompletions();delete (window as unknown as { queryLocalFonts?: unknown }).queryLocalFonts;});diff --git a/frontend/src/editor/core/tools/pdfTextEditor/charcode/FontHelpers.ts b/frontend/src/editor/core/tools/pdfTextEditor/charcode/FontHelpers.tsindex 2652fe31db..41d9b9de36 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/charcode/FontHelpers.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/charcode/FontHelpers.ts@@ -235,7 +235,7 @@ export function _clearFontNameCacheForTests(): void {// Read a font's /BaseFont name, the identity used to tell WHICH face a handle// points at when two fonts on the page render the same char.-function readFontName(+export function readFontName(m: ResolverContext["module"],fontPtr: number,): string | undefined {diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/Command.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/Command.tsindex 0e53ea9bdd..070a46702b 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/commands/Command.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/Command.ts@@ -15,6 +15,7 @@ export interface Command {// Optional - when true, a matching `coalesceKey` merges this command into the// previous undo step however long ago that step ran.coalesceIgnoresTimeWindow?(previous: Command | null): boolean;+ supersedes?(adjacent: Command): boolean;}export class RolledBackError extends Error {diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/CompositeCommand.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/CompositeCommand.tsindex 0091474dbf..2e8516a660 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/commands/CompositeCommand.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/CompositeCommand.ts@@ -39,20 +39,22 @@ export class CompositeCommand implements Command {phase: "apply" | "revert",): void {const done: Command[] = [];- for (const cmd of order) {- try {- if (phase === "apply") cmd.apply(doc);- else cmd.revert(doc);- } catch (err) {- for (let i = done.length - 1; i >= 0; i--) {- try {- if (phase === "apply") done[i].revert(doc);- else done[i].apply(doc);- } catch {- throw err;+ for (const [i, cmd] of order.entries()) {+ if (!order[i + 1]?.supersedes?.(cmd)) {+ try {+ if (phase === "apply") cmd.apply(doc);+ else cmd.revert(doc);+ } catch (err) {+ for (let j = done.length - 1; j >= 0; j--) {+ try {+ if (phase === "apply") done[j].revert(doc);+ else done[j].apply(doc);+ } catch {+ throw err;+ }}+ throw new RolledBackError(err);}- throw new RolledBackError(err);}done.push(cmd);}diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/DeleteObjectCommand.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/DeleteObjectCommand.tsindex d4f25ba0ac..6b5641625e 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/commands/DeleteObjectCommand.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/DeleteObjectCommand.ts@@ -44,9 +44,10 @@ export class DeleteObjectCommand implements Command {const scan = scanEditOf(doc, run);if (scan) {// The words are pixels in the scan; only covering them removes them.- this.scanText ??= run.text;+ const text = run.text;+ if (!renderScanEdit(doc, page, run, scan, "")) return;+ this.scanText ??= text;this.removedRun = run;- renderScanEdit(doc, page, run, scan, "");page.setRuns(page.runs.filter((r) => r.id !== run.id));return;}diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/DuplicateRunCommand.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/DuplicateRunCommand.tsindex 314da2d788..05b1c0b6a4 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/commands/DuplicateRunCommand.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/DuplicateRunCommand.ts@@ -42,8 +42,7 @@ export class DuplicateRunCommand implements Command {Math.max(4, src.fontSize),);if (!newPtr) return;- // Base-14 (WinAnsi) can't render >U+00FF; sanitize so non-Latin code- // points are dropped rather than persisted as U+00FF ydieresis tofu.+ // Base-14 renders only WinAnsi: drop other code points rather than persist them as U+00FF tofu.const textPtr = writeUtf16(m,sanitizeForBase14(src.text.replace(/\r?\n/g, " ")),diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/EditTextCommand.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/EditTextCommand.tsindex 5e1cea2f20..1b44f4de91 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/commands/EditTextCommand.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/EditTextCommand.ts@@ -1,5 +1,6 @@import i18n from "i18next";import type { Command } from "@editor/tools/pdfTextEditor/commands/Command";+import { RENDER_MODE_INVISIBLE } from "@editor/tools/pdfTextEditor/types";import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";import { PdfiumTextWriter } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTextWriter";import {@@ -116,7 +117,6 @@ function planIsPureInsert(plan: PartialEditPlan): boolean {);}-const RENDER_MODE_INVISIBLE = 3;const BLACK = { r: 0, g: 0, b: 0, a: 255 };// Cap height as a share of the em, near enough for the fallback faces.const CAP_HEIGHT_EM = 0.72;@@ -158,6 +158,7 @@ export class EditTextCommand implements Command {private createdPtrs: number[] = [];/** Set when apply went through the word-level scanned-OCR path. */private scanEdited = false;+ private scanRefused = false;private newTextPtr = 0;private revertLines: RevertLine[] = [];/** Rotation of the run when apply() snapshotted it; re-applied on revert. */@@ -208,10 +209,16 @@ export class EditTextCommand implements Command {if (this.prevText === this.nextText) return;if (this.scanEdited || isScanRun(run)) {- run.scanEdit ??= captureScanEdit(doc.module, run);+ run.scanEdit ??= captureScanEdit(doc.module, run, page);if (run.scanEdit) {this.scanEdited = true;- renderScanEdit(doc, page, run, run.scanEdit, this.nextText);+ this.scanRefused = !renderScanEdit(+ doc,+ page,+ run,+ run.scanEdit,+ this.nextText,+ );return;}}@@ -1384,6 +1391,17 @@ export class EditTextCommand implements Command {return `edit-text:${this.pageIndex}:${this.runId}`;}+ supersedes(adjacent: Command): boolean {+ return (+ adjacent instanceof EditTextCommand &&+ this.scanEdited &&+ !this.scanRefused &&+ adjacent.scanEdited &&+ adjacent.pageIndex === this.pageIndex &&+ adjacent.runId === this.runId+ );+ }+/** The text this edit produced - lets the history compare adjacent edits. */get resultText(): string {return this.nextText;diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/InsertTextCommand.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/InsertTextCommand.tsindex fdcf809b67..1e5c93604d 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/commands/InsertTextCommand.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/InsertTextCommand.ts@@ -47,7 +47,7 @@ export class InsertTextCommand implements Command {const page = doc.page(this.pageIndex);const m = doc.module;- // Base-14 (WinAnsi) can't render >U+00FF.+ // Base-14 can only render WinAnsi.const sanitized = sanitizeForBase14(this.text);let objPtr = 0;if ([...this.text].length > [...sanitized].length) {diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/ReflowWrapCommand.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/ReflowWrapCommand.tsindex c6865198eb..332f474fa0 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/commands/ReflowWrapCommand.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/ReflowWrapCommand.ts@@ -10,6 +10,7 @@ import type { WrappedPdfiumModule } from "@embedpdf/pdfium";import { readUtf16 } from "@editor/services/pdfiumService";import { rotationFromMatrix } from "@editor/tools/pdfTextEditor/commands/editTextHelpers";import { transformObject } from "@editor/tools/pdfTextEditor/util/objectTransform";+import { isScanRun } from "@editor/tools/pdfTextEditor/commands/scanTextEdit";import {SCRATCH,scratchPtr,@@ -93,7 +94,7 @@ export class ReflowWrapCommand implements Command {apply(doc: EditorDocument): void {const page = doc.page(this.pageIndex);const run = page.findRun(this.runId);- if (!run) return;+ if (!run || isScanRun(run)) return;if (this.maxWidthPt <= 0) return;// Reflow math is axis-aligned (advance +x, step -y); a rotated run reads// along a rotated axis, so skip rather than scatter glyphs.diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/SetScanStyleCommand.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/SetScanStyleCommand.tsnew file mode 100644index 0000000000..813c70194d--- /dev/null+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/SetScanStyleCommand.ts@@ -0,0 +1,63 @@+import i18n from "i18next";+import type { Command } from "@editor/tools/pdfTextEditor/commands/Command";+import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";+import {+ renderScanEdit,+ scanEditOf,+ setScanOverride,+ type ScanOverride,+} from "@editor/tools/pdfTextEditor/commands/scanTextEdit";+import {+ preferredScanFace,+ setPreferredScanFace,+ type RankedStyle,+} from "@editor/tools/pdfTextEditor/commands/scanFit";++export class SetScanStyleCommand implements Command {+ readonly type = "set-scan-style";+ private readonly pageIndex: number;+ private readonly runId: string;+ private readonly choice: RankedStyle;+ private prev: ScanOverride | null = null;+ private prevPreferred: string | null = null;++ constructor(opts: { pageIndex: number; runId: string; choice: RankedStyle }) {+ this.pageIndex = opts.pageIndex;+ this.runId = opts.runId;+ this.choice = opts.choice;+ }++ apply(doc: EditorDocument): void {+ const page = doc.page(this.pageIndex);+ const run = page.findRun(this.runId);+ const state = run ? scanEditOf(doc, run) : null;+ if (!run || !state) return;+ const prev = state.override;+ state.override = { ...prev, family: undefined, style: this.choice.style };+ if (!renderScanEdit(doc, page, run, state, run.text)) {+ state.override = prev;+ return;+ }+ this.prev = prev;+ this.prevPreferred = preferredScanFace(doc);+ setPreferredScanFace(doc, this.choice.face.label);+ }++ revert(doc: EditorDocument): void {+ const prev = this.prev;+ if (!prev) return;+ const page = doc.page(this.pageIndex);+ const run = page.findRun(this.runId);+ setPreferredScanFace(doc, this.prevPreferred);+ if (run) setScanOverride(doc, page, run, () => prev);+ this.prev = null;+ }++ describe(): string {+ return i18n.t(+ "pdfTextEditor.commands.matchScanFont",+ "Match scanned text to {{face}}",+ { face: this.choice.face.label },+ );+ }+}diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/editTextHelpers.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/editTextHelpers.tsindex fa6c5c17ce..94ecc4e2f7 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/commands/editTextHelpers.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/editTextHelpers.ts@@ -19,6 +19,12 @@ import {import { getActiveCharcodeStrategy } from "@editor/tools/pdfTextEditor/charcode/CharcodeStrategy";import { emitFallbackTextObject } from "@editor/tools/pdfTextEditor/util/fallbackFont";import { emitDeviceFontTextObject } from "@editor/tools/pdfTextEditor/util/deviceFontEmbed";+import { getExternalFontBytes } from "@editor/tools/pdfTextEditor/util/externalFonts";+import {+ advanceWidth,+ parseFontMetrics,+ type FontMetrics,+} from "@editor/tools/pdfTextEditor/util/fontMetrics";import { applyTagMarks } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTagMarks";import {taggedSpans,@@ -26,7 +32,10 @@ import {type TaggedSpan,type TextTags,} from "@editor/tools/pdfTextEditor/model/TextTags";-import { nearestStandardFont } from "@editor/tools/pdfTextEditor/util/fontFamily";+import {+ encodesInBase14,+ nearestStandardFont,+} from "@editor/tools/pdfTextEditor/util/fontFamily";import {SCRATCH,scratchPtr,@@ -94,6 +103,10 @@ export function _clearDroppedBase14CharsForTests(): void {resetDroppedBase14Chars();}+export function recordUndrawableChars(chars: string): void {+ recordDroppedChars(chars, "");+}+/** Record every VISIBLE char present in `original` but missing from `kept`. */function recordDroppedChars(original: string, kept: string): void {const keptSet = new Set(kept);@@ -168,12 +181,9 @@ export function sanitizeForBase14(text: string): string {const cp = ch.codePointAt(0) ?? 0;if (cp === 0x09 || cp === 0x0a || cp === 0x0d) {out += ch;- } else if (cp < 0x20 || cp === 0x7f || (cp >= 0x80 && cp <= 0x9f)) {- // C0/DEL/C1 controls are un-encodable in WinAnsi - drop them.- continue;} else if (cp === 0x00a0) {out += " ";- } else if (cp <= 0xff) {+ } else if (encodesInBase14(cp)) {out += ch;}// else: unrepresentable in base-14 - drop it (no tofu).@@ -317,14 +327,37 @@ export function cssFontSpecFor(fontFamily: string, sizePx: number): string {return `${italic}${bold}${sizePx}px ${stack}`;}+function embeddedMetricsFor(family: string): FontMetrics | null {+ const bytes = getExternalFontBytes(family);+ return bytes ? parseFontMetrics(bytes) : null;+}++const BASE14_SPACE: Array<[RegExp, number]> = [+ [/^times/i, 250],+ [/^courier/i, 600],+ [/^helvetica/i, 278],+];++export function base14SpaceAdvance(family: string): number | null {+ return BASE14_SPACE.find(([re]) => re.test(family))?.[1] ?? null;+}+/** Measure the natural advance width of `s` in PDF points. */function measureAdvancePt(text: string,fontFamily: string,fontSizePt: number,): number {+ const metrics = embeddedMetricsFor(fontFamily);+ const embedded = metrics ? advanceWidth(metrics, text) : null;+ if (embedded !== null) return (embedded * fontSizePt) / 1000;const ctx = measureCtx();- if (!ctx) return text.length * fontSizePt * 0.5;+ if (!ctx) {+ const space = base14SpaceAdvance(fontFamily) ?? 500;+ let sum = 0;+ for (const ch of text) sum += /\s/.test(ch) ? space : 500;+ return (sum * fontSizePt) / 1000;+ }ctx.font = cssFontSpecFor(fontFamily, fontSizePt);return ctx.measureText(text).width;}@@ -698,7 +731,7 @@ export function emitTextLine(opts: CreatedTextOptions): number[] {// Emit ONE word at (x, y) and return its pointer (0 on failure).const emitWord = (text: string, x: number): number => {- // base-14 can only render Latin-1; drop the rest so PDFium never emits+ // base-14 can only render WinAnsi; drop the rest so PDFium never emits// U+00FF tofu.const base14Text = sanitizeForBase14(text);const newBase14 = (): number => {@@ -727,7 +760,7 @@ export function emitTextLine(opts: CreatedTextOptions): number[] {);if (dp) return dp;}- // Some chars are outside base-14's Latin-1 range.+ // Some chars are outside base-14's WinAnsi range.if ([...text].length > [...base14Text].length) {const fp = emitFallbackTextObject(opts.doc,@@ -1245,9 +1278,19 @@ export function measureObjSpanPt(m: WrappedPdfiumModule,ptrs: number[],): { left: number; right: number } | null {+ const box = measureObjBoundsPt(m, ptrs);+ return box && { left: box.left, right: box.right };+}++export function measureObjBoundsPt(+ m: WrappedPdfiumModule,+ ptrs: number[],+): { left: number; bottom: number; right: number; top: number } | null {const buf = scratchPtr(m, SCRATCH.editBoxB, 16);let left = Infinity;+ let bottom = Infinity;let right = -Infinity;+ let top = -Infinity;for (const ptr of ptrs) {if (!ptr) continue;try {@@ -1260,10 +1303,12 @@ export function measureObjSpanPt(const lo = m.pdfium.getValue(buf, "float");const hi = m.pdfium.getValue(buf + 8, "float");if (!Number.isFinite(lo) || !Number.isFinite(hi)) continue;- if (lo < left) left = lo;- if (hi > right) right = hi;+ left = Math.min(left, lo);+ right = Math.max(right, hi);+ bottom = Math.min(bottom, m.pdfium.getValue(buf + 4, "float"));+ top = Math.max(top, m.pdfium.getValue(buf + 12, "float"));}- return right > left ? { left, right } : null;+ return right > left ? { left, bottom, right, top } : null;}function setTextOn(m: WrappedPdfiumModule, ptr: number, text: string): void {diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/scanFit.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/scanFit.tsnew file mode 100644index 0000000000..7588c8ef8d--- /dev/null+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/scanFit.ts@@ -0,0 +1,553 @@+import { median } from "@editor/tools/pdfTextEditor/util/median";+import { luma } from "@editor/tools/pdfTextEditor/model/Color";+import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";+import type { Page } from "@editor/tools/pdfTextEditor/model/Page";+import type { PageRect, RGBA } from "@editor/tools/pdfTextEditor/types";+import {+ INK_SCALE,+ renderLuma,+ type ScanInk,+} from "@editor/tools/pdfTextEditor/pdfium/BackgroundSampler";+import {+ clampStretch,+ fitScale,+ isEvenlySpaced,+ matchScan,+ rememberForFit,+ softnessOf,+ spanOf,+ textAdvance,+ topShare,+ withScanCache,+ type ScanMatch,+} from "@editor/tools/pdfTextEditor/commands/scanStyle";+import {+ candidateFaces,+ type Face,+} from "@editor/tools/pdfTextEditor/util/scanFontLibrary";++// How scanned text is redrawn: one face, size and colour for a whole block.+export interface ScanStyle {+ family: string;+ fontSize: number;+ /** Horizontal scale that gives the face the scan's letter widths. */+ stretch: number;+ ink: RGBA;+ /** Outline that thickens the strokes to the scan's weight, in points. */+ weight: number;+ hollow: number;+ /** Blur, in render pixels, that softens drawn text to the scan's focus. */+ softness: number;+}++export interface RankedStyle {+ face: Face;+ style: ScanStyle;+ score: number;+}++export interface SpanInk {+ ink: ScanInk;+ /** Paper colour right around the span. */+ paper: RGBA;+ baseline: number;+ /** The OCR text of the span, minus any box edge it read as a bracket. */+ original: string;+ dropLead: boolean;+ dropTrail: boolean;+}++export interface FitWord {+ text: string;+ width: number;+}++export interface FitInput {+ spans: SpanInk[];+ ref: SpanInk;+ words: FitWord[];+ wordsLookMono: () => boolean;+ neighboursLookMono: () => boolean;+}++const SIZE_STEPS = [0.88, 0.91, 0.94, 0.97, 1, 1.03];+const BY_WIDTH = 3;+const BY_RENDER = 2;+const CROWDED = 12;+const BY_WIDTH_CROWDED = 5;+const BY_RENDER_CROWDED = 3;+const WIDTH_SLACK = 0.25;+export const CLOSE_CALL = 0.1;+const OFFERED = 3;+const HOLLOW_STROKES = [0.025, 0.05];+const HOLLOW_HEAVIER = 2;+const HOLLOW_FIT = Math.log(1.5);++/** How far the glyphs of a span rise above its baseline. */+export const inkTop = (s: SpanInk) =>+ s.ink.body.y + s.ink.body.height - s.baseline;++// Mostly-lowercase text is sized by its x-height, as readers judge it; the scan's rows decide, since OCR's case is unreliable.+export function sizeFor(face: Face, s: SpanInk): number {+ if (s.ink.xLine !== null && /[\p{Lu}\p{Ll}]/u.test(s.original))+ return (s.ink.xLine - s.baseline) / (face.xh / 1000);+ return inkTop(s) / topShare(face, s.original);+}++const preferredFaces = new WeakMap<EditorDocument, string>();+const preferenceListeners = new Set<() => void>();++export function subscribePreferredScanFace(listener: () => void): () => void {+ preferenceListeners.add(listener);+ return () => preferenceListeners.delete(listener);+}++export function preferredScanFace(doc: EditorDocument): string | null {+ return preferredFaces.get(doc) ?? null;+}++export function setPreferredScanFace(+ doc: EditorDocument,+ label: string | null,+): void {+ if (label) preferredFaces.set(doc, label);+ else preferredFaces.delete(doc);+ for (const listener of [...preferenceListeners]) listener();+}++export function preferredStyle(+ doc: EditorDocument,+ ranked: RankedStyle[],+): ScanStyle | null {+ const pick = ranked.find((r) => r.face.label === preferredScanFace(doc));+ if (!pick) return null;+ return pick.score >= ranked[0].score - CLOSE_CALL ? pick.style : null;+}++interface Candidate {+ face: Face;+ family: string;+ size: number;+ stretch: number;+ k: number;+ softness: number;+ score: number;+ strokeRatio: number;+}++type Cut = Pick<Candidate, "family" | "size" | "stretch">;++const familiesOf = (face: Face) => [...new Set([face.family, face.bold])];++const best = <T extends { score: number }>(cs: T[]) =>+ cs.reduce((p, q) => (q.score > p.score ? q : p));++function nearestOne<T>(items: T[], ratio: (item: T) => number): T {+ return items.reduce((p, q) =>+ Math.abs(Math.log(ratio(q))) < Math.abs(Math.log(ratio(p))) ? q : p,+ );+}++function compare(+ doc: EditorDocument,+ page: Page,+ ref: SpanInk,+ cut: Cut & { weight?: number; hollow?: number },+ softness?: number,+ rough = false,+): ScanMatch {+ return matchScan(+ doc,+ page,+ ref.ink,+ { text: ref.original, x: ref.ink.body.x, baseline: ref.baseline, ...cut },+ softness,+ rough,+ );+}++// Render pixels per scanned pixel: an upscaled low-res scan is soft however sharp its steps look, so this floors the softness.+function scanPixelSpan(+ doc: EditorDocument,+ page: Page,+ rect: PageRect,+): number {+ const m = doc.module;+ const cx = rect.x + rect.width / 2;+ const cy = rect.y + rect.height / 2;+ const under = page.images+ .filter(+ (img) =>+ cx >= img.bounds.x &&+ cx <= img.bounds.x + img.bounds.width &&+ cy >= img.bounds.y &&+ cy <= img.bounds.y + img.bounds.height,+ )+ .sort(+ (p, q) =>+ q.bounds.width * q.bounds.height - p.bounds.width * p.bounds.height,+ )[0];+ if (!under) return 0;+ const wPtr = m.pdfium.wasmExports.malloc(4);+ const hPtr = m.pdfium.wasmExports.malloc(4);+ try {+ if (!m.FPDFImageObj_GetImagePixelSize(under.pdfiumObjPtr, wPtr, hPtr))+ return 0;+ const pixels = m.pdfium.getValue(wPtr, "i32");+ return pixels > 0 ? (INK_SCALE * under.bounds.width) / pixels : 0;+ } catch {+ return 0;+ } finally {+ m.pdfium.wasmExports.free(wPtr);+ m.pdfium.wasmExports.free(hPtr);+ }+}++function halfDensityXHeight(+ doc: EditorDocument,+ page: Page,+ s: SpanInk,+): number | null {+ if (s.ink.xLine === null) return null;+ const rect = s.ink.rect;+ const img = renderLuma(doc.module, page, rect, 0, fitScale(s.ink));+ if (!img) return null;+ const { data, width, height } = img;+ const paper = luma(s.paper.r, s.paper.g, s.paper.b);+ let darkest = paper;+ for (let i = 0; i < data.length; i++)+ if (data[i] < darkest) darkest = data[i];+ const depth = Math.max(30, paper - darkest);+ const rows = Array.from({ length: height }, (_, y) => {+ let sum = 0;+ for (let x = 0; x < width; x++)+ sum += Math.max(0, paper - data[y * width + x]);+ return sum / (width * depth);+ });+ const rowOf = (pageY: number) =>+ ((rect.y + rect.height - pageY) / rect.height) * height;+ const xRow = rowOf(s.ink.xLine);+ const baseRow = rowOf(s.baseline);+ const from = Math.round(xRow + (baseRow - xRow) * 0.25);+ const to = Math.round(baseRow - (baseRow - xRow) * 0.25);+ if (to <= from || from < 0 || to >= height) return null;+ const plateau = median(rows.slice(from, to + 1));+ if (plateau <= 0) return null;+ const half = plateau / 2;+ const crossing = (start: number, step: number) => {+ for (let y = start; y >= 0 && y < height; y += step) {+ const next = y + step;+ if (next < 0 || next >= height) return null;+ if (rows[next] < half) {+ const t = (rows[y] - half) / Math.max(1e-6, rows[y] - rows[next]);+ return y + t * step;+ }+ }+ return null;+ };+ const centre = Math.round((from + to) / 2);+ const up = crossing(centre, -1);+ const down = crossing(centre, 1);+ if (up === null || down === null) return null;+ return ((down - up) / height) * rect.height;+}++function widthMisfit(+ doc: EditorDocument,+ page: Page,+ face: Face,+ family: string,+ ref: SpanInk,+ words: FitWord[],+ xHeight: number | null,+): number {+ const size = xHeight ? xHeight / (face.xh / 1000) : sizeFor(face, ref);+ const line = textAdvance(doc, page, face, family, ref.original);+ if (!line || size <= 2) return Infinity;+ const span = Math.min(+ ...SIZE_STEPS.slice(0, 5).map((k) =>+ Math.abs(Math.log(ref.ink.body.width / ((line * size * k) / 1000))),+ ),+ );+ const ratios = words+ .map((w) => {+ const adv = textAdvance(doc, page, face, family, w.text);+ return adv ? w.width / adv : 0;+ })+ .filter((r) => r > 0);+ if (ratios.length < 4) return span;+ const k = median(ratios);+ return span + 2 * median(ratios.map((r) => Math.abs(r / k - 1)));+}++function shortlist(+ doc: EditorDocument,+ page: Page,+ input: FitInput,+ faces: Face[],+ quickScore: (face: Face) => number,+): Face[] {+ const crowded = faces.length > CROWDED;+ const byWidth = crowded ? BY_WIDTH_CROWDED : BY_WIDTH;+ const byRender = crowded ? BY_RENDER_CROWDED : BY_RENDER;+ if (faces.length <= byWidth + byRender) return faces;+ const words = input.words+ .map((w) => ({ text: w.text.trim(), width: w.width }))+ .filter((w) => w.text.length >= 2 && w.width > 0)+ .slice(0, 24);+ const xHeight = rememberForFit(input.ref.ink, "xHeight", () =>+ halfDensityXHeight(doc, page, input.ref),+ );+ const scored = faces+ .map((face) => ({+ face,+ misfit: Math.min(+ ...familiesOf(face).map((family) =>+ widthMisfit(doc, page, face, family, input.ref, words, xHeight),+ ),+ ),+ }))+ .filter((f) => Number.isFinite(f.misfit))+ .sort((p, q) => p.misfit - q.misfit);+ const plausible = scored.filter(+ (f) => f.misfit <= scored[0].misfit + WIDTH_SLACK,+ );+ const kept = plausible.slice(0, byWidth).map((f) => f.face);+ kept.push(+ ...plausible+ .slice(byWidth)+ .map((f) => ({ face: f.face, score: quickScore(f.face) }))+ .sort((p, q) => q.score - p.score)+ .slice(0, byRender)+ .map((f) => f.face),+ );+ const pick = faces.find((f) => f.label === preferredScanFace(doc));+ if (pick && !kept.includes(pick)) kept.push(pick);+ return kept;+}++export function rankStyles(+ doc: EditorDocument,+ page: Page,+ input: FitInput,+): RankedStyle[] {+ return withScanCache(input.ref.ink, () => rankUncached(doc, page, input));+}++function fitCut(+ doc: EditorDocument,+ page: Page,+ ref: SpanInk,+ face: Face,+ family: string,+ k: number,+) {+ const size = sizeFor(face, ref) * k;+ const natural =+ rememberForFit(ref.ink, `span|${family}|${size}`, () =>+ spanOf(doc, page, ref.original, family, size),+ ) ?? 0;+ const stretch = clampStretch(ref.ink.body.width / Math.max(1e-3, natural));+ return { face, family, size, stretch, k };+}++const toRanked = (+ doc: EditorDocument,+ page: Page,+ input: FitInput,+ c: Candidate,+): RankedStyle => ({+ face: c.face,+ score: c.score,+ style: finishStyle(doc, page, input.spans, input.ref, c),+});++export function withPreferredFace(+ doc: EditorDocument,+ page: Page,+ input: FitInput,+ ranked: RankedStyle[],+): RankedStyle[] {+ const label = preferredScanFace(doc);+ const pick = candidateFaces(input.ref.original).find(+ (f) => f.label === label,+ );+ if (!pick || ranked.some((r) => r.face === pick)) return ranked;+ const choice = withScanCache(input.ref.ink, () => {+ const [scored] = measureFaces(doc, page, input.ref, [pick]);+ return scored ? toRanked(doc, page, input, scored) : null;+ });+ if (!choice) return ranked;+ const at = ranked.findIndex((r) => r.score < choice.score);+ const merged = [...ranked];+ merged.splice(at === -1 ? merged.length : at, 0, choice);+ const offered = merged.slice(0, OFFERED);+ const close = choice.score >= ranked[0].score - CLOSE_CALL;+ if (close && !offered.includes(choice)) offered[OFFERED - 1] = choice;+ return offered;+}++function rankUncached(+ doc: EditorDocument,+ page: Page,+ input: FitInput,+): RankedStyle[] {+ const { ref } = input;+ // Typewriter evidence outlasts pixels on a blurry low-res scan, so it wins close calls.+ const typewriter =+ input.wordsLookMono() || isEvenlySpaced(ref.ink.glyphCenters, ref.original);+ const all = candidateFaces(ref.original);+ if (all.length === 0) return [];+ const quickScore = (face: Face) =>+ Math.max(+ ...familiesOf(face).map(+ (family) =>+ compare(+ doc,+ page,+ ref,+ fitCut(doc, page, ref, face, family, 0.94),+ undefined,+ true,+ ).score,+ ),+ );+ const faces = shortlist(doc, page, input, all, quickScore);+ if (typewriter)+ for (const f of all)+ if (f.kind === "mono" && !faces.includes(f)) faces.push(f);+ const perFace = measureFaces(doc, page, ref, faces);+ if (perFace.length === 0) return [];+ const nudge = (pick: Candidate | undefined) => {+ if (!pick || pick === perFace[0]) return;+ if (pick.score < perFace[0].score - CLOSE_CALL) return;+ perFace.splice(perFace.indexOf(pick), 1);+ perFace.unshift(pick);+ };+ if (typewriter || input.neighboursLookMono())+ nudge(perFace.find((c) => c.face.kind === "mono"));+ return perFace.slice(0, OFFERED).map((c) => toRanked(doc, page, input, c));+}++function measureFaces(+ doc: EditorDocument,+ page: Page,+ ref: SpanInk,+ faces: Face[],+): Candidate[] {+ // Fit size for both weights first: blur and overshoot can inflate glyph height enough to favour the wrong face.+ const sizes = faces+ .flatMap((face) =>+ familiesOf(face).flatMap((family) =>+ SIZE_STEPS.map((k) => fitCut(doc, page, ref, face, family, k)),+ ),+ )+ .filter((c) => c.size > 2)+ .map((c) => ({+ ...c,+ score: compare(doc, page, ref, c, undefined, true).score,+ }));+ if (sizes.length === 0) return [];+ // A scan pixel `span` render pixels wide blurs like a box of radius (span - 1) / 2, so one render pixel or less is crisp.+ const floor = Math.round(+ Math.max(0, scanPixelSpan(doc, page, ref.ink.rect) - 1) / 2,+ );+ // Compare at the scan's softness without blurring the scan again: a second blur makes regular strokes look bold.+ const candidates: Candidate[] = faces+ .flatMap((face) =>+ familiesOf(face).map((family) =>+ sizes.filter((c) => c.face === face && c.family === family),+ ),+ )+ .filter((cs) => cs.length > 0)+ .map((cs) => {+ const c = best(cs);+ const measured = softnessOf(doc, page, ref.ink, {+ text: ref.original,+ x: ref.ink.body.x,+ baseline: ref.baseline,+ family: c.family,+ size: c.size,+ stretch: c.stretch,+ });+ const softness = Math.min(2, Math.max(measured, floor));+ const match = compare(doc, page, ref, c, softness);+ return {+ ...c,+ softness,+ score: match.score,+ strokeRatio: match.weight,+ };+ });+ // Regular and bold blur to near-identical outlines, so close matches are settled on stroke thickness, not extra ink.+ return faces+ .map((face) => {+ const cuts = candidates.filter((c) => c.face === face);+ if (cuts.length === 0) return null;+ const top = best(cuts);+ const weighted = nearestOne(+ cuts.filter((c) => c.score >= top.score - CLOSE_CALL),+ (c) => c.strokeRatio,+ );+ return { ...weighted, score: top.score };+ })+ .filter((c): c is Candidate => c !== null)+ .sort((p, q) => q.score - p.score);+}++function finishStyle(+ doc: EditorDocument,+ page: Page,+ spans: SpanInk[],+ ref: SpanInk,+ chosen: Candidate,+): ScanStyle {+ const { softness } = chosen;+ // Past bold only (on regular text blur alone reads as weight), outline the strokes until, softened alike, they match the scan's.+ const isBoldCut =+ chosen.family === chosen.face.bold &&+ chosen.face.bold !== chosen.face.family;+ const weight = nearestOne(+ (isBoldCut ? [0, 0.025, 0.05] : [0]).map((k) => {+ const w = k * chosen.size;+ return {+ w,+ ratio: compare(doc, page, ref, { ...chosen, weight: w }, softness, true)+ .weight,+ };+ }),+ (o) => o.ratio,+ ).w;+ const hollow = hollowStroke(doc, page, ref, chosen, weight);+ // One size for every line; the median shrugs off a line of lowercase.+ const blockSizes = spans+ .map((s) => sizeFor(chosen.face, s))+ .filter((v) => v > 2);+ return {+ family: chosen.family,+ fontSize: blockSizes.length ? median(blockSizes) * chosen.k : chosen.size,+ stretch: chosen.stretch,+ // Softened text is blurred again, so it starts from the scan's darkest ink.+ ink: softness > 0 ? ref.ink.core : ref.ink.fill,+ weight: hollow > 0 ? 0 : weight,+ hollow,+ softness,+ };+}++function hollowStroke(+ doc: EditorDocument,+ page: Page,+ ref: SpanInk,+ chosen: Candidate,+ weight: number,+): number {+ const strokeRatio = (extra: { weight?: number; hollow?: number }) =>+ compare(doc, page, ref, { ...chosen, ...extra }, chosen.softness, true)+ .weight;+ if (strokeRatio({ weight }) < HOLLOW_HEAVIER) return 0;+ const fitted = HOLLOW_STROKES.map((k) => k * chosen.size)+ .map((w) => ({ w, misfit: Math.abs(Math.log(strokeRatio({ hollow: w }))) }))+ .reduce((p, q) => (q.misfit < p.misfit ? q : p));+ return fitted.misfit < HOLLOW_FIT ? fitted.w : 0;+}diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/scanFitSlices.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/scanFitSlices.tsnew file mode 100644index 0000000000..badc635bee--- /dev/null+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/scanFitSlices.ts@@ -0,0 +1,84 @@+import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";+import type { Page } from "@editor/tools/pdfTextEditor/model/Page";+import type { TextRun } from "@editor/tools/pdfTextEditor/model/TextRun";+import {+ prefitScanRun,+ scanRunNeedsFit,+} from "@editor/tools/pdfTextEditor/commands/scanTextEdit";+import {+ FIT_PAUSED,+ withFitDeadline,+} from "@editor/tools/pdfTextEditor/commands/scanStyle";++export const FIT_SLICE_MS = 12;+export const FIT_GAP_MS = 4;++export interface ScanFitTarget {+ page: Page;+ run: TextRun;+}++export function scanRunsToFit(+ doc: EditorDocument,+ targets: ScanFitTarget[],+): ScanFitTarget[] {+ return targets.filter((t) => scanRunNeedsFit(doc, t.run));+}++const nextSlice = () =>+ new Promise<void>((resolve) => setTimeout(resolve, FIT_GAP_MS));++/** Fits each target between timer slices; returns early once `doc` is disposed, leaving the rest unfitted. */+export async function prefitInSlices(+ doc: EditorDocument,+ targets: ScanFitTarget[],+): Promise<void> {+ for (const { page, run } of targets) {+ try {+ while (true) {+ if (doc.disposed) return;+ if (prefitScanRun(doc, page, run, performance.now() + FIT_SLICE_MS))+ break;+ await nextSlice();+ }+ } catch (err) {+ console.warn("[pdf-editor] scanned text could not be fitted", err);+ continue;+ }+ await nextSlice();+ }+}++export function inSlice<T>(fit: () => T): T | typeof FIT_PAUSED {+ try {+ return withFitDeadline(performance.now() + FIT_SLICE_MS, fit);+ } catch (e) {+ if (e === FIT_PAUSED) return FIT_PAUSED;+ throw e;+ }+}++const visible = () =>+ new Promise<void>((resolve) => {+ const onChange = () => {+ if (document.hidden) return;+ document.removeEventListener("visibilitychange", onChange);+ resolve();+ };+ document.addEventListener("visibilitychange", onChange);+ });++/** Runs `fit` slice by slice as {@link prefitInSlices} does, idle while the tab is hidden; null once `live` turns false. */+export async function fitInSlices<T>(+ fit: () => T,+ live: () => boolean,+): Promise<T | null> {+ for (;;) {+ await nextSlice();+ if (document.hidden) await visible();+ if (!live()) return null;+ const result = inSlice(fit);+ if (result !== FIT_PAUSED) return result;+ await nextSlice();+ }+}diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/scanFrame.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/scanFrame.tsnew file mode 100644index 0000000000..1936c32be5--- /dev/null+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/scanFrame.ts@@ -0,0 +1,79 @@+import type { WrappedPdfiumModule } from "@embedpdf/pdfium";+import type { Page } from "@editor/tools/pdfTextEditor/model/Page";+import type { Affine, PageRect } from "@editor/tools/pdfTextEditor/types";+import { invertAffine } from "@editor/tools/pdfTextEditor/model/affine";+import { transformObject } from "@editor/tools/pdfTextEditor/util/objectTransform";++export interface ScanFrame {+ toUpright: Affine;+ fromUpright: Affine;+}++const SKEW_TOLERANCE = (2 * Math.PI) / 180;++const UPRIGHT_TURNS: Array<Pick<Affine, "a" | "b" | "c" | "d">> = [+ { a: 1, b: 0, c: 0, d: 1 },+ { a: 0, b: -1, c: 1, d: 0 },+ { a: -1, b: 0, c: 0, d: -1 },+ { a: 0, b: 1, c: -1, d: 0 },+];++export function quarterTurns(matrix: Affine): number | null {+ const { a, b, c, d } = matrix;+ if (a * d - b * c <= 0) return null;+ const angle = Math.atan2(b, a);+ const turns = Math.round(angle / (Math.PI / 2));+ if (Math.abs(angle - turns * (Math.PI / 2)) > SKEW_TOLERANCE) return null;+ return ((turns % 4) + 4) % 4;+}++export function applyVector(+ t: Affine,+ dx: number,+ dy: number,+): { dx: number; dy: number } {+ return { dx: t.a * dx + t.c * dy, dy: t.b * dx + t.d * dy };+}++export function scanFrameFor(+ page: Page,+ matrix: Affine,+ bounds: PageRect,+): ScanFrame | null {+ const turns = quarterTurns(matrix);+ if (turns === null || turns === 0) return null;+ const turn = UPRIGHT_TURNS[turns];+ const cx = bounds.x + bounds.width / 2;+ const cy = bounds.y + bounds.height / 2;+ const toUpright: Affine = {+ ...turn,+ e:+ page.display.cropLeft ++ page.display.cropWidth / 2 -+ (turn.a * cx + turn.c * cy),+ f:+ page.display.cropBottom ++ page.display.cropHeight / 2 -+ (turn.b * cx + turn.d * cy),+ };+ return { toUpright, fromUpright: invertAffine(toUpright) };+}++export function moveAllObjects(+ m: WrappedPdfiumModule,+ page: Page,+ t: Affine,+): void {+ const count = m.FPDFPage_CountObjects(page.pagePtr);+ for (let i = 0; i < count; i++)+ transformObject(+ m,+ m.FPDFPage_GetObject(page.pagePtr, i),+ t.a,+ t.b,+ t.c,+ t.d,+ t.e,+ t.f,+ );+}diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/scanGlyphs.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/scanGlyphs.tsnew file mode 100644index 0000000000..e39e204074--- /dev/null+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/scanGlyphs.ts@@ -0,0 +1,276 @@+import { median } from "@editor/tools/pdfTextEditor/util/median";++export interface GlyphImage {+ rgba: Uint8Array;+ width: number;+ height: number;+ inkLeft: number;+ inkRight: number;+}++export interface GlyphAtlas {+ glyphs: Map<string, GlyphImage>;+ scale: number;+ height: number;+ descent: number;+ letterGap: number;+ pitch: number | null;+}++export interface ScannedWord {+ text: string;+ rgba: Uint8Array;+ width: number;+ height: number;+ left: number;+ scale: number;+ spans: Array<{ left: number; right: number }>;+}++function cropColumns(+ word: ScannedWord,+ from: number,+ to: number,+): Pick<GlyphImage, "rgba" | "width" | "height"> {+ const width = to - from;+ const rgba = new Uint8Array(width * word.height * 4);+ for (let y = 0; y < word.height; y++)+ rgba.set(+ word.rgba.subarray(+ (y * word.width + from) * 4,+ (y * word.width + to) * 4,+ ),+ y * width * 4,+ );+ return { rgba, width, height: word.height };+}++interface Sample {+ ch: string;+ word: ScannedWord;+ from: number;+ to: number;+ inkLeft: number;+ inkRight: number;+ top: number;+ bottom: number;+}++const INK_ALPHA = 128;+const HEIGHT_SLACK = 0.2;+const MIN_PITCH_STEPS = 7;+const PITCH_SLACK = 0.15;+const ON_PITCH = 0.85;++const TOP_CLASSES: Array<[RegExp, string]> = [+ [/^[acegmnopqrsuvwxyz]$/, "x"],+ [/^[bdfhijkl]$/, "ascender"],+ [/^[A-Z0-9]$/, "capital"],+];++const BOTTOM_CLASSES: Array<[RegExp, string]> = [+ [/^[gjpqy]$/, "descender"],+ [/^[a-zA-IK-PR-Z0-9]$/, "baseline"],+];++const classIn = (classes: Array<[RegExp, string]>, ch: string) =>+ classes.find(([chars]) => chars.test(ch))?.[1] ?? null;++const topClassOf = (ch: string) => classIn(TOP_CLASSES, ch);++const bottomClassOf = (ch: string) => classIn(BOTTOM_CLASSES, ch);++function inkRows(+ word: ScannedWord,+ left: number,+ right: number,+ baseRow: number,+): { top: number; bottom: number } | null {+ let first = -1;+ let last = -1;+ for (let y = 0; y < word.height; y++)+ for (let x = Math.max(0, left); x < Math.min(word.width, right); x++)+ if (word.rgba[(y * word.width + x) * 4 + 3] >= INK_ALPHA) {+ if (first < 0) first = y;+ last = y;+ break;+ }+ return first < 0+ ? null+ : { top: baseRow - first, bottom: baseRow - last - 1 };+}++function atTheirHeight(samples: Sample[]): Sample[] {+ const tops = samples.filter((s) => topClassOf(s.ch)).map((s) => s.top);+ if (tops.length === 0) return samples;+ const slack = median(tops) * HEIGHT_SLACK;+ const typical = (+ classOf: (ch: string) => string | null,+ edge: (s: Sample) => number,+ ) => {+ const groups = new Map<string, number[]>();+ for (const s of samples) {+ const key = classOf(s.ch);+ if (key) groups.set(key, [...(groups.get(key) ?? []), edge(s)]);+ }+ return (s: Sample) => {+ const key = classOf(s.ch);+ const group = key ? groups.get(key) : undefined;+ return !group || Math.abs(edge(s) - median(group)) <= slack;+ };+ };+ const topFits = typical(topClassOf, (s) => s.top);+ const bottomFits = typical(bottomClassOf, (s) => s.bottom);+ return samples.filter((s) => topFits(s) && bottomFits(s));+}++function evenPitch(steps: number[]): number | null {+ if (steps.length < MIN_PITCH_STEPS) return null;+ const pitch = median(steps);+ if (pitch <= 0) return null;+ const onPitch = steps.filter((st) => Math.abs(st / pitch - 1) < PITCH_SLACK);+ return onPitch.length >= steps.length * ON_PITCH ? pitch : null;+}++// Spans run left to right in ink order, so a word holding right-to-left letters would pair letters with the wrong ink.+const RIGHT_TO_LEFT =+ /[\p{Script=Hebrew}\p{Script=Arabic}\p{Script=Syriac}\p{Script=Thaana}\p{Script=Nko}]/u;++export function buildGlyphAtlas(+ words: ScannedWord[],+ descent: number,+): GlyphAtlas | null {+ const usable = words.filter(+ (w) =>+ w.spans.length > 0 &&+ w.spans.length === [...w.text].length &&+ w.height > 0 &&+ !RIGHT_TO_LEFT.test(w.text),+ );+ if (usable.length === 0) return null;+ const scale = usable[0].scale;+ const height = usable[0].height;+ const baseRow = height - descent * scale;+ const samples: Sample[] = [];+ const gaps: number[] = [];+ const steps: number[] = [];+ for (const word of usable) {+ if (word.height !== height || Math.abs(word.scale - scale) > 1e-6) continue;+ const cols = word.spans.map((s) => ({+ l: Math.round((s.left - word.left) * word.scale),+ r: Math.round((s.right - word.left) * word.scale),+ }));+ const chars = [...word.text];+ const digitsOnly = /^\d+$/.test(word.text);+ cols.forEach((c, i) => {+ const prev = cols[i - 1];+ const next = cols[i + 1];+ if (next) {+ gaps.push(next.l - c.r);+ if (!digitsOnly) steps.push((next.l + next.r - c.l - c.r) / 2);+ }+ const from = Math.max(0, prev ? Math.ceil((prev.r + c.l) / 2) : c.l - 3);+ const to = Math.min(+ word.width,+ next ? Math.floor((c.r + next.l) / 2) : c.r + 3,+ );+ if (to - from < 1 || c.r <= c.l) return;+ const rows = inkRows(word, c.l, c.r, baseRow);+ if (!rows) return;+ samples.push({+ ch: chars[i],+ word,+ from,+ to,+ inkLeft: c.l - from,+ inkRight: c.r - from,+ ...rows,+ });+ });+ }+ const byChar = new Map<string, Sample[]>();+ for (const s of atTheirHeight(samples))+ byChar.set(s.ch, [...(byChar.get(s.ch) ?? []), s]);+ if (byChar.size === 0) return null;+ const glyphs = new Map<string, GlyphImage>();+ for (const [ch, list] of byChar) {+ list.sort((p, q) => p.inkRight - p.inkLeft - (q.inkRight - q.inkLeft));+ const s = list[list.length >> 1];+ glyphs.set(ch, {+ ...cropColumns(s.word, s.from, s.to),+ inkLeft: s.inkLeft,+ inkRight: s.inkRight,+ });+ }+ gaps.sort((p, q) => p - q);+ return {+ glyphs,+ scale,+ height,+ descent,+ letterGap: gaps.length ? gaps[gaps.length >> 1] : Math.round(scale * 0.6),+ pitch: evenPitch(steps),+ };+}++export interface ComposedText {+ rgba: Uint8Array;+ width: number;+ height: number;+ inkLeft: number;+ inkRight: number;+}++export function composeText(+ atlas: GlyphAtlas,+ text: string,+ wordGap: number,+): ComposedText | null {+ const placed: Array<{ glyph: GlyphImage; x: number }> = [];+ let pen = 0;+ let afterSpace = false;+ for (const [i, ch] of [...text].entries()) {+ if (/\s/.test(ch)) {+ afterSpace = placed.length > 0;+ continue;+ }+ const glyph = atlas.glyphs.get(ch);+ if (!glyph) return null;+ if (atlas.pitch !== null) {+ const centre = (glyph.inkLeft + glyph.inkRight) / 2;+ placed.push({ glyph, x: Math.round(i * atlas.pitch - centre) });+ continue;+ }+ // Whole pixels only: a fractional pen makes the width fractional and shifts every row in the buffer.+ if (placed.length > 0)+ pen += afterSpace ? Math.round(wordGap) : atlas.letterGap;+ afterSpace = false;+ placed.push({ glyph, x: pen - glyph.inkLeft });+ pen += glyph.inkRight - glyph.inkLeft;+ }+ if (placed.length === 0) return null;+ const minX = Math.min(...placed.map((p) => p.x));+ const maxX = Math.max(...placed.map((p) => p.x + p.glyph.width));+ const width = maxX - minX;+ const height = atlas.height;+ const rgba = new Uint8Array(width * height * 4);+ for (const { glyph, x } of placed) {+ const ox = x - minX;+ for (let y = 0; y < height; y++)+ for (let gx = 0; gx < glyph.width; gx++) {+ const src = (y * glyph.width + gx) * 4;+ const dst = (y * width + ox + gx) * 4;+ if (glyph.rgba[src + 3] <= rgba[dst + 3]) continue;+ rgba.set(glyph.rgba.subarray(src, src + 4), dst);+ }+ }+ const first = placed[0];+ const last = placed[placed.length - 1];+ return {+ rgba,+ width,+ height,+ inkLeft: first.x + first.glyph.inkLeft - minX,+ inkRight: last.x + last.glyph.inkRight - minX,+ };+}diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/scanLayout.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/scanLayout.tsindex f554e9e0a8..294ba88a6f 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/commands/scanLayout.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/scanLayout.ts@@ -9,6 +9,8 @@ export interface LayoutWord {text: string;/** OCR left edge, raw page x. */x: number;+ /** Spaces the scan's own text has before it beyond the separating one. */+ lead?: number;}export interface LayoutLine {@@ -25,8 +27,12 @@ export interface LayoutInput {space: number;/** How wide a kept word's ink is. */wordWidth: (w: LayoutWord) => number;- /** How wide typed text draws, in the style of the word it replaces. */- textWidth: (text: string, anchor: LayoutWord | null) => number;+ /** How wide typed text draws, in the style of the word it replaces; `replaced` lists every scanned word it stands for, `anchor` first. */+ textWidth: (+ text: string,+ anchor: LayoutWord | null,+ replaced: LayoutWord[],+ ) => number;/** Redraw every word as text (a restyle), instead of keeping the scan. */redraw: boolean;}@@ -34,6 +40,7 @@ export interface LayoutInput {export interface PlacedWord {word: LayoutWord;x: number;+ line: number;baseline: number;/** False when the word stays exactly where the scan has it. */moved: boolean;@@ -42,11 +49,14 @@ export interface PlacedWord {export interface TypedText {text: string;x: number;+ line: number;baseline: number;/** The scanned word it replaces, if any: its style, and where it started. */anchor: LayoutWord | null;/** True when it starts exactly where `anchor` did. */atAnchor: boolean;+ /** Every scanned word it replaces, `anchor` first. */+ replaced: LayoutWord[];}export interface Layout {@@ -56,15 +66,29 @@ export interface Layout {}type Op =- | { kind: "keep"; word: LayoutWord; line: number }+ | { kind: "keep"; word: LayoutWord; line: number; lead: number }| { kind: "del"; word: LayoutWord }- | { kind: "ins"; text: string; line: number };+ | { kind: "ins"; text: string; line: number; lead: number };++interface Token {+ text: string;+ line: number;+ /** Spaces typed before the word beyond the one that separates words. */+ lead: number;+}++function tokensOf(text: string): Token[] {+ return text.split("\n").flatMap((t, line) =>+ [...t.matchAll(/( *)(\S+)/g)].map((found, i) => ({+ text: found[2],+ line,+ lead: Math.max(0, found[1].length - (i === 0 ? 0 : 1)),+ })),+ );+}// Longest common subsequence of the scan's words and the new words, as ops.-function align(- words: LayoutWord[],- tokens: Array<{ text: string; line: number }>,-): Op[] {+function align(words: LayoutWord[], tokens: Token[]): Op[] {const n = words.length;const m = tokens.length;const lcs = Array.from({ length: n + 1 }, () => new Uint16Array(m + 1));@@ -79,9 +103,10 @@ function align(let j = 0;while (i < n || j < m) {if (i < n && j < m && words[i].text === tokens[j].text) {- ops.push({ kind: "keep", word: words[i++], line: tokens[j++].line });+ const { line, lead } = tokens[j++];+ ops.push({ kind: "keep", word: words[i++], line, lead });} else if (j < m && (i >= n || lcs[i][j + 1] >= lcs[i + 1][j])) {- ops.push({ kind: "ins", text: tokens[j].text, line: tokens[j++].line });+ ops.push({ kind: "ins", ...tokens[j++] });} else {ops.push({ kind: "del", word: words[i++] });}@@ -89,16 +114,12 @@ function align(return ops;}+const SNAP_BACK = 0.75;+export function layoutScanEdit(input: LayoutInput): Layout {const { lines } = input;const words = lines.flatMap((l) => l.words).filter((w) => w.text);- const newLines = input.text.split("\n");- const tokens = newLines.flatMap((t, line) =>- t- .split(/\s+/)- .filter(Boolean)- .map((text) => ({ text, line })),- );+ const tokens = tokensOf(input.text);const ops: Op[] = input.redraw? [...words.map((word): Op => ({ kind: "del", word })),@@ -114,26 +135,29 @@ export function layoutScanEdit(input: LayoutInput): Layout {const lineStart = (line: number) =>(lines[line] ?? lines[0]).words.find((w) => w.text)?.x ??lines[0].words[0].x;+ const besideInScan = (a: LayoutWord, b: LayoutWord) =>+ a.line === b.line &&+ !lines[a.line].words.slice(a.index + 1, b.index).some((w) => w.text);// Words that sat side by side in the scan keep the gap they had.- const gap = (a: LayoutWord | null, b: LayoutWord | null) => {- if (!a || !b || a.line !== b.line) return input.space;- const between = lines[a.line].words.slice(a.index + 1, b.index);- if (between.some((w) => w.text)) return input.space;- return b.x - (a.x + input.wordWidth(a));- };+ const gap = (a: LayoutWord | null, b: LayoutWord | null) =>+ !a || !b || !besideInScan(a, b)+ ? input.space+ : b.x - (a.x + input.wordWidth(a));const layout: Layout = { kept: [], removed: [], typed: [] };- let pen: number | null = null;+ let pen: (() => number) | null = null;+ let lastKept: { word: LayoutWord; x: number } | null = null;let penLine = -1;let prev: LayoutWord | null = null;// Removed words since the last kept one: the first stands for typed text.let dels: LayoutWord[] = [];- let pending: { text: string[]; line: number } | null = null;+ let pending: { text: string; lead: number; line: number } | null = null;const startLine = (line: number) => {if (line === penLine) return;pen = null;prev = null;+ lastKept = null;penLine = line;};const flushTyped = () => {@@ -142,22 +166,36 @@ export function layoutScanEdit(input: LayoutInput): Layout {const line = pending.line;// A line starts where it always did, so deleting its first word pulls// the rest left rather than leaving a hole.- const x = pen === null ? lineStart(line) : pen + gap(prev, anchor);- const text = pending.text.join(" ");+ const scannedLead = anchor && anchor.line === line ? (anchor.lead ?? 0) : 0;+ const x =+ (pen === null ? lineStart(line) : pen() + gap(prev, anchor)) ++ Math.max(0, pending.lead - scannedLead) * input.space;+ const text = pending.text;layout.typed.push({text,x,+ line,baseline: baselineOf(line),anchor,atAnchor:!!anchor && anchor.line === line && Math.abs(x - anchor.x) < 0.5,+ replaced: dels,});- pen = x + input.textWidth(text, anchor);+ const end = x + input.textWidth(text, anchor, dels);+ pen = () => end;prev = anchor;+ lastKept = null;dels = [];pending = null;};+ const flowStart = (w: LayoutWord, line: number): number => {+ if (pen === null) return lineStart(line);+ if (lastKept && besideInScan(lastKept.word, w))+ return w.x + (lastKept.x - lastKept.word.x);+ return pen() + gap(prev, w);+ };+for (const op of ops) {if (op.kind === "del") {layout.removed.push(op.word);@@ -167,26 +205,75 @@ export function layoutScanEdit(input: LayoutInput): Layout {if (op.kind === "ins") {if (pending && pending.line !== op.line) flushTyped();startLine(op.line);- pending ??= { text: [], line: op.line };- pending.text.push(op.text);+ if (pending) pending.text += " ".repeat(op.lead + 1) + op.text;+ else pending = { text: op.text, lead: op.lead, line: op.line };continue;}if (pending && pending.line !== op.line) flushTyped();startLine(op.line);flushTyped();const w = op.word;- const x: number = pen === null ? lineStart(op.line) : pen + gap(prev, w);+ // The scan's own gap already shows the spaces its text came with.+ const extra = Math.max(0, op.lead - (w.lead ?? 0));+ const flowed = flowStart(w, op.line) + extra * input.space;+ const x =+ extra === 0 &&+ w.line === op.line &&+ Math.abs(flowed - w.x) < input.space * SNAP_BACK+ ? w.x+ : flowed;const baseline = baselineOf(op.line);layout.kept.push({word: w,x,+ line: op.line,baseline,moved: w.line !== op.line || Math.abs(x - w.x) > 0.3,});- pen = x + input.wordWidth(w);+ pen = () => x + input.wordWidth(w);prev = w;+ lastKept = { word: w, x };dels = [];}flushTyped();return layout;}++/** `text` reflowed so every line `fits` by swapping only spaces and line breaks, so offsets and the caret hold; adds a line only when `canAddLine`, and a word too wide stays put. */+export function rewrapLines(+ text: string,+ fits: (line: string) => boolean,+ canAddLine: boolean,+): string {+ const chars = [...text];+ if (chars.length !== text.length) return text;+ let start = 0;+ while (start < chars.length) {+ let end = chars.indexOf("\n", start);+ if (end < 0) end = chars.length;+ while (!fits(chars.slice(start, end).join("").trim())) {+ const at = lastBreak(chars, start, end);+ if (at < 0) break;+ const nextEnd = chars.indexOf("\n", end + 1);+ const next = chars+ .slice(end + 1, nextEnd < 0 ? chars.length : nextEnd)+ .join("");+ const joins = end < chars.length && next.trim() !== "";+ if (!joins && !canAddLine) break;+ if (joins) chars[end] = " ";+ chars[at] = "\n";+ end = at;+ }+ start = end + 1;+ }+ return chars.join("");+}++// The last space on [start, end) with a word on both sides of it.+function lastBreak(chars: string[], start: number, end: number): number {+ let at = end - 1;+ while (at > start && chars[at] === " ") at--;+ while (at > start && chars[at] !== " ") at--;+ if (at <= start || chars[at] !== " ") return -1;+ return chars.slice(start, at).some((ch) => ch !== " ") ? at : -1;+}diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/scanOffInk.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/scanOffInk.tsnew file mode 100644index 0000000000..323a670961--- /dev/null+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/scanOffInk.ts@@ -0,0 +1,89 @@+import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";+import type { Page } from "@editor/tools/pdfTextEditor/model/Page";+import {+ measureScanInk,+ type ScanRegion,+} from "@editor/tools/pdfTextEditor/pdfium/BackgroundSampler";++export interface PlacedWord {+ x: number;+ right: number;+ baseline: number;+}++export interface OcrLine {+ baseline: number;+ /** OCR's glyph box height above the baseline. */+ height: number;+ words: PlacedWord[];+}++const OFF_INK_SHIFTS = [0.5, 0.75, 1, 1.25, 1.5, 1.75, 2].flatMap((k) => [+ k,+ -k,+]);++export function lineExtent(line: OcrLine): { x0: number; x1: number } {+ return { x0: line.words[0].x, x1: line.words[line.words.length - 1].right };+}++/** The rows that hold glyphs sitting on baselines between `low` and `high`, descenders included. */+export function lineRegion(+ x0: number,+ x1: number,+ low: number,+ high: number,+ height: number,+): ScanRegion {+ return { x0, x1, bottom: low - height * 0.1, top: high + height * 0.9 };+}++function lineInkAt(+ doc: EditorDocument,+ page: Page,+ line: OcrLine,+ dy: number,+): boolean {+ const { x0, x1 } = lineExtent(line);+ const baseline = line.baseline + dy;+ const ink = measureScanInk(+ doc.module,+ page,+ lineRegion(x0, x1, baseline, baseline, line.height),+ );+ return !!ink && ink.rect.width >= (x1 - x0) * 0.5;+}++function claimedByOtherLine(+ lines: OcrLine[],+ others: PlacedWord[],+ line: OcrLine,+ dy: number,+): boolean {+ const { x0, x1 } = lineExtent(line);+ const baseline = line.baseline + dy;+ const placed = [+ ...lines.filter((l) => l !== line).flatMap((l) => l.words),+ ...others,+ ];+ return placed.some(+ (w) =>+ w.right > x0 && w.x < x1 && Math.abs(w.baseline - baseline) < line.height,+ );+}++/** Whether every OCR line has the scan's ink at one shared offset nothing else claims: the OCR layer sits beside the text it read. `lines` must all hold words. */+export function inkBesideOcr(+ doc: EditorDocument,+ page: Page,+ lines: OcrLine[],+ others: PlacedWord[],+): boolean {+ return OFF_INK_SHIFTS.some((k) =>+ lines.every(+ (l) =>+ !claimedByOtherLine(lines, others, l, k * l.height) &&+ lineInkAt(doc, page, l, k * l.height),+ ),+ );+}diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/scanPaint.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/scanPaint.tsnew file mode 100644index 0000000000..e7e02c4ea9--- /dev/null+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/scanPaint.ts@@ -0,0 +1,269 @@+import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";+import type { Page } from "@editor/tools/pdfTextEditor/model/Page";+import {+ RENDER_MODE_INVISIBLE,+ type PageRect,+} from "@editor/tools/pdfTextEditor/types";+import { BLACK, WHITE } from "@editor/tools/pdfTextEditor/model/Color";+import {+ applyTagMarks,+ type TagMark,+} from "@editor/tools/pdfTextEditor/pdfium/PdfiumTagMarks";+import { uniformTags } from "@editor/tools/pdfTextEditor/model/TextTags";+import { capturePatch } from "@editor/tools/pdfTextEditor/pdfium/BackgroundSampler";+import {+ emitTextLine,+ measureObjBoundsPt,+ measureObjSpanPt,+ removeAndDestroyObject,+} from "@editor/tools/pdfTextEditor/commands/editTextHelpers";+import {+ blurRgba,+ opaqueStroke,+ placeText,+ toInkOnly,+ type Placement,+} from "@editor/tools/pdfTextEditor/commands/scanStyle";+import type { ScanStyle } from "@editor/tools/pdfTextEditor/commands/scanFit";+import type {+ ComposedText,+ GlyphAtlas,+} from "@editor/tools/pdfTextEditor/commands/scanGlyphs";+import { transformObject } from "@editor/tools/pdfTextEditor/util/objectTransform";+import {+ createBitmapImageObject,+ type DecodedImage,+} from "@editor/utils/pdfiumBitmapUtils";++const MIN_WORD_GAP = 0.15;+const MAX_SQUEEZE = 0.85;++export interface Canvas {+ doc: EditorDocument;+ page: Page;+ tagMarks: readonly TagMark[];+ created: number[];+ textPtrs: number[];+ searchableFontPtr: number;+}++export function pasteImage(+ canvas: Canvas,+ img: DecodedImage,+ rect: PageRect,+): number {+ const { doc, page } = canvas;+ const ptr = createBitmapImageObject(+ doc.module,+ doc.docPtr,+ page.pagePtr,+ img,+ rect.x,+ rect.y,+ rect.width,+ rect.height,+ );+ if (!ptr) return 0;+ doc.module.FPDFPage_InsertObject(page.pagePtr, ptr);+ canvas.created.push(ptr);+ return ptr;+}++export interface SearchableFont {+ originalFontPtr: number;+ family: string;+}++export interface Span {+ left: number;+ right: number;+}++export function invisibleText(+ canvas: Canvas,+ text: string,+ span: Span,+ baseline: number,+ fontSize: number,+ font: SearchableFont,+): number[] {+ const m = canvas.doc.module;+ const ptrs = emitTextLine({+ doc: canvas.doc,+ page: canvas.page,+ text,+ x: span.left,+ y: baseline,+ fontSize,+ fill: BLACK,+ originalFontPtr: font.originalFontPtr,+ fallbackFamily: font.family,+ renderMode: RENDER_MODE_INVISIBLE,+ tags: uniformTags(canvas.tagMarks),+ });+ opaqueStroke(m, ptrs);+ scaleToSpan(m, ptrs, () => span);+ return ptrs;+}++// Stretch drawn text along x so its measured span becomes `target(span)`; null leaves it alone.+function scaleToSpan(+ m: EditorDocument["module"],+ ptrs: number[],+ target: (drawn: Span) => Span | null,+): void {+ const drawn = measureObjSpanPt(m, ptrs);+ if (!drawn || drawn.right - drawn.left < 1e-3) return;+ const to = target(drawn);+ if (!to || to.right <= to.left) return;+ const sx = (to.right - to.left) / (drawn.right - drawn.left);+ for (const p of ptrs)+ transformObject(m, p, sx, 0, 0, 1, to.left - sx * drawn.left, 0);+}++export function emitSearchable(+ canvas: Canvas,+ text: string,+ span: Span,+ baseline: number,+ fontSize: number,+ font: SearchableFont,+): void {+ const ptrs = invisibleText(canvas, text, span, baseline, fontSize, font);+ canvas.created.push(...ptrs);+ canvas.textPtrs.push(...ptrs);+}++export function squeezeToFit(+ left: number,+ right: number,+ limit: number,+): number {+ return right <= limit || limit <= left+ ? 1+ : Math.max(MAX_SQUEEZE, (limit - left) / (right - left));+}++export const wordGap = (size: number) => Math.max(1, size * MIN_WORD_GAP);++export function drawFromAtlas(+ canvas: Canvas,+ atlas: GlyphAtlas,+ glyphs: ComposedText,+ text: string,+ start: number,+ baseline: number,+ style: ScanStyle,+ limit: number,+): boolean {+ const left = start - glyphs.inkLeft / atlas.scale;+ const width = glyphs.width / atlas.scale;+ const squeeze = squeezeToFit(left, left + width, limit);+ const img = pasteImage(canvas, glyphs, {+ x: left,+ y: baseline - atlas.descent,+ width: width * squeeze,+ height: glyphs.height / atlas.scale,+ });+ if (!img) return false;+ const ink = {+ left: left + (glyphs.inkLeft / atlas.scale) * squeeze,+ right: left + (glyphs.inkRight / atlas.scale) * squeeze,+ };+ emitSearchable(canvas, text, ink, baseline, style.fontSize, {+ originalFontPtr: canvas.searchableFontPtr,+ family: style.family,+ });+ return true;+}++export function drawInFont(+ canvas: Canvas,+ text: string,+ x: number,+ inkLeft: number,+ baseline: number,+ style: ScanStyle,+ limit: number,+): void {+ const { doc, page } = canvas;+ const placement: Placement = {+ text,+ x,+ baseline,+ family: style.family,+ size: style.fontSize,+ stretch: style.stretch,+ inkLeft,+ fill: style.ink,+ weight: style.weight,+ hollow: style.hollow,+ };+ const softened =+ style.softness > 0 ? softenedCopy(canvas, placement, style, limit) : null;+ if (softened) {+ emitSearchable(canvas, text, softened, baseline, style.fontSize, {+ originalFontPtr: canvas.searchableFontPtr,+ family: style.family,+ });+ return;+ }+ const ptrs = placeText(doc, page, placement);+ // The OCR words this replaces leave the page, so the drawn copy carries their tags.+ applyTagMarks(doc.module, doc.docPtr, ptrs, canvas.tagMarks);+ keepClear(doc.module, ptrs, limit);+ canvas.created.push(...ptrs);+ canvas.textPtrs.push(...ptrs);+}++function keepClear(+ m: EditorDocument["module"],+ ptrs: number[],+ limit: number,+): void {+ if (limit === Infinity) return;+ scaleToSpan(m, ptrs, (drawn) => {+ const scale = squeezeToFit(drawn.left, drawn.right, limit);+ if (scale === 1) return null;+ return {+ left: drawn.left,+ right: drawn.left + (drawn.right - drawn.left) * scale,+ };+ });+}++// Crisp vector text stands out on a blurry scan, so blurry blocks get typed words as a picture softened to match.+function softenedCopy(+ canvas: Canvas,+ placement: Placement,+ style: ScanStyle,+ limit: number,+): Span | null {+ const { doc, page } = canvas;+ const m = doc.module;+ const sheet = doc.scratchPageFor(page);+ const ptrs = placeText(sheet.doc, sheet.page, { ...placement, fill: BLACK });+ try {+ keepClear(m, ptrs, limit);+ const box = measureObjBoundsPt(m, ptrs);+ if (!box) return null;+ const margin =+ style.softness / 4 + Math.max(style.weight, style.hollow) / 2 + 0.25;+ const patch = capturePatch(m, sheet.page, {+ x: box.left - margin,+ y: box.bottom - margin,+ width: box.right - box.left + margin * 2,+ height: box.top - box.bottom + margin * 2,+ });+ if (!patch) return null;+ blurRgba(patch, style.softness);+ toInkOnly(patch, WHITE);+ for (let i = 0; i < patch.rgba.length; i += 4)+ patch.rgba.set([placement.fill.r, placement.fill.g, placement.fill.b], i);+ return pasteImage(canvas, patch, patch.rect)+ ? { left: box.left, right: box.right }+ : null;+ } finally {+ for (const p of ptrs) removeAndDestroyObject(m, sheet.page.pagePtr, p);+ }+}diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/scanStyle.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/scanStyle.tsindex 6d32c932e6..b42ab0100f 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/commands/scanStyle.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/scanStyle.ts@@ -2,42 +2,47 @@ import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocimport type { Page } from "@editor/tools/pdfTextEditor/model/Page";import type { PageRect, RGBA } from "@editor/tools/pdfTextEditor/types";import { uniformTags } from "@editor/tools/pdfTextEditor/model/TextTags";-import { renderLuma } from "@editor/tools/pdfTextEditor/pdfium/BackgroundSampler";+import { BLACK, luma } from "@editor/tools/pdfTextEditor/model/Color";+import { boxBlur } from "@editor/tools/pdfTextEditor/util/boxBlur";+import { median } from "@editor/tools/pdfTextEditor/util/median";+import {+ INK_SCALE,+ blurLuma,+ renderLuma,+ type Luma,+} from "@editor/tools/pdfTextEditor/pdfium/BackgroundSampler";import {- emitFillRect,emitTextLine,measureObjSpanPt,removeAndDestroyObject,} from "@editor/tools/pdfTextEditor/commands/editTextHelpers";import { transformObject } from "@editor/tools/pdfTextEditor/util/objectTransform";+import { advanceWidth } from "@editor/tools/pdfTextEditor/util/fontMetrics";+import {+ BASE14_FACES,+ COURIER,+ HELVETICA,+ TIMES,+ type Face,+} from "@editor/tools/pdfTextEditor/util/scanFontLibrary";// Picking and placing a face that passes for scanned text.-// Base-14 metrics (AFM, per 1000 em) for the faces we can draw in.-export const FACES = [- { family: "Helvetica", bold: "Helvetica-Bold", cap: 718, asc: 718, xh: 523 },- { family: "Times-Roman", bold: "Times-Bold", cap: 662, asc: 683, xh: 450 },- { family: "Courier", bold: "Courier-Bold", cap: 562, asc: 629, xh: 426 },-];-export const [HELVETICA, TIMES, COURIER] = FACES;-export type Face = (typeof FACES)[number];--const BLACK: RGBA = { r: 0, g: 0, b: 0, a: 255 };-/** How tall the tallest glyph of `text` is, as a share of the em. */export function topShare(face: Face, text: string): number {- if (/[A-Z0-9]/.test(text))+ const tops = face.metrics?.get(face.family)?.tops;+ if (tops) {+ let tallest = 0;+ for (const ch of text)+ tallest = Math.max(tallest, tops.get(ch.codePointAt(0)!) ?? 0);+ if (tallest > 0) return tallest / 1000;+ }+ if (/[\p{Lu}\p{Nd}]/u.test(text))return Math.max(face.cap, /[bdfhklt]/.test(text) ? face.asc : 0) / 1000;if (/[bdfhklt]/.test(text)) return face.asc / 1000;return face.xh / 1000;}-export const median = (xs: number[]) => {- const v = [...xs].sort((p, q) => p - q);- const mid = v.length >> 1;- return v.length % 2 ? v[mid] : (v[mid - 1] + v[mid]) / 2;-};-export const clampStretch = (s: number) =>Math.min(1.35, Math.max(0.7, s || 1));@@ -49,9 +54,10 @@ export function spanOf(family: string,size: number,): number {+ const sheet = doc.scratchPageFor(page);const ptrs = emitTextLine({- doc,- page,+ doc: sheet.doc,+ page: sheet.page,text,x: 0,y: 0,@@ -62,10 +68,49 @@ export function spanOf(tags: uniformTags([]),});const span = measureObjSpanPt(doc.module, ptrs);- for (const p of ptrs) removeAndDestroyObject(doc.module, page.pagePtr, p);+ for (const p of ptrs)+ removeAndDestroyObject(doc.module, sheet.page.pagePtr, p);return span ? span.right - span.left : 0;}+const measuredAdvances = new Map<string, Map<string, number>>();++function measuredAdvance(+ doc: EditorDocument,+ page: Page,+ family: string,+ ch: string,+): number {+ let byChar = measuredAdvances.get(family);+ if (!byChar) {+ byChar = new Map();+ measuredAdvances.set(family, byChar);+ }+ let adv = byChar.get(ch);+ if (adv === undefined) {+ adv =+ (spanOf(doc, page, `H${ch}H`, family, 100) -+ spanOf(doc, page, "HH", family, 100)) *+ 10;+ byChar.set(ch, adv);+ }+ return adv;+}++export function textAdvance(+ doc: EditorDocument,+ page: Page,+ face: Face,+ family: string,+ text: string,+): number | null {+ const metrics = face.metrics?.get(family);+ if (metrics) return advanceWidth(metrics, text);+ let sum = 0;+ for (const ch of text) sum += measuredAdvance(doc, page, family, ch);+ return sum > 0 ? sum : null;+}+// The face whose letter widths explain these OCR word widths best. A single// scale absorbs size; what is left is the face's shape, which is what tells a// typewriter face from a proportional one. Null when the words cannot tell.@@ -87,7 +132,7 @@ export function fitFace(const k = median(ratios);return median(ratios.map((r) => Math.abs(r / k - 1)));};- const [sans, serif, mono] = FACES.map(err);+ const [sans, serif, mono] = BASE14_FACES.map(err);// Three words line up with any face by chance often enough; ask for four.if (usable.length >= 4 && mono < Math.min(sans, serif) * 0.7) return COURIER;// Serif and sans widths differ little, so a few words cannot settle it.@@ -102,11 +147,12 @@ export function isEvenlySpaced(centers: number[], text: string): boolean {const chars = text.replace(/\s/g, "");if (centers.length < 8 || /^\d+$/.test(chars)) return false;if (centers.length > chars.length * 1.1 + 1) return false;+ if (centers.length < chars.length * 0.9) return false;const steps = centers.slice(1).map((c, i) => c - centers[i]);- const pitch = (centers[centers.length - 1] - centers[0]) / (chars.length - 1);+ const pitch = median(steps);const onGrid = steps.filter((st) => {const n = Math.max(1, Math.round(st / pitch));- return Math.abs(st / pitch - n) / n < 0.15;+ return Math.abs(st / pitch - n) < 0.15;});return onGrid.length >= steps.length * 0.85;}@@ -123,6 +169,7 @@ export interface Placement {fill: RGBA;/** Outline in the fill colour that thickens the strokes, in points. */weight?: number;+ hollow?: number;}/**@@ -144,6 +191,17 @@ export function opaqueStroke(}}+// Fill and stroke (Tr 2): blur makes scanned strokes heavier than any bold.+function strokeOf(p: Placement): {+ renderMode?: number;+ stroke?: RGBA;+ strokeWidth?: number;+} {+ if (p.hollow) return { renderMode: 1, stroke: p.fill, strokeWidth: p.hollow };+ if (p.weight) return { renderMode: 2, stroke: p.fill, strokeWidth: p.weight };+ return {};+}+// Emit text squeezed or widened to the scan's letter widths, its ink starting// where the scanned ink started whatever the face's side bearing.export function placeText(@@ -165,12 +223,9 @@ export function placeText(// The invisible OCR layer carries the run's tags; tagging this visible// copy as well would have assistive technology read the words twice.tags: uniformTags([]),- // Fill and stroke (Tr 2): blur makes scanned strokes heavier than any bold.- ...(p.weight- ? { renderMode: 2, stroke: p.fill, strokeWidth: p.weight }- : {}),+ ...strokeOf(p),});- if (!p.weight) opaqueStroke(m, ptrs);+ if (!p.weight && !p.hollow) opaqueStroke(m, ptrs);for (const ptr of ptrs)transformObject(m, ptr, p.stretch, 0, 0, 1, p.x * (1 - p.stretch), 0);const drawn = measureObjSpanPt(m, ptrs);@@ -180,30 +235,87 @@ export function placeText(return ptrs;}-// Pearson correlation of two same-sized luma images.-function correlation(a: Float32Array, b: Float32Array): number {- const n = a.length;- let ma = 0;- let mb = 0;- for (let i = 0; i < n; i++) {- ma += a[i];- mb += b[i];+function windowCorrelation(+ scan: Luma,+ drawn: Luma,+ x0: number,+ x1: number,+ shift: number,+): { r: number; spread: number } {+ const { width, height } = scan;+ const from = Math.max(x0, -shift);+ const to = Math.min(x1, width - shift);+ if (to <= from) return { r: 0, spread: 0 };+ let n = 0;+ let sa = 0;+ let sb = 0;+ let sab = 0;+ let saa = 0;+ let sbb = 0;+ for (let y = 0; y < height; y++) {+ const row = y * width;+ for (let x = from; x < to; x++) {+ const a = scan.data[row + x];+ const b = drawn.data[row + x + shift];+ sa += a;+ sb += b;+ sab += a * b;+ saa += a * a;+ sbb += b * b;+ }+ n += to - from;}- ma /= n;- mb /= n;- let ab = 0;- let aa = 0;- let bb = 0;- for (let i = 0; i < n; i++) {- const da = a[i] - ma;- const db = b[i] - mb;- ab += da * db;- aa += da * da;- bb += db * db;+ const aa = saa - (sa * sa) / n;+ const bb = sbb - (sb * sb) / n;+ const ab = sab - (sa * sb) / n;+ return {+ r: aa > 0 && bb > 0 ? ab / Math.sqrt(aa * bb) : 0,+ spread: Math.sqrt(Math.max(0, aa) / n),+ };+}++function bestShift(+ scan: Luma,+ drawn: Luma,+ x0: number,+ x1: number,+ reach: number,+): number {+ let best = -1;+ let at = 0;+ for (let shift = -reach; shift <= reach; shift += 2) {+ const r = windowCorrelation(scan, drawn, x0, x1, shift).r;+ if (r > best) {+ best = r;+ at = shift;+ }+ }+ for (const shift of [at - 1, at + 1]) {+ if (Math.abs(shift) > reach) continue;+ best = Math.max(best, windowCorrelation(scan, drawn, x0, x1, shift).r);}- return aa > 0 && bb > 0 ? ab / Math.sqrt(aa * bb) : 0;+ return best;}+function slidingCorrelation(scan: Luma, drawn: Luma): number {+ const { width, height } = scan;+ const span = Math.max(8, Math.round(height * SLIDE_WINDOW));+ const reach = Math.max(1, Math.round(height * SLIDE_REACH));+ let total = 0;+ let weight = 0;+ for (let x0 = 0; x0 < width; x0 += Math.round(span / 2)) {+ const x1 = Math.min(width, x0 + span);+ const spread = windowCorrelation(scan, drawn, x0, x1, 0).spread;+ if (spread === 0) continue;+ total += bestShift(scan, drawn, x0, x1, reach) * spread;+ weight += spread;+ }+ return weight > 0 ? total / weight : 0;+}++const SLIDE_WINDOW = 2;+const SLIDE_REACH = 0.25;+// Average stroke thickness: ink pixels per horizontal run of ink, cut halfway// between paper and ink. Unlike total darkness, paper grain and the grey core// of a blurred stroke barely move it.@@ -225,9 +337,34 @@ function strokeWidth(return runs ? inked / runs : 0;}-function percentile(values: Float32Array, p: number): number {- const sorted = Float32Array.from(values).sort();- return sorted[Math.floor((sorted.length - 1) * p)];+function nthSmallest(values: Float32Array | Float64Array, n: number): number {+ let lo = 0;+ let hi = values.length - 1;+ while (lo < hi) {+ const pivot = values[(lo + hi) >> 1];+ let i = lo;+ let j = hi;+ while (i <= j) {+ while (values[i] < pivot) i++;+ while (values[j] > pivot) j--;+ if (i <= j) {+ const t = values[i];+ values[i] = values[j];+ values[j] = t;+ i++;+ j--;+ }+ }+ if (n <= j) hi = j;+ else if (n >= i) lo = i;+ else break;+ }+ return values[n];+}++function percentiles(values: Float32Array, ps: number[]): number[] {+ const copy = Float32Array.from(values);+ return ps.map((p) => nthSmallest(copy, Math.floor((copy.length - 1) * p)));}export interface ScanMatch {@@ -237,6 +374,160 @@ export interface ScanMatch {weight: number;}+type ScanImage = { img: Luma; stroke: number; edge?: number } | null;++interface FitMemory {+ scans: Map<number, ScanImage>;+ matches: Map<string, ScanMatch>;+ softness: Map<string, number>;+ measures: Map<string, number | null>;+}++const fitMemory = new WeakMap<object, FitMemory>();+let fitDeadline = Infinity;+let measuredThisSlice = false;++export const FIT_PAUSED = Symbol("fit paused");++export function withFitDeadline<T>(deadline: number, fit: () => T): T {+ const outer = fitDeadline;+ fitDeadline = deadline;+ measuredThisSlice = false;+ try {+ return fit();+ } finally {+ fitDeadline = outer;+ }+}++export function withScanCache<T>(ink: object, fit: () => T): T {+ if (!fitMemory.has(ink))+ fitMemory.set(ink, {+ scans: new Map(),+ matches: new Map(),+ softness: new Map(),+ measures: new Map(),+ });+ try {+ const result = fit();+ fitMemory.delete(ink);+ return result;+ } catch (e) {+ if (e !== FIT_PAUSED) fitMemory.delete(ink);+ throw e;+ }+}++export function rememberForFit(+ ink: object,+ key: string,+ measure: () => number | null,+): number | null {+ return remember(fitMemory.get(ink)?.measures, key, measure);+}++function remember<K, V>(+ memory: Map<K, V> | undefined,+ key: K,+ measure: () => V,+): V {+ const known = memory?.get(key);+ if (known !== undefined) return known;+ const value = measure();+ memory?.set(key, value);+ return value;+}++const FIT_PROBE_PX = 96;++export const fitScale = (ink: { rect: PageRect }) =>+ Math.min(INK_SCALE, FIT_PROBE_PX / (ink.rect.height + 2));++const probeOf = (rect: PageRect): PageRect => ({+ x: rect.x - 1,+ y: rect.y - 1,+ width: rect.width + 2,+ height: rect.height + 2,+});++export function checkDeadline(): void {+ if (+ measuredThisSlice &&+ fitDeadline !== Infinity &&+ performance.now() > fitDeadline+ )+ throw FIT_PAUSED;+ measuredThisSlice = true;+}++function placementKey(+ c: Omit<Placement, "inkLeft" | "fill">,+ ...extra: unknown[]+): string {+ return [+ c.text,+ c.x,+ c.baseline,+ c.family,+ c.size,+ c.stretch,+ c.weight ?? 0,+ c.hollow ?? 0,+ ...extra,+ ].join("|");+}++function scanImage(+ doc: EditorDocument,+ page: Page,+ ink: { rect: PageRect; reversed?: boolean },+ probe: PageRect,+ blur: number,+): ScanImage {+ return remember(fitMemory.get(ink)?.scans, blur, () => {+ const sharp = blur === 0 ? null : scanImage(doc, page, ink, probe, 0);+ if (blur !== 0 && !sharp) return null;+ if (!sharp) checkDeadline();+ const img = sharp+ ? blurLuma(sharp.img, blur)+ : renderLuma(doc.module, page, probe, 0, fitScale(ink));+ if (img && !sharp && ink.reversed)+ for (let i = 0; i < img.data.length; i++) img.data[i] = 255 - img.data[i];+ return img ? { img, stroke: strokeWidth(img, midTone(img)) } : null;+ });+}++// Each image cut halfway between its own paper and its own darkest ink.+function midTone(img: { data: Float32Array }): number {+ const [paper, ink] = percentiles(img.data, [0.85, 0.01]);+ return (paper + ink) / 2;+}++function drawnLuma(+ doc: EditorDocument,+ page: Page,+ ink: { rect: PageRect; body: PageRect },+ c: Omit<Placement, "inkLeft" | "fill">,+ blur: number,+): Luma | null {+ const m = doc.module;+ const sheet = doc.scratchPageFor(page);+ const ptrs = placeText(sheet.doc, sheet.page, {+ ...c,+ inkLeft: ink.body.x,+ fill: BLACK,+ });+ const drawn = renderLuma(+ m,+ sheet.page,+ probeOf(ink.rect),+ blur,+ fitScale(ink),+ );+ for (const p of ptrs) removeAndDestroyObject(m, sheet.page.pagePtr, p);+ return drawn;+}+/** How much `c` drawn on the spot looks like the scanned pixels there. */export function matchScan(doc: EditorDocument,@@ -245,30 +536,49 @@ export function matchScan(c: Omit<Placement, "inkLeft" | "fill">,/** Blur for the drawn copy; the scan is compared unblurred when set. */softness?: number,+ rough = false,): ScanMatch {- const m = doc.module;- const probe = {- x: ink.rect.x - 1,- y: ink.rect.y - 1,- width: ink.rect.width + 2,- height: ink.rect.height + 2,- };+ return remember(+ fitMemory.get(ink)?.matches,+ placementKey(c, softness, rough),+ () => measureMatch(doc, page, ink, c, softness, rough),+ );+}++function measureMatch(+ doc: EditorDocument,+ page: Page,+ ink: { rect: PageRect; body: PageRect },+ c: Omit<Placement, "inkLeft" | "fill">,+ softness: number | undefined,+ rough: boolean,+): ScanMatch {+ const probe = probeOf(ink.rect);const none = { score: 0, weight: 1 };- const scan = renderLuma(m, page, probe, softness === undefined ? 2 : 0);- if (!scan) return none;- const cover = emitFillRect(m, page, probe, { r: 255, g: 255, b: 255 }, 1);- const ptrs = placeText(doc, page, { ...c, inkLeft: ink.body.x, fill: BLACK });- const drawn = renderLuma(m, page, probe, softness ?? 2);- for (const p of [cover, ...ptrs]) removeAndDestroyObject(m, page.pagePtr, p);+ const scanned = scanImage(+ doc,+ page,+ ink,+ probe,+ softness === undefined ? 2 : 0,+ );+ if (!scanned) return none;+ const scan = scanned.img;+ checkDeadline();+ const blur =+ softness === undefined+ ? 2+ : Math.round((softness * fitScale(ink)) / INK_SCALE);+ const drawn = drawnLuma(doc, page, ink, c, blur);if (!drawn || drawn.data.length !== scan.data.length) return none;- // Each image cut halfway between its own paper and its own darkest ink.- const mid = (img: { data: Float32Array }) =>- (percentile(img.data, 0.85) + percentile(img.data, 0.01)) / 2;return {- score: correlation(scan.data, drawn.data),+ score: rough+ ? windowCorrelation(scan, drawn, 0, scan.width, 0).r+ : slidingCorrelation(scan, drawn),weight:- strokeWidth(drawn, mid(drawn)) /- Math.max(0.5, strokeWidth(scan, mid(scan))),+ softness === undefined+ ? 1+ : strokeWidth(drawn, midTone(drawn)) / Math.max(0.5, scanned.stroke),};}@@ -276,7 +586,8 @@ export function matchScan(// over the steepest gradients. Blur widens it; noise and colour do not.function edgeWidth(img: { data: Float32Array; width: number; height: number }) {const { data, width, height } = img;- const contrast = percentile(data, 0.95) - percentile(data, 0.02);+ const [paper, ink] = percentiles(data, [0.95, 0.02]);+ const contrast = paper - ink;if (contrast < 20) return 0;const grads: number[] = [];for (let y = 0; y < height - 1; y++)@@ -289,8 +600,11 @@ function edgeWidth(img: { data: Float32Array; width: number; height: number }) {if (g > contrast * 0.05) grads.push(g);}if (grads.length === 0) return 0;- grads.sort((p, q) => p - q);- return contrast / grads[Math.floor(grads.length * 0.9)];+ const steep = nthSmallest(+ Float64Array.from(grads),+ Math.floor(grads.length * 0.9),+ );+ return contrast / steep;}/**@@ -303,28 +617,31 @@ export function softnessOf(ink: { rect: PageRect; body: PageRect },c: Omit<Placement, "inkLeft" | "fill">,): number {- const m = doc.module;- const probe = {- x: ink.rect.x - 1,- y: ink.rect.y - 1,- width: ink.rect.width + 2,- height: ink.rect.height + 2,- };- const scan = renderLuma(m, page, probe, 0);+ return remember(fitMemory.get(ink)?.softness, placementKey(c), () =>+ measureSoftness(doc, page, ink, c),+ );+}++function measureSoftness(+ doc: EditorDocument,+ page: Page,+ ink: { rect: PageRect; body: PageRect },+ c: Omit<Placement, "inkLeft" | "fill">,+): number {+ const scan = scanImage(doc, page, ink, probeOf(ink.rect), 0);if (!scan) return 0;- const target = edgeWidth(scan);- const cover = emitFillRect(m, page, probe, { r: 255, g: 255, b: 255 }, 1);- const ptrs = placeText(doc, page, { ...c, inkLeft: ink.body.x, fill: BLACK });+ const target = (scan.edge ??= edgeWidth(scan.img));+ checkDeadline();+ const sharp = drawnLuma(doc, page, ink, c, 0);+ if (!sharp) return 0;let best = { r: 0, err: Infinity };for (const r of [0, 1, 2]) {- const drawn = renderLuma(m, page, probe, r);- if (!drawn) continue;+ const drawn = blurLuma(sharp, r);// Ties go to the sharper: crisp text should stay crisp.const err = Math.abs(edgeWidth(drawn) - target) + r * 0.05;if (err < best.err) best = { r, err };}- for (const p of [cover, ...ptrs]) removeAndDestroyObject(m, page.pagePtr, p);- return best.r;+ return Math.round((best.r * INK_SCALE) / fitScale(ink));}/** Box-blur an RGBA image in place, `r` pixels each way. */@@ -333,27 +650,8 @@ export function blurRgba(r: number,): void {const { rgba, width, height } = img;- const tmp = new Uint8Array(rgba.length);- const pass = (src: Uint8Array, dst: Uint8Array, dx: number, dy: number) => {- for (let y = 0; y < height; y++)- for (let x = 0; x < width; x++)- for (let c = 0; c < 3; c++) {- let sum = 0;- let n = 0;- for (let k = -r; k <= r; k++) {- const xx = x + k * dx;- const yy = y + k * dy;- if (xx < 0 || yy < 0 || xx >= width || yy >= height) continue;- sum += src[(yy * width + xx) * 4 + c];- n++;- }- const i = (y * width + x) * 4;- dst[i + c] = sum / n;- dst[i + 3] = 255;- }- };- pass(rgba, tmp, 1, 0);- pass(tmp, rgba, 0, 1);+ rgba.set(boxBlur(rgba, width, height, r, 3, 4));+ for (let i = 3; i < rgba.length; i += 4) rgba[i] = 255;}/**@@ -364,17 +662,21 @@ export function blurRgba(export function toInkOnly(img: { rgba: Uint8Array; width: number; height: number },paper: RGBA,+ lightInk = false,): void {const { rgba } = img;- const lum = (i: number) =>- 0.299 * rgba[i] + 0.587 * rgba[i + 1] + 0.114 * rgba[i + 2];- const paperL = 0.299 * paper.r + 0.587 * paper.g + 0.114 * paper.b;- let darkest = paperL;- for (let i = 0; i < rgba.length; i += 4) darkest = Math.min(darkest, lum(i));- const span = Math.max(60, paperL - darkest);+ const paperL = luma(paper.r, paper.g, paper.b);+ const inkiness = (i: number) => {+ const l = luma(rgba[i], rgba[i + 1], rgba[i + 2]);+ return lightInk ? l - paperL : paperL - l;+ };+ let deepest = 0;+ for (let i = 0; i < rgba.length; i += 4)+ deepest = Math.max(deepest, inkiness(i));+ const span = Math.max(60, deepest);const bg = [paper.r, paper.g, paper.b];for (let i = 0; i < rgba.length; i += 4) {- const a = Math.min(1, Math.max(0, (paperL - lum(i)) / span));+ const a = Math.min(1, Math.max(0, inkiness(i) / span));if (a < 0.04) {rgba[i + 3] = 0;continue;diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/scanTextEdit.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/scanTextEdit.tsindex 862c7d6b78..4e7c295dd4 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/commands/scanTextEdit.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/scanTextEdit.ts@@ -1,56 +1,102 @@import type { WrappedPdfiumModule } from "@embedpdf/pdfium";+import {+ applyVector,+ moveAllObjects,+ scanFrameFor,+ type ScanFrame,+} from "@editor/tools/pdfTextEditor/commands/scanFrame";+import { median } from "@editor/tools/pdfTextEditor/util/median";+import { BLACK, WHITE, luma } from "@editor/tools/pdfTextEditor/model/Color";import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";import type { Page } from "@editor/tools/pdfTextEditor/model/Page";import type { TextRun } from "@editor/tools/pdfTextEditor/model/TextRun";-import type { PageRect, RGBA } from "@editor/tools/pdfTextEditor/types";import {- INK_SCALE,+ RENDER_MODE_INVISIBLE,+ type Affine,+ type RGBA,+} from "@editor/tools/pdfTextEditor/types";+import {+ composeAffine,+ invertAffine,+ transformRectAABB,+} from "@editor/tools/pdfTextEditor/model/affine";+import {capturePatch,measureScanInk,sampleBackground,type PixelPatch,- type ScanInk,} from "@editor/tools/pdfTextEditor/pdfium/BackgroundSampler";+import {+ inkBesideOcr,+ lineExtent,+ lineRegion,+ type PlacedWord,+} from "@editor/tools/pdfTextEditor/commands/scanOffInk";import {layoutScanEdit,+ rewrapLines,type LayoutWord,} from "@editor/tools/pdfTextEditor/commands/scanLayout";-import { createBitmapImageObject } from "@editor/utils/pdfiumBitmapUtils";-import type { TagMark } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTagMarks";-import { uniformTags } from "@editor/tools/pdfTextEditor/model/TextTags";import {emitFillRect,- emitTextLine,- measureObjSpanPt,removeAndDestroyObject,removeMemberPtrs,+ recordUndrawableChars,} from "@editor/tools/pdfTextEditor/commands/editTextHelpers";import {- COURIER,- FACES,- HELVETICA,- clampStretch,+ FIT_PAUSED,+ blurRgba,+ checkDeadline,fitFace,- isEvenlySpaced,- matchScan,- median,placeText,- blurRgba,- softnessOf,- toInkOnly,- opaqueStroke,spanOf,- topShare,- type Face,+ toInkOnly,+ withFitDeadline,} from "@editor/tools/pdfTextEditor/commands/scanStyle";+import {+ inkTop,+ preferredScanFace,+ preferredStyle,+ rankStyles,+ withPreferredFace,+ type FitInput,+ type FitWord,+ type RankedStyle,+ type ScanStyle,+ type SpanInk,+} from "@editor/tools/pdfTextEditor/commands/scanFit";+import {+ drawFromAtlas,+ drawInFont,+ emitSearchable,+ invisibleText,+ pasteImage,+ wordGap,+ type Canvas,+} from "@editor/tools/pdfTextEditor/commands/scanPaint";+import {+ COURIER,+ HELVETICA,+ faceCovers,+ scanFaces,+ scanFacesGeneration,+ type Face,+} from "@editor/tools/pdfTextEditor/util/scanFontLibrary";+import {+ buildGlyphAtlas,+ composeText,+ type ComposedText,+ type GlyphAtlas,+ type ScannedWord,+} from "@editor/tools/pdfTextEditor/commands/scanGlyphs";+import { readMatrix } from "@editor/tools/pdfTextEditor/commands/textPieces";// Editing OCR text on a scanned page. The words live twice: as pixels in the// scan and as invisible (Tr 3) text. An edit draws only the words the user// typed; every other word stays the scan's own pixels (moved if it has to make// room), so OCR misreads never reach the page.-const INVISIBLE = 3;-const BLACK: RGBA = { r: 0, g: 0, b: 0, a: 255 };+const REFERENCE_CHARS = 72;interface ScanWord {text: string;@@ -58,6 +104,7 @@ interface ScanWord {start: number;x: number;right: number;+ baseline: number;ptr: number;extraPtrs?: number[];container: number;@@ -72,19 +119,6 @@ interface ScanLine {words: ScanWord[];}-// How scanned text is redrawn: one face, size and colour for a whole block.-interface ScanStyle {- family: string;- fontSize: number;- /** Horizontal scale that gives the face the scan's letter widths. */- stretch: number;- ink: RGBA;- /** Outline that thickens the strokes to the scan's weight, in points. */- weight: number;- /** Blur, in render pixels, that softens drawn text to the scan's focus. */- softness: number;-}-/** A move or restyle the user applied to the whole block. */export interface ScanOverride {dx: number;@@ -92,17 +126,7 @@ export interface ScanOverride {family?: string;fontSize?: number;fill?: RGBA;-}--interface SpanInk {- ink: ScanInk;- /** Paper colour right around the span. */- paper: RGBA;- baseline: number;- /** The OCR text of the span, minus any box edge it read as a bracket. */- original: string;- dropLead: boolean;- dropTrail: boolean;+ style?: ScanStyle;}export interface ScanEditState {@@ -119,22 +143,129 @@ export interface ScanEditState {patches: Map<string, PixelPatch | null>;override: ScanOverride;/** The block's style, and its glyph height above the baseline. */- block?: { style: ScanStyle; top: number } | null;+ block?: {+ style: ScanStyle;+ top: number;+ xHeight: number | null;+ ranked: RankedStyle[];+ ref: SpanInk;+ preferred: string | null;+ drawn?: boolean;+ } | null;+ undrawableWithFaces?: number;/** Styles for text in the block that the scan sets at another size. */classes: Array<{ style: ScanStyle; top: number }>;face?: Face | null;nearbyFace?: Face | null;neighbours?: PlacedWord[];+ atlas?: GlyphAtlas | null;+ atlasChars?: Set<string>;+ frame?: ScanFrame;+ upright?: boolean;+ offScan?: boolean;+ offInk?: boolean;+ edited?: boolean;+ typedFromScan?: boolean;}-interface PlacedWord {- x: number;- right: number;- baseline: number;+export function isScanRun(run: { renderMode?: number }): boolean {+ return run.renderMode === RENDER_MODE_INVISIBLE;+}++function emptyState(lines: ScanLine[], fontPtr: number): ScanEditState {+ return {+ lines,+ fontPtr,+ created: [],+ textPtrs: [],+ lifted: new Set(),+ inks: new Map(),+ patches: new Map(),+ override: { dx: 0, dy: 0 },+ classes: [],+ };}-export function isScanRun(run: TextRun): boolean {- return run.renderMode === INVISIBLE;+function runWords(run: TextRun) {+ return {+ ptrs: run.mergedFromPtrs.length ? run.mergedFromPtrs : [run.pdfiumObjPtr],+ texts: run.mergedFromTexts.length ? run.mergedFromTexts : [run.text],+ starts: run.mergedFromCharStarts.length ? run.mergedFromCharStarts : [0],+ bounds: run.mergedFromBounds.length+ ? run.mergedFromBounds+ : [{ x: run.bounds.x, right: run.bounds.x + run.bounds.width }],+ };+}++function fontOf(m: WrappedPdfiumModule, ptr: number): number {+ try {+ return m.FPDFTextObj_GetFont(ptr);+ } catch {+ return 0;+ }+}++const affineOf = (v: Float32Array): Affine => ({+ a: v[0],+ b: v[1],+ c: v[2],+ d: v[3],+ e: v[4],+ f: v[5],+});++function pageMatrixReader(+ m: WrappedPdfiumModule,+ run: TextRun,+): (ptr: number, container: number) => Affine | null {+ const runOwn = run.containerPtr ? readMatrix(m, run.pdfiumObjPtr) : null;+ const form = runOwn+ ? composeAffine(run.matrix, invertAffine(affineOf(runOwn)))+ : null;+ return (ptr, container) => {+ if (container !== 0 && (container !== run.containerPtr || !form))+ return null;+ const own = readMatrix(m, ptr);+ if (!own) return null;+ return form ? composeAffine(form, affineOf(own)) : affineOf(own);+ };+}++function captureRotatedScanEdit(+ m: WrappedPdfiumModule,+ run: TextRun,+ frame: ScanFrame,+): ScanEditState | null {+ if (run.text.includes("\n")) return null;+ const { ptrs, texts, starts } = runWords(run);+ if (texts.length !== ptrs.length || starts.length !== ptrs.length)+ return null;+ const baseline = composeAffine(frame.toUpright, run.matrix).f;+ const box = transformRectAABB(frame.toUpright, run.bounds);+ const length = Math.max(1, run.text.trimEnd().length);+ const pageMatrix = pageMatrixReader(m, run);+ const words: ScanWord[] = ptrs.map((ptr, w) => {+ const start = starts[w];+ const end = start + texts[w].trimEnd().length;+ const own = pageMatrix(ptr, run.containerPtr);+ return {+ text: texts[w],+ start,+ x: box.x + (box.width * start) / length,+ right: box.x + (box.width * Math.min(end, length)) / length,+ baseline: own ? composeAffine(frame.toUpright, own).f : baseline,+ ptr,+ container: run.containerPtr,+ fontSize: run.fontSize,+ };+ });+ const line = {+ text: run.text,+ baseline,+ height: Math.max(2, box.y + box.height - baseline),+ words,+ };+ return { ...emptyState([line], fontOf(m, ptrs[0])), frame };}// Snapshot a run's OCR words. Null when the run carries no per-word geometry,@@ -142,8 +273,12 @@ export function isScanRun(run: TextRun): boolean {export function captureScanEdit(m: WrappedPdfiumModule,run: TextRun,+ page?: Page,): ScanEditState | null {+ const frame = page ? scanFrameFor(page, run.matrix, run.bounds) : null;+ if (frame) return captureRotatedScanEdit(m, run, frame);const texts = run.text.split("\n");+ const own = runWords(run);const slots =run.paragraphLineSlots.length === texts.length? run.paragraphLineSlots@@ -153,18 +288,10 @@ export function captureScanEdit(baselineY: run.matrix.f,containerPtr: run.containerPtr,fontSize: run.fontSize,- mergedFromPtrs: run.mergedFromPtrs.length- ? run.mergedFromPtrs- : [run.pdfiumObjPtr],- mergedFromTexts: run.mergedFromTexts.length- ? run.mergedFromTexts- : [run.text],- mergedFromBounds: run.mergedFromBounds.length- ? run.mergedFromBounds- : [{ x: run.bounds.x, right: run.bounds.x + run.bounds.width }],- mergedFromCharStarts: run.mergedFromCharStarts.length- ? run.mergedFromCharStarts- : [0],+ mergedFromPtrs: own.ptrs,+ mergedFromTexts: own.texts,+ mergedFromBounds: own.bounds,+ mergedFromCharStarts: own.starts,},]: null;@@ -172,8 +299,8 @@ export function captureScanEdit(const top = run.bounds.y + run.bounds.height;const height = Math.max(2, top - slots[0].baselineY);const lines: ScanLine[] = [];- for (let i = 0; i < slots.length; i++) {- const s = slots[i];+ const pageMatrix = pageMatrixReader(m, run);+ for (const [i, s] of slots.entries()) {const n = s.mergedFromPtrs.length;if (n === 0 ||@@ -183,6 +310,7 @@ export function captureScanEdit(s.mergedFromPtrs.some((p) => !p))return null;+ const container = s.containerPtr || run.containerPtr;lines.push({text: texts[i],baseline: s.baselineY,@@ -192,29 +320,14 @@ export function captureScanEdit(start: s.mergedFromCharStarts[w],x: s.mergedFromBounds[w].x,right: s.mergedFromBounds[w].right,+ baseline: pageMatrix(ptr, container)?.f ?? s.baselineY,ptr,- container: s.containerPtr || run.containerPtr,+ container,fontSize: s.fontSize,})),});}- let fontPtr = 0;- try {- fontPtr = m.FPDFTextObj_GetFont(lines[0].words[0].ptr);- } catch {- fontPtr = 0;- }- return {- lines,- fontPtr,- created: [],- textPtrs: [],- lifted: new Set(),- inks: new Map(),- patches: new Map(),- override: { dx: 0, dy: 0 },- classes: [],- };+ return emptyState(lines, fontOf(m, lines[0].words[0].ptr));}/** Where word `w` of a line ends in the line's text, its trailing space included. */@@ -222,7 +335,7 @@ function wordEnd(line: ScanLine, w: number): number {return w + 1 < line.words.length ? line.words[w + 1].start : line.text.length;}-const wordsOf = (lines: ScanLine[]) =>+const wordsOf = (lines: ScanLine[]): FitWord[] =>lines.flatMap((l) => l.words).map((w) => ({ text: w.text, width: w.right - w.x }));@@ -245,8 +358,9 @@ function nearbyFace(state: ScanEditState,): Face | null {if (state.nearbyFace !== undefined) return state.nearbyFace;+ if (state.frame) return (state.nearbyFace = null);const own = state.lines[0];- const pooled: Array<{ text: string; width: number }> = [];+ const pooled: FitWord[] = [];const others = page.runs.filter((r) => isScanRun(r) && r.scanEdit !== state).map((run) => ({@@ -259,10 +373,7 @@ function nearbyFace(.filter((o) => o.height / own.height > 0.75 && o.height / own.height < 1.33).sort((p, q) => p.dist - q.dist);for (const { run } of others) {- const texts = run.mergedFromTexts.length ? run.mergedFromTexts : [run.text];- const bounds = run.mergedFromBounds.length- ? run.mergedFromBounds- : [{ x: run.bounds.x, right: run.bounds.x + run.bounds.width }];+ const { texts, bounds } = runWords(run);texts.forEach((t, i) =>pooled.push({ text: t, width: bounds[i].right - bounds[i].x }),);@@ -278,18 +389,19 @@ function otherWords(page: Page, state: ScanEditState): PlacedWord[] {const out: PlacedWord[] = [];for (const run of page.runs) {if (!isScanRun(run) || run.scanEdit === state) continue;+ if (state.frame) {+ const box = transformRectAABB(state.frame.toUpright, run.bounds);+ const turned = composeAffine(state.frame.toUpright, run.matrix);+ if (Math.abs(turned.b) > 1e-6 || turned.a <= 0) continue;+ out.push({ x: box.x, right: box.x + box.width, baseline: turned.f });+ continue;+ }const slots = run.paragraphLineSlots.length? run.paragraphLineSlots- : [{ baselineY: run.matrix.f, mergedFromBounds: run.mergedFromBounds }];+ : [{ baselineY: run.matrix.f, mergedFromBounds: runWords(run).bounds }];for (const s of slots)for (const b of s.mergedFromBounds)out.push({ x: b.x, right: b.right, baseline: s.baselineY });- if (!run.mergedFromBounds.length && !run.paragraphLineSlots.length)- out.push({- x: run.bounds.x,- right: run.bounds.x + run.bounds.width,- baseline: run.matrix.f,- });}state.neighbours = out;return out;@@ -307,27 +419,29 @@ function spanInk(): SpanInk | null {const key = `${li}:${from}:${to}`;if (state.inks.has(key)) return state.inks.get(key) ?? null;- const m = doc.module;const line = state.lines[li];const words = line.words;const prev = words[from - 1];const next = words[to + 1];+ const own = words.slice(from, to + 1).map((w) => w.baseline);+ const low = Math.min(...own);+ const high = Math.max(...own);+ const mid = (low + high) / 2;// Stay clear of the neighbouring words' ink, however close they sit.let x0 = prev ? (prev.right + words[from].x) / 2 : words[from].x - 2;let x1 = next ? (words[to].right + next.x) / 2 : words[to].right + 2;// OCR word boxes can overrun into words the OCR put in another block.for (const w of otherWords(page, state)) {- if (Math.abs(w.baseline - line.baseline) > line.height * 0.5) continue;+ if (Math.abs(w.baseline - mid) > line.height * 0.5) continue;if (w.x > words[to].x + 0.5) x1 = Math.min(x1, w.x - 0.3);if (w.right < words[from].x + 0.5) x0 = Math.max(x0, w.right + 0.3);}- const region = {- x0,- x1,- bottom: line.baseline - line.height * 0.1,- top: line.baseline + line.height * 0.9,- };- const ink = measureScanInk(m, page, region);+ checkDeadline();+ const ink = measureScanInk(+ doc.module,+ page,+ lineRegion(x0, x1, low, high, line.height),+ );let result: SpanInk | null = null;if (ink) {// OCR reads a box edge hugging the text as a bracket or bar.@@ -339,9 +453,9 @@ function spanInk(paper: ink.paper,baseline:ink.baseline !== null &&- Math.abs(ink.baseline - line.baseline) < line.height * 0.4+ Math.abs(ink.baseline - mid) < line.height * 0.4? ink.baseline- : line.baseline,+ : mid,original: raw.slice(dropLead ? 1 : 0, dropTrail ? -1 : undefined),dropLead,dropTrail,@@ -358,188 +472,166 @@ const lineInk = (li: number,) => spanInk(doc, page, state, li, 0, state.lines[li].words.length - 1);-/** How far the glyphs of a span rise above its baseline. */-const inkTop = (s: SpanInk) => s.ink.body.y + s.ink.body.height - s.baseline;+function inkedLines(doc: EditorDocument, page: Page, state: ScanEditState) {+ return state.lines+ .map((_, li) => ({ li, ink: lineInk(doc, page, state, li) }))+ .filter(+ (l): l is { li: number; ink: SpanInk } =>+ l.ink !== null && l.ink.original.length > 0,+ );+}-// Readers judge size by the lowercase, so mostly-lowercase text is sized by-// its x-height; ascenders, overshoot and blur all read taller than the face.-// OCR's letter case is unreliable, so the scan's own rows decide.-function sizeFor(face: Face, s: SpanInk): number {- if (s.ink.xLine !== null)- return (s.ink.xLine - s.baseline) / (face.xh / 1000);- return inkTop(s) / topShare(face, s.original);+function offInk(doc: EditorDocument, page: Page, state: ScanEditState) {+ state.offInk ??= onOriginalScan(doc, page, state, () => {+ const lines = state.lines.filter((l) => l.words.length > 0);+ if (lines.length === 0 || inkedLines(doc, page, state).length > 0)+ return false;+ return inkBesideOcr(doc, page, lines, otherWords(page, state));+ });+ return state.offInk;}-// Render pixels per scanned pixel under `rect`. A low-res scan scaled up is-// soft however sharp its pixel steps look, so this sets a floor on softness.-function scanPixelSpan(+const fitInput = (doc: EditorDocument,page: Page,- rect: PageRect,-): number {- const m = doc.module;- const cx = rect.x + rect.width / 2;- const cy = rect.y + rect.height / 2;- const under = page.images- .filter(- (img) =>- cx >= img.bounds.x &&- cx <= img.bounds.x + img.bounds.width &&- cy >= img.bounds.y &&- cy <= img.bounds.y + img.bounds.height,- )- .sort(- (p, q) =>- q.bounds.width * q.bounds.height - p.bounds.width * p.bounds.height,- )[0];- if (!under) return 0;- const wPtr = m.pdfium.wasmExports.malloc(4);- const hPtr = m.pdfium.wasmExports.malloc(4);+ state: ScanEditState,+ spans: SpanInk[],+ ref: SpanInk,+): FitInput => ({+ spans,+ ref,+ words: wordsOf(state.lines),+ wordsLookMono: () => faceFor(doc, page, state) === COURIER,+ neighboursLookMono: () => nearbyFace(doc, page, state) === COURIER,+});++const rank = (+ doc: EditorDocument,+ page: Page,+ state: ScanEditState,+ spans: SpanInk[],+ ref: SpanInk,+) => rankStyles(doc, page, fitInput(doc, page, state, spans, ref));++function fittedForOtherPreference(+ doc: EditorDocument,+ state: ScanEditState,+): boolean {+ const block = state.block;+ if (!block || block.drawn) return false;+ const preferred = preferredScanFace(doc);+ return (+ preferred !== null &&+ block.preferred !== preferred &&+ !block.ranked.some((r) => r.face.label === preferred)+ );+}++const undrawableWithFewerFaces = (state: ScanEditState) =>+ state.block === null && state.undrawableWithFaces !== scanFacesGeneration();++export function scanRunNeedsFit(doc: EditorDocument, run: TextRun): boolean {+ if (!isScanRun(run)) return false;+ const state = run.scanEdit;+ return (+ !state ||+ state.block === undefined ||+ undrawableWithFewerFaces(state) ||+ fittedForOtherPreference(doc, state)+ );+}++export function prefitScanRun(+ doc: EditorDocument,+ page: Page,+ run: TextRun,+ deadline: number,+): boolean {+ const state = isScanRun(run) ? scanEditOf(doc, run) : null;+ if (!state || !scanRunNeedsFit(doc, run)) return true;try {- if (!m.FPDFImageObj_GetImagePixelSize(under.pdfiumObjPtr, wPtr, hPtr))- return 0;- const pixels = m.pdfium.getValue(wPtr, "i32");- return pixels > 0 ? (INK_SCALE * under.bounds.width) / pixels : 0;- } catch {- return 0;- } finally {- m.pdfium.wasmExports.free(wPtr);- m.pdfium.wasmExports.free(hPtr);+ withFitDeadline(deadline, () =>+ upright(doc, page, state, () => styleFor(doc, page, state, null)),+ );+ return true;+ } catch (e) {+ if (e === FIT_PAUSED) return false;+ throw e;}}-// The face, weight, size and letter width that redraw `ref` most like the-// scan; the size is shared by every span in `spans`.-function fitStyle(+function referenceSpan(doc: EditorDocument,page: Page,state: ScanEditState,- spans: SpanInk[],- ref: SpanInk,-): ScanStyle | null {- const fit = (face: Face, family: string, k: number) => {- const size = sizeFor(face, ref) * k;- const natural = spanOf(doc, page, ref.original, family, size);- const stretch = clampStretch(ref.ink.body.width / Math.max(1e-3, natural));- return { face, family, size, stretch, k };- };- // Typewriter evidence is sturdier than pixels on a blurry low-res scan, so- // it settles the face; the pixels still pick the weight.- const typewriter =- faceFor(doc, page, state) === COURIER ||- isEvenlySpaced(ref.ink.glyphCenters, ref.original);- // Fit size for both weights before choosing one. Blur and overshoot can- // inflate glyph height enough to favour the wrong face at the initial size.- const faces = typewriter ? [COURIER] : FACES;- const sizes = faces- .flatMap((face) =>- [face.family, face.bold].flatMap((family) =>- [0.88, 0.91, 0.94, 0.97, 1, 1.03].map((k) => fit(face, family, k)),- ),- )- .filter((c) => c.size > 2)- .map((c) => ({- ...c,- score: matchScan(doc, page, ref.ink, {- text: ref.original,- x: ref.ink.body.x,- baseline: ref.baseline,- family: c.family,- size: c.size,- stretch: c.stretch,- }).score,- }));- if (sizes.length === 0) return null;- const best = <T extends { score: number }>(cs: T[]) =>- cs.reduce((p, q) => (q.score > p.score ? q : p));- const floor = Math.round(scanPixelSpan(doc, page, ref.ink.rect) / 2);- // Compare the tuned faces at the scan's softness. Blurring both images- // gives the scan a second blur, which makes regular strokes look bold.- const candidates = faces- .flatMap((face) => [face.family, face.bold])- .map((family) => sizes.filter((c) => c.family === family))- .filter((cs) => cs.length > 0)- .map((cs) => {- const c = best(cs);- const placement = {- text: ref.original,- x: ref.ink.body.x,- baseline: ref.baseline,- family: c.family,- size: c.size,- stretch: c.stretch,- };- const measured = softnessOf(doc, page, ref.ink, placement);- const softness = Math.min(2, Math.max(measured, floor));- const match = matchScan(doc, page, ref.ink, placement, softness);- return {- ...c,- softness,- score: match.score,- strokeRatio: match.weight,- };- });- let chosen = best(candidates);- // A typewritten block nearby tips a close call its way.- const mono = candidates.filter((c) => c.face === COURIER);- if (- !typewriter &&- nearbyFace(doc, page, state) === COURIER &&- best(mono).score > chosen.score - 0.1+ line: { li: number; ink: SpanInk },+): SpanInk {+ if (line.ink.original.length <= REFERENCE_CHARS) return line.ink;+ const words = state.lines[line.li].words;+ let last = 0;+ while (+ last + 1 < words.length &&+ wordEnd(state.lines[line.li], last + 1) <= REFERENCE_CHARS)- chosen = best(mono);- // Regular and bold can have almost the same blurred outlines. Settle close- // matches using stroke thickness, rather than rewarding blur as extra ink.- const weights = candidates.filter(- (c) => c.face === chosen.face && c.score >= chosen.score - 0.1,+ last++;+ if (last < 2) return line.ink;+ return spanInk(doc, page, state, line.li, 0, last) ?? line.ink;+}++function fitBlock(+ doc: EditorDocument,+ page: Page,+ state: ScanEditState,+): ScanEditState["block"] {+ const inked = inkedLines(doc, page, state);+ if (inked.length === 0) return null;+ const spans = inked.map((l) => l.ink);+ const longest = inked.reduce((p, q) =>+ q.ink.original.length > p.ink.original.length ? q : p,);- chosen = weights.reduce((p, q) =>- Math.abs(Math.log(q.strokeRatio)) < Math.abs(Math.log(p.strokeRatio))- ? q- : p,+ const ref = referenceSpan(doc, page, state, longest);+ const ranked = rank(doc, page, state, spans, ref);+ if (ranked.length === 0) return null;+ const xHeights = spans.flatMap((s) =>+ s.ink.xLine === null ? [] : [s.ink.xLine - s.baseline],);- const { softness } = chosen;- // Blur thickens scanned strokes past any bold; add outline until the drawn- // strokes, softened the same way, are as thick as the scanned ones.- // Only past bold: on regular text blur alone would read as extra weight.- const weight = (chosen.family === chosen.face.bold ? [0, 0.025, 0.05] : [0])- .map((k) => k * chosen.size)- .map((w) => ({- w,- ratio: matchScan(- doc,- page,- ref.ink,- {- text: ref.original,- x: ref.ink.body.x,- baseline: ref.baseline,- family: chosen.family,- size: chosen.size,- stretch: chosen.stretch,- weight: w,- },- softness,- ).weight,- }))- .reduce((p, q) =>- Math.abs(Math.log(q.ratio)) < Math.abs(Math.log(p.ratio)) ? q : p,- ).w;- // One size for every line; the median shrugs off a line of lowercase.- const blockSizes = spans- .map((s) => sizeFor(chosen.face, s))- .filter((v) => v > 2);return {- family: chosen.family,- fontSize: blockSizes.length ? median(blockSizes) * chosen.k : chosen.size,- stretch: chosen.stretch,- // Softened text is blurred again, so it starts from the scan's darkest ink.- ink: softness > 0 ? ref.ink.core : ref.ink.fill,- weight,- softness,+ style: ranked[0].style,+ top: median(spans.map(inkTop)),+ xHeight: xHeights.length ? median(xHeights) : null,+ ranked,+ ref,+ preferred: preferredScanFace(doc),};}+function withPreferredFit(+ doc: EditorDocument,+ page: Page,+ state: ScanEditState,+ block: NonNullable<ScanEditState["block"]>,+): ScanEditState["block"] {+ const spans = inkedLines(doc, page, state).map((l) => l.ink);+ const input = fitInput(doc, page, state, spans, block.ref);+ return {+ ...block,+ ranked: withPreferredFace(doc, page, input, block.ranked),+ preferred: preferredScanFace(doc),+ };+}++export function drawnBlockStyle(+ doc: EditorDocument,+ state: ScanEditState,+): ScanStyle | null {+ const block = state.block;+ if (!block) return null;+ if (block.drawn) return block.style;+ return preferredStyle(doc, block.ranked) ?? block.style;+}++const X_HEIGHT_ONLY = /^[acemnorsuvwxz\s\p{P}]+$/u;+// One style for the whole block, fitted to its longest line, so an edit never// switches face or size part way through a sentence. Only text the scan itself// sets at another size (a label and its value on one OCR line) gets its own.@@ -549,24 +641,44 @@ function styleFor(state: ScanEditState,span: SpanInk | null,): ScanStyle | null {+ return onOriginalScan(doc, page, state, () =>+ styleOnScan(doc, page, state, span),+ );+}++function styleOnScan(+ doc: EditorDocument,+ page: Page,+ state: ScanEditState,+ span: SpanInk | null,+): ScanStyle | null {+ if (undrawableWithFewerFaces(state)) state.block = undefined;if (state.block === undefined) {- const lines = state.lines- .map((_, li) => lineInk(doc, page, state, li))- .filter((s): s is SpanInk => s !== null && s.original.length > 0);- const ref = lines.length- ? lines.reduce((p, q) => (q.original.length > p.original.length ? q : p))- : null;- const style = ref ? fitStyle(doc, page, state, lines, ref) : null;- state.block = style ? { style, top: median(lines.map(inkTop)) } : null;+ state.block = fitBlock(doc, page, state);+ if (state.block === null) state.undrawableWithFaces = scanFacesGeneration();}- if (!state.block || !span) return state.block?.style ?? null;+ if (state.block && fittedForOtherPreference(doc, state))+ state.block = withPreferredFit(doc, page, state, state.block);+ const block = state.block;+ const blockStyle = drawnBlockStyle(doc, state);+ if (!block || !blockStyle) return null;+ if (!span) return blockStyle;const top = inkTop(span);const near = (t: number) => Math.abs(top / t - 1) < 0.25;- if (near(state.block.top)) return state.block.style;+ if (near(block.top)) return blockStyle;+ if (+ block.xHeight !== null &&+ X_HEIGHT_ONLY.test(span.original) &&+ near(block.xHeight)+ )+ return blockStyle;const known = state.classes.find((c) => near(c.top));if (known) return known.style;- const style = fitStyle(doc, page, state, [span], span);- if (!style) return state.block.style;+ const ranked = rank(doc, page, state, [span], span);+ if (ranked.length === 0) return block.style;+ const style = block.drawn+ ? ranked[0].style+ : (preferredStyle(doc, ranked) ?? ranked[0].style);state.classes.push({ style, top });return style;}@@ -580,43 +692,6 @@ function linePitch(state: ScanEditState, style: ScanStyle): number {return gaps.length ? median(gaps) : style.fontSize * 1.25;}-function lift(m: WrappedPdfiumModule, page: Page, word: ScanWord): void {- removeMemberPtrs(- m,- page,- [word.ptr, ...(word.extraPtrs ?? [])],- new Map([[word.ptr, word.container]]),- 0,- );-}--// Invisible OCR text for a word, so search and copy still find it.-function emitInvisible(- doc: EditorDocument,- page: Page,- state: ScanEditState,- word: ScanWord,- x: number,- baseline: number,- tagMarks: readonly TagMark[],-): number[] {- const ptrs = emitTextLine({- doc,- page,- text: word.text.trimEnd() || word.text,- x,- y: baseline,- fontSize: word.fontSize,- fill: BLACK,- originalFontPtr: state.fontPtr,- fallbackFamily: "Helvetica",- renderMode: INVISIBLE,- tags: uniformTags(tagMarks),- });- opaqueStroke(doc.module, ptrs);- return ptrs;-}-/** Typical gap between neighbouring words in the block. */function wordSpace(state: ScanEditState, style: ScanStyle): number {const gaps = state.lines.flatMap((l) =>@@ -628,17 +703,39 @@ function wordSpace(state: ScanEditState, style: ScanStyle): number {return gaps.length ? median(gaps) : style.fontSize * 0.28;}-function fallbackStyle(state: ScanEditState): ScanStyle {+function fallbackStyle(+ state: ScanEditState,+ ink = BLACK,+ text = state.lines.map((l) => l.text).join(" "),+): ScanStyle {+ const face = scanFaces().find((f) => faceCovers(f, text)) ?? HELVETICA;return {- family: HELVETICA.family,- fontSize: state.lines[0].height / (HELVETICA.cap / 1000),+ family: face.family,+ fontSize: state.lines[0].height / (face.cap / 1000),stretch: 1,- ink: BLACK,+ ink,weight: 0,+ hollow: 0,softness: 0,};}+function inkAgainst(+ m: WrappedPdfiumModule,+ page: Page,+ state: ScanEditState,+): RGBA {+ const line = state.lines[0];+ const { x0, x1 } = lineExtent(line);+ const { fill } = sampleBackground(m, page, {+ x: x0,+ y: line.baseline - line.height * 0.2,+ width: x1 - x0,+ height: line.height * 1.2,+ });+ return luma(fill.r, fill.g, fill.b) < 128 ? WHITE : BLACK;+}+// The scanned pixels of one word, copied once: the scan under a word never// changes, only what is drawn over it.function patchOf(@@ -653,6 +750,89 @@ function patchOf(return state.patches.get(key) ?? null;}+function atlasOf(+ doc: EditorDocument,+ page: Page,+ state: ScanEditState,+ needed: Set<string>,+): GlyphAtlas | null {+ const known = state.atlasChars ?? new Set<string>();+ if (state.atlas !== undefined && [...needed].every((ch) => known.has(ch)))+ return state.atlas;+ const chars = new Set([...known, ...needed]);+ const top = state.block?.top ?? state.lines[0].height;+ const pitch =+ state.lines.length > 1 ? linePitch(state, fallbackStyle(state)) : Infinity;+ const descent = top * 0.35;+ const frame = Math.min(top * 1.45, pitch * 0.95);+ const words: ScannedWord[] = [];+ state.lines.forEach((line, li) =>+ line.words.forEach((word, wi) => {+ if (![...word.text].some((ch) => chars.has(ch))) return;+ const span = spanInk(doc, page, state, li, wi, wi);+ if (!span || inkTop(span) > top * 1.3) return;+ const patch = capturePatch(doc.module, page, {+ x: span.ink.rect.x,+ y: span.baseline - descent,+ width: span.ink.rect.width,+ height: frame,+ });+ if (!patch) return;+ toInkOnly(patch, span.paper, span.ink.reversed);+ words.push({+ text: span.original.replace(/\s+/g, ""),+ rgba: patch.rgba,+ width: patch.width,+ height: patch.height,+ left: patch.rect.x,+ scale: patch.width / patch.rect.width,+ spans: span.ink.glyphSpans,+ });+ }),+ );+ state.atlas = buildGlyphAtlas(words, descent);+ state.atlasChars = chars;+ return state.atlas;+}++function styleCovers(style: ScanStyle, text: string): boolean {+ const face = scanFaces().find(+ (f) => f.family === style.family || f.bold === style.family,+ );+ return !face || faceCovers(face, text);+}++function implausibleLine(line: ScanLine): boolean {+ const chars = line.text.replace(/\s/g, "").length;+ if (chars <= 3 || line.words.length === 0) return false;+ const { x0, x1 } = lineExtent(line);+ return x1 - x0 < chars * line.height * 0.15;+}++function extraSpacesBefore(line: ScanLine, w: ScanWord, index: number) {+ const upTo = w.start + w.text.length - w.text.trimStart().length;+ const before = line.text.slice(0, upTo);+ const spaces = before.length - before.trimEnd().length;+ return Math.max(0, spaces - (index === 0 ? 0 : 1));+}++const UNSHAPED_SCRIPT =+ /[\u0590-\u08ff\u0d00-\u0d7f\u0f00-\u0fff\ufb1d-\ufdff\ufe70-\ufeff]/u;++function keepsOnlyScannedWords(state: ScanEditState, text: string): boolean {+ const words = state.lines+ .flatMap((l) => l.words.map((w) => w.text.trim()))+ .filter(Boolean);+ let i = 0;+ return text+ .split(/\s+/)+ .filter(Boolean)+ .every((token) => {+ while (i < words.length && words[i] !== token) i++;+ return i++ < words.length;+ });+}+// Make the page show `text` for this run. Words the user kept stay the scan's// own pixels, moved as a copy when something before them changed width or// wrapped; typed words are drawn in the block's style; removed ones covered.@@ -662,82 +842,291 @@ export function renderScanEdit(run: TextRun,state: ScanEditState,text: string,-): void {- const m = doc.module;- for (const p of state.created) removeAndDestroyObject(m, page.pagePtr, p);- state.created = [];- state.textPtrs = [];+): boolean {+ const drawn = upright(doc, page, state, () =>+ renderUprightScanEdit(doc, page, run, state, text),+ );+ if (drawn && state.block && !state.block.drawn)+ state.block = {+ ...state.block,+ style: preferredStyle(doc, state.block.ranked) ?? state.block.style,+ drawn: true,+ };+ return drawn;+}- const o = state.override;- const restyle =- o.family !== undefined || o.fontSize !== undefined || o.fill !== undefined;- const block = styleFor(doc, page, state, null) ?? fallbackStyle(state);+interface EditStyles {+ blockFit: () => ScanStyle | null;+ fitted: () => ScanStyle;+ /** The fitted block style if anything has asked for it yet, without fitting. */+ fittedSoFar: () => ScanStyle | undefined;+ styleOf: (anchor: LayoutWord | null) => ScanStyle;+ inkOf: (w: LayoutWord) => SpanInk | null;+}++function anchorBase(+ o: ScanOverride,+ own: ScanStyle,+ blockStyle: ScanStyle,+): ScanStyle {+ if (own === blockStyle) return o.style ?? blockStyle;+ if (!o.style) return own;+ const scale = own.fontSize / blockStyle.fontSize;+ return {+ ...o.style,+ fontSize: o.style.fontSize * scale,+ weight: o.style.weight * scale,+ hollow: o.style.hollow * scale,+ ink: own.ink,+ };+}++function withOverride(o: ScanOverride, base: ScanStyle): ScanStyle {+ const newFamily = o.family !== undefined;+ return {+ family: o.family ?? base.family,+ fontSize: o.fontSize ?? base.fontSize,+ ink: o.fill ?? base.ink,+ stretch: newFamily ? 1 : base.stretch,+ weight: newFamily ? 0 : base.weight,+ hollow: newFamily ? 0 : base.hollow,+ softness: base.softness,+ };+}++// Lazy: fitting renders the scan, and an edit that only deletes words needs no style.+function editStyles(+ doc: EditorDocument,+ page: Page,+ state: ScanEditState,+ o: ScanOverride,+ text: string,+): EditStyles {+ let blockFitted: ScanStyle | null | undefined;+ const blockFit = () =>+ blockFitted === undefined+ ? (blockFitted = styleFor(doc, page, state, null))+ : blockFitted;+ let fittedStyle: ScanStyle | undefined;+ const fitted = () =>+ (fittedStyle ??=+ blockFit() ??+ fallbackStyle(state, inkAgainst(doc.module, page, state), text));const inkOf = (w: LayoutWord) =>spanInk(doc, page, state, w.line, w.index, w.index);+ const styles = new Map<LayoutWord | null, ScanStyle>();const styleOf = (anchor: LayoutWord | null): ScanStyle => {- const base =- styleFor(doc, page, state, anchor ? inkOf(anchor) : null) ?? block;- return {- family: o.family ?? base.family,- fontSize: o.fontSize ?? base.fontSize,- ink: o.fill ?? base.ink,- stretch: o.family !== undefined ? 1 : base.stretch,- weight: o.family !== undefined ? 0 : base.weight,- softness: base.softness,- };+ const known = styles.get(anchor);+ if (known) return known;+ const blockStyle = fitted();+ const own =+ styleFor(doc, page, state, anchor ? inkOf(anchor) : null) ?? blockStyle;+ const style = withOverride(o, anchorBase(o, own, blockStyle));+ styles.set(anchor, style);+ return style;+ };+ return {+ blockFit,+ fitted,+ fittedSoFar: () => fittedStyle,+ styleOf,+ inkOf,+ };+}++interface ScanGlyphSource {+ atlas: () => GlyphAtlas | null;+ composed: (text: string) => ComposedText | null;+ /** The letters the edit types, read when the atlas is first built. */+ setTyped: (chars: Iterable<string>) => void;+}++function scanGlyphSource(+ doc: EditorDocument,+ page: Page,+ state: ScanEditState,+ enabled: boolean,+ fitBlock: () => unknown,+ space: number,+): ScanGlyphSource {+ let atlasMemo: GlyphAtlas | null | undefined;+ let typed = new Set<string>();+ const atlas = () => {+ if (atlasMemo !== undefined) return atlasMemo;+ if (!enabled) return (atlasMemo = null);+ fitBlock();+ return (atlasMemo = atlasOf(doc, page, state, typed));};+ const cache = new Map<string, ComposedText | null>();+ const composed = (t: string) => {+ const a = atlas();+ if (!a) return null;+ if (!cache.has(t)) cache.set(t, composeText(a, t, space * a.scale));+ return cache.get(t) ?? null;+ };+ return {+ atlas,+ composed,+ setTyped: (chars) => {+ typed = new Set(chars);+ },+ };+}++function renderUprightScanEdit(+ doc: EditorDocument,+ page: Page,+ run: TextRun,+ state: ScanEditState,+ text: string,+): boolean {+ const m = doc.module;+ if (state.lines.some(implausibleLine) || offInk(doc, page, state)) {+ const original = state.lines.map((l) => l.text).join(" ");+ recordUndrawableChars(+ [...text].filter((ch) => !original.includes(ch)).join(""),+ );+ return false;+ }++ const shift = state.frame+ ? applyVector(state.frame.toUpright, state.override.dx, state.override.dy)+ : { dx: state.override.dx, dy: state.override.dy };+ const o = { ...state.override, ...shift };+ const restyle =+ o.family !== undefined || o.fontSize !== undefined || o.fill !== undefined;+ const needsFont = restyle || !keepsOnlyScannedWords(state, text);+ const styles = editStyles(doc, page, state, o, text);+ const { blockFit, fitted, styleOf, inkOf } = styles;+ const spacing = o.style ?? (needsFont ? fitted() : fallbackStyle(state));const lineBase = (li: number) =>lineInk(doc, page, state, li)?.baseline ?? state.lines[li].baseline;const scanWord = (w: LayoutWord) => state.lines[w.line].words[w.index];+ const space = wordSpace(state, spacing);+ const glyphSource = scanGlyphSource(+ doc,+ page,+ state,+ !restyle && !o.style,+ blockFit,+ space,+ );+ const { atlas, composed } = glyphSource;+ const canDraw = (t: string) =>+ !UNSHAPED_SCRIPT.test(t) &&+ (!!composed(t) ||+ !!o.style ||+ o.family !== undefined ||+ !!blockFit() ||+ scanFaces().some((f) => faceCovers(f, t)));++ const inkWidth = (w: LayoutWord) =>+ inkOf(w)?.ink.body.width ?? scanWord(w).right - scanWord(w).x;+ const shows = (t: string, anchor: LayoutWord | null) =>+ !!composed(t) || styleCovers(styleOf(anchor), t);+ // Text no face can show keeps the scanned words it replaces, so it spans them.+ const keptWidth = (anchor: LayoutWord, replaced: LayoutWord[]) => {+ const last =+ replaced.filter((w) => w.line === anchor.line).at(-1) ?? anchor;+ return last.x + inkWidth(last) - anchor.x;+ };- const layout = layoutScanEdit({- lines: state.lines.map((l, li) => ({+ const plan = onOriginalScan(doc, page, state, () => {+ const lines = state.lines.map((l, li) => ({baseline: lineBase(li),words: l.words.map((w, wi) => ({line: li,index: wi,text: w.text.trim(),x: w.x,+ lead: extraSpacesBefore(l, w, wi),})),- })),- text,- pitch: linePitch(state, block),- space: wordSpace(state, block),- wordWidth: (w) =>- inkOf(w)?.ink.body.width ?? scanWord(w).right - scanWord(w).x,- textWidth: (t, anchor) => {- const st = styleOf(anchor);- return spanOf(doc, page, t, st.family, st.fontSize) * st.stretch;- },- redraw: restyle,+ }));+ const pitch = linePitch(state, spacing);+ glyphSource.setTyped(+ layoutScanEdit({+ lines,+ text,+ pitch,+ space,+ wordWidth: (w) => scanWord(w).right - w.x,+ textWidth: () => 0,+ redraw: restyle,+ }).typed.flatMap((t) => [...t.text.replace(/\s+/g, "")]),+ );+ const layout = layoutScanEdit({+ lines,+ text,+ pitch,+ space,+ wordWidth: inkWidth,+ textWidth: (t, anchor, replaced) => {+ if (!shows(t, anchor)) return anchor ? keptWidth(anchor, replaced) : 0;+ const glyphs = composed(t);+ const a = atlas();+ if (glyphs && a) return (glyphs.inkRight - glyphs.inkLeft) / a.scale;+ const st = styleOf(anchor);+ return spanOf(doc, page, t, st.family, st.fontSize) * st.stretch;+ },+ redraw: restyle,+ });++ // A whole-block move shifts everything, kept pixels included.+ const shifted = o.dx !== 0 || o.dy !== 0;+ const kept = layout.kept.map((k) => ({+ ...k,+ x: k.x + o.dx,+ baseline: k.baseline + o.dy,+ moved: k.moved || shifted,+ }));+ const moving = kept+ .filter((k) => k.moved)+ .map((k) => {+ const ink = inkOf(k.word);+ const key = `${k.word.line}:${k.word.index}`;+ return {+ ...k,+ ink,+ patch: ink ? patchOf(doc, page, state, key, ink) : null,+ };+ });++ const drawn = [+ ...layout.typed.map((t) => ({ text: t.text, anchor: t.anchor })),+ ...moving+ .filter((k) => !k.patch)+ .map((k) => ({ text: k.word.text, anchor: k.word })),+ ];+ const refused = drawn.filter((d) => !canDraw(d.text));+ if (refused.length > 0) {+ recordUndrawableChars(refused.map((d) => d.text).join(""));+ return null;+ }+ for (const d of drawn) styleOf(d.anchor);+ const unshown = new Set(+ layout.typed.filter((t) => !shows(t.text, t.anchor)),+ );+ if (unshown.size > 0)+ recordUndrawableChars(+ [...unshown].map((t) => t.text.replace(/\s+/g, "")).join(""),+ );+ return { layout, kept, moving, unshown };});+ if (!plan) return false;+ const { layout, kept, moving, unshown } = plan;+ const keptScan = new Set([...unshown].flatMap((t) => t.replaced));- // A whole-block move shifts everything, kept pixels included.- const shifted = o.dx !== 0 || o.dy !== 0;- const kept = layout.kept.map((k) => ({- ...k,- x: k.x + o.dx,- baseline: k.baseline + o.dy,- moved: k.moved || shifted,- }));- const typed = layout.typed.map((t) => ({- ...t,- x: t.x + o.dx,- baseline: t.baseline + o.dy,- }));-- // Copy every moving word's pixels before anything is drawn over them.- const moving = kept- .filter((k) => k.moved)- .map((k) => {- const ink = inkOf(k.word);- const key = `${k.word.line}:${k.word.index}`;- return {- ...k,- ink,- patch: ink ? patchOf(doc, page, state, key, ink) : null,- };- });+ for (const p of state.created) removeAndDestroyObject(m, page.pagePtr, p);+ state.created = [];+ state.textPtrs = [];+ const canvas: Canvas = {+ doc,+ page,+ tagMarks: run.tagMarks,+ created: state.created,+ textPtrs: state.textPtrs,+ searchableFontPtr: state.fontPtr,+ };// Cover what was removed or moved away.const coverWord = (w: LayoutWord) => {@@ -746,7 +1135,7 @@ export function renderScanEdit(const line = state.lines[w.line];const rect = ink?.ink.rect ?? {x: sw.x - 0.5,- y: line.baseline - line.height * 0.35,+ y: sw.baseline - line.height * 0.35,width: sw.right - sw.x + 1,height: line.height * 1.7,};@@ -754,16 +1143,54 @@ export function renderScanEdit(const ptr = emitFillRect(m, page, rect, paper, 0);if (ptr) state.created.push(ptr);};- for (const w of layout.removed) coverWord(w);+ for (const w of layout.removed) if (!keptScan.has(w)) coverWord(w);for (const k of moving) coverWord(k.word);- const drawText = (+ const nextWordLimit = (start: number, baseline: number, size: number) => {+ const next = kept+ .filter((k) => Math.abs(k.baseline - baseline) < 1 && k.x > start + 0.5)+ .map((k) => k.x);+ return next.length === 0 ? Infinity : Math.min(...next) - wordGap(size);+ };++ const baselineAt = (li: number, x: number) => {+ const words = state.lines[li].words;+ const centres = words.map((w) => (w.x + w.right) / 2);+ const mean = words.reduce((sum, w) => sum + w.baseline, 0) / words.length;+ const correction = lineBase(li) - mean;+ const after = centres.findIndex((c) => c >= x);+ if (after <= 0)+ return words[after < 0 ? words.length - 1 : 0].baseline + correction;+ const a = words[after - 1];+ const b = words[after];+ const t =+ (x - centres[after - 1]) / (centres[after] - centres[after - 1] || 1);+ return a.baseline + (b.baseline - a.baseline) * t + correction;+ };+ const baselineFor = (+ li: number,+ layoutBaseline: number,+ x: number,+ anchor: LayoutWord | null,+ ) => {+ if (li >= state.lines.length) return layoutBaseline;+ const shift = layoutBaseline - lineBase(li);+ if (anchor && anchor.line === li)+ return (inkOf(anchor)?.baseline ?? scanWord(anchor).baseline) + shift;+ return baselineAt(li, x - o.dx) + shift;+ };++ let fromAtlas = 0;+ let inFont = 0;+ const drawTyped = (t: string,x: number,- baseline: number,+ line: number,+ layoutBaseline: number,anchor: LayoutWord | null,atAnchor: boolean,) => {+ const baseline = baselineFor(line, layoutBaseline, x, anchor);const ink = anchor ? inkOf(anchor) : null;let s = t;// OCR reads a box edge hugging the text as a bracket; never draw it.@@ -771,156 +1198,108 @@ export function renderScanEdit(if (ink?.dropTrail) s = s.replace(/[\]|)]$/, "");if (!s) return;const st = styleOf(anchor);- const ptrs = placeText(doc, page, {- text: s,- x,- baseline,- family: st.family,- size: st.fontSize,- stretch: st.stretch,- inkLeft: atAnchor && ink ? ink.ink.body.x + o.dx : x,- fill: st.ink,- weight: st.weight,- });- const soft =- st.softness > 0- ? softened(ptrs, st, baseline, ink?.ink.rect, ink?.paper)- : null;- if (soft) {- for (const p of ptrs) removeAndDestroyObject(m, page.pagePtr, p);- // Searchable still: the visible copy is now a picture.- const hidden = emitTextLine({- doc,- page,- text: s,- x,- y: baseline,- fontSize: st.fontSize,- fill: BLACK,- originalFontPtr: 0,- fallbackFamily: st.family,- renderMode: INVISIBLE,- tags: uniformTags(run.tagMarks),- });- opaqueStroke(m, hidden);- state.created.push(soft, ...hidden);- state.textPtrs.push(...hidden);+ const start = atAnchor && ink ? ink.ink.body.x + o.dx : x;+ const limit = nextWordLimit(start, layoutBaseline, st.fontSize);+ const glyphs = composed(s);+ const a = atlas();+ if (+ a &&+ glyphs &&+ drawFromAtlas(canvas, a, glyphs, s, start, baseline, st, limit)+ ) {+ fromAtlas++;return;}- state.created.push(...ptrs);- state.textPtrs.push(...ptrs);- };-- // Crisp vector text on a blurry scan stands out, so blurry blocks get their- // typed words as a picture softened to match.- const softened = (- ptrs: number[],- st: ScanStyle,- baseline: number,- /** The scanned word replaced: the copy stays within its height. */- within?: PageRect,- /** The paper under the text, which the copy leaves transparent. */- paper?: RGBA,- ): number => {- const span = measureObjSpanPt(m, ptrs);- if (!span) return 0;- // Just the glyphs and the blur's reach: a taller copy would also blur a- // rule or the next line's ink sitting close above or below.- const margin = st.softness / 4 + 0.25;- const rect = {- x: span.left - margin,- y: baseline - st.fontSize * 0.25 - margin,- width: span.right - span.left + margin * 2,- height: st.fontSize * 1.03 + margin * 2,- };- if (within) {- const top = Math.min(rect.y + rect.height, within.y + within.height);- const bottom = Math.max(rect.y, within.y);- if (top > bottom)- Object.assign(rect, { y: bottom, height: top - bottom });- }- const patch = capturePatch(m, page, rect);- if (!patch) return 0;- blurRgba(patch, st.softness);- toInkOnly(patch, paper ?? sampleBackground(m, page, rect).fill);- const img = createBitmapImageObject(- m,- doc.docPtr,- page.pagePtr,- patch,- patch.rect.x,- patch.rect.y,- patch.rect.width,- patch.rect.height,- );- if (!img) return 0;- m.FPDFPage_InsertObject(page.pagePtr, img);- return img;+ inFont++;+ drawInFont(canvas, s, x, start, baseline, st, limit);};// Moved words: the scan's own pixels at their new spot, plus invisible text.for (const k of moving) {const sw = scanWord(k.word);- const dx = k.x - sw.x;- const dy = k.baseline - lineBase(k.word.line);if (!k.patch) {- drawText(k.word.text, k.x, k.baseline, k.word, false);+ drawTyped(k.word.text, k.x, k.line, k.baseline, k.word, false);continue;}- const r = k.patch.rect;const inkOnly = { ...k.patch, rgba: k.patch.rgba.slice() };- if (k.ink) toInkOnly(inkOnly, k.ink.paper);- const img = createBitmapImageObject(- m,- doc.docPtr,- page.pagePtr,- inkOnly,- r.x + dx,- r.y + dy,- r.width,- r.height,- );- if (img) {- m.FPDFPage_InsertObject(page.pagePtr, img);- state.created.push(img);- }- const hidden = emitInvisible(- doc,- page,- state,- sw,- k.x,- k.baseline,- run.tagMarks,+ if (k.ink) toInkOnly(inkOnly, k.ink.paper, k.ink.ink.reversed);+ const r = k.patch.rect;+ pasteImage(canvas, inkOnly, {+ ...r,+ x: r.x + k.x - sw.x,+ y: r.y + k.baseline - lineBase(k.word.line),+ });+ emitSearchable(+ canvas,+ sw.text.trimEnd() || sw.text,+ { left: k.x, right: k.x + sw.right - sw.x },+ sw.baseline + k.baseline - lineBase(k.word.line),+ sw.fontSize,+ { originalFontPtr: state.fontPtr, family: "Helvetica" },);- state.created.push(...hidden);- state.textPtrs.push(...hidden);}- for (const t of typed)- drawText(t.text, t.x, t.baseline, t.anchor, t.atAnchor);-- // Original OCR words leave the page when removed or moved, and come back- // when an undo puts them where they were.- const gone = new Set(- [...layout.removed, ...moving.map((k) => k.word)].map(- (w) => `${w.line}:${w.index}`,+ for (const t of layout.typed)+ if (!unshown.has(t))+ drawTyped(+ t.text,+ t.x + o.dx,+ t.line,+ t.baseline + o.dy,+ t.anchor,+ t.atAnchor,+ );++ syncOriginalWords(+ canvas,+ state,+ new Set(+ [+ ...layout.removed.filter((w) => !keptScan.has(w)),+ ...moving.map((k) => k.word),+ ].map((w) => `${w.line}:${w.index}`),),);+ attachToRun(run, state);+ state.edited = true;+ state.typedFromScan = fromAtlas > 0 && inFont === 0;+ // Show what is drawn, not OCR's guesses, so the size and colour controls start from it.+ const shown = o.style ?? styles.fittedSoFar();+ run.fontSize = o.fontSize ?? shown?.fontSize ?? run.fontSize;+ run.fill = o.fill ?? shown?.ink ?? run.fill;+ run.text = text;+ run.dirty = true;+ page.markDirty();+ page.markNeedsGenerate();+ return true;+}++// Original OCR words leave the page when removed or moved, and return when an undo puts them back.+function syncOriginalWords(+ canvas: Canvas,+ state: ScanEditState,+ gone: Set<string>,+): void {+ const { doc, page } = canvas;state.lines.forEach((line, li) =>line.words.forEach((word, wi) => {const key = `${li}:${wi}`;if (gone.has(key) && !state.lifted.has(key)) {- lift(m, page, word);+ removeMemberPtrs(+ doc.module,+ page,+ [word.ptr, ...(word.extraPtrs ?? [])],+ new Map([[word.ptr, word.container]]),+ 0,+ );state.lifted.add(key);} else if (!gone.has(key) && state.lifted.has(key)) {- const back = emitInvisible(- doc,- page,- state,- word,- word.x,- line.baseline,- run.tagMarks,+ const back = invisibleText(+ canvas,+ word.text.trimEnd() || word.text,+ { left: word.x, right: word.right },+ word.baseline,+ word.fontSize,+ { originalFontPtr: state.fontPtr, family: "Helvetica" },);word.ptr = back[0] ?? 0;word.extraPtrs = back.slice(1);@@ -929,9 +1308,10 @@ export function renderScanEdit(}}),);+}- // Deleting the run takes the drawn text and the remaining OCR words with it;- // the covers stay, since the scan under them is the old text.+// Deleting the run takes its drawn text and OCR words; the covers stay, as the scan under them is the old text.+function attachToRun(run: TextRun, state: ScanEditState): void {const live = state.lines.flatMap((l, li) =>l.words.filter((_, wi) => !state.lifted.has(`${li}:${wi}`)),);@@ -943,14 +1323,6 @@ export function renderScanEdit(...live.flatMap((w) => [w.container, ...(w.extraPtrs ?? []).map(() => 0)]),...state.textPtrs.map(() => 0),];- // Show what is drawn, not OCR's guesses, so size and colour controls start- // from the right values.- run.fontSize = o.fontSize ?? block.fontSize;- run.fill = o.fill ?? block.ink;- run.text = text;- run.dirty = true;- page.markDirty();- page.markNeedsGenerate();}/** The run's scan-edit state, captured on first use; null when it has none. */@@ -959,10 +1331,91 @@ export function scanEditOf(run: TextRun,): ScanEditState | null {if (!isScanRun(run)) return run.scanEdit;- run.scanEdit ??= captureScanEdit(doc.module, run);+ run.scanEdit ??= captureScanEdit(doc.module, run, doc.page(run.pageIndex));return run.scanEdit;}+/** The run's text reflowed to `maxWidthPt` in its drawn style, or null for non-scanned text; a line is added below only where the page is clear. */+export function wrapScanText(+ doc: EditorDocument,+ page: Page,+ run: TextRun,+ maxWidthPt: number,+): string | null {+ const state = scanEditOf(doc, run);+ if (!state || state.lines.length === 0) return null;+ const style = withOverride(+ state.override,+ state.override.style ?? drawnBlockStyle(doc, state) ?? fallbackStyle(state),+ );+ const width = (line: string) =>+ spanOf(doc, page, line, style.family, style.fontSize) * style.stretch;+ const fits = (line: string) => line === "" || width(line) <= maxWidthPt;+ const grown = rewrapLines(run.text, fits, true);+ const wrapped = roomBelow(+ page,+ run,+ state,+ linePitch(state, style),+ grown.split("\n").length,+ )+ ? grown+ : rewrapLines(run.text, fits, false);+ // All or nothing: without room for the last line's overflow the text would just stick out on another line.+ const settled = wrapped+ .split("\n")+ .every((line) => fits(line.trim()) || !line.trim().includes(" "));+ return settled ? wrapped : run.text;+}++function roomBelow(+ page: Page,+ run: TextRun,+ state: ScanEditState,+ pitch: number,+ lineCount: number,+): boolean {+ const added = lineCount - state.lines.length;+ if (added <= 0) return true;+ // Lines of a turned block are not in the page space other runs are in.+ if (state.frame) return false;+ const last = state.lines[state.lines.length - 1];+ const bottom = last.baseline - added * pitch - last.height * 0.35;+ const top = last.baseline - last.height * 0.35;+ const left = Math.min(...state.lines.map((l) => l.words[0]?.x ?? Infinity));+ const right = Math.max(+ ...state.lines.map((l) => l.words[l.words.length - 1]?.right ?? -Infinity),+ );+ return !page.runs.some((other) => {+ if (other === run) return false;+ const b = other.bounds;+ return (+ b.x < right &&+ b.x + b.width > left &&+ b.y < top &&+ b.y + b.height > bottom+ );+ });+}++function upright<T>(+ doc: EditorDocument,+ page: Page,+ state: ScanEditState,+ fn: () => T,+): T {+ const frame = state.frame;+ if (!frame || state.upright) return fn();+ moveAllObjects(doc.module, page, frame.toUpright);+ state.upright = true;+ try {+ return fn();+ } finally {+ state.upright = false;+ moveAllObjects(doc.module, page, frame.fromUpright);+ }+}+/** The size the block is drawn at, fitting its style first if need be. */export function scanDrawnSize(doc: EditorDocument,@@ -973,7 +1426,11 @@ export function scanDrawnSize(if (!state) return null;return (state.override.fontSize ??- (styleFor(doc, page, state, null) ?? fallbackStyle(state)).fontSize+ state.override.style?.fontSize ??+ (+ upright(doc, page, state, () => styleFor(doc, page, state, null)) ??+ fallbackStyle(state)+ ).fontSize);}@@ -994,3 +1451,174 @@ export function setScanOverride(renderScanEdit(doc, page, run, state, run.text);return prev;}++function onOriginalScan<T>(+ doc: EditorDocument,+ page: Page,+ state: ScanEditState,+ fn: () => T,+): T {+ if (state.offScan) return fn();+ const m = doc.module;+ const created = [...state.created];+ for (const p of created) m.FPDFPage_RemoveObject(page.pagePtr, p);+ state.offScan = true;+ try {+ return fn();+ } finally {+ state.offScan = false;+ for (const p of created) m.FPDFPage_InsertObject(page.pagePtr, p);+ }+}++export function scanTypingDropped(run: TextRun): boolean {+ if (!isScanRun(run)) return false;+ const o = run.scanEdit?.override;+ if (o?.style || o?.family !== undefined) return false;+ return (+ UNSHAPED_SCRIPT.test(run.text) ||+ !scanFaces().some((f) => faceCovers(f, run.text))+ );+}++export function scanBlockMisaligned(+ doc: EditorDocument,+ run: TextRun,+): boolean {+ return scanEditOf(doc, run)?.lines.some(implausibleLine) ?? false;+}++export function scanBlockOffInk(doc: EditorDocument, run: TextRun): boolean {+ const state = scanEditOf(doc, run);+ if (!state) return false;+ const page = doc.page(run.pageIndex);+ return upright(doc, page, state, () => offInk(doc, page, state));+}++export function scanBlockUndrawable(+ doc: EditorDocument,+ run: TextRun,+): boolean {+ return scanEditOf(doc, run)?.block === null;+}++export function rerankScanStyles(+ doc: EditorDocument,+ page: Page,+ run: TextRun,+): RankedStyle[] {+ const state = scanEditOf(doc, run);+ if (!state) return [];+ return upright(doc, page, state, () =>+ onOriginalScan(doc, page, state, () => rerank(doc, page, state)),+ );+}++const rankedOf = (state: ScanEditState) => state.block?.ranked ?? [];++/** Ranks the available faces against text the page draws, as a scanned block is ranked; `state` from {@link captureScanEdit} stays off the run, and after FIT_PAUSED the same `state` carries on. */+export function rankFacesForDrawnText(+ doc: EditorDocument,+ page: Page,+ state: ScanEditState,+): RankedStyle[] {+ return upright(doc, page, state, () => {+ if (state.block === undefined) styleFor(doc, page, state, null);+ return rankedOf(state);+ });+}++function rerank(+ doc: EditorDocument,+ page: Page,+ state: ScanEditState,+): RankedStyle[] {+ const before = state.block;+ if (!before) {+ state.block = undefined;+ styleFor(doc, page, state, null);+ return rankedOf(state);+ }+ const spans = inkedLines(doc, page, state).map((l) => l.ink);+ const ranked = rank(doc, page, state, spans, before.ref);+ if (ranked.length === 0) return before.ranked;+ state.block = {+ ...before,+ ranked,+ style: state.created.length > 0 ? before.style : ranked[0].style,+ };+ return ranked;+}++export function previewScanStyle(+ doc: EditorDocument,+ page: Page,+ run: TextRun,+ style: ScanStyle,+): { scan: PixelPatch; drawn: PixelPatch } | null {+ const state = scanEditOf(doc, run);+ const ref = state?.block?.ref;+ if (!state || !ref) return null;+ return upright(doc, page, state, () =>+ onOriginalScan(doc, page, state, () =>+ previewOnScan(doc, page, ref, style),+ ),+ );+}++function previewOnScan(+ doc: EditorDocument,+ page: Page,+ ref: SpanInk,+ style: ScanStyle,+): { scan: PixelPatch; drawn: PixelPatch } | null {+ const m = doc.module;+ const rect = ref.ink.rect;+ const scan = capturePatch(m, page, rect);+ if (!scan) return null;+ const sheet = doc.scratchPageFor(page);+ const cover = emitFillRect(m, sheet.page, rect, ref.paper);+ const ptrs = placeText(sheet.doc, sheet.page, {+ text: ref.original,+ x: ref.ink.body.x,+ baseline: ref.baseline,+ family: style.family,+ size: style.fontSize,+ stretch: style.stretch,+ inkLeft: ref.ink.body.x,+ fill: style.ink,+ weight: style.weight,+ hollow: style.hollow,+ });+ const drawn = capturePatch(m, sheet.page, rect);+ for (const p of [cover, ...ptrs])+ removeAndDestroyObject(m, sheet.page.pagePtr, p);+ if (!drawn) return null;+ if (style.softness > 0) blurRgba(drawn, style.softness);+ return { scan, drawn };+}++/** The font a scanned block's changed words are drawn in. */+export interface ScanDrawnFont {+ /** The family as the font picker names it. */+ family: string;+ /** How the scan matcher names the face, e.g. "Calibri (Carlito)". */+ label: string;+}++/** The font in force for a scanned run (picked, else matched), never the OCR layer's `fontId`; null while unfitted or typed from scan letters. Cheap: captures no scan state. */+export function scanDrawnFont(+ doc: EditorDocument,+ run: TextRun,+): ScanDrawnFont | null {+ const state = run.scanEdit;+ if (!state || state.typedFromScan) return null;+ const family =+ state.override.family ??+ (state.override.style ?? drawnBlockStyle(doc, state))?.family;+ if (!family) return null;+ const face = scanFaces().find(+ (f) => f.family === family || f.bold === family,+ );+ return { family, label: face?.label ?? family };+}diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/EditorSidebar.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/EditorSidebar.tsxindex c683cabd6b..9323fdd444 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/components/EditorSidebar.tsx+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/EditorSidebar.tsx@@ -10,7 +10,10 @@ import { useSelectionGeometry } from "@editor/tools/pdfTextEditor/hooks/useSelecimport { DocumentInspector } from "@editor/tools/pdfTextEditor/components/inspector/DocumentInspector";import { LanguagesInUse } from "@editor/tools/pdfTextEditor/components/inspector/languagesInUse";import { SelectionInspector } from "@editor/tools/pdfTextEditor/components/inspector/SelectionInspector";-import { useSelectedFontNote } from "@editor/tools/pdfTextEditor/hooks/useSelectedFontNote";+import {+ useSelectedFontNote,+ type ScanNote,+} from "@editor/tools/pdfTextEditor/hooks/useSelectedFontNote";import { readAllPagesInBackground } from "@editor/tools/pdfTextEditor/hooks/useDocumentLoader";import { SetMarkedTaggedCommand } from "@editor/tools/pdfTextEditor/commands/SetMarkedTaggedCommand";import { ACCESSIBILITY_EDITING } from "@editor/constants/featureFlags";@@ -19,6 +22,13 @@ import {type ScanHintProps,} from "@editor/tools/pdfTextEditor/components/ScanHint";import type { EditorStore } from "@editor/tools/pdfTextEditor/store/EditorStore";+import { useScanFontMatch } from "@editor/tools/pdfTextEditor/hooks/useScanFontMatch";+import {+ scanBlockMisaligned,+ scanBlockOffInk,+ scanTypingDropped,+} from "@editor/tools/pdfTextEditor/commands/scanTextEdit";+import { ScanFontMatchModal } from "@editor/tools/pdfTextEditor/components/inspector/ScanFontMatchModal";import type {EditorViewState,LoadProgress,@@ -80,7 +90,12 @@ export function EditorSidebar({if (hasSelection) setTab("selected");}, [hasSelection]);- const fontNote = useSelectedFontNote(state, selection);+ const fontNote = useSelectedFontNote(+ state,+ selection,+ selectedScanNote(store, state, selection),+ );+ const scanFontMatch = useScanFontMatch(store, state, selection);const editorDocument = store.document;const reviewingAccessibility = useMemo(@@ -166,6 +181,7 @@ export function EditorSidebar({selection={selection}geometry={geometry}fontNote={fontNote}+ scanFontMatch={scanFontMatch}canGroup={canGroup}canUngroup={canUngroup}onGroup={onGroup}@@ -211,6 +227,7 @@ export function EditorSidebar({</Tabs.Panel></Box></LanguagesInUse.Provider>+ {scanFontMatch && <ScanFontMatchModal match={scanFontMatch} />}</Tabs>);}@@ -241,6 +258,27 @@ function NothingSelected(props: ScanHintProps) {);}+function selectedScanNote(+ store: EditorStore,+ state: EditorViewState,+ selection: SelectionState,+): ScanNote {+ const doc = store.document;+ if (!doc) return null;+ const picked = new Set(selection.runIds);+ const runs = state.pages.flatMap((page) =>+ page.runs.flatMap((r) => {+ if (!picked.has(r.id)) return [];+ const run = doc.page(page.pageIndex).findRun(r.id);+ return run ? [run] : [];+ }),+ );+ if (runs.some((run) => scanBlockMisaligned(doc, run))) return "misaligned";+ if (runs.some((run) => scanBlockOffInk(doc, run))) return "offInk";+ if (runs.some((run) => scanTypingDropped(run))) return "dropsTyping";+ return null;+}+function EmptySidebar({loading,progress,diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/FindBar.test.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/FindBar.test.tsxnew file mode 100644index 0000000000..71bd8b3c9a--- /dev/null+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/FindBar.test.tsx@@ -0,0 +1,157 @@+import { MantineProvider } from "@mantine/core";+import { fireEvent, render, screen, waitFor } from "@testing-library/react";+import { afterEach, describe, expect, it, vi } from "vitest";++vi.mock("@editor/tools/pdfTextEditor/hooks/useDocumentLoader", () => ({+ readAllPagesInBackground: vi.fn(() => () => {}),+}));+vi.mock(+ "@editor/tools/pdfTextEditor/commands/scanTextEdit",+ async (importOriginal) => ({+ ...(await importOriginal<object>()),+ prefitScanRun: vi.fn(() => true),+ scanRunNeedsFit: vi.fn(() => false),+ }),+);++import { FindBar } from "@editor/tools/pdfTextEditor/components/FindBar";+import {+ prefitScanRun,+ scanRunNeedsFit,+} from "@editor/tools/pdfTextEditor/commands/scanTextEdit";+import type { EditorStore } from "@editor/tools/pdfTextEditor/store/EditorStore";+import type { EditTextCommand } from "@editor/tools/pdfTextEditor/commands/EditTextCommand";+import type { PageSnapshot } from "@editor/tools/pdfTextEditor/types";++function setup() {+ const runs = [+ { id: "a", text: "Invoice for Jane", locked: false },+ { id: "b", text: "Jane Example", locked: false },+ ];+ const page = {+ index: 0,+ runs,+ findRun: (id: string) => runs.find((r) => r.id === id),+ };+ const dispatch = vi.fn();+ const store = {+ dispatch,+ document: { loadedPages: () => [page] },+ selection: {+ selectOne: vi.fn(),+ highlight: { set: vi.fn() },+ },+ } as unknown as EditorStore;+ const pages = [{ pageIndex: 0, runs }] as unknown as PageSnapshot[];+ render(+ <MantineProvider env="test">+ <FindBar store={store} pages={pages} onClose={vi.fn()} />+ </MantineProvider>,+ );+ return { dispatch, runs };+}++describe("Replace all on unfitted scanned text", () => {+ afterEach(() => {+ vi.mocked(prefitScanRun).mockReset().mockReturnValue(true);+ vi.mocked(scanRunNeedsFit).mockReset().mockReturnValue(false);+ });++ it("fits each scanned block in slices while busy, then replaces", async () => {+ const fitted = new Set<string>();+ let calls = 0;+ vi.mocked(scanRunNeedsFit).mockImplementation(+ (_doc, r) => !fitted.has(r.id),+ );+ vi.mocked(prefitScanRun).mockImplementation((_doc, _page, r) => {+ calls++;+ if (calls % 2 === 1) return false;+ fitted.add(r.id);+ return true;+ });+ const { dispatch } = setup();+ fireEvent.change(screen.getByTestId("pdf-editor-find-input"), {+ target: { value: "Jane" },+ });+ fireEvent.change(screen.getByTestId("pdf-editor-replace-input"), {+ target: { value: "Mary" },+ });++ fireEvent.click(screen.getByTestId("pdf-editor-replace-all"));++ expect(dispatch).not.toHaveBeenCalled();+ expect(screen.getByTestId("pdf-editor-replace-all")).toBeDisabled();+ await waitFor(() => expect(dispatch).toHaveBeenCalledTimes(1));+ expect(fitted).toEqual(new Set(["a", "b"]));+ for (const [, , , deadline] of vi.mocked(prefitScanRun).mock.calls)+ expect(Number.isFinite(deadline)).toBe(true);+ });++ it("replaces in the text each run holds once the fit has finished", async () => {+ const fitted = new Set<string>();+ vi.mocked(scanRunNeedsFit).mockImplementation(+ (_doc, r) => !fitted.has(r.id),+ );+ const { dispatch, runs } = setup();+ vi.mocked(prefitScanRun).mockImplementation((_doc, _page, r) => {+ if (r.id === "a" && !runs[0].text.endsWith("Doe")) {+ runs[0].text = "Invoice for Jane Doe";+ return false;+ }+ fitted.add(r.id);+ return true;+ });+ fireEvent.change(screen.getByTestId("pdf-editor-find-input"), {+ target: { value: "Jane" },+ });+ fireEvent.change(screen.getByTestId("pdf-editor-replace-input"), {+ target: { value: "Mary" },+ });++ fireEvent.click(screen.getByTestId("pdf-editor-replace-all"));++ await waitFor(() => expect(dispatch).toHaveBeenCalledTimes(1));+ const { commands } = dispatch.mock.calls[0][0] as unknown as {+ commands: EditTextCommand[];+ };+ expect(commands.map((c) => c.resultText)).toEqual([+ "Invoice for Mary Doe",+ "Mary Example",+ ]);+ });+ it("ignores Enter in the replace field while Replace all is fitting", async () => {+ const fitted = new Set<string>();+ let hold = true;+ vi.mocked(scanRunNeedsFit).mockImplementation(+ (_doc, r) => !fitted.has(r.id),+ );+ vi.mocked(prefitScanRun).mockImplementation((_doc, _page, r) => {+ if (hold) return false;+ fitted.add(r.id);+ return true;+ });+ const { dispatch } = setup();+ fireEvent.change(screen.getByTestId("pdf-editor-find-input"), {+ target: { value: "Jane" },+ });+ const replaceInput = screen.getByTestId("pdf-editor-replace-input");+ fireEvent.change(replaceInput, { target: { value: "Mary" } });++ fireEvent.click(screen.getByTestId("pdf-editor-replace-all"));+ await waitFor(() =>+ expect(vi.mocked(prefitScanRun).mock.calls.length).toBeGreaterThan(1),+ );+ fireEvent.keyDown(replaceInput, { key: "Enter" });++ expect(dispatch).not.toHaveBeenCalled();+ hold = false;+ await waitFor(() => expect(dispatch).toHaveBeenCalledTimes(1));+ const { commands } = dispatch.mock.calls[0][0] as unknown as {+ commands: EditTextCommand[];+ };+ expect(commands.map((c) => c.resultText)).toEqual([+ "Invoice for Mary",+ "Mary Example",+ ]);+ });+});diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/FindBar.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/FindBar.tsxindex f24825216c..826cd73036 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/components/FindBar.tsx+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/FindBar.tsx@@ -5,7 +5,6 @@ import { useTranslation } from "react-i18next";import { Icon } from "@editor/ui/Icon";import "@editor/tools/pdfTextEditor/components/FindBar.css";import { EditTextCommand } from "@editor/tools/pdfTextEditor/commands/EditTextCommand";-import { CompositeCommand } from "@editor/tools/pdfTextEditor/commands/CompositeCommand";import {findMatches,replaceMatches,@@ -15,6 +14,8 @@ import type {TextMatch,} from "@editor/tools/pdfTextEditor/util/textMatching";import { readAllPagesInBackground } from "@editor/tools/pdfTextEditor/hooks/useDocumentLoader";+import type { ScanFitTarget } from "@editor/tools/pdfTextEditor/commands/scanFitSlices";+import { useDispatchAfterScanFit } from "@editor/tools/pdfTextEditor/hooks/useDispatchAfterScanFit";import type { EditorStore } from "@editor/tools/pdfTextEditor/store/EditorStore";import type {PageSnapshot,@@ -58,6 +59,8 @@ export function FindBar({ store, pages, onClose }: FindBarProps) {const [ignoreAccents, setIgnoreAccents] = useState(false);const [activeIndex, setActiveIndex] = useState(0);const [replaceCount, setReplaceCount] = useState<number | null>(null);+ const { busy: replacing, dispatch: dispatchAfterScanFit } =+ useDispatchAfterScanFit(store);useEffect(() => {inputRef.current?.focus();@@ -149,7 +152,7 @@ export function FindBar({ store, pages, onClose }: FindBarProps) {* The replacement is spliced literally, so "$&" stays "$&".*/const doReplaceOne = useCallback(() => {- if (!query) return;+ if (!query || replacing) return;const m = matches[activeIndex];if (!m) return;// A locked run is still findable, but must not be rewritten.@@ -164,35 +167,54 @@ export function FindBar({ store, pages, onClose }: FindBarProps) {}),);setReplaceCount(1);- }, [query, replace, matches, activeIndex, store]);+ }, [query, replacing, replace, matches, activeIndex, store]);/*** Replace EVERY match. Each affected run gets one EditTextCommand,* batched into a single CompositeCommand so "Undo undoes the whole* Replace all".*/- const doReplaceAll = useCallback(() => {- if (!query || matches.length === 0) return;- let n = 0;- const cmds: EditTextCommand[] = [];+ const doReplaceAll = useCallback(async () => {+ const doc = store.document;+ if (!doc || replacing || !query || matches.length === 0) return;+ const targets: ScanFitTarget[] = [];for (const m of matches) {// Skip locked runs: the lock is a user instruction, not a hint.if (m.run.locked) continue;- const updated = replaceMatches(m.run.text, m.ranges, replace);- if (updated === m.run.text) continue;- cmds.push(- new EditTextCommand({- pageIndex: m.pageIndex,- runId: m.runId,- nextText: updated,- }),- );- n += 1;+ if (replaceMatches(m.run.text, m.ranges, replace) === m.run.text)+ continue;+ const page = doc.loadedPages().find((p) => p.index === m.pageIndex);+ const run = page?.findRun(m.runId);+ if (page && run) targets.push({ page, run });}- if (cmds.length === 1) store.dispatch(cmds[0]);- else if (cmds.length > 1) store.dispatch(new CompositeCommand(cmds));- setReplaceCount(n);- }, [query, replace, matches, store]);+ await dispatchAfterScanFit(targets, () => {+ const cmds: EditTextCommand[] = [];+ for (const { page, run: target } of targets) {+ const run = page.findRun(target.id);+ if (!run || run.locked) continue;+ const ranges = findMatches(run.text, query, options);+ const updated = replaceMatches(run.text, ranges, replace);+ if (updated === run.text) continue;+ cmds.push(+ new EditTextCommand({+ pageIndex: page.index,+ runId: run.id,+ nextText: updated,+ }),+ );+ }+ setReplaceCount(cmds.length);+ return cmds;+ });+ }, [+ query,+ replace,+ options,+ matches,+ store,+ replacing,+ dispatchAfterScanFit,+ ]);const countLabel =matches.length === 0@@ -349,7 +371,7 @@ export function FindBar({ store, pages, onClose }: FindBarProps) {onKeyDown={(e) => {if (e.key === "Enter") {e.preventDefault();- if (e.shiftKey) doReplaceAll();+ if (e.shiftKey) void doReplaceAll();else doReplaceOne();} else if (e.key === "Escape") {e.preventDefault();@@ -364,7 +386,7 @@ export function FindBar({ store, pages, onClose }: FindBarProps) {variant="tertiary"accent="neutral"onClick={doReplaceOne}- disabled={matches.length === 0 || !query}+ disabled={replacing || matches.length === 0 || !query}data-testid="pdf-editor-replace-one">{t("pdfTextEditor.find.replace", "Replace")}@@ -373,8 +395,9 @@ export function FindBar({ store, pages, onClose }: FindBarProps) {size="sm"variant="tertiary"accent="neutral"- onClick={doReplaceAll}- disabled={matches.length === 0 || !query}+ onClick={() => void doReplaceAll()}+ loading={replacing}+ disabled={replacing || matches.length === 0 || !query}data-testid="pdf-editor-replace-all">{t("pdfTextEditor.find.replaceAll", "Replace all")}diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/FontFamilySelect.test.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/FontFamilySelect.test.tsxindex 8bc440c4b6..ecdc54fda2 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/components/FontFamilySelect.test.tsx+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/FontFamilySelect.test.tsx@@ -1,6 +1,6 @@import { MantineProvider } from "@mantine/core";import { fireEvent, render, screen, waitFor } from "@testing-library/react";-import { beforeEach, describe, expect, it, vi } from "vitest";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";const { get, alert } = vi.hoisted(() => ({ get: vi.fn(), alert: vi.fn() }));vi.mock("@editor/services/apiClient", () => ({ default: { get } }));@@ -12,6 +12,7 @@ import {SERVER_FONTS_URL,forgetServerFontList,} from "@editor/tools/pdfTextEditor/util/serverFonts";+import { resetLocalFontsCache } from "@editor/tools/pdfTextEditor/util/localFonts";const MANIFEST = {families: [@@ -159,4 +160,83 @@ describe("font picker server fonts", () => {await waitFor(() => expect(onChange).toHaveBeenCalledWith("Acme Sans"));expect(alert).not.toHaveBeenCalled();});++ it("names the font a scan was matched to, not a document font", async () => {+ render(+ <MantineProvider env="test">+ <FontFamilySelect+ value="Carlito"+ scanned={{ label: "Calibri (Carlito)" }}+ onChange={async () => null}+ />+ </MantineProvider>,+ );+ const input = screen.getByTestId("pdf-editor-font-family");+ expect(input).toHaveValue("Calibri (Carlito)");++ fireEvent.click(input);++ expect(+ await screen.findByText("pdfTextEditor.fontPicker.matchedGroup"),+ ).toBeInTheDocument();+ expect(+ screen.queryByText("pdfTextEditor.fontPicker.documentGroup"),+ ).not.toBeInTheDocument();+ });++ it("says scanned text when no font is in force for it", () => {+ render(+ <MantineProvider env="test">+ <FontFamilySelect+ value={null}+ scanned={{}}+ onChange={async () => null}+ />+ </MantineProvider>,+ );+ expect(screen.getByTestId("pdf-editor-font-family")).toHaveAttribute(+ "placeholder",+ "pdfTextEditor.fontPicker.scannedText",+ );+ });+});++describe("font picker device fonts", () => {+ beforeEach(() => {+ resetLocalFontsCache();+ Object.defineProperty(navigator, "permissions", {+ configurable: true,+ value: { query: vi.fn().mockResolvedValue({ state: "granted" }) },+ });+ });++ afterEach(() => {+ Reflect.deleteProperty(navigator, "permissions");+ delete (window as unknown as { queryLocalFonts?: unknown }).queryLocalFonts;+ });++ it("lists the device fonts from the button after the automatic listing failed", async () => {+ const queryLocalFonts = vi+ .fn()+ .mockRejectedValueOnce(new Error("busy"))+ .mockResolvedValue([+ { family: "Acme Serif", style: "Regular", postscriptName: "AcmeSerif" },+ ]);+ (window as unknown as { queryLocalFonts: unknown }).queryLocalFonts =+ queryLocalFonts;+ renderPicker(async () => null);+ await waitFor(() => expect(queryLocalFonts).toHaveBeenCalledTimes(1));++ fireEvent.click(screen.getByTestId("pdf-editor-use-device-fonts"));++ await waitFor(() => expect(queryLocalFonts).toHaveBeenCalledTimes(2));+ await waitFor(() =>+ expect(+ screen.queryByTestId("pdf-editor-use-device-fonts"),+ ).not.toBeInTheDocument(),+ );+ expect(+ screen.queryByTestId("pdf-editor-device-fonts-notice"),+ ).not.toBeInTheDocument();+ });});diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/FontFamilySelect.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/FontFamilySelect.tsxindex 86df51effb..432a07542f 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/components/FontFamilySelect.tsx+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/FontFamilySelect.tsx@@ -1,16 +1,24 @@-import { useCallback, useMemo, useState, useSyncExternalStore } from "react";+import {+ useCallback,+ useEffect,+ useMemo,+ useState,+ useSyncExternalStore,+} from "react";import { Group, Loader, Select, Text, Tooltip } from "@mantine/core";import type { ComboboxData, ComboboxItemGroup } from "@mantine/core";import { useTranslation } from "react-i18next";import { Button } from "@editor/ui/Button";import { Icon } from "@editor/ui/Icon";import { alert } from "@editor/components/toast";+import { useServerFontsGroupLabel } from "@editor/tools/pdfTextEditor/hooks/useServerFontsGroupLabel";import type { FontPickFailure } from "@editor/tools/pdfTextEditor/hooks/useSelectionActions";import {familyOptions,isLocalFontAccessSupported,- listLocalFonts,+ listLocalFontsIfGranted,loadedLocalFonts,+ retryLocalFonts,subscribeLocalFonts,type FontFamilyOption,} from "@editor/tools/pdfTextEditor/util/localFonts";@@ -38,6 +46,10 @@ const PICK_FAILURE_TEXT: Record<FontPickFailure, [string, string]> = {"pdfTextEditor.fontPicker.serverFontFailed","That server font could not be downloaded. The text was left unchanged.",],+ embeddingForbidden: [+ "pdfTextEditor.fontPicker.embeddingForbidden",+ "This font's licence does not allow embedding it in a PDF. The text was left unchanged.",+ ],embedFailed: ["pdfTextEditor.fontPicker.embedFailed","This font could not be embedded in the PDF. The text was left unchanged.",@@ -52,6 +64,8 @@ type DeviceFontNotice = "unavailable" | "none";interface FontFamilySelectProps {value: string | null;+ /** Set for scanned text: `value` is the matched font (null while none is in force) and `label` the matcher's name for it. */+ scanned?: { label?: string };onChange: (family: string) => void | Promise<FontPickFailure | null>;mixed?: boolean;disabled?: boolean;@@ -61,6 +75,7 @@ interface FontFamilySelectProps {/** Font picker. Device fonts are additive: no prompt until the user asks. */export function FontFamilySelect({value,+ scanned,onChange,mixed = false,disabled = false,@@ -71,6 +86,7 @@ export function FontFamilySelect({const [applying, setApplying] = useState(false);const [notice, setNotice] = useState<DeviceFontNotice | null>(null);const supported = useMemo(() => isLocalFontAccessSupported(), []);+ const serverGroupLabel = useServerFontsGroupLabel();// Read the fonts from the module, not local state: switching files remounts// the toolbar, and the grant the user already gave must survive that.const localFonts = useSyncExternalStore(@@ -103,7 +119,7 @@ export function FontFamilySelect({setLoading(true);setNotice(null);try {- const fonts = await listLocalFonts();+ const fonts = await retryLocalFonts();// deviceFamilies recomputes off the store, so only the empty outcomes// need reporting here.if (!fonts) setNotice("unavailable");@@ -113,6 +129,11 @@ export function FontFamilySelect({}}, []);+ // Already allowed, so listing cannot prompt: skip the button.+ useEffect(() => {+ if (supported && !loadedLocalFonts()) void listLocalFontsIfGranted();+ }, [supported]);+const isKnown = useCallback((family: string) =>[...BUILT_IN_FONT_FAMILIES, ...serverOptions, ...deviceOptions].some(@@ -139,9 +160,15 @@ export function FontFamilySelect({const groups: ComboboxItemGroup[] = [];if (documentFamily) {groups.push({- group: t("pdfTextEditor.fontPicker.documentGroup", "Document font"),+ group: scanned+ ? t("pdfTextEditor.fontPicker.matchedGroup", "Matched font")+ : t("pdfTextEditor.fontPicker.documentGroup", "Document font"),items: [- { value: documentFamily, label: documentFamily, disabled: true },+ {+ value: documentFamily,+ label: scanned?.label ?? documentFamily,+ disabled: true,+ },],});}@@ -151,7 +178,7 @@ export function FontFamilySelect({});if (serverOptions.length > 0) {groups.push({- group: t("pdfTextEditor.fontPicker.serverGroup", "Server fonts"),+ group: serverGroupLabel,items: serverOptions,});}@@ -162,7 +189,14 @@ export function FontFamilySelect({});}return groups;- }, [serverOptions, deviceOptions, documentFamily, t]);+ }, [+ serverOptions,+ deviceOptions,+ documentFamily,+ scanned,+ serverGroupLabel,+ t,+ ]);const pickFailureText = useCallback((failure: FontPickFailure): string => {@@ -199,6 +233,13 @@ export function FontFamilySelect({return isKnown(value) || documentFamily === value ? value : null;}, [mixed, value, isKnown, documentFamily]);+ const placeholder = useMemo(() => {+ if (mixed) return t("pdfTextEditor.fontPicker.mixed", "Mixed");+ if (scanned)+ return t("pdfTextEditor.fontPicker.scannedText", "Scanned text");+ return t("pdfTextEditor.fontPicker.placeholder", "Font family");+ }, [mixed, scanned, t]);+return (<Groupgap="xs"@@ -221,11 +262,7 @@ export function FontFamilySelect({}}rightSection={applying ? <Loader size="xs" /> : undefined}disabled={disabled || applying}- placeholder={- mixed- ? t("pdfTextEditor.fontPicker.mixed", "Mixed")- : t("pdfTextEditor.fontPicker.placeholder", "Font family")- }+ placeholder={placeholder}aria-label={t("pdfTextEditor.fontPicker.label", "Font family")}nothingFoundMessage={t("pdfTextEditor.fontPicker.noMatch",diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/PageStage.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/PageStage.tsxindex 410b037a1e..210719a6a3 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/components/PageStage.tsx+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/PageStage.tsx@@ -9,6 +9,8 @@ import {Text,} from "@mantine/core";import { useTranslation } from "react-i18next";+import i18n from "i18next";+import { alert } from "@editor/components/toast";import { useEditorStore } from "@editor/tools/pdfTextEditor/hooks/useEditorStore";import { ensurePageRead } from "@editor/tools/pdfTextEditor/hooks/useDocumentLoader";import { EditorTopBar } from "@editor/tools/pdfTextEditor/components/EditorTopBar";@@ -24,6 +26,10 @@ import { ZoomPill } from "@editor/tools/pdfTextEditor/components/ZoomPill";import { MarqueeSelector } from "@editor/tools/pdfTextEditor/components/MarqueeSelector";import { PageView } from "@editor/tools/pdfTextEditor/components/PageView";import { EditTextCommand } from "@editor/tools/pdfTextEditor/commands/EditTextCommand";+import {+ scanBlockOffInk,+ wrapScanText,+} from "@editor/tools/pdfTextEditor/commands/scanTextEdit";import { ReflowWrapCommand } from "@editor/tools/pdfTextEditor/commands/ReflowWrapCommand";import { MoveShapeCommand } from "@editor/tools/pdfTextEditor/commands/MoveShapeCommand";import { InsertTextCommand } from "@editor/tools/pdfTextEditor/commands/InsertTextCommand";@@ -426,11 +432,34 @@ function pageViewHandlers(store: EditorStore) {const current = store.document?.page(pageIndex).findRun(runId);if (current && current.text === nextText) return;store.dispatch(new EditTextCommand({ pageIndex, runId, nextText }));+ const doc = store.document;+ const run = doc?.page(pageIndex).findRun(runId);+ if (doc && run && scanBlockOffInk(doc, run))+ alert({+ alertType: "warning",+ title: i18n.t(+ "pdfTextEditor.error.scanOffInk",+ "Can't edit this text: its recognised words don't line up with the scan. Run OCR again.",+ ),+ expandable: false,+ });},onMoveRun: (pageIndex: number, runId: string, dx: number, dy: number) => {store.dispatch(new MoveTextRunCommand({ pageIndex, runId, dx, dy }));},onWrapRun: (pageIndex: number, runId: string, maxWidthPt: number) => {+ const doc = store.document;+ const page = doc?.page(pageIndex);+ const run = page?.findRun(runId);+ const wrapped =+ doc && page && run ? wrapScanText(doc, page, run, maxWidthPt) : null;+ if (wrapped !== null) {+ if (wrapped !== run?.text)+ store.dispatch(+ new EditTextCommand({ pageIndex, runId, nextText: wrapped }),+ );+ return;+ }store.dispatch(new ReflowWrapCommand({ pageIndex, runId, maxWidthPt }));},onResizeRun: (pageIndex: number, runId: string, widthPt: number) => {diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/PageView.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/PageView.tsxindex d845bed91b..3920b0c4f7 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/components/PageView.tsx+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/PageView.tsx@@ -9,6 +9,7 @@ import type {TextRange,} from "@editor/tools/pdfTextEditor/types";import { TextRunOverlay } from "@editor/tools/pdfTextEditor/components/TextRunOverlay";+import { isScanRun } from "@editor/tools/pdfTextEditor/commands/scanTextEdit";import { TableOverlay } from "@editor/tools/pdfTextEditor/components/TableOverlay";import { ACCESSIBILITY_EDITING } from "@editor/constants/featureFlags";import {@@ -200,6 +201,12 @@ export const PageView = memo(function PageView({return () => observer.disconnect();}, []);+ useEffect(() => {+ if (!nearViewport) return;+ store.setPageNearViewport(page.pageIndex, true);+ return () => store.setPageNearViewport(page.pageIndex, false);+ }, [store, page.pageIndex, nearViewport]);+useEffect(() => {const canvas = canvasRef.current;if (!nearViewport) {@@ -448,7 +455,7 @@ export const PageView = memo(function PageView({onWrapRun?.(page.pageIndex, run.id, maxWidthPt)}onResize={- onResizeRun+ onResizeRun && !isScanRun(run)? (widthPt) => onResizeRun(page.pageIndex, run.id, widthPt): undefined}diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/TextRunOverlay.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/TextRunOverlay.tsxindex 3cbe23e32d..13cd38761d 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/components/TextRunOverlay.tsx+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/TextRunOverlay.tsx@@ -1,3 +1,4 @@+import { scanFaceCssFamily } from "@editor/tools/pdfTextEditor/util/scanFontLibrary";import { useEffect, useMemo, useRef, useState } from "react";import { useTranslation } from "react-i18next";import {@@ -453,9 +454,13 @@ export function TextRunOverlay({const originalBoundsWidthRef = useRef<number>(run.bounds.width);// Whether this run was a real (multi-line) paragraph when it first mounted.- const fontFamily = cssFontFamilyFor(run.fontId);- const fontWeight = cssWeightFor(run.fontId);- const fontStyle = cssStyleFor(run.fontId);+ const faceName = run.scanFamily ?? run.fontId;+ // The caret is placed by letter widths, so scanned text uses the matched face, not the invisible OCR layer's font.+ const fontFamily = run.scanFamily+ ? scanFaceCssFamily(run.scanFamily)+ : cssFontFamilyFor(run.fontId);+ const fontWeight = cssWeightFor(faceName);+ const fontStyle = cssStyleFor(faceName);const fontSizePx = Math.max(4, run.fontSize * scale);const font = cssFontShorthand(fontStyle, fontWeight, fontSizePx, fontFamily);const { ascent, descent } = useMemo(@@ -858,6 +863,7 @@ export function TextRunOverlay({<divref={ref}data-testid={`pdf-editor-run-${run.id}`}+ data-run-id={run.id}className={`pdf-editor-run${pristine ? " is-pristine" : ""}`}contentEditable={!run.locked}suppressContentEditableWarningdiff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/ScanFontMatchModal.test.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/ScanFontMatchModal.test.tsxnew file mode 100644index 0000000000..4edbb68937--- /dev/null+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/ScanFontMatchModal.test.tsx@@ -0,0 +1,191 @@+import { MantineProvider } from "@mantine/core";+import { fireEvent, render, screen } from "@testing-library/react";+import { describe, expect, it, vi } from "vitest";+import {+ ScanFontMatchModal,+ ScanFontMatchRow,+} from "@editor/tools/pdfTextEditor/components/inspector/ScanFontMatchModal";+import type {+ ScanFontChoice,+ ScanFontMatch,+} from "@editor/tools/pdfTextEditor/hooks/useScanFontMatch";++function match(overrides: Partial<ScanFontMatch> = {}): ScanFontMatch {+ return {+ status: "ready",+ scan: null,+ choices: [+ {+ label: "Carlito",+ match: 90,+ preview: null,+ active: false,+ approximate: false,+ },+ ],+ choose: vi.fn(),+ open: true,+ canShow: true,+ approximate: false,+ undrawable: false,+ typedFromScan: false,+ show: vi.fn(),+ close: vi.fn(),+ deviceFonts: {+ available: true,+ permission: "unsupported",+ loading: false,+ count: null,+ load: vi.fn(),+ },+ ...overrides,+ };+}++function renderModal(m: ScanFontMatch) {+ render(+ <MantineProvider env="test">+ <ScanFontMatchModal match={m} />+ </MantineProvider>,+ );+}++describe("scan font picker hint", () => {+ it("says the typing came from the scan's own letters when it did", () => {+ renderModal(match({ typedFromScan: true }));+ expect(screen.getByTestId("pdf-editor-scan-font-hint")).toHaveTextContent(+ "pdfTextEditor.scanFont.hintFromScan",+ );+ });++ it("says the typing is drawn in a font otherwise", () => {+ renderModal(match());+ expect(screen.getByTestId("pdf-editor-scan-font-hint")).toHaveTextContent(+ /^pdfTextEditor\.scanFont\.hint$/,+ );+ });++ it("says a pick also steers scanned text not yet edited", () => {+ renderModal(match());+ expect(+ screen.getByText("pdfTextEditor.scanFont.hintOthers"),+ ).toBeInTheDocument();+ });+});++describe("scan font picker device fonts prompt", () => {+ const prompting = (available: boolean) =>+ match({+ deviceFonts: {+ available,+ permission: "prompt",+ loading: false,+ count: null,+ load: vi.fn(),+ },+ });++ it("asks for device fonts when the text's script has candidates", () => {+ renderModal(prompting(true));+ expect(screen.getByTestId("pdf-editor-scan-font-device")).toBeVisible();+ });++ it("does not ask when no device font could draw the text's script", () => {+ renderModal(prompting(false));+ expect(screen.queryByTestId("pdf-editor-scan-font-device")).toBeNull();+ });++ it("does not offer device fonts when the scan is too faint to match", () => {+ renderModal({ ...prompting(true), status: "unmeasurable", choices: [] });+ expect(screen.queryByTestId("pdf-editor-scan-font-device")).toBeNull();+ });++ it("asks with one generic button whether or not a font can draw the text", () => {+ for (const status of ["ready", "noFont"] as const) {+ const { unmount } = render(+ <MantineProvider env="test">+ <ScanFontMatchModal match={{ ...prompting(true), status }} />+ </MantineProvider>,+ );+ expect(+ screen.getByTestId("pdf-editor-scan-font-device-allow"),+ ).toHaveTextContent("pdfTextEditor.scanFont.deviceAllow");+ expect(+ screen.getByTestId("pdf-editor-scan-font-device").textContent,+ ).toBe(+ "pdfTextEditor.scanFont.deviceAllowpdfTextEditor.scanFont.deviceNote",+ );+ unmount();+ }+ });+});++describe("approximate scan font matches", () => {+ const choice = (overrides: Partial<ScanFontChoice>): ScanFontChoice => ({+ label: "Carlito",+ match: 70,+ preview: null,+ active: true,+ approximate: false,+ ...overrides,+ });++ it("marks an applied weak match instead of ticking it", () => {+ renderModal(+ match({+ approximate: true,+ choices: [+ choice({ label: "Carlito", approximate: true }),+ choice({ label: "Caladea", active: false, approximate: true }),+ ],+ }),+ );+ const [applied, other] = screen.getAllByTestId(+ "pdf-editor-scan-font-choice",+ );+ expect(applied).toHaveAttribute("aria-pressed", "true");+ expect(applied).toHaveAttribute("data-approximate", "true");+ expect(applied).toHaveTextContent("pdfTextEditor.scanFont.approximate");+ expect(other).not.toHaveAttribute("data-approximate");+ expect(+ screen.getAllByTestId("pdf-editor-scan-font-choice-approximate"),+ ).toHaveLength(1);+ });++ it("ticks a strong match without the approximate label", () => {+ renderModal(+ match({ choices: [choice({ match: 95, approximate: false })] }),+ );+ const [applied] = screen.getAllByTestId("pdf-editor-scan-font-choice");+ expect(applied).not.toHaveAttribute("data-approximate");+ expect(+ screen.queryByTestId("pdf-editor-scan-font-choice-approximate"),+ ).toBeNull();+ });++ it("points the inspector at the picker when the match is approximate", () => {+ const m = match({ open: false, approximate: true });+ render(+ <MantineProvider env="test">+ <ScanFontMatchRow match={m} />+ </MantineProvider>,+ );+ expect(+ screen.getByTestId("pdf-editor-scan-font-approximate"),+ ).toHaveTextContent("pdfTextEditor.scanFont.approximate");+ fireEvent.click(screen.getByTestId("pdf-editor-scan-font-open"));+ expect(m.show).toHaveBeenCalled();+ });++ it("keeps the quiet row for a strong match", () => {+ render(+ <MantineProvider env="test">+ <ScanFontMatchRow match={match({ open: false })} />+ </MantineProvider>,+ );+ expect(screen.queryByTestId("pdf-editor-scan-font-approximate")).toBeNull();+ expect(screen.getByTestId("pdf-editor-scan-font-open")).toHaveTextContent(+ "pdfTextEditor.scanFont.change",+ );+ });+});diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/ScanFontMatchModal.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/ScanFontMatchModal.tsxnew file mode 100644index 0000000000..1fd8c0736f--- /dev/null+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/ScanFontMatchModal.tsx@@ -0,0 +1,440 @@+import { Group, Loader, Modal, Stack, Text } from "@mantine/core";+import { useId } from "react";+import { useTranslation } from "react-i18next";+import { Button } from "@editor/ui/Button";+import { Icon } from "@editor/ui/Icon";+import { Section } from "@editor/tools/pdfTextEditor/components/inspector/InspectorPrimitives";+import type {+ ScanFontChoice,+ ScanFontMatch,+} from "@editor/tools/pdfTextEditor/hooks/useScanFontMatch";++const lineImage = {+ display: "block",+ width: "100%",+ height: "auto",+ boxSizing: "border-box",+ padding: "4px 6px",+ // Page pixels sit on paper in either theme.+ background: "var(--c-document-bg)",+ borderRadius: 4,+ border: "1px solid var(--c-border-subtle)",+} as const;++export function ScanFontMatchModal({ match }: { match: ScanFontMatch }) {+ const { t } = useTranslation();+ return (+ <Modal+ opened={match.open}+ onClose={match.close}+ title={t("pdfTextEditor.scanFont.title", "Match the scanned font")}+ size="md"+ data-testid="pdf-editor-scan-font-match"+ >+ <Stack gap="sm">+ <ScanFontHint+ status={match.status}+ typedFromScan={match.typedFromScan}+ />+ {match.status === "ready" && (+ <Stack gap="md">+ {match.scan && <OriginalScanPreview scan={match.scan} />}+ <ScanFontChoices choices={match.choices} choose={match.choose} />+ </Stack>+ )}+ <DeviceFontsNote+ deviceFonts={match.deviceFonts}+ status={match.status}+ />+ <Group justify="flex-end">+ <Button+ variant="primary"+ onClick={match.close}+ data-testid="pdf-editor-scan-font-done"+ >+ {t("pdfTextEditor.scanFont.done", "Done")}+ </Button>+ </Group>+ </Stack>+ </Modal>+ );+}++function ScanFontHint({+ status,+ typedFromScan,+}: {+ status: ScanFontMatch["status"];+ typedFromScan: boolean;+}) {+ const { t } = useTranslation();+ if (status === "noFont")+ return (+ <Text size="sm" c="dimmed" data-testid="pdf-editor-scan-font-none">+ {t(+ "pdfTextEditor.scanFont.noFont",+ "None of the available fonts can draw this script, so typed text cannot be redrawn yet.",+ )}+ </Text>+ );+ if (status === "unmeasurable")+ return (+ <Text size="sm" c="dimmed">+ {t(+ "pdfTextEditor.scanFont.unmeasurable",+ "This scan is too faint or small to match a font to.",+ )}+ </Text>+ );+ return (+ <>+ <Stack gap={4}>+ <Text size="sm" c="dimmed" data-testid="pdf-editor-scan-font-hint">+ {typedFromScan+ ? t(+ "pdfTextEditor.scanFont.hintFromScan",+ "Your typing is built from letters found in the scan. Pick a font to draw it in that font instead.",+ )+ : t(+ "pdfTextEditor.scanFont.hint",+ "Your typing is drawn in the closest font found. Pick another if it looks more like the scan.",+ )}+ </Text>+ <Text size="xs" c="dimmed">+ {t(+ "pdfTextEditor.scanFont.hintOthers",+ "Your pick is also used for scanned text you have not edited yet.",+ )}+ </Text>+ </Stack>+ {status === "matching" && (+ <Group+ gap="xs"+ role="status"+ data-testid="pdf-editor-scan-font-matching"+ >+ <Loader size="xs" />+ <Text size="sm" c="dimmed">+ {t("pdfTextEditor.scanFont.matching", "Matching fonts…")}+ </Text>+ </Group>+ )}+ </>+ );+}++function OriginalScanPreview({ scan }: { scan: string }) {+ const { t } = useTranslation();+ return (+ <Stack+ gap={6}+ p="sm"+ style={{+ background: "var(--c-surface-sunken)",+ borderRadius: 6,+ }}+ data-testid="pdf-editor-scan-font-original"+ >+ <Group gap={6} wrap="nowrap">+ <Icon name="scan-text" size={14} />+ <Text size="xs" fw={600} c="dimmed" tt="uppercase">+ {t("pdfTextEditor.scanFont.scan", "Original scan")}+ </Text>+ </Group>+ <img+ src={scan}+ alt={t("pdfTextEditor.scanFont.scanAlt", "The scanned line")}+ style={lineImage}+ />+ <Text size="xs" c="dimmed" data-testid="pdf-editor-scan-font-note">+ {t(+ "pdfTextEditor.scanFont.scanNote",+ "Scans often look blurrier or bolder than the font really is. Compare letter shapes rather than thickness.",+ )}+ </Text>+ </Stack>+ );+}++function ScanFontChoices({+ choices,+ choose,+}: {+ choices: ScanFontChoice[];+ choose: (index: number) => void;+}) {+ const { t } = useTranslation();+ const labelId = useId();+ return (+ <Stack gap={6} role="group" aria-labelledby={labelId}>+ <Text id={labelId} size="xs" fw={600} c="dimmed" tt="uppercase">+ {t("pdfTextEditor.scanFont.choose", "Choose a font")}+ </Text>+ {choices.map((choice, i) => (+ <ScanFontChoiceButton+ key={choice.label}+ choice={choice}+ onChoose={() => choose(i)}+ />+ ))}+ </Stack>+ );+}++function choiceTone(choice: ScanFontChoice) {+ if (!choice.active)+ return {+ icon: "circle",+ iconColor: "var(--c-text-subtle)",+ border: "var(--c-border)",+ background: "var(--c-surface)",+ } as const;+ if (choice.approximate)+ return {+ icon: "circle-alert",+ iconColor: "var(--c-warning)",+ border: "var(--c-warning)",+ background: "var(--c-warning-subtle)",+ } as const;+ return {+ icon: "circle-check",+ iconColor: "var(--c-accent-fg, var(--c-primary))",+ border: "var(--c-primary)",+ background: "var(--c-primary-subtle)",+ } as const;+}++function ScanFontChoiceButton({+ choice,+ onChoose,+}: {+ choice: ScanFontChoice;+ onChoose: () => void;+}) {+ const { t } = useTranslation();+ const tone = choiceTone(choice);+ const flagged = choice.active && choice.approximate;+ return (+ <button+ type="button"+ onClick={onChoose}+ aria-pressed={choice.active}+ data-testid="pdf-editor-scan-font-choice"+ data-active={choice.active || undefined}+ data-approximate={flagged || undefined}+ style={{+ display: "flex",+ gap: 10,+ alignItems: "flex-start",+ width: "100%",+ textAlign: "left",+ cursor: "pointer",+ color: "inherit",+ font: "inherit",+ padding: 10,+ borderRadius: 6,+ border: `1px solid ${tone.border}`,+ background: tone.background,+ }}+ >+ <Icon+ name={tone.icon}+ size={18}+ style={{ flexShrink: 0, color: tone.iconColor }}+ />+ <Stack gap={4} style={{ flex: 1, minWidth: 0 }}>+ <Group justify="space-between" gap="xs" wrap="nowrap">+ <Text size="sm" fw={600} truncate>+ {choice.label}+ </Text>+ <Text size="xs" c="dimmed" style={{ flexShrink: 0 }}>+ {t("pdfTextEditor.scanFont.score", "{{match}}% alike", {+ match: choice.match,+ })}+ </Text>+ </Group>+ {flagged && (+ <Text+ size="xs"+ fw={600}+ data-testid="pdf-editor-scan-font-choice-approximate"+ >+ {t("pdfTextEditor.scanFont.approximate", "Approximate match")}+ </Text>+ )}+ {choice.preview && (+ <img src={choice.preview} alt="" style={lineImage} />+ )}+ </Stack>+ </button>+ );+}++function DeviceFontsNote({+ deviceFonts,+ status,+}: {+ deviceFonts: ScanFontMatch["deviceFonts"];+ status: ScanFontMatch["status"];+}) {+ const { t } = useTranslation();+ const { available, permission, count, loading, load } = deviceFonts;+ if (!available || permission === "unsupported" || status === "unmeasurable")+ return null;+ if (count !== null && count > 0)+ return (+ <Group+ gap={6}+ wrap="nowrap"+ role="status"+ data-testid="pdf-editor-scan-font-device-on"+ >+ <Icon+ name="circle-check"+ size={14}+ style={{ color: "var(--c-success)" }}+ />+ <Text size="xs" c="dimmed">+ {t("pdfTextEditor.scanFont.deviceOn", {+ count,+ defaultValue_one:+ "Also compared with {{count}} font on this computer.",+ defaultValue_other:+ "Also compared with {{count}} fonts on this computer.",+ })}+ </Text>+ </Group>+ );+ if (permission === "granted")+ return (+ <Text size="xs" c="dimmed" role="status">+ {loading+ ? t(+ "pdfTextEditor.scanFont.deviceReading",+ "Reading fonts on this computer…",+ )+ : t(+ "pdfTextEditor.scanFont.deviceNone",+ "None of the usual document fonts are installed on this computer.",+ )}+ </Text>+ );+ const allow = (+ <Button+ size="sm"+ variant="secondary"+ accent="neutral"+ loading={loading}+ disabled={loading}+ leftSection={<Icon name="case-sensitive" size={18} />}+ onClick={load}+ data-testid="pdf-editor-scan-font-device-allow"+ >+ {permission === "denied"+ ? t("pdfTextEditor.scanFont.deviceRetry", "Try again")+ : t(+ "pdfTextEditor.scanFont.deviceAllow",+ "Allow font access for better matching",+ )}+ </Button>+ );+ if (permission === "denied")+ return (+ <Stack+ gap={6}+ p="sm"+ style={{ border: "1px solid var(--c-border)", borderRadius: 6 }}+ data-testid="pdf-editor-scan-font-device"+ >+ <Text size="sm" fw={600}>+ {t(+ "pdfTextEditor.scanFont.deviceBlockedTitle",+ "Font access is blocked",+ )}+ </Text>+ <Text size="xs" c="dimmed">+ {t(+ "pdfTextEditor.scanFont.deviceBlocked",+ "Your browser won't ask again. To allow it, click the icon left of the address bar, turn on Fonts, then try again.",+ )}+ </Text>+ <Group>{allow}</Group>+ </Stack>+ );+ return (+ <Stack+ gap={6}+ p="sm"+ align="center"+ style={{ border: "1px solid var(--c-border)", borderRadius: 6 }}+ data-testid="pdf-editor-scan-font-device"+ >+ {allow}+ <Text size="xs" c="dimmed" ta="center">+ {t(+ "pdfTextEditor.scanFont.deviceNote",+ "Your browser asks first. Fonts stay on this device.",+ )}+ </Text>+ </Stack>+ );+}++export function ScanFontMatchRow({ match }: { match: ScanFontMatch }) {+ const { t } = useTranslation();+ if (match.approximate)+ return (+ <Section testId="pdf-editor-scan-font-row">+ <Stack gap={6} data-testid="pdf-editor-scan-font-approximate">+ <Group gap={6} wrap="nowrap">+ <Icon+ name="circle-alert"+ size={16}+ style={{ flexShrink: 0, color: "var(--c-warning)" }}+ />+ <Text size="sm" fw={600}>+ {t("pdfTextEditor.scanFont.approximate", "Approximate match")}+ </Text>+ </Group>+ <Text size="xs" c="dimmed">+ {t(+ "pdfTextEditor.scanFont.approximateHint",+ "The closest font found may not match the scan.",+ )}+ </Text>+ <Group>+ <Button+ size="sm"+ variant="secondary"+ accent="neutral"+ leftSection={<Icon name="case-sensitive" size={18} />}+ onClick={match.show}+ data-testid="pdf-editor-scan-font-open"+ >+ {t("pdfTextEditor.scanFont.compare", "Compare fonts…")}+ </Button>+ </Group>+ </Stack>+ </Section>+ );+ return (+ <Section testId="pdf-editor-scan-font-row">+ <Button+ size="sm"+ variant="tertiary"+ accent="neutral"+ justify="start"+ leftSection={<Icon name="case-sensitive" size={18} />}+ onClick={match.show}+ data-testid="pdf-editor-scan-font-open"+ >+ {match.undrawable+ ? t(+ "pdfTextEditor.scanFont.chooseMissing",+ "Choose a font for this text…",+ )+ : t("pdfTextEditor.scanFont.change", "Font not looking right?")}+ </Button>+ </Section>+ );+}diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/SelectionInspector.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/SelectionInspector.tsxindex 030c5692c9..9fbf2a288d 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/SelectionInspector.tsx+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/inspector/SelectionInspector.tsx@@ -16,6 +16,8 @@ import { modShortcut } from "@editor/utils/hotkeys";import { ACCESSIBILITY_EDITING } from "@editor/constants/featureFlags";import { ImageAccessibilitySection } from "@editor/tools/pdfTextEditor/components/inspector/ImageAccessibilitySection";import { TextAccessibilitySection } from "@editor/tools/pdfTextEditor/components/inspector/TextAccessibilitySection";+import { ScanFontMatchRow } from "@editor/tools/pdfTextEditor/components/inspector/ScanFontMatchModal";+import type { ScanFontMatch } from "@editor/tools/pdfTextEditor/hooks/useScanFontMatch";export type InspectorController = ReturnType<typeof useToolbarController>;@@ -25,6 +27,7 @@ interface Props {geometry: SelectionGeometry;/** Font status for the selected runs, e.g. "Embedded · full alphabet". */fontNote: string | null;+ scanFontMatch?: ScanFontMatch | null;canGroup: boolean;canUngroup: boolean;onGroup: () => void;@@ -44,6 +47,7 @@ export function SelectionInspector({selection,geometry,fontNote,+ scanFontMatch,canGroup,canUngroup,onGroup,@@ -62,6 +66,7 @@ export function SelectionInspector({shapeCount={shapeCount}fontNote={hasRunSelection ? fontNote : null}/>+ {scanFontMatch?.canShow && <ScanFontMatchRow match={scanFontMatch} />}{runCount + imageCount > 0 && (<GeometrySection geometry={geometry} isImage={!hasRunSelection} />)}@@ -288,7 +293,7 @@ function GeometrySection({<Fieldlabel={t("pdfTextEditor.inspector.width", "Width")}hint={- isImage+ isImage || !setWidth? undefined: t("pdfTextEditor.inspector.widthHint",@@ -298,8 +303,9 @@ function GeometrySection({><PointsInputvalue={bounds.width}- onCommit={setWidth}+ onCommit={setWidth ?? (() => undefined)}min={1}+ disabled={!setWidth}label={t("pdfTextEditor.inspector.width", "Width")}testId="pdf-editor-size-w"/>diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/toolbar/FormatGroup.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/toolbar/FormatGroup.tsxindex d69871e41b..36b333de4b 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/components/toolbar/FormatGroup.tsx+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/toolbar/FormatGroup.tsx@@ -30,6 +30,7 @@ export function FormatGroup({ controller, touch = false }: FormatGroupProps) {const { t } = useTranslation();const {state,+ scanFont,hasRunSelection,onChangeFontFamily,onChangeFontSize,@@ -44,7 +45,9 @@ export function FormatGroup({ controller, touch = false }: FormatGroupProps) {const fillHex = state.fill ? toCssHex(state.fill) : "#000000";const outlineHex = state.stroke ? toCssHex(state.stroke) : "#000000";const outlineWidth = state.strokeWidth ?? 0;- const fontFamily = state.fontFamily ? familyOf(state.fontFamily) : null;+ const documentFamily = state.fontFamily ? familyOf(state.fontFamily) : null;+ const fontFamily =+ scanFont === undefined ? documentFamily : (scanFont?.family ?? null);const inputSize = touch ? "lg" : "xs";const buttonSize = touch ? "xl" : "sm";@@ -52,6 +55,9 @@ export function FormatGroup({ controller, touch = false }: FormatGroupProps) {<><FontFamilySelectvalue={fontFamily}+ scanned={+ scanFont === undefined ? undefined : { label: scanFont?.label }+ }onChange={onChangeFontFamily}mixed={state.mixed.fontFamily}touch={touch}diff --git a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useDispatchAfterScanFit.ts b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useDispatchAfterScanFit.tsnew file mode 100644index 0000000000..3032bc0bb5--- /dev/null+++ b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useDispatchAfterScanFit.ts@@ -0,0 +1,35 @@+import { useCallback, useState } from "react";+import type { Command } from "@editor/tools/pdfTextEditor/commands/Command";+import { CompositeCommand } from "@editor/tools/pdfTextEditor/commands/CompositeCommand";+import {+ prefitInSlices,+ scanRunsToFit,+ type ScanFitTarget,+} from "@editor/tools/pdfTextEditor/commands/scanFitSlices";+import type { EditorStore } from "@editor/tools/pdfTextEditor/store/EditorStore";++/** Fits any scanned targets in slices first, then dispatches `build()` as one undo step; `busy` while fitting, and nothing dispatches if the document changed meanwhile. */+export function useDispatchAfterScanFit(store: EditorStore) {+ const [busy, setBusy] = useState(false);+ const dispatch = useCallback(+ async (targets: ScanFitTarget[], build: () => Command[]) => {+ const doc = store.document;+ if (!doc) return;+ const unfitted = scanRunsToFit(doc, targets);+ if (unfitted.length > 0) {+ setBusy(true);+ try {+ await prefitInSlices(doc, unfitted);+ } finally {+ setBusy(false);+ }+ if (store.document !== doc) return;+ }+ const cmds = build();+ if (cmds.length === 1) store.dispatch(cmds[0]);+ else if (cmds.length > 1) store.dispatch(new CompositeCommand(cmds));+ },+ [store],+ );+ return { busy, dispatch };+}diff --git a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useDocumentFontCompletion.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useDocumentFontCompletion.test.tsnew file mode 100644index 0000000000..50c87697b3--- /dev/null+++ b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useDocumentFontCompletion.test.ts@@ -0,0 +1,233 @@+import { beforeEach, describe, expect, test, vi } from "vitest";+import { renderHook, waitFor } from "@testing-library/react";+import { useDocumentFontCompletion } from "@editor/tools/pdfTextEditor/hooks/useDocumentFontCompletion";+import { setClosestFont } from "@editor/tools/pdfTextEditor/util/documentFontCompletion";+import { matchableSample } from "@editor/tools/pdfTextEditor/util/matchableSample";+import { rankFacesForDrawnText } from "@editor/tools/pdfTextEditor/commands/scanTextEdit";+import { fitInSlices } from "@editor/tools/pdfTextEditor/commands/scanFitSlices";+import {+ loadScriptScanFaces,+ scanScriptsOf,+} from "@editor/tools/pdfTextEditor/util/scanFontLibrary";+import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";+import type {+ EditorStore,+ EditorViewState,+} from "@editor/tools/pdfTextEditor/store/EditorStore";++vi.mock("@editor/tools/pdfTextEditor/util/documentFontCompletion", () => ({+ fontCanBeCompleted: () => true,+ fontCompletionFor: () => null,+ fontCompletionsGeneration: () => 0,+ originalFontLookedUp: () => true,+ resolveOriginalFonts: vi.fn(() => Promise.resolve()),+ setClosestFont: vi.fn(),+ subscribeFontCompletions: () => () => {},+}));++vi.mock("@editor/tools/pdfTextEditor/util/externalFonts", () => ({+ loadedExternalFonts: () => null,+ subscribeExternalFonts: () => () => {},+}));++vi.mock("@editor/tools/pdfTextEditor/util/localFonts", () => ({+ listLocalFontsIfGranted: vi.fn(() => Promise.resolve(null)),+}));++vi.mock("@editor/tools/pdfTextEditor/util/fontFamily", () => ({+ isDocumentFontId: () => true,+}));++vi.mock("@editor/tools/pdfTextEditor/util/matchableSample", () => ({+ matchableSample: vi.fn(),+}));++vi.mock("@editor/tools/pdfTextEditor/commands/scanTextEdit", () => ({+ isScanRun: () => false,+ rankFacesForDrawnText: vi.fn(),+}));++vi.mock("@editor/tools/pdfTextEditor/commands/scanFitSlices", () => ({+ fitInSlices: vi.fn(),+}));++vi.mock(+ "@editor/tools/pdfTextEditor/util/scanFontLibrary",+ async (importOriginal) => ({+ ...(await importOriginal<object>()),+ loadBundledScanFaces: vi.fn(() => Promise.resolve()),+ loadDeviceScanFacesIfAllowed: vi.fn(() => Promise.resolve()),+ loadScriptScanFaces: vi.fn(() => Promise.resolve()),+ }),+);++const FONT = "F1";++function pagesOf(count: number): EditorViewState["pages"] {+ return Array.from({ length: count }, (_, pageIndex) => ({+ pageIndex,+ runs: [{ id: `r${pageIndex}`, fontId: FONT, text: "Invoice total" }],+ })) as unknown as EditorViewState["pages"];+}++function setup(pageCount: number) {+ let loaded = pageCount;+ const doc = {+ module: {},+ loadedPages: () =>+ Array.from({ length: loaded }, (_, index) => ({ index, runs: [] })),+ } as unknown as EditorDocument;+ const store = { document: doc } as unknown as EditorStore;+ const selection = { runIds: [] };+ const view = renderHook(+ ({ pages }) =>+ useDocumentFontCompletion(+ store,+ { pages } as EditorViewState,+ selection as never,+ null,+ ),+ { initialProps: { pages: pagesOf(pageCount) } },+ );+ return {+ edit: () => view.rerender({ pages: pagesOf(loaded) }),+ loadPage: () => {+ loaded++;+ view.rerender({ pages: pagesOf(loaded) });+ },+ };+}++function setupWithFonts(fontIds: string[]) {+ const doc = {+ module: {},+ loadedPages: () => [{ index: 0, runs: [] }],+ } as unknown as EditorDocument;+ const store = { document: doc } as unknown as EditorStore;+ const pagesFor = (ids: string[]) =>+ [+ {+ pageIndex: 0,+ runs: ids.map((fontId) => ({ id: fontId, fontId, text: "Invoice" })),+ },+ ] as unknown as EditorViewState["pages"];+ const view = renderHook(+ ({ pages }) =>+ useDocumentFontCompletion(+ store,+ { pages } as EditorViewState,+ { runIds: [] } as never,+ null,+ ),+ { initialProps: { pages: pagesFor(fontIds) } },+ );+ return {+ showFonts: (ids: string[]) => view.rerender({ pages: pagesFor(ids) }),+ };+}++function deferred() {+ let resolve: () => void = () => {};+ const promise = new Promise<void>((r) => (resolve = r));+ return { promise, resolve };+}++function sampleWith(text: string) {+ return {+ page: { index: 0 },+ captured: {},+ text,+ } as unknown as ReturnType<typeof matchableSample>;+}++beforeEach(() => {+ vi.mocked(matchableSample).mockReset();+ vi.mocked(rankFacesForDrawnText).mockReset();+ vi.mocked(setClosestFont).mockReset();+ vi.mocked(loadScriptScanFaces).mockClear();+ vi.mocked(fitInSlices).mockReset();+ vi.mocked(fitInSlices).mockImplementation(async (fit) => fit());+ vi.mocked(rankFacesForDrawnText).mockReturnValue([+ { style: { family: "Noto Sans JP" } },+ ] as never);+});++describe("useDocumentFontCompletion", () => {+ test("matches a font once a later page gives it a usable sample", async () => {+ vi.mocked(matchableSample).mockReturnValue(null);+ const { loadPage } = setup(1);+ await waitFor(() => expect(matchableSample).toHaveBeenCalled());+ expect(setClosestFont).not.toHaveBeenCalled();++ vi.mocked(matchableSample).mockReturnValue(sampleWith("Invoice total"));+ loadPage();+ await waitFor(() =>+ expect(setClosestFont).toHaveBeenCalledWith(FONT, "Noto Sans JP"),+ );+ });++ test("samples an unsampled font again only when more pages load", async () => {+ vi.mocked(matchableSample).mockReturnValue(null);+ const { edit, loadPage } = setup(1);+ await waitFor(() => expect(matchableSample).toHaveBeenCalledTimes(1));+ edit();+ vi.mocked(matchableSample).mockReturnValue(sampleWith("Invoice total"));+ loadPage();+ await waitFor(() => expect(setClosestFont).toHaveBeenCalled());+ expect(matchableSample).toHaveBeenCalledTimes(2);+ });++ test("loads the server faces for the sample's script before ranking", async () => {+ const text = "請求書 お支払い ください";+ vi.mocked(matchableSample).mockReturnValue(sampleWith(text));+ let scriptsLoaded = false;+ vi.mocked(loadScriptScanFaces).mockImplementation(async () => {+ scriptsLoaded = true;+ });+ let loadedBeforeRanking = false;+ vi.mocked(rankFacesForDrawnText).mockImplementation(() => {+ loadedBeforeRanking = scriptsLoaded;+ return [{ style: { family: "Noto Sans JP" } }] as never;+ });+ setup(1);+ await waitFor(() => expect(setClosestFont).toHaveBeenCalled());+ expect(loadScriptScanFaces).toHaveBeenCalledWith(scanScriptsOf(text));+ expect(scanScriptsOf(text).length).toBeGreaterThan(0);+ expect(loadedBeforeRanking).toBe(true);+ });++ test("matches a font again when a matcher stopped before ranking lets it go", async () => {+ vi.mocked(matchableSample).mockReturnValue(sampleWith("Invoice total"));+ const held = deferred();+ vi.mocked(loadScriptScanFaces).mockImplementationOnce(() => held.promise);+ const { showFonts } = setupWithFonts([FONT]);+ await waitFor(() => expect(loadScriptScanFaces).toHaveBeenCalled());+ showFonts([FONT, "F2"]);+ await waitFor(() =>+ expect(setClosestFont).toHaveBeenCalledWith("F2", "Noto Sans JP"),+ );+ held.resolve();+ await waitFor(() =>+ expect(setClosestFont).toHaveBeenCalledWith(FONT, "Noto Sans JP"),+ );+ });++ test("matches a font again when a matcher stopped mid-ranking lets it go", async () => {+ vi.mocked(matchableSample).mockReturnValue(sampleWith("Invoice total"));+ const held = deferred();+ vi.mocked(fitInSlices).mockImplementationOnce(async (fit, live) => {+ await held.promise;+ return live() ? fit() : null;+ });+ const { showFonts } = setupWithFonts([FONT]);+ await waitFor(() => expect(fitInSlices).toHaveBeenCalled());+ showFonts([FONT, "F2"]);+ await waitFor(() =>+ expect(setClosestFont).toHaveBeenCalledWith("F2", "Noto Sans JP"),+ );+ held.resolve();+ await waitFor(() =>+ expect(setClosestFont).toHaveBeenCalledWith(FONT, "Noto Sans JP"),+ );+ });+});diff --git a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useDocumentFontCompletion.ts b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useDocumentFontCompletion.tsnew file mode 100644index 0000000000..10729af84a--- /dev/null+++ b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useDocumentFontCompletion.ts@@ -0,0 +1,189 @@+import { useEffect, useMemo, useRef, useSyncExternalStore } from "react";+import type {+ EditorStore,+ EditorViewState,+} from "@editor/tools/pdfTextEditor/store/EditorStore";+import type { SelectionState } from "@editor/tools/pdfTextEditor/types";+import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";+import {+ listLocalFontsIfGranted,+ type LocalFont,+} from "@editor/tools/pdfTextEditor/util/localFonts";+import {+ fontCanBeCompleted,+ fontCompletionFor,+ fontCompletionsGeneration,+ originalFontLookedUp,+ resolveOriginalFonts,+ setClosestFont,+ subscribeFontCompletions,+} from "@editor/tools/pdfTextEditor/util/documentFontCompletion";+import {+ loadedExternalFonts,+ subscribeExternalFonts,+} from "@editor/tools/pdfTextEditor/util/externalFonts";+import { isDocumentFontId } from "@editor/tools/pdfTextEditor/util/fontFamily";+import { matchableSample } from "@editor/tools/pdfTextEditor/util/matchableSample";+import {+ isScanRun,+ rankFacesForDrawnText,+} from "@editor/tools/pdfTextEditor/commands/scanTextEdit";+import { fitInSlices } from "@editor/tools/pdfTextEditor/commands/scanFitSlices";+import {+ loadBundledScanFaces,+ loadDeviceScanFacesIfAllowed,+ loadScriptScanFaces,+ scanScriptsOf,+} from "@editor/tools/pdfTextEditor/util/scanFontLibrary";++const closestTried = new WeakMap<EditorDocument, Set<string>>();+const unsampledAt = new WeakMap<EditorDocument, Map<string, number>>();++/** Changes whenever a completion font is found or forgotten. */+export function useFontCompletionsGeneration(): number {+ return useSyncExternalStore(+ subscribeFontCompletions,+ fontCompletionsGeneration,+ fontCompletionsGeneration,+ );+}++function documentFontsKey(pages: EditorViewState["pages"]): string {+ const ids = new Set<string>();+ for (const page of pages)+ for (const run of page.runs)+ if (!isScanRun(run) && isDocumentFontId(run.fontId)) ids.add(run.fontId);+ return [...ids].sort().join("\n");+}++function selectedFontOf(+ pages: EditorViewState["pages"],+ runIds: string[],+): string | null {+ if (runIds.length !== 1) return null;+ for (const page of pages)+ for (const run of page.runs) if (run.id === runIds[0]) return run.fontId;+ return null;+}++/** Resolves what completes each embedded font: its installed or served original once font lists are in, else the closest face, matched in the background. */+export function useDocumentFontCompletion(+ store: EditorStore,+ state: EditorViewState,+ selection: SelectionState,+ externalFonts: LocalFont[] | null,+): void {+ // The picker lists installed fonts when it opens; an edit can need them before that.+ useEffect(() => {+ void listLocalFontsIfGranted();+ }, []);++ const fontsKey = useMemo(() => documentFontsKey(state.pages), [state.pages]);+ const selectedFont = useRef<string | null>(null);+ useEffect(() => {+ selectedFont.current = selectedFontOf(state.pages, selection.runIds);+ }, [state.pages, selection.runIds]);+ const wakeMatching = useRef<() => void>(() => {});+ useEffect(() => wakeMatching.current(), [state.pages]);++ useEffect(() => {+ const doc = store.document;+ if (!doc || !externalFonts || !fontsKey) return;+ void resolveOriginalFonts(+ doc.module,+ fontsKey.split("\n"),+ () => store.document === doc,+ );+ }, [store, externalFonts, fontsKey]);++ useEffect(() => {+ const doc = store.document;+ if (!doc || !fontsKey) return;+ const tried = closestTried.get(doc) ?? new Set<string>();+ closestTried.set(doc, tried);+ const unsampled = unsampledAt.get(doc) ?? new Map<string, number>();+ unsampledAt.set(doc, unsampled);+ const fontIds = fontsKey.split("\n");+ let stopped = false;+ let running = false;+ let wokenWhileRunning = false;+ const live = () => !stopped && store.document === doc;++ const wanted = (fontId: string) => {+ if (tried.has(fontId) || fontCompletionFor(fontId)) return false;+ if (unsampled.get(fontId) === doc.loadedPages().length) return false;+ if (!fontCanBeCompleted(doc.module, fontId)) return false;+ // With font lists in, the original gets its chance first; one found later still takes over.+ return !loadedExternalFonts()?.length || originalFontLookedUp(fontId);+ };+ const nextFont = () => {+ const selected = selectedFont.current;+ if (selected && fontIds.includes(selected) && wanted(selected))+ return selected;+ return fontIds.find(wanted) ?? null;+ };++ // Cut off part-way: the matcher that replaced this one may already have passed the font by.+ const release = (fontId: string) => {+ tried.delete(fontId);+ wakeMatching.current();+ };++ const matchClosest = async () => {+ if (running) {+ wokenWhileRunning = true;+ return;+ }+ running = true;+ try {+ await Promise.all([+ loadBundledScanFaces(),+ loadDeviceScanFacesIfAllowed(),+ ]).catch(() => undefined);+ for (let fontId = nextFont(); fontId && live(); fontId = nextFont()) {+ const sample = matchableSample(doc, fontId);+ if (!sample) {+ unsampled.set(fontId, doc.loadedPages().length);+ continue;+ }+ unsampled.delete(fontId);+ tried.add(fontId);+ await loadScriptScanFaces(scanScriptsOf(sample.text)).catch(+ () => undefined,+ );+ if (!live()) {+ release(fontId);+ break;+ }+ const ranked = await fitInSlices(+ () => rankFacesForDrawnText(doc, sample.page, sample.captured),+ live,+ ).catch((err: unknown) => {+ console.warn("[pdf-editor] no closest font found", err);+ return [];+ });+ if (!ranked) release(fontId);+ else if (ranked[0]) setClosestFont(fontId, ranked[0].style.family);+ }+ } finally {+ running = false;+ }+ if (wokenWhileRunning && live()) {+ wokenWhileRunning = false;+ void matchClosest();+ }+ };++ const wake = () => void matchClosest();+ wakeMatching.current = wake;+ const unsubscribeCompletions = subscribeFontCompletions(wake);+ const unsubscribeFonts = subscribeExternalFonts(wake);+ wake();+ return () => {+ stopped = true;+ wakeMatching.current = () => {};+ unsubscribeCompletions();+ unsubscribeFonts();+ };+ }, [store, fontsKey]);+}diff --git a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useScanFontMatch.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useScanFontMatch.test.tsnew file mode 100644index 0000000000..c3c41821f4--- /dev/null+++ b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useScanFontMatch.test.ts@@ -0,0 +1,120 @@+import { act, renderHook } from "@testing-library/react";+import { describe, expect, test, vi } from "vitest";++vi.mock(+ "@editor/tools/pdfTextEditor/commands/scanTextEdit",+ async (importOriginal) => ({+ ...(await importOriginal<object>()),+ scanEditOf: () => null,+ scanBlockUndrawable: () => false,+ scanBlockOffInk: () => false,+ rerankScanStyles: () => [],+ }),+);+import {+ APPROXIMATE_MATCH_SCORE,+ isApproximateMatch,+ useScanFontMatch,+} from "@editor/tools/pdfTextEditor/hooks/useScanFontMatch";+import type {+ EditorStore,+ EditorViewState,+} from "@editor/tools/pdfTextEditor/store/EditorStore";+import type { SelectionState } from "@editor/tools/pdfTextEditor/types";+import { RENDER_MODE_INVISIBLE } from "@editor/tools/pdfTextEditor/types";+import type {+ RankedStyle,+ ScanStyle,+} from "@editor/tools/pdfTextEditor/commands/scanFit";+import {+ HELVETICA,+ TIMES,+ type Face,+} from "@editor/tools/pdfTextEditor/util/scanFontLibrary";++const style: ScanStyle = {+ family: "Helvetica",+ fontSize: 12,+ stretch: 1,+ ink: { r: 0, g: 0, b: 0, a: 255 },+ weight: 0,+ hollow: 0,+ softness: 0,+};++const ranked = (face: Face, score: number): RankedStyle => ({+ face,+ style: { ...style, family: face.family },+ score,+});++describe("approximate scan font matches", () => {+ test("flags a best match that scores under the threshold", () => {+ const choices = [ranked(HELVETICA, 0.74), ranked(TIMES, 0.72)];+ expect(isApproximateMatch(choices, choices[0])).toBe(true);+ });++ test("does not flag a best match at or over the threshold", () => {+ const choices = [+ ranked(HELVETICA, APPROXIMATE_MATCH_SCORE),+ ranked(TIMES, 0.6),+ ];+ expect(isApproximateMatch(choices, choices[0])).toBe(false);+ });++ test("does not flag the only font that can draw the script", () => {+ const only = [ranked(HELVETICA, 0.57)];+ expect(isApproximateMatch(only, only[0])).toBe(false);+ });+});++function fakeDocument(pageCount: number) {+ const pages = Array.from({ length: pageCount }, (_, i) => ({+ index: i,+ findRun: (id: string) =>+ id === `r${i}`+ ? { id, text: "Invoice", renderMode: RENDER_MODE_INVISIBLE }+ : undefined,+ }));+ return {+ page: (i: number) => {+ if (!pages[i]) throw new Error(`no page ${i}`);+ return pages[i];+ },+ };+}++const viewOf = (pageCount: number) =>+ ({+ pages: Array.from({ length: pageCount }, (_, pageIndex) => ({+ pageIndex,+ runs: [+ {+ id: `r${pageIndex}`,+ text: "Invoice",+ renderMode: RENDER_MODE_INVISIBLE,+ },+ ],+ })),+ }) as unknown as EditorViewState;++describe("the scan font picker", () => {+ test("closes when another document replaces the one it was opened on", () => {+ const store = { document: fakeDocument(3), dispatch: () => {} };+ const selected = { runIds: ["r2"] } as unknown as SelectionState;+ const view = renderHook(+ ({ state, selection }) =>+ useScanFontMatch(store as unknown as EditorStore, state, selection),+ { initialProps: { state: viewOf(3), selection: selected } },+ );+ act(() => view.result.current!.show());+ expect(view.result.current?.open).toBe(true);++ store.document = fakeDocument(1);+ view.rerender({+ state: viewOf(1),+ selection: { runIds: [] } as unknown as SelectionState,+ });+ expect(view.result.current).toBeNull();+ });+});diff --git a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useScanFontMatch.ts b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useScanFontMatch.tsnew file mode 100644index 0000000000..44ce73169d--- /dev/null+++ b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useScanFontMatch.ts@@ -0,0 +1,326 @@+import {+ useCallback,+ useEffect,+ useMemo,+ useState,+ useSyncExternalStore,+} from "react";+import type {+ EditorStore,+ EditorViewState,+} from "@editor/tools/pdfTextEditor/store/EditorStore";+import type { SelectionState } from "@editor/tools/pdfTextEditor/types";+import {+ drawnBlockStyle,+ isScanRun,+ previewScanStyle,+ rerankScanStyles,+ scanBlockOffInk,+ scanBlockUndrawable,+ scanEditOf,+} from "@editor/tools/pdfTextEditor/commands/scanTextEdit";+import {+ preferredScanFace,+ type RankedStyle,+ type ScanStyle,+} from "@editor/tools/pdfTextEditor/commands/scanFit";+import { FIT_PAUSED } from "@editor/tools/pdfTextEditor/commands/scanStyle";+import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";+import type { TextRun } from "@editor/tools/pdfTextEditor/model/TextRun";+import {+ FIT_GAP_MS,+ inSlice,+} from "@editor/tools/pdfTextEditor/commands/scanFitSlices";+import { SetScanStyleCommand } from "@editor/tools/pdfTextEditor/commands/SetScanStyleCommand";+import type { PixelPatch } from "@editor/tools/pdfTextEditor/pdfium/BackgroundSampler";+import {+ localFontPermission,+ watchLocalFontPermission,+ type LocalFontPermission,+} from "@editor/tools/pdfTextEditor/util/localFontSource";+import {+ deviceFontsCouldCover,+ deviceScanFaceCount,+ faceCovers,+ loadDeviceScanFaces,+ noteRankedWithCurrentFaces,+ rankedWithCurrentFaces,+ scanFaces,+ scanFacesGeneration,+ subscribeScanFaces,+} from "@editor/tools/pdfTextEditor/util/scanFontLibrary";++export const APPROXIMATE_MATCH_SCORE = 0.8;++export interface ScanFontChoice {+ label: string;+ match: number;+ preview: string | null;+ active: boolean;+ approximate: boolean;+}++export interface ScanFontMatch {+ status: "matching" | "ready" | "unmeasurable" | "noFont";+ scan: string | null;+ choices: ScanFontChoice[];+ choose: (index: number) => void;+ open: boolean;+ canShow: boolean;+ approximate: boolean;+ undrawable: boolean;+ typedFromScan: boolean;+ show: () => void;+ close: () => void;+ deviceFonts: {+ available: boolean;+ permission: LocalFontPermission;+ loading: boolean;+ count: number | null;+ load: () => void;+ };+}++function patchUrl(patch: PixelPatch): string | null {+ if (typeof document === "undefined") return null;+ const canvas = document.createElement("canvas");+ canvas.width = patch.width;+ canvas.height = patch.height;+ const ctx = canvas.getContext("2d");+ if (!ctx) return null;+ ctx.putImageData(+ new ImageData(new Uint8ClampedArray(patch.rgba), patch.width, patch.height),+ 0,+ 0,+ );+ return canvas.toDataURL();+}++interface Ranked {+ runId: string;+ drawable: boolean;+ ranked: RankedStyle[];+ scan: string | null;+ previews: Array<string | null>;+}++function currentRanking(+ doc: EditorDocument,+ run: TextRun,+): RankedStyle[] | null {+ const block = scanEditOf(doc, run)?.block;+ if (!block || !rankedWithCurrentFaces(block.ranked)) return null;+ const preferred = preferredScanFace(doc);+ const fresh =+ !preferred ||+ block.preferred === preferred ||+ block.ranked.some((r) => r.face.label === preferred);+ return fresh ? block.ranked : null;+}++export function isApproximateMatch(+ ranked: RankedStyle[],+ choice: RankedStyle,+): boolean {+ return ranked.length > 1 && choice.score < APPROXIMATE_MATCH_SCORE;+}++function matchStatus(current: Ranked | null): ScanFontMatch["status"] {+ if (!current) return "matching";+ if (current.ranked.length > 0) return "ready";+ return current.drawable ? "unmeasurable" : "noFont";+}++function drawnStyle(doc: EditorDocument, run: TextRun): ScanStyle | undefined {+ const state = scanEditOf(doc, run);+ if (!state || state.typedFromScan) return undefined;+ return state.override.style ?? drawnBlockStyle(doc, state) ?? undefined;+}++interface ScanRunRef {+ runId: string;+ pageIndex: number;+}++function runOf(store: EditorStore, ref: ScanRunRef | null) {+ const doc = store.document;+ const run = ref ? doc?.page(ref.pageIndex).findRun(ref.runId) : null;+ return doc && run ? { doc, run } : null;+}++export function useScanFontMatch(+ store: EditorStore,+ state: EditorViewState,+ selection: SelectionState,+): ScanFontMatch | null {+ const facesVersion = useSyncExternalStore(+ subscribeScanFaces,+ scanFacesGeneration,+ scanFacesGeneration,+ );+ const selected = useMemo<ScanRunRef | null>(() => {+ if (selection.runIds.length !== 1) return null;+ const id = selection.runIds[0];+ for (const page of state.pages)+ for (const run of page.runs)+ if (run.id === id && isScanRun(run))+ return { runId: id, pageIndex: page.pageIndex };+ return null;+ }, [selection.runIds, state.pages]);++ const [ranked, setRanked] = useState<Ranked | null>(null);+ const [loadingDevice, setLoadingDevice] = useState(false);+ const [permission, setPermission] =+ useState<LocalFontPermission>("unsupported");+ const [opened, setPicking] = useState<+ (ScanRunRef & { doc: EditorDocument | null }) | null+ >(null);+ const picking = opened && opened.doc === store.document ? opened : null;++ const loadDevice = useCallback(() => {+ setLoadingDevice(true);+ void loadDeviceScanFaces()+ .then(localFontPermission)+ .then(setPermission)+ .finally(() => setLoadingDevice(false));+ }, []);++ useEffect(() => {+ if (!picking) return;+ let stopped = false;+ const settle = (next: LocalFontPermission) => {+ if (stopped) return;+ setPermission(next);+ if (next === "granted" && deviceScanFaceCount() === null) loadDevice();+ };+ void localFontPermission().then(settle);+ const unwatch = watchLocalFontPermission(settle);+ return () => {+ stopped = true;+ unwatch();+ };+ }, [picking, loadDevice]);++ const target = picking ?? selected;++ useEffect(() => {+ if (!picking) return;+ let timer = 0;+ let undrawable: boolean | null = null;+ const attempt = () => {+ const doc = store.document;+ if (!doc || doc !== picking.doc) return;+ const page = doc.page(picking.pageIndex);+ const run = page.findRun(picking.runId);+ undrawable ??= !!run && scanBlockUndrawable(doc, run);+ const fitted = run+ ? (currentRanking(doc, run) ??+ inSlice(() => rerankScanStyles(doc, page, run)))+ : [];+ if (fitted === FIT_PAUSED) {+ timer = window.setTimeout(attempt, FIT_GAP_MS);+ return;+ }+ noteRankedWithCurrentFaces(fitted);+ if (undrawable && fitted[0] && run && scanEditOf(doc, run)?.edited)+ store.dispatch(+ new SetScanStyleCommand({+ pageIndex: picking.pageIndex,+ runId: picking.runId,+ choice: fitted[0],+ }),+ );+ const previews = fitted.map((choice) =>+ run ? previewScanStyle(doc, page, run, choice.style) : null,+ );+ setRanked({+ runId: picking.runId,+ drawable: !!run && scanFaces().some((f) => faceCovers(f, run.text)),+ ranked: fitted,+ scan: previews[0] ? patchUrl(previews[0].scan) : null,+ previews: previews.map((p) => (p ? patchUrl(p.drawn) : null)),+ });+ };+ timer = window.setTimeout(attempt, 0);+ return () => window.clearTimeout(timer);+ }, [store, picking, facesVersion]);++ const targetRun = runOf(store, target);+ const activeStyle = targetRun+ ? drawnStyle(targetRun.doc, targetRun.run)+ : undefined;+ const activeFamily = activeStyle?.family;+ const activeSize = activeStyle?.fontSize;+ const isActive = useCallback(+ (choice: RankedStyle) =>+ activeFamily !== undefined &&+ activeFamily === choice.style.family &&+ activeSize === choice.style.fontSize,+ [activeFamily, activeSize],+ );++ const choose = useCallback(+ (index: number) => {+ if (!target || !ranked || ranked.runId !== target.runId) return;+ const choice = ranked.ranked[index];+ if (!choice) return;+ if (!isActive(choice))+ store.dispatch(+ new SetScanStyleCommand({+ pageIndex: target.pageIndex,+ runId: target.runId,+ choice,+ }),+ );+ setPicking(null);+ },+ [store, target, ranked, isActive],+ );++ if (!target) return null;+ const selectedRun = runOf(store, selected);+ const unfitted =+ !!selectedRun && scanBlockUndrawable(selectedRun.doc, selectedRun.run);+ const undrawable =+ unfitted &&+ !!selectedRun &&+ !scanFaces().some((f) => faceCovers(f, selectedRun.run.text));+ const scanEdit = selectedRun?.run.scanEdit;+ const redrawn = !!scanEdit?.created.length || !!scanEdit?.override.style;+ const offInk =+ !!selectedRun && scanBlockOffInk(selectedRun.doc, selectedRun.run);+ const current = ranked && ranked.runId === target.runId ? ranked : null;+ const applied = targetRun+ ? (scanEditOf(targetRun.doc, targetRun.run)?.block?.ranked ?? [])+ : [];+ const appliedChoice = applied.find(isActive);+ return {+ status: matchStatus(current),+ scan: current?.scan ?? null,+ choices: (current?.ranked ?? []).map((choice, i) => ({+ label: choice.face.label,+ match: Math.round(Math.max(0, choice.score) * 100),+ preview: current?.previews[i] ?? null,+ active: isActive(choice),+ approximate: isApproximateMatch(current?.ranked ?? [], choice),+ })),+ choose,+ open: !!picking,+ canShow: (redrawn || unfitted) && !offInk,+ approximate: !!appliedChoice && isApproximateMatch(applied, appliedChoice),+ undrawable,+ typedFromScan: !!targetRun?.run.scanEdit?.typedFromScan,+ show: () => {+ setRanked(null);+ setPicking(selected && { ...selected, doc: store.document });+ },+ close: () => setPicking(null),+ deviceFonts: {+ available: !!targetRun && deviceFontsCouldCover(targetRun.run.text),+ permission,+ loading: loadingDevice,+ count: deviceScanFaceCount(),+ load: loadDevice,+ },+ };+}diff --git a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useScanPrefit.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useScanPrefit.test.tsnew file mode 100644index 0000000000..86bd501d74--- /dev/null+++ b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useScanPrefit.test.ts@@ -0,0 +1,256 @@+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";+import { renderHook } from "@testing-library/react";+import { useScanPrefit } from "@editor/tools/pdfTextEditor/hooks/useScanPrefit";+import { setPreferredScanFace } from "@editor/tools/pdfTextEditor/commands/scanFit";+import {+ prefitScanRun,+ scanRunNeedsFit,+} from "@editor/tools/pdfTextEditor/commands/scanTextEdit";+import {+ loadBundledScanFaces,+ loadDeviceScanFacesIfAllowed,+} from "@editor/tools/pdfTextEditor/util/scanFontLibrary";+import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";+import type {+ EditorStore,+ EditorViewState,+} from "@editor/tools/pdfTextEditor/store/EditorStore";++vi.mock("@editor/tools/pdfTextEditor/commands/scanTextEdit", async () => {+ const { RENDER_MODE_INVISIBLE } = await vi.importActual<+ typeof import("@editor/tools/pdfTextEditor/types")+ >("@editor/tools/pdfTextEditor/types");+ return {+ isScanRun: (run: { renderMode?: number }) =>+ run.renderMode === RENDER_MODE_INVISIBLE,+ prefitScanRun: vi.fn(),+ scanRunNeedsFit: vi.fn(),+ };+});++vi.mock(+ "@editor/tools/pdfTextEditor/util/scanFontLibrary",+ async (importOriginal) => ({+ ...(await importOriginal<object>()),+ loadBundledScanFaces: vi.fn(() => Promise.resolve()),+ loadDeviceScanFacesIfAllowed: vi.fn(() => Promise.resolve()),+ loadScriptScanFaces: vi.fn(() => Promise.resolve()),+ }),+);++const fitted = new Set<string>();+const order: string[] = [];+let failing = new Set<string>();++function setup(+ pages: Array<{ ids: string[]; near: boolean; shown?: boolean }>,+) {+ const near = new Set(pages.flatMap((p, i) => (p.near ? [i] : [])));+ const unshown = new Set(+ pages.flatMap((p, i) => (p.shown === false ? [i] : [])),+ );+ const nearListeners = new Set<() => void>();+ const selectionListeners = new Set<() => void>();+ const doc = {+ loadedPages: () =>+ pages.map((p, index) => ({+ index,+ shownInViewer: !unshown.has(index),+ runs: p.ids.map((id) => runs.get(id)!),+ })),+ } as unknown as EditorDocument;+ const runs = new Map(pages.flatMap((p) => p.ids.map((id) => [id, { id }])));+ const selection = { runIds: [] as string[] };+ const store = {+ document: doc,+ selection: {+ get value() {+ return selection;+ },+ subscribe: (l: () => void) => {+ selectionListeners.add(l);+ return () => selectionListeners.delete(l);+ },+ },+ isPageNearViewport: (i: number) => near.has(i),+ subscribeNearViewport: (l: () => void) => {+ nearListeners.add(l);+ return () => nearListeners.delete(l);+ },+ } as unknown as EditorStore;+ const stateOf = (text: string) =>+ ({+ pages: pages.map((p, pageIndex) => ({+ pageIndex,+ runs: p.ids.map((id) => ({ id, renderMode: 3, text })),+ })),+ }) as unknown as EditorViewState;+ const view = renderHook(({ state }) => useScanPrefit(store, state), {+ initialProps: { state: stateOf("Invoice") },+ });+ return {+ doc,+ view,+ showText: (text: string) => view.rerender({ state: stateOf(text) }),+ select: (ids: string[]) => {+ selection.runIds = ids;+ for (const l of [...selectionListeners]) l();+ },+ bringNear: (i: number) => {+ near.add(i);+ for (const l of [...nearListeners]) l();+ },+ draw: (i: number) => unshown.delete(i),+ loadRuns: (i: number, ids: string[]) => {+ pages[i].ids = ids;+ for (const id of ids) runs.set(id, { id });+ view.rerender({ state: stateOf("Invoice") });+ },+ };+}++beforeEach(() => {+ vi.useFakeTimers();+ fitted.clear();+ order.length = 0;+ failing = new Set();+ vi.mocked(scanRunNeedsFit).mockImplementation(+ (_doc, run) => !fitted.has(run.id),+ );+ vi.mocked(prefitScanRun).mockImplementation((_doc, _page, run) => {+ order.push(run.id);+ if (failing.has(run.id)) throw new Error("unfittable");+ fitted.add(run.id);+ return true;+ });+});++afterEach(() => {+ vi.useRealTimers();+});++describe("background scan font fitting", () => {+ test("fits the selected run before earlier runs on the page", async () => {+ const { select } = setup([{ ids: ["a", "b", "c"], near: true }]);+ select(["c"]);+ await vi.advanceTimersByTimeAsync(100);+ expect(order).toEqual(["c", "a", "b"]);+ });++ test("asks for the device's fonts without holding up the first fit", async () => {+ vi.mocked(loadDeviceScanFacesIfAllowed).mockReturnValueOnce(+ new Promise(() => {}),+ );+ setup([{ ids: ["a"], near: true }]);+ await vi.advanceTimersByTimeAsync(100);+ expect(loadDeviceScanFacesIfAllowed).toHaveBeenCalled();+ expect(order).toEqual(["a"]);+ });++ test("reads installed fonts again when text in a new script turns up", async () => {+ const { showText } = setup([{ ids: ["a"], near: true }]);+ await vi.advanceTimersByTimeAsync(100);+ vi.mocked(loadDeviceScanFacesIfAllowed).mockClear();+ showText("請求書");+ await vi.advanceTimersByTimeAsync(100);+ expect(loadDeviceScanFacesIfAllowed).toHaveBeenCalled();+ });++ test("leaves runs on far pages until one is selected or the page comes near", async () => {+ const { select, bringNear } = setup([+ { ids: ["a"], near: true },+ { ids: ["b", "c"], near: false },+ { ids: ["d"], near: false },+ ]);+ await vi.advanceTimersByTimeAsync(100);+ expect(order).toEqual(["a"]);+ select(["d"]);+ await vi.advanceTimersByTimeAsync(100);+ expect(order).toEqual(["a", "d"]);+ bringNear(1);+ await vi.advanceTimersByTimeAsync(100);+ expect(order).toEqual(["a", "d", "b", "c"]);+ });++ test("waits for the viewer to draw a page, even for a selected run", async () => {+ const { select, draw } = setup([{ ids: ["a"], near: true, shown: false }]);+ select(["a"]);+ await vi.advanceTimersByTimeAsync(100);+ expect(order).toEqual([]);+ draw(0);+ await vi.advanceTimersByTimeAsync(1000);+ expect(order).toEqual(["a"]);+ });++ test("fits the runs of a page that loads after fitting went idle", async () => {+ const { loadRuns } = setup([+ { ids: ["a"], near: true },+ { ids: [], near: true },+ ]);+ await vi.advanceTimersByTimeAsync(100);+ expect(order).toEqual(["a"]);+ loadRuns(1, ["b"]);+ await vi.advanceTimersByTimeAsync(100);+ expect(order).toEqual(["a", "b"]);+ });++ test("skips a run that cannot be fitted and finishes the rest", async () => {+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});+ failing = new Set(["a"]);+ setup([{ ids: ["a", "b"], near: true }]);+ await vi.advanceTimersByTimeAsync(100);+ expect(order).toEqual(["a", "b"]);+ expect(warn).toHaveBeenCalledOnce();+ warn.mockRestore();+ });++ test("waits for the bundled fonts before fitting", async () => {+ let loaded = () => {};+ vi.mocked(loadBundledScanFaces).mockReturnValueOnce(+ new Promise<void>((resolve) => (loaded = resolve)),+ );+ setup([{ ids: ["a"], near: true }]);+ await vi.advanceTimersByTimeAsync(100);+ expect(order).toEqual([]);+ loaded();+ await vi.advanceTimersByTimeAsync(100);+ expect(order).toEqual(["a"]);+ });++ test("an idle loop starts again when the preferred face changes", async () => {+ const { doc } = setup([{ ids: ["a"], near: true }]);+ await vi.advanceTimersByTimeAsync(100);+ fitted.delete("a");+ setPreferredScanFace(doc, "Courier");+ await vi.advanceTimersByTimeAsync(100);+ expect(order).toEqual(["a", "a"]);+ setPreferredScanFace(doc, null);+ });++ test("pauses while the page is hidden", async () => {+ let hidden = true;+ const spy = vi+ .spyOn(document, "hidden", "get")+ .mockImplementation(() => hidden);+ try {+ setup([{ ids: ["a"], near: true }]);+ await vi.advanceTimersByTimeAsync(100);+ expect(order).toEqual([]);+ hidden = false;+ document.dispatchEvent(new Event("visibilitychange"));+ await vi.advanceTimersByTimeAsync(100);+ expect(order).toEqual(["a"]);+ } finally {+ spy.mockRestore();+ }+ });++ test("stops fitting once unmounted", async () => {+ const { view, select } = setup([{ ids: ["a", "b"], near: false }]);+ select(["a"]);+ view.unmount();+ select(["b"]);+ await vi.advanceTimersByTimeAsync(100);+ expect(order).toEqual([]);+ });+});diff --git a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useScanPrefit.ts b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useScanPrefit.tsnew file mode 100644index 0000000000..c2db037c06--- /dev/null+++ b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useScanPrefit.ts@@ -0,0 +1,206 @@+import { useEffect, useMemo, useRef } from "react";+import type {+ EditorStore,+ EditorViewState,+} from "@editor/tools/pdfTextEditor/store/EditorStore";+import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";+import type { PageSnapshot } from "@editor/tools/pdfTextEditor/types";+import {+ isScanRun,+ prefitScanRun,+ scanRunNeedsFit,+} from "@editor/tools/pdfTextEditor/commands/scanTextEdit";+import { subscribePreferredScanFace } from "@editor/tools/pdfTextEditor/commands/scanFit";+import {+ FIT_GAP_MS,+ FIT_SLICE_MS,+} from "@editor/tools/pdfTextEditor/commands/scanFitSlices";+import {+ loadBundledScanFaces,+ loadDeviceScanFacesIfAllowed,+ loadScriptScanFaces,+ noteRankedWithCurrentFaces,+ scanScriptsOf,+ subscribeScanFaces,+ type Script,+} from "@editor/tools/pdfTextEditor/util/scanFontLibrary";++const UNSHOWN_RECHECK_MS = 500;++const scriptsByPage = new WeakMap<PageSnapshot, Script[] | null>();++function pageScripts(page: PageSnapshot): Script[] | null {+ let scripts = scriptsByPage.get(page);+ if (scripts === undefined) {+ const text = page.runs.filter(isScanRun).map((run) => run.text);+ scripts = text.length > 0 ? scanScriptsOf(text.join(" ")) : null;+ scriptsByPage.set(page, scripts);+ }+ return scripts;+}++function nextScanRun(+ doc: EditorDocument,+ store: EditorStore,+ skipped: WeakSet<object>,+ wanted: string[],+) {+ let fallback = null;+ for (const page of doc.loadedPages()) {+ if (!page.shownInViewer) continue;+ const near = store.isPageNearViewport(page.index);+ for (const run of page.runs) {+ const isWanted = wanted.includes(run.id);+ if (!isWanted && (!near || fallback)) continue;+ if (skipped.has(run) || !scanRunNeedsFit(doc, run)) continue;+ if (isWanted) return { page, run };+ fallback = { page, run };+ }+ }+ return fallback;+}++const awaitsViewer = (+ doc: EditorDocument,+ store: EditorStore,+ wanted: string[],+) =>+ doc+ .loadedPages()+ .some(+ (page) =>+ !page.shownInViewer &&+ page.runs.some(+ (run) =>+ (store.isPageNearViewport(page.index) || wanted.includes(run.id)) &&+ scanRunNeedsFit(doc, run),+ ),+ );++export function useScanPrefit(+ store: EditorStore,+ state: EditorViewState,+): void {+ const { hasScannedText, scripts } = useMemo(() => {+ const found = new Set<Script>();+ let scanned = false;+ for (const page of state.pages) {+ const own = pageScripts(page);+ if (!own) continue;+ scanned = true;+ for (const script of own) found.add(script);+ }+ return { hasScannedText: scanned, scripts: [...found].sort() };+ }, [state.pages]);+ const scriptKey = scripts.join(" ");+ const resume = useRef<() => void>(() => {});+ const scriptsRef = useRef(scripts);+ scriptsRef.current = scripts;++ useEffect(() => {+ if (!hasScannedText) return;+ let stopped = false;+ let ready = false;+ let timer = 0;+ let idle = true;+ let fittedSinceSnapshot = false;+ let hovered: string | null = null;+ const skipped = new WeakSet<object>();+ const onPointerOver = (e: PointerEvent) => {+ const el =+ e.target instanceof Element ? e.target.closest("[data-run-id]") : null;+ const id = el?.getAttribute("data-run-id");+ if (!id || id === hovered) return;+ hovered = id;+ resume.current();+ };+ const step = () => {+ const doc = store.document;+ const wanted = [...store.selection.value.runIds];+ if (hovered) wanted.push(hovered);+ const next =+ !stopped && doc && !document.hidden+ ? nextScanRun(doc, store, skipped, wanted)+ : null;+ if (!doc || !next) {+ if (+ doc &&+ !stopped &&+ !document.hidden &&+ awaitsViewer(doc, store, wanted)+ )+ timer = window.setTimeout(step, UNSHOWN_RECHECK_MS);+ else idle = true;+ // The editing layer and the font box both read the match from the run snapshots.+ if (idle && fittedSinceSnapshot) {+ fittedSinceSnapshot = false;+ store.resnapshot();+ }+ return;+ }+ try {+ const finished = prefitScanRun(+ doc,+ next.page,+ next.run,+ performance.now() + FIT_SLICE_MS,+ );+ const ranked = next.run.scanEdit?.block?.ranked;+ if (finished && scanRunNeedsFit(doc, next.run)) skipped.add(next.run);+ else if (finished && ranked) {+ noteRankedWithCurrentFaces(ranked);+ // A fit changes no page content, so nothing else marks the snapshot stale.+ next.page.bumpRevision();+ fittedSinceSnapshot = true;+ }+ } catch (err) {+ console.warn("[pdf-editor] scanned text could not be fitted", err);+ skipped.add(next.run);+ }+ timer = window.setTimeout(step, FIT_GAP_MS);+ };+ resume.current = () => {+ if (stopped || !ready || !idle) return;+ idle = false;+ timer = window.setTimeout(step, FIT_GAP_MS);+ };+ const wake = () => resume.current();+ document.addEventListener("pointerover", onPointerOver);+ document.addEventListener("visibilitychange", wake);+ const unsubscribePreferred = subscribePreferredScanFace(wake);+ const unsubscribeFaces = subscribeScanFaces(wake);+ const unsubscribeNear = store.subscribeNearViewport(wake);+ const unsubscribeSelection = store.selection.subscribe(wake);+ void Promise.all([+ loadBundledScanFaces(),+ loadScriptScanFaces(scriptsRef.current),+ ])+ .catch(() => undefined)+ .then(() => {+ ready = true;+ resume.current();+ });+ return () => {+ stopped = true;+ resume.current = () => {};+ window.clearTimeout(timer);+ unsubscribePreferred();+ unsubscribeFaces();+ unsubscribeNear();+ unsubscribeSelection();+ document.removeEventListener("pointerover", onPointerOver);+ document.removeEventListener("visibilitychange", wake);+ };+ }, [store, hasScannedText]);++ useEffect(() => {+ if (!hasScannedText) return;+ void loadScriptScanFaces(scriptsRef.current).then(() => resume.current());+ // Not awaited: installed fonts can take seconds to read; bundled faces suffice to start and later arrivals re-rank.+ void loadDeviceScanFacesIfAllowed().catch(() => undefined);+ }, [hasScannedText, scriptKey]);++ useEffect(() => {+ resume.current();+ }, [state.pages]);+}diff --git a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useSelectedFontNote.ts b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useSelectedFontNote.tsindex 3d4a37f248..aea2b5e14f 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useSelectedFontNote.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useSelectedFontNote.ts@@ -3,14 +3,18 @@ import { useTranslation } from "react-i18next";import type { EditorViewState } from "@editor/tools/pdfTextEditor/store/EditorStore";import type { SelectionState } from "@editor/tools/pdfTextEditor/types";import { selectedFontNote } from "@editor/tools/pdfTextEditor/util/selectedFontNote";+import { useFontCompletionsGeneration } from "@editor/tools/pdfTextEditor/hooks/useDocumentFontCompletion";import {serverFontBytesVersion,subscribeServerFontBytes,} from "@editor/tools/pdfTextEditor/util/serverFonts";+export type ScanNote = "misaligned" | "offInk" | "dropsTyping" | null;+export function useSelectedFontNote(state: EditorViewState,selection: SelectionState,+ scanNote: ScanNote = null,): string | null {const { t } = useTranslation();const fontBytesVersion = useSyncExternalStore(@@ -18,15 +22,31 @@ export function useSelectedFontNote(serverFontBytesVersion,serverFontBytesVersion,);+ const completions = useFontCompletionsGeneration();return useMemo(() => {const note = selectedFontNote(state.pages, selection.runIds);if (!note) return null;switch (note.kind) {case "scanned":- return t(- "pdfTextEditor.inspector.scannedText",- "Scanned text · changed words are covered and redrawn in a matching font.",- );+ if (scanNote === "misaligned")+ return t(+ "pdfTextEditor.inspector.scannedTextMisaligned",+ "Scanned text · its recognised words do not line up with the scan, so this block cannot be edited or deleted.",+ );+ if (scanNote === "offInk")+ return t(+ "pdfTextEditor.inspector.scannedTextOffInk",+ "Scanned text · its recognised words sit off the scanned words, so this block cannot be edited. Run OCR again.",+ );+ return scanNote === "dropsTyping"+ ? t(+ "pdfTextEditor.inspector.scannedTextNoFont",+ "Scanned text · typed words in this script cannot be drawn yet, so they are not kept. Deleting words still works.",+ )+ : t(+ "pdfTextEditor.inspector.scannedText",+ "Scanned text · changed words are covered and redrawn in a matching font.",+ );case "embeddedUnknown":return t("pdfTextEditor.inspector.fontEmbedded",@@ -38,6 +58,18 @@ export function useSelectedFontNote("{{name}} · a character it lacks falls back to {{fallback}}.",{ name: note.name, fallback: note.fallback },);+ case "completed":+ return note.source === "original"+ ? t(+ "pdfTextEditor.inspector.fontCompletedOriginal",+ "Embedded font · characters it lacks are drawn in {{name}}, the same font.",+ { name: note.name },+ )+ : t(+ "pdfTextEditor.inspector.fontCompletedClosest",+ "Embedded font · characters it lacks are drawn in {{name}}, the closest match available.",+ { name: note.name },+ );case "gap":return t("pdfTextEditor.inspector.fontGap",@@ -45,5 +77,12 @@ export function useSelectedFontNote({ name: note.name, glyphs: note.glyphs, fallback: note.fallback },);}- }, [state.pages, selection.runIds, fontBytesVersion, t]);+ }, [+ state.pages,+ selection.runIds,+ scanNote,+ fontBytesVersion,+ completions,+ t,+ ]);}diff --git a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useSelectionActions.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useSelectionActions.test.tsindex 051259c0da..671b3961b6 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useSelectionActions.test.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useSelectionActions.test.ts@@ -1,6 +1,6 @@import { readFileSync } from "node:fs";import path from "node:path";-import { renderHook } from "@testing-library/react";+import { act, renderHook, waitFor } from "@testing-library/react";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";const { get } = vi.hoisted(() => ({ get: vi.fn() }));@@ -10,6 +10,14 @@ vi.mock("@editor/tools/pdfTextEditor/commands/SetFontFamilyCommand", () => ({constructor(readonly opts: { runId: string; nextFamily: string }) {}},}));+vi.mock(+ "@editor/tools/pdfTextEditor/commands/scanTextEdit",+ async (importOriginal) => ({+ ...(await importOriginal<object>()),+ prefitScanRun: vi.fn(() => true),+ scanRunNeedsFit: vi.fn(() => false),+ }),+);vi.mock("@editor/tools/pdfTextEditor/commands/CompositeCommand", () => ({CompositeCommand: class {constructor(readonly commands: unknown[]) {}@@ -23,8 +31,15 @@ import {loadServerFonts,forgetServerFontList,} from "@editor/tools/pdfTextEditor/util/serverFonts";-import { resetLocalFontsCache } from "@editor/tools/pdfTextEditor/util/localFonts";+import {+ listLocalFonts,+ resetLocalFontsCache,+} from "@editor/tools/pdfTextEditor/util/localFonts";import { resetDeviceFontEmbedCache } from "@editor/tools/pdfTextEditor/util/deviceFontEmbed";+import {+ prefitScanRun,+ scanRunNeedsFit,+} from "@editor/tools/pdfTextEditor/commands/scanTextEdit";const REGULAR = "1".repeat(64);const ITALIC = "2".repeat(64);@@ -173,6 +188,17 @@ describe("useSelectionActions font changes", () => {expect(dispatchedChanges(dispatch)).toEqual(["a:Times-Roman"]);});+ it("leaves a run locked while its font change was waiting", async () => {+ const runs = [run("a", "base14:Helvetica")];+ const { store, dispatch } = fakeStore(runs, ["a"]);++ const change = actionsFor(store).changeFontFamily("Times-Roman");+ runs[0].locked = true;+ expect(await change).toBeNull();++ expect(dispatchedChanges(dispatch)).toEqual([]);+ });+it("leaves the text alone when a server font cannot be downloaded", async () => {serveFaces(async () => {throw new Error("gone");@@ -302,6 +328,27 @@ describe("useSelectionActions font changes", () => {expect(dispatch).not.toHaveBeenCalled();});+ it("keeps a run's font when its device italic face cannot be embedded", async () => {+ const cff = new Uint8Array([0x4f, 0x54, 0x54, 0x4f, 0, 0]);+ const deviceFace = (style: string) => ({+ family: "Acme Serif",+ style,+ postscriptName: `AcmeSerif-${style}`,+ blob: async () => new Blob([cff]),+ });+ (window as unknown as { queryLocalFonts: unknown }).queryLocalFonts =+ async () => [deviceFace("Regular"), deviceFace("Italic")];+ await listLocalFonts();+ const { store, dispatch } = fakeStore(+ [run("a", "device:Acme Serif")],+ ["a"],+ );++ await actionsFor(store).toggleItalic();++ expect(dispatch).not.toHaveBeenCalled();+ });+it("leaves a run locked during the download unchanged", async () => {let finishDownload: (value: { data: ArrayBuffer }) => void = () => {};serveFaces(@@ -366,3 +413,71 @@ describe("useSelectionActions font changes", () => {expect(dispatchedChanges(mixed.dispatch)).toEqual(["b:Noto Sans Hebrew"]);});});++describe("useSelectionActions on unfitted scanned text", () => {+ afterEach(() => {+ vi.mocked(prefitScanRun).mockReset().mockReturnValue(true);+ vi.mocked(scanRunNeedsFit).mockReset().mockReturnValue(false);+ });++ it("fits the scanned blocks in slices behind a busy state before recolouring", async () => {+ const fitted = new Set<string>();+ let calls = 0;+ vi.mocked(scanRunNeedsFit).mockImplementation(+ (_doc, r) => !fitted.has(r.id),+ );+ vi.mocked(prefitScanRun).mockImplementation((_doc, _page, r) => {+ calls++;+ if (calls < 3) return false;+ fitted.add(r.id);+ return true;+ });+ const { store, dispatch } = fakeStore(+ [run("scan", "base14:Helvetica")],+ ["scan"],+ );+ const { result } = renderHook(() => useSelectionActions(store));++ act(() => result.current.changeFill("#ff0000"));++ expect(dispatch).not.toHaveBeenCalled();+ expect(result.current.fittingScan).toBe(true);+ await waitFor(() => expect(dispatch).toHaveBeenCalledTimes(1));+ await waitFor(() => expect(result.current.fittingScan).toBe(false));+ expect(calls).toBe(3);+ for (const [, , , deadline] of vi.mocked(prefitScanRun).mock.calls)+ expect(Number.isFinite(deadline)).toBe(true);+ });++ it("builds each change from the run as it is once the fit has finished", async () => {+ const fitted = new Set<string>();+ vi.mocked(scanRunNeedsFit).mockImplementation(+ (_doc, r) => !fitted.has(r.id),+ );+ const runs = [+ run("scan", "base14:Helvetica"),+ run("gone", "base14:Helvetica"),+ ];+ vi.mocked(prefitScanRun).mockImplementation((_doc, _page, r) => {+ if (runs[0].fill.a === 255) {+ runs[0].fill = { ...runs[0].fill, a: 128 };+ runs.splice(1, 1);+ return false;+ }+ fitted.add(r.id);+ return true;+ });+ const { store, dispatch } = fakeStore(runs, ["scan", "gone"]);+ const { result } = renderHook(() => useSelectionActions(store));++ act(() => result.current.changeFill("#ff0000"));++ await waitFor(() => expect(dispatch).toHaveBeenCalledTimes(1));+ const dispatched = dispatch.mock.calls[0][0] as {+ runId: string;+ nextFill: { r: number; a: number };+ };+ expect(dispatched.runId).toBe("scan");+ expect(dispatched.nextFill).toMatchObject({ r: 255, a: 128 });+ });+});diff --git a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useSelectionActions.ts b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useSelectionActions.tsindex 925ae7a2a6..9095e2702f 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useSelectionActions.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useSelectionActions.ts@@ -12,7 +12,6 @@ import { SetFontSizeCommand } from "@editor/tools/pdfTextEditor/commands/SetFontimport { parseCssColor } from "@editor/tools/pdfTextEditor/model/Color";import {deviceFontDrawsAnyOf,- ensureDeviceFontReady,loadDeviceFontInto,} from "@editor/tools/pdfTextEditor/util/deviceFontEmbed";import type { EditorStore } from "@editor/tools/pdfTextEditor/store/EditorStore";@@ -22,10 +21,17 @@ import {nearestStandardFont,} from "@editor/tools/pdfTextEditor/util/fontFamily";import { italicCapability } from "@editor/tools/pdfTextEditor/util/fontCapability";-import { loadedExternalFonts } from "@editor/tools/pdfTextEditor/util/externalFonts";+import {+ loadedExternalFonts,+ loadExternalFont,+} from "@editor/tools/pdfTextEditor/util/externalFonts";import { serverFaceFor } from "@editor/tools/pdfTextEditor/util/serverFonts";import { CompositeCommand } from "@editor/tools/pdfTextEditor/commands/CompositeCommand";import type { Command } from "@editor/tools/pdfTextEditor/commands/Command";+import type { Page } from "@editor/tools/pdfTextEditor/model/Page";+import type { TextRun } from "@editor/tools/pdfTextEditor/model/TextRun";+import type { ScanFitTarget } from "@editor/tools/pdfTextEditor/commands/scanFitSlices";+import { useDispatchAfterScanFit } from "@editor/tools/pdfTextEditor/hooks/useDispatchAfterScanFit";/** The fields the selection actions read off a run they are about to change. */interface SelectedRun {@@ -36,9 +42,11 @@ interface SelectedRun {fill: { r: number; g: number; b: number; a: number };}-export type FontPickFailure = "serverFontFailed" | "embedFailed" | "noGlyphs";--type ExternalFontLoad = "loaded" | "serverDownloadFailed" | "unavailable";+export type FontPickFailure =+ | "serverFontFailed"+ | "embeddingForbidden"+ | "embedFailed"+ | "noGlyphs";interface FamilyChange {pageIndex: number;@@ -46,9 +54,14 @@ interface FamilyChange {family: string;}-async function prepareExternalFont(family: string): Promise<ExternalFontLoad> {- if (await ensureDeviceFontReady(family)) return "loaded";- return serverFaceFor(family) ? "serverDownloadFailed" : "unavailable";+/** Loads the family's bytes; the failure that must stop the pick, or null to go on. */+async function prepareExternalFont(+ family: string,+): Promise<FontPickFailure | null> {+ const load = await loadExternalFont(family);+ if ("bytes" in load) return null;+ if (serverFaceFor(family)) return "serverFontFailed";+ return load.refused === "licence" ? "embeddingForbidden" : null;}function tryEmbedDeviceFont(doc: EditorDocument, family: string): boolean {@@ -60,23 +73,25 @@ async function fontPickFailure(text: string,): Promise<FontPickFailure | null> {if (nearestStandardFont(family) === family) return null;- if ((await prepareExternalFont(family)) === "serverDownloadFailed")- return "serverFontFailed";+ const refusal = await prepareExternalFont(family);+ if (refusal) return refusal;return deviceFontDrawsAnyOf(family, text) ? null : "noGlyphs";}-function editableRunIds(store: EditorStore): Set<string> {- const ids = new Set<string>();+function liveRuns(store: EditorStore): Map<string, TextRun> {+ const runs = new Map<string, TextRun>();for (const page of store.document?.loadedPages() ?? []) {- for (const run of page.runs) if (!run.locked) ids.add(run.id);+ for (const run of page.runs) runs.set(run.id, run);}- return ids;+ return runs;}/** Bundle of callbacks that operate on the current selection. */export function useSelectionActions(store: EditorStore) {+ const { busy: fittingScan, dispatch: dispatchAfterScanFit } =+ useDispatchAfterScanFit(store);const forEachSelectedRun = useCallback(- (visit: (run: SelectedRun) => void) => {+ (visit: (run: SelectedRun, page: Page) => void) => {const sel = store.selection.value;const doc = store.document;if (!doc || sel.runIds.length === 0) return;@@ -85,40 +100,34 @@ export function useSelectionActions(store: EditorStore) {for (const page of doc.loadedPages()) {for (const run of page.runs) {// Locked runs are selectable but must not mutate.- if (selIds.has(run.id) && !run.locked) visit(run);+ if (selIds.has(run.id) && !run.locked) visit(run, page);}}},[store],);- // One command per run, dispatched as ONE undo step - same reason- // `deleteSelection` groups its deletes. Select-all now reaches the whole- // document, so a per-run dispatch left the user hundreds of undos behind and- // the first Ctrl+Z looked like the restyle had only covered part of the file.- const dispatchAll = useCallback(- (cmds: Command[]) => {- if (cmds.length === 1) store.dispatch(cmds[0]);- else if (cmds.length > 1) store.dispatch(new CompositeCommand(cmds));- },- [store],- );-const dispatchPerRun = useCallback((build: (run: SelectedRun) => Command | null) => {- const cmds: Command[] = [];- forEachSelectedRun((run) => {- const cmd = build(run);- if (cmd) cmds.push(cmd);+ const targets: ScanFitTarget[] = [];+ forEachSelectedRun((run, page) => {+ targets.push({ page, run: run as TextRun });+ });+ return dispatchAfterScanFit(targets, () => {+ const live = liveRuns(store);+ return targets.flatMap(({ run: target }) => {+ const run = live.get(target.id);+ const cmd = run && !run.locked ? build(run) : null;+ return cmd ? [cmd] : [];+ });});- dispatchAll(cmds);},- [forEachSelectedRun, dispatchAll],+ [store, forEachSelectedRun, dispatchAfterScanFit],);const changeFontSize = useCallback((size: number) => {- dispatchPerRun(+ void dispatchPerRun((run) =>new SetFontSizeCommand({pageIndex: run.pageIndex,@@ -134,7 +143,7 @@ export function useSelectionActions(store: EditorStore) {(hex: string) => {const fill = parseCssColor(hex);if (!fill) return;- dispatchPerRun(+ void dispatchPerRun((run) =>new SetColourCommand({pageIndex: run.pageIndex,@@ -151,7 +160,7 @@ export function useSelectionActions(store: EditorStore) {const changeOutline = useCallback((hex: string | null, width: number) => {const stroke = hex ? parseCssColor(hex) : null;- dispatchPerRun(+ void dispatchPerRun((run) =>new SetTextOutlineCommand({pageIndex: run.pageIndex,@@ -165,12 +174,19 @@ export function useSelectionActions(store: EditorStore) {);const dispatchFamilyChanges = useCallback(- (doc: EditorDocument | null, changes: FamilyChange[]) => {+ async (+ doc: EditorDocument | null,+ changes: FamilyChange[],+ fit: ScanFitTarget[],+ ) => {if (store.document !== doc) return;- const editable = editableRunIds(store);- dispatchAll(- changes- .filter((change) => editable.has(change.runId))+ await dispatchAfterScanFit(fit, () => {+ const live = liveRuns(store);+ return changes+ .filter((change) => {+ const run = live.get(change.runId);+ return !!run && !run.locked;+ }).map((change) =>new SetFontFamilyCommand({@@ -178,17 +194,21 @@ export function useSelectionActions(store: EditorStore) {runId: change.runId,nextFamily: change.family,}),- ),- );+ );+ });},- [store, dispatchAll],+ [store, dispatchAfterScanFit],);const changeFontFamily = useCallback(async (family: string): Promise<FontPickFailure | null> => {const doc = store.document;const targets: SelectedRun[] = [];- forEachSelectedRun((run) => targets.push(run));+ const fit: ScanFitTarget[] = [];+ forEachSelectedRun((run, page) => {+ targets.push(run);+ fit.push({ page, run: run as TextRun });+ });const changes = targets.map((run) => ({pageIndex: run.pageIndex,runId: run.id,@@ -209,7 +229,7 @@ export function useSelectionActions(store: EditorStore) {!tryEmbedDeviceFont(doc, family))return "embedFailed";- dispatchFamilyChanges(doc, changes);+ await dispatchFamilyChanges(doc, changes, fit);return null;},[store, forEachSelectedRun, dispatchFamilyChanges],@@ -218,8 +238,10 @@ export function useSelectionActions(store: EditorStore) {const toggleItalic = useCallback(async () => {const doc = store.document;const fonts = loadedExternalFonts();- const targets: Array<FamilyChange & { device: boolean }> = [];- forEachSelectedRun((run) => {+ const targets: Array<+ FamilyChange & { device: boolean; fit: ScanFitTarget }+ > = [];+ forEachSelectedRun((run, page) => {const cap = italicCapability(run.fontId,!isItalicFamily(run.fontId),@@ -233,22 +255,23 @@ export function useSelectionActions(store: EditorStore) {runId: run.id,family: cap.family,device: cap.source === "device",+ fit: { page, run: run as TextRun },});});// Embedding is async and Command.apply is not, so warm the bytes first.- const ready: FamilyChange[] = [];+ const ready: Array<FamilyChange & { fit: ScanFitTarget }> = [];for (const target of targets) {- if (- target.device &&- ((await prepareExternalFont(target.family)) ===- "serverDownloadFailed" ||- !doc ||- !tryEmbedDeviceFont(doc, target.family))- )- continue;+ if (target.device) {+ if (await prepareExternalFont(target.family)) continue;+ if (!doc || !tryEmbedDeviceFont(doc, target.family)) continue;+ }ready.push(target);}- dispatchFamilyChanges(doc, ready);+ await dispatchFamilyChanges(+ doc,+ ready,+ ready.map((target) => target.fit),+ );}, [store, forEachSelectedRun, dispatchFamilyChanges]);const deleteSelection = useCallback(() => {@@ -363,6 +386,7 @@ export function useSelectionActions(store: EditorStore) {}, [store]);return {+ fittingScan,changeFontSize,changeFill,changeOutline,diff --git a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useSelectionGeometry.ts b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useSelectionGeometry.tsindex 1626b51519..0c5d238f9a 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useSelectionGeometry.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useSelectionGeometry.ts@@ -1,6 +1,7 @@import { useMemo } from "react";import { MoveTextRunCommand } from "@editor/tools/pdfTextEditor/commands/MoveTextRunCommand";import { ReflowWrapCommand } from "@editor/tools/pdfTextEditor/commands/ReflowWrapCommand";+import { isScanRun } from "@editor/tools/pdfTextEditor/commands/scanTextEdit";import { SetImageTransformCommand } from "@editor/tools/pdfTextEditor/commands/SetImageTransformCommand";import type { EditorStore } from "@editor/tools/pdfTextEditor/store/EditorStore";import type { EditorViewState } from "@editor/tools/pdfTextEditor/store/EditorStore";@@ -13,7 +14,7 @@ export interface SingleSelectionGeometry {bounds: PageRect;setX: (next: number) => void;setY: (next: number) => void;- setWidth: (next: number) => void;+ setWidth?: (next: number) => void;/** Absent for text runs: their height follows the type, not a handle. */setHeight?: (next: number) => void;}@@ -74,15 +75,17 @@ export function useSelectionGeometry(),// Narrowing a run is exactly the wrap gesture, so it reuses the// same command the canvas resize handle drives.- setWidth: (next) =>- store.dispatch(- new ReflowWrapCommand({- pageIndex,- runId,- maxWidthPt: Math.max(1, next),- explicit: true,- }),- ),+ setWidth: isScanRun(run)+ ? undefined+ : (next) =>+ store.dispatch(+ new ReflowWrapCommand({+ pageIndex,+ runId,+ maxWidthPt: Math.max(1, next),+ explicit: true,+ }),+ ),},};}diff --git a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useServerFontsGroupLabel.ts b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useServerFontsGroupLabel.tsnew file mode 100644index 0000000000..2116dcac77--- /dev/null+++ b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useServerFontsGroupLabel.ts@@ -0,0 +1,7 @@+import { useTranslation } from "react-i18next";++/** Heading for the fonts the backend supplies in the font picker; a seam for builds whose backend the user does not think of as a server. */+export function useServerFontsGroupLabel(): string {+ const { t } = useTranslation();+ return t("pdfTextEditor.fontPicker.serverGroup", "Server fonts");+}diff --git a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useToolbarController.ts b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useToolbarController.tsindex b3bfab219f..609780f3e3 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useToolbarController.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useToolbarController.ts@@ -8,8 +8,17 @@ import {import { useSelectionActions } from "@editor/tools/pdfTextEditor/hooks/useSelectionActions";import { useImageAccessibility } from "@editor/tools/pdfTextEditor/hooks/useImageAccessibility";import { useTextAccessibility } from "@editor/tools/pdfTextEditor/hooks/useTextAccessibility";+import {+ isScanRun,+ scanDrawnFont,+ type ScanDrawnFont,+} from "@editor/tools/pdfTextEditor/commands/scanTextEdit";+import {+ scanFacesGeneration,+ subscribeScanFaces,+} from "@editor/tools/pdfTextEditor/util/scanFontLibrary";import { deriveToolbarState } from "@editor/tools/pdfTextEditor/util/toolbarState";-import { warmDocumentDeviceFonts } from "@editor/tools/pdfTextEditor/util/fontCapability";+import { useDocumentFontCompletion } from "@editor/tools/pdfTextEditor/hooks/useDocumentFontCompletion";import {loadedExternalFonts,subscribeExternalFonts,@@ -413,23 +422,35 @@ export function useToolbarController(if (hasTextSelection) void loadServerFonts();}, [hasTextSelection]);- const documentFontIds = useMemo(- () => [...new Set(state.pages.flatMap((p) => p.runs.map((r) => r.fontId)))],- [state.pages],- );-- // Match the document's own families against the installed ones, so an edit- // that outgrows an embedded subset completes from the real face.- useEffect(() => {- if (!externalFonts) return;- void warmDocumentDeviceFonts(documentFontIds);- }, [externalFonts, documentFontIds]);+ useDocumentFontCompletion(store, state, selection, externalFonts);const toolbarState = useMemo(() => deriveToolbarState(state.pages, selection, externalFonts),[state.pages, selection, externalFonts],);+ const scanFacesVersion = useSyncExternalStore(+ subscribeScanFaces,+ scanFacesGeneration,+ scanFacesGeneration,+ );+ // Undefined unless the selection is wholly scanned text; null when no single font is in force.+ const scanFont = useMemo<ScanDrawnFont | null | undefined>(() => {+ const doc = store.document;+ if (!doc || selection.runIds.length === 0) return undefined;+ const ids = new Set(selection.runIds);+ const runs = doc+ .loadedPages()+ .flatMap((page) => page.runs.filter((run) => ids.has(run.id)));+ if (runs.length === 0 || !runs.every(isScanRun)) return undefined;+ const fonts = runs.map((run) => scanDrawnFont(doc, run));+ const first = fonts[0];+ return first && fonts.every((font) => font?.family === first.family)+ ? first+ : null;+ // state.pages and scanFacesVersion are unread but change whenever a block is refitted.+ }, [store, selection.runIds, state.pages, scanFacesVersion]);+const selectionAllLocked = useMemo(() => {const runs = new Set(selection.runIds);const images = new Set(selection.imageIds);@@ -505,6 +526,7 @@ export function useToolbarController(return {state: toolbarState,+ scanFont,canUndo: store.history.canUndo,canRedo: store.history.canRedo,onUndo: () => store.undo(),@@ -544,6 +566,7 @@ export function useToolbarController(selection.shapeIds.length,canAlignLines,disabled:+ sel.fittingScan ||!state.hasDocument ||(selection.runIds.length === 0 && selection.imageIds.length === 0),};diff --git a/frontend/src/editor/core/tools/pdfTextEditor/model/Color.ts b/frontend/src/editor/core/tools/pdfTextEditor/model/Color.tsindex 6e89de92ea..a843f491c9 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/model/Color.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/model/Color.ts@@ -3,6 +3,11 @@ import type { RGBA } from "@editor/tools/pdfTextEditor/types";export const BLACK: RGBA = { r: 0, g: 0, b: 0, a: 255 };export const WHITE: RGBA = { r: 255, g: 255, b: 255, a: 255 };+/** Rec. 601 luma, 0-255 for 0-255 channels. */+export function luma(r: number, g: number, b: number): number {+ return 0.299 * r + 0.587 * g + 0.114 * b;+}+/** Parse a `#rrggbb`, `#rrggbbaa`, or `rgb(...)` string. Returns null on failure. */export function parseCssColor(value: string): RGBA | null {const trimmed = value.trim();diff --git a/frontend/src/editor/core/tools/pdfTextEditor/model/EditorDocument.ts b/frontend/src/editor/core/tools/pdfTextEditor/model/EditorDocument.tsindex 305df8c332..318d079613 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/model/EditorDocument.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/model/EditorDocument.ts@@ -102,6 +102,7 @@ export class EditorDocument {private formEnvPtr: number | null = null;private formEnvTried = false;private readonly formLoadedPages = new Set<number>();+ private scratch: EditorDocument | null = null;/** By page index, as each page is first read: the artifact marks whose kinds only the file names. */private readonly artifactMarks = new Map<number, ArtifactMarkRef[]>();private readonly artifactKindReads = new Map<number, Promise<boolean>>();@@ -788,9 +789,49 @@ export class EditorDocument {return Array.from(this.pageCache.values());}+ scratchPageFor(page: Page): { doc: EditorDocument; page: Page } {+ this.scratch ??= new EditorDocument(+ this.module,+ this.module.FPDF_CreateNewDocument(),+ EMPTY,+ null,+ );+ return { doc: this.scratch, page: this.scratch.blankPageLike(page) };+ }++ private blankPageLike(like: Page): Page {+ const cached = this.pageCache.get(like.index);+ if (cached) return cached;+ const m = this.module;+ const d = like.display;+ const pagePtr = m.FPDFPage_New(+ this.docPtr,+ this.pageCache.size,+ d.cropWidth,+ d.cropHeight,+ );+ if (!pagePtr) throw new Error("EditorDocument: failed to add a page");+ const right = d.cropLeft + d.cropWidth;+ const top = d.cropBottom + d.cropHeight;+ m.FPDFPage_SetMediaBox(pagePtr, d.cropLeft, d.cropBottom, right, top);+ m.FPDFPage_SetCropBox(pagePtr, d.cropLeft, d.cropBottom, right, top);+ m.FPDFPage_SetRotation(pagePtr, d.rotate);+ const page = new Page({+ index: like.index,+ pagePtr,+ width: like.width,+ height: like.height,+ display: d,+ });+ this.pageCache.set(like.index, page);+ return page;+ }+dispose(): void {if (this._disposed) return;this._disposed = true;+ this.scratch?.dispose();+ this.scratch = null;if (this.formEnvPtr) {const m = this.module as unknown as {FORM_OnBeforeClosePage?: (pagePtr: number, env: number) => void;diff --git a/frontend/src/editor/core/tools/pdfTextEditor/model/Page.ts b/frontend/src/editor/core/tools/pdfTextEditor/model/Page.tsindex b2066020ba..aee2a7e969 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/model/Page.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/model/Page.ts@@ -48,6 +48,7 @@ export class Page {// Sticky: regenerated at least once. Regeneration is what drops shadings, so// the save-time repair needs this long after `dirty` was cleared.regenerated: boolean;+ shownInViewer: boolean;constructor(opts: {index: number;@@ -75,6 +76,7 @@ export class Page {this.fills = [];this.needsGenerateContent = false;this.regenerated = false;+ this.shownInViewer = false;}setRuns(runs: TextRun[]): void {diff --git a/frontend/src/editor/core/tools/pdfTextEditor/model/TextRun.ts b/frontend/src/editor/core/tools/pdfTextEditor/model/TextRun.tsindex 388b34b428..99ce06046c 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/model/TextRun.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/model/TextRun.ts@@ -193,6 +193,10 @@ export class TextRun {fontSize: this.fontSize,fill: { ...this.fill },fontSubset: this.fontSubset,+ scanFamily:+ this.scanEdit?.override.style?.family ??+ this.scanEdit?.override.family ??+ this.scanEdit?.block?.style.family,renderMode: this.renderMode || undefined,stroke: this.stroke ? { ...this.stroke } : undefined,strokeWidth: this.strokeWidth || undefined,diff --git a/frontend/src/editor/core/tools/pdfTextEditor/pdfium/BackgroundSampler.ts b/frontend/src/editor/core/tools/pdfTextEditor/pdfium/BackgroundSampler.tsindex 5216cba311..f58a885d2c 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/pdfium/BackgroundSampler.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/pdfium/BackgroundSampler.ts@@ -1,6 +1,9 @@import type { WrappedPdfiumModule } from "@embedpdf/pdfium";import type { Page } from "@editor/tools/pdfTextEditor/model/Page";import type { PageRect, RGBA } from "@editor/tools/pdfTextEditor/types";+import { DisplayTransform } from "@editor/tools/pdfTextEditor/model/DisplayTransform";+import { luma } from "@editor/tools/pdfTextEditor/model/Color";+import { boxBlur } from "@editor/tools/pdfTextEditor/util/boxBlur";// Render the area of the page surrounding a text run and pick the dominant// background color.@@ -15,7 +18,7 @@ export interface SampleResult {}interface Slice {- /** Display-space point at the bitmap's top-left pixel. */+ /** Crop-space point at the bitmap's top-left pixel. */left: number;top: number;scale: number;@@ -25,6 +28,19 @@ interface Slice {stride: number;}+function rawView(page: Page): DisplayTransform {+ const d = page.display;+ return DisplayTransform.fromCropAndRotate(+ d.cropLeft,+ d.cropBottom,+ d.cropWidth,+ d.cropHeight,+ 0,+ d.cropWidth,+ d.cropHeight,+ );+}+// Rasterize `bounds` grown by `margin` points; null when it has no area.function renderSlice(m: WrappedPdfiumModule,@@ -34,9 +50,8 @@ function renderSlice(scale = SAMPLE_SCALE,): Slice | null {// No flush needed: the render path draws from the in-memory object list.- // The rendered bitmap is CropBox/rotation (display) space; the run bounds- // are raw PDF.- const d = page.display;+ // The bitmap is raw PDF space cropped to the CropBox with /Rotate undone, so rows run along the page's x axis.+ const d = rawView(page);const cs = [d.apply(bounds.x, bounds.y),d.apply(bounds.x + bounds.width, bounds.y),@@ -44,8 +59,14 @@ function renderSlice(d.apply(bounds.x + bounds.width, bounds.y + bounds.height),];const left = Math.max(0, Math.min(...cs.map((c) => c.x)) - margin);- const right = Math.min(page.width, Math.max(...cs.map((c) => c.x)) + margin);- const top = Math.min(page.height, Math.max(...cs.map((c) => c.y)) + margin);+ const right = Math.min(+ d.displayWidth,+ Math.max(...cs.map((c) => c.x)) + margin,+ );+ const top = Math.min(+ d.displayHeight,+ Math.max(...cs.map((c) => c.y)) + margin,+ );const bottom = Math.max(0, Math.min(...cs.map((c) => c.y)) - margin);const widthPts = right - left;const heightPts = top - bottom;@@ -59,11 +80,11 @@ function renderSlice(m.FPDFBitmap_FillRect(bitmapPtr, 0, 0, w, h, 0xffffffff);// PDFium renders the WHOLE page sized to (pageW*scale, pageH*scale)// at the bitmap's origin. We translate so our slice lands at 0,0.- const fullW = Math.round(page.width * scale);- const fullH = Math.round(page.height * scale);+ const fullW = Math.round(d.displayWidth * scale);+ const fullH = Math.round(d.displayHeight * scale);const startX = -Math.round(left * scale);// CSS-style y: PDFium origin is page top-left in render coords.- const startY = -Math.round((page.height - top) * scale);+ const startY = -Math.round((d.displayHeight - top) * scale);// 0x01 = FPDF_ANNOT, 0x10 = FPDF_REVERSE_BYTE_ORDER (gives RGBA).m.FPDF_RenderPageBitmap(bitmapPtr,@@ -72,7 +93,7 @@ function renderSlice(startY,fullW,fullH,- 0,+ (4 - page.display.rotate) & 3,0x01 | 0x10,);const bufferPtr = m.FPDFBitmap_GetBuffer(bitmapPtr);@@ -154,9 +175,6 @@ export function sampleBackground(}}-const luma = (r: number, g: number, b: number) =>- 0.299 * r + 0.587 * g + 0.114 * b;-export interface ScanInk {fill: RGBA;/** Box around the scanned glyphs and their blur, raw page space. */@@ -175,9 +193,145 @@ export interface ScanInk {density: number;/** Centre x of each separate glyph, raw page space, left to right. */glyphCenters: number[];+ glyphSpans: Array<{ left: number; right: number }>;/** A box edge sits just left / right of the glyphs (OCR may read it as "["). */edgeLeft: boolean;edgeRight: boolean;+ reversed: boolean;+}++const INK_NONE = 0;+const INK_SOFT = 1;+const INK_SOLID = 2;+const SOLID_INK_CUT = 60;+const SOFT_INK_CUT = 30;+const GROUND_SHARE = 0.65;+const HIGHLIGHT_SHARE = 0.97;+const REVERSED_GROUND_MAX = 110;+const REVERSED_CONTRAST = 60;+const DOT_GAP_SHARE = 0.2;++// Faint anti-aliased edges still show once the paper around them is covered, so the extent uses a softer cut than the colour does.+function inkLevel(l: number, paper: number): number {+ if (l < paper - SOLID_INK_CUT) return INK_SOLID;+ if (l < paper - SOFT_INK_CUT) return INK_SOFT;+ return INK_NONE;+}++// Light text on a dark fill: the ground of the glyph rows is dark, and their brightest pixels stand well clear of it.+function readGround(core: number[]): { ground: number; reversed: boolean } {+ const sorted = [...core].sort((p, q) => p - q);+ const ground = sorted[Math.floor(sorted.length * GROUND_SHARE)] ?? 255;+ const highlight = sorted[Math.floor(sorted.length * HIGHLIGHT_SHARE)] ?? 0;+ const reversed =+ ground < REVERSED_GROUND_MAX && highlight > ground + REVERSED_CONTRAST;+ return { ground, reversed };+}++interface InkGrid {+ ink: Uint8Array;+ width: number;+ height: number;+ x0: number;+ x1: number;+}++interface InkRows {+ rowInk: number[];+ rowSolid: number[];+ ruled: Uint8Array;+}++function countRows({ ink, width, height, x0, x1 }: InkGrid): InkRows {+ const span = x1 - x0 + 1;+ const rowInk = new Array<number>(height).fill(0);+ const rowSolid = new Array<number>(height).fill(0);+ const ruled = new Uint8Array(height);+ for (let y = 0; y < height; y++)+ for (let x = x0; x <= x1; x++) {+ const v = ink[y * width + x];+ if (v) rowInk[y]++;+ if (v === INK_SOLID) rowSolid[y]++;+ }+ // A row solidly inked edge to edge is a rule or box border; its blurred fringe is not, or glyphs touching it would stop short.+ for (let y = 0; y < height; y++) {+ if (span <= 12 || rowSolid[y] <= span * 0.85) continue;+ for (let k = y - 3; k <= y + 3; k++)+ if (k >= 0 && k < height && (k === y || rowInk[k] > span * 0.3))+ ruled[k] = 1;+ }+ return { rowInk, rowSolid, ruled };+}++// A column inked all the way between the rules around the text (or the whole slice) is a box edge: no glyph spans it. Clears those columns and returns them.+function stripBoxEdges(+ grid: InkGrid,+ ruled: Uint8Array,+ mid: number,+): number[] {+ const { ink, width, height, x0, x1 } = grid;+ let above = mid;+ while (above > 0 && !ruled[above]) above--;+ let below = mid;+ while (below < height - 1 && !ruled[below]) below++;+ const edgeCols: number[] = [];+ const interior = below - above - 1;+ for (let x = x0; x <= x1 && interior > 4; x++) {+ let n = 0;+ for (let y = above + 1; y < below; y++) if (ink[y * width + x]) n++;+ if (n < interior * 0.9) continue;+ edgeCols.push(x);+ for (let y = 0; y < height; y++) ink[y * width + x] = INK_NONE;+ }+ return edgeCols;+}++const pairInk = (rowInk: number[], y: number) =>+ (rowInk[y] ?? 0) + (rowInk[y - 1] ?? 0);++// Only descenders go below the baseline, so it is where the ink per row falls away most sharply; a share of the peak misses thin, light strokes.+function baselineRow(rowInk: number[], top: number, bottom: number): number {+ let baseRow = bottom + 1;+ let drop = -1;+ for (let y = Math.round(top + (bottom - top) * 0.4); y <= bottom; y++) {+ const d = pairInk(rowInk, y) - pairInk(rowInk, y + 2);+ if (d > drop) {+ drop = d;+ baseRow = y + 1;+ }+ }+ return baseRow;+}++// Lowercase text is densest below its x-height, so the x-line is where ink rises most sharply going down.+function xHeightRow(rowInk: number[], top: number, baseRow: number): number {+ let xRow = top;+ let rise = -1;+ for (let y = top + 1; y <= baseRow - (baseRow - top) * 0.3; y++) {+ const r = pairInk(rowInk, y + 1) - pairInk(rowInk, y - 1);+ if (r > rise) {+ rise = r;+ xRow = y;+ }+ }+ return xRow;+}++// A real lowercase band is several times denser than the ascenders and fills about two thirds of the height; capitals fill it all or leave only blur above.+function isLowercaseBand(+ rowInk: number[],+ top: number,+ xRow: number,+ baseRow: number,+): boolean {+ const mean = (a: number, b: number) => {+ let sum = 0;+ for (let y = a; y < b; y++) sum += rowInk[y];+ return b > a ? sum / (b - a) : 0;+ };+ const band = (baseRow - xRow) / Math.max(1, baseRow - top);+ const density = mean(xRow, baseRow) / Math.max(0.1, mean(top, xRow));+ return band > 0.5 && band < 0.75 && density > 2 && density < 15;}/** Where to look: an x span and the rows the OCR says hold the glyphs. */@@ -199,13 +353,10 @@ export function measureScanInk(region: ScanRegion,): ScanInk | null {try {- const d = page.display;+ const d = rawView(page);const o = d.apply(0, 0);const ux = d.apply(1, 0);const uy = d.apply(0, 1);- // Rows of the bitmap only line up with text rows on an upright page.- if (Math.abs(ux.y - o.y) > 1e-6 || ux.x - o.x <= 0 || uy.y - o.y <= 0)- return null;const boxH = region.top - region.bottom;const box = {x: region.x0,@@ -225,25 +376,28 @@ export function measureScanInk(const coreTop = Math.max(0, toPxY(region.top));const coreBottom = Math.min(height - 1, toPxY(region.bottom));if (x1 <= x0 || coreBottom < coreTop) return null;- // The paper is what most of the slice is. Sampled from a ring instead, a- // ruled line under the ring passed for paper and hid every thin stroke.- const sample: number[] = [];- for (let y = 0; y < height; y += 2)- for (let x = x0; x <= x1; x += 2) {- const i = y * stride + x * 4;- sample.push(luma(rgba[i], rgba[i + 1], rgba[i + 2]));- }- sample.sort((p, q) => p - q);- // Bright enough to clear the ink, not so bright that grain sets it.- const paper = sample[Math.floor(sample.length * 0.75)] ?? 255;- // Faint anti-aliased edges still show once the paper around them is- // covered, so the extent uses a softer cut than the colour does.+ const lumaAt = (i: number) => luma(rgba[i], rgba[i + 1], rgba[i + 2]);+ const core: number[] = [];+ for (let y = coreTop; y <= coreBottom; y += 2)+ for (let x = x0; x <= x1; x += 2) core.push(lumaAt(y * stride + x * 4));+ const { ground, reversed } = readGround(core);+ const tone = reversed ? (i: number) => 255 - lumaAt(i) : lumaAt;+ const slicePaper = () => {+ // Paper is most of the slice: sampled from a ring, a ruled line under it passed for paper and hid thin strokes.+ const sample: number[] = [];+ for (let y = 0; y < height; y += 2)+ for (let x = x0; x <= x1; x += 2)+ sample.push(lumaAt(y * stride + x * 4));+ sample.sort((p, q) => p - q);+ // Bright enough to clear the ink, not so bright that grain sets it.+ return sample[Math.floor(sample.length * 0.75)] ?? 255;+ };+ const paper = reversed ? 255 - ground : slicePaper();const ink = new Uint8Array(width * height);for (let y = 0; y < height; y++) {for (let x = x0; x <= x1; x++) {- const i = y * stride + x * 4;- const l = luma(rgba[i], rgba[i + 1], rgba[i + 2]);- ink[y * width + x] = l < paper - 60 ? 2 : l < paper - 30 ? 1 : 0;+ const l = tone(y * stride + x * 4);+ ink[y * width + x] = inkLevel(l, paper);}}// The cover colour is the paper itself: every pixel clear of ink, with a@@ -266,47 +420,15 @@ export function measureScanInk(paperRgb[2] += rgba[i + 2];paperN++;}- const span = x1 - x0 + 1;- const rowInk = new Array<number>(height).fill(0);- const rowSolid = new Array<number>(height).fill(0);- const ruled = new Uint8Array(height);- const countRows = () => {- rowInk.fill(0);- rowSolid.fill(0);- ruled.fill(0);- for (let y = 0; y < height; y++)- for (let x = x0; x <= x1; x++) {- const v = ink[y * width + x];- if (v) rowInk[y]++;- if (v === 2) rowSolid[y]++;- }- // A row solidly inked edge to edge is a ruled line or box border; its- // blurred fringe is not, or glyphs touching the rule would stop short.- for (let y = 0; y < height; y++) {- if (span <= 12 || rowSolid[y] <= span * 0.85) continue;- for (let k = y - 3; k <= y + 3; k++)- if (k >= 0 && k < height && (k === y || rowInk[k] > span * 0.3))- ruled[k] = 1;- }- };- countRows();- // A column inked all the way between the rules around the text (or the- // whole slice) is a box edge, however tight the box: no glyph spans it.- const mid = Math.round((coreTop + coreBottom) / 2);- let above = mid;- while (above > 0 && !ruled[above]) above--;- let below = mid;- while (below < height - 1 && !ruled[below]) below++;- const edgeCols: number[] = [];- const interior = below - above - 1;- for (let x = x0; x <= x1 && interior > 4; x++) {- let n = 0;- for (let y = above + 1; y < below; y++) if (ink[y * width + x]) n++;- if (n < interior * 0.9) continue;- edgeCols.push(x);- for (let y = 0; y < height; y++) ink[y * width + x] = 0;- }- if (edgeCols.length) countRows();+ const grid: InkGrid = { ink, width, height, x0, x1 };+ let rows = countRows(grid);+ const edgeCols = stripBoxEdges(+ grid,+ rows.ruled,+ Math.round((coreTop + coreBottom) / 2),+ );+ if (edgeCols.length) rows = countRows(grid);+ const { rowInk, rowSolid, ruled } = rows;const isRule = (y: number) => ruled[y] === 1;let first = -1;let last = -1;@@ -320,7 +442,12 @@ export function measureScanInk(// while a wider gap would reach into the neighbouring line.const gap = Math.round(scale * 0.8);const boxPx = coreBottom - coreTop;- const grow = (from: number, step: number, limit: number) => {+ const grow = (+ from: number,+ step: number,+ limit: number,+ maxBlank = gap,+ ) => {let edge = from;let blank = 0;for (@@ -332,7 +459,7 @@ export function measureScanInk(if (rowSolid[y] > 0) {edge = y;blank = 0;- } else if (++blank > gap) break;+ } else if (++blank > maxBlank) break;}return edge;};@@ -352,47 +479,17 @@ export function measureScanInk(const solidBottom = grow(last, 1, boxPx * 0.7);const top = fringe(solidTop, -1);const bottom = fringe(solidBottom, 1);+ // An i or j dot floats past `gap` at body sizes; the cover and copied pixels must take it, the measurements above must not.+ const dotGap = Math.max(gap, Math.round(boxPx * DOT_GAP_SHARE));+ const coverTop = fringe(grow(first, -1, boxPx * 0.6, dotGap), -1);- // Glyph bodies end on the baseline and only descenders go below it, so- // the baseline is where the ink per row falls away most sharply. A fixed- // share of the peak misses it on thin, light strokes.- const ink2 = (y: number) => (rowInk[y] ?? 0) + (rowInk[y - 1] ?? 0);- let baseRow = bottom + 1;- let drop = -1;- for (let y = Math.round(top + (bottom - top) * 0.4); y <= bottom; y++) {- const d = ink2(y) - ink2(y + 2);- if (d > drop) {- drop = d;- baseRow = y + 1;- }- }- // Lowercase text is densest between the baseline and its x-height; the- // top of that band is where ink rises most sharply going down.- let xRow = top;- let rise = -1;- for (let y = top + 1; y <= baseRow - (baseRow - top) * 0.3; y++) {- const r = ink2(y + 1) - ink2(y - 1);- if (r > rise) {- rise = r;- xRow = y;- }- }- // A real lowercase band is several times denser than the ascenders above- // it and fills about two thirds of the glyph height. Capitals fill it all,- // or leave only empty blur above, which reads as a band with no ascenders.- const mean = (a: number, b: number) => {- let sum = 0;- for (let y = a; y < b; y++) sum += rowInk[y];- return b > a ? sum / (b - a) : 0;- };- const band = (baseRow - xRow) / Math.max(1, baseRow - top);- const density = mean(xRow, baseRow) / Math.max(0.1, mean(top, xRow));- const lowercaseBand =- band > 0.5 && band < 0.75 && density > 2 && density < 15;+ const baseRow = baselineRow(rowInk, top, bottom);+ const xRow = xHeightRow(rowInk, top, baseRow);+ const lowercaseBand = isLowercaseBand(rowInk, top, xRow, baseRow);const colInk = (x: number) => {for (let y = top; y <= bottom; y++)- if (ink[y * width + x] === 2) return true;+ if (ink[y * width + x] === INK_SOLID) return true;return false;};const colSoft = (x: number) => {@@ -411,13 +508,13 @@ export function measureScanInk(while (right < x1 && colSoft(right + 1)) right++;// Separate glyphs: runs of solid columns split by at least one blank.- const centers: number[] = [];+ const spans: Array<[number, number]> = [];let runStart = -1;for (let x = left; x <= right + 1; x++) {const on = x <= right && colInk(x);if (on && runStart < 0) runStart = x;if (!on && runStart >= 0) {- centers.push((runStart + x - 1) / 2);+ spans.push([runStart, x - 1]);runStart = -1;}}@@ -425,10 +522,9 @@ export function measureScanInk(const dark: Array<[number, number, number, number]> = [];for (let y = top; y <= bottom; y++) {for (let x = left; x <= right; x++) {- if (ink[y * width + x] !== 2) continue;+ if (ink[y * width + x] !== INK_SOLID) continue;const i = y * stride + x * 4;- const px = [rgba[i], rgba[i + 1], rgba[i + 2]] as const;- dark.push([luma(...px), ...px]);+ dark.push([tone(i), rgba[i], rgba[i + 1], rgba[i + 2]]);}}// Pixel rows/cols back to raw page space through the display map.@@ -470,7 +566,7 @@ export function measureScanInk(a: 255,},rect: pageBox(- top - clearance(top, -1, (y) => ruled[y] === 1),+ coverTop - clearance(coverTop, -1, (y) => ruled[y] === 1),bottom + clearance(bottom, 1, (y) => ruled[y] === 1),left - clearance(left, -1, (x) => edgeCols.includes(x)),right + clearance(right, 1, (x) => edgeCols.includes(x)),@@ -479,13 +575,18 @@ export function measureScanInk(baseline: pageY(baseRow),xLine: lowercaseBand ? pageY(xRow) : null,density: dark.length / ((right - left + 1) * (bottom - top + 1)),- glyphCenters: centers.map((c) => pageX(c + 0.5)),+ glyphCenters: spans.map(([l, r]) => pageX((l + r + 1) / 2)),+ glyphSpans: spans.map(([l, r]) => ({+ left: pageX(l),+ right: pageX(r + 1),+ })),edgeLeft: edgeCols.some((c) => c < solidLeft && solidLeft - c < scale * 6,),edgeRight: edgeCols.some((c) => c > solidRight && c - solidRight < scale * 6,),+ reversed,};} catch {return null;@@ -507,12 +608,7 @@ export function capturePatch(rect: PageRect,): PixelPatch | null {try {- const d = page.display;- const o = d.apply(0, 0);- const ux = d.apply(1, 0);- const uy = d.apply(0, 1);- // Display space must be raw page space shifted, or the copy lands skewed.- if (ux.x - o.x !== 1 || uy.y - o.y !== 1 || ux.y !== o.y) return null;+ const o = rawView(page).apply(0, 0);const slice = renderSlice(m, page, rect, 0, INK_SCALE);if (!slice) return null;const { width, height, stride, scale } = slice;@@ -538,50 +634,42 @@ export function capturePatch(}}-/** Luma of a page area at the ink-measuring resolution, softened by `blur` px. */+/** Luma of a page area at `scale` px per point, softened by `blur` px. */export function renderLuma(m: WrappedPdfiumModule,page: Page,rect: PageRect,blur = 2,-): { data: Float32Array; width: number; height: number } | null {+ scale = INK_SCALE,+): Luma | null {try {- const slice = renderSlice(m, page, rect, 0, INK_SCALE);+ const slice = renderSlice(m, page, rect, 0, scale);if (!slice) return null;const { rgba, width, height, stride } = slice;- let data = new Float32Array(width * height);+ const data = new Float32Array(width * height);for (let y = 0; y < height; y++)for (let x = 0; x < width; x++) {const i = y * stride + x * 4;data[y * width + x] = luma(rgba[i], rgba[i + 1], rgba[i + 2]);}- // Box blur rows then columns: scans are soft, drawn text is crisp.- for (const [dx, dy] of [- [1, 0],- [0, 1],- ]) {- const out = new Float32Array(data.length);- for (let y = 0; y < height; y++)- for (let x = 0; x < width; x++) {- let sum = 0;- let n = 0;- for (let k = -blur; k <= blur; k++) {- const xx = x + k * dx;- const yy = y + k * dy;- if (xx < 0 || yy < 0 || xx >= width || yy >= height) continue;- sum += data[yy * width + xx];- n++;- }- out[y * width + x] = sum / n;- }- data = out;- }- return { data, width, height };+ return blurLuma({ data, width, height }, blur);} catch {return null;}}+export interface Luma {+ data: Float32Array;+ width: number;+ height: number;+}++// Box blur rows then columns: scans are soft, drawn text is crisp.+export function blurLuma(img: Luma, blur: number): Luma {+ const { width, height } = img;+ return { data: boxBlur(img.data, width, height, blur), width, height };+}+// The darker part of the ink pixels: glyph edges anti-alias toward the paper,// yet the darkest few alone read blacker than the scan looks.function inkColour(diff --git a/frontend/src/editor/core/tools/pdfTextEditor/pdfium/LineGrouper.ts b/frontend/src/editor/core/tools/pdfTextEditor/pdfium/LineGrouper.tsindex f03babfc09..2c9c5c863d 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/pdfium/LineGrouper.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/pdfium/LineGrouper.ts@@ -1,6 +1,7 @@import type { Page } from "@editor/tools/pdfTextEditor/model/Page";import type { TextRun } from "@editor/tools/pdfTextEditor/model/TextRun";import { innermostMcid } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTagMarks";+import { RENDER_MODE_INVISIBLE } from "@editor/tools/pdfTextEditor/types";/** Cluster adjacent text runs on a page into "line groups". */export interface LineGroupInfo {@@ -18,6 +19,10 @@ export type BlockKey = (run: TextRun) => string;export const SAME_BLOCK: BlockKey = () => "";+export const sameTextLayer = (a: TextRun, b: TextRun): boolean =>+ (a.renderMode === RENDER_MODE_INVISIBLE) ===+ (b.renderMode === RENDER_MODE_INVISIBLE);+const BASELINE_TOLERANCE = 0.4;// Two runs on the same baseline join the same line only when the horizontal gap// between them is below this absolute cap.@@ -146,7 +151,7 @@ function groupPartitionIntoLines(const sameBlock =isBulletLead(run) || block === null || blockKey(run) === block;- if (sameLine && close && sameBlock) {+ if (sameLine && close && sameBlock && sameTextLayer(prev, run)) {current.members.push(run);} else {current = { representative: run, members: [run] };@@ -158,10 +163,10 @@ function groupPartitionIntoLines(export class LineGrouper {/** Group a page's runs and store the result back onto the page. */static apply(page: Page, blockKey: BlockKey = SAME_BLOCK): LineGroupInfo[] {- // Partition by form-xobject container BEFORE grouping.- const partitions = new Map<number, TextRun[]>();+ // Partition by form-xobject container and text layer BEFORE grouping: OCR words over printed ones would interleave in x.+ const partitions = new Map<string, TextRun[]>();for (const run of page.runs) {- const key = run.containerPtr || 0;+ const key = `${run.containerPtr || 0}:${run.renderMode === RENDER_MODE_INVISIBLE}`;const list = partitions.get(key);if (list) list.push(run);else partitions.set(key, [run]);diff --git a/frontend/src/editor/core/tools/pdfTextEditor/pdfium/ParagraphGrouper.ts b/frontend/src/editor/core/tools/pdfTextEditor/pdfium/ParagraphGrouper.tsindex ac24bccdaf..10f977c8df 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/pdfium/ParagraphGrouper.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/pdfium/ParagraphGrouper.ts@@ -1,12 +1,14 @@import type { Page } from "@editor/tools/pdfTextEditor/model/Page";import {SAME_BLOCK,+ sameTextLayer,type BlockKey,} from "@editor/tools/pdfTextEditor/pdfium/LineGrouper";import type {ParagraphLineSlot,TextRun,} from "@editor/tools/pdfTextEditor/model/TextRun";+import { median } from "@editor/tools/pdfTextEditor/util/median";/** Cluster consecutive `LineGroup` representatives into "paragraphs". */const MIN_LINE_FACTOR = 0.6;@@ -293,7 +295,14 @@ function groupColumnLines(const sameBlock = blockKey(prev) === blockKey(line);- if (sameFont && sameColor && lineHeightOk && leftOk && sameBlock) {+ if (+ sameFont &&+ sameColor &&+ lineHeightOk &&+ leftOk &&+ sameBlock &&+ sameTextLayer(prev, line)+ ) {current.members.push(line);currentDeltas.push(baselineDelta);if (line.bounds.x < currentLeftEdge) currentLeftEdge = line.bounds.x;@@ -306,15 +315,6 @@ function groupColumnLines(}}-function median(values: number[]): number {- if (values.length === 0) return 0;- const sorted = [...values].sort((a, b) => a - b);- const mid = sorted.length >> 1;- return sorted.length % 2 === 0- ? (sorted[mid - 1] + sorted[mid]) / 2- : sorted[mid];-}-function computeMedianLineHeight(members: TextRun[]): number {if (members.length < 2) return members[0].fontSize * 1.2;return medianLineHeightFromBaselines(diff --git a/frontend/src/editor/core/tools/pdfTextEditor/pdfium/PdfiumPageRenderer.ts b/frontend/src/editor/core/tools/pdfTextEditor/pdfium/PdfiumPageRenderer.tsindex abbfb052a7..9a17fe7f13 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/pdfium/PdfiumPageRenderer.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/pdfium/PdfiumPageRenderer.ts@@ -71,6 +71,7 @@ export class PdfiumPageRenderer {0,0x01 | 0x10,);+ page.shownInViewer = true;// Second pass for the form layer. A widget with no appearance stream is// drawn ONLY here - FPDF_ANNOT alone leaves such fields blank, which isdiff --git a/frontend/src/editor/core/tools/pdfTextEditor/pdfium/PdfiumTextReader.ts b/frontend/src/editor/core/tools/pdfTextEditor/pdfium/PdfiumTextReader.tsindex 0ae9704c62..8c4c7a6079 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/pdfium/PdfiumTextReader.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/pdfium/PdfiumTextReader.ts@@ -348,10 +348,7 @@ function samePositions(prev: number[] | null, next: number[]): boolean {// Record where the engine put every glyph, indexed by code unit of `text`.// Both units of a surrogate pair share a value; synthesised spaces stay NaN.function captureCharPositions(geometry: CharGeometry[]): Set<TextRun> {- const glyphs = new Map<- TextRun,- Array<{ cp: number; x: number; end: number }>- >();+ const glyphs = new Map<TextRun, PlacedGlyph[]>();for (const g of geometry) {if (!g.run || !g.cp || !g.ok) continue;if (!Number.isFinite(g.originX) || g.right < g.originX) continue;@@ -362,7 +359,7 @@ function captureCharPositions(geometry: CharGeometry[]): Set<TextRun> {}// The loose box's right edge is the pen position after the glyph, which// is what makes consecutive word boxes tile without drift.- list.push({ cp: g.cp, x: g.originX, end: g.right });+ list.push({ cp: g.cp, x: g.originX, end: g.right, bottom: g.bottom });}const changed = new Set<TextRun>();@@ -373,7 +370,18 @@ function captureCharPositions(geometry: CharGeometry[]): Set<TextRun> {if (!scale || Math.abs(run.matrix.b) / scale > 0.02 || run.matrix.a <= 0) {continue;}- const aligned = alignToText(run.text, list);+ // Text typed into a paragraph, and an edited scan's redrawn words, are new+ // objects at the end of the page content, so the engine lists them after+ // lines that read later. Content order stays first choice: reading order+ // can misjudge lines set close together.+ const aligned = run.scanEdit?.created.length+ ? alignToText(run.text, inReadingOrder(list, run.fontSize))+ : run.text.includes("\n")+ ? betterAlignment(+ alignToText(run.text, list),+ alignToText(run.text, inReadingOrder(list, run.fontSize)),+ )+ : alignToText(run.text, list);if (!aligned) continue;// Same positions under a still-current key is a no-op capture; skipping it// keeps untouched runs' snapshots stable across the periodic tick.@@ -392,12 +400,42 @@ function captureCharPositions(geometry: CharGeometry[]): Set<TextRun> {return changed;}+export interface PlacedGlyph {+ cp: number;+ x: number;+ end: number;+ bottom: number;+}++// Top line first, then left to right; glyph boxes within half a font size share a line.+export function inReadingOrder(+ glyphs: PlacedGlyph[],+ fontSize: number,+): PlacedGlyph[] {+ const tolerance = Math.max(1, fontSize * 0.5);+ const byHeight = [...glyphs].sort((a, b) => b.bottom - a.bottom);+ const lines: PlacedGlyph[][] = [];+ for (const glyph of byHeight) {+ const line = lines[lines.length - 1];+ if (line && line[0].bottom - glyph.bottom <= tolerance) line.push(glyph);+ else lines.push([glyph]);+ }+ return lines.flatMap((line) => line.sort((a, b) => a.x - b.x));+}++type Alignment = { starts: number[]; ends: number[]; placed: number };++function betterAlignment(+ a: Alignment | null,+ b: Alignment | null,+): Alignment | null {+ if (!a || !b) return a ?? b;+ return b.placed > a.placed ? b : a;+}+// Line up the engine's glyph list with the run's text - they are not// index-for-index, and anything unplaceable is left unknown, not guessed.-function alignToText(- text: string,- glyphs: Array<{ cp: number; x: number; end: number }>,-): { starts: number[]; ends: number[] } | null {+function alignToText(text: string, glyphs: PlacedGlyph[]): Alignment | null {const starts = new Array<number>(text.length).fill(Number.NaN);const ends = new Array<number>(text.length).fill(Number.NaN);let g = 0;@@ -432,7 +470,7 @@ function alignToText(// A capture that placed almost nothing is not worth trusting.const visible = [...text].filter((c) => !/\s/.test(c)).length;return placed >= Math.max(1, Math.floor(visible * 0.6))- ? { starts, ends }+ ? { starts, ends, placed }: null;}diff --git a/frontend/src/editor/core/tools/pdfTextEditor/store/EditorStore.ts b/frontend/src/editor/core/tools/pdfTextEditor/store/EditorStore.tsindex cc8a72ffba..0c3ccba048 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/store/EditorStore.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/store/EditorStore.ts@@ -34,6 +34,7 @@ import type {WidthMode,} from "@editor/tools/pdfTextEditor/types";import { resetEmbeddedFaces } from "@editor/tools/pdfTextEditor/util/embeddedFace";+import { resetFontCompletions } from "@editor/tools/pdfTextEditor/util/documentFontCompletion";/** Drop EVERY per-document charcode/glyph cache. */function resetCharcodeCaches(): void {@@ -48,6 +49,7 @@ function resetCharcodeCaches(): void {resetCharCoverageCache();// FontFaces are keyed by font pointer, which PDFium reuses across documents.resetEmbeddedFaces();+ resetFontCompletions();}export type InteractionMode = "select" | "addText" | "addTable";@@ -147,6 +149,8 @@ export class EditorStore {private loadToken = 0;/** File awaiting a password retry; held off the view state (not serialisable). */private _pendingPasswordFile: File | null = null;+ private nearViewportPages = new Set<number>();+ private nearViewportListeners = new Set<() => void>();constructor() {this.history = new HistoryStack();@@ -232,6 +236,22 @@ export class EditorStore {this.patch({ findOpen });}+ setPageNearViewport(pageIndex: number, near: boolean): void {+ if (this.nearViewportPages.has(pageIndex) === near) return;+ if (near) this.nearViewportPages.add(pageIndex);+ else this.nearViewportPages.delete(pageIndex);+ for (const listener of [...this.nearViewportListeners]) listener();+ }++ isPageNearViewport(pageIndex: number): boolean {+ return this.nearViewportPages.has(pageIndex);+ }++ subscribeNearViewport(listener: () => void): () => void {+ this.nearViewportListeners.add(listener);+ return () => this.nearViewportListeners.delete(listener);+ }+setHelpOpen(helpOpen: boolean): void {if (this.state.helpOpen === helpOpen) return;this.patch({ helpOpen });diff --git a/frontend/src/editor/core/tools/pdfTextEditor/types.ts b/frontend/src/editor/core/tools/pdfTextEditor/types.tsindex 845b7b3f55..2ff71fe262 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/types.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/types.ts@@ -62,6 +62,8 @@ export interface TextRunSnapshot {fill: RGBA;/** True if PDFium says the source PDF subsetted this run's font */fontSubset: boolean;+ /** For scanned text, the family its ink is matched to or redrawn in; `fontId` there is only the OCR layer's font. */+ scanFamily?: string;/** PDF text render mode (Tr). 0/absent = normal fill; 3 = invisible. */renderMode?: number;/** Outline colour, when the run's render mode strokes its glyphs. */diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/boxBlur.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/boxBlur.tsnew file mode 100644index 0000000000..d57a15d4e4--- /dev/null+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/boxBlur.ts@@ -0,0 +1,33 @@+/** Separable box blur of the first `channels` of every `stride`-wide pixel into a copy, `radius` pixels each way; other channels keep their values. */+export function boxBlur<T extends Float32Array | Uint8Array>(+ src: T,+ width: number,+ height: number,+ radius: number,+ channels = 1,+ stride = channels,+): T {+ let data = src;+ for (const [dx, dy] of [+ [1, 0],+ [0, 1],+ ]) {+ const out = data.slice() as T;+ for (let y = 0; y < height; y++)+ for (let x = 0; x < width; x++)+ for (let c = 0; c < channels; c++) {+ let sum = 0;+ let n = 0;+ for (let k = -radius; k <= radius; k++) {+ const xx = x + k * dx;+ const yy = y + k * dy;+ if (xx < 0 || yy < 0 || xx >= width || yy >= height) continue;+ sum += data[(yy * width + xx) * stride + c];+ n++;+ }+ out[(y * width + x) * stride + c] = sum / n;+ }+ data = out;+ }+ return data;+}diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/deviceFontEmbed.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/deviceFontEmbed.tsindex ffa9d8a98f..a1e04dd47b 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/util/deviceFontEmbed.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/deviceFontEmbed.ts@@ -3,6 +3,7 @@ import type { Page } from "@editor/tools/pdfTextEditor/model/Page";import type { RGBA } from "@editor/tools/pdfTextEditor/types";import { FontRef } from "@editor/tools/pdfTextEditor/model/FontRef";import { parseTrueTypeCmap } from "@editor/tools/pdfTextEditor/charcode/CmapResolver";+import { parseFontMetrics } from "@editor/tools/pdfTextEditor/util/fontMetrics";import { writeUtf16 } from "@editor/services/pdfiumService";import {externalFaceKey,@@ -58,7 +59,7 @@ interface DeviceFontModule {}/** Parsed cmap per family, so coverage is computed once per session. */-const coverageByFamily = new Map<string, Map<number, number> | null>();+const coverageByFamily = new Map<string, Set<number> | null>();/** Families PDFium already refused for a document; never retried. */let refusedByDoc = new WeakMap<EditorDocument, Set<string>>();/** Successful device-font emits per document, keyed by owned-font id. */@@ -80,20 +81,21 @@ export function resetDeviceFontEmbedCache(): void {emitCountByDoc = new WeakMap<EditorDocument, Map<string, number>>();}-function coverageOf(- family: string,- bytes: Uint8Array,-): Map<number, number> | null {- const key = deviceFontIdFor(family);- if (!coverageByFamily.has(key)) {- let parsed: Map<number, number> | null = null;- try {- parsed = parseTrueTypeCmap(bytes);- } catch {- parsed = null;- }- coverageByFamily.set(key, parsed);+/** Code points the font draws, or null when its tables cannot be read. */+export function fontCoverage(bytes: Uint8Array): Set<number> | null {+ try {+ const mapped =+ parseFontMetrics(bytes)?.advances ?? parseTrueTypeCmap(bytes);+ return mapped ? new Set(mapped.keys()) : null;+ } catch {+ return null;}+}++function coverageOf(family: string, bytes: Uint8Array): Set<number> | null {+ const key = deviceFontIdFor(family);+ if (!coverageByFamily.has(key))+ coverageByFamily.set(key, fontCoverage(bytes));return coverageByFamily.get(key) ?? null;}@@ -118,7 +120,7 @@ function deviceFontCovers(return visibleCodePoints(text).every((cp) => coverage.has(cp));}-export function deviceFontCoverage(family: string): Map<number, number> | null {+export function deviceFontCoverage(family: string): Set<number> | null {const bytes = getExternalFontBytes(family);return bytes ? coverageOf(family, bytes) : null;}diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/documentFontCompletion.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/documentFontCompletion.tsnew file mode 100644index 0000000000..800330d16b--- /dev/null+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/documentFontCompletion.ts@@ -0,0 +1,220 @@+import type { WrappedPdfiumModule } from "@embedpdf/pdfium";+import {+ documentFontHandle,+ familyOf,+ nearestStandardFont,+ stripSubsetTag,+} from "@editor/tools/pdfTextEditor/util/fontFamily";+import {+ getExternalFontBytes,+ loadExternalFontBytes,+ loadedExternalFonts,+} from "@editor/tools/pdfTextEditor/util/externalFonts";+import {+ faceStyleFlags,+ pickLocalFontFace,+ type LocalFont,+} from "@editor/tools/pdfTextEditor/util/localFonts";+import { embeddedFontProgram } from "@editor/tools/pdfTextEditor/util/embeddedFace";+import { compareFontPrograms } from "@editor/tools/pdfTextEditor/util/fontProgramMatch";+import { readFontName } from "@editor/tools/pdfTextEditor/charcode/FontHelpers";++// Which font draws the characters an embedded subset lacks: the same typeface when installed or served, else the closest available one.++/** `original` is the document's own typeface; `closest` is a lookalike. */+export type FontCompletionSource = "original" | "closest";++export interface FontCompletion {+ /** A family the text emitter can draw in right now. */+ family: string;+ source: FontCompletionSource;+}++// Keyed by PDFium font handle, unique only within one open document: EditorStore resets them with its other pointer-keyed caches.+const completions = new Map<number, FontCompletion>();+const refused = new Set<number>();+const lookedUp = new Map<number, LocalFont[]>();+const lookingUp = new Set<number>();+const listeners = new Set<() => void>();+let generation = 0;++function changed(): void {+ generation++;+ for (const listener of listeners) listener();+}++export function subscribeFontCompletions(listener: () => void): () => void {+ listeners.add(listener);+ return () => listeners.delete(listener);+}++export function fontCompletionsGeneration(): number {+ return generation;+}++export function resetFontCompletions(): void {+ completions.clear();+ refused.clear();+ lookedUp.clear();+ lookingUp.clear();+ changed();+}++function drawable(family: string): boolean {+ return (+ nearestStandardFont(family) === family || !!getExternalFontBytes(family)+ );+}++/** The font standing in for the characters `fontId` lacks, once one is known. */+export function fontCompletionFor(fontId: string): FontCompletion | null {+ const found = completions.get(documentFontHandle(fontId));+ return found && drawable(found.family) ? found : null;+}++/** True when a font with this document font's name is available but is a different typeface, so the name alone must not be trusted. */+export function fontNameRefused(fontId: string): boolean {+ return refused.has(documentFontHandle(fontId));+}++/** Whether {@link resolveOriginalFonts} has finished looking for `fontId`. */+export function originalFontLookedUp(fontId: string): boolean {+ return lookedUp.has(documentFontHandle(fontId));+}++export function setClosestFont(fontId: string, family: string): void {+ const handle = documentFontHandle(fontId);+ if (!handle || completions.get(handle)?.source === "original") return;+ completions.set(handle, { family, source: "closest" });+ changed();+}++function baseFontName(m: WrappedPdfiumModule, handle: number): string | null {+ const name = readFontName(m, handle);+ return name ? stripSubsetTag(name) : null;+}++/** Whether `fontId` is the document's own font and may need completing; judged by the PDF's /BaseFont, since a named standard font is drawn by a stand-in ("Chrom Sans OTF"). */+export function fontCanBeCompleted(+ m: WrappedPdfiumModule,+ fontId: string,+): boolean {+ const handle = documentFontHandle(fontId);+ const family = familyOf(fontId);+ if (!handle || !family || nearestStandardFont(family) === family)+ return false;+ const named = baseFontName(m, handle);+ return !named || nearestStandardFont(named) !== named;+}++const letters = (name: string) => name.toLowerCase().replace(/[^a-z0-9]/g, "");++// A PostScript name identifies one face, where a family name needs the style guessed: "Arial-BoldMT" is the bold cut of "Arial".+function requestForPostScriptName(+ fonts: LocalFont[],+ name: string,+): string | null {+ const wanted = letters(name);+ const face = wanted+ ? fonts.find((font) => letters(font.postscriptName) === wanted)+ : undefined;+ if (!face) return null;+ const { bold, italic } = faceStyleFlags(face);+ const flagged = [face.family, bold ? "Bold" : "", italic ? "Italic" : ""]+ .filter(Boolean)+ .join(" ");+ if (pickLocalFontFace(fonts, flagged) === face) return flagged;+ return pickLocalFontFace(fonts, face.fullName) === face+ ? face.fullName+ : null;+}++function candidateRequests(+ fonts: LocalFont[],+ baseName: string | null,+ family: string,+): string[] {+ const byName = baseName ? requestForPostScriptName(fonts, baseName) : null;+ const byFamily = pickLocalFontFace(fonts, family) ? family : null;+ return [...new Set([byName, byFamily].filter((r): r is string => !!r))];+}++function readEmbeddedProgram(+ m: WrappedPdfiumModule,+ handle: number,+): Uint8Array | null {+ try {+ return embeddedFontProgram(m, handle);+ } catch {+ return null;+ }+}++type Lookup =+ | { kind: "accepted"; family: string }+ | { kind: "mismatched" }+ | { kind: "none" }+ | { kind: "closed" };++async function lookUpOriginal(+ m: WrappedPdfiumModule,+ fontId: string,+ fonts: LocalFont[],+ stillOpen: () => boolean,+): Promise<Lookup> {+ const handle = documentFontHandle(fontId);+ const requests = candidateRequests(+ fonts,+ baseFontName(m, handle),+ familyOf(fontId),+ );+ if (requests.length === 0) return { kind: "none" };+ const embedded = readEmbeddedProgram(m, handle);+ let mismatched = false;+ for (const request of requests) {+ const bytes = await loadExternalFontBytes(request);+ if (!stillOpen()) return { kind: "closed" };+ if (!bytes) continue;+ const verdict = embedded ? compareFontPrograms(embedded, bytes) : "unknown";+ if (verdict !== "different") return { kind: "accepted", family: request };+ mismatched = true;+ }+ return mismatched ? { kind: "mismatched" } : { kind: "none" };+}++function record(handle: number, lookup: Lookup): void {+ if (lookup.kind === "accepted") {+ refused.delete(handle);+ completions.set(handle, { family: lookup.family, source: "original" });+ } else if (lookup.kind === "mismatched") {+ refused.add(handle);+ if (completions.get(handle)?.source === "original")+ completions.delete(handle);+ }+}++/** Finds each embedded font's installed or served namesake and keeps it only if its glyphs agree; `stillOpen` is asked after every file read. */+export async function resolveOriginalFonts(+ m: WrappedPdfiumModule,+ fontIds: Iterable<string>,+ stillOpen: () => boolean,+): Promise<void> {+ const fonts = loadedExternalFonts();+ if (!fonts || fonts.length === 0) return;+ const ids = new Set(fontIds);+ for (const fontId of ids) {+ const handle = documentFontHandle(fontId);+ if (lookedUp.get(handle) === fonts || lookingUp.has(handle)) continue;+ if (!fontCanBeCompleted(m, fontId)) continue;+ lookingUp.add(handle);+ const lookup = await lookUpOriginal(m, fontId, fonts, stillOpen);+ if (lookup.kind === "closed") return;+ lookingUp.delete(handle);+ record(handle, lookup);+ lookedUp.set(handle, fonts);+ changed();+ }+ // A call made while this one was reading skipped the fonts it was looking up.+ if (stillOpen() && loadedExternalFonts() !== fonts)+ await resolveOriginalFonts(m, ids, stillOpen);+}diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/embeddedFace.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/embeddedFace.tsindex 5f7675cf1f..68220f677e 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/util/embeddedFace.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/embeddedFace.ts@@ -30,7 +30,7 @@ export function registerEmbeddedFace(if (typeof document === "undefined" || typeof FontFace === "undefined") {return;}- const bytes = readFontData(m, fontPtr);+ const bytes = embeddedFontProgram(m, fontPtr);if (!bytes || bytes.length === 0) return;if (faceBytesHeld + bytes.length > MAX_TOTAL_FACE_BYTES) return;const held = bytes.length;@@ -91,8 +91,8 @@ function isLoadableFaceHeader(head: Uint8Array): boolean {);}-/** Copy a font's face bytes out of the WASM heap. */-function readFontData(+/** The font file a document font embeds, copied out of the WASM heap; null when PDFium has none to give. */+export function embeddedFontProgram(m: WrappedPdfiumModule,fontPtr: number,): Uint8Array<ArrayBuffer> | null {diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/externalFonts.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/externalFonts.tsindex 503df10b86..4fda3ae805 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/util/externalFonts.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/externalFonts.ts@@ -2,10 +2,11 @@ import {getLocalFaceKey,getLocalFontBytes,loadedLocalFonts,- loadLocalFontBytes,+ loadLocalFont,normaliseName,subscribeLocalFonts,type LocalFont,+ type LocalFontLoad,} from "@editor/tools/pdfTextEditor/util/localFonts";import {getServerFaceId,@@ -62,9 +63,16 @@ export function externalFaceKey(family: string): string {return local ? `local:${local}` : normaliseName(family);}+/** A family's bytes from the server when it supplies the family, else from the device; never refused for licence when the server supplies it. */+export async function loadExternalFont(family: string): Promise<LocalFontLoad> {+ if (!serverFaceFor(family)) return loadLocalFont(family);+ const bytes = await loadServerFontBytes(family);+ return bytes ? { bytes } : { refused: "unavailable" };+}+export async function loadExternalFontBytes(family: string,): Promise<Uint8Array | null> {- if (serverFaceFor(family)) return loadServerFontBytes(family);- return loadLocalFontBytes(family);+ const load = await loadExternalFont(family);+ return "bytes" in load ? load.bytes : null;}diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/fallbackFont.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/fallbackFont.tsindex 1c15170767..47ce1a5dfe 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/util/fallbackFont.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/fallbackFont.ts@@ -3,6 +3,7 @@ import type { Page } from "@editor/tools/pdfTextEditor/model/Page";import type { RGBA } from "@editor/tools/pdfTextEditor/types";import { FontRef } from "@editor/tools/pdfTextEditor/model/FontRef";import { parseTrueTypeCmap } from "@editor/tools/pdfTextEditor/charcode/CmapResolver";+import { visibleCodePoints } from "@editor/tools/pdfTextEditor/util/deviceFontEmbed";import { writeUtf16 } from "@editor/services/pdfiumService";import { BASE_PATH } from "@editor/constants/app";import {@@ -29,13 +30,9 @@ function fallbackFontCovers(text: string): boolean {if (!fallbackCoverage && cachedBytes) {fallbackCoverage = parseTrueTypeCmap(cachedBytes);}- if (!fallbackCoverage) return true;- for (const ch of text) {- if (/\s/.test(ch)) continue;- const cp = ch.codePointAt(0)!;- if (!fallbackCoverage.has(cp)) return false;- }- return true;+ const coverage = fallbackCoverage;+ if (!coverage) return true;+ return visibleCodePoints(text).every((cp) => coverage.has(cp));}interface ExtendedPdfiumRuntime {diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/fontCapability.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/fontCapability.tsindex 709713298b..8687ed89c6 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/util/fontCapability.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/fontCapability.ts@@ -8,13 +8,16 @@ import { helveticaVariantFor } from "@editor/tools/pdfTextEditor/util/helveticaVimport {faceStyleFlags,knownFamilyOf,- pickLocalFontFace,+ pickRequestedFace,resolveRequested,type LocalFont,} from "@editor/tools/pdfTextEditor/util/localFonts";+import {+ fontCompletionFor,+ fontNameRefused,+} from "@editor/tools/pdfTextEditor/util/documentFontCompletion";import {getExternalFontBytes,- loadExternalFontBytes,loadedExternalFonts,} from "@editor/tools/pdfTextEditor/util/externalFonts";@@ -33,16 +36,6 @@ export interface StyleCapability {const NONE: StyleCapability = { family: null, source: null };-/** Families {@link warmDocumentDeviceFonts} has already looked up this session. */-const attempted = new Set<string>();-let attemptedAgainst: LocalFont[] | null = null;--/** Test hook: forget which document families have been matched. */-export function resetDocumentFontMatchCache(): void {- attempted.clear();- attemptedAgainst = null;-}-/** The installed face for `family` in the requested style, or null. */function deviceFaceFor(fonts: LocalFont[],@@ -51,16 +44,15 @@ function deviceFaceFor(): string | null {const req = resolveRequested(fonts, family);if (!req.family) return null;- const wanted = [req.family, req.bold ? "Bold" : "", italic ? "Italic" : ""]- .filter(Boolean)- .join(" ");- const face = pickLocalFontFace(fonts, wanted);+ const face = pickRequestedFace(fonts, { ...req, italic });if (!face) return null;- // pickLocalFontFace always returns SOMETHING from a matching family, so the+ // pickRequestedFace always returns SOMETHING from a matching family, so the// style has to be checked: a family with no italic cut answers with upright.const flags = faceStyleFlags(face);if (flags.italic !== italic) return null;- return wanted;+ return [req.family, req.bold ? "Bold" : "", italic ? "Italic" : ""]+ .filter(Boolean)+ .join(" ");}/** Base-14 flips in place unless an external family of that name exists; others need a real face. */@@ -110,8 +102,11 @@ export function canToggleItalic(* subset from the device font keeps it.*/export function fallbackFamilyFor(fontId: string): string {+ const completion = fontCompletionFor(fontId);+ if (completion) return completion.family;const family = familyOf(fontId);- if (family && getExternalFontBytes(family)) return family;+ if (family && !fontNameRefused(fontId) && getExternalFontBytes(family))+ return family;return helveticaVariantFor(fontId);}@@ -124,38 +119,3 @@ export function fallbackFamilyFor(fontId: string): string {export function fallbackFontIdFor(family: string): string {return `${getExternalFontBytes(family) ? "device" : "base14"}:${family}`;}--/**- * Read the installed faces matching the DOCUMENT's own families, so a later- * edit that outgrows a subset has real bytes to complete it from.- *- * Only exact family matches are loaded - "Calibri" never warms "Calibri Light"- * - so recognition stays a match, not a guess. Returns the families matched.- */-export async function warmDocumentDeviceFonts(- fontIds: Iterable<string>,-): Promise<string[]> {- const fonts = loadedExternalFonts();- if (!fonts || fonts.length === 0) return [];- if (fonts !== attemptedAgainst) {- attempted.clear();- attemptedAgainst = fonts;- }- const wanted = new Set<string>();- for (const id of fontIds) {- const family = familyOf(id);- // base-14 renders everywhere already; nothing to complete.- if (!family || nearestStandardFont(family) === family) continue;- // Every edit re-runs this over the whole page model, and scanning a few- // thousand installed faces per keystroke is not free.- if (attempted.has(family)) continue;- attempted.add(family);- if (getExternalFontBytes(family)) continue;- if (pickLocalFontFace(fonts, family)) wanted.add(family);- }- const matched: string[] = [];- for (const family of wanted) {- if (await loadExternalFontBytes(family)) matched.push(family);- }- return matched;-}diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/fontCollection.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/fontCollection.tsnew file mode 100644index 0000000000..416ec20c2a--- /dev/null+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/fontCollection.ts@@ -0,0 +1,89 @@+import {+ assembleSfnt,+ readTableDirectory,+ type SfntTable,+} from "@editor/tools/pdfTextEditor/util/sfnt";++const TTCF = 0x74746366;++function isCollection(dv: DataView): boolean {+ return dv.byteLength >= 12 && dv.getUint32(0) === TTCF;+}++function faceOffsets(dv: DataView): number[] {+ const count = dv.getUint32(8);+ const offsets: number[] = [];+ for (let i = 0; i < count && 12 + i * 4 + 4 <= dv.byteLength; i++)+ offsets.push(dv.getUint32(12 + i * 4));+ return offsets;+}++function tablesAt(dv: DataView, sfnt: number): Map<string, SfntTable> {+ const face = new DataView(+ dv.buffer,+ dv.byteOffset + sfnt,+ dv.byteLength - sfnt,+ );+ return readTableDirectory(face) ?? new Map();+}++function readPostscriptName(dv: DataView, sfnt: number): string | null {+ const name = tablesAt(dv, sfnt).get("name");+ if (!name || name.offset + 6 > dv.byteLength) return null;+ const count = dv.getUint16(name.offset + 2);+ const strings = name.offset + dv.getUint16(name.offset + 4);+ for (let i = 0; i < count; i++) {+ const rec = name.offset + 6 + i * 12;+ if (rec + 12 > dv.byteLength) break;+ if (dv.getUint16(rec + 6) !== 6) continue;+ const platform = dv.getUint16(rec);+ const length = dv.getUint16(rec + 8);+ const start = strings + dv.getUint16(rec + 10);+ if (start + length > dv.byteLength) continue;+ let text = "";+ if (platform === 3 || platform === 0)+ for (let k = 0; k + 1 < length; k += 2)+ text += String.fromCharCode(dv.getUint16(start + k));+ else+ for (let k = 0; k < length; k++)+ text += String.fromCharCode(dv.getUint8(start + k));+ if (text) return text;+ }+ return null;+}++function standalone(dv: DataView, bytes: Uint8Array, sfnt: number): Uint8Array {+ const tables = new Map<string, Uint8Array>();+ for (const [tag, t] of tablesAt(dv, sfnt))+ if (t.offset + t.length <= bytes.length)+ tables.set(tag, bytes.subarray(t.offset, t.offset + t.length));+ return assembleSfnt(dv.getUint32(sfnt), tables);+}++export function fontFace(+ bytes: Uint8Array,+ postscriptName?: string,+): Uint8Array | null {+ const dv = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);+ if (!isCollection(dv)) return bytes;+ try {+ const offsets = faceOffsets(dv);+ const wanted = postscriptName?.trim();+ const pick = wanted+ ? offsets.find((o) => readPostscriptName(dv, o) === wanted)+ : offsets[0];+ return pick === undefined ? null : standalone(dv, bytes, pick);+ } catch {+ return null;+ }+}++export function facePostscriptNames(bytes: Uint8Array): string[] {+ const dv = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);+ try {+ const offsets = isCollection(dv) ? faceOffsets(dv) : [0];+ return offsets.map((o) => readPostscriptName(dv, o) ?? "");+ } catch {+ return [];+ }+}diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/fontFamily.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/fontFamily.tsindex f68e4bd0a4..3ddf2d7a41 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/util/fontFamily.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/fontFamily.ts@@ -9,6 +9,11 @@ export function isItalicFamily(fontId: string): boolean {return /italic|oblique/i.test(fontId);}+/** Subset fonts carry a 6-letter "ABCDEF+" tag; strip it for display. */+export function stripSubsetTag(name: string): string {+ return name.replace(/^[A-Z]{6}\+/, "");+}+/** Strip any `prefix:` qualifier that `PdfiumTextReader` adds to font ids. */export function familyOf(fontId: string): string {const idx = fontId.lastIndexOf(":");@@ -111,6 +116,20 @@ const STANDARD_FONTS = new Set(["ZapfDingbats",]);+const WIN_ANSI_EXTRAS = new Set([+ 0x0152, 0x0153, 0x0160, 0x0161, 0x0178, 0x017d, 0x017e, 0x0192, 0x02c6,+ 0x02dc, 0x2013, 0x2014, 0x2018, 0x2019, 0x201a, 0x201c, 0x201d, 0x201e,+ 0x2020, 0x2021, 0x2022, 0x2026, 0x2030, 0x2039, 0x203a, 0x20ac, 0x2122,+]);++export function encodesInBase14(cp: number): boolean {+ return (+ (cp >= 0x20 && cp < 0x7f) ||+ (cp >= 0xa0 && cp <= 0xff) ||+ WIN_ANSI_EXTRAS.has(cp)+ );+}+// The standard PDF font that best stands in for an arbitrary family: PDFium// can only build a text object for one of the 14, so approximate, don't drop.export function nearestStandardFont(family: string): string {diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/fontMetrics.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/fontMetrics.tsnew file mode 100644index 0000000000..28fae15ee9--- /dev/null+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/fontMetrics.ts@@ -0,0 +1,227 @@+import { parseTrueTypeCmap } from "@editor/tools/pdfTextEditor/charcode/CmapResolver";+import {+ readTableDirectory,+ tableChecksum,+ type SfntTable,+} from "@editor/tools/pdfTextEditor/util/sfnt";++export type FaceKind = "sans" | "serif" | "mono";++export interface FontMetrics {+ cap: number;+ xh: number;+ asc: number;+ advances: Map<number, number>;+ tops: Map<number, number>;+ kind: FaceKind;+ weight: number;+ variableWeight: number | null;+ outlines: string;+}++function kindOf(fixedPitch: boolean, panose: number[] | null): FaceKind {+ if (fixedPitch || panose?.[3] === 9) return "mono";+ const serifStyle = panose?.[1] ?? 0;+ if (serifStyle >= 11) return "sans";+ if (serifStyle >= 2) return "serif";+ return "sans";+}++const WGHT_AXIS = 0x77676874; // "wght"++function defaultWeight(+ dv: DataView,+ fvar: { offset: number } | undefined,+): number | null {+ if (!fvar) return null;+ const axes = fvar.offset + dv.getUint16(fvar.offset + 4);+ const count = dv.getUint16(fvar.offset + 8);+ const size = dv.getUint16(fvar.offset + 10);+ for (let i = 0; i < count; i++) {+ const axis = axes + i * size;+ if (dv.getUint32(axis) !== WGHT_AXIS) continue;+ const max = dv.getInt32(axis + 12) / 65536;+ return max >= 100 ? dv.getInt32(axis + 8) / 65536 : null;+ }+ return null;+}++const FS_TYPE_OFFSET = 8;+const FS_TYPE_USAGE_MASK = 0x000f;+const FS_TYPE_RESTRICTED = 0x0002;+const FS_TYPE_BITMAP_ONLY = 0x0200;++function tablesOf(bytes: Uint8Array): {+ dv: DataView;+ tables: Map<string, SfntTable> | null;+} {+ const dv = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);+ return { dv, tables: readTableDirectory(dv) };+}++/** Whether one face's OS/2 fsType forbids embedding it (Restricted Licence, or bitmap-only); no readable OS/2 means no restriction. Must match EditorFontReader on the server. */+export function embeddingForbidden(bytes: Uint8Array): boolean {+ const { dv, tables } = tablesOf(bytes);+ const os2 = tables?.get("OS/2");+ if (!os2 || os2.offset + FS_TYPE_OFFSET + 2 > dv.byteLength) return false;+ const fsType = dv.getUint16(os2.offset + FS_TYPE_OFFSET);+ return (+ (fsType & FS_TYPE_USAGE_MASK) === FS_TYPE_RESTRICTED ||+ (fsType & FS_TYPE_BITMAP_ONLY) !== 0+ );+}++/** Whether one face has TrueType outlines: the editor embeds device fonts as TrueType, and a CFF face saves as a broken font resource. */+export function hasTrueTypeOutlines(bytes: Uint8Array): boolean {+ const { tables } = tablesOf(bytes);+ return !!tables?.has("glyf") && !tables.has("CFF ") && !tables.has("CFF2");+}++const parsed = new WeakMap<Uint8Array, FontMetrics | null>();++export function parseFontMetrics(bytes: Uint8Array): FontMetrics | null {+ if (!parsed.has(bytes)) parsed.set(bytes, readFontMetrics(bytes));+ return parsed.get(bytes) ?? null;+}++function readFontMetrics(bytes: Uint8Array): FontMetrics | null {+ if (bytes.length < 12) return null;+ const dv = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);+ const scaler = dv.getUint32(0);+ if (scaler !== 0x00010000 && scaler !== 0x74727565 && scaler !== 0x4f54544f)+ return null;+ try {+ const t = readTableDirectory(dv);+ if (!t) return null;+ const head = t.get("head");+ if (!head) return null;+ const upm = dv.getUint16(head.offset + 18) || 1000;+ const em = (v: number) => Math.round((v * 1000) / upm);+ const cmap = parseTrueTypeCmap(bytes);+ if (!cmap) return null;+ const advances = advancesOf(dv, t, cmap);+ if (!advances?.has(0x20)) return null;++ const glyphRange = glyphRangeReader(dv, t);+ const tops = new Map<number, number>();+ for (const [cp, gid] of cmap) {+ const range = gid > 0 ? glyphRange?.(gid) : null;+ if (range) tops.set(cp, em(dv.getInt16(range.start + 8)));+ }+ const top = (ch: string) => tops.get(ch.charCodeAt(0)) ?? null;++ const os2 = t.get("OS/2");+ let weight = 400;+ let os2Xh = 0;+ let os2Cap = 0;+ let panose: number[] | null = null;+ if (os2 && os2.length >= 78) {+ const version = dv.getUint16(os2.offset);+ weight = dv.getUint16(os2.offset + 4);+ panose = Array.from({ length: 10 }, (_, i) =>+ dv.getUint8(os2.offset + 32 + i),+ );+ if (version >= 2 && os2.length >= 90) {+ os2Xh = em(dv.getInt16(os2.offset + 86));+ os2Cap = em(dv.getInt16(os2.offset + 88));+ }+ }+ const post = t.get("post");+ const fixedPitch = !!post && dv.getUint32(post.offset + 12) !== 0;++ const cap = top("H") ?? (os2Cap || 700);+ const xh = top("x") ?? (os2Xh || Math.round(cap * 0.72));+ const asc = Math.max(cap, top("d") ?? cap);+ return {+ cap,+ xh,+ asc,+ advances,+ tops,+ kind: kindOf(fixedPitch, panose),+ weight,+ variableWeight: defaultWeight(dv, t.get("fvar")),+ outlines: outlinesKey(bytes, t.get("glyf")),+ };+ } catch {+ return null;+ }+}++function outlinesKey(bytes: Uint8Array, glyf: SfntTable | undefined): string {+ if (!glyf) return "";+ const data = bytes.subarray(glyf.offset, glyf.offset + glyf.length);+ return `${tableChecksum(data)}:${glyf.length}`;+}++function advancesOf(+ dv: DataView,+ t: Map<string, SfntTable>,+ cmap: Map<number, number>,+): Map<number, number> | null {+ const head = t.get("head");+ const hhea = t.get("hhea");+ const hmtx = t.get("hmtx");+ if (!head || !hhea || !hmtx) return null;+ const upm = dv.getUint16(head.offset + 18) || 1000;+ const numHMetrics = dv.getUint16(hhea.offset + 34);+ if (numHMetrics === 0) return null;+ const advances = new Map<number, number>();+ for (const [cp, gid] of cmap) {+ if (gid <= 0) continue;+ const at = hmtx.offset + Math.min(gid, numHMetrics - 1) * 4;+ advances.set(cp, Math.round((dv.getUint16(at) * 1000) / upm));+ }+ return advances;+}++/** Each mapped code point's advance in thousandths of an em, or null when the font has no cmap or horizontal metrics. */+export function charAdvances(bytes: Uint8Array): Map<number, number> | null {+ if (bytes.length < 12) return null;+ const dv = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);+ const t = readTableDirectory(dv);+ const cmap = t && parseTrueTypeCmap(bytes);+ return t && cmap ? advancesOf(dv, t, cmap) : null;+}++export interface GlyphRange {+ start: number;+ end: number;+}++/** Where each glyph's outline lies in the font bytes; null for a font without TrueType outlines, and the reader gives null for an empty or out-of-range glyph. */+export function glyphRangeReader(+ dv: DataView,+ t: Map<string, SfntTable>,+): ((gid: number) => GlyphRange | null) | null {+ const head = t.get("head");+ const loca = t.get("loca");+ const glyf = t.get("glyf");+ if (!head || !loca || !glyf) return null;+ const longOffsets = dv.getInt16(head.offset + 50) === 1;+ const entry = longOffsets ? 4 : 2;+ const offsetAt = (gid: number) =>+ longOffsets+ ? dv.getUint32(loca.offset + gid * 4)+ : dv.getUint16(loca.offset + gid * 2) * 2;+ return (gid) => {+ if (gid < 0 || (gid + 2) * entry > loca.length) return null;+ const start = offsetAt(gid);+ const end = offsetAt(gid + 1);+ if (end <= start || end > glyf.length) return null;+ return { start: glyf.offset + start, end: glyf.offset + end };+ };+}++export function advanceWidth(+ metrics: Pick<FontMetrics, "advances">,+ text: string,+): number | null {+ let sum = 0;+ for (const ch of text) {+ const adv = metrics.advances.get(ch.codePointAt(0)!);+ if (adv === undefined) return null;+ sum += adv;+ }+ return sum;+}diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/fontProgramMatch.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/fontProgramMatch.tsnew file mode 100644index 0000000000..3626d20635--- /dev/null+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/fontProgramMatch.ts@@ -0,0 +1,98 @@+import { readTableDirectory } from "@editor/tools/pdfTextEditor/util/sfnt";+import {+ charAdvances,+ glyphRangeReader,+ type GlyphRange,+} from "@editor/tools/pdfTextEditor/util/fontMetrics";++/** Whether two font files are the same typeface; `unknown` when they gave too little to compare. */+export type FontProgramMatch = "same" | "different" | "unknown";++const MIN_GLYPHS_FOR_VERDICT = 3; // fewer agree by chance too easily+const MAX_GLYPHS_COMPARED = 64; // a verdict by then; a CJK font holds thousands+const ADVANCE_TOLERANCE = 1; // thousandths of an em: rounding both to that grid alone opens a gap of one+const AGREEING_SHARE = 0.9; // a revision of the same face may change a few widths++interface Program {+ bytes: Uint8Array;+ glyphCount: number;+ glyph: ((gid: number) => GlyphRange | null) | null;+}++function readProgram(bytes: Uint8Array): Program | null {+ const dv = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);+ const t = readTableDirectory(dv);+ const maxp = t?.get("maxp");+ if (!t || !maxp) return null;+ return {+ bytes,+ glyphCount: dv.getUint16(maxp.offset + 4),+ glyph: glyphRangeReader(dv, t),+ };+}++function outlineOf(program: Program, gid: number): Uint8Array | null {+ const range = program.glyph?.(gid);+ if (!range) return null;+ let end = range.end;+ // Glyph records are padded to a word boundary, and not every writer pads alike.+ while (end > range.start && program.bytes[end - 1] === 0) end--;+ return end > range.start ? program.bytes.subarray(range.start, end) : null;+}++function sameBytes(a: Uint8Array, b: Uint8Array): boolean {+ if (a.length !== b.length) return false;+ for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;+ return true;+}++// A subset that renumbers glyph ids proves nothing either way, so only agreement is a verdict.+function outlinesAtSameIds(embedded: Program, candidate: Program): boolean {+ if (!embedded.glyph || !candidate.glyph) return false;+ let compared = 0;+ for (let gid = 1; gid < embedded.glyphCount; gid++) {+ const glyph = outlineOf(embedded, gid);+ if (!glyph) continue;+ const other = outlineOf(candidate, gid);+ if (!other || !sameBytes(glyph, other)) return false;+ if (++compared >= MAX_GLYPHS_COMPARED) break;+ }+ return compared >= MIN_GLYPHS_FOR_VERDICT;+}++function advancesByCharacter(+ embedded: Uint8Array,+ candidate: Uint8Array,+): FontProgramMatch {+ const ours = charAdvances(embedded);+ const theirs = charAdvances(candidate);+ if (!ours || !theirs) return "unknown";+ let compared = 0;+ let agreeing = 0;+ for (const [codePoint, a] of ours) {+ const b = theirs.get(codePoint);+ // A subset can leave a mapped glyph empty with no width to compare.+ if (b === undefined || a === 0) continue;+ compared++;+ if (Math.abs(a - b) <= ADVANCE_TOLERANCE) agreeing++;+ if (compared >= MAX_GLYPHS_COMPARED) break;+ }+ if (compared < MIN_GLYPHS_FOR_VERDICT) return "unknown";+ return agreeing >= compared * AGREEING_SHARE ? "same" : "different";+}++/** Same outlines at the same glyph ids settle it; else shared characters' widths decide, accepting a metric-compatible face and rejecting a mere namesake. */+export function compareFontPrograms(+ embedded: Uint8Array,+ candidate: Uint8Array,+): FontProgramMatch {+ try {+ const ours = readProgram(embedded);+ const theirs = readProgram(candidate);+ if (!ours || !theirs) return "unknown";+ if (outlinesAtSameIds(ours, theirs)) return "same";+ return advancesByCharacter(embedded, candidate);+ } catch {+ return "unknown";+ }+}diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/localFontSource.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/localFontSource.tsnew file mode 100644index 0000000000..5f5399946d--- /dev/null+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/localFontSource.ts@@ -0,0 +1,124 @@+/** Where the editor gets this device's installed fonts: the seam a build shadows when the Chromium-only, permission-gated Local Font Access API is not the source. */++import type { LocalFont } from "@editor/tools/pdfTextEditor/util/localFonts";++export type LocalFontPermission =+ | "granted"+ | "prompt"+ | "denied"+ | "unsupported";++type QueryLocalFonts = () => Promise<unknown[]>;++interface BlobSource {+ blob?: () => Promise<unknown>;+}++interface BlobBytes {+ arrayBuffer?: () => Promise<ArrayBuffer>;+}++const sourceOf = new WeakMap<LocalFont, unknown>();++function browserQuery(): QueryLocalFonts | null {+ if (typeof window === "undefined") return null;+ const w = window as unknown as { queryLocalFonts?: QueryLocalFonts };+ if (typeof w.queryLocalFonts !== "function") return null;+ // Bound: Chrome throws "Illegal invocation" when the method is detached.+ return w.queryLocalFonts.bind(w);+}++function readString(value: unknown): string {+ return typeof value === "string" ? value.trim() : "";+}++function toLocalFont(face: unknown): LocalFont | null {+ if (!face || typeof face !== "object") return null;+ const data = face as Record<string, unknown>;+ const family = readString(data.family);+ if (!family) return null;+ return {+ family,+ fullName: readString(data.fullName) || family,+ style: readString(data.style),+ postscriptName: readString(data.postscriptName),+ };+}++/** Whether this build has any way to list device fonts. Never prompts. */+export function hasDeviceFontSource(): boolean {+ return browserQuery() !== null;+}++/** The installed faces. May prompt; rejects when the user refuses or there is no source. */+export async function listDeviceFaces(): Promise<LocalFont[]> {+ const query = browserQuery();+ if (!query) throw new Error("No device font source");+ const faces = await query();+ if (!Array.isArray(faces)) throw new TypeError("Unexpected font list");+ const fonts: LocalFont[] = [];+ for (const face of faces) {+ const font = toLocalFont(face);+ if (!font) continue;+ sourceOf.set(font, face);+ fonts.push(font);+ }+ return fonts;+}++/** The font file behind a face {@link listDeviceFaces} returned, or null when it cannot be read. Never throws. */+export async function readDeviceFace(+ face: LocalFont,+): Promise<Uint8Array | null> {+ const source = sourceOf.get(face);+ if (!source || typeof source !== "object") return null;+ const read = (source as BlobSource).blob;+ if (typeof read !== "function") return null;+ try {+ const blob = await read.call(source);+ if (!blob || typeof blob !== "object") return null;+ const toBuffer = (blob as BlobBytes).arrayBuffer;+ if (typeof toBuffer !== "function") return null;+ const bytes = new Uint8Array(await toBuffer.call(blob));+ return bytes.length > 0 ? bytes : null;+ } catch {+ return null;+ }+}++async function permissionStatus(): Promise<PermissionStatus | null> {+ try {+ return await navigator.permissions.query({+ name: "local-fonts" as PermissionName,+ });+ } catch {+ return null;+ }+}++/** Whether listing would prompt. Never prompts itself. */+export async function localFontPermission(): Promise<LocalFontPermission> {+ if (!hasDeviceFontSource()) return "unsupported";+ return (await permissionStatus())?.state ?? "prompt";+}++/** Calls `listener` on each later permission change, never with the current value; the returned stop also cancels a pending registration. */+export function watchLocalFontPermission(+ listener: (permission: LocalFontPermission) => void,+): () => void {+ if (!hasDeviceFontSource()) return () => {};+ let status: PermissionStatus | null = null;+ let stopped = false;+ const onChange = () => {+ if (status) listener(status.state);+ };+ void permissionStatus().then((s) => {+ if (stopped || !s) return;+ status = s;+ s.addEventListener("change", onChange);+ });+ return () => {+ stopped = true;+ status?.removeEventListener("change", onChange);+ };+}diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/localFonts.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/localFonts.tsindex ce2d076c80..30cae3d29a 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/util/localFonts.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/localFonts.ts@@ -1,5 +1,16 @@-// Local Font Access API wrapper. Chromium-only and permission-gated, so every-// entry point degrades to null instead of throwing.+// The fonts installed on this device; the source may be missing or refuse, so every entry point degrades instead of throwing.++import { fontFace } from "@editor/tools/pdfTextEditor/util/fontCollection";+import {+ embeddingForbidden,+ hasTrueTypeOutlines,+} from "@editor/tools/pdfTextEditor/util/fontMetrics";+import {+ hasDeviceFontSource,+ listDeviceFaces,+ localFontPermission,+ readDeviceFace,+} from "@editor/tools/pdfTextEditor/util/localFontSource";export interface FaceAxes {bold: boolean;@@ -26,62 +37,18 @@ export interface LocalFontFamily {styles: string[];}-type QueryLocalFonts = () => Promise<unknown[]>;--function localFontQuery(): QueryLocalFonts | null {- if (typeof window === "undefined") return null;- const w = window as unknown as { queryLocalFonts?: QueryLocalFonts };- if (typeof w.queryLocalFonts !== "function") return null;- // Bound: Chrome throws "Illegal invocation" when the method is detached.- return w.queryLocalFonts.bind(w);-}-/** Feature detection only - never prompts and has no side effects. */export function isLocalFontAccessSupported(): boolean {- return localFontQuery() !== null;-}--function readString(value: unknown): string {- return typeof value === "string" ? value.trim() : "";-}--function toLocalFont(face: unknown): LocalFont | null {- if (!face || typeof face !== "object") return null;- const data = face as Record<string, unknown>;- const family = readString(data.family);- if (!family) return null;- return {- family,- fullName: readString(data.fullName) || family,- style: readString(data.style),- postscriptName: readString(data.postscriptName),- };-}--// The raw `FontData` each mapped face came from: only it exposes `.blob()`,-// and `LocalFont` stays a plain data shape.-interface FaceEntry {- font: LocalFont;- source: unknown;+ return hasDeviceFontSource();}-let faceEntries: FaceEntry[] = [];let resolved: LocalFont[] | null = null;const listeners = new Set<() => void>();async function queryOnce(): Promise<LocalFont[] | null> {- const query = localFontQuery();- if (!query) return null;+ if (!hasDeviceFontSource()) return null;try {- const faces = await query();- if (!Array.isArray(faces)) return null;- const entries: FaceEntry[] = [];- for (const face of faces) {- const font = toLocalFont(face);- if (font) entries.push({ font, source: face });- }- faceEntries = entries;- resolved = entries.map((entry) => entry.font);+ resolved = await listDeviceFaces();for (const listener of [...listeners]) listener();return resolved;} catch {@@ -99,6 +66,18 @@ export async function listLocalFonts(): Promise<LocalFont[] | null> {return pending;}+export async function retryLocalFonts(): Promise<LocalFont[] | null> {+ if (pending && (await pending) === null) pending = null;+ return listLocalFonts();+}++/** Lists the device's fonts only when that cannot prompt: access was granted earlier. Resolves to what is already loaded, or null without access. */+export async function listLocalFontsIfGranted(): Promise<LocalFont[] | null> {+ if (!isLocalFontAccessSupported() || resolved) return resolved;+ if ((await localFontPermission()) !== "granted") return null;+ return retryLocalFonts();+}+/*** The faces {@link listLocalFonts} has already resolved, or null.*@@ -120,7 +99,6 @@ export function subscribeLocalFonts(listener: () => void): () => void {/** Drops the memoised result. Exists for tests. */export function resetLocalFontsCache(): void {pending = null;- faceEntries = [];resolved = null;bytesByFamily.clear();faceKeyByFamily.clear();@@ -277,10 +255,11 @@ function scoreFace(const style = faceStyleText(font);const bold = /bold|black|heavy|semib|demi/.test(style);const italic = /italic|oblique/.test(style);+ const plain = /^(regular|book|normal|roman)?$/.test(style);let score = 0;if (bold === wantBold) score += 4;if (italic === wantItalic) score += 4;- if (/^(regular|book|normal|roman)?$/.test(style)) score += 2;+ if (plain) score += 2;// Tie-break towards the plainer cut: "Light Condensed" also matches an// upright non-bold request, but "Regular" is what the user meant.return score - Math.min(style.length, 32) / 100;@@ -305,7 +284,18 @@ export function pickLocalFontFace(fonts: LocalFont[],requested: string,): LocalFont | null {- const wanted = resolveRequested(fonts, requested);+ const name = normaliseName(requested);+ return (+ pickRequestedFace(fonts, resolveRequested(fonts, requested)) ??+ fonts.find((font) => normaliseName(font.fullName) === name) ??+ null+ );+}++export function pickRequestedFace(+ fonts: LocalFont[],+ wanted: RequestedFace,+): LocalFont | null {const family = normaliseName(wanted.family);let best: LocalFont | null = null;let bestScore = Number.NEGATIVE_INFINITY;@@ -320,33 +310,21 @@ export function pickLocalFontFace(return best;}-interface BlobSource {- blob?: () => Promise<unknown>;-}--interface BlobBytes {- arrayBuffer?: () => Promise<ArrayBuffer>;-}+/** A device face's bytes, or why there are none: its licence forbids embedding, or it is missing, unreadable or not TrueType. */+export type LocalFontLoad =+ | { bytes: Uint8Array }+ | { refused: "licence" | "unavailable" };-async function readFaceBytes(source: unknown): Promise<Uint8Array | null> {- if (!source || typeof source !== "object") return null;- const read = (source as BlobSource).blob;- if (typeof read !== "function") return null;- try {- const blob = await read.call(source);- if (!blob || typeof blob !== "object") return null;- const toBuffer = (blob as BlobBytes).arrayBuffer;- if (typeof toBuffer !== "function") return null;- const bytes = new Uint8Array(await toBuffer.call(blob));- return bytes.length > 0 ? bytes : null;- } catch {- return null;- }-}+const UNAVAILABLE: LocalFontLoad = { refused: "unavailable" };const bytesByFamily = new Map<string, Uint8Array>();const faceKeyByFamily = new Map<string, string>();-const bytesPending = new Map<string, Promise<Uint8Array | null>>();+const bytesPending = new Map<string, Promise<LocalFontLoad>>();++export function registerFontBytes(family: string, bytes: Uint8Array): void {+ const key = normaliseName(family);+ if (key && bytes.length > 0) bytesByFamily.set(key, bytes);+}/** Already-read bytes for a family, or null. Never prompts, never awaits. */export function getLocalFontBytes(family: string): Uint8Array | null {@@ -358,30 +336,30 @@ export function getLocalFaceKey(family: string): string | null {return faceKeyByFamily.get(normaliseName(family)) ?? null;}-// The font file bytes behind a family name, cached for the session. Null when-// unsupported, denied, unmatched, or unreadable - never throws.-export async function loadLocalFontBytes(- family: string,-): Promise<Uint8Array | null> {+async function readFamily(family: string): Promise<LocalFontLoad> {+ const fonts = await listLocalFonts();+ const picked = fonts ? pickLocalFontFace(fonts, family) : null;+ if (!picked) return UNAVAILABLE;+ const file = await readDeviceFace(picked);+ const bytes = file ? fontFace(file, picked.postscriptName) : null;+ if (!bytes) return UNAVAILABLE;+ if (embeddingForbidden(bytes)) return { refused: "licence" };+ if (!hasTrueTypeOutlines(bytes)) return UNAVAILABLE;+ const key = normaliseName(family);+ bytesByFamily.set(key, bytes);+ faceKeyByFamily.set(key, picked.postscriptName || picked.fullName);+ return { bytes };+}++/** The font file behind a family name, cached for the session. Never throws. */+export async function loadLocalFont(family: string): Promise<LocalFontLoad> {const key = normaliseName(family);- if (!key) return null;+ if (!key) return UNAVAILABLE;const cached = bytesByFamily.get(key);- if (cached) return cached;+ if (cached) return { bytes: cached };const inFlight = bytesPending.get(key);if (inFlight) return inFlight;- const job = (async (): Promise<Uint8Array | null> => {- const fonts = await listLocalFonts();- if (!fonts) return null;- const picked = pickLocalFontFace(fonts, family);- if (!picked) return null;- const entry = faceEntries.find((candidate) => candidate.font === picked);- const bytes = entry ? await readFaceBytes(entry.source) : null;- if (bytes) {- bytesByFamily.set(key, bytes);- faceKeyByFamily.set(key, picked.postscriptName || picked.fullName);- }- return bytes;- })();+ const job = readFamily(family);bytesPending.set(key, job);try {return await job;@@ -391,3 +369,11 @@ export async function loadLocalFontBytes(bytesPending.delete(key);}}++/** {@link loadLocalFont}'s bytes, or null whatever the reason. */+export async function loadLocalFontBytes(+ family: string,+): Promise<Uint8Array | null> {+ const load = await loadLocalFont(family);+ return "bytes" in load ? load.bytes : null;+}diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/matchableSample.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/matchableSample.tsnew file mode 100644index 0000000000..4d14ce81dc--- /dev/null+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/matchableSample.ts@@ -0,0 +1,41 @@+import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";+import type { Page } from "@editor/tools/pdfTextEditor/model/Page";+import type { TextRun } from "@editor/tools/pdfTextEditor/model/TextRun";+import { scanFrameFor } from "@editor/tools/pdfTextEditor/commands/scanFrame";+import {+ captureScanEdit,+ isScanRun,+ type ScanEditState,+} from "@editor/tools/pdfTextEditor/commands/scanTextEdit";++const MIN_MATCHABLE_LETTERS = 6; // shorter runs rank faces by too few glyphs to trust+const MAX_RUNS_CAPTURED = 4; // a shorter run rarely captures where the longest few failed++export interface MatchableSample {+ page: Page;+ captured: ScanEditState;+ text: string;+}++/** The longest upright run in `fontId`, captured for ranking; turned text is skipped because measuring it turns the whole page upright and back. */+export function matchableSample(+ doc: EditorDocument,+ fontId: string,+): MatchableSample | null {+ const runs: Array<{ page: Page; run: TextRun; letters: number }> = [];+ for (const page of doc.loadedPages())+ for (const run of page.runs) {+ if (run.fontId !== fontId || isScanRun(run)) continue;+ const letters = run.text.replace(/\s/g, "").length;+ if (letters >= MIN_MATCHABLE_LETTERS) runs.push({ page, run, letters });+ }+ runs.sort((a, b) => b.letters - a.letters);+ const upright = runs.filter(+ ({ page, run }) => !scanFrameFor(page, run.matrix, run.bounds),+ );+ for (const { page, run } of upright.slice(0, MAX_RUNS_CAPTURED)) {+ const captured = captureScanEdit(doc.module, run, page);+ if (captured && !captured.frame) return { page, captured, text: run.text };+ }+ return null;+}diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/median.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/median.tsnew file mode 100644index 0000000000..8ae60897ad--- /dev/null+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/median.ts@@ -0,0 +1,9 @@+/** Middle value, the mean of the middle two for an even count; 0 when empty. */+export function median(values: number[]): number {+ if (values.length === 0) return 0;+ const sorted = [...values].sort((a, b) => a - b);+ const mid = sorted.length >> 1;+ return sorted.length % 2 === 0+ ? (sorted[mid - 1] + sorted[mid]) / 2+ : sorted[mid];+}diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/pageFonts.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/pageFonts.tsindex 7bd62d86fb..b5f6a24f5f 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/util/pageFonts.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/pageFonts.ts@@ -5,6 +5,7 @@ import {familyOf,isBase14FontId,isDeviceFontId,+ stripSubsetTag,} from "@editor/tools/pdfTextEditor/util/fontFamily";import { deviceFontCoverage } from "@editor/tools/pdfTextEditor/util/deviceFontEmbed";@@ -40,7 +41,9 @@ const ALNUM_CODEPOINTS: readonly number[] = (() => {})();/** Pure: which of a-z A-Z 0-9 are absent from a Unicode→glyphId cmap. */-export function missingAlnumFromCmap(cmap: Map<number, number>): string[] {+export function missingAlnumFromCmap(cmap: {+ has(codePoint: number): boolean;+}): string[] {const out: string[] = [];for (const cp of ALNUM_CODEPOINTS)if (!cmap.has(cp)) out.push(String.fromCodePoint(cp));@@ -80,11 +83,6 @@ const STANDARD_14 = [// (e.g. "Helvetica-BoldOblique", "ArialMT", "Times-Roman").const BASE14_STYLE_SUFFIX = /^(bold|italic|oblique|regular|roman|mt|ps)+$/;-/** Subset fonts carry a 6-letter "ABCDEF+" tag; strip it for display. */-function stripSubsetTag(name: string): string {- return name.replace(/^[A-Z]{6}\+/, "");-}-// Weight/width modifiers that mark a DIFFERENT font even when the name starts// with a base-14 root (e.g. "Arial Black", "Helvetica Neue Condensed").const NON_BASE14_MODIFIERS = [diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/scanFontLibrary.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/scanFontLibrary.tsnew file mode 100644index 0000000000..8da3334cce--- /dev/null+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/scanFontLibrary.ts@@ -0,0 +1,706 @@+import { getFontBaseUrl } from "@editor/services/fontBaseUrl";+import {+ faceStyleFlags,+ retryLocalFonts,+ loadLocalFontBytes,+ loadedLocalFonts,+ normaliseName,+ pickLocalFontFace,+ registerFontBytes,+ type LocalFont,+} from "@editor/tools/pdfTextEditor/util/localFonts";+import { localFontPermission } from "@editor/tools/pdfTextEditor/util/localFontSource";+import {+ loadServerFontBytes,+ loadServerFonts,+ serverFontCssFamily,+ serverFontsGeneration,+} from "@editor/tools/pdfTextEditor/util/serverFonts";+import {+ embeddingForbidden,+ hasTrueTypeOutlines,+ parseFontMetrics,+ type FaceKind,+ type FontMetrics,+} from "@editor/tools/pdfTextEditor/util/fontMetrics";+import { encodesInBase14 } from "@editor/tools/pdfTextEditor/util/fontFamily";+import { visibleCodePoints } from "@editor/tools/pdfTextEditor/util/deviceFontEmbed";++type FaceSource = "base14" | "bundled" | "device";++export interface Face {+ label: string;+ family: string;+ bold: string;+ cap: number;+ asc: number;+ xh: number;+ kind: FaceKind;+ source: FaceSource;+ metrics?: Map<string, FontMetrics>;+ twin?: Face;+}++export const HELVETICA: Face = {+ label: "Helvetica / Arial",+ family: "Helvetica",+ bold: "Helvetica-Bold",+ cap: 718,+ asc: 718,+ xh: 523,+ kind: "sans",+ source: "base14",+};+export const TIMES: Face = {+ label: "Times",+ family: "Times-Roman",+ bold: "Times-Bold",+ cap: 662,+ asc: 683,+ xh: 450,+ kind: "serif",+ source: "base14",+};+export const COURIER: Face = {+ label: "Courier",+ family: "Courier",+ bold: "Courier-Bold",+ cap: 562,+ asc: 629,+ xh: 426,+ kind: "mono",+ source: "base14",+};+export const BASE14_FACES: Face[] = [HELVETICA, TIMES, COURIER];++type BundledScanFont = Pick<Face, "label" | "family" | "bold"> & {+ files: [regular: string, bold: string];+};++export const BUNDLED_SCAN_FONTS: BundledScanFont[] = [+ {+ label: "Calibri (Carlito)",+ family: "Carlito",+ bold: "Carlito Bold",+ files: ["Carlito-Regular.ttf", "Carlito-Bold.ttf"],+ },+ {+ label: "Cambria (Caladea)",+ family: "Caladea",+ bold: "Caladea Bold",+ files: ["Caladea-Regular.ttf", "Caladea-Bold.ttf"],+ },+ {+ label: "DejaVu Sans",+ family: "DejaVu Sans",+ bold: "DejaVu Sans Bold",+ files: ["DejaVuSans.ttf", "DejaVuSans-Bold.ttf"],+ },+ {+ label: "DejaVu Serif",+ family: "DejaVu Serif",+ bold: "DejaVu Serif Bold",+ files: ["DejaVuSerif.ttf", "DejaVuSerif-Bold.ttf"],+ },+];++const DEVICE_TEXT_FAMILIES = [+ "Arial",+ "Arial Narrow",+ "Aptos",+ "Book Antiqua",+ "Bookman Old Style",+ "Calibri",+ "Cambria",+ "Candara",+ "Century Gothic",+ "Century Schoolbook",+ "Consolas",+ "Constantia",+ "Corbel",+ "Courier New",+ "Franklin Gothic Book",+ "Garamond",+ "EB Garamond",+ "Georgia",+ "Gill Sans MT",+ "Lato",+ "Lucida Console",+ "Lucida Sans",+ "Noto Sans",+ "Noto Serif",+ "Open Sans",+ "Palatino Linotype",+ "Roboto",+ "Segoe UI",+ "Source Sans Pro",+ "Tahoma",+ "Times New Roman",+ "Trebuchet MS",+ "Verdana",+ "American Typewriter",+ "Arial Black",+ "Avenir",+ "Avenir Next",+ "Baskerville",+ "Bodoni 72",+ "Cochin",+ "Comic Sans MS",+ "Copperplate",+ "Didot",+ "Futura",+ "Gill Sans",+ "Helvetica",+ "Helvetica Neue",+ "Hoefler Text",+ "Impact",+ "Optima",+ "Palatino",+ "Rockwell",+];++export type Script =+ | "greekCyrillic"+ | "hangul"+ | "kana"+ | "han"+ | "arabic"+ | "hebrew"+ | "thai"+ | "devanagari"+ | "malayalam"+ | "tibetan";++interface ScriptFonts {+ script: Script;+ chars: RegExp;+ server: RegExp;+ device: string[];+ servedBy?: Script;+ clones?: Record<string, { label: string; twin: Face }>;+}++const SCRIPTS: ScriptFonts[] = [+ {+ script: "greekCyrillic",+ chars: /[\u0370-\u03ff\u0400-\u04ff]/,+ server: /^Liberation (Sans|Serif|Mono)$/,+ device: [],+ clones: {+ "Liberation Sans": { label: "Arial (Liberation Sans)", twin: HELVETICA },+ "Liberation Serif": {+ label: "Times New Roman (Liberation Serif)",+ twin: TIMES,+ },+ "Liberation Mono": {+ label: "Courier New (Liberation Mono)",+ twin: COURIER,+ },+ },+ },+ {+ script: "hangul",+ chars: /[\u1100-\u11ff\u3130-\u318f\uac00-\ud7af]/,+ server: /\b(KR|Korean)\b/i,+ device: [+ "Malgun Gothic",+ "AppleGothic",+ "Gulim",+ "Dotum",+ "Batang",+ "NanumGothic",+ "Noto Sans KR",+ "UnDotum",+ ],+ },+ {+ script: "kana",+ chars: /[\u3040-\u30ff]/,+ server: /\b(JP|Japanese)\b/i,+ device: [+ "Yu Gothic",+ "Meiryo",+ "MS Gothic",+ "MS PGothic",+ "MS Mincho",+ "Osaka",+ "Noto Sans JP",+ "TakaoGothic",+ ],+ },+ {+ script: "han",+ chars: /[\u3400-\u4dbf\u4e00-\u9fff]/,+ server: /\b(SC|TC|HK|JP|Chinese)\b/i,+ servedBy: "kana",+ device: [+ "Microsoft YaHei",+ "SimSun",+ "SimHei",+ "Microsoft JhengHei",+ "PMingLiU",+ "MingLiU",+ "Heiti SC",+ "Heiti TC",+ "STHeiti",+ "Noto Sans SC",+ "Noto Sans TC",+ "WenQuanYi Micro Hei",+ "AR PL UMing CN",+ ],+ },+ {+ script: "arabic",+ chars: /[\u0600-\u06ff\u0750-\u077f]/,+ server: /Arabic/i,+ device: ["Noto Naskh Arabic", "Geeza Pro", "Segoe UI"],+ },+ {+ script: "hebrew",+ chars: /[\u0590-\u05ff]/,+ server: /Hebrew/i,+ device: ["Noto Sans Hebrew", "Arial Hebrew", "David"],+ },+ {+ script: "thai",+ chars: /[\u0e00-\u0e7f]/,+ server: /Thai/i,+ device: ["Noto Sans Thai", "Tahoma", "Leelawadee UI", "Thonburi"],+ },+ {+ script: "devanagari",+ chars: /[\u0900-\u097f]/,+ server: /Devanagari/i,+ device: ["Noto Sans Devanagari", "Mangal", "Kohinoor Devanagari"],+ },+ {+ script: "malayalam",+ chars: /[\u0d00-\u0d7f]/,+ server: /Malayalam/i,+ device: ["Noto Sans Malayalam", "Kartika"],+ },+ {+ script: "tibetan",+ chars: /[\u0f00-\u0fff]/,+ server: /Tibetan/i,+ device: ["Noto Serif Tibetan", "Microsoft Himalaya"],+ },+];++const COVERAGE = 0.9;++export function faceCovers(face: Face, text: string): boolean {+ const advances = face.metrics?.get(face.family)?.advances;+ const codePoints = visibleCodePoints(text);+ const drawable = codePoints.filter((cp) =>+ advances ? advances.has(cp) : encodesInBase14(cp),+ ).length;+ return drawable >= codePoints.length * COVERAGE;+}++export function candidateFaces(text: string): Face[] {+ return scanFaces().filter(+ (face) =>+ faceCovers(face, text) && !(face.twin && faceCovers(face.twin, text)),+ );+}++const DEVICE_TEXT_SCRIPTS =+ /[\p{Script=Latin}\p{Script=Greek}\p{Script=Cyrillic}]/u;++export function deviceFontsCouldCover(text: string): boolean {+ for (const ch of text) {+ if (!/\p{L}/u.test(ch) || DEVICE_TEXT_SCRIPTS.test(ch)) continue;+ if (!SCRIPTS.some((s) => s.device.length > 0 && s.chars.test(ch)))+ return false;+ }+ return true;+}++export function scanScriptsOf(text: string): Script[] {+ return SCRIPTS.filter((s) => s.chars.test(text)).map((s) => s.script);+}++let bundled: Face[] = [];+let scriptFaces: Face[] = [];+const neededScripts = new Set<Script>();+const scriptJobs = new Map<Script, Promise<void>>();+const serverFamiliesTaken = new Set<string>();+let serverFontsSeen = serverFontsGeneration();+let device: Face[] = [];+let deviceRead = false;+const deviceFamiliesRead = new Set<string>();+let bundledJob: Promise<void> | null = null;+let deviceJob: Promise<number> | null = null;+let generation = 0;+const listeners = new Set<() => void>();++function notify(): void {+ generation++;+ for (const listener of [...listeners]) listener();+}++export function subscribeScanFaces(listener: () => void): () => void {+ listeners.add(listener);+ return () => listeners.delete(listener);+}++export function scanFacesGeneration(): number {+ return generation;+}++const generationAtRanking = new WeakMap<object, number>();++export function noteRankedWithCurrentFaces(ranked: object): void {+ generationAtRanking.set(ranked, generation);+}++export function rankedWithCurrentFaces(ranked: object): boolean {+ return generationAtRanking.get(ranked) === generation;+}++export function scanFaces(): Face[] {+ return [...BASE14_FACES, ...bundled, ...scriptFaces, ...device];+}++/** CSS `font-family` list that draws a scan face by its family or bold name; give a bold name weight 700, as the regular family's CSS face carries the bold cut. */+export function scanFaceCssFamily(family: string): string {+ const face = scanFaces().find(+ (f) => f.family === family || f.bold === family,+ );+ const names = [family, face?.family ?? family].flatMap((name) => {+ const server = serverFontCssFamily(name);+ return server ? [server, name] : [name];+ });+ const named = [...new Set(names)].map((name) => `"${name}", `).join("");+ if (face?.kind === "serif")+ return `${named}"Liberation Serif", "Times New Roman", Times, serif`;+ if (face?.kind === "mono")+ return `${named}"Liberation Mono", "Courier New", Courier, monospace`;+ return `${named}"Liberation Sans", "Helvetica Neue", Helvetica, Arial, sans-serif`;+}++function hasFaceFor(family: string): boolean {+ const key = normaliseName(family);+ return scanFaces().some((face) => normaliseName(face.family) === key);+}++export function deviceScanFaceCount(): number | null {+ return deviceRead ? device.length : null;+}++type FaceSpec = Pick<Face, "label" | "family" | "bold" | "source" | "twin">;++function drawableMetrics(+ bytes: Uint8Array | null,+ weight: (variable: number) => boolean,+): FontMetrics | null {+ if (!bytes || embeddingForbidden(bytes) || !hasTrueTypeOutlines(bytes))+ return null;+ const metrics = parseFontMetrics(bytes);+ if (!metrics) return null;+ if (metrics.variableWeight !== null && !weight(metrics.variableWeight))+ return null;+ return metrics;+}++export function faceFromBytes(+ spec: FaceSpec,+ regular: Uint8Array,+ boldBytes: Uint8Array | null,+): Face | null {+ const regularMetrics = drawableMetrics(regular, (w) => w >= 300);+ if (!regularMetrics) return null;+ const metrics = new Map<string, FontMetrics>([[spec.family, regularMetrics]]);+ const boldMetrics = drawableMetrics(boldBytes, (w) => w >= 600);+ if (boldMetrics) metrics.set(spec.bold, boldMetrics);+ return {+ ...spec,+ bold: boldMetrics ? spec.bold : spec.family,+ cap: regularMetrics.cap,+ asc: regularMetrics.asc,+ xh: regularMetrics.xh,+ kind: regularMetrics.kind,+ metrics,+ };+}++type FontBytesLoader = (family: string) => Promise<Uint8Array | null>;++async function loadFace(+ spec: FaceSpec,+ load: FontBytesLoader,+ hasBold = true,+): Promise<Face | "unusable" | null> {+ const [regular, boldBytes] = await Promise.all([+ load(spec.family),+ hasBold ? load(spec.bold) : Promise.resolve(null),+ ]);+ if (!regular) return null;+ return faceFromBytes(spec, regular, boldBytes) ?? "unusable";+}++const cssFacesAdded = new Set<string>();++async function addCssFace(+ family: string,+ bytes: Uint8Array,+ bold: boolean,+): Promise<void> {+ const key = `${family}|${bold}`;+ if (cssFacesAdded.has(key) || typeof FontFace === "undefined") return;+ const fonts = typeof document === "undefined" ? undefined : document.fonts;+ if (!fonts) return;+ cssFacesAdded.add(key);+ try {+ const face = new FontFace(family, bytes.slice().buffer, {+ weight: bold ? "700" : "400",+ });+ await face.load();+ fonts.add(face);+ } catch {+ cssFacesAdded.delete(key);+ }+}++async function loadJarFontBytes(+ spec: BundledScanFont,+ family: string,+): Promise<Uint8Array | null> {+ const base = getFontBaseUrl();+ if (!base) return null;+ const bold = family !== spec.family;+ try {+ const res = await fetch(`${base}/${spec.files[bold ? 1 : 0]}`);+ const bytes = res.ok ? new Uint8Array(await res.arrayBuffer()) : null;+ if (!bytes || bytes.length === 0) return null;+ registerFontBytes(family, bytes);+ void addCssFace(spec.family, bytes, bold);+ return bytes;+ } catch {+ return null;+ }+}++function bundledFontBytes(spec: BundledScanFont): FontBytesLoader {+ return async (family) =>+ (await loadServerFontBytes(family)) ?? loadJarFontBytes(spec, family);+}++function isFace(face: Face | "unusable" | null): face is Face {+ return face !== null && face !== "unusable";+}++function forgetFacesOfResetServer(): void {+ if (serverFontsSeen === serverFontsGeneration()) return;+ serverFontsSeen = serverFontsGeneration();+ bundledJob = null;+ scriptJobs.clear();+ serverFamiliesTaken.clear();+ if (scriptFaces.length === 0) return;+ scriptFaces = [];+ notify();+}++export function loadBundledScanFaces(): Promise<void> {+ forgetFacesOfResetServer();+ if (bundledJob) return bundledJob;+ let job: Promise<void> | null = null;+ const started = serverFontsGeneration();+ job = (async () => {+ const faces = await Promise.all(+ BUNDLED_SCAN_FONTS.map((spec) =>+ loadFace(+ {+ label: spec.label,+ family: spec.family,+ bold: spec.bold,+ source: "bundled",+ },+ bundledFontBytes(spec),+ ),+ ),+ );+ if (bundledJob !== job || started !== serverFontsGeneration()) return;+ bundled = faces.filter(isFace);+ if (faces.includes(null)) bundledJob = null;+ notify();+ })();+ bundledJob = job;+ return job;+}++function serverCandidates(script: ScriptFonts, fonts: LocalFont[]): string[] {+ const families = [...new Set(fonts.map((f) => f.family))];+ const named = script.device.flatMap((name) =>+ families.filter((family) => normaliseName(family) === normaliseName(name)),+ );+ const matched = families.filter((family) => script.server.test(family));+ return [...new Set([...named, ...matched])];+}++async function loadServerScript(script: ScriptFonts): Promise<boolean> {+ const started = serverFontsGeneration();+ const fonts = await loadServerFonts();+ if (!fonts || started !== serverFontsGeneration()) return false;+ for (const family of serverCandidates(script, fonts)) {+ if (hasFaceFor(family)) {+ if (!script.clones) break;+ continue;+ }+ const key = normaliseName(family);+ if (serverFamiliesTaken.has(key)) continue;+ serverFamiliesTaken.add(key);+ const clone = script.clones?.[family];+ const face = await loadFace(+ {+ label: clone?.label ?? family,+ family,+ bold: `${family} Bold`,+ source: "bundled",+ twin: clone?.twin,+ },+ loadServerFontBytes,+ fonts.some((f) => f.family === family && faceStyleFlags(f).bold),+ );+ if (started !== serverFontsGeneration()) return false;+ if (face === null) {+ serverFamiliesTaken.delete(key);+ return false;+ }+ if (face === "unusable") continue;+ scriptFaces = [...scriptFaces, face];+ notify();+ if (!script.clones) break;+ }+ return true;+}++export function loadScriptScanFaces(scripts: readonly Script[]): Promise<void> {+ forgetFacesOfResetServer();+ const wanted = SCRIPTS.filter((s) => scripts.includes(s.script));+ const jobs = wanted.map((script) => {+ neededScripts.add(script.script);+ const server = wanted.find((other) => other.script === script.servedBy);+ if (!server) return scriptJob(script);+ return scriptJob(server).then(() =>+ scriptFaces.some((face) => script.server.test(face.family))+ ? undefined+ : scriptJob(script),+ );+ });+ return Promise.all(jobs).then(() => undefined);+}++function scriptJob(script: ScriptFonts): Promise<void> {+ let job = scriptJobs.get(script.script);+ if (!job) {+ job = loadServerScript(script)+ .catch(() => false)+ .then((settled) => {+ if (!settled && scriptJobs.get(script.script) === job)+ scriptJobs.delete(script.script);+ });+ scriptJobs.set(script.script, job);+ }+ return job;+}++export function _setBundledScanFacesForTests(faces: Face[]): void {+ bundled = faces;+ bundledJob = Promise.resolve();+ notify();+}++export function _resetScanFacesForTests(): void {+ bundled = [];+ scriptFaces = [];+ neededScripts.clear();+ scriptJobs.clear();+ serverFamiliesTaken.clear();+ serverFontsSeen = serverFontsGeneration();+ device = [];+ deviceRead = false;+ deviceFamiliesRead.clear();+ bundledJob = null;+ deviceJob = null;+ cssFacesAdded.clear();+ notify();+}++// Null when reading the installed file failed, which a later read may not.+async function deviceFace(family: string): Promise<Face | "unusable" | null> {+ const fonts = loadedLocalFonts();+ if (!fonts) return null;+ const regularFace = pickLocalFontFace(fonts, family);+ if (!regularFace || regularFace.family.toLowerCase() !== family.toLowerCase())+ return "unusable";+ const bold = `${family} Bold`;+ const boldFace = pickLocalFontFace(fonts, bold);+ const face = await loadFace(+ { label: family, family, bold, source: "device" },+ loadLocalFontBytes,+ !!boldFace && faceStyleFlags(boldFace).bold,+ );+ return face;+}++function sameOutlines(a: Face, b: Face): boolean {+ const key = a.metrics?.get(a.family)?.outlines;+ return !!key && key === b.metrics?.get(b.family)?.outlines;+}++async function readDeviceFaces(+ families: string[],+ known: Face[],+): Promise<Face[]> {+ const faces = [...known];+ for (const family of families) {+ if (serverFamiliesTaken.has(normaliseName(family)) || hasFaceFor(family)) {+ deviceFamiliesRead.add(family);+ continue;+ }+ const face = await deviceFace(family);+ if (face === null) continue;+ deviceFamiliesRead.add(family);+ if (isFace(face) && !faces.some((other) => sameOutlines(other, face)))+ faces.push(face);+ }+ return faces;+}++function unreadDeviceFamilies(): string[] {+ const families = [+ ...DEVICE_TEXT_FAMILIES,+ ...SCRIPTS.filter((s) => neededScripts.has(s.script)).flatMap(+ (s) => s.device,+ ),+ ];+ return [...new Set(families)].filter((f) => !deviceFamiliesRead.has(f));+}++/** Reads the installed fonts for Latin text and every script requested so far; a later call reads only the families a newly requested script adds. */+export function loadDeviceScanFaces(): Promise<number> {+ if (deviceJob && unreadDeviceFamilies().length === 0) return deviceJob;+ const previous = deviceJob;+ let job: Promise<number> | null = null;+ job = (async () => {+ await previous?.catch(() => undefined);+ const fonts = await retryLocalFonts();+ if (!fonts) {+ if (deviceJob === job) deviceJob = null;+ return device.length;+ }+ device = await readDeviceFaces(unreadDeviceFamilies(), device);+ deviceRead = true;+ notify();+ return device.length;+ })();+ deviceJob = job;+ return job;+}++/** Reads device fonts for scan matching only when that cannot prompt (granted earlier, or no permission needed); otherwise resolves at once. */+export async function loadDeviceScanFacesIfAllowed(): Promise<void> {+ if ((await localFontPermission()) === "granted") await loadDeviceScanFaces();+}diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/scanSampling.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/scanSampling.tsindex 0aa01fa5c3..c27c4a5b00 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/util/scanSampling.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/scanSampling.ts@@ -4,6 +4,7 @@ import type {TableSnapshot,} from "@editor/tools/pdfTextEditor/types";import type { DisplayTransform } from "@editor/tools/pdfTextEditor/model/DisplayTransform";+import { luma } from "@editor/tools/pdfTextEditor/model/Color";/** What a scan actually looks like inside one cell. */export interface CellColors {@@ -81,7 +82,7 @@ function dominant(counts: Map<number, Bucket>): RGBA | null {return best ? meanOf(best) : null;}-const luma = (c: RGBA): number => 0.299 * c.r + 0.587 * c.g + 0.114 * c.b;+const colourLuma = (c: RGBA): number => luma(c.r, c.g, c.b);const distance = (a: RGBA, b: RGBA): number =>Math.abs(a.r - b.r) + Math.abs(a.g - b.g) + Math.abs(a.b - b.b);@@ -172,8 +173,8 @@ export function sampleTableColors(for (const entry of inside.values()) {// The rule colour has to be genuinely present, not one stray dark pixel.const c = meanOf(entry);- if (entry.n > 8 && luma(c) < darkest) {- darkest = luma(c);+ if (entry.n > 8 && colourLuma(c) < darkest) {+ darkest = colourLuma(c);rule = c;}}@@ -255,7 +256,7 @@ function colorsOf(counts: Map<number, Bucket>): CellColors | null {if (!bg) return null;let total = 0;for (const entry of counts.values()) total += entry.n;- const light = luma(bg) > 128;+ const light = colourLuma(bg) > 128;let ink: RGBA | null = null;let far = 0;for (const entry of counts.values()) {@@ -264,7 +265,9 @@ function colorsOf(counts: Map<number, Bucket>): CellColors | null {// Ink on a pale cell is DARKER, ink on a dark cell is lighter. Without// that direction the paper showing through a shaded cell scores as its// ink, and the entry is painted in a colour close to its background.- const contrast = light ? luma(bg) - luma(c) : luma(c) - luma(bg);+ const contrast = light+ ? colourLuma(bg) - colourLuma(c)+ : colourLuma(c) - colourLuma(bg);if (contrast < INK_MIN_CONTRAST) continue;const d = distance(c, bg);if (d > far) {@@ -279,7 +282,7 @@ function colorsOf(counts: Map<number, Bucket>): CellColors | null {/** Fallback ink when a cell holds no text to sample: whatever reads on it. */function contrastTo(bg: RGBA): RGBA {- return luma(bg) > 128+ return colourLuma(bg) > 128? { r: 0, g: 0, b: 0, a: 255 }: { r: 255, g: 255, b: 255, a: 255 };}diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/selectedFontNote.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/selectedFontNote.tsindex bbfba61b27..07f424108a 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/util/selectedFontNote.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/selectedFontNote.ts@@ -18,6 +18,10 @@ import {isDeviceFontId,nearestStandardFont,} from "@editor/tools/pdfTextEditor/util/fontFamily";+import {+ fontCompletionFor,+ type FontCompletionSource,+} from "@editor/tools/pdfTextEditor/util/documentFontCompletion";const MAX_LISTED_GLYPHS = 6;const PDF_FONT_FALLBACK = "Helvetica";@@ -26,10 +30,13 @@ export type SelectedFontNote =| { kind: "scanned" }| { kind: "embeddedUnknown" }| { kind: "gap"; name: string; glyphs: string; fallback: string }- | { kind: "deviceUnknown"; name: string; fallback: string };+ | { kind: "deviceUnknown"; name: string; fallback: string }+ | { kind: "completed"; name: string; source: FontCompletionSource };interface SelectedRuns {fontIds: Set<string>;+ /** Those of `fontIds` the document embeds only in part. */+ subsetFontIds: Set<string>;text: string;scanned: number;}@@ -40,16 +47,18 @@ function collectSelectedRuns(): SelectedRuns {const picked = new Set(runIds);const fontIds = new Set<string>();+ const subsetFontIds = new Set<string>();let text = "";let scanned = 0;for (const page of pages)for (const run of page.runs)if (picked.has(run.id)) {fontIds.add(run.fontId);+ if (run.fontSubset) subsetFontIds.add(run.fontId);text += run.text;if (run.renderMode === RENDER_MODE_INVISIBLE) scanned++;}- return { fontIds, text, scanned };+ return { fontIds, subsetFontIds, text, scanned };}function standardFallbackName(family: string): string {@@ -57,7 +66,7 @@ function standardFallbackName(family: string): string {}function missingFromCoverage(- coverage: Map<number, number>,+ coverage: ReadonlySet<number>,text: string,): string[] {const missing = new Set<string>();@@ -81,6 +90,16 @@ function deviceFontNote(family: string, text: string): SelectedFontNote | null {};}+function completedNote(fontIds: Iterable<string>): SelectedFontNote | null {+ const found = [...fontIds].map(fontCompletionFor);+ const first = found[0];+ if (!first || found.some((c) => c?.family !== first.family)) return null;+ const source = found.every((c) => c?.source === "original")+ ? "original"+ : "closest";+ return { kind: "completed", name: first.family, source };+}+// analyzePageFonts merges same-named fonts, device faces included, so read each selected font's own coverage.function selectedCoverage(fontIds: Set<string>,@@ -99,14 +118,20 @@ function selectedCoverage(function documentFontNote(pages: PageSnapshot[],fontIds: Set<string>,+ allSubset: boolean,): SelectedFontNote | null {const fonts = analyzePageFonts(pages).filter((f) =>Array.from(fontIds).some((id) => id.endsWith(f.name)),);- if (fonts.length !== 1) return null;- const font = fonts[0];- const coverage = selectedCoverage(fontIds, font.status);- const gaps = coverage.missing;+ const font = fonts.length === 1 ? fonts[0] : null;+ const coverage = font ? selectedCoverage(fontIds, font.status) : null;+ const gaps = coverage?.missing ?? [];+ const complete = !!font && (font.status === "standard" || !!coverage?.known);+ // A subset says so itself, whatever the page-wide coverage scan concludes.+ const mayLack = allSubset || (!!font && (gaps.length > 0 || !complete));+ const completed = mayLack ? completedNote(fontIds) : null;+ if (completed) return completed;+ if (!font) return null;if (gaps.length > 0) {return {kind: "gap",@@ -115,8 +140,7 @@ function documentFontNote(fallback: PDF_FONT_FALLBACK,};}- if (font.status === "standard" || coverage.known) return null;- return { kind: "embeddedUnknown" };+ return complete ? null : { kind: "embeddedUnknown" };}export function selectedFontNote(@@ -124,7 +148,10 @@ export function selectedFontNote(runIds: string[],): SelectedFontNote | null {if (runIds.length === 0) return null;- const { fontIds, text, scanned } = collectSelectedRuns(pages, runIds);+ const { fontIds, subsetFontIds, text, scanned } = collectSelectedRuns(+ pages,+ runIds,+ );if (fontIds.size === 0) return null;if (scanned === runIds.length) return { kind: "scanned" };const ids = [...fontIds];@@ -133,5 +160,5 @@ export function selectedFontNote(return families.length === 1 ? deviceFontNote(families[0], text) : null;}if (ids.some(isDeviceFontId)) return null;- return documentFontNote(pages, fontIds);+ return documentFontNote(pages, fontIds, subsetFontIds.size === fontIds.size);}diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/serverFonts.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/serverFonts.tsindex 1054d9cbdb..80abe6e5ed 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/util/serverFonts.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/serverFonts.ts@@ -185,6 +185,11 @@ export function forgetServerFontList(): void {notifyBytesChanged();}+/** Changes on every `forgetServerFontList()`, so anything built from server fonts can tell it is stale. */+export function serverFontsGeneration(): number {+ return generation;+}+export function loadedServerFonts(): LocalFont[] | null {return resolved;}diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/sfnt.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/sfnt.tsnew file mode 100644index 0000000000..413887152e--- /dev/null+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/sfnt.ts@@ -0,0 +1,92 @@+export const SFNT_HEADER_SIZE = 12;+export const TABLE_RECORD_SIZE = 16;+const HEAD_CHECKSUM_ADJUSTMENT = 8;+const CHECKSUM_MAGIC = 0xb1b0afba;++export interface SfntTable {+ offset: number;+ length: number;+}++/** The table records of an sfnt font by tag; null when the directory runs past the data. */+export function readTableDirectory(+ dv: DataView,+): Map<string, SfntTable> | null {+ if (dv.byteLength < SFNT_HEADER_SIZE) return null;+ const count = dv.getUint16(4);+ const tables = new Map<string, SfntTable>();+ for (let i = 0; i < count; i++) {+ const rec = SFNT_HEADER_SIZE + i * TABLE_RECORD_SIZE;+ if (rec + TABLE_RECORD_SIZE > dv.byteLength) return null;+ const tag = String.fromCharCode(+ dv.getUint8(rec),+ dv.getUint8(rec + 1),+ dv.getUint8(rec + 2),+ dv.getUint8(rec + 3),+ );+ if (!tables.has(tag))+ tables.set(tag, {+ offset: dv.getUint32(rec + 8),+ length: dv.getUint32(rec + 12),+ });+ }+ return tables;+}++export function pad4(n: number): number {+ return (n + 3) & ~3;+}++export function tableChecksum(bytes: Uint8Array): number {+ const dv = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);+ let sum = 0;+ const whole = bytes.length & ~3;+ for (let i = 0; i < whole; i += 4) sum = (sum + dv.getUint32(i)) >>> 0;+ let tail = 0;+ for (let i = whole; i < bytes.length; i++)+ tail |= bytes[i] << (24 - (i - whole) * 8);+ return (sum + (tail >>> 0)) >>> 0;+}++/** Lay `tables` out behind a fresh directory and set head's checkSumAdjustment. */+export function assembleSfnt(+ sfntVersion: number,+ tables: Map<string, Uint8Array>,+): Uint8Array {+ const tags = [...tables.keys()].sort();+ const count = tags.length;+ const entrySelector = Math.floor(Math.log2(count));+ const searchRange = 2 ** entrySelector * TABLE_RECORD_SIZE;+ const directory = SFNT_HEADER_SIZE + count * TABLE_RECORD_SIZE;+ let size = directory;+ for (const tag of tags) size += pad4(tables.get(tag)!.length);+ const out = new Uint8Array(size);+ const dv = new DataView(out.buffer);+ dv.setUint32(0, sfntVersion);+ dv.setUint16(4, count);+ dv.setUint16(6, searchRange);+ dv.setUint16(8, entrySelector);+ dv.setUint16(10, count * TABLE_RECORD_SIZE - searchRange);+ let at = directory;+ let headAt = -1;+ tags.forEach((tag, i) => {+ const data = tables.get(tag)!;+ const rec = SFNT_HEADER_SIZE + i * TABLE_RECORD_SIZE;+ for (let k = 0; k < 4; k++) out[rec + k] = tag.charCodeAt(k);+ out.set(data, at);+ if (tag === "head") {+ headAt = at;+ dv.setUint32(at + HEAD_CHECKSUM_ADJUSTMENT, 0);+ }+ dv.setUint32(rec + 4, tableChecksum(out.subarray(at, at + data.length)));+ dv.setUint32(rec + 8, at);+ dv.setUint32(rec + 12, data.length);+ at += pad4(data.length);+ });+ if (headAt >= 0)+ dv.setUint32(+ headAt + HEAD_CHECKSUM_ADJUSTMENT,+ (CHECKSUM_MAGIC - tableChecksum(out)) >>> 0,+ );+ return out;+}diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/tableAdoption.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/tableAdoption.tsindex db386a6acb..9a18ef4863 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/util/tableAdoption.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/tableAdoption.ts@@ -7,11 +7,12 @@ import {type RowFill,TableModel,} from "@editor/tools/pdfTextEditor/model/TableModel";-import type {- PageRect,- RGBA,- TableCellStyle,- TableSnapshot,+import {+ RENDER_MODE_INVISIBLE,+ type PageRect,+ type RGBA,+ type TableCellStyle,+ type TableSnapshot,} from "@editor/tools/pdfTextEditor/types";import {headerDiffers,@@ -20,8 +21,6 @@ import {} from "@editor/tools/pdfTextEditor/util/tableStyle";const FALLBACK_FONT_SIZE = 11;-/** PDF text render mode 3 = invisible, which is what an OCR layer writes. */-const RENDER_INVISIBLE = 3;const LINE_WIDTH = 0.75;/** Id the editable twin of a recognized table takes. */@@ -119,7 +118,7 @@ function looksScanned(const run = page.findRun(id);if (!run?.pdfiumObjPtr) continue;seen++;- if (run.renderMode === RENDER_INVISIBLE) {+ if (run.renderMode === RENDER_MODE_INVISIBLE) {invisible++;}}diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/tableDetection.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/tableDetection.tsindex 92ae99cf48..86e906f91d 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/util/tableDetection.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/tableDetection.ts@@ -4,6 +4,7 @@ import type {TableSnapshot,TextRunSnapshot,} from "@editor/tools/pdfTextEditor/types";+import { median } from "@editor/tools/pdfTextEditor/util/median";// Recognizes tabular layouts from a page's text runs. PDF has no native table// object, so a "table" here is a derived grid: runs that line up into shared@@ -55,15 +56,6 @@ interface Row {bottom: number;}-function median(values: number[]): number {- if (values.length === 0) return 0;- const sorted = [...values].sort((a, b) => a - b);- const mid = Math.floor(sorted.length / 2);- return sorted.length % 2 === 0- ? (sorted[mid - 1] + sorted[mid]) / 2- : sorted[mid];-}-// One candidate box per line of text. A table cell is a single line, but the// editor's paragraph grouping merges a whole table COLUMN into one multi-line// run, so a run must be expanded into its member lines or the cells neverdiff --git a/frontend/src/editor/desktop/hooks/useConnectedServer.ts b/frontend/src/editor/desktop/hooks/useConnectedServer.tsindex 9b285dbcb7..f62fe229cb 100644--- a/frontend/src/editor/desktop/hooks/useConnectedServer.ts+++ b/frontend/src/editor/desktop/hooks/useConnectedServer.ts@@ -1,9 +1,7 @@import { useEffect, useState } from "react";import { authService } from "@editor/services/authService";-import {- connectionModeService,- type ConnectionMode,-} from "@editor/services/connectionModeService";+import type { ConnectionMode } from "@editor/services/connectionModeService";+import { useConnectionMode } from "@editor/hooks/useConnectionMode";function isServerMode(mode: ConnectionMode | null): boolean {return mode === "saas" || mode === "selfhosted";@@ -13,9 +11,7 @@ function isServerMode(mode: ConnectionMode | null): boolean {* gates surfaces that fetch on mount, and the bundled backend 404s every one of those calls. */export function useConnectedServer(): boolean {const [isAuthenticated, setIsAuthenticated] = useState(false);- const [isServer, setIsServer] = useState(() =>- isServerMode(connectionModeService.getCachedMode()),- );+ const isServer = isServerMode(useConnectionMode());useEffect(() =>@@ -33,22 +29,5 @@ export function useConnectedServer(): boolean {[],);- useEffect(() => {- let current = true;- void connectionModeService.getCurrentMode().then((mode) => {- if (current) setIsServer(isServerMode(mode));- });- const unsubscribe = connectionModeService.subscribeToModeChanges(- (config) => {- current = false;- setIsServer(isServerMode(config.mode));- },- );- return () => {- current = false;- unsubscribe();- };- }, []);-return isAuthenticated && isServer;}diff --git a/frontend/src/editor/desktop/hooks/useConnectionMode.ts b/frontend/src/editor/desktop/hooks/useConnectionMode.tsnew file mode 100644index 0000000000..a8ee8a196b--- /dev/null+++ b/frontend/src/editor/desktop/hooks/useConnectionMode.ts@@ -0,0 +1,30 @@+import { useEffect, useState } from "react";+import {+ connectionModeService,+ type ConnectionMode,+} from "@editor/services/connectionModeService";++/** The live connection mode; null until the saved mode is known. */+export function useConnectionMode(): ConnectionMode | null {+ const [mode, setMode] = useState(() => connectionModeService.getCachedMode());++ useEffect(() => {+ let current = true;+ void connectionModeService.getCurrentMode().then((saved) => {+ if (current) setMode(saved);+ });+ const unsubscribe = connectionModeService.subscribeToModeChanges(+ (config) => {+ // A change can land before the saved mode resolves; that read is stale.+ current = false;+ setMode(config.mode);+ },+ );+ return () => {+ current = false;+ unsubscribe();+ };+ }, []);++ return mode;+}diff --git a/frontend/src/editor/desktop/hooks/useSaaSMode.ts b/frontend/src/editor/desktop/hooks/useSaaSMode.tsindex d5fd216599..52f130f41e 100644--- a/frontend/src/editor/desktop/hooks/useSaaSMode.ts+++ b/frontend/src/editor/desktop/hooks/useSaaSMode.ts@@ -1,23 +1,9 @@-import { useState, useEffect } from "react";-import { connectionModeService } from "@editor/services/connectionModeService";+import { useConnectionMode } from "@editor/hooks/useConnectionMode";/*** Returns whether the app is currently in SaaS connection mode.* Cloud requests stay disabled until the saved connection mode is known.*/export function useSaaSMode(): boolean {- const [isSaaSMode, setIsSaaSMode] = useState(- () => connectionModeService.getCachedMode() === "saas",- );-- useEffect(() => {- void connectionModeService- .getCurrentMode()- .then((mode) => setIsSaaSMode(mode === "saas"));- return connectionModeService.subscribeToModeChanges((cfg) =>- setIsSaaSMode(cfg.mode === "saas"),- );- }, []);-- return isSaaSMode;+ return useConnectionMode() === "saas";}diff --git a/frontend/src/editor/desktop/services/operationRouter.ts b/frontend/src/editor/desktop/services/operationRouter.tsindex 20cf1aa947..cf4618656b 100644--- a/frontend/src/editor/desktop/services/operationRouter.ts+++ b/frontend/src/editor/desktop/services/operationRouter.ts@@ -5,7 +5,10 @@ import {documentPrivacyError,} from "@editor/services/documentPrivacyService";import { authService } from "@editor/services/authService";-import { connectionModeService } from "@editor/services/connectionModeService";+import {+ connectionModeService,+ type ConnectionMode,+} from "@editor/services/connectionModeService";import { tauriBackendService } from "@editor/services/tauriBackendService";import { endpointAvailabilityService } from "@editor/services/endpointAvailabilityService";import { selfHostedServerMonitor } from "@editor/services/selfHostedServerMonitor";@@ -17,6 +20,11 @@ import {export type ExecutionTarget = "local" | "remote";+/** Where a standalone tool runs in `mode`, before any per-endpoint capability fallback. */+export function executionTargetFor(mode: ConnectionMode): ExecutionTarget {+ return mode === "saas" || mode === "local" ? "local" : "remote";+}+export class OperationRouter {private static instance: OperationRouter;@@ -60,13 +68,7 @@ export class OperationRouter {/** Standalone tools route by connection mode. Automation endpoints never reach here —* getBaseUrl resolves those via getConnectedServerBaseUrl before this is consulted. */async getExecutionTarget(): Promise<ExecutionTarget> {- const mode = await connectionModeService.getCurrentMode();-- if (mode === "saas" || mode === "local") {- return "local";- }-- return "remote";+ return executionTargetFor(await connectionModeService.getCurrentMode());}/**diff --git a/frontend/src/editor/desktop/tools/pdfTextEditor/hooks/useServerFontsGroupLabel.ts b/frontend/src/editor/desktop/tools/pdfTextEditor/hooks/useServerFontsGroupLabel.tsnew file mode 100644index 0000000000..b601b6ef23--- /dev/null+++ b/frontend/src/editor/desktop/tools/pdfTextEditor/hooks/useServerFontsGroupLabel.ts@@ -0,0 +1,12 @@+import { useTranslation } from "react-i18next";+import { useConnectionMode } from "@editor/hooks/useConnectionMode";+import { executionTargetFor } from "@editor/services/operationRouter";++/** Desktop shadow: fonts from the bundled backend ship with the app, so only a remote backend is named a server. */+export function useServerFontsGroupLabel(): string {+ const { t } = useTranslation();+ const mode = useConnectionMode();+ return mode && executionTargetFor(mode) === "remote"+ ? t("pdfTextEditor.fontPicker.serverGroup", "Server fonts")+ : t("pdfTextEditor.fontPicker.includedGroup", "Included fonts");+}diff --git a/frontend/src/editor/desktop/tools/pdfTextEditor/util/localFontSource.test.ts b/frontend/src/editor/desktop/tools/pdfTextEditor/util/localFontSource.test.tsnew file mode 100644index 0000000000..0fd4083274--- /dev/null+++ b/frontend/src/editor/desktop/tools/pdfTextEditor/util/localFontSource.test.ts@@ -0,0 +1,109 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++const invoke = vi.fn();+vi.mock("@tauri-apps/api/core", () => ({+ invoke: (...args: unknown[]) => invoke(...args),+}));++import {+ listDeviceFaces,+ localFontPermission,+ readDeviceFace,+} from "@editor/tools/pdfTextEditor/util/localFontSource";+import {+ faceStyleFlags,+ familyOptions,+ pickLocalFontFace,+} from "@editor/tools/pdfTextEditor/util/localFonts";++const ARIAL = {+ id: 7,+ family: "Arial",+ fullName: "Arial Bold",+ style: "Bold",+ postscriptName: "Arial-BoldMT",+ weight: 700,+ bold: true,+ italic: false,+};++function germanFace(style: string, weight: number, italic: boolean) {+ return {+ id: weight + (italic ? 1 : 0),+ family: "Arial",+ fullName: `Arial ${style}`,+ style,+ postscriptName: "Arial",+ weight,+ bold: weight >= 600,+ italic,+ };+}++describe("desktop local font source", () => {+ beforeEach(() => invoke.mockReset());++ it("never needs a permission prompt", async () => {+ await expect(localFontPermission()).resolves.toBe("granted");+ });++ it("lists the installed faces from the native side", async () => {+ invoke.mockResolvedValue([ARIAL]);+ const faces = await listDeviceFaces();+ expect(invoke).toHaveBeenCalledWith("list_system_fonts");+ expect(faces).toEqual([+ {+ family: "Arial",+ fullName: "Arial Bold",+ style: "Bold",+ postscriptName: "Arial-BoldMT",+ axes: { weight: 700, bold: true, italic: false },+ },+ ]);+ });++ it("reads bold and italic from the native axes, not the localized style name", async () => {+ invoke.mockResolvedValue([+ germanFace("Standard", 400, false),+ germanFace("Fett", 700, false),+ germanFace("Kursiv", 400, true),+ germanFace("Fett Kursiv", 700, true),+ ]);+ const faces = await listDeviceFaces();+ expect(faces.map(faceStyleFlags)).toEqual([+ { bold: false, italic: false },+ { bold: true, italic: false },+ { bold: false, italic: true },+ { bold: true, italic: true },+ ]);+ expect(pickLocalFontFace(faces, "Arial")?.style).toBe("Standard");+ expect(pickLocalFontFace(faces, "Arial Bold")?.style).toBe("Fett");+ expect(familyOptions(faces, []).map((o) => o.value)).toEqual([+ "Arial",+ "Arial Bold",+ ]);+ });++ it("reads a face's file by the id it was listed with", async () => {+ invoke.mockResolvedValueOnce([ARIAL]);+ const [face] = await listDeviceFaces();+ invoke.mockResolvedValueOnce(new Uint8Array([0, 1, 0, 0]).buffer);+ const bytes = await readDeviceFace(face);+ expect(invoke).toHaveBeenLastCalledWith("read_system_font", { id: 7 });+ expect([...bytes!]).toEqual([0, 1, 0, 0]);+ });++ it("reads nothing for a face it did not list", async () => {+ await expect(+ readDeviceFace({ ...ARIAL, fullName: "Arial" }),+ ).resolves.toBeNull();+ expect(invoke).not.toHaveBeenCalled();+ });++ it("reads nothing when the native read fails", async () => {+ invoke.mockResolvedValueOnce([ARIAL]);+ const [face] = await listDeviceFaces();+ invoke.mockRejectedValueOnce(new Error("Unknown system font"));+ await expect(readDeviceFace(face)).resolves.toBeNull();+ });+});diff --git a/frontend/src/editor/desktop/tools/pdfTextEditor/util/localFontSource.ts b/frontend/src/editor/desktop/tools/pdfTextEditor/util/localFontSource.tsnew file mode 100644index 0000000000..5323732417--- /dev/null+++ b/frontend/src/editor/desktop/tools/pdfTextEditor/util/localFontSource.ts@@ -0,0 +1,51 @@+import { invoke } from "@tauri-apps/api/core";+import type { LocalFontPermission } from "@editor-core/tools/pdfTextEditor/util/localFontSource";+import type {+ FaceAxes,+ LocalFont,+} from "@editor/tools/pdfTextEditor/util/localFonts";++export type { LocalFontPermission };++interface SystemFontFace extends Omit<LocalFont, "axes">, FaceAxes {+ id: number;+}++const idOf = new WeakMap<LocalFont, number>();++export function hasDeviceFontSource(): boolean {+ return true;+}++// list_system_fonts already drops faces that are not TrueType or whose licence forbids embedding.+export async function listDeviceFaces(): Promise<LocalFont[]> {+ const faces = await invoke<SystemFontFace[]>("list_system_fonts");+ return faces.map(({ id, weight, bold, italic, ...names }) => {+ const font: LocalFont = { ...names, axes: { weight, bold, italic } };+ idOf.set(font, id);+ return font;+ });+}++export async function readDeviceFace(+ face: LocalFont,+): Promise<Uint8Array | null> {+ const id = idOf.get(face);+ if (id === undefined) return null;+ try {+ const file = await invoke<ArrayBuffer>("read_system_font", { id });+ return file.byteLength > 0 ? new Uint8Array(file) : null;+ } catch {+ return null;+ }+}++export async function localFontPermission(): Promise<LocalFontPermission> {+ return "granted";+}++export function watchLocalFontPermission(+ _listener: (permission: LocalFontPermission) => void,+): () => void {+ return () => {};+}