Skip to content

#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere

Add server-provided fonts to the PDF text editor (#8796)

Anthony Stirlingb0e87a91c909
diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/EditorFontController.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/EditorFontController.java
new file mode 100644
index 0000000000..d4db547c13
--- /dev/null
+++ b/app/core/src/main/java/stirling/software/SPDF/controller/api/EditorFontController.java
@@ -0,0 +1,59 @@
+package stirling.software.SPDF.controller.api;
+
+import java.util.Optional;
+import java.util.concurrent.TimeUnit;
+
+import org.springframework.core.io.Resource;
+import org.springframework.http.CacheControl;
+import org.springframework.http.MediaType;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.PathVariable;
+
+import io.swagger.v3.oas.annotations.Operation;
+
+import lombok.RequiredArgsConstructor;
+
+import stirling.software.SPDF.service.EditorFontRegistry;
+import stirling.software.SPDF.service.EditorFontRegistry.EditorFontManifest;
+import stirling.software.SPDF.service.EditorFontRegistry.FontFile;
+import stirling.software.SPDF.service.EditorFontRegistry.Snapshot;
+import stirling.software.common.annotations.api.UiDataApi;
+
+@UiDataApi
+@RequiredArgsConstructor
+public class EditorFontController {
+
+ private static final CacheControl MANIFEST_CACHE = CacheControl.noCache().cachePrivate();
+ private static final CacheControl FONT_CACHE =
+ CacheControl.maxAge(365, TimeUnit.DAYS).cachePrivate().immutable();
+
+ private final EditorFontRegistry registry;
+
+ @GetMapping("/editor-fonts")
+ @Operation(summary = "List the server-provided fonts the PDF text editor can embed")
+ public ResponseEntity<EditorFontManifest> manifest() {
+ Snapshot snapshot = registry.snapshot();
+ return ResponseEntity.ok()
+ .cacheControl(MANIFEST_CACHE)
+ .eTag(snapshot.etag())
+ .body(snapshot.manifest());
+ }
+
+ @GetMapping("/editor-fonts/{id}")
+ @Operation(summary = "Download one server-provided editor font face by its content hash")
+ public ResponseEntity<Resource> font(@PathVariable String id) {
+ Optional<FontFile> file = registry.resolve(id);
+ if (file.isEmpty()) {
+ return ResponseEntity.notFound().build();
+ }
+ FontFile font = file.get();
+ return ResponseEntity.ok()
+ .cacheControl(FONT_CACHE)
+ .eTag(id)
+ .header("X-Content-Type-Options", "nosniff")
+ .contentType(MediaType.parseMediaType("font/" + font.format()))
+ .contentLength(font.size())
+ .body(font.resource());
+ }
+}
diff --git a/app/core/src/main/java/stirling/software/SPDF/service/EditorFontReader.java b/app/core/src/main/java/stirling/software/SPDF/service/EditorFontReader.java
new file mode 100644
index 0000000000..09ed7dfc40
--- /dev/null
+++ b/app/core/src/main/java/stirling/software/SPDF/service/EditorFontReader.java
@@ -0,0 +1,164 @@
+package stirling.software.SPDF.service;
+
+import java.io.IOException;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.util.HexFormat;
+import java.util.List;
+import java.util.Locale;
+
+import org.apache.fontbox.ttf.HeaderTable;
+import org.apache.fontbox.ttf.NameRecord;
+import org.apache.fontbox.ttf.NamingTable;
+import org.apache.fontbox.ttf.OS2WindowsMetricsTable;
+import org.apache.fontbox.ttf.OTFParser;
+import org.apache.fontbox.ttf.OpenTypeFont;
+import org.apache.fontbox.ttf.TrueTypeFont;
+import org.apache.pdfbox.io.RandomAccessRead;
+import org.apache.pdfbox.io.RandomAccessReadBuffer;
+
+import lombok.extern.slf4j.Slf4j;
+
+import stirling.software.SPDF.service.EditorFontRegistry.EditorFontFace;
+
+@Slf4j
+final class EditorFontReader {
+
+ private static final int FS_TYPE_USAGE_MASK = 0x000F;
+ private static final int FS_TYPE_RESTRICTED = 0x0002;
+ private static final int FS_TYPE_BITMAP_ONLY = 0x0200;
+ private static final int FS_SELECTION_ITALIC = 0x0001;
+ private static final int FS_SELECTION_BOLD = 0x0020;
+ private static final int FS_SELECTION_OBLIQUE = 0x0200;
+ private static final int MAC_STYLE_BOLD = 0x0001;
+ private static final int MAC_STYLE_ITALIC = 0x0002;
+ private static final int NAME_TYPOGRAPHIC_FAMILY = 16;
+ private static final int NAME_TYPOGRAPHIC_SUBFAMILY = 17;
+ private static final int WEIGHT_REGULAR = 400;
+ private static final int WEIGHT_SEMIBOLD = 600;
+ private static final int WEIGHT_BOLD = 700;
+
+ private static final List<String> UNSUPPORTED_EXTENSIONS =
+ List.of(".ttc", ".otc", ".woff", ".woff2");
+
+ record ReadFace(String family, EditorFontFace face) {}
+
+ private EditorFontReader() {}
+
+ static String formatOf(String filename) {
+ String name = filename.toLowerCase(Locale.ROOT);
+ if (name.endsWith(".ttf")) return "ttf";
+ if (name.endsWith(".otf")) return "otf";
+ return null;
+ }
+
+ static boolean isUnsupported(String filename) {
+ String name = filename.toLowerCase(Locale.ROOT);
+ return UNSUPPORTED_EXTENSIONS.stream().anyMatch(name::endsWith);
+ }
+
+ static ReadFace read(byte[] bytes, String format, Object source) {
+ try (RandomAccessRead in = new RandomAccessReadBuffer(bytes);
+ TrueTypeFont font = new OTFParser().parse(in)) {
+ String unusable = whyUnusable(font);
+ if (unusable != null) {
+ log.info("Skipping editor font {}: {}", source, unusable);
+ return null;
+ }
+ NamingTable naming = font.getNaming();
+ String family =
+ firstNonBlank(
+ name(naming, NAME_TYPOGRAPHIC_FAMILY),
+ naming == null ? null : naming.getFontFamily());
+ if (family == null) {
+ log.info("Skipping editor font {}: no family name", source);
+ return null;
+ }
+ OS2WindowsMetricsTable os2 = font.getOS2Windows();
+ HeaderTable header = font.getHeader();
+ int macStyle = header == null ? 0 : header.getMacStyle();
+ int fsSelection = os2 == null ? 0 : os2.getFsSelection();
+ int weightClass = os2 == null ? 0 : os2.getWeightClass();
+ boolean bold;
+ int weight;
+ if (weightClass > 0) {
+ bold = weightClass >= WEIGHT_SEMIBOLD;
+ weight = weightClass;
+ } else {
+ bold = (macStyle & MAC_STYLE_BOLD) != 0 || (fsSelection & FS_SELECTION_BOLD) != 0;
+ weight = bold ? WEIGHT_BOLD : WEIGHT_REGULAR;
+ }
+ boolean italic =
+ (fsSelection & (FS_SELECTION_ITALIC | FS_SELECTION_OBLIQUE)) != 0
+ || (macStyle & MAC_STYLE_ITALIC) != 0;
+ EditorFontFace face =
+ new EditorFontFace(
+ sha256(bytes),
+ firstNonBlank(
+ name(naming, NAME_TYPOGRAPHIC_SUBFAMILY),
+ naming.getFontSubFamily(),
+ "Regular"),
+ bold,
+ italic,
+ weight,
+ firstNonBlank(naming.getPostScriptName(), ""),
+ format,
+ bytes.length);
+ return new ReadFace(family, face);
+ } catch (IOException | RuntimeException e) {
+ log.warn("Skipping editor font {}: {}", source, e.getMessage());
+ return null;
+ }
+ }
+
+ private static String whyUnusable(TrueTypeFont font) throws IOException {
+ if (font instanceof OpenTypeFont otf && otf.isPostScript()) {
+ return "CFF outlines cannot be embedded as TrueType";
+ }
+ if (font.getTableMap().containsKey("fvar")) {
+ return "variable fonts embed only their default instance";
+ }
+ OS2WindowsMetricsTable os2 = font.getOS2Windows();
+ int fsType = os2 == null ? 0 : os2.getFsType() & 0xFFFF;
+ if ((fsType & FS_TYPE_USAGE_MASK) == FS_TYPE_RESTRICTED
+ || (fsType & FS_TYPE_BITMAP_ONLY) != 0) {
+ return "its licence forbids embedding (fsType " + fsType + ")";
+ }
+ return null;
+ }
+
+ private static String name(NamingTable naming, int nameId) {
+ if (naming == null) return null;
+ String fallback = null;
+ for (NameRecord record : naming.getNameRecords()) {
+ if (record.getNameId() != nameId) continue;
+ String value = record.getString();
+ if (value == null || value.isBlank()) continue;
+ if (record.getPlatformId() == NameRecord.PLATFORM_WINDOWS
+ && record.getLanguageId() == NameRecord.LANGUAGE_WINDOWS_EN_US) {
+ return value.trim();
+ }
+ if (fallback == null) fallback = value.trim();
+ }
+ return fallback;
+ }
+
+ private static String firstNonBlank(String... values) {
+ for (String value : values) {
+ if (value != null && !value.isBlank()) return value.trim();
+ }
+ return null;
+ }
+
+ static String sha256(byte[] bytes) {
+ return HexFormat.of().formatHex(newDigest().digest(bytes));
+ }
+
+ static MessageDigest newDigest() {
+ try {
+ return MessageDigest.getInstance("SHA-256");
+ } catch (NoSuchAlgorithmException e) {
+ throw new IllegalStateException(e);
+ }
+ }
+}
diff --git a/app/core/src/main/java/stirling/software/SPDF/service/EditorFontRegistry.java b/app/core/src/main/java/stirling/software/SPDF/service/EditorFontRegistry.java
new file mode 100644
index 0000000000..ce8c1825e9
--- /dev/null
+++ b/app/core/src/main/java/stirling/software/SPDF/service/EditorFontRegistry.java
@@ -0,0 +1,434 @@
+package stirling.software.SPDF.service;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.lang.ref.SoftReference;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.FileVisitOption;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.nio.file.attribute.FileTime;
+import java.security.MessageDigest;
+import java.time.Clock;
+import java.time.Duration;
+import java.time.Instant;
+import java.util.ArrayList;
+import java.util.Comparator;
+import java.util.EnumSet;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.HexFormat;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.TreeMap;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.regex.Pattern;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.core.io.ByteArrayResource;
+import org.springframework.core.io.Resource;
+import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
+import org.springframework.stereotype.Service;
+
+import lombok.extern.slf4j.Slf4j;
+
+import stirling.software.SPDF.service.EditorFontReader.ReadFace;
+import stirling.software.common.configuration.InstallationPathConfig;
+
+@Slf4j
+@Service
+public class EditorFontRegistry {
+
+ static final String BUNDLED_FONTS = "classpath:static/fonts/*";
+ static final long MAX_FONT_BYTES = 64L * 1024 * 1024;
+ static final Duration RESCAN_INTERVAL = Duration.ofSeconds(30);
+ private static final int MAX_FONT_FOLDER_DEPTH = 4;
+ private static final Pattern FONT_ID = Pattern.compile("[0-9a-f]{64}");
+
+ public record EditorFontFace(
+ String id,
+ String style,
+ boolean bold,
+ boolean italic,
+ int weight,
+ String postscriptName,
+ String format,
+ long size) {}
+
+ public record EditorFontFamily(String family, List<EditorFontFace> faces) {}
+
+ public record EditorFontManifest(List<EditorFontFamily> families) {}
+
+ public record Snapshot(EditorFontManifest manifest, String etag) {}
+
+ public record FontFile(Resource resource, String format, long size) {}
+
+ private record IndexedFace(String family, EditorFontFace face, Path path) {}
+
+ private record BundledFace(String family, EditorFontFace face, Resource resource) {}
+
+ private record ScanEntry(long size, long modified, IndexedFace face) {}
+
+ private record FileStamp(Path path, long size, FileTime modified, Object fileKey) {}
+
+ /**
+ * Bytes that hashed to a face's id, with the file's stamp from just before they were read. Its
+ * monitor is held across a read, so simultaneous requests for the face wait for one read.
+ */
+ private static final class VerifiedFace {
+ private FileStamp stamp;
+ private SoftReference<byte[]> bytes;
+
+ byte[] bytesAt(FileStamp current) {
+ return current.equals(stamp) ? bytes.get() : null;
+ }
+
+ void keep(FileStamp current, byte[] verified) {
+ stamp = current;
+ bytes = new SoftReference<>(verified);
+ }
+
+ void clear() {
+ stamp = null;
+ bytes = null;
+ }
+ }
+
+ private final Path root;
+ private final String bundledPattern;
+ private final Clock clock;
+ private final Map<Path, ScanEntry> scanned = new HashMap<>();
+ private final Map<String, VerifiedFace> verifiedById = new ConcurrentHashMap<>();
+ private List<BundledFace> bundled;
+ private volatile Map<String, FontFile> bundledById = Map.of();
+ private volatile Map<String, IndexedFace> customById = Map.of();
+ private volatile Snapshot snapshot = emptySnapshot();
+ private volatile Instant lastScan = Instant.MIN;
+
+ @Autowired
+ public EditorFontRegistry() {
+ this(
+ Path.of(InstallationPathConfig.getStaticPath(), "fonts"),
+ BUNDLED_FONTS,
+ Clock.systemUTC());
+ }
+
+ EditorFontRegistry(Path root, String bundledPattern, Clock clock) {
+ this.root = root;
+ this.bundledPattern = bundledPattern;
+ this.clock = clock;
+ }
+
+ public Snapshot snapshot() {
+ refreshIfDue();
+ return snapshot;
+ }
+
+ public Optional<FontFile> resolve(String id) {
+ if (id == null || !FONT_ID.matcher(id).matches()) {
+ return Optional.empty();
+ }
+ refreshIfDue();
+ IndexedFace custom = customById.get(id);
+ if (custom == null) {
+ return Optional.ofNullable(bundledById.get(id));
+ }
+ FontFile verified = readVerified(custom);
+ if (verified == null) {
+ forgetAndRescan(custom.path());
+ IndexedFace rescanned = customById.get(id);
+ verified = rescanned == null ? bundledById.get(id) : readVerified(rescanned);
+ }
+ return Optional.ofNullable(verified);
+ }
+
+ /**
+ * Requests for one face share one read and one array, because a face can be 64 MiB and a copy
+ * per request exhausts the heap. The array is held softly: once no response is using it, the
+ * collector may reclaim it rather than run out of memory.
+ */
+ private FontFile readVerified(IndexedFace face) {
+ VerifiedFace verified =
+ verifiedById.computeIfAbsent(face.face().id(), id -> new VerifiedFace());
+ byte[] bytes;
+ synchronized (verified) {
+ bytes = verifiedBytes(face, verified);
+ if (bytes == null) {
+ verified.clear();
+ }
+ }
+ return bytes == null
+ ? null
+ : new FontFile(new ByteArrayResource(bytes), face.face().format(), bytes.length);
+ }
+
+ private byte[] verifiedBytes(IndexedFace face, VerifiedFace verified) {
+ try {
+ // Stamped before the read, so a file that changes during it no longer matches.
+ FileStamp stamp = stampOf(face.path());
+ byte[] bytes = verified.bytesAt(stamp);
+ if (bytes == null) {
+ bytes = readBounded(face.path());
+ if (bytes == null || !face.face().id().equals(EditorFontReader.sha256(bytes))) {
+ return null;
+ }
+ verified.keep(stamp, bytes);
+ }
+ return bytes;
+ } catch (IOException e) {
+ return null;
+ }
+ }
+
+ private static FileStamp stampOf(Path path) throws IOException {
+ BasicFileAttributes attrs = Files.readAttributes(path, BasicFileAttributes.class);
+ return new FileStamp(path, attrs.size(), attrs.lastModifiedTime(), attrs.fileKey());
+ }
+
+ byte[] readBounded(Path path) throws IOException {
+ try (InputStream in = Files.newInputStream(path)) {
+ return readBounded(in);
+ }
+ }
+
+ private static byte[] readBounded(InputStream in) throws IOException {
+ byte[] bytes = in.readNBytes((int) MAX_FONT_BYTES + 1);
+ return bytes.length > MAX_FONT_BYTES ? null : bytes;
+ }
+
+ private void refreshIfDue() {
+ if (isScanDue()) {
+ rescan(false);
+ }
+ }
+
+ private synchronized void forgetAndRescan(Path path) {
+ scanned.remove(path);
+ rescan(true);
+ }
+
+ private boolean isScanDue() {
+ return !lastScan.plus(RESCAN_INTERVAL).isAfter(clock.instant());
+ }
+
+ private synchronized void rescan(boolean force) {
+ if (!force && !isScanDue()) {
+ return;
+ }
+ if (bundled == null) {
+ bundled = loadBundled();
+ }
+ Map<Path, ScanEntry> next = new HashMap<>();
+ for (Path path : listFontFiles()) {
+ BasicFileAttributes attrs;
+ try {
+ attrs = Files.readAttributes(path, BasicFileAttributes.class);
+ } catch (IOException e) {
+ continue;
+ }
+ long size = attrs.size();
+ long modified = attrs.lastModifiedTime().toMillis();
+ ScanEntry previous = scanned.get(path);
+ if (previous != null && previous.size() == size && previous.modified() == modified) {
+ next.put(path, previous);
+ continue;
+ }
+ try {
+ next.put(path, new ScanEntry(size, modified, index(path, size, modified)));
+ } catch (IOException e) {
+ log.warn("Skipping editor font {} until the next scan: {}", path, e.getMessage());
+ }
+ }
+ scanned.clear();
+ scanned.putAll(next);
+ publish();
+ lastScan = clock.instant();
+ }
+
+ private List<Path> listFontFiles() {
+ if (!Files.isDirectory(root)) {
+ return List.of();
+ }
+ Path realRoot;
+ try {
+ realRoot = root.toRealPath();
+ } catch (IOException e) {
+ return List.of();
+ }
+ List<Path> found = new ArrayList<>();
+ try {
+ Files.walkFileTree(
+ realRoot,
+ EnumSet.noneOf(FileVisitOption.class),
+ MAX_FONT_FOLDER_DEPTH,
+ new SimpleFileVisitor<>() {
+ @Override
+ public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
+ Path path = root.resolve(realRoot.relativize(file));
+ if (Files.isRegularFile(path)
+ && isFontFile(path)
+ && resolvesInside(path, realRoot)) {
+ found.add(path);
+ }
+ return FileVisitResult.CONTINUE;
+ }
+
+ @Override
+ public FileVisitResult visitFileFailed(Path file, IOException e) {
+ log.warn(
+ "Skipping editor fonts under {}: {}",
+ root.resolve(realRoot.relativize(file)),
+ e.toString());
+ return FileVisitResult.CONTINUE;
+ }
+ });
+ } catch (IOException e) {
+ log.warn("Could not list editor fonts in {}: {}", root, e.getMessage());
+ return List.of();
+ }
+ found.sort(null);
+ return found;
+ }
+
+ private static boolean isFontFile(Path path) {
+ String name = path.getFileName().toString();
+ return EditorFontReader.formatOf(name) != null || EditorFontReader.isUnsupported(name);
+ }
+
+ private static boolean resolvesInside(Path path, Path realRoot) {
+ try {
+ return path.toRealPath().startsWith(realRoot);
+ } catch (IOException e) {
+ return false;
+ }
+ }
+
+ private static String formatOf(Path path) {
+ return EditorFontReader.formatOf(path.getFileName().toString());
+ }
+
+ private IndexedFace index(Path path, long size, long modified) throws IOException {
+ if (formatOf(path) == null) {
+ log.info("Skipping editor font {}: only .ttf and .otf files are supported", path);
+ return null;
+ }
+ if (size > MAX_FONT_BYTES) {
+ log.warn(
+ "Skipping editor font {}: {} bytes exceeds the {} byte limit",
+ path,
+ size,
+ MAX_FONT_BYTES);
+ return null;
+ }
+ byte[] bytes = readBounded(path);
+ BasicFileAttributes after = Files.readAttributes(path, BasicFileAttributes.class);
+ if (bytes == null
+ || bytes.length != size
+ || after.size() != size
+ || after.lastModifiedTime().toMillis() != modified) {
+ throw new IOException("it changed while being read");
+ }
+ ReadFace read = EditorFontReader.read(bytes, formatOf(path), path);
+ return read == null ? null : new IndexedFace(read.family(), read.face(), path);
+ }
+
+ private List<BundledFace> loadBundled() {
+ if (bundledPattern == null) {
+ return List.of();
+ }
+ Resource[] resources;
+ try {
+ resources = new PathMatchingResourcePatternResolver().getResources(bundledPattern);
+ } catch (IOException e) {
+ log.warn("Could not list bundled editor fonts: {}", e.getMessage());
+ return List.of();
+ }
+ List<BundledFace> faces = new ArrayList<>();
+ for (Resource resource : resources) {
+ String filename = resource.getFilename();
+ String format = filename == null ? null : EditorFontReader.formatOf(filename);
+ if (format == null) {
+ continue;
+ }
+ try (InputStream in = resource.getInputStream()) {
+ byte[] bytes = readBounded(in);
+ ReadFace read =
+ bytes == null ? null : EditorFontReader.read(bytes, format, filename);
+ if (read != null) {
+ faces.add(new BundledFace(read.family(), read.face(), resource));
+ }
+ } catch (IOException e) {
+ log.warn("Skipping bundled editor font {}: {}", filename, e.getMessage());
+ }
+ }
+ return List.copyOf(faces);
+ }
+
+ private void publish() {
+ Map<String, FontFile> bundledFiles = new LinkedHashMap<>();
+ Map<String, IndexedFace> customs = new LinkedHashMap<>();
+ Map<String, List<EditorFontFace>> grouped = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
+ for (ScanEntry entry : new TreeMap<>(scanned).values()) {
+ IndexedFace face = entry.face();
+ if (face == null || customs.containsKey(face.face().id())) {
+ continue;
+ }
+ customs.put(face.face().id(), face);
+ grouped.computeIfAbsent(face.family(), k -> new ArrayList<>()).add(face.face());
+ }
+ Set<String> customFamilies = new HashSet<>();
+ for (String family : grouped.keySet()) {
+ customFamilies.add(family.toLowerCase(Locale.ROOT));
+ }
+ for (BundledFace face : bundled) {
+ String id = face.face().id();
+ if (customs.containsKey(id) || bundledFiles.containsKey(id)) {
+ continue;
+ }
+ bundledFiles.put(
+ id, new FontFile(face.resource(), face.face().format(), face.face().size()));
+ if (customFamilies.contains(face.family().toLowerCase(Locale.ROOT))) {
+ continue;
+ }
+ grouped.computeIfAbsent(face.family(), k -> new ArrayList<>()).add(face.face());
+ }
+ List<EditorFontFamily> families = new ArrayList<>();
+ for (Map.Entry<String, List<EditorFontFace>> group : grouped.entrySet()) {
+ List<EditorFontFace> faces = new ArrayList<>(group.getValue());
+ faces.sort(
+ Comparator.comparingInt(EditorFontFace::weight)
+ .thenComparing(EditorFontFace::italic)
+ .thenComparing(EditorFontFace::style));
+ families.add(new EditorFontFamily(group.getKey(), List.copyOf(faces)));
+ }
+ customById = Map.copyOf(customs);
+ verifiedById.keySet().retainAll(customs.keySet());
+ bundledById = Map.copyOf(bundledFiles);
+ snapshot = new Snapshot(new EditorFontManifest(List.copyOf(families)), etagOf(families));
+ }
+
+ private static String etagOf(List<EditorFontFamily> families) {
+ MessageDigest digest = EditorFontReader.newDigest();
+ for (EditorFontFamily family : families) {
+ digest.update(family.family().getBytes(StandardCharsets.UTF_8));
+ for (EditorFontFace face : family.faces()) {
+ digest.update((byte) 0);
+ digest.update(face.id().getBytes(StandardCharsets.UTF_8));
+ digest.update(face.style().getBytes(StandardCharsets.UTF_8));
+ }
+ digest.update((byte) 1);
+ }
+ return HexFormat.of().formatHex(digest.digest()).substring(0, 32);
+ }
+
+ private static Snapshot emptySnapshot() {
+ return new Snapshot(new EditorFontManifest(List.of()), etagOf(List.of()));
+ }
+}
diff --git a/app/core/src/main/resources/application.properties b/app/core/src/main/resources/application.properties
index 87d0779d84..87afddd976 100644
--- a/app/core/src/main/resources/application.properties
+++ b/app/core/src/main/resources/application.properties
@@ -32,7 +32,7 @@ spring.security.filter.dispatcher-types=REQUEST,ERROR
# Response compression; JettyCompressionConfig stops it also inflating request bodies
server.compression.enabled=true
server.compression.min-response-size=1024
-server.compression.mime-types=application/json,application/xml,text/html,text/plain,text/css,application/javascript,image/svg+xml,application/x-font-ttf,font/opentype,application/vnd.ms-fontobject,font/woff,font/woff2,application/font-woff,application/font-woff2,application/wasm
+server.compression.mime-types=application/json,application/xml,text/html,text/plain,text/css,application/javascript,image/svg+xml,font/ttf,font/otf,application/x-font-ttf,font/opentype,application/vnd.ms-fontobject,font/woff,font/woff2,application/font-woff,application/font-woff2,application/wasm
spring.web.error.path=/error
spring.web.error.whitelabel.enabled=false
diff --git a/app/core/src/main/resources/static/fonts/NotoSansKR-Regular.ttf b/app/core/src/main/resources/static/fonts/NotoSansKR-Regular.ttf
index 90a4a2aad6..0e13866cea 100644
Binary files a/app/core/src/main/resources/static/fonts/NotoSansKR-Regular.ttf and b/app/core/src/main/resources/static/fonts/NotoSansKR-Regular.ttf differ
diff --git a/app/core/src/main/resources/static/fonts/NotoSansSC-Regular.ttf b/app/core/src/main/resources/static/fonts/NotoSansSC-Regular.ttf
index 23164652bd..8eaf08e187 100644
Binary files a/app/core/src/main/resources/static/fonts/NotoSansSC-Regular.ttf and b/app/core/src/main/resources/static/fonts/NotoSansSC-Regular.ttf differ
diff --git a/app/core/src/test/java/stirling/software/SPDF/controller/api/EditorFontControllerTest.java b/app/core/src/test/java/stirling/software/SPDF/controller/api/EditorFontControllerTest.java
new file mode 100644
index 0000000000..80d818ab5e
--- /dev/null
+++ b/app/core/src/test/java/stirling/software/SPDF/controller/api/EditorFontControllerTest.java
@@ -0,0 +1,113 @@
+package stirling.software.SPDF.controller.api;
+
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
+
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Optional;
+
+import org.hamcrest.Matchers;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+import org.springframework.core.io.FileSystemResource;
+import org.springframework.test.web.servlet.MockMvc;
+import org.springframework.test.web.servlet.setup.MockMvcBuilders;
+
+import stirling.software.SPDF.config.EndpointConfiguration;
+import stirling.software.SPDF.config.EndpointInterceptor;
+import stirling.software.SPDF.service.EditorFontRegistry;
+import stirling.software.SPDF.service.EditorFontRegistry.EditorFontFace;
+import stirling.software.SPDF.service.EditorFontRegistry.EditorFontFamily;
+import stirling.software.SPDF.service.EditorFontRegistry.EditorFontManifest;
+import stirling.software.SPDF.service.EditorFontRegistry.FontFile;
+import stirling.software.SPDF.service.EditorFontRegistry.Snapshot;
+
+class EditorFontControllerTest {
+
+ private static final String MANIFEST = "/api/v1/ui-data/editor-fonts";
+ private static final String ID = "a".repeat(64);
+ private static final String ETAG = "0123456789abcdef0123456789abcdef";
+
+ @TempDir Path tempDir;
+
+ private EditorFontRegistry registry;
+ private MockMvc mvc;
+
+ @BeforeEach
+ void setUp() {
+ registry = mock(EditorFontRegistry.class);
+ EditorFontFace face =
+ new EditorFontFace(ID, "Regular", false, false, 400, "AcmeSans", "ttf", 4);
+ when(registry.snapshot())
+ .thenReturn(
+ new Snapshot(
+ new EditorFontManifest(
+ List.of(new EditorFontFamily("Acme Sans", List.of(face)))),
+ ETAG));
+ EndpointConfiguration endpoints = mock(EndpointConfiguration.class);
+ when(endpoints.isEndpointEnabledForUri(anyString())).thenReturn(true);
+ mvc =
+ MockMvcBuilders.standaloneSetup(new EditorFontController(registry))
+ .addInterceptors(new EndpointInterceptor(endpoints))
+ .build();
+ }
+
+ @Test
+ void manifestIsRevalidatedByEtag() throws Exception {
+ mvc.perform(get(MANIFEST).servletPath(MANIFEST))
+ .andExpect(status().isOk())
+ .andExpect(header().string("ETag", "\"" + ETAG + "\""))
+ .andExpect(header().string("Cache-Control", Matchers.containsString("no-cache")))
+ .andExpect(jsonPath("$.families[0].family").value("Acme Sans"))
+ .andExpect(jsonPath("$.families[0].faces[0].id").value(ID))
+ .andExpect(jsonPath("$.families[0].faces[0].path").doesNotExist());
+
+ mvc.perform(get(MANIFEST).servletPath(MANIFEST).header("If-None-Match", "\"" + ETAG + "\""))
+ .andExpect(status().isNotModified())
+ .andExpect(header().string("Cache-Control", "no-cache, private"));
+ }
+
+ @Test
+ void fontBytesAreImmutableAndContentAddressed() throws Exception {
+ Path font = tempDir.resolve("Acme.ttf");
+ Files.write(font, new byte[] {0, 1, 0, 0});
+ when(registry.resolve(ID))
+ .thenReturn(Optional.of(new FontFile(new FileSystemResource(font), "ttf", 4)));
+
+ mvc.perform(get(MANIFEST + "/" + ID).servletPath(MANIFEST + "/" + ID))
+ .andExpect(status().isOk())
+ .andExpect(header().string("Content-Type", "font/ttf"))
+ .andExpect(header().string("Cache-Control", Matchers.containsString("immutable")))
+ .andExpect(header().string("Cache-Control", Matchers.containsString("private")))
+ .andExpect(header().string("ETag", "\"" + ID + "\""))
+ .andExpect(header().string("X-Content-Type-Options", "nosniff"))
+ .andExpect(content().bytes(new byte[] {0, 1, 0, 0}));
+
+ mvc.perform(
+ get(MANIFEST + "/" + ID)
+ .servletPath(MANIFEST + "/" + ID)
+ .header("If-None-Match", "\"" + ID + "\""))
+ .andExpect(status().isNotModified())
+ .andExpect(header().string("Cache-Control", Matchers.containsString("immutable")))
+ .andExpect(
+ header().string(
+ "Cache-Control",
+ Matchers.not(Matchers.containsString("no-store"))));
+ }
+
+ @Test
+ void unknownFontIsNotFound() throws Exception {
+ when(registry.resolve("missing")).thenReturn(Optional.empty());
+
+ mvc.perform(get("/api/v1/ui-data/editor-fonts/missing")).andExpect(status().isNotFound());
+ }
+}
diff --git a/app/core/src/test/java/stirling/software/SPDF/service/EditorFontRegistryTest.java b/app/core/src/test/java/stirling/software/SPDF/service/EditorFontRegistryTest.java
new file mode 100644
index 0000000000..833663e4ae
--- /dev/null
+++ b/app/core/src/test/java/stirling/software/SPDF/service/EditorFontRegistryTest.java
@@ -0,0 +1,705 @@
+package stirling.software.SPDF.service;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.jupiter.api.Assertions.fail;
+import static org.junit.jupiter.api.Assumptions.abort;
+import static org.junit.jupiter.api.Assumptions.assumeFalse;
+import static org.junit.jupiter.api.Assumptions.assumeTrue;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.URL;
+import java.nio.ByteBuffer;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.FileSystemException;
+import java.nio.file.FileSystems;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.attribute.FileTime;
+import java.nio.file.attribute.PosixFilePermission;
+import java.security.MessageDigest;
+import java.time.Clock;
+import java.time.Instant;
+import java.time.ZoneId;
+import java.util.ArrayList;
+import java.util.Enumeration;
+import java.util.HexFormat;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicReference;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+import org.springframework.core.io.ByteArrayResource;
+
+import stirling.software.SPDF.service.EditorFontRegistry.EditorFontFace;
+import stirling.software.SPDF.service.EditorFontRegistry.EditorFontFamily;
+import stirling.software.SPDF.service.EditorFontRegistry.FontFile;
+import stirling.software.SPDF.service.EditorFontRegistry.Snapshot;
+
+class EditorFontRegistryTest {
+
+ @TempDir Path root;
+
+ private MutableClock clock;
+ private EditorFontRegistry registry;
+
+ @BeforeEach
+ void setUp() {
+ clock = new MutableClock(Instant.parse("2026-11-05T10:00:00Z"));
+ registry = new EditorFontRegistry(root, null, clock);
+ }
+
+ @Test
+ void groupsFacesByFamilyWithStyleFlags() throws IOException {
+ copyFixture("LiberationSans-Regular.ttf", root.resolve("LiberationSans-Regular.ttf"));
+ copyFixture(
+ "LiberationSans-BoldItalic.ttf",
+ root.resolve("nested/LiberationSans-BoldItalic.ttf"));
+
+ List<EditorFontFamily> families = registry.snapshot().manifest().families();
+
+ assertThat(families)
+ .extracting(EditorFontFamily::family)
+ .containsExactly("Liberation Sans");
+ List<EditorFontFace> faces = families.get(0).faces();
+ assertThat(faces).hasSize(2);
+ EditorFontFace regular = faces.get(0);
+ assertThat(regular.bold()).isFalse();
+ assertThat(regular.italic()).isFalse();
+ assertThat(regular.style()).isEqualTo("Regular");
+ assertThat(regular.format()).isEqualTo("ttf");
+ assertThat(regular.postscriptName()).isEqualTo("LiberationSans");
+ assertThat(regular.id()).matches("[0-9a-f]{64}");
+ EditorFontFace boldItalic = faces.get(1);
+ assertThat(boldItalic.bold()).isTrue();
+ assertThat(boldItalic.italic()).isTrue();
+ }
+
+ @Test
+ void emptyWhenFolderIsMissing() {
+ EditorFontRegistry missing =
+ new EditorFontRegistry(root.resolve("does-not-exist"), null, clock);
+
+ assertThat(missing.snapshot().manifest().families()).isEmpty();
+ }
+
+ @Test
+ void skipsFilesThatAreNotLoadableTrueTypeFonts() throws IOException {
+ Files.writeString(root.resolve("broken.ttf"), "not a font");
+ Files.writeString(root.resolve("readme.txt"), "hello");
+ copyFixture("DejaVuSans.ttf", root.resolve("signature.woff2"));
+ copyFixture("DejaVuSans.ttf", root.resolve("DejaVuSans.ttf"));
+
+ List<EditorFontFamily> families = registry.snapshot().manifest().families();
+
+ assertThat(families).extracting(EditorFontFamily::family).containsExactly("DejaVu Sans");
+ }
+
+ @Test
+ void skipsFontsWhoseLicenceForbidsEmbedding() throws IOException {
+ Path restricted = root.resolve("Restricted.ttf");
+ copyFixture("DejaVuSans.ttf", restricted);
+ setFsType(restricted, 0x0002);
+ Path bitmapOnly = root.resolve("BitmapOnly.ttf");
+ copyFixture("DejaVuSans-Bold.ttf", bitmapOnly);
+ setFsType(bitmapOnly, 0x0200);
+
+ assertThat(registry.snapshot().manifest().families()).isEmpty();
+ }
+
+ @Test
+ void listsFontsThatAlsoGrantALessRestrictiveEmbedding() throws IOException {
+ Path previewAndPrint = root.resolve("PreviewAndPrint.ttf");
+ copyFixture("DejaVuSans.ttf", previewAndPrint);
+ setFsType(previewAndPrint, 0x0006);
+ Path editable = root.resolve("Editable.ttf");
+ copyFixture("DejaVuSans-Bold.ttf", editable);
+ setFsType(editable, 0x000E);
+
+ List<EditorFontFamily> families = registry.snapshot().manifest().families();
+
+ assertThat(families).extracting(EditorFontFamily::family).containsExactly("DejaVu Sans");
+ assertThat(families.get(0).faces()).hasSize(2);
+ }
+
+ @Test
+ void groupsFacesUnderTheirTypographicFamilyName() throws IOException {
+ Path light = root.resolve("DejaVuSans-Light.ttf");
+ copyFixture("DejaVuSans.ttf", light);
+ setLegacyFamilyName(light, "DejaVu Thin");
+
+ List<EditorFontFamily> families = registry.snapshot().manifest().families();
+
+ assertThat(families).extracting(EditorFontFamily::family).containsExactly("DejaVu Sans");
+ }
+
+ @Test
+ void ignoresLinksThatLeadOutOfTheFolder(@TempDir Path outside) throws IOException {
+ Path elsewhere = outside.resolve("DejaVuSans.ttf");
+ copyFixture("DejaVuSans.ttf", elsewhere);
+ symlink(root.resolve("linked.ttf"), elsewhere);
+ symlink(root.resolve("linked-folder"), outside);
+ copyFixture("LiberationSans-Regular.ttf", root.resolve("LiberationSans-Regular.ttf"));
+
+ List<EditorFontFamily> families = registry.snapshot().manifest().families();
+
+ assertThat(families)
+ .extracting(EditorFontFamily::family)
+ .containsExactly("Liberation Sans");
+ }
+
+ @Test
+ void followsAFontsFolderThatIsItselfALink(@TempDir Path outside) throws IOException {
+ copyFixture("DejaVuSans.ttf", outside.resolve("DejaVuSans.ttf"));
+ Path link = symlink(root.resolve("fonts"), outside);
+
+ EditorFontRegistry linked = new EditorFontRegistry(link, null, clock);
+
+ assertThat(linked.snapshot().manifest().families())
+ .extracting(EditorFontFamily::family)
+ .containsExactly("DejaVu Sans");
+ }
+
+ @Test
+ void anUnreadableFolderHidesOnlyItsOwnFonts() throws IOException {
+ assumeTrue(FileSystems.getDefault().supportedFileAttributeViews().contains("posix"));
+ copyFixture("DejaVuSans.ttf", root.resolve("DejaVuSans.ttf"));
+ Path locked = root.resolve("locked");
+ copyFixture("LiberationSans-Regular.ttf", locked.resolve("LiberationSans-Regular.ttf"));
+ Set<PosixFilePermission> original = Files.getPosixFilePermissions(locked);
+ Files.setPosixFilePermissions(locked, Set.of());
+ try {
+ assumeFalse(Files.isReadable(locked), "running with permission to read any folder");
+
+ List<EditorFontFamily> families = registry.snapshot().manifest().families();
+
+ assertThat(families)
+ .extracting(EditorFontFamily::family)
+ .containsExactly("DejaVu Sans");
+ assertThat(registry.resolve(families.get(0).faces().get(0).id())).isPresent();
+ } finally {
+ Files.setPosixFilePermissions(locked, original);
+ }
+ }
+
+ @Test
+ void requestsDuringTheFirstScanWaitForItsResult() throws Exception {
+ copyFixture("DejaVuSans.ttf", root.resolve("DejaVuSans.ttf"));
+ EditorFontRegistry withBundled =
+ new EditorFontRegistry(root, EditorFontRegistry.BUNDLED_FONTS, clock);
+ CountDownLatch scanning = new CountDownLatch(1);
+ CountDownLatch release = new CountDownLatch(1);
+ AtomicReference<Snapshot> first = new AtomicReference<>();
+ AtomicReference<Snapshot> during = new AtomicReference<>();
+ Thread firstRequest = new Thread(() -> first.set(withBundled.snapshot()));
+ firstRequest.setContextClassLoader(
+ new PausingClassLoader(
+ EditorFontRegistryTest.class.getClassLoader(), scanning, release));
+ Thread laterRequest = new Thread(() -> during.set(withBundled.snapshot()));
+
+ firstRequest.start();
+ assertThat(scanning.await(30, TimeUnit.SECONDS)).isTrue();
+ laterRequest.start();
+ try {
+ long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(30);
+ while (laterRequest.getState() != Thread.State.BLOCKED
+ && laterRequest.getState() != Thread.State.TERMINATED) {
+ if (System.nanoTime() > deadline) {
+ fail("later request never waited, state " + laterRequest.getState());
+ }
+ Thread.onSpinWait();
+ }
+ } finally {
+ release.countDown();
+ }
+ firstRequest.join();
+ laterRequest.join();
+
+ assertThat(during.get().manifest().families())
+ .extracting(EditorFontFamily::family)
+ .contains("DejaVu Sans", "Liberation Sans");
+ assertThat(during.get().etag()).isEqualTo(first.get().etag());
+ }
+
+ @Test
+ void identicalFilesAreListedOnce() throws IOException {
+ copyFixture("DejaVuSans.ttf", root.resolve("a/DejaVuSans.ttf"));
+ copyFixture("DejaVuSans.ttf", root.resolve("b/DejaVuSans.ttf"));
+
+ List<EditorFontFamily> families = registry.snapshot().manifest().families();
+
+ assertThat(families).hasSize(1);
+ assertThat(families.get(0).faces()).hasSize(1);
+ }
+
+ @Test
+ void listsTheFontsBundledWithTheApp() throws Exception {
+ EditorFontRegistry withBundled =
+ new EditorFontRegistry(root, EditorFontRegistry.BUNDLED_FONTS, clock);
+
+ List<EditorFontFamily> families = withBundled.snapshot().manifest().families();
+
+ assertThat(families)
+ .extracting(EditorFontFamily::family)
+ .contains(
+ "Liberation Sans",
+ "DejaVu Serif",
+ "Noto Sans",
+ "Noto Sans JP",
+ "Noto Sans KR",
+ "Noto Sans SC")
+ .doesNotContain("Tangerine", "Noto Sans TC");
+ EditorFontFace regular = family(families, "Liberation Sans").faces().get(0);
+ assertThat(family(families, "Liberation Sans").faces()).hasSize(4);
+ assertThat(regular.style()).isEqualTo("Regular");
+ assertThat(withBundled.resolve(regular.id()))
+ .hasValueSatisfying(
+ file -> {
+ try (InputStream in = file.resource().getInputStream()) {
+ byte[] bytes = in.readAllBytes();
+ assertThat(bytes).hasSize((int) regular.size());
+ assertThat(
+ HexFormat.of()
+ .formatHex(
+ MessageDigest.getInstance("SHA-256")
+ .digest(bytes)))
+ .isEqualTo(regular.id());
+ } catch (Exception e) {
+ throw new AssertionError(e);
+ }
+ });
+ }
+
+ @Test
+ void customFolderReplacesABundledFamily() throws IOException {
+ Path custom = root.resolve("DejaVuSans.ttf");
+ copyFixture("DejaVuSans.ttf", custom);
+ EditorFontRegistry withBundled =
+ new EditorFontRegistry(root, EditorFontRegistry.BUNDLED_FONTS, clock);
+
+ EditorFontFamily dejaVu =
+ family(withBundled.snapshot().manifest().families(), "DejaVu Sans");
+
+ assertThat(dejaVu.faces()).hasSize(1);
+ byte[] expected = Files.readAllBytes(custom);
+ assertThat(withBundled.resolve(dejaVu.faces().get(0).id()))
+ .hasValueSatisfying(file -> assertThat(bytesOf(file)).isEqualTo(expected));
+ }
+
+ @Test
+ void bundledFacesHiddenByACustomFamilyStillResolve() throws IOException {
+ EditorFontRegistry withBundled =
+ new EditorFontRegistry(root, EditorFontRegistry.BUNDLED_FONTS, clock);
+ String boldId =
+ family(withBundled.snapshot().manifest().families(), "DejaVu Sans").faces().stream()
+ .filter(EditorFontFace::bold)
+ .findFirst()
+ .orElseThrow()
+ .id();
+
+ copyFixture("DejaVuSans.ttf", root.resolve("DejaVuSans.ttf"));
+ clock.advance(EditorFontRegistry.RESCAN_INTERVAL.plusSeconds(1));
+
+ assertThat(family(withBundled.snapshot().manifest().families(), "DejaVu Sans").faces())
+ .extracting(EditorFontFace::id)
+ .doesNotContain(boldId);
+ assertThat(withBundled.resolve(boldId))
+ .hasValueSatisfying(
+ file ->
+ assertThat(file.resource().getFilename())
+ .isEqualTo("DejaVuSans-Bold.ttf"));
+ }
+
+ @Test
+ void resolvesOnlyKnownWellFormedIds() throws IOException {
+ Path font = root.resolve("DejaVuSans.ttf");
+ copyFixture("DejaVuSans.ttf", font);
+ String id = registry.snapshot().manifest().families().get(0).faces().get(0).id();
+
+ byte[] expected = Files.readAllBytes(font);
+ assertThat(registry.resolve(id))
+ .hasValueSatisfying(
+ file -> {
+ assertThat(bytesOf(file)).isEqualTo(expected);
+ assertThat(file.size()).isEqualTo(expected.length);
+ assertThat(file.format()).isEqualTo("ttf");
+ });
+ assertThat(registry.resolve("0".repeat(64))).isEmpty();
+ assertThat(registry.resolve("../../etc/passwd")).isEmpty();
+ assertThat(registry.resolve(id.toUpperCase())).isEmpty();
+ assertThat(registry.resolve(null)).isEmpty();
+ }
+
+ @Test
+ void picksUpNewFilesOnceTheRescanIntervalPasses() throws IOException {
+ copyFixture("DejaVuSans.ttf", root.resolve("DejaVuSans.ttf"));
+ String firstEtag = registry.snapshot().etag();
+
+ copyFixture("LiberationSerif-Regular.ttf", root.resolve("LiberationSerif-Regular.ttf"));
+ assertThat(registry.snapshot().manifest().families()).hasSize(1);
+
+ clock.advance(EditorFontRegistry.RESCAN_INTERVAL.plusSeconds(1));
+ assertThat(registry.snapshot().manifest().families())
+ .extracting(EditorFontFamily::family)
+ .containsExactly("DejaVu Sans", "Liberation Serif");
+ assertThat(registry.snapshot().etag()).isNotEqualTo(firstEtag);
+ }
+
+ @Test
+ void replacedFileNoLongerResolvesUnderItsOldId() throws IOException {
+ Path font = root.resolve("Face.ttf");
+ copyFixture("DejaVuSans.ttf", font);
+ String oldId = registry.snapshot().manifest().families().get(0).faces().get(0).id();
+
+ copyFixture("LiberationSans-Regular.ttf", font);
+ Files.setLastModifiedTime(font, FileTime.from(Instant.parse("2030-01-01T00:00:00Z")));
+
+ assertThat(registry.resolve(oldId)).isEmpty();
+ String newId = registry.snapshot().manifest().families().get(0).faces().get(0).id();
+ assertThat(newId).isNotEqualTo(oldId);
+ assertThat(registry.resolve(newId)).isPresent();
+ }
+
+ @Test
+ void doesNotServeALinkSwappedInWithTheSameSizeAndTime(@TempDir Path outside)
+ throws IOException {
+ Path font = root.resolve("DejaVuSans.ttf");
+ copyFixture("DejaVuSans.ttf", font);
+ String id = registry.snapshot().manifest().families().get(0).faces().get(0).id();
+ FileTime modified = Files.getLastModifiedTime(font);
+ Path secret = outside.resolve("secret.ttf");
+ copyFixture("DejaVuSans.ttf", secret);
+ setFsType(secret, 0x0008);
+ Files.setLastModifiedTime(secret, modified);
+ Files.delete(font);
+ symlink(font, secret);
+
+ assertThat(registry.resolve(id)).isEmpty();
+ }
+
+ @Test
+ void servesTheVerifiedBytesWhenTheFileIsSwappedAfterResolving(@TempDir Path outside)
+ throws IOException {
+ Path font = root.resolve("DejaVuSans.ttf");
+ copyFixture("DejaVuSans.ttf", font);
+ byte[] indexed = Files.readAllBytes(font);
+ String id = registry.snapshot().manifest().families().get(0).faces().get(0).id();
+ FontFile file = registry.resolve(id).orElseThrow();
+ Path secret = outside.resolve("secret.ttf");
+ copyFixture("LiberationSans-Regular.ttf", secret);
+ Files.delete(font);
+ symlink(font, secret);
+
+ assertThat(bytesOf(file)).isEqualTo(indexed);
+ }
+
+ @Test
+ void doesNotServeAFileWhoseBytesNoLongerMatchItsId() throws IOException {
+ Path font = root.resolve("DejaVuSans.ttf");
+ copyFixture("DejaVuSans.ttf", font);
+ String id = registry.snapshot().manifest().families().get(0).faces().get(0).id();
+ FileTime modified = Files.getLastModifiedTime(font);
+ setFsType(font, 0x0008);
+ Files.setLastModifiedTime(font, modified);
+
+ assertThat(registry.resolve(id)).isEmpty();
+ }
+
+ @Test
+ void listsTheReplacementOnceItsBytesFailVerification() throws IOException {
+ Path font = root.resolve("DejaVuSans.ttf");
+ copyFixture("DejaVuSans.ttf", font);
+ String oldId = registry.snapshot().manifest().families().get(0).faces().get(0).id();
+ FileTime modified = Files.getLastModifiedTime(font);
+ setFsType(font, 0x0008);
+ Files.setLastModifiedTime(font, modified);
+
+ assertThat(registry.resolve(oldId)).isEmpty();
+ String newId = registry.snapshot().manifest().families().get(0).faces().get(0).id();
+ assertThat(newId).isNotEqualTo(oldId);
+ assertThat(registry.resolve(newId)).isPresent();
+ }
+
+ @Test
+ void retriesAFontThatCouldNotBeOpened() throws IOException {
+ assumeTrue(FileSystems.getDefault().supportedFileAttributeViews().contains("posix"));
+ Path font = root.resolve("DejaVuSans.ttf");
+ copyFixture("DejaVuSans.ttf", font);
+ Set<PosixFilePermission> original = Files.getPosixFilePermissions(font);
+ Files.setPosixFilePermissions(font, Set.of());
+ try {
+ assumeFalse(Files.isReadable(font), "running with permission to read any file");
+ assertThat(registry.snapshot().manifest().families()).isEmpty();
+ } finally {
+ Files.setPosixFilePermissions(font, original);
+ }
+
+ clock.advance(EditorFontRegistry.RESCAN_INTERVAL.plusSeconds(1));
+
+ assertThat(registry.snapshot().manifest().families())
+ .extracting(EditorFontFamily::family)
+ .containsExactly("DejaVu Sans");
+ }
+
+ @Test
+ void simultaneousRequestsForOneFaceShareOneRead() throws Exception {
+ Path font = root.resolve("DejaVuSans.ttf");
+ copyFixture("DejaVuSans.ttf", font);
+ byte[] expected = Files.readAllBytes(font);
+ CountingRegistry counting = new CountingRegistry(root, clock);
+ String id = counting.snapshot().manifest().families().get(0).faces().get(0).id();
+ counting.reads.set(0);
+ CountDownLatch release = new CountDownLatch(1);
+ counting.hold = release;
+ List<AtomicReference<FontFile>> served = new ArrayList<>();
+ List<Thread> requests = new ArrayList<>();
+ for (int i = 0; i < 8; i++) {
+ AtomicReference<FontFile> result = new AtomicReference<>();
+ served.add(result);
+ requests.add(new Thread(() -> result.set(counting.resolve(id).orElse(null))));
+ }
+
+ requests.forEach(Thread::start);
+ try {
+ long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(30);
+ while (requests.stream().anyMatch(EditorFontRegistryTest::isStillRunning)) {
+ if (System.nanoTime() > deadline) {
+ fail("requests never settled into reading or waiting for the read");
+ }
+ Thread.onSpinWait();
+ }
+ } finally {
+ release.countDown();
+ }
+ for (Thread request : requests) {
+ request.join();
+ }
+
+ assertThat(counting.reads).hasValue(1);
+ byte[] shared = arrayOf(served.get(0).get());
+ assertThat(shared).isEqualTo(expected);
+ assertThat(served).allSatisfy(result -> assertThat(arrayOf(result.get())).isSameAs(shared));
+ assertThat(arrayOf(counting.resolve(id).orElseThrow())).isSameAs(shared);
+ assertThat(counting.reads).hasValue(1);
+ }
+
+ @Test
+ void aFaceRemovedFromTheFolderIsNotServedFromMemory() throws IOException {
+ Path font = root.resolve("DejaVuSans.ttf");
+ copyFixture("DejaVuSans.ttf", font);
+ byte[] original = Files.readAllBytes(font);
+ String id = registry.snapshot().manifest().families().get(0).faces().get(0).id();
+ FontFile served = registry.resolve(id).orElseThrow();
+
+ Files.delete(font);
+ clock.advance(EditorFontRegistry.RESCAN_INTERVAL.plusSeconds(1));
+
+ assertThat(registry.snapshot().manifest().families()).isEmpty();
+ assertThat(registry.resolve(id)).isEmpty();
+ assertThat(bytesOf(served)).isEqualTo(original);
+ }
+
+ @Test
+ void aFileSwappedForOtherBytesIsNotServedUnderItsOldIdFromMemory() throws IOException {
+ Path font = root.resolve("Face.ttf");
+ copyFixture("DejaVuSans.ttf", font);
+ byte[] original = Files.readAllBytes(font);
+ String oldId = registry.snapshot().manifest().families().get(0).faces().get(0).id();
+ FontFile served = registry.resolve(oldId).orElseThrow();
+
+ copyFixture("LiberationSans-Regular.ttf", font);
+ byte[] replacement = Files.readAllBytes(font);
+
+ assertThat(registry.resolve(oldId)).isEmpty();
+ String newId = registry.snapshot().manifest().families().get(0).faces().get(0).id();
+ assertThat(newId).isNotEqualTo(oldId);
+ assertThat(registry.resolve(newId))
+ .hasValueSatisfying(file -> assertThat(bytesOf(file)).isEqualTo(replacement));
+ assertThat(bytesOf(served)).isEqualTo(original);
+ }
+
+ @Test
+ void aSwapKeepingSizeAndTimeNeverServesTheNewBytesUnderTheOldId() throws IOException {
+ Path font = root.resolve("DejaVuSans.ttf");
+ copyFixture("DejaVuSans.ttf", font);
+ byte[] original = Files.readAllBytes(font);
+ String id = registry.snapshot().manifest().families().get(0).faces().get(0).id();
+ FontFile served = registry.resolve(id).orElseThrow();
+ FileTime modified = Files.getLastModifiedTime(font);
+ setFsType(font, 0x0008);
+ Files.setLastModifiedTime(font, modified);
+
+ registry.resolve(id).ifPresent(file -> assertThat(bytesOf(file)).isEqualTo(original));
+ assertThat(bytesOf(served)).isEqualTo(original);
+ }
+
+ private static boolean isStillRunning(Thread thread) {
+ Thread.State state = thread.getState();
+ return state == Thread.State.NEW || state == Thread.State.RUNNABLE;
+ }
+
+ private static byte[] arrayOf(FontFile file) {
+ assertThat(file).isNotNull();
+ return ((ByteArrayResource) file.resource()).getByteArray();
+ }
+
+ private static byte[] bytesOf(FontFile file) {
+ try (InputStream in = file.resource().getInputStream()) {
+ return in.readAllBytes();
+ } catch (IOException e) {
+ throw new AssertionError(e);
+ }
+ }
+
+ private static Path symlink(Path link, Path target) throws IOException {
+ try {
+ return Files.createSymbolicLink(link, target);
+ } catch (UnsupportedOperationException e) {
+ return abort("symbolic links are not supported here");
+ } catch (FileSystemException e) {
+ if (e.getClass() != FileSystemException.class) throw e;
+ return abort("no permission to create symbolic links: " + e.getMessage());
+ }
+ }
+
+ private static EditorFontFamily family(List<EditorFontFamily> families, String name) {
+ return families.stream().filter(f -> f.family().equals(name)).findFirst().orElseThrow();
+ }
+
+ private static void copyFixture(String name, Path target) throws IOException {
+ Files.createDirectories(target.getParent());
+ try (InputStream in =
+ EditorFontRegistryTest.class.getResourceAsStream("/static/fonts/" + name)) {
+ assertThat(in).as("fixture %s", name).isNotNull();
+ Files.write(target, in.readAllBytes());
+ }
+ }
+
+ private static void setFsType(Path font, int fsType) throws IOException {
+ byte[] bytes = Files.readAllBytes(font);
+ ByteBuffer.wrap(bytes).putShort(tableOffset(bytes, "OS/2") + 8, (short) fsType);
+ Files.write(font, bytes);
+ }
+
+ private static void setLegacyFamilyName(Path font, String family) throws IOException {
+ byte[] bytes = Files.readAllBytes(font);
+ ByteBuffer buffer = ByteBuffer.wrap(bytes);
+ int name = tableOffset(bytes, "name");
+ int count = buffer.getShort(name + 2) & 0xFFFF;
+ int strings = name + (buffer.getShort(name + 4) & 0xFFFF);
+ for (int i = 0; i < count; i++) {
+ int record = name + 6 + i * 12;
+ if (buffer.getShort(record + 6) != 1) continue;
+ boolean windows = buffer.getShort(record) == 3;
+ byte[] value =
+ family.getBytes(
+ windows ? StandardCharsets.UTF_16BE : StandardCharsets.US_ASCII);
+ int length = buffer.getShort(record + 8) & 0xFFFF;
+ assertThat(value).as("same-length family name").hasSize(length);
+ System.arraycopy(
+ value, 0, bytes, strings + (buffer.getShort(record + 10) & 0xFFFF), length);
+ }
+ Files.write(font, bytes);
+ }
+
+ private static int tableOffset(byte[] bytes, String table) {
+ ByteBuffer buffer = ByteBuffer.wrap(bytes);
+ int tables = buffer.getShort(4) & 0xFFFF;
+ for (int i = 0; i < tables; i++) {
+ int record = 12 + i * 16;
+ if (table.equals(new String(bytes, record, 4, StandardCharsets.US_ASCII))) {
+ return buffer.getInt(record + 8);
+ }
+ }
+ throw new IllegalStateException("no " + table + " table");
+ }
+
+ private static final class CountingRegistry extends EditorFontRegistry {
+ private final AtomicInteger reads = new AtomicInteger();
+ private volatile CountDownLatch hold;
+
+ CountingRegistry(Path root, Clock clock) {
+ super(root, null, clock);
+ }
+
+ @Override
+ byte[] readBounded(Path path) throws IOException {
+ reads.incrementAndGet();
+ CountDownLatch latch = hold;
+ try {
+ if (latch != null && !latch.await(60, TimeUnit.SECONDS)) {
+ throw new IOException("the read was never released");
+ }
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw new IOException(e);
+ }
+ return super.readBounded(path);
+ }
+ }
+
+ private static final class PausingClassLoader extends ClassLoader {
+ private final CountDownLatch scanning;
+ private final CountDownLatch release;
+
+ PausingClassLoader(ClassLoader parent, CountDownLatch scanning, CountDownLatch release) {
+ super(parent);
+ this.scanning = scanning;
+ this.release = release;
+ }
+
+ @Override
+ public URL getResource(String name) {
+ pauseOnFonts(name);
+ return super.getResource(name);
+ }
+
+ @Override
+ public Enumeration<URL> getResources(String name) throws IOException {
+ pauseOnFonts(name);
+ return super.getResources(name);
+ }
+
+ private void pauseOnFonts(String name) {
+ if (!name.startsWith("static/fonts")) return;
+ scanning.countDown();
+ try {
+ release.await();
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ }
+ }
+ }
+
+ private static final class MutableClock extends Clock {
+ private Instant now;
+
+ MutableClock(Instant now) {
+ this.now = now;
+ }
+
+ void advance(java.time.Duration by) {
+ now = now.plus(by);
+ }
+
+ @Override
+ public ZoneId getZone() {
+ return ZoneId.of("UTC");
+ }
+
+ @Override
+ public Clock withZone(ZoneId zone) {
+ return this;
+ }
+
+ @Override
+ public Instant instant() {
+ return now;
+ }
+ }
+}
diff --git a/frontend/public/locales/en-US/translation.toml b/frontend/public/locales/en-US/translation.toml
index 5a8e11eadd..8f90263ffd 100644
--- a/frontend/public/locales/en-US/translation.toml
+++ b/frontend/public/locales/en-US/translation.toml
@@ -7626,10 +7626,14 @@ deviceFontsNone = "No extra device fonts were found."
deviceFontsUnavailable = "Device fonts are unavailable. The built-in fonts still work."
deviceGroup = "Device fonts"
documentGroup = "Document font"
+embedFailed = "This font could not be embedded in the PDF. The text was left unchanged."
label = "Font family"
mixed = "Mixed"
+noGlyphs = "This font has no characters for the selected text. The text was left unchanged."
noMatch = "No matching font"
placeholder = "Font family"
+serverFontFailed = "That server font could not be downloaded. The text was left unchanged."
+serverGroup = "Server fonts"
useDeviceFonts = "Use device fonts"
[pdfTextEditor.fonts]
@@ -7699,7 +7703,8 @@ zoomDesc = "Zoom in / out"
[pdfTextEditor.inspector]
document = "Document"
fontEmbedded = "Embedded font · a character it lacks falls back to Helvetica."
-fontGap = "{{name}} · missing {{glyphs}} - typing those falls back to Helvetica."
+fontGap = "{{name}} · missing {{glyphs}} - typing those falls back to {{fallback}}."
+fontUnknownCoverage = "{{name}} · a character it lacks falls back to {{fallback}}."
geometry = "Position & size"
height = "Height"
heightHint = "A text box's height follows its type size and line count."
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/pageFonts.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/pageFonts.test.ts
index 46374cb61a..068045da46 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/pageFonts.test.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/pageFonts.test.ts
@@ -103,6 +103,23 @@ describe("analyzePageFonts", () => {
expect(fonts[0].pages).toEqual([1, 3]);
});
+ it("names a run drawn in a server or device face by its family", () => {
+ const fonts = analyzePageFonts([
+ mkPage(0, [mkRun("a", "device:Liberation Serif")]),
+ ]);
+ expect(fonts).toHaveLength(1);
+ expect(fonts[0].name).toBe("Liberation Serif");
+ expect(fonts[0].status).toBe("embedded");
+ });
+
+ it("counts a device face with a standard family name as embedded", () => {
+ const fonts = analyzePageFonts([
+ mkPage(0, [mkRun("a", "device:Times New Roman")]),
+ ]);
+ expect(fonts[0].status).toBe("embedded");
+ expect(fonts[0].coverage.known).toBe(false);
+ });
+
it("returns nothing when there are no runs", () => {
expect(analyzePageFonts([mkPage(0, [])])).toEqual([]);
});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/selectedFontNote.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/selectedFontNote.test.ts
new file mode 100644
index 0000000000..5dee23ca08
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/selectedFontNote.test.ts
@@ -0,0 +1,163 @@
+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() }));
+vi.mock("@editor/services/apiClient", () => ({ default: { get } }));
+
+import { selectedFontNote } from "@editor/tools/pdfTextEditor/util/selectedFontNote";
+import {
+ SERVER_FONTS_URL,
+ loadServerFontBytes,
+ forgetServerFontList,
+} from "@editor/tools/pdfTextEditor/util/serverFonts";
+import { resetDeviceFontEmbedCache } from "@editor/tools/pdfTextEditor/util/deviceFontEmbed";
+import type { PageSnapshot } from "@editor/tools/pdfTextEditor/types";
+
+const SERIF_BOLD = "1".repeat(64);
+const HEBREW_AS_TIMES = "2".repeat(64);
+
+function bundledFont(name: string): ArrayBuffer {
+ const bytes = readFileSync(
+ path.resolve(
+ __dirname,
+ "../../../../../../../app/core/src/main/resources/static/fonts",
+ name,
+ ),
+ );
+ return bytes.buffer.slice(
+ bytes.byteOffset,
+ bytes.byteOffset + bytes.byteLength,
+ );
+}
+
+const FILES: Record<string, string> = {
+ [SERIF_BOLD]: "DejaVuSerif-Bold.ttf",
+ [HEBREW_AS_TIMES]: "NotoSansHebrew-Regular.ttf",
+};
+
+const MANIFEST = {
+ families: [
+ {
+ family: "DejaVu Serif",
+ faces: [{ id: SERIF_BOLD, style: "Bold", bold: true, italic: false }],
+ },
+ {
+ family: "Times New Roman",
+ faces: [
+ { id: HEBREW_AS_TIMES, style: "Regular", bold: false, italic: false },
+ ],
+ },
+ ],
+};
+
+function run(id: string, fontId: string, text: string) {
+ return {
+ id,
+ pageIndex: 0,
+ bounds: { x: 0, y: 0, width: 10, height: 10 },
+ matrix: { a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 },
+ text,
+ fontId,
+ fontSize: 12,
+ fill: { r: 0, g: 0, b: 0, a: 255 },
+ fontSubset: false,
+ };
+}
+
+function page(runs: ReturnType<typeof run>[]): PageSnapshot[] {
+ return [
+ {
+ pageIndex: 0,
+ width: 100,
+ height: 100,
+ revision: 0,
+ dirty: false,
+ runs,
+ images: [],
+ shapes: [],
+ } as unknown as PageSnapshot,
+ ];
+}
+
+describe("selectedFontNote", () => {
+ beforeAll(async () => {
+ forgetServerFontList();
+ resetDeviceFontEmbedCache();
+ get.mockImplementation(async (url: string) => {
+ if (url === SERVER_FONTS_URL) return { data: MANIFEST };
+ return {
+ data: bundledFont(FILES[url.slice(SERVER_FONTS_URL.length + 1)]),
+ };
+ });
+ expect(await loadServerFontBytes("DejaVu Serif Bold")).not.toBeNull();
+ expect(await loadServerFontBytes("Times New Roman")).not.toBeNull();
+ });
+
+ it("says nothing when a device face covers the run's text", () => {
+ const pages = page([run("a", "device:DejaVu Serif Bold", "Hello 42")]);
+
+ expect(selectedFontNote(pages, ["a"])).toBeNull();
+ });
+
+ it("names the glyphs a device face lacks and its serif fallback", () => {
+ const pages = page([run("a", "device:DejaVu Serif Bold", "Hello 中文")]);
+
+ expect(selectedFontNote(pages, ["a"])).toEqual({
+ kind: "gap",
+ name: "DejaVu Serif Bold",
+ glyphs: "中 文",
+ fallback: "Times",
+ });
+ });
+
+ it("judges a device face with a standard name by its own coverage", () => {
+ const pages = page([run("a", "device:Times New Roman", "שלום")]);
+
+ const note = selectedFontNote(pages, ["a"]);
+
+ expect(note).toMatchObject({
+ kind: "gap",
+ name: "Times New Roman",
+ fallback: "Times",
+ });
+ expect(note?.kind === "gap" && note.glyphs.length).toBeGreaterThan(0);
+ });
+
+ it("names the fallback when a device face's coverage is unknown", () => {
+ const pages = page([run("a", "device:Acme Sans", "Hello")]);
+
+ expect(selectedFontNote(pages, ["a"])).toEqual({
+ kind: "deviceUnknown",
+ name: "Acme Sans",
+ fallback: "Helvetica",
+ });
+ });
+
+ it("keeps standard document fonts silent and unreadable embedded ones noted", () => {
+ expect(
+ selectedFontNote(page([run("a", "base14:Times-Roman", "Hi")]), ["a"]),
+ ).toBeNull();
+ expect(
+ selectedFontNote(page([run("a", "pdf:0:Acme Sans", "Hi")]), ["a"]),
+ ).toEqual({ kind: "embeddedUnknown" });
+ });
+
+ 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"),
+ run("b", "pdf:0:DejaVu Serif Bold", "Hi"),
+ ]);
+
+ expect(selectedFontNote(pages, ["b"])).toEqual({ kind: "embeddedUnknown" });
+ });
+
+ it("says nothing for a selection mixing device and document fonts", () => {
+ const pages = page([
+ run("a", "device:Acme Sans", "Hi"),
+ run("b", "pdf:0:Acme Sans", "Hi"),
+ ]);
+
+ expect(selectedFontNote(pages, ["a", "b"])).toBeNull();
+ });
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/serverFonts.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/serverFonts.test.ts
new file mode 100644
index 0000000000..2ef2e37f2d
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/serverFonts.test.ts
@@ -0,0 +1,614 @@
+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_REFRESH_MS,
+ SERVER_FONTS_URL,
+ forgetServerFontList,
+ getServerFontBytes,
+ loadServerFontBytes,
+ loadServerFonts,
+ loadedServerFonts,
+ serverFaceFor,
+ serverFontCssFamily,
+ subscribeServerFonts,
+} from "@editor/tools/pdfTextEditor/util/serverFonts";
+import {
+ getExternalFontBytes,
+ loadedExternalFonts,
+} from "@editor/tools/pdfTextEditor/util/externalFonts";
+import {
+ familyOptions,
+ listLocalFonts,
+ pickLocalFontFace,
+ resetLocalFontsCache,
+} from "@editor/tools/pdfTextEditor/util/localFonts";
+import { deviceFontIdFor } from "@editor/tools/pdfTextEditor/util/deviceFontEmbed";
+import {
+ italicCapability,
+ resetDocumentFontMatchCache,
+} from "@editor/tools/pdfTextEditor/util/fontCapability";
+
+const requestsAtImport = get.mock.calls.length;
+
+const REGULAR = "1".repeat(64);
+const ITALIC = "2".repeat(64);
+const BOLD = "3".repeat(64);
+
+const MANIFEST = {
+ families: [
+ {
+ family: "Acme Sans",
+ faces: [
+ face(REGULAR, "Regular", false, false),
+ face(ITALIC, "Italic", false, true),
+ face(BOLD, "Bold", true, false),
+ { id: "../../etc/passwd", style: "Evil" },
+ ],
+ },
+ { family: "", faces: [face("4".repeat(64), "Regular", false, false)] },
+ ],
+};
+
+function face(id: string, style: string, bold: boolean, italic: boolean) {
+ return {
+ id,
+ style,
+ bold,
+ italic,
+ weight: bold ? 700 : 400,
+ postscriptName: `AcmeSans-${style}`,
+ format: "ttf",
+ size: 4,
+ };
+}
+
+function bytesFor(id: string): ArrayBuffer {
+ return new Uint8Array([Number(id[0]), 0, 0, 1]).buffer;
+}
+
+function serveManifestAndFaces(): void {
+ get.mockImplementation(async (url: string) => {
+ if (url === SERVER_FONTS_URL) return { data: MANIFEST };
+ const id = url.slice(SERVER_FONTS_URL.length + 1);
+ return { data: bytesFor(id) };
+ });
+}
+
+function faceRequests(): string[] {
+ return get.mock.calls
+ .map(([url]) => url as string)
+ .filter((url) => url !== SERVER_FONTS_URL);
+}
+
+describe("server fonts", () => {
+ afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ delete (document as unknown as { fonts?: unknown }).fonts;
+ });
+
+ beforeEach(() => {
+ get.mockReset();
+ forgetServerFontList();
+ resetLocalFontsCache();
+ resetDocumentFontMatchCache();
+ delete (window as unknown as { queryLocalFonts?: unknown }).queryLocalFonts;
+ });
+
+ it("fetches nothing until asked", () => {
+ expect(requestsAtImport).toBe(0);
+ expect(loadedServerFonts()).toBeNull();
+ expect(get).not.toHaveBeenCalled();
+ });
+
+ it("loads the manifest once and keeps only well-formed faces", async () => {
+ serveManifestAndFaces();
+
+ const [first, second] = await Promise.all([
+ loadServerFonts(),
+ loadServerFonts(),
+ ]);
+ await loadServerFonts();
+
+ expect(get).toHaveBeenCalledTimes(1);
+ expect(first).toBe(second);
+ expect(first?.map((font) => font.style)).toEqual([
+ "Regular",
+ "Italic",
+ "Bold",
+ ]);
+ expect(serverFaceFor("acme-sans")?.id).toBe(REGULAR);
+ expect(serverFaceFor("Other")).toBeNull();
+ });
+
+ it("retries the manifest after a failed fetch", async () => {
+ get.mockRejectedValueOnce(new Error("offline"));
+ expect(await loadServerFonts()).toBeNull();
+
+ serveManifestAndFaces();
+ expect(await loadServerFonts()).toHaveLength(3);
+ });
+
+ it("keeps an empty answer instead of asking again straight away", async () => {
+ get.mockResolvedValue({ data: { families: [] } });
+
+ expect(await loadServerFonts()).toEqual([]);
+ expect(await loadServerFonts()).toEqual([]);
+ expect(loadedServerFonts()).toEqual([]);
+ expect(await loadServerFontBytes("Acme Sans")).toBeNull();
+ expect(get).toHaveBeenCalledTimes(1);
+
+ forgetServerFontList();
+ serveManifestAndFaces();
+ expect(await loadServerFonts()).toHaveLength(3);
+ });
+
+ it("forgets the list when the backend changes, ignoring the old answer", async () => {
+ let answerOldServer: (value: { data: unknown }) => void = () => {};
+ get.mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ answerOldServer = resolve;
+ }),
+ );
+ const fromOldServer = loadServerFonts();
+ const listener = vi.fn();
+ const unsubscribe = subscribeServerFonts(listener);
+
+ forgetServerFontList();
+ expect(listener).toHaveBeenCalledTimes(1);
+ get.mockResolvedValueOnce({
+ data: {
+ families: [
+ {
+ family: "Beta Serif",
+ faces: [face("5".repeat(64), "Regular", false, false)],
+ },
+ ],
+ },
+ });
+ const fromNewServer = await loadServerFonts();
+ answerOldServer({ data: MANIFEST });
+
+ expect(await fromOldServer).toBeNull();
+ expect(fromNewServer?.map((font) => font.family)).toEqual(["Beta Serif"]);
+ expect(loadedServerFonts()).toBe(fromNewServer);
+ unsubscribe();
+ });
+
+ it("drops the old backend's faces and bytes when the backend changes", async () => {
+ const added: unknown[] = [];
+ const removed: unknown[] = [];
+ vi.stubGlobal(
+ "FontFace",
+ class {
+ load() {
+ return Promise.resolve(this);
+ }
+ },
+ );
+ Object.defineProperty(document, "fonts", {
+ configurable: true,
+ value: {
+ add: (css: unknown) => added.push(css),
+ delete: (css: unknown) => removed.push(css),
+ },
+ });
+ serveManifestAndFaces();
+ expect((await loadServerFontBytes("Acme Sans"))?.[0]).toBe(1);
+ expect(serverFontCssFamily("Acme Sans")).toBe(`serverface-${REGULAR}`);
+
+ forgetServerFontList();
+
+ expect(getServerFontBytes("Acme Sans")).toBeNull();
+ expect(getExternalFontBytes("Acme Sans")).toBeNull();
+ expect(serverFontCssFamily("Acme Sans")).toBeNull();
+ expect(removed).toEqual(added);
+
+ const OTHER = "8".repeat(64);
+ get.mockImplementation(async (url: string) => {
+ if (url === SERVER_FONTS_URL) {
+ return {
+ data: {
+ families: [
+ {
+ family: "Acme Sans",
+ faces: [face(OTHER, "Regular", false, false)],
+ },
+ ],
+ },
+ };
+ }
+ return { data: bytesFor(url.slice(SERVER_FONTS_URL.length + 1)) };
+ });
+ expect((await loadServerFontBytes("Acme Sans"))?.[0]).toBe(8);
+ expect(getServerFontBytes("Acme Sans")?.[0]).toBe(8);
+ expect(serverFontCssFamily("Acme Sans")).toBe(`serverface-${OTHER}`);
+ });
+
+ it("ignores a face download that finishes after the backend changed", async () => {
+ let finishOldDownload: (value: { data: ArrayBuffer }) => void = () => {};
+ get.mockImplementation((url: string) => {
+ if (url === SERVER_FONTS_URL) return Promise.resolve({ data: MANIFEST });
+ return new Promise((resolve) => {
+ finishOldDownload = resolve;
+ });
+ });
+ const fromOldServer = loadServerFontBytes("Acme Sans");
+ await vi.waitFor(() => expect(faceRequests()).toHaveLength(1));
+
+ forgetServerFontList();
+ let finishNewDownload: (value: { data: ArrayBuffer }) => void = () => {};
+ get.mockImplementation((url: string) => {
+ if (url === SERVER_FONTS_URL) return Promise.resolve({ data: MANIFEST });
+ return new Promise((resolve) => {
+ finishNewDownload = resolve;
+ });
+ });
+ const fromNewServer = loadServerFontBytes("Acme Sans");
+ await vi.waitFor(() => expect(faceRequests()).toHaveLength(2));
+
+ finishOldDownload({ data: new Uint8Array([7, 7, 7, 7]).buffer });
+ expect(await fromOldServer).toBeNull();
+ expect(getServerFontBytes("Acme Sans")).toBeNull();
+ const askedAgain = loadServerFontBytes("Acme Sans");
+
+ finishNewDownload({ data: bytesFor(REGULAR) });
+ expect((await fromNewServer)?.[0]).toBe(1);
+ expect(getServerFontBytes("Acme Sans")?.[0]).toBe(1);
+ expect((await askedAgain)?.[0]).toBe(1);
+ expect(faceRequests()).toHaveLength(2);
+ });
+
+ it("registers a downloaded face under its own alias, not the family name", async () => {
+ const families: string[] = [];
+ vi.stubGlobal(
+ "FontFace",
+ class {
+ constructor(family: string) {
+ families.push(family);
+ }
+ load() {
+ return Promise.resolve(this);
+ }
+ },
+ );
+ Object.defineProperty(document, "fonts", {
+ configurable: true,
+ value: { add: vi.fn() },
+ });
+ serveManifestAndFaces();
+ await loadServerFonts();
+
+ expect(serverFontCssFamily("Acme Sans")).toBeNull();
+ await loadServerFontBytes("Acme Sans");
+
+ expect(families).toEqual([`serverface-${REGULAR}`]);
+ expect(serverFontCssFamily("acme-sans")).toBe(`serverface-${REGULAR}`);
+ });
+
+ it("embeds one face once whichever spelling asked for it", async () => {
+ serveManifestAndFaces();
+ await loadServerFonts();
+
+ await loadServerFontBytes("Acme Sans");
+ await loadServerFontBytes("Acme Sans Regular");
+ await loadServerFontBytes("Acme Sans Italic");
+
+ expect(deviceFontIdFor("Acme Sans Regular")).toBe(
+ deviceFontIdFor("Acme Sans"),
+ );
+ expect(deviceFontIdFor("Acme Sans Italic")).not.toBe(
+ deviceFontIdFor("Acme Sans"),
+ );
+ });
+
+ it("downloads only the face that answers the request", async () => {
+ serveManifestAndFaces();
+ await loadServerFonts();
+
+ const regular = await loadServerFontBytes("Acme Sans");
+ expect(regular?.[0]).toBe(1);
+ expect(faceRequests()).toEqual([`${SERVER_FONTS_URL}/${REGULAR}`]);
+
+ const italic = await loadServerFontBytes("Acme Sans Italic");
+ expect(italic?.[0]).toBe(2);
+ expect(faceRequests()).toEqual([
+ `${SERVER_FONTS_URL}/${REGULAR}`,
+ `${SERVER_FONTS_URL}/${ITALIC}`,
+ ]);
+
+ await loadServerFontBytes("Acme Sans");
+ expect(faceRequests()).toHaveLength(2);
+ expect(getServerFontBytes("acme sans")?.[0]).toBe(1);
+ });
+
+ it("downloads a face once when two names ask for it together", async () => {
+ serveManifestAndFaces();
+ await loadServerFonts();
+
+ await Promise.all([
+ loadServerFontBytes("Acme Sans Bold"),
+ loadServerFontBytes("AcmeSans-Bold"),
+ ]);
+
+ expect(faceRequests()).toEqual([`${SERVER_FONTS_URL}/${BOLD}`]);
+ });
+
+ it("retries a face download once, then gives up without throwing", async () => {
+ let faceCalls = 0;
+ get.mockImplementation(async (url: string) => {
+ if (url === SERVER_FONTS_URL) return { data: MANIFEST };
+ faceCalls++;
+ if (faceCalls === 1) throw new Error("404 on a node without the file");
+ return { data: bytesFor(REGULAR) };
+ });
+
+ expect(await loadServerFontBytes("Acme Sans")).not.toBeNull();
+ expect(faceCalls).toBe(2);
+
+ forgetServerFontList();
+ faceCalls = 0;
+ get.mockImplementation(async (url: string) => {
+ if (url === SERVER_FONTS_URL) return { data: MANIFEST };
+ faceCalls++;
+ throw new Error("gone");
+ });
+ expect(await loadServerFontBytes("Acme Sans")).toBeNull();
+ expect(faceCalls).toBe(2);
+ expect(getServerFontBytes("Acme Sans")).toBeNull();
+ });
+
+ it("revalidates the list once it is stale and publishes only a change", async () => {
+ let now = 1_000_000;
+ vi.spyOn(Date, "now").mockImplementation(() => now);
+ serveManifestAndFaces();
+ const first = await loadServerFonts();
+ const listener = vi.fn();
+ const unsubscribe = subscribeServerFonts(listener);
+
+ now += SERVER_FONTS_REFRESH_MS - 1;
+ expect(await loadServerFonts()).toBe(first);
+ expect(get).toHaveBeenCalledTimes(1);
+
+ now += 1;
+ loadServerFonts();
+ loadServerFonts();
+ await vi.waitFor(() => expect(get).toHaveBeenCalledTimes(2));
+ await Promise.resolve();
+ expect(listener).not.toHaveBeenCalled();
+ expect(loadedServerFonts()).toBe(first);
+
+ get.mockResolvedValue({
+ data: {
+ families: [
+ {
+ family: "Beta Serif",
+ faces: [face("5".repeat(64), "Regular", false, false)],
+ },
+ ],
+ },
+ });
+ now += SERVER_FONTS_REFRESH_MS;
+ loadServerFonts();
+ await vi.waitFor(() => expect(listener).toHaveBeenCalledTimes(1));
+ expect(loadedServerFonts()?.map((font) => font.family)).toEqual([
+ "Beta Serif",
+ ]);
+ unsubscribe();
+ });
+
+ it("asks for the list again after a face fails to download", async () => {
+ vi.spyOn(Date, "now").mockReturnValue(1_000_000);
+ get.mockImplementation(async (url: string) => {
+ if (url === SERVER_FONTS_URL) return { data: MANIFEST };
+ throw new Error("gone");
+ });
+
+ expect(await loadServerFontBytes("Acme Sans")).toBeNull();
+ loadServerFonts();
+
+ await vi.waitFor(() =>
+ expect(
+ get.mock.calls.filter(([url]) => url === SERVER_FONTS_URL),
+ ).toHaveLength(2),
+ );
+ });
+
+ it("returns null for a family the server does not have", async () => {
+ serveManifestAndFaces();
+
+ expect(await loadServerFontBytes("Comic Sans")).toBeNull();
+ expect(faceRequests()).toEqual([]);
+ });
+
+ it("lists server faces ahead of device faces of the same family", async () => {
+ serveManifestAndFaces();
+ (window as unknown as { queryLocalFonts: unknown }).queryLocalFonts = vi.fn(
+ async () => [
+ {
+ family: "Acme Sans",
+ fullName: "Acme Sans",
+ style: "Regular",
+ postscriptName: "AcmeSans-Device",
+ blob: async () => ({
+ arrayBuffer: async () => new Uint8Array([9, 9, 9, 9]).buffer,
+ }),
+ },
+ {
+ family: "Calibri",
+ fullName: "Calibri",
+ style: "Regular",
+ postscriptName: "Calibri",
+ },
+ ],
+ );
+ await listLocalFonts();
+ await loadServerFonts();
+
+ const merged = loadedExternalFonts();
+ expect(merged?.map((font) => font.postscriptName)).toEqual([
+ "AcmeSans-Regular",
+ "AcmeSans-Italic",
+ "AcmeSans-Bold",
+ "Calibri",
+ ]);
+ expect(loadedExternalFonts()).toBe(merged);
+
+ await loadServerFontBytes("Acme Sans");
+ expect(getExternalFontBytes("Acme Sans")?.[0]).toBe(1);
+ });
+
+ it("offers italic for a server family that has an italic cut", async () => {
+ serveManifestAndFaces();
+ await loadServerFonts();
+
+ expect(italicCapability("device:Acme Sans", true)).toEqual({
+ family: "Acme Sans Italic",
+ source: "device",
+ });
+ expect(italicCapability("device:Acme Sans Bold", true)).toEqual({
+ family: null,
+ source: null,
+ });
+ });
+
+ it("loads the new face after a refresh replaces the one already loaded", async () => {
+ let now = 1_000_000;
+ vi.spyOn(Date, "now").mockImplementation(() => now);
+ serveManifestAndFaces();
+ expect((await loadServerFontBytes("Acme Sans"))?.[0]).toBe(1);
+
+ const REPLACED = "9".repeat(64);
+ get.mockImplementation(async (url: string) => {
+ if (url === SERVER_FONTS_URL) {
+ return {
+ data: {
+ families: [
+ {
+ family: "Acme Sans",
+ faces: [face(REPLACED, "Regular", false, false)],
+ },
+ ],
+ },
+ };
+ }
+ return { data: bytesFor(url.slice(SERVER_FONTS_URL.length + 1)) };
+ });
+ const listener = vi.fn();
+ const unsubscribe = subscribeServerFonts(listener);
+ now += SERVER_FONTS_REFRESH_MS;
+ loadServerFonts();
+ await vi.waitFor(() => expect(listener).toHaveBeenCalledTimes(1));
+
+ expect(serverFaceFor("Acme Sans")?.id).toBe(REPLACED);
+ expect(getServerFontBytes("Acme Sans")).toBeNull();
+ expect((await loadServerFontBytes("Acme Sans"))?.[0]).toBe(9);
+ expect(getExternalFontBytes("Acme Sans")?.[0]).toBe(9);
+ unsubscribe();
+ });
+
+ it("keeps a loaded face readable when a refresh adds another family", async () => {
+ let now = 1_000_000;
+ vi.spyOn(Date, "now").mockImplementation(() => now);
+ serveManifestAndFaces();
+ expect((await loadServerFontBytes("Acme Sans"))?.[0]).toBe(1);
+
+ get.mockImplementation(async (url: string) => {
+ if (url === SERVER_FONTS_URL) {
+ return {
+ data: {
+ families: [
+ ...MANIFEST.families,
+ {
+ family: "Beta Serif",
+ faces: [face("5".repeat(64), "Regular", false, false)],
+ },
+ ],
+ },
+ };
+ }
+ return { data: bytesFor(url.slice(SERVER_FONTS_URL.length + 1)) };
+ });
+ const listener = vi.fn();
+ const unsubscribe = subscribeServerFonts(listener);
+ now += SERVER_FONTS_REFRESH_MS;
+ loadServerFonts();
+ await vi.waitFor(() => expect(listener).toHaveBeenCalledTimes(1));
+
+ expect(getServerFontBytes("Acme Sans")?.[0]).toBe(1);
+ expect(getExternalFontBytes("Acme Sans")?.[0]).toBe(1);
+ unsubscribe();
+ });
+
+ it("reads bold and italic from the server, not from the style name", async () => {
+ get.mockResolvedValue({
+ data: {
+ families: [
+ {
+ family: "Acme Sans",
+ faces: [
+ face(REGULAR, "Standard", false, false),
+ face(ITALIC, "Kursiv", false, true),
+ face(BOLD, "Fett", true, false),
+ ],
+ },
+ ],
+ },
+ });
+ const fonts = (await loadServerFonts()) ?? [];
+
+ expect(familyOptions(fonts, []).map((option) => option.value)).toEqual([
+ "Acme Sans",
+ "Acme Sans Bold",
+ ]);
+ expect(serverFaceFor("Acme Sans")?.id).toBe(REGULAR);
+ expect(serverFaceFor("Acme Sans Bold")?.id).toBe(BOLD);
+ expect(serverFaceFor("Acme Sans Italic")?.id).toBe(ITALIC);
+ expect(italicCapability("device:Acme Sans", true)).toEqual({
+ family: "Acme Sans Italic",
+ source: "device",
+ });
+ });
+
+ it("italicises a server Times New Roman with its own italic face", async () => {
+ get.mockResolvedValue({
+ data: {
+ families: [
+ {
+ family: "Times New Roman",
+ faces: [
+ face("6".repeat(64), "Regular", false, false),
+ face("7".repeat(64), "Italic", false, true),
+ ],
+ },
+ ],
+ },
+ });
+ expect(italicCapability("pdf:1:Times New Roman", true)).toEqual({
+ family: "Times-Italic",
+ source: "base14",
+ });
+
+ const fonts = await loadServerFonts();
+
+ expect(italicCapability("device:Times New Roman", true)).toEqual({
+ family: "Times New Roman Italic",
+ source: "device",
+ });
+ expect(italicCapability("device:Times New Roman Italic", false)).toEqual({
+ family: "Times New Roman",
+ source: "device",
+ });
+ expect(
+ pickLocalFontFace(fonts ?? [], "Times New Roman Italic")?.style,
+ ).toBe("Italic");
+ expect(italicCapability("base14:Times-Roman", true)).toEqual({
+ family: "Times-Italic",
+ source: "base14",
+ });
+ });
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/SetFontFamilyCommand.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/SetFontFamilyCommand.ts
index 5f97175f86..e4191495f8 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/commands/SetFontFamilyCommand.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/SetFontFamilyCommand.ts
@@ -19,6 +19,10 @@ import {
type TextTags,
} from "@editor/tools/pdfTextEditor/model/TextTags";
import { deviceFontEmitCount } from "@editor/tools/pdfTextEditor/util/deviceFontEmbed";
+import {
+ base14FontId,
+ deviceFontId,
+} from "@editor/tools/pdfTextEditor/util/fontFamily";
import {
setScanOverride,
type ScanOverride,
@@ -161,7 +165,9 @@ export class SetFontFamilyCommand implements Command {
// keeps `base14:`, so nothing keying off that prefix changes meaning.
const embedded =
deviceFontEmitCount(doc, this.nextFamily) > deviceEmitsBefore;
- run.fontId = `${embedded ? "device" : "base14"}:${this.nextFamily}`;
+ run.fontId = embedded
+ ? deviceFontId(this.nextFamily)
+ : base14FontId(this.nextFamily);
run.fontSubset = false;
// Reset ALL model bookkeeping to the freshly-emitted objects so later
// commands act on the live objects, not the removed originals.
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/EditorSidebar.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/EditorSidebar.tsx
index 858ac36518..c683cabd6b 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/components/EditorSidebar.tsx
+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/EditorSidebar.tsx
@@ -10,7 +10,7 @@ import { useSelectionGeometry } from "@editor/tools/pdfTextEditor/hooks/useSelec
import { 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 { analyzePageFonts } from "@editor/tools/pdfTextEditor/util/pageFonts";
+import { useSelectedFontNote } 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";
@@ -241,66 +241,6 @@ function NothingSelected(props: ScanHintProps) {
);
}
-/**
- * One line about the selected runs' font - or nothing at all.
- *
- * It speaks only when a character the user types might not survive: a missing
- * glyph, or an embedded face whose coverage we could not read. A font that can
- * render everything says nothing, because "all fine" is not worth a line.
- */
-function useSelectedFontNote(
- state: EditorViewState,
- selection: SelectionState,
-): string | null {
- const { t } = useTranslation();
- return useMemo(() => {
- if (selection.runIds.length === 0) return null;
- const picked = new Set(selection.runIds);
- const fontIds = new Set<string>();
- let scanned = 0;
- for (const page of state.pages)
- for (const run of page.runs)
- if (picked.has(run.id)) {
- fontIds.add(run.fontId);
- if (run.renderMode === 3) scanned++;
- }
- if (fontIds.size === 0) return null;
- // OCR text is invisible; its font says nothing about what an edit draws.
- if (scanned === selection.runIds.length)
- return t(
- "pdfTextEditor.inspector.scannedText",
- "Scanned text · changed words are covered and redrawn in a matching font.",
- );
-
- const fonts = analyzePageFonts(state.pages).filter((f) =>
- // analyzePageFonts keys by display name + status, so match on the names
- // the selected runs' fonts resolve to.
- Array.from(fontIds).some((id) => id.endsWith(f.name)),
- );
- if (fonts.length !== 1) return null;
- const font = fonts[0];
- const gaps = font.coverage.known ? font.coverage.missing : [];
- if (gaps.length > 0) {
- return t(
- "pdfTextEditor.inspector.fontGap",
- "{{name}} · missing {{glyphs}} - typing those falls back to Helvetica.",
- {
- name: font.name,
- glyphs: gaps.slice(0, 6).join(" "),
- },
- );
- }
- // Silent when the font can render anything the user types: a standard
- // base-14 face, or an embedded one whose cmap we read and found complete.
- if (font.status === "standard") return null;
- if (font.coverage.known) return null;
- return t(
- "pdfTextEditor.inspector.fontEmbedded",
- "Embedded font · a character it lacks falls back to Helvetica.",
- );
- }, [state.pages, selection.runIds, t]);
-}
-
function EmptySidebar({
loading,
progress,
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/FontFamilySelect.test.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/FontFamilySelect.test.tsx
new file mode 100644
index 0000000000..8bc440c4b6
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/FontFamilySelect.test.tsx
@@ -0,0 +1,162 @@
+import { MantineProvider } from "@mantine/core";
+import { fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { 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 } }));
+vi.mock("@editor/components/toast", () => ({ alert }));
+
+import { FontFamilySelect } from "@editor/tools/pdfTextEditor/components/FontFamilySelect";
+import type { FontPickFailure } from "@editor/tools/pdfTextEditor/hooks/useSelectionActions";
+import {
+ SERVER_FONTS_URL,
+ forgetServerFontList,
+} from "@editor/tools/pdfTextEditor/util/serverFonts";
+
+const MANIFEST = {
+ families: [
+ {
+ family: "Acme Sans",
+ faces: [
+ {
+ id: "1".repeat(64),
+ style: "Regular",
+ bold: false,
+ italic: false,
+ weight: 400,
+ postscriptName: "AcmeSans-Regular",
+ format: "ttf",
+ size: 4,
+ },
+ {
+ id: "2".repeat(64),
+ style: "Bold",
+ bold: true,
+ italic: false,
+ weight: 700,
+ postscriptName: "AcmeSans-Bold",
+ format: "ttf",
+ size: 4,
+ },
+ ],
+ },
+ ],
+};
+
+function renderPicker(
+ onChange: (family: string) => Promise<FontPickFailure | null>,
+) {
+ render(
+ <MantineProvider env="test">
+ <FontFamilySelect value="Helvetica" onChange={onChange} />
+ </MantineProvider>,
+ );
+ return screen.getByTestId("pdf-editor-font-family");
+}
+
+describe("font picker server fonts", () => {
+ beforeEach(() => {
+ Element.prototype.scrollIntoView = vi.fn();
+ get.mockReset();
+ alert.mockReset();
+ forgetServerFontList();
+ get.mockImplementation(async (url: string) => {
+ if (url === SERVER_FONTS_URL) return { data: MANIFEST };
+ throw new Error(`unexpected ${url}`);
+ });
+ });
+
+ it("asks the server for its font list only when the picker opens", async () => {
+ const input = renderPicker(async () => null);
+ expect(get).not.toHaveBeenCalled();
+
+ fireEvent.click(input);
+
+ expect(await screen.findByText("Acme Sans")).toBeInTheDocument();
+ expect(get).toHaveBeenCalledTimes(1);
+ expect(get).toHaveBeenCalledWith(SERVER_FONTS_URL, expect.anything());
+ });
+
+ it("offers the bold cut of a server family that has one", async () => {
+ const onChange = vi.fn(async () => null);
+ const input = renderPicker(onChange);
+
+ fireEvent.click(input);
+ fireEvent.click(await screen.findByText("Acme Sans Bold"));
+
+ await waitFor(() =>
+ expect(onChange).toHaveBeenCalledWith("Acme Sans Bold"),
+ );
+ });
+
+ it("reports a server font that could not be applied", async () => {
+ const onChange = vi.fn(
+ async (): Promise<FontPickFailure> => "serverFontFailed",
+ );
+ const input = renderPicker(onChange);
+
+ fireEvent.click(input);
+ fireEvent.click(await screen.findByText("Acme Sans"));
+
+ await waitFor(() => expect(onChange).toHaveBeenCalledWith("Acme Sans"));
+ await waitFor(() =>
+ expect(alert).toHaveBeenCalledWith({
+ alertType: "warning",
+ expandable: false,
+ title: "pdfTextEditor.fontPicker.serverFontFailed",
+ }),
+ );
+ expect(
+ screen.queryByTestId("pdf-editor-device-fonts-notice"),
+ ).not.toBeInTheDocument();
+ });
+
+ it("reports a font with no characters for the selected text", async () => {
+ const onChange = vi.fn(async (): Promise<FontPickFailure> => "noGlyphs");
+ const input = renderPicker(onChange);
+
+ fireEvent.click(input);
+ fireEvent.click(await screen.findByText("Acme Sans Bold"));
+
+ await waitFor(() =>
+ expect(alert).toHaveBeenCalledWith({
+ alertType: "warning",
+ expandable: false,
+ title: "pdfTextEditor.fontPicker.noGlyphs",
+ }),
+ );
+ });
+
+ it("lists a family named like another family's bold cut once", async () => {
+ get.mockImplementation(async (url: string) => {
+ if (url !== SERVER_FONTS_URL) throw new Error(`unexpected ${url}`);
+ return {
+ data: {
+ families: [
+ ...MANIFEST.families,
+ {
+ family: "Acme Sans Bold",
+ faces: [{ ...MANIFEST.families[0].faces[0], id: "3".repeat(64) }],
+ },
+ ],
+ },
+ };
+ });
+ const input = renderPicker(async () => null);
+
+ fireEvent.click(input);
+
+ expect(await screen.findAllByText("Acme Sans Bold")).toHaveLength(1);
+ });
+
+ it("raises nothing when the font applies", async () => {
+ const onChange = vi.fn(async () => null);
+ const input = renderPicker(onChange);
+
+ fireEvent.click(input);
+ fireEvent.click(await screen.findByText("Acme Sans"));
+
+ await waitFor(() => expect(onChange).toHaveBeenCalledWith("Acme Sans"));
+ expect(alert).not.toHaveBeenCalled();
+ });
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/FontFamilySelect.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/FontFamilySelect.tsx
index b21b7dcffb..86df51effb 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/components/FontFamilySelect.tsx
+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/FontFamilySelect.tsx
@@ -1,21 +1,24 @@
import { useCallback, useMemo, useState, useSyncExternalStore } from "react";
-import { Group, Select, Text, Tooltip } from "@mantine/core";
+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 type { FontPickFailure } from "@editor/tools/pdfTextEditor/hooks/useSelectionActions";
import {
- groupByFamily,
+ familyOptions,
isLocalFontAccessSupported,
listLocalFonts,
loadedLocalFonts,
subscribeLocalFonts,
+ type FontFamilyOption,
} from "@editor/tools/pdfTextEditor/util/localFonts";
-
-export interface FontFamilyOption {
- value: string;
- label: string;
-}
+import {
+ loadedServerFonts,
+ loadServerFonts,
+ subscribeServerFonts,
+} from "@editor/tools/pdfTextEditor/util/serverFonts";
/** Base-14 families, renderable by every viewer without embedding. */
export const BUILT_IN_FONT_FAMILIES: FontFamilyOption[] = [
@@ -28,11 +31,28 @@ export const BUILT_IN_FONT_FAMILIES: FontFamilyOption[] = [
{ value: "Courier-Bold", label: "Courier Bold" },
];
+const BUILT_IN_NAMES = BUILT_IN_FONT_FAMILIES.map((option) => option.value);
+
+const PICK_FAILURE_TEXT: Record<FontPickFailure, [string, string]> = {
+ serverFontFailed: [
+ "pdfTextEditor.fontPicker.serverFontFailed",
+ "That server font could not be downloaded. The text was left unchanged.",
+ ],
+ embedFailed: [
+ "pdfTextEditor.fontPicker.embedFailed",
+ "This font could not be embedded in the PDF. The text was left unchanged.",
+ ],
+ noGlyphs: [
+ "pdfTextEditor.fontPicker.noGlyphs",
+ "This font has no characters for the selected text. The text was left unchanged.",
+ ],
+};
+
type DeviceFontNotice = "unavailable" | "none";
interface FontFamilySelectProps {
value: string | null;
- onChange: (family: string) => void;
+ onChange: (family: string) => void | Promise<FontPickFailure | null>;
mixed?: boolean;
disabled?: boolean;
touch?: boolean;
@@ -48,6 +68,7 @@ export function FontFamilySelect({
}: FontFamilySelectProps) {
const { t } = useTranslation();
const [loading, setLoading] = useState(false);
+ const [applying, setApplying] = useState(false);
const [notice, setNotice] = useState<DeviceFontNotice | null>(null);
const supported = useMemo(() => isLocalFontAccessSupported(), []);
// Read the fonts from the module, not local state: switching files remounts
@@ -58,15 +79,25 @@ export function FontFamilySelect({
loadedLocalFonts,
);
- const deviceFamilies = useMemo(() => {
- if (!localFonts) return [];
- const builtIn = new Set(
- BUILT_IN_FONT_FAMILIES.map((option) => option.value.toLowerCase()),
- );
- return groupByFamily(localFonts)
- .map((family) => family.family)
- .filter((family) => !builtIn.has(family.toLowerCase()));
- }, [localFonts]);
+ const serverFonts = useSyncExternalStore(
+ subscribeServerFonts,
+ loadedServerFonts,
+ loadedServerFonts,
+ );
+
+ const serverOptions = useMemo(
+ () => familyOptions(serverFonts, BUILT_IN_NAMES),
+ [serverFonts],
+ );
+
+ const deviceOptions = useMemo(
+ () =>
+ familyOptions(localFonts, [
+ ...BUILT_IN_NAMES,
+ ...serverOptions.map((option) => option.value),
+ ]),
+ [localFonts, serverOptions],
+ );
const loadDeviceFonts = useCallback(async () => {
setLoading(true);
@@ -84,9 +115,10 @@ export function FontFamilySelect({
const isKnown = useCallback(
(family: string) =>
- BUILT_IN_FONT_FAMILIES.some((option) => option.value === family) ||
- deviceFamilies.includes(family),
- [deviceFamilies],
+ [...BUILT_IN_FONT_FAMILIES, ...serverOptions, ...deviceOptions].some(
+ (option) => option.value === family,
+ ),
+ [serverOptions, deviceOptions],
);
// The run's own face when we hold no bytes for it. Shown so the user can see
@@ -97,7 +129,11 @@ export function FontFamilySelect({
);
const data = useMemo<ComboboxData>(() => {
- if (deviceFamilies.length === 0 && !documentFamily) {
+ if (
+ serverOptions.length === 0 &&
+ deviceOptions.length === 0 &&
+ !documentFamily
+ ) {
return BUILT_IN_FONT_FAMILIES;
}
const groups: ComboboxItemGroup[] = [];
@@ -113,17 +149,48 @@ export function FontFamilySelect({
group: t("pdfTextEditor.fontPicker.builtInGroup", "Built-in fonts"),
items: BUILT_IN_FONT_FAMILIES,
});
- if (deviceFamilies.length > 0) {
+ if (serverOptions.length > 0) {
+ groups.push({
+ group: t("pdfTextEditor.fontPicker.serverGroup", "Server fonts"),
+ items: serverOptions,
+ });
+ }
+ if (deviceOptions.length > 0) {
groups.push({
group: t("pdfTextEditor.fontPicker.deviceGroup", "Device fonts"),
- items: deviceFamilies.map((family) => ({
- value: family,
- label: family,
- })),
+ items: deviceOptions,
});
}
return groups;
- }, [deviceFamilies, documentFamily, t]);
+ }, [serverOptions, deviceOptions, documentFamily, t]);
+
+ const pickFailureText = useCallback(
+ (failure: FontPickFailure): string => {
+ const [key, fallback] = PICK_FAILURE_TEXT[failure];
+ return t(key, fallback);
+ },
+ [t],
+ );
+
+ const applyFamily = useCallback(
+ async (family: string) => {
+ setNotice(null);
+ setApplying(true);
+ try {
+ const failure = await onChange(family);
+ if (failure) {
+ alert({
+ alertType: "warning",
+ title: pickFailureText(failure),
+ expandable: false,
+ });
+ }
+ } finally {
+ setApplying(false);
+ }
+ },
+ [onChange, pickFailureText],
+ );
// Mantine shows nothing for a value with no matching option; the document
// font is in `data` precisely so a recognised face still gets named.
@@ -147,9 +214,13 @@ export function FontFamilySelect({
data={data}
value={selected}
onChange={(next) => {
- if (next) onChange(next);
+ if (next) void applyFamily(next);
+ }}
+ onDropdownOpen={() => {
+ void loadServerFonts();
}}
- disabled={disabled}
+ rightSection={applying ? <Loader size="xs" /> : undefined}
+ disabled={disabled || applying}
placeholder={
mixed
? t("pdfTextEditor.fontPicker.mixed", "Mixed")
@@ -162,7 +233,7 @@ export function FontFamilySelect({
)}
data-testid="pdf-editor-font-family"
/>
- {supported && deviceFamilies.length === 0 && (
+ {supported && deviceOptions.length === 0 && (
<Tooltip
label={t(
"pdfTextEditor.fontPicker.useDeviceFonts",
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/TextRunOverlay.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/TextRunOverlay.tsx
index 0ca35a8900..3cbe23e32d 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/components/TextRunOverlay.tsx
+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/TextRunOverlay.tsx
@@ -1,9 +1,10 @@
import { useEffect, useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
-import type {
- TextRange,
- TextRunSnapshot,
- WidthMode,
+import {
+ RENDER_MODE_INVISIBLE,
+ type TextRange,
+ type TextRunSnapshot,
+ type WidthMode,
} from "@editor/tools/pdfTextEditor/types";
import { toCssHex } from "@editor/tools/pdfTextEditor/model/Color";
import type { DisplayTransform } from "@editor/tools/pdfTextEditor/model/DisplayTransform";
@@ -15,7 +16,10 @@ import {
embeddedFaceFamily,
onEmbeddedFaceLoaded,
} from "@editor/tools/pdfTextEditor/util/embeddedFace";
-import { nearestStandardFont } from "@editor/tools/pdfTextEditor/util/fontFamily";
+import {
+ isDeviceFontId,
+ nearestStandardFont,
+} from "@editor/tools/pdfTextEditor/util/fontFamily";
import {
fitTextToWidth,
NO_FIT,
@@ -49,10 +53,9 @@ import {
resetTextMetricsCache,
} from "@editor/tools/pdfTextEditor/util/textMetrics";
import { MIN_WRAP_WIDTH_EM } from "@editor/tools/pdfTextEditor/commands/ReflowWrapCommand";
+import { serverFontCssFamily } from "@editor/tools/pdfTextEditor/util/serverFonts";
import "@editor/tools/pdfTextEditor/components/TextRunOverlay.css";
-const RENDER_MODE_INVISIBLE = 3;
-
const SETTLE_MS = 400;
const STALL_MS = 250;
@@ -77,13 +80,15 @@ function cssFontFamilyFor(fontId: string): string {
// The document's own face, when PDFium gave us bytes a FontFace accepts.
// An unresolved name costs nothing: the browser moves on to the next entry.
const own = ownFaceFor(fontId);
- // An edit that outgrew a subset now re-emits in the user's INSTALLED face
+ // An edit that outgrew a subset now re-emits in an installed or server face
// (`device:Calibri`), so the page really is Calibri. Naming it first keeps
// the overlay measuring and drawing what the page renders; without it
// nearestStandardFont collapses it to Helvetica and every advance the
// overlay predicts is a different font's.
- if (fontId.startsWith("device:")) {
- return `"${family}", ${own}"Liberation Sans", "Helvetica Neue", Helvetica, Arial, sans-serif`;
+ if (isDeviceFontId(fontId)) {
+ const server = serverFontCssFamily(family);
+ const served = server ? `"${server}", ` : "";
+ return `${served}"${family}", ${own}"Liberation Sans", "Helvetica Neue", Helvetica, Arial, sans-serif`;
}
const standard = nearestStandardFont(family);
if (standard.startsWith("Times")) {
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useSelectedFontNote.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useSelectedFontNote.test.ts
new file mode 100644
index 0000000000..4d19e41c58
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useSelectedFontNote.test.ts
@@ -0,0 +1,86 @@
+import { readFileSync } from "node:fs";
+import path from "node:path";
+import { act, renderHook } from "@testing-library/react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const { get } = vi.hoisted(() => ({ get: vi.fn() }));
+vi.mock("@editor/services/apiClient", () => ({ default: { get } }));
+
+import { useSelectedFontNote } from "@editor/tools/pdfTextEditor/hooks/useSelectedFontNote";
+import type { EditorViewState } from "@editor/tools/pdfTextEditor/store/EditorStore";
+import type { SelectionState } from "@editor/tools/pdfTextEditor/types";
+import {
+ SERVER_FONTS_URL,
+ forgetServerFontList,
+ loadServerFontBytes,
+} from "@editor/tools/pdfTextEditor/util/serverFonts";
+import { resetDeviceFontEmbedCache } from "@editor/tools/pdfTextEditor/util/deviceFontEmbed";
+
+const SERIF_BOLD = "1".repeat(64);
+
+const SERIF_BOLD_TTF = readFileSync(
+ path.resolve(
+ __dirname,
+ "../../../../../../../app/core/src/main/resources/static/fonts/DejaVuSerif-Bold.ttf",
+ ),
+);
+
+const STATE = {
+ pages: [
+ {
+ pageIndex: 0,
+ runs: [
+ {
+ id: "a",
+ pageIndex: 0,
+ text: "Hello",
+ fontId: "device:DejaVu Serif Bold",
+ fontSubset: false,
+ },
+ ],
+ },
+ ],
+} as unknown as EditorViewState;
+
+const SELECTION = { runIds: ["a"] } as unknown as SelectionState;
+
+describe("useSelectedFontNote", () => {
+ beforeEach(() => {
+ get.mockReset();
+ forgetServerFontList();
+ resetDeviceFontEmbedCache();
+ get.mockImplementation(async (url: string) => {
+ if (url === SERVER_FONTS_URL) {
+ return {
+ data: {
+ families: [
+ {
+ family: "DejaVu Serif",
+ faces: [
+ { id: SERIF_BOLD, style: "Bold", bold: true, italic: false },
+ ],
+ },
+ ],
+ },
+ };
+ }
+ return {
+ data: SERIF_BOLD_TTF.buffer.slice(
+ SERIF_BOLD_TTF.byteOffset,
+ SERIF_BOLD_TTF.byteOffset + SERIF_BOLD_TTF.byteLength,
+ ),
+ };
+ });
+ });
+
+ it("drops the unknown-coverage note once the server face arrives", async () => {
+ const { result } = renderHook(() => useSelectedFontNote(STATE, SELECTION));
+ expect(result.current).toBe("pdfTextEditor.inspector.fontUnknownCoverage");
+
+ await act(async () => {
+ await loadServerFontBytes("DejaVu Serif Bold");
+ });
+
+ expect(result.current).toBeNull();
+ });
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useSelectedFontNote.ts b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useSelectedFontNote.ts
new file mode 100644
index 0000000000..3d4a37f248
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useSelectedFontNote.ts
@@ -0,0 +1,49 @@
+import { useMemo, useSyncExternalStore } from "react";
+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 {
+ serverFontBytesVersion,
+ subscribeServerFontBytes,
+} from "@editor/tools/pdfTextEditor/util/serverFonts";
+
+export function useSelectedFontNote(
+ state: EditorViewState,
+ selection: SelectionState,
+): string | null {
+ const { t } = useTranslation();
+ const fontBytesVersion = useSyncExternalStore(
+ subscribeServerFontBytes,
+ serverFontBytesVersion,
+ serverFontBytesVersion,
+ );
+ 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.",
+ );
+ case "embeddedUnknown":
+ return t(
+ "pdfTextEditor.inspector.fontEmbedded",
+ "Embedded font · a character it lacks falls back to Helvetica.",
+ );
+ case "deviceUnknown":
+ return t(
+ "pdfTextEditor.inspector.fontUnknownCoverage",
+ "{{name}} · a character it lacks falls back to {{fallback}}.",
+ { name: note.name, fallback: note.fallback },
+ );
+ case "gap":
+ return t(
+ "pdfTextEditor.inspector.fontGap",
+ "{{name}} · missing {{glyphs}} - typing those falls back to {{fallback}}.",
+ { name: note.name, glyphs: note.glyphs, fallback: note.fallback },
+ );
+ }
+ }, [state.pages, selection.runIds, fontBytesVersion, t]);
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useSelectionActions.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useSelectionActions.test.ts
new file mode 100644
index 0000000000..051259c0da
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useSelectionActions.test.ts
@@ -0,0 +1,368 @@
+import { readFileSync } from "node:fs";
+import path from "node:path";
+import { renderHook } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+const { get } = vi.hoisted(() => ({ get: vi.fn() }));
+vi.mock("@editor/services/apiClient", () => ({ default: { get } }));
+vi.mock("@editor/tools/pdfTextEditor/commands/SetFontFamilyCommand", () => ({
+ SetFontFamilyCommand: class {
+ constructor(readonly opts: { runId: string; nextFamily: string }) {}
+ },
+}));
+vi.mock("@editor/tools/pdfTextEditor/commands/CompositeCommand", () => ({
+ CompositeCommand: class {
+ constructor(readonly commands: unknown[]) {}
+ },
+}));
+
+import { useSelectionActions } from "@editor/tools/pdfTextEditor/hooks/useSelectionActions";
+import type { EditorStore } from "@editor/tools/pdfTextEditor/store/EditorStore";
+import {
+ SERVER_FONTS_URL,
+ loadServerFonts,
+ forgetServerFontList,
+} from "@editor/tools/pdfTextEditor/util/serverFonts";
+import { resetLocalFontsCache } from "@editor/tools/pdfTextEditor/util/localFonts";
+import { resetDeviceFontEmbedCache } from "@editor/tools/pdfTextEditor/util/deviceFontEmbed";
+
+const REGULAR = "1".repeat(64);
+const ITALIC = "2".repeat(64);
+const HEBREW = "5".repeat(64);
+
+const HEBREW_TTF = readFileSync(
+ path.resolve(
+ __dirname,
+ "../../../../../../../app/core/src/main/resources/static/fonts/NotoSansHebrew-Regular.ttf",
+ ),
+);
+
+function face(id: string, style: string, italic: boolean) {
+ return { id, style, bold: false, italic, weight: 400, postscriptName: "" };
+}
+
+const MANIFEST = {
+ families: [
+ {
+ family: "Acme Sans",
+ faces: [face(REGULAR, "Regular", false), face(ITALIC, "Italic", true)],
+ },
+ { family: "Noto Sans Hebrew", faces: [face(HEBREW, "Regular", false)] },
+ ],
+};
+
+interface FakeRun {
+ id: string;
+ pageIndex: number;
+ fontId: string;
+ text: string;
+ locked: boolean;
+ fill: { r: number; g: number; b: number; a: number };
+}
+
+function run(id: string, fontId: string, text = "Hello"): FakeRun {
+ return {
+ id,
+ pageIndex: 0,
+ fontId,
+ text,
+ locked: false,
+ fill: { r: 0, g: 0, b: 0, a: 255 },
+ };
+}
+
+const FONT_HANDLE = 7;
+
+function fakeStore(
+ runs: FakeRun[],
+ selected: string[],
+ pdfiumLoadsFont = true,
+) {
+ const openDocument = () => {
+ const owned = new Map<string, { id: string }>();
+ return {
+ loadedPages: () => [{ runs }],
+ docPtr: 1,
+ ownedFont: (id: string) => owned.get(id),
+ registerOwnedFont: (font: { id: string }) => owned.set(font.id, font),
+ recordEmbeddedFontFile: () => {},
+ module: {
+ FPDFText_LoadFont: () => (pdfiumLoadsFont ? FONT_HANDLE : 0),
+ pdfium: {
+ HEAPU8: new Uint8Array(1 << 20),
+ wasmExports: { malloc: () => 8, free: () => {} },
+ },
+ },
+ };
+ };
+ let doc = openDocument();
+ const selection = { value: { runIds: selected } };
+ const dispatch = vi.fn();
+ const store = {
+ selection,
+ dispatch,
+ get document() {
+ return doc;
+ },
+ } as unknown as EditorStore;
+ return {
+ store,
+ dispatch,
+ select: (ids: string[]) => {
+ selection.value = { runIds: ids };
+ },
+ openAnotherDocument: () => {
+ doc = openDocument();
+ },
+ };
+}
+
+interface Recorded {
+ opts?: { runId: string; nextFamily: string };
+ commands?: Recorded[];
+}
+
+function dispatchedChanges(dispatch: ReturnType<typeof vi.fn>): string[] {
+ const flatten = (cmd: Recorded): Recorded[] =>
+ cmd.commands ? cmd.commands.flatMap(flatten) : [cmd];
+ return dispatch.mock.calls
+ .flatMap(([cmd]) => flatten(cmd as Recorded))
+ .map((cmd) => `${cmd.opts?.runId}:${cmd.opts?.nextFamily}`);
+}
+
+function serveFaces(serve: (id: string) => Promise<{ data: ArrayBuffer }>) {
+ get.mockImplementation(async (url: string) => {
+ if (url === SERVER_FONTS_URL) return { data: MANIFEST };
+ return serve(url.slice(SERVER_FONTS_URL.length + 1));
+ });
+}
+
+function fontBytes(): { data: ArrayBuffer } {
+ return { data: new Uint8Array([0, 1, 0, 0]).buffer };
+}
+
+function actionsFor(store: EditorStore) {
+ return renderHook(() => useSelectionActions(store)).result.current;
+}
+
+describe("useSelectionActions font changes", () => {
+ beforeEach(() => {
+ get.mockReset();
+ forgetServerFontList();
+ resetLocalFontsCache();
+ resetDeviceFontEmbedCache();
+ });
+
+ afterEach(() => {
+ delete (window as unknown as { queryLocalFonts?: unknown }).queryLocalFonts;
+ });
+
+ it("applies a built-in font without asking for device fonts", async () => {
+ const queryLocalFonts = vi.fn(async () => []);
+ (window as unknown as { queryLocalFonts: unknown }).queryLocalFonts =
+ queryLocalFonts;
+ const { store, dispatch } = fakeStore(
+ [run("a", "base14:Helvetica")],
+ ["a"],
+ );
+
+ expect(await actionsFor(store).changeFontFamily("Times-Roman")).toBeNull();
+
+ expect(queryLocalFonts).not.toHaveBeenCalled();
+ expect(get).not.toHaveBeenCalled();
+ expect(dispatchedChanges(dispatch)).toEqual(["a:Times-Roman"]);
+ });
+
+ it("leaves the text alone when a server font cannot be downloaded", async () => {
+ serveFaces(async () => {
+ throw new Error("gone");
+ });
+ await loadServerFonts();
+ const { store, dispatch } = fakeStore(
+ [run("a", "base14:Helvetica")],
+ ["a"],
+ );
+
+ expect(await actionsFor(store).changeFontFamily("Acme Sans")).toBe(
+ "serverFontFailed",
+ );
+ expect(dispatch).not.toHaveBeenCalled();
+ });
+
+ it("leaves the text alone when the font will not embed", async () => {
+ serveFaces(async () => fontBytes());
+ await loadServerFonts();
+ const { store, dispatch } = fakeStore(
+ [run("a", "base14:Helvetica")],
+ ["a"],
+ false,
+ );
+
+ expect(await actionsFor(store).changeFontFamily("Acme Sans")).toBe(
+ "embedFailed",
+ );
+ expect(dispatch).not.toHaveBeenCalled();
+ });
+
+ it("changes the runs that were selected when the font was picked", async () => {
+ let finishDownload: (value: { data: ArrayBuffer }) => void = () => {};
+ serveFaces(
+ () =>
+ new Promise((resolve) => {
+ finishDownload = resolve;
+ }),
+ );
+ await loadServerFonts();
+ const { store, dispatch, select } = fakeStore(
+ [run("a", "base14:Helvetica"), run("b", "base14:Helvetica")],
+ ["a"],
+ );
+
+ const picked = actionsFor(store).changeFontFamily("Acme Sans");
+ select(["b"]);
+ await vi.waitFor(() => expect(get).toHaveBeenCalledTimes(2));
+ finishDownload(fontBytes());
+
+ expect(await picked).toBeNull();
+ expect(dispatchedChanges(dispatch)).toEqual(["a:Acme Sans"]);
+ });
+
+ it("drops a font change when another document opened during the download", async () => {
+ let finishDownload: (value: { data: ArrayBuffer }) => void = () => {};
+ serveFaces(
+ () =>
+ new Promise((resolve) => {
+ finishDownload = resolve;
+ }),
+ );
+ await loadServerFonts();
+ const { store, dispatch, openAnotherDocument } = fakeStore(
+ [run("a", "base14:Helvetica")],
+ ["a"],
+ );
+
+ const picked = actionsFor(store).changeFontFamily("Acme Sans");
+ openAnotherDocument();
+ await vi.waitFor(() => expect(get).toHaveBeenCalledTimes(2));
+ finishDownload(fontBytes());
+
+ expect(await picked).toBeNull();
+ expect(dispatch).not.toHaveBeenCalled();
+ });
+
+ it("skips runs removed during the download and records nothing when none remain", async () => {
+ let finishDownload: (value: { data: ArrayBuffer }) => void = () => {};
+ serveFaces(
+ () =>
+ new Promise((resolve) => {
+ finishDownload = resolve;
+ }),
+ );
+ await loadServerFonts();
+ const runs = [run("a", "base14:Helvetica"), run("b", "base14:Helvetica")];
+ const { store, dispatch } = fakeStore(runs, ["a", "b"]);
+
+ const picked = actionsFor(store).changeFontFamily("Acme Sans");
+ runs.splice(1, 1);
+ await vi.waitFor(() => expect(get).toHaveBeenCalledTimes(2));
+ finishDownload(fontBytes());
+
+ expect(await picked).toBeNull();
+ expect(dispatchedChanges(dispatch)).toEqual(["a:Acme Sans"]);
+
+ dispatch.mockClear();
+ runs.push(run("c", "base14:Helvetica"));
+ const { store: other, dispatch: otherDispatch } = fakeStore(runs, ["c"]);
+ const removedAll = actionsFor(other).changeFontFamily("Acme Sans Italic");
+ runs.splice(0, runs.length, run("c2", "base14:Helvetica"));
+ await vi.waitFor(() => expect(get).toHaveBeenCalledTimes(3));
+ finishDownload(fontBytes());
+
+ expect(await removedAll).toBeNull();
+ expect(otherDispatch).not.toHaveBeenCalled();
+ });
+
+ it("keeps a run's font when its italic face cannot be downloaded", async () => {
+ serveFaces(async (id) => {
+ if (id === ITALIC) throw new Error("gone");
+ return fontBytes();
+ });
+ await loadServerFonts();
+ const { store, dispatch } = fakeStore(
+ [run("a", "device:Acme Sans")],
+ ["a"],
+ );
+
+ await actionsFor(store).toggleItalic();
+
+ expect(get).toHaveBeenCalledWith(
+ `${SERVER_FONTS_URL}/${ITALIC}`,
+ expect.anything(),
+ );
+ expect(dispatch).not.toHaveBeenCalled();
+ });
+
+ it("leaves a run locked during the download unchanged", async () => {
+ let finishDownload: (value: { data: ArrayBuffer }) => void = () => {};
+ serveFaces(
+ () =>
+ new Promise((resolve) => {
+ finishDownload = resolve;
+ }),
+ );
+ await loadServerFonts();
+ const runs = [run("a", "base14:Helvetica"), run("b", "base14:Helvetica")];
+ const { store, dispatch } = fakeStore(runs, ["a", "b"]);
+
+ const picked = actionsFor(store).changeFontFamily("Acme Sans");
+ runs[1].locked = true;
+ await vi.waitFor(() => expect(get).toHaveBeenCalledTimes(2));
+ finishDownload(fontBytes());
+
+ expect(await picked).toBeNull();
+ expect(dispatchedChanges(dispatch)).toEqual(["a:Acme Sans"]);
+ });
+
+ it("keeps a run's font when its italic face will not embed", async () => {
+ serveFaces(async () => fontBytes());
+ await loadServerFonts();
+ const { store, dispatch } = fakeStore(
+ [run("a", "device:Acme Sans")],
+ ["a"],
+ false,
+ );
+
+ await actionsFor(store).toggleItalic();
+
+ expect(get).toHaveBeenCalledWith(
+ `${SERVER_FONTS_URL}/${ITALIC}`,
+ expect.anything(),
+ );
+ expect(dispatch).not.toHaveBeenCalled();
+ });
+
+ it("refuses a font that has none of the selected characters", async () => {
+ serveFaces(async () => ({
+ data: HEBREW_TTF.buffer.slice(
+ HEBREW_TTF.byteOffset,
+ HEBREW_TTF.byteOffset + HEBREW_TTF.byteLength,
+ ),
+ }));
+ await loadServerFonts();
+ const english = fakeStore([run("a", "base14:Helvetica", "Hello")], ["a"]);
+ const mixed = fakeStore(
+ [run("b", "base14:Helvetica", "Hello שלום")],
+ ["b"],
+ );
+
+ expect(
+ await actionsFor(english.store).changeFontFamily("Noto Sans Hebrew"),
+ ).toBe("noGlyphs");
+ expect(english.dispatch).not.toHaveBeenCalled();
+
+ expect(
+ await actionsFor(mixed.store).changeFontFamily("Noto Sans Hebrew"),
+ ).toBeNull();
+ expect(dispatchedChanges(mixed.dispatch)).toEqual(["b:Noto Sans Hebrew"]);
+ });
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useSelectionActions.ts b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useSelectionActions.ts
index 8d98aa2a97..925ae7a2a6 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useSelectionActions.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useSelectionActions.ts
@@ -10,11 +10,20 @@ import { SetTextOutlineCommand } from "@editor/tools/pdfTextEditor/commands/SetT
import { SetFontFamilyCommand } from "@editor/tools/pdfTextEditor/commands/SetFontFamilyCommand";
import { SetFontSizeCommand } from "@editor/tools/pdfTextEditor/commands/SetFontSizeCommand";
import { parseCssColor } from "@editor/tools/pdfTextEditor/model/Color";
-import { ensureDeviceFontReady } from "@editor/tools/pdfTextEditor/util/deviceFontEmbed";
+import {
+ deviceFontDrawsAnyOf,
+ ensureDeviceFontReady,
+ loadDeviceFontInto,
+} from "@editor/tools/pdfTextEditor/util/deviceFontEmbed";
import type { EditorStore } from "@editor/tools/pdfTextEditor/store/EditorStore";
-import { isItalicFamily } from "@editor/tools/pdfTextEditor/util/fontFamily";
+import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
+import {
+ isItalicFamily,
+ nearestStandardFont,
+} from "@editor/tools/pdfTextEditor/util/fontFamily";
import { italicCapability } from "@editor/tools/pdfTextEditor/util/fontCapability";
-import { loadedLocalFonts } from "@editor/tools/pdfTextEditor/util/localFonts";
+import { loadedExternalFonts } 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";
@@ -23,9 +32,47 @@ interface SelectedRun {
id: string;
pageIndex: number;
fontId: string;
+ text: string;
fill: { r: number; g: number; b: number; a: number };
}
+export type FontPickFailure = "serverFontFailed" | "embedFailed" | "noGlyphs";
+
+type ExternalFontLoad = "loaded" | "serverDownloadFailed" | "unavailable";
+
+interface FamilyChange {
+ pageIndex: number;
+ runId: string;
+ family: string;
+}
+
+async function prepareExternalFont(family: string): Promise<ExternalFontLoad> {
+ if (await ensureDeviceFontReady(family)) return "loaded";
+ return serverFaceFor(family) ? "serverDownloadFailed" : "unavailable";
+}
+
+function tryEmbedDeviceFont(doc: EditorDocument, family: string): boolean {
+ return loadDeviceFontInto(doc, family) !== 0;
+}
+
+async function fontPickFailure(
+ family: string,
+ text: string,
+): Promise<FontPickFailure | null> {
+ if (nearestStandardFont(family) === family) return null;
+ if ((await prepareExternalFont(family)) === "serverDownloadFailed")
+ return "serverFontFailed";
+ return deviceFontDrawsAnyOf(family, text) ? null : "noGlyphs";
+}
+
+function editableRunIds(store: EditorStore): Set<string> {
+ const ids = new Set<string>();
+ for (const page of store.document?.loadedPages() ?? []) {
+ for (const run of page.runs) if (!run.locked) ids.add(run.id);
+ }
+ return ids;
+}
+
/** Bundle of callbacks that operate on the current selection. */
export function useSelectionActions(store: EditorStore) {
const forEachSelectedRun = useCallback(
@@ -49,6 +96,14 @@ export function useSelectionActions(store: EditorStore) {
// `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[] = [];
@@ -56,10 +111,9 @@ export function useSelectionActions(store: EditorStore) {
const cmd = build(run);
if (cmd) cmds.push(cmd);
});
- if (cmds.length === 1) store.dispatch(cmds[0]);
- else if (cmds.length > 1) store.dispatch(new CompositeCommand(cmds));
+ dispatchAll(cmds);
},
- [store, forEachSelectedRun],
+ [forEachSelectedRun, dispatchAll],
);
const changeFontSize = useCallback(
@@ -110,31 +164,61 @@ export function useSelectionActions(store: EditorStore) {
[dispatchPerRun],
);
+ const dispatchFamilyChanges = useCallback(
+ (doc: EditorDocument | null, changes: FamilyChange[]) => {
+ if (store.document !== doc) return;
+ const editable = editableRunIds(store);
+ dispatchAll(
+ changes
+ .filter((change) => editable.has(change.runId))
+ .map(
+ (change) =>
+ new SetFontFamilyCommand({
+ pageIndex: change.pageIndex,
+ runId: change.runId,
+ nextFamily: change.family,
+ }),
+ ),
+ );
+ },
+ [store, dispatchAll],
+ );
+
const changeFontFamily = useCallback(
- async (family: string) => {
+ async (family: string): Promise<FontPickFailure | null> => {
+ const doc = store.document;
+ const targets: SelectedRun[] = [];
+ forEachSelectedRun((run) => targets.push(run));
+ const changes = targets.map((run) => ({
+ pageIndex: run.pageIndex,
+ runId: run.id,
+ family,
+ }));
// Embedding is async and Command.apply is not, so warm the bytes first.
// A no-op for the built-in families.
- await ensureDeviceFontReady(family);
- dispatchPerRun(
- (run) =>
- new SetFontFamilyCommand({
- pageIndex: run.pageIndex,
- runId: run.id,
- nextFamily: family,
- }),
+ const failure = await fontPickFailure(
+ family,
+ targets.map((run) => run.text).join(""),
);
+ if (failure) return failure;
+ if (store.document !== doc) return null;
+ // Refuse here, as the command would fall back to a standard face the user never picked.
+ if (
+ doc &&
+ nearestStandardFont(family) !== family &&
+ !tryEmbedDeviceFont(doc, family)
+ )
+ return "embedFailed";
+ dispatchFamilyChanges(doc, changes);
+ return null;
},
- [dispatchPerRun],
+ [store, forEachSelectedRun, dispatchFamilyChanges],
);
const toggleItalic = useCallback(async () => {
- const fonts = loadedLocalFonts();
- const targets: Array<{
- pageIndex: number;
- runId: string;
- family: string;
- device: boolean;
- }> = [];
+ const doc = store.document;
+ const fonts = loadedExternalFonts();
+ const targets: Array<FamilyChange & { device: boolean }> = [];
forEachSelectedRun((run) => {
const cap = italicCapability(
run.fontId,
@@ -152,20 +236,20 @@ export function useSelectionActions(store: EditorStore) {
});
});
// Embedding is async and Command.apply is not, so warm the bytes first.
+ const ready: FamilyChange[] = [];
for (const target of targets) {
- if (target.device) await ensureDeviceFontReady(target.family);
+ if (
+ target.device &&
+ ((await prepareExternalFont(target.family)) ===
+ "serverDownloadFailed" ||
+ !doc ||
+ !tryEmbedDeviceFont(doc, target.family))
+ )
+ continue;
+ ready.push(target);
}
- const cmds = targets.map(
- (target) =>
- new SetFontFamilyCommand({
- pageIndex: target.pageIndex,
- runId: target.runId,
- nextFamily: target.family,
- }),
- );
- if (cmds.length === 1) store.dispatch(cmds[0]);
- else if (cmds.length > 1) store.dispatch(new CompositeCommand(cmds));
- }, [store, forEachSelectedRun]);
+ dispatchFamilyChanges(doc, ready);
+ }, [store, forEachSelectedRun, dispatchFamilyChanges]);
const deleteSelection = useCallback(() => {
const sel = store.selection.value;
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useToolbarController.ts b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useToolbarController.ts
index b9c97f24bd..b3bfab219f 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useToolbarController.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useToolbarController.ts
@@ -11,9 +11,10 @@ import { useTextAccessibility } from "@editor/tools/pdfTextEditor/hooks/useTextA
import { deriveToolbarState } from "@editor/tools/pdfTextEditor/util/toolbarState";
import { warmDocumentDeviceFonts } from "@editor/tools/pdfTextEditor/util/fontCapability";
import {
- loadedLocalFonts,
- subscribeLocalFonts,
-} from "@editor/tools/pdfTextEditor/util/localFonts";
+ loadedExternalFonts,
+ subscribeExternalFonts,
+} from "@editor/tools/pdfTextEditor/util/externalFonts";
+import { loadServerFonts } from "@editor/tools/pdfTextEditor/util/serverFonts";
import {
ChangeZOrderCommand,
type ZOrderMode,
@@ -400,14 +401,18 @@ export function useToolbarController(
[store],
);
- // Null until the user loads their device fonts, and it must re-render when
- // they do - the italic control's availability is derived from it.
- const localFonts = useSyncExternalStore(
- subscribeLocalFonts,
- loadedLocalFonts,
- loadedLocalFonts,
+ // Null until device or server fonts load; re-render then, as italic availability derives from it.
+ const externalFonts = useSyncExternalStore(
+ subscribeExternalFonts,
+ loadedExternalFonts,
+ loadedExternalFonts,
);
+ const hasTextSelection = selection.runIds.length > 0;
+ useEffect(() => {
+ if (hasTextSelection) void loadServerFonts();
+ }, [hasTextSelection]);
+
const documentFontIds = useMemo(
() => [...new Set(state.pages.flatMap((p) => p.runs.map((r) => r.fontId)))],
[state.pages],
@@ -416,13 +421,13 @@ export function useToolbarController(
// 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 (!localFonts) return;
+ if (!externalFonts) return;
void warmDocumentDeviceFonts(documentFontIds);
- }, [localFonts, documentFontIds]);
+ }, [externalFonts, documentFontIds]);
const toolbarState = useMemo(
- () => deriveToolbarState(state.pages, selection, localFonts),
- [state.pages, selection, localFonts],
+ () => deriveToolbarState(state.pages, selection, externalFonts),
+ [state.pages, selection, externalFonts],
);
const selectionAllLocked = useMemo(() => {
@@ -507,9 +512,7 @@ export function useToolbarController(
onChangeFontSize: sel.changeFontSize,
onChangeFill: sel.changeFill,
onChangeOutline: sel.changeOutline,
- onChangeFontFamily: (family: string) => {
- void sel.changeFontFamily(family);
- },
+ onChangeFontFamily: sel.changeFontFamily,
onToggleItalic: sel.toggleItalic,
onDelete: sel.deleteSelection,
onToggleLock,
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/types.ts b/frontend/src/editor/core/tools/pdfTextEditor/types.ts
index 9ff1e96c54..845b7b3f55 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/types.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/types.ts
@@ -4,6 +4,8 @@ import type { DisplayTransformData } from "@editor/tools/pdfTextEditor/model/Dis
import type { AnnotationBox } from "@editor/tools/pdfTextEditor/model/AnnotationBox";
import type { Furniture } from "@editor/tools/pdfTextEditor/model/artifactKind";
+export const RENDER_MODE_INVISIBLE = 3;
+
export interface RGBA {
r: number; // 0..255
g: number;
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/deviceFontEmbed.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/deviceFontEmbed.ts
index 8e3d5c6e08..ffa9d8a98f 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/util/deviceFontEmbed.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/deviceFontEmbed.ts
@@ -5,9 +5,10 @@ import { FontRef } from "@editor/tools/pdfTextEditor/model/FontRef";
import { parseTrueTypeCmap } from "@editor/tools/pdfTextEditor/charcode/CmapResolver";
import { writeUtf16 } from "@editor/services/pdfiumService";
import {
- getLocalFontBytes,
- loadLocalFontBytes,
-} from "@editor/tools/pdfTextEditor/util/localFonts";
+ externalFaceKey,
+ getExternalFontBytes,
+ loadExternalFontBytes,
+} from "@editor/tools/pdfTextEditor/util/externalFonts";
import {
isBoldFamily,
isItalicFamily,
@@ -26,7 +27,7 @@ const DEVICE_FONT_ID_PREFIX = "__device_font:";
/** Owned-font id for a family, stable across emits of the same document. */
export function deviceFontIdFor(family: string): string {
- return `${DEVICE_FONT_ID_PREFIX}${family.trim().toLowerCase()}`;
+ return `${DEVICE_FONT_ID_PREFIX}${externalFaceKey(family)}`;
}
interface ExtendedPdfiumRuntime {
@@ -79,13 +80,10 @@ export function resetDeviceFontEmbedCache(): void {
emitCountByDoc = new WeakMap<EditorDocument, Map<string, number>>();
}
-// True if the face covers every non-whitespace code point. Fails open, leaving
-// the width self-check as the backstop.
-function deviceFontCovers(
+function coverageOf(
family: string,
bytes: Uint8Array,
- text: string,
-): boolean {
+): Map<number, number> | null {
const key = deviceFontIdFor(family);
if (!coverageByFamily.has(key)) {
let parsed: Map<number, number> | null = null;
@@ -96,26 +94,53 @@ function deviceFontCovers(
}
coverageByFamily.set(key, parsed);
}
- const coverage = coverageByFamily.get(key) ?? null;
- if (!coverage) return true;
+ return coverageByFamily.get(key) ?? null;
+}
+
+export function visibleCodePoints(text: string): number[] {
+ const out: number[] = [];
for (const ch of text) {
if (/\s/.test(ch)) continue;
const cp = ch.codePointAt(0);
- if (cp === undefined || !coverage.has(cp)) return false;
+ if (cp !== undefined) out.push(cp);
}
- return true;
+ return out;
+}
+
+// Whether the face covers every visible code point; fails open to the width self-check.
+function deviceFontCovers(
+ family: string,
+ bytes: Uint8Array,
+ text: string,
+): boolean {
+ const coverage = coverageOf(family, bytes);
+ if (!coverage) return true;
+ return visibleCodePoints(text).every((cp) => coverage.has(cp));
+}
+
+export function deviceFontCoverage(family: string): Map<number, number> | null {
+ const bytes = getExternalFontBytes(family);
+ return bytes ? coverageOf(family, bytes) : null;
+}
+
+export function deviceFontDrawsAnyOf(family: string, text: string): boolean {
+ const bytes = getExternalFontBytes(family);
+ const coverage = bytes ? coverageOf(family, bytes) : null;
+ const codePoints = visibleCodePoints(text);
+ if (!coverage || codePoints.length === 0) return true;
+ return codePoints.some((cp) => coverage.has(cp));
}
// Read the family's font file so a later synchronous emit can embed it. The UI
// must AWAIT this before dispatching a font-family change.
export async function ensureDeviceFontReady(family: string): Promise<boolean> {
- const bytes = await loadLocalFontBytes(family);
+ const bytes = await loadExternalFontBytes(family);
return !!bytes && bytes.length > 0;
}
/** Whether a synchronous emit can embed this family right now. */
export function isDeviceFontReady(family: string): boolean {
- const bytes = getLocalFontBytes(family);
+ const bytes = getExternalFontBytes(family);
return !!bytes && bytes.length > 0;
}
@@ -158,7 +183,7 @@ export function loadDeviceFontInto(
// A refusal is permanent for this document; retrying would re-malloc the
// whole font file on every keystroke.
if (refused.has(id)) return 0;
- const bytes = getLocalFontBytes(family);
+ const bytes = getExternalFontBytes(family);
if (!bytes || bytes.length === 0) return 0;
const m = doc.module;
@@ -252,7 +277,7 @@ export function emitDeviceFontTextObject(
y: number,
): number {
if (text.length === 0) return 0;
- const bytes = getLocalFontBytes(family);
+ const bytes = getExternalFontBytes(family);
if (!bytes || bytes.length === 0) return 0;
if (!deviceFontCovers(family, bytes, text)) return 0;
const fontPtr = loadDeviceFontInto(doc, family);
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/externalFonts.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/externalFonts.ts
new file mode 100644
index 0000000000..503df10b86
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/externalFonts.ts
@@ -0,0 +1,70 @@
+import {
+ getLocalFaceKey,
+ getLocalFontBytes,
+ loadedLocalFonts,
+ loadLocalFontBytes,
+ normaliseName,
+ subscribeLocalFonts,
+ type LocalFont,
+} from "@editor/tools/pdfTextEditor/util/localFonts";
+import {
+ getServerFaceId,
+ getServerFontBytes,
+ loadedServerFonts,
+ loadServerFontBytes,
+ serverFaceFor,
+ subscribeServerFonts,
+} from "@editor/tools/pdfTextEditor/util/serverFonts";
+
+let lastServer: LocalFont[] | null = null;
+let lastDevice: LocalFont[] | null = null;
+let merged: LocalFont[] | null = null;
+
+export function loadedExternalFonts(): LocalFont[] | null {
+ const server = loadedServerFonts();
+ const device = loadedLocalFonts();
+ if (server === lastServer && device === lastDevice) return merged;
+ lastServer = server;
+ lastDevice = device;
+ if (!server && !device) {
+ merged = null;
+ return merged;
+ }
+ const serverFamilies = new Set(
+ (server ?? []).map((font) => normaliseName(font.family)),
+ );
+ merged = [
+ ...(server ?? []),
+ ...(device ?? []).filter(
+ (font) => !serverFamilies.has(normaliseName(font.family)),
+ ),
+ ];
+ return merged;
+}
+
+export function subscribeExternalFonts(listener: () => void): () => void {
+ const offDevice = subscribeLocalFonts(listener);
+ const offServer = subscribeServerFonts(listener);
+ return () => {
+ offDevice();
+ offServer();
+ };
+}
+
+export function getExternalFontBytes(family: string): Uint8Array | null {
+ return getServerFontBytes(family) ?? getLocalFontBytes(family);
+}
+
+export function externalFaceKey(family: string): string {
+ const server = getServerFaceId(family);
+ if (server) return `server:${server}`;
+ const local = getLocalFaceKey(family);
+ return local ? `local:${local}` : normaliseName(family);
+}
+
+export async function loadExternalFontBytes(
+ family: string,
+): Promise<Uint8Array | null> {
+ if (serverFaceFor(family)) return loadServerFontBytes(family);
+ return loadLocalFontBytes(family);
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/fontCapability.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/fontCapability.ts
index 572231d313..709713298b 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/util/fontCapability.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/fontCapability.ts
@@ -2,17 +2,21 @@ import {
familyOf,
flipItalic,
isItalicFamily,
+ nearestStandardFont,
} from "@editor/tools/pdfTextEditor/util/fontFamily";
import { helveticaVariantFor } from "@editor/tools/pdfTextEditor/util/helveticaVariant";
import {
faceStyleFlags,
- getLocalFontBytes,
- loadLocalFontBytes,
- loadedLocalFonts,
+ knownFamilyOf,
pickLocalFontFace,
- splitRequested,
+ resolveRequested,
type LocalFont,
} from "@editor/tools/pdfTextEditor/util/localFonts";
+import {
+ getExternalFontBytes,
+ loadExternalFontBytes,
+ loadedExternalFonts,
+} from "@editor/tools/pdfTextEditor/util/externalFonts";
// Whether a style change is actually possible for a run's face, and in which
// family. The toolbar asks before offering the control: replacing a document's
@@ -31,10 +35,12 @@ 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. */
@@ -43,7 +49,7 @@ function deviceFaceFor(
family: string,
italic: boolean,
): string | null {
- const req = splitRequested(family);
+ const req = resolveRequested(fonts, family);
if (!req.family) return null;
const wanted = [req.family, req.bold ? "Bold" : "", italic ? "Italic" : ""]
.filter(Boolean)
@@ -57,31 +63,32 @@ function deviceFaceFor(
return wanted;
}
-/**
- * Which family gives `fontId` its italic cut (or its upright one back).
- *
- * base-14 flips in place. Anything else - an embedded or subset face - needs a
- * device font of the same family that genuinely carries the style, which only
- * exists once the user has loaded their device fonts.
- */
+/** Base-14 flips in place unless an external family of that name exists; others need a real face. */
export function italicCapability(
fontId: string,
italic: boolean,
- fonts: LocalFont[] | null = loadedLocalFonts(),
+ fonts: LocalFont[] | null = loadedExternalFonts(),
): StyleCapability {
const family = familyOf(fontId);
if (!family) return NONE;
const flipped = flipItalic(family, italic);
- if (flipped) return { family: flipped, source: "base14" };
+ if (flipped && !hasExternalFamily(fonts, family)) {
+ return { family: flipped, source: "base14" };
+ }
if (!fonts || fonts.length === 0) return NONE;
const device = deviceFaceFor(fonts, family, italic);
return device ? { family: device, source: "device" } : NONE;
}
+function hasExternalFamily(fonts: LocalFont[] | null, family: string): boolean {
+ if (!fonts || nearestStandardFont(family) === family) return false;
+ return knownFamilyOf(fonts, family) !== null;
+}
+
/** Whether every one of these runs can be flipped to the other italic state. */
export function canToggleItalic(
fontIds: string[],
- fonts: LocalFont[] | null = loadedLocalFonts(),
+ fonts: LocalFont[] | null = loadedExternalFonts(),
): boolean {
if (fontIds.length === 0) return false;
// Deduped: each miss costs a linear scan of every installed face, and a
@@ -104,9 +111,7 @@ export function canToggleItalic(
*/
export function fallbackFamilyFor(fontId: string): string {
const family = familyOf(fontId);
- // Readiness IS the opt-in: bytes only exist for a family the user has loaded
- // their device fonts for.
- if (family && getLocalFontBytes(family)) return family;
+ if (family && getExternalFontBytes(family)) return family;
return helveticaVariantFor(fontId);
}
@@ -117,7 +122,7 @@ export function fallbackFamilyFor(fontId: string): string {
* prefix is how {@link fallbackFamilyFor} recognises a face worth keeping.
*/
export function fallbackFontIdFor(family: string): string {
- return `${getLocalFontBytes(family) ? "device" : "base14"}:${family}`;
+ return `${getExternalFontBytes(family) ? "device" : "base14"}:${family}`;
}
/**
@@ -130,23 +135,27 @@ export function fallbackFontIdFor(family: string): string {
export async function warmDocumentDeviceFonts(
fontIds: Iterable<string>,
): Promise<string[]> {
- const fonts = loadedLocalFonts();
+ 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 || flipItalic(family, false)) continue;
+ 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 (getLocalFontBytes(family)) continue;
+ if (getExternalFontBytes(family)) continue;
if (pickLocalFontFace(fonts, family)) wanted.add(family);
}
const matched: string[] = [];
for (const family of wanted) {
- if (await loadLocalFontBytes(family)) matched.push(family);
+ if (await loadExternalFontBytes(family)) matched.push(family);
}
return matched;
}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/fontFamily.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/fontFamily.ts
index 4fbaf7a626..f68e4bd0a4 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/util/fontFamily.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/fontFamily.ts
@@ -15,6 +15,38 @@ export function familyOf(fontId: string): string {
return idx >= 0 ? fontId.slice(idx + 1) : fontId;
}
+/** Whether a fontId names a font carried by the PDF itself. */
+export function isDocumentFontId(fontId: string): boolean {
+ return fontId.startsWith("pdf:");
+}
+
+/** The PDFium font handle in a pdf:<ptr>:<family> fontId, or 0; valid while some object uses it. */
+export function documentFontHandle(fontId: string): number {
+ if (!isDocumentFontId(fontId)) return 0;
+ const n = Number(fontId.split(":")[1]);
+ return Number.isFinite(n) && n > 0 ? n : 0;
+}
+
+const DEVICE_FONT_PREFIX = "device:";
+const BASE14_FONT_PREFIX = "base14:";
+
+/** Whether a fontId names an installed or server font embedded by the editor. */
+export function isDeviceFontId(fontId: string): boolean {
+ return fontId.startsWith(DEVICE_FONT_PREFIX);
+}
+
+export function isBase14FontId(fontId: string): boolean {
+ return fontId.startsWith(BASE14_FONT_PREFIX);
+}
+
+export function deviceFontId(family: string): string {
+ return `${DEVICE_FONT_PREFIX}${family}`;
+}
+
+export function base14FontId(family: string): string {
+ return `${BASE14_FONT_PREFIX}${family}`;
+}
+
type Base14Root = "Helvetica" | "Times" | "Courier";
/** Which base-14 family a name belongs to, or null if it isn't base-14. */
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/helveticaVariant.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/helveticaVariant.ts
index b158e714c1..ab627434f4 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/util/helveticaVariant.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/helveticaVariant.ts
@@ -1,13 +1,14 @@
-const DEVICE_FONT_PREFIX = "device:";
+import {
+ familyOf,
+ isDeviceFontId,
+} from "@editor/tools/pdfTextEditor/util/fontFamily";
// Map a source font id to the base-14 family + style that best preserves its
// broad class.
export function helveticaVariantFor(fontId: string): string {
// A run already carrying an embedded device font keeps it; mapping to
// base-14 here is what reverted "Segoe UI" to Helvetica on the next edit.
- if (fontId.startsWith(DEVICE_FONT_PREFIX)) {
- return fontId.slice(DEVICE_FONT_PREFIX.length);
- }
+ if (isDeviceFontId(fontId)) return familyOf(fontId);
const bold = /bold|black|heavy/i.test(fontId);
const italic = /italic|oblique/i.test(fontId);
const mono = /mono|courier|consol/i.test(fontId);
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/localFonts.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/localFonts.ts
index 1906900af2..ce2d076c80 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/util/localFonts.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/localFonts.ts
@@ -1,11 +1,24 @@
// Local Font Access API wrapper. Chromium-only and permission-gated, so every
// entry point degrades to null instead of throwing.
+export interface FaceAxes {
+ bold: boolean;
+ italic: boolean;
+ weight: number | null;
+}
+
export interface LocalFont {
family: string;
fullName: string;
style: string;
postscriptName: string;
+ /** Style axes the font source states outright; absent for device faces, whose axes are read from the style name. */
+ axes?: FaceAxes;
+}
+
+export interface FontFamilyOption {
+ value: string;
+ label: string;
}
export interface LocalFontFamily {
@@ -110,6 +123,7 @@ export function resetLocalFontsCache(): void {
faceEntries = [];
resolved = null;
bytesByFamily.clear();
+ faceKeyByFamily.clear();
bytesPending.clear();
}
@@ -141,8 +155,36 @@ export function groupByFamily(fonts: LocalFont[]): LocalFontFamily[] {
return families;
}
+/** Picker options per family, plus a Bold entry where an upright bold cut exists; `taken` names are left out. */
+export function familyOptions(
+ fonts: LocalFont[] | null,
+ taken: string[],
+): FontFamilyOption[] {
+ if (!fonts) return [];
+ const hidden = new Set(taken.map(normaliseName));
+ const families = groupByFamily(fonts);
+ const listed = new Set([
+ ...hidden,
+ ...families.map(({ family }) => normaliseName(family)),
+ ]);
+ const withBold = new Set<string>();
+ for (const font of fonts) {
+ const flags = faceStyleFlags(font);
+ if (flags.bold && !flags.italic) withBold.add(normaliseName(font.family));
+ }
+ return families.flatMap(({ family }) => {
+ const key = normaliseName(family);
+ if (hidden.has(key)) return [];
+ const options = [{ value: family, label: family }];
+ if (withBold.has(key) && !listed.has(normaliseName(`${family} Bold`))) {
+ options.push({ value: `${family} Bold`, label: `${family} Bold` });
+ }
+ return options;
+ });
+}
+
/** Case/separator-insensitive key, so "Segoe-UI" and "Segoe UI" are one name. */
-function normaliseName(name: string): string {
+export function normaliseName(name: string): string {
return name
.trim()
.toLowerCase()
@@ -155,17 +197,47 @@ export interface RequestedFace {
italic: boolean;
}
+const STYLE_WORDS = /\b(bold|italic|oblique|regular|book|normal|roman)\b/gi;
+
+function styleAxes(text: string): { bold: boolean; italic: boolean } {
+ return {
+ bold: /\bbold\b/i.test(text),
+ italic: /\b(italic|oblique)\b/i.test(text),
+ };
+}
+
// Split a picker value into family plus style axes, so "Segoe UI Bold" finds
// "Segoe UI". A bare name yields the upright regular cut.
export function splitRequested(requested: string): RequestedFace {
const spaced = requested.trim().replace(/[_-]+/g, " ");
- const bold = /\bbold\b/i.test(spaced);
- const italic = /\b(italic|oblique)\b/i.test(spaced);
- const family = spaced
- .replace(/\b(bold|italic|oblique|regular|book|normal|roman)\b/gi, " ")
- .replace(/\s+/g, " ")
- .trim();
- return { family: family || spaced, bold, italic };
+ const family = spaced.replace(STYLE_WORDS, " ").replace(/\s+/g, " ").trim();
+ return { family: family || spaced, ...styleAxes(spaced) };
+}
+
+export function knownFamilyOf(
+ fonts: LocalFont[],
+ requested: string,
+): RequestedFace | null {
+ const name = normaliseName(requested);
+ let best: RequestedFace | null = null;
+ let bestLength = 0;
+ for (const font of fonts) {
+ const family = normaliseName(font.family);
+ if (!family || family.length <= bestLength) continue;
+ if (name !== family && !name.startsWith(`${family} `)) continue;
+ const rest = name.slice(family.length);
+ if (rest.replace(STYLE_WORDS, "").trim()) continue;
+ best = { family: font.family, ...styleAxes(rest) };
+ bestLength = family.length;
+ }
+ return best;
+}
+
+export function resolveRequested(
+ fonts: LocalFont[],
+ requested: string,
+): RequestedFace {
+ return knownFamilyOf(fonts, requested) ?? splitRequested(requested);
}
// The style words of a face. The family is excluded on purpose so a face of
@@ -186,6 +258,7 @@ export function faceStyleFlags(font: LocalFont): {
bold: boolean;
italic: boolean;
} {
+ if (font.axes) return { bold: font.axes.bold, italic: font.axes.italic };
const style = faceStyleText(font);
return {
bold: /bold|black|heavy|semib|demi/.test(style),
@@ -200,6 +273,7 @@ function scoreFace(
wantBold: boolean,
wantItalic: boolean,
): number {
+ if (font.axes) return scoreStatedAxes(font.axes, wantBold, wantItalic);
const style = faceStyleText(font);
const bold = /bold|black|heavy|semib|demi/.test(style);
const italic = /italic|oblique/.test(style);
@@ -212,29 +286,32 @@ function scoreFace(
return score - Math.min(style.length, 32) / 100;
}
+function scoreStatedAxes(
+ axes: FaceAxes,
+ wantBold: boolean,
+ wantItalic: boolean,
+): number {
+ let score = 0;
+ if (axes.bold === wantBold) score += 4;
+ if (axes.italic === wantItalic) score += 4;
+ const target = wantBold ? 700 : 400;
+ const weight = axes.weight ?? (axes.bold ? 700 : 400);
+ return score - Math.min(Math.abs(weight - target), 900) / 1000;
+}
+
// The installed face best answering a family name, or null. An exact family
// hit wins, so "Arial Black" is not read as a bold cut of "Arial".
export function pickLocalFontFace(
fonts: LocalFont[],
requested: string,
): LocalFont | null {
- const wanted = splitRequested(requested);
- const exact = fonts.filter(
- (font) => normaliseName(font.family) === normaliseName(requested),
- );
- const group =
- exact.length > 0
- ? exact
- : fonts.filter(
- (font) => normaliseName(font.family) === normaliseName(wanted.family),
- );
- if (group.length === 0) return null;
- const wantBold = exact.length > 0 ? false : wanted.bold;
- const wantItalic = exact.length > 0 ? false : wanted.italic;
+ const wanted = resolveRequested(fonts, requested);
+ const family = normaliseName(wanted.family);
let best: LocalFont | null = null;
let bestScore = Number.NEGATIVE_INFINITY;
- for (const font of group) {
- const score = scoreFace(font, wantBold, wantItalic);
+ for (const font of fonts) {
+ if (normaliseName(font.family) !== family) continue;
+ const score = scoreFace(font, wanted.bold, wanted.italic);
if (score > bestScore) {
best = font;
bestScore = score;
@@ -268,6 +345,7 @@ async function readFaceBytes(source: unknown): Promise<Uint8Array | null> {
}
const bytesByFamily = new Map<string, Uint8Array>();
+const faceKeyByFamily = new Map<string, string>();
const bytesPending = new Map<string, Promise<Uint8Array | null>>();
/** Already-read bytes for a family, or null. Never prompts, never awaits. */
@@ -275,6 +353,11 @@ export function getLocalFontBytes(family: string): Uint8Array | null {
return bytesByFamily.get(normaliseName(family)) ?? null;
}
+/** Which installed face the bytes for `family` were read from, or null. */
+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(
@@ -293,7 +376,10 @@ export async function loadLocalFontBytes(
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);
+ if (bytes) {
+ bytesByFamily.set(key, bytes);
+ faceKeyByFamily.set(key, picked.postscriptName || picked.fullName);
+ }
return bytes;
})();
bytesPending.set(key, job);
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/pageFonts.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/pageFonts.ts
index 88e4eb9dea..7bd62d86fb 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/util/pageFonts.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/pageFonts.ts
@@ -1,5 +1,12 @@
import type { PageSnapshot } from "@editor/tools/pdfTextEditor/types";
import { getCachedFontGlyphMap } from "@editor/tools/pdfTextEditor/charcode/CmapResolver";
+import {
+ documentFontHandle,
+ familyOf,
+ isBase14FontId,
+ isDeviceFontId,
+} from "@editor/tools/pdfTextEditor/util/fontFamily";
+import { deviceFontCoverage } from "@editor/tools/pdfTextEditor/util/deviceFontEmbed";
// Editability status of a font as the PDF text editor can determine it purely
// client-side (from PDFium), without the backend JSON font model.
@@ -40,18 +47,17 @@ export function missingAlnumFromCmap(cmap: Map<number, number>): string[] {
return out;
}
-/** Parse the live PDFium font handle out of a `pdf:<ptr>:<family>` fontId. */
-function fontHandleOf(fontId: string): number {
- if (!fontId.startsWith("pdf:")) return 0;
- const n = Number(fontId.split(":")[1]);
- return Number.isFinite(n) && n > 0 ? n : 0;
-}
-
/** a-zA-Z0-9 coverage for a font, from the loader-primed cache (no WASM). */
-function coverageFor(fontId: string, status: FontStatus): GlyphCoverage {
+export function coverageFor(fontId: string, status: FontStatus): GlyphCoverage {
// Base-14 fonts carry the whole standard set - always full, no cmap needed.
if (status === "standard") return { known: true, missing: [] };
- const handle = fontHandleOf(fontId);
+ if (isDeviceFontId(fontId)) {
+ const coverage = deviceFontCoverage(familyOf(fontId));
+ return coverage
+ ? { known: true, missing: missingAlnumFromCmap(coverage) }
+ : { known: false, missing: [] };
+ }
+ const handle = documentFontHandle(fontId);
if (!handle) return { known: false, missing: [] };
const cmap = getCachedFontGlyphMap(handle);
if (!cmap || cmap.size === 0) return { known: false, missing: [] };
@@ -74,13 +80,6 @@ const STANDARD_14 = [
// (e.g. "Helvetica-BoldOblique", "ArialMT", "Times-Roman").
const BASE14_STYLE_SUFFIX = /^(bold|italic|oblique|regular|roman|mt|ps)+$/;
-/** Pull the readable family from a fontId (`pdf:<ptr>:<family>` or `base14:<name>`). */
-function familyOf(fontId: string): string {
- if (fontId.startsWith("base14:")) return fontId.slice("base14:".length);
- const parts = fontId.split(":");
- return parts.length >= 3 ? parts.slice(2).join(":") : fontId;
-}
-
/** Subset fonts carry a 6-letter "ABCDEF+" tag; strip it for display. */
function stripSubsetTag(name: string): string {
return name.replace(/^[A-Z]{6}\+/, "");
@@ -130,7 +129,10 @@ export function analyzePageFonts(pages: PageSnapshot[]): PageFont[] {
for (const run of page.runs) {
const name = stripSubsetTag(familyOf(run.fontId)) || "Unknown font";
let status: FontStatus;
- if (run.fontId.startsWith("base14:") || isStandard14(run.fontId)) {
+ if (
+ isBase14FontId(run.fontId) ||
+ (!isDeviceFontId(run.fontId) && isStandard14(run.fontId))
+ ) {
status = "standard";
} else if (run.fontSubset) {
status = "subset";
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/selectedFontNote.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/selectedFontNote.ts
new file mode 100644
index 0000000000..bbfba61b27
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/selectedFontNote.ts
@@ -0,0 +1,137 @@
+import {
+ RENDER_MODE_INVISIBLE,
+ type PageSnapshot,
+} from "@editor/tools/pdfTextEditor/types";
+import {
+ analyzePageFonts,
+ coverageFor,
+ missingAlnumFromCmap,
+ type FontStatus,
+ type GlyphCoverage,
+} from "@editor/tools/pdfTextEditor/util/pageFonts";
+import {
+ deviceFontCoverage,
+ visibleCodePoints,
+} from "@editor/tools/pdfTextEditor/util/deviceFontEmbed";
+import {
+ familyOf,
+ isDeviceFontId,
+ nearestStandardFont,
+} from "@editor/tools/pdfTextEditor/util/fontFamily";
+
+const MAX_LISTED_GLYPHS = 6;
+const PDF_FONT_FALLBACK = "Helvetica";
+
+export type SelectedFontNote =
+ | { kind: "scanned" }
+ | { kind: "embeddedUnknown" }
+ | { kind: "gap"; name: string; glyphs: string; fallback: string }
+ | { kind: "deviceUnknown"; name: string; fallback: string };
+
+interface SelectedRuns {
+ fontIds: Set<string>;
+ text: string;
+ scanned: number;
+}
+
+function collectSelectedRuns(
+ pages: PageSnapshot[],
+ runIds: string[],
+): SelectedRuns {
+ const picked = new Set(runIds);
+ const fontIds = 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);
+ text += run.text;
+ if (run.renderMode === RENDER_MODE_INVISIBLE) scanned++;
+ }
+ return { fontIds, text, scanned };
+}
+
+function standardFallbackName(family: string): string {
+ return nearestStandardFont(family).split("-")[0];
+}
+
+function missingFromCoverage(
+ coverage: Map<number, number>,
+ text: string,
+): string[] {
+ const missing = new Set<string>();
+ for (const cp of visibleCodePoints(text))
+ if (!coverage.has(cp)) missing.add(String.fromCodePoint(cp));
+ for (const ch of missingAlnumFromCmap(coverage)) missing.add(ch);
+ return [...missing];
+}
+
+function deviceFontNote(family: string, text: string): SelectedFontNote | null {
+ const fallback = standardFallbackName(family);
+ const coverage = deviceFontCoverage(family);
+ if (!coverage) return { kind: "deviceUnknown", name: family, fallback };
+ const missing = missingFromCoverage(coverage, text);
+ if (missing.length === 0) return null;
+ return {
+ kind: "gap",
+ name: family,
+ glyphs: missing.slice(0, MAX_LISTED_GLYPHS).join(" "),
+ fallback,
+ };
+}
+
+// analyzePageFonts merges same-named fonts, device faces included, so read each selected font's own coverage.
+function selectedCoverage(
+ fontIds: Set<string>,
+ status: FontStatus,
+): GlyphCoverage {
+ const missing = new Set<string>();
+ let known = true;
+ for (const id of fontIds) {
+ const coverage = coverageFor(id, status);
+ known &&= coverage.known;
+ for (const ch of coverage.missing) missing.add(ch);
+ }
+ return { known, missing: [...missing] };
+}
+
+function documentFontNote(
+ pages: PageSnapshot[],
+ fontIds: Set<string>,
+): 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;
+ if (gaps.length > 0) {
+ return {
+ kind: "gap",
+ name: font.name,
+ glyphs: gaps.slice(0, MAX_LISTED_GLYPHS).join(" "),
+ fallback: PDF_FONT_FALLBACK,
+ };
+ }
+ if (font.status === "standard" || coverage.known) return null;
+ return { kind: "embeddedUnknown" };
+}
+
+export function selectedFontNote(
+ pages: PageSnapshot[],
+ runIds: string[],
+): SelectedFontNote | null {
+ if (runIds.length === 0) return null;
+ const { fontIds, text, scanned } = collectSelectedRuns(pages, runIds);
+ if (fontIds.size === 0) return null;
+ if (scanned === runIds.length) return { kind: "scanned" };
+ const ids = [...fontIds];
+ if (ids.every(isDeviceFontId)) {
+ const families = [...new Set(ids.map(familyOf))];
+ return families.length === 1 ? deviceFontNote(families[0], text) : null;
+ }
+ if (ids.some(isDeviceFontId)) return null;
+ return documentFontNote(pages, fontIds);
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/serverFonts.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/serverFonts.ts
new file mode 100644
index 0000000000..1054d9cbdb
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/serverFonts.ts
@@ -0,0 +1,322 @@
+import apiClient from "@editor/services/apiClient";
+import {
+ normaliseName,
+ pickLocalFontFace,
+ type LocalFont,
+} from "@editor/tools/pdfTextEditor/util/localFonts";
+
+export const SERVER_FONTS_URL = "/api/v1/ui-data/editor-fonts";
+
+export interface ServerFontFace {
+ id: string;
+ style: string;
+ bold: boolean;
+ italic: boolean;
+ weight: number | null;
+ postscriptName: string;
+}
+
+interface ServerFontFamily {
+ family: string;
+ faces: ServerFontFace[];
+}
+
+const FONT_ID = /^[0-9a-f]{64}$/;
+export const SERVER_FONTS_REFRESH_MS = 30_000;
+const FACE_DOWNLOAD_ATTEMPTS = 2;
+
+let resolved: LocalFont[] | null = null;
+let manifestPending: Promise<LocalFont[] | null> | null = null;
+let refreshPending: Promise<void> | null = null;
+let publishedManifest = "";
+let fetchedAt = 0;
+let generation = 0;
+let faceByFont = new Map<LocalFont, ServerFontFace>();
+const listeners = new Set<() => void>();
+const bytesListeners = new Set<() => void>();
+let bytesVersion = 0;
+const bytesByFaceId = new Map<string, Uint8Array>();
+const faceIdByName = new Map<string, string>();
+const bytesPending = new Map<string, Promise<Uint8Array | null>>();
+const facePending = new Map<string, Promise<Uint8Array | null>>();
+const cssFacesRegistered = new Map<string, FontFace>();
+
+function readFace(value: unknown): ServerFontFace | null {
+ if (!value || typeof value !== "object") return null;
+ const face = value as Record<string, unknown>;
+ if (typeof face.id !== "string" || !FONT_ID.test(face.id)) return null;
+ return {
+ id: face.id,
+ style: typeof face.style === "string" ? face.style.trim() : "",
+ bold: face.bold === true,
+ italic: face.italic === true,
+ weight:
+ typeof face.weight === "number" && Number.isFinite(face.weight)
+ ? face.weight
+ : null,
+ postscriptName:
+ typeof face.postscriptName === "string" ? face.postscriptName : "",
+ };
+}
+
+function readFamilies(data: unknown): ServerFontFamily[] {
+ if (!data || typeof data !== "object") return [];
+ const families = (data as { families?: unknown }).families;
+ if (!Array.isArray(families)) return [];
+ const out: ServerFontFamily[] = [];
+ for (const entry of families) {
+ if (!entry || typeof entry !== "object") continue;
+ const raw = entry as { family?: unknown; faces?: unknown };
+ if (typeof raw.family !== "string" || !raw.family.trim()) continue;
+ if (!Array.isArray(raw.faces)) continue;
+ const faces = raw.faces
+ .map(readFace)
+ .filter((face): face is ServerFontFace => face !== null);
+ if (faces.length > 0) out.push({ family: raw.family.trim(), faces });
+ }
+ return out;
+}
+
+function publish(families: ServerFontFamily[]): LocalFont[] {
+ publishedManifest = JSON.stringify(families);
+ const fonts: LocalFont[] = [];
+ const byFont = new Map<LocalFont, ServerFontFace>();
+ for (const { family, faces } of families) {
+ for (const face of faces) {
+ const font: LocalFont = {
+ family,
+ fullName: face.style ? `${family} ${face.style}` : family,
+ style: face.style,
+ postscriptName: face.postscriptName,
+ axes: { bold: face.bold, italic: face.italic, weight: face.weight },
+ };
+ fonts.push(font);
+ byFont.set(font, face);
+ }
+ }
+ faceByFont = byFont;
+ resolved = fonts;
+ forgetFaceBindings(new Set([...byFont.values()].map((face) => face.id)));
+ notifyListeners();
+ return fonts;
+}
+
+function forgetFaceBindings(listed: Set<string>): void {
+ for (const [name, id] of faceIdByName) {
+ if (serverFaceFor(name)?.id !== id) faceIdByName.delete(name);
+ }
+ bytesPending.clear();
+ for (const id of bytesByFaceId.keys()) {
+ if (!listed.has(id)) bytesByFaceId.delete(id);
+ }
+}
+
+function notifyListeners(): void {
+ for (const listener of [...listeners]) listener();
+}
+
+function notifyBytesChanged(): void {
+ bytesVersion++;
+ for (const listener of [...bytesListeners]) listener();
+}
+
+async function fetchManifest(): Promise<ServerFontFamily[] | null> {
+ try {
+ const res = await apiClient.get<unknown>(SERVER_FONTS_URL, {
+ suppressErrorToast: true,
+ });
+ return readFamilies(res.data);
+ } catch {
+ return null;
+ }
+}
+
+function refreshManifest(): void {
+ if (refreshPending) return;
+ const started = generation;
+ fetchedAt = Date.now();
+ const job = fetchManifest().then((families) => {
+ if (refreshPending === job) refreshPending = null;
+ if (started !== generation || !families) return;
+ if (JSON.stringify(families) !== publishedManifest) publish(families);
+ });
+ refreshPending = job;
+}
+
+export function loadServerFonts(): Promise<LocalFont[] | null> {
+ if (resolved) {
+ if (Date.now() - fetchedAt >= SERVER_FONTS_REFRESH_MS) refreshManifest();
+ return Promise.resolve(resolved);
+ }
+ if (!manifestPending) {
+ const started = generation;
+ fetchedAt = Date.now();
+ manifestPending = fetchManifest().then((families) => {
+ if (started !== generation) return null;
+ if (families) return publish(families);
+ manifestPending = null;
+ return null;
+ });
+ }
+ return manifestPending;
+}
+
+function documentFonts(): FontFaceSet | null {
+ if (typeof document === "undefined") return null;
+ return (document as Document & { fonts?: FontFaceSet }).fonts ?? null;
+}
+
+export function forgetServerFontList(): void {
+ generation++;
+ resolved = null;
+ manifestPending = null;
+ refreshPending = null;
+ publishedManifest = "";
+ fetchedAt = 0;
+ faceByFont = new Map();
+ bytesByFaceId.clear();
+ faceIdByName.clear();
+ bytesPending.clear();
+ facePending.clear();
+ const fonts = documentFonts();
+ for (const css of cssFacesRegistered.values()) fonts?.delete(css);
+ cssFacesRegistered.clear();
+ notifyListeners();
+ notifyBytesChanged();
+}
+
+export function loadedServerFonts(): LocalFont[] | null {
+ return resolved;
+}
+
+export function subscribeServerFonts(listener: () => void): () => void {
+ listeners.add(listener);
+ return () => listeners.delete(listener);
+}
+
+/** Fires when a requested name gains or loses readable face bytes, which {@link subscribeServerFonts} does not report. */
+export function subscribeServerFontBytes(listener: () => void): () => void {
+ bytesListeners.add(listener);
+ return () => bytesListeners.delete(listener);
+}
+
+export function serverFontBytesVersion(): number {
+ return bytesVersion;
+}
+
+export function serverFaceFor(requested: string): ServerFontFace | null {
+ if (!resolved || resolved.length === 0) return null;
+ const font = pickLocalFontFace(resolved, requested);
+ return font ? (faceByFont.get(font) ?? null) : null;
+}
+
+export function getServerFaceId(requested: string): string | null {
+ return faceIdByName.get(normaliseName(requested)) ?? null;
+}
+
+export function getServerFontBytes(requested: string): Uint8Array | null {
+ const id = getServerFaceId(requested);
+ return id ? (bytesByFaceId.get(id) ?? null) : null;
+}
+
+function cssFamilyForFace(id: string): string {
+ return `serverface-${id}`;
+}
+
+export function serverFontCssFamily(requested: string): string | null {
+ const id = getServerFaceId(requested);
+ return id && cssFacesRegistered.has(id) ? cssFamilyForFace(id) : null;
+}
+
+function shared<T>(
+ pending: Map<string, Promise<T>>,
+ key: string,
+ run: () => Promise<T>,
+): Promise<T> {
+ const inFlight = pending.get(key);
+ if (inFlight) return inFlight;
+ const job = run().finally(() => {
+ if (pending.get(key) === job) pending.delete(key);
+ });
+ pending.set(key, job);
+ return job;
+}
+
+function fetchFaceBytes(id: string): Promise<Uint8Array | null> {
+ const cached = bytesByFaceId.get(id);
+ if (cached) return Promise.resolve(cached);
+ return shared(facePending, id, () => downloadFace(id));
+}
+
+async function downloadFace(id: string): Promise<Uint8Array | null> {
+ const started = generation;
+ for (let attempt = 0; attempt < FACE_DOWNLOAD_ATTEMPTS; attempt++) {
+ try {
+ const res = await apiClient.get<ArrayBuffer>(
+ `${SERVER_FONTS_URL}/${id}`,
+ {
+ responseType: "arraybuffer",
+ suppressErrorToast: true,
+ },
+ );
+ if (started !== generation) return null;
+ const bytes = new Uint8Array(res.data);
+ if (bytes.length > 0) {
+ bytesByFaceId.set(id, bytes);
+ return bytes;
+ }
+ } catch {
+ continue;
+ }
+ }
+ if (started === generation) fetchedAt = 0;
+ return null;
+}
+
+async function registerCssFace(
+ face: ServerFontFace,
+ bytes: Uint8Array,
+): Promise<void> {
+ if (cssFacesRegistered.has(face.id)) return;
+ if (typeof FontFace === "undefined") return;
+ const fonts = documentFonts();
+ if (!fonts) return;
+ const started = generation;
+ try {
+ const css = new FontFace(cssFamilyForFace(face.id), bytes.slice(), {
+ style: face.italic ? "italic" : "normal",
+ weight: "1 1000",
+ });
+ await css.load();
+ if (started !== generation || cssFacesRegistered.has(face.id)) return;
+ fonts.add(css);
+ cssFacesRegistered.set(face.id, css);
+ } catch {
+ return;
+ }
+}
+
+export async function loadServerFontBytes(
+ requested: string,
+): Promise<Uint8Array | null> {
+ const key = normaliseName(requested);
+ if (!key) return null;
+ const cached = getServerFontBytes(requested);
+ if (cached) return cached;
+ return shared(bytesPending, key, async () => {
+ const started = generation;
+ await loadServerFonts();
+ if (started !== generation) return null;
+ const face = serverFaceFor(requested);
+ if (!face) return null;
+ const bytes = await fetchFaceBytes(face.id);
+ if (!bytes || started !== generation) return null;
+ await registerCssFace(face, bytes);
+ if (started !== generation) return null;
+ if (serverFaceFor(requested)?.id === face.id) {
+ faceIdByName.set(key, face.id);
+ notifyBytesChanged();
+ }
+ return bytes;
+ });
+}
diff --git a/frontend/src/editor/desktop/components/DesktopQueryCacheReset.test.tsx b/frontend/src/editor/desktop/components/DesktopQueryCacheReset.test.tsx
index a104ebd905..c6fe160828 100644
--- a/frontend/src/editor/desktop/components/DesktopQueryCacheReset.test.tsx
+++ b/frontend/src/editor/desktop/components/DesktopQueryCacheReset.test.tsx
@@ -32,6 +32,13 @@ vi.mock("@editor/services/selfHostedServerMonitor", () => ({
},
}));
+const { forgetServerFontList } = vi.hoisted(() => ({
+ forgetServerFontList: vi.fn(),
+}));
+vi.mock("@editor/tools/pdfTextEditor/util/serverFonts", () => ({
+ forgetServerFontList,
+}));
+
function renderWithConsumer(queryFn: () => Promise<string>) {
const client = new QueryClient({
defaultOptions: { queries: { retry: false, staleTime: Infinity } },
@@ -57,6 +64,21 @@ describe("DesktopQueryCacheReset", () => {
beforeEach(() => {
modeListeners.clear();
serverListeners.clear();
+ forgetServerFontList.mockClear();
+ });
+
+ it("forgets the editor's server font list when the backend changes", async () => {
+ const queryFn = vi.fn<() => Promise<string>>().mockResolvedValue("x");
+
+ renderWithConsumer(queryFn);
+ await waitFor(() => expect(queryFn).toHaveBeenCalledTimes(1));
+ expect(forgetServerFontList).not.toHaveBeenCalled();
+
+ modeListeners.forEach((l) => l({ mode: "selfhosted" }));
+ expect(forgetServerFontList).toHaveBeenCalledTimes(1);
+
+ serverListeners.forEach((l) => l({ status: "offline" }));
+ expect(forgetServerFontList).toHaveBeenCalledTimes(2);
});
it("refetches a mounted query when the connection mode changes", async () => {
diff --git a/frontend/src/editor/desktop/components/DesktopQueryCacheReset.tsx b/frontend/src/editor/desktop/components/DesktopQueryCacheReset.tsx
index dac74e323f..8c5daec298 100644
--- a/frontend/src/editor/desktop/components/DesktopQueryCacheReset.tsx
+++ b/frontend/src/editor/desktop/components/DesktopQueryCacheReset.tsx
@@ -4,6 +4,7 @@ import { connectionModeService } from "@editor/services/connectionModeService";
import { selfHostedServerMonitor } from "@editor/services/selfHostedServerMonitor";
import { clearPolicies } from "@editor/services/policyStorage";
import { resetPolicyRuns } from "@editor/components/policies/policyRunStore";
+import { forgetServerFontList } from "@editor/tools/pdfTextEditor/util/serverFonts";
/**
* Drops cached responses when the backend behind them changes. operationRouter
@@ -16,7 +17,10 @@ export function DesktopQueryCacheReset() {
useEffect(() => {
// resetQueries, not clear(): clear() evicts without notifying mounted
// observers, so a panel keeps rendering the old backend's answer.
- const reset = () => void queryClient.resetQueries();
+ const reset = () => {
+ forgetServerFontList();
+ void queryClient.resetQueries();
+ };
const unsubscribeMode = connectionModeService.subscribeToModeChanges(() => {
clearPolicies();
resetPolicyRuns();