#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere
TypeScript dockerhacktoberfestjavapdfpdf-converterpdf-editorpdf-manipulationpdf-mergerpdf-ocrpdf-toolspdf-web-appspdfmergerself-hosted
chore: remove deprecated backend PDF text editing and Type3 font cache (#8504)
brios459e20d164a4
diff --git a/.github/config/.files.yaml b/.github/config/.files.yamlindex 106110134f..c09cda6ae5 100644--- a/.github/config/.files.yaml+++ b/.github/config/.files.yaml@@ -89,13 +89,7 @@ frontend: &frontend- docker/**- scripts/translations/*.py- .taskfiles/desktop.yml- - scripts/convert_cff_to_ttf.py- - scripts/harvest_type3_fonts.py- scripts/ignore_translation.toml- - scripts/index_type3_catalogue.py- - scripts/summarize_type3_signatures.py- - scripts/type3_to_cff.py- - scripts/update_type3_library.py- Taskfile.yml- .taskfiles/frontend.yml- .taskfiles/e2e.ymldiff --git a/.gitignore b/.gitignoreindex 655a0c109e..d584b11df4 100644--- a/.gitignore+++ b/.gitignore@@ -296,13 +296,6 @@ scripts/pdf-collection/**/tmp/*.backup-# Type3 development data-docs/type3/signatures/---# Type3 sample PDFs (development only)-**/type3/samples/-**/application-dev-local.properties# Claude. Contents are ignored so personal config stays local, with the twodiff --git a/app/common/src/main/java/stirling/software/SPDF/config/EndpointConfiguration.java b/app/common/src/main/java/stirling/software/SPDF/config/EndpointConfiguration.javaindex 8aaeba37e8..7789d2b1ee 100644--- a/app/common/src/main/java/stirling/software/SPDF/config/EndpointConfiguration.java+++ b/app/common/src/main/java/stirling/software/SPDF/config/EndpointConfiguration.java@@ -428,7 +428,6 @@ public class EndpointConfiguration {addEndpointToGroup("Other", "extract-single-attachment");addEndpointToGroup("Other", "replace-invert-pdf");addEndpointToGroup("Other", "edit-table-of-contents");- addEndpointToGroup("Other", "text-editor-pdf");// Backend-only endpoints (not in frontend tool registry endpoints)addEndpointToGroup("Other", "add-image");addEndpointToGroup("Other", "compare");@@ -561,7 +560,6 @@ public class EndpointConfiguration {addEndpointToGroup("Java", "flatten");addEndpointToGroup("Java", "unlock-pdf-forms");addEndpointToGroup("Java", "validate-signature");- addEndpointToGroup("Java", "text-editor-pdf");addEndpointToGroup("Java", "edit-table-of-contents");addEndpointToGroup("Java", "pdf-to-epub");addEndpointToGroup("Java", "eml-to-pdf");@@ -574,7 +572,6 @@ public class EndpointConfiguration {addEndpointToGroup("Javascript", "sign");addEndpointToGroup("Javascript", "compare");addEndpointToGroup("Javascript", "adjust-contrast");- addEndpointToGroup("Javascript", "text-editor-pdf");/* qpdf */addEndpointToGroup("qpdf", "repair");diff --git a/app/common/src/main/java/stirling/software/common/annotations/api/ConvertApi.java b/app/common/src/main/java/stirling/software/common/annotations/api/ConvertApi.javaindex b3202ad3c7..a065f89bd7 100644--- a/app/common/src/main/java/stirling/software/common/annotations/api/ConvertApi.java+++ b/app/common/src/main/java/stirling/software/common/annotations/api/ConvertApi.java@@ -23,7 +23,6 @@ import io.swagger.v3.oas.annotations.tags.Tag;description ="""Convert PDFs to and from other formats (Word, images, HTML, Markdown, PDF/A, CBZ/CBR, EML, etc.).- This group also powers the text-editor / jobId-based editing flow for incremental PDF edits.Typical uses:• Turn PDFs into Word or text for editingdiff --git a/app/common/src/main/java/stirling/software/common/model/ApplicationProperties.java b/app/common/src/main/java/stirling/software/common/model/ApplicationProperties.javaindex a64c5334ee..b4a88c850d 100644--- a/app/common/src/main/java/stirling/software/common/model/ApplicationProperties.java+++ b/app/common/src/main/java/stirling/software/common/model/ApplicationProperties.java@@ -78,7 +78,6 @@ public class ApplicationProperties {private AutoPipeline autoPipeline = new AutoPipeline();private ProcessExecutor processExecutor = new ProcessExecutor();- private PdfEditor pdfEditor = new PdfEditor();private AiEngine aiEngine = new AiEngine();private FormDetection formDetection = new FormDetection();private Docparse docparse = new Docparse();@@ -330,46 +329,6 @@ public class ApplicationProperties {private long webhookMaxBytes = 104857600L;}- @Data- public static class PdfEditor {- private Cache cache = new Cache();- private FontNormalization fontNormalization = new FontNormalization();- private CffConverter cffConverter = new CffConverter();- private Type3 type3 = new Type3();- private String fallbackFont = "classpath:/static/fonts/NotoSans-Regular.ttf";-- @Data- public static class Cache {- private long maxBytes = -1;- private int maxPercent = 20;- }-- @Data- public static class FontNormalization {- private boolean enabled = false;- }-- @Data- public static class CffConverter {- private boolean enabled = true;- private String method = "python";- private String pythonCommand = "/opt/venv/bin/python3";- private String pythonScript = "/scripts/convert_cff_to_ttf.py";- private String fontforgeCommand = "fontforge";- }-- @Data- public static class Type3 {- private Library library = new Library();-- @Data- public static class Library {- private boolean enabled = true;- private String index = "classpath:/type3/library/index.json";- }- }- }-@Datapublic static class AiEngine {private boolean enabled = false;diff --git a/app/common/src/main/java/stirling/software/common/model/api/general/EditTextOperation.java b/app/common/src/main/java/stirling/software/common/model/api/general/EditTextOperation.javadeleted file mode 100644index 76815c5fbc..0000000000--- a/app/common/src/main/java/stirling/software/common/model/api/general/EditTextOperation.java+++ /dev/null@@ -1,19 +0,0 @@-package stirling.software.common.model.api.general;--import io.swagger.v3.oas.annotations.media.Schema;--import lombok.Data;-import lombok.EqualsAndHashCode;--@Data-@EqualsAndHashCode-public class EditTextOperation {-- @Schema(description = "The literal text to find.", requiredMode = Schema.RequiredMode.REQUIRED)- private String find;-- @Schema(- description = "The replacement text. May be empty to delete the matched text.",- requiredMode = Schema.RequiredMode.REQUIRED)- private String replace;-}diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/EditTextController.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/EditTextController.javadeleted file mode 100644index b76f52144a..0000000000--- a/app/core/src/main/java/stirling/software/SPDF/controller/api/EditTextController.java+++ /dev/null@@ -1,340 +0,0 @@-package stirling.software.SPDF.controller.api;--import java.io.OutputStream;-import java.nio.file.Files;-import java.util.ArrayList;-import java.util.Collections;-import java.util.HashSet;-import java.util.List;-import java.util.Objects;-import java.util.Set;-import java.util.regex.Matcher;-import java.util.regex.Pattern;--import org.springframework.core.io.Resource;-import org.springframework.http.ResponseEntity;-import org.springframework.web.bind.WebDataBinder;-import org.springframework.web.bind.annotation.InitBinder;-import org.springframework.web.bind.annotation.ModelAttribute;-import org.springframework.web.multipart.MultipartFile;--import io.github.pixee.security.Filenames;-import io.swagger.v3.oas.annotations.Operation;--import lombok.RequiredArgsConstructor;-import lombok.extern.slf4j.Slf4j;--import stirling.software.SPDF.config.swagger.StandardPdfResponse;-import stirling.software.SPDF.model.api.general.EditTextRequest;-import stirling.software.SPDF.model.json.PdfJsonDocument;-import stirling.software.SPDF.model.json.PdfJsonPage;-import stirling.software.SPDF.model.json.PdfJsonTextElement;-import stirling.software.SPDF.service.PdfJsonConversionService;-import stirling.software.common.annotations.AutoJobPostMapping;-import stirling.software.common.annotations.api.GeneralApi;-import stirling.software.common.enumeration.ResourceWeight;-import stirling.software.common.model.api.general.EditTextOperation;-import stirling.software.common.model.tool.ToolFormat;-import stirling.software.common.model.tool.ToolIO;-import stirling.software.common.util.ExceptionUtils;-import stirling.software.common.util.GeneralUtils;-import stirling.software.common.util.TempFile;-import stirling.software.common.util.TempFileManager;-import stirling.software.common.util.WebResponseUtils;-import stirling.software.common.util.propertyeditor.JsonListPropertyEditor;--import tools.jackson.core.type.TypeReference;--/**- * Find/replace text editing for PDFs. Round-trips through {@link PdfJsonConversionService}: the- * input PDF is parsed into the editable JSON model, find/replace operations are applied to the- * {@code text} field of each text element, and the mutated model is rebuilt into a PDF.- *- * <p>Matching joins all text elements on a page into a single string before searching, so find- * strings can span multiple visual runs (titles split per word, kerning-broken phrases, etc.).- *- * <p>For cross-element matches the entire replacement is written into the first matched element,- * any intermediate elements are emptied, and the suffix of the last matched element is preserved.- * This anchors the new text at the leftmost match position and lets the font lay it out as one run,- * which is more visually reliable than redistributing words to the original per-element X positions- * (those positions are calibrated to the original word widths and rarely match the replacement- * widths). Centered or tracked layouts will become left-aligned at the original first-word position- * when their text is replaced - the trade-off is accepted in favour of avoiding glyph overlaps and- * gaps from variable-width word distribution.- */-@Slf4j-@GeneralApi-@RequiredArgsConstructor-public class EditTextController {-- private static final Pattern FILE_EXTENSION_PATTERN = Pattern.compile("[.][^.]+$");-- private final PdfJsonConversionService pdfJsonConversionService;- private final TempFileManager tempFileManager;-- @InitBinder- public void initBinder(WebDataBinder binder) {- binder.registerCustomEditor(- List.class,- "edits",- new JsonListPropertyEditor<>(new TypeReference<List<EditTextOperation>>() {}));- }-- @AutoJobPostMapping(- consumes = "multipart/form-data",- value = "/edit-text",- resourceWeight = ResourceWeight.LARGE_WEIGHT)- @StandardPdfResponse- @ToolIO(produces = ToolFormat.PDF)- @Operation(- summary = "Edit text in a PDF via find and replace",- description =- "Applies an ordered list of find/replace operations to the text in a PDF and"- + " returns the edited PDF. Useful for find-and-replace, bulk renames (e.g."- + " updating a company name throughout a document), and copy editing where the AI"- + " agent has identified specific replacements. Matching is performed against the"- + " joined text of each page, so find strings can span multiple visual runs"- + " (titles split per word, kerning-broken phrases). Cross-element matches are"- + " written as a single replacement run anchored at the leftmost matched position;"- + " centered or tracked text may shift left when its content changes.")- public ResponseEntity<Resource> editText(@ModelAttribute EditTextRequest request)- throws Exception {- MultipartFile inputFile = request.getFileInput();- if (inputFile == null) {- throw ExceptionUtils.createFileNullOrEmptyException();- }- List<EditTextOperation> edits = request.getEdits();- if (edits == null || edits.isEmpty()) {- throw ExceptionUtils.createIllegalArgumentException(- "error.editText.no.edits",- "No find/replace operations provided for text editing");- }- for (EditTextOperation edit : edits) {- if (edit == null || edit.getFind() == null || edit.getFind().isEmpty()) {- throw ExceptionUtils.createIllegalArgumentException(- "error.editText.empty.find", "Each edit must have a non-empty find string");- }- }-- boolean wholeWordSearch = Boolean.TRUE.equals(request.getWholeWordSearch());- List<CompiledEdit> compiledEdits = compileEdits(edits, wholeWordSearch);-- PdfJsonDocument document = pdfJsonConversionService.convertPdfToJsonDocument(inputFile);- Set<Integer> pageFilter = resolvePageFilter(request, document);- int modifiedSpans = applyEdits(document, compiledEdits, pageFilter);- log.info(- "edit-text: modified {} text span(s) using {} edit(s) on {} page(s)",- modifiedSpans,- compiledEdits.size(),- pageFilter == null- ? document.getPages() == null ? 0 : document.getPages().size()- : pageFilter.size());-- String docName = buildOutputFilename(inputFile);- TempFile tempOut = tempFileManager.createManagedTempFile(".pdf");- try (OutputStream os = Files.newOutputStream(tempOut.getPath())) {- pdfJsonConversionService.convertJsonToPdf(document, os);- } catch (Exception e) {- tempOut.close();- throw e;- }- return WebResponseUtils.pdfFileToWebResponse(tempOut, docName);- }-- private List<CompiledEdit> compileEdits(- List<EditTextOperation> edits, boolean wholeWordSearch) {- return edits.stream().map(edit -> compileEdit(edit, wholeWordSearch)).toList();- }-- private CompiledEdit compileEdit(EditTextOperation edit, boolean wholeWordSearch) {- // Always treat the user-supplied find string as a literal: Pattern.quote escapes any- // regex metacharacters, so the constructed pattern can only ever do a literal match- // (optionally bounded by our own word-boundary anchors). This rules out catastrophic- // backtracking from a malicious find string.- String findRaw = edit.getFind();- String replacement = Objects.toString(edit.getReplace(), "");- String regex = Pattern.quote(findRaw);- if (wholeWordSearch) {- // Use lookarounds rather than \b so the bound works even when the find string starts- // or ends with a non-word character (e.g. "-foo" or "$id"). \b only fires at a- // word/non-word transition, which would never trigger for a find that starts with a- // non-word char and was preceded by another non-word char in the source text.- regex = "(?<!\\w)(?:" + regex + ")(?!\\w)";- }- Pattern pattern = Pattern.compile(regex);- String safeReplacement = Matcher.quoteReplacement(replacement);- return new CompiledEdit(pattern, safeReplacement);- }-- private Set<Integer> resolvePageFilter(EditTextRequest request, PdfJsonDocument document) {- String pageNumbers = request.getPageNumbers();- int totalPages = document.getPages() == null ? 0 : document.getPages().size();- if (totalPages == 0) {- return Collections.emptySet();- }- if (pageNumbers == null || pageNumbers.isBlank() || "all".equalsIgnoreCase(pageNumbers)) {- return null;- }- List<Integer> pages = GeneralUtils.parsePageList(pageNumbers, totalPages, true);- return new HashSet<>(pages);- }-- private int applyEdits(- PdfJsonDocument document, List<CompiledEdit> edits, Set<Integer> pageFilter) {- List<PdfJsonPage> pages = document.getPages();- if (pages == null) {- return 0;- }- int modifiedSpans = 0;- // The page filter is built from parsePageList against pages.size(), so it returns 1-based- // positional page numbers. Match against the same positional numbering here rather than- // the per-page pageNumber field, which can become non-sequential after split/merge round- // trips and would misalign the filter.- for (int i = 0; i < pages.size(); i++) {- int positionalPageNumber = i + 1;- if (pageFilter != null && !pageFilter.contains(positionalPageNumber)) {- continue;- }- modifiedSpans += applyEditsToPage(pages.get(i), edits);- }- return modifiedSpans;- }-- private int applyEditsToPage(PdfJsonPage page, List<CompiledEdit> edits) {- List<PdfJsonTextElement> elements = page.getTextElements();- if (elements == null || elements.isEmpty()) {- return 0;- }- Set<Integer> modifiedIndices = new HashSet<>();- for (CompiledEdit edit : edits) {- applyEditToPage(elements, edit, modifiedIndices);- }- for (Integer index : modifiedIndices) {- // Char codes were captured for the original glyph sequence; clear them so the rebuild- // re-encodes from the new text via the font.- elements.get(index).setCharCodes(null);- }- return modifiedIndices.size();- }-- /**- * Apply a single edit across the page by matching against the concatenation of all element- * texts, then writing the replacement back into the originating element(s).- */- private void applyEditToPage(- List<PdfJsonTextElement> elements, CompiledEdit edit, Set<Integer> modifiedIndices) {- StringBuilder joined = new StringBuilder();- int[] starts = new int[elements.size()];- int[] ends = new int[elements.size()];- for (int i = 0; i < elements.size(); i++) {- starts[i] = joined.length();- String text = elements.get(i).getText();- if (text != null) {- joined.append(text);- }- ends[i] = joined.length();- }-- Matcher matcher = edit.pattern().matcher(joined);- List<MatchSpan> spans = new ArrayList<>();- StringBuilder interpolation = new StringBuilder();- int previousAppendPosition = 0;- while (matcher.find()) {- if (matcher.start() == matcher.end()) {- // Skip zero-length matches (e.g. /a*/ on empty input) — they cannot be applied.- continue;- }- int sizeBefore = interpolation.length();- matcher.appendReplacement(interpolation, edit.replacement());- int prefixLength = matcher.start() - previousAppendPosition;- String actualReplacement =- interpolation.substring(sizeBefore + prefixLength, interpolation.length());- spans.add(new MatchSpan(matcher.start(), matcher.end(), actualReplacement));- previousAppendPosition = matcher.end();- }-- // Apply right-to-left so earlier match positions stay valid as we mutate elements.- for (int i = spans.size() - 1; i >= 0; i--) {- MatchSpan span = spans.get(i);- int firstElement = findElementForCharIndex(starts, ends, span.start());- int lastElement = findElementForCharIndex(starts, ends, span.end() - 1);- if (firstElement < 0 || lastElement < 0) {- continue;- }- applyMatchToElements(- elements, starts, span, firstElement, lastElement, modifiedIndices);- }- }-- /**- * Find the element whose text covers the character at {@code charIndex} in the joined string.- * Returns -1 if no element covers that index (which should not happen for valid match spans).- */- private static int findElementForCharIndex(int[] starts, int[] ends, int charIndex) {- for (int i = 0; i < starts.length; i++) {- if (starts[i] <= charIndex && charIndex < ends[i]) {- return i;- }- }- return -1;- }-- private static void applyMatchToElements(- List<PdfJsonTextElement> elements,- int[] starts,- MatchSpan span,- int firstElement,- int lastElement,- Set<Integer> modifiedIndices) {- if (firstElement == lastElement) {- PdfJsonTextElement element = elements.get(firstElement);- String text = nullToEmpty(element.getText());- int matchStartInElement = span.start() - starts[firstElement];- int matchEndInElement = span.end() - starts[firstElement];- element.setText(- text.substring(0, matchStartInElement)- + span.replacement()- + text.substring(matchEndInElement));- modifiedIndices.add(firstElement);- return;- }-- // Cross-element match: write the whole replacement into the first matched element, empty- // any intermediate elements, and keep only the suffix of the last matched element. The- // JSON->PDF rebuild concatenates per-token text, so the font lays out the replacement as- // one continuous run anchored at the first element's X position.- String firstText = nullToEmpty(elements.get(firstElement).getText());- int firstSplit = span.start() - starts[firstElement];- elements.get(firstElement).setText(firstText.substring(0, firstSplit) + span.replacement());- modifiedIndices.add(firstElement);-- for (int mid = firstElement + 1; mid < lastElement; mid++) {- elements.get(mid).setText("");- modifiedIndices.add(mid);- }-- String lastText = nullToEmpty(elements.get(lastElement).getText());- int lastSplit = span.end() - starts[lastElement];- elements.get(lastElement).setText(lastText.substring(lastSplit));- modifiedIndices.add(lastElement);- }-- private static String nullToEmpty(String value) {- return value != null ? value : "";- }-- private String buildOutputFilename(MultipartFile inputFile) {- String originalName = inputFile.getOriginalFilename();- String baseName =- (originalName != null && !originalName.isBlank())- ? FILE_EXTENSION_PATTERN- .matcher(Filenames.toSimpleFileName(originalName))- .replaceFirst("")- : "document";- return baseName + "_edited.pdf";- }-- private record CompiledEdit(Pattern pattern, String replacement) {}-- private record MatchSpan(int start, int end, String replacement) {}-}diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/PdfTextEditorCharcodeController.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/PdfTextEditorCharcodeController.javadeleted file mode 100644index 169197a199..0000000000--- a/app/core/src/main/java/stirling/software/SPDF/controller/api/PdfTextEditorCharcodeController.java+++ /dev/null@@ -1,598 +0,0 @@-package stirling.software.SPDF.controller.api;--import java.io.IOException;-import java.util.ArrayList;-import java.util.Base64;-import java.util.List;--import org.apache.pdfbox.pdmodel.PDDocument;-import org.apache.pdfbox.pdmodel.PDPage;-import org.apache.pdfbox.pdmodel.PDResources;-import org.apache.pdfbox.pdmodel.font.PDFont;-import org.springframework.http.ResponseEntity;-import org.springframework.web.bind.annotation.PostMapping;-import org.springframework.web.bind.annotation.RequestBody;--import com.fasterxml.jackson.annotation.JsonInclude;--import io.swagger.v3.oas.annotations.Operation;--import lombok.Data;-import lombok.RequiredArgsConstructor;-import lombok.extern.slf4j.Slf4j;--import stirling.software.common.annotations.api.GeneralApi;-import stirling.software.common.service.CustomPDFDocumentFactory;--/**- * Charcode-encode helper for the v2 PDF text editor.- *- * <p>The frontend editor uses PDFium-WASM, which exposes {@code FPDFText_SetCharcodes} for writing- * new text using raw font charcodes (skipping PDFium's broken reverse Unicode→CID lookup for- * embedded subset fonts). What PDFium does NOT expose is the byte-encoding side of an existing font- * - given a PDFont and a Unicode string, what are the bytes the font's encoding produces? PDFBox- * does have that ({@link PDFont#encode}).- *- * <p>This endpoint accepts the source PDF + a "locator" describing where to find the font in- * question (page index + a sample char known to render in the target font, optionally narrowed by- * the font's /BaseFont name) + the Unicode text the frontend wants to encode. It returns the- * charcode sequence the frontend can pass to {@code FPDFText_SetCharcodes}.- *- * <p>If the locator can't find a matching text fragment, or if the font can't encode some chars,- * the response reports which chars are missing so the frontend can fall back to Helvetica per char.- */-@Slf4j-@GeneralApi-@RequiredArgsConstructor-public class PdfTextEditorCharcodeController {-- /** Reject JSON bodies whose base64 implies a decoded PDF larger than this. */- private static final int MAX_PDF_BYTES = 100 * 1024 * 1024;-- /**- * Upper bound on {@code request.text} code units. Editor requests are word-sized; an unbounded- * text drove a per-code-point encode/exception loop (CPU burn) on crafted requests.- */- private static final int MAX_TEXT_CHARS = 4096;-- /** Nested form-XObject resource dictionaries visited per lookup (cycle/DoS guard). */- private static final int MAX_RESOURCE_DICTS = 32;-- /** Bound on the reverse-map cache so a busy multi-document server can't grow it forever. */- private static final int REVERSE_MAP_CACHE_MAX = 32;-- /** Access-ordered LRU bounded at {@link #REVERSE_MAP_CACHE_MAX} entries. */- private static final class BoundedReverseMapCache- extends java.util.LinkedHashMap<String, java.util.Map<String, Long>> {- private static final long serialVersionUID = 1L;-- BoundedReverseMapCache() {- super(16, 0.75f, true);- }-- @Override- protected boolean removeEldestEntry(- java.util.Map.Entry<String, java.util.Map<String, Long>> eldest) {- return size() > REVERSE_MAP_CACHE_MAX;- }- }-- private static final java.util.Map<String, java.util.Map<String, Long>> REVERSE_MAP_CACHE =- java.util.Collections.synchronizedMap(new BoundedReverseMapCache());-- private final CustomPDFDocumentFactory pdfDocumentFactory;-- // NOTE: PDFBox's PDSimpleFont emits one "No Unicode mapping for .notdef" WARN per probed- // charcode when buildReverseUnicodeMap iterates 0..0xFFFF, which once flooded info.log to- // ~1.4 GB overnight. That logger is silenced DECLARATIVELY in logback.xml (a config entry ops- // can see and revert) rather than by mutating the global logger from a static block here -- // mutating it at class-load time hid the same warnings from every other tool in the JVM with- // no trace in configuration.-- @Data- public static class EncodeCharcodesRequest {-- /** Base64-encoded original PDF. The frontend already has the bytes loaded. */- private String pdfBase64;-- /** 0-based page index containing the font sample. */- private int pageIndex;-- /**- * A char known to exist on the page in the target font. Combined with {@code fontName}- * (when supplied) it locates the source PDFont via its ToUnicode CMap.- */- private String locatorChar;-- /**- * Optional /BaseFont name of the target font (as PDFium's FPDFFont_GetBaseFontName reports- * it). When a page has TWO fonts that both render {@code locatorChar}, this disambiguates- * which one to encode against - otherwise the first font found wins and a cross-font edit- * gets the wrong font's charcode. Null = keep the legacy first-match behaviour.- */- private String fontName;-- /**- * Optional SHA-256 (lowercase hex) of the target font's embedded program bytes (what- * PDFium's FPDFFont_GetFontData returns = the decoded FontFile/FontFile2/FontFile3 stream).- * This is the ONLY unambiguous font identity: PDFium strips the "ABCDEF+" subset tag from- * font names, so every subset of one family reports the same {@code fontName} and a- * name-based lookup can land on a SIBLING subset whose charcode space is different -- * returning valid-but-wrong charcodes that scramble the edited text. When present and a- * font on the page matches, it wins over name matching.- */- private String fontSha256;-- /** Unicode text the frontend wants to encode. */- private String text;- }-- @Data- @JsonInclude(JsonInclude.Include.NON_NULL)- public static class EncodeCharcodesResponse {- /**- * Per-char charcode array (one entry per code point in {@code request.text}). When the- * font's encoding produces multi-byte sequences, each char gets the full unsigned int value- * of its bytes packed big-endian (so a 2-byte CID like 0x004D becomes 77).- */- private List<Long> charcodes;-- /** Chars from the request that the font couldn't encode. */- private List<String> missing;-- /** Diagnostic note - included so the frontend HUD can show what happened. */- private String note;-- /** Set when the request failed entirely (bad pdf bytes, no matching font, etc.). */- private String error;- }-- @Operation(- summary = "Encode Unicode → font charcodes for the v2 PDF text editor",- description =- """- Frontend-only helper: takes the source PDF, a locator pointing at an existing- char rendered in the target font, and a Unicode string. Returns the byte- sequence the target font produces for that Unicode, packed as one unsigned- int per char. The frontend then calls FPDFText_SetCharcodes with the- returned ints to inject new text that reuses the embedded font's actual- glyphs. Chars the font can't encode are listed in `missing` so the caller- can fall back per-char.- """)- @PostMapping(- value = "/pdf-text-editor/encode-charcodes",- consumes = "application/json",- produces = "application/json")- public ResponseEntity<EncodeCharcodesResponse> encodeCharcodes(- @RequestBody EncodeCharcodesRequest request) {- EncodeCharcodesResponse resp = new EncodeCharcodesResponse();- if (request == null- || request.getPdfBase64() == null- || request.getText() == null- || request.getLocatorChar() == null) {- resp.setError("missing required fields");- return ResponseEntity.badRequest().body(resp);- }- // length/4*3 bounds the decoded size without decoding, so we reject early before- // allocating.- String b64 = request.getPdfBase64();- if ((long) b64.length() / 4 * 3 > MAX_PDF_BYTES) {- resp.setError("pdf too large");- return ResponseEntity.status(413).body(resp);- }- // Reported separately: a combined check names only one cause and misleads the caller.- if (request.getText().length() > MAX_TEXT_CHARS) {- resp.setError("text too long");- return ResponseEntity.badRequest().body(resp);- }- if (request.getLocatorChar().length() > 4) {- resp.setError("locatorChar too long");- return ResponseEntity.badRequest().body(resp);- }- byte[] pdfBytes;- try {- pdfBytes = Base64.getDecoder().decode(b64);- } catch (IllegalArgumentException e) {- resp.setError("pdfBase64 is not valid base64");- return ResponseEntity.badRequest().body(resp);- }- try (PDDocument doc = pdfDocumentFactory.load(pdfBytes, true)) {- if (request.getPageIndex() < 0 || request.getPageIndex() >= doc.getNumberOfPages()) {- resp.setError("pageIndex out of range");- return ResponseEntity.badRequest().body(resp);- }- PDPage page = doc.getPage(request.getPageIndex());- // Skip walking the page's content stream (it crashes on Type3 fonts with- // UnsupportedOperationException("Not implemented: Type3") before we can do anything- // useful). Instead enumerate the page's font resources and pick the one identified by- // the request's font-program hash (definitive), falling back to name matching.- // For Chrome/Skia-printed PDFs that emit one Type3 font per glyph, this lands on- // the exact font that renders the locator char.- ResourceFont located =- findFontByToUnicode(- page,- request.getLocatorChar(),- request.getFontName(),- request.getFontSha256(),- doc);- if (located == null) {- resp.setError(- "no font on page "- + request.getPageIndex()- + " renders locatorChar="- + request.getLocatorChar()- + (request.getFontName() != null- ? " (fontName=" + request.getFontName() + ")"- : ""));- return ResponseEntity.ok(resp);- }- // Build a reverse Unicode→charcode map by walking the font's ToUnicode CMap.- // This is the ONLY path that works for Type3 fonts (PDFBox's font.encode() throws- // "Not implemented: Type3" on them), and it also acts as a more reliable fallback- // for subset fonts whose encode() rejects chars not in the original document.- //- // For Sample.pdf specifically, every embedded font is Type3 (Chrome/Skia output),- // but they all carry a ToUnicode CMap mapping CIDs back to Unicode. We iterate- // charcodes 0..0xFFFF, call font.toUnicode(cc) for each, and record the inverse- // mapping for the chars the user wants to write.- PDFont font = located.font();- java.util.Map<String, Long> reverseMap =- buildReverseUnicodeMap(pdfBytes, located, request.getPageIndex());- List<Long> charcodes = new ArrayList<>();- List<String> missing = new ArrayList<>();- String text = request.getText();- int i = 0;- while (i < text.length()) {- int cp = text.codePointAt(i);- String oneChar = new String(Character.toChars(cp));- i += Character.charCount(cp);- // Whitespace is NEVER charcode-reused. Subset Type1/LaTeX fonts- // usually have no real space glyph, yet font.encode(0x20) still- // returns code 0x20 without throwing - and SetCharcodes(0x20)- // then paints whatever glyph sits at that subset code (e.g. „- // quotedblbase in LMRoman). Report whitespace as missing so the- // frontend emits it as a positional gap instead.- if (Character.isWhitespace(cp)) {- missing.add(oneChar);- continue;- }- // 1st try: font.encode() - works for Type0/TrueType/Type1- Long packed = null;- try {- byte[] encoded = font.encode(oneChar);- long p = 0L;- for (byte b : encoded) p = (p << 8) | (b & 0xff);- packed = p;- } catch (IOException- | IllegalArgumentException- | UnsupportedOperationException encodeEx) {- // 2nd try: ToUnicode reverse lookup - works for Type3 + anything with a CMap- packed = reverseMap.get(oneChar);- }- if (packed != null) charcodes.add(packed);- else missing.add(oneChar);- }- resp.setCharcodes(charcodes);- if (!missing.isEmpty()) resp.setMissing(missing);- resp.setNote(- "font="- + font.getName()- + " encoded "- + charcodes.size()- + " of "- + (charcodes.size() + missing.size())- + " chars");- return ResponseEntity.ok(resp);- } catch (IOException e) {- log.warn("encodeCharcodes: failed to load PDF", e);- resp.setError("failed to load PDF");- return ResponseEntity.badRequest().body(resp);- } catch (RuntimeException e) {- log.warn("encodeCharcodes: unexpected error", e);- resp.setError("unexpected error");- return ResponseEntity.status(500).body(resp);- }- }-- /**- * Locate the font the request targets. Identity sources, strongest first:- *- * <ol>- * <li><b>Program hash</b>: SHA-256 of the embedded font program bytes. Definitive - two- * different subsets NEVER share program bytes, and PDFium's FPDFFont_GetFontData returns- * exactly the decoded FontFile stream, so frontend and backend hash the same bytes.- * <li><b>Exact /BaseFont name</b> (subset tag included), then <b>tag-stripped name</b>. Name- * matches are only accepted when UNAMBIGUOUS: PDFium reports subset fonts WITHOUT their- * "ABCDEF+" tag, so a page with several subsets of one family ("AAAAAC+Garamond",- * "AAAAAG+Garamond", ...) has them ALL match the stripped name - and encoding against the- * wrong sibling returns valid-but-wrong charcodes that scramble the edited text ("RUSSELL- * W. MANGUM" rendered "US EEL W. MANGS M"). With 2+ candidates we return null so the- * frontend takes its safe fallback instead of a coin flip.- * </ol>- *- * <p>This avoids running PDFStreamEngine.processPage, which throws- * UnsupportedOperationException on Type3 font glyph rendering. The PDFont lookup itself is- * purely metadata-driven and works on all subtypes.- */- private static ResourceFont findFontByToUnicode(- PDPage page, String wantChar, String fontName, String fontSha256, PDDocument doc) {- try {- List<ResourceFont> fonts = collectResourceTreeFonts(page.getResources());-- // 1) Program-hash identity. When several dicts share one program (identical bytes- // re-embedded), any of them renders the same glyphs for the same codes; prefer the- // one whose ToUnicode covers the locator char so the reverse map is usable.- if (fontSha256 != null && !fontSha256.isEmpty()) {- List<ResourceFont> hashMatches = new ArrayList<>();- for (ResourceFont rf : fonts) {- String sha = fontProgramSha256(rf.font());- if (fontSha256.equalsIgnoreCase(sha)) hashMatches.add(rf);- }- for (ResourceFont rf : hashMatches) {- if (probesToUnicode(rf.font(), wantChar)) return rf;- }- if (!hashMatches.isEmpty()) return hashMatches.get(0);- // No program on this page hashes to what the frontend is editing (e.g. PDFium- // returned a substitute font's bytes for a non-embedded font). Fall through to- // name matching rather than failing outright.- }-- // 2) Name identity - exact tag-included first, then tag-stripped - each accepted- // only when it selects a single font.- if (fontName != null && !fontName.isEmpty()) {- ResourceFont exact =- selectUnambiguous(- fonts, wantChar, f -> fontName.equals(f.getName()), "exact");- if (exact != null) return exact;- String wantStripped = stripSubsetTag(fontName);- ResourceFont stripped =- selectUnambiguous(- fonts,- wantChar,- f -> wantStripped.equals(stripSubsetTag(f.getName())),- "stripped");- if (stripped != null) return stripped;- // The frontend NAMED the font it is editing. Falling back to "any font that- // renders the char" would hand back a DIFFERENT font's charcodes, which the- // frontend then writes into the named font's text object - wrong glyph, and the- // backend strategy skips all frontend validation. Report the char missing- // instead so the caller takes its own fallback path.- return null;- }-- // 3) Legacy locator-only behaviour: first font whose ToUnicode renders the char.- for (ResourceFont rf : fonts) {- if (probesToUnicode(rf.font(), wantChar)) return rf;- }- } catch (RuntimeException ignore) {- // Be defensive: any single bad font shouldn't sink the whole request.- }- return null;- }-- /**- * Apply {@code nameFilter}, then decide: exactly one candidate whose ToUnicode covers {@code- * wantChar} wins; two+ probe-hits are AMBIGUOUS (null). With zero probe-hits, a single- * name-matching font is still returned (font.encode() may handle chars without a ToUnicode -- * common for Type0/Identity-H), but two+ name matches are again ambiguous.- */- private static ResourceFont selectUnambiguous(- List<ResourceFont> fonts,- String wantChar,- java.util.function.Predicate<PDFont> nameFilter,- String modeLabel) {- List<ResourceFont> named = new ArrayList<>();- for (ResourceFont rf : fonts) {- try {- if (rf.font().getName() != null && nameFilter.test(rf.font())) named.add(rf);- } catch (RuntimeException ignore) {- }- }- if (named.isEmpty()) return null;- List<ResourceFont> probed = new ArrayList<>();- for (ResourceFont rf : named) {- if (probesToUnicode(rf.font(), wantChar)) probed.add(rf);- }- if (probed.size() == 1) return probed.get(0);- if (probed.size() > 1) {- log.debug(- "encodeCharcodes: {} name match ambiguous ({} fonts render locator '{}') -"- + " refusing cross-subset guess",- modeLabel,- probed.size(),- wantChar);- return null;- }- return named.size() == 1 ? named.get(0) : null;- }-- /** True when some charcode in the font's ToUnicode CMap maps to {@code wantChar}. */- private static boolean probesToUnicode(PDFont font, String wantChar) {- // Cheap inverse-CMap probe: iterate codes until we hit one whose toUnicode is wantChar.- // For Type3 with at most ~16 glyphs, this is microseconds. For full Type0 subsets- // it's a few-thousand-iteration scan.- int upper = font.isStandard14() ? 256 : 0x10000;- for (int cc = 0; cc < upper; cc++) {- String u;- try {- u = font.toUnicode(cc);- } catch (Exception ignore) {- continue;- }- if (u != null && u.equals(wantChar)) return true;- }- return false;- }-- private record ResourceFont(PDFont font, String path) {}-- private record PendingResources(PDResources resources, String path) {}-- /**- * Breadth-first collection of every distinct font reachable from the page's resources AND every- * nested form XObject's resources (bounded by {@link #MAX_RESOURCE_DICTS}, cycle-safe, deduped- * by COS dictionary identity). The v2 reader surfaces form-XObject text as editable, so its- * fonts must be findable too.- */- private static List<ResourceFont> collectResourceTreeFonts(PDResources resources) {- List<ResourceFont> out = new ArrayList<>();- java.util.ArrayDeque<PendingResources> queue = new java.util.ArrayDeque<>();- java.util.Set<org.apache.pdfbox.cos.COSDictionary> seenDicts =- java.util.Collections.newSetFromMap(new java.util.IdentityHashMap<>());- java.util.Set<org.apache.pdfbox.cos.COSDictionary> seenFonts =- java.util.Collections.newSetFromMap(new java.util.IdentityHashMap<>());- if (resources != null) queue.add(new PendingResources(resources, ""));- int visited = 0;- // Bound a crafted page declaring many fonts none of which match (CPU-DoS guard).- final int MAX_FONTS = 64;- while (!queue.isEmpty() && visited < MAX_RESOURCE_DICTS) {- PendingResources pending = queue.poll();- PDResources res = pending.resources();- if (!seenDicts.add(res.getCOSObject())) continue;- visited++;- for (org.apache.pdfbox.cos.COSName name : res.getFontNames()) {- if (out.size() >= MAX_FONTS) break;- PDFont font;- try {- font = res.getFont(name);- } catch (IOException | RuntimeException e) {- continue;- }- if (font == null || !seenFonts.add(font.getCOSObject())) continue;- out.add(new ResourceFont(font, pending.path() + "/" + name.getName()));- }- try {- for (org.apache.pdfbox.cos.COSName xn : res.getXObjectNames()) {- try {- org.apache.pdfbox.pdmodel.graphics.PDXObject xo = res.getXObject(xn);- if (xo- instanceof- org.apache.pdfbox.pdmodel.graphics.form.PDFormXObject form) {- PDResources fr = form.getResources();- if (fr != null) {- queue.add(- new PendingResources(- fr, pending.path() + "/" + xn.getName()));- }- }- } catch (IOException | RuntimeException ignore) {- }- }- } catch (RuntimeException ignore) {- }- }- return out;- }-- /**- * SHA-256 (lowercase hex) of a font's embedded program bytes - the decoded- * FontFile/FontFile2/FontFile3 stream, which is byte-identical to what PDFium's- * FPDFFont_GetFontData hands the frontend. Null when the font embeds no program.- */- private static String fontProgramSha256(PDFont font) {- try {- org.apache.pdfbox.pdmodel.font.PDFontDescriptor fd = font.getFontDescriptor();- if (fd == null && font instanceof org.apache.pdfbox.pdmodel.font.PDType0Font type0) {- fd = type0.getDescendantFont().getFontDescriptor();- }- if (fd == null) return null;- org.apache.pdfbox.pdmodel.common.PDStream stream = fd.getFontFile2();- if (stream == null) stream = fd.getFontFile3();- if (stream == null) stream = fd.getFontFile();- if (stream == null) return null;- return sha256Hex(stream.toByteArray());- } catch (IOException | RuntimeException e) {- return null;- }- }-- /** Drop the 6-letter "ABCDEF+" subset prefix PDF puts on subset /BaseFont names. */- private static String stripSubsetTag(String fontName) {- if (fontName == null) return null;- if (fontName.length() > 7- && fontName.charAt(6) == '+'- && fontName.chars().limit(6).allMatch(c -> c >= 'A' && c <= 'Z')) {- return fontName.substring(7);- }- return fontName;- }-- /**- * Build a Unicode→charcode map for a font by iterating every charcode in 0..0xFFFF and asking- * the font's ToUnicode CMap what Unicode it maps to. Charcodes that aren't in the CMap throw- * inside toUnicode (PDFBox returns null or throws depending on font subtype), and those are- * skipped silently.- *- * <p>This is the encoding inverse PDFBox doesn't expose directly. For Type3 fonts (where- * font.encode() throws "Not implemented"), this is the ONLY way to write text in the same font- * - we look up the user's char in the reverse map and pass that charcode to- * FPDFText_SetCharcodes on the frontend.- *- * <p>The 0..0xFFFF range is sufficient for Type0/CIDFontType2 fonts (CIDs are 16-bit). For- * single-byte fonts the loop short-circuits after 256. We don't go higher because no PDF font- * has a CID outside that range in practice; the per-font result is memoised in {@link- * #REVERSE_MAP_CACHE} so the 65 536-entry probe runs once per document+font, not per request.- */- private static java.util.Map<String, Long> buildReverseUnicodeMap(- byte[] pdfBytes, ResourceFont located, int pageIndex) {- String key = sha256Hex(pdfBytes) + "|" + fontCacheIdentity(located, pageIndex);- // Compound get/put under the map's own monitor. The 0..0xFFFF probe runs OUTSIDE the- // lock so one slow build can't block every other request on the shared cache.- java.util.Map<String, Long> cached;- synchronized (REVERSE_MAP_CACHE) {- cached = REVERSE_MAP_CACHE.get(key);- }- if (cached != null) return cached;- java.util.Map<String, Long> built = computeReverseUnicodeMap(located.font());- synchronized (REVERSE_MAP_CACHE) {- java.util.Map<String, Long> raced = REVERSE_MAP_CACHE.putIfAbsent(key, built);- return raced != null ? raced : built;- }- }-- private static String fontCacheIdentity(ResourceFont located, int pageIndex) {- org.apache.pdfbox.cos.COSObjectKey objectKey = null;- try {- objectKey = located.font().getCOSObject().getKey();- } catch (RuntimeException ignore) {- }- if (objectKey != null) {- return "obj|" + objectKey.getNumber() + "." + objectKey.getGeneration();- }- return "res|p" + pageIndex + located.path();- }-- /** Lowercase hex SHA-256 of the PDF bytes; used as the reverse-map cache key. */- private static String sha256Hex(byte[] bytes) {- try {- byte[] digest = java.security.MessageDigest.getInstance("SHA-256").digest(bytes);- StringBuilder sb = new StringBuilder(digest.length * 2);- for (byte b : digest) {- sb.append(Character.forDigit((b >> 4) & 0xf, 16));- sb.append(Character.forDigit(b & 0xf, 16));- }- return sb.toString();- } catch (java.security.NoSuchAlgorithmException e) {- // SHA-256 is always present in a JRE; fall back to a length+hash key just in case so- // the cache still functions (correctness holds - collisions only cost a rebuild).- return bytes.length + ":" + java.util.Arrays.hashCode(bytes);- }- }-- private static java.util.Map<String, Long> computeReverseUnicodeMap(PDFont font) {- java.util.Map<String, Long> out = new java.util.HashMap<>();- int upper = font.isStandard14() ? 256 : 0x10000;- for (int cc = 0; cc < upper; cc++) {- String u;- try {- u = font.toUnicode(cc);- } catch (Exception ignore) {- continue;- }- if (u == null || u.isEmpty()) continue;- // First charcode wins for a given Unicode (the canonical mapping).- out.putIfAbsent(u, (long) cc);- }- return out;- }-}diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertPdfJsonController.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertPdfJsonController.javadeleted file mode 100644index 6aeb033761..0000000000--- a/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertPdfJsonController.java+++ /dev/null@@ -1,515 +0,0 @@-package stirling.software.SPDF.controller.api.converters;--import java.io.IOException;-import java.io.OutputStream;-import java.nio.charset.StandardCharsets;-import java.nio.file.Files;-import java.nio.file.Path;-import java.util.Optional;-import java.util.UUID;-import java.util.regex.Pattern;--import org.springframework.beans.factory.annotation.Autowired;-import org.springframework.core.io.Resource;-import org.springframework.http.MediaType;-import org.springframework.http.ResponseEntity;-import org.springframework.web.bind.annotation.GetMapping;-import org.springframework.web.bind.annotation.ModelAttribute;-import org.springframework.web.bind.annotation.PathVariable;-import org.springframework.web.bind.annotation.RequestBody;-import org.springframework.web.bind.annotation.RequestParam;-import org.springframework.web.multipart.MultipartFile;--import io.github.pixee.security.Filenames;-import io.swagger.v3.oas.annotations.Operation;--import lombok.RequiredArgsConstructor;-import lombok.extern.slf4j.Slf4j;--import stirling.software.SPDF.config.swagger.StandardPdfResponse;-import stirling.software.SPDF.model.json.PdfJsonDocument;-import stirling.software.SPDF.model.json.PdfJsonMetadata;-import stirling.software.SPDF.service.PdfJsonConversionService;-import stirling.software.common.annotations.AutoJobPostMapping;-import stirling.software.common.annotations.api.ConvertApi;-import stirling.software.common.enumeration.ResourceWeight;-import stirling.software.common.model.api.GeneralFile;-import stirling.software.common.model.api.PDFFile;-import stirling.software.common.service.JobOwnershipService;-import stirling.software.common.util.ExceptionUtils;-import stirling.software.common.util.TempFile;-import stirling.software.common.util.TempFileManager;-import stirling.software.common.util.WebResponseUtils;--@Slf4j-@ConvertApi-@RequiredArgsConstructor-public class ConvertPdfJsonController {-- private static final Pattern FILE_EXTENSION_PATTERN = Pattern.compile("[.][^.]+$");- private static final Pattern WHITESPACE_PATTERN = Pattern.compile("[\\r\\n\\t]+");- private static final Pattern NON_PRINTABLE_PATTERN = Pattern.compile("[^\\x20-\\x7E]");- private final PdfJsonConversionService pdfJsonConversionService;- private final TempFileManager tempFileManager;-- @Autowired(required = false)- private JobOwnershipService jobOwnershipService;-- @AutoJobPostMapping(- consumes = "multipart/form-data",- value = "/pdf/text-editor",- resourceWeight = ResourceWeight.MEDIUM_WEIGHT)- @Operation(- summary = "Convert PDF to Text Editor Format",- description =- "Extracts PDF text, fonts, and metadata into an editable JSON structure for the text editor tool.")- public ResponseEntity<Resource> convertPdfToJson(- @ModelAttribute PDFFile request,- @RequestParam(value = "lightweight", defaultValue = "false") boolean lightweight)- throws Exception {- MultipartFile inputFile = request.getFileInput();- if (inputFile == null) {- throw ExceptionUtils.createNullArgumentException("fileInput");- }-- String originalName = inputFile.getOriginalFilename();- String baseName =- (originalName != null && !originalName.isBlank())- ? FILE_EXTENSION_PATTERN- .matcher(Filenames.toSimpleFileName(originalName))- .replaceFirst("")- : "document";- String docName = baseName + ".json";- TempFile tempOut = tempFileManager.createManagedTempFile(".json");- try (OutputStream os = Files.newOutputStream(tempOut.getPath())) {- pdfJsonConversionService.convertPdfToJson(inputFile, lightweight, os);- } catch (Exception e) {- tempOut.close();- throw e;- }- try {- logJsonResponse("pdf/text-editor", tempOut.getPath());- return WebResponseUtils.fileToWebResponse(tempOut, docName, MediaType.APPLICATION_JSON);- } catch (Exception e) {- tempOut.close();- throw e;- }- }-- @AutoJobPostMapping(- consumes = "multipart/form-data",- value = "/text-editor/pdf",- resourceWeight = ResourceWeight.MEDIUM_WEIGHT)- @StandardPdfResponse- @Operation(- summary = "Convert Text Editor Format to PDF",- description =- "Rebuilds a PDF from the editable JSON structure generated by the text editor tool.")- public ResponseEntity<Resource> convertJsonToPdf(@ModelAttribute GeneralFile request)- throws Exception {- MultipartFile jsonFile = request.getFileInput();- if (jsonFile == null) {- throw ExceptionUtils.createNullArgumentException("fileInput");- }-- String originalName = jsonFile.getOriginalFilename();- String baseName =- (originalName != null && !originalName.isBlank())- ? FILE_EXTENSION_PATTERN- .matcher(Filenames.toSimpleFileName(originalName))- .replaceFirst("")- : "document";- String docName = baseName.endsWith(".pdf") ? baseName : baseName + ".pdf";- TempFile tempOut = tempFileManager.createManagedTempFile(".pdf");- try (OutputStream os = Files.newOutputStream(tempOut.getPath())) {- pdfJsonConversionService.convertJsonToPdf(jsonFile, os);- } catch (Exception e) {- tempOut.close();- throw e;- }- return WebResponseUtils.pdfFileToWebResponse(tempOut, docName);- }-- @AutoJobPostMapping(- consumes = "multipart/form-data",- value = "/pdf/text-editor/metadata",- resourceWeight = ResourceWeight.MEDIUM_WEIGHT)- @Operation(- summary = "Extract PDF metadata for text editor lazy loading",- description =- "Extracts document metadata, fonts, and page dimensions for the text editor tool. Caches the document for"- + " subsequent page requests. Returns a server-generated jobId scoped to the"- + " authenticated user.")- public ResponseEntity<Resource> extractPdfMetadata(@ModelAttribute PDFFile request)- throws Exception {- MultipartFile inputFile = request.getFileInput();- if (inputFile == null) {- throw ExceptionUtils.createNullArgumentException("fileInput");- }-- String baseJobId = UUID.randomUUID().toString();-- String scopedJobKey = getScopedJobKey(baseJobId);-- log.debug("Extracting metadata for PDF, assigned jobId: {}", scopedJobKey);-- TempFile tempOut = tempFileManager.createManagedTempFile(".json");- try (OutputStream os = Files.newOutputStream(tempOut.getPath())) {- pdfJsonConversionService.extractDocumentMetadata(inputFile, scopedJobKey, os);- } catch (Exception e) {- tempOut.close();- throw e;- }- try {- logJsonResponse("pdf/text-editor/metadata", tempOut.getPath());- return ResponseEntity.ok()- .header("X-Job-Id", scopedJobKey)- .contentType(MediaType.APPLICATION_JSON)- .contentLength(Files.size(tempOut.getPath()))- .body(new WebResponseUtils.ManagedTempFileResource(tempOut));- } catch (IOException | RuntimeException e) {- tempOut.close();- throw e;- }- }-- @AutoJobPostMapping(- value = "/pdf/text-editor/partial/{jobId}",- consumes = MediaType.APPLICATION_JSON_VALUE,- resourceWeight = ResourceWeight.MEDIUM_WEIGHT)- @StandardPdfResponse- @Operation(- summary = "Apply incremental edits from text editor to a cached PDF",- description =- "Applies edits for the specified pages of a cached PDF and returns an updated PDF."- + " Requires the PDF to have been previously cached via the text editor metadata endpoint."- + " The jobId must be obtained from the metadata extraction endpoint.")- public ResponseEntity<Resource> exportPartialPdf(- @PathVariable String jobId,- @RequestBody PdfJsonDocument document,- @RequestParam(value = "filename", required = false) String filename)- throws Exception {- if (document == null) {- throw ExceptionUtils.createNullArgumentException("document");- }-- validateJobAccess(jobId);-- String baseName =- (filename != null && !filename.isBlank())- ? FILE_EXTENSION_PATTERN- .matcher(Filenames.toSimpleFileName(filename))- .replaceFirst("")- : Optional.ofNullable(document.getMetadata())- .map(PdfJsonMetadata::getTitle)- .filter(title -> title != null && !title.isBlank())- .orElse("document");- String docName = baseName.endsWith(".pdf") ? baseName : baseName + ".pdf";- TempFile tempOut = tempFileManager.createManagedTempFile(".pdf");- try (OutputStream os = Files.newOutputStream(tempOut.getPath())) {- pdfJsonConversionService.exportUpdatedPages(jobId, document, os);- } catch (Exception e) {- tempOut.close();- throw e;- }- try {- return WebResponseUtils.pdfFileToWebResponse(tempOut, docName);- } catch (Exception e) {- tempOut.close();- throw e;- }- }-- @GetMapping(value = "/pdf/text-editor/page/{jobId}/{pageNumber}")- @Operation(- summary = "Extract single page from cached PDF for text editor",- description =- "Retrieves a single page's content from a previously cached PDF document for the text editor tool."- + " Requires prior call to /pdf/text-editor/metadata. The jobId must belong to the"- + " authenticated user.")- public ResponseEntity<Resource> extractSinglePage(- @PathVariable String jobId, @PathVariable int pageNumber) throws Exception {-- validateJobAccess(jobId);-- String docName = "page_" + pageNumber + ".json";- TempFile tempOut = tempFileManager.createManagedTempFile(".json");- try (OutputStream os = Files.newOutputStream(tempOut.getPath())) {- pdfJsonConversionService.extractSinglePage(jobId, pageNumber, os);- } catch (Exception e) {- tempOut.close();- throw e;- }- try {- logJsonResponse("pdf/text-editor/page", tempOut.getPath());- return WebResponseUtils.fileToWebResponse(tempOut, docName, MediaType.APPLICATION_JSON);- } catch (Exception e) {- tempOut.close();- throw e;- }- }-- @GetMapping(value = "/pdf/text-editor/fonts/{jobId}/{pageNumber}")- @Operation(- summary = "Extract fonts used by a single cached page for text editor",- description =- "Retrieves the font payloads used by a single page from a previously cached PDF document."- + " Requires prior call to /pdf/text-editor/metadata. The jobId must belong to the"- + " authenticated user.")- public ResponseEntity<Resource> extractPageFonts(- @PathVariable String jobId, @PathVariable int pageNumber) throws Exception {-- validateJobAccess(jobId);-- String docName = "page_fonts_" + pageNumber + ".json";- TempFile tempOut = tempFileManager.createManagedTempFile(".json");- try (OutputStream os = Files.newOutputStream(tempOut.getPath())) {- pdfJsonConversionService.extractPageFonts(jobId, pageNumber, os);- } catch (Exception e) {- tempOut.close();- throw e;- }- try {- logJsonResponse("pdf/text-editor/fonts/page", tempOut.getPath());- return WebResponseUtils.fileToWebResponse(tempOut, docName, MediaType.APPLICATION_JSON);- } catch (Exception e) {- tempOut.close();- throw e;- }- }-- @AutoJobPostMapping(- value = "/pdf/text-editor/clear-cache/{jobId}",- consumes = MediaType.ALL_VALUE,- resourceWeight = ResourceWeight.MEDIUM_WEIGHT)- @Operation(- summary = "Clear cached PDF document for text editor",- description =- "Manually clears a cached PDF document used by the text editor to free up server resources."- + " Called automatically after 30 minutes. The jobId must belong to the"- + " authenticated user.")- public ResponseEntity<Void> clearCache(@PathVariable String jobId) {-- validateJobAccess(jobId);-- pdfJsonConversionService.clearCachedDocument(jobId);- return ResponseEntity.ok().build();- }-- private String getScopedJobKey(String baseJobId) {- if (jobOwnershipService != null) {- return jobOwnershipService.createScopedJobKey(baseJobId);- }- return baseJobId;- }-- private void logJsonResponse(String label, Path jsonPath) {- if (jsonPath == null) {- log.warn("Returning {} JSON response: null path", label);- return;- }-- boolean debugEnabled = log.isDebugEnabled();- boolean dumpEnabled = isPdfJsonDebugDumpEnabled();- boolean repeatScanEnabled = isPdfJsonRepeatScanEnabled();-- // Reading the full file back from disk is only worth it for these diagnostic paths.- // The happy path (no debug flags) returns here immediately — no extra IO.- if (!debugEnabled && !dumpEnabled && !repeatScanEnabled) {- return;- }-- byte[] jsonBytes;- try {- jsonBytes = Files.readAllBytes(jsonPath);- } catch (IOException ex) {- log.warn(- "Failed to read PDF JSON ({}) for diagnostic logging: {}",- label,- ex.getMessage());- return;- }-- if (debugEnabled) {- int length = jsonBytes.length;- boolean endsWithJson =- length > 0 && (jsonBytes[length - 1] == '}' || jsonBytes[length - 1] == ']');- String tail = "";- if (length > 0) {- int start = Math.max(0, length - 64);- tail = new String(jsonBytes, start, length - start, StandardCharsets.UTF_8);- tail =- NON_PRINTABLE_PATTERN- .matcher(WHITESPACE_PATTERN.matcher(tail).replaceAll(" "))- .replaceAll("?");- }- log.debug(- "Returning {} JSON response ({} bytes, endsWithJson={}, tail='{}')",- label,- length,- endsWithJson,- tail);- }-- if (dumpEnabled) {- try {- String tmpDir = System.getProperty("java.io.tmpdir");- String customDir = System.getenv("SPDF_PDFJSON_DUMP_DIR");- Path dumpDir =- customDir != null && !customDir.isBlank()- ? Path.of(customDir)- : Path.of(tmpDir);- Path dumpPath = Files.createTempFile(dumpDir, "pdfjson_", ".json");- Files.copy(jsonPath, dumpPath, java.nio.file.StandardCopyOption.REPLACE_EXISTING);- log.debug("PDF JSON debug dump ({}): {}", label, dumpPath);- } catch (Exception ex) {- log.warn("Failed to write PDF JSON debug dump ({}): {}", label, ex.getMessage());- }- }-- if (repeatScanEnabled) {- logRepeatedJsonStrings(label, jsonBytes);- }- }-- private boolean isPdfJsonDebugDumpEnabled() {- String env = System.getenv("SPDF_PDFJSON_DUMP");- if (env != null && env.equalsIgnoreCase("true")) {- return true;- }- return Boolean.getBoolean("spdf.pdfjson.dump");- }-- private boolean isPdfJsonRepeatScanEnabled() {- String env = System.getenv("SPDF_PDFJSON_REPEAT_SCAN");- if (env != null && env.equalsIgnoreCase("true")) {- return true;- }- return Boolean.getBoolean("spdf.pdfjson.repeatScan");- }-- private void logRepeatedJsonStrings(String label, byte[] jsonBytes) {- final int minLen = 12;- final int maxLen = 200;- final int maxUnique = 50000;- java.util.Map<String, Integer> counts = new java.util.HashMap<>();- boolean inString = false;- boolean escape = false;- boolean tooLong = false;- StringBuilder current = new StringBuilder(64);- boolean capped = false;-- for (byte b : jsonBytes) {- char ch = (char) (b & 0xFF);- if (!inString) {- if (ch == '"') {- inString = true;- escape = false;- tooLong = false;- current.setLength(0);- }- continue;- }-- if (escape) {- escape = false;- if (!tooLong && current.length() < maxLen) {- current.append(ch);- }- continue;- }- if (ch == '\\') {- escape = true;- continue;- }- if (ch == '"') {- inString = false;- if (!tooLong) {- int len = current.length();- if (len >= minLen && len <= maxLen) {- String value = current.toString();- if (!looksLikeBase64(value)) {- if (!capped || counts.containsKey(value)) {- counts.merge(value, 1, Integer::sum);- if (!capped && counts.size() >= maxUnique) {- capped = true;- }- }- }- }- }- continue;- }- if (!tooLong) {- if (current.length() < maxLen) {- current.append(ch);- } else {- tooLong = true;- }- }- }-- java.util.List<java.util.Map.Entry<String, Integer>> top =- counts.entrySet().stream()- .filter(e -> e.getValue() > 1)- .sorted((a, b) -> Integer.compare(b.getValue(), a.getValue()))- .limit(20)- .toList();-- if (!top.isEmpty()) {- String summary =- top.stream()- .map(- e ->- String.format(- "\"%s\"(len=%d,count=%d)",- truncateForLog(e.getKey()),- e.getKey().length(),- e.getValue()))- .collect(java.util.stream.Collectors.joining("; "));- log.debug(- "PDF JSON repeat scan ({}): top strings -> {}{}",- label,- summary,- capped ? " (capped)" : "");- } else {- log.debug(- "PDF JSON repeat scan ({}): no repeated strings found{}",- label,- capped ? " (capped)" : "");- }- }-- private boolean looksLikeBase64(String value) {- if (value.length() < 32) {- return false;- }- int base64Chars = 0;- for (int i = 0; i < value.length(); i++) {- char c = value.charAt(i);- if ((c >= 'A' && c <= 'Z')- || (c >= 'a' && c <= 'z')- || (c >= '0' && c <= '9')- || c == '+'- || c == '/'- || c == '=') {- base64Chars++;- }- }- return base64Chars >= value.length() * 0.9;- }-- private String truncateForLog(String value) {- int max = 64;- if (value.length() <= max) {- return WHITESPACE_PATTERN.matcher(value).replaceAll(" ");- }- return WHITESPACE_PATTERN.matcher(value.substring(0, max)).replaceAll(" ") + "...";- }-- private void validateJobAccess(String jobId) {- if (jobOwnershipService != null) {- jobOwnershipService.validateJobAccess(jobId);- }- }-}diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertPdfJsonExceptionHandler.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertPdfJsonExceptionHandler.javadeleted file mode 100644index a7d9d8c5bb..0000000000--- a/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertPdfJsonExceptionHandler.java+++ /dev/null@@ -1,60 +0,0 @@-package stirling.software.SPDF.controller.api.converters;--import java.nio.charset.StandardCharsets;--import org.springframework.http.HttpStatus;-import org.springframework.http.MediaType;-import org.springframework.http.ResponseEntity;-import org.springframework.web.bind.annotation.ControllerAdvice;-import org.springframework.web.bind.annotation.ExceptionHandler;-import org.springframework.web.bind.annotation.ResponseBody;--import lombok.RequiredArgsConstructor;-import lombok.extern.slf4j.Slf4j;--import stirling.software.SPDF.exception.CacheUnavailableException;--import tools.jackson.databind.ObjectMapper;--@ControllerAdvice(assignableTypes = ConvertPdfJsonController.class)-@Slf4j-@RequiredArgsConstructor-public class ConvertPdfJsonExceptionHandler {-- private final ObjectMapper objectMapper;-- @ExceptionHandler(CacheUnavailableException.class)- @ResponseBody- public ResponseEntity<byte[]> handleCacheUnavailable(CacheUnavailableException ex) {- try {- byte[] body =- objectMapper.writeValueAsBytes(- java.util.Map.of(- "error", "cache_unavailable",- "action", "reupload",- "message", ex.getMessage()));- return ResponseEntity.status(HttpStatus.GONE)- .contentType(MediaType.APPLICATION_JSON)- .body(body);- } catch (Exception e) {- log.warn("Failed to serialize cache_unavailable response", e);- var fallbackBody =- java.util.Map.of(- "error", "cache_unavailable",- "action", "reupload",- "message", String.valueOf(ex.getMessage()));- try {- return ResponseEntity.status(HttpStatus.GONE)- .contentType(MediaType.APPLICATION_JSON)- .body(objectMapper.writeValueAsBytes(fallbackBody));- } catch (Exception ignored) {- // Truly last-ditch fallback- return ResponseEntity.status(HttpStatus.GONE)- .contentType(MediaType.APPLICATION_JSON)- .body(- "{\"error\":\"cache_unavailable\",\"action\":\"reupload\",\"message\":\"Cache unavailable\"}"- .getBytes(StandardCharsets.UTF_8));- }- }- }-}diff --git a/app/core/src/main/java/stirling/software/SPDF/model/api/PdfJsonConversionProgress.java b/app/core/src/main/java/stirling/software/SPDF/model/api/PdfJsonConversionProgress.javadeleted file mode 100644index 75e41541a2..0000000000--- a/app/core/src/main/java/stirling/software/SPDF/model/api/PdfJsonConversionProgress.java+++ /dev/null@@ -1,49 +0,0 @@-package stirling.software.SPDF.model.api;--import lombok.AllArgsConstructor;-import lombok.Builder;-import lombok.Data;-import lombok.NoArgsConstructor;--@Data-@Builder-@NoArgsConstructor-@AllArgsConstructor-public class PdfJsonConversionProgress {- private int percent;- private String stage;- private String message;- private boolean complete;- private Integer current; // Current item being processed (e.g., page number)- private Integer total; // Total items to process (e.g., total pages)-- public static PdfJsonConversionProgress of(int percent, String stage, String message) {- return PdfJsonConversionProgress.builder()- .percent(percent)- .stage(stage)- .message(message)- .complete(false)- .build();- }-- public static PdfJsonConversionProgress of(- int percent, String stage, String message, int current, int total) {- return PdfJsonConversionProgress.builder()- .percent(percent)- .stage(stage)- .message(message)- .current(current)- .total(total)- .complete(false)- .build();- }-- public static PdfJsonConversionProgress complete() {- return PdfJsonConversionProgress.builder()- .percent(100)- .stage("complete")- .message("Conversion complete")- .complete(true)- .build();- }-}diff --git a/app/core/src/main/java/stirling/software/SPDF/model/api/general/EditTextRequest.java b/app/core/src/main/java/stirling/software/SPDF/model/api/general/EditTextRequest.javadeleted file mode 100644index 8130d0edc9..0000000000--- a/app/core/src/main/java/stirling/software/SPDF/model/api/general/EditTextRequest.java+++ /dev/null@@ -1,32 +0,0 @@-package stirling.software.SPDF.model.api.general;--import java.util.List;--import io.swagger.v3.oas.annotations.media.Schema;--import lombok.Data;-import lombok.EqualsAndHashCode;--import stirling.software.SPDF.model.api.PDFWithPageNums;-import stirling.software.common.model.api.general.EditTextOperation;--@Data-@EqualsAndHashCode(callSuper = true)-public class EditTextRequest extends PDFWithPageNums {-- @Schema(- description =- "Ordered list of find/replace operations. Each replaces every occurrence on"- + " the selected pages, in order; later operations see the result of"- + " earlier ones (so 'foo'->'foos' then 'foos'->'bars' turns 'foo'"- + " into 'bars').",- requiredMode = Schema.RequiredMode.REQUIRED)- private List<EditTextOperation> edits;-- @Schema(- description =- "Whether matches must be whole words (boundaries determined by non-word"- + " characters)",- defaultValue = "false")- private Boolean wholeWordSearch;-}diff --git a/app/core/src/main/java/stirling/software/SPDF/model/json/PdfJsonAnnotation.java b/app/core/src/main/java/stirling/software/SPDF/model/json/PdfJsonAnnotation.javadeleted file mode 100644index 2ce55c2007..0000000000--- a/app/core/src/main/java/stirling/software/SPDF/model/json/PdfJsonAnnotation.java+++ /dev/null@@ -1,59 +0,0 @@-package stirling.software.SPDF.model.json;--import com.fasterxml.jackson.annotation.JsonInclude;--import lombok.AllArgsConstructor;-import lombok.Builder;-import lombok.Data;-import lombok.NoArgsConstructor;--/**- * Represents a PDF annotation (comments, highlights, stamps, etc.). Annotations often contain OCR- * text layers or other metadata not visible in content streams.- */-@Data-@Builder-@NoArgsConstructor-@AllArgsConstructor-@JsonInclude(JsonInclude.Include.NON_NULL)-public class PdfJsonAnnotation {-- /** Annotation subtype (Text, Highlight, Link, Stamp, Widget, etc.) */- private String subtype;-- /** Human-readable text content of the annotation */- private String contents;-- /** Annotation rectangle [x1, y1, x2, y2] */- private float[] rect;-- /** Annotation appearance characteristics */- private String appearanceState;-- /** Color components (e.g., [r, g, b] for RGB) */- private float[] color;-- /** Annotation flags (print, hidden, etc.) */- private Integer flags;-- /** For link annotations: destination or action */- private String destination;-- /** For text annotations: icon name */- private String iconName;-- /** Subject/title of the annotation */- private String subject;-- /** Author of the annotation */- private String author;-- /** Creation date (ISO 8601 format) */- private String creationDate;-- /** Modification date (ISO 8601 format) */- private String modificationDate;-- /** Full annotation dictionary for lossless round-tripping */- private PdfJsonCosValue rawData;-}diff --git a/app/core/src/main/java/stirling/software/SPDF/model/json/PdfJsonCosValue.java b/app/core/src/main/java/stirling/software/SPDF/model/json/PdfJsonCosValue.javadeleted file mode 100644index 043414c4bd..0000000000--- a/app/core/src/main/java/stirling/software/SPDF/model/json/PdfJsonCosValue.java+++ /dev/null@@ -1,49 +0,0 @@-package stirling.software.SPDF.model.json;--import java.util.List;-import java.util.Map;--import com.fasterxml.jackson.annotation.JsonInclude;--import lombok.AllArgsConstructor;-import lombok.Builder;-import lombok.Data;-import lombok.NoArgsConstructor;--@Data-@Builder-@NoArgsConstructor-@AllArgsConstructor-@JsonInclude(JsonInclude.Include.NON_NULL)-public class PdfJsonCosValue {-- public enum Type {- NULL,- BOOLEAN,- INTEGER,- FLOAT,- NAME,- STRING,- ARRAY,- DICTIONARY,- STREAM- }-- private Type type;-- /**- * Holds the decoded value for primitives (boolean, integer, float, name, string). For name- * values the stored value is the PDF name literal. For string values the content is Base64- * encoded to safely transport arbitrary binaries.- */- private Object value;-- /** Reference to nested values for arrays. */- private List<PdfJsonCosValue> items;-- /** Reference to nested values for dictionaries. */- private Map<String, PdfJsonCosValue> entries;-- /** Stream payload when {@code type == STREAM}. */- private PdfJsonStream stream;-}diff --git a/app/core/src/main/java/stirling/software/SPDF/model/json/PdfJsonDocument.java b/app/core/src/main/java/stirling/software/SPDF/model/json/PdfJsonDocument.javadeleted file mode 100644index 856006748f..0000000000--- a/app/core/src/main/java/stirling/software/SPDF/model/json/PdfJsonDocument.java+++ /dev/null@@ -1,34 +0,0 @@-package stirling.software.SPDF.model.json;--import java.util.ArrayList;-import java.util.List;--import com.fasterxml.jackson.annotation.JsonInclude;--import lombok.AllArgsConstructor;-import lombok.Builder;-import lombok.Data;-import lombok.NoArgsConstructor;--@Data-@Builder-@NoArgsConstructor-@AllArgsConstructor-@JsonInclude(JsonInclude.Include.NON_DEFAULT)-public class PdfJsonDocument {-- private PdfJsonMetadata metadata;-- /** Optional XMP metadata packet stored as Base64. */- private String xmpMetadata;-- /** Indicates that images should be loaded lazily via API rather than embedded in the JSON. */- private boolean lazyImages;-- @Builder.Default private List<PdfJsonFont> fonts = new ArrayList<>();-- @Builder.Default private List<PdfJsonPage> pages = new ArrayList<>();-- /** Form fields (AcroForm) at document level */- @Builder.Default private List<PdfJsonFormField> formFields = new ArrayList<>();-}diff --git a/app/core/src/main/java/stirling/software/SPDF/model/json/PdfJsonDocumentMetadata.java b/app/core/src/main/java/stirling/software/SPDF/model/json/PdfJsonDocumentMetadata.javadeleted file mode 100644index 15819973e6..0000000000--- a/app/core/src/main/java/stirling/software/SPDF/model/json/PdfJsonDocumentMetadata.java+++ /dev/null@@ -1,34 +0,0 @@-package stirling.software.SPDF.model.json;--import java.util.ArrayList;-import java.util.List;--import com.fasterxml.jackson.annotation.JsonInclude;--import lombok.AllArgsConstructor;-import lombok.Builder;-import lombok.Data;-import lombok.NoArgsConstructor;--@Data-@Builder-@NoArgsConstructor-@AllArgsConstructor-@JsonInclude(JsonInclude.Include.NON_NULL)-public class PdfJsonDocumentMetadata {-- private PdfJsonMetadata metadata;-- /** Optional XMP metadata packet stored as Base64. */- private String xmpMetadata;-- /** Indicates that images should be requested lazily via the page endpoint. */- private Boolean lazyImages;-- @Builder.Default private List<PdfJsonFont> fonts = new ArrayList<>();-- @Builder.Default private List<PdfJsonPageDimension> pageDimensions = new ArrayList<>();-- /** Form fields (AcroForm) at document level */- @Builder.Default private List<PdfJsonFormField> formFields = new ArrayList<>();-}diff --git a/app/core/src/main/java/stirling/software/SPDF/model/json/PdfJsonFont.java b/app/core/src/main/java/stirling/software/SPDF/model/json/PdfJsonFont.javadeleted file mode 100644index 1fbbbd5b3f..0000000000--- a/app/core/src/main/java/stirling/software/SPDF/model/json/PdfJsonFont.java+++ /dev/null@@ -1,96 +0,0 @@-package stirling.software.SPDF.model.json;--import java.util.List;--import com.fasterxml.jackson.annotation.JsonInclude;--import lombok.AllArgsConstructor;-import lombok.Builder;-import lombok.Data;-import lombok.NoArgsConstructor;--@Data-@Builder-@NoArgsConstructor-@AllArgsConstructor-@JsonInclude(JsonInclude.Include.NON_NULL)-public class PdfJsonFont {-- /** PDF resource name (e.g. F1) used as the primary identifier. */- private String id;-- /** Logical page number that owns this font resource. */- private Integer pageNumber;-- /** Stable UID combining page number and resource for diagnostics. */- private String uid;-- /** Reported PostScript/Base font name. */- private String baseName;-- /** Declared subtype in the COS dictionary. */- private String subtype;-- /** Encoding dictionary or name. */- private String encoding;-- /** CID system info for Type0 fonts. */- private PdfJsonFontCidSystemInfo cidSystemInfo;-- /** True when the original PDF embedded the font program. */- private Boolean embedded;-- /** Font program bytes (TTF/OTF/CFF/PFB) encoded as Base64. */- private String program;-- /** Hint describing the font program type (ttf, otf, cff, pfb, etc.). */- private String programFormat;-- /** Web-optimized font program (e.g. converted TrueType) encoded as Base64. */- private String webProgram;-- /** Format hint for the webProgram payload. */- private String webProgramFormat;-- /** PDF-friendly font program (e.g. converted TrueType) encoded as Base64. */- private String pdfProgram;-- /** Format hint for the pdfProgram payload. */- private String pdfProgramFormat;-- /** Glyph metadata for Type3 fonts to enable precise text rewrites. */- private List<PdfJsonFontType3Glyph> type3Glyphs;-- /** Per-strategy synthesized font payloads for Type3 normalization. */- private List<PdfJsonFontConversionCandidate> conversionCandidates;-- /** ToUnicode stream encoded as Base64 when present. */- private String toUnicode;-- /** Mapped Standard 14 font name when available. */- private String standard14Name;-- /** Font descriptor flags copied from the source document. */- private Integer fontDescriptorFlags;-- /** Font ascent in glyph units (typically 1/1000). */- private Float ascent;-- /** Font descent in glyph units (typically negative). */- private Float descent;-- /** Capital height when available. */- private Float capHeight;-- /** x-height when available. */- private Float xHeight;-- /** Italic angle reported by the font descriptor. */- private Float italicAngle;-- /** Units per em extracted from the font matrix. */- private Integer unitsPerEm;-- /** Serialized COS dictionary describing the original font resource. */- private PdfJsonCosValue cosDictionary;-}diff --git a/app/core/src/main/java/stirling/software/SPDF/model/json/PdfJsonFontCidSystemInfo.java b/app/core/src/main/java/stirling/software/SPDF/model/json/PdfJsonFontCidSystemInfo.javadeleted file mode 100644index 7ddd20f5f7..0000000000--- a/app/core/src/main/java/stirling/software/SPDF/model/json/PdfJsonFontCidSystemInfo.java+++ /dev/null@@ -1,20 +0,0 @@-package stirling.software.SPDF.model.json;--import com.fasterxml.jackson.annotation.JsonInclude;--import lombok.AllArgsConstructor;-import lombok.Builder;-import lombok.Data;-import lombok.NoArgsConstructor;--@Data-@Builder-@NoArgsConstructor-@AllArgsConstructor-@JsonInclude(JsonInclude.Include.NON_NULL)-public class PdfJsonFontCidSystemInfo {-- private String registry;- private String ordering;- private Integer supplement;-}diff --git a/app/core/src/main/java/stirling/software/SPDF/model/json/PdfJsonFontConversionCandidate.java b/app/core/src/main/java/stirling/software/SPDF/model/json/PdfJsonFontConversionCandidate.javadeleted file mode 100644index ead2b0f9f1..0000000000--- a/app/core/src/main/java/stirling/software/SPDF/model/json/PdfJsonFontConversionCandidate.java+++ /dev/null@@ -1,67 +0,0 @@-package stirling.software.SPDF.model.json;--import com.fasterxml.jackson.annotation.JsonInclude;--import lombok.AllArgsConstructor;-import lombok.Builder;-import lombok.Data;-import lombok.NoArgsConstructor;--@Data-@Builder-@NoArgsConstructor-@AllArgsConstructor-@JsonInclude(JsonInclude.Include.NON_NULL)-public class PdfJsonFontConversionCandidate {-- /** Stable identifier for the strategy that produced this candidate. */- private String strategyId;-- /** Human-readable label for diagnostics and UI toggles. */- private String strategyLabel;-- /** Outcome of the conversion attempt. */- private PdfJsonFontConversionStatus status;-- /** Summary diagnostics or error details. */- private String message;-- /** Count of glyphs successfully synthesized. */- private Integer synthesizedGlyphs;-- /** Count of glyphs that could not be reproduced accurately. */- private Integer missingGlyphs;-- /** Approximate width delta (in glyph units) across the test sample. */- private Double widthDelta;-- /** Approximate bounding box delta (in glyph units). */- private Double bboxDelta;-- /** Base64-encoded font program (typically TTF/OTF) produced by the strategy. */- private String program;-- /** Format hint for {@link #program}. */- private String programFormat;-- /** Web-optimized payload (e.g. TTF) for browser preview. */- private String webProgram;-- /** Format for the web payload. */- private String webProgramFormat;-- /** PDF-friendly payload for re-embedding during export. */- private String pdfProgram;-- /** Format for the PDF payload. */- private String pdfProgramFormat;-- /** Optional PNG preview of rendered glyphs (Base64). */- private String previewImage;-- /** Additional structured diagnostics (JSON string). */- private String diagnostics;-- /** Known unicode/codepoint coverage derived from the conversion strategy. */- private int[] glyphCoverage;-}diff --git a/app/core/src/main/java/stirling/software/SPDF/model/json/PdfJsonFontConversionStatus.java b/app/core/src/main/java/stirling/software/SPDF/model/json/PdfJsonFontConversionStatus.javadeleted file mode 100644index 4d8c6b8e14..0000000000--- a/app/core/src/main/java/stirling/software/SPDF/model/json/PdfJsonFontConversionStatus.java+++ /dev/null@@ -1,9 +0,0 @@-package stirling.software.SPDF.model.json;--public enum PdfJsonFontConversionStatus {- SUCCESS,- WARNING,- FAILURE,- SKIPPED,- UNSUPPORTED-}diff --git a/app/core/src/main/java/stirling/software/SPDF/model/json/PdfJsonFontType3Glyph.java b/app/core/src/main/java/stirling/software/SPDF/model/json/PdfJsonFontType3Glyph.javadeleted file mode 100644index 510c6f0bac..0000000000--- a/app/core/src/main/java/stirling/software/SPDF/model/json/PdfJsonFontType3Glyph.java+++ /dev/null@@ -1,27 +0,0 @@-package stirling.software.SPDF.model.json;--import com.fasterxml.jackson.annotation.JsonInclude;--import lombok.AllArgsConstructor;-import lombok.Builder;-import lombok.Data;-import lombok.NoArgsConstructor;--@Data-@Builder-@NoArgsConstructor-@AllArgsConstructor-@JsonInclude(JsonInclude.Include.NON_NULL)-public class PdfJsonFontType3Glyph {- /** Character code used in the content stream to reference this glyph. */- private Integer charCode;-- /** PostScript glyph name, when available. */- private String glyphName;-- /** Unicode code point represented by this glyph, if it can be resolved. */- private Integer unicode;-- /** Raw char code used in the Type3 font encoding (0-255). */- private Integer charCodeRaw;-}diff --git a/app/core/src/main/java/stirling/software/SPDF/model/json/PdfJsonFormField.java b/app/core/src/main/java/stirling/software/SPDF/model/json/PdfJsonFormField.javadeleted file mode 100644index a475b09126..0000000000--- a/app/core/src/main/java/stirling/software/SPDF/model/json/PdfJsonFormField.java+++ /dev/null@@ -1,66 +0,0 @@-package stirling.software.SPDF.model.json;--import java.util.List;--import com.fasterxml.jackson.annotation.JsonInclude;--import lombok.AllArgsConstructor;-import lombok.Builder;-import lombok.Data;-import lombok.NoArgsConstructor;--/** Represents a PDF form field (AcroForm). */-@Data-@Builder-@NoArgsConstructor-@AllArgsConstructor-@JsonInclude(JsonInclude.Include.NON_NULL)-public class PdfJsonFormField {-- /** Fully qualified field name (e.g., "form1.textfield1") */- private String name;-- /** Partial field name (last component) */- private String partialName;-- /** Field type (Tx=text, Btn=button, Ch=choice, Sig=signature) */- private String fieldType;-- /** Field value as string */- private String value;-- /** Default value */- private String defaultValue;-- /** Field flags (readonly, required, multiline, etc.) */- private Integer flags;-- /** Alternative field name (for accessibility) */- private String alternateFieldName;-- /** Mapping name (for export) */- private String mappingName;-- /** Page number where field appears (1-indexed) */- private Integer pageNumber;-- /** Field rectangle [x1, y1, x2, y2] on the page */- private float[] rect;-- /** For choice fields: list of options */- private List<String> options;-- /** For choice fields: selected indices */- private int[] selectedIndices;-- /** For button fields: whether it's checked */- private Boolean checked;-- /** Font information for text fields */- private String fontName;-- private Float fontSize;-- /** Full field dictionary for lossless round-tripping */- private PdfJsonCosValue rawData;-}diff --git a/app/core/src/main/java/stirling/software/SPDF/model/json/PdfJsonImageElement.java b/app/core/src/main/java/stirling/software/SPDF/model/json/PdfJsonImageElement.javadeleted file mode 100644index 3e68034be0..0000000000--- a/app/core/src/main/java/stirling/software/SPDF/model/json/PdfJsonImageElement.java+++ /dev/null@@ -1,34 +0,0 @@-package stirling.software.SPDF.model.json;--import com.fasterxml.jackson.annotation.JsonInclude;--import lombok.AllArgsConstructor;-import lombok.Builder;-import lombok.Data;-import lombok.NoArgsConstructor;--@Data-@Builder-@NoArgsConstructor-@AllArgsConstructor-@JsonInclude(JsonInclude.Include.NON_NULL)-public class PdfJsonImageElement {-- private String id;- private String objectName;- private Boolean inlineImage;- private Integer nativeWidth;- private Integer nativeHeight;- private Float x;- private Float y;- private Float width;- private Float height;- private Float left;- private Float right;- private Float top;- private Float bottom;- private float[] transform;- private Integer zOrder;- private String imageData;- private String imageFormat;-}diff --git a/app/core/src/main/java/stirling/software/SPDF/model/json/PdfJsonMetadata.java b/app/core/src/main/java/stirling/software/SPDF/model/json/PdfJsonMetadata.javadeleted file mode 100644index 8db869ca5b..0000000000--- a/app/core/src/main/java/stirling/software/SPDF/model/json/PdfJsonMetadata.java+++ /dev/null@@ -1,27 +0,0 @@-package stirling.software.SPDF.model.json;--import com.fasterxml.jackson.annotation.JsonInclude;--import lombok.AllArgsConstructor;-import lombok.Builder;-import lombok.Data;-import lombok.NoArgsConstructor;--@Data-@Builder-@NoArgsConstructor-@AllArgsConstructor-@JsonInclude(JsonInclude.Include.NON_NULL)-public class PdfJsonMetadata {-- private String title;- private String author;- private String subject;- private String keywords;- private String creator;- private String producer;- private String creationDate;- private String modificationDate;- private String trapped;- private Integer numberOfPages;-}diff --git a/app/core/src/main/java/stirling/software/SPDF/model/json/PdfJsonPage.java b/app/core/src/main/java/stirling/software/SPDF/model/json/PdfJsonPage.javadeleted file mode 100644index fa1417d5c6..0000000000--- a/app/core/src/main/java/stirling/software/SPDF/model/json/PdfJsonPage.java+++ /dev/null@@ -1,34 +0,0 @@-package stirling.software.SPDF.model.json;--import java.util.ArrayList;-import java.util.List;--import com.fasterxml.jackson.annotation.JsonInclude;--import lombok.AllArgsConstructor;-import lombok.Builder;-import lombok.Data;-import lombok.NoArgsConstructor;--@Data-@Builder-@NoArgsConstructor-@AllArgsConstructor-@JsonInclude(JsonInclude.Include.NON_NULL)-public class PdfJsonPage {-- private Integer pageNumber;- private Float width;- private Float height;- private Integer rotation;-- @Builder.Default private List<PdfJsonTextElement> textElements = new ArrayList<>();- @Builder.Default private List<PdfJsonImageElement> imageElements = new ArrayList<>();- @Builder.Default private List<PdfJsonAnnotation> annotations = new ArrayList<>();-- /** Serialized representation of the page resources dictionary. */- private PdfJsonCosValue resources;-- /** Raw content streams associated with the page, preserved for lossless round-tripping. */- @Builder.Default private List<PdfJsonStream> contentStreams = new ArrayList<>();-}diff --git a/app/core/src/main/java/stirling/software/SPDF/model/json/PdfJsonPageDimension.java b/app/core/src/main/java/stirling/software/SPDF/model/json/PdfJsonPageDimension.javadeleted file mode 100644index ff9eda9241..0000000000--- a/app/core/src/main/java/stirling/software/SPDF/model/json/PdfJsonPageDimension.java+++ /dev/null@@ -1,20 +0,0 @@-package stirling.software.SPDF.model.json;--import com.fasterxml.jackson.annotation.JsonInclude;--import lombok.AllArgsConstructor;-import lombok.Builder;-import lombok.Data;-import lombok.NoArgsConstructor;--@Data-@Builder-@NoArgsConstructor-@AllArgsConstructor-@JsonInclude(JsonInclude.Include.NON_DEFAULT)-public class PdfJsonPageDimension {- private int pageNumber;- private float width;- private float height;- private int rotation;-}diff --git a/app/core/src/main/java/stirling/software/SPDF/model/json/PdfJsonStream.java b/app/core/src/main/java/stirling/software/SPDF/model/json/PdfJsonStream.javadeleted file mode 100644index eb8ca66a27..0000000000--- a/app/core/src/main/java/stirling/software/SPDF/model/json/PdfJsonStream.java+++ /dev/null@@ -1,27 +0,0 @@-package stirling.software.SPDF.model.json;--import java.util.Map;--import com.fasterxml.jackson.annotation.JsonInclude;--import lombok.AllArgsConstructor;-import lombok.Builder;-import lombok.Data;-import lombok.NoArgsConstructor;--@Data-@Builder-@NoArgsConstructor-@AllArgsConstructor-@JsonInclude(JsonInclude.Include.NON_NULL)-public class PdfJsonStream {-- /**- * A dictionary of entries that describe the stream metadata (Filter, DecodeParms, etc). Each- * entry is represented using {@link PdfJsonCosValue} so nested structures are supported.- */- private Map<String, PdfJsonCosValue> dictionary;-- /** Raw stream bytes in Base64 form. Data is stored exactly as it appeared in the source PDF. */- private String rawData;-}diff --git a/app/core/src/main/java/stirling/software/SPDF/model/json/PdfJsonTextColor.java b/app/core/src/main/java/stirling/software/SPDF/model/json/PdfJsonTextColor.javadeleted file mode 100644index 7d9561f165..0000000000--- a/app/core/src/main/java/stirling/software/SPDF/model/json/PdfJsonTextColor.java+++ /dev/null@@ -1,19 +0,0 @@-package stirling.software.SPDF.model.json;--import com.fasterxml.jackson.annotation.JsonInclude;--import lombok.AllArgsConstructor;-import lombok.Builder;-import lombok.Data;-import lombok.NoArgsConstructor;--@Data-@Builder-@NoArgsConstructor-@AllArgsConstructor-@JsonInclude(JsonInclude.Include.NON_NULL)-public class PdfJsonTextColor {-- private String colorSpace;- private float[] components;-}diff --git a/app/core/src/main/java/stirling/software/SPDF/model/json/PdfJsonTextElement.java b/app/core/src/main/java/stirling/software/SPDF/model/json/PdfJsonTextElement.javadeleted file mode 100644index f56c8ff538..0000000000--- a/app/core/src/main/java/stirling/software/SPDF/model/json/PdfJsonTextElement.java+++ /dev/null@@ -1,39 +0,0 @@-package stirling.software.SPDF.model.json;--import com.fasterxml.jackson.annotation.JsonInclude;--import lombok.AllArgsConstructor;-import lombok.Builder;-import lombok.Data;-import lombok.NoArgsConstructor;--@Data-@Builder-@NoArgsConstructor-@AllArgsConstructor-@JsonInclude(JsonInclude.Include.NON_NULL)-public class PdfJsonTextElement {-- private String text;- private String fontId;- private Float fontSize;- private Float fontMatrixSize;- private Float fontSizeInPt;- private Float characterSpacing;- private Float wordSpacing;- private Float spaceWidth;- private Integer zOrder;- private Float horizontalScaling;- private Float leading;- private Float rise;- private Float x;- private Float y;- private Float width;- private Float height;- private float[] textMatrix;- private PdfJsonTextColor fillColor;- private PdfJsonTextColor strokeColor;- private Integer renderingMode;- private Boolean fallbackUsed;- private int[] charCodes;-}diff --git a/app/core/src/main/java/stirling/software/SPDF/service/pdfjson/JobOwnershipServiceImpl.java b/app/core/src/main/java/stirling/software/SPDF/service/JobOwnershipServiceImpl.javasimilarity index 99%rename from app/core/src/main/java/stirling/software/SPDF/service/pdfjson/JobOwnershipServiceImpl.javarename to app/core/src/main/java/stirling/software/SPDF/service/JobOwnershipServiceImpl.javaindex 2cca1a535d..7f7dca7cdd 100644--- a/app/core/src/main/java/stirling/software/SPDF/service/pdfjson/JobOwnershipServiceImpl.java+++ b/app/core/src/main/java/stirling/software/SPDF/service/JobOwnershipServiceImpl.java@@ -1,4 +1,4 @@-package stirling.software.SPDF.service.pdfjson;+package stirling.software.SPDF.service;import java.util.Optional;diff --git a/app/core/src/main/java/stirling/software/SPDF/service/pdfjson/NoOpJobOwnershipService.java b/app/core/src/main/java/stirling/software/SPDF/service/NoOpJobOwnershipService.javasimilarity index 96%rename from app/core/src/main/java/stirling/software/SPDF/service/pdfjson/NoOpJobOwnershipService.javarename to app/core/src/main/java/stirling/software/SPDF/service/NoOpJobOwnershipService.javaindex 24eb149e16..3a7b5da868 100644--- a/app/core/src/main/java/stirling/software/SPDF/service/pdfjson/NoOpJobOwnershipService.java+++ b/app/core/src/main/java/stirling/software/SPDF/service/NoOpJobOwnershipService.java@@ -1,4 +1,4 @@-package stirling.software.SPDF.service.pdfjson;+package stirling.software.SPDF.service;import java.util.Optional;diff --git a/app/core/src/main/java/stirling/software/SPDF/service/PdfJsonConversionService.java b/app/core/src/main/java/stirling/software/SPDF/service/PdfJsonConversionService.javadeleted file mode 100644index ff5fcc527e..0000000000--- a/app/core/src/main/java/stirling/software/SPDF/service/PdfJsonConversionService.java+++ /dev/null@@ -1,6965 +0,0 @@-package stirling.software.SPDF.service;--import static stirling.software.SPDF.service.PdfJsonFallbackFontService.FALLBACK_FONT_ID;--import java.awt.geom.AffineTransform;-import java.awt.geom.Point2D;-import java.awt.image.BufferedImage;-import java.io.ByteArrayInputStream;-import java.io.ByteArrayOutputStream;-import java.io.IOException;-import java.io.InputStream;-import java.io.OutputStream;-import java.nio.charset.StandardCharsets;-import java.nio.file.Files;-import java.nio.file.Path;-import java.time.Instant;-import java.time.format.DateTimeParseException;-import java.util.ArrayList;-import java.util.Base64;-import java.util.Calendar;-import java.util.Collection;-import java.util.Collections;-import java.util.Comparator;-import java.util.HashMap;-import java.util.HashSet;-import java.util.IdentityHashMap;-import java.util.Iterator;-import java.util.LinkedHashMap;-import java.util.LinkedHashSet;-import java.util.List;-import java.util.Locale;-import java.util.Map;-import java.util.Objects;-import java.util.Optional;-import java.util.Set;-import java.util.TimeZone;-import java.util.UUID;-import java.util.concurrent.ConcurrentHashMap;-import java.util.concurrent.TimeUnit;-import java.util.function.Consumer;-import java.util.regex.Pattern;-import java.util.stream.Collectors;--import javax.imageio.ImageIO;--import org.apache.pdfbox.contentstream.PDFGraphicsStreamEngine;-import org.apache.pdfbox.contentstream.operator.Operator;-import org.apache.pdfbox.contentstream.operator.OperatorName;-import org.apache.pdfbox.cos.COSArray;-import org.apache.pdfbox.cos.COSBase;-import org.apache.pdfbox.cos.COSDictionary;-import org.apache.pdfbox.cos.COSName;-import org.apache.pdfbox.cos.COSStream;-import org.apache.pdfbox.cos.COSString;-import org.apache.pdfbox.pdfparser.PDFStreamParser;-import org.apache.pdfbox.pdfwriter.ContentStreamWriter;-import org.apache.pdfbox.pdmodel.PDDocument;-import org.apache.pdfbox.pdmodel.PDDocumentInformation;-import org.apache.pdfbox.pdmodel.PDPage;-import org.apache.pdfbox.pdmodel.PDPageContentStream;-import org.apache.pdfbox.pdmodel.PDPageContentStream.AppendMode;-import org.apache.pdfbox.pdmodel.PDResources;-import org.apache.pdfbox.pdmodel.common.PDMetadata;-import org.apache.pdfbox.pdmodel.common.PDRectangle;-import org.apache.pdfbox.pdmodel.common.PDStream;-import org.apache.pdfbox.pdmodel.font.PDFont;-import org.apache.pdfbox.pdmodel.font.PDFontDescriptor;-import org.apache.pdfbox.pdmodel.font.PDFontFactory;-import org.apache.pdfbox.pdmodel.font.PDType0Font;-import org.apache.pdfbox.pdmodel.font.PDType1Font;-import org.apache.pdfbox.pdmodel.font.PDType3Font;-import org.apache.pdfbox.pdmodel.font.Standard14Fonts;-import org.apache.pdfbox.pdmodel.graphics.PDXObject;-import org.apache.pdfbox.pdmodel.graphics.color.PDColor;-import org.apache.pdfbox.pdmodel.graphics.color.PDColorSpace;-import org.apache.pdfbox.pdmodel.graphics.form.PDFormXObject;-import org.apache.pdfbox.pdmodel.graphics.image.PDImage;-import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;-import org.apache.pdfbox.pdmodel.graphics.state.PDGraphicsState;-import org.apache.pdfbox.pdmodel.graphics.state.PDTextState;-import org.apache.pdfbox.pdmodel.graphics.state.RenderingMode;-import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotation;-import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationWidget;-import org.apache.pdfbox.pdmodel.interactive.form.PDAcroForm;-import org.apache.pdfbox.pdmodel.interactive.form.PDField;-import org.apache.pdfbox.text.PDFTextStripper;-import org.apache.pdfbox.text.TextPosition;-import org.apache.pdfbox.util.DateConverter;-import org.apache.pdfbox.util.Matrix;-import org.springframework.stereotype.Service;-import org.springframework.web.multipart.MultipartFile;--import jakarta.annotation.PostConstruct;--import lombok.RequiredArgsConstructor;-import lombok.extern.slf4j.Slf4j;--import stirling.software.SPDF.config.EndpointConfiguration;-import stirling.software.SPDF.model.api.PdfJsonConversionProgress;-import stirling.software.SPDF.model.json.PdfJsonAnnotation;-import stirling.software.SPDF.model.json.PdfJsonCosValue;-import stirling.software.SPDF.model.json.PdfJsonDocument;-import stirling.software.SPDF.model.json.PdfJsonDocumentMetadata;-import stirling.software.SPDF.model.json.PdfJsonFont;-import stirling.software.SPDF.model.json.PdfJsonFontCidSystemInfo;-import stirling.software.SPDF.model.json.PdfJsonFontConversionCandidate;-import stirling.software.SPDF.model.json.PdfJsonFontConversionStatus;-import stirling.software.SPDF.model.json.PdfJsonFontType3Glyph;-import stirling.software.SPDF.model.json.PdfJsonFormField;-import stirling.software.SPDF.model.json.PdfJsonImageElement;-import stirling.software.SPDF.model.json.PdfJsonMetadata;-import stirling.software.SPDF.model.json.PdfJsonPage;-import stirling.software.SPDF.model.json.PdfJsonPageDimension;-import stirling.software.SPDF.model.json.PdfJsonStream;-import stirling.software.SPDF.model.json.PdfJsonTextColor;-import stirling.software.SPDF.model.json.PdfJsonTextElement;-import stirling.software.SPDF.service.pdfjson.PdfJsonFontService;-import stirling.software.SPDF.service.pdfjson.type3.Type3ConversionRequest;-import stirling.software.SPDF.service.pdfjson.type3.Type3FontConversionService;-import stirling.software.SPDF.service.pdfjson.type3.Type3GlyphExtractor;-import stirling.software.SPDF.service.pdfjson.type3.model.Type3GlyphOutline;-import stirling.software.common.service.CustomPDFDocumentFactory;-import stirling.software.common.service.TaskManager;-import stirling.software.common.util.ExceptionUtils;-import stirling.software.common.util.ProcessExecutor;-import stirling.software.common.util.ProcessExecutor.ProcessExecutorResult;-import stirling.software.common.util.TempFile;-import stirling.software.common.util.TempFileManager;--import tools.jackson.databind.ObjectMapper;--@Slf4j-@Service-@RequiredArgsConstructor-public class PdfJsonConversionService {-- private static final Pattern WHITESPACE_PATTERN = Pattern.compile("\\s+");- private static final Pattern WHITESPACE_DASH_UNDERSCORE_PATTERN = Pattern.compile("[\\s\\-_]");- private static final Pattern FONT_SUBSET_PREFIX_PATTERN = Pattern.compile("^[A-Z]{6}\\+");- private final CustomPDFDocumentFactory pdfDocumentFactory;- private final ObjectMapper objectMapper;- private final EndpointConfiguration endpointConfiguration;- private final TempFileManager tempFileManager;- private final TaskManager taskManager;- private final PdfJsonCosMapper cosMapper;- private final PdfJsonFallbackFontService fallbackFontService;- private final PdfJsonFontService fontService;- private final Type3FontConversionService type3FontConversionService;- private final Type3GlyphExtractor type3GlyphExtractor;- private final stirling.software.common.model.ApplicationProperties applicationProperties;- private final Map<String, PDFont> type3NormalizedFontCache = new ConcurrentHashMap<>();- private final Map<String, Set<Integer>> type3GlyphCoverageCache = new ConcurrentHashMap<>();-- private boolean fontNormalizationEnabled;- private long cacheMaxBytes;- private int cacheMaxPercent;-- /** Cache for storing PDDocuments for lazy page loading. Key is jobId. */- private final Map<String, CachedPdfDocument> documentCache = new ConcurrentHashMap<>();-- private final java.util.LinkedHashMap<String, CachedPdfDocument> lruCache =- new java.util.LinkedHashMap<>(16, 0.75f, true);- private final Object cacheLock = new Object();- private volatile long currentCacheBytes = 0L;- private volatile long cacheBudgetBytes = -1L;-- private volatile boolean ghostscriptAvailable;-- private static final float FLOAT_EPSILON = 0.0001f;- private static final float ORIENTATION_TOLERANCE = 0.0005f;- private static final float BASELINE_TOLERANCE = 0.5f;-- @PostConstruct- private void initializeToolAvailability() {- loadConfigurationFromProperties();- initializeGhostscriptAvailability();- initializeCacheBudget();- }-- private void loadConfigurationFromProperties() {- stirling.software.common.model.ApplicationProperties.PdfEditor cfg =- applicationProperties.getPdfEditor();- if (cfg != null) {- fontNormalizationEnabled = cfg.getFontNormalization().isEnabled();- cacheMaxBytes = cfg.getCache().getMaxBytes();- cacheMaxPercent = cfg.getCache().getMaxPercent();- } else {- fontNormalizationEnabled = false;- cacheMaxBytes = -1;- cacheMaxPercent = 20;- }- }-- private void initializeGhostscriptAvailability() {- if (!fontNormalizationEnabled) {- ghostscriptAvailable = false;- return;- }-- if (!isGhostscriptGroupEnabled()) {- ghostscriptAvailable = false;- log.warn(- "Ghostscript font normalization disabled: Ghostscript group is not enabled in configuration");- return;- }-- List<String> command = List.of("gs", "-version");- try {- ProcessExecutorResult result =- ProcessExecutor.getInstance(ProcessExecutor.Processes.GHOSTSCRIPT)- .runCommandWithOutputHandling(command);- ghostscriptAvailable = result.getRc() == 0;- if (!ghostscriptAvailable) {- log.warn(- "Ghostscript executable not available (exit code {}); font normalization will be skipped",- result.getRc());- }- } catch (InterruptedException ex) {- Thread.currentThread().interrupt();- ghostscriptAvailable = false;- log.warn(- "Ghostscript availability check interrupted; font normalization will be skipped: {}",- ex.getMessage());- } catch (IOException ex) {- ghostscriptAvailable = false;- log.warn(- "Ghostscript executable not found or failed to start; font normalization will be skipped: {}",- ex.getMessage());- }- }-- private void initializeCacheBudget() {- long effective = -1L;- if (cacheMaxBytes > 0) {- effective = cacheMaxBytes;- } else if (cacheMaxPercent > 0) {- long maxMem = Runtime.getRuntime().maxMemory();- effective = Math.max(0L, (maxMem * cacheMaxPercent) / 100);- }- cacheBudgetBytes = effective;- if (cacheBudgetBytes > 0) {- log.debug(- "PDF JSON cache budget configured: {} bytes (source: {})",- cacheBudgetBytes,- cacheMaxBytes > 0 ? "max-bytes" : "max-percent");- } else {- log.debug("PDF JSON cache budget: unlimited");- }- }-- public void convertPdfToJson(MultipartFile file, OutputStream out) throws IOException {- convertPdfToJson(file, null, false, out);- }-- /**- * Converts a PDF to the editable {@link PdfJsonDocument} model. Convenience wrapper around- * {@link #convertPdfToJson(MultipartFile, OutputStream)} for callers that need to inspect or- * mutate the document in memory before round-tripping it back to PDF.- */- public PdfJsonDocument convertPdfToJsonDocument(MultipartFile file) throws IOException {- ByteArrayOutputStream buffer = new ByteArrayOutputStream();- convertPdfToJson(file, null, false, buffer);- return objectMapper.readValue(buffer.toByteArray(), PdfJsonDocument.class);- }-- public void convertPdfToJson(MultipartFile file, boolean lightweight, OutputStream out)- throws IOException {- convertPdfToJson(file, null, lightweight, out);- }-- public void convertPdfToJson(- MultipartFile file,- Consumer<PdfJsonConversionProgress> progressCallback,- OutputStream out)- throws IOException {- convertPdfToJson(file, progressCallback, false, out);- }-- public void convertPdfToJson(- MultipartFile file,- Consumer<PdfJsonConversionProgress> progressCallback,- boolean lightweight,- OutputStream out)- throws IOException {- if (file == null) {- throw ExceptionUtils.createNullArgumentException("fileInput");- }-- // Get job ID from request context if running in async mode- String contextJobId = getJobIdFromRequest();- boolean useLazyImages = (contextJobId != null && !contextJobId.isEmpty());-- // Generate synthetic jobId for synchronous conversions to prevent cache collisions- final String jobId;- if (!useLazyImages) {- jobId = "pdf2json:" + java.util.UUID.randomUUID().toString();- log.debug("Generated synthetic jobId for synchronous conversion: {}", jobId);- } else {- jobId = contextJobId;- log.info(- "Starting PDF to JSON conversion, jobId from context: {} (lightweight={})",- jobId,- lightweight);- }-- Consumer<PdfJsonConversionProgress> progress =- progressCallback != null- ? (p) -> {- log.debug(- "Progress: [{}%] {} - {}{}",- p.getPercent(),- p.getStage(),- p.getMessage(),- (p.getCurrent() != null && p.getTotal() != null)- ? String.format(- " (%d/%d)", p.getCurrent(), p.getTotal())- : "");- progressCallback.accept(p);- }- : useLazyImages- ? (p) -> {- log.debug(- "Progress: [{}%] {} - {}{}",- p.getPercent(),- p.getStage(),- p.getMessage(),- (p.getCurrent() != null && p.getTotal() != null)- ? String.format(- " (%d/%d)",- p.getCurrent(), p.getTotal())- : "");- reportProgressToTaskManager(jobId, p);- }- : (p) -> {- log.debug(- "Progress (no job): [{}%] {} - {}{}",- p.getPercent(),- p.getStage(),- p.getMessage(),- (p.getCurrent() != null && p.getTotal() != null)- ? String.format(- " (%d/%d)",- p.getCurrent(), p.getTotal())- : "");- };-- TempFile normalizedFile = null;- try (TempFile originalFile = new TempFile(tempFileManager, ".pdf")) {- progress.accept(PdfJsonConversionProgress.of(5, "loading", "Loading PDF document"));- file.transferTo(originalFile.getFile());- Path workingPath = originalFile.getPath();-- if (fontNormalizationEnabled && canRunGhostscript()) {- try {- progress.accept(- PdfJsonConversionProgress.of(- 10, "normalizing", "Normalizing fonts with Ghostscript"));- normalizedFile = normalizePdfFonts(workingPath);- if (normalizedFile != null && normalizedFile.exists()) {- workingPath = normalizedFile.getPath();- log.debug("Using Ghostscript-normalized PDF for JSON export");- }- } catch (IOException ex) {- log.warn(- "Ghostscript font normalization failed ({}); using original PDF",- ex.getMessage());- closeQuietly(normalizedFile);- normalizedFile = null;- }- }-- progress.accept(PdfJsonConversionProgress.of(20, "parsing", "Parsing PDF structure"));-- byte[] cachedPdfBytes = null;-- // Pre-read file bytes before loading PDDocument, since loading may delete the file- // (small files get loaded into memory and original is deleted)- // This is needed for lazy image caching where we need the bytes later- if (Files.size(workingPath) <= CustomPDFDocumentFactory.SMALL_FILE_THRESHOLD) {- cachedPdfBytes = Files.readAllBytes(workingPath);- }-- try (PDDocument document = pdfDocumentFactory.load(workingPath, true)) {- int totalPages = document.getNumberOfPages();- // Always enable lazy mode for real async jobs so cache is available regardless of- // page count. Synchronous calls with synthetic jobId still do full extraction.- Map<COSBase, FontModelCacheEntry> fontCache = new IdentityHashMap<>();- Map<COSBase, EncodedImage> imageCache = new IdentityHashMap<>();- log.debug(- "Converting PDF to JSON ({} pages) - {} mode (jobId: {}, isRealJobId: {})",- totalPages,- useLazyImages ? "lazy image" : "standard",- jobId,- useLazyImages);- Map<String, PdfJsonFont> fonts = new LinkedHashMap<>();- Map<Integer, List<PdfJsonTextElement>> textByPage = new LinkedHashMap<>();- Map<Integer, Map<PDFont, String>> pageFontResources = new HashMap<>();-- progress.accept(- PdfJsonConversionProgress.of(30, "fonts", "Collecting font information"));- int pageNumber = 1;- for (PDPage page : document.getPages()) {- Map<PDFont, String> resourceMap =- collectFontsForPage(- document, page, pageNumber, fonts, fontCache, jobId);- pageFontResources.put(pageNumber, resourceMap);- log.debug(- "PDF->JSON: collected {} font resources on page {}",- resourceMap.size(),- pageNumber);-- // Update progress for font collection (30-50%)- int fontProgress = 30 + (int) ((pageNumber / (double) totalPages) * 20);- progress.accept(- PdfJsonConversionProgress.of(- fontProgress,- "fonts",- "Collecting fonts",- pageNumber,- totalPages));- pageNumber++;- }-- progress.accept(- PdfJsonConversionProgress.of(50, "text", "Extracting text content"));- TextCollectingStripper stripper =- new TextCollectingStripper(- document, fonts, textByPage, pageFontResources, fontCache, jobId);- stripper.setSortByPosition(true);- stripper.getText(document);-- Map<Integer, List<PdfJsonImageElement>> imagesByPage;- if (useLazyImages) {- progress.accept(- PdfJsonConversionProgress.of(- 70, "images", "Skipping upfront image extraction"));- imagesByPage = new LinkedHashMap<>();- } else {- progress.accept(- PdfJsonConversionProgress.of(- 70, "images", "Extracting embedded images"));- imagesByPage = collectImages(document, totalPages, progress, imageCache);- }-- progress.accept(- PdfJsonConversionProgress.of(- 80, "annotations", "Collecting annotations and form fields"));- boolean includeAnnotationRawData = !(lightweight && useLazyImages);- Map<Integer, List<PdfJsonAnnotation>> annotationsByPage =- collectAnnotations(- document, totalPages, progress, includeAnnotationRawData);-- progress.accept(- PdfJsonConversionProgress.of(90, "metadata", "Extracting metadata"));- PdfJsonDocument pdfJson = new PdfJsonDocument();- pdfJson.setMetadata(extractMetadata(document));- pdfJson.setXmpMetadata(extractXmpMetadata(document));- pdfJson.setLazyImages(useLazyImages);- List<PdfJsonFont> cachedFonts = cloneFontList(fonts.values());- cachedFonts.sort(- Comparator.comparing(- PdfJsonFont::getUid,- Comparator.nullsLast(Comparator.naturalOrder())));- dedupeFontPayloads(cachedFonts);- Map<String, PdfJsonFont> cachedFontMap = new LinkedHashMap<>();- for (PdfJsonFont cachedFont : cachedFonts) {- String cacheKey = resolveFontCacheKey(cachedFont);- if (cacheKey != null) {- cachedFontMap.put(cacheKey, cachedFont);- }- }- List<PdfJsonFont> responseFonts = cloneFontList(cachedFonts);- pdfJson.setFonts(responseFonts);- pdfJson.setPages(- extractPages(- document,- textByPage,- imagesByPage,- annotationsByPage,- lightweight && useLazyImages));- if (lightweight && useLazyImages) {- // Lightweight async editor flow does not use form fields and this payload can- // be- // very large due nested raw dictionaries.- pdfJson.setFormFields(null);- } else {- pdfJson.setFormFields(collectFormFields(document));- }-- // Only cache for real async jobIds, not synthetic synchronous ones- if (useLazyImages) {- log.debug(- "Creating cache for jobId: {} (useLazyImages={})",- jobId,- useLazyImages);- PdfJsonDocumentMetadata docMetadata = new PdfJsonDocumentMetadata();- docMetadata.setMetadata(pdfJson.getMetadata());- docMetadata.setXmpMetadata(pdfJson.getXmpMetadata());- docMetadata.setFonts(cloneFontList(responseFonts));- docMetadata.setFormFields(pdfJson.getFormFields());- docMetadata.setLazyImages(Boolean.TRUE);-- List<PdfJsonPageDimension> pageDimensions = new ArrayList<>();- int pageIndex = 0;- for (PDPage page : document.getPages()) {- PdfJsonPageDimension dim = new PdfJsonPageDimension();- dim.setPageNumber(pageIndex + 1);- // Use CropBox if present (defines visible page area), otherwise fall back- // to MediaBox- PDRectangle pageBox = page.getCropBox();- if (pageBox == null- || pageBox.getWidth() == 0- || pageBox.getHeight() == 0) {- pageBox = page.getMediaBox();- }- dim.setWidth(pageBox.getWidth());- dim.setHeight(pageBox.getHeight());- dim.setRotation(page.getRotation());- pageDimensions.add(dim);- pageIndex++;- }- docMetadata.setPageDimensions(pageDimensions);-- if (cachedPdfBytes == null) {- cachedPdfBytes = Files.readAllBytes(workingPath);- }- CachedPdfDocument cached =- buildCachedDocument(- jobId,- cachedPdfBytes,- docMetadata,- cachedFontMap,- pageFontResources);- putCachedDocument(jobId, cached);- log.info(- "Successfully cached PDF ({} bytes, {} pages, {} fonts) for jobId: {} (diskBacked={})",- cached.getPdfSize(),- totalPages,- fonts.size(),- jobId,- cached.isDiskBacked());- scheduleDocumentCleanup(jobId);- } else {- log.warn(- "Skipping cache creation: useLazyImages={}, jobId={}",- useLazyImages,- jobId);- }-- if (lightweight) {- applyLightweightTransformations(pdfJson);- }- if (lightweight && useLazyImages) {- stripFontProgramPayloads(responseFonts);- stripFontCosStreamData(responseFonts);- }-- logFontPayloadStats(responseFonts, "pdf/text-editor");- analyzePdfJson(pdfJson, "pdf/text-editor");-- progress.accept(- PdfJsonConversionProgress.of(95, "serializing", "Generating JSON output"));-- // Collect font issues for summary- java.util.List<String> fontsWithMissingProgram =- responseFonts.stream()- .filter(- f ->- Boolean.TRUE.equals(f.getEmbedded())- && !(hasPayload(f.getProgram())- || hasPayload(f.getPdfProgram())- || hasPayload(f.getWebProgram())))- .map(- f -> {- String name =- f.getBaseName() != null- ? f.getBaseName()- : "Unknown";- String subtype =- f.getSubtype() != null- ? f.getSubtype()- : "Unknown";- // Clean up subset prefix (e.g., "ABCDEF+TimesNewRoman"- // -> "TimesNewRoman")- String cleanName =- FONT_SUBSET_PREFIX_PATTERN- .matcher(name)- .replaceAll("");- return String.format("%s (%s)", cleanName, subtype);- })- .toList();- long type3Fonts =- responseFonts.stream().filter(f -> "Type3".equals(f.getSubtype())).count();-- if (!fontsWithMissingProgram.isEmpty()) {- log.warn(- "PDF->JSON conversion complete: {} fonts ({} Type3), {} pages. Missing font programs for {} embedded font(s): {}",- responseFonts.size(),- type3Fonts,- pdfJson.getPages().size(),- fontsWithMissingProgram.size(),- String.join(", ", fontsWithMissingProgram));- } else {- log.info(- "PDF->JSON conversion complete: {} fonts ({} Type3), {} pages",- responseFonts.size(),- type3Fonts,- pdfJson.getPages().size());- }-- // Stream JSON directly to the caller's OutputStream to avoid allocating the- // entire document on the heap before writing it out.- objectMapper.writeValue(out, pdfJson);- progress.accept(PdfJsonConversionProgress.complete());-- // Clear Type3 cache entries immediately for non-cached conversions- // Cached conversions (useLazyImages=true) are cleaned when cache expires- // Synchronous conversions always clear immediately since they don't use lazy mode- if (!useLazyImages) {- clearType3CacheEntriesForJob(jobId);- }- }- } finally {- closeQuietly(normalizedFile);- }- }-- public void convertJsonToPdf(MultipartFile file, OutputStream out) throws IOException {- if (file == null) {- throw ExceptionUtils.createNullArgumentException("fileInput");- }- byte[] jsonBytes = file.getBytes();- PdfJsonDocument pdfJson = objectMapper.readValue(jsonBytes, PdfJsonDocument.class);- convertJsonToPdf(pdfJson, out);- }-- public void convertJsonToPdf(PdfJsonDocument pdfJson, OutputStream out) throws IOException {- if (pdfJson == null) {- throw ExceptionUtils.createNullArgumentException("document");- }-- List<PdfJsonFont> fontModels = pdfJson.getFonts();- if (fontModels == null) {- fontModels = new ArrayList<>();- pdfJson.setFonts(fontModels);- }-- // Generate synthetic jobId for this JSON->PDF conversion to prevent cache collisions- // Each conversion gets its own namespace for Type3 font caching- String syntheticJobId = "json2pdf:" + java.util.UUID.randomUUID().toString();-- try (PDDocument document = new PDDocument()) {- applyMetadata(document, pdfJson.getMetadata());- applyXmpMetadata(document, pdfJson.getXmpMetadata());-- Map<String, PDFont> fontMap = buildFontMap(document, fontModels, syntheticJobId);- log.debug("Converting JSON to PDF ({} font resources)", fontMap.size());-- Map<String, PdfJsonFont> fontLookup = buildFontModelLookup(fontModels);-- List<PdfJsonPage> pages = pdfJson.getPages();- if (pages == null) {- pages = new ArrayList<>();- }-- int pageIndex = 0;- Set<String> allFallbackFontIds = new java.util.HashSet<>();- int pagesWithFallbacks = 0;- for (PdfJsonPage pageModel : pages) {- int pageNumberValue =- pageModel.getPageNumber() != null- ? pageModel.getPageNumber()- : pageIndex + 1;- log.debug("Reconstructing page {}", pageNumberValue);- PDRectangle pageSize =- new PDRectangle(- safeFloat(pageModel.getWidth(), 612f),- safeFloat(pageModel.getHeight(), 792f));- PDPage page = new PDPage(pageSize);- if (pageModel.getRotation() != null) {- page.setRotation(pageModel.getRotation());- }- document.addPage(page);-- applyPageResources(document, page, pageModel.getResources());-- List<PDStream> preservedStreams =- buildContentStreams(document, pageModel.getContentStreams());- if (!preservedStreams.isEmpty()) {- page.setContents(preservedStreams);- }-- List<PdfJsonImageElement> imageElements =- pageModel.getImageElements() != null- ? pageModel.getImageElements()- : new ArrayList<>();-- // Reconstruct image XObjects if content streams are preserved- // (images were filtered out during serialization to avoid duplication)- if (!preservedStreams.isEmpty() && !imageElements.isEmpty()) {- reconstructImageXObjects(document, page, preservedStreams, imageElements);- }-- List<PdfJsonTextElement> elements =- pageModel.getTextElements() != null- ? pageModel.getTextElements()- : new ArrayList<>();-- PreflightResult preflightResult =- preflightTextElements(- document, fontMap, fontModels, elements, pageNumberValue);-- fontLookup = buildFontModelLookup(fontModels);-- log.debug(- "Page {} preflight complete (elements={}, fallbackApplied={})",- pageNumberValue,- elements.size(),- preflightResult.usesFallback());-- if (!preflightResult.fallbackFontIds().isEmpty()) {- ensureFallbackResources(page, preflightResult.fallbackFontIds(), fontMap);- allFallbackFontIds.addAll(preflightResult.fallbackFontIds());- pagesWithFallbacks++;- log.debug(- "Page {} registered fallback fonts: {}",- pageNumberValue,- preflightResult.fallbackFontIds());- }-- boolean hasText = !elements.isEmpty();- boolean hasImages = !imageElements.isEmpty();- boolean rewriteSucceeded = true;-- if (hasText) {- if (preflightResult.usesFallback()) {- log.debug(- "Skipping token rewrite for page {} because fallback fonts are required",- pageNumberValue);- rewriteSucceeded = false;- } else if (!preservedStreams.isEmpty()) {- log.debug("Attempting token rewrite for page {}", pageNumberValue);- rewriteSucceeded =- rewriteTextOperators(- document,- page,- elements,- false,- false,- fontLookup,- pageNumberValue);- if (!rewriteSucceeded) {- log.debug(- "Token rewrite failed for page {}, regenerating text stream",- pageNumberValue);- } else {- log.debug("Token rewrite succeeded for page {}", pageNumberValue);- }- } else {- rewriteSucceeded = false;- }- }-- boolean shouldRegenerate = preservedStreams.isEmpty();- if (hasText && (!rewriteSucceeded || preflightResult.usesFallback())) {- shouldRegenerate = true;- }- if (hasImages && preservedStreams.isEmpty()) {- shouldRegenerate = true;- }-- if (!(hasText || hasImages)) {- pageIndex++;- continue;- }-- if (shouldRegenerate) {- log.debug("Regenerating page content for page {}", pageNumberValue);- AppendMode appendMode = AppendMode.OVERWRITE;- if (!preservedStreams.isEmpty()) {- PDStream vectorStream =- extractVectorGraphics(document, preservedStreams, imageElements);- if (vectorStream != null) {- page.setContents(Collections.singletonList(vectorStream));- appendMode = AppendMode.APPEND;- } else {- page.setContents(new ArrayList<>());- }- }- regeneratePageContent(- document,- page,- elements,- imageElements,- fontMap,- fontModels,- pageNumberValue,- appendMode);- log.debug("Page content regeneration complete for page {}", pageNumberValue);- }-- // Restore annotations for this page- List<PdfJsonAnnotation> annotations =- pageModel.getAnnotations() != null- ? pageModel.getAnnotations()- : new ArrayList<>();- restoreAnnotations(document, page, annotations);-- pageIndex++;- }-- // Restore form fields- List<PdfJsonFormField> formFields =- pdfJson.getFormFields() != null ? pdfJson.getFormFields() : new ArrayList<>();- restoreFormFields(document, formFields);-- // Log conversion summary- if (!allFallbackFontIds.isEmpty()) {- log.info(- "JSON->PDF conversion complete: {} pages, {} fallback font(s) used across {} page(s): {}",- pages.size(),- allFallbackFontIds.size(),- pagesWithFallbacks,- allFallbackFontIds);- } else {- log.info("JSON->PDF conversion complete: {} pages", pages.size());- }-- // Stream the PDF directly to the caller's OutputStream — PDFBox writes incrementally.- document.save(out);-- // Clear Type3 cache entries for this conversion- clearType3CacheEntriesForJob(syntheticJobId);- }- }-- private Map<PDFont, String> collectFontsForPage(- PDDocument document,- PDPage page,- int pageNumber,- Map<String, PdfJsonFont> fonts,- Map<COSBase, FontModelCacheEntry> fontCache,- String jobId)- throws IOException {- Map<PDFont, String> mapping = new HashMap<>();- Set<COSBase> visited = Collections.newSetFromMap(new IdentityHashMap<>());- collectFontsFromResources(- document,- page.getResources(),- pageNumber,- fonts,- mapping,- visited,- "",- fontCache,- jobId);- log.debug(- "Page {} font scan complete (unique fonts discovered: {})",- pageNumber,- mapping.size());- return mapping;- }-- /**- * Recursively collect fonts from a resource dictionary, including Form XObjects.- *- * @param document The PDF document- * @param resources The resources to scan- * @param pageNumber The page number (for font UID generation)- * @param fonts The global font map to populate- * @param mapping The page-level PDFont -> fontId mapping- * @param visited Set of visited XObject names to prevent infinite recursion- */- private void collectFontsFromResources(- PDDocument document,- PDResources resources,- int pageNumber,- Map<String, PdfJsonFont> fonts,- Map<PDFont, String> mapping,- Set<COSBase> visited,- String prefix,- Map<COSBase, FontModelCacheEntry> fontCache,- String jobId)- throws IOException {- if (resources == null) {- log.debug(- "Page {} resource scan skipped{} (resources null)",- pageNumber,- prefix.isEmpty() ? "" : " under " + prefix);- return;- }- if (!visited.add(resources.getCOSObject())) {- return;- }-- for (COSName resourceName : resources.getFontNames()) {- PDFont font = resources.getFont(resourceName);- if (font == null) {- continue;- }- String fontId =- prefix.isEmpty()- ? resourceName.getName()- : prefix + "/" + resourceName.getName();- mapping.put(font, fontId);- String key = buildFontKey(jobId, pageNumber, fontId);- if (!fonts.containsKey(key)) {- fonts.put(- key, buildFontModel(document, font, fontId, pageNumber, fontCache, jobId));- }- }-- for (COSName xobjectName : resources.getXObjectNames()) {- try {- PDXObject xobject = resources.getXObject(xobjectName);- if (xobject instanceof PDFormXObject form) {- collectFontsFromResources(- document,- form.getResources(),- pageNumber,- fonts,- mapping,- visited,- prefix.isEmpty()- ? xobjectName.getName()- : prefix + "/" + xobjectName.getName(),- fontCache,- jobId);- }- } catch (Exception ex) {- log.debug(- "Failed to inspect XObject {} for fonts on page {}: {}",- xobjectName.getName(),- pageNumber,- ex.getMessage());- }- }- }-- private String buildFontKey(String jobId, int pageNumber, String fontId) {- // Include jobId to ensure font UIDs are globally unique across concurrent jobs- String jobPrefix = (jobId != null && !jobId.isEmpty()) ? jobId + ":" : "";- return jobPrefix + pageNumber + ":" + fontId;- }-- private String buildFontKey(String jobId, Integer pageNumber, String fontId) {- int page = pageNumber != null ? pageNumber : -1;- return buildFontKey(jobId, page, fontId);- }-- private String resolveFontCacheKey(PdfJsonFont font) {- if (font == null) {- return null;- }- if (font.getUid() != null && !font.getUid().isBlank()) {- return font.getUid();- }- if (font.getId() == null) {- return null;- }- // JSON->PDF conversion: no jobId context, pass null- return buildFontKey(null, font.getPageNumber(), font.getId());- }-- private Map<String, PdfJsonFont> buildFontModelLookup(List<PdfJsonFont> fontModels) {- Map<String, PdfJsonFont> lookup = new HashMap<>();- if (fontModels == null) {- return lookup;- }- for (PdfJsonFont font : fontModels) {- if (font == null || font.getId() == null) {- continue;- }- // JSON->PDF conversion: no jobId context, pass null- lookup.put(buildFontKey(null, font.getPageNumber(), font.getId()), font);- }- return lookup;- }-- private PdfJsonFont resolveFontModel(- Map<String, PdfJsonFont> lookup, int pageNumber, String fontId) {- if (lookup == null || fontId == null) {- return null;- }- // JSON->PDF conversion: no jobId context, pass null- PdfJsonFont model = lookup.get(buildFontKey(null, pageNumber, fontId));- if (model != null) {- return model;- }- return lookup.get(buildFontKey(null, -1, fontId));- }-- private List<PdfJsonFont> cloneFontList(Collection<PdfJsonFont> source) {- List<PdfJsonFont> clones = new ArrayList<>();- if (source == null) {- return clones;- }- for (PdfJsonFont font : source) {- PdfJsonFont copy = cloneFont(font);- if (copy != null) {- clones.add(copy);- }- }- return clones;- }-- private PdfJsonFont cloneFont(PdfJsonFont font) {- if (font == null) {- return null;- }- try {- byte[] bytes = objectMapper.writeValueAsBytes(font);- return objectMapper.readValue(bytes, PdfJsonFont.class);- } catch (Exception ex) {- log.debug(- "Failed deep-cloning font {} via roundtrip: {}", font.getId(), ex.getMessage());- PdfJsonCosValue cosClone = null;- try {- if (font.getCosDictionary() != null) {- byte[] cosBytes = objectMapper.writeValueAsBytes(font.getCosDictionary());- cosClone = objectMapper.readValue(cosBytes, PdfJsonCosValue.class);- }- } catch (Exception cosEx) {- log.debug(- "Failed deep-cloning font cosDictionary {}: {}",- font.getId(),- cosEx.getMessage());- }- return PdfJsonFont.builder()- .id(font.getId())- .pageNumber(font.getPageNumber())- .uid(font.getUid())- .baseName(font.getBaseName())- .subtype(font.getSubtype())- .encoding(font.getEncoding())- .cidSystemInfo(font.getCidSystemInfo())- .embedded(font.getEmbedded())- .program(font.getProgram())- .programFormat(font.getProgramFormat())- .webProgram(font.getWebProgram())- .webProgramFormat(font.getWebProgramFormat())- .pdfProgram(font.getPdfProgram())- .pdfProgramFormat(font.getPdfProgramFormat())- .type3Glyphs(- font.getType3Glyphs() == null- ? null- : new ArrayList<>(font.getType3Glyphs()))- .conversionCandidates(- font.getConversionCandidates() == null- ? null- : new ArrayList<>(font.getConversionCandidates()))- .toUnicode(font.getToUnicode())- .standard14Name(font.getStandard14Name())- .fontDescriptorFlags(font.getFontDescriptorFlags())- .ascent(font.getAscent())- .descent(font.getDescent())- .capHeight(font.getCapHeight())- .xHeight(font.getXHeight())- .italicAngle(font.getItalicAngle())- .unitsPerEm(font.getUnitsPerEm())- .cosDictionary(cosClone)- .build();- }- }-- private void applyLightweightTransformations(PdfJsonDocument document) {- if (document == null) {- return;- }- List<PdfJsonFont> fonts = document.getFonts();- if (fonts == null) {- return;- }- for (PdfJsonFont font : fonts) {- if (font == null) {- continue;- }- boolean hasUsableProgram =- hasPayload(font.getPdfProgram())- || hasPayload(font.getWebProgram())- || hasPayload(font.getProgram());-- // Only clear cosDictionary for Type3 fonts (which have inline content streams)- // All other font types may need ToUnicode CMap or encoding from the dictionary- // Conservative approach: better to keep extra data than lose encoding info- String subtype = font.getSubtype();- boolean isType3 = subtype != null && subtype.equalsIgnoreCase("Type3");-- if (hasUsableProgram && isType3) {- font.setCosDictionary(null);- }- }- }-- private boolean hasPayload(String value) {- return value != null && !value.isBlank();- }-- private PdfJsonFont buildFontModel(- PDDocument document,- PDFont font,- String fontId,- int pageNumber,- Map<COSBase, FontModelCacheEntry> fontCache,- String jobId)- throws IOException {- COSBase cosObject = font.getCOSObject();- FontModelCacheEntry cacheEntry = fontCache.get(cosObject);- if (cacheEntry == null) {- cacheEntry = createFontCacheEntry(document, font, fontId, pageNumber, jobId);- fontCache.put(cosObject, cacheEntry);- }- return toPdfJsonFont(cacheEntry, fontId, pageNumber, jobId);- }-- private void logFontPayloadStats(List<PdfJsonFont> fonts, String label) {- if (!log.isDebugEnabled()) {- return;- }- if (fonts == null || fonts.isEmpty()) {- return;- }- long programBytes = 0;- long webProgramBytes = 0;- long pdfProgramBytes = 0;- long toUnicodeBytes = 0;- long maxFontPayload = 0;- String maxFontId = null;-- for (PdfJsonFont font : fonts) {- if (font == null) {- continue;- }- long fontBytes = 0;- if (font.getProgram() != null) {- long len = font.getProgram().length();- programBytes += len;- fontBytes += len;- }- if (font.getWebProgram() != null) {- long len = font.getWebProgram().length();- webProgramBytes += len;- fontBytes += len;- }- if (font.getPdfProgram() != null) {- long len = font.getPdfProgram().length();- pdfProgramBytes += len;- fontBytes += len;- }- if (font.getToUnicode() != null) {- long len = font.getToUnicode().length();- toUnicodeBytes += len;- fontBytes += len;- }- if (fontBytes > maxFontPayload) {- maxFontPayload = fontBytes;- maxFontId = font.getUid() != null ? font.getUid() : font.getId();- }- }-- log.debug(- "Font payload stats ({}): fonts={}, programBytes={}, webProgramBytes={}, pdfProgramBytes={}, toUnicodeBytes={}, maxFontPayloadBytes={} (fontId={})",- label,- fonts.size(),- programBytes,- webProgramBytes,- pdfProgramBytes,- toUnicodeBytes,- maxFontPayload,- maxFontId);- }-- private void analyzePdfJson(PdfJsonDocument pdfJson, String label) {- if (!isPdfJsonDebugAnalyzeEnabled() || pdfJson == null) {- return;- }-- try {- Map<String, DuplicateStats> resourceStats = new HashMap<>();- Map<String, DuplicateStats> fontDictStats = new HashMap<>();- Map<String, DuplicateStats> annotationStats = new HashMap<>();- long imageDataBytes = 0;- long imageCount = 0;- long textElementCount = 0;- long textCharCount = 0;-- List<PdfJsonPage> pages = pdfJson.getPages();- if (pages != null) {- for (PdfJsonPage page : pages) {- if (page == null) {- continue;- }- recordDuplicate(resourceStats, page.getResources());-- List<PdfJsonAnnotation> annotations = page.getAnnotations();- if (annotations != null) {- for (PdfJsonAnnotation annotation : annotations) {- recordDuplicate(annotationStats, annotation.getRawData());- }- }-- List<PdfJsonImageElement> images = page.getImageElements();- if (images != null) {- for (PdfJsonImageElement image : images) {- if (image == null) {- continue;- }- String data = image.getImageData();- if (data != null) {- imageDataBytes += data.length();- }- imageCount++;- }- }-- List<PdfJsonTextElement> textElements = page.getTextElements();- if (textElements != null) {- for (PdfJsonTextElement element : textElements) {- if (element == null) {- continue;- }- textElementCount++;- String text = element.getText();- if (text != null) {- textCharCount += text.length();- }- }- }- }- }-- List<PdfJsonFont> fonts = pdfJson.getFonts();- if (fonts != null) {- for (PdfJsonFont font : fonts) {- recordDuplicate(fontDictStats, font.getCosDictionary());- }- }-- logDuplicateSummary("resources", label, resourceStats);- logDuplicateSummary("fontCosDictionary", label, fontDictStats);- logDuplicateSummary("annotationRawData", label, annotationStats);- log.debug(- "PDF JSON analysis ({}): images={} imageDataBytes={} textElements={} textChars={}",- label,- imageCount,- imageDataBytes,- textElementCount,- textCharCount);-- long fontsBytes = sizeOfObject(pdfJson.getFonts());- long pagesBytes = sizeOfObject(pdfJson.getPages());- long metadataBytes = sizeOfObject(pdfJson.getMetadata());- long xmpBytes = sizeOfObject(pdfJson.getXmpMetadata());- long formFieldsBytes = sizeOfObject(pdfJson.getFormFields());- log.debug(- "PDF JSON analysis ({}): sectionSizes fonts={} pages={} metadata={} xmp={} formFields={}",- label,- fontsBytes,- pagesBytes,- metadataBytes,- xmpBytes,- formFieldsBytes);-- if (pages != null && !pages.isEmpty()) {- List<PageSizeStat> topPages = new ArrayList<>();- int pageIndex = 0;- for (PdfJsonPage page : pages) {- if (page == null) {- pageIndex++;- continue;- }- long size = sizeOfObject(page);- int pageNumber =- page.getPageNumber() != null ? page.getPageNumber() : pageIndex + 1;- topPages.add(new PageSizeStat(pageNumber, size, page));- pageIndex++;- }- topPages.sort((a, b) -> Long.compare(b.sizeBytes, a.sizeBytes));- String top =- topPages.stream()- .limit(5)- .map(- s ->- String.format(- "page=%d size=%d",- s.pageNumber, s.sizeBytes))- .collect(java.util.stream.Collectors.joining("; "));- log.debug("PDF JSON analysis ({}): topPageSizes -> {}", label, top);-- topPages.stream()- .limit(3)- .forEach(- s -> {- PdfJsonPage page = s.page;- long resources = sizeOfObject(page.getResources());- long contentStreams = sizeOfObject(page.getContentStreams());- long annotations = sizeOfObject(page.getAnnotations());- long textElements = sizeOfObject(page.getTextElements());- long imageElements = sizeOfObject(page.getImageElements());- log.debug(- "PDF JSON analysis ({}): pageBreakdown page={} total={} resources={} contentStreams={} annotations={} textElements={} imageElements={}",- label,- s.pageNumber,- s.sizeBytes,- resources,- contentStreams,- annotations,- textElements,- imageElements);- });- }- } catch (Exception ex) {- log.warn("PDF JSON analysis failed ({}): {}", label, ex.getMessage());- }- }-- private void recordDuplicate(Map<String, DuplicateStats> stats, PdfJsonCosValue value)- throws IOException, java.security.NoSuchAlgorithmException {- if (value == null) {- return;- }- byte[] bytes = objectMapper.writeValueAsBytes(value);- if (bytes.length == 0) {- return;- }- String hash =- Base64.getEncoder()- .encodeToString(- java.security.MessageDigest.getInstance("SHA-256").digest(bytes));- DuplicateStats entry = stats.computeIfAbsent(hash, k -> new DuplicateStats());- entry.count++;- if (entry.sizeBytes == 0) {- entry.sizeBytes = bytes.length;- }- }-- private void logDuplicateSummary(- String category, String label, Map<String, DuplicateStats> stats) {- if (stats.isEmpty()) {- return;- }- List<DuplicateStats> duplicates =- stats.values().stream()- .filter(s -> s.count > 1)- .sorted((a, b) -> Long.compare(b.totalBytesSaved(), a.totalBytesSaved()))- .limit(5)- .toList();-- if (duplicates.isEmpty()) {- return;- }-- String summary =- duplicates.stream()- .map(- s ->- String.format(- "count=%d size=%d potentialSavings=%d",- s.count, s.sizeBytes, s.totalBytesSaved()))- .collect(java.util.stream.Collectors.joining("; "));- log.debug("PDF JSON analysis ({}): top duplicates for {} -> {}", label, category, summary);- }-- private boolean isPdfJsonDebugAnalyzeEnabled() {- String env = System.getenv("SPDF_PDFJSON_ANALYZE");- if (env != null && env.equalsIgnoreCase("true")) {- return true;- }- return Boolean.getBoolean("spdf.pdfjson.analyze");- }-- private long sizeOfObject(Object value) {- if (value == null) {- return 0;- }- try {- return objectMapper.writeValueAsBytes(value).length;- } catch (Exception ex) {- log.warn("Failed to serialize object for size analysis: {}", ex.getMessage());- return -1;- }- }-- private static final class DuplicateStats {- private int count;- private long sizeBytes;-- private long totalBytesSaved() {- return sizeBytes * (long) (count - 1);- }- }-- private static final class PageSizeStat {- private final int pageNumber;- private final long sizeBytes;- private final PdfJsonPage page;-- private PageSizeStat(int pageNumber, long sizeBytes, PdfJsonPage page) {- this.pageNumber = pageNumber;- this.sizeBytes = sizeBytes;- this.page = page;- }- }-- private void dedupeFontPayloads(List<PdfJsonFont> fonts) {- if (fonts == null || fonts.isEmpty()) {- return;- }- for (PdfJsonFont font : fonts) {- if (font == null) {- continue;- }- String program = font.getProgram();- String pdfProgram = font.getPdfProgram();- String webProgram = font.getWebProgram();-- if (pdfProgram != null && !pdfProgram.isBlank()) {- if (program != null && program.equals(pdfProgram)) {- font.setProgram(null);- font.setProgramFormat(null);- }- if (webProgram != null && webProgram.equals(pdfProgram)) {- font.setWebProgram(null);- font.setWebProgramFormat(null);- }- continue;- }-- if (program != null && webProgram != null && program.equals(webProgram)) {- font.setWebProgram(null);- font.setWebProgramFormat(null);- }- }- }-- private void stripFontProgramPayloads(List<PdfJsonFont> fonts) {- if (fonts == null || fonts.isEmpty()) {- return;- }- for (PdfJsonFont font : fonts) {- if (font == null) {- continue;- }- font.setProgram(null);- font.setProgramFormat(null);- font.setWebProgram(null);- font.setWebProgramFormat(null);- font.setPdfProgram(null);- font.setPdfProgramFormat(null);- }- }-- private void stripFontCosStreamData(List<PdfJsonFont> fonts) {- if (fonts == null || fonts.isEmpty()) {- return;- }- Set<PdfJsonCosValue> visited = Collections.newSetFromMap(new IdentityHashMap<>());- for (PdfJsonFont font : fonts) {- if (font == null) {- continue;- }- PdfJsonCosValue cosDictionary = font.getCosDictionary();- if (cosDictionary != null) {- stripStreamRawData(cosDictionary, visited);- }- }- }-- private void stripStreamRawData(PdfJsonCosValue value, Set<PdfJsonCosValue> visited) {- if (value == null || value.getType() == null) {- return;- }- if (!visited.add(value)) {- return;- }- switch (value.getType()) {- case STREAM:- if (value.getStream() != null) {- value.getStream().setRawData(null);- }- break;- case ARRAY:- if (value.getItems() != null) {- for (PdfJsonCosValue item : value.getItems()) {- stripStreamRawData(item, visited);- }- }- break;- case DICTIONARY:- if (value.getEntries() != null) {- for (PdfJsonCosValue entry : value.getEntries().values()) {- stripStreamRawData(entry, visited);- }- }- break;- default:- break;- }- }-- private FontModelCacheEntry createFontCacheEntry(- PDDocument document, PDFont font, String fontId, int pageNumber, String jobId)- throws IOException {- PDFontDescriptor descriptor = font.getFontDescriptor();- String subtype = font.getCOSObject().getNameAsString(COSName.SUBTYPE);- String encoding = resolveEncoding(font);- PdfJsonFontCidSystemInfo cidInfo = extractCidSystemInfo(font.getCOSObject());- boolean embedded = font.isEmbedded();- String toUnicode = extractToUnicode(font.getCOSObject());- String unicodeMapping = buildUnicodeMapping(font, toUnicode);- FontProgramData programData = embedded ? extractFontProgram(font, unicodeMapping) : null;- String standard14Name = resolveStandard14Name(font);- Integer flags = descriptor != null ? descriptor.getFlags() : null;- Float ascent = descriptor != null ? descriptor.getAscent() : null;- Float descent = descriptor != null ? descriptor.getDescent() : null;- Float capHeight = descriptor != null ? descriptor.getCapHeight() : null;- Float xHeight = descriptor != null ? descriptor.getXHeight() : null;- Float italicAngle = descriptor != null ? descriptor.getItalicAngle() : null;- Integer unitsPerEm = extractUnitsPerEm(font);- PdfJsonCosValue cosDictionary = cosMapper.serializeCosValue(font.getCOSObject());- List<PdfJsonFontConversionCandidate> conversionCandidates = null;- List<PdfJsonFontType3Glyph> type3Glyphs = null;- String fontUid = buildFontKey(jobId, pageNumber, fontId);- if (font instanceof PDType3Font type3Font) {- try {- conversionCandidates =- type3FontConversionService.synthesize(- Type3ConversionRequest.builder()- .document(document)- .font(type3Font)- .fontId(fontId)- .pageNumber(pageNumber)- .fontUid(fontUid)- .build());- if (conversionCandidates != null && conversionCandidates.isEmpty()) {- conversionCandidates = null;- }- try {- List<Type3GlyphOutline> outlines =- type3GlyphExtractor.extractGlyphs(- document, type3Font, fontId, pageNumber);- if (outlines != null && !outlines.isEmpty()) {- type3Glyphs =- outlines.stream()- .map(- outline ->- PdfJsonFontType3Glyph.builder()- .charCode(outline.getCharCode())- .charCodeRaw(- outline.getCharCode() >= 0- ? outline- .getCharCode()- : null)- .glyphName(outline.getGlyphName())- .unicode(outline.getUnicode())- .build())- .toList();- }- } catch (Exception ex) {- log.debug(- "[TYPE3] Failed to extract glyph metadata for {} (page {}): {}",- fontId,- pageNumber,- ex.getMessage());- }- } catch (Exception ex) {- log.warn(- "[TYPE3] Failed to evaluate conversion strategies for {} (page {}): {}",- fontId,- pageNumber,- ex.getMessage(),- ex);- }- registerType3GlyphCoverage(fontUid, conversionCandidates, type3Glyphs);- }-- return new FontModelCacheEntry(- font.getName(),- subtype,- encoding,- cidInfo,- Boolean.valueOf(embedded),- programData,- toUnicode,- standard14Name,- flags,- ascent,- descent,- capHeight,- xHeight,- italicAngle,- unitsPerEm,- cosDictionary,- type3Glyphs,- conversionCandidates);- }-- private PdfJsonFont toPdfJsonFont(- FontModelCacheEntry cacheEntry, String fontId, int pageNumber, String jobId) {- FontProgramData programData = cacheEntry.programData();- return PdfJsonFont.builder()- .id(fontId)- .pageNumber(pageNumber)- .uid(buildFontKey(jobId, pageNumber, fontId))- .baseName(cacheEntry.baseName())- .subtype(cacheEntry.subtype())- .encoding(cacheEntry.encoding())- .cidSystemInfo(cacheEntry.cidSystemInfo())- .embedded(cacheEntry.embedded())- .program(programData != null ? programData.getBase64() : null)- .programFormat(programData != null ? programData.getFormat() : null)- .webProgram(programData != null ? programData.getWebBase64() : null)- .webProgramFormat(programData != null ? programData.getWebFormat() : null)- .pdfProgram(programData != null ? programData.getPdfBase64() : null)- .pdfProgramFormat(programData != null ? programData.getPdfFormat() : null)- .type3Glyphs(cacheEntry.type3Glyphs())- .conversionCandidates(cacheEntry.conversionCandidates())- .toUnicode(cacheEntry.toUnicode())- .standard14Name(cacheEntry.standard14Name())- .fontDescriptorFlags(cacheEntry.fontDescriptorFlags())- .ascent(cacheEntry.ascent())- .descent(cacheEntry.descent())- .capHeight(cacheEntry.capHeight())- .xHeight(cacheEntry.xHeight())- .italicAngle(cacheEntry.italicAngle())- .unitsPerEm(cacheEntry.unitsPerEm())- .cosDictionary(cacheEntry.cosDictionary())- .build();- }-- private record FontByteSource(byte[] bytes, String format, String originLabel) {}-- private List<FontByteSource> collectConversionCandidateSources(- List<PdfJsonFontConversionCandidate> conversionCandidates) {- if (conversionCandidates == null || conversionCandidates.isEmpty()) {- return Collections.emptyList();- }- List<PdfJsonFontConversionCandidate> prioritized = new ArrayList<>();- for (PdfJsonFontConversionCandidate candidate : conversionCandidates) {- if (candidate == null) {- continue;- }- PdfJsonFontConversionStatus status = candidate.getStatus();- if (status == PdfJsonFontConversionStatus.SUCCESS- || status == PdfJsonFontConversionStatus.WARNING) {- prioritized.add(candidate);- }- }- if (prioritized.isEmpty()) {- return Collections.emptyList();- }- prioritized.sort(- Comparator.comparingInt(- c ->- conversionStatusPriority(- c.getStatus() != null- ? c.getStatus()- : PdfJsonFontConversionStatus.FAILURE)));-- List<FontByteSource> sources = new ArrayList<>();- for (PdfJsonFontConversionCandidate candidate : prioritized) {- addCandidatePayload(- sources,- candidate.getPdfProgram(),- candidate.getPdfProgramFormat(),- candidate,- "pdfProgram");- addCandidatePayload(- sources,- candidate.getProgram(),- candidate.getProgramFormat(),- candidate,- "program");- addCandidatePayload(- sources,- candidate.getWebProgram(),- candidate.getWebProgramFormat(),- candidate,- "webProgram");- }- sources.sort(- Comparator.comparingInt(- source -> fontFormatPreference(source.format(), source.originLabel())));- return sources;- }-- private int conversionStatusPriority(PdfJsonFontConversionStatus status) {- return switch (status) {- case SUCCESS -> 0;- case WARNING -> 1;- default -> 2;- };- }-- private void addCandidatePayload(- List<FontByteSource> sources,- String base64,- String format,- PdfJsonFontConversionCandidate candidate,- String label) {- if (base64 == null || base64.isBlank()) {- return;- }- try {- byte[] bytes = Base64.getDecoder().decode(base64);- if (bytes.length == 0) {- return;- }- String normalizedFormat = format != null ? format.toLowerCase(Locale.ROOT) : null;- String strategyId =- candidate.getStrategyId() != null ? candidate.getStrategyId() : "unknown";- String origin = "candidate:" + strategyId + ":" + label;- sources.add(new FontByteSource(bytes, normalizedFormat, origin));- log.debug(- "[FONT-DEBUG] Registered conversion candidate payload from {} (format={}, size={} bytes)",- origin,- normalizedFormat,- bytes.length);- } catch (IllegalArgumentException ex) {- log.warn(- "[TYPE3] Failed to decode {} payload for strategy {}: {}",- label,- candidate.getStrategyId(),- ex.getMessage());- }- }-- private void registerType3GlyphCoverage(- String fontUid,- List<PdfJsonFontConversionCandidate> conversionCandidates,- List<PdfJsonFontType3Glyph> glyphs) {- if (fontUid == null) {- return;- }- Set<Integer> coverage = new LinkedHashSet<>();- if (conversionCandidates != null) {- for (PdfJsonFontConversionCandidate candidate : conversionCandidates) {- if (candidate == null || candidate.getGlyphCoverage() == null) {- continue;- }- for (Integer value : candidate.getGlyphCoverage()) {- if (value != null) {- coverage.add(value);- }- }- }- }- if (glyphs != null) {- for (PdfJsonFontType3Glyph glyph : glyphs) {- if (glyph == null) {- continue;- }- Integer unicode = glyph.getUnicode();- if (unicode != null) {- coverage.add(unicode);- } else {- Integer charCode = glyph.getCharCode();- if (charCode != null && charCode >= 0) {- coverage.add(0xF000 | (charCode & 0xFF));- }- }- }- }- if (!coverage.isEmpty()) {- type3GlyphCoverageCache.put(fontUid, Collections.unmodifiableSet(coverage));- }- }-- private boolean isGlyphCoveredByType3Font(Set<Integer> coverage, int codePoint) {- if (coverage == null || coverage.isEmpty()) {- return true;- }- if (coverage.contains(codePoint)) {- return true;- }- if (codePoint >= 0 && codePoint <= 0xFF) {- return coverage.contains(0xF000 | (codePoint & 0xFF));- }- return false;- }-- private int fontFormatPreference(String format, String origin) {- if (format == null) {- return 5;- }- switch (format) {- case "ttf":- return 0;- case "truetype":- return 1;- case "otf":- case "cff":- case "type1c":- case "cidfonttype0c":- return 2;- default:- log.debug("[FONT-DEBUG] Unknown font format '{}' from {}", format, origin);- return 4;- }- }-- private record FontModelCacheEntry(- String baseName,- String subtype,- String encoding,- PdfJsonFontCidSystemInfo cidSystemInfo,- Boolean embedded,- FontProgramData programData,- String toUnicode,- String standard14Name,- Integer fontDescriptorFlags,- Float ascent,- Float descent,- Float capHeight,- Float xHeight,- Float italicAngle,- Integer unitsPerEm,- PdfJsonCosValue cosDictionary,- List<PdfJsonFontType3Glyph> type3Glyphs,- List<PdfJsonFontConversionCandidate> conversionCandidates) {}-- private PreflightResult preflightTextElements(- PDDocument document,- Map<String, PDFont> fontMap,- List<PdfJsonFont> fontModels,- List<PdfJsonTextElement> elements,- int pageNumber)- throws IOException {- if (elements == null || elements.isEmpty()) {- return PreflightResult.empty();- }-- Set<String> fallbackIds = new LinkedHashSet<>();- boolean fallbackNeeded = false;- Set<String> warnedFonts =- new HashSet<>(); // Track fonts we've already warned about on this page-- Map<String, PdfJsonFont> fontLookup = buildFontModelLookup(fontModels);- Map<String, Set<Integer>> type3GlyphCache = new HashMap<>();-- for (PdfJsonTextElement element : elements) {- String text = Objects.toString(element.getText(), "");- if (text.isEmpty()) {- continue;- }-- PDFont font = fontMap.get(buildFontKey(null, pageNumber, element.getFontId()));- if (font == null && element.getFontId() != null) {- font = fontMap.get(buildFontKey(null, -1, element.getFontId()));- }-- if (font == null) {- fallbackNeeded = true;- fallbackIds.add(FALLBACK_FONT_ID);- element.setFallbackUsed(Boolean.TRUE);- continue;- }-- PdfJsonFont fontModel = resolveFontModel(fontLookup, pageNumber, element.getFontId());- if (font instanceof PDType3Font && fontModel != null) {- Set<Integer> supportedGlyphs =- type3GlyphCache.computeIfAbsent(- fontModel.getUid() != null ? fontModel.getUid() : fontModel.getId(),- key -> {- List<PdfJsonFontType3Glyph> glyphs = fontModel.getType3Glyphs();- if (glyphs == null || glyphs.isEmpty()) {- return Collections.emptySet();- }- return glyphs.stream()- .map(PdfJsonFontType3Glyph::getUnicode)- .filter(Objects::nonNull)- .collect(Collectors.toSet());- });-- boolean missingGlyph = false;- for (int offset = 0; offset < text.length(); ) {- int codePoint = text.codePointAt(offset);- offset += Character.charCount(codePoint);- if (!supportedGlyphs.contains(codePoint)) {- missingGlyph = true;- break;- }- }-- if (missingGlyph) {- fallbackNeeded = true;- element.setFallbackUsed(Boolean.TRUE);- for (int offset = 0; offset < text.length(); ) {- int codePoint = text.codePointAt(offset);- offset += Character.charCount(codePoint);- if (!supportedGlyphs.contains(codePoint)) {- String fallbackId =- fallbackFontService.resolveFallbackFontId(codePoint);- fallbackIds.add(fallbackId != null ? fallbackId : FALLBACK_FONT_ID);- }- }- }- continue;- }-- if (!fallbackFontService.canEncodeFully(font, text)) {- String fontName =- fontModel != null && fontModel.getBaseName() != null- ? FONT_SUBSET_PREFIX_PATTERN- .matcher(fontModel.getBaseName())- .replaceAll("") // Remove subset prefix- : (font != null ? font.getName() : "unknown");- String fontKey = fontName + ":" + element.getFontId() + ":" + pageNumber;- if (!warnedFonts.contains(fontKey)) {- log.warn(- "[FALLBACK-NEEDED] Font '{}' (resource {}, subtype {}) cannot encode text on page {}. Using fallback font.",- fontName,- element.getFontId(),- fontModel != null ? fontModel.getSubtype() : "unknown",- pageNumber);- warnedFonts.add(fontKey);- }- fallbackNeeded = true;- element.setFallbackUsed(Boolean.TRUE);- for (int offset = 0; offset < text.length(); ) {- int codePoint = text.codePointAt(offset);- offset += Character.charCount(codePoint);- if (!fallbackFontService.canEncode(font, codePoint)) {- String fallbackId = fallbackFontService.resolveFallbackFontId(codePoint);- fallbackIds.add(fallbackId != null ? fallbackId : FALLBACK_FONT_ID);- }- }- }- }-- for (String fallbackId : fallbackIds) {- ensureFallbackFont(document, fontMap, fontModels, fallbackId);- }-- if (fallbackNeeded && fallbackIds.isEmpty()) {- fallbackIds.add(FALLBACK_FONT_ID);- ensureFallbackFont(document, fontMap, fontModels, FALLBACK_FONT_ID);- }-- return new PreflightResult(fallbackNeeded, fallbackIds);- }-- private void ensureFallbackResources(- PDPage page, Set<String> fallbackFontIds, Map<String, PDFont> fontMap) {- if (fallbackFontIds == null || fallbackFontIds.isEmpty()) {- return;- }- PDResources resources = page.getResources();- if (resources == null) {- resources = new PDResources();- page.setResources(resources);- }- for (String fallbackId : fallbackFontIds) {- if (fallbackId == null) {- continue;- }- PDFont fallbackFont = fontMap.get(buildFontKey(null, -1, fallbackId));- if (fallbackFont == null) {- continue;- }- COSName fallbackName = COSName.getPDFName(fallbackId);- boolean exists = false;- for (COSName name : resources.getFontNames()) {- if (fallbackName.equals(name)) {- exists = true;- break;- }- }- if (!exists) {- resources.put(fallbackName, fallbackFont);- }- }- }-- private PDFont ensureFallbackFont(- PDDocument document,- Map<String, PDFont> fontMap,- List<PdfJsonFont> fontModels,- String fallbackId)- throws IOException {- String effectiveId = fallbackId != null ? fallbackId : FALLBACK_FONT_ID;- String key = buildFontKey(null, -1, effectiveId);- PDFont font = fontMap.get(key);- if (font != null) {- log.debug(- "[FALLBACK-DEBUG] Reusing cached fallback font {} (key: {})", effectiveId, key);- return font;- }- log.debug(- "[FALLBACK-DEBUG] Loading fallback font {} (key: {}) via fallbackFontService",- effectiveId,- key);- PDFont loaded = fallbackFontService.loadFallbackPdfFont(document, effectiveId);- log.debug(- "[FALLBACK-DEBUG] Loaded fallback font {} - PDFont class: {}, name: {}",- effectiveId,- loaded.getClass().getSimpleName(),- loaded.getName());- fontMap.put(key, loaded);- if (fontModels != null- && fontModels.stream().noneMatch(f -> effectiveId.equals(f.getId()))) {- fontModels.add(fallbackFontService.buildFallbackFontModel(effectiveId));- }- return loaded;- }-- private boolean canRunGhostscript() {- if (!fontNormalizationEnabled) {- return false;- }- if (!isGhostscriptGroupEnabled()) {- return false;- }- if (!ghostscriptAvailable) {- log.debug("Skipping Ghostscript normalization; executable not available");- return false;- }- return true;- }-- private boolean isGhostscriptGroupEnabled() {- try {- return endpointConfiguration != null- && endpointConfiguration.isGroupEnabled("Ghostscript");- } catch (Exception ex) {- log.debug("Ghostscript group check failed: {}", ex.getMessage());- return false;- }- }-- private TempFile normalizePdfFonts(Path sourcePath) throws IOException {- if (sourcePath == null || !Files.exists(sourcePath)) {- return null;- }- TempFile outputFile = new TempFile(tempFileManager, ".pdf");- List<String> command = new ArrayList<>();- command.add("gs");- command.add("-sDEVICE=pdfwrite");- command.add("-dCompatibilityLevel=1.7");- command.add("-dPDFSETTINGS=/prepress");- command.add("-dEmbedAllFonts=true");- command.add("-dSubsetFonts=true");- command.add("-dCompressFonts=true");- command.add("-dNOPAUSE");- command.add("-dBATCH");- command.add("-dQUIET");- command.add("-o");- command.add(outputFile.getAbsolutePath());- command.add("-c");- command.add("<</NeverEmbed[]>> setdistillerparams");- command.add("-f");- command.add(sourcePath.toString());- try {- ProcessExecutorResult result =- ProcessExecutor.getInstance(ProcessExecutor.Processes.GHOSTSCRIPT)- .runCommandWithOutputHandling(command);- if (result.getRc() == 0- && Files.exists(outputFile.getPath())- && Files.size(outputFile.getPath()) > 0) {- return outputFile;- }- log.warn("Ghostscript normalization exited with code {}", result.getRc());- } catch (InterruptedException ex) {- Thread.currentThread().interrupt();- closeQuietly(outputFile);- throw new IOException("Ghostscript normalization interrupted", ex);- } catch (IOException ex) {- closeQuietly(outputFile);- throw ex;- }-- closeQuietly(outputFile);- return null;- }-- private byte[] convertCffProgramToTrueType(byte[] fontBytes, String toUnicode) {- return fontService.convertCffProgramToTrueType(fontBytes, toUnicode);- }-- private String buildUnicodeMapping(PDFont font, String toUnicodeBase64) throws IOException {- if (toUnicodeBase64 == null || toUnicodeBase64.isBlank()) {- return null;- }-- // For CID fonts (Type0), build complete CharCode→CID→GID→Unicode mapping- if (!(font instanceof PDType0Font type0Font)) {- // For non-CID fonts, just return ToUnicode as-is- return toUnicodeBase64;- }-- try {- // Build a map of CharCode → Unicode from ToUnicode- Map<Integer, Integer> charCodeToUnicode = new HashMap<>();- byte[] toUnicodeBytes = Base64.getDecoder().decode(toUnicodeBase64);- String toUnicodeStr = new String(toUnicodeBytes, StandardCharsets.UTF_8);-- // Parse ToUnicode CMap for bfchar and bfrange. Both sides go through- // parseToUnicodeCodepoint so an 8-hex-char surrogate-pair value on either side- // (e.g. "D837DF0E") is decoded as a single supplementary codepoint instead of- // overflowing Integer.parseInt and aborting the whole mapping build.- java.util.regex.Pattern bfcharPattern =- java.util.regex.Pattern.compile("<([0-9A-Fa-f]+)>\\s*<([0-9A-Fa-f]+)>");- java.util.regex.Matcher matcher = bfcharPattern.matcher(toUnicodeStr);- while (matcher.find()) {- try {- int charCode = parseToUnicodeCodepoint(matcher.group(1));- int unicode = parseToUnicodeCodepoint(matcher.group(2));- charCodeToUnicode.put(charCode, unicode);- } catch (NumberFormatException entryEx) {- // Tolerate a single malformed entry: log and skip rather than aborting the- // entire ToUnicode CMap (which would force the whole font onto the slow- // raw-bytes fallback path).- log.debug(- "Skipping malformed ToUnicode entry <{}> <{}> in font {}: {}",- matcher.group(1),- matcher.group(2),- font.getName(),- entryEx.getMessage());- }- }-- // Build JSON mapping: CharCode → CID → GID → Unicode- StringBuilder json = new StringBuilder();- json.append("{\"isCID\":true,\"cidToGidIdentity\":true,\"entries\":[");-- boolean first = true;- for (Map.Entry<Integer, Integer> entry : charCodeToUnicode.entrySet()) {- int charCode = entry.getKey();- int unicode = entry.getValue();-- try {- // Get CID from char code- int cid = type0Font.codeToCID(charCode);- // For Identity-H/V encoding, GID == CID- int gid = cid;-- if (!first) {- json.append(",");- }- first = false;- json.append(- String.format(- "{\"code\":%d,\"cid\":%d,\"gid\":%d,\"unicode\":%d}",- charCode, cid, gid, unicode));- } catch (Exception e) {- // Skip entries that fail to map- log.debug(- "Failed to map charCode {} in font {}: {}",- charCode,- font.getName(),- e.getMessage());- }- }-- json.append("]}");- String jsonStr = json.toString();- log.debug(- "Built Unicode mapping for CID font {} with {} entries",- font.getName(),- charCodeToUnicode.size());- return Base64.getEncoder().encodeToString(jsonStr.getBytes(StandardCharsets.UTF_8));-- } catch (Exception e) {- log.warn(- "Failed to build Unicode mapping for font {}: {}",- font.getName(),- e.getMessage());- return toUnicodeBase64; // Fall back to raw ToUnicode- }- }-- /**- * Parse a hex string from a PDF ToUnicode CMap into a single Unicode codepoint. Handles three- * cases: a single BMP code unit (4 hex chars), a UTF-16 surrogate pair encoding a supplementary- * codepoint above U+FFFF (8 hex chars, e.g. {@code D837DF0E} for U+1F40E), and multi-codepoint- * mappings (longer; returns the first codepoint as a best-effort representative).- *- * <p>Without this, {@code Integer.parseInt("D837DF0E", 16)} overflows because the value is ~3.6- * billion, throwing {@link NumberFormatException} and forcing the conversion to fall back to a- * raw ToUnicode payload that the JSON→PDF rebuild then fails to use efficiently.- */- static int parseToUnicodeCodepoint(String hex) {- if (hex == null || hex.isEmpty()) {- throw new NumberFormatException("Empty ToUnicode hex value");- }- if (hex.length() <= 4) {- return Integer.parseInt(hex, 16);- }- // Treat the hex string as UTF-16BE: pairs of hex digits form bytes, four hex digits form- // one UTF-16 code unit. The PDF ToUnicode CMap convention requires an even number of bytes- // (i.e. a multiple of four hex characters) for multi-unit values.- if (hex.length() % 4 != 0) {- throw new NumberFormatException(- "ToUnicode hex value not a multiple of 4 chars: " + hex);- }- int unitCount = hex.length() / 4;- char[] units = new char[unitCount];- for (int i = 0; i < unitCount; i++) {- units[i] = (char) Integer.parseInt(hex.substring(i * 4, i * 4 + 4), 16);- }- // codePointAt assembles a surrogate pair into a supplementary codepoint when the- // high/low surrogates appear in sequence; for any other multi-unit sequence it returns- // the first BMP codepoint, which is the right best-effort fallback for ligature- // decompositions (one charCode -> several Unicode chars).- return new String(units).codePointAt(0);- }-- private PdfJsonFontCidSystemInfo extractCidSystemInfo(COSDictionary fontDictionary) {- if (fontDictionary == null) {- return null;- }- COSBase base = fontDictionary.getDictionaryObject(COSName.CIDSYSTEMINFO);- if (!(base instanceof COSDictionary cidDictionary)) {- return null;- }- String registry = cidDictionary.getString(COSName.REGISTRY);- String ordering = cidDictionary.getString(COSName.ORDERING);- int supplementValue = cidDictionary.getInt(COSName.SUPPLEMENT, -1);- if (registry == null && ordering == null && supplementValue < 0) {- return null;- }- PdfJsonFontCidSystemInfo info = new PdfJsonFontCidSystemInfo();- info.setRegistry(registry);- info.setOrdering(ordering);- if (supplementValue >= 0) {- info.setSupplement(supplementValue);- }- return info;- }-- private FontProgramData extractFontProgram(PDFont font, String toUnicode) throws IOException {- PDFontDescriptor descriptor = font.getFontDescriptor();- if (descriptor == null) {- return null;- }-- PDStream fontFile3 = descriptor.getFontFile3();- if (fontFile3 != null) {- String subtype = fontFile3.getCOSObject().getNameAsString(COSName.SUBTYPE);- log.debug(- "[FONT-DEBUG] Font {}: Found FontFile3 with subtype {}",- font.getName(),- subtype);- return readFontProgram(- fontFile3, subtype != null ? subtype : "fontfile3", false, toUnicode);- }-- PDStream fontFile2 = descriptor.getFontFile2();- if (fontFile2 != null) {- log.debug("[FONT-DEBUG] Font {}: Found FontFile2 (TrueType)", font.getName());- return readFontProgram(fontFile2, null, true, toUnicode);- }-- PDStream fontFile = descriptor.getFontFile();- if (fontFile != null) {- log.debug("[FONT-DEBUG] Font {}: Found FontFile (Type1)", font.getName());- return readFontProgram(fontFile, "type1", false, toUnicode);- }-- log.debug("[FONT-DEBUG] Font {}: No font program found", font.getName());- return null;- }-- private FontProgramData readFontProgram(- PDStream stream, String formatHint, boolean detectTrueType, String toUnicode)- throws IOException {- try (InputStream inputStream = stream.createInputStream();- ByteArrayOutputStream baos = new ByteArrayOutputStream()) {- inputStream.transferTo(baos);- byte[] data = baos.toByteArray();- String format = formatHint;- if (detectTrueType) {- format = fontService.detectTrueTypeFormat(data);- }- log.debug(- "[FONT-DEBUG] Font program: size={} bytes, formatHint={}, detectedFormat={}",- data.length,- formatHint,- format);-- String webBase64 = null;- String webFormat = null;- String pdfBase64 = null;- String pdfFormat = null;- boolean labelledCff = format != null && isCffFormat(format);- boolean cffProgram = labelledCff && fontService.isCffFontProgram(data);- if (labelledCff && !cffProgram) {- log.warn(- "Font program labelled {} has no CFF header; skipping CFF conversion",- format);- }- if (cffProgram) {- log.debug(- "[FONT-DEBUG] Font is CFF format, attempting conversion. CFF conversion enabled: {}, method: {}",- fontService.isCffConversionEnabled(),- fontService.getCffConverterMethod());-- byte[] converted = convertCffProgramToTrueType(data, toUnicode);- if (converted != null && converted.length > 0) {- String detectedFormat = fontService.detectFontFlavor(converted);- webBase64 = Base64.getEncoder().encodeToString(converted);- webFormat = detectedFormat;- log.debug(- "[FONT-DEBUG] Primary CFF conversion succeeded: {} bytes -> {}",- data.length,- detectedFormat);- if ("ttf".equals(detectedFormat)) {- pdfBase64 = webBase64;- pdfFormat = detectedFormat;- }- } else {- log.debug("[FONT-DEBUG] Primary CFF conversion returned null/empty");- }-- if (pdfBase64 == null && fontService.isCffConversionEnabled()) {- log.debug("[FONT-DEBUG] Attempting fallback FontForge conversion");- byte[] ttfConverted = fontService.convertCffUsingFontForge(data);- if (ttfConverted != null && ttfConverted.length > 0) {- String detectedFormat = fontService.detectFontFlavor(ttfConverted);- if (detectedFormat != null) {- pdfBase64 = Base64.getEncoder().encodeToString(ttfConverted);- pdfFormat = detectedFormat;- if (webBase64 == null) {- webBase64 = pdfBase64;- webFormat = detectedFormat;- }- log.debug(- "[FONT-DEBUG] FontForge conversion succeeded: {} bytes -> {}",- data.length,- detectedFormat);- }- } else {- log.debug("[FONT-DEBUG] FontForge conversion also returned null/empty");- }- }-- if (webBase64 == null && pdfBase64 == null) {- log.warn(- "[FONT-DEBUG] ALL CFF conversions failed - font will not be usable in browser!");- }- } else if (format != null) {- log.debug("[FONT-DEBUG] Font is non-CFF format ({}), using as-is", format);- // For non-CFF formats (TrueType, etc.), preserve original font stream as pdfProgram- // This allows PDFBox to reconstruct the font during JSON->PDF- String base64 = Base64.getEncoder().encodeToString(data);- pdfBase64 = base64;- pdfFormat = format;- }-- String base64 = Base64.getEncoder().encodeToString(data);- return new FontProgramData(base64, format, webBase64, webFormat, pdfBase64, pdfFormat);- }- }-- private String extractToUnicode(COSDictionary fontDictionary) throws IOException {- if (fontDictionary == null) {- return null;- }- COSBase base = fontDictionary.getDictionaryObject(COSName.TO_UNICODE);- if (!(base instanceof COSStream stream)) {- return null;- }- try (InputStream inputStream = stream.createInputStream();- ByteArrayOutputStream baos = new ByteArrayOutputStream()) {- inputStream.transferTo(baos);- byte[] data = baos.toByteArray();- if (data.length == 0) {- return null;- }- return Base64.getEncoder().encodeToString(data);- }- }-- private String resolveEncoding(PDFont font) {- if (font == null) {- return null;- }- COSDictionary dictionary = font.getCOSObject();- if (dictionary == null) {- return null;- }- COSBase encoding = dictionary.getDictionaryObject(COSName.ENCODING);- if (encoding instanceof COSName name) {- return name.getName();- }- if (encoding instanceof COSDictionary encodingDictionary) {- return encodingDictionary.getNameAsString(COSName.BASE_ENCODING);- }- return null;- }-- private String resolveStandard14Name(PDFont font) {- if (font == null) {- return null;- }- try {- Standard14Fonts.FontName mapped = Standard14Fonts.getMappedFontName(font.getName());- return mapped != null ? mapped.getName() : null;- } catch (IllegalArgumentException ex) {- return null;- }- }-- /**- * Fuzzy match a font name against Standard14 fonts as a last resort. Handles common variations- * like "TimesNewRoman" → "Times-Roman", "Arial" → "Helvetica", etc.- *- * @param baseName the font base name to match- * @return matched Standard14 font, or null if no reasonable match found- */- private Standard14Fonts.FontName fuzzyMatchStandard14(String baseName) {- if (baseName == null || baseName.isBlank()) {- return null;- }-- // Normalize: lowercase, remove spaces/hyphens/underscores, strip prefix (ABCD+FontName)- String normalized = baseName.trim();- int plusIndex = normalized.indexOf('+');- if (plusIndex >= 0 && plusIndex < normalized.length() - 1) {- normalized = normalized.substring(plusIndex + 1);- }- normalized =- WHITESPACE_DASH_UNDERSCORE_PATTERN- .matcher(normalized.toLowerCase(Locale.ROOT))- .replaceAll("");-- // Exact match after normalization- try {- Standard14Fonts.FontName exact = Standard14Fonts.getMappedFontName(baseName);- if (exact != null) {- return exact;- }- } catch (IllegalArgumentException ignored) {- // Not an exact match, continue with fuzzy matching- }-- // Times family: Times, TimesRoman, TimesNewRoman, TNR- if (normalized.contains("times") || normalized.equals("tnr")) {- if (normalized.contains("bold") && normalized.contains("italic")) {- return Standard14Fonts.FontName.TIMES_BOLD_ITALIC;- }- if (normalized.contains("bold")) {- return Standard14Fonts.FontName.TIMES_BOLD;- }- if (normalized.contains("italic") || normalized.contains("oblique")) {- return Standard14Fonts.FontName.TIMES_ITALIC;- }- return Standard14Fonts.FontName.TIMES_ROMAN;- }-- // Helvetica family: Helvetica, Arial, Swiss- if (normalized.contains("helvetica")- || normalized.contains("arial")- || normalized.contains("swiss")) {- if (normalized.contains("bold") && normalized.contains("oblique")) {- return Standard14Fonts.FontName.HELVETICA_BOLD_OBLIQUE;- }- if (normalized.contains("bold")) {- return Standard14Fonts.FontName.HELVETICA_BOLD;- }- if (normalized.contains("oblique") || normalized.contains("italic")) {- return Standard14Fonts.FontName.HELVETICA_OBLIQUE;- }- return Standard14Fonts.FontName.HELVETICA;- }-- // Courier family: Courier, CourierNew, Mono, Monospace- if (normalized.contains("courier") || normalized.contains("mono")) {- if (normalized.contains("bold")- && (normalized.contains("oblique") || normalized.contains("italic"))) {- return Standard14Fonts.FontName.COURIER_BOLD_OBLIQUE;- }- if (normalized.contains("bold")) {- return Standard14Fonts.FontName.COURIER_BOLD;- }- if (normalized.contains("oblique") || normalized.contains("italic")) {- return Standard14Fonts.FontName.COURIER_OBLIQUE;- }- return Standard14Fonts.FontName.COURIER;- }-- // Symbol and ZapfDingbats (less common)- if (normalized.contains("symbol")) {- return Standard14Fonts.FontName.SYMBOL;- }- if (normalized.contains("zapf") || normalized.contains("dingbat")) {- return Standard14Fonts.FontName.ZAPF_DINGBATS;- }-- // No reasonable match found- return null;- }-- private List<PdfJsonPage> extractPages(- PDDocument document,- Map<Integer, List<PdfJsonTextElement>> textByPage,- Map<Integer, List<PdfJsonImageElement>> imagesByPage,- Map<Integer, List<PdfJsonAnnotation>> annotationsByPage,- boolean omitResourceStreamData)- throws IOException {- List<PdfJsonPage> pages = new ArrayList<>();- int pageIndex = 0;- for (PDPage page : document.getPages()) {- PdfJsonPage pageModel = new PdfJsonPage();- pageModel.setPageNumber(pageIndex + 1);- // Use CropBox if present (defines visible page area), otherwise fall back to MediaBox- PDRectangle pageBox = page.getCropBox();- if (pageBox == null || pageBox.getWidth() == 0 || pageBox.getHeight() == 0) {- pageBox = page.getMediaBox();- }- pageModel.setWidth(pageBox.getWidth());- pageModel.setHeight(pageBox.getHeight());- pageModel.setRotation(page.getRotation());- pageModel.setTextElements(textByPage.getOrDefault(pageIndex + 1, new ArrayList<>()));- pageModel.setImageElements(imagesByPage.getOrDefault(pageIndex + 1, new ArrayList<>()));- pageModel.setAnnotations(- annotationsByPage.getOrDefault(pageIndex + 1, new ArrayList<>()));- // Serialize resources but exclude image XObject streams to avoid duplication with- // imageElements- COSBase resourcesBase = page.getCOSObject().getDictionaryObject(COSName.RESOURCES);- COSBase filteredResources = filterImageXObjectsFromResources(resourcesBase);- if (omitResourceStreamData) {- // In lightweight editor mode, omit heavy resource/content stream payloads entirely.- // Partial export preserves originals from cached PDF when these fields are missing.- pageModel.setResources(null);- pageModel.setContentStreams(null);- } else {- pageModel.setResources(cosMapper.serializeCosValue(filteredResources));- pageModel.setContentStreams(extractContentStreams(page, false));- }- pages.add(pageModel);- pageIndex++;- }- return pages;- }-- private Map<Integer, List<PdfJsonImageElement>> collectImages(- PDDocument document,- int totalPages,- Consumer<PdfJsonConversionProgress> progress,- Map<COSBase, EncodedImage> imageCache)- throws IOException {- Map<Integer, List<PdfJsonImageElement>> imagesByPage = new LinkedHashMap<>();- int pageNumber = 1;- for (PDPage page : document.getPages()) {- ImageCollectingEngine engine =- new ImageCollectingEngine(page, pageNumber, imagesByPage, imageCache);- engine.processPage(page);-- // Update progress for image extraction (70-80%)- int imageProgress = 70 + (int) ((pageNumber / (double) totalPages) * 10);- progress.accept(- PdfJsonConversionProgress.of(- imageProgress, "images", "Extracting images", pageNumber, totalPages));- pageNumber++;- }- return imagesByPage;- }-- private Map<Integer, List<PdfJsonAnnotation>> collectAnnotations(- PDDocument document,- int totalPages,- Consumer<PdfJsonConversionProgress> progress,- boolean includeRawData)- throws IOException {- Map<Integer, List<PdfJsonAnnotation>> annotationsByPage = new LinkedHashMap<>();- int pageNumber = 1;- for (PDPage page : document.getPages()) {- List<PdfJsonAnnotation> annotations = new ArrayList<>();- for (PDAnnotation annotation : page.getAnnotations()) {- try {- PdfJsonAnnotation ann = new PdfJsonAnnotation();- ann.setSubtype(annotation.getSubtype());- ann.setContents(annotation.getContents());-- PDRectangle rect = annotation.getRectangle();- if (rect != null) {- ann.setRect(- new float[] {- rect.getLowerLeftX(),- rect.getLowerLeftY(),- rect.getUpperRightX(),- rect.getUpperRightY()- });- }-- COSName appearanceState = annotation.getAppearanceState();- if (appearanceState != null) {- ann.setAppearanceState(appearanceState.getName());- }-- if (annotation.getColor() != null) {- ann.setColor(annotation.getColor().getComponents());- }-- COSDictionary annotDict = annotation.getCOSObject();- COSString title = (COSString) annotDict.getDictionaryObject(COSName.T);- if (title != null) {- ann.setAuthor(title.getString());- }-- COSString subj = (COSString) annotDict.getDictionaryObject(COSName.SUBJ);- if (subj != null) {- ann.setSubject(subj.getString());- }-- COSString creationDateStr =- (COSString) annotDict.getDictionaryObject(COSName.CREATION_DATE);- if (creationDateStr != null) {- try {- Calendar creationDate =- DateConverter.toCalendar(creationDateStr.getString());- ann.setCreationDate(formatCalendar(creationDate));- } catch (Exception e) {- log.debug(- "Failed to parse annotation creation date: {}", e.getMessage());- }- }-- COSString modDateStr = (COSString) annotDict.getDictionaryObject(COSName.M);- if (modDateStr != null) {- try {- Calendar modDate = DateConverter.toCalendar(modDateStr.getString());- ann.setModificationDate(formatCalendar(modDate));- } catch (Exception e) {- log.debug(- "Failed to parse annotation modification date: {}",- e.getMessage());- }- }-- if (includeRawData) {- // Store raw dictionary for lossless round-trip- ann.setRawData(- cosMapper.serializeCosValue(- annotDict,- PdfJsonCosMapper.SerializationContext.ANNOTATION_RAW_DATA));- }-- annotations.add(ann);- } catch (Exception e) {- log.warn(- "Failed to extract annotation on page {}: {}",- pageNumber,- e.getMessage());- }- }- if (!annotations.isEmpty()) {- annotationsByPage.put(pageNumber, annotations);- }-- // Update progress for annotation collection (80-90%)- int annotationProgress = 80 + (int) ((pageNumber / (double) totalPages) * 10);- progress.accept(- PdfJsonConversionProgress.of(- annotationProgress,- "annotations",- "Collecting annotations",- pageNumber,- totalPages));- pageNumber++;- }- return annotationsByPage;- }-- private List<PdfJsonFormField> collectFormFields(PDDocument document) {- List<PdfJsonFormField> formFields = new ArrayList<>();- PDAcroForm acroForm = document.getDocumentCatalog().getAcroForm();- if (acroForm == null) {- return formFields;- }-- try {- for (PDField field : acroForm.getFields()) {- try {- PdfJsonFormField formField = new PdfJsonFormField();- formField.setName(field.getFullyQualifiedName());- formField.setPartialName(field.getPartialName());- formField.setFieldType(field.getFieldType());- formField.setValue(field.getValueAsString());-- // Get default value from COS dictionary- COSBase dv = field.getCOSObject().getDictionaryObject(COSName.DV);- if (dv != null) {- if (dv instanceof COSString) {- formField.setDefaultValue(((COSString) dv).getString());- } else if (dv instanceof COSName) {- formField.setDefaultValue(((COSName) dv).getName());- }- }-- formField.setFlags(field.getFieldFlags());- formField.setAlternateFieldName(field.getAlternateFieldName());- formField.setMappingName(field.getMappingName());-- // Find which page the field is on- PDAnnotationWidget widget =- field.getWidgets().isEmpty() ? null : field.getWidgets().getFirst();- if (widget != null) {- PDPage fieldPage = widget.getPage();- if (fieldPage != null) {- int pageNum = document.getPages().indexOf(fieldPage) + 1;- formField.setPageNumber(pageNum);-- PDRectangle rect = widget.getRectangle();- if (rect != null) {- formField.setRect(- new float[] {- rect.getLowerLeftX(),- rect.getLowerLeftY(),- rect.getUpperRightX(),- rect.getUpperRightY()- });- }- }- }-- // Store raw dictionary for lossless round-trip- formField.setRawData(- cosMapper.serializeCosValue(- field.getCOSObject(),- PdfJsonCosMapper.SerializationContext.FORM_FIELD_RAW_DATA));-- formFields.add(formField);- } catch (Exception e) {- log.warn(- "Failed to extract form field {}: {}",- field.getFullyQualifiedName(),- e.getMessage());- }- }- } catch (Exception e) {- log.warn("Failed to extract form fields: {}", e.getMessage());- }-- return formFields;- }-- /**- * Filters out image XObject streams from resources to avoid duplication with imageElements.- * Images are already captured in imageElements[] with their base64 data, so we don't need them- * in the resources dictionary.- */- private COSBase filterImageXObjectsFromResources(COSBase resourcesBase) {- if (!(resourcesBase instanceof COSDictionary)) {- return resourcesBase;- }-- // Clone the resources dictionary- COSDictionary resources = new COSDictionary((COSDictionary) resourcesBase);-- // Get the XObject dictionary- COSBase xobjectBase = resources.getDictionaryObject(COSName.XOBJECT);- if (!(xobjectBase instanceof COSDictionary)) {- return resources;- }-- COSDictionary xobjects = (COSDictionary) xobjectBase;- COSDictionary filteredXObjects = new COSDictionary();-- // Copy all XObjects except images- for (COSName key : xobjects.keySet()) {- COSBase value = xobjects.getDictionaryObject(key);- if (value instanceof COSStream) {- COSStream stream = (COSStream) value;- COSName type = (COSName) stream.getDictionaryObject(COSName.TYPE);- COSName subtype = (COSName) stream.getDictionaryObject(COSName.SUBTYPE);-- // Skip if this is an Image XObject- if (COSName.XOBJECT.equals(type) && COSName.IMAGE.equals(subtype)) {- continue;- }- }- // Keep non-image XObjects (Form XObjects, etc.)- filteredXObjects.setItem(key, value);- }-- // If all XObjects were images, remove the XObject entry entirely- if (filteredXObjects.keySet().isEmpty()) {- resources.removeItem(COSName.XOBJECT);- } else {- resources.setItem(COSName.XOBJECT, filteredXObjects);- }-- return resources;- }-- private PdfJsonMetadata extractMetadata(PDDocument document) {- PdfJsonMetadata metadata = new PdfJsonMetadata();- PDDocumentInformation info = document.getDocumentInformation();- if (info != null) {- metadata.setTitle(info.getTitle());- metadata.setAuthor(info.getAuthor());- metadata.setSubject(info.getSubject());- metadata.setKeywords(info.getKeywords());- metadata.setCreator(info.getCreator());- metadata.setProducer(info.getProducer());- metadata.setCreationDate(formatCalendar(info.getCreationDate()));- metadata.setModificationDate(formatCalendar(info.getModificationDate()));- metadata.setTrapped(info.getTrapped());- }- metadata.setNumberOfPages(document.getNumberOfPages());- return metadata;- }-- private String extractXmpMetadata(PDDocument document) {- if (document.getDocumentCatalog() == null) {- return null;- }- PDMetadata metadata = document.getDocumentCatalog().getMetadata();- if (metadata == null) {- return null;- }- try (InputStream inputStream = metadata.createInputStream();- ByteArrayOutputStream baos = new ByteArrayOutputStream()) {- inputStream.transferTo(baos);- byte[] data = baos.toByteArray();- if (data.length == 0) {- return null;- }- return Base64.getEncoder().encodeToString(data);- } catch (IOException ex) {- log.debug("Failed to extract XMP metadata: {}", ex.getMessage());- return null;- }- }-- private void applyMetadata(PDDocument document, PdfJsonMetadata metadata) {- if (metadata == null) {- return;- }- PDDocumentInformation info = document.getDocumentInformation();- info.setTitle(metadata.getTitle());- info.setAuthor(metadata.getAuthor());- info.setSubject(metadata.getSubject());- info.setKeywords(metadata.getKeywords());- info.setCreator(metadata.getCreator());- info.setProducer(metadata.getProducer());- if (metadata.getCreationDate() != null) {- parseInstant(metadata.getCreationDate())- .ifPresent(instant -> info.setCreationDate(toCalendar(instant)));- }- if (metadata.getModificationDate() != null) {- parseInstant(metadata.getModificationDate())- .ifPresent(instant -> info.setModificationDate(toCalendar(instant)));- }- info.setTrapped(metadata.getTrapped());- }-- private void applyXmpMetadata(PDDocument document, String base64) {- if (base64 == null || base64.isBlank()) {- return;- }- try (InputStream inputStream =- new ByteArrayInputStream(Base64.getDecoder().decode(base64))) {- PDMetadata metadata = new PDMetadata(document, inputStream);- document.getDocumentCatalog().setMetadata(metadata);- } catch (IllegalArgumentException | IOException ex) {- log.debug("Failed to apply XMP metadata: {}", ex.getMessage());- }- }-- private void restoreAnnotations(- PDDocument document, PDPage page, List<PdfJsonAnnotation> annotations) {- if (annotations == null || annotations.isEmpty()) {- return;- }-- for (PdfJsonAnnotation annModel : annotations) {- try {- // Restore from raw COS data if available for lossless round-trip- if (annModel.getRawData() != null) {- COSBase rawAnnot =- cosMapper.deserializeCosValue(annModel.getRawData(), document);- if (rawAnnot instanceof COSDictionary) {- PDAnnotation annotation =- PDAnnotation.createAnnotation((COSDictionary) rawAnnot);- page.getAnnotations().add(annotation);- log.debug("Restored annotation from raw data: {}", annModel.getSubtype());- continue;- }- }-- // Fallback: reconstruct from structured fields- // Note: This is simplified - full annotation reconstruction is complex- // Most use cases should rely on rawData for lossless round-trip- log.debug(- "Warning: Annotation {} has no rawData, basic reconstruction may lose information",- annModel.getSubtype());-- } catch (Exception e) {- log.warn(- "Failed to restore annotation {}: {}",- annModel.getSubtype(),- e.getMessage());- }- }- }-- private void restoreFormFields(PDDocument document, List<PdfJsonFormField> formFields) {- if (formFields == null || formFields.isEmpty()) {- return;- }-- try {- PDAcroForm acroForm = document.getDocumentCatalog().getAcroForm();- if (acroForm == null) {- acroForm = new PDAcroForm(document);- document.getDocumentCatalog().setAcroForm(acroForm);- }-- COSArray fieldsArray =- (COSArray) acroForm.getCOSObject().getDictionaryObject(COSName.FIELDS);- if (fieldsArray == null) {- fieldsArray = new COSArray();- acroForm.getCOSObject().setItem(COSName.FIELDS, fieldsArray);- }-- for (PdfJsonFormField fieldModel : formFields) {- try {- // Restore from raw COS data if available for lossless round-trip- if (fieldModel.getRawData() != null) {- COSBase rawField =- cosMapper.deserializeCosValue(fieldModel.getRawData(), document);- if (rawField instanceof COSDictionary) {- // Add the field dictionary directly to the fields array- fieldsArray.add(rawField);- log.debug(- "Restored form field from raw data: {}", fieldModel.getName());- continue;- }- }-- // Fallback: reconstruct from structured fields- // Note: This is simplified - full field reconstruction is complex- log.debug(- "Warning: Form field {} has no rawData, basic reconstruction may lose information",- fieldModel.getName());-- } catch (Exception e) {- log.warn(- "Failed to restore form field {}: {}",- fieldModel.getName(),- e.getMessage());- }- }- } catch (Exception e) {- log.warn("Failed to restore form fields: {}", e.getMessage());- }- }-- private void applyPageResources(- PDDocument document, PDPage page, PdfJsonCosValue resourcesModel) throws IOException {- if (resourcesModel == null) {- return;- }- COSBase base = cosMapper.deserializeCosValue(resourcesModel, document);- if (base instanceof COSDictionary dictionary) {- page.setResources(new PDResources(dictionary));- }- }-- /**- * Reconstructs image XObjects from imageElements when content streams are preserved. During- * serialization, image streams are filtered out from resources to avoid duplication. This- * method adds them back by scanning content streams for XObject references and matching them- * with imageElements by objectName.- */- private void reconstructImageXObjects(- PDDocument document,- PDPage page,- List<PDStream> contentStreams,- List<PdfJsonImageElement> imageElements)- throws IOException {-- // Build map of objectName -> imageElement- Map<String, PdfJsonImageElement> imageMap = new HashMap<>();- for (PdfJsonImageElement img : imageElements) {- if (img.getObjectName() != null && !img.getObjectName().isBlank()) {- imageMap.put(img.getObjectName(), img);- }- }-- if (imageMap.isEmpty()) {- return;- }-- // Scan content streams for image XObject references- Set<String> referencedXObjects = new HashSet<>();- for (PDStream stream : contentStreams) {- try {- byte[] contentBytes = stream.toByteArray();- PDFStreamParser parser = new PDFStreamParser(contentBytes);- List<Object> tokens = parser.parse();-- for (int i = 0; i < tokens.size(); i++) {- Object token = tokens.get(i);- if (token instanceof Operator op- && OperatorName.DRAW_OBJECT.equals(op.getName())) {- if (i > 0 && tokens.get(i - 1) instanceof COSName name) {- referencedXObjects.add(name.getName());- }- }- }- } catch (Exception e) {- log.warn("Failed to parse content stream for image references: {}", e.getMessage());- }- }-- // Reconstruct referenced image XObjects- PDResources resources = page.getResources();- if (resources == null) {- resources = new PDResources();- page.setResources(resources);- }-- for (String xobjName : referencedXObjects) {- PdfJsonImageElement imageElement = imageMap.get(xobjName);- if (imageElement == null) {- log.warn(- "Content stream references image XObject '{}' but no matching imageElement found",- xobjName);- continue;- }-- try {- PDImageXObject image = createImageXObject(document, imageElement);- if (image != null) {- resources.put(COSName.getPDFName(xobjName), image);- log.debug("Reconstructed image XObject: {}", xobjName);- }- } catch (Exception e) {- log.warn("Failed to reconstruct image XObject '{}': {}", xobjName, e.getMessage());- }- }- }-- private List<PDStream> buildContentStreams(- PDDocument document, List<PdfJsonStream> streamModels) throws IOException {- List<PDStream> streams = new ArrayList<>();- if (streamModels == null) {- return streams;- }- for (PdfJsonStream streamModel : streamModels) {- if (streamModel == null) {- continue;- }- COSStream cosStream = cosMapper.buildStreamFromModel(streamModel, document);- if (cosStream != null) {- streams.add(new PDStream(cosStream));- }- }- return streams;- }-- private List<PdfJsonStream> extractContentStreams(PDPage page, boolean omitRawData)- throws IOException {- List<PdfJsonStream> streams = new ArrayList<>();- Iterator<PDStream> iterator = page.getContentStreams();- if (iterator == null) {- return streams;- }- while (iterator.hasNext()) {- PDStream stream = iterator.next();- PdfJsonStream model =- omitRawData- ? cosMapper.serializeStream(- stream,- PdfJsonCosMapper.SerializationContext- .CONTENT_STREAMS_LIGHTWEIGHT)- : cosMapper.serializeStream(stream);- if (model != null) {- streams.add(model);- }- }- return streams;- }-- private List<PdfJsonStream> extractContentStreams(PDPage page) throws IOException {- return extractContentStreams(page, false);- }-- private PDStream extractVectorGraphics(- PDDocument document,- List<PDStream> preservedStreams,- List<PdfJsonImageElement> imageElements)- throws IOException {- if (preservedStreams == null || preservedStreams.isEmpty()) {- return null;- }-- Set<String> imageObjectNames = new HashSet<>();- if (imageElements != null) {- for (PdfJsonImageElement element : imageElements) {- if (element == null) {- continue;- }- String objectName = element.getObjectName();- if (objectName != null && !objectName.isBlank()) {- imageObjectNames.add(objectName);- }- }- }-- List<Object> filteredTokens = new ArrayList<>();- for (PDStream stream : preservedStreams) {- if (stream == null) {- continue;- }- try {- PDFStreamParser parser = new PDFStreamParser(stream.toByteArray());- List<Object> tokens = parser.parse();- collectVectorTokens(tokens, filteredTokens, imageObjectNames);- } catch (IOException ex) {- log.debug(- "Failed to parse preserved content stream for vector extraction: {}",- ex.getMessage());- }- }-- if (filteredTokens.isEmpty()) {- return null;- }-- PDStream vectorStream = new PDStream(document);- try (OutputStream outputStream = vectorStream.createOutputStream(COSName.FLATE_DECODE)) {- new ContentStreamWriter(outputStream).writeTokens(filteredTokens);- }- return vectorStream;- }-- private void collectVectorTokens(- List<Object> sourceTokens, List<Object> targetTokens, Set<String> imageObjectNames) {- if (sourceTokens == null || sourceTokens.isEmpty()) {- return;- }-- boolean insideText = false;- boolean insideInlineImage = false;-- for (Object token : sourceTokens) {- if (token instanceof Operator operator) {- String name = operator.getName();- if (OperatorName.BEGIN_TEXT.equals(name)) {- insideText = true;- continue;- }- if (OperatorName.END_TEXT.equals(name)) {- insideText = false;- continue;- }- if (OperatorName.BEGIN_INLINE_IMAGE.equals(name)- || OperatorName.BEGIN_INLINE_IMAGE_DATA.equals(name)) {- if (!insideText) {- targetTokens.add(operator);- }- insideInlineImage = true;- continue;- }- if (OperatorName.END_INLINE_IMAGE.equals(name)) {- if (!insideText) {- targetTokens.add(operator);- }- insideInlineImage = false;- continue;- }- if (insideText && !insideInlineImage) {- continue;- }- if (OperatorName.DRAW_OBJECT.equals(name)- && imageObjectNames != null- && !imageObjectNames.isEmpty()- && !targetTokens.isEmpty()) {- Object previous = targetTokens.getLast();- if (previous instanceof COSName cosName- && imageObjectNames.contains(cosName.getName())) {- targetTokens.remove(targetTokens.size() - 1);- continue;- }- }- targetTokens.add(operator);- } else {- if (insideText && !insideInlineImage) {- continue;- }- targetTokens.add(token);- }- }- }-- private void regeneratePageContent(- PDDocument document,- PDPage page,- List<PdfJsonTextElement> textElements,- List<PdfJsonImageElement> imageElements,- Map<String, PDFont> fontMap,- List<PdfJsonFont> fontModels,- int pageNumber,- AppendMode appendMode)- throws IOException {- List<DrawableElement> drawables = mergeDrawables(textElements, imageElements);- Map<String, PDImageXObject> imageCache = new HashMap<>();- Map<String, PdfJsonFont> runFontLookup = buildFontModelLookup(fontModels);-- AppendMode mode = appendMode != null ? appendMode : AppendMode.OVERWRITE;- try (PDPageContentStream contentStream =- new PDPageContentStream(document, page, mode, true, true)) {- boolean textOpen = false;- for (DrawableElement drawable : drawables) {- switch (drawable.type()) {- case TEXT -> {- PdfJsonTextElement element = drawable.textElement();- if (element == null) {- continue;- }- String text = Objects.toString(element.getText(), "");-- if (!textOpen) {- contentStream.beginText();- textOpen = true;- }-- PDFont baseFont =- fontMap.get(buildFontKey(null, pageNumber, element.getFontId()));- if (baseFont == null && element.getFontId() != null) {- baseFont = fontMap.get(buildFontKey(null, -1, element.getFontId()));- }-- float fontScale = resolveFontMatrixSize(element);-- applyTextState(contentStream, element);- applyRenderingMode(contentStream, element.getRenderingMode());- applyTextMatrix(contentStream, element);-- List<FontRun> runs =- buildFontRuns(- document,- fontMap,- fontModels,- pageNumber,- baseFont,- text,- element);-- PDFont activeFont = null;- for (FontRun run : runs) {- if (run == null || run.text().isEmpty()) {- continue;- }- if (run.font() != activeFont) {- contentStream.setFont(run.font(), fontScale);- activeFont = run.font();- }- PdfJsonFont runFontModel =- resolveFontModel(runFontLookup, pageNumber, run.fontId());- if (runFontModel == null) {- runFontLookup = buildFontModelLookup(fontModels);- runFontModel =- resolveFontModel(runFontLookup, pageNumber, run.fontId());- }- // Check if this is a normalized Type3 font (has Type3 metadata but is- // not PDType3Font)- boolean isNormalizedType3 =- !(run.font() instanceof PDType3Font)- && runFontModel != null- && runFontModel.getType3Glyphs() != null- && !runFontModel.getType3Glyphs().isEmpty();-- // For fonts with proper Unicode mappings, let PDFBox handle encoding- // This includes: normalized Type3 fonts, PDType0Font (composite fonts)- boolean useDirectText =- isNormalizedType3- || run.font()- instanceof- org.apache.pdfbox.pdmodel.font.PDType0Font;-- if (useDirectText) {- // Pass text directly - PDFBox handles encoding internally- contentStream.showText(run.text());- } else {- // For actual Type3 fonts and other fonts, encode manually- byte[] encoded;- if (run.font() instanceof PDType3Font- && run.charCodes() != null- && !run.charCodes().isEmpty()) {- encoded = encodeType3CharCodes(run.charCodes());- if (encoded == null || encoded.length == 0) {- log.warn(- "[FONT-DEBUG] Failed to emit raw Type3 char codes for font {} on page {}",- run.font().getName(),- pageNumber);- continue;- }- } else {- try {- log.debug(- "[ENCODE-DEBUG] Encoding text '{}' with font {} (fontId={}, runFontModel={})",- run.text(),- run.font().getName(),- run.fontId(),- runFontModel != null- ? runFontModel.getId()- : "null");- encoded =- encodeTextWithFont(- run.font(),- runFontModel,- run.text(),- run.charCodes());- } catch (IOException ex) {- log.warn(- "Failed to encode text '{}' with font {} (fontId={}, runFontModel={}) on page {}: {}",- run.text(),- run.font().getName(),- run.fontId(),- runFontModel != null- ? runFontModel.getId()- : "null",- pageNumber,- ex.getMessage());- continue;- }- }- if (encoded == null || encoded.length == 0) {- log.warn(- "Failed to encode text '{}' with font {} on page {}",- run.text(),- run.font().getName(),- pageNumber);- continue;- }- try {- contentStream.showText(- new String(encoded, StandardCharsets.ISO_8859_1));- } catch (IllegalArgumentException ex) {- log.warn(- "Failed to render text '{}' with font {} on page {}: {}",- run.text(),- run.font().getName(),- pageNumber,- ex.getMessage());- continue;- }- }- }- }- case IMAGE -> {- if (textOpen) {- contentStream.endText();- textOpen = false;- }- PdfJsonImageElement element = drawable.imageElement();- if (element == null) {- continue;- }- drawImageElement(contentStream, document, element, imageCache);- }- }- }- if (textOpen) {- contentStream.endText();- }- }- }-- private List<FontRun> buildFontRuns(- PDDocument document,- Map<String, PDFont> fontMap,- List<PdfJsonFont> fontModels,- int pageNumber,- PDFont primaryFont,- String text,- PdfJsonTextElement element)- throws IOException {- List<FontRun> runs = new ArrayList<>();- if (text == null || text.isEmpty()) {- return runs;- }-- PDFont baseFont = primaryFont;- String baseFontId = element.getFontId();- boolean fallbackApplied = primaryFont == null;- if (baseFont == null) {- baseFont = ensureFallbackFont(document, fontMap, fontModels, FALLBACK_FONT_ID);- if (baseFont != null) {- baseFontId = FALLBACK_FONT_ID;- fallbackApplied = true;- }- }- if (baseFont == null) {- log.warn("Unable to resolve a base font for text element; skipping text content");- return runs;- }-- Map<String, PdfJsonFont> runFontLookup = buildFontModelLookup(fontModels);- PdfJsonFont baseFontModel = resolveFontModel(runFontLookup, pageNumber, baseFontId);- boolean baseIsType3 =- baseFontModel != null- && baseFontModel.getSubtype() != null- && "type3".equalsIgnoreCase(baseFontModel.getSubtype());- PDFont normalizedType3Font =- baseIsType3 && baseFontModel.getUid() != null- ? type3NormalizedFontCache.get(baseFontModel.getUid())- : null;- Set<Integer> baseType3Coverage =- baseIsType3 && baseFontModel != null- ? type3GlyphCoverageCache.getOrDefault(- baseFontModel.getUid(), Collections.emptySet())- : Collections.emptySet();- boolean hasNormalizedType3 = baseIsType3 && normalizedType3Font != null;- if (hasNormalizedType3 && log.isDebugEnabled()) {- log.debug(- "[TYPE3-RUNTIME] Using normalized library font {} for Type3 resource {} on page {}",- normalizedType3Font.getName(),- baseFontModel != null ? baseFontModel.getId() : baseFontId,- pageNumber);- }-- StringBuilder buffer = new StringBuilder();- List<Integer> codeBuffer = new ArrayList<>();- PDFont currentFont = baseFont;- String currentFontId = baseFontId;-- int[] elementCodes = element.getCharCodes();- int codeIndex = 0;- boolean rawType3CodesUsed = false;- int rawType3GlyphCount = 0;-- for (int offset = 0; offset < text.length(); ) {- int codePoint = text.codePointAt(offset);- offset += Character.charCount(codePoint);- String glyph = new String(Character.toChars(codePoint));- PDFont targetFont = baseFont;- String targetFontId = baseFontId;- Integer rawCode = null;- if (elementCodes != null && codeIndex < elementCodes.length) {- rawCode = elementCodes[codeIndex];- }- codeIndex++;-- if (hasNormalizedType3) {- targetFont = normalizedType3Font;- // For normalized fonts, check if the font can actually encode the glyph- // Don't check Type3 coverage since normalized fonts have full glyph sets- if (!fallbackFontService.canEncode(normalizedType3Font, glyph)) {- // Glyph not in normalized font, will trigger fallback below- targetFont = null;- targetFontId = null;- }- } else if (baseIsType3) {- // For actual Type3 fonts without normalized replacement- boolean type3SupportsGlyph =- isGlyphCoveredByType3Font(baseType3Coverage, codePoint);- if (!type3SupportsGlyph) {- targetFont = null;- targetFontId = null;- }- }- if (targetFont == null || !fallbackFontService.canEncode(targetFont, glyph)) {- fallbackApplied = true;- // Try to match fallback font to original font family for visual consistency- String originalFontName =- baseFontModel != null ? baseFontModel.getBaseName() : null;- String fallbackId =- fallbackFontService.resolveFallbackFontId(originalFontName, codePoint);- targetFont = ensureFallbackFont(document, fontMap, fontModels, fallbackId);- targetFontId = fallbackId != null ? fallbackId : FALLBACK_FONT_ID;- if (targetFont == null || !fallbackFontService.canEncode(targetFont, glyph)) {- String mapped = fallbackFontService.mapUnsupportedGlyph(codePoint);- if (mapped != null) {- if (targetFont != null- && fallbackFontService.canEncode(targetFont, mapped)) {- glyph = mapped;- } else if (fallbackFontService.canEncode(baseFont, mapped)) {- glyph = mapped;- targetFont = baseFont;- targetFontId = baseFontId;- }- }- if (targetFont == null || !fallbackFontService.canEncode(targetFont, glyph)) {- glyph = "?";- targetFont =- ensureFallbackFont(document, fontMap, fontModels, FALLBACK_FONT_ID);- targetFontId = FALLBACK_FONT_ID;- if (targetFont == null- || !fallbackFontService.canEncode(targetFont, glyph)) {- log.debug(- "Dropping unsupported glyph U+{} for text element",- Integer.toHexString(codePoint));- continue;- }- }- }- // Fallback applied - tracked at page level, not logged per character- }-- boolean useRawType3Glyph =- rawCode != null- && baseIsType3- && !hasNormalizedType3- && targetFont == baseFont- && targetFont instanceof PDType3Font;-- if (targetFont != currentFont) {- if (buffer.length() > 0) {- runs.add(- new FontRun(- currentFont,- currentFontId,- buffer.toString(),- codeBuffer.isEmpty() ? null : new ArrayList<>(codeBuffer)));- buffer.setLength(0);- codeBuffer.clear();- }- currentFont = targetFont;- currentFontId = targetFontId;- }- buffer.append(glyph);- if (useRawType3Glyph- && currentFontId != null- && currentFontId.equals(element.getFontId())) {- codeBuffer.add(rawCode);- rawType3CodesUsed = true;- rawType3GlyphCount++;- }- }-- if (buffer.length() > 0) {- runs.add(- new FontRun(- currentFont,- currentFontId,- buffer.toString(),- codeBuffer.isEmpty() ? null : new ArrayList<>(codeBuffer)));- }-- if (fallbackApplied) {- element.setFallbackUsed(Boolean.TRUE);- }-- if (rawType3CodesUsed) {- log.debug(- "[TYPE3-RUNTIME] Reused original Type3 charCodes for font {} on page {} ({} glyphs)",- baseFontModel != null ? baseFontModel.getId() : baseFontId,- pageNumber,- rawType3GlyphCount);- }-- return runs;- }-- private Integer extractUnitsPerEm(PDFont font) {- if (font == null) {- return null;- }- Matrix matrix = font.getFontMatrix();- if (matrix != null) {- float scaleX = matrix.getScaleX();- if (scaleX != 0f) {- int units = Math.round(Math.abs(1f / scaleX));- if (units > 0 && units < 10_000) {- return units;- }- }- }- return 1000;- }-- private void closeQuietly(TempFile tempFile) {- if (tempFile == null) {- return;- }- try {- tempFile.close();- } catch (Exception ex) {- log.debug("Failed to close temporary file: {}", ex.getMessage());- }- }-- // Cache helpers- private CachedPdfDocument buildCachedDocument(- String jobId,- byte[] pdfBytes,- PdfJsonDocumentMetadata metadata,- Map<String, PdfJsonFont> fonts,- Map<Integer, Map<PDFont, String>> pageFontResources)- throws IOException {- if (pdfBytes == null) {- throw new IllegalArgumentException("pdfBytes must not be null");- }- long budget = cacheBudgetBytes;- // If single document is larger than budget, spill straight to disk- if (budget > 0 && pdfBytes.length > budget) {- TempFile tempFile = new TempFile(tempFileManager, ".pdfjsoncache");- Files.write(tempFile.getPath(), pdfBytes);- log.debug(- "Cached PDF spilled to disk ({} bytes exceeds budget {}) for jobId {}",- pdfBytes.length,- budget,- jobId);- return new CachedPdfDocument(- null, tempFile, pdfBytes.length, metadata, fonts, pageFontResources);- }- return new CachedPdfDocument(- pdfBytes, null, pdfBytes.length, metadata, fonts, pageFontResources);- }-- private void putCachedDocument(String jobId, CachedPdfDocument cached) {- synchronized (cacheLock) {- CachedPdfDocument existing = documentCache.put(jobId, cached);- if (existing != null) {- lruCache.remove(jobId);- currentCacheBytes = Math.max(0L, currentCacheBytes - existing.getInMemorySize());- existing.close();- }- lruCache.put(jobId, cached);- currentCacheBytes += cached.getInMemorySize();- enforceCacheBudget();- }- }-- private CachedPdfDocument getCachedDocument(String jobId) {- synchronized (cacheLock) {- CachedPdfDocument cached = documentCache.get(jobId);- if (cached != null) {- lruCache.remove(jobId);- lruCache.put(jobId, cached);- }- return cached;- }- }-- private void enforceCacheBudget() {- if (cacheBudgetBytes <= 0) {- return;- }- // Must be called under cacheLock- java.util.Iterator<java.util.Map.Entry<String, CachedPdfDocument>> it =- lruCache.entrySet().iterator();- while (currentCacheBytes > cacheBudgetBytes && it.hasNext()) {- java.util.Map.Entry<String, CachedPdfDocument> entry = it.next();- it.remove();- CachedPdfDocument removed = entry.getValue();- documentCache.remove(entry.getKey(), removed);- currentCacheBytes = Math.max(0L, currentCacheBytes - removed.getInMemorySize());- removed.close();- log.warn(- "Evicted cached PDF for jobId {} to enforce cache budget (budget={} bytes, current={} bytes)",- entry.getKey(),- cacheBudgetBytes,- currentCacheBytes);- }- if (currentCacheBytes > cacheBudgetBytes && !lruCache.isEmpty()) {- // Spill the most recently used large entry to disk- String key =- lruCache.entrySet().stream()- .reduce((first, second) -> second)- .map(java.util.Map.Entry::getKey)- .orElse(null);- if (key != null) {- CachedPdfDocument doc = lruCache.get(key);- if (doc != null && doc.getInMemorySize() > 0) {- try {- CachedPdfDocument diskDoc =- buildCachedDocument(- key,- doc.getPdfBytes(),- doc.getMetadata(),- doc.getFonts(),- doc.getPageFontResources());- lruCache.put(key, diskDoc);- documentCache.put(key, diskDoc);- currentCacheBytes =- Math.max(0L, currentCacheBytes - doc.getInMemorySize())- + diskDoc.getInMemorySize();- doc.close();- log.debug("Spilled cached PDF for jobId {} to disk to satisfy budget", key);- } catch (IOException ex) {- log.warn(- "Failed to spill cached PDF for jobId {} to disk: {}",- key,- ex.getMessage());- }- }- }- }- }-- private void removeCachedDocument(String jobId) {- log.warn(- "removeCachedDocument called for jobId: {} [CALLER: {}]",- jobId,- Thread.currentThread().getStackTrace()[2].toString());- CachedPdfDocument removed = null;- synchronized (cacheLock) {- removed = documentCache.remove(jobId);- if (removed != null) {- lruCache.remove(jobId);- currentCacheBytes = Math.max(0L, currentCacheBytes - removed.getInMemorySize());- log.warn(- "Removed cached document for jobId: {} (size={} bytes)",- jobId,- removed.getInMemorySize());- } else {- log.warn("Attempted to remove jobId: {} but it was not in cache", jobId);- }- }- if (removed != null) {- removed.close();- }- }-- private void applyTextState(PDPageContentStream contentStream, PdfJsonTextElement element)- throws IOException {- if (element.getCharacterSpacing() != null) {- contentStream.setCharacterSpacing(element.getCharacterSpacing());- }- if (element.getWordSpacing() != null) {- contentStream.setWordSpacing(element.getWordSpacing());- }- if (element.getHorizontalScaling() != null) {- contentStream.setHorizontalScaling(element.getHorizontalScaling());- }- if (element.getLeading() != null) {- contentStream.setLeading(element.getLeading());- }- if (element.getRise() != null) {- contentStream.setTextRise(element.getRise());- }- applyColor(contentStream, element.getFillColor(), true);- applyColor(contentStream, element.getStrokeColor(), false);- }-- private void applyColor(- PDPageContentStream contentStream, PdfJsonTextColor color, boolean nonStroking)- throws IOException {- if (color == null || color.getComponents() == null) {- return;- }- float[] components = color.getComponents();- String space = color.getColorSpace();- if (space == null) {- // Infer color space from component count- PDColorSpace colorSpace;- if (components.length == 1) {- colorSpace = PDColorSpace.create(COSName.DEVICEGRAY);- } else if (components.length == 3) {- colorSpace = PDColorSpace.create(COSName.DEVICERGB);- } else if (components.length == 4) {- colorSpace = PDColorSpace.create(COSName.DEVICECMYK);- } else {- // Default to RGB if unsure- colorSpace = PDColorSpace.create(COSName.DEVICERGB);- }- PDColor pdColor = new PDColor(components, colorSpace);- if (nonStroking) {- contentStream.setNonStrokingColor(pdColor);- } else {- contentStream.setStrokingColor(pdColor);- }- return;- }- switch (space) {- case "DeviceRGB":- if (components.length >= 3) {- if (nonStroking) {- contentStream.setNonStrokingColor(- components[0], components[1], components[2]);- } else {- contentStream.setStrokingColor(components[0], components[1], components[2]);- }- }- break;- case "DeviceCMYK":- if (components.length >= 4) {- if (nonStroking) {- contentStream.setNonStrokingColor(- components[0], components[1], components[2], components[3]);- } else {- contentStream.setStrokingColor(- components[0], components[1], components[2], components[3]);- }- }- break;- case "DeviceGray":- if (components.length >= 1) {- if (nonStroking) {- contentStream.setNonStrokingColor(components[0]);- } else {- contentStream.setStrokingColor(components[0]);- }- }- break;- default:- log.debug("[ColorApply] Skipping unsupported color space {}", space);- }- }-- private String abbreviate(String value) {- if (value == null) {- return "";- }- String trimmed = WHITESPACE_PATTERN.matcher(value).replaceAll(" ").trim();- if (trimmed.length() <= 32) {- return trimmed;- }- return trimmed.substring(0, 29) + "...";- }-- private static class FontProgramData {- private final String base64;- private final String format;- private final String webBase64;- private final String webFormat;- private final String pdfBase64;- private final String pdfFormat;-- private FontProgramData(- String base64,- String format,- String webBase64,- String webFormat,- String pdfBase64,- String pdfFormat) {- this.base64 = base64;- this.format = format;- this.webBase64 = webBase64;- this.webFormat = webFormat;- this.pdfBase64 = pdfBase64;- this.pdfFormat = pdfFormat;- }-- private String getBase64() {- return base64;- }-- private String getFormat() {- return format;- }-- private String getWebBase64() {- return webBase64;- }-- private String getWebFormat() {- return webFormat;- }-- private String getPdfBase64() {- return pdfBase64;- }-- private String getPdfFormat() {- return pdfFormat;- }- }-- private static final class PreflightResult {- private static final PreflightResult EMPTY = new PreflightResult(false, Set.of());-- private final boolean usesFallback;- private final Set<String> fallbackFontIds;-- private PreflightResult(boolean usesFallback, Set<String> fallbackFontIds) {- this.usesFallback = usesFallback;- this.fallbackFontIds = fallbackFontIds != null ? Set.copyOf(fallbackFontIds) : Set.of();- }-- private static PreflightResult empty() {- return EMPTY;- }-- private boolean usesFallback() {- return usesFallback;- }-- private Set<String> fallbackFontIds() {- return fallbackFontIds;- }- }-- private static final class FontRun {- private final PDFont font;- private final String fontId;- private final String text;- private final List<Integer> charCodes;-- private FontRun(PDFont font, String fontId, String text, List<Integer> charCodes) {- this.font = font;- this.fontId = fontId;- this.text = text;- this.charCodes = charCodes;- }-- private PDFont font() {- return font;- }-- private String fontId() {- return fontId;- }-- private String text() {- return text;- }-- private List<Integer> charCodes() {- return charCodes;- }- }-- private boolean rewriteTextOperators(- PDDocument document,- PDPage page,- List<PdfJsonTextElement> elements,- boolean removeOnly,- boolean forceRegenerate,- Map<String, PdfJsonFont> fontLookup,- int pageNumber) {- if (forceRegenerate) {- log.debug("forceRegenerate flag set; skipping token rewrite for page");- return false;- }- if (elements == null || elements.isEmpty()) {- return true;- }- PDResources resources = page.getResources();- if (resources == null) {- return false;- }- try {- log.debug("Attempting token-level rewrite for page");- PDFStreamParser parser = new PDFStreamParser(page);- List<Object> tokens = parser.parse();- log.debug("Parsed {} tokens for rewrite", tokens.size());- TextElementCursor cursor = new TextElementCursor(elements);- PDFont currentFont = null;- String currentFontName = null;- PdfJsonFont currentFontModel = null;-- boolean encounteredModifiedFont = false;-- for (int i = 0; i < tokens.size(); i++) {- Object token = tokens.get(i);- if (!(token instanceof Operator operator)) {- continue;- }- String operatorName = operator.getName();- switch (operatorName) {- case "Tf":- if (i >= 2 && tokens.get(i - 2) instanceof COSName fontResourceName) {- currentFont = resources.getFont(fontResourceName);- currentFontName = fontResourceName.getName();- currentFontModel =- resolveFontModel(fontLookup, pageNumber, currentFontName);- log.trace(- "Encountered Tf operator; switching to font resource {}",- currentFontName);- if (forceRegenerate) {- encounteredModifiedFont = true;- }- } else {- currentFont = null;- currentFontName = null;- currentFontModel = null;- log.debug(- "Tf operator missing resource operand; clearing current font");- }- break;- case "Tj":- if (i == 0 || !(tokens.get(i - 1) instanceof COSString)) {- log.debug(- "Encountered Tj without preceding string operand; aborting rewrite");- return false;- }- log.trace(- "Rewriting Tj operator using font {} (token index {}, cursor remaining {})",- currentFontName,- i,- cursor.remaining());- if (!rewriteShowText(- tokens,- i - 1,- currentFont,- currentFontModel,- currentFontName,- cursor,- removeOnly)) {- log.debug("Failed to rewrite Tj operator; aborting rewrite");- return false;- }- break;- case "TJ":- if (i == 0 || !(tokens.get(i - 1) instanceof COSArray array)) {- log.debug("Encountered TJ without array operand; aborting rewrite");- return false;- }- log.trace(- "Rewriting TJ operator using font {} (token index {}, cursor remaining {})",- currentFontName,- i,- cursor.remaining());- if (!rewriteShowTextArray(- array,- currentFont,- currentFontModel,- currentFontName,- cursor,- removeOnly)) {- log.debug("Failed to rewrite TJ operator; aborting rewrite");- return false;- }- break;- default:- break;- }- }-- if (cursor.hasRemaining()) {- log.debug("Rewrite cursor still has {} elements; falling back", cursor.remaining());- return false;- }-- if (forceRegenerate && encounteredModifiedFont) {- log.debug(- "Rewrite succeeded but forceRegenerate=true, returning false to trigger rebuild");- return false;- }-- PDStream newStream = new PDStream(document);- try (OutputStream outputStream = newStream.createOutputStream(COSName.FLATE_DECODE)) {- new ContentStreamWriter(outputStream).writeTokens(tokens);- }- page.setContents(newStream);- log.debug("Token rewrite completed successfully");- return true;- } catch (IOException ex) {- log.debug("Failed to rewrite content stream: {}", ex.getMessage());- return false;- }- }-- private boolean rewriteShowText(- List<Object> tokens,- int tokenIndex,- PDFont font,- PdfJsonFont fontModel,- String expectedFontName,- TextElementCursor cursor,- boolean removeOnly)- throws IOException {- if (font == null) {- log.debug(- "rewriteShowText aborted: no active font for expected resource {}",- expectedFontName);- return false;- }- COSString cosString = (COSString) tokens.get(tokenIndex);- int glyphCount = countGlyphs(cosString, font);- log.trace(- "rewriteShowText consuming {} glyphs at cursor index {} for font {}",- glyphCount,- cursor.index,- expectedFontName);- List<PdfJsonTextElement> consumed = cursor.consume(expectedFontName, glyphCount);- if (consumed == null) {- log.debug(- "Failed to consume {} glyphs for font {} (cursor remaining {})",- glyphCount,- expectedFontName,- cursor.remaining());- return false;- }- if (removeOnly) {- tokens.set(tokenIndex, new COSString(new byte[0]));- return true;- }- MergedText replacement = mergeText(consumed);- try {- byte[] encoded =- encodeTextWithFont(- font, fontModel, replacement.text(), replacement.charCodes());- if (encoded == null) {- log.debug(- "Failed to map replacement text to glyphs for font {} (text='{}')",- expectedFontName,- replacement.text());- return false;- }- tokens.set(tokenIndex, new COSString(encoded));- return true;- } catch (IOException | IllegalArgumentException | UnsupportedOperationException ex) {- log.debug(- "Failed to encode replacement text with font {}: {}",- expectedFontName,- ex.getMessage());- return false;- }- }-- private boolean rewriteShowTextArray(- COSArray array,- PDFont font,- PdfJsonFont fontModel,- String expectedFontName,- TextElementCursor cursor,- boolean removeOnly)- throws IOException {- if (font == null) {- log.debug(- "rewriteShowTextArray aborted: no active font for expected resource {}",- expectedFontName);- return false;- }- for (int i = 0; i < array.size(); i++) {- COSBase element = array.get(i);- if (element instanceof COSString cosString) {- int glyphCount = countGlyphs(cosString, font);- List<PdfJsonTextElement> consumed = cursor.consume(expectedFontName, glyphCount);- if (consumed == null) {- log.debug(- "Failed to consume {} glyphs for font {} in TJ segment {} (cursor remaining {})",- glyphCount,- expectedFontName,- i,- cursor.remaining());- return false;- }- if (removeOnly) {- array.set(i, new COSString(new byte[0]));- continue;- }- MergedText replacement = mergeText(consumed);- try {- byte[] encoded =- encodeTextWithFont(- font, fontModel, replacement.text(), replacement.charCodes());- if (encoded == null) {- log.debug(- "Failed to map replacement text in TJ array for font {} segment {}",- expectedFontName,- i);- return false;- }- array.set(i, new COSString(encoded));- } catch (IOException- | IllegalArgumentException- | UnsupportedOperationException ex) {- log.debug(- "Failed to encode replacement text in TJ array for font {} segment {}: {}",- expectedFontName,- i,- ex.getMessage());- return false;- }- }- }- return true;- }-- private byte[] encodeTextWithFont(- PDFont font, PdfJsonFont fontModel, String text, List<Integer> rawCharCodes)- throws IOException {- boolean isType3Font = font instanceof PDType3Font;- boolean hasType3Metadata =- fontModel != null- && fontModel.getType3Glyphs() != null- && !fontModel.getType3Glyphs().isEmpty();-- // For normalized Type3 fonts (font is NOT Type3 but has Type3 metadata)- if (!isType3Font && hasType3Metadata) {- // If loaded as full font (not subset), use standard Unicode encoding- // Try standard encoding first - this works when the font has all glyphs- try {- byte[] encoded = font.encode(text);- // NOTE: Do NOT sanitize encoded bytes for normalized Type3 fonts- // Multi-byte encodings (UTF-16BE, CID fonts) have null bytes that are essential- // Removing them corrupts the byte boundaries and produces garbled text- log.debug(- "[TYPE3] Encoded text '{}' for normalized font {}: encoded={} bytes",- text.length() > 20 ? text.substring(0, 20) + "..." : text,- fontModel.getId(),- encoded != null ? encoded.length : 0);- if (encoded != null && encoded.length > 0) {- log.debug(- "[TYPE3] Successfully encoded text for normalized Type3 font {} using standard encoding",- fontModel.getId());- return encoded;- }- log.debug(- "[TYPE3] Standard encoding produced empty result for normalized Type3 font {}, falling through to Type3 mapping",- fontModel.getId());- } catch (IOException | IllegalArgumentException ex) {- log.debug(- "[TYPE3] Standard encoding failed for normalized Type3 font {}: {}",- fontModel.getId(),- ex.getMessage());- }- // If standard encoding failed, fall through to Type3 glyph mapping (for subset fonts)- // or return null to trigger fallback font- } else if (!isType3Font || fontModel == null) {- // For non-Type3 fonts without Type3 metadata, use standard encoding- try {- byte[] encoded = font.encode(text);- return sanitizeEncoded(encoded);- } catch (IllegalArgumentException ex) {- log.debug(- "[FONT-DEBUG] Font {} cannot encode text '{}': {}",- font.getName(),- text,- ex.getMessage());- // Return null to trigger fallback font mechanism- return null;- }- }-- // Type3 glyph mapping logic (for actual Type3 fonts AND normalized Type3 fonts)- List<PdfJsonFontType3Glyph> glyphs = fontModel.getType3Glyphs();- if (glyphs == null || glyphs.isEmpty()) {- return null;- }-- // For normalized Type3 fonts, DO NOT use rawCharCodes because:- // 1. They may be stale if text was edited- // 2. The subset font only has glyphs from the original PDF- // Instead, try Type3 glyph mapping and return null if glyphs are missing- // (null will trigger fallback font usage in the calling code)-- // Build Unicode to character code mapping from Type3 glyphs- Map<Integer, Integer> unicodeToCode = new HashMap<>();- for (PdfJsonFontType3Glyph glyph : glyphs) {- if (glyph == null) {- continue;- }- Integer unicode = glyph.getUnicode();- Integer charCode = glyph.getCharCode();- if (unicode == null || charCode == null) {- continue;- }- unicodeToCode.putIfAbsent(unicode, charCode);- }- ByteArrayOutputStream baos = new ByteArrayOutputStream();- boolean mappedAll = true;- for (int offset = 0; offset < text.length(); ) {- int codePoint = text.codePointAt(offset);- offset += Character.charCount(codePoint);- Integer charCode = unicodeToCode.get(codePoint);- if (charCode == null) {- log.debug(- "[TYPE3] Missing glyph mapping for code point U+{} in font {}",- Integer.toHexString(codePoint).toUpperCase(Locale.ROOT),- fontModel.getId());- mappedAll = false;- break;- }- if (charCode < 0 || charCode > 0xFF) {- log.debug(- "[TYPE3] Unsupported Type3 charCode {} for font {} (only 1-byte codes supported)",- charCode,- fontModel.getId());- mappedAll = false;- break;- }- baos.write(charCode);- }- if (mappedAll) {- return sanitizeEncoded(baos.toByteArray());- }- // Fallback to rawCharCodes for actual Type3 fonts if mapping failed- if (rawCharCodes != null && !rawCharCodes.isEmpty()) {- boolean valid = true;- ByteArrayOutputStream fallbackBytes = new ByteArrayOutputStream(rawCharCodes.size());- for (Integer code : rawCharCodes) {- if (code == null || code < 0 || code > 0xFF) {- valid = false;- break;- }- fallbackBytes.write(code);- }- if (valid) {- return fallbackBytes.toByteArray();- }- }- return null;- }-- private byte[] encodeType3CharCodes(List<Integer> charCodes) {- if (charCodes == null || charCodes.isEmpty()) {- return null;- }- ByteArrayOutputStream baos = new ByteArrayOutputStream(charCodes.size());- for (Integer code : charCodes) {- if (code == null || code < 0 || code > 0xFF) {- return null;- }- baos.write(code);- }- return baos.toByteArray();- }-- private byte[] sanitizeEncoded(byte[] encoded) {- if (encoded == null || encoded.length == 0) {- return new byte[0];- }- ByteArrayOutputStream baos = new ByteArrayOutputStream(encoded.length);- for (byte b : encoded) {- if (isStrippedControlByte(b)) {- continue;- }- baos.write(b);- }- byte[] sanitized = baos.toByteArray();- if (sanitized.length == 0) {- return sanitized;- }- return sanitized;- }-- private boolean isStrippedControlByte(byte value) {- if (value == 0) {- return true;- }- int unsigned = Byte.toUnsignedInt(value);- if (unsigned <= 0x1F) {- return !(unsigned == 0x09 || unsigned == 0x0A || unsigned == 0x0D);- }- return false;- }-- private int countGlyphs(COSString value, PDFont font) {- if (value == null) {- return 0;- }- if (font != null) {- try (ByteArrayInputStream inputStream = new ByteArrayInputStream(value.getBytes())) {- int count = countCodesProtected(inputStream, font::readCode);- if (count > 0) {- return count;- }- } catch (IOException ex) {- log.debug("Failed to decode glyphs: {}", ex.getMessage());- }- }- byte[] bytes = value.getBytes();- return Math.max(1, bytes.length);- }-- /**- * Functional accessor for {@link PDFont#readCode(InputStream)} so the bounded counting loop can- * be exercised in isolation without instantiating a {@link PDFont}.- */- @FunctionalInterface- interface CodeReader {- int readCode(InputStream stream) throws IOException;- }-- /**- * Count how many codes the supplied {@code reader} can extract from {@code inputStream}, with- * two safety nets that PDFBox's raw {@link PDFont#readCode(InputStream)} loop lacks:- *- * <ol>- * <li>Stop when the stream is empty (a corrupt CMap can otherwise loop forever returning- * successfully-matched zero-bytes from an exhausted {@link ByteArrayInputStream}).- * <li>Stop when a {@code readCode} call did not consume any bytes, even if it returned a- * non-{@code -1} value.- * </ol>- *- * <p>Both conditions were observed in the wild on round-tripped fallback fonts where the- * embedded ToUnicode CMap matched 0x00 sequences, hanging the JSON→PDF rebuild.- */- static int countCodesProtected(ByteArrayInputStream inputStream, CodeReader reader)- throws IOException {- int count = 0;- int previousAvailable = inputStream.available();- while (previousAvailable > 0) {- int code = reader.readCode(inputStream);- if (code == -1) {- break;- }- int currentAvailable = inputStream.available();- if (currentAvailable >= previousAvailable) {- // No progress made; break to avoid infinite loop on corrupt CMaps.- break;- }- count++;- previousAvailable = currentAvailable;- }- return count;- }-- private MergedText mergeText(List<PdfJsonTextElement> elements) {- StringBuilder builder = new StringBuilder();- List<Integer> combinedCodes = new ArrayList<>();- for (PdfJsonTextElement element : elements) {- builder.append(Objects.toString(element.getText(), ""));- int[] codes = element.getCharCodes();- if (codes != null && codes.length > 0) {- for (int code : codes) {- combinedCodes.add(code);- }- }- }- return new MergedText(builder.toString(), combinedCodes.isEmpty() ? null : combinedCodes);- }-- private record MergedText(String text, List<Integer> charCodes) {}-- private static class TextElementCursor {- private final List<PdfJsonTextElement> elements;- private int index = 0;-- TextElementCursor(List<PdfJsonTextElement> elements) {- this.elements = elements;- }-- boolean hasRemaining() {- return index < elements.size();- }-- int remaining() {- return Math.max(0, elements.size() - index);- }-- List<PdfJsonTextElement> consume(String expectedFontName, int glyphCount) {- if (glyphCount <= 0) {- return Collections.emptyList();- }- List<PdfJsonTextElement> consumed = new ArrayList<>();- int remaining = glyphCount;- while (remaining > 0 && index < elements.size()) {- PdfJsonTextElement element = elements.get(index);- if (!fontMatches(expectedFontName, element.getFontId())) {- log.debug(- "Cursor consume failed: font mismatch (expected={}, actual={}) at element {}",- expectedFontName,- element.getFontId(),- index);- return null;- }- consumed.add(element);- remaining -= countGlyphs(element);- index++;- }- if (remaining > 0) {- log.debug(- "Cursor consume failed: ran out of elements (remaining={}, currentIndex={}, total={})",- remaining,- index,- elements.size());- return null;- }- return consumed;- }-- private boolean fontMatches(String expected, String actual) {- if (expected == null || expected.isEmpty()) {- return true;- }- if (actual == null) {- return false;- }- return Objects.equals(expected, actual);- }-- private int countGlyphs(PdfJsonTextElement element) {- int[] codes = element.getCharCodes();- if (codes != null && codes.length > 0) {- return codes.length;- }- String text = element.getText();- if (text != null && !text.isEmpty()) {- return Math.max(1, text.codePointCount(0, text.length()));- }- return 1;- }- }-- private Map<String, PDFont> buildFontMap(- PDDocument document, List<PdfJsonFont> fonts, String jobId) throws IOException {- Map<String, PDFont> fontMap = new HashMap<>();- if (fonts != null) {- for (PdfJsonFont fontModel : fonts) {- if (FALLBACK_FONT_ID.equals(fontModel.getId())) {- continue;- }- PDFont loadedFont = createFontFromModel(document, fontModel, jobId);- if (loadedFont != null && fontModel.getId() != null) {- // Use null jobId for map keys - JSON->PDF doesn't need job-scoped lookups- // The jobId is only used internally for Type3 cache isolation- fontMap.put(- buildFontKey(null, fontModel.getPageNumber(), fontModel.getId()),- loadedFont);- }- }- }-- boolean fallbackPresent =- fonts != null && fonts.stream().anyMatch(f -> FALLBACK_FONT_ID.equals(f.getId()));- if (!fallbackPresent) {- PdfJsonFont fallbackModel = fallbackFontService.buildFallbackFontModel();- if (fonts != null) {- fonts.add(fallbackModel);- log.debug("Added fallback font definition to JSON font list");- }- PDFont fallbackFont = createFontFromModel(document, fallbackModel, jobId);- fontMap.put(buildFontKey(null, -1, FALLBACK_FONT_ID), fallbackFont);- } else if (!fontMap.containsKey(buildFontKey(null, -1, FALLBACK_FONT_ID))) {- PdfJsonFont fallbackModel =- fonts.stream()- .filter(f -> FALLBACK_FONT_ID.equals(f.getId()))- .findFirst()- .orElse(null);- if (fallbackModel == null) {- fallbackModel = fallbackFontService.buildFallbackFontModel();- fonts.add(fallbackModel);- }- PDFont fallbackFont = createFontFromModel(document, fallbackModel, jobId);- fontMap.put(buildFontKey(null, -1, FALLBACK_FONT_ID), fallbackFont);- }-- return fontMap;- }-- private PDFont createFontFromModel(PDDocument document, PdfJsonFont fontModel, String jobId)- throws IOException {- if (fontModel == null || fontModel.getId() == null) {- return null;- }-- if (FALLBACK_FONT_ID.equals(fontModel.getId())) {- return fallbackFontService.loadFallbackPdfFont(document);- }-- log.debug(- "[FONT-LOAD] Loading font {} (subtype={}, hasCosDictionary={}, hasProgram={}, hasPdfProgram={}, hasWebProgram={})",- fontModel.getId(),- fontModel.getSubtype(),- fontModel.getCosDictionary() != null,- fontModel.getProgram() != null && !fontModel.getProgram().isBlank(),- fontModel.getPdfProgram() != null && !fontModel.getPdfProgram().isBlank(),- fontModel.getWebProgram() != null && !fontModel.getWebProgram().isBlank());-- String originalFormat =- fontModel.getProgramFormat() != null- ? fontModel.getProgramFormat().toLowerCase(Locale.ROOT)- : null;-- String program = fontModel.getProgram();- String webProgram = fontModel.getWebProgram();- String pdfProgram = fontModel.getPdfProgram();- String webFormat =- fontModel.getWebProgramFormat() != null- ? fontModel.getWebProgramFormat().toLowerCase(Locale.ROOT)- : null;- String pdfFormat =- fontModel.getPdfProgramFormat() != null- ? fontModel.getPdfProgramFormat().toLowerCase(Locale.ROOT)- : null;-- List<FontByteSource> baseCandidates = new ArrayList<>();- List<FontByteSource> deferredWebCandidates = new ArrayList<>();-- boolean hasPdfProgram = pdfProgram != null && !pdfProgram.isBlank();- boolean hasWebProgram = webProgram != null && !webProgram.isBlank();-- if (hasPdfProgram) {- try {- byte[] bytes = Base64.getDecoder().decode(pdfProgram);- if (bytes.length > 0) {- baseCandidates.add(new FontByteSource(bytes, pdfFormat, "pdfProgram"));- }- } catch (IllegalArgumentException ex) {- log.warn(- "Failed to decode pdfProgram for {}: {}",- fontModel.getId(),- ex.getMessage());- }- }-- if (hasWebProgram) {- try {- byte[] bytes = Base64.getDecoder().decode(webProgram);- if (bytes.length > 0) {- // Prefer the converted blob when the original program is CFF/Type1C, because- // PDFBox expects TrueType/OpenType data during reconstruction.- boolean preferWeb =- originalFormat == null- || isCffFormat(originalFormat)- || "cidfonttype0c".equals(originalFormat);- FontByteSource source = new FontByteSource(bytes, webFormat, "webProgram");- if (preferWeb) {- baseCandidates.add(source);- } else {- // Keep the converted blob as a secondary option in case loading the- // original program fails: some PDFs mix Type1 metadata with actual CFF- // payloads that PDFBox cannot parse.- deferredWebCandidates.add(source);- }- }- } catch (IllegalArgumentException ex) {- log.warn(- "Failed to decode webProgram for {}: {}",- fontModel.getId(),- ex.getMessage());- }- }-- if (program != null && !program.isBlank()) {- try {- byte[] bytes = Base64.getDecoder().decode(program);- if (bytes.length > 0) {- // Original bytes should still be attempted. When we already preferred the- // converted blob, these will be appended as fallback.- baseCandidates.add(new FontByteSource(bytes, originalFormat, "program"));- }- } catch (IllegalArgumentException ex) {- log.warn(- "Failed to decode font program for {}: {}",- fontModel.getId(),- ex.getMessage());- }- }-- // If no candidates were added (e.g. both payloads missing/invalid) attempt to fall back to- // the converted program when it exists but we skipped it earlier.- if (baseCandidates.isEmpty() && hasWebProgram) {- try {- byte[] bytes = Base64.getDecoder().decode(webProgram);- if (bytes.length > 0) {- baseCandidates.add(new FontByteSource(bytes, webFormat, "webProgram"));- }- } catch (IllegalArgumentException ignored) {- // Already logged above when decoding failed the first time.- }- }-- baseCandidates.addAll(deferredWebCandidates);-- List<FontByteSource> conversionCandidates =- collectConversionCandidateSources(fontModel.getConversionCandidates());-- List<FontByteSource> orderedCandidates = new ArrayList<>();- if (!conversionCandidates.isEmpty()) {- orderedCandidates.addAll(conversionCandidates);- }- orderedCandidates.addAll(baseCandidates);-- boolean isType3Font =- fontModel.getSubtype() != null && "type3".equalsIgnoreCase(fontModel.getSubtype());- if (isType3Font) {- // Generate new UID with current jobId to prevent cache collisions across conversions- String type3CacheKey =- buildFontKey(jobId, fontModel.getPageNumber(), fontModel.getId());-- // Update fontModel UID so runtime lookups use the same key- fontModel.setUid(type3CacheKey);-- cacheType3NormalizedFont(- document, fontModel, orderedCandidates, originalFormat, type3CacheKey);- PDFont cachedNormalized = type3NormalizedFontCache.get(type3CacheKey);- if (cachedNormalized != null) {- log.debug("Using cached normalized font for Type3 {}", fontModel.getId());- return cachedNormalized;- }- PDFont restored = restoreFontFromDictionary(document, fontModel);- if (restored != null) {- return restored;- }- // Fall through to Standard14 fallback below if nothing else succeeded.- } else {- // For TrueType and Type0 fonts, prioritize cosDictionary restoration- // These fonts often use ToUnicode CMap which is preserved in the dictionary- String subtype = fontModel.getSubtype();- boolean preferDictionary =- subtype != null- && (subtype.equalsIgnoreCase("TrueType")- || subtype.equalsIgnoreCase("Type0"));-- if (preferDictionary) {- PDFont restored = restoreFontFromDictionary(document, fontModel);- if (restored != null) {- log.debug(- "Font {} restored from cosDictionary (preferred for subsetted {})",- fontModel.getId(),- subtype);- return restored;- }- // If dictionary restoration fails, fall back to font program bytes- log.debug(- "Font {} cosDictionary restoration failed, trying font program bytes",- fontModel.getId());- }-- PDFont loaded =- loadFirstAvailableFont(document, fontModel, orderedCandidates, originalFormat);- if (loaded != null) {- return loaded;- }-- // Try to restore from COS dictionary if font programs failed and we haven't tried yet- if (!preferDictionary) {- PDFont restored = restoreFontFromDictionary(document, fontModel);- if (restored != null) {- return restored;- }- }- }-- for (FontByteSource source : orderedCandidates) {- byte[] fontBytes = source.bytes();- String format = source.format();- String originLabel = source.originLabel();-- if (fontBytes == null || fontBytes.length == 0) {- continue;- }-- try {- PDFont font =- loadFontFromSource(- document, fontModel, source, originalFormat, false, false, false);- if (font != null) {- return font;- }- } catch (IOException ex) {- // loadFontFromSource already logged details.- }- }-- PDFont restored = restoreFontFromDictionary(document, fontModel);- if (restored != null) {- return restored;- }-- log.warn(- "Font {} has no usable program bytes (originalFormat: {}, hasWebProgram: {}, hasPdfProgram: {})",- fontModel.getId(),- originalFormat,- hasWebProgram,- hasPdfProgram);-- String standardName = fontModel.getStandard14Name();- if (standardName != null) {- try {- Standard14Fonts.FontName fontName = Standard14Fonts.getMappedFontName(standardName);- if (fontName != null) {- PDFont font = new PDType1Font(fontName);- applyAdditionalFontMetadata(document, font, fontModel);- return font;- }- log.warn(- "Standard 14 font mapping for {} returned null, using fallback",- standardName);- } catch (IllegalArgumentException ex) {- log.warn("Unknown Standard 14 font {}, using fallback", standardName);- }- }-- // Last resort: Fuzzy match baseName against Standard14 fonts- Standard14Fonts.FontName fuzzyMatch = fuzzyMatchStandard14(fontModel.getBaseName());- if (fuzzyMatch != null) {- log.debug(- "Fuzzy-matched font {} (baseName: {}) to Standard14 font {}",- fontModel.getId(),- fontModel.getBaseName(),- fuzzyMatch.getName());- PDFont font = new PDType1Font(fuzzyMatch);- applyAdditionalFontMetadata(document, font, fontModel);- return font;- }-- PDFont fallback = fallbackFontService.loadFallbackPdfFont(document);- applyAdditionalFontMetadata(document, fallback, fontModel);- return fallback;- }-- private void cacheType3NormalizedFont(- PDDocument document,- PdfJsonFont fontModel,- List<FontByteSource> candidates,- String originalFormat,- String cacheKey)- throws IOException {- if (cacheKey == null || candidates == null || candidates.isEmpty()) {- return;- }- if (type3NormalizedFontCache.containsKey(cacheKey)) {- return;- }- for (FontByteSource source : candidates) {- PDFont font =- loadFontFromSource(- document, fontModel, source, originalFormat, true, true, true);- if (font != null) {- type3NormalizedFontCache.put(cacheKey, font);- log.debug(- "Cached normalized font {} for Type3 {} (key: {})",- source.originLabel(),- fontModel.getId(),- cacheKey);- break;- }- }- }-- private PDFont loadFirstAvailableFont(- PDDocument document,- PdfJsonFont fontModel,- List<FontByteSource> candidates,- String originalFormat)- throws IOException {- for (FontByteSource source : candidates) {- PDFont font =- loadFontFromSource(- document, fontModel, source, originalFormat, false, false, false);- if (font != null) {- return font;- }- }- return null;- }-- private PDFont loadFontFromSource(- PDDocument document,- PdfJsonFont fontModel,- FontByteSource source,- String originalFormat,- boolean suppressWarn,- boolean skipMetadataLog,- boolean skipMetadata)- throws IOException {- if (source == null) {- return null;- }- byte[] fontBytes = source.bytes();- if (fontBytes == null || fontBytes.length == 0) {- return null;- }- String format = source.format();- String originLabel = source.originLabel();- try {- if (!skipMetadataLog) {- log.debug(- "[FONT-DEBUG] Attempting to load font {} using payload {} (format={}, size={} bytes)",- fontModel.getId(),- originLabel,- format,- fontBytes.length);- }- if (isType1Format(format)) {- try (InputStream stream = new ByteArrayInputStream(fontBytes)) {- PDFont font = new PDType1Font(document, stream);- if (!skipMetadata) {- applyAdditionalFontMetadata(document, font, fontModel);- }- log.debug(- "Successfully loaded Type1 font {} from {} bytes (format: {}, originalFormat: {})",- fontModel.getId(),- originLabel,- format,- originalFormat);- return font;- }- }- try (InputStream stream = new ByteArrayInputStream(fontBytes)) {- // For library fonts (Type3 normalized fonts), load WITHOUT subsetting- // so all glyphs are available for editing- boolean willBeSubset = !originLabel.contains("type3-library");- if (!willBeSubset) {- log.debug(- "[TYPE3-RUNTIME] Loading library font {} WITHOUT subsetting (full glyph set) from {}",- fontModel.getId(),- originLabel);- }- PDFont font = PDType0Font.load(document, stream, willBeSubset);- if (!skipMetadata) {- applyAdditionalFontMetadata(document, font, fontModel);- }- log.debug(- "Successfully loaded Type0 font {} from {} bytes (format: {}, originalFormat: {}, subset: {})",- fontModel.getId(),- originLabel,- format,- originalFormat,- willBeSubset);- return font;- }- } catch (IOException ex) {- if (suppressWarn) {- log.debug(- "Unable to load embedded font program for {} from {} (format: {}, originalFormat: {}): {}",- fontModel.getId(),- originLabel,- format,- originalFormat,- ex.getMessage());- } else {- log.warn(- "Unable to load embedded font program for {} from {} (format: {}, originalFormat: {}): {}",- fontModel.getId(),- originLabel,- format,- originalFormat,- ex.getMessage());- }- return null;- }- }-- private PDFont restoreFontFromDictionary(PDDocument document, PdfJsonFont fontModel)- throws IOException {- if (fontModel.getCosDictionary() == null) {- log.debug("[FONT-RESTORE] Font {} has no cosDictionary", fontModel.getId());- return null;- }-- // Deserialize the cosDictionary - cosMapper handles validation internally- COSBase restored;- try {- restored = cosMapper.deserializeCosValue(fontModel.getCosDictionary(), document);- } catch (Exception ex) {- log.debug(- "[FONT-RESTORE] Font {} cosDictionary deserialization failed: {}",- fontModel.getId(),- ex.getMessage());- return null;- }-- if (!(restored instanceof COSDictionary cosDictionary)) {- log.debug(- "[FONT-RESTORE] Font {} cosDictionary deserialized to {} instead of COSDictionary",- fontModel.getId(),- restored != null ? restored.getClass().getSimpleName() : "null");- return null;- }-- // Validate that dictionary contains required font keys- if (!cosDictionary.containsKey(org.apache.pdfbox.cos.COSName.TYPE)- || !cosDictionary.containsKey(org.apache.pdfbox.cos.COSName.SUBTYPE)) {- log.debug(- "[FONT-RESTORE] Font {} cosDictionary missing required Type or Subtype keys",- fontModel.getId());- return null;- }-- try {- PDFont font = PDFontFactory.createFont(cosDictionary);- if (font == null) {- log.debug(- "[FONT-RESTORE] Font {} PDFontFactory returned null for valid dictionary",- fontModel.getId());- return null;- }-- if (!font.isEmbedded()) {- log.debug(- "[FONT-RESTORE] Font {} restored from dictionary but is not embedded; rejecting to avoid system font substitution",- fontModel.getId());- return null;- }-- applyAdditionalFontMetadata(document, font, fontModel);- log.debug(- "[FONT-RESTORE] Successfully restored embedded font {} (subtype={}) from original dictionary",- fontModel.getId(),- font.getSubType());- return font;-- } catch (IOException ex) {- log.debug(- "[FONT-RESTORE] Failed to restore font {} from dictionary ({}): {}",- fontModel.getId(),- fontModel.getSubtype(),- ex.getMessage());- return null;- } catch (Exception ex) {- log.error(- "[FONT-RESTORE] Unexpected error restoring font {} from dictionary: {}",- fontModel.getId(),- ex.getMessage(),- ex);- return null;- }- }-- private boolean isType1Format(String format) {- if (format == null) {- return false;- }- return "type1".equals(format) || format.endsWith("pfb");- }-- private boolean isCffFormat(String format) {- if (format == null) {- return false;- }- String normalized = format.toLowerCase(Locale.ROOT);- return normalized.contains("type1c")- || normalized.contains("cidfonttype0c")- || "cff".equals(normalized);- }-- private void applyAdditionalFontMetadata(- PDDocument document, PDFont font, PdfJsonFont fontModel) throws IOException {- if (fontModel.getToUnicode() != null && !fontModel.getToUnicode().isBlank()) {- byte[] bytes = Base64.getDecoder().decode(fontModel.getToUnicode());- PDStream toUnicodeStream = new PDStream(document);- try (OutputStream outputStream = toUnicodeStream.createOutputStream()) {- outputStream.write(bytes);- }- font.getCOSObject().setItem(COSName.TO_UNICODE, toUnicodeStream.getCOSObject());- }-- PdfJsonFontCidSystemInfo cidInfo = fontModel.getCidSystemInfo();- if (cidInfo != null) {- COSDictionary cidDictionary = new COSDictionary();- if (cidInfo.getRegistry() != null) {- cidDictionary.setString(COSName.REGISTRY, cidInfo.getRegistry());- }- if (cidInfo.getOrdering() != null) {- cidDictionary.setString(COSName.ORDERING, cidInfo.getOrdering());- }- if (cidInfo.getSupplement() != null) {- cidDictionary.setInt(COSName.SUPPLEMENT, cidInfo.getSupplement());- }- font.getCOSObject().setItem(COSName.CIDSYSTEMINFO, cidDictionary);- }- }-- private void applyTextMatrix(PDPageContentStream contentStream, PdfJsonTextElement element)- throws IOException {- float[] matrix = element.getTextMatrix();- if (matrix != null && matrix.length == 6) {- float fontScale = resolveFontMatrixSize(element);- float a = matrix[0];- float b = matrix[1];- float c = matrix[2];- float d = matrix[3];- float e = matrix[4];- float f = matrix[5];-- if (fontScale != 0f) {- a /= fontScale;- b /= fontScale;- c /= fontScale;- d /= fontScale;- }-- contentStream.setTextMatrix(new Matrix(a, b, c, d, e, f));- return;- }- float x = safeFloat(element.getX(), 0f);- float y = safeFloat(element.getY(), 0f);- contentStream.setTextMatrix(new Matrix(1, 0, 0, 1, x, y));- }-- private float resolveFontMatrixSize(PdfJsonTextElement element) {- Float fromElement = element.getFontMatrixSize();- if (fromElement != null && fromElement > 0f) {- return fromElement;- }- float[] matrix = element.getTextMatrix();- if (matrix != null && matrix.length >= 4) {- float a = matrix[0];- float b = matrix[1];- float c = matrix[2];- float d = matrix[3];- float verticalScale = (float) Math.hypot(b, d);- if (verticalScale > 0f) {- return verticalScale;- }- float horizontalScale = (float) Math.hypot(a, c);- if (horizontalScale > 0f) {- return horizontalScale;- }- }- return safeFloat(element.getFontSize(), 12f);- }-- private void applyRenderingMode(PDPageContentStream contentStream, Integer renderingMode)- throws IOException {- if (renderingMode == null) {- return;- }- RenderingMode mode = toRenderingMode(renderingMode);- if (mode == null) {- log.debug("Ignoring unsupported rendering mode {}", renderingMode);- return;- }- try {- contentStream.setRenderingMode(mode);- } catch (IllegalArgumentException ex) {- log.debug("Failed to apply rendering mode {}: {}", renderingMode, ex.getMessage());- }- }-- private float safeFloat(Float value, float defaultValue) {- if (value == null || Float.isNaN(value) || Float.isInfinite(value)) {- return defaultValue;- }- return value;- }-- private String formatCalendar(Calendar calendar) {- if (calendar == null) {- return null;- }- return calendar.toInstant().toString();- }-- private Optional<Instant> parseInstant(String value) {- try {- return Optional.of(Instant.parse(value));- } catch (DateTimeParseException ex) {- log.warn("Failed to parse instant '{}': {}", value, ex.getMessage());- return Optional.empty();- }- }-- private Calendar toCalendar(Instant instant) {- Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));- calendar.setTimeInMillis(instant.toEpochMilli());- return calendar;- }-- private class ImageCollectingEngine extends PDFGraphicsStreamEngine {-- private final int pageNumber;- private final Map<Integer, List<PdfJsonImageElement>> imagesByPage;- private final Map<COSBase, EncodedImage> imageCache;-- private COSName currentXObjectName;- private int imageCounter = 0;-- protected ImageCollectingEngine(- PDPage page,- int pageNumber,- Map<Integer, List<PdfJsonImageElement>> imagesByPage,- Map<COSBase, EncodedImage> imageCache)- throws IOException {- super(page);- this.pageNumber = pageNumber;- this.imagesByPage = imagesByPage;- this.imageCache = imageCache;- }-- @Override- public void processPage(PDPage page) throws IOException {- super.processPage(page);- }-- @Override- public void drawImage(PDImage pdImage) throws IOException {- EncodedImage encoded = getOrEncodeImage(pdImage);- if (encoded == null) {- return;- }- Matrix ctm = getGraphicsState().getCurrentTransformationMatrix();- Bounds bounds = computeBounds(ctm);- float[] matrixValues = toMatrixValues(ctm);-- PdfJsonImageElement element =- PdfJsonImageElement.builder()- .id(UUID.randomUUID().toString())- .objectName(- currentXObjectName != null- ? currentXObjectName.getName()- : null)- .inlineImage(!(pdImage instanceof PDImageXObject))- .nativeWidth(pdImage.getWidth())- .nativeHeight(pdImage.getHeight())- .x(bounds.left)- .y(bounds.bottom)- .width(bounds.width())- .height(bounds.height())- .left(bounds.left)- .right(bounds.right)- .top(bounds.top)- .bottom(bounds.bottom)- .transform(matrixValues)- .zOrder(-1_000_000 + imageCounter)- .imageData(encoded.base64())- .imageFormat(encoded.format())- .build();- imageCounter++;- imagesByPage.computeIfAbsent(pageNumber, key -> new ArrayList<>()).add(element);- }-- @Override- public void appendRectangle(Point2D p0, Point2D p1, Point2D p2, Point2D p3)- throws IOException {- // Not needed for image extraction- }-- @Override- public void clip(int windingRule) throws IOException {- // Not needed for image extraction- }-- @Override- public void moveTo(float x, float y) throws IOException {- // Not needed for image extraction- }-- @Override- public void lineTo(float x, float y) throws IOException {- // Not needed for image extraction- }-- @Override- public void curveTo(float x1, float y1, float x2, float y2, float x3, float y3)- throws IOException {- // Not needed for image extraction- }-- @Override- public Point2D getCurrentPoint() throws IOException {- return new Point2D.Float();- }-- @Override- public void closePath() throws IOException {- // Not needed for image extraction- }-- @Override- public void endPath() throws IOException {- // Not needed for image extraction- }-- @Override- public void shadingFill(COSName shadingName) throws IOException {- // Not needed for image extraction- }-- @Override- public void fillAndStrokePath(int windingRule) throws IOException {- // Not needed for image extraction- }-- @Override- public void fillPath(int windingRule) throws IOException {- // Not needed for image extraction- }-- @Override- public void strokePath() throws IOException {- // Not needed for image extraction- }-- @Override- protected void processOperator(Operator operator, List<COSBase> operands)- throws IOException {- if (OperatorName.DRAW_OBJECT.equals(operator.getName())- && !operands.isEmpty()- && operands.getFirst() instanceof COSName name) {- currentXObjectName = name;- }- super.processOperator(operator, operands);- currentXObjectName = null;- }-- private EncodedImage getOrEncodeImage(PDImage pdImage) {- if (pdImage == null) {- return null;- }-- if (pdImage instanceof PDImageXObject xObject) {- if (xObject.isStencil()) {- return encodeImage(pdImage);- }- COSBase key = xObject.getCOSObject();- EncodedImage cached = imageCache.get(key);- if (cached != null) {- return cached;- }- EncodedImage encoded = encodeImage(pdImage);- if (encoded != null) {- imageCache.put(key, encoded);- }- return encoded;- }-- return encodeImage(pdImage);- }-- private Bounds computeBounds(Matrix ctm) {- AffineTransform transform = ctm.createAffineTransform();- Point2D.Float p0 = new Point2D.Float(0, 0);- Point2D.Float p1 = new Point2D.Float(1, 0);- Point2D.Float p2 = new Point2D.Float(0, 1);- Point2D.Float p3 = new Point2D.Float(1, 1);- transform.transform(p0, p0);- transform.transform(p1, p1);- transform.transform(p2, p2);- transform.transform(p3, p3);-- float minX = Math.min(Math.min(p0.x, p1.x), Math.min(p2.x, p3.x));- float maxX = Math.max(Math.max(p0.x, p1.x), Math.max(p2.x, p3.x));- float minY = Math.min(Math.min(p0.y, p1.y), Math.min(p2.y, p3.y));- float maxY = Math.max(Math.max(p0.y, p1.y), Math.max(p2.y, p3.y));-- if (!Float.isFinite(minX) || !Float.isFinite(minY)) {- return new Bounds(0f, 0f, 0f, 0f);- }- return new Bounds(minX, maxX, minY, maxY);- }- }-- private record Bounds(float left, float right, float bottom, float top) {- float width() {- return Math.max(0f, right - left);- }-- float height() {- return Math.max(0f, top - bottom);- }- }-- private enum DrawableType {- TEXT,- IMAGE- }-- private record DrawableElement(- DrawableType type,- PdfJsonTextElement textElement,- PdfJsonImageElement imageElement,- int zOrder,- int sequence) {}-- private record EncodedImage(String base64, String format) {}-- private float[] toMatrixValues(Matrix matrix) {- return new float[] {- matrix.getValue(0, 0),- matrix.getValue(0, 1),- matrix.getValue(1, 0),- matrix.getValue(1, 1),- matrix.getValue(2, 0),- matrix.getValue(2, 1)- };- }-- private EncodedImage encodeImage(PDImage image) {- try {- BufferedImage bufferedImage = image.getImage();- if (bufferedImage == null) {- return null;- }- String format = resolveImageFormat(image);- if (format == null || format.isBlank()) {- format = "png";- }- ByteArrayOutputStream baos = new ByteArrayOutputStream();- boolean written = ImageIO.write(bufferedImage, format, baos);- if (!written) {- if (!"png".equalsIgnoreCase(format)) {- baos.reset();- if (!ImageIO.write(bufferedImage, "png", baos)) {- return null;- }- format = "png";- } else {- return null;- }- }- return new EncodedImage(Base64.getEncoder().encodeToString(baos.toByteArray()), format);- } catch (IOException ex) {- log.debug("Failed to encode image: {}", ex.getMessage());- return null;- }- }-- private String resolveImageFormat(PDImage image) {- if (image instanceof PDImageXObject xObject) {- String suffix = xObject.getSuffix();- if (suffix != null && !suffix.isBlank()) {- return suffix.toLowerCase(Locale.ROOT);- }- }- return "png";- }-- private List<DrawableElement> mergeDrawables(- List<PdfJsonTextElement> textElements, List<PdfJsonImageElement> imageElements) {- List<DrawableElement> drawables = new ArrayList<>();- int sequence = 0;-- if (imageElements != null) {- int imageIndex = 0;- for (PdfJsonImageElement imageElement : imageElements) {- if (imageElement == null) {- continue;- }- int order =- imageElement.getZOrder() != null- ? imageElement.getZOrder()- : Integer.MIN_VALUE / 2 + imageIndex;- drawables.add(- new DrawableElement(- DrawableType.IMAGE, null, imageElement, order, sequence++));- imageIndex++;- }- }-- if (textElements != null) {- int textIndex = 0;- for (PdfJsonTextElement textElement : textElements) {- if (textElement == null) {- continue;- }- int order =- textElement.getZOrder() != null- ? textElement.getZOrder()- : 1_000_000 + textIndex;- drawables.add(- new DrawableElement(- DrawableType.TEXT, textElement, null, order, sequence++));- textIndex++;- }- }-- drawables.sort(- Comparator.comparingInt(DrawableElement::zOrder)- .thenComparingInt(DrawableElement::sequence));- return drawables;- }-- private void drawImageElement(- PDPageContentStream contentStream,- PDDocument document,- PdfJsonImageElement element,- Map<String, PDImageXObject> cache)- throws IOException {- if (element == null || element.getImageData() == null || element.getImageData().isBlank()) {- return;- }-- String cacheKey =- element.getId() != null && !element.getId().isBlank()- ? element.getId()- : Integer.toHexString(System.identityHashCode(element));- PDImageXObject image = cache.get(cacheKey);- if (image == null) {- image = createImageXObject(document, element);- if (image == null) {- return;- }- cache.put(cacheKey, image);- }-- float[] transform = element.getTransform();- if (transform != null && transform.length == 6) {- Matrix matrix =- new Matrix(- safeFloat(transform[0], 1f),- safeFloat(transform[1], 0f),- safeFloat(transform[2], 0f),- safeFloat(transform[3], 1f),- safeFloat(transform[4], 0f),- safeFloat(transform[5], 0f));- contentStream.drawImage(image, matrix);- return;- }-- float width = safeFloat(element.getWidth(), fallbackWidth(element));- float height = safeFloat(element.getHeight(), fallbackHeight(element));- if (width <= 0f) {- width = Math.max(1f, fallbackWidth(element));- }- if (height <= 0f) {- height = Math.max(1f, fallbackHeight(element));- }- float left = resolveLeft(element, width);- float bottom = resolveBottom(element, height);-- contentStream.drawImage(image, left, bottom, width, height);- }-- private PDImageXObject createImageXObject(PDDocument document, PdfJsonImageElement element)- throws IOException {- byte[] data;- try {- data = Base64.getDecoder().decode(element.getImageData());- } catch (IllegalArgumentException ex) {- log.debug("Failed to decode image element: {}", ex.getMessage());- return null;- }- String name = element.getId() != null ? element.getId() : UUID.randomUUID().toString();- return PDImageXObject.createFromByteArray(document, data, name);- }-- private float fallbackWidth(PdfJsonImageElement element) {- if (element.getRight() != null && element.getLeft() != null) {- return Math.max(0f, element.getRight() - element.getLeft());- }- if (element.getNativeWidth() != null) {- return element.getNativeWidth();- }- return 1f;- }-- private float resolveLeft(PdfJsonImageElement element, float width) {- if (element.getLeft() != null) {- return element.getLeft();- }- if (element.getX() != null) {- return element.getX();- }- if (element.getRight() != null) {- return element.getRight() - width;- }- return 0f;- }-- private float resolveBottom(PdfJsonImageElement element, float height) {- if (element.getBottom() != null) {- return element.getBottom();- }- if (element.getY() != null) {- return element.getY();- }- if (element.getTop() != null) {- return element.getTop() - height;- }- return 0f;- }-- private float fallbackHeight(PdfJsonImageElement element) {- if (element.getTop() != null && element.getBottom() != null) {- return Math.max(0f, element.getTop() - element.getBottom());- }- if (element.getNativeHeight() != null) {- return element.getNativeHeight();- }- return 1f;- }-- private class TextCollectingStripper extends PDFTextStripper {-- private final PDDocument document;- private final Map<String, PdfJsonFont> fonts;- private final Map<Integer, List<PdfJsonTextElement>> textByPage;- private final Map<Integer, Map<PDFont, String>> pageFontResources;- private final Map<COSBase, FontModelCacheEntry> fontCache;- private final String jobId;-- private int currentPage = 1;- private Map<PDFont, String> currentFontResources = Collections.emptyMap();- private int currentZOrderCounter;-- TextCollectingStripper(- PDDocument document,- Map<String, PdfJsonFont> fonts,- Map<Integer, List<PdfJsonTextElement>> textByPage,- Map<Integer, Map<PDFont, String>> pageFontResources,- Map<COSBase, FontModelCacheEntry> fontCache,- String jobId)- throws IOException {- this.document = document;- this.fonts = fonts;- this.textByPage = textByPage;- this.pageFontResources = pageFontResources;- this.fontCache = fontCache != null ? fontCache : new IdentityHashMap<>();- this.jobId = jobId;- }-- @Override- protected void startPage(PDPage page) throws IOException {- super.startPage(page);- currentPage = getCurrentPageNo();- currentFontResources =- pageFontResources.getOrDefault(currentPage, Collections.emptyMap());- currentZOrderCounter = 0;- }-- @Override- protected void writeString(String text, List<TextPosition> textPositions)- throws IOException {- if (textPositions == null || textPositions.isEmpty()) {- return;- }- List<PdfJsonTextElement> pageElements =- textByPage.computeIfAbsent(currentPage, key -> new ArrayList<>());-- TextRunAccumulator accumulator = null;- for (TextPosition position : textPositions) {- PDFont font = position.getFont();- String fontId = registerFont(font);- PdfJsonTextElement element = createTextElement(position, fontId, font);-- if (accumulator == null) {- accumulator = new TextRunAccumulator(element, position);- } else if (!accumulator.canAppend(element, position)) {- PdfJsonTextElement built = accumulator.build();- built.setZOrder(1_000_000 + currentZOrderCounter++);- pageElements.add(built);- accumulator = new TextRunAccumulator(element, position);- } else {- accumulator.append(element, position);- }- }-- if (accumulator != null) {- PdfJsonTextElement built = accumulator.build();- built.setZOrder(1_000_000 + currentZOrderCounter++);- pageElements.add(built);- }- }-- private PdfJsonTextElement createTextElement(- TextPosition position, String fontId, PDFont pdfont) throws IOException {- PdfJsonTextElement element = new PdfJsonTextElement();- element.setText(position.getUnicode());- element.setFontId(fontId);- element.setFontSize(position.getFontSizeInPt());- element.setX(position.getXDirAdj());- element.setY(position.getYDirAdj());- element.setWidth(position.getWidthDirAdj());- element.setHeight(position.getHeightDir());- element.setTextMatrix(extractMatrix(position));- element.setFontMatrixSize(computeFontMatrixSize(element.getTextMatrix()));- element.setSpaceWidth(position.getWidthOfSpace());- if (pdfont instanceof PDType3Font) {- int[] codes = position.getCharacterCodes();- if (codes != null && codes.length > 0) {- int count = 0;- for (int code : codes) {- if (code >= 0) count++;- }- if (count > 0) {- int[] filtered = new int[count];- int idx = 0;- for (int code : codes) {- if (code >= 0) filtered[idx++] = code;- }- element.setCharCodes(filtered);- }- }- }-- PDGraphicsState graphicsState = getGraphicsState();- if (graphicsState != null) {- PDTextState textState = graphicsState.getTextState();- if (textState != null) {- element.setCharacterSpacing(textState.getCharacterSpacing());- element.setWordSpacing(textState.getWordSpacing());- element.setHorizontalScaling(textState.getHorizontalScaling());- element.setLeading(textState.getLeading());- element.setRise(textState.getRise());- if (textState.getRenderingMode() != null) {- element.setRenderingMode(textState.getRenderingMode().intValue());- }- }- element.setFillColor(toTextColor(graphicsState.getNonStrokingColor()));- element.setStrokeColor(toTextColor(graphicsState.getStrokingColor()));- }- return element;- }-- private void compactTextElement(PdfJsonTextElement element) {- if (element == null) {- return;- }-- float[] matrix = element.getTextMatrix();- if (matrix != null) {- if (matrix.length == 0) {- element.setTextMatrix(null);- } else if (matrix.length == 6) {- element.setX(null);- element.setY(null);- }- }-- if (isZero(element.getCharacterSpacing())) {- element.setCharacterSpacing(null);- }- if (isZero(element.getWordSpacing())) {- element.setWordSpacing(null);- }- if (isZero(element.getLeading())) {- element.setLeading(null);- }- if (isZero(element.getRise())) {- element.setRise(null);- }- if (element.getHorizontalScaling() != null- && Math.abs(element.getHorizontalScaling() - 100f) < FLOAT_EPSILON) {- element.setHorizontalScaling(null);- }- if (element.getRenderingMode() != null && element.getRenderingMode() == 0) {- element.setRenderingMode(null);- }- if (isDefaultBlack(element.getFillColor())) {- element.setFillColor(null);- }- if (isDefaultBlack(element.getStrokeColor())) {- element.setStrokeColor(null);- }- }-- private boolean isZero(Float value) {- return value != null && Math.abs(value) < FLOAT_EPSILON;- }-- private boolean isDefaultBlack(PdfJsonTextColor color) {- if (color == null || color.getComponents() == null) {- return true;- }- float[] components = color.getComponents();- if (components.length == 0) {- return true;- }- String space = color.getColorSpace();- if (space == null || "DeviceRGB".equals(space)) {- if (components.length < 3) {- return false;- }- return Math.abs(components[0]) < FLOAT_EPSILON- && Math.abs(components[1]) < FLOAT_EPSILON- && Math.abs(components[2]) < FLOAT_EPSILON;- }- if ("DeviceGray".equals(space)) {- return Math.abs(components[0]) < FLOAT_EPSILON;- }- return false;- }-- private Float baselineFrom(PdfJsonTextElement element) {- float[] matrix = element.getTextMatrix();- if (matrix != null && matrix.length >= 6) {- return matrix[5];- }- return element.getY();- }-- private TextStyleKey buildStyleKey(PdfJsonTextElement element) {- return new TextStyleKey(- element.getFontId(),- element.getFontSize(),- element.getFontMatrixSize(),- element.getCharacterSpacing(),- element.getWordSpacing(),- element.getHorizontalScaling(),- element.getLeading(),- element.getRise(),- element.getFillColor(),- element.getStrokeColor(),- element.getRenderingMode(),- element.getSpaceWidth());- }-- private class TextRunAccumulator {- private final PdfJsonTextElement baseElement;- private final TextStyleKey styleKey;- private final float orientationA;- private final float orientationB;- private final float orientationC;- private final float orientationD;- private final Float baseline;- private final float[] baseMatrix;- private final float startXCoord;- private final float startYCoord;- private final StringBuilder textBuilder = new StringBuilder();- private int[] charCodeBuf = new int[16];- private int charCodeLen = 0;- private float totalWidth;- private float maxHeight;- private float endXCoord;-- TextRunAccumulator(PdfJsonTextElement element, TextPosition position) {- this.baseElement = element;- this.styleKey = buildStyleKey(element);- float[] tm = element.getTextMatrix();- this.baseMatrix = tm != null ? tm.clone() : null;- if (baseMatrix != null && baseMatrix.length >= 6) {- orientationA = baseMatrix[0];- orientationB = baseMatrix[1];- orientationC = baseMatrix[2];- orientationD = baseMatrix[3];- startXCoord = baseMatrix[4];- startYCoord = baseMatrix[5];- } else {- orientationA = 1f;- orientationB = 0f;- orientationC = 0f;- orientationD = 1f;- startXCoord = element.getX() != null ? element.getX() : 0f;- startYCoord = element.getY() != null ? element.getY() : 0f;- }- this.baseline = baselineFrom(element);- this.totalWidth = element.getWidth() != null ? element.getWidth() : 0f;- this.maxHeight = element.getHeight() != null ? element.getHeight() : 0f;- this.endXCoord = position.getXDirAdj() + position.getWidthDirAdj();- this.textBuilder.append(element.getText());- appendCharCodes(element.getCharCodes());- }-- boolean canAppend(PdfJsonTextElement element, TextPosition position) {- if (!styleKey.equals(buildStyleKey(element))) {- return false;- }- float[] matrix = element.getTextMatrix();- float a = 1f;- float b = 0f;- float c = 0f;- float d = 1f;- if (matrix != null && matrix.length >= 4) {- a = matrix[0];- b = matrix[1];- c = matrix[2];- d = matrix[3];- }- if (Math.abs(a - orientationA) > ORIENTATION_TOLERANCE- || Math.abs(b - orientationB) > ORIENTATION_TOLERANCE- || Math.abs(c - orientationC) > ORIENTATION_TOLERANCE- || Math.abs(d - orientationD) > ORIENTATION_TOLERANCE) {- return false;- }-- Float otherBaseline = baselineFrom(element);- if (baseline != null && otherBaseline != null) {- if (Math.abs(otherBaseline - baseline) > BASELINE_TOLERANCE) {- return false;- }- } else if (baseline != null || otherBaseline != null) {- return false;- }-- return true;- }-- void append(PdfJsonTextElement element, TextPosition position) {- textBuilder.append(element.getText());- float width =- element.getWidth() != null ? element.getWidth() : position.getWidthDirAdj();- totalWidth += width;- float height =- element.getHeight() != null ? element.getHeight() : position.getHeightDir();- if (height > maxHeight) {- maxHeight = height;- }- endXCoord = position.getXDirAdj() + position.getWidthDirAdj();- appendCharCodes(element.getCharCodes());- }-- private void appendCharCodes(int[] codes) {- if (codes == null) return;- int needed = charCodeLen + codes.length;- if (needed > charCodeBuf.length) {- charCodeBuf =- java.util.Arrays.copyOf(- charCodeBuf, Math.max(needed, charCodeBuf.length * 2));- }- System.arraycopy(codes, 0, charCodeBuf, charCodeLen, codes.length);- charCodeLen += codes.length;- }-- PdfJsonTextElement build() {- PdfJsonTextElement result = baseElement;- result.setText(textBuilder.toString());- float widthCandidate = endXCoord - startXCoord;- if (widthCandidate > totalWidth) {- totalWidth = widthCandidate;- }- result.setWidth(totalWidth);- result.setHeight(maxHeight);- if (baseMatrix != null && baseMatrix.length == 6) {- float[] matrix =- new float[] {- orientationA, orientationB,- orientationC, orientationD,- startXCoord, startYCoord- };- result.setTextMatrix(matrix);- result.setX(null);- result.setY(null);- }- if (charCodeLen == 0) {- result.setCharCodes(null);- } else {- result.setCharCodes(java.util.Arrays.copyOf(charCodeBuf, charCodeLen));- }- compactTextElement(result);- return result;- }- }-- private record TextStyleKey(- String fontId,- Float fontSize,- Float fontMatrixSize,- Float characterSpacing,- Float wordSpacing,- Float horizontalScaling,- Float leading,- Float rise,- PdfJsonTextColor fillColor,- PdfJsonTextColor strokeColor,- Integer renderingMode,- Float spaceWidth) {}-- private float[] extractMatrix(TextPosition position) {- return new float[] {- position.getTextMatrix().getValue(0, 0),- position.getTextMatrix().getValue(0, 1),- position.getTextMatrix().getValue(1, 0),- position.getTextMatrix().getValue(1, 1),- position.getTextMatrix().getValue(2, 0),- position.getTextMatrix().getValue(2, 1)- };- }-- private Float computeFontMatrixSize(float[] matrix) {- if (matrix == null || matrix.length < 4) {- return null;- }- float a = matrix[0];- float b = matrix[1];- float c = matrix[2];- float d = matrix[3];- float scaleX = (float) Math.hypot(a, c);- float scaleY = (float) Math.hypot(b, d);- float scale = Math.max(scaleX, scaleY);- return scale > 0 ? scale : null;- }-- private String registerFont(PDFont font) throws IOException {- String fontId = currentFontResources.get(font);- if (fontId == null || fontId.isBlank()) {- fontId = font.getName();- }- String key = buildFontKey(jobId, currentPage, fontId);- if (!fonts.containsKey(key)) {- fonts.put(- key, buildFontModel(document, font, fontId, currentPage, fontCache, jobId));- }- return fontId;- }-- private PdfJsonTextColor toTextColor(PDColor color) {- if (color == null) {- return null;- }- PDColorSpace colorSpace = color.getColorSpace();- if (colorSpace == null) {- log.debug("[ColorCapture] No color space for PDColor {}", color);- return null;- }- float[] components = color.getComponents();- String colorSpaceName = colorSpace.getName();- float[] effective = components;- try {- float[] rgb = colorSpace.toRGB(components);- if (rgb != null && rgb.length >= 3) {- effective = rgb;- colorSpaceName = COSName.DEVICERGB.getName();- }- } catch (IOException ex) {- log.debug(- "[ColorCapture] Failed to convert color space {} to RGB: {}",- colorSpaceName,- ex.getMessage());- }- return PdfJsonTextColor.builder()- .colorSpace(colorSpaceName)- .components(effective)- .build();- }-- private String sanitizeForLog(String value) {- if (value == null) {- return "null";- }- return value.replace("\n", "\\n").replace("\r", "\\r");- }-- private String describeColor(PdfJsonTextColor color) {- if (color == null || color.getComponents() == null) {- return "null";- }- return color.getColorSpace() + "=" + color.getComponents();- }- }-- private RenderingMode toRenderingMode(Integer renderingMode) {- if (renderingMode == null) {- return null;- }- switch (renderingMode) {- case 0:- return RenderingMode.FILL;- case 1:- return RenderingMode.STROKE;- case 2:- return RenderingMode.FILL_STROKE;- case 3:- return RenderingMode.NEITHER;- case 4:- return RenderingMode.FILL_CLIP;- case 5:- return RenderingMode.STROKE_CLIP;- case 6:- return RenderingMode.FILL_STROKE_CLIP;- case 7:- return RenderingMode.NEITHER_CLIP;- default:- return null;- }- }-- /**- * Get the job ID from the current request context- *- * @return The job ID, or null if not in an async job context- */- private String getJobIdFromRequest() {- // First check ThreadLocal (for async jobs)- String jobId = stirling.software.common.util.JobContext.getJobId();- if (jobId != null) {- log.debug("Retrieved jobId from JobContext: {}", jobId);- return jobId;- }-- // Fallback to request attribute (for sync jobs)- try {- org.springframework.web.context.request.RequestAttributes attrs =- org.springframework.web.context.request.RequestContextHolder- .getRequestAttributes();- if (attrs instanceof org.springframework.web.context.request.ServletRequestAttributes) {- jakarta.servlet.http.HttpServletRequest request =- ((org.springframework.web.context.request.ServletRequestAttributes) attrs)- .getRequest();- jobId = (String) request.getAttribute("jobId");- if (jobId != null) {- log.debug("Retrieved jobId from request attribute: {}", jobId);- return jobId;- }- }- } catch (Exception e) {- log.debug("Could not retrieve job ID from request context: {}", e.getMessage());- }- return null;- }-- /**- * Report progress to TaskManager for async jobs- *- * @param jobId The job ID- * @param progress The progress update- */- private void reportProgressToTaskManager(String jobId, PdfJsonConversionProgress progress) {- try {- log.debug(- "Reporting progress for job {}: {}% - {}",- jobId, progress.getPercent(), progress.getStage());- // Add progress note to job- String note;- if (progress.getCurrent() != null && progress.getTotal() != null) {- note =- String.format(- "[%d%%] %s: %s (%d/%d)",- progress.getPercent(),- progress.getStage(),- progress.getMessage(),- progress.getCurrent(),- progress.getTotal());- } else {- note =- String.format(- "[%d%%] %s: %s",- progress.getPercent(), progress.getStage(), progress.getMessage());- }- boolean added = taskManager.addNote(jobId, note);- if (!added) {- log.warn("Failed to add note - job {} not found in TaskManager", jobId);- } else {- log.debug("Successfully added progress note for job {}: {}", jobId, note);- }- } catch (Exception e) {- log.error("Exception reporting progress for job {}: {}", jobId, e.getMessage(), e);- }- }-- // ========================================================================- // Lazy Page Loading Support- // ========================================================================-- /**- * Stores PDF bytes for lazy page loading. Each page is extracted on-demand by re-loading the- * PDF from bytes.- */- private static class CachedPdfDocument {- private final byte[] pdfBytes;- private final TempFile pdfTempFile;- private final long pdfSize;- private final PdfJsonDocumentMetadata metadata;- private final Map<String, PdfJsonFont> fonts; // Font map with UIDs for consistency- private final Map<Integer, Map<PDFont, String>> pageFontResources; // Page font resources- private final long timestamp;-- public CachedPdfDocument(- byte[] pdfBytes,- TempFile pdfTempFile,- long pdfSize,- PdfJsonDocumentMetadata metadata,- Map<String, PdfJsonFont> fonts,- Map<Integer, Map<PDFont, String>> pageFontResources) {- this.pdfBytes = pdfBytes;- this.pdfTempFile = pdfTempFile;- this.pdfSize = pdfSize;- this.metadata = metadata;- // Create defensive copies to prevent mutation of shared maps- this.fonts =- fonts != null- ? new java.util.concurrent.ConcurrentHashMap<>(fonts)- : new java.util.concurrent.ConcurrentHashMap<>();- this.pageFontResources =- pageFontResources != null- ? new java.util.concurrent.ConcurrentHashMap<>(pageFontResources)- : new java.util.concurrent.ConcurrentHashMap<>();- this.timestamp = System.currentTimeMillis();- }-- // Getters return defensive copies to prevent external mutation- public byte[] getPdfBytes() throws IOException {- if (pdfBytes != null) {- return pdfBytes;- }- if (pdfTempFile != null) {- return Files.readAllBytes(pdfTempFile.getPath());- }- throw new IOException("Cached PDF backing missing");- }-- public PdfJsonDocumentMetadata getMetadata() {- return metadata;- }-- public Map<String, PdfJsonFont> getFonts() {- return new java.util.concurrent.ConcurrentHashMap<>(fonts);- }-- public Map<Integer, Map<PDFont, String>> getPageFontResources() {- return new java.util.concurrent.ConcurrentHashMap<>(pageFontResources);- }-- public long getPdfSize() {- return pdfSize;- }-- public long getInMemorySize() {- return pdfBytes != null ? pdfBytes.length : 0L;- }-- public boolean isDiskBacked() {- return pdfBytes == null && pdfTempFile != null;- }-- public long getTimestamp() {- return timestamp;- }-- public CachedPdfDocument withUpdatedPdfBytes(byte[] nextBytes) {- return withUpdatedFonts(nextBytes, this.fonts);- }-- public CachedPdfDocument withUpdatedFonts(- byte[] nextBytes, Map<String, PdfJsonFont> nextFonts) {- Map<String, PdfJsonFont> fontsToUse = nextFonts != null ? nextFonts : this.fonts;- return new CachedPdfDocument(- nextBytes,- null,- nextBytes != null ? nextBytes.length : 0,- metadata,- fontsToUse,- pageFontResources);- }-- public void close() {- if (pdfTempFile != null) {- pdfTempFile.close();- }- }- }-- /**- * Extracts document metadata, fonts, and page dimensions without page content. Caches the PDF- * bytes for subsequent page requests.- */- public void extractDocumentMetadata(MultipartFile file, String jobId, OutputStream out)- throws IOException {- if (file == null) {- throw ExceptionUtils.createNullArgumentException("fileInput");- }-- Consumer<PdfJsonConversionProgress> progress =- jobId != null- ? (p) -> {- log.debug(- "Progress: [{}%] {} - {}{}",- p.getPercent(),- p.getStage(),- p.getMessage(),- (p.getCurrent() != null && p.getTotal() != null)- ? String.format(- " (%d/%d)", p.getCurrent(), p.getTotal())- : "");- reportProgressToTaskManager(jobId, p);- }- : (p) -> {};-- // Read PDF bytes once for processing and caching- byte[] pdfBytes = file.getBytes();-- try (PDDocument document = pdfDocumentFactory.load(pdfBytes, true)) {- int totalPages = document.getNumberOfPages();-- // Extract fonts- progress.accept(- PdfJsonConversionProgress.of(30, "fonts", "Collecting font information"));- Map<String, PdfJsonFont> fonts = new LinkedHashMap<>();- Map<Integer, Map<PDFont, String>> pageFontResources = new HashMap<>();- Map<COSBase, FontModelCacheEntry> fontCache = new IdentityHashMap<>();- int pageNumber = 1;- for (PDPage page : document.getPages()) {- Map<PDFont, String> resourceMap =- collectFontsForPage(document, page, pageNumber, fonts, fontCache, jobId);- pageFontResources.put(pageNumber, resourceMap);- pageNumber++;- }-- // Build metadata response- progress.accept(PdfJsonConversionProgress.of(90, "metadata", "Extracting metadata"));- PdfJsonDocumentMetadata docMetadata = new PdfJsonDocumentMetadata();- docMetadata.setMetadata(extractMetadata(document));- docMetadata.setXmpMetadata(extractXmpMetadata(document));-- List<PdfJsonFont> serializedFonts = cloneFontList(fonts.values());- serializedFonts.sort(- Comparator.comparing(- PdfJsonFont::getUid, Comparator.nullsLast(Comparator.naturalOrder())));- dedupeFontPayloads(serializedFonts);- stripFontProgramPayloads(serializedFonts);- stripFontCosStreamData(serializedFonts);- docMetadata.setFonts(serializedFonts);-- // Extract page dimensions- List<PdfJsonPageDimension> pageDimensions = new ArrayList<>();- int pageIndex = 0;- for (PDPage page : document.getPages()) {- PdfJsonPageDimension dim = new PdfJsonPageDimension();- dim.setPageNumber(pageIndex + 1);- PDRectangle mediaBox = page.getMediaBox();- dim.setWidth(mediaBox.getWidth());- dim.setHeight(mediaBox.getHeight());- dim.setRotation(page.getRotation());- pageDimensions.add(dim);- pageIndex++;- }- docMetadata.setPageDimensions(pageDimensions);- // Metadata endpoint is used for lazy editor bootstrapping; omit form fields to avoid- // shipping large duplicate raw dictionaries before any edit occurs.- docMetadata.setFormFields(null);- docMetadata.setLazyImages(Boolean.TRUE);-- // Cache PDF bytes, metadata, and fonts for lazy page loading- if (jobId != null) {- CachedPdfDocument cached =- buildCachedDocument(jobId, pdfBytes, docMetadata, fonts, pageFontResources);- putCachedDocument(jobId, cached);- log.debug(- "Cached PDF bytes ({} bytes, {} pages, {} fonts) for lazy loading, jobId: {} (diskBacked={})",- cached.getPdfSize(),- totalPages,- fonts.size(),- jobId,- cached.isDiskBacked());-- // Schedule cleanup after 30 minutes- scheduleDocumentCleanup(jobId);- }-- progress.accept(- PdfJsonConversionProgress.of(100, "complete", "Metadata extraction complete"));-- objectMapper.writeValue(out, docMetadata);- }- }-- /** Extracts a single page from cached PDF bytes. Re-loads the PDF for each request. */- public void extractSinglePage(String jobId, int pageNumber, OutputStream out)- throws IOException {- CachedPdfDocument cached = getCachedDocument(jobId);- if (cached == null) {- throw new stirling.software.SPDF.exception.CacheUnavailableException(- "No cached document found for jobId: " + jobId);- }-- int pageIndex = pageNumber - 1;- int totalPages = cached.getMetadata().getPageDimensions().size();-- if (pageIndex < 0 || pageIndex >= totalPages) {- throw new IllegalArgumentException(- "Page number " + pageNumber + " out of range (1-" + totalPages + ")");- }-- log.debug(- "Loading PDF from {} to extract page {} (jobId: {})",- cached.isDiskBacked() ? "disk cache" : "memory cache",- pageNumber,- jobId);-- // Re-load PDF from cached bytes and extract the single page- try (PDDocument document = pdfDocumentFactory.load(cached.getPdfBytes(), true)) {- PDPage page = document.getPage(pageIndex);- PdfJsonPage pageModel = new PdfJsonPage();- pageModel.setPageNumber(pageNumber);- PDRectangle mediaBox = page.getMediaBox();- pageModel.setWidth(mediaBox.getWidth());- pageModel.setHeight(mediaBox.getHeight());- pageModel.setRotation(page.getRotation());-- // Extract text on-demand using cached fonts (ensures consistent font UIDs)- // Create thread-local copies to prevent mutation of cached maps- Map<String, PdfJsonFont> threadLocalFonts =- new java.util.concurrent.ConcurrentHashMap<>(cached.getFonts());- Map<Integer, Map<PDFont, String>> threadLocalPageFontResources =- new java.util.concurrent.ConcurrentHashMap<>(cached.getPageFontResources());-- Map<Integer, List<PdfJsonTextElement>> textByPage = new LinkedHashMap<>();- TextCollectingStripper stripper =- new TextCollectingStripper(- document,- threadLocalFonts,- textByPage,- threadLocalPageFontResources,- new IdentityHashMap<>(),- jobId);- stripper.setStartPage(pageNumber);- stripper.setEndPage(pageNumber);- stripper.setSortByPosition(true);- stripper.getText(document);- pageModel.setTextElements(textByPage.getOrDefault(pageNumber, List.of()));-- // Extract annotations on-demand- List<PdfJsonAnnotation> annotations = new ArrayList<>();- for (PDAnnotation annotation : page.getAnnotations()) {- try {- PdfJsonAnnotation ann = new PdfJsonAnnotation();- ann.setSubtype(annotation.getSubtype());- ann.setContents(annotation.getContents());-- PDRectangle rect = annotation.getRectangle();- if (rect != null) {- ann.setRect(- new float[] {- rect.getLowerLeftX(),- rect.getLowerLeftY(),- rect.getUpperRightX(),- rect.getUpperRightY()- });- }-- COSName appearanceState = annotation.getAppearanceState();- if (appearanceState != null) {- ann.setAppearanceState(appearanceState.getName());- }-- if (annotation.getColor() != null) {- ann.setColor(annotation.getColor().getComponents());- }-- COSDictionary annotDict = annotation.getCOSObject();- COSString title = (COSString) annotDict.getDictionaryObject(COSName.T);- if (title != null) {- ann.setAuthor(title.getString());- }-- COSString subj = (COSString) annotDict.getDictionaryObject(COSName.SUBJ);- if (subj != null) {- ann.setSubject(subj.getString());- }-- COSString creationDateStr =- (COSString) annotDict.getDictionaryObject(COSName.CREATION_DATE);- if (creationDateStr != null) {- try {- Calendar creationDate =- DateConverter.toCalendar(creationDateStr.getString());- ann.setCreationDate(formatCalendar(creationDate));- } catch (Exception e) {- log.debug(- "Failed to parse annotation creation date: {}", e.getMessage());- }- }-- COSString modDateStr = (COSString) annotDict.getDictionaryObject(COSName.M);- if (modDateStr != null) {- try {- Calendar modDate = DateConverter.toCalendar(modDateStr.getString());- ann.setModificationDate(formatCalendar(modDate));- } catch (Exception e) {- log.debug(- "Failed to parse annotation modification date: {}",- e.getMessage());- }- }-- // For cached page extraction, skip rawData to avoid huge payloads- annotations.add(ann);- } catch (Exception e) {- log.warn(- "Failed to extract annotation on page {}: {}",- pageNumber,- e.getMessage());- }- }- pageModel.setAnnotations(annotations);-- // Extract images on-demand- Map<Integer, List<PdfJsonImageElement>> singlePageImages = new LinkedHashMap<>();- ImageCollectingEngine engine =- new ImageCollectingEngine(- page, pageNumber, singlePageImages, new IdentityHashMap<>());- engine.processPage(page);- List<PdfJsonImageElement> images = singlePageImages.getOrDefault(pageNumber, List.of());- pageModel.setImageElements(images);-- // Extract resources and content streams- COSBase resourcesBase = page.getCOSObject().getDictionaryObject(COSName.RESOURCES);- COSBase filteredResources = filterImageXObjectsFromResources(resourcesBase);- pageModel.setResources(null);- pageModel.setContentStreams(null);-- log.debug(- "Extracted page {} (text: {}, images: {}, annotations: {}) for jobId: {}",- pageNumber,- pageModel.getTextElements().size(),- images.size(),- pageModel.getAnnotations().size(),- jobId);-- objectMapper.writeValue(out, pageModel);- }- }-- public void extractPageFonts(String jobId, int pageNumber, OutputStream out)- throws IOException {- CachedPdfDocument cached = getCachedDocument(jobId);- if (cached == null) {- throw new stirling.software.SPDF.exception.CacheUnavailableException(- "No cached document found for jobId: " + jobId);- }-- int totalPages = cached.getMetadata().getPageDimensions().size();- if (pageNumber < 1 || pageNumber > totalPages) {- throw new IllegalArgumentException(- String.format("pageNumber must be between 1 and %d", totalPages));- }-- Map<Integer, Map<PDFont, String>> pageFontResources = cached.getPageFontResources();- Map<PDFont, String> pageMap =- pageFontResources != null ? pageFontResources.get(pageNumber) : null;- if (pageMap == null || pageMap.isEmpty()) {- objectMapper.writeValue(out, Collections.emptyList());- return;- }-- Map<String, PdfJsonFont> cachedFonts = cached.getFonts();- List<PdfJsonFont> pageFonts = new ArrayList<>();- Set<String> seen = new LinkedHashSet<>();- for (String fontId : pageMap.values()) {- if (fontId == null || fontId.isBlank()) {- continue;- }- String key = buildFontKey(jobId, pageNumber, fontId);- if (!seen.add(key)) {- continue;- }- PdfJsonFont font = cachedFonts.get(key);- if (font == null) {- // Fallback to unscoped key for resilience with legacy cached entries.- font = cachedFonts.get(buildFontKey(null, pageNumber, fontId));- }- if (font == null) {- continue;- }- PdfJsonFont clone = cloneFont(font);- pageFonts.add(clone != null ? clone : font);- }- pageFonts.sort(- Comparator.comparing(- PdfJsonFont::getUid, Comparator.nullsLast(Comparator.naturalOrder())));- objectMapper.writeValue(out, pageFonts);- }-- public void exportUpdatedPages(String jobId, PdfJsonDocument updates, OutputStream outputStream)- throws IOException {- if (jobId == null || jobId.isBlank()) {- throw new IllegalArgumentException("jobId is required for incremental export");- }- log.debug("Looking up cache for jobId: {}", jobId);- CachedPdfDocument cached = getCachedDocument(jobId);- if (cached == null) {- log.error(- "Cache not found for jobId: {}. Available cache keys: {}",- jobId,- documentCache.keySet());- throw new stirling.software.SPDF.exception.CacheUnavailableException(- "No cached document available for jobId: " + jobId);- }- log.debug(- "Found cached document for jobId: {} (size={}, diskBacked={})",- jobId,- cached.getPdfSize(),- cached.isDiskBacked());- if (updates == null || updates.getPages() == null || updates.getPages().isEmpty()) {- log.debug(- "Incremental export requested with no page updates; returning cached PDF for jobId {}",- jobId);- outputStream.write(cached.getPdfBytes());- return;- }-- try (PDDocument document = pdfDocumentFactory.load(cached.getPdfBytes(), true)) {- Map<String, PdfJsonFont> mergedFonts = new LinkedHashMap<>();- if (cached.getFonts() != null) {- cached.getFonts()- .forEach(- (key, value) -> {- PdfJsonFont clone = cloneFont(value);- mergedFonts.put(key, clone != null ? clone : value);- });- }- if (updates.getFonts() != null) {- for (PdfJsonFont font : updates.getFonts()) {- if (font == null) {- continue;- }- String cacheKey = resolveFontCacheKey(font);- if (cacheKey == null) {- continue;- }- PdfJsonFont clone = cloneFont(font);- PdfJsonFont toStore = clone != null ? clone : font;- mergedFonts.put(cacheKey, toStore);- if (toStore.getUid() != null) {- type3NormalizedFontCache.remove(toStore.getUid());- }- }- }-- List<PdfJsonFont> fontModels = new ArrayList<>(mergedFonts.values());- List<PdfJsonFont> fontModelsCopy = new ArrayList<>(fontModels);- // Generate synthetic jobId for this incremental update to prevent cache collisions- String updateJobId = "incremental:" + jobId + ":" + java.util.UUID.randomUUID();- Map<String, PDFont> fontMap = buildFontMap(document, fontModelsCopy, updateJobId);-- Set<Integer> updatedPages = new HashSet<>();- for (PdfJsonPage pageModel : updates.getPages()) {- if (pageModel == null) {- continue;- }- Integer pageNumber = pageModel.getPageNumber();- if (pageNumber == null) {- log.warn(- "Skipping incremental page update without pageNumber for jobId {}",- jobId);- continue;- }- int pageIndex = pageNumber - 1;- if (pageIndex < 0 || pageIndex >= document.getNumberOfPages()) {- log.warn(- "Skipping incremental update for out-of-range page {} (jobId {})",- pageNumber,- jobId);- continue;- }- PDPage page = document.getPage(pageIndex);- replacePageContentFromModel(- document, page, pageModel, fontMap, fontModelsCopy, pageNumber);- updatedPages.add(pageIndex);- }-- if (updatedPages.isEmpty()) {- log.debug(- "Incremental export for jobId {} resulted in no page updates; returning cached PDF",- jobId);- outputStream.write(cached.getPdfBytes());- return;- }-- ByteArrayOutputStream baos = new ByteArrayOutputStream();- document.save(baos);- byte[] updatedBytes = baos.toByteArray();-- CachedPdfDocument updated =- buildCachedDocument(- jobId,- updatedBytes,- cached.getMetadata(),- mergedFonts,- cached.getPageFontResources());- putCachedDocument(jobId, updated);-- // Clear Type3 cache entries for this incremental update- clearType3CacheEntriesForJob(updateJobId);-- log.debug(- "Incremental export complete for jobId {} (pages updated: {})",- jobId,- updatedPages.stream().map(i -> i + 1).sorted().toList());- outputStream.write(updatedBytes);- }- }-- /** Clears a cached document. */- public void clearCachedDocument(String jobId) {- CachedPdfDocument cached = getCachedDocument(jobId);- removeCachedDocument(jobId);- if (cached != null) {- log.debug(- "Removed cached PDF ({} bytes, diskBacked={}) for jobId: {}",- cached.getPdfSize(),- cached.isDiskBacked(),- jobId);- }-- // Clear Type3 caches for this job- clearType3CacheEntriesForJob(jobId);- }-- /**- * Clear job-specific entries from Type3 font caches. Font UIDs include jobId prefix, so we can- * identify and remove them.- */- private void clearType3CacheEntriesForJob(String jobId) {- if (jobId == null || jobId.isEmpty()) {- return;- }-- String jobPrefix = jobId + ":";-- // Collect keys to remove (to avoid ConcurrentModificationException)- java.util.List<String> keysToRemove = new java.util.ArrayList<>();-- // Find Type3 normalized font keys for this job- for (String key : type3NormalizedFontCache.keySet()) {- if (key.startsWith(jobPrefix)) {- keysToRemove.add(key);- }- }-- // Remove collected keys- for (String key : keysToRemove) {- type3NormalizedFontCache.remove(key);- }- int removedFonts = keysToRemove.size();-- // Find Type3 glyph coverage keys for this job- keysToRemove.clear();- for (String key : type3GlyphCoverageCache.keySet()) {- if (key.startsWith(jobPrefix)) {- keysToRemove.add(key);- }- }-- // Remove collected keys- for (String key : keysToRemove) {- type3GlyphCoverageCache.remove(key);- }- int removedGlyphs = keysToRemove.size();-- if (removedFonts > 0 || removedGlyphs > 0) {- log.debug(- "Cleared Type3 caches for jobId {}: {} fonts, {} glyph entries",- jobId,- removedFonts,- removedGlyphs);- }- }-- private void replacePageContentFromModel(- PDDocument document,- PDPage page,- PdfJsonPage pageModel,- Map<String, PDFont> fontMap,- List<PdfJsonFont> fontModels,- int pageNumberValue)- throws IOException {- boolean preserveExistingAnnotations =- shouldPreserveExistingAnnotations(pageModel.getAnnotations());- boolean preserveExistingContentStreams =- shouldPreserveExistingContentStreams(pageModel.getContentStreams());- boolean preserveExistingResources =- shouldPreserveExistingResources(pageModel.getResources());-- PDRectangle currentBox = page.getMediaBox();- float fallbackWidth = currentBox != null ? currentBox.getWidth() : 612f;- float fallbackHeight = currentBox != null ? currentBox.getHeight() : 792f;-- float width = safeFloat(pageModel.getWidth(), fallbackWidth);- float height = safeFloat(pageModel.getHeight(), fallbackHeight);- PDRectangle newBox = new PDRectangle(width, height);- page.setMediaBox(newBox);- page.setCropBox(newBox);-- if (pageModel.getRotation() != null) {- page.setRotation(pageModel.getRotation());- }-- if (!preserveExistingResources) {- applyPageResources(document, page, pageModel.getResources());- }-- List<PDStream> preservedStreams;- if (preserveExistingContentStreams) {- preservedStreams = snapshotExistingContentStreams(page);- } else {- preservedStreams = buildContentStreams(document, pageModel.getContentStreams());- if (preservedStreams.isEmpty()) {- page.setContents(new ArrayList<>());- } else {- page.setContents(preservedStreams);- }- }-- List<PdfJsonImageElement> imageElements =- pageModel.getImageElements() != null- ? new ArrayList<>(pageModel.getImageElements())- : new ArrayList<>();-- if (!preservedStreams.isEmpty() && !imageElements.isEmpty()) {- reconstructImageXObjects(document, page, preservedStreams, imageElements);- }-- List<PdfJsonTextElement> textElements =- pageModel.getTextElements() != null- ? new ArrayList<>(pageModel.getTextElements())- : new ArrayList<>();-- PreflightResult preflightResult =- preflightTextElements(document, fontMap, fontModels, textElements, pageNumberValue);- if (!preflightResult.fallbackFontIds().isEmpty()) {- ensureFallbackResources(page, preflightResult.fallbackFontIds(), fontMap);- }-- Map<String, PdfJsonFont> fontLookup = buildFontModelLookup(fontModels);-- AppendMode appendMode =- preservedStreams.isEmpty() ? AppendMode.OVERWRITE : AppendMode.APPEND;-- RegenerateMode regenerateMode =- determineRegenerateMode(- document,- page,- preservedStreams,- textElements,- imageElements,- preflightResult,- fontLookup,- pageNumberValue);-- if (regenerateMode == RegenerateMode.REUSE_EXISTING) {- if (!preserveExistingAnnotations) {- page.getAnnotations().clear();- List<PdfJsonAnnotation> annotations =- pageModel.getAnnotations() != null- ? new ArrayList<>(pageModel.getAnnotations())- : new ArrayList<>();- restoreAnnotations(document, page, annotations);- }- return;- }-- if (regenerateMode == RegenerateMode.REGENERATE_WITH_VECTOR_OVERLAY) {- PDStream vectorStream =- extractVectorGraphics(document, preservedStreams, imageElements);- if (vectorStream != null) {- page.setContents(Collections.singletonList(vectorStream));- appendMode = AppendMode.APPEND;- } else {- page.setContents(new ArrayList<>());- appendMode = AppendMode.OVERWRITE;- }- } else if (regenerateMode == RegenerateMode.REGENERATE_CLEAR) {- page.setContents(new ArrayList<>());- appendMode = AppendMode.OVERWRITE;- }-- regeneratePageContent(- document,- page,- textElements,- imageElements,- fontMap,- fontModels,- pageNumberValue,- appendMode);-- if (!preserveExistingAnnotations) {- page.getAnnotations().clear();- List<PdfJsonAnnotation> annotations =- pageModel.getAnnotations() != null- ? new ArrayList<>(pageModel.getAnnotations())- : new ArrayList<>();- restoreAnnotations(document, page, annotations);- }- }-- private RegenerateMode determineRegenerateMode(- PDDocument document,- PDPage page,- List<PDStream> preservedStreams,- List<PdfJsonTextElement> textElements,- List<PdfJsonImageElement> imageElements,- PreflightResult preflightResult,- Map<String, PdfJsonFont> fontLookup,- int pageNumberValue)- throws IOException {- boolean hasText = textElements != null && !textElements.isEmpty();- boolean hasImages = imageElements != null && !imageElements.isEmpty();-- if (!hasText && !hasImages) {- return RegenerateMode.REGENERATE_CLEAR;- }-- if (preservedStreams.isEmpty()) {- return RegenerateMode.REGENERATE_CLEAR;- }-- if (hasImages) {- return RegenerateMode.REGENERATE_WITH_VECTOR_OVERLAY;- }-- if (hasText && !preflightResult.usesFallback()) {- boolean rewriteSucceeded =- rewriteTextOperators(- document, page, textElements, false, true, fontLookup, pageNumberValue);- if (rewriteSucceeded) {- return RegenerateMode.REUSE_EXISTING;- }- return RegenerateMode.REGENERATE_WITH_VECTOR_OVERLAY;- }-- return RegenerateMode.REGENERATE_WITH_VECTOR_OVERLAY;- }-- private enum RegenerateMode {- REUSE_EXISTING,- REGENERATE_WITH_VECTOR_OVERLAY,- REGENERATE_CLEAR- }-- private boolean shouldPreserveExistingAnnotations(List<PdfJsonAnnotation> annotations) {- if (annotations == null) {- return true;- }- if (annotations.isEmpty()) {- return false;- }- for (PdfJsonAnnotation annotation : annotations) {- if (annotation == null || annotation.getRawData() == null) {- return true;- }- if (hasMissingStreamData(annotation.getRawData())) {- return true;- }- }- return false;- }-- private boolean shouldPreserveExistingContentStreams(List<PdfJsonStream> streams) {- if (streams == null) {- return true;- }- if (streams.isEmpty()) {- return false;- }- for (PdfJsonStream stream : streams) {- if (stream == null || stream.getRawData() == null) {- return true;- }- }- return false;- }-- private boolean shouldPreserveExistingResources(PdfJsonCosValue resources) {- if (resources == null) {- return true;- }- return hasMissingStreamData(resources);- }-- private List<PDStream> snapshotExistingContentStreams(PDPage page) throws IOException {- List<PDStream> streams = new ArrayList<>();- Iterator<PDStream> iterator = page.getContentStreams();- if (iterator == null) {- return streams;- }- while (iterator.hasNext()) {- PDStream stream = iterator.next();- if (stream != null) {- streams.add(stream);- }- }- return streams;- }-- private boolean hasMissingStreamData(PdfJsonCosValue value) {- return hasMissingStreamData(value, Collections.newSetFromMap(new IdentityHashMap<>()));- }-- private boolean hasMissingStreamData(PdfJsonCosValue value, Set<PdfJsonCosValue> visited) {- if (value == null || value.getType() == null) {- return false;- }- if (!visited.add(value)) {- return false;- }- switch (value.getType()) {- case STREAM:- PdfJsonStream stream = value.getStream();- return stream == null || stream.getRawData() == null;- case ARRAY:- if (value.getItems() != null) {- for (PdfJsonCosValue item : value.getItems()) {- if (hasMissingStreamData(item, visited)) {- return true;- }- }- }- return false;- case DICTIONARY:- if (value.getEntries() != null) {- for (PdfJsonCosValue entry : value.getEntries().values()) {- if (hasMissingStreamData(entry, visited)) {- return true;- }- }- }- return false;- default:- return false;- }- }-- /** Schedules automatic cleanup of cached documents after 30 minutes. */- private void scheduleDocumentCleanup(String jobId) {- Thread.ofVirtual()- .start(- () -> {- try {- Thread.sleep(TimeUnit.MINUTES.toMillis(30));- clearCachedDocument(jobId);- log.debug("Auto-cleaned cached document for jobId: {}", jobId);- } catch (InterruptedException e) {- Thread.currentThread().interrupt();- }- });- }-}diff --git a/app/core/src/main/java/stirling/software/SPDF/service/PdfJsonCosMapper.java b/app/core/src/main/java/stirling/software/SPDF/service/PdfJsonCosMapper.javadeleted file mode 100644index 070600329a..0000000000--- a/app/core/src/main/java/stirling/software/SPDF/service/PdfJsonCosMapper.java+++ /dev/null@@ -1,328 +0,0 @@-package stirling.software.SPDF.service;--import java.io.ByteArrayOutputStream;-import java.io.IOException;-import java.io.InputStream;-import java.io.OutputStream;-import java.util.ArrayList;-import java.util.Base64;-import java.util.Collections;-import java.util.IdentityHashMap;-import java.util.LinkedHashMap;-import java.util.List;-import java.util.Map;-import java.util.Set;--import org.apache.pdfbox.cos.COSArray;-import org.apache.pdfbox.cos.COSBase;-import org.apache.pdfbox.cos.COSBoolean;-import org.apache.pdfbox.cos.COSDictionary;-import org.apache.pdfbox.cos.COSFloat;-import org.apache.pdfbox.cos.COSInteger;-import org.apache.pdfbox.cos.COSName;-import org.apache.pdfbox.cos.COSNull;-import org.apache.pdfbox.cos.COSObject;-import org.apache.pdfbox.cos.COSStream;-import org.apache.pdfbox.cos.COSString;-import org.apache.pdfbox.pdmodel.PDDocument;-import org.apache.pdfbox.pdmodel.common.PDStream;-import org.springframework.stereotype.Component;--import lombok.extern.slf4j.Slf4j;--import stirling.software.SPDF.model.json.PdfJsonCosValue;-import stirling.software.SPDF.model.json.PdfJsonStream;--@Slf4j-@Component-public class PdfJsonCosMapper {-- public enum SerializationContext {- DEFAULT,- ANNOTATION_RAW_DATA,- FORM_FIELD_RAW_DATA,- CONTENT_STREAMS_LIGHTWEIGHT,- RESOURCES_LIGHTWEIGHT;-- public boolean omitStreamData() {- return this == CONTENT_STREAMS_LIGHTWEIGHT || this == RESOURCES_LIGHTWEIGHT;- }- }-- public PdfJsonStream serializeStream(PDStream stream) throws IOException {- if (stream == null) {- return null;- }- return serializeStream(- stream.getCOSObject(),- Collections.newSetFromMap(new IdentityHashMap<>()),- SerializationContext.DEFAULT);- }-- public PdfJsonStream serializeStream(COSStream cosStream) throws IOException {- if (cosStream == null) {- return null;- }- return serializeStream(- cosStream,- Collections.newSetFromMap(new IdentityHashMap<>()),- SerializationContext.DEFAULT);- }-- public PdfJsonStream serializeStream(COSStream cosStream, SerializationContext context)- throws IOException {- if (cosStream == null) {- return null;- }- SerializationContext effective = context != null ? context : SerializationContext.DEFAULT;- return serializeStream(- cosStream, Collections.newSetFromMap(new IdentityHashMap<>()), effective);- }-- public PdfJsonStream serializeStream(PDStream stream, SerializationContext context)- throws IOException {- if (stream == null) {- return null;- }- return serializeStream(stream.getCOSObject(), context);- }-- public PdfJsonCosValue serializeCosValue(COSBase base) throws IOException {- return serializeCosValue(- base,- Collections.newSetFromMap(new IdentityHashMap<>()),- SerializationContext.DEFAULT);- }-- public PdfJsonCosValue serializeCosValue(COSBase base, SerializationContext context)- throws IOException {- SerializationContext effective = context != null ? context : SerializationContext.DEFAULT;- return serializeCosValue(- base, Collections.newSetFromMap(new IdentityHashMap<>()), effective);- }-- public COSBase deserializeCosValue(PdfJsonCosValue value, PDDocument document)- throws IOException {- if (value == null || value.getType() == null) {- return null;- }- switch (value.getType()) {- case NULL:- return COSNull.NULL;- case BOOLEAN:- if (value.getValue() instanceof Boolean bool) {- return COSBoolean.getBoolean(bool);- }- return null;- case INTEGER:- if (value.getValue() instanceof Number number) {- return COSInteger.get(number.longValue());- }- return null;- case FLOAT:- if (value.getValue() instanceof Number number) {- return new COSFloat(number.floatValue());- }- return null;- case NAME:- if (value.getValue() instanceof String name) {- return COSName.getPDFName(name);- }- return null;- case STRING:- if (value.getValue() instanceof String encoded) {- try {- byte[] bytes = Base64.getDecoder().decode(encoded);- return new COSString(bytes);- } catch (IllegalArgumentException ex) {- log.debug("Failed to decode COSString value: {}", ex.getMessage());- }- }- return null;- case ARRAY:- COSArray array = new COSArray();- if (value.getItems() != null) {- for (PdfJsonCosValue item : value.getItems()) {- COSBase entry = deserializeCosValue(item, document);- if (entry != null) {- array.add(entry);- } else {- array.add(COSNull.NULL);- }- }- }- return array;- case DICTIONARY:- COSDictionary dictionary = new COSDictionary();- if (value.getEntries() != null) {- for (Map.Entry<String, PdfJsonCosValue> entry : value.getEntries().entrySet()) {- COSName key = COSName.getPDFName(entry.getKey());- COSBase entryValue = deserializeCosValue(entry.getValue(), document);- if (entryValue != null) {- dictionary.setItem(key, entryValue);- }- }- }- return dictionary;- case STREAM:- if (value.getStream() != null) {- return buildStreamFromModel(value.getStream(), document);- }- return null;- default:- return null;- }- }-- public COSStream buildStreamFromModel(PdfJsonStream streamModel, PDDocument document)- throws IOException {- if (streamModel == null) {- return null;- }- COSStream cosStream = document.getDocument().createCOSStream();- if (streamModel.getDictionary() != null) {- for (Map.Entry<String, PdfJsonCosValue> entry :- streamModel.getDictionary().entrySet()) {- COSName key = COSName.getPDFName(entry.getKey());- COSBase value = deserializeCosValue(entry.getValue(), document);- if (value != null) {- cosStream.setItem(key, value);- }- }- }-- String rawData = streamModel.getRawData();- if (rawData != null && !rawData.isBlank()) {- byte[] data;- try {- data = Base64.getDecoder().decode(rawData);- } catch (IllegalArgumentException ex) {- log.debug("Invalid base64 content stream data: {}", ex.getMessage());- data = new byte[0];- }- try (OutputStream outputStream = cosStream.createRawOutputStream()) {- outputStream.write(data);- }- cosStream.setItem(COSName.LENGTH, COSInteger.get(data.length));- } else {- cosStream.setItem(COSName.LENGTH, COSInteger.get(0));- }- return cosStream;- }-- private PdfJsonCosValue serializeCosValue(- COSBase base, Set<COSBase> visited, SerializationContext context) throws IOException {- if (base == null) {- return null;- }- if (base instanceof COSObject cosObject) {- base = cosObject.getObject();- if (base == null) {- return null;- }- }-- boolean complex =- base instanceof COSDictionary- || base instanceof COSArray- || base instanceof COSStream;- if (complex) {- if (!visited.add(base)) {- return PdfJsonCosValue.builder()- .type(PdfJsonCosValue.Type.NAME)- .value("__circular__")- .build();- }- }-- try {- PdfJsonCosValue.PdfJsonCosValueBuilder builder = PdfJsonCosValue.builder();- if (base instanceof COSNull) {- builder.type(PdfJsonCosValue.Type.NULL);- return builder.build();- }- if (base instanceof COSBoolean booleanValue) {- builder.type(PdfJsonCosValue.Type.BOOLEAN).value(booleanValue.getValue());- return builder.build();- }- if (base instanceof COSInteger integer) {- builder.type(PdfJsonCosValue.Type.INTEGER).value(integer.longValue());- return builder.build();- }- if (base instanceof COSFloat floatValue) {- builder.type(PdfJsonCosValue.Type.FLOAT).value(floatValue.floatValue());- return builder.build();- }- if (base instanceof COSName name) {- builder.type(PdfJsonCosValue.Type.NAME).value(name.getName());- return builder.build();- }- if (base instanceof COSString cosString) {- builder.type(PdfJsonCosValue.Type.STRING)- .value(Base64.getEncoder().encodeToString(cosString.getBytes()));- return builder.build();- }- if (base instanceof COSArray array) {- List<PdfJsonCosValue> items = new ArrayList<>(array.size());- for (COSBase item : array) {- PdfJsonCosValue serialized = serializeCosValue(item, visited, context);- items.add(serialized);- }- builder.type(PdfJsonCosValue.Type.ARRAY).items(items);- return builder.build();- }- if (base instanceof COSStream stream) {- builder.type(PdfJsonCosValue.Type.STREAM).stream(- serializeStream(stream, visited, context));- return builder.build();- }- if (base instanceof COSDictionary dictionary) {- Map<String, PdfJsonCosValue> entries = new LinkedHashMap<>();- for (COSName key : dictionary.keySet()) {- PdfJsonCosValue serialized =- serializeCosValue(- dictionary.getDictionaryObject(key), visited, context);- entries.put(key.getName(), serialized);- }- builder.type(PdfJsonCosValue.Type.DICTIONARY).entries(entries);- return builder.build();- }- return null;- } finally {- if (complex) {- visited.remove(base);- }- }- }-- private PdfJsonStream serializeStream(- COSStream cosStream, Set<COSBase> visited, SerializationContext context)- throws IOException {- Map<String, PdfJsonCosValue> dictionary = new LinkedHashMap<>();- for (COSName key : cosStream.keySet()) {- COSBase value = cosStream.getDictionaryObject(key);- PdfJsonCosValue serialized = serializeCosValue(value, visited, context);- if (serialized != null) {- dictionary.put(key.getName(), serialized);- }- }-- if (context != null && context.omitStreamData()) {- log.debug("Omitting stream rawData during {} serialization", context);- return PdfJsonStream.builder().dictionary(dictionary).rawData(null).build();- }-- String rawData = null;- try (InputStream inputStream = cosStream.createRawInputStream();- ByteArrayOutputStream baos = new ByteArrayOutputStream()) {- if (inputStream != null) {- inputStream.transferTo(baos);- }- byte[] data = baos.toByteArray();- if (data.length > 0) {- rawData = Base64.getEncoder().encodeToString(data);- }- }- return PdfJsonStream.builder().dictionary(dictionary).rawData(rawData).build();- }-}diff --git a/app/core/src/main/java/stirling/software/SPDF/service/PdfJsonFallbackFontService.java b/app/core/src/main/java/stirling/software/SPDF/service/PdfJsonFallbackFontService.javadeleted file mode 100644index 46067611a5..0000000000--- a/app/core/src/main/java/stirling/software/SPDF/service/PdfJsonFallbackFontService.java+++ /dev/null@@ -1,664 +0,0 @@-package stirling.software.SPDF.service;--import java.io.ByteArrayInputStream;-import java.io.ByteArrayOutputStream;-import java.io.IOException;-import java.io.InputStream;-import java.util.Locale;-import java.util.Map;-import java.util.concurrent.ConcurrentHashMap;-import java.util.regex.Pattern;--import org.apache.pdfbox.pdmodel.PDDocument;-import org.apache.pdfbox.pdmodel.font.PDFont;-import org.apache.pdfbox.pdmodel.font.PDType0Font;-import org.apache.pdfbox.pdmodel.font.PDType3Font;-import org.springframework.beans.factory.annotation.Value;-import org.springframework.core.io.Resource;-import org.springframework.core.io.ResourceLoader;-import org.springframework.stereotype.Component;--import lombok.RequiredArgsConstructor;-import lombok.extern.slf4j.Slf4j;--import stirling.software.SPDF.model.json.PdfJsonFont;--@Slf4j-@Component-@RequiredArgsConstructor-public class PdfJsonFallbackFontService {-- public static final String FALLBACK_FONT_ID = "fallback-noto-sans";- public static final String DEFAULT_FALLBACK_FONT_LOCATION =- "classpath:/static/fonts/NotoSans-Regular.ttf";- public static final String FALLBACK_FONT_CJK_ID = "fallback-noto-cjk";- public static final String FALLBACK_FONT_JP_ID = "fallback-noto-jp";- public static final String FALLBACK_FONT_KR_ID = "fallback-noto-korean";- public static final String FALLBACK_FONT_TC_ID = "fallback-noto-tc";- public static final String FALLBACK_FONT_AR_ID = "fallback-noto-arabic";- public static final String FALLBACK_FONT_TH_ID = "fallback-noto-thai";- public static final String FALLBACK_FONT_DEVANAGARI_ID = "fallback-noto-devanagari";- public static final String FALLBACK_FONT_MALAYALAM_ID = "fallback-noto-malayalam";- public static final String FALLBACK_FONT_TIBETAN_ID = "fallback-noto-tibetan";-- // Font name aliases map PDF font names to available fallback fonts- // This provides better visual consistency when editing PDFs- private static final Map<String, String> FONT_NAME_ALIASES =- Map.ofEntries(- // Liberation fonts are metric-compatible with Microsoft core fonts- Map.entry("arial", "fallback-liberation-sans"),- Map.entry("helvetica", "fallback-liberation-sans"),- Map.entry("arimo", "fallback-liberation-sans"),- Map.entry("liberationsans", "fallback-liberation-sans"),- Map.entry("times", "fallback-liberation-serif"),- Map.entry("timesnewroman", "fallback-liberation-serif"),- Map.entry("tinos", "fallback-liberation-serif"),- Map.entry("liberationserif", "fallback-liberation-serif"),- Map.entry("courier", "fallback-liberation-mono"),- Map.entry("couriernew", "fallback-liberation-mono"),- Map.entry("cousine", "fallback-liberation-mono"),- Map.entry("liberationmono", "fallback-liberation-mono"),- // DejaVu fonts - widely used open source fonts- Map.entry("dejavu", "fallback-dejavu-sans"),- Map.entry("dejavusans", "fallback-dejavu-sans"),- Map.entry("dejavuserif", "fallback-dejavu-serif"),- Map.entry("dejavumono", "fallback-dejavu-mono"),- Map.entry("dejavusansmono", "fallback-dejavu-mono"),- // Traditional Chinese fonts (Taiwan, Hong Kong, Macau)- Map.entry("mingliu", "fallback-noto-tc"),- Map.entry("pmingliu", "fallback-noto-tc"),- Map.entry("microsoftjhenghei", "fallback-noto-tc"),- Map.entry("jhenghei", "fallback-noto-tc"),- Map.entry("kaiti", "fallback-noto-tc"),- Map.entry("kaiu", "fallback-noto-tc"),- Map.entry("dfkaib5", "fallback-noto-tc"),- Map.entry("dfkai", "fallback-noto-tc"),- // Simplified Chinese fonts (Mainland China) - more common- Map.entry("simsun", "fallback-noto-cjk"),- Map.entry("simhei", "fallback-noto-cjk"),- Map.entry("microsoftyahei", "fallback-noto-cjk"),- Map.entry("yahei", "fallback-noto-cjk"),- Map.entry("songti", "fallback-noto-cjk"),- Map.entry("heiti", "fallback-noto-cjk"),- // Noto Sans - Google's universal font (use as last resort generic fallback)- Map.entry("noto", "fallback-noto-sans"),- Map.entry("notosans", "fallback-noto-sans"));-- private static final Map<String, FallbackFontSpec> BUILT_IN_FALLBACK_FONTS =- Map.ofEntries(- Map.entry(- FALLBACK_FONT_CJK_ID,- new FallbackFontSpec(- "classpath:/static/fonts/NotoSansSC-Regular.ttf",- "NotoSansSC-Regular",- "ttf")),- Map.entry(- FALLBACK_FONT_JP_ID,- new FallbackFontSpec(- "classpath:/static/fonts/NotoSansJP-Regular.ttf",- "NotoSansJP-Regular",- "ttf")),- Map.entry(- FALLBACK_FONT_KR_ID,- new FallbackFontSpec(- "classpath:/static/fonts/NotoSansKR-Regular.ttf",- "NotoSansKR-Regular",- "ttf")),- Map.entry(- FALLBACK_FONT_TC_ID,- new FallbackFontSpec(- "classpath:/static/fonts/NotoSansTC-Regular.ttf",- "NotoSansTC-Regular",- "ttf")),- Map.entry(- FALLBACK_FONT_AR_ID,- new FallbackFontSpec(- "classpath:/static/fonts/NotoSansArabic-Regular.ttf",- "NotoSansArabic-Regular",- "ttf")),- Map.entry(- FALLBACK_FONT_TH_ID,- new FallbackFontSpec(- "classpath:/static/fonts/NotoSansThai-Regular.ttf",- "NotoSansThai-Regular",- "ttf")),- Map.entry(- FALLBACK_FONT_DEVANAGARI_ID,- new FallbackFontSpec(- "classpath:/static/fonts/NotoSansDevanagari-Regular.ttf",- "NotoSansDevanagari-Regular",- "ttf")),- Map.entry(- FALLBACK_FONT_MALAYALAM_ID,- new FallbackFontSpec(- "classpath:/static/fonts/NotoSansMalayalam-Regular.ttf",- "NotoSansMalayalam-Regular",- "ttf")),- Map.entry(- FALLBACK_FONT_TIBETAN_ID,- new FallbackFontSpec(- "classpath:/static/fonts/NotoSerifTibetan-Regular.ttf",- "NotoSerifTibetan-Regular",- "ttf")),- // Liberation Sans family- Map.entry(- "fallback-liberation-sans",- new FallbackFontSpec(- "classpath:/static/fonts/LiberationSans-Regular.ttf",- "LiberationSans-Regular",- "ttf")),- Map.entry(- "fallback-liberation-sans-bold",- new FallbackFontSpec(- "classpath:/static/fonts/LiberationSans-Bold.ttf",- "LiberationSans-Bold",- "ttf")),- Map.entry(- "fallback-liberation-sans-italic",- new FallbackFontSpec(- "classpath:/static/fonts/LiberationSans-Italic.ttf",- "LiberationSans-Italic",- "ttf")),- Map.entry(- "fallback-liberation-sans-bolditalic",- new FallbackFontSpec(- "classpath:/static/fonts/LiberationSans-BoldItalic.ttf",- "LiberationSans-BoldItalic",- "ttf")),- // Liberation Serif family- Map.entry(- "fallback-liberation-serif",- new FallbackFontSpec(- "classpath:/static/fonts/LiberationSerif-Regular.ttf",- "LiberationSerif-Regular",- "ttf")),- Map.entry(- "fallback-liberation-serif-bold",- new FallbackFontSpec(- "classpath:/static/fonts/LiberationSerif-Bold.ttf",- "LiberationSerif-Bold",- "ttf")),- Map.entry(- "fallback-liberation-serif-italic",- new FallbackFontSpec(- "classpath:/static/fonts/LiberationSerif-Italic.ttf",- "LiberationSerif-Italic",- "ttf")),- Map.entry(- "fallback-liberation-serif-bolditalic",- new FallbackFontSpec(- "classpath:/static/fonts/LiberationSerif-BoldItalic.ttf",- "LiberationSerif-BoldItalic",- "ttf")),- // Liberation Mono family- Map.entry(- "fallback-liberation-mono",- new FallbackFontSpec(- "classpath:/static/fonts/LiberationMono-Regular.ttf",- "LiberationMono-Regular",- "ttf")),- Map.entry(- "fallback-liberation-mono-bold",- new FallbackFontSpec(- "classpath:/static/fonts/LiberationMono-Bold.ttf",- "LiberationMono-Bold",- "ttf")),- Map.entry(- "fallback-liberation-mono-italic",- new FallbackFontSpec(- "classpath:/static/fonts/LiberationMono-Italic.ttf",- "LiberationMono-Italic",- "ttf")),- Map.entry(- "fallback-liberation-mono-bolditalic",- new FallbackFontSpec(- "classpath:/static/fonts/LiberationMono-BoldItalic.ttf",- "LiberationMono-BoldItalic",- "ttf")),- // Noto Sans family (enhanced with weight variants)- Map.entry(- FALLBACK_FONT_ID,- new FallbackFontSpec(- DEFAULT_FALLBACK_FONT_LOCATION, "NotoSans-Regular", "ttf")),- Map.entry(- "fallback-noto-sans-bold",- new FallbackFontSpec(- "classpath:/static/fonts/NotoSans-Bold.ttf",- "NotoSans-Bold",- "ttf")),- Map.entry(- "fallback-noto-sans-italic",- new FallbackFontSpec(- "classpath:/static/fonts/NotoSans-Italic.ttf",- "NotoSans-Italic",- "ttf")),- Map.entry(- "fallback-noto-sans-bolditalic",- new FallbackFontSpec(- "classpath:/static/fonts/NotoSans-BoldItalic.ttf",- "NotoSans-BoldItalic",- "ttf")),- // DejaVu Sans family- Map.entry(- "fallback-dejavu-sans",- new FallbackFontSpec(- "classpath:/static/fonts/DejaVuSans.ttf", "DejaVuSans", "ttf")),- Map.entry(- "fallback-dejavu-sans-bold",- new FallbackFontSpec(- "classpath:/static/fonts/DejaVuSans-Bold.ttf",- "DejaVuSans-Bold",- "ttf")),- Map.entry(- "fallback-dejavu-sans-oblique",- new FallbackFontSpec(- "classpath:/static/fonts/DejaVuSans-Oblique.ttf",- "DejaVuSans-Oblique",- "ttf")),- Map.entry(- "fallback-dejavu-sans-boldoblique",- new FallbackFontSpec(- "classpath:/static/fonts/DejaVuSans-BoldOblique.ttf",- "DejaVuSans-BoldOblique",- "ttf")),- // DejaVu Serif family- Map.entry(- "fallback-dejavu-serif",- new FallbackFontSpec(- "classpath:/static/fonts/DejaVuSerif.ttf",- "DejaVuSerif",- "ttf")),- Map.entry(- "fallback-dejavu-serif-bold",- new FallbackFontSpec(- "classpath:/static/fonts/DejaVuSerif-Bold.ttf",- "DejaVuSerif-Bold",- "ttf")),- Map.entry(- "fallback-dejavu-serif-italic",- new FallbackFontSpec(- "classpath:/static/fonts/DejaVuSerif-Italic.ttf",- "DejaVuSerif-Italic",- "ttf")),- Map.entry(- "fallback-dejavu-serif-bolditalic",- new FallbackFontSpec(- "classpath:/static/fonts/DejaVuSerif-BoldItalic.ttf",- "DejaVuSerif-BoldItalic",- "ttf")),- // DejaVu Mono family- Map.entry(- "fallback-dejavu-mono",- new FallbackFontSpec(- "classpath:/static/fonts/DejaVuSansMono.ttf",- "DejaVuSansMono",- "ttf")),- Map.entry(- "fallback-dejavu-mono-bold",- new FallbackFontSpec(- "classpath:/static/fonts/DejaVuSansMono-Bold.ttf",- "DejaVuSansMono-Bold",- "ttf")),- Map.entry(- "fallback-dejavu-mono-oblique",- new FallbackFontSpec(- "classpath:/static/fonts/DejaVuSansMono-Oblique.ttf",- "DejaVuSansMono-Oblique",- "ttf")),- Map.entry(- "fallback-dejavu-mono-boldoblique",- new FallbackFontSpec(- "classpath:/static/fonts/DejaVuSansMono-BoldOblique.ttf",- "DejaVuSansMono-BoldOblique",- "ttf")));- private static final Pattern BOLD_FONT_WEIGHT_PATTERN =- Pattern.compile(".*[_-]?[6-9]00(wght)?.*");- private static final Pattern FONT_NAME_DELIMITER_PATTERN = Pattern.compile("[-_,+]");- private static final Pattern WHITESPACE_PATTERN = Pattern.compile("\\s+");- private static final Pattern PATTERN = Pattern.compile("^[A-Z]{6}\\+");-- private final ResourceLoader resourceLoader;- private final stirling.software.common.model.ApplicationProperties applicationProperties;-- @Value("${stirling.pdf.fallback-font:" + DEFAULT_FALLBACK_FONT_LOCATION + "}")- private String legacyFallbackFontLocation;-- private String fallbackFontLocation;-- private final Map<String, byte[]> fallbackFontCache = new ConcurrentHashMap<>();-- @jakarta.annotation.PostConstruct- private void loadConfig() {- String configured = null;- if (applicationProperties.getPdfEditor() != null) {- configured = applicationProperties.getPdfEditor().getFallbackFont();- }- if (configured != null && !configured.isBlank()) {- fallbackFontLocation = configured;- } else {- fallbackFontLocation = legacyFallbackFontLocation;- }- log.info("Using fallback font location: {}", fallbackFontLocation);- }-- public PdfJsonFont buildFallbackFontModel() throws IOException {- return buildFallbackFontModel(FALLBACK_FONT_ID);- }-- public PdfJsonFont buildFallbackFontModel(String fallbackId) throws IOException {- FallbackFontSpec spec = getFallbackFontSpec(fallbackId);- if (spec == null) {- throw new IOException("Unknown fallback font id " + fallbackId);- }- byte[] bytes = loadFallbackFontBytes(fallbackId, spec);- String base64 = java.util.Base64.getEncoder().encodeToString(bytes);- return PdfJsonFont.builder()- .id(fallbackId)- .uid(fallbackId)- .baseName(spec.baseName())- .subtype("TrueType")- .embedded(true)- .program(base64)- .programFormat(spec.format())- .build();- }-- public PDFont loadFallbackPdfFont(PDDocument document) throws IOException {- return loadFallbackPdfFont(document, FALLBACK_FONT_ID);- }-- public PDFont loadFallbackPdfFont(PDDocument document, String fallbackId) throws IOException {- FallbackFontSpec spec = getFallbackFontSpec(fallbackId);- if (spec == null) {- throw new IOException("Unknown fallback font id " + fallbackId);- }- byte[] bytes = loadFallbackFontBytes(fallbackId, spec);- try (InputStream stream = new ByteArrayInputStream(bytes)) {- // Load with embedSubset=false to ensure full glyph coverage- // Fallback fonts need all glyphs available for substituting missing characters- return PDType0Font.load(document, stream, false);- }- }-- public boolean canEncodeFully(PDFont font, String text) {- return canEncode(font, text);- }-- public boolean canEncode(PDFont font, int codePoint) {- return canEncode(font, new String(Character.toChars(codePoint)));- }-- public boolean canEncode(PDFont font, String text) {- if (font == null || text == null || text.isEmpty()) {- return false;- }- if (font instanceof PDType3Font) {- return false;- }- try {- font.encode(text);- return true;- } catch (IOException | IllegalArgumentException | UnsupportedOperationException ex) {- // Only log at debug level to reduce verbosity - summary is logged elsewhere- log.debug(- "[FONT-DEBUG] Font {} cannot encode text '{}' ({}): {}",- font != null ? font.getName() : "null",- text,- font != null ? font.getClass().getSimpleName() : "null",- ex.getMessage());- return false;- }- }-- /**- * Resolve fallback font ID based on the original font name and code point. Attempts to match- * font family and weight/style for visual consistency.- *- * @param originalFontName the name of the original font (may be null)- * @param codePoint the Unicode code point that needs to be rendered- * @return fallback font ID- */- public String resolveFallbackFontId(String originalFontName, int codePoint) {- // First try to match based on original font name for visual consistency- if (originalFontName != null && !originalFontName.isEmpty()) {- // Normalize font name: remove subset prefix (e.g. "PXAAAC+"), convert to lowercase,- // remove spaces- String normalized =- WHITESPACE_PATTERN- .matcher(- PATTERN.matcher(originalFontName)- .replaceAll("") // Remove subset prefix- .toLowerCase())- .replaceAll(""); // Remove spaces (e.g. "Times New Roman" ->- // "timesnewroman")-- // Extract base name without weight/style suffixes- // Split on common delimiters: hyphen, underscore, comma, plus- // Handles: "Arimo_700wght" -> "arimo", "Arial-Bold" -> "arial", "Arial,Bold" -> "arial"- String baseName = FONT_NAME_DELIMITER_PATTERN.split(normalized)[0];-- String aliasedFontId = FONT_NAME_ALIASES.get(baseName);- if (aliasedFontId != null) {- // Detect weight and style from the normalized font name- boolean isBold = detectBold(normalized);- boolean isItalic = detectItalic(normalized);-- // Apply weight/style suffix to fallback font ID- String styledFontId = applyWeightStyle(aliasedFontId, isBold, isItalic);-- log.debug(- "Matched font '{}' (normalized: '{}', base: '{}', bold: {}, italic: {}) to fallback '{}'",- originalFontName,- normalized,- baseName,- isBold,- isItalic,- styledFontId);- return styledFontId;- }- }-- // Fall back to Unicode-based selection- return resolveFallbackFontId(codePoint);- }-- /**- * Detect if font name indicates bold weight.- *- * @param normalizedFontName lowercase font name without subset prefix or spaces- * @return true if bold weight is detected- */- private boolean detectBold(String normalizedFontName) {- // Check for explicit bold indicators- if (normalizedFontName.contains("bold")- || normalizedFontName.contains("heavy")- || normalizedFontName.contains("black")) {- return true;- }-- // Check for numeric weight indicators (600-900 = bold)- // Handles: "Arimo_700wght", "Arial-700", "Font-w700"- if (BOLD_FONT_WEIGHT_PATTERN.matcher(normalizedFontName).matches()) {- return true;- }-- return false;- }-- /**- * Detect if font name indicates italic/oblique style.- *- * @param normalizedFontName lowercase font name without subset prefix or spaces- * @return true if italic style is detected- */- private boolean detectItalic(String normalizedFontName) {- return normalizedFontName.contains("italic") || normalizedFontName.contains("oblique");- }-- /**- * Apply weight/style suffix to fallback font ID.- *- * <p>Weight/style variants are only applied to font families where we have the actual font- * files available. Currently supported: - Liberation Sans: Regular, Bold, Italic, BoldItalic- * (full support) - Liberation Serif: Regular, Bold, Italic, BoldItalic (full support) -- * Liberation Mono: Regular, Bold, Italic, BoldItalic (full support) - Noto Sans: Regular, Bold,- * Italic, BoldItalic (full support) - DejaVu Sans: Regular, Bold, Oblique, BoldOblique (full- * support) - DejaVu Serif: Regular, Bold, Italic, BoldItalic (full support) - DejaVu Mono:- * Regular, Bold, Oblique, BoldOblique (full support)- *- * <p>To add weight/style support for additional font families: 1. Download the font files- * (Bold, Italic, BoldItalic) to: app/core/src/main/resources/static/fonts/ 2. Register the- * variants in BUILT_IN_FALLBACK_FONTS map (see lines 63-267) 3. Update the check below to- * include the font family prefix- *- * @param baseFontId base fallback font ID (e.g., "fallback-liberation-sans")- * @param isBold true if bold weight needed- * @param isItalic true if italic style needed- * @return styled font ID (e.g., "fallback-liberation-sans-bold"), or base ID if variants not- * available- */- private String applyWeightStyle(String baseFontId, boolean isBold, boolean isItalic) {- // Only apply weight/style to font families where we have the font files available- // Supported: Liberation (Sans/Serif/Mono), Noto Sans, DejaVu (Sans/Serif/Mono)- boolean isSupported =- baseFontId.startsWith("fallback-liberation-")- || "fallback-noto-sans".equals(baseFontId)- || baseFontId.startsWith("fallback-dejavu-");-- if (!isSupported) {- return baseFontId;- }-- // DejaVu Sans and Mono use "oblique" instead of "italic"- boolean useOblique =- "fallback-dejavu-sans".equals(baseFontId)- || "fallback-dejavu-mono".equals(baseFontId);-- if (isBold && isItalic) {- return baseFontId + (useOblique ? "-boldoblique" : "-bolditalic");- } else if (isBold) {- return baseFontId + "-bold";- } else if (isItalic) {- return baseFontId + (useOblique ? "-oblique" : "-italic");- }-- return baseFontId;- }-- /**- * Resolve fallback font ID based on Unicode code point properties.- *- * @param codePoint the Unicode code point- * @return fallback font ID- */- public String resolveFallbackFontId(int codePoint) {- Character.UnicodeBlock block = Character.UnicodeBlock.of(codePoint);-- // Bopomofo is primarily used in Taiwan for Traditional Chinese phonetic annotation- if (block == Character.UnicodeBlock.BOPOMOFO- || block == Character.UnicodeBlock.BOPOMOFO_EXTENDED) {- return FALLBACK_FONT_TC_ID;- }-- // Compatibility ideographs are primarily used by Traditional Chinese encodings (e.g., Big5,- // HKSCS) so prefer the Traditional Chinese fallback here.- if (block == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS- || block == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS_SUPPLEMENT) {- return FALLBACK_FONT_TC_ID;- }-- if (block == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS- || block == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A- || block == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B- || block == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_C- || block == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_D- || block == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_E- || block == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_F- || block == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION- || block == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {- return FALLBACK_FONT_CJK_ID;- }-- Character.UnicodeScript script = Character.UnicodeScript.of(codePoint);- return switch (script) {- // HAN script is used by both Simplified and Traditional Chinese- // Default to Simplified (mainland China, 1.4B speakers) as it's more common- // Traditional Chinese PDFs are detected via font name aliases (MingLiU, PMingLiU,- // etc.)- case HAN -> FALLBACK_FONT_CJK_ID;- case HIRAGANA, KATAKANA -> FALLBACK_FONT_JP_ID;- case HANGUL -> FALLBACK_FONT_KR_ID;- case ARABIC -> FALLBACK_FONT_AR_ID;- case THAI -> FALLBACK_FONT_TH_ID;- case DEVANAGARI -> FALLBACK_FONT_DEVANAGARI_ID;- case MALAYALAM -> FALLBACK_FONT_MALAYALAM_ID;- case TIBETAN -> FALLBACK_FONT_TIBETAN_ID;- default -> FALLBACK_FONT_ID;- };- }-- public String mapUnsupportedGlyph(int codePoint) {- return switch (codePoint) {- case 0x276E -> "<";- case 0x276F -> ">";- default -> null;- };- }-- private FallbackFontSpec getFallbackFontSpec(String fallbackId) {- if (FALLBACK_FONT_ID.equals(fallbackId)) {- String baseName = inferBaseName(fallbackFontLocation, "NotoSans-Regular");- String format = inferFormat(fallbackFontLocation, "ttf");- return new FallbackFontSpec(fallbackFontLocation, baseName, format);- }- return BUILT_IN_FALLBACK_FONTS.get(fallbackId);- }-- private byte[] loadFallbackFontBytes(String fallbackId, FallbackFontSpec spec)- throws IOException {- if (spec == null) {- throw new IOException("No fallback font specification for " + fallbackId);- }- byte[] cached = fallbackFontCache.get(fallbackId);- if (cached != null) {- return cached;- }- Resource resource = resourceLoader.getResource(spec.resourceLocation());- if (!resource.exists()) {- throw new IOException("Fallback font resource not found at " + spec.resourceLocation());- }- try (InputStream inputStream = resource.getInputStream();- ByteArrayOutputStream baos = new ByteArrayOutputStream()) {- inputStream.transferTo(baos);- byte[] bytes = baos.toByteArray();- fallbackFontCache.put(fallbackId, bytes);- return bytes;- }- }-- private String inferBaseName(String location, String defaultName) {- if (location == null || location.isBlank()) {- return defaultName;- }- int slash = location.lastIndexOf('/');- String fileName = slash >= 0 ? location.substring(slash + 1) : location;- int dot = fileName.lastIndexOf('.');- if (dot > 0) {- fileName = fileName.substring(0, dot);- }- return fileName.isEmpty() ? defaultName : fileName;- }-- private String inferFormat(String location, String defaultFormat) {- if (location == null || location.isBlank()) {- return defaultFormat;- }- int dot = location.lastIndexOf('.');- if (dot >= 0 && dot < location.length() - 1) {- return location.substring(dot + 1).toLowerCase(Locale.ROOT);- }- return defaultFormat;- }-- private record FallbackFontSpec(String resourceLocation, String baseName, String format) {}-}diff --git a/app/core/src/main/java/stirling/software/SPDF/service/pdfjson/PdfJsonFontService.java b/app/core/src/main/java/stirling/software/SPDF/service/pdfjson/PdfJsonFontService.javadeleted file mode 100644index 3cd7fa4acb..0000000000--- a/app/core/src/main/java/stirling/software/SPDF/service/pdfjson/PdfJsonFontService.java+++ /dev/null@@ -1,380 +0,0 @@-package stirling.software.SPDF.service.pdfjson;--import java.io.IOException;-import java.nio.file.Files;-import java.util.Base64;-import java.util.Locale;--import org.springframework.stereotype.Service;--import jakarta.annotation.PostConstruct;--import lombok.Getter;-import lombok.RequiredArgsConstructor;-import lombok.extern.slf4j.Slf4j;--import stirling.software.common.util.ProcessExecutor;-import stirling.software.common.util.ProcessExecutor.ProcessExecutorResult;-import stirling.software.common.util.TempFile;-import stirling.software.common.util.TempFileManager;--@Slf4j-@Service-@RequiredArgsConstructor-public class PdfJsonFontService {-- private final TempFileManager tempFileManager;- private final stirling.software.common.model.ApplicationProperties applicationProperties;-- @Getter private boolean cffConversionEnabled;-- @Getter private String cffConverterMethod;-- private String pythonCommand;-- private String pythonScript;-- private String fontforgeCommand;-- private volatile boolean pythonCffConverterAvailable;- private volatile boolean fontForgeCffConverterAvailable;-- @PostConstruct- private void initialiseCffConverterAvailability() {- loadConfiguration();- if (!cffConversionEnabled) {- log.warn("[FONT-DEBUG] CFF conversion is DISABLED in configuration");- pythonCffConverterAvailable = false;- fontForgeCffConverterAvailable = false;- return;- }-- log.info("[FONT-DEBUG] CFF conversion enabled, checking tool availability...");- pythonCffConverterAvailable = isCommandAvailable(pythonCommand);- if (!pythonCffConverterAvailable) {- log.warn(- "[FONT-DEBUG] Python command '{}' not found; Python CFF conversion disabled",- pythonCommand);- } else {- log.info("[FONT-DEBUG] Python command '{}' is available", pythonCommand);- }-- fontForgeCffConverterAvailable = isCommandAvailable(fontforgeCommand);- if (!fontForgeCffConverterAvailable) {- log.warn(- "[FONT-DEBUG] FontForge command '{}' not found; FontForge CFF conversion disabled",- fontforgeCommand);- } else {- log.info("[FONT-DEBUG] FontForge command '{}' is available", fontforgeCommand);- }-- log.info("[FONT-DEBUG] Selected CFF converter method: {}", cffConverterMethod);- }-- private void loadConfiguration() {- if (applicationProperties.getPdfEditor() != null- && applicationProperties.getPdfEditor().getCffConverter() != null) {- var cfg = applicationProperties.getPdfEditor().getCffConverter();- this.cffConversionEnabled = cfg.isEnabled();- this.cffConverterMethod = cfg.getMethod();- this.pythonCommand = cfg.getPythonCommand();- this.pythonScript = cfg.getPythonScript();- this.fontforgeCommand = cfg.getFontforgeCommand();- } else {- // Use defaults when config is not available- this.cffConversionEnabled = false;- log.warn("[FONT-DEBUG] PdfEditor configuration not available, CFF conversion disabled");- }- }-- public byte[] convertCffProgramToTrueType(byte[] fontBytes, String toUnicode) {- if (!cffConversionEnabled || fontBytes == null || fontBytes.length == 0) {- log.warn(- "[FONT-DEBUG] CFF conversion skipped: enabled={}, bytes={}",- cffConversionEnabled,- fontBytes == null ? "null" : fontBytes.length);- return null;- }-- log.info(- "[FONT-DEBUG] Converting CFF font: {} bytes, method: {}",- fontBytes.length,- cffConverterMethod);-- if ("python".equalsIgnoreCase(cffConverterMethod)) {- if (!pythonCffConverterAvailable) {- log.debug("[FONT-DEBUG] Python CFF converter not available, skipping conversion");- return null;- }- byte[] result = convertCffUsingPython(fontBytes, toUnicode);- log.debug(- "[FONT-DEBUG] Python conversion result: {}",- result == null ? "null" : result.length + " bytes");- return result;- } else if ("fontforge".equalsIgnoreCase(cffConverterMethod)) {- if (!fontForgeCffConverterAvailable) {- log.debug(- "[FONT-DEBUG] FontForge CFF converter not available, skipping conversion");- return null;- }- byte[] result = convertCffUsingFontForge(fontBytes);- log.debug(- "[FONT-DEBUG] FontForge conversion result: {}",- result == null ? "null" : result.length + " bytes");- return result;- } else {- log.debug(- "[FONT-DEBUG] Unknown CFF converter method: {}, falling back to Python",- cffConverterMethod);- if (!pythonCffConverterAvailable) {- log.debug("[FONT-DEBUG] Python CFF converter not available, skipping conversion");- return null;- }- byte[] result = convertCffUsingPython(fontBytes, toUnicode);- log.debug(- "[FONT-DEBUG] Python conversion result: {}",- result == null ? "null" : result.length + " bytes");- return result;- }- }-- public String detectFontFlavor(byte[] fontBytes) {- if (fontBytes == null || fontBytes.length < 4) {- return null;- }- int signature =- ((fontBytes[0] & 0xFF) << 24)- | ((fontBytes[1] & 0xFF) << 16)- | ((fontBytes[2] & 0xFF) << 8)- | (fontBytes[3] & 0xFF);- if (signature == 0x00010000 || signature == 0x74727565) {- return "ttf";- }- if (signature == 0x4F54544F) {- return "otf";- }- if (signature == 0x74746366) {- log.debug("[FONT-DEBUG] TrueType Collection ('ttcf') font program is unsupported");- return null;- }- return null;- }-- public String detectTrueTypeFormat(byte[] data) {- if (data == null || data.length < 4) {- return null;- }- int signature =- ((data[0] & 0xFF) << 24)- | ((data[1] & 0xFF) << 16)- | ((data[2] & 0xFF) << 8)- | (data[3] & 0xFF);- if (signature == 0x00010000) {- return "ttf";- }- if (signature == 0x4F54544F) {- return "otf";- }- if (signature == 0x74746366) {- log.debug("[FONT-DEBUG] TrueType Collection ('ttcf') FontFile2 is unsupported");- return null;- }- return null;- }-- public String validateFontTables(byte[] fontBytes) {- if (fontBytes == null || fontBytes.length < 12) {- return "Font program too small";- }- int numTables = ((fontBytes[4] & 0xFF) << 8) | (fontBytes[5] & 0xFF);- if (numTables <= 0 || numTables > 512) {- return "Invalid numTables: " + numTables;- }- return null;- }-- public boolean isCffFontProgram(byte[] fontBytes) {- if (fontBytes == null || fontBytes.length < 4) {- return false;- }- int majorVersion = fontBytes[0] & 0xFF;- int headerSize = fontBytes[2] & 0xFF;- int offsetSize = fontBytes[3] & 0xFF;- return majorVersion == 1- && headerSize >= 4- && headerSize <= fontBytes.length- && offsetSize >= 1- && offsetSize <= 4;- }-- private byte[] convertCffUsingPython(byte[] fontBytes, String toUnicode) {- if (!pythonCffConverterAvailable) {- log.debug("[FONT-DEBUG] Python CFF converter not available");- return null;- }- if (pythonCommand == null- || pythonCommand.isBlank()- || pythonScript == null- || pythonScript.isBlank()) {- log.debug("[FONT-DEBUG] Python converter not configured");- return null;- }-- log.debug(- "[FONT-DEBUG] Running Python CFF converter: command={}, script={}",- pythonCommand,- pythonScript);-- try (TempFile inputFile = new TempFile(tempFileManager, ".cff");- TempFile outputFile = new TempFile(tempFileManager, ".otf");- TempFile toUnicodeFile =- toUnicode != null ? new TempFile(tempFileManager, ".tounicode") : null) {- Files.write(inputFile.getPath(), fontBytes);- if (toUnicodeFile != null) {- try {- byte[] toUnicodeBytes = Base64.getDecoder().decode(toUnicode);- Files.write(toUnicodeFile.getPath(), toUnicodeBytes);- } catch (IllegalArgumentException ex) {- log.debug(- "[FONT-DEBUG] Failed to decode ToUnicode data for CFF conversion: {}",- ex.getMessage());- return null;- }- }-- String[] command =- buildPythonCommand(- inputFile.getAbsolutePath(),- outputFile.getAbsolutePath(),- toUnicodeFile != null ? toUnicodeFile.getAbsolutePath() : null);- log.debug("[FONT-DEBUG] Executing: {}", String.join(" ", command));-- ProcessExecutorResult result =- ProcessExecutor.getInstance(ProcessExecutor.Processes.CFF_CONVERTER)- .runCommandWithOutputHandling(java.util.Arrays.asList(command));-- if (result.getRc() != 0) {- log.error(- "[FONT-DEBUG] Python CFF conversion failed with exit code: {}",- result.getRc());- log.error("[FONT-DEBUG] Stdout: {}", result.getMessages());- return null;- }- if (!Files.exists(outputFile.getPath())) {- log.error("[FONT-DEBUG] Python CFF conversion produced no output file");- return null;- }- byte[] data = Files.readAllBytes(outputFile.getPath());- if (data.length == 0) {- log.error("[FONT-DEBUG] Python CFF conversion returned empty output");- return null;- }- log.info(- "[FONT-DEBUG] Python CFF conversion succeeded: {} bytes -> {} bytes",- fontBytes.length,- data.length);- return data;- } catch (IOException | InterruptedException ex) {- if (ex instanceof InterruptedException) {- Thread.currentThread().interrupt();- }- log.error("[FONT-DEBUG] Python CFF conversion exception: {}", ex.getMessage(), ex);- return null;- }- }-- public byte[] convertCffUsingFontForge(byte[] fontBytes) {- if (!fontForgeCffConverterAvailable) {- log.debug("FontForge CFF converter not available");- return null;- }- if (!isCffFontProgram(fontBytes)) {- log.warn("Font program labelled as CFF has no CFF header; skipping FontForge");- return null;- }-- try (TempFile inputFile = new TempFile(tempFileManager, ".cff");- TempFile outputFile = new TempFile(tempFileManager, ".ttf")) {- Files.write(inputFile.getPath(), fontBytes);-- ProcessExecutorResult result =- ProcessExecutor.getInstance(ProcessExecutor.Processes.CFF_CONVERTER)- .runCommandWithOutputHandling(- java.util.Arrays.asList(- fontforgeCommand,- "-lang=ff",- "-c",- "Open($1); "- + "ScaleToEm(1000); "- + "SelectWorthOutputting(); "- + "SetFontOrder(2); "- + "Reencode(\"unicode\"); "- + "RoundToInt(); "- + "RemoveOverlap(); "- + "Simplify(); "- + "CorrectDirection(); "- + "Generate($2, \"\", 4+16+32); "- + "Close(); "- + "Quit()",- inputFile.getAbsolutePath(),- outputFile.getAbsolutePath()));-- if (result.getRc() != 0) {- log.warn("FontForge CFF conversion failed: {}", result.getRc());- return null;- }- if (!Files.exists(outputFile.getPath())) {- log.warn("FontForge CFF conversion produced no output");- return null;- }- byte[] data = Files.readAllBytes(outputFile.getPath());- if (data.length == 0) {- log.warn("FontForge CFF conversion returned empty output");- return null;- }- return data;- } catch (IOException | InterruptedException ex) {- if (ex instanceof InterruptedException) {- Thread.currentThread().interrupt();- }- log.warn("FontForge CFF conversion failed: {}", ex.getMessage());- return null;- }- }-- private boolean isCommandAvailable(String command) {- if (command == null || command.isBlank()) {- return false;- }- try {- ProcessBuilder processBuilder = new ProcessBuilder();- if (System.getProperty("os.name").toLowerCase(Locale.ROOT).contains("windows")) {- processBuilder.command("where", command);- } else {- processBuilder.command("which", command);- }- Process process = processBuilder.start();- int exitCode = process.waitFor();- return exitCode == 0;- } catch (Exception e) {- log.debug("Error checking for command {}: {}", command, e.getMessage());- return false;- }- }-- private String[] buildPythonCommand(String input, String output, String toUnicode) {- if (toUnicode != null) {- return new String[] {- pythonCommand,- pythonScript,- "--input",- input,- "--output",- output,- "--to-unicode",- toUnicode- };- }- return new String[] {pythonCommand, pythonScript, "--input", input, "--output", output};- }-}diff --git a/app/core/src/main/java/stirling/software/SPDF/service/pdfjson/PdfJsonImageService.java b/app/core/src/main/java/stirling/software/SPDF/service/pdfjson/PdfJsonImageService.javadeleted file mode 100644index 4ac18596f2..0000000000--- a/app/core/src/main/java/stirling/software/SPDF/service/pdfjson/PdfJsonImageService.java+++ /dev/null@@ -1,474 +0,0 @@-package stirling.software.SPDF.service.pdfjson;--import java.awt.geom.AffineTransform;-import java.awt.geom.Point2D;-import java.awt.image.BufferedImage;-import java.io.ByteArrayOutputStream;-import java.io.IOException;-import java.util.ArrayList;-import java.util.Base64;-import java.util.IdentityHashMap;-import java.util.LinkedHashMap;-import java.util.List;-import java.util.Locale;-import java.util.Map;-import java.util.UUID;-import java.util.function.Consumer;--import javax.imageio.ImageIO;--import org.apache.pdfbox.contentstream.PDFGraphicsStreamEngine;-import org.apache.pdfbox.contentstream.operator.Operator;-import org.apache.pdfbox.contentstream.operator.OperatorName;-import org.apache.pdfbox.cos.COSBase;-import org.apache.pdfbox.cos.COSName;-import org.apache.pdfbox.pdmodel.PDDocument;-import org.apache.pdfbox.pdmodel.PDPage;-import org.apache.pdfbox.pdmodel.PDPageContentStream;-import org.apache.pdfbox.pdmodel.graphics.image.PDImage;-import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;-import org.apache.pdfbox.util.Matrix;-import org.springframework.stereotype.Service;--import lombok.extern.slf4j.Slf4j;--import stirling.software.SPDF.model.api.PdfJsonConversionProgress;-import stirling.software.SPDF.model.json.PdfJsonImageElement;--/**- * Service for handling PDF image operations for JSON conversion (extraction, encoding, rendering).- */-@Service-@Slf4j-public class PdfJsonImageService {-- private record EncodedImage(String base64, String format) {}-- private record Bounds(float left, float right, float bottom, float top) {- float width() {- return Math.max(0f, right - left);- }-- float height() {- return Math.max(0f, top - bottom);- }- }-- /**- * Collects images from all pages in a PDF document.- *- * @param document The PDF document- * @param totalPages Total number of pages- * @param progress Progress callback- * @return Map of page number to list of image elements- * @throws IOException If image extraction fails- */- public Map<Integer, List<PdfJsonImageElement>> collectImages(- PDDocument document, int totalPages, Consumer<PdfJsonConversionProgress> progress)- throws IOException {- Map<Integer, List<PdfJsonImageElement>> imagesByPage = new LinkedHashMap<>();- Map<COSBase, EncodedImage> imageCache = new IdentityHashMap<>();- int pageNumber = 1;- for (PDPage page : document.getPages()) {- ImageCollectingEngine engine =- new ImageCollectingEngine(page, pageNumber, imagesByPage, imageCache);- engine.processPage(page);-- // Update progress for image extraction (70-80%)- int imageProgress = 70 + (int) ((pageNumber / (double) totalPages) * 10);- progress.accept(- PdfJsonConversionProgress.of(- imageProgress, "images", "Extracting images", pageNumber, totalPages));- pageNumber++;- }- return imagesByPage;- }-- /**- * Extracts images from a single PDF page (for on-demand lazy loading).- *- * @param document The PDF document- * @param page The specific page to extract images from- * @param pageNumber The page number (1-indexed)- * @return List of image elements for this page- * @throws IOException If image extraction fails- */- public List<PdfJsonImageElement> extractImagesForPage(- PDDocument document, PDPage page, int pageNumber) throws IOException {- Map<Integer, List<PdfJsonImageElement>> imagesByPage = new LinkedHashMap<>();- ImageCollectingEngine engine =- new ImageCollectingEngine(page, pageNumber, imagesByPage, new IdentityHashMap<>());- engine.processPage(page);- return imagesByPage.getOrDefault(pageNumber, new ArrayList<>());- }-- /**- * Draws an image element on a PDF page content stream.- *- * @param contentStream The content stream to draw on- * @param document The PDF document- * @param element The image element to draw- * @param cache Cache of previously created image XObjects- * @throws IOException If drawing fails- */- public void drawImageElement(- PDPageContentStream contentStream,- PDDocument document,- PdfJsonImageElement element,- Map<String, PDImageXObject> cache)- throws IOException {- if (element == null || element.getImageData() == null || element.getImageData().isBlank()) {- return;- }-- String cacheKey =- element.getId() != null && !element.getId().isBlank()- ? element.getId()- : Integer.toHexString(System.identityHashCode(element));- PDImageXObject image = cache.get(cacheKey);- if (image == null) {- image = createImageXObject(document, element);- if (image == null) {- return;- }- cache.put(cacheKey, image);- }-- float[] transform = element.getTransform();- if (transform != null && transform.length == 6) {- Matrix matrix =- new Matrix(- safeFloat(transform[0], 1f),- safeFloat(transform[1], 0f),- safeFloat(transform[2], 0f),- safeFloat(transform[3], 1f),- safeFloat(transform[4], 0f),- safeFloat(transform[5], 0f));- contentStream.drawImage(image, matrix);- return;- }-- float width = safeFloat(element.getWidth(), fallbackWidth(element));- float height = safeFloat(element.getHeight(), fallbackHeight(element));- if (width <= 0f) {- width = Math.max(1f, fallbackWidth(element));- }- if (height <= 0f) {- height = Math.max(1f, fallbackHeight(element));- }- float left = resolveLeft(element, width);- float bottom = resolveBottom(element, height);-- contentStream.drawImage(image, left, bottom, width, height);- }-- /**- * Creates a PDImageXObject from a PdfJsonImageElement.- *- * @param document The PDF document- * @param element The image element with base64 data- * @return The created image XObject- * @throws IOException If image creation fails- */- public PDImageXObject createImageXObject(PDDocument document, PdfJsonImageElement element)- throws IOException {- byte[] data;- try {- data = Base64.getDecoder().decode(element.getImageData());- } catch (IllegalArgumentException ex) {- log.debug("Failed to decode image element: {}", ex.getMessage());- return null;- }- String name = element.getId() != null ? element.getId() : UUID.randomUUID().toString();- return PDImageXObject.createFromByteArray(document, data, name);- }-- private EncodedImage encodeImage(PDImage image) {- try {- BufferedImage bufferedImage = image.getImage();- if (bufferedImage == null) {- return null;- }- String format = resolveImageFormat(image);- if (format == null || format.isBlank()) {- format = "png";- }- ByteArrayOutputStream baos = new ByteArrayOutputStream();- boolean written = ImageIO.write(bufferedImage, format, baos);- if (!written) {- if (!"png".equalsIgnoreCase(format)) {- baos.reset();- if (!ImageIO.write(bufferedImage, "png", baos)) {- return null;- }- format = "png";- } else {- return null;- }- }- return new EncodedImage(Base64.getEncoder().encodeToString(baos.toByteArray()), format);- } catch (IOException ex) {- log.debug("Failed to encode image: {}", ex.getMessage());- return null;- }- }-- private String resolveImageFormat(PDImage image) {- if (image instanceof PDImageXObject xObject) {- String suffix = xObject.getSuffix();- if (suffix != null && !suffix.isBlank()) {- return suffix.toLowerCase(Locale.ROOT);- }- }- return "png";- }-- private float fallbackWidth(PdfJsonImageElement element) {- if (element.getRight() != null && element.getLeft() != null) {- return Math.max(0f, element.getRight() - element.getLeft());- }- if (element.getNativeWidth() != null) {- return element.getNativeWidth();- }- return 1f;- }-- private float fallbackHeight(PdfJsonImageElement element) {- if (element.getTop() != null && element.getBottom() != null) {- return Math.max(0f, element.getTop() - element.getBottom());- }- if (element.getNativeHeight() != null) {- return element.getNativeHeight();- }- return 1f;- }-- private float resolveLeft(PdfJsonImageElement element, float width) {- if (element.getLeft() != null) {- return element.getLeft();- }- if (element.getX() != null) {- return element.getX();- }- if (element.getRight() != null) {- return element.getRight() - width;- }- return 0f;- }-- private float resolveBottom(PdfJsonImageElement element, float height) {- if (element.getBottom() != null) {- return element.getBottom();- }- if (element.getY() != null) {- return element.getY();- }- if (element.getTop() != null) {- return element.getTop() - height;- }- return 0f;- }-- private float[] toMatrixValues(Matrix matrix) {- return new float[] {- matrix.getValue(0, 0),- matrix.getValue(0, 1),- matrix.getValue(1, 0),- matrix.getValue(1, 1),- matrix.getValue(2, 0),- matrix.getValue(2, 1)- };- }-- private static float safeFloat(Float value, float defaultValue) {- if (value == null || Float.isNaN(value) || Float.isInfinite(value)) {- return defaultValue;- }- return value;- }-- /**- * Inner engine that extends PDFGraphicsStreamEngine to collect images from PDF content streams.- */- private class ImageCollectingEngine extends PDFGraphicsStreamEngine {-- private final int pageNumber;- private final Map<Integer, List<PdfJsonImageElement>> imagesByPage;- private final Map<COSBase, EncodedImage> imageCache;-- private COSName currentXObjectName;- private int imageCounter = 0;-- protected ImageCollectingEngine(- PDPage page,- int pageNumber,- Map<Integer, List<PdfJsonImageElement>> imagesByPage,- Map<COSBase, EncodedImage> imageCache)- throws IOException {- super(page);- this.pageNumber = pageNumber;- this.imagesByPage = imagesByPage;- this.imageCache = imageCache;- }-- @Override- public void processPage(PDPage page) throws IOException {- super.processPage(page);- }-- @Override- public void drawImage(PDImage pdImage) throws IOException {- EncodedImage encoded = getOrEncodeImage(pdImage);- if (encoded == null) {- return;- }- Matrix ctm = getGraphicsState().getCurrentTransformationMatrix();- Bounds bounds = computeBounds(ctm);- float[] matrixValues = toMatrixValues(ctm);-- PdfJsonImageElement element =- PdfJsonImageElement.builder()- .id(UUID.randomUUID().toString())- .objectName(- currentXObjectName != null- ? currentXObjectName.getName()- : null)- .inlineImage(!(pdImage instanceof PDImageXObject))- .nativeWidth(pdImage.getWidth())- .nativeHeight(pdImage.getHeight())- .x(bounds.left)- .y(bounds.bottom)- .width(bounds.width())- .height(bounds.height())- .left(bounds.left)- .right(bounds.right)- .top(bounds.top)- .bottom(bounds.bottom)- .transform(matrixValues)- .zOrder(-1_000_000 + imageCounter)- .imageData(encoded.base64())- .imageFormat(encoded.format())- .build();- imageCounter++;- imagesByPage.computeIfAbsent(pageNumber, key -> new ArrayList<>()).add(element);- }-- @Override- public void appendRectangle(Point2D p0, Point2D p1, Point2D p2, Point2D p3)- throws IOException {- // Not needed for image extraction- }-- @Override- public void clip(int windingRule) throws IOException {- // Not needed for image extraction- }-- @Override- public void moveTo(float x, float y) throws IOException {- // Not needed for image extraction- }-- @Override- public void lineTo(float x, float y) throws IOException {- // Not needed for image extraction- }-- @Override- public void curveTo(float x1, float y1, float x2, float y2, float x3, float y3)- throws IOException {- // Not needed for image extraction- }-- @Override- public Point2D getCurrentPoint() throws IOException {- return new Point2D.Float();- }-- @Override- public void closePath() throws IOException {- // Not needed for image extraction- }-- @Override- public void endPath() throws IOException {- // Not needed for image extraction- }-- @Override- public void shadingFill(COSName shadingName) throws IOException {- // Not needed for image extraction- }-- @Override- public void fillAndStrokePath(int windingRule) throws IOException {- // Not needed for image extraction- }-- @Override- public void fillPath(int windingRule) throws IOException {- // Not needed for image extraction- }-- @Override- public void strokePath() throws IOException {- // Not needed for image extraction- }-- @Override- protected void processOperator(Operator operator, List<COSBase> operands)- throws IOException {- if (OperatorName.DRAW_OBJECT.equals(operator.getName())- && !operands.isEmpty()- && operands.getFirst() instanceof COSName name) {- currentXObjectName = name;- }- super.processOperator(operator, operands);- currentXObjectName = null;- }-- private EncodedImage getOrEncodeImage(PDImage pdImage) {- if (pdImage == null) {- return null;- }- if (pdImage instanceof PDImageXObject xObject) {- if (xObject.isStencil()) {- return encodeImage(pdImage);- }- COSBase key = xObject.getCOSObject();- EncodedImage cached = imageCache.get(key);- if (cached != null) {- return cached;- }- EncodedImage encoded = encodeImage(pdImage);- if (encoded != null) {- imageCache.put(key, encoded);- }- return encoded;- }- return encodeImage(pdImage);- }-- private Bounds computeBounds(Matrix ctm) {- AffineTransform transform = ctm.createAffineTransform();- Point2D.Float p0 = new Point2D.Float(0, 0);- Point2D.Float p1 = new Point2D.Float(1, 0);- Point2D.Float p2 = new Point2D.Float(0, 1);- Point2D.Float p3 = new Point2D.Float(1, 1);- transform.transform(p0, p0);- transform.transform(p1, p1);- transform.transform(p2, p2);- transform.transform(p3, p3);-- float minX = Math.min(Math.min(p0.x, p1.x), Math.min(p2.x, p3.x));- float maxX = Math.max(Math.max(p0.x, p1.x), Math.max(p2.x, p3.x));- float minY = Math.min(Math.min(p0.y, p1.y), Math.min(p2.y, p3.y));- float maxY = Math.max(Math.max(p0.y, p1.y), Math.max(p2.y, p3.y));-- if (!Float.isFinite(minX) || !Float.isFinite(minY)) {- return new Bounds(0f, 0f, 0f, 0f);- }- return new Bounds(minX, maxX, minY, maxY);- }- }-}diff --git a/app/core/src/main/java/stirling/software/SPDF/service/pdfjson/PdfJsonMetadataService.java b/app/core/src/main/java/stirling/software/SPDF/service/pdfjson/PdfJsonMetadataService.javadeleted file mode 100644index 8cbffd538e..0000000000--- a/app/core/src/main/java/stirling/software/SPDF/service/pdfjson/PdfJsonMetadataService.java+++ /dev/null@@ -1,148 +0,0 @@-package stirling.software.SPDF.service.pdfjson;--import java.io.ByteArrayInputStream;-import java.io.ByteArrayOutputStream;-import java.io.IOException;-import java.io.InputStream;-import java.time.Instant;-import java.time.format.DateTimeParseException;-import java.util.Base64;-import java.util.Calendar;-import java.util.Optional;-import java.util.TimeZone;--import org.apache.pdfbox.pdmodel.PDDocument;-import org.apache.pdfbox.pdmodel.PDDocumentInformation;-import org.apache.pdfbox.pdmodel.common.PDMetadata;-import org.springframework.stereotype.Service;--import lombok.extern.slf4j.Slf4j;--import stirling.software.SPDF.model.json.PdfJsonMetadata;--/** Service for extracting and applying PDF metadata (document info and XMP) for JSON conversion. */-@Service-@Slf4j-public class PdfJsonMetadataService {-- /**- * Extracts document information metadata from a PDF.- *- * @param document The PDF document- * @return Metadata model with document info- */- public PdfJsonMetadata extractMetadata(PDDocument document) {- PdfJsonMetadata metadata = new PdfJsonMetadata();- PDDocumentInformation info = document.getDocumentInformation();- if (info != null) {- metadata.setTitle(info.getTitle());- metadata.setAuthor(info.getAuthor());- metadata.setSubject(info.getSubject());- metadata.setKeywords(info.getKeywords());- metadata.setCreator(info.getCreator());- metadata.setProducer(info.getProducer());- metadata.setCreationDate(formatCalendar(info.getCreationDate()));- metadata.setModificationDate(formatCalendar(info.getModificationDate()));- metadata.setTrapped(info.getTrapped());- }- metadata.setNumberOfPages(document.getNumberOfPages());- return metadata;- }-- /**- * Extracts XMP metadata from a PDF as base64-encoded string.- *- * @param document The PDF document- * @return Base64-encoded XMP metadata, or null if not present- */- public String extractXmpMetadata(PDDocument document) {- if (document.getDocumentCatalog() == null) {- return null;- }- PDMetadata metadata = document.getDocumentCatalog().getMetadata();- if (metadata == null) {- return null;- }- try (InputStream inputStream = metadata.createInputStream();- ByteArrayOutputStream baos = new ByteArrayOutputStream()) {- inputStream.transferTo(baos);- byte[] data = baos.toByteArray();- if (data.length == 0) {- return null;- }- return Base64.getEncoder().encodeToString(data);- } catch (IOException ex) {- log.debug("Failed to extract XMP metadata: {}", ex.getMessage());- return null;- }- }-- /**- * Applies metadata to a PDF document.- *- * @param document The PDF document- * @param metadata The metadata to apply- */- public void applyMetadata(PDDocument document, PdfJsonMetadata metadata) {- if (metadata == null) {- return;- }- PDDocumentInformation info = document.getDocumentInformation();- info.setTitle(metadata.getTitle());- info.setAuthor(metadata.getAuthor());- info.setSubject(metadata.getSubject());- info.setKeywords(metadata.getKeywords());- info.setCreator(metadata.getCreator());- info.setProducer(metadata.getProducer());- if (metadata.getCreationDate() != null) {- parseInstant(metadata.getCreationDate())- .ifPresent(instant -> info.setCreationDate(toCalendar(instant)));- }- if (metadata.getModificationDate() != null) {- parseInstant(metadata.getModificationDate())- .ifPresent(instant -> info.setModificationDate(toCalendar(instant)));- }- info.setTrapped(metadata.getTrapped());- }-- /**- * Applies XMP metadata to a PDF document from base64-encoded string.- *- * @param document The PDF document- * @param base64 Base64-encoded XMP metadata- */- public void applyXmpMetadata(PDDocument document, String base64) {- if (base64 == null || base64.isBlank()) {- return;- }- try (InputStream inputStream =- new ByteArrayInputStream(Base64.getDecoder().decode(base64))) {- PDMetadata metadata = new PDMetadata(document, inputStream);- document.getDocumentCatalog().setMetadata(metadata);- } catch (IllegalArgumentException | IOException ex) {- log.debug("Failed to apply XMP metadata: {}", ex.getMessage());- }- }-- private String formatCalendar(Calendar calendar) {- if (calendar == null) {- return null;- }- return calendar.toInstant().toString();- }-- private Optional<Instant> parseInstant(String value) {- try {- return Optional.of(Instant.parse(value));- } catch (DateTimeParseException ex) {- log.warn("Failed to parse instant '{}': {}", value, ex.getMessage());- return Optional.empty();- }- }-- private Calendar toCalendar(Instant instant) {- Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));- calendar.setTimeInMillis(instant.toEpochMilli());- return calendar;- }-}diff --git a/app/core/src/main/java/stirling/software/SPDF/service/pdfjson/PdfLazyLoadingService.java b/app/core/src/main/java/stirling/software/SPDF/service/pdfjson/PdfLazyLoadingService.javadeleted file mode 100644index ba0f2c2ce0..0000000000--- a/app/core/src/main/java/stirling/software/SPDF/service/pdfjson/PdfLazyLoadingService.java+++ /dev/null@@ -1,311 +0,0 @@-package stirling.software.SPDF.service.pdfjson;--import java.io.IOException;-import java.io.OutputStream;-import java.util.ArrayList;-import java.util.Comparator;-import java.util.List;-import java.util.Map;-import java.util.concurrent.ConcurrentHashMap;-import java.util.concurrent.TimeUnit;-import java.util.function.Consumer;--import org.apache.pdfbox.cos.COSBase;-import org.apache.pdfbox.cos.COSName;-import org.apache.pdfbox.pdmodel.PDDocument;-import org.apache.pdfbox.pdmodel.PDPage;-import org.apache.pdfbox.pdmodel.common.PDRectangle;-import org.apache.pdfbox.pdmodel.font.PDFont;-import org.springframework.stereotype.Service;-import org.springframework.web.multipart.MultipartFile;--import lombok.Data;-import lombok.RequiredArgsConstructor;-import lombok.extern.slf4j.Slf4j;--import stirling.software.SPDF.model.api.PdfJsonConversionProgress;-import stirling.software.SPDF.model.json.PdfJsonAnnotation;-import stirling.software.SPDF.model.json.PdfJsonCosValue;-import stirling.software.SPDF.model.json.PdfJsonDocumentMetadata;-import stirling.software.SPDF.model.json.PdfJsonFont;-import stirling.software.SPDF.model.json.PdfJsonImageElement;-import stirling.software.SPDF.model.json.PdfJsonPage;-import stirling.software.SPDF.model.json.PdfJsonPageDimension;-import stirling.software.SPDF.model.json.PdfJsonStream;-import stirling.software.SPDF.model.json.PdfJsonTextElement;-import stirling.software.common.service.CustomPDFDocumentFactory;-import stirling.software.common.service.TaskManager;-import stirling.software.common.util.ExceptionUtils;--import tools.jackson.databind.ObjectMapper;--/**- * Service for lazy loading PDF pages. Caches PDF documents and extracts pages on-demand to reduce- * memory usage for large PDFs.- */-@Service-@Slf4j-@RequiredArgsConstructor-public class PdfLazyLoadingService {-- private final CustomPDFDocumentFactory pdfDocumentFactory;- private final ObjectMapper objectMapper;- private final TaskManager taskManager;- private final PdfJsonMetadataService metadataService;- private final PdfJsonImageService imageService;-- /** Cache for storing PDDocuments for lazy page loading. Key is jobId. */- private final Map<String, CachedPdfDocument> documentCache = new ConcurrentHashMap<>();-- /**- * Stores PDF file bytes for lazy page loading. Each page is extracted on-demand by re-loading- * the PDF from bytes.- */- @Data- private static class CachedPdfDocument {- private final byte[] pdfBytes;- private final PdfJsonDocumentMetadata metadata;- private final long timestamp;-- public CachedPdfDocument(byte[] pdfBytes, PdfJsonDocumentMetadata metadata) {- this.pdfBytes = pdfBytes;- this.metadata = metadata;- this.timestamp = System.currentTimeMillis();- }- }-- /**- * Extracts document metadata, fonts, and page dimensions without page content. Caches the PDF- * bytes for subsequent page requests.- *- * @param file The uploaded PDF file- * @param jobId The job ID for caching- * @param fonts Font map (will be populated)- * @param pageFontResources Page font resources map (will be populated)- * @param out The output stream to write the serialized metadata JSON to- * @throws IOException If extraction fails- */- public void extractDocumentMetadata(- MultipartFile file,- String jobId,- Map<String, PdfJsonFont> fonts,- Map<Integer, Map<PDFont, String>> pageFontResources,- OutputStream out)- throws IOException {- if (file == null) {- throw ExceptionUtils.createNullArgumentException("fileInput");- }-- Consumer<PdfJsonConversionProgress> progress =- jobId != null- ? (p) -> {- log.info(- "Progress: [{}%] {} - {}{}",- p.getPercent(),- p.getStage(),- p.getMessage(),- (p.getCurrent() != null && p.getTotal() != null)- ? String.format(- " (%d/%d)", p.getCurrent(), p.getTotal())- : "");- reportProgressToTaskManager(jobId, p);- }- : (p) -> {};-- // Read PDF bytes once for processing and caching- byte[] pdfBytes = file.getBytes();-- try (PDDocument document = pdfDocumentFactory.load(pdfBytes, true)) {- int totalPages = document.getNumberOfPages();-- // Build metadata response- progress.accept(PdfJsonConversionProgress.of(90, "metadata", "Extracting metadata"));- PdfJsonDocumentMetadata docMetadata = new PdfJsonDocumentMetadata();- docMetadata.setMetadata(metadataService.extractMetadata(document));- docMetadata.setXmpMetadata(metadataService.extractXmpMetadata(document));- docMetadata.setLazyImages(Boolean.TRUE);-- List<PdfJsonFont> serializedFonts = new ArrayList<>(fonts.values());- serializedFonts.sort(- Comparator.comparing(- PdfJsonFont::getUid, Comparator.nullsLast(Comparator.naturalOrder())));- docMetadata.setFonts(serializedFonts);-- // Extract page dimensions- List<PdfJsonPageDimension> pageDimensions = new ArrayList<>();- int pageIndex = 0;- for (PDPage page : document.getPages()) {- PdfJsonPageDimension dim = new PdfJsonPageDimension();- dim.setPageNumber(pageIndex + 1);- PDRectangle mediaBox = page.getMediaBox();- dim.setWidth(mediaBox.getWidth());- dim.setHeight(mediaBox.getHeight());- dim.setRotation(page.getRotation());- pageDimensions.add(dim);- pageIndex++;- }- docMetadata.setPageDimensions(pageDimensions);-- // Cache PDF bytes and metadata for lazy page loading- if (jobId != null) {- CachedPdfDocument cached = new CachedPdfDocument(pdfBytes, docMetadata);- documentCache.put(jobId, cached);- log.info(- "Cached PDF bytes ({} bytes) for lazy loading, jobId: {}",- pdfBytes.length,- jobId);-- // Schedule cleanup after 30 minutes- scheduleDocumentCleanup(jobId);- }-- progress.accept(- PdfJsonConversionProgress.of(100, "complete", "Metadata extraction complete"));-- objectMapper.writeValue(out, docMetadata);- }- }-- /**- * Extracts a single page from cached PDF bytes. Re-loads the PDF for each request.- *- * @param jobId The job ID- * @param pageNumber The page number (1-indexed)- * @param serializeCosValue Function to serialize COS values- * @param extractContentStreams Function to extract content streams- * @param filterImageXObjectsFromResources Function to filter image XObjects- * @param extractText Function to extract text elements for the page- * @param extractAnnotations Function to extract annotations for the page- * @param out The output stream to write the serialized page JSON to- * @throws IOException If extraction fails- */- public void extractSinglePage(- String jobId,- int pageNumber,- java.util.function.Function<COSBase, PdfJsonCosValue> serializeCosValue,- java.util.function.Function<PDPage, List<PdfJsonStream>> extractContentStreams,- java.util.function.Function<COSBase, COSBase> filterImageXObjectsFromResources,- java.util.function.BiFunction<PDDocument, Integer, List<PdfJsonTextElement>>- extractText,- java.util.function.BiFunction<PDDocument, Integer, List<PdfJsonAnnotation>>- extractAnnotations,- OutputStream out)- throws IOException {- CachedPdfDocument cached = documentCache.get(jobId);- if (cached == null) {- throw new IllegalArgumentException("No cached document found for jobId: " + jobId);- }-- int pageIndex = pageNumber - 1;- int totalPages = cached.getMetadata().getPageDimensions().size();-- if (pageIndex < 0 || pageIndex >= totalPages) {- throw new IllegalArgumentException(- "Page number " + pageNumber + " out of range (1-" + totalPages + ")");- }-- log.debug("Loading PDF from bytes to extract page {} (jobId: {})", pageNumber, jobId);-- // Re-load PDF from cached bytes and extract the single page- try (PDDocument document = pdfDocumentFactory.load(cached.getPdfBytes(), true)) {- PDPage page = document.getPage(pageIndex);- PdfJsonPage pageModel = new PdfJsonPage();- pageModel.setPageNumber(pageNumber);- PDRectangle mediaBox = page.getMediaBox();- pageModel.setWidth(mediaBox.getWidth());- pageModel.setHeight(mediaBox.getHeight());- pageModel.setRotation(page.getRotation());-- // Extract text on-demand- pageModel.setTextElements(extractText.apply(document, pageNumber));-- // Extract annotations on-demand- pageModel.setAnnotations(extractAnnotations.apply(document, pageNumber));-- // Extract images on-demand- List<PdfJsonImageElement> images =- imageService.extractImagesForPage(document, page, pageNumber);- pageModel.setImageElements(images);-- // Extract resources and content streams- COSBase resourcesBase = page.getCOSObject().getDictionaryObject(COSName.RESOURCES);- COSBase filteredResources = filterImageXObjectsFromResources.apply(resourcesBase);- pageModel.setResources(serializeCosValue.apply(filteredResources));- pageModel.setContentStreams(extractContentStreams.apply(page));-- log.debug(- "Extracted page {} (text: {}, images: {}, annotations: {}) for jobId: {}",- pageNumber,- pageModel.getTextElements().size(),- images.size(),- pageModel.getAnnotations().size(),- jobId);-- objectMapper.writeValue(out, pageModel);- }- }-- /** Clears a cached document. */- public void clearCachedDocument(String jobId) {- CachedPdfDocument cached = documentCache.remove(jobId);- if (cached != null) {- log.info(- "Removed cached PDF bytes ({} bytes) for jobId: {}",- cached.getPdfBytes().length,- jobId);- }- }-- /** Schedules automatic cleanup of cached documents after 30 minutes. */- private void scheduleDocumentCleanup(String jobId) {- Thread.ofVirtual()- .start(- () -> {- try {- Thread.sleep(TimeUnit.MINUTES.toMillis(30));- clearCachedDocument(jobId);- log.info("Auto-cleaned cached document for jobId: {}", jobId);- } catch (InterruptedException e) {- Thread.currentThread().interrupt();- }- });- }-- /**- * Report progress to TaskManager for async jobs- *- * @param jobId The job ID- * @param progress The progress update- */- private void reportProgressToTaskManager(String jobId, PdfJsonConversionProgress progress) {- try {- log.info(- "Reporting progress for job {}: {}% - {}",- jobId, progress.getPercent(), progress.getStage());- String note;- if (progress.getCurrent() != null && progress.getTotal() != null) {- note =- String.format(- "[%d%%] %s: %s (%d/%d)",- progress.getPercent(),- progress.getStage(),- progress.getMessage(),- progress.getCurrent(),- progress.getTotal());- } else {- note =- String.format(- "[%d%%] %s: %s",- progress.getPercent(), progress.getStage(), progress.getMessage());- }- boolean added = taskManager.addNote(jobId, note);- if (!added) {- log.warn("Failed to add note - job {} not found in TaskManager", jobId);- } else {- log.info("Successfully added progress note for job {}: {}", jobId, note);- }- } catch (Exception e) {- log.error("Exception reporting progress for job {}: {}", jobId, e.getMessage(), e);- }- }-}diff --git a/app/core/src/main/java/stirling/software/SPDF/service/pdfjson/type3/Type3ConversionRequest.java b/app/core/src/main/java/stirling/software/SPDF/service/pdfjson/type3/Type3ConversionRequest.javadeleted file mode 100644index 7a811f8156..0000000000--- a/app/core/src/main/java/stirling/software/SPDF/service/pdfjson/type3/Type3ConversionRequest.java+++ /dev/null@@ -1,17 +0,0 @@-package stirling.software.SPDF.service.pdfjson.type3;--import org.apache.pdfbox.pdmodel.PDDocument;-import org.apache.pdfbox.pdmodel.font.PDType3Font;--import lombok.Builder;-import lombok.Getter;--@Getter-@Builder-public class Type3ConversionRequest {- private final PDDocument document;- private final PDType3Font font;- private final String fontId;- private final int pageNumber;- private final String fontUid;-}diff --git a/app/core/src/main/java/stirling/software/SPDF/service/pdfjson/type3/Type3ConversionStrategy.java b/app/core/src/main/java/stirling/software/SPDF/service/pdfjson/type3/Type3ConversionStrategy.javadeleted file mode 100644index 9f62dea7e5..0000000000--- a/app/core/src/main/java/stirling/software/SPDF/service/pdfjson/type3/Type3ConversionStrategy.java+++ /dev/null@@ -1,32 +0,0 @@-package stirling.software.SPDF.service.pdfjson.type3;--import java.io.IOException;--import stirling.software.SPDF.model.json.PdfJsonFontConversionCandidate;--public interface Type3ConversionStrategy {-- /** Unique identifier used when reporting results. */- String getId();-- /** Human-readable label for UI toggles or logs. */- String getLabel();-- /** True when the underlying tooling is usable on this host. */- boolean isAvailable();-- /** Quick predicate to avoid running on unsupported Type3 shapes. */- default boolean supports(Type3ConversionRequest request, Type3GlyphContext context)- throws IOException {- return request != null && request.getFont() != null;- }-- /**- * Attempt to synthesise a font program for the supplied Type3 font.- *- * @param request contextual information for the conversion attempt- * @return a candidate describing the outcome, never {@code null}- */- PdfJsonFontConversionCandidate convert(- Type3ConversionRequest request, Type3GlyphContext context) throws IOException;-}diff --git a/app/core/src/main/java/stirling/software/SPDF/service/pdfjson/type3/Type3FontConversionService.java b/app/core/src/main/java/stirling/software/SPDF/service/pdfjson/type3/Type3FontConversionService.javadeleted file mode 100644index a77c36ba5e..0000000000--- a/app/core/src/main/java/stirling/software/SPDF/service/pdfjson/type3/Type3FontConversionService.java+++ /dev/null@@ -1,133 +0,0 @@-package stirling.software.SPDF.service.pdfjson.type3;--import java.io.IOException;-import java.util.ArrayList;-import java.util.Collections;-import java.util.List;--import org.springframework.stereotype.Service;--import lombok.RequiredArgsConstructor;-import lombok.extern.slf4j.Slf4j;--import stirling.software.SPDF.model.json.PdfJsonFontConversionCandidate;-import stirling.software.SPDF.model.json.PdfJsonFontConversionStatus;--@Slf4j-@Service-@RequiredArgsConstructor-public class Type3FontConversionService {-- private final List<Type3ConversionStrategy> strategies;- private final Type3GlyphExtractor glyphExtractor;-- public List<PdfJsonFontConversionCandidate> synthesize(Type3ConversionRequest request) {- if (request == null || request.getFont() == null) {- return Collections.emptyList();- }- if (strategies == null || strategies.isEmpty()) {- log.debug(- "[TYPE3] No conversion strategies registered for font {}", request.getFontId());- return Collections.emptyList();- }-- List<PdfJsonFontConversionCandidate> candidates = new ArrayList<>();- Type3GlyphContext glyphContext = null;- for (Type3ConversionStrategy strategy : strategies) {- if (strategy == null) {- continue;- }- PdfJsonFontConversionCandidate candidate =- runStrategy(- strategy,- request,- glyphContext == null- ? (glyphContext =- new Type3GlyphContext(request, glyphExtractor))- : glyphContext);- if (candidate != null) {- candidates.add(candidate);- }- }- return candidates;- }-- private PdfJsonFontConversionCandidate runStrategy(- Type3ConversionStrategy strategy,- Type3ConversionRequest request,- Type3GlyphContext glyphContext) {- if (!strategy.isAvailable()) {- return PdfJsonFontConversionCandidate.builder()- .strategyId(strategy.getId())- .strategyLabel(strategy.getLabel())- .status(PdfJsonFontConversionStatus.SKIPPED)- .message("Strategy unavailable on current host")- .build();- }- try {- if (!strategy.supports(request, glyphContext)) {- return PdfJsonFontConversionCandidate.builder()- .strategyId(strategy.getId())- .strategyLabel(strategy.getLabel())- .status(PdfJsonFontConversionStatus.UNSUPPORTED)- .message("Font not supported by strategy")- .build();- }- } catch (IOException supportCheckException) {- log.warn(- "[TYPE3] Strategy {} support check failed for font {}: {}",- strategy.getId(),- request.getFontUid(),- supportCheckException.getMessage(),- supportCheckException);- return PdfJsonFontConversionCandidate.builder()- .strategyId(strategy.getId())- .strategyLabel(strategy.getLabel())- .status(PdfJsonFontConversionStatus.UNSUPPORTED)- .message("Support check failed: " + supportCheckException.getMessage())- .build();- }-- try {- PdfJsonFontConversionCandidate result = strategy.convert(request, glyphContext);- if (result == null) {- log.info(- "[TYPE3] Strategy {} returned null result for font {}",- strategy.getId(),- request.getFontUid());- return PdfJsonFontConversionCandidate.builder()- .strategyId(strategy.getId())- .strategyLabel(strategy.getLabel())- .status(PdfJsonFontConversionStatus.FAILURE)- .message("Strategy returned null result")- .build();- }- if (result.getStrategyId() == null) {- result.setStrategyId(strategy.getId());- }- if (result.getStrategyLabel() == null) {- result.setStrategyLabel(strategy.getLabel());- }- log.debug(- "[TYPE3] Strategy {} finished with status {} (message: {}) for font {}",- strategy.getId(),- result.getStatus(),- result.getMessage(),- request.getFontUid());- return result;- } catch (IOException ex) {- log.warn(- "[TYPE3] Strategy {} failed for font {}: {}",- strategy.getId(),- request.getFontUid(),- ex.getMessage(),- ex);- return PdfJsonFontConversionCandidate.builder()- .strategyId(strategy.getId())- .strategyLabel(strategy.getLabel())- .status(PdfJsonFontConversionStatus.FAILURE)- .message(ex.getMessage())- .build();- }- }-}diff --git a/app/core/src/main/java/stirling/software/SPDF/service/pdfjson/type3/Type3FontSignatureCalculator.java b/app/core/src/main/java/stirling/software/SPDF/service/pdfjson/type3/Type3FontSignatureCalculator.javadeleted file mode 100644index 23634a7a3d..0000000000--- a/app/core/src/main/java/stirling/software/SPDF/service/pdfjson/type3/Type3FontSignatureCalculator.java+++ /dev/null@@ -1,218 +0,0 @@-package stirling.software.SPDF.service.pdfjson.type3;--import java.io.IOException;-import java.io.InputStream;-import java.nio.ByteBuffer;-import java.security.MessageDigest;-import java.security.NoSuchAlgorithmException;-import java.util.ArrayList;-import java.util.Comparator;-import java.util.List;-import java.util.Locale;--import org.apache.pdfbox.cos.COSArray;-import org.apache.pdfbox.cos.COSBase;-import org.apache.pdfbox.cos.COSDictionary;-import org.apache.pdfbox.cos.COSName;-import org.apache.pdfbox.cos.COSNumber;-import org.apache.pdfbox.cos.COSStream;-import org.apache.pdfbox.pdmodel.common.PDRectangle;-import org.apache.pdfbox.pdmodel.font.PDType3CharProc;-import org.apache.pdfbox.pdmodel.font.PDType3Font;-import org.apache.pdfbox.pdmodel.font.encoding.Encoding;-import org.apache.pdfbox.util.Matrix;--/**- * Computes a reproducible hash for Type3 fonts so we can match them against a pre-built library of- * converted programs. The signature intentionally combines multiple aspects of the font (encoding,- * CharProc streams, glyph widths, font metrics) to minimise collisions between unrelated fonts that- * coincidentally share glyph names.- */-public final class Type3FontSignatureCalculator {-- private Type3FontSignatureCalculator() {}-- public static String computeSignature(PDType3Font font) throws IOException {- if (font == null) {- return null;- }- MessageDigest digest = newDigest();- updateMatrix(digest, font.getFontMatrix());- updateRectangle(digest, font.getFontBBox());- updateEncoding(digest, font.getEncoding());- updateCharProcs(digest, font);- byte[] hash = digest.digest();- return "sha256:" + toHex(hash);- }-- private static void updateEncoding(MessageDigest digest, Encoding encoding) {- if (encoding == null) {- updateInt(digest, -1);- return;- }- for (int code = 0; code <= 0xFF; code++) {- String name = encoding.getName(code);- if (name != null) {- updateInt(digest, code);- updateString(digest, name);- }- }- }-- private static void updateCharProcs(MessageDigest digest, PDType3Font font) throws IOException {- COSDictionary charProcs =- (COSDictionary) font.getCOSObject().getDictionaryObject(COSName.CHAR_PROCS);- if (charProcs == null || charProcs.size() == 0) {- updateInt(digest, 0);- return;- }- List<COSName> glyphNames = new ArrayList<>(charProcs.keySet());- glyphNames.sort(Comparator.comparing(COSName::getName, String.CASE_INSENSITIVE_ORDER));- for (COSName glyphName : glyphNames) {- updateString(digest, glyphName.getName());- int code = resolveCharCode(font, glyphName.getName());- updateInt(digest, code);- if (code >= 0) {- try {- updateFloat(digest, font.getWidthFromFont(code));- } catch (IOException ignored) {- updateFloat(digest, 0f);- }- } else {- updateFloat(digest, 0f);- }-- COSStream stream =- charProcs.getDictionaryObject(glyphName) instanceof COSStream cosStream- ? cosStream- : null;- if (stream != null) {- byte[] payload = readAllBytes(stream);- updateInt(digest, payload.length);- digest.update(payload);- PDType3CharProc charProc = new PDType3CharProc(font, stream);- updateRectangle(digest, extractGlyphBoundingBox(font, charProc));- } else {- updateInt(digest, -1);- }- }- updateInt(digest, glyphNames.size());- }-- private static byte[] readAllBytes(COSStream stream) throws IOException {- try (InputStream inputStream = stream.createInputStream()) {- return inputStream.readAllBytes();- }- }-- private static COSArray extractGlyphBoundingBox(PDType3Font font, PDType3CharProc charProc) {- if (charProc == null) {- return null;- }- COSStream stream = charProc.getCOSObject();- if (stream != null) {- COSArray bboxArray = (COSArray) stream.getDictionaryObject(COSName.BBOX);- if (bboxArray != null && bboxArray.size() == 4) {- return bboxArray;- }- }- return font.getCOSObject().getCOSArray(COSName.BBOX);- }-- private static int resolveCharCode(PDType3Font font, String glyphName) {- if (glyphName == null || font.getEncoding() == null) {- return -1;- }- Encoding encoding = font.getEncoding();- for (int code = 0; code <= 0xFF; code++) {- String name = encoding.getName(code);- if (glyphName.equals(name)) {- return code;- }- }- return -1;- }-- private static void updateMatrix(MessageDigest digest, Matrix matrix) {- if (matrix == null) {- updateInt(digest, -1);- return;- }- float[][] values = matrix.getValues();- updateInt(digest, values.length);- for (float[] row : values) {- if (row == null) {- updateInt(digest, -1);- continue;- }- updateInt(digest, row.length);- for (float value : row) {- updateFloat(digest, value);- }- }- }-- private static void updateRectangle(MessageDigest digest, PDRectangle rectangle) {- if (rectangle == null) {- updateInt(digest, -1);- return;- }- updateFloat(digest, rectangle.getLowerLeftX());- updateFloat(digest, rectangle.getLowerLeftY());- updateFloat(digest, rectangle.getUpperRightX());- updateFloat(digest, rectangle.getUpperRightY());- }-- private static void updateRectangle(MessageDigest digest, COSArray array) {- if (array == null) {- updateInt(digest, -1);- return;- }- updateInt(digest, array.size());- for (int i = 0; i < array.size(); i++) {- COSBase value = array.getObject(i);- if (value instanceof COSNumber number) {- updateFloat(digest, number.floatValue());- } else {- updateFloat(digest, 0f);- }- }- }-- private static void updateString(MessageDigest digest, String value) {- if (value == null) {- updateInt(digest, -1);- return;- }- byte[] bytes = value.getBytes(java.nio.charset.StandardCharsets.UTF_8);- updateInt(digest, bytes.length);- digest.update(bytes);- }-- private static void updateInt(MessageDigest digest, int value) {- digest.update(ByteBuffer.allocate(Integer.BYTES).putInt(value).array());- }-- private static void updateFloat(MessageDigest digest, float value) {- if (Float.isNaN(value) || Float.isInfinite(value)) {- value = 0f;- }- digest.update(ByteBuffer.allocate(Float.BYTES).putFloat(value).array());- }-- private static MessageDigest newDigest() {- try {- return MessageDigest.getInstance("SHA-256");- } catch (NoSuchAlgorithmException ex) {- throw new IllegalStateException("Missing SHA-256 MessageDigest", ex);- }- }-- private static String toHex(byte[] bytes) {- StringBuilder builder = new StringBuilder(bytes.length * 2);- for (byte value : bytes) {- builder.append(String.format(Locale.ROOT, "%02x", Byte.toUnsignedInt(value)));- }- return builder.toString();- }-}diff --git a/app/core/src/main/java/stirling/software/SPDF/service/pdfjson/type3/Type3GlyphContext.java b/app/core/src/main/java/stirling/software/SPDF/service/pdfjson/type3/Type3GlyphContext.javadeleted file mode 100644index 082813cc36..0000000000--- a/app/core/src/main/java/stirling/software/SPDF/service/pdfjson/type3/Type3GlyphContext.java+++ /dev/null@@ -1,38 +0,0 @@-package stirling.software.SPDF.service.pdfjson.type3;--import java.io.IOException;-import java.util.List;-import java.util.concurrent.atomic.AtomicReference;--import org.apache.pdfbox.pdmodel.font.PDType3Font;--import stirling.software.SPDF.service.pdfjson.type3.model.Type3GlyphOutline;--class Type3GlyphContext {- private final Type3ConversionRequest request;- private final Type3GlyphExtractor extractor;- private final AtomicReference<List<Type3GlyphOutline>> glyphs = new AtomicReference<>();-- Type3GlyphContext(Type3ConversionRequest request, Type3GlyphExtractor extractor) {- this.request = request;- this.extractor = extractor;- }-- public List<Type3GlyphOutline> getGlyphs() throws IOException {- List<Type3GlyphOutline> cached = glyphs.get();- if (cached == null) {- cached =- extractor.extractGlyphs(- request.getDocument(),- request.getFont(),- request.getFontId(),- request.getPageNumber());- glyphs.compareAndSet(null, cached);- }- return cached;- }-- public PDType3Font getFont() {- return request.getFont();- }-}diff --git a/app/core/src/main/java/stirling/software/SPDF/service/pdfjson/type3/Type3GlyphExtractor.java b/app/core/src/main/java/stirling/software/SPDF/service/pdfjson/type3/Type3GlyphExtractor.javadeleted file mode 100644index b662f5683f..0000000000--- a/app/core/src/main/java/stirling/software/SPDF/service/pdfjson/type3/Type3GlyphExtractor.java+++ /dev/null@@ -1,126 +0,0 @@-package stirling.software.SPDF.service.pdfjson.type3;--import java.awt.geom.GeneralPath;-import java.io.IOException;-import java.util.ArrayList;-import java.util.List;-import java.util.Objects;--import org.apache.pdfbox.cos.COSArray;-import org.apache.pdfbox.cos.COSDictionary;-import org.apache.pdfbox.cos.COSName;-import org.apache.pdfbox.cos.COSStream;-import org.apache.pdfbox.pdmodel.PDDocument;-import org.apache.pdfbox.pdmodel.PDPage;-import org.apache.pdfbox.pdmodel.common.PDRectangle;-import org.apache.pdfbox.pdmodel.font.PDType3CharProc;-import org.apache.pdfbox.pdmodel.font.PDType3Font;-import org.springframework.stereotype.Component;--import lombok.extern.slf4j.Slf4j;--import stirling.software.SPDF.service.pdfjson.type3.model.Type3GlyphOutline;--@Slf4j-@Component-public class Type3GlyphExtractor {-- public List<Type3GlyphOutline> extractGlyphs(- PDDocument document, PDType3Font font, String fontId, int pageNumber)- throws IOException {- Objects.requireNonNull(font, "font");- COSDictionary charProcs =- (COSDictionary) font.getCOSObject().getDictionaryObject(COSName.CHAR_PROCS);- if (charProcs == null || charProcs.size() == 0) {- return List.of();- }- List<Type3GlyphOutline> outlines = new ArrayList<>();- for (COSName glyphName : charProcs.keySet()) {- COSStream stream =- charProcs.getDictionaryObject(glyphName) instanceof COSStream cosStream- ? cosStream- : null;- if (stream == null) {- continue;- }- PDType3CharProc charProc = new PDType3CharProc(font, stream);- outlines.add(analyseGlyph(document, font, glyphName, charProc, fontId, pageNumber));- }- return outlines;- }-- private Type3GlyphOutline analyseGlyph(- PDDocument document,- PDType3Font font,- COSName glyphName,- PDType3CharProc charProc,- String fontId,- int pageNumber)- throws IOException {- int code = resolveCharCode(font, glyphName.getName());- float advanceWidth = 0f;- if (code >= 0) {- advanceWidth = font.getWidthFromFont(code);- }-- PDRectangle glyphBBox = extractGlyphBoundingBox(font, charProc);- PDRectangle bbox = font.getFontBBox();- GlyphGraphicsExtractor extractor =- new GlyphGraphicsExtractor(new PDPage(bbox != null ? bbox : new PDRectangle()));- extractor.process(charProc);- GeneralPath outline = extractor.getAccumulatedPath();- Integer unicodeValue = null;- if (code >= 0) {- String unicode = font.toUnicode(code);- if (unicode != null && !unicode.isEmpty()) {- unicodeValue = unicode.codePointAt(0);- } else {- unicodeValue = code;- }- }- return Type3GlyphOutline.builder()- .glyphName(glyphName.getName())- .charCode(code)- .advanceWidth(advanceWidth)- .boundingBox(glyphBBox)- .outline(outline)- .hasFill(extractor.isSawFill())- .hasStroke(extractor.isSawStroke())- .hasImages(extractor.isSawImage())- .hasText(extractor.isSawText())- .hasShading(extractor.isSawShading())- .warnings(extractor.getWarnings())- .unicode(unicodeValue)- .build();- }-- private PDRectangle extractGlyphBoundingBox(PDType3Font font, PDType3CharProc charProc) {- COSStream stream = charProc != null ? charProc.getCOSObject() : null;- if (stream != null) {- COSArray bboxArray = (COSArray) stream.getDictionaryObject(COSName.BBOX);- if (bboxArray != null && bboxArray.size() == 4) {- return new PDRectangle(bboxArray);- }- }- return font.getFontBBox();- }-- private int resolveCharCode(PDType3Font font, String glyphName) {- if (glyphName == null || font.getEncoding() == null) {- return -1;- }- for (int code = 0; code <= 0xFF; code++) {- String name = font.getEncoding().getName(code);- if (glyphName.equals(name)) {- return code;- }- }- return -1;- }-- private static final class GlyphGraphicsExtractor extends Type3GraphicsEngine {- GlyphGraphicsExtractor(PDPage page) {- super(page);- }- }-}diff --git a/app/core/src/main/java/stirling/software/SPDF/service/pdfjson/type3/Type3GraphicsEngine.java b/app/core/src/main/java/stirling/software/SPDF/service/pdfjson/type3/Type3GraphicsEngine.javadeleted file mode 100644index d4e3cd6e95..0000000000--- a/app/core/src/main/java/stirling/software/SPDF/service/pdfjson/type3/Type3GraphicsEngine.java+++ /dev/null@@ -1,164 +0,0 @@-package stirling.software.SPDF.service.pdfjson.type3;--import java.awt.geom.GeneralPath;-import java.awt.geom.Point2D;-import java.io.IOException;--import org.apache.pdfbox.contentstream.PDFGraphicsStreamEngine;-import org.apache.pdfbox.contentstream.operator.Operator;-import org.apache.pdfbox.cos.COSName;-import org.apache.pdfbox.pdmodel.PDPage;-import org.apache.pdfbox.pdmodel.font.PDFont;-import org.apache.pdfbox.pdmodel.font.PDType3CharProc;-import org.apache.pdfbox.pdmodel.graphics.image.PDImage;-import org.apache.pdfbox.util.Matrix;-import org.apache.pdfbox.util.Vector;--import lombok.Getter;-import lombok.extern.slf4j.Slf4j;--@Slf4j-class Type3GraphicsEngine extends PDFGraphicsStreamEngine {-- private final GeneralPath accumulatedPath = new GeneralPath();- private final GeneralPath linePath = new GeneralPath();- private final Point2D.Float currentPoint = new Point2D.Float();- private boolean hasCurrentPoint;- @Getter private boolean sawStroke;- @Getter private boolean sawFill;- @Getter private boolean sawImage;- @Getter private boolean sawText;- @Getter private boolean sawShading;- @Getter private String warnings;-- protected Type3GraphicsEngine(PDPage page) {- super(page);- }-- public GeneralPath getAccumulatedPath() {- return (GeneralPath) accumulatedPath.clone();- }-- public void process(PDType3CharProc charProc) throws IOException {- accumulatedPath.reset();- linePath.reset();- sawStroke = false;- sawFill = false;- sawImage = false;- sawText = false;- sawShading = false;- warnings = null;- if (charProc != null) {- processChildStream(charProc, getPage());- }- }-- @Override- public void appendRectangle(Point2D p0, Point2D p1, Point2D p2, Point2D p3) throws IOException {- moveTo((float) p0.getX(), (float) p0.getY());- lineTo((float) p1.getX(), (float) p1.getY());- lineTo((float) p2.getX(), (float) p2.getY());- lineTo((float) p3.getX(), (float) p3.getY());- closePath();- }-- @Override- public void drawImage(PDImage pdImage) throws IOException {- sawImage = true;- }-- @Override- public void shadingFill(COSName shadingName) throws IOException {- sawShading = true;- }-- @Override- public void strokePath() throws IOException {- accumulatedPath.append(linePath, false);- linePath.reset();- sawStroke = true;- }-- @Override- public void fillPath(int windingRule) throws IOException {- linePath.setWindingRule(- windingRule == 0 ? GeneralPath.WIND_EVEN_ODD : GeneralPath.WIND_NON_ZERO);- accumulatedPath.append(linePath, false);- linePath.reset();- sawFill = true;- }-- @Override- public void fillAndStrokePath(int windingRule) throws IOException {- fillPath(windingRule);- sawStroke = true;- }-- @Override- public void clip(int windingRule) throws IOException {- // ignore- }-- @Override- public void moveTo(float x, float y) throws IOException {- linePath.moveTo(x, y);- currentPoint.setLocation(x, y);- hasCurrentPoint = true;- }-- @Override- public void lineTo(float x, float y) throws IOException {- linePath.lineTo(x, y);- currentPoint.setLocation(x, y);- hasCurrentPoint = true;- }-- @Override- public void curveTo(float x1, float y1, float x2, float y2, float x3, float y3)- throws IOException {- linePath.curveTo(x1, y1, x2, y2, x3, y3);- currentPoint.setLocation(x3, y3);- hasCurrentPoint = true;- }-- @Override- public Point2D getCurrentPoint() throws IOException {- return hasCurrentPoint ? (Point2D) currentPoint.clone() : null;- }-- @Override- public void closePath() throws IOException {- linePath.closePath();- }-- @Override- public void endPath() throws IOException {- linePath.reset();- hasCurrentPoint = false;- }-- @Override- protected void showText(byte[] string) throws IOException {- sawText = true;- super.showText(string);- }-- @Override- protected void showFontGlyph(- Matrix textRenderingMatrix, PDFont font, int code, Vector displacement)- throws IOException {- sawText = true;- super.showFontGlyph(textRenderingMatrix, font, code, displacement);- }-- @Override- protected void processOperator(- Operator operator, java.util.List<org.apache.pdfbox.cos.COSBase> operands)- throws IOException {- if ("cm".equals(operator.getName())) {- warnings =- warnings == null ? "Encountered CTM concatenation" : warnings + "; CTM concat";- }- super.processOperator(operator, operands);- }-}diff --git a/app/core/src/main/java/stirling/software/SPDF/service/pdfjson/type3/Type3LibraryStrategy.java b/app/core/src/main/java/stirling/software/SPDF/service/pdfjson/type3/Type3LibraryStrategy.javadeleted file mode 100644index 5eaa4cbb78..0000000000--- a/app/core/src/main/java/stirling/software/SPDF/service/pdfjson/type3/Type3LibraryStrategy.java+++ /dev/null@@ -1,130 +0,0 @@-package stirling.software.SPDF.service.pdfjson.type3;--import java.io.IOException;--import org.springframework.core.annotation.Order;-import org.springframework.stereotype.Component;--import lombok.RequiredArgsConstructor;-import lombok.extern.slf4j.Slf4j;--import stirling.software.SPDF.model.json.PdfJsonFontConversionCandidate;-import stirling.software.SPDF.model.json.PdfJsonFontConversionStatus;-import stirling.software.SPDF.service.pdfjson.type3.library.Type3FontLibrary;-import stirling.software.SPDF.service.pdfjson.type3.library.Type3FontLibraryEntry;-import stirling.software.SPDF.service.pdfjson.type3.library.Type3FontLibraryMatch;-import stirling.software.SPDF.service.pdfjson.type3.library.Type3FontLibraryPayload;--@Slf4j-@Component-@Order(0)-@RequiredArgsConstructor-public class Type3LibraryStrategy implements Type3ConversionStrategy {-- private final Type3FontLibrary fontLibrary;- private final stirling.software.common.model.ApplicationProperties applicationProperties;-- private boolean enabled;-- @Override- public String getId() {- return "type3-library";- }-- @Override- public String getLabel() {- return "Type3 Font Library";- }-- @Override- public boolean isAvailable() {- return enabled && fontLibrary != null && fontLibrary.isLoaded();- }-- @jakarta.annotation.PostConstruct- private void loadConfiguration() {- if (applicationProperties.getPdfEditor() != null- && applicationProperties.getPdfEditor().getType3() != null- && applicationProperties.getPdfEditor().getType3().getLibrary() != null) {- var cfg = applicationProperties.getPdfEditor().getType3().getLibrary();- this.enabled = cfg.isEnabled();- } else {- this.enabled = false;- log.warn("PdfEditor Type3 library configuration not available, disabled");- }- }-- @Override- public PdfJsonFontConversionCandidate convert(- Type3ConversionRequest request, Type3GlyphContext context) throws IOException {- if (request == null || request.getFont() == null) {- return PdfJsonFontConversionCandidate.builder()- .strategyId(getId())- .strategyLabel(getLabel())- .status(PdfJsonFontConversionStatus.FAILURE)- .message("No font supplied")- .build();- }- if (!isAvailable()) {- return PdfJsonFontConversionCandidate.builder()- .strategyId(getId())- .strategyLabel(getLabel())- .status(PdfJsonFontConversionStatus.SKIPPED)- .message("Library disabled")- .build();- }-- Type3FontLibraryMatch match = fontLibrary.match(request.getFont(), request.getFontUid());- if (match == null || match.getEntry() == null) {- return PdfJsonFontConversionCandidate.builder()- .strategyId(getId())- .strategyLabel(getLabel())- .status(PdfJsonFontConversionStatus.UNSUPPORTED)- .message("No library entry found")- .build();- }-- Type3FontLibraryEntry entry = match.getEntry();- if (!entry.hasAnyPayload()) {- return PdfJsonFontConversionCandidate.builder()- .strategyId(getId())- .strategyLabel(getLabel())- .status(PdfJsonFontConversionStatus.FAILURE)- .message("Library entry has no payloads")- .build();- }-- String message =- String.format(- "Matched %s via %s",- entry.getLabel(),- match.getMatchType() != null ? match.getMatchType() : "alias");-- return PdfJsonFontConversionCandidate.builder()- .strategyId(getId())- .strategyLabel(getLabel())- .status(PdfJsonFontConversionStatus.SUCCESS)- .program(toBase64(entry.getProgram()))- .programFormat(toFormat(entry.getProgram()))- .webProgram(toBase64(entry.getWebProgram()))- .webProgramFormat(toFormat(entry.getWebProgram()))- .pdfProgram(toBase64(entry.getPdfProgram()))- .pdfProgramFormat(toFormat(entry.getPdfProgram()))- .glyphCoverage(- entry.getGlyphCoverage() != null- ? entry.getGlyphCoverage().stream()- .mapToInt(Integer::intValue)- .toArray()- : null)- .message(message)- .build();- }-- private String toBase64(Type3FontLibraryPayload payload) {- return payload != null ? payload.getBase64() : null;- }-- private String toFormat(Type3FontLibraryPayload payload) {- return payload != null ? payload.getFormat() : null;- }-}diff --git a/app/core/src/main/java/stirling/software/SPDF/service/pdfjson/type3/library/Type3FontLibrary.java b/app/core/src/main/java/stirling/software/SPDF/service/pdfjson/type3/library/Type3FontLibrary.javadeleted file mode 100644index 7468bdbc3a..0000000000--- a/app/core/src/main/java/stirling/software/SPDF/service/pdfjson/type3/library/Type3FontLibrary.java+++ /dev/null@@ -1,350 +0,0 @@-package stirling.software.SPDF.service.pdfjson.type3.library;--import java.io.IOException;-import java.io.InputStream;-import java.util.ArrayList;-import java.util.Base64;-import java.util.Collections;-import java.util.HashMap;-import java.util.List;-import java.util.Locale;-import java.util.Map;-import java.util.Objects;-import java.util.concurrent.ConcurrentHashMap;--import org.apache.pdfbox.cos.COSName;-import org.apache.pdfbox.pdmodel.font.PDType3Font;-import org.springframework.core.io.Resource;-import org.springframework.core.io.ResourceLoader;-import org.springframework.stereotype.Component;--import lombok.RequiredArgsConstructor;-import lombok.extern.slf4j.Slf4j;--import stirling.software.SPDF.service.pdfjson.type3.Type3FontSignatureCalculator;--import tools.jackson.core.type.TypeReference;-import tools.jackson.databind.ObjectMapper;--@Slf4j-@Component-@RequiredArgsConstructor-public class Type3FontLibrary {-- private final ObjectMapper objectMapper;- private final ResourceLoader resourceLoader;- private final stirling.software.common.model.ApplicationProperties applicationProperties;-- private String indexLocation;-- private final Map<String, Type3FontLibraryEntry> signatureIndex = new ConcurrentHashMap<>();- private final Map<String, Type3FontLibraryEntry> aliasIndex = new ConcurrentHashMap<>();- private final Map<String, Type3FontLibraryPayload> payloadCache = new HashMap<>();- private List<Type3FontLibraryEntry> entries = List.of();-- @jakarta.annotation.PostConstruct- void initialise() {- payloadCache.clear();- if (applicationProperties.getPdfEditor() != null- && applicationProperties.getPdfEditor().getType3() != null- && applicationProperties.getPdfEditor().getType3().getLibrary() != null) {- this.indexLocation =- applicationProperties.getPdfEditor().getType3().getLibrary().getIndex();- } else {- log.warn(- "[TYPE3] PdfEditor Type3 library configuration not available; Type3 library disabled");- entries = List.of();- return;- }- Resource resource = resourceLoader.getResource(indexLocation);- if (!resource.exists()) {- log.info("[TYPE3] Library index {} not found; Type3 library disabled", indexLocation);- entries = List.of();- return;- }- try (InputStream inputStream = resource.getInputStream()) {- List<RawEntry> rawEntries =- objectMapper.readValue(inputStream, new TypeReference<List<RawEntry>>() {});- List<Type3FontLibraryEntry> loaded = new ArrayList<>();- for (RawEntry rawEntry : rawEntries) {- Type3FontLibraryEntry entry = toEntry(rawEntry);- if (entry != null && entry.hasAnyPayload()) {- loaded.add(entry);- }- }- entries = Collections.unmodifiableList(loaded);- signatureIndex.clear();- aliasIndex.clear();-- for (Type3FontLibraryEntry entry : entries) {- if (entry.getSignatures() != null) {- for (String signature : entry.getSignatures()) {- if (signature == null) {- continue;- }- String key = signature.toLowerCase(Locale.ROOT);- signatureIndex.putIfAbsent(key, entry);- }- }- if (entry.getAliases() != null) {- for (String alias : entry.getAliases()) {- String normalized = normalizeAlias(alias);- if (normalized != null) {- aliasIndex.putIfAbsent(normalized, entry);- }- }- }- }- log.info(- "[TYPE3] Loaded {} Type3 library entries (signatures={}, aliases={}) from {}",- entries.size(),- signatureIndex.size(),- aliasIndex.size(),- indexLocation);- } catch (IOException ex) {- log.warn(- "[TYPE3] Failed to load Type3 library index {}: {}",- indexLocation,- ex.getMessage(),- ex);- entries = List.of();- signatureIndex.clear();- aliasIndex.clear();- }- }-- public boolean isLoaded() {- return !entries.isEmpty();- }-- public Type3FontLibraryMatch match(PDType3Font font, String fontUid) throws IOException {- if (font == null || entries.isEmpty()) {- return null;- }- String signature = Type3FontSignatureCalculator.computeSignature(font);- if (signature != null) {- Type3FontLibraryEntry entry = signatureIndex.get(signature.toLowerCase(Locale.ROOT));- if (entry != null) {- log.debug(- "[TYPE3] Matched Type3 font {} to library entry {} via signature {}",- fontUid,- entry.getId(),- signature);- return Type3FontLibraryMatch.builder()- .entry(entry)- .matchType("signature")- .signature(signature)- .build();- }- log.debug(- "[TYPE3] No library entry for signature {} (font {})",- signature,- fontUid != null ? fontUid : font.getName());- }-- String aliasKey = normalizeAlias(resolveBaseFontName(font));- if (aliasKey != null) {- Type3FontLibraryEntry entry = aliasIndex.get(aliasKey);- if (entry != null) {- log.debug(- "[TYPE3] Matched Type3 font {} to library entry {} via alias {}",- fontUid,- entry.getId(),- aliasKey);- return Type3FontLibraryMatch.builder()- .entry(entry)- .matchType("alias:" + aliasKey)- .signature(signature)- .build();- }- }-- if (signature != null) {- log.debug(- "[TYPE3] Library had no alias match for signature {} (font {})",- signature,- fontUid != null ? fontUid : font.getName());- }- return null;- }-- private Type3FontLibraryEntry toEntry(RawEntry rawEntry) {- if (rawEntry == null || rawEntry.id == null) {- return null;- }- try {- Type3FontLibraryEntry.Type3FontLibraryEntryBuilder builder =- Type3FontLibraryEntry.builder()- .id(rawEntry.id)- .label(rawEntry.label != null ? rawEntry.label : rawEntry.id)- .signatures(normalizeList(rawEntry.signatures))- .aliases(normalizeList(rawEntry.aliases))- .program(loadPayloadCached(rawEntry.program))- .webProgram(loadPayloadCached(rawEntry.webProgram))- .pdfProgram(loadPayloadCached(rawEntry.pdfProgram))- .source(rawEntry.source);- if (rawEntry.glyphCoverage != null && !rawEntry.glyphCoverage.isEmpty()) {- for (Integer codePoint : rawEntry.glyphCoverage) {- if (codePoint != null) {- builder.glyphCode(codePoint);- }- }- }- return builder.build();- } catch (IOException ex) {- log.warn(- "[TYPE3] Failed to load Type3 library entry {}: {}",- rawEntry.id,- ex.getMessage());- return null;- }- }-- private Type3FontLibraryPayload loadPayloadCached(RawPayload payload) throws IOException {- if (payload == null) {- return null;- }- if (payload.base64 != null && !payload.base64.isBlank()) {- return loadPayload(payload);- }- try {- if (payload.resource == null || payload.resource.isBlank()) {- return loadPayload(payload);- }- String key = payload.resource + "|" + payload.format;- Type3FontLibraryPayload cached = payloadCache.get(key);- if (cached != null) {- return cached;- }- Type3FontLibraryPayload loaded = loadPayload(payload);- if (loaded != null) {- payloadCache.put(key, loaded);- }- return loaded;- } catch (IOException ex) {- log.warn("[TYPE3] Failed to load Type3 payload: {}", ex.getMessage());- return null;- }- }-- private Type3FontLibraryPayload loadPayload(RawPayload payload) throws IOException {- if (payload == null) {- return null;- }- if (payload.base64 != null && !payload.base64.isBlank()) {- try {- byte[] probe =- Base64.getDecoder()- .decode(- payload.base64.substring(- 0, Math.min(4, payload.base64.length())));- if (probe.length == 0 && payload.base64.length() <= 4) {- return null;- }- } catch (IllegalArgumentException ex) {- log.warn("[TYPE3] Invalid base64 payload in Type3 library: {}", ex.getMessage());- return null;- }- return new Type3FontLibraryPayload(payload.base64, normalizeFormat(payload.format));- } else if (payload.resource != null && !payload.resource.isBlank()) {- String resolved = resolveLocation(payload.resource);- Resource res = resourceLoader.getResource(resolved);- if (!res.exists()) {- throw new IOException("Resource not found: " + resolved);- }- return new Type3FontLibraryPayload(res, normalizeFormat(payload.format));- }- return null;- }-- private byte[] loadResourceBytes(String location) throws IOException {- if (location == null || location.isBlank()) {- throw new IOException("Resource location is null or blank");- }- String resolved = resolveLocation(location);- Resource resource = resourceLoader.getResource(resolved);- if (!resource.exists()) {- throw new IOException("Resource not found: " + resolved);- }- try (InputStream inputStream = resource.getInputStream()) {- return inputStream.readAllBytes();- }- }-- private String resolveLocation(String location) {- if (location == null || location.isBlank()) {- return location;- }- if (location.contains(":")) {- return location;- }- if (location.startsWith("/")) {- return "classpath:" + location;- }- return "classpath:/" + location;- }-- private List<String> normalizeList(List<String> values) {- if (values == null || values.isEmpty()) {- return List.of();- }- return values.stream()- .filter(Objects::nonNull)- .map(String::trim)- .filter(s -> !s.isEmpty())- .toList();- }-- private String normalizeAlias(String alias) {- if (alias == null) {- return null;- }- String value = alias.trim();- int plus = value.indexOf('+');- if (plus >= 0 && plus < value.length() - 1) {- value = value.substring(plus + 1);- }- return value.isEmpty() ? null : value.toLowerCase(Locale.ROOT);- }-- private String normalizeFormat(String format) {- if (format == null) {- return null;- }- return format.trim().toLowerCase(Locale.ROOT);- }-- private String resolveBaseFontName(PDType3Font font) {- if (font == null) {- return null;- }- String baseName = null;- try {- baseName = font.getName();- } catch (Exception ignored) {- // Some Type3 fonts throw when resolving names; fall back to COS dictionary.- }- if (baseName == null && font.getCOSObject() != null) {- baseName = font.getCOSObject().getNameAsString(COSName.BASE_FONT);- }- return baseName;- }-- private static final class RawEntry {- public String id;- public String label;- public List<String> signatures;- public List<String> aliases;- public RawPayload program;- public RawPayload webProgram;- public RawPayload pdfProgram;- public List<Integer> glyphCoverage;- public String source;- }-- private static final class RawPayload {- public String resource;- public String format;- public String base64;- }-}diff --git a/app/core/src/main/java/stirling/software/SPDF/service/pdfjson/type3/library/Type3FontLibraryEntry.java b/app/core/src/main/java/stirling/software/SPDF/service/pdfjson/type3/library/Type3FontLibraryEntry.javadeleted file mode 100644index 6163998cf6..0000000000--- a/app/core/src/main/java/stirling/software/SPDF/service/pdfjson/type3/library/Type3FontLibraryEntry.java+++ /dev/null@@ -1,30 +0,0 @@-package stirling.software.SPDF.service.pdfjson.type3.library;--import java.util.List;--import lombok.Builder;-import lombok.Singular;-import lombok.Value;--@Value-@Builder-public class Type3FontLibraryEntry {- String id;- String label;- @Singular List<String> signatures;- @Singular List<String> aliases;- Type3FontLibraryPayload program;- Type3FontLibraryPayload webProgram;- Type3FontLibraryPayload pdfProgram;-- @Singular("glyphCode")- List<Integer> glyphCoverage;-- String source;-- public boolean hasAnyPayload() {- return (program != null && program.hasPayload())- || (webProgram != null && webProgram.hasPayload())- || (pdfProgram != null && pdfProgram.hasPayload());- }-}diff --git a/app/core/src/main/java/stirling/software/SPDF/service/pdfjson/type3/library/Type3FontLibraryMatch.java b/app/core/src/main/java/stirling/software/SPDF/service/pdfjson/type3/library/Type3FontLibraryMatch.javadeleted file mode 100644index 9f1255b2c5..0000000000--- a/app/core/src/main/java/stirling/software/SPDF/service/pdfjson/type3/library/Type3FontLibraryMatch.java+++ /dev/null@@ -1,12 +0,0 @@-package stirling.software.SPDF.service.pdfjson.type3.library;--import lombok.Builder;-import lombok.Value;--@Value-@Builder-public class Type3FontLibraryMatch {- Type3FontLibraryEntry entry;- String matchType;- String signature;-}diff --git a/app/core/src/main/java/stirling/software/SPDF/service/pdfjson/type3/library/Type3FontLibraryPayload.java b/app/core/src/main/java/stirling/software/SPDF/service/pdfjson/type3/library/Type3FontLibraryPayload.javadeleted file mode 100644index 9edfc8e239..0000000000--- a/app/core/src/main/java/stirling/software/SPDF/service/pdfjson/type3/library/Type3FontLibraryPayload.java+++ /dev/null@@ -1,104 +0,0 @@-package stirling.software.SPDF.service.pdfjson.type3.library;--import java.io.IOException;-import java.io.InputStream;-import java.util.Base64;-import java.util.Objects;-import java.util.concurrent.TimeUnit;--import org.springframework.core.io.Resource;--import lombok.extern.slf4j.Slf4j;--@Slf4j-public class Type3FontLibraryPayload {- private static final long FAILURE_RETRY_DELAY_NANOS = TimeUnit.SECONDS.toNanos(1);-- private final String directBase64;- private final Resource resource;- private final String format;- private volatile String cachedBase64;- private volatile long retryAfterNanos;-- public Type3FontLibraryPayload(String base64, String format) {- this.directBase64 = base64;- this.resource = null;- this.format = format;- }-- public Type3FontLibraryPayload(Resource resource, String format) {- this.directBase64 = null;- this.resource = resource;- this.format = format;- }-- public String getBase64() {- if (directBase64 != null) {- return directBase64;- }- if (resource == null) {- return null;- }- if (System.nanoTime() < retryAfterNanos) {- return null;- }- if (cachedBase64 == null) {- synchronized (this) {- if (cachedBase64 == null) {- if (System.nanoTime() < retryAfterNanos) {- return null;- }- try (InputStream is = resource.getInputStream()) {- byte[] bytes = is.readAllBytes();- if (bytes.length == 0) {- retryAfterNanos = System.nanoTime() + FAILURE_RETRY_DELAY_NANOS;- return null;- }- cachedBase64 = Base64.getEncoder().encodeToString(bytes);- retryAfterNanos = 0;- } catch (IOException e) {- retryAfterNanos = System.nanoTime() + FAILURE_RETRY_DELAY_NANOS;- log.warn(- "[TYPE3] Failed to read Type3 payload {}: {}",- resource.getDescription(),- e.getMessage());- return null;- }- }- }- }- return cachedBase64;- }-- public String getFormat() {- return format;- }-- public boolean hasPayload() {- if (directBase64 != null) {- return !directBase64.isBlank();- }- return resource != null && resource.exists();- }-- @Override- public boolean equals(Object o) {- if (this == o) return true;- if (o == null || getClass() != o.getClass()) return false;- Type3FontLibraryPayload that = (Type3FontLibraryPayload) o;- // Compare descriptors only: resolving base64 reads and encodes the whole font file, so- // equality must never trigger it.- return Objects.equals(directBase64, that.directBase64)- && Objects.equals(describe(resource), describe(that.resource))- && Objects.equals(format, that.format);- }-- @Override- public int hashCode() {- return Objects.hash(directBase64, describe(resource), format);- }-- private static String describe(Resource resource) {- return resource == null ? null : resource.getDescription();- }-}diff --git a/app/core/src/main/java/stirling/software/SPDF/service/pdfjson/type3/model/Type3GlyphOutline.java b/app/core/src/main/java/stirling/software/SPDF/service/pdfjson/type3/model/Type3GlyphOutline.javadeleted file mode 100644index 32bbe4f836..0000000000--- a/app/core/src/main/java/stirling/software/SPDF/service/pdfjson/type3/model/Type3GlyphOutline.java+++ /dev/null@@ -1,25 +0,0 @@-package stirling.software.SPDF.service.pdfjson.type3.model;--import java.awt.geom.GeneralPath;--import org.apache.pdfbox.pdmodel.common.PDRectangle;--import lombok.Builder;-import lombok.Value;--@Value-@Builder-public class Type3GlyphOutline {- String glyphName;- int charCode;- float advanceWidth;- PDRectangle boundingBox;- GeneralPath outline;- boolean hasStroke;- boolean hasFill;- boolean hasImages;- boolean hasText;- boolean hasShading;- String warnings;- Integer unicode;-}diff --git a/app/core/src/main/java/stirling/software/SPDF/service/pdfjson/type3/tool/Type3SignatureTool.java b/app/core/src/main/java/stirling/software/SPDF/service/pdfjson/type3/tool/Type3SignatureTool.javadeleted file mode 100644index 10bc396185..0000000000--- a/app/core/src/main/java/stirling/software/SPDF/service/pdfjson/type3/tool/Type3SignatureTool.java+++ /dev/null@@ -1,299 +0,0 @@-package stirling.software.SPDF.service.pdfjson.type3.tool;--import java.io.IOException;-import java.nio.file.Files;-import java.nio.file.Path;-import java.util.ArrayDeque;-import java.util.ArrayList;-import java.util.Collections;-import java.util.Deque;-import java.util.IdentityHashMap;-import java.util.LinkedHashMap;-import java.util.List;-import java.util.Locale;-import java.util.Map;-import java.util.Set;-import java.util.TreeSet;--import org.apache.pdfbox.Loader;-import org.apache.pdfbox.cos.COSName;-import org.apache.pdfbox.pdmodel.PDDocument;-import org.apache.pdfbox.pdmodel.PDPage;-import org.apache.pdfbox.pdmodel.PDResources;-import org.apache.pdfbox.pdmodel.font.PDFont;-import org.apache.pdfbox.pdmodel.font.PDType3Font;-import org.apache.pdfbox.pdmodel.graphics.PDXObject;-import org.apache.pdfbox.pdmodel.graphics.form.PDFormXObject;--import stirling.software.SPDF.service.pdfjson.type3.Type3FontSignatureCalculator;-import stirling.software.SPDF.service.pdfjson.type3.Type3GlyphExtractor;-import stirling.software.SPDF.service.pdfjson.type3.model.Type3GlyphOutline;--import tools.jackson.databind.ObjectMapper;-import tools.jackson.databind.ObjectWriter;-import tools.jackson.databind.SerializationFeature;-import tools.jackson.databind.json.JsonMapper;--/**- * Small CLI helper that scans a PDF for Type3 fonts, computes their signatures, and optionally- * emits JSON describing the glyph coverage. This allows Type3 library entries to be added without- * digging through backend logs.- *- * <p>Usage:- *- * <pre>- * ./gradlew :proprietary:type3SignatureTool --args="--pdf path/to/sample.pdf --output type3.json --pretty"- * </pre>- */-public final class Type3SignatureTool {-- private static final ObjectMapper OBJECT_MAPPER =- JsonMapper.builder().enable(SerializationFeature.INDENT_OUTPUT).build();-- private Type3SignatureTool() {}-- public static void main(String[] args) throws Exception {- Arguments arguments = Arguments.parse(args);- if (arguments.showHelp || arguments.pdf == null) {- printUsage();- return;- }-- Path pdfPath = arguments.pdf.toAbsolutePath();- if (!Files.exists(pdfPath)) {- throw new IOException("PDF not found: " + pdfPath);- }-- List<Map<String, Object>> fonts;- try (PDDocument document = Loader.loadPDF(pdfPath.toFile())) {- fonts = collectType3Fonts(document);- }-- Map<String, Object> output = new LinkedHashMap<>();- output.put("pdf", pdfPath.toString());- output.put("fonts", fonts);- ObjectWriter writer =- arguments.pretty- ? OBJECT_MAPPER.writerWithDefaultPrettyPrinter()- : OBJECT_MAPPER.writer();- if (arguments.output != null) {- Path parent = arguments.output.toAbsolutePath().getParent();- if (parent != null) {- Files.createDirectories(parent);- }- writer.writeValue(arguments.output.toFile(), output);- verifyOutput(arguments.output, fonts.size());- } else {- writer.writeValue(System.out, output);- }- }-- private static List<Map<String, Object>> collectType3Fonts(PDDocument document)- throws IOException {- if (document == null || document.getNumberOfPages() == 0) {- return List.of();- }- List<Map<String, Object>> fonts = new ArrayList<>();- Type3GlyphExtractor glyphExtractor = new Type3GlyphExtractor();- Set<Object> visited = Collections.newSetFromMap(new IdentityHashMap<>());-- for (int pageIndex = 0; pageIndex < document.getNumberOfPages(); pageIndex++) {- PDPage page = document.getPage(pageIndex);- PDResources resources = page.getResources();- if (resources == null) {- continue;- }- scanResources(document, pageIndex + 1, resources, glyphExtractor, visited, fonts);- }- return fonts;- }-- private static void scanResources(- PDDocument document,- int pageNumber,- PDResources resources,- Type3GlyphExtractor glyphExtractor,- Set<Object> visited,- List<Map<String, Object>> fonts)- throws IOException {- if (resources == null) {- return;- }-- for (COSName name : resources.getFontNames()) {- PDFont font = resources.getFont(name);- if (!(font instanceof PDType3Font type3Font)) {- continue;- }- Object cosObject = type3Font.getCOSObject();- if (cosObject != null && !visited.add(cosObject)) {- continue;- }- fonts.add(- describeFont(document, pageNumber, name.getName(), type3Font, glyphExtractor));- }-- Deque<PDResources> embedded = new ArrayDeque<>();- for (COSName name : resources.getXObjectNames()) {- PDXObject xobject = resources.getXObject(name);- if (xobject instanceof PDFormXObject form && form.getResources() != null) {- embedded.add(form.getResources());- }- }- while (!embedded.isEmpty()) {- scanResources(document, pageNumber, embedded.pop(), glyphExtractor, visited, fonts);- }- }-- private static Map<String, Object> describeFont(- PDDocument document,- int pageNumber,- String fontId,- PDType3Font font,- Type3GlyphExtractor glyphExtractor)- throws IOException {- Map<String, Object> payload = new LinkedHashMap<>();- payload.put("pageNumber", pageNumber);- payload.put("fontId", fontId);- payload.put("baseName", safeFontName(font));- payload.put("alias", normalizeAlias(safeFontName(font)));- payload.put("encoding", resolveEncoding(font));- payload.put("signature", Type3FontSignatureCalculator.computeSignature(font));-- List<Type3GlyphOutline> glyphs =- glyphExtractor.extractGlyphs(document, font, fontId, pageNumber);- payload.put("glyphCount", glyphs != null ? glyphs.size() : 0);-- Set<Integer> coverage = new TreeSet<>();- if (glyphs != null) {- for (Type3GlyphOutline glyph : glyphs) {- if (glyph == null) {- continue;- }- if (glyph.getUnicode() != null) {- coverage.add(glyph.getUnicode());- } else if (glyph.getCharCode() >= 0) {- coverage.add(0xF000 | (glyph.getCharCode() & 0xFF));- }- }- List<Map<String, Object>> warnings = new ArrayList<>();- for (Type3GlyphOutline glyph : glyphs) {- if (glyph != null && glyph.getWarnings() != null) {- Map<String, Object> warning = new LinkedHashMap<>();- warning.put("glyphName", glyph.getGlyphName());- warning.put("message", glyph.getWarnings());- warnings.add(warning);- }- }- if (!warnings.isEmpty()) {- payload.put("warnings", warnings);- }- }- if (!coverage.isEmpty()) {- payload.put("glyphCoverage", new ArrayList<>(coverage));- }- return payload;- }-- private static void verifyOutput(Path output, int fontCount) throws IOException {- Path absolute = output.toAbsolutePath();- if (!Files.exists(absolute)) {- throw new IOException("Expected output file not found: " + absolute);- }- long size = Files.size(absolute);- if (size == 0) {- throw new IOException("Output file is empty: " + absolute);- }- System.out.println(- "Wrote " + fontCount + " fonts to " + absolute + " (" + size + " bytes, verified)");- }-- private static String resolveEncoding(PDType3Font font) {- if (font == null || font.getEncoding() == null) {- return null;- }- Object encoding = font.getCOSObject().getDictionaryObject(COSName.ENCODING);- return encoding != null- ? encoding.toString()- : font.getEncoding().getClass().getSimpleName();- }-- private static String safeFontName(PDType3Font font) {- if (font == null) {- return null;- }- try {- if (font.getName() != null) {- return font.getName();- }- } catch (Exception ignored) {- // ignore- }- if (font.getCOSObject() != null) {- return font.getCOSObject().getNameAsString(COSName.BASE_FONT);- }- return null;- }-- private static String normalizeAlias(String name) {- if (name == null) {- return null;- }- int plus = name.indexOf('+');- String normalized = plus >= 0 ? name.substring(plus + 1) : name;- normalized = normalized.trim();- return normalized.isEmpty() ? null : normalized.toLowerCase(Locale.ROOT);- }-- private static void printUsage() {- System.out.println(- """- Type3SignatureTool - dump Type3 font signatures for library building- Usage:- --pdf <file.pdf> Input PDF to analyse (required)- --output <file.json> Optional output file (defaults to stdout)- --pretty Pretty-print JSON output- --help Show this help-- Example:- ./gradlew :proprietary:type3SignatureTool --args="--pdf samples/foo.pdf --output foo.json --pretty"- """);- }-- private static final class Arguments {- private final Path pdf;- private final Path output;- private final boolean pretty;- private final boolean showHelp;-- private Arguments(Path pdf, Path output, boolean pretty, boolean showHelp) {- this.pdf = pdf;- this.output = output;- this.pretty = pretty;- this.showHelp = showHelp;- }-- static Arguments parse(String[] args) {- if (args == null || args.length == 0) {- return new Arguments(null, null, true, true);- }- Path pdf = null;- Path output = null;- boolean pretty = false;- boolean showHelp = false;- for (int i = 0; i < args.length; i++) {- String arg = args[i];- if ("--pdf".equals(arg) && i + 1 < args.length) {- pdf = Path.of(args[++i]);- } else if ("--output".equals(arg) && i + 1 < args.length) {- output = Path.of(args[++i]);- } else if ("--pretty".equals(arg)) {- pretty = true;- } else if ("--help".equals(arg) || "-h".equals(arg)) {- showHelp = true;- }- }- return new Arguments(pdf, output, pretty, showHelp);- }- }-}diff --git a/app/core/src/main/resources/application.properties b/app/core/src/main/resources/application.propertiesindex 86e35ec66d..3f7beac6c3 100644--- a/app/core/src/main/resources/application.properties+++ b/app/core/src/main/resources/application.properties@@ -13,7 +13,6 @@ logging.level.org.eclipse.jetty=WARN#logging.level.org.opensaml=DEBUG#logging.level.stirling.software.proprietary.security=DEBUGlogging.level.com.zaxxer.hikari=WARN-logging.level.stirling.software.SPDF.service.PdfJsonConversionService=INFOlogging.level.stirling.software.common.service.JobExecutorService=INFOlogging.level.stirling.software.common.service.TaskManager=INFOspring.jpa.open-in-view=falsediff --git a/app/core/src/main/resources/logback.xml b/app/core/src/main/resources/logback.xmlindex f96540d3cc..59603d67a2 100644--- a/app/core/src/main/resources/logback.xml+++ b/app/core/src/main/resources/logback.xml@@ -51,27 +51,6 @@</rollingPolicy></appender>- <!-- Suppress PDFBox PDSimpleFont's per-charcode .notdef WARN.-- Required by the v2 PDF text editor's `buildReverseUnicodeMap`- which DELIBERATELY iterates every charcode in 0..0xFFFF to- discover the encoding-to-Unicode map of an embedded subset- font. For any subset font ~99% of those probes hit .notdef,- and the default WARN level for those misses turned info.log- into a 1.4 GB monster overnight.-- This declarative logback entry is the SOLE mechanism: it is- visible to ops and revertable via configuration. An earlier- build also mutated this logger's level from a static block in- PdfTextEditorCharcodeController, which silenced the same- warnings JVM-wide with no trace in any config file - that- static block has been removed in favour of this entry. -->- <logger name="org.apache.pdfbox.pdmodel.font.PDSimpleFont"- level="ERROR" additivity="false">- <appender-ref ref="CONSOLE"/>- <appender-ref ref="GENERAL"/>- </logger>-<!-- Root Logger --><root level="INFO"><appender-ref ref="CONSOLE"/>diff --git a/app/core/src/main/resources/settings.yml.template b/app/core/src/main/resources/settings.yml.templateindex 810f4693df..dcbbc2b01d 100644--- a/app/core/src/main/resources/settings.yml.template+++ b/app/core/src/main/resources/settings.yml.template@@ -526,21 +526,3 @@ cluster:maxWaitMillis: 2000 # Must be > 0: negative blocks forever, 0 fails the borrow instantly.timeBetweenEvictionRunsMillis: 30000 # Idle-evictor interval; minIdle only applies while it runs.testOnBorrow: true # Local isOpen() check only, no round trip.--pdfEditor:- fallback-font: classpath:/static/fonts/NotoSans-Regular.ttf # Override to point at a custom fallback font- cache:- max-bytes: -1 # Max in-memory cache size in bytes; -1 disables byte cap- max-percent: 20 # Max in-memory cache as % of JVM max; used when max-bytes <= 0- font-normalization:- enabled: false # IMPORTANT: Disable to preserve ToUnicode CMaps for correct font rendering. Ghostscript strips Unicode mappings from CID fonts.- cff-converter:- enabled: true # Wrap CFF/Type1CFF fonts as OpenType-CFF for browser compatibility- method: python # Converter method: 'python' (fontTools, recommended - wraps as OTF), 'fontforge' (legacy - converts to TTF, may hang on CID fonts)- python-command: /opt/venv/bin/python3 # Python interpreter path- python-script: /scripts/convert_cff_to_ttf.py # Path to font wrapping script- fontforge-command: fontforge # Override if FontForge is installed under a different name/path- type3:- library:- enabled: true # Match common Type3 fonts against the built-in library of converted programs- index: classpath:/type3/library/index.json # Override to point at a custom index.json (supports http:, file:, classpath:)diff --git a/app/core/src/main/resources/type3/catalogue.json b/app/core/src/main/resources/type3/catalogue.jsondeleted file mode 100644index 4aca2f414d..0000000000--- a/app/core/src/main/resources/type3/catalogue.json+++ /dev/null@@ -1,592 +0,0 @@-[- {- "source": "01_Matplotlib.pdf",- "fontName": "DejaVuSans",- "encoding": "1867"- },- {- "source": "01_Matplotlib.pdf",- "fontName": "DejaVuSans",- "encoding": "1888"- },- {- "source": "01_Matplotlib.pdf",- "fontName": "DejaVuSans",- "encoding": "2029"- },- {- "source": "01_Matplotlib.pdf",- "fontName": "DejaVuSans",- "encoding": "2069"- },- {- "source": "01_Matplotlib.pdf",- "fontName": "DejaVuSans",- "encoding": "2089"- },- {- "source": "01_Matplotlib.pdf",- "fontName": "DejaVuSans",- "encoding": "2116"- },- {- "source": "01_Matplotlib.pdf",- "fontName": "DejaVuSansMono",- "encoding": "2174"- },- {- "source": "01_Matplotlib.pdf",- "fontName": "DejaVuSans-Oblique",- "encoding": "2192"- },- {- "source": "01_Matplotlib.pdf",- "fontName": "DejaVuSans",- "encoding": "2209"- },- {- "source": "01_Matplotlib.pdf",- "fontName": "Cmsy10",- "encoding": "2228"- },- {- "source": "01_Matplotlib.pdf",- "fontName": "STIXSizeThreeSym-Regular",- "encoding": "2233"- },- {- "source": "01_Matplotlib.pdf",- "fontName": "DejaVuSansDisplay",- "encoding": "2239"- },- {- "source": "01_Matplotlib.pdf",- "fontName": "DejaVuSans",- "encoding": "4403"- },- {- "source": "01_Matplotlib.pdf",- "fontName": "DejaVuSans",- "encoding": "4438"- },- {- "source": "01_Matplotlib.pdf",- "fontName": "DejaVuSans",- "encoding": "4519"- },- {- "source": "01_Matplotlib.pdf",- "fontName": "DejaVuSans",- "encoding": "4685"- },- {- "source": "01_Matplotlib.pdf",- "fontName": "DejaVuSans",- "encoding": "4733"- },- {- "source": "01_Matplotlib.pdf",- "fontName": "DejaVuSans",- "encoding": "4782"- },- {- "source": "01_Matplotlib.pdf",- "fontName": "DejaVuSans",- "encoding": "4813"- },- {- "source": "01_Matplotlib.pdf",- "fontName": "DejaVuSans",- "encoding": "4834"- },- {- "source": "01_Matplotlib.pdf",- "fontName": "DejaVuSansMono",- "encoding": "4878"- },- {- "source": "01_Matplotlib.pdf",- "fontName": "DejaVuSans",- "encoding": "4906"- },- {- "source": "01_Matplotlib.pdf",- "fontName": "DejaVuSans",- "encoding": "4929"- },- {- "source": "01_Matplotlib.pdf",- "fontName": "DejaVuSans",- "encoding": "4971"- },- {- "source": "01_Matplotlib.pdf",- "fontName": "DejaVuSans",- "encoding": "5001"- },- {- "source": "01_Matplotlib.pdf",- "fontName": "DejaVuSans",- "encoding": "5030"- },- {- "source": "01_Matplotlib.pdf",- "fontName": "DejaVuSans",- "encoding": "5052"- },- {- "source": "01_Matplotlib.pdf",- "fontName": "DejaVuSans",- "encoding": "5083"- },- {- "source": "01_Matplotlib.pdf",- "fontName": "DejaVuSans",- "encoding": "5116"- },- {- "source": "01_Matplotlib.pdf",- "fontName": "DejaVuSans",- "encoding": "5143"- },- {- "source": "01_Matplotlib.pdf",- "fontName": "DejaVuSans",- "encoding": "5175"- },- {- "source": "01_Matplotlib.pdf",- "fontName": "DejaVuSans",- "encoding": "5207"- },- {- "source": "01_Matplotlib.pdf",- "fontName": "DejaVuSans",- "encoding": "5243"- },- {- "source": "01_Matplotlib.pdf",- "fontName": "Cmr10",- "encoding": "5263"- },- {- "source": "01_Matplotlib.pdf",- "fontName": "Cmex10",- "encoding": "5270"- },- {- "source": "01_Matplotlib.pdf",- "fontName": "Cmsy10",- "encoding": "5275"- },- {- "source": "01_Matplotlib.pdf",- "fontName": "Cmmi10",- "encoding": "5280"- },- {- "source": "01_Matplotlib.pdf",- "fontName": "DejaVuSans",- "encoding": "5295"- },- {- "source": "01_Matplotlib.pdf",- "fontName": "DejaVuSans-Oblique",- "encoding": "5313"- },- {- "source": "01_Matplotlib.pdf",- "fontName": "DejaVuSansDisplay",- "encoding": "5319"- },- {- "source": "01_Matplotlib.pdf",- "fontName": "DejaVuSans",- "encoding": "5334"- },- {- "source": "01_Matplotlib.pdf",- "fontName": "DejaVuSans",- "encoding": "5370"- },- {- "source": "01_Matplotlib.pdf",- "fontName": "DejaVuSans",- "encoding": "5399"- },- {- "source": "01_Matplotlib.pdf",- "fontName": "DejaVuSans",- "encoding": "5427"- },- {- "source": "01_Matplotlib.pdf",- "fontName": "DejaVuSans",- "encoding": "5459"- },- {- "source": "01_Matplotlib.pdf",- "fontName": "DejaVuSans",- "encoding": "5486"- },- {- "source": "01_Matplotlib.pdf",- "fontName": "DejaVuSans",- "encoding": "5513"- },- {- "source": "01_Matplotlib.pdf",- "fontName": "DejaVuSans",- "encoding": "5554"- },- {- "source": "01_Matplotlib.pdf",- "fontName": "DejaVuSans",- "encoding": "5601"- },- {- "source": "01_Matplotlib.pdf",- "fontName": "DejaVuSans",- "encoding": "5647"- },- {- "source": "01_Matplotlib.pdf",- "fontName": "DejaVuSans",- "encoding": "5694"- },- {- "source": "01_Matplotlib.pdf",- "fontName": "DejaVuSans",- "encoding": "5732"- },- {- "source": "01_Matplotlib.pdf",- "fontName": "DejaVuSans",- "encoding": "5771"- },- {- "source": "01_Matplotlib.pdf",- "fontName": "DejaVuSans",- "encoding": "5803"- },- {- "source": "01_Matplotlib.pdf",- "fontName": "DejaVuSans",- "encoding": "5861"- },- {- "source": "01_Matplotlib.pdf",- "fontName": "DejaVuSans",- "encoding": "5904"- },- {- "source": "01_Matplotlib.pdf",- "fontName": "DejaVuSans",- "encoding": "5924"- },- {- "source": "01_Matplotlib.pdf",- "fontName": "DejaVuSans",- "encoding": "5951"- },- {- "source": "01_Matplotlib.pdf",- "fontName": "DejaVuSans",- "encoding": "6084"- },- {- "source": "01_Matplotlib.pdf",- "fontName": "DejaVuSans",- "encoding": "6445"- },- {- "source": "01_Matplotlib.pdf",- "fontName": "DejaVuSans",- "encoding": "7195"- },- {- "source": "01_Matplotlib.pdf",- "fontName": "DejaVuSans",- "encoding": "7409"- },- {- "source": "01_Matplotlib.pdf",- "fontName": "DejaVuSans",- "encoding": "7474"- },- {- "source": "01_Matplotlib.pdf",- "fontName": "DejaVuSans",- "encoding": "7708"- },- {- "source": "01_Matplotlib.pdf",- "fontName": "DejaVuSans",- "encoding": "7747"- },- {- "source": "01_Matplotlib.pdf",- "fontName": "DejaVuSans",- "encoding": "7885"- },- {- "source": "01_Matplotlib.pdf",- "fontName": "DejaVuSans",- "encoding": "9029"- },- {- "source": "01_Matplotlib.pdf",- "fontName": "DejaVuSans",- "encoding": "9617"- },- {- "source": "01_Matplotlib.pdf",- "fontName": "DejaVuSans",- "encoding": "10460"- },- {- "source": "01_Matplotlib.pdf",- "fontName": "DejaVuSans",- "encoding": "11445"- },- {- "source": "01_Matplotlib.pdf",- "fontName": "DejaVuSans-Bold",- "encoding": "11486"- },- {- "source": "01_Matplotlib.pdf",- "fontName": "DejaVuSans",- "encoding": "11497"- },- {- "source": "01_Matplotlib.pdf",- "fontName": "DejaVuSans",- "encoding": "11543"- },- {- "source": "01_Matplotlib.pdf",- "fontName": "DejaVuSans",- "encoding": "12280"- },- {- "source": "01_Matplotlib.pdf",- "fontName": "DejaVuSans",- "encoding": "12301"- },- {- "source": "01_Matplotlib.pdf",- "fontName": "DejaVuSans",- "encoding": "12350"- },- {- "source": "01_Matplotlib.pdf",- "fontName": "DejaVuSans",- "encoding": "12372"- },- {- "source": "01_Matplotlib.pdf",- "fontName": "DejaVuSans",- "encoding": "12395"- },- {- "source": "01_Matplotlib.pdf",- "fontName": "DejaVuSans",- "encoding": "12416"- },- {- "source": "01_Matplotlib.pdf",- "fontName": "DejaVuSans",- "encoding": "13324"- },- {- "source": "02_Matplotlib.pdf",- "fontName": "DejaVuSans",- "encoding": "3214"- },- {- "source": "02_Matplotlib.pdf",- "fontName": "DejaVuSans",- "encoding": "3251"- },- {- "source": "02_Matplotlib.pdf",- "fontName": "DejaVuSans",- "encoding": "7190"- },- {- "source": "02_Matplotlib.pdf",- "fontName": "DejaVuSans",- "encoding": "9937"- },- {- "source": "02_Matplotlib.pdf",- "fontName": "DejaVuSans",- "encoding": "10792"- },- {- "source": "02_Matplotlib.pdf",- "fontName": "DejaVuSans",- "encoding": "10852"- },- {- "source": "02_Matplotlib.pdf",- "fontName": "DejaVuSans",- "encoding": "14712"- },- {- "source": "02_Matplotlib.pdf",- "fontName": "DejaVuSans",- "encoding": "18396"- },- {- "source": "02_Matplotlib.pdf",- "fontName": "DejaVuSans",- "encoding": "18719"- },- {- "source": "02_Matplotlib.pdf",- "fontName": "DejaVuSans-Bold",- "encoding": "18741"- },- {- "source": "02_Matplotlib.pdf",- "fontName": "DejaVuSans",- "encoding": "18778"- },- {- "source": "02_Matplotlib.pdf",- "fontName": "DejaVuSans",- "encoding": "18804"- },- {- "source": "02_Matplotlib.pdf",- "fontName": "DejaVuSans",- "encoding": "20974"- },- {- "source": "02_Matplotlib.pdf",- "fontName": "DejaVuSans",- "encoding": "20993"- },- {- "source": "02_Matplotlib.pdf",- "fontName": "DejaVuSans",- "encoding": "21093"- },- {- "source": "02_Matplotlib.pdf",- "fontName": "DejaVuSans",- "encoding": "21117"- },- {- "source": "02_Matplotlib.pdf",- "fontName": "DejaVuSans",- "encoding": "21141"- },- {- "source": "02_Matplotlib.pdf",- "fontName": "DejaVuSans",- "encoding": "21174"- },- {- "source": "03_handout-beginner.pdf",- "fontName": "BMQQDV+DejaVuSans",- "encoding": "17"- },- {- "source": "03_handout-beginner.pdf",- "fontName": "EVICAO+DejaVuSans-Bold",- "encoding": "133"- },- {- "source": "03_handout-beginner.pdf",- "fontName": "BMQQDV+DejaVuSans",- "encoding": "152"- },- {- "source": "04_handout-intermediate.pdf",- "fontName": "BMQQDV+DejaVuSans",- "encoding": "13"- },- {- "source": "04_handout-intermediate.pdf",- "fontName": "BMQQDV+DejaVuSans",- "encoding": "85"- },- {- "source": "04_handout-intermediate.pdf",- "fontName": "BMQQDV+DejaVuSans",- "encoding": "104"- },- {- "source": "04_handout-intermediate.pdf",- "fontName": "BMQQDV+DejaVuSans",- "encoding": "121"- },- {- "source": "04_handout-intermediate.pdf",- "fontName": "BMQQDV+DejaVuSans",- "encoding": "135"- },- {- "source": "04_handout-intermediate.pdf",- "fontName": "BMQQDV+DejaVuSans",- "encoding": "159"- },- {- "source": "04_handout-intermediate.pdf",- "fontName": "BMQQDV+DejaVuSans",- "encoding": "179"- },- {- "source": "04_handout-intermediate.pdf",- "fontName": "BMQQDV+DejaVuSans",- "encoding": "198"- },- {- "source": "04_handout-intermediate.pdf",- "fontName": "NVMZUP+SourceCodePro-Regular",- "encoding": "208"- },- {- "source": "04_handout-intermediate.pdf",- "fontName": "BMQQDV+DejaVuSans",- "encoding": "231"- },- {- "source": "04_handout-intermediate.pdf",- "fontName": "NVMZUP+SourceCodePro-Regular",- "encoding": "241"- },- {- "source": "07_matplotlib.pdf",- "fontName": "SauceCodePowerline-Bold",- "encoding": "22"- },- {- "source": "07_matplotlib.pdf",- "fontName": "SauceCodePowerline-Regular",- "encoding": "47"- },- {- "source": "07_matplotlib.pdf",- "fontName": "SauceCodePowerline-Regular",- "encoding": "65"- },- {- "source": "07_matplotlib.pdf",- "fontName": "SauceCodePowerline-Bold",- "encoding": "110"- },- {- "source": "08_matplotlib.pdf",- "fontName": "F36",- "encoding": "12"- },- {- "source": "08_matplotlib.pdf",- "fontName": "F59",- "encoding": "42"- }-]\ No newline at end of filediff --git a/app/core/src/main/resources/type3/library/fonts/cm/cmbx10.ttf b/app/core/src/main/resources/type3/library/fonts/cm/cmbx10.ttfdeleted file mode 100644index 2c7198e5d3..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/cm/cmbx10.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/cm/cmmi10.ttf b/app/core/src/main/resources/type3/library/fonts/cm/cmmi10.ttfdeleted file mode 100644index bd30a3f977..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/cm/cmmi10.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/cm/cmr10.ttf b/app/core/src/main/resources/type3/library/fonts/cm/cmr10.ttfdeleted file mode 100644index 1c3fff0a6e..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/cm/cmr10.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/cm/cmss10.ttf b/app/core/src/main/resources/type3/library/fonts/cm/cmss10.ttfdeleted file mode 100644index d7513c86a6..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/cm/cmss10.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/cm/cmsy10.ttf b/app/core/src/main/resources/type3/library/fonts/cm/cmsy10.ttfdeleted file mode 100644index 45d8421a5b..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/cm/cmsy10.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/cm/cmti10.ttf b/app/core/src/main/resources/type3/library/fonts/cm/cmti10.ttfdeleted file mode 100644index 993d5c029f..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/cm/cmti10.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/cm/cmtt10.ttf b/app/core/src/main/resources/type3/library/fonts/cm/cmtt10.ttfdeleted file mode 100644index 1651877dbe..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/cm/cmtt10.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/dejavu/DejaVuSans-Bold.ttf b/app/core/src/main/resources/type3/library/fonts/dejavu/DejaVuSans-Bold.ttfdeleted file mode 100644index 6d65fa7dc4..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/dejavu/DejaVuSans-Bold.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/dejavu/DejaVuSans-BoldOblique.ttf b/app/core/src/main/resources/type3/library/fonts/dejavu/DejaVuSans-BoldOblique.ttfdeleted file mode 100644index 753f2d80b1..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/dejavu/DejaVuSans-BoldOblique.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/dejavu/DejaVuSans-ExtraLight.ttf b/app/core/src/main/resources/type3/library/fonts/dejavu/DejaVuSans-ExtraLight.ttfdeleted file mode 100644index b09f32d7d6..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/dejavu/DejaVuSans-ExtraLight.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/dejavu/DejaVuSans-Oblique.ttf b/app/core/src/main/resources/type3/library/fonts/dejavu/DejaVuSans-Oblique.ttfdeleted file mode 100644index 999bac7714..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/dejavu/DejaVuSans-Oblique.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/dejavu/DejaVuSans.ttf b/app/core/src/main/resources/type3/library/fonts/dejavu/DejaVuSans.ttfdeleted file mode 100644index e5f7eecce4..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/dejavu/DejaVuSans.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/dejavu/DejaVuSansCondensed-Bold.ttf b/app/core/src/main/resources/type3/library/fonts/dejavu/DejaVuSansCondensed-Bold.ttfdeleted file mode 100644index 22987c62d9..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/dejavu/DejaVuSansCondensed-Bold.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/dejavu/DejaVuSansCondensed-BoldOblique.ttf b/app/core/src/main/resources/type3/library/fonts/dejavu/DejaVuSansCondensed-BoldOblique.ttfdeleted file mode 100644index f5fa0ca26f..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/dejavu/DejaVuSansCondensed-BoldOblique.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/dejavu/DejaVuSansCondensed-Oblique.ttf b/app/core/src/main/resources/type3/library/fonts/dejavu/DejaVuSansCondensed-Oblique.ttfdeleted file mode 100644index 7fde907894..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/dejavu/DejaVuSansCondensed-Oblique.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/dejavu/DejaVuSansCondensed.ttf b/app/core/src/main/resources/type3/library/fonts/dejavu/DejaVuSansCondensed.ttfdeleted file mode 100644index 3259bc21ae..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/dejavu/DejaVuSansCondensed.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/dejavu/DejaVuSansMono-Bold.ttf b/app/core/src/main/resources/type3/library/fonts/dejavu/DejaVuSansMono-Bold.ttfdeleted file mode 100644index 8184ced8cf..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/dejavu/DejaVuSansMono-Bold.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/dejavu/DejaVuSansMono-BoldOblique.ttf b/app/core/src/main/resources/type3/library/fonts/dejavu/DejaVuSansMono-BoldOblique.ttfdeleted file mode 100644index 754dca7325..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/dejavu/DejaVuSansMono-BoldOblique.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/dejavu/DejaVuSansMono-Oblique.ttf b/app/core/src/main/resources/type3/library/fonts/dejavu/DejaVuSansMono-Oblique.ttfdeleted file mode 100644index 4c858d401a..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/dejavu/DejaVuSansMono-Oblique.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/dejavu/DejaVuSansMono.ttf b/app/core/src/main/resources/type3/library/fonts/dejavu/DejaVuSansMono.ttfdeleted file mode 100644index f5786022f1..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/dejavu/DejaVuSansMono.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/dejavu/DejaVuSerif-Bold.ttf b/app/core/src/main/resources/type3/library/fonts/dejavu/DejaVuSerif-Bold.ttfdeleted file mode 100644index 3bb755fa1e..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/dejavu/DejaVuSerif-Bold.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/dejavu/DejaVuSerif-BoldItalic.ttf b/app/core/src/main/resources/type3/library/fonts/dejavu/DejaVuSerif-BoldItalic.ttfdeleted file mode 100644index a36dd4b70a..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/dejavu/DejaVuSerif-BoldItalic.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/dejavu/DejaVuSerif-Italic.ttf b/app/core/src/main/resources/type3/library/fonts/dejavu/DejaVuSerif-Italic.ttfdeleted file mode 100644index 805daf2228..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/dejavu/DejaVuSerif-Italic.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/dejavu/DejaVuSerif.ttf b/app/core/src/main/resources/type3/library/fonts/dejavu/DejaVuSerif.ttfdeleted file mode 100644index 0b803d206c..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/dejavu/DejaVuSerif.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/dejavu/DejaVuSerifCondensed-Bold.ttf b/app/core/src/main/resources/type3/library/fonts/dejavu/DejaVuSerifCondensed-Bold.ttfdeleted file mode 100644index 222bf134bc..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/dejavu/DejaVuSerifCondensed-Bold.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/dejavu/DejaVuSerifCondensed-BoldItalic.ttf b/app/core/src/main/resources/type3/library/fonts/dejavu/DejaVuSerifCondensed-BoldItalic.ttfdeleted file mode 100644index e44663695d..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/dejavu/DejaVuSerifCondensed-BoldItalic.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/dejavu/DejaVuSerifCondensed-Italic.ttf b/app/core/src/main/resources/type3/library/fonts/dejavu/DejaVuSerifCondensed-Italic.ttfdeleted file mode 100644index c529df31bf..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/dejavu/DejaVuSerifCondensed-Italic.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/dejavu/DejaVuSerifCondensed.ttf b/app/core/src/main/resources/type3/library/fonts/dejavu/DejaVuSerifCondensed.ttfdeleted file mode 100644index d3959b3228..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/dejavu/DejaVuSerifCondensed.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/liberation/LiberationMono-Bold.ttf b/app/core/src/main/resources/type3/library/fonts/liberation/LiberationMono-Bold.ttfdeleted file mode 100644index 2e46737ac7..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/liberation/LiberationMono-Bold.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/liberation/LiberationMono-BoldItalic.ttf b/app/core/src/main/resources/type3/library/fonts/liberation/LiberationMono-BoldItalic.ttfdeleted file mode 100644index d1f46d7cd8..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/liberation/LiberationMono-BoldItalic.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/liberation/LiberationMono-Italic.ttf b/app/core/src/main/resources/type3/library/fonts/liberation/LiberationMono-Italic.ttfdeleted file mode 100644index 954c39436f..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/liberation/LiberationMono-Italic.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/liberation/LiberationMono-Regular.ttf b/app/core/src/main/resources/type3/library/fonts/liberation/LiberationMono-Regular.ttfdeleted file mode 100644index e774859cba..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/liberation/LiberationMono-Regular.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/liberation/LiberationSans-Bold.ttf b/app/core/src/main/resources/type3/library/fonts/liberation/LiberationSans-Bold.ttfdeleted file mode 100644index dc5d57f15f..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/liberation/LiberationSans-Bold.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/liberation/LiberationSans-BoldItalic.ttf b/app/core/src/main/resources/type3/library/fonts/liberation/LiberationSans-BoldItalic.ttfdeleted file mode 100644index 158488a12e..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/liberation/LiberationSans-BoldItalic.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/liberation/LiberationSans-Italic.ttf b/app/core/src/main/resources/type3/library/fonts/liberation/LiberationSans-Italic.ttfdeleted file mode 100644index 25970d9d57..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/liberation/LiberationSans-Italic.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/liberation/LiberationSans-Regular.ttf b/app/core/src/main/resources/type3/library/fonts/liberation/LiberationSans-Regular.ttfdeleted file mode 100644index e6339859d0..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/liberation/LiberationSans-Regular.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/liberation/LiberationSerif-Bold.ttf b/app/core/src/main/resources/type3/library/fonts/liberation/LiberationSerif-Bold.ttfdeleted file mode 100644index 3c7c55b575..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/liberation/LiberationSerif-Bold.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/liberation/LiberationSerif-BoldItalic.ttf b/app/core/src/main/resources/type3/library/fonts/liberation/LiberationSerif-BoldItalic.ttfdeleted file mode 100644index 6b35d9f7c1..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/liberation/LiberationSerif-BoldItalic.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/liberation/LiberationSerif-Italic.ttf b/app/core/src/main/resources/type3/library/fonts/liberation/LiberationSerif-Italic.ttfdeleted file mode 100644index 54d516481c..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/liberation/LiberationSerif-Italic.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/liberation/LiberationSerif-Regular.ttf b/app/core/src/main/resources/type3/library/fonts/liberation/LiberationSerif-Regular.ttfdeleted file mode 100644index 5e5550c0af..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/liberation/LiberationSerif-Regular.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-Black.ttf b/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-Black.ttfdeleted file mode 100644index 0974247d7c..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-Black.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-BlackItalic.ttf b/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-BlackItalic.ttfdeleted file mode 100644index 5bea657fce..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-BlackItalic.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-Bold.ttf b/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-Bold.ttfdeleted file mode 100644index 21fbbcc6d6..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-Bold.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-BoldItalic.ttf b/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-BoldItalic.ttfdeleted file mode 100644index 8faac05c22..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-BoldItalic.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-Condensed.ttf b/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-Condensed.ttfdeleted file mode 100644index a55d3fcfb3..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-Condensed.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-CondensedBlack.ttf b/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-CondensedBlack.ttfdeleted file mode 100644index fa2163405d..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-CondensedBlack.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-CondensedBlackItalic.ttf b/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-CondensedBlackItalic.ttfdeleted file mode 100644index 4f4e6d1e9c..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-CondensedBlackItalic.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-CondensedBold.ttf b/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-CondensedBold.ttfdeleted file mode 100644index 4912d87fcf..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-CondensedBold.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-CondensedBoldItalic.ttf b/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-CondensedBoldItalic.ttfdeleted file mode 100644index 57c3b43095..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-CondensedBoldItalic.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-CondensedExtraBold.ttf b/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-CondensedExtraBold.ttfdeleted file mode 100644index 4acd19d2ed..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-CondensedExtraBold.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-CondensedExtraBoldItalic.ttf b/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-CondensedExtraBoldItalic.ttfdeleted file mode 100644index addcb56f5b..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-CondensedExtraBoldItalic.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-CondensedExtraLight.ttf b/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-CondensedExtraLight.ttfdeleted file mode 100644index 54082b208e..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-CondensedExtraLight.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-CondensedExtraLightItalic.ttf b/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-CondensedExtraLightItalic.ttfdeleted file mode 100644index 87a0624e0a..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-CondensedExtraLightItalic.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-CondensedItalic.ttf b/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-CondensedItalic.ttfdeleted file mode 100644index 8a6de5cad9..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-CondensedItalic.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-CondensedLight.ttf b/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-CondensedLight.ttfdeleted file mode 100644index 02e817c70e..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-CondensedLight.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-CondensedLightItalic.ttf b/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-CondensedLightItalic.ttfdeleted file mode 100644index 67f99d1488..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-CondensedLightItalic.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-CondensedMedium.ttf b/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-CondensedMedium.ttfdeleted file mode 100644index 515cef661b..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-CondensedMedium.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-CondensedMediumItalic.ttf b/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-CondensedMediumItalic.ttfdeleted file mode 100644index 1952105389..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-CondensedMediumItalic.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-CondensedSemiBold.ttf b/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-CondensedSemiBold.ttfdeleted file mode 100644index 9ce5f3b07a..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-CondensedSemiBold.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-CondensedSemiBoldItalic.ttf b/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-CondensedSemiBoldItalic.ttfdeleted file mode 100644index f4c36bf2be..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-CondensedSemiBoldItalic.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-CondensedThin.ttf b/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-CondensedThin.ttfdeleted file mode 100644index 6c754b6d20..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-CondensedThin.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-CondensedThinItalic.ttf b/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-CondensedThinItalic.ttfdeleted file mode 100644index 73f005a3e2..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-CondensedThinItalic.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-ExtraBold.ttf b/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-ExtraBold.ttfdeleted file mode 100644index e69de29bb2..0000000000diff --git a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-ExtraBoldItalic.ttf b/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-ExtraBoldItalic.ttfdeleted file mode 100644index 3f48694e50..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-ExtraBoldItalic.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-ExtraCondensed.ttf b/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-ExtraCondensed.ttfdeleted file mode 100644index a15499b257..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-ExtraCondensed.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-ExtraCondensedBlack.ttf b/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-ExtraCondensedBlack.ttfdeleted file mode 100644index 3ecae1b52f..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-ExtraCondensedBlack.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-ExtraCondensedBlackItalic.ttf b/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-ExtraCondensedBlackItalic.ttfdeleted file mode 100644index 7558fcf6fc..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-ExtraCondensedBlackItalic.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-ExtraCondensedBold.ttf b/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-ExtraCondensedBold.ttfdeleted file mode 100644index e575ce5864..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-ExtraCondensedBold.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-ExtraCondensedBoldItalic.ttf b/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-ExtraCondensedBoldItalic.ttfdeleted file mode 100644index 7cbadb4b5a..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-ExtraCondensedBoldItalic.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-ExtraCondensedExtraBold.ttf b/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-ExtraCondensedExtraBold.ttfdeleted file mode 100644index ec244607ed..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-ExtraCondensedExtraBold.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-ExtraCondensedExtraBoldItalic.ttf b/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-ExtraCondensedExtraBoldItalic.ttfdeleted file mode 100644index 2bb7179cce..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-ExtraCondensedExtraBoldItalic.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-ExtraCondensedExtraLight.ttf b/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-ExtraCondensedExtraLight.ttfdeleted file mode 100644index 3568d87557..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-ExtraCondensedExtraLight.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-ExtraCondensedExtraLightItalic.ttf b/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-ExtraCondensedExtraLightItalic.ttfdeleted file mode 100644index 23a3207e51..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-ExtraCondensedExtraLightItalic.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-ExtraCondensedItalic.ttf b/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-ExtraCondensedItalic.ttfdeleted file mode 100644index 33f9e1a647..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-ExtraCondensedItalic.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-ExtraCondensedLight.ttf b/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-ExtraCondensedLight.ttfdeleted file mode 100644index 4cdf575cce..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-ExtraCondensedLight.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-ExtraCondensedLightItalic.ttf b/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-ExtraCondensedLightItalic.ttfdeleted file mode 100644index 09c998752a..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-ExtraCondensedLightItalic.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-ExtraCondensedMedium.ttf b/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-ExtraCondensedMedium.ttfdeleted file mode 100644index 0a4d4c480f..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-ExtraCondensedMedium.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-ExtraCondensedMediumItalic.ttf b/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-ExtraCondensedMediumItalic.ttfdeleted file mode 100644index 4c572c9c3e..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-ExtraCondensedMediumItalic.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-ExtraCondensedSemiBold.ttf b/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-ExtraCondensedSemiBold.ttfdeleted file mode 100644index 8ef21c4b9f..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-ExtraCondensedSemiBold.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-ExtraCondensedSemiBoldItalic.ttf b/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-ExtraCondensedSemiBoldItalic.ttfdeleted file mode 100644index 0b57703013..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-ExtraCondensedSemiBoldItalic.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-ExtraCondensedThin.ttf b/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-ExtraCondensedThin.ttfdeleted file mode 100644index 5d4d0e4837..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-ExtraCondensedThin.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-ExtraCondensedThinItalic.ttf b/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-ExtraCondensedThinItalic.ttfdeleted file mode 100644index 5d8c0bec82..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-ExtraCondensedThinItalic.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-ExtraLight.ttf b/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-ExtraLight.ttfdeleted file mode 100644index 8aaf9ba7a7..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-ExtraLight.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-ExtraLightItalic.ttf b/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-ExtraLightItalic.ttfdeleted file mode 100644index d324a64249..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-ExtraLightItalic.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-Italic.ttf b/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-Italic.ttfdeleted file mode 100644index 76c5e1a7cb..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-Italic.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-Italic[wdth,wght].ttf b/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-Italic[wdth,wght].ttfdeleted file mode 100644index deb23b6bcb..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-Italic[wdth,wght].ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-Italic[wght].ttf b/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-Italic[wght].ttfdeleted file mode 100644index a77768fcca..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-Italic[wght].ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-Light.ttf b/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-Light.ttfdeleted file mode 100644index d56d2444eb..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-Light.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-LightItalic.ttf b/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-LightItalic.ttfdeleted file mode 100644index 5a5338f967..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-LightItalic.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-Medium.ttf b/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-Medium.ttfdeleted file mode 100644index 831f8f0154..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-Medium.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-MediumItalic.ttf b/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-MediumItalic.ttfdeleted file mode 100644index 6f207f78e3..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-MediumItalic.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-Regular.ttf b/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-Regular.ttfdeleted file mode 100644index 546cd89769..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-Regular.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-SemiBold.ttf b/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-SemiBold.ttfdeleted file mode 100644index 611bbd50c3..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-SemiBold.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-SemiBoldItalic.ttf b/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-SemiBoldItalic.ttfdeleted file mode 100644index 8cd12e2ee8..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-SemiBoldItalic.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-SemiCondensed.ttf b/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-SemiCondensed.ttfdeleted file mode 100644index c12b84be09..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-SemiCondensed.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-SemiCondensedBlack.ttf b/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-SemiCondensedBlack.ttfdeleted file mode 100644index 283eab70ed..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-SemiCondensedBlack.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-SemiCondensedBlackItalic.ttf b/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-SemiCondensedBlackItalic.ttfdeleted file mode 100644index a3ccf73edf..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-SemiCondensedBlackItalic.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-SemiCondensedBold.ttf b/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-SemiCondensedBold.ttfdeleted file mode 100644index 9995d5bab7..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-SemiCondensedBold.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-SemiCondensedBoldItalic.ttf b/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-SemiCondensedBoldItalic.ttfdeleted file mode 100644index e8c2a6838f..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-SemiCondensedBoldItalic.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-SemiCondensedExtraBold.ttf b/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-SemiCondensedExtraBold.ttfdeleted file mode 100644index 0c7b6c330f..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-SemiCondensedExtraBold.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-SemiCondensedExtraBoldItalic.ttf b/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-SemiCondensedExtraBoldItalic.ttfdeleted file mode 100644index 2d0ad283fe..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-SemiCondensedExtraBoldItalic.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-SemiCondensedExtraLight.ttf b/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-SemiCondensedExtraLight.ttfdeleted file mode 100644index c6630c5f7e..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-SemiCondensedExtraLight.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-SemiCondensedExtraLightItalic.ttf b/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-SemiCondensedExtraLightItalic.ttfdeleted file mode 100644index 828cd48be7..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-SemiCondensedExtraLightItalic.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-SemiCondensedItalic.ttf b/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-SemiCondensedItalic.ttfdeleted file mode 100644index 8ab05404c0..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-SemiCondensedItalic.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-SemiCondensedLight.ttf b/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-SemiCondensedLight.ttfdeleted file mode 100644index 4ad428541c..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-SemiCondensedLight.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-SemiCondensedLightItalic.ttf b/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-SemiCondensedLightItalic.ttfdeleted file mode 100644index 975c4ef2f9..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-SemiCondensedLightItalic.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-SemiCondensedMedium.ttf b/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-SemiCondensedMedium.ttfdeleted file mode 100644index 57cb29cb06..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-SemiCondensedMedium.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-SemiCondensedMediumItalic.ttf b/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-SemiCondensedMediumItalic.ttfdeleted file mode 100644index cc4423af3a..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-SemiCondensedMediumItalic.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-SemiCondensedSemiBold.ttf b/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-SemiCondensedSemiBold.ttfdeleted file mode 100644index f790ede207..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-SemiCondensedSemiBold.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-SemiCondensedSemiBoldItalic.ttf b/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-SemiCondensedSemiBoldItalic.ttfdeleted file mode 100644index c81e35733a..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-SemiCondensedSemiBoldItalic.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-SemiCondensedThin.ttf b/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-SemiCondensedThin.ttfdeleted file mode 100644index 21dcf9c273..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-SemiCondensedThin.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-SemiCondensedThinItalic.ttf b/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-SemiCondensedThinItalic.ttfdeleted file mode 100644index 1cd1f5d25a..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-SemiCondensedThinItalic.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-Thin.ttf b/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-Thin.ttfdeleted file mode 100644index c4ba58e4f7..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-Thin.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-ThinItalic.ttf b/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-ThinItalic.ttfdeleted file mode 100644index 43f1becdd1..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/noto/NotoSans-ThinItalic.ttf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/scp/SauceCodeProNerdFont-Regular.ttf b/app/core/src/main/resources/type3/library/fonts/scp/SauceCodeProNerdFont-Regular.ttfdeleted file mode 100644index 54ceb7ce22..0000000000--- a/app/core/src/main/resources/type3/library/fonts/scp/SauceCodeProNerdFont-Regular.ttf+++ /dev/null@@ -1,1882 +0,0 @@---<!DOCTYPE html>-<html- lang="en"-- data-color-mode="auto" data-light-theme="light" data-dark-theme="dark"- data-a11y-animated-images="system" data-a11y-link-underlines="true"-- >----- <head>- <meta charset="utf-8">- <link rel="dns-prefetch" href="https://github.githubassets.com">- <link rel="dns-prefetch" href="https://avatars.githubusercontent.com">- <link rel="dns-prefetch" href="https://github-cloud.s3.amazonaws.com">- <link rel="dns-prefetch" href="https://user-images.githubusercontent.com/">- <link rel="preconnect" href="https://github.githubassets.com" crossorigin>- <link rel="preconnect" href="https://avatars.githubusercontent.com">---- <link crossorigin="anonymous" media="all" rel="stylesheet" href="https://github.githubassets.com/assets/light-8e973f836952.css" /><link crossorigin="anonymous" media="all" rel="stylesheet" href="https://github.githubassets.com/assets/light_high_contrast-34b642d57214.css" /><link crossorigin="anonymous" media="all" rel="stylesheet" href="https://github.githubassets.com/assets/dark-4bce7af39e21.css" /><link crossorigin="anonymous" media="all" rel="stylesheet" href="https://github.githubassets.com/assets/dark_high_contrast-ad512d3e2f3b.css" /><link data-color-theme="light" crossorigin="anonymous" media="all" rel="stylesheet" data-href="https://github.githubassets.com/assets/light-8e973f836952.css" /><link data-color-theme="light_high_contrast" crossorigin="anonymous" media="all" rel="stylesheet" data-href="https://github.githubassets.com/assets/light_high_contrast-34b642d57214.css" /><link data-color-theme="light_colorblind" crossorigin="anonymous" media="all" rel="stylesheet" data-href="https://github.githubassets.com/assets/light_colorblind-54be93e666a7.css" /><link data-color-theme="light_colorblind_high_contrast" crossorigin="anonymous" media="all" rel="stylesheet" data-href="https://github.githubassets.com/assets/light_colorblind_high_contrast-8ae7edf5489c.css" /><link data-color-theme="light_tritanopia" crossorigin="anonymous" media="all" rel="stylesheet" data-href="https://github.githubassets.com/assets/light_tritanopia-84d50df427c0.css" /><link data-color-theme="light_tritanopia_high_contrast" crossorigin="anonymous" media="all" rel="stylesheet" data-href="https://github.githubassets.com/assets/light_tritanopia_high_contrast-a80873375146.css" /><link data-color-theme="dark" crossorigin="anonymous" media="all" rel="stylesheet" data-href="https://github.githubassets.com/assets/dark-4bce7af39e21.css" /><link data-color-theme="dark_high_contrast" crossorigin="anonymous" media="all" rel="stylesheet" data-href="https://github.githubassets.com/assets/dark_high_contrast-ad512d3e2f3b.css" /><link data-color-theme="dark_colorblind" crossorigin="anonymous" media="all" rel="stylesheet" data-href="https://github.githubassets.com/assets/dark_colorblind-d152d6cd6879.css" /><link data-color-theme="dark_colorblind_high_contrast" crossorigin="anonymous" media="all" rel="stylesheet" data-href="https://github.githubassets.com/assets/dark_colorblind_high_contrast-fa4060c1a9da.css" /><link data-color-theme="dark_tritanopia" crossorigin="anonymous" media="all" rel="stylesheet" data-href="https://github.githubassets.com/assets/dark_tritanopia-d7bad0fb00bb.css" /><link data-color-theme="dark_tritanopia_high_contrast" crossorigin="anonymous" media="all" rel="stylesheet" data-href="https://github.githubassets.com/assets/dark_tritanopia_high_contrast-4a0107c0f60c.css" /><link data-color-theme="dark_dimmed" crossorigin="anonymous" media="all" rel="stylesheet" data-href="https://github.githubassets.com/assets/dark_dimmed-045e6b6ac094.css" /><link data-color-theme="dark_dimmed_high_contrast" crossorigin="anonymous" media="all" rel="stylesheet" data-href="https://github.githubassets.com/assets/dark_dimmed_high_contrast-5de537db5e79.css" />-- <style type="text/css">- :root {- --tab-size-preference: 4;- }-- pre, code {- tab-size: var(--tab-size-preference);- }- </style>-- <link crossorigin="anonymous" media="all" rel="stylesheet" href="https://github.githubassets.com/assets/primer-primitives-15839d47b75d.css" />- <link crossorigin="anonymous" media="all" rel="stylesheet" href="https://github.githubassets.com/assets/primer-a5c85403da8c.css" />- <link crossorigin="anonymous" media="all" rel="stylesheet" href="https://github.githubassets.com/assets/global-abde950b7df1.css" />- <link crossorigin="anonymous" media="all" rel="stylesheet" href="https://github.githubassets.com/assets/github-490b3f68bf33.css" />- <link crossorigin="anonymous" media="all" rel="stylesheet" href="https://github.githubassets.com/assets/profile-1832ec223d40.css" />-<link crossorigin="anonymous" media="all" rel="stylesheet" href="https://github.githubassets.com/assets/insights-388cd09d03ad.css" />---- <script type="application/json" id="client-env">{"locale":"en","featureFlags":["actions_custom_images_public_preview_visibility","actions_custom_images_storage_billing_ui_visibility","actions_enable_snapshot_keyword","actions_image_version_event","alternate_user_config_repo","api_insights_show_missing_data_banner","attestations_filtering","attestations_sorting","automated_review_comment_simplification","billing_split_pru_skus","billing_split_pru_skus","client_version_header","codespaces_prebuild_region_target_update","contentful_lp_footnotes","copilot_agent_cli_public_preview","copilot_agent_task_list_v2","copilot_agent_tasks_btn_code_nav","copilot_agent_tasks_btn_code_view","copilot_agent_tasks_btn_code_view_lines","copilot_api_agentic_issue_marshal_yaml","copilot_api_draft_issues_with_dependencies","copilot_api_github_draft_update_issue_skill","copilot_chat_agents_empty_state","copilot_chat_attach_multiple_images","copilot_chat_file_redirect","copilot_chat_input_commands","copilot_chat_reduce_quota_checks","copilot_chat_search_bar_redirect","copilot_chat_selection_attachments","copilot_chat_vision_in_claude","copilot_chat_vision_skip_thread_create","copilot_coding_agent_task_response","copilot_custom_copilots","copilot_custom_copilots_feature_preview","copilot_duplicate_thread","copilot_extensions_deprecation_notice","copilot_extensions_removal_on_marketplace","copilot_features_raycast_logo","copilot_file_block_ref_matching","copilot_free_to_paid_telem","copilot_ftp_hyperspace_upgrade_prompt","copilot_ftp_settings_upgrade","copilot_ftp_upgrade_to_pro_from_models","copilot_ftp_your_copilot_settings","copilot_immersive_structured_model_picker","copilot_immersive_task_hyperlinking","copilot_immersive_task_within_chat_thread","copilot_insights_column_chart_axis_legibility_fix","copilot_insights_public_preview","copilot_insights_usage_export_ndjson","copilot_no_floating_button","copilot_org_policy_page_focus_mode","copilot_read_shared_conversation","copilot_security_alert_assignee_options","copilot_spaces_as_attachments","copilot_spaces_ga","copilot_spark_empty_state","copilot_spark_loading_webgl","copilot_spark_progressive_error_handling","copilot_spark_use_billing_headers","copilot_stable_conversation_view","copilot_swe_agent_progress_commands","copilot_swe_agent_use_subagents","copilot_workbench_agent_seed_tool","copilot_workbench_cache","copilot_workbench_preview_analytics","copilot_workbench_skip_repo_on_codespace","copilot_workbench_use_single_prompt","deployment_record_api","direct_to_salesforce","disable_dashboard_universe_2025_private_preview","dotcom_chat_client_side_skills","failbot_report_error_react_apps_on_page","ghost_pilot_confidence_truncation_25","ghost_pilot_confidence_truncation_40","global_search_multi_orgs","hpc_improve_dom_insertion_observer","hyperspace_2025_logged_out_batch_1","hyperspace_nudges_universe25","hyperspace_nudges_universe25_post_event","inp_reduced_threshold","insert_before_patch","issue_fields_report_usage","issues_copilot_cross_repo_assign","issues_react_blur_item_picker_on_close","issues_react_bots_timeline_pagination","issues_react_prohibit_title_fallback","issues_react_remove_placeholders","issues_sticky_sidebar","item_picker_search_cancellation","kb_convert_to_space","lifecycle_label_name_updates","link_contact_sales_swp_marketo","marketing_pages_search_explore_provider","mcp_registry_install","memex_default_issue_create_repository","memex_grouped_by_edit_route","memex_mwl_filter_field_delimiter","new_traffic_page_banner","open_agent_session_in_vscode_insiders","pinned_issue_fields","primer_react_segmented_control_tooltip","primer_react_unified_portal_root","primer_react_use_styled_react_theming","projects_assignee_max_limit","react_fetch_graphql_filter_sensitive_data","react_fetch_graphql_rate_limit_error_handling","react_fetch_graphql_validate_base_url","record_sso_banner_metrics","remove_child_patch","repos_insights_remove_new_url","ruleset_deletion_confirmation","sample_network_conn_type","scheduled_reminders_updated_limits","site_features_copilot_universe","site_homepage_collaborate_video","site_homepage_contentful","site_homepage_eyebrow_banner","site_homepage_universe_animations","site_msbuild_webgl_hero","spark_fix_rename","spark_force_push_after_checkout","spark_improve_image_upload","spark_kv_encocoded_keys","spark_show_data_access_on_publish","spark_sync_repository_after_iteration","viewscreen_sandbox","webp_support","workbench_store_readonly"],"copilotApiOverrideUrl":"https://api.githubcopilot.com"}</script>-<script crossorigin="anonymous" type="application/javascript" src="https://github.githubassets.com/assets/high-contrast-cookie-1a011967750c.js"></script>-<script crossorigin="anonymous" type="application/javascript" src="https://github.githubassets.com/assets/wp-runtime-15377c53774e.js" defer="defer"></script>-<script crossorigin="anonymous" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_oddbird_popover-polyfill_dist_popover-fn_js-392bf0ab720a.js" defer="defer"></script>-<script crossorigin="anonymous" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_stacktrace-parser_dist_stack-trace-parser_esm_js-node_modules_github_bro-2f4e04-ebb51d646f4d.js" defer="defer"></script>-<script crossorigin="anonymous" type="application/javascript" src="https://github.githubassets.com/assets/environment-18c386dc8ed3.js" defer="defer"></script>-<script crossorigin="anonymous" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_primer_behaviors_dist_esm_index_mjs-1b15302f2da0.js" defer="defer"></script>-<script crossorigin="anonymous" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_selector-observer_dist_index_esm_js-9ab93471824e.js" defer="defer"></script>-<script crossorigin="anonymous" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_relative-time-element_dist_index_js-15c8a75d3ef5.js" defer="defer"></script>-<script crossorigin="anonymous" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_auto-complete-element_dist_index_js-node_modules_github_catalyst_-0d7d60-a999b98ae398.js" defer="defer"></script>-<script crossorigin="anonymous" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_text-expander-element_dist_index_js-69eb26872f2d.js" defer="defer"></script>-<script crossorigin="anonymous" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_filter-input-element_dist_index_js-node_modules_github_remote-inp-665e70-6080d4c6306d.js" defer="defer"></script>-<script crossorigin="anonymous" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_markdown-toolbar-element_dist_index_js-b03ed9e33b62.js" defer="defer"></script>-<script crossorigin="anonymous" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_file-attachment-element_dist_index_js-node_modules_primer_view-co-777ce2-fc39771b9382.js" defer="defer"></script>-<script crossorigin="anonymous" type="application/javascript" src="https://github.githubassets.com/assets/github-elements-b6c5dfce8b45.js" defer="defer"></script>-<script crossorigin="anonymous" type="application/javascript" src="https://github.githubassets.com/assets/element-registry-2810038c0b2f.js" defer="defer"></script>-<script crossorigin="anonymous" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_braintree_browser-detection_dist_browser-detection_js-node_modules_githu-bb80ec-4e1c4d231e25.js" defer="defer"></script>-<script crossorigin="anonymous" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_lit-html_lit-html_js-0bb805df324c.js" defer="defer"></script>-<script crossorigin="anonymous" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_mini-throttle_dist_index_js-node_modules_morphdom_dist_morphdom-e-c1896e-ba47f43192a8.js" defer="defer"></script>-<script crossorigin="anonymous" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_remote-form_dist_index_js-node_modules_delegated-events_dist_inde-893f9f-25a564a55564.js" defer="defer"></script>-<script crossorigin="anonymous" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_turbo_dist_turbo_es2017-esm_js-b9d3c573623e.js" defer="defer"></script>-<script crossorigin="anonymous" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_hotkey_dist_index_js-node_modules_github_hydro-analytics-client_d-502318-5215461ac705.js" defer="defer"></script>-<script crossorigin="anonymous" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_quote-selection_dist_index_js-node_modules_github_session-resume_-7154bb-5d699c37a4cf.js" defer="defer"></script>-<script crossorigin="anonymous" type="application/javascript" src="https://github.githubassets.com/assets/packages_document-metadata_document-metadata_ts-packages_failbot_failbot_ts-54754da9db3d.js" defer="defer"></script>-<script crossorigin="anonymous" type="application/javascript" src="https://github.githubassets.com/assets/packages_updatable-content_updatable-content_ts-38f5e2f7c2a7.js" defer="defer"></script>-<script crossorigin="anonymous" type="application/javascript" src="https://github.githubassets.com/assets/app_assets_modules_github_behaviors_ajax-error_ts-app_assets_modules_github_behaviors_details-6493f1-48f516987b6b.js" defer="defer"></script>-<script crossorigin="anonymous" type="application/javascript" src="https://github.githubassets.com/assets/app_assets_modules_github_behaviors_task-list_ts-app_assets_modules_github_throttled-input_ts-047775-c6f476084254.js" defer="defer"></script>-<script crossorigin="anonymous" type="application/javascript" src="https://github.githubassets.com/assets/app_assets_modules_github_behaviors_commenting_edit_ts-app_assets_modules_github_behaviors_ht-83c235-d8c5bfe37d1d.js" defer="defer"></script>-<script crossorigin="anonymous" type="application/javascript" src="https://github.githubassets.com/assets/behaviors-d0668d6c9939.js" defer="defer"></script>-<script crossorigin="anonymous" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_delegated-events_dist_index_js-node_modules_github_catalyst_lib_index_js-ef6d0f-af7473406ffd.js" defer="defer"></script>-<script crossorigin="anonymous" type="application/javascript" src="https://github.githubassets.com/assets/notifications-global-54d9bcff2c38.js" defer="defer"></script>-<script crossorigin="anonymous" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_remote-form_dist_index_js-node_modules_delegated-events_dist_inde-08b0f5-a3d67a2e862b.js" defer="defer"></script>-<script crossorigin="anonymous" type="application/javascript" src="https://github.githubassets.com/assets/app_assets_modules_github_profile_edit-social-account_ts-app_assets_modules_github_settings_p-b03314-2de9e53b2fe6.js" defer="defer"></script>-<script crossorigin="anonymous" type="application/javascript" src="https://github.githubassets.com/assets/profile-4218128e4f70.js" defer="defer"></script>--- <title>ryanoasis (Ryan L McIntyre) · GitHub</title>---- <meta name="route-pattern" content="/:user_id(.:format)" data-turbo-transient>- <meta name="route-controller" content="profiles" data-turbo-transient>- <meta name="route-action" content="show" data-turbo-transient>- <meta name="fetch-nonce" content="v2:772d3842-29b0-c56f-6ee8-099c37fc3685">--- <meta name="current-catalog-service-hash" content="4a1c50a83cf6cc4b55b6b9c53e553e3f847c876b87fb333f71f5d05db8f1a7db">--- <meta name="request-id" content="DF2A:2A6C4A:53356:5BCF1:690DE2B2" data-pjax-transient="true"/><meta name="html-safe-nonce" content="8f93a2aaa14bce2be283d553447043ba1d1a6ec6a2fdd21ea893a364ec34576e" data-pjax-transient="true"/><meta name="visitor-payload" content="eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJERjJBOjJBNkM0QTo1MzM1Njo1QkNGMTo2OTBERTJCMiIsInZpc2l0b3JfaWQiOiI4ODA3OTc0Mjg2NDkwNzIyOTk0IiwicmVnaW9uX2VkZ2UiOiJ1a3NvdXRoIiwicmVnaW9uX3JlbmRlciI6InVrc291dGgifQ==" data-pjax-transient="true"/><meta name="visitor-hmac" content="4d4cb3c09ad38106635a79981be0897f33d2b9e9f5a74bb233091be7d7947961" data-pjax-transient="true"/>----- <meta name="github-keyboard-shortcuts" content="copilot" data-turbo-transient="true" />--- <meta name="selected-link" value="overview" data-turbo-transient>- <link rel="assets" href="https://github.githubassets.com/">-- <meta name="google-site-verification" content="Apib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I">--<meta name="octolytics-url" content="https://collector.github.com/github/collect" />-- <meta name="analytics-location" content="/<user-name>" data-turbo-transient="true" />------- <meta name="user-login" content="">---- <meta name="viewport" content="width=device-width">---- <meta name="description" content=" Full Stack Application Developer ┋ Focused on UI - JavaScript - OSS - Vim ┋ Creator of Nerd Fonts & VimDevIcons - ryanoasis">-- <link rel="search" type="application/opensearchdescription+xml" href="/opensearch.xml" title="GitHub">-- <link rel="fluid-icon" href="https://github.com/fluidicon.png" title="GitHub">- <meta property="fb:app_id" content="1401488693436528">- <meta name="apple-itunes-app" content="app-id=1477376905, app-argument=https://github.com/ryanoasis" />-- <meta name="twitter:image" content="https://avatars.githubusercontent.com/u/8083459?v=4?s=400" /><meta name="twitter:site" content="@github" /><meta name="twitter:card" content="summary" /><meta name="twitter:title" content="ryanoasis - Overview" /><meta name="twitter:description" content=" Full Stack Application Developer ┋ Focused on UI - JavaScript - OSS - Vim ┋ Creator of Nerd Fonts & VimDevIcons - ryanoasis" />- <meta property="og:image" content="https://avatars.githubusercontent.com/u/8083459?v=4?s=400" /><meta property="og:image:alt" content=" Full Stack Application Developer ┋ Focused on UI - JavaScript - OSS - Vim ┋ Creator of Nerd Fonts & VimDevIcons - ryanoasis" /><meta property="og:site_name" content="GitHub" /><meta property="og:type" content="profile" /><meta property="og:title" content="ryanoasis - Overview" /><meta property="og:url" content="https://github.com/ryanoasis" /><meta property="og:description" content=" Full Stack Application Developer ┋ Focused on UI - JavaScript - OSS - Vim ┋ Creator of Nerd Fonts & VimDevIcons - ryanoasis" /><meta property="profile:username" content="ryanoasis" />------ <meta name="hostname" content="github.com">---- <meta name="expected-hostname" content="github.com">--- <meta http-equiv="x-pjax-version" content="20d4d190ad98a2c2b308bc9064de12eabbd325e43d545510dbe8615eb8813c37" data-turbo-track="reload">- <meta http-equiv="x-pjax-csp-version" content="21a43568025709b66240454fc92d4f09335a96863f8ab1c46b4a07f6a5b67102" data-turbo-track="reload">- <meta http-equiv="x-pjax-css-version" content="64aa48ca69ddc4d1267863e96c8a5c11e0cb33842931f16e1441b54a84bcc1ad" data-turbo-track="reload">- <meta http-equiv="x-pjax-js-version" content="4868c5dba4ede62dc57074a8973225c79271ff4c71c86d22974ed0988061774e" data-turbo-track="reload">-- <meta name="turbo-cache-control" content="no-preview" data-turbo-transient="">-- <meta name="octolytics-dimension-user_id" content="8083459" /><meta name="octolytics-dimension-user_login" content="ryanoasis" />--- <link rel="canonical" href="https://github.com/ryanoasis" data-turbo-transient>--- <meta name="turbo-body-classes" content="logged-out env-production page-responsive page-profile">--- <meta name="browser-stats-url" content="https://api.github.com/_private/browser/stats">-- <meta name="browser-errors-url" content="https://api.github.com/_private/browser/errors">-- <meta name="release" content="dc34584cbd2dbbcdc6207a9dca58c59883a292db">- <meta name="ui-target" content="full">-- <link rel="mask-icon" href="https://github.githubassets.com/assets/pinned-octocat-093da3e6fa40.svg" color="#000000">- <link rel="alternate icon" class="js-site-favicon" type="image/png" href="https://github.githubassets.com/favicons/favicon.png">- <link rel="icon" class="js-site-favicon" type="image/svg+xml" href="https://github.githubassets.com/favicons/favicon.svg" data-base-href="https://github.githubassets.com/favicons/favicon">--<meta name="theme-color" content="#1e2327">-<meta name="color-scheme" content="light dark" />--- <link rel="manifest" href="/manifest.json" crossOrigin="use-credentials">-- </head>-- <body class="logged-out env-production page-responsive page-profile" style="word-wrap: break-word;" >- <div data-turbo-body class="logged-out env-production page-responsive page-profile" style="word-wrap: break-word;">----- <div class="position-relative header-wrapper js-header-wrapper ">- <a href="#start-of-content" data-skip-target-assigned="false" class="px-2 py-4 color-bg-accent-emphasis color-fg-on-emphasis show-on-focus js-skip-to-content">Skip to content</a>-- <span data-view-component="true" class="progress-pjax-loader Progress position-fixed width-full">- <span style="width: 0%;" data-view-component="true" class="Progress-item progress-pjax-loader-bar left-0 top-0 color-bg-accent-emphasis"></span>-</span>-- <link crossorigin="anonymous" media="all" rel="stylesheet" href="https://github.githubassets.com/assets/primer-react.53f37102c46fd176a96b.module.css" />-<link crossorigin="anonymous" media="all" rel="stylesheet" href="https://github.githubassets.com/assets/keyboard-shortcuts-dialog.2de9c7d6456a311fce49.module.css" />--<react-partial- partial-name="keyboard-shortcuts-dialog"- data-ssr="false"- data-attempted-ssr="false"- data-react-profiling="false"->-- <script type="application/json" data-target="react-partial.embeddedData">{"props":{"docsUrl":"https://docs.github.com/get-started/accessibility/keyboard-shortcuts"}}</script>- <div data-target="react-partial.reactRoot"></div>-</react-partial>-----------<script crossorigin="anonymous" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_gsap_index_js-1399719d10c8.js" defer="defer"></script>-<script crossorigin="anonymous" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_remote-form_dist_index_js-node_modules_delegated-events_dist_inde-94fd67-0b6bd345de5a.js" defer="defer"></script>-<script crossorigin="anonymous" type="application/javascript" src="https://github.githubassets.com/assets/sessions-f691799f782d.js" defer="defer"></script>--<header class="HeaderMktg header-logged-out js-details-container js-header Details f4 py-3" role="banner" data-is-top="true" data-color-mode=light data-light-theme=light data-dark-theme=dark>- <h2 class="sr-only">Navigation Menu</h2>-- <button type="button" class="HeaderMktg-backdrop d-lg-none border-0 position-fixed top-0 left-0 width-full height-full js-details-target" aria-label="Toggle navigation">- <span class="d-none">Toggle navigation</span>- </button>-- <div class="d-flex flex-column flex-lg-row flex-items-center px-3 px-md-4 px-lg-5 height-full position-relative z-1">- <div class="d-flex flex-justify-between flex-items-center width-full width-lg-auto">- <div class="flex-1">- <button aria-label="Toggle navigation" aria-expanded="false" type="button" data-view-component="true" class="js-details-target js-nav-padding-recalculate js-header-menu-toggle Button--link Button--medium Button d-lg-none color-fg-inherit p-1"> <span class="Button-content">- <span class="Button-label"><div class="HeaderMenu-toggle-bar rounded my-1"></div>- <div class="HeaderMenu-toggle-bar rounded my-1"></div>- <div class="HeaderMenu-toggle-bar rounded my-1"></div></span>- </span>-</button>- </div>-- <a class="mr-lg-3 color-fg-inherit flex-order-2 js-prevent-focus-on-mobile-nav"- href="/"- aria-label="Homepage"- data-analytics-event="{"category":"Marketing nav","action":"click to go to homepage","label":"ref_page:Marketing;ref_cta:Logomark;ref_loc:Header"}">- <svg height="32" aria-hidden="true" viewBox="0 0 24 24" version="1.1" width="32" data-view-component="true" class="octicon octicon-mark-github">- <path d="M12 1C5.923 1 1 5.923 1 12c0 4.867 3.149 8.979 7.521 10.436.55.096.756-.233.756-.522 0-.262-.013-1.128-.013-2.049-2.764.509-3.479-.674-3.699-1.292-.124-.317-.66-1.293-1.127-1.554-.385-.207-.936-.715-.014-.729.866-.014 1.485.797 1.691 1.128.99 1.663 2.571 1.196 3.204.907.096-.715.385-1.196.701-1.471-2.448-.275-5.005-1.224-5.005-5.432 0-1.196.426-2.186 1.128-2.956-.111-.275-.496-1.402.11-2.915 0 0 .921-.288 3.024 1.128a10.193 10.193 0 0 1 2.75-.371c.936 0 1.871.123 2.75.371 2.104-1.43 3.025-1.128 3.025-1.128.605 1.513.221 2.64.111 2.915.701.77 1.127 1.747 1.127 2.956 0 4.222-2.571 5.157-5.019 5.432.399.344.743 1.004.743 2.035 0 1.471-.014 2.654-.014 3.025 0 .289.206.632.756.522C19.851 20.979 23 16.854 23 12c0-6.077-4.922-11-11-11Z"></path>-</svg>- </a>-- <div class="d-flex flex-1 flex-order-2 text-right d-lg-none gap-2 flex-justify-end">- <a- href="/login?return_to=https%3A%2F%2Fgithub.com%2Fryanoasis%2F"- class="HeaderMenu-link HeaderMenu-button d-inline-flex f5 no-underline border color-border-default rounded-2 px-2 py-1 color-fg-inherit js-prevent-focus-on-mobile-nav"- data-hydro-click="{"event_type":"authentication.click","payload":{"location_in_page":"site header menu","repository_id":null,"auth_type":"SIGN_UP","originating_url":"https://github.com/ryanoasis","user_id":null}}" data-hydro-click-hmac="06273eeb1cd2e1c4974fecca6b6e9adbb7d95f6c1c53441c3fa555a3d7682fd3"- data-analytics-event="{"category":"Marketing nav","action":"click to Sign in","label":"ref_page:Marketing;ref_cta:Sign in;ref_loc:Header"}"- >- Sign in- </a>- <div class="AppHeader-appearanceSettings">- <react-partial-anchor>- <button data-target="react-partial-anchor.anchor" id="icon-button-646e8453-fe36-4ece-b3ef-f0408a8d299d" aria-labelledby="tooltip-b703278b-ab8f-4282-831b-a0aed71cce98" type="button" disabled="disabled" data-view-component="true" class="Button Button--iconOnly Button--invisible Button--medium AppHeader-button HeaderMenu-link border cursor-wait"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-sliders Button-visual">- <path d="M15 2.75a.75.75 0 0 1-.75.75h-4a.75.75 0 0 1 0-1.5h4a.75.75 0 0 1 .75.75Zm-8.5.75v1.25a.75.75 0 0 0 1.5 0v-4a.75.75 0 0 0-1.5 0V2H1.75a.75.75 0 0 0 0 1.5H6.5Zm1.25 5.25a.75.75 0 0 0 0-1.5h-6a.75.75 0 0 0 0 1.5h6ZM15 8a.75.75 0 0 1-.75.75H11.5V10a.75.75 0 1 1-1.5 0V6a.75.75 0 0 1 1.5 0v1.25h2.75A.75.75 0 0 1 15 8Zm-9 5.25v-2a.75.75 0 0 0-1.5 0v1.25H1.75a.75.75 0 0 0 0 1.5H4.5v1.25a.75.75 0 0 0 1.5 0v-2Zm9 0a.75.75 0 0 1-.75.75h-6a.75.75 0 0 1 0-1.5h6a.75.75 0 0 1 .75.75Z"></path>-</svg>-</button><tool-tip id="tooltip-b703278b-ab8f-4282-831b-a0aed71cce98" for="icon-button-646e8453-fe36-4ece-b3ef-f0408a8d299d" popover="manual" data-direction="s" data-type="label" data-view-component="true" class="sr-only position-absolute">Appearance settings</tool-tip>-- <template data-target="react-partial-anchor.template">- <link crossorigin="anonymous" media="all" rel="stylesheet" href="https://github.githubassets.com/assets/primer-react.53f37102c46fd176a96b.module.css" />-<link crossorigin="anonymous" media="all" rel="stylesheet" href="https://github.githubassets.com/assets/appearance-settings.6c63a6de228d6520804d.module.css" />--<react-partial- partial-name="appearance-settings"- data-ssr="false"- data-attempted-ssr="false"- data-react-profiling="false"->-- <script type="application/json" data-target="react-partial.embeddedData">{"props":{}}</script>- <div data-target="react-partial.reactRoot"></div>-</react-partial>--- </template>- </react-partial-anchor>- </div>-- </div>- </div>--- <div class="HeaderMenu js-header-menu height-fit position-lg-relative d-lg-flex flex-column flex-auto top-0">- <div class="HeaderMenu-wrapper d-flex flex-column flex-self-start flex-lg-row flex-auto rounded rounded-lg-0">- <link crossorigin="anonymous" media="all" rel="stylesheet" href="https://github.githubassets.com/assets/primer-react.53f37102c46fd176a96b.module.css" />-<link crossorigin="anonymous" media="all" rel="stylesheet" href="https://github.githubassets.com/assets/marketing-navigation.fd20bacfa4fdf4953836.module.css" />--<react-partial- partial-name="marketing-navigation"- data-ssr="true"- data-attempted-ssr="true"- data-react-profiling="false"->-- <script type="application/json" data-target="react-partial.embeddedData">{"props":{"should_use_dotcom_links":true}}</script>- <div data-target="react-partial.reactRoot"><nav class="MarketingNavigation-module__nav--jA9Zq" aria-label="Global"><ul class="MarketingNavigation-module__list--r_vr2"><li><div class="NavDropdown-module__container--bmXM2 js-details-container js-header-menu-item"><button type="button" class="NavDropdown-module__button--Hq9UR js-details-target" aria-expanded="false">Platform<svg aria-hidden="true" focusable="false" class="octicon octicon-chevron-right NavDropdown-module__buttonIcon--SR0Ke" viewBox="0 0 16 16" width="16" height="16" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M6.22 3.22a.75.75 0 0 1 1.06 0l4.25 4.25a.75.75 0 0 1 0 1.06l-4.25 4.25a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042L9.94 8 6.22 4.28a.75.75 0 0 1 0-1.06Z"></path></svg></button><div class="NavDropdown-module__dropdown--Ig57Y"><ul class="NavDropdown-module__list--RwSSK"><li><div class="NavGroup-module__group--T925n"><span class="NavGroup-module__title--TdKyz">AI CODE CREATION</span><ul class="NavGroup-module__list--M8eGv"><li><a href="https://github.com/features/copilot" data-analytics-event="{"action":"github_copilot","tag":"link","context":"platform","location":"navbar","label":"github_copilot_link_platform_navbar"}" class="NavLink-module__link--n48VB"><div class="NavLink-module__text--SdWkb"><svg aria-hidden="true" focusable="false" class="octicon octicon-copilot NavLink-module__icon--h0sw7" viewBox="0 0 24 24" width="24" height="24" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M23.922 16.992c-.861 1.495-5.859 5.023-11.922 5.023-6.063 0-11.061-3.528-11.922-5.023A.641.641 0 0 1 0 16.736v-2.869a.841.841 0 0 1 .053-.22c.372-.935 1.347-2.292 2.605-2.656.167-.429.414-1.055.644-1.517a10.195 10.195 0 0 1-.052-1.086c0-1.331.282-2.499 1.132-3.368.397-.406.89-.717 1.474-.952 1.399-1.136 3.392-2.093 6.122-2.093 2.731 0 4.767.957 6.166 2.093.584.235 1.077.546 1.474.952.85.869 1.132 2.037 1.132 3.368 0 .368-.014.733-.052 1.086.23.462.477 1.088.644 1.517 1.258.364 2.233 1.721 2.605 2.656a.832.832 0 0 1 .053.22v2.869a.641.641 0 0 1-.078.256ZM12.172 11h-.344a4.323 4.323 0 0 1-.355.508C10.703 12.455 9.555 13 7.965 13c-1.725 0-2.989-.359-3.782-1.259a2.005 2.005 0 0 1-.085-.104L4 11.741v6.585c1.435.779 4.514 2.179 8 2.179 3.486 0 6.565-1.4 8-2.179v-6.585l-.098-.104s-.033.045-.085.104c-.793.9-2.057 1.259-3.782 1.259-1.59 0-2.738-.545-3.508-1.492a4.323 4.323 0 0 1-.355-.508h-.016.016Zm.641-2.935c.136 1.057.403 1.913.878 2.497.442.544 1.134.938 2.344.938 1.573 0 2.292-.337 2.657-.751.384-.435.558-1.15.558-2.361 0-1.14-.243-1.847-.705-2.319-.477-.488-1.319-.862-2.824-1.025-1.487-.161-2.192.138-2.533.529-.269.307-.437.808-.438 1.578v.021c0 .265.021.562.063.893Zm-1.626 0c.042-.331.063-.628.063-.894v-.02c-.001-.77-.169-1.271-.438-1.578-.341-.391-1.046-.69-2.533-.529-1.505.163-2.347.537-2.824 1.025-.462.472-.705 1.179-.705 2.319 0 1.211.175 1.926.558 2.361.365.414 1.084.751 2.657.751 1.21 0 1.902-.394 2.344-.938.475-.584.742-1.44.878-2.497Z"></path><path d="M14.5 14.25a1 1 0 0 1 1 1v2a1 1 0 0 1-2 0v-2a1 1 0 0 1 1-1Zm-5 0a1 1 0 0 1 1 1v2a1 1 0 0 1-2 0v-2a1 1 0 0 1 1-1Z"></path></svg><span class="NavLink-module__title--xw3ok">GitHub Copilot</span><span class="NavLink-module__subtitle--qC15H">Write better code with AI</span></div></a></li><li><a href="https://github.com/features/spark" data-analytics-event="{"action":"github_spark","tag":"link","context":"platform","location":"navbar","label":"github_spark_link_platform_navbar"}" class="NavLink-module__link--n48VB"><div class="NavLink-module__text--SdWkb"><svg aria-hidden="true" focusable="false" class="octicon octicon-sparkle-fill NavLink-module__icon--h0sw7" viewBox="0 0 24 24" width="24" height="24" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M11.296 1.924c.24-.656 1.168-.656 1.408 0l.717 1.958a11.25 11.25 0 0 0 6.697 6.697l1.958.717c.657.24.657 1.168 0 1.408l-1.958.717a11.25 11.25 0 0 0-6.697 6.697l-.717 1.958c-.24.657-1.168.657-1.408 0l-.717-1.958a11.25 11.25 0 0 0-6.697-6.697l-1.958-.717c-.656-.24-.656-1.168 0-1.408l1.958-.717a11.25 11.25 0 0 0 6.697-6.697l.717-1.958Z"></path></svg><span class="NavLink-module__title--xw3ok">GitHub Spark</span><span class="NavLink-module__subtitle--qC15H">Build and deploy intelligent apps</span></div></a></li><li><a href="https://github.com/features/models" data-analytics-event="{"action":"github_models","tag":"link","context":"platform","location":"navbar","label":"github_models_link_platform_navbar"}" class="NavLink-module__link--n48VB"><div class="NavLink-module__text--SdWkb"><svg aria-hidden="true" focusable="false" class="octicon octicon-ai-model NavLink-module__icon--h0sw7" viewBox="0 0 24 24" width="24" height="24" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M19.375 8.5a3.25 3.25 0 1 1-3.163 4h-3a3.252 3.252 0 0 1-4.443 2.509L7.214 17.76a3.25 3.25 0 1 1-1.342-.674l1.672-2.957A3.238 3.238 0 0 1 6.75 12c0-.907.371-1.727.97-2.316L6.117 6.846A3.253 3.253 0 0 1 1.875 3.75a3.25 3.25 0 1 1 5.526 2.32l1.603 2.836A3.25 3.25 0 0 1 13.093 11h3.119a3.252 3.252 0 0 1 3.163-2.5ZM10 10.25a1.75 1.75 0 1 0-.001 3.499A1.75 1.75 0 0 0 10 10.25ZM5.125 2a1.75 1.75 0 1 0 0 3.5 1.75 1.75 0 0 0 0-3.5Zm12.5 9.75a1.75 1.75 0 1 0 3.5 0 1.75 1.75 0 0 0-3.5 0Zm-14.25 8.5a1.75 1.75 0 1 0 3.501-.001 1.75 1.75 0 0 0-3.501.001Z"></path></svg><span class="NavLink-module__title--xw3ok">GitHub Models</span><span class="NavLink-module__subtitle--qC15H">Manage and compare prompts</span></div></a></li><li><a href="https://github.com/mcp" data-analytics-event="{"action":"mcp_registry","tag":"link","context":"platform","location":"navbar","label":"mcp_registry_link_platform_navbar"}" class="NavLink-module__link--n48VB"><div class="NavLink-module__text--SdWkb"><svg aria-hidden="true" focusable="false" class="octicon octicon-mcp NavLink-module__icon--h0sw7" viewBox="0 0 24 24" width="24" height="24" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M9.795 1.694a4.287 4.287 0 0 1 6.061 0 4.28 4.28 0 0 1 1.181 3.819 4.282 4.282 0 0 1 3.819 1.181 4.287 4.287 0 0 1 0 6.061l-6.793 6.793a.249.249 0 0 0 0 .353l2.617 2.618a.75.75 0 1 1-1.061 1.061l-2.617-2.618a1.75 1.75 0 0 1 0-2.475l6.793-6.793a2.785 2.785 0 1 0-3.939-3.939l-5.9 5.9a.734.734 0 0 1-.249.165.749.749 0 0 1-.812-1.225l5.9-5.901a2.785 2.785 0 1 0-3.939-3.939L2.931 10.68A.75.75 0 1 1 1.87 9.619l7.925-7.925Z"></path><path d="M12.42 4.069a.752.752 0 0 1 1.061 0 .752.752 0 0 1 0 1.061L7.33 11.28a2.788 2.788 0 0 0 0 3.94 2.788 2.788 0 0 0 3.94 0l6.15-6.151a.752.752 0 0 1 1.061 0 .752.752 0 0 1 0 1.061l-6.151 6.15a4.285 4.285 0 1 1-6.06-6.06l6.15-6.151Z"></path></svg><span class="NavLink-module__title--xw3ok">MCP Registry<sup class="NavLink-module__label--MrIhm">New</sup></span><span class="NavLink-module__subtitle--qC15H">Discover and integrate external tools</span></div></a></li></ul></div></li><li><div class="NavGroup-module__group--T925n"><span class="NavGroup-module__title--TdKyz">DEVELOPER WORKFLOWS</span><ul class="NavGroup-module__list--M8eGv"><li><a href="https://github.com/features/actions" data-analytics-event="{"action":"actions","tag":"link","context":"platform","location":"navbar","label":"actions_link_platform_navbar"}" class="NavLink-module__link--n48VB"><div class="NavLink-module__text--SdWkb"><svg aria-hidden="true" focusable="false" class="octicon octicon-workflow NavLink-module__icon--h0sw7" viewBox="0 0 24 24" width="24" height="24" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M1 3a2 2 0 0 1 2-2h6.5a2 2 0 0 1 2 2v6.5a2 2 0 0 1-2 2H7v4.063C7 16.355 7.644 17 8.438 17H12.5v-2.5a2 2 0 0 1 2-2H21a2 2 0 0 1 2 2V21a2 2 0 0 1-2 2h-6.5a2 2 0 0 1-2-2v-2.5H8.437A2.939 2.939 0 0 1 5.5 15.562V11.5H3a2 2 0 0 1-2-2Zm2-.5a.5.5 0 0 0-.5.5v6.5a.5.5 0 0 0 .5.5h6.5a.5.5 0 0 0 .5-.5V3a.5.5 0 0 0-.5-.5ZM14.5 14a.5.5 0 0 0-.5.5V21a.5.5 0 0 0 .5.5H21a.5.5 0 0 0 .5-.5v-6.5a.5.5 0 0 0-.5-.5Z"></path></svg><span class="NavLink-module__title--xw3ok">Actions</span><span class="NavLink-module__subtitle--qC15H">Automate any workflow</span></div></a></li><li><a href="https://github.com/features/codespaces" data-analytics-event="{"action":"codespaces","tag":"link","context":"platform","location":"navbar","label":"codespaces_link_platform_navbar"}" class="NavLink-module__link--n48VB"><div class="NavLink-module__text--SdWkb"><svg aria-hidden="true" focusable="false" class="octicon octicon-codespaces NavLink-module__icon--h0sw7" viewBox="0 0 24 24" width="24" height="24" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M3.5 3.75C3.5 2.784 4.284 2 5.25 2h13.5c.966 0 1.75.784 1.75 1.75v7.5A1.75 1.75 0 0 1 18.75 13H5.25a1.75 1.75 0 0 1-1.75-1.75Zm-2 12c0-.966.784-1.75 1.75-1.75h17.5c.966 0 1.75.784 1.75 1.75v4a1.75 1.75 0 0 1-1.75 1.75H3.25a1.75 1.75 0 0 1-1.75-1.75ZM5.25 3.5a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h13.5a.25.25 0 0 0 .25-.25v-7.5a.25.25 0 0 0-.25-.25Zm-2 12a.25.25 0 0 0-.25.25v4c0 .138.112.25.25.25h17.5a.25.25 0 0 0 .25-.25v-4a.25.25 0 0 0-.25-.25Z"></path><path d="M10 17.75a.75.75 0 0 1 .75-.75h6.5a.75.75 0 0 1 0 1.5h-6.5a.75.75 0 0 1-.75-.75Zm-4 0a.75.75 0 0 1 .75-.75h.5a.75.75 0 0 1 0 1.5h-.5a.75.75 0 0 1-.75-.75Z"></path></svg><span class="NavLink-module__title--xw3ok">Codespaces</span><span class="NavLink-module__subtitle--qC15H">Instant dev environments</span></div></a></li><li><a href="https://github.com/features/issues" data-analytics-event="{"action":"issues","tag":"link","context":"platform","location":"navbar","label":"issues_link_platform_navbar"}" class="NavLink-module__link--n48VB"><div class="NavLink-module__text--SdWkb"><svg aria-hidden="true" focusable="false" class="octicon octicon-issue-opened NavLink-module__icon--h0sw7" viewBox="0 0 24 24" width="24" height="24" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M12 1c6.075 0 11 4.925 11 11s-4.925 11-11 11S1 18.075 1 12 5.925 1 12 1ZM2.5 12a9.5 9.5 0 0 0 9.5 9.5 9.5 9.5 0 0 0 9.5-9.5A9.5 9.5 0 0 0 12 2.5 9.5 9.5 0 0 0 2.5 12Zm9.5 2a2 2 0 1 1-.001-3.999A2 2 0 0 1 12 14Z"></path></svg><span class="NavLink-module__title--xw3ok">Issues</span><span class="NavLink-module__subtitle--qC15H">Plan and track work</span></div></a></li><li><a href="https://github.com/features/code-review" data-analytics-event="{"action":"code_review","tag":"link","context":"platform","location":"navbar","label":"code_review_link_platform_navbar"}" class="NavLink-module__link--n48VB"><div class="NavLink-module__text--SdWkb"><svg aria-hidden="true" focusable="false" class="octicon octicon-code NavLink-module__icon--h0sw7" viewBox="0 0 24 24" width="24" height="24" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M15.22 4.97a.75.75 0 0 1 1.06 0l6.5 6.5a.75.75 0 0 1 0 1.06l-6.5 6.5a.749.749 0 0 1-1.275-.326.749.749 0 0 1 .215-.734L21.19 12l-5.97-5.97a.75.75 0 0 1 0-1.06Zm-6.44 0a.75.75 0 0 1 0 1.06L2.81 12l5.97 5.97a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215l-6.5-6.5a.75.75 0 0 1 0-1.06l6.5-6.5a.75.75 0 0 1 1.06 0Z"></path></svg><span class="NavLink-module__title--xw3ok">Code Review</span><span class="NavLink-module__subtitle--qC15H">Manage code changes</span></div></a></li></ul></div></li><li><div class="NavGroup-module__group--T925n"><span class="NavGroup-module__title--TdKyz">APPLICATION SECURITY</span><ul class="NavGroup-module__list--M8eGv"><li><a href="https://github.com/security/advanced-security" data-analytics-event="{"action":"github_advanced_security","tag":"link","context":"platform","location":"navbar","label":"github_advanced_security_link_platform_navbar"}" class="NavLink-module__link--n48VB"><div class="NavLink-module__text--SdWkb"><svg aria-hidden="true" focusable="false" class="octicon octicon-shield-check NavLink-module__icon--h0sw7" viewBox="0 0 24 24" width="24" height="24" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M16.53 9.78a.75.75 0 0 0-1.06-1.06L11 13.19l-1.97-1.97a.75.75 0 0 0-1.06 1.06l2.5 2.5a.75.75 0 0 0 1.06 0l5-5Z"></path><path d="m12.54.637 8.25 2.675A1.75 1.75 0 0 1 22 4.976V10c0 6.19-3.771 10.704-9.401 12.83a1.704 1.704 0 0 1-1.198 0C5.77 20.705 2 16.19 2 10V4.976c0-.758.489-1.43 1.21-1.664L11.46.637a1.748 1.748 0 0 1 1.08 0Zm-.617 1.426-8.25 2.676a.249.249 0 0 0-.173.237V10c0 5.46 3.28 9.483 8.43 11.426a.199.199 0 0 0 .14 0C17.22 19.483 20.5 15.461 20.5 10V4.976a.25.25 0 0 0-.173-.237l-8.25-2.676a.253.253 0 0 0-.154 0Z"></path></svg><span class="NavLink-module__title--xw3ok">GitHub Advanced Security</span><span class="NavLink-module__subtitle--qC15H">Find and fix vulnerabilities</span></div></a></li><li><a href="https://github.com/security/advanced-security/code-security" data-analytics-event="{"action":"code_security","tag":"link","context":"platform","location":"navbar","label":"code_security_link_platform_navbar"}" class="NavLink-module__link--n48VB"><div class="NavLink-module__text--SdWkb"><svg aria-hidden="true" focusable="false" class="octicon octicon-code-square NavLink-module__icon--h0sw7" viewBox="0 0 24 24" width="24" height="24" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M10.3 8.24a.75.75 0 0 1-.04 1.06L7.352 12l2.908 2.7a.75.75 0 1 1-1.02 1.1l-3.5-3.25a.75.75 0 0 1 0-1.1l3.5-3.25a.75.75 0 0 1 1.06.04Zm3.44 1.06a.75.75 0 1 1 1.02-1.1l3.5 3.25a.75.75 0 0 1 0 1.1l-3.5 3.25a.75.75 0 1 1-1.02-1.1l2.908-2.7-2.908-2.7Z"></path><path d="M2 3.75C2 2.784 2.784 2 3.75 2h16.5c.966 0 1.75.784 1.75 1.75v16.5A1.75 1.75 0 0 1 20.25 22H3.75A1.75 1.75 0 0 1 2 20.25Zm1.75-.25a.25.25 0 0 0-.25.25v16.5c0 .138.112.25.25.25h16.5a.25.25 0 0 0 .25-.25V3.75a.25.25 0 0 0-.25-.25Z"></path></svg><span class="NavLink-module__title--xw3ok">Code security</span><span class="NavLink-module__subtitle--qC15H">Secure your code as you build</span></div></a></li><li><a href="https://github.com/security/advanced-security/secret-protection" data-analytics-event="{"action":"secret_protection","tag":"link","context":"platform","location":"navbar","label":"secret_protection_link_platform_navbar"}" class="NavLink-module__link--n48VB"><div class="NavLink-module__text--SdWkb"><svg aria-hidden="true" focusable="false" class="octicon octicon-lock NavLink-module__icon--h0sw7" viewBox="0 0 24 24" width="24" height="24" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M6 9V7.25C6 3.845 8.503 1 12 1s6 2.845 6 6.25V9h.5a2.5 2.5 0 0 1 2.5 2.5v8a2.5 2.5 0 0 1-2.5 2.5h-13A2.5 2.5 0 0 1 3 19.5v-8A2.5 2.5 0 0 1 5.5 9Zm-1.5 2.5v8a1 1 0 0 0 1 1h13a1 1 0 0 0 1-1v-8a1 1 0 0 0-1-1h-13a1 1 0 0 0-1 1Zm3-4.25V9h9V7.25c0-2.67-1.922-4.75-4.5-4.75-2.578 0-4.5 2.08-4.5 4.75Z"></path></svg><span class="NavLink-module__title--xw3ok">Secret protection</span><span class="NavLink-module__subtitle--qC15H">Stop leaks before they start</span></div></a></li></ul></div></li><li><div class="NavGroup-module__group--T925n NavGroup-module__hasSeparator--AJeNz"><span class="NavGroup-module__title--TdKyz">EXPLORE</span><ul class="NavGroup-module__list--M8eGv"><li><a href="https://github.com/why-github" data-analytics-event="{"action":"why_github","tag":"link","context":"platform","location":"navbar","label":"why_github_link_platform_navbar"}" class="NavLink-module__link--n48VB"><span class="NavLink-module__title--xw3ok">Why GitHub</span></a></li><li><a href="https://docs.github.com" data-analytics-event="{"action":"documentation","tag":"link","context":"platform","location":"navbar","label":"documentation_link_platform_navbar"}" class="NavLink-module__link--n48VB" target="_blank" rel="noreferrer"><span class="NavLink-module__title--xw3ok">Documentation</span><svg aria-hidden="true" focusable="false" class="octicon octicon-link-external NavLink-module__externalIcon--JurQ9" viewBox="0 0 16 16" width="16" height="16" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M3.75 2h3.5a.75.75 0 0 1 0 1.5h-3.5a.25.25 0 0 0-.25.25v8.5c0 .138.112.25.25.25h8.5a.25.25 0 0 0 .25-.25v-3.5a.75.75 0 0 1 1.5 0v3.5A1.75 1.75 0 0 1 12.25 14h-8.5A1.75 1.75 0 0 1 2 12.25v-8.5C2 2.784 2.784 2 3.75 2Zm6.854-1h4.146a.25.25 0 0 1 .25.25v4.146a.25.25 0 0 1-.427.177L13.03 4.03 9.28 7.78a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042l3.75-3.75-1.543-1.543A.25.25 0 0 1 10.604 1Z"></path></svg></a></li><li><a href="https://github.blog" data-analytics-event="{"action":"blog","tag":"link","context":"platform","location":"navbar","label":"blog_link_platform_navbar"}" class="NavLink-module__link--n48VB" target="_blank" rel="noreferrer"><span class="NavLink-module__title--xw3ok">Blog</span><svg aria-hidden="true" focusable="false" class="octicon octicon-link-external NavLink-module__externalIcon--JurQ9" viewBox="0 0 16 16" width="16" height="16" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M3.75 2h3.5a.75.75 0 0 1 0 1.5h-3.5a.25.25 0 0 0-.25.25v8.5c0 .138.112.25.25.25h8.5a.25.25 0 0 0 .25-.25v-3.5a.75.75 0 0 1 1.5 0v3.5A1.75 1.75 0 0 1 12.25 14h-8.5A1.75 1.75 0 0 1 2 12.25v-8.5C2 2.784 2.784 2 3.75 2Zm6.854-1h4.146a.25.25 0 0 1 .25.25v4.146a.25.25 0 0 1-.427.177L13.03 4.03 9.28 7.78a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042l3.75-3.75-1.543-1.543A.25.25 0 0 1 10.604 1Z"></path></svg></a></li><li><a href="https://github.blog/changelog" data-analytics-event="{"action":"changelog","tag":"link","context":"platform","location":"navbar","label":"changelog_link_platform_navbar"}" class="NavLink-module__link--n48VB" target="_blank" rel="noreferrer"><span class="NavLink-module__title--xw3ok">Changelog</span><svg aria-hidden="true" focusable="false" class="octicon octicon-link-external NavLink-module__externalIcon--JurQ9" viewBox="0 0 16 16" width="16" height="16" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M3.75 2h3.5a.75.75 0 0 1 0 1.5h-3.5a.25.25 0 0 0-.25.25v8.5c0 .138.112.25.25.25h8.5a.25.25 0 0 0 .25-.25v-3.5a.75.75 0 0 1 1.5 0v3.5A1.75 1.75 0 0 1 12.25 14h-8.5A1.75 1.75 0 0 1 2 12.25v-8.5C2 2.784 2.784 2 3.75 2Zm6.854-1h4.146a.25.25 0 0 1 .25.25v4.146a.25.25 0 0 1-.427.177L13.03 4.03 9.28 7.78a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042l3.75-3.75-1.543-1.543A.25.25 0 0 1 10.604 1Z"></path></svg></a></li><li><a href="https://github.com/marketplace" data-analytics-event="{"action":"marketplace","tag":"link","context":"platform","location":"navbar","label":"marketplace_link_platform_navbar"}" class="NavLink-module__link--n48VB"><span class="NavLink-module__title--xw3ok">Marketplace</span></a></li></ul></div></li></ul><div class="NavDropdown-module__trailingLinkContainer--MNB5T"><a href="https://github.com/features" data-analytics-event="{"action":"view_all_features","tag":"link","context":"platform","location":"navbar","label":"view_all_features_link_platform_navbar"}" class="NavLink-module__link--n48VB"><span class="NavLink-module__title--xw3ok">View all features</span><svg aria-hidden="true" focusable="false" class="octicon octicon-chevron-right NavLink-module__arrowIcon--g6Lip" viewBox="0 0 16 16" width="16" height="16" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M6.22 3.22a.75.75 0 0 1 1.06 0l4.25 4.25a.75.75 0 0 1 0 1.06l-4.25 4.25a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042L9.94 8 6.22 4.28a.75.75 0 0 1 0-1.06Z"></path></svg></a></div></div></div></li><li><div class="NavDropdown-module__container--bmXM2 js-details-container js-header-menu-item"><button type="button" class="NavDropdown-module__button--Hq9UR js-details-target" aria-expanded="false">Solutions<svg aria-hidden="true" focusable="false" class="octicon octicon-chevron-right NavDropdown-module__buttonIcon--SR0Ke" viewBox="0 0 16 16" width="16" height="16" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M6.22 3.22a.75.75 0 0 1 1.06 0l4.25 4.25a.75.75 0 0 1 0 1.06l-4.25 4.25a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042L9.94 8 6.22 4.28a.75.75 0 0 1 0-1.06Z"></path></svg></button><div class="NavDropdown-module__dropdown--Ig57Y"><ul class="NavDropdown-module__list--RwSSK"><li><div class="NavGroup-module__group--T925n"><span class="NavGroup-module__title--TdKyz">BY COMPANY SIZE</span><ul class="NavGroup-module__list--M8eGv"><li><a href="https://github.com/enterprise" data-analytics-event="{"action":"enterprises","tag":"link","context":"solutions","location":"navbar","label":"enterprises_link_solutions_navbar"}" class="NavLink-module__link--n48VB"><span class="NavLink-module__title--xw3ok">Enterprises</span></a></li><li><a href="https://github.com/team" data-analytics-event="{"action":"small_and_medium_teams","tag":"link","context":"solutions","location":"navbar","label":"small_and_medium_teams_link_solutions_navbar"}" class="NavLink-module__link--n48VB"><span class="NavLink-module__title--xw3ok">Small and medium teams</span></a></li><li><a href="https://github.com/enterprise/startups" data-analytics-event="{"action":"startups","tag":"link","context":"solutions","location":"navbar","label":"startups_link_solutions_navbar"}" class="NavLink-module__link--n48VB"><span class="NavLink-module__title--xw3ok">Startups</span></a></li><li><a href="https://github.com/solutions/industry/nonprofits" data-analytics-event="{"action":"nonprofits","tag":"link","context":"solutions","location":"navbar","label":"nonprofits_link_solutions_navbar"}" class="NavLink-module__link--n48VB"><span class="NavLink-module__title--xw3ok">Nonprofits</span></a></li></ul></div></li><li><div class="NavGroup-module__group--T925n"><span class="NavGroup-module__title--TdKyz">BY USE CASE</span><ul class="NavGroup-module__list--M8eGv"><li><a href="https://github.com/solutions/use-case/app-modernization" data-analytics-event="{"action":"app_modernization","tag":"link","context":"solutions","location":"navbar","label":"app_modernization_link_solutions_navbar"}" class="NavLink-module__link--n48VB"><span class="NavLink-module__title--xw3ok">App Modernization</span></a></li><li><a href="https://github.com/solutions/use-case/devsecops" data-analytics-event="{"action":"devsecops","tag":"link","context":"solutions","location":"navbar","label":"devsecops_link_solutions_navbar"}" class="NavLink-module__link--n48VB"><span class="NavLink-module__title--xw3ok">DevSecOps</span></a></li><li><a href="https://github.com/solutions/use-case/devops" data-analytics-event="{"action":"devops","tag":"link","context":"solutions","location":"navbar","label":"devops_link_solutions_navbar"}" class="NavLink-module__link--n48VB"><span class="NavLink-module__title--xw3ok">DevOps</span></a></li><li><a href="https://github.com/solutions/use-case/ci-cd" data-analytics-event="{"action":"ci/cd","tag":"link","context":"solutions","location":"navbar","label":"ci/cd_link_solutions_navbar"}" class="NavLink-module__link--n48VB"><span class="NavLink-module__title--xw3ok">CI/CD</span></a></li><li><a href="https://github.com/solutions/use-case" data-analytics-event="{"action":"view_all_use_cases","tag":"link","context":"solutions","location":"navbar","label":"view_all_use_cases_link_solutions_navbar"}" class="NavLink-module__link--n48VB"><span class="NavLink-module__title--xw3ok">View all use cases</span><svg aria-hidden="true" focusable="false" class="octicon octicon-chevron-right NavLink-module__arrowIcon--g6Lip" viewBox="0 0 16 16" width="16" height="16" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M6.22 3.22a.75.75 0 0 1 1.06 0l4.25 4.25a.75.75 0 0 1 0 1.06l-4.25 4.25a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042L9.94 8 6.22 4.28a.75.75 0 0 1 0-1.06Z"></path></svg></a></li></ul></div></li><li><div class="NavGroup-module__group--T925n"><span class="NavGroup-module__title--TdKyz">BY INDUSTRY</span><ul class="NavGroup-module__list--M8eGv"><li><a href="https://github.com/solutions/industry/healthcare" data-analytics-event="{"action":"healthcare","tag":"link","context":"solutions","location":"navbar","label":"healthcare_link_solutions_navbar"}" class="NavLink-module__link--n48VB"><span class="NavLink-module__title--xw3ok">Healthcare</span></a></li><li><a href="https://github.com/solutions/industry/financial-services" data-analytics-event="{"action":"financial_services","tag":"link","context":"solutions","location":"navbar","label":"financial_services_link_solutions_navbar"}" class="NavLink-module__link--n48VB"><span class="NavLink-module__title--xw3ok">Financial services</span></a></li><li><a href="https://github.com/solutions/industry/manufacturing" data-analytics-event="{"action":"manufacturing","tag":"link","context":"solutions","location":"navbar","label":"manufacturing_link_solutions_navbar"}" class="NavLink-module__link--n48VB"><span class="NavLink-module__title--xw3ok">Manufacturing</span></a></li><li><a href="https://github.com/solutions/industry/government" data-analytics-event="{"action":"government","tag":"link","context":"solutions","location":"navbar","label":"government_link_solutions_navbar"}" class="NavLink-module__link--n48VB"><span class="NavLink-module__title--xw3ok">Government</span></a></li><li><a href="https://github.com/solutions/industry" data-analytics-event="{"action":"view_all_industries","tag":"link","context":"solutions","location":"navbar","label":"view_all_industries_link_solutions_navbar"}" class="NavLink-module__link--n48VB"><span class="NavLink-module__title--xw3ok">View all industries</span><svg aria-hidden="true" focusable="false" class="octicon octicon-chevron-right NavLink-module__arrowIcon--g6Lip" viewBox="0 0 16 16" width="16" height="16" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M6.22 3.22a.75.75 0 0 1 1.06 0l4.25 4.25a.75.75 0 0 1 0 1.06l-4.25 4.25a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042L9.94 8 6.22 4.28a.75.75 0 0 1 0-1.06Z"></path></svg></a></li></ul></div></li></ul><div class="NavDropdown-module__trailingLinkContainer--MNB5T"><a href="https://github.com/solutions" data-analytics-event="{"action":"view_all_solutions","tag":"link","context":"solutions","location":"navbar","label":"view_all_solutions_link_solutions_navbar"}" class="NavLink-module__link--n48VB"><span class="NavLink-module__title--xw3ok">View all solutions</span><svg aria-hidden="true" focusable="false" class="octicon octicon-chevron-right NavLink-module__arrowIcon--g6Lip" viewBox="0 0 16 16" width="16" height="16" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M6.22 3.22a.75.75 0 0 1 1.06 0l4.25 4.25a.75.75 0 0 1 0 1.06l-4.25 4.25a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042L9.94 8 6.22 4.28a.75.75 0 0 1 0-1.06Z"></path></svg></a></div></div></div></li><li><div class="NavDropdown-module__container--bmXM2 js-details-container js-header-menu-item"><button type="button" class="NavDropdown-module__button--Hq9UR js-details-target" aria-expanded="false">Resources<svg aria-hidden="true" focusable="false" class="octicon octicon-chevron-right NavDropdown-module__buttonIcon--SR0Ke" viewBox="0 0 16 16" width="16" height="16" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M6.22 3.22a.75.75 0 0 1 1.06 0l4.25 4.25a.75.75 0 0 1 0 1.06l-4.25 4.25a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042L9.94 8 6.22 4.28a.75.75 0 0 1 0-1.06Z"></path></svg></button><div class="NavDropdown-module__dropdown--Ig57Y"><ul class="NavDropdown-module__list--RwSSK"><li><div class="NavGroup-module__group--T925n"><span class="NavGroup-module__title--TdKyz">EXPLORE BY TOPIC</span><ul class="NavGroup-module__list--M8eGv"><li><a href="https://github.com/resources/articles?topic=ai" data-analytics-event="{"action":"ai","tag":"link","context":"resources","location":"navbar","label":"ai_link_resources_navbar"}" class="NavLink-module__link--n48VB"><span class="NavLink-module__title--xw3ok">AI</span></a></li><li><a href="https://github.com/resources/articles?topic=software-development" data-analytics-event="{"action":"software_development","tag":"link","context":"resources","location":"navbar","label":"software_development_link_resources_navbar"}" class="NavLink-module__link--n48VB"><span class="NavLink-module__title--xw3ok">Software Development</span></a></li><li><a href="https://github.com/resources/articles?topic=devops" data-analytics-event="{"action":"devops","tag":"link","context":"resources","location":"navbar","label":"devops_link_resources_navbar"}" class="NavLink-module__link--n48VB"><span class="NavLink-module__title--xw3ok">DevOps</span></a></li><li><a href="https://github.com/resources/articles?topic=security" data-analytics-event="{"action":"security","tag":"link","context":"resources","location":"navbar","label":"security_link_resources_navbar"}" class="NavLink-module__link--n48VB"><span class="NavLink-module__title--xw3ok">Security</span></a></li><li><a href="https://github.com/resources/articles" data-analytics-event="{"action":"view_all_topics","tag":"link","context":"resources","location":"navbar","label":"view_all_topics_link_resources_navbar"}" class="NavLink-module__link--n48VB"><span class="NavLink-module__title--xw3ok">View all topics</span><svg aria-hidden="true" focusable="false" class="octicon octicon-chevron-right NavLink-module__arrowIcon--g6Lip" viewBox="0 0 16 16" width="16" height="16" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M6.22 3.22a.75.75 0 0 1 1.06 0l4.25 4.25a.75.75 0 0 1 0 1.06l-4.25 4.25a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042L9.94 8 6.22 4.28a.75.75 0 0 1 0-1.06Z"></path></svg></a></li></ul></div></li><li><div class="NavGroup-module__group--T925n"><span class="NavGroup-module__title--TdKyz">EXPLORE BY TYPE</span><ul class="NavGroup-module__list--M8eGv"><li><a href="https://github.com/customer-stories" data-analytics-event="{"action":"customer_stories","tag":"link","context":"resources","location":"navbar","label":"customer_stories_link_resources_navbar"}" class="NavLink-module__link--n48VB"><span class="NavLink-module__title--xw3ok">Customer stories</span></a></li><li><a href="https://github.com/resources/events" data-analytics-event="{"action":"events__webinars","tag":"link","context":"resources","location":"navbar","label":"events__webinars_link_resources_navbar"}" class="NavLink-module__link--n48VB"><span class="NavLink-module__title--xw3ok">Events & webinars</span></a></li><li><a href="https://github.com/resources/whitepapers" data-analytics-event="{"action":"ebooks__reports","tag":"link","context":"resources","location":"navbar","label":"ebooks__reports_link_resources_navbar"}" class="NavLink-module__link--n48VB"><span class="NavLink-module__title--xw3ok">Ebooks & reports</span></a></li><li><a href="https://github.com/solutions/executive-insights" data-analytics-event="{"action":"business_insights","tag":"link","context":"resources","location":"navbar","label":"business_insights_link_resources_navbar"}" class="NavLink-module__link--n48VB"><span class="NavLink-module__title--xw3ok">Business insights</span></a></li><li><a href="https://skills.github.com" data-analytics-event="{"action":"github_skills","tag":"link","context":"resources","location":"navbar","label":"github_skills_link_resources_navbar"}" class="NavLink-module__link--n48VB" target="_blank" rel="noreferrer"><span class="NavLink-module__title--xw3ok">GitHub Skills</span><svg aria-hidden="true" focusable="false" class="octicon octicon-link-external NavLink-module__externalIcon--JurQ9" viewBox="0 0 16 16" width="16" height="16" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M3.75 2h3.5a.75.75 0 0 1 0 1.5h-3.5a.25.25 0 0 0-.25.25v8.5c0 .138.112.25.25.25h8.5a.25.25 0 0 0 .25-.25v-3.5a.75.75 0 0 1 1.5 0v3.5A1.75 1.75 0 0 1 12.25 14h-8.5A1.75 1.75 0 0 1 2 12.25v-8.5C2 2.784 2.784 2 3.75 2Zm6.854-1h4.146a.25.25 0 0 1 .25.25v4.146a.25.25 0 0 1-.427.177L13.03 4.03 9.28 7.78a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042l3.75-3.75-1.543-1.543A.25.25 0 0 1 10.604 1Z"></path></svg></a></li></ul></div></li><li><div class="NavGroup-module__group--T925n"><span class="NavGroup-module__title--TdKyz">SUPPORT & SERVICES</span><ul class="NavGroup-module__list--M8eGv"><li><a href="https://docs.github.com" data-analytics-event="{"action":"documentation","tag":"link","context":"resources","location":"navbar","label":"documentation_link_resources_navbar"}" class="NavLink-module__link--n48VB" target="_blank" rel="noreferrer"><span class="NavLink-module__title--xw3ok">Documentation</span><svg aria-hidden="true" focusable="false" class="octicon octicon-link-external NavLink-module__externalIcon--JurQ9" viewBox="0 0 16 16" width="16" height="16" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M3.75 2h3.5a.75.75 0 0 1 0 1.5h-3.5a.25.25 0 0 0-.25.25v8.5c0 .138.112.25.25.25h8.5a.25.25 0 0 0 .25-.25v-3.5a.75.75 0 0 1 1.5 0v3.5A1.75 1.75 0 0 1 12.25 14h-8.5A1.75 1.75 0 0 1 2 12.25v-8.5C2 2.784 2.784 2 3.75 2Zm6.854-1h4.146a.25.25 0 0 1 .25.25v4.146a.25.25 0 0 1-.427.177L13.03 4.03 9.28 7.78a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042l3.75-3.75-1.543-1.543A.25.25 0 0 1 10.604 1Z"></path></svg></a></li><li><a href="https://support.github.com" data-analytics-event="{"action":"customer_support","tag":"link","context":"resources","location":"navbar","label":"customer_support_link_resources_navbar"}" class="NavLink-module__link--n48VB" target="_blank" rel="noreferrer"><span class="NavLink-module__title--xw3ok">Customer support</span><svg aria-hidden="true" focusable="false" class="octicon octicon-link-external NavLink-module__externalIcon--JurQ9" viewBox="0 0 16 16" width="16" height="16" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M3.75 2h3.5a.75.75 0 0 1 0 1.5h-3.5a.25.25 0 0 0-.25.25v8.5c0 .138.112.25.25.25h8.5a.25.25 0 0 0 .25-.25v-3.5a.75.75 0 0 1 1.5 0v3.5A1.75 1.75 0 0 1 12.25 14h-8.5A1.75 1.75 0 0 1 2 12.25v-8.5C2 2.784 2.784 2 3.75 2Zm6.854-1h4.146a.25.25 0 0 1 .25.25v4.146a.25.25 0 0 1-.427.177L13.03 4.03 9.28 7.78a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042l3.75-3.75-1.543-1.543A.25.25 0 0 1 10.604 1Z"></path></svg></a></li><li><a href="https://github.com/orgs/community/discussions" data-analytics-event="{"action":"community_forum","tag":"link","context":"resources","location":"navbar","label":"community_forum_link_resources_navbar"}" class="NavLink-module__link--n48VB"><span class="NavLink-module__title--xw3ok">Community forum</span></a></li><li><a href="https://github.com/trust-center" data-analytics-event="{"action":"trust_center","tag":"link","context":"resources","location":"navbar","label":"trust_center_link_resources_navbar"}" class="NavLink-module__link--n48VB"><span class="NavLink-module__title--xw3ok">Trust center</span></a></li><li><a href="https://github.com/partners" data-analytics-event="{"action":"partners","tag":"link","context":"resources","location":"navbar","label":"partners_link_resources_navbar"}" class="NavLink-module__link--n48VB"><span class="NavLink-module__title--xw3ok">Partners</span></a></li></ul></div></li></ul></div></div></li><li><div class="NavDropdown-module__container--bmXM2 js-details-container js-header-menu-item"><button type="button" class="NavDropdown-module__button--Hq9UR js-details-target" aria-expanded="false">Open Source<svg aria-hidden="true" focusable="false" class="octicon octicon-chevron-right NavDropdown-module__buttonIcon--SR0Ke" viewBox="0 0 16 16" width="16" height="16" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M6.22 3.22a.75.75 0 0 1 1.06 0l4.25 4.25a.75.75 0 0 1 0 1.06l-4.25 4.25a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042L9.94 8 6.22 4.28a.75.75 0 0 1 0-1.06Z"></path></svg></button><div class="NavDropdown-module__dropdown--Ig57Y"><ul class="NavDropdown-module__list--RwSSK"><li><div class="NavGroup-module__group--T925n"><span class="NavGroup-module__title--TdKyz">COMMUNITY</span><ul class="NavGroup-module__list--M8eGv"><li><a href="https://github.com/sponsors" data-analytics-event="{"action":"github_sponsors","tag":"link","context":"open_source","location":"navbar","label":"github_sponsors_link_open_source_navbar"}" class="NavLink-module__link--n48VB"><div class="NavLink-module__text--SdWkb"><svg aria-hidden="true" focusable="false" class="octicon octicon-sponsor-tiers NavLink-module__icon--h0sw7" viewBox="0 0 24 24" width="24" height="24" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M16.004 1.25C18.311 1.25 20 3.128 20 5.75c0 2.292-1.23 4.464-3.295 6.485-.481.47-.98.909-1.482 1.31l.265 1.32 1.375 7.5a.75.75 0 0 1-.982.844l-3.512-1.207a.75.75 0 0 0-.488 0L8.37 23.209a.75.75 0 0 1-.982-.844l1.378-7.512.261-1.309c-.5-.4-1-.838-1.481-1.31C5.479 10.215 4.25 8.043 4.25 5.75c0-2.622 1.689-4.5 3.996-4.5 1.55 0 2.947.752 3.832 1.967l.047.067.047-.067a4.726 4.726 0 0 1 3.612-1.962l.22-.005ZM13.89 14.531c-.418.285-.828.542-1.218.77l-.18.103a.75.75 0 0 1-.734 0l-.071-.04-.46-.272c-.282-.173-.573-.36-.868-.562l-.121.605-1.145 6.239 2.3-.79a2.248 2.248 0 0 1 1.284-.054l.18.053 2.299.79-1.141-6.226-.125-.616ZM16.004 2.75c-1.464 0-2.731.983-3.159 2.459-.209.721-1.231.721-1.44 0-.428-1.476-1.695-2.459-3.16-2.459-1.44 0-2.495 1.173-2.495 3 0 1.811 1.039 3.647 2.844 5.412a19.624 19.624 0 0 0 3.734 2.84l-.019-.011-.184-.111.147-.088a19.81 19.81 0 0 0 3.015-2.278l.37-.352C17.46 9.397 18.5 7.561 18.5 5.75c0-1.827-1.055-3-2.496-3Z"></path></svg><span class="NavLink-module__title--xw3ok">GitHub Sponsors</span><span class="NavLink-module__subtitle--qC15H">Fund open source developers</span></div></a></li></ul></div></li><li><div class="NavGroup-module__group--T925n"><span class="NavGroup-module__title--TdKyz">PROGRAMS</span><ul class="NavGroup-module__list--M8eGv"><li><a href="https://securitylab.github.com" data-analytics-event="{"action":"security_lab","tag":"link","context":"open_source","location":"navbar","label":"security_lab_link_open_source_navbar"}" class="NavLink-module__link--n48VB" target="_blank" rel="noreferrer"><span class="NavLink-module__title--xw3ok">Security Lab</span><svg aria-hidden="true" focusable="false" class="octicon octicon-link-external NavLink-module__externalIcon--JurQ9" viewBox="0 0 16 16" width="16" height="16" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M3.75 2h3.5a.75.75 0 0 1 0 1.5h-3.5a.25.25 0 0 0-.25.25v8.5c0 .138.112.25.25.25h8.5a.25.25 0 0 0 .25-.25v-3.5a.75.75 0 0 1 1.5 0v3.5A1.75 1.75 0 0 1 12.25 14h-8.5A1.75 1.75 0 0 1 2 12.25v-8.5C2 2.784 2.784 2 3.75 2Zm6.854-1h4.146a.25.25 0 0 1 .25.25v4.146a.25.25 0 0 1-.427.177L13.03 4.03 9.28 7.78a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042l3.75-3.75-1.543-1.543A.25.25 0 0 1 10.604 1Z"></path></svg></a></li><li><a href="https://maintainers.github.com" data-analytics-event="{"action":"maintainer_community","tag":"link","context":"open_source","location":"navbar","label":"maintainer_community_link_open_source_navbar"}" class="NavLink-module__link--n48VB" target="_blank" rel="noreferrer"><span class="NavLink-module__title--xw3ok">Maintainer Community</span><svg aria-hidden="true" focusable="false" class="octicon octicon-link-external NavLink-module__externalIcon--JurQ9" viewBox="0 0 16 16" width="16" height="16" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M3.75 2h3.5a.75.75 0 0 1 0 1.5h-3.5a.25.25 0 0 0-.25.25v8.5c0 .138.112.25.25.25h8.5a.25.25 0 0 0 .25-.25v-3.5a.75.75 0 0 1 1.5 0v3.5A1.75 1.75 0 0 1 12.25 14h-8.5A1.75 1.75 0 0 1 2 12.25v-8.5C2 2.784 2.784 2 3.75 2Zm6.854-1h4.146a.25.25 0 0 1 .25.25v4.146a.25.25 0 0 1-.427.177L13.03 4.03 9.28 7.78a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042l3.75-3.75-1.543-1.543A.25.25 0 0 1 10.604 1Z"></path></svg></a></li><li><a href="https://github.com/accelerator" data-analytics-event="{"action":"accelerator","tag":"link","context":"open_source","location":"navbar","label":"accelerator_link_open_source_navbar"}" class="NavLink-module__link--n48VB"><span class="NavLink-module__title--xw3ok">Accelerator</span></a></li><li><a href="https://archiveprogram.github.com" data-analytics-event="{"action":"archive_program","tag":"link","context":"open_source","location":"navbar","label":"archive_program_link_open_source_navbar"}" class="NavLink-module__link--n48VB" target="_blank" rel="noreferrer"><span class="NavLink-module__title--xw3ok">Archive Program</span><svg aria-hidden="true" focusable="false" class="octicon octicon-link-external NavLink-module__externalIcon--JurQ9" viewBox="0 0 16 16" width="16" height="16" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M3.75 2h3.5a.75.75 0 0 1 0 1.5h-3.5a.25.25 0 0 0-.25.25v8.5c0 .138.112.25.25.25h8.5a.25.25 0 0 0 .25-.25v-3.5a.75.75 0 0 1 1.5 0v3.5A1.75 1.75 0 0 1 12.25 14h-8.5A1.75 1.75 0 0 1 2 12.25v-8.5C2 2.784 2.784 2 3.75 2Zm6.854-1h4.146a.25.25 0 0 1 .25.25v4.146a.25.25 0 0 1-.427.177L13.03 4.03 9.28 7.78a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042l3.75-3.75-1.543-1.543A.25.25 0 0 1 10.604 1Z"></path></svg></a></li></ul></div></li><li><div class="NavGroup-module__group--T925n"><span class="NavGroup-module__title--TdKyz">REPOSITORIES</span><ul class="NavGroup-module__list--M8eGv"><li><a href="https://github.com/topics" data-analytics-event="{"action":"topics","tag":"link","context":"open_source","location":"navbar","label":"topics_link_open_source_navbar"}" class="NavLink-module__link--n48VB"><span class="NavLink-module__title--xw3ok">Topics</span></a></li><li><a href="https://github.com/trending" data-analytics-event="{"action":"trending","tag":"link","context":"open_source","location":"navbar","label":"trending_link_open_source_navbar"}" class="NavLink-module__link--n48VB"><span class="NavLink-module__title--xw3ok">Trending</span></a></li><li><a href="https://github.com/collections" data-analytics-event="{"action":"collections","tag":"link","context":"open_source","location":"navbar","label":"collections_link_open_source_navbar"}" class="NavLink-module__link--n48VB"><span class="NavLink-module__title--xw3ok">Collections</span></a></li></ul></div></li></ul></div></div></li><li><div class="NavDropdown-module__container--bmXM2 js-details-container js-header-menu-item"><button type="button" class="NavDropdown-module__button--Hq9UR js-details-target" aria-expanded="false">Enterprise<svg aria-hidden="true" focusable="false" class="octicon octicon-chevron-right NavDropdown-module__buttonIcon--SR0Ke" viewBox="0 0 16 16" width="16" height="16" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M6.22 3.22a.75.75 0 0 1 1.06 0l4.25 4.25a.75.75 0 0 1 0 1.06l-4.25 4.25a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042L9.94 8 6.22 4.28a.75.75 0 0 1 0-1.06Z"></path></svg></button><div class="NavDropdown-module__dropdown--Ig57Y"><ul class="NavDropdown-module__list--RwSSK"><li><div class="NavGroup-module__group--T925n"><span class="NavGroup-module__title--TdKyz">ENTERPRISE SOLUTIONS</span><ul class="NavGroup-module__list--M8eGv"><li><a href="https://github.com/enterprise" data-analytics-event="{"action":"enterprise_platform","tag":"link","context":"enterprise","location":"navbar","label":"enterprise_platform_link_enterprise_navbar"}" class="NavLink-module__link--n48VB"><div class="NavLink-module__text--SdWkb"><svg aria-hidden="true" focusable="false" class="octicon octicon-stack NavLink-module__icon--h0sw7" viewBox="0 0 24 24" width="24" height="24" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M11.063 1.456a1.749 1.749 0 0 1 1.874 0l8.383 5.316a1.751 1.751 0 0 1 0 2.956l-8.383 5.316a1.749 1.749 0 0 1-1.874 0L2.68 9.728a1.751 1.751 0 0 1 0-2.956Zm1.071 1.267a.25.25 0 0 0-.268 0L3.483 8.039a.25.25 0 0 0 0 .422l8.383 5.316a.25.25 0 0 0 .268 0l8.383-5.316a.25.25 0 0 0 0-.422Z"></path><path d="M1.867 12.324a.75.75 0 0 1 1.035-.232l8.964 5.685a.25.25 0 0 0 .268 0l8.964-5.685a.75.75 0 0 1 .804 1.267l-8.965 5.685a1.749 1.749 0 0 1-1.874 0l-8.965-5.685a.75.75 0 0 1-.231-1.035Z"></path><path d="M1.867 16.324a.75.75 0 0 1 1.035-.232l8.964 5.685a.25.25 0 0 0 .268 0l8.964-5.685a.75.75 0 0 1 .804 1.267l-8.965 5.685a1.749 1.749 0 0 1-1.874 0l-8.965-5.685a.75.75 0 0 1-.231-1.035Z"></path></svg><span class="NavLink-module__title--xw3ok">Enterprise platform</span><span class="NavLink-module__subtitle--qC15H">AI-powered developer platform</span></div></a></li></ul></div></li><li><div class="NavGroup-module__group--T925n"><span class="NavGroup-module__title--TdKyz">AVAILABLE ADD-ONS</span><ul class="NavGroup-module__list--M8eGv"><li><a href="https://github.com/security/advanced-security" data-analytics-event="{"action":"github_advanced_security","tag":"link","context":"enterprise","location":"navbar","label":"github_advanced_security_link_enterprise_navbar"}" class="NavLink-module__link--n48VB"><div class="NavLink-module__text--SdWkb"><svg aria-hidden="true" focusable="false" class="octicon octicon-shield-check NavLink-module__icon--h0sw7" viewBox="0 0 24 24" width="24" height="24" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M16.53 9.78a.75.75 0 0 0-1.06-1.06L11 13.19l-1.97-1.97a.75.75 0 0 0-1.06 1.06l2.5 2.5a.75.75 0 0 0 1.06 0l5-5Z"></path><path d="m12.54.637 8.25 2.675A1.75 1.75 0 0 1 22 4.976V10c0 6.19-3.771 10.704-9.401 12.83a1.704 1.704 0 0 1-1.198 0C5.77 20.705 2 16.19 2 10V4.976c0-.758.489-1.43 1.21-1.664L11.46.637a1.748 1.748 0 0 1 1.08 0Zm-.617 1.426-8.25 2.676a.249.249 0 0 0-.173.237V10c0 5.46 3.28 9.483 8.43 11.426a.199.199 0 0 0 .14 0C17.22 19.483 20.5 15.461 20.5 10V4.976a.25.25 0 0 0-.173-.237l-8.25-2.676a.253.253 0 0 0-.154 0Z"></path></svg><span class="NavLink-module__title--xw3ok">GitHub Advanced Security</span><span class="NavLink-module__subtitle--qC15H">Enterprise-grade security features</span></div></a></li><li><a href="https://github.com/features/copilot/copilot-business" data-analytics-event="{"action":"copilot_for_business","tag":"link","context":"enterprise","location":"navbar","label":"copilot_for_business_link_enterprise_navbar"}" class="NavLink-module__link--n48VB"><div class="NavLink-module__text--SdWkb"><svg aria-hidden="true" focusable="false" class="octicon octicon-copilot NavLink-module__icon--h0sw7" viewBox="0 0 24 24" width="24" height="24" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M23.922 16.992c-.861 1.495-5.859 5.023-11.922 5.023-6.063 0-11.061-3.528-11.922-5.023A.641.641 0 0 1 0 16.736v-2.869a.841.841 0 0 1 .053-.22c.372-.935 1.347-2.292 2.605-2.656.167-.429.414-1.055.644-1.517a10.195 10.195 0 0 1-.052-1.086c0-1.331.282-2.499 1.132-3.368.397-.406.89-.717 1.474-.952 1.399-1.136 3.392-2.093 6.122-2.093 2.731 0 4.767.957 6.166 2.093.584.235 1.077.546 1.474.952.85.869 1.132 2.037 1.132 3.368 0 .368-.014.733-.052 1.086.23.462.477 1.088.644 1.517 1.258.364 2.233 1.721 2.605 2.656a.832.832 0 0 1 .053.22v2.869a.641.641 0 0 1-.078.256ZM12.172 11h-.344a4.323 4.323 0 0 1-.355.508C10.703 12.455 9.555 13 7.965 13c-1.725 0-2.989-.359-3.782-1.259a2.005 2.005 0 0 1-.085-.104L4 11.741v6.585c1.435.779 4.514 2.179 8 2.179 3.486 0 6.565-1.4 8-2.179v-6.585l-.098-.104s-.033.045-.085.104c-.793.9-2.057 1.259-3.782 1.259-1.59 0-2.738-.545-3.508-1.492a4.323 4.323 0 0 1-.355-.508h-.016.016Zm.641-2.935c.136 1.057.403 1.913.878 2.497.442.544 1.134.938 2.344.938 1.573 0 2.292-.337 2.657-.751.384-.435.558-1.15.558-2.361 0-1.14-.243-1.847-.705-2.319-.477-.488-1.319-.862-2.824-1.025-1.487-.161-2.192.138-2.533.529-.269.307-.437.808-.438 1.578v.021c0 .265.021.562.063.893Zm-1.626 0c.042-.331.063-.628.063-.894v-.02c-.001-.77-.169-1.271-.438-1.578-.341-.391-1.046-.69-2.533-.529-1.505.163-2.347.537-2.824 1.025-.462.472-.705 1.179-.705 2.319 0 1.211.175 1.926.558 2.361.365.414 1.084.751 2.657.751 1.21 0 1.902-.394 2.344-.938.475-.584.742-1.44.878-2.497Z"></path><path d="M14.5 14.25a1 1 0 0 1 1 1v2a1 1 0 0 1-2 0v-2a1 1 0 0 1 1-1Zm-5 0a1 1 0 0 1 1 1v2a1 1 0 0 1-2 0v-2a1 1 0 0 1 1-1Z"></path></svg><span class="NavLink-module__title--xw3ok">Copilot for Business</span><span class="NavLink-module__subtitle--qC15H">Enterprise-grade AI features</span></div></a></li><li><a href="https://github.com/premium-support" data-analytics-event="{"action":"premium_support","tag":"link","context":"enterprise","location":"navbar","label":"premium_support_link_enterprise_navbar"}" class="NavLink-module__link--n48VB"><div class="NavLink-module__text--SdWkb"><svg aria-hidden="true" focusable="false" class="octicon octicon-comment-discussion NavLink-module__icon--h0sw7" viewBox="0 0 24 24" width="24" height="24" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M1.75 1h12.5c.966 0 1.75.784 1.75 1.75v9.5A1.75 1.75 0 0 1 14.25 14H8.061l-2.574 2.573A1.458 1.458 0 0 1 3 15.543V14H1.75A1.75 1.75 0 0 1 0 12.25v-9.5C0 1.784.784 1 1.75 1ZM1.5 2.75v9.5c0 .138.112.25.25.25h2a.75.75 0 0 1 .75.75v2.19l2.72-2.72a.749.749 0 0 1 .53-.22h6.5a.25.25 0 0 0 .25-.25v-9.5a.25.25 0 0 0-.25-.25H1.75a.25.25 0 0 0-.25.25Z"></path><path d="M22.5 8.75a.25.25 0 0 0-.25-.25h-3.5a.75.75 0 0 1 0-1.5h3.5c.966 0 1.75.784 1.75 1.75v9.5A1.75 1.75 0 0 1 22.25 20H21v1.543a1.457 1.457 0 0 1-2.487 1.03L15.939 20H10.75A1.75 1.75 0 0 1 9 18.25v-1.465a.75.75 0 0 1 1.5 0v1.465c0 .138.112.25.25.25h5.5a.75.75 0 0 1 .53.22l2.72 2.72v-2.19a.75.75 0 0 1 .75-.75h2a.25.25 0 0 0 .25-.25v-9.5Z"></path></svg><span class="NavLink-module__title--xw3ok">Premium Support</span><span class="NavLink-module__subtitle--qC15H">Enterprise-grade 24/7 support</span></div></a></li></ul></div></li></ul></div></div></li><li><a href="https://github.com/pricing" data-analytics-event="{"action":"pricing","tag":"link","context":"pricing","location":"navbar","label":"pricing_link_pricing_navbar"}" class="NavLink-module__link--n48VB MarketingNavigation-module__navLink--U9Uuk"><span class="NavLink-module__title--xw3ok">Pricing</span></a></li></ul></nav><script type="application/json" id="__PRIMER_DATA_:R0:__">{"resolvedServerColorMode":"day"}</script></div>-</react-partial>---- <div class="d-flex flex-column flex-lg-row width-full flex-justify-end flex-lg-items-center text-center mt-3 mt-lg-0 text-lg-left ml-lg-3">----<qbsearch-input class="search-input" data-scope="owner:ryanoasis" data-custom-scopes-path="/search/custom_scopes" data-delete-custom-scopes-csrf="oRqugm9QszWm5nlAn_v44pyAmFGybq64yNut2RtrV1tGR5RnnsOX7eOb0Ct6uqMMpagu5pmMb2zwYISYpTRmoA" data-max-custom-scopes="10" data-header-redesign-enabled="false" data-initial-value="" data-blackbird-suggestions-path="/search/suggestions" data-jump-to-suggestions-path="/_graphql/GetSuggestedNavigationDestinations" data-current-repository="" data-current-org="" data-current-owner="" data-logged-in="false" data-copilot-chat-enabled="false" data-nl-search-enabled="false" data-retain-scroll-position="true">- <div- class="search-input-container search-with-dialog position-relative d-flex flex-row flex-items-center mr-4 rounded"- data-action="click:qbsearch-input#searchInputContainerClicked"- >- <button- type="button"- class="header-search-button placeholder input-button form-control d-flex flex-1 flex-self-stretch flex-items-center no-wrap width-full py-0 pl-2 pr-0 text-left border-0 box-shadow-none"- data-target="qbsearch-input.inputButton"- aria-label="Search or jump to…"- aria-haspopup="dialog"- placeholder="Search or jump to..."- data-hotkey=s,/- autocapitalize="off"- data-analytics-event="{"location":"navbar","action":"searchbar","context":"global","tag":"input","label":"searchbar_input_global_navbar"}"- data-action="click:qbsearch-input#handleExpand"- >- <div class="mr-2 color-fg-muted">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-search">- <path d="M10.68 11.74a6 6 0 0 1-7.922-8.982 6 6 0 0 1 8.982 7.922l3.04 3.04a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215ZM11.5 7a4.499 4.499 0 1 0-8.997 0A4.499 4.499 0 0 0 11.5 7Z"></path>-</svg>- </div>- <span class="flex-1" data-target="qbsearch-input.inputButtonText">Search or jump to...</span>- <div class="d-flex" data-target="qbsearch-input.hotkeyIndicator">- <svg xmlns="http://www.w3.org/2000/svg" width="22" height="20" aria-hidden="true" class="mr-1"><path fill="none" stroke="#979A9C" opacity=".4" d="M3.5.5h12c1.7 0 3 1.3 3 3v13c0 1.7-1.3 3-3 3h-12c-1.7 0-3-1.3-3-3v-13c0-1.7 1.3-3 3-3z"></path><path fill="#979A9C" d="M11.8 6L8 15.1h-.9L10.8 6h1z"></path></svg>- </div>- </button>-- <input type="hidden" name="type" class="js-site-search-type-field">---<div class="Overlay--hidden " data-modal-dialog-overlay>- <modal-dialog data-action="close:qbsearch-input#handleClose cancel:qbsearch-input#handleClose" data-target="qbsearch-input.searchSuggestionsDialog" role="dialog" id="search-suggestions-dialog" aria-modal="true" aria-labelledby="search-suggestions-dialog-header" data-view-component="true" class="Overlay Overlay--width-large Overlay--height-auto">- <h1 id="search-suggestions-dialog-header" class="sr-only">Search code, repositories, users, issues, pull requests...</h1>- <div class="Overlay-body Overlay-body--paddingNone">-- <div data-view-component="true"> <div class="search-suggestions position-fixed width-full color-shadow-large border color-fg-default color-bg-default overflow-hidden d-flex flex-column query-builder-container"- style="border-radius: 12px;"- data-target="qbsearch-input.queryBuilderContainer"- hidden- >- <!-- '"` --><!-- </textarea></xmp> --></option></form><form id="query-builder-test-form" action="" accept-charset="UTF-8" method="get">- <query-builder data-target="qbsearch-input.queryBuilder" id="query-builder-query-builder-test" data-filter-key=":" data-view-component="true" class="QueryBuilder search-query-builder">- <div class="FormControl FormControl--fullWidth">- <label id="query-builder-test-label" for="query-builder-test" class="FormControl-label sr-only">- Search- </label>- <div- class="QueryBuilder-StyledInput width-fit "- data-target="query-builder.styledInput"- >- <span id="query-builder-test-leadingvisual-wrap" class="FormControl-input-leadingVisualWrap QueryBuilder-leadingVisualWrap">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-search FormControl-input-leadingVisual">- <path d="M10.68 11.74a6 6 0 0 1-7.922-8.982 6 6 0 0 1 8.982 7.922l3.04 3.04a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215ZM11.5 7a4.499 4.499 0 1 0-8.997 0A4.499 4.499 0 0 0 11.5 7Z"></path>-</svg>- </span>- <div data-target="query-builder.styledInputContainer" class="QueryBuilder-StyledInputContainer">- <div- aria-hidden="true"- class="QueryBuilder-StyledInputContent"- data-target="query-builder.styledInputContent"- ></div>- <div class="QueryBuilder-InputWrapper">- <div aria-hidden="true" class="QueryBuilder-Sizer" data-target="query-builder.sizer"></div>- <input id="query-builder-test" name="query-builder-test" value="" autocomplete="off" type="text" role="combobox" spellcheck="false" aria-expanded="false" aria-describedby="validation-2ad1b152-938a-4ef6-b9b9-6fa4f2272e0c" data-target="query-builder.input" data-action="- input:query-builder#inputChange- blur:query-builder#inputBlur- keydown:query-builder#inputKeydown- focus:query-builder#inputFocus- " data-view-component="true" class="FormControl-input QueryBuilder-Input FormControl-medium" />- </div>- </div>- <span class="sr-only" id="query-builder-test-clear">Clear</span>- <button role="button" id="query-builder-test-clear-button" aria-labelledby="query-builder-test-clear query-builder-test-label" data-target="query-builder.clearButton" data-action="- click:query-builder#clear- focus:query-builder#clearButtonFocus- blur:query-builder#clearButtonBlur- " variant="small" hidden="hidden" type="button" data-view-component="true" class="Button Button--iconOnly Button--invisible Button--medium mr-1 px-2 py-0 d-flex flex-items-center rounded-1 color-fg-muted"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-x-circle-fill Button-visual">- <path d="M2.343 13.657A8 8 0 1 1 13.658 2.343 8 8 0 0 1 2.343 13.657ZM6.03 4.97a.751.751 0 0 0-1.042.018.751.751 0 0 0-.018 1.042L6.94 8 4.97 9.97a.749.749 0 0 0 .326 1.275.749.749 0 0 0 .734-.215L8 9.06l1.97 1.97a.749.749 0 0 0 1.275-.326.749.749 0 0 0-.215-.734L9.06 8l1.97-1.97a.749.749 0 0 0-.326-1.275.749.749 0 0 0-.734.215L8 6.94Z"></path>-</svg>-</button>-- </div>- <template id="search-icon">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-search">- <path d="M10.68 11.74a6 6 0 0 1-7.922-8.982 6 6 0 0 1 8.982 7.922l3.04 3.04a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215ZM11.5 7a4.499 4.499 0 1 0-8.997 0A4.499 4.499 0 0 0 11.5 7Z"></path>-</svg>-</template>--<template id="code-icon">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-code">- <path d="m11.28 3.22 4.25 4.25a.75.75 0 0 1 0 1.06l-4.25 4.25a.749.749 0 0 1-1.275-.326.749.749 0 0 1 .215-.734L13.94 8l-3.72-3.72a.749.749 0 0 1 .326-1.275.749.749 0 0 1 .734.215Zm-6.56 0a.751.751 0 0 1 1.042.018.751.751 0 0 1 .018 1.042L2.06 8l3.72 3.72a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215L.47 8.53a.75.75 0 0 1 0-1.06Z"></path>-</svg>-</template>--<template id="file-code-icon">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-file-code">- <path d="M4 1.75C4 .784 4.784 0 5.75 0h5.586c.464 0 .909.184 1.237.513l2.914 2.914c.329.328.513.773.513 1.237v8.586A1.75 1.75 0 0 1 14.25 15h-9a.75.75 0 0 1 0-1.5h9a.25.25 0 0 0 .25-.25V6h-2.75A1.75 1.75 0 0 1 10 4.25V1.5H5.75a.25.25 0 0 0-.25.25v2.5a.75.75 0 0 1-1.5 0Zm1.72 4.97a.75.75 0 0 1 1.06 0l2 2a.75.75 0 0 1 0 1.06l-2 2a.749.749 0 0 1-1.275-.326.749.749 0 0 1 .215-.734l1.47-1.47-1.47-1.47a.75.75 0 0 1 0-1.06ZM3.28 7.78 1.81 9.25l1.47 1.47a.751.751 0 0 1-.018 1.042.751.751 0 0 1-1.042.018l-2-2a.75.75 0 0 1 0-1.06l2-2a.751.751 0 0 1 1.042.018.751.751 0 0 1 .018 1.042Zm8.22-6.218V4.25c0 .138.112.25.25.25h2.688l-.011-.013-2.914-2.914-.013-.011Z"></path>-</svg>-</template>--<template id="history-icon">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-history">- <path d="m.427 1.927 1.215 1.215a8.002 8.002 0 1 1-1.6 5.685.75.75 0 1 1 1.493-.154 6.5 6.5 0 1 0 1.18-4.458l1.358 1.358A.25.25 0 0 1 3.896 6H.25A.25.25 0 0 1 0 5.75V2.104a.25.25 0 0 1 .427-.177ZM7.75 4a.75.75 0 0 1 .75.75v2.992l2.028.812a.75.75 0 0 1-.557 1.392l-2.5-1A.751.751 0 0 1 7 8.25v-3.5A.75.75 0 0 1 7.75 4Z"></path>-</svg>-</template>--<template id="repo-icon">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-repo">- <path d="M2 2.5A2.5 2.5 0 0 1 4.5 0h8.75a.75.75 0 0 1 .75.75v12.5a.75.75 0 0 1-.75.75h-2.5a.75.75 0 0 1 0-1.5h1.75v-2h-8a1 1 0 0 0-.714 1.7.75.75 0 1 1-1.072 1.05A2.495 2.495 0 0 1 2 11.5Zm10.5-1h-8a1 1 0 0 0-1 1v6.708A2.486 2.486 0 0 1 4.5 9h8ZM5 12.25a.25.25 0 0 1 .25-.25h3.5a.25.25 0 0 1 .25.25v3.25a.25.25 0 0 1-.4.2l-1.45-1.087a.249.249 0 0 0-.3 0L5.4 15.7a.25.25 0 0 1-.4-.2Z"></path>-</svg>-</template>--<template id="bookmark-icon">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-bookmark">- <path d="M3 2.75C3 1.784 3.784 1 4.75 1h6.5c.966 0 1.75.784 1.75 1.75v11.5a.75.75 0 0 1-1.227.579L8 11.722l-3.773 3.107A.751.751 0 0 1 3 14.25Zm1.75-.25a.25.25 0 0 0-.25.25v9.91l3.023-2.489a.75.75 0 0 1 .954 0l3.023 2.49V2.75a.25.25 0 0 0-.25-.25Z"></path>-</svg>-</template>--<template id="plus-circle-icon">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-plus-circle">- <path d="M8 0a8 8 0 1 1 0 16A8 8 0 0 1 8 0ZM1.5 8a6.5 6.5 0 1 0 13 0 6.5 6.5 0 0 0-13 0Zm7.25-3.25v2.5h2.5a.75.75 0 0 1 0 1.5h-2.5v2.5a.75.75 0 0 1-1.5 0v-2.5h-2.5a.75.75 0 0 1 0-1.5h2.5v-2.5a.75.75 0 0 1 1.5 0Z"></path>-</svg>-</template>--<template id="circle-icon">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-dot-fill">- <path d="M8 4a4 4 0 1 1 0 8 4 4 0 0 1 0-8Z"></path>-</svg>-</template>--<template id="trash-icon">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-trash">- <path d="M11 1.75V3h2.25a.75.75 0 0 1 0 1.5H2.75a.75.75 0 0 1 0-1.5H5V1.75C5 .784 5.784 0 6.75 0h2.5C10.216 0 11 .784 11 1.75ZM4.496 6.675l.66 6.6a.25.25 0 0 0 .249.225h5.19a.25.25 0 0 0 .249-.225l.66-6.6a.75.75 0 0 1 1.492.149l-.66 6.6A1.748 1.748 0 0 1 10.595 15h-5.19a1.75 1.75 0 0 1-1.741-1.575l-.66-6.6a.75.75 0 1 1 1.492-.15ZM6.5 1.75V3h3V1.75a.25.25 0 0 0-.25-.25h-2.5a.25.25 0 0 0-.25.25Z"></path>-</svg>-</template>--<template id="team-icon">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-people">- <path d="M2 5.5a3.5 3.5 0 1 1 5.898 2.549 5.508 5.508 0 0 1 3.034 4.084.75.75 0 1 1-1.482.235 4 4 0 0 0-7.9 0 .75.75 0 0 1-1.482-.236A5.507 5.507 0 0 1 3.102 8.05 3.493 3.493 0 0 1 2 5.5ZM11 4a3.001 3.001 0 0 1 2.22 5.018 5.01 5.01 0 0 1 2.56 3.012.749.749 0 0 1-.885.954.752.752 0 0 1-.549-.514 3.507 3.507 0 0 0-2.522-2.372.75.75 0 0 1-.574-.73v-.352a.75.75 0 0 1 .416-.672A1.5 1.5 0 0 0 11 5.5.75.75 0 0 1 11 4Zm-5.5-.5a2 2 0 1 0-.001 3.999A2 2 0 0 0 5.5 3.5Z"></path>-</svg>-</template>--<template id="project-icon">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-project">- <path d="M1.75 0h12.5C15.216 0 16 .784 16 1.75v12.5A1.75 1.75 0 0 1 14.25 16H1.75A1.75 1.75 0 0 1 0 14.25V1.75C0 .784.784 0 1.75 0ZM1.5 1.75v12.5c0 .138.112.25.25.25h12.5a.25.25 0 0 0 .25-.25V1.75a.25.25 0 0 0-.25-.25H1.75a.25.25 0 0 0-.25.25ZM11.75 3a.75.75 0 0 1 .75.75v7.5a.75.75 0 0 1-1.5 0v-7.5a.75.75 0 0 1 .75-.75Zm-8.25.75a.75.75 0 0 1 1.5 0v5.5a.75.75 0 0 1-1.5 0ZM8 3a.75.75 0 0 1 .75.75v3.5a.75.75 0 0 1-1.5 0v-3.5A.75.75 0 0 1 8 3Z"></path>-</svg>-</template>--<template id="pencil-icon">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-pencil">- <path d="M11.013 1.427a1.75 1.75 0 0 1 2.474 0l1.086 1.086a1.75 1.75 0 0 1 0 2.474l-8.61 8.61c-.21.21-.47.364-.756.445l-3.251.93a.75.75 0 0 1-.927-.928l.929-3.25c.081-.286.235-.547.445-.758l8.61-8.61Zm.176 4.823L9.75 4.81l-6.286 6.287a.253.253 0 0 0-.064.108l-.558 1.953 1.953-.558a.253.253 0 0 0 .108-.064Zm1.238-3.763a.25.25 0 0 0-.354 0L10.811 3.75l1.439 1.44 1.263-1.263a.25.25 0 0 0 0-.354Z"></path>-</svg>-</template>--<template id="copilot-icon">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-copilot">- <path d="M7.998 15.035c-4.562 0-7.873-2.914-7.998-3.749V9.338c.085-.628.677-1.686 1.588-2.065.013-.07.024-.143.036-.218.029-.183.06-.384.126-.612-.201-.508-.254-1.084-.254-1.656 0-.87.128-1.769.693-2.484.579-.733 1.494-1.124 2.724-1.261 1.206-.134 2.262.034 2.944.765.05.053.096.108.139.165.044-.057.094-.112.143-.165.682-.731 1.738-.899 2.944-.765 1.23.137 2.145.528 2.724 1.261.566.715.693 1.614.693 2.484 0 .572-.053 1.148-.254 1.656.066.228.098.429.126.612.012.076.024.148.037.218.924.385 1.522 1.471 1.591 2.095v1.872c0 .766-3.351 3.795-8.002 3.795Zm0-1.485c2.28 0 4.584-1.11 5.002-1.433V7.862l-.023-.116c-.49.21-1.075.291-1.727.291-1.146 0-2.059-.327-2.71-.991A3.222 3.222 0 0 1 8 6.303a3.24 3.24 0 0 1-.544.743c-.65.664-1.563.991-2.71.991-.652 0-1.236-.081-1.727-.291l-.023.116v4.255c.419.323 2.722 1.433 5.002 1.433ZM6.762 2.83c-.193-.206-.637-.413-1.682-.297-1.019.113-1.479.404-1.713.7-.247.312-.369.789-.369 1.554 0 .793.129 1.171.308 1.371.162.181.519.379 1.442.379.853 0 1.339-.235 1.638-.54.315-.322.527-.827.617-1.553.117-.935-.037-1.395-.241-1.614Zm4.155-.297c-1.044-.116-1.488.091-1.681.297-.204.219-.359.679-.242 1.614.091.726.303 1.231.618 1.553.299.305.784.54 1.638.54.922 0 1.28-.198 1.442-.379.179-.2.308-.578.308-1.371 0-.765-.123-1.242-.37-1.554-.233-.296-.693-.587-1.713-.7Z"></path><path d="M6.25 9.037a.75.75 0 0 1 .75.75v1.501a.75.75 0 0 1-1.5 0V9.787a.75.75 0 0 1 .75-.75Zm4.25.75v1.501a.75.75 0 0 1-1.5 0V9.787a.75.75 0 0 1 1.5 0Z"></path>-</svg>-</template>--<template id="copilot-error-icon">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-copilot-error">- <path d="M16 11.24c0 .112-.072.274-.21.467L13 9.688V7.862l-.023-.116c-.49.21-1.075.291-1.727.291-.198 0-.388-.009-.571-.029L6.833 5.226a4.01 4.01 0 0 0 .17-.782c.117-.935-.037-1.395-.241-1.614-.193-.206-.637-.413-1.682-.297-.683.076-1.115.231-1.395.415l-1.257-.91c.579-.564 1.413-.877 2.485-.996 1.206-.134 2.262.034 2.944.765.05.053.096.108.139.165.044-.057.094-.112.143-.165.682-.731 1.738-.899 2.944-.765 1.23.137 2.145.528 2.724 1.261.566.715.693 1.614.693 2.484 0 .572-.053 1.148-.254 1.656.066.228.098.429.126.612.012.076.024.148.037.218.924.385 1.522 1.471 1.591 2.095Zm-5.083-8.707c-1.044-.116-1.488.091-1.681.297-.204.219-.359.679-.242 1.614.091.726.303 1.231.618 1.553.299.305.784.54 1.638.54.922 0 1.28-.198 1.442-.379.179-.2.308-.578.308-1.371 0-.765-.123-1.242-.37-1.554-.233-.296-.693-.587-1.713-.7Zm2.511 11.074c-1.393.776-3.272 1.428-5.43 1.428-4.562 0-7.873-2.914-7.998-3.749V9.338c.085-.628.677-1.686 1.588-2.065.013-.07.024-.143.036-.218.029-.183.06-.384.126-.612-.18-.455-.241-.963-.252-1.475L.31 4.107A.747.747 0 0 1 0 3.509V3.49a.748.748 0 0 1 .625-.73c.156-.026.306.047.435.139l14.667 10.578a.592.592 0 0 1 .227.264.752.752 0 0 1 .046.249v.022a.75.75 0 0 1-1.19.596Zm-1.367-.991L5.635 7.964a5.128 5.128 0 0 1-.889.073c-.652 0-1.236-.081-1.727-.291l-.023.116v4.255c.419.323 2.722 1.433 5.002 1.433 1.539 0 3.089-.505 4.063-.934Z"></path>-</svg>-</template>--<template id="workflow-icon">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-workflow">- <path d="M0 1.75C0 .784.784 0 1.75 0h3.5C6.216 0 7 .784 7 1.75v3.5A1.75 1.75 0 0 1 5.25 7H4v4a1 1 0 0 0 1 1h4v-1.25C9 9.784 9.784 9 10.75 9h3.5c.966 0 1.75.784 1.75 1.75v3.5A1.75 1.75 0 0 1 14.25 16h-3.5A1.75 1.75 0 0 1 9 14.25v-.75H5A2.5 2.5 0 0 1 2.5 11V7h-.75A1.75 1.75 0 0 1 0 5.25Zm1.75-.25a.25.25 0 0 0-.25.25v3.5c0 .138.112.25.25.25h3.5a.25.25 0 0 0 .25-.25v-3.5a.25.25 0 0 0-.25-.25Zm9 9a.25.25 0 0 0-.25.25v3.5c0 .138.112.25.25.25h3.5a.25.25 0 0 0 .25-.25v-3.5a.25.25 0 0 0-.25-.25Z"></path>-</svg>-</template>--<template id="book-icon">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-book">- <path d="M0 1.75A.75.75 0 0 1 .75 1h4.253c1.227 0 2.317.59 3 1.501A3.743 3.743 0 0 1 11.006 1h4.245a.75.75 0 0 1 .75.75v10.5a.75.75 0 0 1-.75.75h-4.507a2.25 2.25 0 0 0-1.591.659l-.622.621a.75.75 0 0 1-1.06 0l-.622-.621A2.25 2.25 0 0 0 5.258 13H.75a.75.75 0 0 1-.75-.75Zm7.251 10.324.004-5.073-.002-2.253A2.25 2.25 0 0 0 5.003 2.5H1.5v9h3.757a3.75 3.75 0 0 1 1.994.574ZM8.755 4.75l-.004 7.322a3.752 3.752 0 0 1 1.992-.572H14.5v-9h-3.495a2.25 2.25 0 0 0-2.25 2.25Z"></path>-</svg>-</template>--<template id="code-review-icon">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-code-review">- <path d="M1.75 1h12.5c.966 0 1.75.784 1.75 1.75v8.5A1.75 1.75 0 0 1 14.25 13H8.061l-2.574 2.573A1.458 1.458 0 0 1 3 14.543V13H1.75A1.75 1.75 0 0 1 0 11.25v-8.5C0 1.784.784 1 1.75 1ZM1.5 2.75v8.5c0 .138.112.25.25.25h2a.75.75 0 0 1 .75.75v2.19l2.72-2.72a.749.749 0 0 1 .53-.22h6.5a.25.25 0 0 0 .25-.25v-8.5a.25.25 0 0 0-.25-.25H1.75a.25.25 0 0 0-.25.25Zm5.28 1.72a.75.75 0 0 1 0 1.06L5.31 7l1.47 1.47a.751.751 0 0 1-.018 1.042.751.751 0 0 1-1.042.018l-2-2a.75.75 0 0 1 0-1.06l2-2a.75.75 0 0 1 1.06 0Zm2.44 0a.75.75 0 0 1 1.06 0l2 2a.75.75 0 0 1 0 1.06l-2 2a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042L10.69 7 9.22 5.53a.75.75 0 0 1 0-1.06Z"></path>-</svg>-</template>--<template id="codespaces-icon">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-codespaces">- <path d="M0 11.25c0-.966.784-1.75 1.75-1.75h12.5c.966 0 1.75.784 1.75 1.75v3A1.75 1.75 0 0 1 14.25 16H1.75A1.75 1.75 0 0 1 0 14.25Zm2-9.5C2 .784 2.784 0 3.75 0h8.5C13.216 0 14 .784 14 1.75v5a1.75 1.75 0 0 1-1.75 1.75h-8.5A1.75 1.75 0 0 1 2 6.75Zm1.75-.25a.25.25 0 0 0-.25.25v5c0 .138.112.25.25.25h8.5a.25.25 0 0 0 .25-.25v-5a.25.25 0 0 0-.25-.25Zm-2 9.5a.25.25 0 0 0-.25.25v3c0 .138.112.25.25.25h12.5a.25.25 0 0 0 .25-.25v-3a.25.25 0 0 0-.25-.25Z"></path><path d="M7 12.75a.75.75 0 0 1 .75-.75h4.5a.75.75 0 0 1 0 1.5h-4.5a.75.75 0 0 1-.75-.75Zm-4 0a.75.75 0 0 1 .75-.75h.5a.75.75 0 0 1 0 1.5h-.5a.75.75 0 0 1-.75-.75Z"></path>-</svg>-</template>--<template id="comment-icon">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-comment">- <path d="M1 2.75C1 1.784 1.784 1 2.75 1h10.5c.966 0 1.75.784 1.75 1.75v7.5A1.75 1.75 0 0 1 13.25 12H9.06l-2.573 2.573A1.458 1.458 0 0 1 4 13.543V12H2.75A1.75 1.75 0 0 1 1 10.25Zm1.75-.25a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h2a.75.75 0 0 1 .75.75v2.19l2.72-2.72a.749.749 0 0 1 .53-.22h4.5a.25.25 0 0 0 .25-.25v-7.5a.25.25 0 0 0-.25-.25Z"></path>-</svg>-</template>--<template id="comment-discussion-icon">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-comment-discussion">- <path d="M1.75 1h8.5c.966 0 1.75.784 1.75 1.75v5.5A1.75 1.75 0 0 1 10.25 10H7.061l-2.574 2.573A1.458 1.458 0 0 1 2 11.543V10h-.25A1.75 1.75 0 0 1 0 8.25v-5.5C0 1.784.784 1 1.75 1ZM1.5 2.75v5.5c0 .138.112.25.25.25h1a.75.75 0 0 1 .75.75v2.19l2.72-2.72a.749.749 0 0 1 .53-.22h3.5a.25.25 0 0 0 .25-.25v-5.5a.25.25 0 0 0-.25-.25h-8.5a.25.25 0 0 0-.25.25Zm13 2a.25.25 0 0 0-.25-.25h-.5a.75.75 0 0 1 0-1.5h.5c.966 0 1.75.784 1.75 1.75v5.5A1.75 1.75 0 0 1 14.25 12H14v1.543a1.458 1.458 0 0 1-2.487 1.03L9.22 12.28a.749.749 0 0 1 .326-1.275.749.749 0 0 1 .734.215l2.22 2.22v-2.19a.75.75 0 0 1 .75-.75h1a.25.25 0 0 0 .25-.25Z"></path>-</svg>-</template>--<template id="organization-icon">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-organization">- <path d="M1.75 16A1.75 1.75 0 0 1 0 14.25V1.75C0 .784.784 0 1.75 0h8.5C11.216 0 12 .784 12 1.75v12.5c0 .085-.006.168-.018.25h2.268a.25.25 0 0 0 .25-.25V8.285a.25.25 0 0 0-.111-.208l-1.055-.703a.749.749 0 1 1 .832-1.248l1.055.703c.487.325.779.871.779 1.456v5.965A1.75 1.75 0 0 1 14.25 16h-3.5a.766.766 0 0 1-.197-.026c-.099.017-.2.026-.303.026h-3a.75.75 0 0 1-.75-.75V14h-1v1.25a.75.75 0 0 1-.75.75Zm-.25-1.75c0 .138.112.25.25.25H4v-1.25a.75.75 0 0 1 .75-.75h2.5a.75.75 0 0 1 .75.75v1.25h2.25a.25.25 0 0 0 .25-.25V1.75a.25.25 0 0 0-.25-.25h-8.5a.25.25 0 0 0-.25.25ZM3.75 6h.5a.75.75 0 0 1 0 1.5h-.5a.75.75 0 0 1 0-1.5ZM3 3.75A.75.75 0 0 1 3.75 3h.5a.75.75 0 0 1 0 1.5h-.5A.75.75 0 0 1 3 3.75Zm4 3A.75.75 0 0 1 7.75 6h.5a.75.75 0 0 1 0 1.5h-.5A.75.75 0 0 1 7 6.75ZM7.75 3h.5a.75.75 0 0 1 0 1.5h-.5a.75.75 0 0 1 0-1.5ZM3 9.75A.75.75 0 0 1 3.75 9h.5a.75.75 0 0 1 0 1.5h-.5A.75.75 0 0 1 3 9.75ZM7.75 9h.5a.75.75 0 0 1 0 1.5h-.5a.75.75 0 0 1 0-1.5Z"></path>-</svg>-</template>--<template id="rocket-icon">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-rocket">- <path d="M14.064 0h.186C15.216 0 16 .784 16 1.75v.186a8.752 8.752 0 0 1-2.564 6.186l-.458.459c-.314.314-.641.616-.979.904v3.207c0 .608-.315 1.172-.833 1.49l-2.774 1.707a.749.749 0 0 1-1.11-.418l-.954-3.102a1.214 1.214 0 0 1-.145-.125L3.754 9.816a1.218 1.218 0 0 1-.124-.145L.528 8.717a.749.749 0 0 1-.418-1.11l1.71-2.774A1.748 1.748 0 0 1 3.31 4h3.204c.288-.338.59-.665.904-.979l.459-.458A8.749 8.749 0 0 1 14.064 0ZM8.938 3.623h-.002l-.458.458c-.76.76-1.437 1.598-2.02 2.5l-1.5 2.317 2.143 2.143 2.317-1.5c.902-.583 1.74-1.26 2.499-2.02l.459-.458a7.25 7.25 0 0 0 2.123-5.127V1.75a.25.25 0 0 0-.25-.25h-.186a7.249 7.249 0 0 0-5.125 2.123ZM3.56 14.56c-.732.732-2.334 1.045-3.005 1.148a.234.234 0 0 1-.201-.064.234.234 0 0 1-.064-.201c.103-.671.416-2.273 1.15-3.003a1.502 1.502 0 1 1 2.12 2.12Zm6.94-3.935c-.088.06-.177.118-.266.175l-2.35 1.521.548 1.783 1.949-1.2a.25.25 0 0 0 .119-.213ZM3.678 8.116 5.2 5.766c.058-.09.117-.178.176-.266H3.309a.25.25 0 0 0-.213.119l-1.2 1.95ZM12 5a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>-</svg>-</template>--<template id="shield-check-icon">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-shield-check">- <path d="m8.533.133 5.25 1.68A1.75 1.75 0 0 1 15 3.48V7c0 1.566-.32 3.182-1.303 4.682-.983 1.498-2.585 2.813-5.032 3.855a1.697 1.697 0 0 1-1.33 0c-2.447-1.042-4.049-2.357-5.032-3.855C1.32 10.182 1 8.566 1 7V3.48a1.75 1.75 0 0 1 1.217-1.667l5.25-1.68a1.748 1.748 0 0 1 1.066 0Zm-.61 1.429.001.001-5.25 1.68a.251.251 0 0 0-.174.237V7c0 1.36.275 2.666 1.057 3.859.784 1.194 2.121 2.342 4.366 3.298a.196.196 0 0 0 .154 0c2.245-.957 3.582-2.103 4.366-3.297C13.225 9.666 13.5 8.358 13.5 7V3.48a.25.25 0 0 0-.174-.238l-5.25-1.68a.25.25 0 0 0-.153 0ZM11.28 6.28l-3.5 3.5a.75.75 0 0 1-1.06 0l-1.5-1.5a.749.749 0 0 1 .326-1.275.749.749 0 0 1 .734.215l.97.97 2.97-2.97a.751.751 0 0 1 1.042.018.751.751 0 0 1 .018 1.042Z"></path>-</svg>-</template>--<template id="heart-icon">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-heart">- <path d="m8 14.25.345.666a.75.75 0 0 1-.69 0l-.008-.004-.018-.01a7.152 7.152 0 0 1-.31-.17 22.055 22.055 0 0 1-3.434-2.414C2.045 10.731 0 8.35 0 5.5 0 2.836 2.086 1 4.25 1 5.797 1 7.153 1.802 8 3.02 8.847 1.802 10.203 1 11.75 1 13.914 1 16 2.836 16 5.5c0 2.85-2.045 5.231-3.885 6.818a22.066 22.066 0 0 1-3.744 2.584l-.018.01-.006.003h-.002ZM4.25 2.5c-1.336 0-2.75 1.164-2.75 3 0 2.15 1.58 4.144 3.365 5.682A20.58 20.58 0 0 0 8 13.393a20.58 20.58 0 0 0 3.135-2.211C12.92 9.644 14.5 7.65 14.5 5.5c0-1.836-1.414-3-2.75-3-1.373 0-2.609.986-3.029 2.456a.749.749 0 0 1-1.442 0C6.859 3.486 5.623 2.5 4.25 2.5Z"></path>-</svg>-</template>--<template id="server-icon">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-server">- <path d="M1.75 1h12.5c.966 0 1.75.784 1.75 1.75v4c0 .372-.116.717-.314 1 .198.283.314.628.314 1v4a1.75 1.75 0 0 1-1.75 1.75H1.75A1.75 1.75 0 0 1 0 12.75v-4c0-.358.109-.707.314-1a1.739 1.739 0 0 1-.314-1v-4C0 1.784.784 1 1.75 1ZM1.5 2.75v4c0 .138.112.25.25.25h12.5a.25.25 0 0 0 .25-.25v-4a.25.25 0 0 0-.25-.25H1.75a.25.25 0 0 0-.25.25Zm.25 5.75a.25.25 0 0 0-.25.25v4c0 .138.112.25.25.25h12.5a.25.25 0 0 0 .25-.25v-4a.25.25 0 0 0-.25-.25ZM7 4.75A.75.75 0 0 1 7.75 4h4.5a.75.75 0 0 1 0 1.5h-4.5A.75.75 0 0 1 7 4.75ZM7.75 10h4.5a.75.75 0 0 1 0 1.5h-4.5a.75.75 0 0 1 0-1.5ZM3 4.75A.75.75 0 0 1 3.75 4h.5a.75.75 0 0 1 0 1.5h-.5A.75.75 0 0 1 3 4.75ZM3.75 10h.5a.75.75 0 0 1 0 1.5h-.5a.75.75 0 0 1 0-1.5Z"></path>-</svg>-</template>--<template id="globe-icon">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-globe">- <path d="M8 0a8 8 0 1 1 0 16A8 8 0 0 1 8 0ZM5.78 8.75a9.64 9.64 0 0 0 1.363 4.177c.255.426.542.832.857 1.215.245-.296.551-.705.857-1.215A9.64 9.64 0 0 0 10.22 8.75Zm4.44-1.5a9.64 9.64 0 0 0-1.363-4.177c-.307-.51-.612-.919-.857-1.215a9.927 9.927 0 0 0-.857 1.215A9.64 9.64 0 0 0 5.78 7.25Zm-5.944 1.5H1.543a6.507 6.507 0 0 0 4.666 5.5c-.123-.181-.24-.365-.352-.552-.715-1.192-1.437-2.874-1.581-4.948Zm-2.733-1.5h2.733c.144-2.074.866-3.756 1.58-4.948.12-.197.237-.381.353-.552a6.507 6.507 0 0 0-4.666 5.5Zm10.181 1.5c-.144 2.074-.866 3.756-1.58 4.948-.12.197-.237.381-.353.552a6.507 6.507 0 0 0 4.666-5.5Zm2.733-1.5a6.507 6.507 0 0 0-4.666-5.5c.123.181.24.365.353.552.714 1.192 1.436 2.874 1.58 4.948Z"></path>-</svg>-</template>--<template id="issue-opened-icon">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-issue-opened">- <path d="M8 9.5a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3Z"></path><path d="M8 0a8 8 0 1 1 0 16A8 8 0 0 1 8 0ZM1.5 8a6.5 6.5 0 1 0 13 0 6.5 6.5 0 0 0-13 0Z"></path>-</svg>-</template>--<template id="device-mobile-icon">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-device-mobile">- <path d="M3.75 0h8.5C13.216 0 14 .784 14 1.75v12.5A1.75 1.75 0 0 1 12.25 16h-8.5A1.75 1.75 0 0 1 2 14.25V1.75C2 .784 2.784 0 3.75 0ZM3.5 1.75v12.5c0 .138.112.25.25.25h8.5a.25.25 0 0 0 .25-.25V1.75a.25.25 0 0 0-.25-.25h-8.5a.25.25 0 0 0-.25.25ZM8 13a1 1 0 1 1 0-2 1 1 0 0 1 0 2Z"></path>-</svg>-</template>--<template id="package-icon">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-package">- <path d="m8.878.392 5.25 3.045c.54.314.872.89.872 1.514v6.098a1.75 1.75 0 0 1-.872 1.514l-5.25 3.045a1.75 1.75 0 0 1-1.756 0l-5.25-3.045A1.75 1.75 0 0 1 1 11.049V4.951c0-.624.332-1.201.872-1.514L7.122.392a1.75 1.75 0 0 1 1.756 0ZM7.875 1.69l-4.63 2.685L8 7.133l4.755-2.758-4.63-2.685a.248.248 0 0 0-.25 0ZM2.5 5.677v5.372c0 .09.047.171.125.216l4.625 2.683V8.432Zm6.25 8.271 4.625-2.683a.25.25 0 0 0 .125-.216V5.677L8.75 8.432Z"></path>-</svg>-</template>--<template id="credit-card-icon">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-credit-card">- <path d="M10.75 9a.75.75 0 0 0 0 1.5h1.5a.75.75 0 0 0 0-1.5h-1.5Z"></path><path d="M0 3.75C0 2.784.784 2 1.75 2h12.5c.966 0 1.75.784 1.75 1.75v8.5A1.75 1.75 0 0 1 14.25 14H1.75A1.75 1.75 0 0 1 0 12.25ZM14.5 6.5h-13v5.75c0 .138.112.25.25.25h12.5a.25.25 0 0 0 .25-.25Zm0-2.75a.25.25 0 0 0-.25-.25H1.75a.25.25 0 0 0-.25.25V5h13Z"></path>-</svg>-</template>--<template id="play-icon">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-play">- <path d="M8 0a8 8 0 1 1 0 16A8 8 0 0 1 8 0ZM1.5 8a6.5 6.5 0 1 0 13 0 6.5 6.5 0 0 0-13 0Zm4.879-2.773 4.264 2.559a.25.25 0 0 1 0 .428l-4.264 2.559A.25.25 0 0 1 6 10.559V5.442a.25.25 0 0 1 .379-.215Z"></path>-</svg>-</template>--<template id="gift-icon">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-gift">- <path d="M2 2.75A2.75 2.75 0 0 1 4.75 0c.983 0 1.873.42 2.57 1.232.268.318.497.668.68 1.042.183-.375.411-.725.68-1.044C9.376.42 10.266 0 11.25 0a2.75 2.75 0 0 1 2.45 4h.55c.966 0 1.75.784 1.75 1.75v2c0 .698-.409 1.301-1 1.582v4.918A1.75 1.75 0 0 1 13.25 16H2.75A1.75 1.75 0 0 1 1 14.25V9.332C.409 9.05 0 8.448 0 7.75v-2C0 4.784.784 4 1.75 4h.55c-.192-.375-.3-.8-.3-1.25ZM7.25 9.5H2.5v4.75c0 .138.112.25.25.25h4.5Zm1.5 0v5h4.5a.25.25 0 0 0 .25-.25V9.5Zm0-4V8h5.5a.25.25 0 0 0 .25-.25v-2a.25.25 0 0 0-.25-.25Zm-7 0a.25.25 0 0 0-.25.25v2c0 .138.112.25.25.25h5.5V5.5h-5.5Zm3-4a1.25 1.25 0 0 0 0 2.5h2.309c-.233-.818-.542-1.401-.878-1.793-.43-.502-.915-.707-1.431-.707ZM8.941 4h2.309a1.25 1.25 0 0 0 0-2.5c-.516 0-1 .205-1.43.707-.337.392-.646.975-.879 1.793Z"></path>-</svg>-</template>--<template id="code-square-icon">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-code-square">- <path d="M0 1.75C0 .784.784 0 1.75 0h12.5C15.216 0 16 .784 16 1.75v12.5A1.75 1.75 0 0 1 14.25 16H1.75A1.75 1.75 0 0 1 0 14.25Zm1.75-.25a.25.25 0 0 0-.25.25v12.5c0 .138.112.25.25.25h12.5a.25.25 0 0 0 .25-.25V1.75a.25.25 0 0 0-.25-.25Zm7.47 3.97a.75.75 0 0 1 1.06 0l2 2a.75.75 0 0 1 0 1.06l-2 2a.749.749 0 0 1-1.275-.326.749.749 0 0 1 .215-.734L10.69 8 9.22 6.53a.75.75 0 0 1 0-1.06ZM6.78 6.53 5.31 8l1.47 1.47a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215l-2-2a.75.75 0 0 1 0-1.06l2-2a.751.751 0 0 1 1.042.018.751.751 0 0 1 .018 1.042Z"></path>-</svg>-</template>--<template id="device-desktop-icon">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-device-desktop">- <path d="M14.25 1c.966 0 1.75.784 1.75 1.75v7.5A1.75 1.75 0 0 1 14.25 12h-3.727c.099 1.041.52 1.872 1.292 2.757A.752.752 0 0 1 11.25 16h-6.5a.75.75 0 0 1-.565-1.243c.772-.885 1.192-1.716 1.292-2.757H1.75A1.75 1.75 0 0 1 0 10.25v-7.5C0 1.784.784 1 1.75 1ZM1.75 2.5a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h12.5a.25.25 0 0 0 .25-.25v-7.5a.25.25 0 0 0-.25-.25ZM9.018 12H6.982a5.72 5.72 0 0 1-.765 2.5h3.566a5.72 5.72 0 0 1-.765-2.5Z"></path>-</svg>-</template>-- <div class="position-relative">- <ul- role="listbox"- class="ActionListWrap QueryBuilder-ListWrap"- aria-label="Suggestions"- data-action="- combobox-commit:query-builder#comboboxCommit- mousedown:query-builder#resultsMousedown- "- data-target="query-builder.resultsList"- data-persist-list=false- id="query-builder-test-results"- tabindex="-1"- ></ul>- </div>- <div class="FormControl-inlineValidation" id="validation-2ad1b152-938a-4ef6-b9b9-6fa4f2272e0c" hidden="hidden">- <span class="FormControl-inlineValidation--visual">- <svg aria-hidden="true" height="12" viewBox="0 0 12 12" version="1.1" width="12" data-view-component="true" class="octicon octicon-alert-fill">- <path d="M4.855.708c.5-.896 1.79-.896 2.29 0l4.675 8.351a1.312 1.312 0 0 1-1.146 1.954H1.33A1.313 1.313 0 0 1 .183 9.058ZM7 7V3H5v4Zm-1 3a1 1 0 1 0 0-2 1 1 0 0 0 0 2Z"></path>-</svg>- </span>- <span></span>-</div> </div>- <div data-target="query-builder.screenReaderFeedback" aria-live="polite" aria-atomic="true" class="sr-only"></div>-</query-builder></form>- <div class="d-flex flex-row color-fg-muted px-3 text-small color-bg-default search-feedback-prompt">- <a target="_blank" href="https://docs.github.com/search-github/github-code-search/understanding-github-code-search-syntax" data-view-component="true" class="Link color-fg-accent text-normal ml-2">Search syntax tips</a> <div class="d-flex flex-1"></div>- </div>- </div>-</div>-- </div>-</modal-dialog></div>- </div>- <div data-action="click:qbsearch-input#retract" class="dark-backdrop position-fixed" hidden data-target="qbsearch-input.darkBackdrop"></div>- <div class="color-fg-default">--<dialog-helper>- <dialog data-target="qbsearch-input.feedbackDialog" data-action="close:qbsearch-input#handleDialogClose cancel:qbsearch-input#handleDialogClose" id="feedback-dialog" aria-modal="true" aria-labelledby="feedback-dialog-title" aria-describedby="feedback-dialog-description" data-view-component="true" class="Overlay Overlay-whenNarrow Overlay--size-medium Overlay--motion-scaleFade Overlay--disableScroll">- <div data-view-component="true" class="Overlay-header">- <div class="Overlay-headerContentWrap">- <div class="Overlay-titleWrap">- <h1 class="Overlay-title " id="feedback-dialog-title">- Provide feedback- </h1>-- </div>- <div class="Overlay-actionWrap">- <button data-close-dialog-id="feedback-dialog" aria-label="Close" aria-label="Close" type="button" data-view-component="true" class="close-button Overlay-closeButton"><svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-x">- <path d="M3.72 3.72a.75.75 0 0 1 1.06 0L8 6.94l3.22-3.22a.749.749 0 0 1 1.275.326.749.749 0 0 1-.215.734L9.06 8l3.22 3.22a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215L8 9.06l-3.22 3.22a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042L6.94 8 3.72 4.78a.75.75 0 0 1 0-1.06Z"></path>-</svg></button>- </div>- </div>--</div>- <scrollable-region data-labelled-by="feedback-dialog-title">- <div data-view-component="true" class="Overlay-body"> <!-- '"` --><!-- </textarea></xmp> --></option></form><form id="code-search-feedback-form" data-turbo="false" action="/search/feedback" accept-charset="UTF-8" method="post"><input type="hidden" data-csrf="true" name="authenticity_token" value="qyt5QiWmmsPwzAz0MP/yslTVLUme4uNG9lrbqLQFFWRzN731+QsmLZy4j7aj5b2NOCQKD1DFUMqCpcn8ByZFyg==" />- <p>We read every piece of feedback, and take your input very seriously.</p>- <textarea name="feedback" class="form-control width-full mb-2" style="height: 120px" id="feedback"></textarea>- <input name="include_email" id="include_email" aria-label="Include my email address so I can be contacted" class="form-control mr-2" type="checkbox">- <label for="include_email" style="font-weight: normal">Include my email address so I can be contacted</label>-</form></div>- </scrollable-region>- <div data-view-component="true" class="Overlay-footer Overlay-footer--alignEnd"> <button data-close-dialog-id="feedback-dialog" type="button" data-view-component="true" class="btn"> Cancel-</button>- <button form="code-search-feedback-form" data-action="click:qbsearch-input#submitFeedback" type="submit" data-view-component="true" class="btn-primary btn"> Submit feedback-</button>-</div>-</dialog></dialog-helper>-- <custom-scopes data-target="qbsearch-input.customScopesManager">--<dialog-helper>- <dialog data-target="custom-scopes.customScopesModalDialog" data-action="close:qbsearch-input#handleDialogClose cancel:qbsearch-input#handleDialogClose" id="custom-scopes-dialog" aria-modal="true" aria-labelledby="custom-scopes-dialog-title" aria-describedby="custom-scopes-dialog-description" data-view-component="true" class="Overlay Overlay-whenNarrow Overlay--size-medium Overlay--motion-scaleFade Overlay--disableScroll">- <div data-view-component="true" class="Overlay-header Overlay-header--divided">- <div class="Overlay-headerContentWrap">- <div class="Overlay-titleWrap">- <h1 class="Overlay-title " id="custom-scopes-dialog-title">- Saved searches- </h1>- <h2 id="custom-scopes-dialog-description" class="Overlay-description">Use saved searches to filter your results more quickly</h2>- </div>- <div class="Overlay-actionWrap">- <button data-close-dialog-id="custom-scopes-dialog" aria-label="Close" aria-label="Close" type="button" data-view-component="true" class="close-button Overlay-closeButton"><svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-x">- <path d="M3.72 3.72a.75.75 0 0 1 1.06 0L8 6.94l3.22-3.22a.749.749 0 0 1 1.275.326.749.749 0 0 1-.215.734L9.06 8l3.22 3.22a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215L8 9.06l-3.22 3.22a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042L6.94 8 3.72 4.78a.75.75 0 0 1 0-1.06Z"></path>-</svg></button>- </div>- </div>--</div>- <scrollable-region data-labelled-by="custom-scopes-dialog-title">- <div data-view-component="true" class="Overlay-body"> <div data-target="custom-scopes.customScopesModalDialogFlash"></div>-- <div hidden class="create-custom-scope-form" data-target="custom-scopes.createCustomScopeForm">- <!-- '"` --><!-- </textarea></xmp> --></option></form><form id="custom-scopes-dialog-form" data-turbo="false" action="/search/custom_scopes" accept-charset="UTF-8" method="post"><input type="hidden" data-csrf="true" name="authenticity_token" value="AjmEaEVFMLRcwkuEg0efomR3LqfWXzIP+X3J33yCS+nFIwjmnMMElXmjk3Q1ALwynpVvmPrKVOk+ju7FZN/Pyg==" />- <div data-target="custom-scopes.customScopesModalDialogFlash"></div>-- <input type="hidden" id="custom_scope_id" name="custom_scope_id" data-target="custom-scopes.customScopesIdField">-- <div class="form-group">- <label for="custom_scope_name">Name</label>- <auto-check src="/search/custom_scopes/check_name" required>- <input- type="text"- name="custom_scope_name"- id="custom_scope_name"- data-target="custom-scopes.customScopesNameField"- class="form-control"- autocomplete="off"- placeholder="github-ruby"- required- maxlength="50">- <input type="hidden" data-csrf="true" value="TK3pmCEqVJY4a6CnTaPLP9xbHTMW3fr16u3dRgxw4KQYlX8gM3Nh4PmqXXnj2FlNRFWRAkPJKMW0CzpePGUmpw==" />- </auto-check>- </div>-- <div class="form-group">- <label for="custom_scope_query">Query</label>- <input- type="text"- name="custom_scope_query"- id="custom_scope_query"- data-target="custom-scopes.customScopesQueryField"- class="form-control"- autocomplete="off"- placeholder="(repo:mona/a OR repo:mona/b) AND lang:python"- required- maxlength="500">- </div>-- <p class="text-small color-fg-muted">- To see all available qualifiers, see our <a class="Link--inTextBlock" href="https://docs.github.com/search-github/github-code-search/understanding-github-code-search-syntax">documentation</a>.- </p>-</form> </div>-- <div data-target="custom-scopes.manageCustomScopesForm">- <div data-target="custom-scopes.list"></div>- </div>--</div>- </scrollable-region>- <div data-view-component="true" class="Overlay-footer Overlay-footer--alignEnd Overlay-footer--divided"> <button data-action="click:custom-scopes#customScopesCancel" type="button" data-view-component="true" class="btn"> Cancel-</button>- <button form="custom-scopes-dialog-form" data-action="click:custom-scopes#customScopesSubmit" data-target="custom-scopes.customScopesSubmitButton" type="submit" data-view-component="true" class="btn-primary btn"> Create saved search-</button>-</div>-</dialog></dialog-helper>- </custom-scopes>- </div>-</qbsearch-input>--- <div class="position-relative HeaderMenu-link-wrap d-lg-inline-block">- <a- href="/login?return_to=https%3A%2F%2Fgithub.com%2Fryanoasis%2F"- class="HeaderMenu-link HeaderMenu-link--sign-in HeaderMenu-button flex-shrink-0 no-underline d-none d-lg-inline-flex border border-lg-0 rounded px-2 py-1"- style="margin-left: 12px;"- data-hydro-click="{"event_type":"authentication.click","payload":{"location_in_page":"site header menu","repository_id":null,"auth_type":"SIGN_UP","originating_url":"https://github.com/ryanoasis","user_id":null}}" data-hydro-click-hmac="06273eeb1cd2e1c4974fecca6b6e9adbb7d95f6c1c53441c3fa555a3d7682fd3"- data-analytics-event="{"category":"Marketing nav","action":"click to go to homepage","label":"ref_page:Marketing;ref_cta:Sign in;ref_loc:Header"}"- >- Sign in- </a>- </div>-- <a href="/signup?ref_cta=Sign+up&ref_loc=header+logged+out&ref_page=%2F%3Cuser-name%3E&source=header"- class="HeaderMenu-link HeaderMenu-link--sign-up HeaderMenu-button flex-shrink-0 d-flex d-lg-inline-flex no-underline border color-border-default rounded px-2 py-1"- data-hydro-click="{"event_type":"authentication.click","payload":{"location_in_page":"site header menu","repository_id":null,"auth_type":"SIGN_UP","originating_url":"https://github.com/ryanoasis","user_id":null}}" data-hydro-click-hmac="06273eeb1cd2e1c4974fecca6b6e9adbb7d95f6c1c53441c3fa555a3d7682fd3"- data-analytics-event="{"category":"Sign up","action":"click to sign up for account","label":"ref_page:/<user-name>;ref_cta:Sign up;ref_loc:header logged out"}"- >- Sign up- </a>-- <div class="AppHeader-appearanceSettings">- <react-partial-anchor>- <button data-target="react-partial-anchor.anchor" id="icon-button-37e419c9-5249-4a2b-8ac6-0d3f9c537088" aria-labelledby="tooltip-d84a5da4-a625-4533-8b4b-2c9f1e43503c" type="button" disabled="disabled" data-view-component="true" class="Button Button--iconOnly Button--invisible Button--medium AppHeader-button HeaderMenu-link border cursor-wait"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-sliders Button-visual">- <path d="M15 2.75a.75.75 0 0 1-.75.75h-4a.75.75 0 0 1 0-1.5h4a.75.75 0 0 1 .75.75Zm-8.5.75v1.25a.75.75 0 0 0 1.5 0v-4a.75.75 0 0 0-1.5 0V2H1.75a.75.75 0 0 0 0 1.5H6.5Zm1.25 5.25a.75.75 0 0 0 0-1.5h-6a.75.75 0 0 0 0 1.5h6ZM15 8a.75.75 0 0 1-.75.75H11.5V10a.75.75 0 1 1-1.5 0V6a.75.75 0 0 1 1.5 0v1.25h2.75A.75.75 0 0 1 15 8Zm-9 5.25v-2a.75.75 0 0 0-1.5 0v1.25H1.75a.75.75 0 0 0 0 1.5H4.5v1.25a.75.75 0 0 0 1.5 0v-2Zm9 0a.75.75 0 0 1-.75.75h-6a.75.75 0 0 1 0-1.5h6a.75.75 0 0 1 .75.75Z"></path>-</svg>-</button><tool-tip id="tooltip-d84a5da4-a625-4533-8b4b-2c9f1e43503c" for="icon-button-37e419c9-5249-4a2b-8ac6-0d3f9c537088" popover="manual" data-direction="s" data-type="label" data-view-component="true" class="sr-only position-absolute">Appearance settings</tool-tip>-- <template data-target="react-partial-anchor.template">- <link crossorigin="anonymous" media="all" rel="stylesheet" href="https://github.githubassets.com/assets/primer-react.53f37102c46fd176a96b.module.css" />-<link crossorigin="anonymous" media="all" rel="stylesheet" href="https://github.githubassets.com/assets/appearance-settings.6c63a6de228d6520804d.module.css" />--<react-partial- partial-name="appearance-settings"- data-ssr="false"- data-attempted-ssr="false"- data-react-profiling="false"->-- <script type="application/json" data-target="react-partial.embeddedData">{"props":{}}</script>- <div data-target="react-partial.reactRoot"></div>-</react-partial>--- </template>- </react-partial-anchor>- </div>-- <button type="button" class="sr-only js-header-menu-focus-trap d-block d-lg-none">Resetting focus</button>- </div>- </div>- </div>- </div>-</header>-- <div hidden="hidden" data-view-component="true" class="js-stale-session-flash stale-session-flash flash flash-warn flash-full">-- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">- <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>-</svg>- <span class="js-stale-session-flash-signed-in" hidden>You signed in with another tab or window. <a class="Link--inTextBlock" href="">Reload</a> to refresh your session.</span>- <span class="js-stale-session-flash-signed-out" hidden>You signed out in another tab or window. <a class="Link--inTextBlock" href="">Reload</a> to refresh your session.</span>- <span class="js-stale-session-flash-switched" hidden>You switched accounts on another tab or window. <a class="Link--inTextBlock" href="">Reload</a> to refresh your session.</span>-- <button id="icon-button-bcc32402-a9cb-4926-a329-c55daa81ede2" aria-labelledby="tooltip-b3b6ca7a-688a-4b6a-a24e-62a517d6190a" type="button" data-view-component="true" class="Button Button--iconOnly Button--invisible Button--medium flash-close js-flash-close"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-x Button-visual">- <path d="M3.72 3.72a.75.75 0 0 1 1.06 0L8 6.94l3.22-3.22a.749.749 0 0 1 1.275.326.749.749 0 0 1-.215.734L9.06 8l3.22 3.22a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215L8 9.06l-3.22 3.22a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042L6.94 8 3.72 4.78a.75.75 0 0 1 0-1.06Z"></path>-</svg>-</button><tool-tip id="tooltip-b3b6ca7a-688a-4b6a-a24e-62a517d6190a" for="icon-button-bcc32402-a9cb-4926-a329-c55daa81ede2" popover="manual" data-direction="s" data-type="label" data-view-component="true" class="sr-only position-absolute">Dismiss alert</tool-tip>----</div>- </div>-- <div id="start-of-content" class="show-on-focus"></div>--------- <div id="js-flash-container" class="flash-container" data-turbo-replace>----- <template class="js-flash-template">--<div class="flash flash-full {{ className }}">- <div >- <button autofocus class="flash-close js-flash-close" type="button" aria-label="Dismiss this message">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-x">- <path d="M3.72 3.72a.75.75 0 0 1 1.06 0L8 6.94l3.22-3.22a.749.749 0 0 1 1.275.326.749.749 0 0 1-.215.734L9.06 8l3.22 3.22a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215L8 9.06l-3.22 3.22a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042L6.94 8 3.72 4.78a.75.75 0 0 1 0-1.06Z"></path>-</svg>- </button>- <div aria-atomic="true" role="alert" class="js-flash-alert">-- <div>{{ message }}</div>-- </div>- </div>-</div>- </template>-</div>---------- <div- class="application-main "- data-commit-hovercards-enabled- data-discussion-hovercards-enabled- data-issue-and-pr-hovercards-enabled- data-project-hovercards-enabled- >- <main>--<x-banner data-dismiss-scheme="none" data-view-component="true">- <div hidden="hidden" data-view-component="true" class="js-user-status-banner Banner flash Banner--full flash-full">- <div class="Banner-visual">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-info">- <path d="M0 8a8 8 0 1 1 16 0A8 8 0 0 1 0 8Zm8-6.5a6.5 6.5 0 1 0 0 13 6.5 6.5 0 0 0 0-13ZM6.5 7.75A.75.75 0 0 1 7.25 7h1a.75.75 0 0 1 .75.75v2.75h.25a.75.75 0 0 1 0 1.5h-2a.75.75 0 0 1 0-1.5h.25v-2h-.25a.75.75 0 0 1-.75-.75ZM8 6a1 1 0 1 1 0-2 1 1 0 0 1 0 2Z"></path>-</svg>- </div>- <div data-view-component="true" class="Banner-message">- <p class="Banner-title" data-target="x-banner.titleText">- <span class="js-user-status-banner-message"></span>-</p>-</div></div></x-banner>- <div- class="mt-4 position-sticky top-0 d-none d-md-block color-bg-default width-full border-bottom- color-border-muted"- style="z-index:3;"- data-turbo-frame="user-profile-frame"- >- <div class="container-xl px-3 px-md-4 px-lg-5">- <div data-view-component="true" class="Layout Layout--flowRow-until-md Layout--sidebarPosition-start Layout--sidebarPosition-flowRow-start">-- <div data-view-component="true" class="Layout-sidebar"> <div class="user-profile-sticky-bar">- <div class="user-profile-mini-vcard d-table">- <span class="user-profile-mini-avatar d-table-cell v-align-middle lh-condensed-ultra pr-2">- <img class="rounded-2 avatar-user" src="https://avatars.githubusercontent.com/u/8083459?s=64&v=4" width="32" height="32" alt="@ryanoasis" />- </span>- <span class="d-table-cell v-align-middle lh-condensed">- <strong>ryanoasis</strong>-- <span class="user-following-container">- <span class="follow d-block">- <a class="btn btn-sm mini-follow-button" data-hydro-click="{"event_type":"authentication.click","payload":{"location_in_page":"follow button","repository_id":null,"auth_type":"LOG_IN","originating_url":"https://github.com/ryanoasis","user_id":null}}" data-hydro-click-hmac="cb8153d566f692d20d213ac6dbd9a5ceed8a98e26b53980cd1ba988e254679e5" href="/login?return_to=https%3A%2F%2Fgithub.com%2Fryanoasis%2F">Follow</a>- </span>- </span>-- </span>- </div>- </div>-</div>- <div data-view-component="true" class="Layout-main"> <div class="UnderlineNav width-full box-shadow-none js-responsive-underlinenav overflow-md-x-hidden">- <nav class="UnderlineNav-body width-full p-responsive js-sidenav-container-pjax" aria-label="User profile">- <a aria-current="page" class="UnderlineNav-item js-responsive-underlinenav-item js-selected-navigation-item selected" data-hydro-click="{"event_type":"user_profile.click","payload":{"profile_user_id":8083459,"target":"TAB_OVERVIEW","user_id":null,"originating_url":"https://github.com/ryanoasis"}}" data-hydro-click-hmac="d3ff66bee709c9dc00d68add28f4ab108bbd2e3d38660b37fb1a60d5dd9f13f5" data-tab-item="overview" data-selected-links="overview /ryanoasis" href="/ryanoasis">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-book UnderlineNav-octicon hide-sm">- <path d="M0 1.75A.75.75 0 0 1 .75 1h4.253c1.227 0 2.317.59 3 1.501A3.743 3.743 0 0 1 11.006 1h4.245a.75.75 0 0 1 .75.75v10.5a.75.75 0 0 1-.75.75h-4.507a2.25 2.25 0 0 0-1.591.659l-.622.621a.75.75 0 0 1-1.06 0l-.622-.621A2.25 2.25 0 0 0 5.258 13H.75a.75.75 0 0 1-.75-.75Zm7.251 10.324.004-5.073-.002-2.253A2.25 2.25 0 0 0 5.003 2.5H1.5v9h3.757a3.75 3.75 0 0 1 1.994.574ZM8.755 4.75l-.004 7.322a3.752 3.752 0 0 1 1.992-.572H14.5v-9h-3.495a2.25 2.25 0 0 0-2.25 2.25Z"></path>-</svg>- Overview-</a>- <a class="UnderlineNav-item js-responsive-underlinenav-item js-selected-navigation-item" data-hydro-click="{"event_type":"user_profile.click","payload":{"profile_user_id":8083459,"target":"TAB_REPOSITORIES","user_id":null,"originating_url":"https://github.com/ryanoasis"}}" data-hydro-click-hmac="7233758002c793c89831f2c7650c7404529e397d95d86d8d96a85b90e707e14f" data-tab-item="repositories" data-selected-links="repositories /ryanoasis?tab=repositories" href="/ryanoasis?tab=repositories">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-repo UnderlineNav-octicon hide-sm">- <path d="M2 2.5A2.5 2.5 0 0 1 4.5 0h8.75a.75.75 0 0 1 .75.75v12.5a.75.75 0 0 1-.75.75h-2.5a.75.75 0 0 1 0-1.5h1.75v-2h-8a1 1 0 0 0-.714 1.7.75.75 0 1 1-1.072 1.05A2.495 2.495 0 0 1 2 11.5Zm10.5-1h-8a1 1 0 0 0-1 1v6.708A2.486 2.486 0 0 1 4.5 9h8ZM5 12.25a.25.25 0 0 1 .25-.25h3.5a.25.25 0 0 1 .25.25v3.25a.25.25 0 0 1-.4.2l-1.45-1.087a.249.249 0 0 0-.3 0L5.4 15.7a.25.25 0 0 1-.4-.2Z"></path>-</svg>- Repositories- <span title="151" data-view-component="true" class="Counter">151</span>-</a>- <a class="UnderlineNav-item js-responsive-underlinenav-item js-selected-navigation-item" data-hydro-click="{"event_type":"user_profile.click","payload":{"profile_user_id":8083459,"target":"TAB_PROJECTS","user_id":null,"originating_url":"https://github.com/ryanoasis"}}" data-hydro-click-hmac="a112e2d90bf20bd2778843f5ecbd0485108e720240257897a94632d97093fec0" data-tab-item="projects" data-selected-links="projects /ryanoasis?tab=projects" href="/ryanoasis?tab=projects">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-table UnderlineNav-octicon hide-sm">- <path d="M0 1.75C0 .784.784 0 1.75 0h12.5C15.216 0 16 .784 16 1.75v12.5A1.75 1.75 0 0 1 14.25 16H1.75A1.75 1.75 0 0 1 0 14.25ZM6.5 6.5v8h7.75a.25.25 0 0 0 .25-.25V6.5Zm8-1.5V1.75a.25.25 0 0 0-.25-.25H6.5V5Zm-13 1.5v7.75c0 .138.112.25.25.25H5v-8ZM5 5V1.5H1.75a.25.25 0 0 0-.25.25V5Z"></path>-</svg>- Projects- <span title="0" hidden="hidden" data-view-component="true" class="Counter">0</span>-</a>- <a class="UnderlineNav-item js-responsive-underlinenav-item js-selected-navigation-item" data-hydro-click="{"event_type":"user_profile.click","payload":{"profile_user_id":8083459,"target":"TAB_PACKAGES","user_id":null,"originating_url":"https://github.com/ryanoasis"}}" data-hydro-click-hmac="f1307e244d3481812867ad1ba376176f58b7807a030618813afca0ec6518427f" data-tab-item="packages" data-selected-links="packages /ryanoasis?tab=packages" href="/ryanoasis?tab=packages">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-package UnderlineNav-octicon hide-sm">- <path d="m8.878.392 5.25 3.045c.54.314.872.89.872 1.514v6.098a1.75 1.75 0 0 1-.872 1.514l-5.25 3.045a1.75 1.75 0 0 1-1.756 0l-5.25-3.045A1.75 1.75 0 0 1 1 11.049V4.951c0-.624.332-1.201.872-1.514L7.122.392a1.75 1.75 0 0 1 1.756 0ZM7.875 1.69l-4.63 2.685L8 7.133l4.755-2.758-4.63-2.685a.248.248 0 0 0-.25 0ZM2.5 5.677v5.372c0 .09.047.171.125.216l4.625 2.683V8.432Zm6.25 8.271 4.625-2.683a.25.25 0 0 0 .125-.216V5.677L8.75 8.432Z"></path>-</svg>- Packages- <span title="0" hidden="hidden" data-view-component="true" class="Counter">0</span>-</a>- <a class="UnderlineNav-item js-responsive-underlinenav-item js-selected-navigation-item" data-hydro-click="{"event_type":"user_profile.click","payload":{"profile_user_id":8083459,"target":"TAB_STARS","user_id":null,"originating_url":"https://github.com/ryanoasis"}}" data-hydro-click-hmac="99382a2b600e57c5c95d55b45416e95a1f772023fbe5183f226d8ffd6cd4913e" data-tab-item="stars" data-selected-links="stars /ryanoasis?tab=stars" href="/ryanoasis?tab=stars">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-star UnderlineNav-octicon hide-sm">- <path d="M8 .25a.75.75 0 0 1 .673.418l1.882 3.815 4.21.612a.75.75 0 0 1 .416 1.279l-3.046 2.97.719 4.192a.751.751 0 0 1-1.088.791L8 12.347l-3.766 1.98a.75.75 0 0 1-1.088-.79l.72-4.194L.818 6.374a.75.75 0 0 1 .416-1.28l4.21-.611L7.327.668A.75.75 0 0 1 8 .25Zm0 2.445L6.615 5.5a.75.75 0 0 1-.564.41l-3.097.45 2.24 2.184a.75.75 0 0 1 .216.664l-.528 3.084 2.769-1.456a.75.75 0 0 1 .698 0l2.77 1.456-.53-3.084a.75.75 0 0 1 .216-.664l2.24-2.183-3.096-.45a.75.75 0 0 1-.564-.41L8 2.694Z"></path>-</svg>- Stars- <span title="881" data-view-component="true" class="Counter">881</span>-</a>-</nav>--<div class="position-absolute pr-3 pr-md-4 pr-lg-5 right-0 js-responsive-underlinenav-overflow" style="visibility: hidden">- <details-toggle>- <details data-target="details-toggle.detailsTarget" data-view-component="true" class="details-overlay details-reset position-relative">- <summary role="button" data-target="details-toggle.summaryTarget" data-action="click:details-toggle#toggle" aria-expanded="false" data-view-component="true"> <div class="UnderlineNav-item mr-0 border-0">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-kebab-horizontal">- <path d="M8 9a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3ZM1.5 9a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3Zm13 0a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3Z"></path>-</svg>- <span class="sr-only">More</span>- </div>-</summary>- <div data-view-component="true"> <details-menu role="menu" class="dropdown-menu dropdown-menu-sw">- <ul >- <li data-menu-item="overview" hidden>- <a role="menuitem" class="js-selected-navigation-item selected dropdown-item" aria-current="page" data-selected-links=" /ryanoasis" href="/ryanoasis">Overview</a>- </li>- <li data-menu-item="repositories" hidden>- <a role="menuitem" class="js-selected-navigation-item dropdown-item" data-selected-links=" /ryanoasis?tab=repositories" href="/ryanoasis?tab=repositories">Repositories</a>- </li>- <li data-menu-item="projects" hidden>- <a role="menuitem" class="js-selected-navigation-item dropdown-item" data-selected-links=" /ryanoasis?tab=projects" href="/ryanoasis?tab=projects">Projects</a>- </li>- <li data-menu-item="packages" hidden>- <a role="menuitem" class="js-selected-navigation-item dropdown-item" data-selected-links=" /ryanoasis?tab=packages" href="/ryanoasis?tab=packages">Packages</a>- </li>- <li data-menu-item="stars" hidden>- <a role="menuitem" class="js-selected-navigation-item dropdown-item" data-selected-links=" /ryanoasis?tab=stars" href="/ryanoasis?tab=stars">Stars</a>- </li>- </ul>- </details-menu>-</div>-</details></details-toggle>-</div>-- </div>-</div>-</div> </div>- </div>--<div class="container-xl px-3 px-md-4 px-lg-5 ">- <div data-view-component="true" class="Layout Layout--flowRow-until-md Layout--sidebarPosition-start Layout--sidebarPosition-flowRow-start">-- <div data-view-component="true" class="Layout-sidebar"> <div- class="h-card mt-5 mt-md-n5"- data-acv-badge-hovercards-enabled- itemscope- itemtype="http://schema.org/Person"- >- <div class="user-profile-sticky-bar js-user-profile-sticky-bar d-none d-md-block">- <div class="user-profile-mini-vcard d-table">- <span class="user-profile-mini-avatar d-table-cell v-align-middle lh-condensed-ultra pr-2">- <img class="rounded-2 avatar-user" src="https://avatars.githubusercontent.com/u/8083459?s=64&v=4" width="32" height="32" alt="@ryanoasis" />- </span>- <span class="d-table-cell v-align-middle lh-condensed pr-2">- <div style="max-width: 180px;" data-view-component="true" class="css-truncate css-truncate-target expandable">- <strong>ryanoasis</strong>-</div> </span>- <span class="d-table-cell v-align-middle lh-condensed">-- <span class="user-following-container">- <span class="follow d-block">- <a class="btn mini-follow-button" data-hydro-click="{"event_type":"authentication.click","payload":{"location_in_page":"follow button","repository_id":null,"auth_type":"LOG_IN","originating_url":"https://github.com/ryanoasis","user_id":null}}" data-hydro-click-hmac="cb8153d566f692d20d213ac6dbd9a5ceed8a98e26b53980cd1ba988e254679e5" href="/login?return_to=https%3A%2F%2Fgithub.com%2Fryanoasis%2F">Follow</a>- </span>- </span>-- </span>- </div>- </div>-- <div class="js-profile-editable-replace">- <div class="clearfix d-flex d-md-block flex-items-center mb-4 mb-md-0">- <div- class="position-relative d-inline-block col-2 col-md-12 mr-3 mr-md-0 flex-shrink-0"- style="z-index:4;"- >- <a class="d-block" itemprop="image" href="https://avatars.githubusercontent.com/u/8083459?v=4"><img style="height:auto;" alt="View ryanoasis's full-sized avatar" src="https://avatars.githubusercontent.com/u/8083459?v=4" width="260" height="260" class="avatar avatar-user width-full border color-bg-default" /></a>-- <div class="user-status-container position-relative hide-sm hide-md">- <div class="- d-flex user-status-circle-badge-container- user-status-has-content">--<div class="d-flex flex-items-center flex-items-stretch">- <div- class="f6 d-flex flex-items-center p-2 width-full user-status-circle-badge lh-condensed"- data-team-hovercards-enabled- >- <div class="user-status-emoji-container flex-shrink-0 mr-2 d-flex flex-items-center flex-justify-center">- <div>💻</div>- </div>- <div class="user-status-message-wrapper f6 color-fg-default no-wrap " >- <div>🏗️ 🔣 🌐 🐚 </div>-- </div>- </div>-</div>-- </div>- </div>-- </div>-- <div- class="vcard-names-container float-left js-profile-editable-names col-12 py-3 js-toggle-stuck js-user-profile-sticky-fields"- >- <h1 class="vcard-names ">- <span class="p-name vcard-fullname d-block overflow-hidden" itemprop="name">- Ryan L McIntyre- </span>- <span class="p-nickname vcard-username d-block" itemprop="additionalName">- ryanoasis-- </span>- </h1>- </div>- </div>-- <div class="mt-2 user-status-container d-md-none">--<div class="d-flex flex-items-center flex-items-stretch">- <div- class="f6 d-flex flex-items-center p-2 width-full"- data-team-hovercards-enabled- >- <div class="user-status-emoji-container flex-shrink-0 mr-2 d-flex flex-items-center flex-justify-center">- <div>💻</div>- </div>- <div class="user-status-message-wrapper f6 color-fg-default ws-normal lh-condensed" >- <div>🏗️ 🔣 🌐 🐚 </div>-- </div>- </div>-</div>-- </div>--- <div class="d-flex flex-column">- <div class="flex-order-1 flex-md-order-none">- <div class="d-flex flex-lg-row flex-md-column">- <div class="flex-1 mb-0 mb-md-3">- <div class="js-toggle-stuck js-user-profile-follow-button pb-1 mb-n1"></div>-- <span class="user-following-container">- <span class="follow d-block">- <a class="btn btn-block" data-hydro-click="{"event_type":"authentication.click","payload":{"location_in_page":"follow button","repository_id":null,"auth_type":"LOG_IN","originating_url":"https://github.com/ryanoasis","user_id":null}}" data-hydro-click-hmac="cb8153d566f692d20d213ac6dbd9a5ceed8a98e26b53980cd1ba988e254679e5" href="/login?return_to=https%3A%2F%2Fgithub.com%2Fryanoasis%2F">Follow</a>- </span>- </span>-- </div>- <div class="flex-1 ml-lg-2 ml-md-0 ml-2 mb-0 mb-md-3">- <a id="sponsor-profile-button" href="/sponsors/ryanoasis" aria-label="Sponsor @ryanoasis" data-hydro-click="{"event_type":"sponsors.button_click","payload":{"button":"PROFILE_SPONSOR","sponsorable_login":"ryanoasis","originating_url":"https://github.com/ryanoasis","user_id":null}}" data-hydro-click-hmac="f2ab80012aeb26a62bf49eeddabe5e7b76e1afb3389dec9e088c17bcac1cc7a4" data-view-component="true" class="Button--secondary Button--medium Button Button--fullWidth"> <span class="Button-content">- <span class="Button-label"><svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-heart icon-sponsor mr-1 v-align-middle color-fg-sponsors anim-pulse-in">- <path d="m8 14.25.345.666a.75.75 0 0 1-.69 0l-.008-.004-.018-.01a7.152 7.152 0 0 1-.31-.17 22.055 22.055 0 0 1-3.434-2.414C2.045 10.731 0 8.35 0 5.5 0 2.836 2.086 1 4.25 1 5.797 1 7.153 1.802 8 3.02 8.847 1.802 10.203 1 11.75 1 13.914 1 16 2.836 16 5.5c0 2.85-2.045 5.231-3.885 6.818a22.066 22.066 0 0 1-3.744 2.584l-.018.01-.006.003h-.002ZM4.25 2.5c-1.336 0-2.75 1.164-2.75 3 0 2.15 1.58 4.144 3.365 5.682A20.58 20.58 0 0 0 8 13.393a20.58 20.58 0 0 0 3.135-2.211C12.92 9.644 14.5 7.65 14.5 5.5c0-1.836-1.414-3-2.75-3-1.373 0-2.609.986-3.029 2.456a.749.749 0 0 1-1.442 0C6.859 3.486 5.623 2.5 4.25 2.5Z"></path>-</svg>- <span class="v-align-middle" >- Sponsor- </span></span>- </span>-</a>-- </div>- </div>--- </div>---<div class="js-profile-editable-area d-flex flex-column d-md-block">- <div class="p-note user-profile-bio mb-3 js-user-profile-bio f4" data-bio-text=" Full Stack Application Developer ┋ Focused on UI - JavaScript - OSS - Vim ┋ Creator of Nerd Fonts & VimDevIcons "- ><div> Full Stack Application Developer ┋ Focused on UI - JavaScript - OSS - Vim ┋ Creator of Nerd Fonts & VimDevIcons </div></div>--- <div class="flex-order-1 flex-md-order-none mt-2 mt-md-0">- <div class="mb-3">- <a class="Link--secondary no-underline no-wrap" href="https://github.com/ryanoasis?tab=followers">- <svg text="muted" aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-people">- <path d="M2 5.5a3.5 3.5 0 1 1 5.898 2.549 5.508 5.508 0 0 1 3.034 4.084.75.75 0 1 1-1.482.235 4 4 0 0 0-7.9 0 .75.75 0 0 1-1.482-.236A5.507 5.507 0 0 1 3.102 8.05 3.493 3.493 0 0 1 2 5.5ZM11 4a3.001 3.001 0 0 1 2.22 5.018 5.01 5.01 0 0 1 2.56 3.012.749.749 0 0 1-.885.954.752.752 0 0 1-.549-.514 3.507 3.507 0 0 0-2.522-2.372.75.75 0 0 1-.574-.73v-.352a.75.75 0 0 1 .416-.672A1.5 1.5 0 0 0 11 5.5.75.75 0 0 1 11 4Zm-5.5-.5a2 2 0 1 0-.001 3.999A2 2 0 0 0 5.5 3.5Z"></path>-</svg>- <span class="text-bold color-fg-default">1.3k</span>- followers-</a> · <a class="Link--secondary no-underline no-wrap" href="https://github.com/ryanoasis?tab=following">- <span class="text-bold color-fg-default">21</span>- following-</a> </div>- </div>-- <ul class="vcard-details">-- <li class="vcard-detail pt-1 hide-sm hide-md" itemprop="homeLocation" show_title="false" aria-label="Home location: Seattle, WA, USA"><svg class="octicon octicon-location" viewBox="0 0 16 16" version="1.1" width="16" height="16" aria-hidden="true"><path d="m12.596 11.596-3.535 3.536a1.5 1.5 0 0 1-2.122 0l-3.535-3.536a6.5 6.5 0 1 1 9.192-9.193 6.5 6.5 0 0 1 0 9.193Zm-1.06-8.132v-.001a5 5 0 1 0-7.072 7.072L8 14.07l3.536-3.534a5 5 0 0 0 0-7.072ZM8 9a2 2 0 1 1-.001-3.999A2 2 0 0 1 8 9Z"></path></svg>- <span class="p-label">Seattle, WA, USA</span>-</li>--- <li itemprop="url" data-test-selector="profile-website-url" class="vcard-detail pt-1 "><svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-link">- <path d="m7.775 3.275 1.25-1.25a3.5 3.5 0 1 1 4.95 4.95l-2.5 2.5a3.5 3.5 0 0 1-4.95 0 .751.751 0 0 1 .018-1.042.751.751 0 0 1 1.042-.018 1.998 1.998 0 0 0 2.83 0l2.5-2.5a2.002 2.002 0 0 0-2.83-2.83l-1.25 1.25a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042Zm-4.69 9.64a1.998 1.998 0 0 0 2.83 0l1.25-1.25a.751.751 0 0 1 1.042.018.751.751 0 0 1 .018 1.042l-1.25 1.25a3.5 3.5 0 1 1-4.95-4.95l2.5-2.5a3.5 3.5 0 0 1 4.95 0 .751.751 0 0 1-.018 1.042.751.751 0 0 1-1.042.018 1.998 1.998 0 0 0-2.83 0l-2.5 2.5a1.998 1.998 0 0 0 0 2.83Z"></path>-</svg>- <a rel="nofollow me" class="Link--primary wb-break-all" href="https://RyanLMcIntyre.com">https://RyanLMcIntyre.com</a>-</li>--- </ul>-</div>-- </div>-- <div >- <div class="border-top color-border-muted pt-3 mt-3 clearfix hide-sm hide-md" >- <h2 class="h4 d-flex flex-items-start mb-2">Sponsors</h2>-- <div class="d-flex flex-wrap">- <div class="d-flex mb-1 mr-1" >- <a class="d-inline-block" data-hovercard-type="user" data-hovercard-url="/users/gshpychka/hovercard" data-octo-click="hovercard-link-click" data-octo-dimensions="link_type:self" href="/gshpychka"><img class="avatar avatar-user" src="https://avatars.githubusercontent.com/u/23005347?s=70&v=4" width="35" height="35" alt="@gshpychka" /></a>-</div>-- <div class="d-flex mb-1 mr-1" >- <a class="d-inline-block" data-hovercard-type="user" data-hovercard-url="/users/InfoSec812/hovercard" data-octo-click="hovercard-link-click" data-octo-dimensions="link_type:self" href="/InfoSec812"><img class="avatar avatar-user" src="https://avatars.githubusercontent.com/u/99691?s=70&v=4" width="35" height="35" alt="@InfoSec812" /></a>-</div>--- </div>- </div>--</div>-- <div class="border-top color-border-muted pt-3 mt-3 d-none d-md-block"><h2 class="h4 mb-2"><a href="/ryanoasis?tab=achievements" class="Link--primary mb-2">Achievements</a></h2><div class="d-flex flex-wrap"><a href="/ryanoasis?achievement=pair-extraordinaire&tab=achievements" class="position-relative"><img src="https://github.githubassets.com/assets/pair-extraordinaire-default-579438a20e01.png" data-hovercard-type="achievement" data-hovercard-url="/users/ryanoasis/achievements/pair-extraordinaire/detail?hovercard=1" width="64" alt="Achievement: Pair Extraordinaire" data-view-component="true" class="achievement-badge-sidebar" /><span data-view-component="true" class="Label achievement-tier-label achievement-tier-label--silver text-small text-bold color-shadow-medium px-2 py-0 mb-1 position-absolute right-0 bottom-0">x3</span></a><a href="/ryanoasis?achievement=pull-shark&tab=achievements" class="position-relative"><img src="https://github.githubassets.com/assets/pull-shark-default-498c279a747d.png" data-hovercard-type="achievement" data-hovercard-url="/users/ryanoasis/achievements/pull-shark/detail?hovercard=1" width="64" alt="Achievement: Pull Shark" data-view-component="true" class="achievement-badge-sidebar" /><span data-view-component="true" class="Label achievement-tier-label achievement-tier-label--silver text-small text-bold color-shadow-medium px-2 py-0 mb-1 position-absolute right-0 bottom-0">x3</span></a><a href="/ryanoasis?achievement=arctic-code-vault-contributor&tab=achievements" class="position-relative"><img src="https://github.githubassets.com/assets/arctic-code-vault-contributor-default-df8d74122a06.png" data-hovercard-type="achievement" data-hovercard-url="/users/ryanoasis/achievements/arctic-code-vault-contributor/detail?hovercard=1" width="64" alt="Achievement: Arctic Code Vault Contributor" data-view-component="true" class="achievement-badge-sidebar" /></a><a href="/ryanoasis?achievement=starstruck&tab=achievements" class="position-relative"><img src="https://github.githubassets.com/assets/starstruck-default--light-a594e2a027e0.png" data-hovercard-type="achievement" data-hovercard-url="/users/ryanoasis/achievements/starstruck/detail?hovercard=1" width="64" alt="Achievement: Starstruck" data-view-component="true" class="achievement-badge-sidebar" /><span data-view-component="true" class="Label achievement-tier-label achievement-tier-label--gold text-small text-bold color-shadow-medium px-2 py-0 mb-1 position-absolute right-0 bottom-0">x4</span></a></div></div><div class="border-top color-border-muted pt-3 mt-3 d-md-none d-block"><h2 class="h4 mb-2"><a href="/ryanoasis?tab=achievements" class="Link--primary mb-2">Achievements</a></h2><div class="d-flex flex-wrap"><a href="/ryanoasis?achievement=pair-extraordinaire&tab=achievements" class="position-relative"><img src="https://github.githubassets.com/assets/pair-extraordinaire-default-579438a20e01.png" data-hovercard-type="achievement" data-hovercard-url="/users/ryanoasis/achievements/pair-extraordinaire/detail?hovercard=1" width="64" alt="Achievement: Pair Extraordinaire" data-view-component="true" class="achievement-badge-sidebar" /><span data-view-component="true" class="Label achievement-tier-label achievement-tier-label--silver text-small text-bold color-shadow-medium px-2 py-0 mb-1 position-absolute right-0 bottom-0">x3</span></a><a href="/ryanoasis?achievement=pull-shark&tab=achievements" class="position-relative"><img src="https://github.githubassets.com/assets/pull-shark-default-498c279a747d.png" data-hovercard-type="achievement" data-hovercard-url="/users/ryanoasis/achievements/pull-shark/detail?hovercard=1" width="64" alt="Achievement: Pull Shark" data-view-component="true" class="achievement-badge-sidebar" /><span data-view-component="true" class="Label achievement-tier-label achievement-tier-label--silver text-small text-bold color-shadow-medium px-2 py-0 mb-1 position-absolute right-0 bottom-0">x3</span></a><a href="/ryanoasis?achievement=arctic-code-vault-contributor&tab=achievements" class="position-relative"><img src="https://github.githubassets.com/assets/arctic-code-vault-contributor-default-df8d74122a06.png" data-hovercard-type="achievement" data-hovercard-url="/users/ryanoasis/achievements/arctic-code-vault-contributor/detail?hovercard=1" width="64" alt="Achievement: Arctic Code Vault Contributor" data-view-component="true" class="achievement-badge-sidebar" /></a><a href="/ryanoasis?achievement=starstruck&tab=achievements" class="position-relative"><img src="https://github.githubassets.com/assets/starstruck-default--light-a594e2a027e0.png" data-hovercard-type="achievement" data-hovercard-url="/users/ryanoasis/achievements/starstruck/detail?hovercard=1" width="64" alt="Achievement: Starstruck" data-view-component="true" class="achievement-badge-sidebar" /><span data-view-component="true" class="Label achievement-tier-label achievement-tier-label--gold text-small text-bold color-shadow-medium px-2 py-0 mb-1 position-absolute right-0 bottom-0">x4</span></a></div></div>-- <div class="border-top color-border-muted pt-3 mt-3 clearfix hide-sm hide-md">- <h2 class="mb-2 h4" >Organizations</h2>-- <a aria-label="EpicGames" itemprop="follows" class="avatar-group-item" data-hovercard-type="organization" data-hovercard-url="/orgs/EpicGames/hovercard" data-octo-click="hovercard-link-click" data-octo-dimensions="link_type:self" data-hydro-click="{"event_type":"user_profile.click","payload":{"profile_user_id":8083459,"target":"MEMBER_ORGANIZATION_AVATAR","user_id":null,"originating_url":"https://github.com/ryanoasis"}}" data-hydro-click-hmac="932da2be8188ba81a9a622885b56e194f548e03ab2a7d5b6d704035a62ac9b13" href="/EpicGames">- <img src="https://avatars.githubusercontent.com/u/6615685?s=64&v=4" alt="@EpicGames" size="32" height="32" width="32" data-view-component="true" class="avatar" />-</a> <a aria-label="VundleVim" itemprop="follows" class="avatar-group-item" data-hovercard-type="organization" data-hovercard-url="/orgs/VundleVim/hovercard" data-octo-click="hovercard-link-click" data-octo-dimensions="link_type:self" data-hydro-click="{"event_type":"user_profile.click","payload":{"profile_user_id":8083459,"target":"MEMBER_ORGANIZATION_AVATAR","user_id":null,"originating_url":"https://github.com/ryanoasis"}}" data-hydro-click-hmac="932da2be8188ba81a9a622885b56e194f548e03ab2a7d5b6d704035a62ac9b13" href="/VundleVim">- <img src="https://avatars.githubusercontent.com/u/12930284?s=64&v=4" alt="@VundleVim" size="32" height="32" width="32" data-view-component="true" class="avatar" />-</a> <a aria-label="NerdFonts" itemprop="follows" class="avatar-group-item" data-hovercard-type="organization" data-hovercard-url="/orgs/NerdFonts/hovercard" data-octo-click="hovercard-link-click" data-octo-dimensions="link_type:self" data-hydro-click="{"event_type":"user_profile.click","payload":{"profile_user_id":8083459,"target":"MEMBER_ORGANIZATION_AVATAR","user_id":null,"originating_url":"https://github.com/ryanoasis"}}" data-hydro-click-hmac="932da2be8188ba81a9a622885b56e194f548e03ab2a7d5b6d704035a62ac9b13" href="/NerdFonts">- <img src="https://avatars.githubusercontent.com/u/13179460?s=64&v=4" alt="@NerdFonts" size="32" height="32" width="32" data-view-component="true" class="avatar" />-</a> <a aria-label="Powerlevel9k" itemprop="follows" class="avatar-group-item" data-hovercard-type="organization" data-hovercard-url="/orgs/Powerlevel9k/hovercard" data-octo-click="hovercard-link-click" data-octo-dimensions="link_type:self" data-hydro-click="{"event_type":"user_profile.click","payload":{"profile_user_id":8083459,"target":"MEMBER_ORGANIZATION_AVATAR","user_id":null,"originating_url":"https://github.com/ryanoasis"}}" data-hydro-click-hmac="932da2be8188ba81a9a622885b56e194f548e03ab2a7d5b6d704035a62ac9b13" href="/Powerlevel9k">- <img src="https://avatars.githubusercontent.com/u/26906588?s=64&v=4" alt="@Powerlevel9k" size="32" height="32" width="32" data-view-component="true" class="avatar" />-</a></div>-- <button id="dialog-show-dialog-6065dbf4-a869-462a-a905-050c270cd8cd" data-show-dialog-id="dialog-6065dbf4-a869-462a-a905-050c270cd8cd" type="button" data-view-component="true" class="Button--link Button--medium Button color-fg-muted"> <span class="Button-content">- <span class="Button-label">Block or Report</span>- </span>-</button>--<dialog-helper>- <dialog variant="narrow" id="dialog-6065dbf4-a869-462a-a905-050c270cd8cd" aria-modal="true" aria-labelledby="dialog-6065dbf4-a869-462a-a905-050c270cd8cd-title" aria-describedby="dialog-6065dbf4-a869-462a-a905-050c270cd8cd-description" data-view-component="true" class="Overlay Overlay-whenNarrow Overlay--size-medium-portrait Overlay--motion-scaleFade Overlay--disableScroll">- <div data-view-component="true" class="Overlay-header">- <div class="Overlay-headerContentWrap">- <div class="Overlay-titleWrap">- <h1 class="Overlay-title " id="dialog-6065dbf4-a869-462a-a905-050c270cd8cd-title">- Block or report ryanoasis- </h1>-- </div>- <div class="Overlay-actionWrap">- <button data-close-dialog-id="dialog-6065dbf4-a869-462a-a905-050c270cd8cd" aria-label="Close" aria-label="Close" type="button" data-view-component="true" class="close-button Overlay-closeButton"><svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-x">- <path d="M3.72 3.72a.75.75 0 0 1 1.06 0L8 6.94l3.22-3.22a.749.749 0 0 1 1.275.326.749.749 0 0 1-.215.734L9.06 8l3.22 3.22a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215L8 9.06l-3.22 3.22a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042L6.94 8 3.72 4.78a.75.75 0 0 1 0-1.06Z"></path>-</svg></button>- </div>- </div>--</div>- <scrollable-region data-labelled-by="dialog-6065dbf4-a869-462a-a905-050c270cd8cd-title">- <div data-view-component="true" class="Overlay-body"> <div class="border-bottom">- <!-- '"` --><!-- </textarea></xmp> --></option></form><form class="mb-3" data-turbo="false" action="/settings/blocked_users" accept-charset="UTF-8" method="post"><input type="hidden" name="authenticity_token" value="xsIQXYpJrweKnh0DyJr2ZTYTREJbNs_olee6z4y3MXeh74Lzhs8HFlMA7rD_ySJX2i4iljuGNza3-RChI8UWIw" autocomplete="off" />- <input type="hidden" name="login" value="ryanoasis">- <input type="hidden" name="return_to" value="/ryanoasis">-- <strong>Block user</strong>- <p>- Prevent this user from interacting with your repositories and sending you notifications.- Learn more about <a class="Link--inTextBlock" href="https://docs.github.com/articles/blocking-a-user-from-your-personal-account">blocking users</a>.- </p>------ <p class="text-small color-fg-muted">- You must be logged in to block users.- </p>-- <div class="mb-2">- <div class="FormControl width-full FormControl--fullWidth">- <label for="new-block-note-from-sidebar" class="FormControl-label">- Add an optional note-</label>- <div class="FormControl-input-wrap">- <textarea id="new-block-note-from-sidebar" data-test-selector="ignored_user_note_text_field" data-character-limit="250" style="resize: vertical" aria-describedby="validation-6d725507-d975-4104-832a-31c6f9ad1f04 caption-6d725507-d975-4104-832a-31c6f9ad1f04" class="form-control FormControl-input FormControl-textarea js-ignored-user-note-field" name="note">-</textarea>-</div>- <div class="FormControl-inlineValidation" id="validation-6d725507-d975-4104-832a-31c6f9ad1f04" hidden="hidden">- <span class="FormControl-inlineValidation--visual" data-target="" hidden><svg aria-hidden="true" height="12" viewBox="0 0 12 12" version="1.1" width="12" data-view-component="true" class="octicon octicon-check-circle-fill">- <path d="M6 0a6 6 0 1 1 0 12A6 6 0 0 1 6 0Zm-.705 8.737L9.63 4.403 8.392 3.166 5.295 6.263l-1.7-1.702L2.356 5.8l2.938 2.938Z"></path>-</svg></span>- <span class=" FormControl-inlineValidation--visual" data-target=""><svg aria-hidden="true" height="12" viewBox="0 0 12 12" version="1.1" width="12" data-view-component="true" class="octicon octicon-alert-fill">- <path d="M4.855.708c.5-.896 1.79-.896 2.29 0l4.675 8.351a1.312 1.312 0 0 1-1.146 1.954H1.33A1.313 1.313 0 0 1 .183 9.058ZM7 7V3H5v4Zm-1 3a1 1 0 1 0 0-2 1 1 0 0 0 0 2Z"></path>-</svg></span>- <span></span>-</div>- <span class="FormControl-caption" id="caption-6d725507-d975-4104-832a-31c6f9ad1f04">Maximum 250 characters. Please don't include any personal information such as legal names or email addresses. Markdown supported. This note will be visible to only you.</span>--</div>-<span class="sr-only" id="ignored-user-character-count-sr" aria-live="polite" aria-atomic="true"></span>-- </div>-- <button- type="submit"- class="btn btn-danger"- disabled- >- Block user- </button>-</form> </div>- <div class="mt-3">- <strong>Report abuse</strong>- <p>- Contact GitHub support about this user’s behavior.- Learn more about <a class="Link--inTextBlock" href="https://docs.github.com/articles/reporting-abuse-or-spam">reporting abuse</a>.- </p>- <a href="/contact/report-abuse?report=ryanoasis+%28user%29" class="btn btn-danger">Report abuse</a>- </div>-</div>- </scrollable-region>--</dialog></dialog-helper>--</div>-- </div>-</div>- <div data-view-component="true" class="Layout-main"> <div- class="UnderlineNav user-profile-nav d-block d-md-none position-sticky top-0 pl-3 ml-n3- mr-n3 pr-3 color-bg-default"- style="z-index:3;"- data-turbo-frame="user-profile-frame"- >- <nav class="UnderlineNav-body width-full p-responsive js-sidenav-container-pjax" aria-label="User profile">- <a aria-current="page" class="UnderlineNav-item js-responsive-underlinenav-item js-selected-navigation-item selected" data-hydro-click="{"event_type":"user_profile.click","payload":{"profile_user_id":8083459,"target":"TAB_OVERVIEW","user_id":null,"originating_url":"https://github.com/ryanoasis"}}" data-hydro-click-hmac="d3ff66bee709c9dc00d68add28f4ab108bbd2e3d38660b37fb1a60d5dd9f13f5" data-tab-item="overview" data-selected-links="overview /ryanoasis" href="/ryanoasis">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-book UnderlineNav-octicon hide-sm">- <path d="M0 1.75A.75.75 0 0 1 .75 1h4.253c1.227 0 2.317.59 3 1.501A3.743 3.743 0 0 1 11.006 1h4.245a.75.75 0 0 1 .75.75v10.5a.75.75 0 0 1-.75.75h-4.507a2.25 2.25 0 0 0-1.591.659l-.622.621a.75.75 0 0 1-1.06 0l-.622-.621A2.25 2.25 0 0 0 5.258 13H.75a.75.75 0 0 1-.75-.75Zm7.251 10.324.004-5.073-.002-2.253A2.25 2.25 0 0 0 5.003 2.5H1.5v9h3.757a3.75 3.75 0 0 1 1.994.574ZM8.755 4.75l-.004 7.322a3.752 3.752 0 0 1 1.992-.572H14.5v-9h-3.495a2.25 2.25 0 0 0-2.25 2.25Z"></path>-</svg>- Overview-</a>- <a class="UnderlineNav-item js-responsive-underlinenav-item js-selected-navigation-item" data-hydro-click="{"event_type":"user_profile.click","payload":{"profile_user_id":8083459,"target":"TAB_REPOSITORIES","user_id":null,"originating_url":"https://github.com/ryanoasis"}}" data-hydro-click-hmac="7233758002c793c89831f2c7650c7404529e397d95d86d8d96a85b90e707e14f" data-tab-item="repositories" data-selected-links="repositories /ryanoasis?tab=repositories" href="/ryanoasis?tab=repositories">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-repo UnderlineNav-octicon hide-sm">- <path d="M2 2.5A2.5 2.5 0 0 1 4.5 0h8.75a.75.75 0 0 1 .75.75v12.5a.75.75 0 0 1-.75.75h-2.5a.75.75 0 0 1 0-1.5h1.75v-2h-8a1 1 0 0 0-.714 1.7.75.75 0 1 1-1.072 1.05A2.495 2.495 0 0 1 2 11.5Zm10.5-1h-8a1 1 0 0 0-1 1v6.708A2.486 2.486 0 0 1 4.5 9h8ZM5 12.25a.25.25 0 0 1 .25-.25h3.5a.25.25 0 0 1 .25.25v3.25a.25.25 0 0 1-.4.2l-1.45-1.087a.249.249 0 0 0-.3 0L5.4 15.7a.25.25 0 0 1-.4-.2Z"></path>-</svg>- Repositories- <span title="151" data-view-component="true" class="Counter">151</span>-</a>- <a class="UnderlineNav-item js-responsive-underlinenav-item js-selected-navigation-item" data-hydro-click="{"event_type":"user_profile.click","payload":{"profile_user_id":8083459,"target":"TAB_PROJECTS","user_id":null,"originating_url":"https://github.com/ryanoasis"}}" data-hydro-click-hmac="a112e2d90bf20bd2778843f5ecbd0485108e720240257897a94632d97093fec0" data-tab-item="projects" data-selected-links="projects /ryanoasis?tab=projects" href="/ryanoasis?tab=projects">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-table UnderlineNav-octicon hide-sm">- <path d="M0 1.75C0 .784.784 0 1.75 0h12.5C15.216 0 16 .784 16 1.75v12.5A1.75 1.75 0 0 1 14.25 16H1.75A1.75 1.75 0 0 1 0 14.25ZM6.5 6.5v8h7.75a.25.25 0 0 0 .25-.25V6.5Zm8-1.5V1.75a.25.25 0 0 0-.25-.25H6.5V5Zm-13 1.5v7.75c0 .138.112.25.25.25H5v-8ZM5 5V1.5H1.75a.25.25 0 0 0-.25.25V5Z"></path>-</svg>- Projects- <span title="0" hidden="hidden" data-view-component="true" class="Counter">0</span>-</a>- <a class="UnderlineNav-item js-responsive-underlinenav-item js-selected-navigation-item" data-hydro-click="{"event_type":"user_profile.click","payload":{"profile_user_id":8083459,"target":"TAB_PACKAGES","user_id":null,"originating_url":"https://github.com/ryanoasis"}}" data-hydro-click-hmac="f1307e244d3481812867ad1ba376176f58b7807a030618813afca0ec6518427f" data-tab-item="packages" data-selected-links="packages /ryanoasis?tab=packages" href="/ryanoasis?tab=packages">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-package UnderlineNav-octicon hide-sm">- <path d="m8.878.392 5.25 3.045c.54.314.872.89.872 1.514v6.098a1.75 1.75 0 0 1-.872 1.514l-5.25 3.045a1.75 1.75 0 0 1-1.756 0l-5.25-3.045A1.75 1.75 0 0 1 1 11.049V4.951c0-.624.332-1.201.872-1.514L7.122.392a1.75 1.75 0 0 1 1.756 0ZM7.875 1.69l-4.63 2.685L8 7.133l4.755-2.758-4.63-2.685a.248.248 0 0 0-.25 0ZM2.5 5.677v5.372c0 .09.047.171.125.216l4.625 2.683V8.432Zm6.25 8.271 4.625-2.683a.25.25 0 0 0 .125-.216V5.677L8.75 8.432Z"></path>-</svg>- Packages- <span title="0" hidden="hidden" data-view-component="true" class="Counter">0</span>-</a>- <a class="UnderlineNav-item js-responsive-underlinenav-item js-selected-navigation-item" data-hydro-click="{"event_type":"user_profile.click","payload":{"profile_user_id":8083459,"target":"TAB_STARS","user_id":null,"originating_url":"https://github.com/ryanoasis"}}" data-hydro-click-hmac="99382a2b600e57c5c95d55b45416e95a1f772023fbe5183f226d8ffd6cd4913e" data-tab-item="stars" data-selected-links="stars /ryanoasis?tab=stars" href="/ryanoasis?tab=stars">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-star UnderlineNav-octicon hide-sm">- <path d="M8 .25a.75.75 0 0 1 .673.418l1.882 3.815 4.21.612a.75.75 0 0 1 .416 1.279l-3.046 2.97.719 4.192a.751.751 0 0 1-1.088.791L8 12.347l-3.766 1.98a.75.75 0 0 1-1.088-.79l.72-4.194L.818 6.374a.75.75 0 0 1 .416-1.28l4.21-.611L7.327.668A.75.75 0 0 1 8 .25Zm0 2.445L6.615 5.5a.75.75 0 0 1-.564.41l-3.097.45 2.24 2.184a.75.75 0 0 1 .216.664l-.528 3.084 2.769-1.456a.75.75 0 0 1 .698 0l2.77 1.456-.53-3.084a.75.75 0 0 1 .216-.664l2.24-2.183-3.096-.45a.75.75 0 0 1-.564-.41L8 2.694Z"></path>-</svg>- Stars- <span title="881" data-view-component="true" class="Counter">881</span>-</a>-</nav>--<div class="position-absolute pr-3 pr-md-4 pr-lg-5 right-0 js-responsive-underlinenav-overflow" style="visibility: hidden">- <details-toggle>- <details data-target="details-toggle.detailsTarget" data-view-component="true" class="details-overlay details-reset position-relative">- <summary role="button" data-target="details-toggle.summaryTarget" data-action="click:details-toggle#toggle" aria-expanded="false" data-view-component="true"> <div class="UnderlineNav-item mr-0 border-0">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-kebab-horizontal">- <path d="M8 9a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3ZM1.5 9a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3Zm13 0a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3Z"></path>-</svg>- <span class="sr-only">More</span>- </div>-</summary>- <div data-view-component="true"> <details-menu role="menu" class="dropdown-menu dropdown-menu-sw">- <ul >- <li data-menu-item="overview" hidden>- <a role="menuitem" class="js-selected-navigation-item selected dropdown-item" aria-current="page" data-selected-links=" /ryanoasis" href="/ryanoasis">Overview</a>- </li>- <li data-menu-item="repositories" hidden>- <a role="menuitem" class="js-selected-navigation-item dropdown-item" data-selected-links=" /ryanoasis?tab=repositories" href="/ryanoasis?tab=repositories">Repositories</a>- </li>- <li data-menu-item="projects" hidden>- <a role="menuitem" class="js-selected-navigation-item dropdown-item" data-selected-links=" /ryanoasis?tab=projects" href="/ryanoasis?tab=projects">Projects</a>- </li>- <li data-menu-item="packages" hidden>- <a role="menuitem" class="js-selected-navigation-item dropdown-item" data-selected-links=" /ryanoasis?tab=packages" href="/ryanoasis?tab=packages">Packages</a>- </li>- <li data-menu-item="stars" hidden>- <a role="menuitem" class="js-selected-navigation-item dropdown-item" data-selected-links=" /ryanoasis?tab=stars" href="/ryanoasis?tab=stars">Stars</a>- </li>- </ul>- </details-menu>-</div>-</details></details-toggle>-</div>-- </div>- <turbo-frame id="user-profile-frame" data-turbo-action="advance">-- <div class="position-relative" data-hpc>--------<div class="mt-4">- <div class="js-pinned-items-reorder-container">- <h2 class="f4 mb-2 text-normal">- Popular repositories- <span data-view-component="true">- <svg style="box-sizing: content-box; color: var(--color-icon-primary);" width="16" height="16" viewBox="0 0 16 16" fill="none" aria-hidden="true" data-view-component="true" class="spinner pinned-items-spinner js-pinned-items-spinner v-align-text-bottom ml-1 anim-rotate">- <circle cx="8" cy="8" r="7" stroke="currentColor" stroke-opacity="0.25" stroke-width="2" vector-effect="non-scaling-stroke" fill="none" />- <path d="M15 8a7.002 7.002 0 00-7-7" stroke="currentColor" stroke-width="2" stroke-linecap="round" vector-effect="non-scaling-stroke" />-</svg> <span class="sr-only">Loading</span>-</span>- <span- class="ml-2 color-fg-muted f6 js-pinned-items-reorder-message"- role="status"- aria-live="polite"- data-error-text="Something went wrong."- data-success-text="Order updated."- ></span>- </h2>-- <ol class="d-flex flex-wrap list-style-none gutter-condensed mb-4">-- <li- class="mb-3 d-flex flex-content-stretch col-12 col-md-6 col-lg-6"- >- <div- class="Box pinned-item-list-item d-flex p-3 width-full public source"- >- <div class="pinned-item-list-item-content">- <div class="d-flex v-align-middle mr-2">- <span data-view-component="true" class="position-relative"><a id="27574418" href="/ryanoasis/nerd-fonts" data-view-component="true" class="min-width-0 Link text-bold flex-auto wb-break-all"><span class="repo" >- nerd-fonts- </span></a> <tool-tip id="tooltip-f4be2554-9fff-444b-838d-dc220cdf944a" for="27574418" popover="manual" data-direction="n" data-type="description" data-view-component="true" class="sr-only position-absolute">nerd-fonts</tool-tip></span> <span class="flex-auto text-right">- <span></span><span class="Label Label--secondary v-align-middle ">Public</span>- </span>- </div>--- <p class="pinned-item-desc color-fg-muted text-small d-block mt-2 mb-3">- Iconic font aggregator, collection, & patcher. 3,600+ icons, 50+ patched fonts: Hack, Source Code Pro, more. Glyph collections: Font Awesome, Material Design Icons, Octicons, & more- </p>-- <p class="mb-0 f6 color-fg-muted">- <span class="d-inline-block mr-3">- <span class="repo-language-color" style="background-color: #663399"></span>- <span itemprop="programmingLanguage">CSS</span>-</span>-- <a- href="/ryanoasis/nerd-fonts/stargazers"- class="pinned-item-meta Link--muted"- >- <svg aria-label="stars" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-star">- <path d="M8 .25a.75.75 0 0 1 .673.418l1.882 3.815 4.21.612a.75.75 0 0 1 .416 1.279l-3.046 2.97.719 4.192a.751.751 0 0 1-1.088.791L8 12.347l-3.766 1.98a.75.75 0 0 1-1.088-.79l.72-4.194L.818 6.374a.75.75 0 0 1 .416-1.28l4.21-.611L7.327.668A.75.75 0 0 1 8 .25Zm0 2.445L6.615 5.5a.75.75 0 0 1-.564.41l-3.097.45 2.24 2.184a.75.75 0 0 1 .216.664l-.528 3.084 2.769-1.456a.75.75 0 0 1 .698 0l2.77 1.456-.53-3.084a.75.75 0 0 1 .216-.664l2.24-2.183-3.096-.45a.75.75 0 0 1-.564-.41L8 2.694Z"></path>-</svg>- 60.4k- </a>- <a- href="/ryanoasis/nerd-fonts/forks"- class="pinned-item-meta Link--muted"- >- <svg aria-label="forks" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-repo-forked">- <path d="M5 5.372v.878c0 .414.336.75.75.75h4.5a.75.75 0 0 0 .75-.75v-.878a2.25 2.25 0 1 1 1.5 0v.878a2.25 2.25 0 0 1-2.25 2.25h-1.5v2.128a2.251 2.251 0 1 1-1.5 0V8.5h-1.5A2.25 2.25 0 0 1 3.5 6.25v-.878a2.25 2.25 0 1 1 1.5 0ZM5 3.25a.75.75 0 1 0-1.5 0 .75.75 0 0 0 1.5 0Zm6.75.75a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5Zm-3 8.75a.75.75 0 1 0-1.5 0 .75.75 0 0 0 1.5 0Z"></path>-</svg>- 3.8k- </a>- </p>- </div>- </div>- </li>-- <li- class="mb-3 d-flex flex-content-stretch col-12 col-md-6 col-lg-6"- >- <div- class="Box pinned-item-list-item d-flex p-3 width-full public source"- >- <div class="pinned-item-list-item-content">- <div class="d-flex v-align-middle mr-2">- <span data-view-component="true" class="position-relative"><a id="26986729" href="/ryanoasis/vim-devicons" data-view-component="true" class="min-width-0 Link text-bold flex-auto wb-break-all"><span class="repo" >- vim-devicons- </span></a> <tool-tip id="tooltip-afddbb07-3d2e-4366-a7dc-e0a57a10cbe4" for="26986729" popover="manual" data-direction="n" data-type="description" data-view-component="true" class="sr-only position-absolute">vim-devicons</tool-tip></span> <span class="flex-auto text-right">- <span></span><span class="Label Label--secondary v-align-middle ">Public</span>- </span>- </div>--- <p class="pinned-item-desc color-fg-muted text-small d-block mt-2 mb-3">- Adds file type icons to Vim plugins such as: NERDTree, vim-airline, CtrlP, unite, Denite, lightline, vim-startify and many more- </p>-- <p class="mb-0 f6 color-fg-muted">- <span class="d-inline-block mr-3">- <span class="repo-language-color" style="background-color: #199f4b"></span>- <span itemprop="programmingLanguage">Vim Script</span>-</span>-- <a- href="/ryanoasis/vim-devicons/stargazers"- class="pinned-item-meta Link--muted"- >- <svg aria-label="stars" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-star">- <path d="M8 .25a.75.75 0 0 1 .673.418l1.882 3.815 4.21.612a.75.75 0 0 1 .416 1.279l-3.046 2.97.719 4.192a.751.751 0 0 1-1.088.791L8 12.347l-3.766 1.98a.75.75 0 0 1-1.088-.79l.72-4.194L.818 6.374a.75.75 0 0 1 .416-1.28l4.21-.611L7.327.668A.75.75 0 0 1 8 .25Zm0 2.445L6.615 5.5a.75.75 0 0 1-.564.41l-3.097.45 2.24 2.184a.75.75 0 0 1 .216.664l-.528 3.084 2.769-1.456a.75.75 0 0 1 .698 0l2.77 1.456-.53-3.084a.75.75 0 0 1 .216-.664l2.24-2.183-3.096-.45a.75.75 0 0 1-.564-.41L8 2.694Z"></path>-</svg>- 5.8k- </a>- <a- href="/ryanoasis/vim-devicons/forks"- class="pinned-item-meta Link--muted"- >- <svg aria-label="forks" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-repo-forked">- <path d="M5 5.372v.878c0 .414.336.75.75.75h4.5a.75.75 0 0 0 .75-.75v-.878a2.25 2.25 0 1 1 1.5 0v.878a2.25 2.25 0 0 1-2.25 2.25h-1.5v2.128a2.251 2.251 0 1 1-1.5 0V8.5h-1.5A2.25 2.25 0 0 1 3.5 6.25v-.878a2.25 2.25 0 1 1 1.5 0ZM5 3.25a.75.75 0 1 0-1.5 0 .75.75 0 0 0 1.5 0Zm6.75.75a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5Zm-3 8.75a.75.75 0 1 0-1.5 0 .75.75 0 0 0 1.5 0Z"></path>-</svg>- 271- </a>- </p>- </div>- </div>- </li>-- <li- class="mb-3 d-flex flex-content-stretch col-12 col-md-6 col-lg-6"- >- <div- class="Box pinned-item-list-item d-flex p-3 width-full public source"- >- <div class="pinned-item-list-item-content">- <div class="d-flex v-align-middle mr-2">- <span data-view-component="true" class="position-relative"><a id="38125973" href="/ryanoasis/powerline-extra-symbols" data-view-component="true" class="min-width-0 Link text-bold flex-auto wb-break-all"><span class="repo" >- powerline-extra-symbols- </span></a> <tool-tip id="tooltip-8e2e8567-8e3f-4314-94da-2a120e7a15e8" for="38125973" popover="manual" data-direction="n" data-type="description" data-view-component="true" class="sr-only position-absolute">powerline-extra-symbols</tool-tip></span> <span class="flex-auto text-right">- <span></span><span class="Label Label--secondary v-align-middle ">Public</span>- </span>- </div>--- <p class="pinned-item-desc color-fg-muted text-small d-block mt-2 mb-3">- <g-emoji class="g-emoji" alias="arrow_forward">▶️</g-emoji> Extra glyphs for your powerline separators- </p>-- <p class="mb-0 f6 color-fg-muted">- <span class="d-inline-block mr-3">- <span class="repo-language-color" style="background-color: #da291c"></span>- <span itemprop="programmingLanguage">PostScript</span>-</span>-- <a- href="/ryanoasis/powerline-extra-symbols/stargazers"- class="pinned-item-meta Link--muted"- >- <svg aria-label="stars" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-star">- <path d="M8 .25a.75.75 0 0 1 .673.418l1.882 3.815 4.21.612a.75.75 0 0 1 .416 1.279l-3.046 2.97.719 4.192a.751.751 0 0 1-1.088.791L8 12.347l-3.766 1.98a.75.75 0 0 1-1.088-.79l.72-4.194L.818 6.374a.75.75 0 0 1 .416-1.28l4.21-.611L7.327.668A.75.75 0 0 1 8 .25Zm0 2.445L6.615 5.5a.75.75 0 0 1-.564.41l-3.097.45 2.24 2.184a.75.75 0 0 1 .216.664l-.528 3.084 2.769-1.456a.75.75 0 0 1 .698 0l2.77 1.456-.53-3.084a.75.75 0 0 1 .216-.664l2.24-2.183-3.096-.45a.75.75 0 0 1-.564-.41L8 2.694Z"></path>-</svg>- 1.4k- </a>- <a- href="/ryanoasis/powerline-extra-symbols/forks"- class="pinned-item-meta Link--muted"- >- <svg aria-label="forks" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-repo-forked">- <path d="M5 5.372v.878c0 .414.336.75.75.75h4.5a.75.75 0 0 0 .75-.75v-.878a2.25 2.25 0 1 1 1.5 0v.878a2.25 2.25 0 0 1-2.25 2.25h-1.5v2.128a2.251 2.251 0 1 1-1.5 0V8.5h-1.5A2.25 2.25 0 0 1 3.5 6.25v-.878a2.25 2.25 0 1 1 1.5 0ZM5 3.25a.75.75 0 1 0-1.5 0 .75.75 0 0 0 1.5 0Zm6.75.75a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5Zm-3 8.75a.75.75 0 1 0-1.5 0 .75.75 0 0 0 1.5 0Z"></path>-</svg>- 72- </a>- </p>- </div>- </div>- </li>-- <li- class="mb-3 d-flex flex-content-stretch col-12 col-md-6 col-lg-6"- >- <div- class="Box pinned-item-list-item d-flex p-3 width-full public source"- >- <div class="pinned-item-list-item-content">- <div class="d-flex v-align-middle mr-2">- <span data-view-component="true" class="position-relative"><a id="44979030" href="/ryanoasis/public-bash-scripts" data-view-component="true" class="min-width-0 Link text-bold flex-auto wb-break-all"><span class="repo" >- public-bash-scripts- </span></a> <tool-tip id="tooltip-90105c05-01dd-48a1-9dc2-42d93b2727d2" for="44979030" popover="manual" data-direction="n" data-type="description" data-view-component="true" class="sr-only position-absolute">public-bash-scripts</tool-tip></span> <span class="flex-auto text-right">- <span></span><span class="Label Label--secondary v-align-middle ">Public</span>- </span>- </div>--- <p class="pinned-item-desc color-fg-muted text-small d-block mt-2 mb-3">- Bash Scripts that I can share publicly- </p>-- <p class="mb-0 f6 color-fg-muted">- <span class="d-inline-block mr-3">- <span class="repo-language-color" style="background-color: #89e051"></span>- <span itemprop="programmingLanguage">Shell</span>-</span>-- <a- href="/ryanoasis/public-bash-scripts/stargazers"- class="pinned-item-meta Link--muted"- >- <svg aria-label="stars" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-star">- <path d="M8 .25a.75.75 0 0 1 .673.418l1.882 3.815 4.21.612a.75.75 0 0 1 .416 1.279l-3.046 2.97.719 4.192a.751.751 0 0 1-1.088.791L8 12.347l-3.766 1.98a.75.75 0 0 1-1.088-.79l.72-4.194L.818 6.374a.75.75 0 0 1 .416-1.28l4.21-.611L7.327.668A.75.75 0 0 1 8 .25Zm0 2.445L6.615 5.5a.75.75 0 0 1-.564.41l-3.097.45 2.24 2.184a.75.75 0 0 1 .216.664l-.528 3.084 2.769-1.456a.75.75 0 0 1 .698 0l2.77 1.456-.53-3.084a.75.75 0 0 1 .216-.664l2.24-2.183-3.096-.45a.75.75 0 0 1-.564-.41L8 2.694Z"></path>-</svg>- 191- </a>- <a- href="/ryanoasis/public-bash-scripts/forks"- class="pinned-item-meta Link--muted"- >- <svg aria-label="forks" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-repo-forked">- <path d="M5 5.372v.878c0 .414.336.75.75.75h4.5a.75.75 0 0 0 .75-.75v-.878a2.25 2.25 0 1 1 1.5 0v.878a2.25 2.25 0 0 1-2.25 2.25h-1.5v2.128a2.251 2.251 0 1 1-1.5 0V8.5h-1.5A2.25 2.25 0 0 1 3.5 6.25v-.878a2.25 2.25 0 1 1 1.5 0ZM5 3.25a.75.75 0 1 0-1.5 0 .75.75 0 0 0 1.5 0Zm6.75.75a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5Zm-3 8.75a.75.75 0 1 0-1.5 0 .75.75 0 0 0 1.5 0Z"></path>-</svg>- 77- </a>- </p>- </div>- </div>- </li>-- <li- class="mb-3 d-flex flex-content-stretch col-12 col-md-6 col-lg-6"- >- <div- class="Box pinned-item-list-item d-flex p-3 width-full public source"- >- <div class="pinned-item-list-item-content">- <div class="d-flex v-align-middle mr-2">- <span data-view-component="true" class="position-relative"><a id="96135825" href="/ryanoasis/dev-interview-study-guide" data-view-component="true" class="min-width-0 Link text-bold flex-auto wb-break-all"><span class="repo" >- dev-interview-study-guide- </span></a> <tool-tip id="tooltip-864a6026-3603-4525-b986-29745fe3ba55" for="96135825" popover="manual" data-direction="n" data-type="description" data-view-component="true" class="sr-only position-absolute">dev-interview-study-guide</tool-tip></span> <span class="flex-auto text-right">- <span></span><span class="Label Label--secondary v-align-middle ">Public</span>- </span>- </div>--- <p class="pinned-item-desc color-fg-muted text-small d-block mt-2 mb-3">-- </p>-- <p class="mb-0 f6 color-fg-muted">- <a- href="/ryanoasis/dev-interview-study-guide/stargazers"- class="pinned-item-meta Link--muted"- >- <svg aria-label="stars" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-star">- <path d="M8 .25a.75.75 0 0 1 .673.418l1.882 3.815 4.21.612a.75.75 0 0 1 .416 1.279l-3.046 2.97.719 4.192a.751.751 0 0 1-1.088.791L8 12.347l-3.766 1.98a.75.75 0 0 1-1.088-.79l.72-4.194L.818 6.374a.75.75 0 0 1 .416-1.28l4.21-.611L7.327.668A.75.75 0 0 1 8 .25Zm0 2.445L6.615 5.5a.75.75 0 0 1-.564.41l-3.097.45 2.24 2.184a.75.75 0 0 1 .216.664l-.528 3.084 2.769-1.456a.75.75 0 0 1 .698 0l2.77 1.456-.53-3.084a.75.75 0 0 1 .216-.664l2.24-2.183-3.096-.45a.75.75 0 0 1-.564-.41L8 2.694Z"></path>-</svg>- 157- </a>- <a- href="/ryanoasis/dev-interview-study-guide/forks"- class="pinned-item-meta Link--muted"- >- <svg aria-label="forks" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-repo-forked">- <path d="M5 5.372v.878c0 .414.336.75.75.75h4.5a.75.75 0 0 0 .75-.75v-.878a2.25 2.25 0 1 1 1.5 0v.878a2.25 2.25 0 0 1-2.25 2.25h-1.5v2.128a2.251 2.251 0 1 1-1.5 0V8.5h-1.5A2.25 2.25 0 0 1 3.5 6.25v-.878a2.25 2.25 0 1 1 1.5 0ZM5 3.25a.75.75 0 1 0-1.5 0 .75.75 0 0 0 1.5 0Zm6.75.75a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5Zm-3 8.75a.75.75 0 1 0-1.5 0 .75.75 0 0 0 1.5 0Z"></path>-</svg>- 55- </a>- </p>- </div>- </div>- </li>-- <li- class="mb-3 d-flex flex-content-stretch col-12 col-md-6 col-lg-6"- >- <div- class="Box pinned-item-list-item d-flex p-3 width-full public source"- >- <div class="pinned-item-list-item-content">- <div class="d-flex v-align-middle mr-2">- <span data-view-component="true" class="position-relative"><a id="59440264" href="/ryanoasis/devicons-shell" data-view-component="true" class="min-width-0 Link text-bold flex-auto wb-break-all"><span class="repo" >- devicons-shell- </span></a> <tool-tip id="tooltip-a1cc7bbd-2256-414e-a409-554249275266" for="59440264" popover="manual" data-direction="n" data-type="description" data-view-component="true" class="sr-only position-absolute">devicons-shell</tool-tip></span> <span class="flex-auto text-right">- <span></span><span class="Label Label--secondary v-align-middle ">Public</span>- </span>- </div>--- <p class="pinned-item-desc color-fg-muted text-small d-block mt-2 mb-3">- 🔣 adds font icons (glyphs ★♨☢) to filetypes via bash (faux ls with icons)- </p>-- <p class="mb-0 f6 color-fg-muted">- <span class="d-inline-block mr-3">- <span class="repo-language-color" style="background-color: #89e051"></span>- <span itemprop="programmingLanguage">Shell</span>-</span>-- <a- href="/ryanoasis/devicons-shell/stargazers"- class="pinned-item-meta Link--muted"- >- <svg aria-label="stars" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-star">- <path d="M8 .25a.75.75 0 0 1 .673.418l1.882 3.815 4.21.612a.75.75 0 0 1 .416 1.279l-3.046 2.97.719 4.192a.751.751 0 0 1-1.088.791L8 12.347l-3.766 1.98a.75.75 0 0 1-1.088-.79l.72-4.194L.818 6.374a.75.75 0 0 1 .416-1.28l4.21-.611L7.327.668A.75.75 0 0 1 8 .25Zm0 2.445L6.615 5.5a.75.75 0 0 1-.564.41l-3.097.45 2.24 2.184a.75.75 0 0 1 .216.664l-.528 3.084 2.769-1.456a.75.75 0 0 1 .698 0l2.77 1.456-.53-3.084a.75.75 0 0 1 .216-.664l2.24-2.183-3.096-.45a.75.75 0 0 1-.564-.41L8 2.694Z"></path>-</svg>- 99- </a>- <a- href="/ryanoasis/devicons-shell/forks"- class="pinned-item-meta Link--muted"- >- <svg aria-label="forks" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-repo-forked">- <path d="M5 5.372v.878c0 .414.336.75.75.75h4.5a.75.75 0 0 0 .75-.75v-.878a2.25 2.25 0 1 1 1.5 0v.878a2.25 2.25 0 0 1-2.25 2.25h-1.5v2.128a2.251 2.251 0 1 1-1.5 0V8.5h-1.5A2.25 2.25 0 0 1 3.5 6.25v-.878a2.25 2.25 0 1 1 1.5 0ZM5 3.25a.75.75 0 1 0-1.5 0 .75.75 0 0 0 1.5 0Zm6.75.75a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5Zm-3 8.75a.75.75 0 1 0-1.5 0 .75.75 0 0 0 1.5 0Z"></path>-</svg>- 10- </a>- </p>- </div>- </div>- </li>-</ol>--</div>--</div>--<div class="mt-4 position-relative">- <include-fragment src="/ryanoasis?action=show&controller=profiles&tab=contributions&user_id=ryanoasis" data-nonce="v2:772d3842-29b0-c56f-6ee8-099c37fc3685" data-view-component="true">-- <div class="text-center" data-hide-on-error>- <span data-view-component="true">- <svg aria-label="Loading" style="box-sizing: content-box; color: var(--color-icon-primary);" width="32" height="32" viewBox="0 0 16 16" fill="none" role="img" data-view-component="true" class="anim-rotate">- <circle cx="8" cy="8" r="7" stroke="currentColor" stroke-opacity="0.25" stroke-width="2" vector-effect="non-scaling-stroke" fill="none" />- <path d="M15 8a7.002 7.002 0 00-7-7" stroke="currentColor" stroke-width="2" stroke-linecap="round" vector-effect="non-scaling-stroke" />-</svg></span>- </div>- <div class="text-center" data-show-on-error hidden>- Something went wrong, please refresh the page to try again.<br>- If the problem persists, check the <a href="https://www.githubstatus.com/" data-view-component="true" class="Link--inTextBlock Link">GitHub status page</a>- or <a href="/contact" data-view-component="true" class="Link--inTextBlock Link">contact support</a>.- </div>-- <div data-show-on-forbidden-error hidden>- <div class="Box">- <div class="blankslate-container">- <div data-view-component="true" class="blankslate blankslate-spacious color-bg-default rounded-2">--- <h3 data-view-component="true" class="blankslate-heading"> Uh oh!-</h3>- <p data-view-component="true"> <p class="color-fg-muted my-2 mb-2 ws-normal">There was an error while loading. <a class="Link--inTextBlock" data-turbo="false" href="" aria-label="Please reload this page">Please reload this page</a>.</p>-</p>--</div> </div>-</div> </div>-</include-fragment></div>---- </div>- </turbo-frame>-</div>-</div></div>-- </main>- </div>-- <footer class="footer pt-8 pb-6 f6 color-fg-muted p-responsive" role="contentinfo" >- <h2 class='sr-only'>Footer</h2>----- <div class="d-flex flex-justify-center flex-items-center flex-column-reverse flex-lg-row flex-wrap flex-lg-nowrap">- <div class="d-flex flex-items-center flex-shrink-0 mx-2">- <a aria-label="GitHub Homepage" class="footer-octicon mr-2" href="https://github.com">- <svg aria-hidden="true" height="24" viewBox="0 0 24 24" version="1.1" width="24" data-view-component="true" class="octicon octicon-mark-github">- <path d="M12 1C5.923 1 1 5.923 1 12c0 4.867 3.149 8.979 7.521 10.436.55.096.756-.233.756-.522 0-.262-.013-1.128-.013-2.049-2.764.509-3.479-.674-3.699-1.292-.124-.317-.66-1.293-1.127-1.554-.385-.207-.936-.715-.014-.729.866-.014 1.485.797 1.691 1.128.99 1.663 2.571 1.196 3.204.907.096-.715.385-1.196.701-1.471-2.448-.275-5.005-1.224-5.005-5.432 0-1.196.426-2.186 1.128-2.956-.111-.275-.496-1.402.11-2.915 0 0 .921-.288 3.024 1.128a10.193 10.193 0 0 1 2.75-.371c.936 0 1.871.123 2.75.371 2.104-1.43 3.025-1.128 3.025-1.128.605 1.513.221 2.64.111 2.915.701.77 1.127 1.747 1.127 2.956 0 4.222-2.571 5.157-5.019 5.432.399.344.743 1.004.743 2.035 0 1.471-.014 2.654-.014 3.025 0 .289.206.632.756.522C19.851 20.979 23 16.854 23 12c0-6.077-4.922-11-11-11Z"></path>-</svg>-</a>- <span>- © 2025 GitHub, Inc.- </span>- </div>-- <nav aria-label="Footer">- <h3 class="sr-only" id="sr-footer-heading">Footer navigation</h3>-- <ul class="list-style-none d-flex flex-justify-center flex-wrap mb-2 mb-lg-0" aria-labelledby="sr-footer-heading">-- <li class="mx-2">- <a data-analytics-event="{"category":"Footer","action":"go to Terms","label":"text:terms"}" href="https://docs.github.com/site-policy/github-terms/github-terms-of-service" data-view-component="true" class="Link--secondary Link">Terms</a>- </li>-- <li class="mx-2">- <a data-analytics-event="{"category":"Footer","action":"go to privacy","label":"text:privacy"}" href="https://docs.github.com/site-policy/privacy-policies/github-privacy-statement" data-view-component="true" class="Link--secondary Link">Privacy</a>- </li>-- <li class="mx-2">- <a data-analytics-event="{"category":"Footer","action":"go to security","label":"text:security"}" href="https://github.com/security" data-view-component="true" class="Link--secondary Link">Security</a>- </li>-- <li class="mx-2">- <a data-analytics-event="{"category":"Footer","action":"go to status","label":"text:status"}" href="https://www.githubstatus.com/" data-view-component="true" class="Link--secondary Link">Status</a>- </li>-- <li class="mx-2">- <a data-analytics-event="{"category":"Footer","action":"go to community","label":"text:community"}" href="https://github.community/" data-view-component="true" class="Link--secondary Link">Community</a>- </li>-- <li class="mx-2">- <a data-analytics-event="{"category":"Footer","action":"go to docs","label":"text:docs"}" href="https://docs.github.com/" data-view-component="true" class="Link--secondary Link">Docs</a>- </li>-- <li class="mx-2">- <a data-analytics-event="{"category":"Footer","action":"go to contact","label":"text:contact"}" href="https://support.github.com?tags=dotcom-footer" data-view-component="true" class="Link--secondary Link">Contact</a>- </li>-- <li class="mx-2" >- <cookie-consent-link>- <button- type="button"- class="Link--secondary underline-on-hover border-0 p-0 color-bg-transparent"- data-action="click:cookie-consent-link#showConsentManagement"- data-analytics-event="{"location":"footer","action":"cookies","context":"subfooter","tag":"link","label":"cookies_link_subfooter_footer"}"- >- Manage cookies- </button>- </cookie-consent-link>-</li>--<li class="mx-2">- <cookie-consent-link>- <button- type="button"- class="Link--secondary underline-on-hover border-0 p-0 color-bg-transparent text-left"- data-action="click:cookie-consent-link#showConsentManagement"- data-analytics-event="{"location":"footer","action":"dont_share_info","context":"subfooter","tag":"link","label":"dont_share_info_link_subfooter_footer"}"- >- Do not share my personal information- </button>- </cookie-consent-link>-</li>-- </ul>- </nav>- </div>-</footer>---- <ghcc-consent id="ghcc" class="position-fixed bottom-0 left-0" style="z-index: 999999"- data-locale="en"- data-initial-cookie-consent-allowed=""- data-cookie-consent-required="true"- ></ghcc-consent>----- <div id="ajax-error-message" class="ajax-error-message flash flash-error" hidden>- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">- <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>-</svg>- <button type="button" class="flash-close js-ajax-error-dismiss" aria-label="Dismiss error">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-x">- <path d="M3.72 3.72a.75.75 0 0 1 1.06 0L8 6.94l3.22-3.22a.749.749 0 0 1 1.275.326.749.749 0 0 1-.215.734L9.06 8l3.22 3.22a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215L8 9.06l-3.22 3.22a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042L6.94 8 3.72 4.78a.75.75 0 0 1 0-1.06Z"></path>-</svg>- </button>- You can’t perform that action at this time.- </div>-- <template id="site-details-dialog">- <details class="details-reset details-overlay details-overlay-dark lh-default color-fg-default hx_rsm" open>- <summary role="button" aria-label="Close dialog"></summary>- <details-dialog class="Box Box--overlay d-flex flex-column anim-fade-in fast hx_rsm-dialog hx_rsm-modal">- <button class="Box-btn-octicon m-0 btn-octicon position-absolute right-0 top-0" type="button" aria-label="Close dialog" data-close-dialog>- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-x">- <path d="M3.72 3.72a.75.75 0 0 1 1.06 0L8 6.94l3.22-3.22a.749.749 0 0 1 1.275.326.749.749 0 0 1-.215.734L9.06 8l3.22 3.22a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215L8 9.06l-3.22 3.22a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042L6.94 8 3.72 4.78a.75.75 0 0 1 0-1.06Z"></path>-</svg>- </button>- <div class="octocat-spinner my-6 js-details-dialog-spinner"></div>- </details-dialog>- </details>-</template>-- <div class="Popover js-hovercard-content position-absolute" style="display: none; outline: none;">- <div class="Popover-message Popover-message--bottom-left Popover-message--large Box color-shadow-large" style="width:360px;">- </div>-</div>-- <template id="snippet-clipboard-copy-button">- <div class="zeroclipboard-container position-absolute right-0 top-0">- <clipboard-copy aria-label="Copy" class="ClipboardButton btn js-clipboard-copy m-2 p-0" data-copy-feedback="Copied!" data-tooltip-direction="w">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-copy js-clipboard-copy-icon m-2">- <path d="M0 6.75C0 5.784.784 5 1.75 5h1.5a.75.75 0 0 1 0 1.5h-1.5a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-1.5a.75.75 0 0 1 1.5 0v1.5A1.75 1.75 0 0 1 9.25 16h-7.5A1.75 1.75 0 0 1 0 14.25Z"></path><path d="M5 1.75C5 .784 5.784 0 6.75 0h7.5C15.216 0 16 .784 16 1.75v7.5A1.75 1.75 0 0 1 14.25 11h-7.5A1.75 1.75 0 0 1 5 9.25Zm1.75-.25a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-7.5a.25.25 0 0 0-.25-.25Z"></path>-</svg>- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-check js-clipboard-check-icon color-fg-success d-none m-2">- <path d="M13.78 4.22a.75.75 0 0 1 0 1.06l-7.25 7.25a.75.75 0 0 1-1.06 0L2.22 9.28a.751.751 0 0 1 .018-1.042.751.751 0 0 1 1.042-.018L6 10.94l6.72-6.72a.75.75 0 0 1 1.06 0Z"></path>-</svg>- </clipboard-copy>- </div>-</template>-<template id="snippet-clipboard-copy-button-unpositioned">- <div class="zeroclipboard-container">- <clipboard-copy aria-label="Copy" class="ClipboardButton btn btn-invisible js-clipboard-copy m-2 p-0 d-flex flex-justify-center flex-items-center" data-copy-feedback="Copied!" data-tooltip-direction="w">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-copy js-clipboard-copy-icon">- <path d="M0 6.75C0 5.784.784 5 1.75 5h1.5a.75.75 0 0 1 0 1.5h-1.5a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-1.5a.75.75 0 0 1 1.5 0v1.5A1.75 1.75 0 0 1 9.25 16h-7.5A1.75 1.75 0 0 1 0 14.25Z"></path><path d="M5 1.75C5 .784 5.784 0 6.75 0h7.5C15.216 0 16 .784 16 1.75v7.5A1.75 1.75 0 0 1 14.25 11h-7.5A1.75 1.75 0 0 1 5 9.25Zm1.75-.25a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-7.5a.25.25 0 0 0-.25-.25Z"></path>-</svg>- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-check js-clipboard-check-icon color-fg-success d-none">- <path d="M13.78 4.22a.75.75 0 0 1 0 1.06l-7.25 7.25a.75.75 0 0 1-1.06 0L2.22 9.28a.751.751 0 0 1 .018-1.042.751.751 0 0 1 1.042-.018L6 10.94l6.72-6.72a.75.75 0 0 1 1.06 0Z"></path>-</svg>- </clipboard-copy>- </div>-</template>----- </div>- <div id="js-global-screen-reader-notice" class="sr-only mt-n1" aria-live="polite" aria-atomic="true" ></div>- <div id="js-global-screen-reader-notice-assertive" class="sr-only mt-n1" aria-live="assertive" aria-atomic="true"></div>- </body>-</html>diff --git a/app/core/src/main/resources/type3/library/fonts/stix/STIXSizeThreeSym-Regular.otf b/app/core/src/main/resources/type3/library/fonts/stix/STIXSizeThreeSym-Regular.otfdeleted file mode 100644index 1eda1d949f..0000000000--- a/app/core/src/main/resources/type3/library/fonts/stix/STIXSizeThreeSym-Regular.otf+++ /dev/null@@ -1,2055 +0,0 @@--------<!DOCTYPE html>-<html- lang="en"-- data-color-mode="auto" data-light-theme="light" data-dark-theme="dark"- data-a11y-animated-images="system" data-a11y-link-underlines="true"-- >----- <head>- <meta charset="utf-8">- <link rel="dns-prefetch" href="https://github.githubassets.com">- <link rel="dns-prefetch" href="https://avatars.githubusercontent.com">- <link rel="dns-prefetch" href="https://github-cloud.s3.amazonaws.com">- <link rel="dns-prefetch" href="https://user-images.githubusercontent.com/">- <link rel="preconnect" href="https://github.githubassets.com" crossorigin>- <link rel="preconnect" href="https://avatars.githubusercontent.com">---- <link crossorigin="anonymous" media="all" rel="stylesheet" href="https://github.githubassets.com/assets/light-8e973f836952.css" /><link crossorigin="anonymous" media="all" rel="stylesheet" href="https://github.githubassets.com/assets/light_high_contrast-34b642d57214.css" /><link crossorigin="anonymous" media="all" rel="stylesheet" href="https://github.githubassets.com/assets/dark-4bce7af39e21.css" /><link crossorigin="anonymous" media="all" rel="stylesheet" href="https://github.githubassets.com/assets/dark_high_contrast-ad512d3e2f3b.css" /><link data-color-theme="light" crossorigin="anonymous" media="all" rel="stylesheet" data-href="https://github.githubassets.com/assets/light-8e973f836952.css" /><link data-color-theme="light_high_contrast" crossorigin="anonymous" media="all" rel="stylesheet" data-href="https://github.githubassets.com/assets/light_high_contrast-34b642d57214.css" /><link data-color-theme="light_colorblind" crossorigin="anonymous" media="all" rel="stylesheet" data-href="https://github.githubassets.com/assets/light_colorblind-54be93e666a7.css" /><link data-color-theme="light_colorblind_high_contrast" crossorigin="anonymous" media="all" rel="stylesheet" data-href="https://github.githubassets.com/assets/light_colorblind_high_contrast-8ae7edf5489c.css" /><link data-color-theme="light_tritanopia" crossorigin="anonymous" media="all" rel="stylesheet" data-href="https://github.githubassets.com/assets/light_tritanopia-84d50df427c0.css" /><link data-color-theme="light_tritanopia_high_contrast" crossorigin="anonymous" media="all" rel="stylesheet" data-href="https://github.githubassets.com/assets/light_tritanopia_high_contrast-a80873375146.css" /><link data-color-theme="dark" crossorigin="anonymous" media="all" rel="stylesheet" data-href="https://github.githubassets.com/assets/dark-4bce7af39e21.css" /><link data-color-theme="dark_high_contrast" crossorigin="anonymous" media="all" rel="stylesheet" data-href="https://github.githubassets.com/assets/dark_high_contrast-ad512d3e2f3b.css" /><link data-color-theme="dark_colorblind" crossorigin="anonymous" media="all" rel="stylesheet" data-href="https://github.githubassets.com/assets/dark_colorblind-d152d6cd6879.css" /><link data-color-theme="dark_colorblind_high_contrast" crossorigin="anonymous" media="all" rel="stylesheet" data-href="https://github.githubassets.com/assets/dark_colorblind_high_contrast-fa4060c1a9da.css" /><link data-color-theme="dark_tritanopia" crossorigin="anonymous" media="all" rel="stylesheet" data-href="https://github.githubassets.com/assets/dark_tritanopia-d7bad0fb00bb.css" /><link data-color-theme="dark_tritanopia_high_contrast" crossorigin="anonymous" media="all" rel="stylesheet" data-href="https://github.githubassets.com/assets/dark_tritanopia_high_contrast-4a0107c0f60c.css" /><link data-color-theme="dark_dimmed" crossorigin="anonymous" media="all" rel="stylesheet" data-href="https://github.githubassets.com/assets/dark_dimmed-045e6b6ac094.css" /><link data-color-theme="dark_dimmed_high_contrast" crossorigin="anonymous" media="all" rel="stylesheet" data-href="https://github.githubassets.com/assets/dark_dimmed_high_contrast-5de537db5e79.css" />-- <style type="text/css">- :root {- --tab-size-preference: 4;- }-- pre, code {- tab-size: var(--tab-size-preference);- }- </style>-- <link crossorigin="anonymous" media="all" rel="stylesheet" href="https://github.githubassets.com/assets/primer-primitives-15839d47b75d.css" />- <link crossorigin="anonymous" media="all" rel="stylesheet" href="https://github.githubassets.com/assets/primer-a5c85403da8c.css" />- <link crossorigin="anonymous" media="all" rel="stylesheet" href="https://github.githubassets.com/assets/global-abde950b7df1.css" />- <link crossorigin="anonymous" media="all" rel="stylesheet" href="https://github.githubassets.com/assets/github-490b3f68bf33.css" />- <link crossorigin="anonymous" media="all" rel="stylesheet" href="https://github.githubassets.com/assets/repository-5d735668c600.css" />-<link crossorigin="anonymous" media="all" rel="stylesheet" href="https://github.githubassets.com/assets/code-9c9b8dc61e74.css" />---- <script type="application/json" id="client-env">{"locale":"en","featureFlags":["actions_custom_images_public_preview_visibility","actions_custom_images_storage_billing_ui_visibility","actions_enable_snapshot_keyword","actions_image_version_event","alternate_user_config_repo","api_insights_show_missing_data_banner","attestations_filtering","attestations_sorting","automated_review_comment_simplification","billing_split_pru_skus","billing_split_pru_skus","client_version_header","codespaces_prebuild_region_target_update","contentful_lp_footnotes","copilot_agent_cli_public_preview","copilot_agent_task_list_v2","copilot_agent_tasks_btn_code_nav","copilot_agent_tasks_btn_code_view","copilot_agent_tasks_btn_code_view_lines","copilot_api_agentic_issue_marshal_yaml","copilot_api_draft_issues_with_dependencies","copilot_api_github_draft_update_issue_skill","copilot_chat_agents_empty_state","copilot_chat_attach_multiple_images","copilot_chat_file_redirect","copilot_chat_input_commands","copilot_chat_reduce_quota_checks","copilot_chat_search_bar_redirect","copilot_chat_selection_attachments","copilot_chat_vision_in_claude","copilot_chat_vision_skip_thread_create","copilot_coding_agent_task_response","copilot_custom_copilots","copilot_custom_copilots_feature_preview","copilot_duplicate_thread","copilot_extensions_deprecation_notice","copilot_extensions_removal_on_marketplace","copilot_features_raycast_logo","copilot_file_block_ref_matching","copilot_free_to_paid_telem","copilot_ftp_hyperspace_upgrade_prompt","copilot_ftp_settings_upgrade","copilot_ftp_upgrade_to_pro_from_models","copilot_ftp_your_copilot_settings","copilot_immersive_structured_model_picker","copilot_immersive_task_hyperlinking","copilot_immersive_task_within_chat_thread","copilot_insights_column_chart_axis_legibility_fix","copilot_insights_public_preview","copilot_insights_usage_export_ndjson","copilot_no_floating_button","copilot_org_policy_page_focus_mode","copilot_read_shared_conversation","copilot_security_alert_assignee_options","copilot_spaces_as_attachments","copilot_spaces_ga","copilot_spark_empty_state","copilot_spark_loading_webgl","copilot_spark_progressive_error_handling","copilot_spark_use_billing_headers","copilot_stable_conversation_view","copilot_swe_agent_progress_commands","copilot_swe_agent_use_subagents","copilot_workbench_agent_seed_tool","copilot_workbench_cache","copilot_workbench_preview_analytics","copilot_workbench_skip_repo_on_codespace","copilot_workbench_use_single_prompt","deployment_record_api","direct_to_salesforce","disable_dashboard_universe_2025_private_preview","dotcom_chat_client_side_skills","failbot_report_error_react_apps_on_page","ghost_pilot_confidence_truncation_25","ghost_pilot_confidence_truncation_40","global_search_multi_orgs","hpc_improve_dom_insertion_observer","hyperspace_2025_logged_out_batch_1","hyperspace_nudges_universe25","hyperspace_nudges_universe25_post_event","inp_reduced_threshold","insert_before_patch","issue_fields_report_usage","issues_copilot_cross_repo_assign","issues_react_blur_item_picker_on_close","issues_react_bots_timeline_pagination","issues_react_prohibit_title_fallback","issues_react_remove_placeholders","issues_sticky_sidebar","item_picker_search_cancellation","kb_convert_to_space","lifecycle_label_name_updates","link_contact_sales_swp_marketo","marketing_pages_search_explore_provider","mcp_registry_install","memex_default_issue_create_repository","memex_grouped_by_edit_route","memex_mwl_filter_field_delimiter","new_traffic_page_banner","open_agent_session_in_vscode_insiders","pinned_issue_fields","primer_react_segmented_control_tooltip","primer_react_unified_portal_root","primer_react_use_styled_react_theming","projects_assignee_max_limit","react_fetch_graphql_filter_sensitive_data","react_fetch_graphql_rate_limit_error_handling","react_fetch_graphql_validate_base_url","record_sso_banner_metrics","remove_child_patch","report_hydro_web_vitals","repos_insights_remove_new_url","ruleset_deletion_confirmation","sample_network_conn_type","scheduled_reminders_updated_limits","site_features_copilot_universe","site_homepage_collaborate_video","site_homepage_contentful","site_homepage_eyebrow_banner","site_homepage_universe_animations","site_msbuild_webgl_hero","spark_fix_rename","spark_force_push_after_checkout","spark_improve_image_upload","spark_kv_encocoded_keys","spark_show_data_access_on_publish","spark_sync_repository_after_iteration","viewscreen_sandbox","webp_support","workbench_store_readonly"],"copilotApiOverrideUrl":"https://api.githubcopilot.com"}</script>-<script crossorigin="anonymous" type="application/javascript" src="https://github.githubassets.com/assets/high-contrast-cookie-1a011967750c.js"></script>-<script crossorigin="anonymous" type="application/javascript" src="https://github.githubassets.com/assets/wp-runtime-15377c53774e.js" defer="defer"></script>-<script crossorigin="anonymous" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_oddbird_popover-polyfill_dist_popover-fn_js-392bf0ab720a.js" defer="defer"></script>-<script crossorigin="anonymous" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_stacktrace-parser_dist_stack-trace-parser_esm_js-node_modules_github_bro-2f4e04-ebb51d646f4d.js" defer="defer"></script>-<script crossorigin="anonymous" type="application/javascript" src="https://github.githubassets.com/assets/environment-18c386dc8ed3.js" defer="defer"></script>-<script crossorigin="anonymous" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_primer_behaviors_dist_esm_index_mjs-1b15302f2da0.js" defer="defer"></script>-<script crossorigin="anonymous" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_selector-observer_dist_index_esm_js-9ab93471824e.js" defer="defer"></script>-<script crossorigin="anonymous" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_relative-time-element_dist_index_js-15c8a75d3ef5.js" defer="defer"></script>-<script crossorigin="anonymous" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_auto-complete-element_dist_index_js-node_modules_github_catalyst_-0d7d60-a999b98ae398.js" defer="defer"></script>-<script crossorigin="anonymous" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_text-expander-element_dist_index_js-69eb26872f2d.js" defer="defer"></script>-<script crossorigin="anonymous" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_filter-input-element_dist_index_js-node_modules_github_remote-inp-665e70-6080d4c6306d.js" defer="defer"></script>-<script crossorigin="anonymous" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_markdown-toolbar-element_dist_index_js-b03ed9e33b62.js" defer="defer"></script>-<script crossorigin="anonymous" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_file-attachment-element_dist_index_js-node_modules_primer_view-co-777ce2-fc39771b9382.js" defer="defer"></script>-<script crossorigin="anonymous" type="application/javascript" src="https://github.githubassets.com/assets/github-elements-b6c5dfce8b45.js" defer="defer"></script>-<script crossorigin="anonymous" type="application/javascript" src="https://github.githubassets.com/assets/element-registry-2810038c0b2f.js" defer="defer"></script>-<script crossorigin="anonymous" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_braintree_browser-detection_dist_browser-detection_js-node_modules_githu-bb80ec-4e1c4d231e25.js" defer="defer"></script>-<script crossorigin="anonymous" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_lit-html_lit-html_js-0bb805df324c.js" defer="defer"></script>-<script crossorigin="anonymous" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_mini-throttle_dist_index_js-node_modules_morphdom_dist_morphdom-e-c1896e-ba47f43192a8.js" defer="defer"></script>-<script crossorigin="anonymous" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_remote-form_dist_index_js-node_modules_delegated-events_dist_inde-893f9f-25a564a55564.js" defer="defer"></script>-<script crossorigin="anonymous" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_turbo_dist_turbo_es2017-esm_js-b9d3c573623e.js" defer="defer"></script>-<script crossorigin="anonymous" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_hotkey_dist_index_js-node_modules_github_hydro-analytics-client_d-502318-5215461ac705.js" defer="defer"></script>-<script crossorigin="anonymous" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_quote-selection_dist_index_js-node_modules_github_session-resume_-7154bb-5d699c37a4cf.js" defer="defer"></script>-<script crossorigin="anonymous" type="application/javascript" src="https://github.githubassets.com/assets/packages_document-metadata_document-metadata_ts-packages_failbot_failbot_ts-54754da9db3d.js" defer="defer"></script>-<script crossorigin="anonymous" type="application/javascript" src="https://github.githubassets.com/assets/packages_updatable-content_updatable-content_ts-38f5e2f7c2a7.js" defer="defer"></script>-<script crossorigin="anonymous" type="application/javascript" src="https://github.githubassets.com/assets/app_assets_modules_github_behaviors_ajax-error_ts-app_assets_modules_github_behaviors_details-6493f1-48f516987b6b.js" defer="defer"></script>-<script crossorigin="anonymous" type="application/javascript" src="https://github.githubassets.com/assets/app_assets_modules_github_behaviors_task-list_ts-app_assets_modules_github_throttled-input_ts-047775-c6f476084254.js" defer="defer"></script>-<script crossorigin="anonymous" type="application/javascript" src="https://github.githubassets.com/assets/app_assets_modules_github_behaviors_commenting_edit_ts-app_assets_modules_github_behaviors_ht-83c235-d8c5bfe37d1d.js" defer="defer"></script>-<script crossorigin="anonymous" type="application/javascript" src="https://github.githubassets.com/assets/behaviors-d0668d6c9939.js" defer="defer"></script>-<script crossorigin="anonymous" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_delegated-events_dist_index_js-node_modules_github_catalyst_lib_index_js-ef6d0f-af7473406ffd.js" defer="defer"></script>-<script crossorigin="anonymous" type="application/javascript" src="https://github.githubassets.com/assets/notifications-global-54d9bcff2c38.js" defer="defer"></script>-<script crossorigin="anonymous" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_virtualized-list_es_index_js-node_modules_github_template-parts_lib_inde-f69fd1-d11f6dba4250.js" defer="defer"></script>-<script crossorigin="anonymous" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_remote-form_dist_index_js-node_modules_delegated-events_dist_inde-0d71a9-0f8d3e460099.js" defer="defer"></script>-<script crossorigin="anonymous" type="application/javascript" src="https://github.githubassets.com/assets/app_assets_modules_github_ref-selector_ts-ac9e5838e83c.js" defer="defer"></script>-<script crossorigin="anonymous" type="application/javascript" src="https://github.githubassets.com/assets/codespaces-3a2d8a28790d.js" defer="defer"></script>-<script crossorigin="anonymous" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_filter-input-element_dist_index_js-node_modules_github_remote-inp-3eebbd-27c3c9a5e9d5.js" defer="defer"></script>-<script crossorigin="anonymous" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_mini-throttle_dist_decorators_js-node_modules_delegated-events_di-e161aa-b6027876f4ac.js" defer="defer"></script>-<script crossorigin="anonymous" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_file-attachment-element_dist_index_js-node_modules_github_remote--abdaf7-3c17801dfcb5.js" defer="defer"></script>-<script crossorigin="anonymous" type="application/javascript" src="https://github.githubassets.com/assets/repositories-d0d4fc51ced6.js" defer="defer"></script>-<script crossorigin="anonymous" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_mini-throttle_dist_index_js-node_modules_github_catalyst_lib_inde-96937f-55dff362c2cc.js" defer="defer"></script>-<script crossorigin="anonymous" type="application/javascript" src="https://github.githubassets.com/assets/code-menu-79e3f1125b29.js" defer="defer"></script>-- <script crossorigin="anonymous" type="application/javascript" src="https://github.githubassets.com/assets/primer-react-8e71f33d9997.js" defer="defer"></script>-<script crossorigin="anonymous" type="application/javascript" src="https://github.githubassets.com/assets/react-lib-15cc174d9050.js" defer="defer"></script>-<script crossorigin="anonymous" type="application/javascript" src="https://github.githubassets.com/assets/react-core-572052063bb8.js" defer="defer"></script>-<script crossorigin="anonymous" type="application/javascript" src="https://github.githubassets.com/assets/octicons-react-dfcd3f5e8531.js" defer="defer"></script>-<script crossorigin="anonymous" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_emotion_is-prop-valid_dist_emotion-is-prop-valid_esm_js-node_modules_emo-825c28-530c0dc3faaf.js" defer="defer"></script>-<script crossorigin="anonymous" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_mini-throttle_dist_index_js-node_modules_github_hydro-analytics-c-c228f9-ee0085693179.js" defer="defer"></script>-<script crossorigin="anonymous" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_tanstack_query-core_build_modern_mutation_js-node_modules_tanstack_query-9bf7e4-aae5b6d19426.js" defer="defer"></script>-<script crossorigin="anonymous" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_swc_helpers_esm__class_private_method_get_js-node_modules_swc_helpers_es-d6b1a6-670f1fbb1e13.js" defer="defer"></script>-<script crossorigin="anonymous" type="application/javascript" src="https://github.githubassets.com/assets/packages_notifications-subscriptions-menu_entry_ts-packages_promise-with-resolvers-polyfill_p-15cb60-52e041329aa5.js" defer="defer"></script>-<script crossorigin="anonymous" type="application/javascript" src="https://github.githubassets.com/assets/notifications-subscriptions-menu-6a3e85ea286e.js" defer="defer"></script>-<link crossorigin="anonymous" media="all" rel="stylesheet" href="https://github.githubassets.com/assets/primer-react.53f37102c46fd176a96b.module.css" />-<link crossorigin="anonymous" media="all" rel="stylesheet" href="https://github.githubassets.com/assets/notifications-subscriptions-menu.bab8822ac328fb95c70d.module.css" />-- <link crossorigin="anonymous" media="all" rel="stylesheet" href="https://github.githubassets.com/assets/primer-react.53f37102c46fd176a96b.module.css" />-<link crossorigin="anonymous" media="all" rel="stylesheet" href="https://github.githubassets.com/assets/notifications-subscriptions-menu.bab8822ac328fb95c70d.module.css" />--- <title>GitHub - stipub/stixfonts: OpenType Unicode fonts for Scientific, Technical, and Mathematical texts</title>---- <meta name="route-pattern" content="/:user_id/:repository" data-turbo-transient>- <meta name="route-controller" content="files" data-turbo-transient>- <meta name="route-action" content="disambiguate" data-turbo-transient>- <meta name="fetch-nonce" content="v2:b49ec1ff-5698-f083-23b7-2d32904b38f1">--- <meta name="current-catalog-service-hash" content="f3abb0cc802f3d7b95fc8762b94bdcb13bf39634c40c357301c4aa1d67a256fb">--- <meta name="request-id" content="DF28:3530F9:4D4F3:55892:690DE2B2" data-pjax-transient="true"/><meta name="html-safe-nonce" content="d994a1fc77b50050d6122315ec0f67cba532089b9b31f4eec35d3fc595e04453" data-pjax-transient="true"/><meta name="visitor-payload" content="eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJERjI4OjM1MzBGOTo0RDRGMzo1NTg5Mjo2OTBERTJCMiIsInZpc2l0b3JfaWQiOiIyNjg2OTY1OTI3NjQ4Mjg5NDU4IiwicmVnaW9uX2VkZ2UiOiJ1a3NvdXRoIiwicmVnaW9uX3JlbmRlciI6InVrc291dGgifQ==" data-pjax-transient="true"/><meta name="visitor-hmac" content="4c9af536282f0fb1c2c507fd8beb179f449d13d8c59604c407a60cf1fa6b58dc" data-pjax-transient="true"/>--- <meta name="hovercard-subject-tag" content="repository:128424630" data-turbo-transient>--- <meta name="github-keyboard-shortcuts" content="repository,copilot" data-turbo-transient="true" />--- <meta name="selected-link" value="repo_source" data-turbo-transient>- <link rel="assets" href="https://github.githubassets.com/">-- <meta name="google-site-verification" content="Apib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I">--<meta name="octolytics-url" content="https://collector.github.com/github/collect" />-- <meta name="analytics-location" content="/<user-name>/<repo-name>" data-turbo-transient="true" />------- <meta name="user-login" content="">---- <meta name="viewport" content="width=device-width">---- <meta name="description" content="OpenType Unicode fonts for Scientific, Technical, and Mathematical texts - stipub/stixfonts">-- <link rel="search" type="application/opensearchdescription+xml" href="/opensearch.xml" title="GitHub">-- <link rel="fluid-icon" href="https://github.com/fluidicon.png" title="GitHub">- <meta property="fb:app_id" content="1401488693436528">- <meta name="apple-itunes-app" content="app-id=1477376905, app-argument=https://github.com/stipub/stixfonts" />-- <meta name="twitter:image" content="https://opengraph.githubassets.com/533fe4a25195df468c4b4f57a2590e7e1d34ef06240b93e1e96643b20867e12f/stipub/stixfonts" /><meta name="twitter:site" content="@github" /><meta name="twitter:card" content="summary_large_image" /><meta name="twitter:title" content="GitHub - stipub/stixfonts: OpenType Unicode fonts for Scientific, Technical, and Mathematical texts" /><meta name="twitter:description" content="OpenType Unicode fonts for Scientific, Technical, and Mathematical texts - stipub/stixfonts" />- <meta property="og:image" content="https://opengraph.githubassets.com/533fe4a25195df468c4b4f57a2590e7e1d34ef06240b93e1e96643b20867e12f/stipub/stixfonts" /><meta property="og:image:alt" content="OpenType Unicode fonts for Scientific, Technical, and Mathematical texts - stipub/stixfonts" /><meta property="og:image:width" content="1200" /><meta property="og:image:height" content="600" /><meta property="og:site_name" content="GitHub" /><meta property="og:type" content="object" /><meta property="og:title" content="GitHub - stipub/stixfonts: OpenType Unicode fonts for Scientific, Technical, and Mathematical texts" /><meta property="og:url" content="https://github.com/stipub/stixfonts" /><meta property="og:description" content="OpenType Unicode fonts for Scientific, Technical, and Mathematical texts - stipub/stixfonts" />------ <meta name="hostname" content="github.com">---- <meta name="expected-hostname" content="github.com">--- <meta http-equiv="x-pjax-version" content="20d4d190ad98a2c2b308bc9064de12eabbd325e43d545510dbe8615eb8813c37" data-turbo-track="reload">- <meta http-equiv="x-pjax-csp-version" content="21a43568025709b66240454fc92d4f09335a96863f8ab1c46b4a07f6a5b67102" data-turbo-track="reload">- <meta http-equiv="x-pjax-css-version" content="64aa48ca69ddc4d1267863e96c8a5c11e0cb33842931f16e1441b54a84bcc1ad" data-turbo-track="reload">- <meta http-equiv="x-pjax-js-version" content="4868c5dba4ede62dc57074a8973225c79271ff4c71c86d22974ed0988061774e" data-turbo-track="reload">-- <meta name="turbo-cache-control" content="no-preview" data-turbo-transient="">-- <meta data-hydrostats="publish">- <meta name="go-import" content="github.com/stipub/stixfonts git https://github.com/stipub/stixfonts.git">-- <meta name="octolytics-dimension-user_id" content="12853237" /><meta name="octolytics-dimension-user_login" content="stipub" /><meta name="octolytics-dimension-repository_id" content="128424630" /><meta name="octolytics-dimension-repository_nwo" content="stipub/stixfonts" /><meta name="octolytics-dimension-repository_public" content="true" /><meta name="octolytics-dimension-repository_is_fork" content="false" /><meta name="octolytics-dimension-repository_network_root_id" content="128424630" /><meta name="octolytics-dimension-repository_network_root_nwo" content="stipub/stixfonts" />---- <link rel="canonical" href="https://github.com/stipub/stixfonts" data-turbo-transient>--- <meta name="turbo-body-classes" content="logged-out env-production page-responsive">--- <meta name="browser-stats-url" content="https://api.github.com/_private/browser/stats">-- <meta name="browser-errors-url" content="https://api.github.com/_private/browser/errors">-- <meta name="release" content="dc34584cbd2dbbcdc6207a9dca58c59883a292db">- <meta name="ui-target" content="full">-- <link rel="mask-icon" href="https://github.githubassets.com/assets/pinned-octocat-093da3e6fa40.svg" color="#000000">- <link rel="alternate icon" class="js-site-favicon" type="image/png" href="https://github.githubassets.com/favicons/favicon.png">- <link rel="icon" class="js-site-favicon" type="image/svg+xml" href="https://github.githubassets.com/favicons/favicon.svg" data-base-href="https://github.githubassets.com/favicons/favicon">--<meta name="theme-color" content="#1e2327">-<meta name="color-scheme" content="light dark" />--- <link rel="manifest" href="/manifest.json" crossOrigin="use-credentials">-- </head>-- <body class="logged-out env-production page-responsive" style="word-wrap: break-word;" >- <div data-turbo-body class="logged-out env-production page-responsive" style="word-wrap: break-word;">----- <div class="position-relative header-wrapper js-header-wrapper ">- <a href="#start-of-content" data-skip-target-assigned="false" class="px-2 py-4 color-bg-accent-emphasis color-fg-on-emphasis show-on-focus js-skip-to-content">Skip to content</a>-- <span data-view-component="true" class="progress-pjax-loader Progress position-fixed width-full">- <span style="width: 0%;" data-view-component="true" class="Progress-item progress-pjax-loader-bar left-0 top-0 color-bg-accent-emphasis"></span>-</span>-- <link crossorigin="anonymous" media="all" rel="stylesheet" href="https://github.githubassets.com/assets/primer-react.53f37102c46fd176a96b.module.css" />-<link crossorigin="anonymous" media="all" rel="stylesheet" href="https://github.githubassets.com/assets/keyboard-shortcuts-dialog.2de9c7d6456a311fce49.module.css" />--<react-partial- partial-name="keyboard-shortcuts-dialog"- data-ssr="false"- data-attempted-ssr="false"- data-react-profiling="false"->-- <script type="application/json" data-target="react-partial.embeddedData">{"props":{"docsUrl":"https://docs.github.com/get-started/accessibility/keyboard-shortcuts"}}</script>- <div data-target="react-partial.reactRoot"></div>-</react-partial>-----------<script crossorigin="anonymous" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_gsap_index_js-1399719d10c8.js" defer="defer"></script>-<script crossorigin="anonymous" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_remote-form_dist_index_js-node_modules_delegated-events_dist_inde-94fd67-0b6bd345de5a.js" defer="defer"></script>-<script crossorigin="anonymous" type="application/javascript" src="https://github.githubassets.com/assets/sessions-f691799f782d.js" defer="defer"></script>--<header class="HeaderMktg header-logged-out js-details-container js-header Details f4 py-3" role="banner" data-is-top="true" data-color-mode=light data-light-theme=light data-dark-theme=dark>- <h2 class="sr-only">Navigation Menu</h2>-- <button type="button" class="HeaderMktg-backdrop d-lg-none border-0 position-fixed top-0 left-0 width-full height-full js-details-target" aria-label="Toggle navigation">- <span class="d-none">Toggle navigation</span>- </button>-- <div class="d-flex flex-column flex-lg-row flex-items-center px-3 px-md-4 px-lg-5 height-full position-relative z-1">- <div class="d-flex flex-justify-between flex-items-center width-full width-lg-auto">- <div class="flex-1">- <button aria-label="Toggle navigation" aria-expanded="false" type="button" data-view-component="true" class="js-details-target js-nav-padding-recalculate js-header-menu-toggle Button--link Button--medium Button d-lg-none color-fg-inherit p-1"> <span class="Button-content">- <span class="Button-label"><div class="HeaderMenu-toggle-bar rounded my-1"></div>- <div class="HeaderMenu-toggle-bar rounded my-1"></div>- <div class="HeaderMenu-toggle-bar rounded my-1"></div></span>- </span>-</button>- </div>-- <a class="mr-lg-3 color-fg-inherit flex-order-2 js-prevent-focus-on-mobile-nav"- href="/"- aria-label="Homepage"- data-analytics-event="{"category":"Marketing nav","action":"click to go to homepage","label":"ref_page:Marketing;ref_cta:Logomark;ref_loc:Header"}">- <svg height="32" aria-hidden="true" viewBox="0 0 24 24" version="1.1" width="32" data-view-component="true" class="octicon octicon-mark-github">- <path d="M12 1C5.923 1 1 5.923 1 12c0 4.867 3.149 8.979 7.521 10.436.55.096.756-.233.756-.522 0-.262-.013-1.128-.013-2.049-2.764.509-3.479-.674-3.699-1.292-.124-.317-.66-1.293-1.127-1.554-.385-.207-.936-.715-.014-.729.866-.014 1.485.797 1.691 1.128.99 1.663 2.571 1.196 3.204.907.096-.715.385-1.196.701-1.471-2.448-.275-5.005-1.224-5.005-5.432 0-1.196.426-2.186 1.128-2.956-.111-.275-.496-1.402.11-2.915 0 0 .921-.288 3.024 1.128a10.193 10.193 0 0 1 2.75-.371c.936 0 1.871.123 2.75.371 2.104-1.43 3.025-1.128 3.025-1.128.605 1.513.221 2.64.111 2.915.701.77 1.127 1.747 1.127 2.956 0 4.222-2.571 5.157-5.019 5.432.399.344.743 1.004.743 2.035 0 1.471-.014 2.654-.014 3.025 0 .289.206.632.756.522C19.851 20.979 23 16.854 23 12c0-6.077-4.922-11-11-11Z"></path>-</svg>- </a>-- <div class="d-flex flex-1 flex-order-2 text-right d-lg-none gap-2 flex-justify-end">- <a- href="/login?return_to=https%3A%2F%2Fgithub.com%2Fstipub%2Fstixfonts%2F"- class="HeaderMenu-link HeaderMenu-button d-inline-flex f5 no-underline border color-border-default rounded-2 px-2 py-1 color-fg-inherit js-prevent-focus-on-mobile-nav"- data-hydro-click="{"event_type":"authentication.click","payload":{"location_in_page":"site header menu","repository_id":null,"auth_type":"SIGN_UP","originating_url":"https://github.com/stipub/stixfonts","user_id":null}}" data-hydro-click-hmac="593a19135ddfa1362b376b817f3d4cfb97274702995b6b2018b94233d5572800"- data-analytics-event="{"category":"Marketing nav","action":"click to Sign in","label":"ref_page:Marketing;ref_cta:Sign in;ref_loc:Header"}"- >- Sign in- </a>- <div class="AppHeader-appearanceSettings">- <react-partial-anchor>- <button data-target="react-partial-anchor.anchor" id="icon-button-a3a34a66-2dfa-4cfd-b2f0-7aa68545c09d" aria-labelledby="tooltip-a0bd9b7c-9849-4bec-b385-32babe77fcd9" type="button" disabled="disabled" data-view-component="true" class="Button Button--iconOnly Button--invisible Button--medium AppHeader-button HeaderMenu-link border cursor-wait"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-sliders Button-visual">- <path d="M15 2.75a.75.75 0 0 1-.75.75h-4a.75.75 0 0 1 0-1.5h4a.75.75 0 0 1 .75.75Zm-8.5.75v1.25a.75.75 0 0 0 1.5 0v-4a.75.75 0 0 0-1.5 0V2H1.75a.75.75 0 0 0 0 1.5H6.5Zm1.25 5.25a.75.75 0 0 0 0-1.5h-6a.75.75 0 0 0 0 1.5h6ZM15 8a.75.75 0 0 1-.75.75H11.5V10a.75.75 0 1 1-1.5 0V6a.75.75 0 0 1 1.5 0v1.25h2.75A.75.75 0 0 1 15 8Zm-9 5.25v-2a.75.75 0 0 0-1.5 0v1.25H1.75a.75.75 0 0 0 0 1.5H4.5v1.25a.75.75 0 0 0 1.5 0v-2Zm9 0a.75.75 0 0 1-.75.75h-6a.75.75 0 0 1 0-1.5h6a.75.75 0 0 1 .75.75Z"></path>-</svg>-</button><tool-tip id="tooltip-a0bd9b7c-9849-4bec-b385-32babe77fcd9" for="icon-button-a3a34a66-2dfa-4cfd-b2f0-7aa68545c09d" popover="manual" data-direction="s" data-type="label" data-view-component="true" class="sr-only position-absolute">Appearance settings</tool-tip>-- <template data-target="react-partial-anchor.template">- <link crossorigin="anonymous" media="all" rel="stylesheet" href="https://github.githubassets.com/assets/primer-react.53f37102c46fd176a96b.module.css" />-<link crossorigin="anonymous" media="all" rel="stylesheet" href="https://github.githubassets.com/assets/appearance-settings.6c63a6de228d6520804d.module.css" />--<react-partial- partial-name="appearance-settings"- data-ssr="false"- data-attempted-ssr="false"- data-react-profiling="false"->-- <script type="application/json" data-target="react-partial.embeddedData">{"props":{}}</script>- <div data-target="react-partial.reactRoot"></div>-</react-partial>--- </template>- </react-partial-anchor>- </div>-- </div>- </div>--- <div class="HeaderMenu js-header-menu height-fit position-lg-relative d-lg-flex flex-column flex-auto top-0">- <div class="HeaderMenu-wrapper d-flex flex-column flex-self-start flex-lg-row flex-auto rounded rounded-lg-0">- <link crossorigin="anonymous" media="all" rel="stylesheet" href="https://github.githubassets.com/assets/primer-react.53f37102c46fd176a96b.module.css" />-<link crossorigin="anonymous" media="all" rel="stylesheet" href="https://github.githubassets.com/assets/marketing-navigation.fd20bacfa4fdf4953836.module.css" />--<react-partial- partial-name="marketing-navigation"- data-ssr="true"- data-attempted-ssr="true"- data-react-profiling="false"->-- <script type="application/json" data-target="react-partial.embeddedData">{"props":{"should_use_dotcom_links":true}}</script>- <div data-target="react-partial.reactRoot"><nav class="MarketingNavigation-module__nav--jA9Zq" aria-label="Global"><ul class="MarketingNavigation-module__list--r_vr2"><li><div class="NavDropdown-module__container--bmXM2 js-details-container js-header-menu-item"><button type="button" class="NavDropdown-module__button--Hq9UR js-details-target" aria-expanded="false">Platform<svg aria-hidden="true" focusable="false" class="octicon octicon-chevron-right NavDropdown-module__buttonIcon--SR0Ke" viewBox="0 0 16 16" width="16" height="16" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M6.22 3.22a.75.75 0 0 1 1.06 0l4.25 4.25a.75.75 0 0 1 0 1.06l-4.25 4.25a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042L9.94 8 6.22 4.28a.75.75 0 0 1 0-1.06Z"></path></svg></button><div class="NavDropdown-module__dropdown--Ig57Y"><ul class="NavDropdown-module__list--RwSSK"><li><div class="NavGroup-module__group--T925n"><span class="NavGroup-module__title--TdKyz">AI CODE CREATION</span><ul class="NavGroup-module__list--M8eGv"><li><a href="https://github.com/features/copilot" data-analytics-event="{"action":"github_copilot","tag":"link","context":"platform","location":"navbar","label":"github_copilot_link_platform_navbar"}" class="NavLink-module__link--n48VB"><div class="NavLink-module__text--SdWkb"><svg aria-hidden="true" focusable="false" class="octicon octicon-copilot NavLink-module__icon--h0sw7" viewBox="0 0 24 24" width="24" height="24" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M23.922 16.992c-.861 1.495-5.859 5.023-11.922 5.023-6.063 0-11.061-3.528-11.922-5.023A.641.641 0 0 1 0 16.736v-2.869a.841.841 0 0 1 .053-.22c.372-.935 1.347-2.292 2.605-2.656.167-.429.414-1.055.644-1.517a10.195 10.195 0 0 1-.052-1.086c0-1.331.282-2.499 1.132-3.368.397-.406.89-.717 1.474-.952 1.399-1.136 3.392-2.093 6.122-2.093 2.731 0 4.767.957 6.166 2.093.584.235 1.077.546 1.474.952.85.869 1.132 2.037 1.132 3.368 0 .368-.014.733-.052 1.086.23.462.477 1.088.644 1.517 1.258.364 2.233 1.721 2.605 2.656a.832.832 0 0 1 .053.22v2.869a.641.641 0 0 1-.078.256ZM12.172 11h-.344a4.323 4.323 0 0 1-.355.508C10.703 12.455 9.555 13 7.965 13c-1.725 0-2.989-.359-3.782-1.259a2.005 2.005 0 0 1-.085-.104L4 11.741v6.585c1.435.779 4.514 2.179 8 2.179 3.486 0 6.565-1.4 8-2.179v-6.585l-.098-.104s-.033.045-.085.104c-.793.9-2.057 1.259-3.782 1.259-1.59 0-2.738-.545-3.508-1.492a4.323 4.323 0 0 1-.355-.508h-.016.016Zm.641-2.935c.136 1.057.403 1.913.878 2.497.442.544 1.134.938 2.344.938 1.573 0 2.292-.337 2.657-.751.384-.435.558-1.15.558-2.361 0-1.14-.243-1.847-.705-2.319-.477-.488-1.319-.862-2.824-1.025-1.487-.161-2.192.138-2.533.529-.269.307-.437.808-.438 1.578v.021c0 .265.021.562.063.893Zm-1.626 0c.042-.331.063-.628.063-.894v-.02c-.001-.77-.169-1.271-.438-1.578-.341-.391-1.046-.69-2.533-.529-1.505.163-2.347.537-2.824 1.025-.462.472-.705 1.179-.705 2.319 0 1.211.175 1.926.558 2.361.365.414 1.084.751 2.657.751 1.21 0 1.902-.394 2.344-.938.475-.584.742-1.44.878-2.497Z"></path><path d="M14.5 14.25a1 1 0 0 1 1 1v2a1 1 0 0 1-2 0v-2a1 1 0 0 1 1-1Zm-5 0a1 1 0 0 1 1 1v2a1 1 0 0 1-2 0v-2a1 1 0 0 1 1-1Z"></path></svg><span class="NavLink-module__title--xw3ok">GitHub Copilot</span><span class="NavLink-module__subtitle--qC15H">Write better code with AI</span></div></a></li><li><a href="https://github.com/features/spark" data-analytics-event="{"action":"github_spark","tag":"link","context":"platform","location":"navbar","label":"github_spark_link_platform_navbar"}" class="NavLink-module__link--n48VB"><div class="NavLink-module__text--SdWkb"><svg aria-hidden="true" focusable="false" class="octicon octicon-sparkle-fill NavLink-module__icon--h0sw7" viewBox="0 0 24 24" width="24" height="24" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M11.296 1.924c.24-.656 1.168-.656 1.408 0l.717 1.958a11.25 11.25 0 0 0 6.697 6.697l1.958.717c.657.24.657 1.168 0 1.408l-1.958.717a11.25 11.25 0 0 0-6.697 6.697l-.717 1.958c-.24.657-1.168.657-1.408 0l-.717-1.958a11.25 11.25 0 0 0-6.697-6.697l-1.958-.717c-.656-.24-.656-1.168 0-1.408l1.958-.717a11.25 11.25 0 0 0 6.697-6.697l.717-1.958Z"></path></svg><span class="NavLink-module__title--xw3ok">GitHub Spark</span><span class="NavLink-module__subtitle--qC15H">Build and deploy intelligent apps</span></div></a></li><li><a href="https://github.com/features/models" data-analytics-event="{"action":"github_models","tag":"link","context":"platform","location":"navbar","label":"github_models_link_platform_navbar"}" class="NavLink-module__link--n48VB"><div class="NavLink-module__text--SdWkb"><svg aria-hidden="true" focusable="false" class="octicon octicon-ai-model NavLink-module__icon--h0sw7" viewBox="0 0 24 24" width="24" height="24" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M19.375 8.5a3.25 3.25 0 1 1-3.163 4h-3a3.252 3.252 0 0 1-4.443 2.509L7.214 17.76a3.25 3.25 0 1 1-1.342-.674l1.672-2.957A3.238 3.238 0 0 1 6.75 12c0-.907.371-1.727.97-2.316L6.117 6.846A3.253 3.253 0 0 1 1.875 3.75a3.25 3.25 0 1 1 5.526 2.32l1.603 2.836A3.25 3.25 0 0 1 13.093 11h3.119a3.252 3.252 0 0 1 3.163-2.5ZM10 10.25a1.75 1.75 0 1 0-.001 3.499A1.75 1.75 0 0 0 10 10.25ZM5.125 2a1.75 1.75 0 1 0 0 3.5 1.75 1.75 0 0 0 0-3.5Zm12.5 9.75a1.75 1.75 0 1 0 3.5 0 1.75 1.75 0 0 0-3.5 0Zm-14.25 8.5a1.75 1.75 0 1 0 3.501-.001 1.75 1.75 0 0 0-3.501.001Z"></path></svg><span class="NavLink-module__title--xw3ok">GitHub Models</span><span class="NavLink-module__subtitle--qC15H">Manage and compare prompts</span></div></a></li><li><a href="https://github.com/mcp" data-analytics-event="{"action":"mcp_registry","tag":"link","context":"platform","location":"navbar","label":"mcp_registry_link_platform_navbar"}" class="NavLink-module__link--n48VB"><div class="NavLink-module__text--SdWkb"><svg aria-hidden="true" focusable="false" class="octicon octicon-mcp NavLink-module__icon--h0sw7" viewBox="0 0 24 24" width="24" height="24" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M9.795 1.694a4.287 4.287 0 0 1 6.061 0 4.28 4.28 0 0 1 1.181 3.819 4.282 4.282 0 0 1 3.819 1.181 4.287 4.287 0 0 1 0 6.061l-6.793 6.793a.249.249 0 0 0 0 .353l2.617 2.618a.75.75 0 1 1-1.061 1.061l-2.617-2.618a1.75 1.75 0 0 1 0-2.475l6.793-6.793a2.785 2.785 0 1 0-3.939-3.939l-5.9 5.9a.734.734 0 0 1-.249.165.749.749 0 0 1-.812-1.225l5.9-5.901a2.785 2.785 0 1 0-3.939-3.939L2.931 10.68A.75.75 0 1 1 1.87 9.619l7.925-7.925Z"></path><path d="M12.42 4.069a.752.752 0 0 1 1.061 0 .752.752 0 0 1 0 1.061L7.33 11.28a2.788 2.788 0 0 0 0 3.94 2.788 2.788 0 0 0 3.94 0l6.15-6.151a.752.752 0 0 1 1.061 0 .752.752 0 0 1 0 1.061l-6.151 6.15a4.285 4.285 0 1 1-6.06-6.06l6.15-6.151Z"></path></svg><span class="NavLink-module__title--xw3ok">MCP Registry<sup class="NavLink-module__label--MrIhm">New</sup></span><span class="NavLink-module__subtitle--qC15H">Discover and integrate external tools</span></div></a></li></ul></div></li><li><div class="NavGroup-module__group--T925n"><span class="NavGroup-module__title--TdKyz">DEVELOPER WORKFLOWS</span><ul class="NavGroup-module__list--M8eGv"><li><a href="https://github.com/features/actions" data-analytics-event="{"action":"actions","tag":"link","context":"platform","location":"navbar","label":"actions_link_platform_navbar"}" class="NavLink-module__link--n48VB"><div class="NavLink-module__text--SdWkb"><svg aria-hidden="true" focusable="false" class="octicon octicon-workflow NavLink-module__icon--h0sw7" viewBox="0 0 24 24" width="24" height="24" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M1 3a2 2 0 0 1 2-2h6.5a2 2 0 0 1 2 2v6.5a2 2 0 0 1-2 2H7v4.063C7 16.355 7.644 17 8.438 17H12.5v-2.5a2 2 0 0 1 2-2H21a2 2 0 0 1 2 2V21a2 2 0 0 1-2 2h-6.5a2 2 0 0 1-2-2v-2.5H8.437A2.939 2.939 0 0 1 5.5 15.562V11.5H3a2 2 0 0 1-2-2Zm2-.5a.5.5 0 0 0-.5.5v6.5a.5.5 0 0 0 .5.5h6.5a.5.5 0 0 0 .5-.5V3a.5.5 0 0 0-.5-.5ZM14.5 14a.5.5 0 0 0-.5.5V21a.5.5 0 0 0 .5.5H21a.5.5 0 0 0 .5-.5v-6.5a.5.5 0 0 0-.5-.5Z"></path></svg><span class="NavLink-module__title--xw3ok">Actions</span><span class="NavLink-module__subtitle--qC15H">Automate any workflow</span></div></a></li><li><a href="https://github.com/features/codespaces" data-analytics-event="{"action":"codespaces","tag":"link","context":"platform","location":"navbar","label":"codespaces_link_platform_navbar"}" class="NavLink-module__link--n48VB"><div class="NavLink-module__text--SdWkb"><svg aria-hidden="true" focusable="false" class="octicon octicon-codespaces NavLink-module__icon--h0sw7" viewBox="0 0 24 24" width="24" height="24" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M3.5 3.75C3.5 2.784 4.284 2 5.25 2h13.5c.966 0 1.75.784 1.75 1.75v7.5A1.75 1.75 0 0 1 18.75 13H5.25a1.75 1.75 0 0 1-1.75-1.75Zm-2 12c0-.966.784-1.75 1.75-1.75h17.5c.966 0 1.75.784 1.75 1.75v4a1.75 1.75 0 0 1-1.75 1.75H3.25a1.75 1.75 0 0 1-1.75-1.75ZM5.25 3.5a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h13.5a.25.25 0 0 0 .25-.25v-7.5a.25.25 0 0 0-.25-.25Zm-2 12a.25.25 0 0 0-.25.25v4c0 .138.112.25.25.25h17.5a.25.25 0 0 0 .25-.25v-4a.25.25 0 0 0-.25-.25Z"></path><path d="M10 17.75a.75.75 0 0 1 .75-.75h6.5a.75.75 0 0 1 0 1.5h-6.5a.75.75 0 0 1-.75-.75Zm-4 0a.75.75 0 0 1 .75-.75h.5a.75.75 0 0 1 0 1.5h-.5a.75.75 0 0 1-.75-.75Z"></path></svg><span class="NavLink-module__title--xw3ok">Codespaces</span><span class="NavLink-module__subtitle--qC15H">Instant dev environments</span></div></a></li><li><a href="https://github.com/features/issues" data-analytics-event="{"action":"issues","tag":"link","context":"platform","location":"navbar","label":"issues_link_platform_navbar"}" class="NavLink-module__link--n48VB"><div class="NavLink-module__text--SdWkb"><svg aria-hidden="true" focusable="false" class="octicon octicon-issue-opened NavLink-module__icon--h0sw7" viewBox="0 0 24 24" width="24" height="24" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M12 1c6.075 0 11 4.925 11 11s-4.925 11-11 11S1 18.075 1 12 5.925 1 12 1ZM2.5 12a9.5 9.5 0 0 0 9.5 9.5 9.5 9.5 0 0 0 9.5-9.5A9.5 9.5 0 0 0 12 2.5 9.5 9.5 0 0 0 2.5 12Zm9.5 2a2 2 0 1 1-.001-3.999A2 2 0 0 1 12 14Z"></path></svg><span class="NavLink-module__title--xw3ok">Issues</span><span class="NavLink-module__subtitle--qC15H">Plan and track work</span></div></a></li><li><a href="https://github.com/features/code-review" data-analytics-event="{"action":"code_review","tag":"link","context":"platform","location":"navbar","label":"code_review_link_platform_navbar"}" class="NavLink-module__link--n48VB"><div class="NavLink-module__text--SdWkb"><svg aria-hidden="true" focusable="false" class="octicon octicon-code NavLink-module__icon--h0sw7" viewBox="0 0 24 24" width="24" height="24" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M15.22 4.97a.75.75 0 0 1 1.06 0l6.5 6.5a.75.75 0 0 1 0 1.06l-6.5 6.5a.749.749 0 0 1-1.275-.326.749.749 0 0 1 .215-.734L21.19 12l-5.97-5.97a.75.75 0 0 1 0-1.06Zm-6.44 0a.75.75 0 0 1 0 1.06L2.81 12l5.97 5.97a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215l-6.5-6.5a.75.75 0 0 1 0-1.06l6.5-6.5a.75.75 0 0 1 1.06 0Z"></path></svg><span class="NavLink-module__title--xw3ok">Code Review</span><span class="NavLink-module__subtitle--qC15H">Manage code changes</span></div></a></li></ul></div></li><li><div class="NavGroup-module__group--T925n"><span class="NavGroup-module__title--TdKyz">APPLICATION SECURITY</span><ul class="NavGroup-module__list--M8eGv"><li><a href="https://github.com/security/advanced-security" data-analytics-event="{"action":"github_advanced_security","tag":"link","context":"platform","location":"navbar","label":"github_advanced_security_link_platform_navbar"}" class="NavLink-module__link--n48VB"><div class="NavLink-module__text--SdWkb"><svg aria-hidden="true" focusable="false" class="octicon octicon-shield-check NavLink-module__icon--h0sw7" viewBox="0 0 24 24" width="24" height="24" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M16.53 9.78a.75.75 0 0 0-1.06-1.06L11 13.19l-1.97-1.97a.75.75 0 0 0-1.06 1.06l2.5 2.5a.75.75 0 0 0 1.06 0l5-5Z"></path><path d="m12.54.637 8.25 2.675A1.75 1.75 0 0 1 22 4.976V10c0 6.19-3.771 10.704-9.401 12.83a1.704 1.704 0 0 1-1.198 0C5.77 20.705 2 16.19 2 10V4.976c0-.758.489-1.43 1.21-1.664L11.46.637a1.748 1.748 0 0 1 1.08 0Zm-.617 1.426-8.25 2.676a.249.249 0 0 0-.173.237V10c0 5.46 3.28 9.483 8.43 11.426a.199.199 0 0 0 .14 0C17.22 19.483 20.5 15.461 20.5 10V4.976a.25.25 0 0 0-.173-.237l-8.25-2.676a.253.253 0 0 0-.154 0Z"></path></svg><span class="NavLink-module__title--xw3ok">GitHub Advanced Security</span><span class="NavLink-module__subtitle--qC15H">Find and fix vulnerabilities</span></div></a></li><li><a href="https://github.com/security/advanced-security/code-security" data-analytics-event="{"action":"code_security","tag":"link","context":"platform","location":"navbar","label":"code_security_link_platform_navbar"}" class="NavLink-module__link--n48VB"><div class="NavLink-module__text--SdWkb"><svg aria-hidden="true" focusable="false" class="octicon octicon-code-square NavLink-module__icon--h0sw7" viewBox="0 0 24 24" width="24" height="24" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M10.3 8.24a.75.75 0 0 1-.04 1.06L7.352 12l2.908 2.7a.75.75 0 1 1-1.02 1.1l-3.5-3.25a.75.75 0 0 1 0-1.1l3.5-3.25a.75.75 0 0 1 1.06.04Zm3.44 1.06a.75.75 0 1 1 1.02-1.1l3.5 3.25a.75.75 0 0 1 0 1.1l-3.5 3.25a.75.75 0 1 1-1.02-1.1l2.908-2.7-2.908-2.7Z"></path><path d="M2 3.75C2 2.784 2.784 2 3.75 2h16.5c.966 0 1.75.784 1.75 1.75v16.5A1.75 1.75 0 0 1 20.25 22H3.75A1.75 1.75 0 0 1 2 20.25Zm1.75-.25a.25.25 0 0 0-.25.25v16.5c0 .138.112.25.25.25h16.5a.25.25 0 0 0 .25-.25V3.75a.25.25 0 0 0-.25-.25Z"></path></svg><span class="NavLink-module__title--xw3ok">Code security</span><span class="NavLink-module__subtitle--qC15H">Secure your code as you build</span></div></a></li><li><a href="https://github.com/security/advanced-security/secret-protection" data-analytics-event="{"action":"secret_protection","tag":"link","context":"platform","location":"navbar","label":"secret_protection_link_platform_navbar"}" class="NavLink-module__link--n48VB"><div class="NavLink-module__text--SdWkb"><svg aria-hidden="true" focusable="false" class="octicon octicon-lock NavLink-module__icon--h0sw7" viewBox="0 0 24 24" width="24" height="24" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M6 9V7.25C6 3.845 8.503 1 12 1s6 2.845 6 6.25V9h.5a2.5 2.5 0 0 1 2.5 2.5v8a2.5 2.5 0 0 1-2.5 2.5h-13A2.5 2.5 0 0 1 3 19.5v-8A2.5 2.5 0 0 1 5.5 9Zm-1.5 2.5v8a1 1 0 0 0 1 1h13a1 1 0 0 0 1-1v-8a1 1 0 0 0-1-1h-13a1 1 0 0 0-1 1Zm3-4.25V9h9V7.25c0-2.67-1.922-4.75-4.5-4.75-2.578 0-4.5 2.08-4.5 4.75Z"></path></svg><span class="NavLink-module__title--xw3ok">Secret protection</span><span class="NavLink-module__subtitle--qC15H">Stop leaks before they start</span></div></a></li></ul></div></li><li><div class="NavGroup-module__group--T925n NavGroup-module__hasSeparator--AJeNz"><span class="NavGroup-module__title--TdKyz">EXPLORE</span><ul class="NavGroup-module__list--M8eGv"><li><a href="https://github.com/why-github" data-analytics-event="{"action":"why_github","tag":"link","context":"platform","location":"navbar","label":"why_github_link_platform_navbar"}" class="NavLink-module__link--n48VB"><span class="NavLink-module__title--xw3ok">Why GitHub</span></a></li><li><a href="https://docs.github.com" data-analytics-event="{"action":"documentation","tag":"link","context":"platform","location":"navbar","label":"documentation_link_platform_navbar"}" class="NavLink-module__link--n48VB" target="_blank" rel="noreferrer"><span class="NavLink-module__title--xw3ok">Documentation</span><svg aria-hidden="true" focusable="false" class="octicon octicon-link-external NavLink-module__externalIcon--JurQ9" viewBox="0 0 16 16" width="16" height="16" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M3.75 2h3.5a.75.75 0 0 1 0 1.5h-3.5a.25.25 0 0 0-.25.25v8.5c0 .138.112.25.25.25h8.5a.25.25 0 0 0 .25-.25v-3.5a.75.75 0 0 1 1.5 0v3.5A1.75 1.75 0 0 1 12.25 14h-8.5A1.75 1.75 0 0 1 2 12.25v-8.5C2 2.784 2.784 2 3.75 2Zm6.854-1h4.146a.25.25 0 0 1 .25.25v4.146a.25.25 0 0 1-.427.177L13.03 4.03 9.28 7.78a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042l3.75-3.75-1.543-1.543A.25.25 0 0 1 10.604 1Z"></path></svg></a></li><li><a href="https://github.blog" data-analytics-event="{"action":"blog","tag":"link","context":"platform","location":"navbar","label":"blog_link_platform_navbar"}" class="NavLink-module__link--n48VB" target="_blank" rel="noreferrer"><span class="NavLink-module__title--xw3ok">Blog</span><svg aria-hidden="true" focusable="false" class="octicon octicon-link-external NavLink-module__externalIcon--JurQ9" viewBox="0 0 16 16" width="16" height="16" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M3.75 2h3.5a.75.75 0 0 1 0 1.5h-3.5a.25.25 0 0 0-.25.25v8.5c0 .138.112.25.25.25h8.5a.25.25 0 0 0 .25-.25v-3.5a.75.75 0 0 1 1.5 0v3.5A1.75 1.75 0 0 1 12.25 14h-8.5A1.75 1.75 0 0 1 2 12.25v-8.5C2 2.784 2.784 2 3.75 2Zm6.854-1h4.146a.25.25 0 0 1 .25.25v4.146a.25.25 0 0 1-.427.177L13.03 4.03 9.28 7.78a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042l3.75-3.75-1.543-1.543A.25.25 0 0 1 10.604 1Z"></path></svg></a></li><li><a href="https://github.blog/changelog" data-analytics-event="{"action":"changelog","tag":"link","context":"platform","location":"navbar","label":"changelog_link_platform_navbar"}" class="NavLink-module__link--n48VB" target="_blank" rel="noreferrer"><span class="NavLink-module__title--xw3ok">Changelog</span><svg aria-hidden="true" focusable="false" class="octicon octicon-link-external NavLink-module__externalIcon--JurQ9" viewBox="0 0 16 16" width="16" height="16" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M3.75 2h3.5a.75.75 0 0 1 0 1.5h-3.5a.25.25 0 0 0-.25.25v8.5c0 .138.112.25.25.25h8.5a.25.25 0 0 0 .25-.25v-3.5a.75.75 0 0 1 1.5 0v3.5A1.75 1.75 0 0 1 12.25 14h-8.5A1.75 1.75 0 0 1 2 12.25v-8.5C2 2.784 2.784 2 3.75 2Zm6.854-1h4.146a.25.25 0 0 1 .25.25v4.146a.25.25 0 0 1-.427.177L13.03 4.03 9.28 7.78a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042l3.75-3.75-1.543-1.543A.25.25 0 0 1 10.604 1Z"></path></svg></a></li><li><a href="https://github.com/marketplace" data-analytics-event="{"action":"marketplace","tag":"link","context":"platform","location":"navbar","label":"marketplace_link_platform_navbar"}" class="NavLink-module__link--n48VB"><span class="NavLink-module__title--xw3ok">Marketplace</span></a></li></ul></div></li></ul><div class="NavDropdown-module__trailingLinkContainer--MNB5T"><a href="https://github.com/features" data-analytics-event="{"action":"view_all_features","tag":"link","context":"platform","location":"navbar","label":"view_all_features_link_platform_navbar"}" class="NavLink-module__link--n48VB"><span class="NavLink-module__title--xw3ok">View all features</span><svg aria-hidden="true" focusable="false" class="octicon octicon-chevron-right NavLink-module__arrowIcon--g6Lip" viewBox="0 0 16 16" width="16" height="16" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M6.22 3.22a.75.75 0 0 1 1.06 0l4.25 4.25a.75.75 0 0 1 0 1.06l-4.25 4.25a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042L9.94 8 6.22 4.28a.75.75 0 0 1 0-1.06Z"></path></svg></a></div></div></div></li><li><div class="NavDropdown-module__container--bmXM2 js-details-container js-header-menu-item"><button type="button" class="NavDropdown-module__button--Hq9UR js-details-target" aria-expanded="false">Solutions<svg aria-hidden="true" focusable="false" class="octicon octicon-chevron-right NavDropdown-module__buttonIcon--SR0Ke" viewBox="0 0 16 16" width="16" height="16" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M6.22 3.22a.75.75 0 0 1 1.06 0l4.25 4.25a.75.75 0 0 1 0 1.06l-4.25 4.25a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042L9.94 8 6.22 4.28a.75.75 0 0 1 0-1.06Z"></path></svg></button><div class="NavDropdown-module__dropdown--Ig57Y"><ul class="NavDropdown-module__list--RwSSK"><li><div class="NavGroup-module__group--T925n"><span class="NavGroup-module__title--TdKyz">BY COMPANY SIZE</span><ul class="NavGroup-module__list--M8eGv"><li><a href="https://github.com/enterprise" data-analytics-event="{"action":"enterprises","tag":"link","context":"solutions","location":"navbar","label":"enterprises_link_solutions_navbar"}" class="NavLink-module__link--n48VB"><span class="NavLink-module__title--xw3ok">Enterprises</span></a></li><li><a href="https://github.com/team" data-analytics-event="{"action":"small_and_medium_teams","tag":"link","context":"solutions","location":"navbar","label":"small_and_medium_teams_link_solutions_navbar"}" class="NavLink-module__link--n48VB"><span class="NavLink-module__title--xw3ok">Small and medium teams</span></a></li><li><a href="https://github.com/enterprise/startups" data-analytics-event="{"action":"startups","tag":"link","context":"solutions","location":"navbar","label":"startups_link_solutions_navbar"}" class="NavLink-module__link--n48VB"><span class="NavLink-module__title--xw3ok">Startups</span></a></li><li><a href="https://github.com/solutions/industry/nonprofits" data-analytics-event="{"action":"nonprofits","tag":"link","context":"solutions","location":"navbar","label":"nonprofits_link_solutions_navbar"}" class="NavLink-module__link--n48VB"><span class="NavLink-module__title--xw3ok">Nonprofits</span></a></li></ul></div></li><li><div class="NavGroup-module__group--T925n"><span class="NavGroup-module__title--TdKyz">BY USE CASE</span><ul class="NavGroup-module__list--M8eGv"><li><a href="https://github.com/solutions/use-case/app-modernization" data-analytics-event="{"action":"app_modernization","tag":"link","context":"solutions","location":"navbar","label":"app_modernization_link_solutions_navbar"}" class="NavLink-module__link--n48VB"><span class="NavLink-module__title--xw3ok">App Modernization</span></a></li><li><a href="https://github.com/solutions/use-case/devsecops" data-analytics-event="{"action":"devsecops","tag":"link","context":"solutions","location":"navbar","label":"devsecops_link_solutions_navbar"}" class="NavLink-module__link--n48VB"><span class="NavLink-module__title--xw3ok">DevSecOps</span></a></li><li><a href="https://github.com/solutions/use-case/devops" data-analytics-event="{"action":"devops","tag":"link","context":"solutions","location":"navbar","label":"devops_link_solutions_navbar"}" class="NavLink-module__link--n48VB"><span class="NavLink-module__title--xw3ok">DevOps</span></a></li><li><a href="https://github.com/solutions/use-case/ci-cd" data-analytics-event="{"action":"ci/cd","tag":"link","context":"solutions","location":"navbar","label":"ci/cd_link_solutions_navbar"}" class="NavLink-module__link--n48VB"><span class="NavLink-module__title--xw3ok">CI/CD</span></a></li><li><a href="https://github.com/solutions/use-case" data-analytics-event="{"action":"view_all_use_cases","tag":"link","context":"solutions","location":"navbar","label":"view_all_use_cases_link_solutions_navbar"}" class="NavLink-module__link--n48VB"><span class="NavLink-module__title--xw3ok">View all use cases</span><svg aria-hidden="true" focusable="false" class="octicon octicon-chevron-right NavLink-module__arrowIcon--g6Lip" viewBox="0 0 16 16" width="16" height="16" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M6.22 3.22a.75.75 0 0 1 1.06 0l4.25 4.25a.75.75 0 0 1 0 1.06l-4.25 4.25a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042L9.94 8 6.22 4.28a.75.75 0 0 1 0-1.06Z"></path></svg></a></li></ul></div></li><li><div class="NavGroup-module__group--T925n"><span class="NavGroup-module__title--TdKyz">BY INDUSTRY</span><ul class="NavGroup-module__list--M8eGv"><li><a href="https://github.com/solutions/industry/healthcare" data-analytics-event="{"action":"healthcare","tag":"link","context":"solutions","location":"navbar","label":"healthcare_link_solutions_navbar"}" class="NavLink-module__link--n48VB"><span class="NavLink-module__title--xw3ok">Healthcare</span></a></li><li><a href="https://github.com/solutions/industry/financial-services" data-analytics-event="{"action":"financial_services","tag":"link","context":"solutions","location":"navbar","label":"financial_services_link_solutions_navbar"}" class="NavLink-module__link--n48VB"><span class="NavLink-module__title--xw3ok">Financial services</span></a></li><li><a href="https://github.com/solutions/industry/manufacturing" data-analytics-event="{"action":"manufacturing","tag":"link","context":"solutions","location":"navbar","label":"manufacturing_link_solutions_navbar"}" class="NavLink-module__link--n48VB"><span class="NavLink-module__title--xw3ok">Manufacturing</span></a></li><li><a href="https://github.com/solutions/industry/government" data-analytics-event="{"action":"government","tag":"link","context":"solutions","location":"navbar","label":"government_link_solutions_navbar"}" class="NavLink-module__link--n48VB"><span class="NavLink-module__title--xw3ok">Government</span></a></li><li><a href="https://github.com/solutions/industry" data-analytics-event="{"action":"view_all_industries","tag":"link","context":"solutions","location":"navbar","label":"view_all_industries_link_solutions_navbar"}" class="NavLink-module__link--n48VB"><span class="NavLink-module__title--xw3ok">View all industries</span><svg aria-hidden="true" focusable="false" class="octicon octicon-chevron-right NavLink-module__arrowIcon--g6Lip" viewBox="0 0 16 16" width="16" height="16" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M6.22 3.22a.75.75 0 0 1 1.06 0l4.25 4.25a.75.75 0 0 1 0 1.06l-4.25 4.25a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042L9.94 8 6.22 4.28a.75.75 0 0 1 0-1.06Z"></path></svg></a></li></ul></div></li></ul><div class="NavDropdown-module__trailingLinkContainer--MNB5T"><a href="https://github.com/solutions" data-analytics-event="{"action":"view_all_solutions","tag":"link","context":"solutions","location":"navbar","label":"view_all_solutions_link_solutions_navbar"}" class="NavLink-module__link--n48VB"><span class="NavLink-module__title--xw3ok">View all solutions</span><svg aria-hidden="true" focusable="false" class="octicon octicon-chevron-right NavLink-module__arrowIcon--g6Lip" viewBox="0 0 16 16" width="16" height="16" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M6.22 3.22a.75.75 0 0 1 1.06 0l4.25 4.25a.75.75 0 0 1 0 1.06l-4.25 4.25a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042L9.94 8 6.22 4.28a.75.75 0 0 1 0-1.06Z"></path></svg></a></div></div></div></li><li><div class="NavDropdown-module__container--bmXM2 js-details-container js-header-menu-item"><button type="button" class="NavDropdown-module__button--Hq9UR js-details-target" aria-expanded="false">Resources<svg aria-hidden="true" focusable="false" class="octicon octicon-chevron-right NavDropdown-module__buttonIcon--SR0Ke" viewBox="0 0 16 16" width="16" height="16" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M6.22 3.22a.75.75 0 0 1 1.06 0l4.25 4.25a.75.75 0 0 1 0 1.06l-4.25 4.25a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042L9.94 8 6.22 4.28a.75.75 0 0 1 0-1.06Z"></path></svg></button><div class="NavDropdown-module__dropdown--Ig57Y"><ul class="NavDropdown-module__list--RwSSK"><li><div class="NavGroup-module__group--T925n"><span class="NavGroup-module__title--TdKyz">EXPLORE BY TOPIC</span><ul class="NavGroup-module__list--M8eGv"><li><a href="https://github.com/resources/articles?topic=ai" data-analytics-event="{"action":"ai","tag":"link","context":"resources","location":"navbar","label":"ai_link_resources_navbar"}" class="NavLink-module__link--n48VB"><span class="NavLink-module__title--xw3ok">AI</span></a></li><li><a href="https://github.com/resources/articles?topic=software-development" data-analytics-event="{"action":"software_development","tag":"link","context":"resources","location":"navbar","label":"software_development_link_resources_navbar"}" class="NavLink-module__link--n48VB"><span class="NavLink-module__title--xw3ok">Software Development</span></a></li><li><a href="https://github.com/resources/articles?topic=devops" data-analytics-event="{"action":"devops","tag":"link","context":"resources","location":"navbar","label":"devops_link_resources_navbar"}" class="NavLink-module__link--n48VB"><span class="NavLink-module__title--xw3ok">DevOps</span></a></li><li><a href="https://github.com/resources/articles?topic=security" data-analytics-event="{"action":"security","tag":"link","context":"resources","location":"navbar","label":"security_link_resources_navbar"}" class="NavLink-module__link--n48VB"><span class="NavLink-module__title--xw3ok">Security</span></a></li><li><a href="https://github.com/resources/articles" data-analytics-event="{"action":"view_all_topics","tag":"link","context":"resources","location":"navbar","label":"view_all_topics_link_resources_navbar"}" class="NavLink-module__link--n48VB"><span class="NavLink-module__title--xw3ok">View all topics</span><svg aria-hidden="true" focusable="false" class="octicon octicon-chevron-right NavLink-module__arrowIcon--g6Lip" viewBox="0 0 16 16" width="16" height="16" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M6.22 3.22a.75.75 0 0 1 1.06 0l4.25 4.25a.75.75 0 0 1 0 1.06l-4.25 4.25a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042L9.94 8 6.22 4.28a.75.75 0 0 1 0-1.06Z"></path></svg></a></li></ul></div></li><li><div class="NavGroup-module__group--T925n"><span class="NavGroup-module__title--TdKyz">EXPLORE BY TYPE</span><ul class="NavGroup-module__list--M8eGv"><li><a href="https://github.com/customer-stories" data-analytics-event="{"action":"customer_stories","tag":"link","context":"resources","location":"navbar","label":"customer_stories_link_resources_navbar"}" class="NavLink-module__link--n48VB"><span class="NavLink-module__title--xw3ok">Customer stories</span></a></li><li><a href="https://github.com/resources/events" data-analytics-event="{"action":"events__webinars","tag":"link","context":"resources","location":"navbar","label":"events__webinars_link_resources_navbar"}" class="NavLink-module__link--n48VB"><span class="NavLink-module__title--xw3ok">Events & webinars</span></a></li><li><a href="https://github.com/resources/whitepapers" data-analytics-event="{"action":"ebooks__reports","tag":"link","context":"resources","location":"navbar","label":"ebooks__reports_link_resources_navbar"}" class="NavLink-module__link--n48VB"><span class="NavLink-module__title--xw3ok">Ebooks & reports</span></a></li><li><a href="https://github.com/solutions/executive-insights" data-analytics-event="{"action":"business_insights","tag":"link","context":"resources","location":"navbar","label":"business_insights_link_resources_navbar"}" class="NavLink-module__link--n48VB"><span class="NavLink-module__title--xw3ok">Business insights</span></a></li><li><a href="https://skills.github.com" data-analytics-event="{"action":"github_skills","tag":"link","context":"resources","location":"navbar","label":"github_skills_link_resources_navbar"}" class="NavLink-module__link--n48VB" target="_blank" rel="noreferrer"><span class="NavLink-module__title--xw3ok">GitHub Skills</span><svg aria-hidden="true" focusable="false" class="octicon octicon-link-external NavLink-module__externalIcon--JurQ9" viewBox="0 0 16 16" width="16" height="16" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M3.75 2h3.5a.75.75 0 0 1 0 1.5h-3.5a.25.25 0 0 0-.25.25v8.5c0 .138.112.25.25.25h8.5a.25.25 0 0 0 .25-.25v-3.5a.75.75 0 0 1 1.5 0v3.5A1.75 1.75 0 0 1 12.25 14h-8.5A1.75 1.75 0 0 1 2 12.25v-8.5C2 2.784 2.784 2 3.75 2Zm6.854-1h4.146a.25.25 0 0 1 .25.25v4.146a.25.25 0 0 1-.427.177L13.03 4.03 9.28 7.78a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042l3.75-3.75-1.543-1.543A.25.25 0 0 1 10.604 1Z"></path></svg></a></li></ul></div></li><li><div class="NavGroup-module__group--T925n"><span class="NavGroup-module__title--TdKyz">SUPPORT & SERVICES</span><ul class="NavGroup-module__list--M8eGv"><li><a href="https://docs.github.com" data-analytics-event="{"action":"documentation","tag":"link","context":"resources","location":"navbar","label":"documentation_link_resources_navbar"}" class="NavLink-module__link--n48VB" target="_blank" rel="noreferrer"><span class="NavLink-module__title--xw3ok">Documentation</span><svg aria-hidden="true" focusable="false" class="octicon octicon-link-external NavLink-module__externalIcon--JurQ9" viewBox="0 0 16 16" width="16" height="16" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M3.75 2h3.5a.75.75 0 0 1 0 1.5h-3.5a.25.25 0 0 0-.25.25v8.5c0 .138.112.25.25.25h8.5a.25.25 0 0 0 .25-.25v-3.5a.75.75 0 0 1 1.5 0v3.5A1.75 1.75 0 0 1 12.25 14h-8.5A1.75 1.75 0 0 1 2 12.25v-8.5C2 2.784 2.784 2 3.75 2Zm6.854-1h4.146a.25.25 0 0 1 .25.25v4.146a.25.25 0 0 1-.427.177L13.03 4.03 9.28 7.78a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042l3.75-3.75-1.543-1.543A.25.25 0 0 1 10.604 1Z"></path></svg></a></li><li><a href="https://support.github.com" data-analytics-event="{"action":"customer_support","tag":"link","context":"resources","location":"navbar","label":"customer_support_link_resources_navbar"}" class="NavLink-module__link--n48VB" target="_blank" rel="noreferrer"><span class="NavLink-module__title--xw3ok">Customer support</span><svg aria-hidden="true" focusable="false" class="octicon octicon-link-external NavLink-module__externalIcon--JurQ9" viewBox="0 0 16 16" width="16" height="16" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M3.75 2h3.5a.75.75 0 0 1 0 1.5h-3.5a.25.25 0 0 0-.25.25v8.5c0 .138.112.25.25.25h8.5a.25.25 0 0 0 .25-.25v-3.5a.75.75 0 0 1 1.5 0v3.5A1.75 1.75 0 0 1 12.25 14h-8.5A1.75 1.75 0 0 1 2 12.25v-8.5C2 2.784 2.784 2 3.75 2Zm6.854-1h4.146a.25.25 0 0 1 .25.25v4.146a.25.25 0 0 1-.427.177L13.03 4.03 9.28 7.78a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042l3.75-3.75-1.543-1.543A.25.25 0 0 1 10.604 1Z"></path></svg></a></li><li><a href="https://github.com/orgs/community/discussions" data-analytics-event="{"action":"community_forum","tag":"link","context":"resources","location":"navbar","label":"community_forum_link_resources_navbar"}" class="NavLink-module__link--n48VB"><span class="NavLink-module__title--xw3ok">Community forum</span></a></li><li><a href="https://github.com/trust-center" data-analytics-event="{"action":"trust_center","tag":"link","context":"resources","location":"navbar","label":"trust_center_link_resources_navbar"}" class="NavLink-module__link--n48VB"><span class="NavLink-module__title--xw3ok">Trust center</span></a></li><li><a href="https://github.com/partners" data-analytics-event="{"action":"partners","tag":"link","context":"resources","location":"navbar","label":"partners_link_resources_navbar"}" class="NavLink-module__link--n48VB"><span class="NavLink-module__title--xw3ok">Partners</span></a></li></ul></div></li></ul></div></div></li><li><div class="NavDropdown-module__container--bmXM2 js-details-container js-header-menu-item"><button type="button" class="NavDropdown-module__button--Hq9UR js-details-target" aria-expanded="false">Open Source<svg aria-hidden="true" focusable="false" class="octicon octicon-chevron-right NavDropdown-module__buttonIcon--SR0Ke" viewBox="0 0 16 16" width="16" height="16" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M6.22 3.22a.75.75 0 0 1 1.06 0l4.25 4.25a.75.75 0 0 1 0 1.06l-4.25 4.25a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042L9.94 8 6.22 4.28a.75.75 0 0 1 0-1.06Z"></path></svg></button><div class="NavDropdown-module__dropdown--Ig57Y"><ul class="NavDropdown-module__list--RwSSK"><li><div class="NavGroup-module__group--T925n"><span class="NavGroup-module__title--TdKyz">COMMUNITY</span><ul class="NavGroup-module__list--M8eGv"><li><a href="https://github.com/sponsors" data-analytics-event="{"action":"github_sponsors","tag":"link","context":"open_source","location":"navbar","label":"github_sponsors_link_open_source_navbar"}" class="NavLink-module__link--n48VB"><div class="NavLink-module__text--SdWkb"><svg aria-hidden="true" focusable="false" class="octicon octicon-sponsor-tiers NavLink-module__icon--h0sw7" viewBox="0 0 24 24" width="24" height="24" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M16.004 1.25C18.311 1.25 20 3.128 20 5.75c0 2.292-1.23 4.464-3.295 6.485-.481.47-.98.909-1.482 1.31l.265 1.32 1.375 7.5a.75.75 0 0 1-.982.844l-3.512-1.207a.75.75 0 0 0-.488 0L8.37 23.209a.75.75 0 0 1-.982-.844l1.378-7.512.261-1.309c-.5-.4-1-.838-1.481-1.31C5.479 10.215 4.25 8.043 4.25 5.75c0-2.622 1.689-4.5 3.996-4.5 1.55 0 2.947.752 3.832 1.967l.047.067.047-.067a4.726 4.726 0 0 1 3.612-1.962l.22-.005ZM13.89 14.531c-.418.285-.828.542-1.218.77l-.18.103a.75.75 0 0 1-.734 0l-.071-.04-.46-.272c-.282-.173-.573-.36-.868-.562l-.121.605-1.145 6.239 2.3-.79a2.248 2.248 0 0 1 1.284-.054l.18.053 2.299.79-1.141-6.226-.125-.616ZM16.004 2.75c-1.464 0-2.731.983-3.159 2.459-.209.721-1.231.721-1.44 0-.428-1.476-1.695-2.459-3.16-2.459-1.44 0-2.495 1.173-2.495 3 0 1.811 1.039 3.647 2.844 5.412a19.624 19.624 0 0 0 3.734 2.84l-.019-.011-.184-.111.147-.088a19.81 19.81 0 0 0 3.015-2.278l.37-.352C17.46 9.397 18.5 7.561 18.5 5.75c0-1.827-1.055-3-2.496-3Z"></path></svg><span class="NavLink-module__title--xw3ok">GitHub Sponsors</span><span class="NavLink-module__subtitle--qC15H">Fund open source developers</span></div></a></li></ul></div></li><li><div class="NavGroup-module__group--T925n"><span class="NavGroup-module__title--TdKyz">PROGRAMS</span><ul class="NavGroup-module__list--M8eGv"><li><a href="https://securitylab.github.com" data-analytics-event="{"action":"security_lab","tag":"link","context":"open_source","location":"navbar","label":"security_lab_link_open_source_navbar"}" class="NavLink-module__link--n48VB" target="_blank" rel="noreferrer"><span class="NavLink-module__title--xw3ok">Security Lab</span><svg aria-hidden="true" focusable="false" class="octicon octicon-link-external NavLink-module__externalIcon--JurQ9" viewBox="0 0 16 16" width="16" height="16" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M3.75 2h3.5a.75.75 0 0 1 0 1.5h-3.5a.25.25 0 0 0-.25.25v8.5c0 .138.112.25.25.25h8.5a.25.25 0 0 0 .25-.25v-3.5a.75.75 0 0 1 1.5 0v3.5A1.75 1.75 0 0 1 12.25 14h-8.5A1.75 1.75 0 0 1 2 12.25v-8.5C2 2.784 2.784 2 3.75 2Zm6.854-1h4.146a.25.25 0 0 1 .25.25v4.146a.25.25 0 0 1-.427.177L13.03 4.03 9.28 7.78a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042l3.75-3.75-1.543-1.543A.25.25 0 0 1 10.604 1Z"></path></svg></a></li><li><a href="https://maintainers.github.com" data-analytics-event="{"action":"maintainer_community","tag":"link","context":"open_source","location":"navbar","label":"maintainer_community_link_open_source_navbar"}" class="NavLink-module__link--n48VB" target="_blank" rel="noreferrer"><span class="NavLink-module__title--xw3ok">Maintainer Community</span><svg aria-hidden="true" focusable="false" class="octicon octicon-link-external NavLink-module__externalIcon--JurQ9" viewBox="0 0 16 16" width="16" height="16" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M3.75 2h3.5a.75.75 0 0 1 0 1.5h-3.5a.25.25 0 0 0-.25.25v8.5c0 .138.112.25.25.25h8.5a.25.25 0 0 0 .25-.25v-3.5a.75.75 0 0 1 1.5 0v3.5A1.75 1.75 0 0 1 12.25 14h-8.5A1.75 1.75 0 0 1 2 12.25v-8.5C2 2.784 2.784 2 3.75 2Zm6.854-1h4.146a.25.25 0 0 1 .25.25v4.146a.25.25 0 0 1-.427.177L13.03 4.03 9.28 7.78a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042l3.75-3.75-1.543-1.543A.25.25 0 0 1 10.604 1Z"></path></svg></a></li><li><a href="https://github.com/accelerator" data-analytics-event="{"action":"accelerator","tag":"link","context":"open_source","location":"navbar","label":"accelerator_link_open_source_navbar"}" class="NavLink-module__link--n48VB"><span class="NavLink-module__title--xw3ok">Accelerator</span></a></li><li><a href="https://archiveprogram.github.com" data-analytics-event="{"action":"archive_program","tag":"link","context":"open_source","location":"navbar","label":"archive_program_link_open_source_navbar"}" class="NavLink-module__link--n48VB" target="_blank" rel="noreferrer"><span class="NavLink-module__title--xw3ok">Archive Program</span><svg aria-hidden="true" focusable="false" class="octicon octicon-link-external NavLink-module__externalIcon--JurQ9" viewBox="0 0 16 16" width="16" height="16" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M3.75 2h3.5a.75.75 0 0 1 0 1.5h-3.5a.25.25 0 0 0-.25.25v8.5c0 .138.112.25.25.25h8.5a.25.25 0 0 0 .25-.25v-3.5a.75.75 0 0 1 1.5 0v3.5A1.75 1.75 0 0 1 12.25 14h-8.5A1.75 1.75 0 0 1 2 12.25v-8.5C2 2.784 2.784 2 3.75 2Zm6.854-1h4.146a.25.25 0 0 1 .25.25v4.146a.25.25 0 0 1-.427.177L13.03 4.03 9.28 7.78a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042l3.75-3.75-1.543-1.543A.25.25 0 0 1 10.604 1Z"></path></svg></a></li></ul></div></li><li><div class="NavGroup-module__group--T925n"><span class="NavGroup-module__title--TdKyz">REPOSITORIES</span><ul class="NavGroup-module__list--M8eGv"><li><a href="https://github.com/topics" data-analytics-event="{"action":"topics","tag":"link","context":"open_source","location":"navbar","label":"topics_link_open_source_navbar"}" class="NavLink-module__link--n48VB"><span class="NavLink-module__title--xw3ok">Topics</span></a></li><li><a href="https://github.com/trending" data-analytics-event="{"action":"trending","tag":"link","context":"open_source","location":"navbar","label":"trending_link_open_source_navbar"}" class="NavLink-module__link--n48VB"><span class="NavLink-module__title--xw3ok">Trending</span></a></li><li><a href="https://github.com/collections" data-analytics-event="{"action":"collections","tag":"link","context":"open_source","location":"navbar","label":"collections_link_open_source_navbar"}" class="NavLink-module__link--n48VB"><span class="NavLink-module__title--xw3ok">Collections</span></a></li></ul></div></li></ul></div></div></li><li><div class="NavDropdown-module__container--bmXM2 js-details-container js-header-menu-item"><button type="button" class="NavDropdown-module__button--Hq9UR js-details-target" aria-expanded="false">Enterprise<svg aria-hidden="true" focusable="false" class="octicon octicon-chevron-right NavDropdown-module__buttonIcon--SR0Ke" viewBox="0 0 16 16" width="16" height="16" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M6.22 3.22a.75.75 0 0 1 1.06 0l4.25 4.25a.75.75 0 0 1 0 1.06l-4.25 4.25a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042L9.94 8 6.22 4.28a.75.75 0 0 1 0-1.06Z"></path></svg></button><div class="NavDropdown-module__dropdown--Ig57Y"><ul class="NavDropdown-module__list--RwSSK"><li><div class="NavGroup-module__group--T925n"><span class="NavGroup-module__title--TdKyz">ENTERPRISE SOLUTIONS</span><ul class="NavGroup-module__list--M8eGv"><li><a href="https://github.com/enterprise" data-analytics-event="{"action":"enterprise_platform","tag":"link","context":"enterprise","location":"navbar","label":"enterprise_platform_link_enterprise_navbar"}" class="NavLink-module__link--n48VB"><div class="NavLink-module__text--SdWkb"><svg aria-hidden="true" focusable="false" class="octicon octicon-stack NavLink-module__icon--h0sw7" viewBox="0 0 24 24" width="24" height="24" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M11.063 1.456a1.749 1.749 0 0 1 1.874 0l8.383 5.316a1.751 1.751 0 0 1 0 2.956l-8.383 5.316a1.749 1.749 0 0 1-1.874 0L2.68 9.728a1.751 1.751 0 0 1 0-2.956Zm1.071 1.267a.25.25 0 0 0-.268 0L3.483 8.039a.25.25 0 0 0 0 .422l8.383 5.316a.25.25 0 0 0 .268 0l8.383-5.316a.25.25 0 0 0 0-.422Z"></path><path d="M1.867 12.324a.75.75 0 0 1 1.035-.232l8.964 5.685a.25.25 0 0 0 .268 0l8.964-5.685a.75.75 0 0 1 .804 1.267l-8.965 5.685a1.749 1.749 0 0 1-1.874 0l-8.965-5.685a.75.75 0 0 1-.231-1.035Z"></path><path d="M1.867 16.324a.75.75 0 0 1 1.035-.232l8.964 5.685a.25.25 0 0 0 .268 0l8.964-5.685a.75.75 0 0 1 .804 1.267l-8.965 5.685a1.749 1.749 0 0 1-1.874 0l-8.965-5.685a.75.75 0 0 1-.231-1.035Z"></path></svg><span class="NavLink-module__title--xw3ok">Enterprise platform</span><span class="NavLink-module__subtitle--qC15H">AI-powered developer platform</span></div></a></li></ul></div></li><li><div class="NavGroup-module__group--T925n"><span class="NavGroup-module__title--TdKyz">AVAILABLE ADD-ONS</span><ul class="NavGroup-module__list--M8eGv"><li><a href="https://github.com/security/advanced-security" data-analytics-event="{"action":"github_advanced_security","tag":"link","context":"enterprise","location":"navbar","label":"github_advanced_security_link_enterprise_navbar"}" class="NavLink-module__link--n48VB"><div class="NavLink-module__text--SdWkb"><svg aria-hidden="true" focusable="false" class="octicon octicon-shield-check NavLink-module__icon--h0sw7" viewBox="0 0 24 24" width="24" height="24" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M16.53 9.78a.75.75 0 0 0-1.06-1.06L11 13.19l-1.97-1.97a.75.75 0 0 0-1.06 1.06l2.5 2.5a.75.75 0 0 0 1.06 0l5-5Z"></path><path d="m12.54.637 8.25 2.675A1.75 1.75 0 0 1 22 4.976V10c0 6.19-3.771 10.704-9.401 12.83a1.704 1.704 0 0 1-1.198 0C5.77 20.705 2 16.19 2 10V4.976c0-.758.489-1.43 1.21-1.664L11.46.637a1.748 1.748 0 0 1 1.08 0Zm-.617 1.426-8.25 2.676a.249.249 0 0 0-.173.237V10c0 5.46 3.28 9.483 8.43 11.426a.199.199 0 0 0 .14 0C17.22 19.483 20.5 15.461 20.5 10V4.976a.25.25 0 0 0-.173-.237l-8.25-2.676a.253.253 0 0 0-.154 0Z"></path></svg><span class="NavLink-module__title--xw3ok">GitHub Advanced Security</span><span class="NavLink-module__subtitle--qC15H">Enterprise-grade security features</span></div></a></li><li><a href="https://github.com/features/copilot/copilot-business" data-analytics-event="{"action":"copilot_for_business","tag":"link","context":"enterprise","location":"navbar","label":"copilot_for_business_link_enterprise_navbar"}" class="NavLink-module__link--n48VB"><div class="NavLink-module__text--SdWkb"><svg aria-hidden="true" focusable="false" class="octicon octicon-copilot NavLink-module__icon--h0sw7" viewBox="0 0 24 24" width="24" height="24" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M23.922 16.992c-.861 1.495-5.859 5.023-11.922 5.023-6.063 0-11.061-3.528-11.922-5.023A.641.641 0 0 1 0 16.736v-2.869a.841.841 0 0 1 .053-.22c.372-.935 1.347-2.292 2.605-2.656.167-.429.414-1.055.644-1.517a10.195 10.195 0 0 1-.052-1.086c0-1.331.282-2.499 1.132-3.368.397-.406.89-.717 1.474-.952 1.399-1.136 3.392-2.093 6.122-2.093 2.731 0 4.767.957 6.166 2.093.584.235 1.077.546 1.474.952.85.869 1.132 2.037 1.132 3.368 0 .368-.014.733-.052 1.086.23.462.477 1.088.644 1.517 1.258.364 2.233 1.721 2.605 2.656a.832.832 0 0 1 .053.22v2.869a.641.641 0 0 1-.078.256ZM12.172 11h-.344a4.323 4.323 0 0 1-.355.508C10.703 12.455 9.555 13 7.965 13c-1.725 0-2.989-.359-3.782-1.259a2.005 2.005 0 0 1-.085-.104L4 11.741v6.585c1.435.779 4.514 2.179 8 2.179 3.486 0 6.565-1.4 8-2.179v-6.585l-.098-.104s-.033.045-.085.104c-.793.9-2.057 1.259-3.782 1.259-1.59 0-2.738-.545-3.508-1.492a4.323 4.323 0 0 1-.355-.508h-.016.016Zm.641-2.935c.136 1.057.403 1.913.878 2.497.442.544 1.134.938 2.344.938 1.573 0 2.292-.337 2.657-.751.384-.435.558-1.15.558-2.361 0-1.14-.243-1.847-.705-2.319-.477-.488-1.319-.862-2.824-1.025-1.487-.161-2.192.138-2.533.529-.269.307-.437.808-.438 1.578v.021c0 .265.021.562.063.893Zm-1.626 0c.042-.331.063-.628.063-.894v-.02c-.001-.77-.169-1.271-.438-1.578-.341-.391-1.046-.69-2.533-.529-1.505.163-2.347.537-2.824 1.025-.462.472-.705 1.179-.705 2.319 0 1.211.175 1.926.558 2.361.365.414 1.084.751 2.657.751 1.21 0 1.902-.394 2.344-.938.475-.584.742-1.44.878-2.497Z"></path><path d="M14.5 14.25a1 1 0 0 1 1 1v2a1 1 0 0 1-2 0v-2a1 1 0 0 1 1-1Zm-5 0a1 1 0 0 1 1 1v2a1 1 0 0 1-2 0v-2a1 1 0 0 1 1-1Z"></path></svg><span class="NavLink-module__title--xw3ok">Copilot for Business</span><span class="NavLink-module__subtitle--qC15H">Enterprise-grade AI features</span></div></a></li><li><a href="https://github.com/premium-support" data-analytics-event="{"action":"premium_support","tag":"link","context":"enterprise","location":"navbar","label":"premium_support_link_enterprise_navbar"}" class="NavLink-module__link--n48VB"><div class="NavLink-module__text--SdWkb"><svg aria-hidden="true" focusable="false" class="octicon octicon-comment-discussion NavLink-module__icon--h0sw7" viewBox="0 0 24 24" width="24" height="24" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M1.75 1h12.5c.966 0 1.75.784 1.75 1.75v9.5A1.75 1.75 0 0 1 14.25 14H8.061l-2.574 2.573A1.458 1.458 0 0 1 3 15.543V14H1.75A1.75 1.75 0 0 1 0 12.25v-9.5C0 1.784.784 1 1.75 1ZM1.5 2.75v9.5c0 .138.112.25.25.25h2a.75.75 0 0 1 .75.75v2.19l2.72-2.72a.749.749 0 0 1 .53-.22h6.5a.25.25 0 0 0 .25-.25v-9.5a.25.25 0 0 0-.25-.25H1.75a.25.25 0 0 0-.25.25Z"></path><path d="M22.5 8.75a.25.25 0 0 0-.25-.25h-3.5a.75.75 0 0 1 0-1.5h3.5c.966 0 1.75.784 1.75 1.75v9.5A1.75 1.75 0 0 1 22.25 20H21v1.543a1.457 1.457 0 0 1-2.487 1.03L15.939 20H10.75A1.75 1.75 0 0 1 9 18.25v-1.465a.75.75 0 0 1 1.5 0v1.465c0 .138.112.25.25.25h5.5a.75.75 0 0 1 .53.22l2.72 2.72v-2.19a.75.75 0 0 1 .75-.75h2a.25.25 0 0 0 .25-.25v-9.5Z"></path></svg><span class="NavLink-module__title--xw3ok">Premium Support</span><span class="NavLink-module__subtitle--qC15H">Enterprise-grade 24/7 support</span></div></a></li></ul></div></li></ul></div></div></li><li><a href="https://github.com/pricing" data-analytics-event="{"action":"pricing","tag":"link","context":"pricing","location":"navbar","label":"pricing_link_pricing_navbar"}" class="NavLink-module__link--n48VB MarketingNavigation-module__navLink--U9Uuk"><span class="NavLink-module__title--xw3ok">Pricing</span></a></li></ul></nav><script type="application/json" id="__PRIMER_DATA_:R0:__">{"resolvedServerColorMode":"day"}</script></div>-</react-partial>---- <div class="d-flex flex-column flex-lg-row width-full flex-justify-end flex-lg-items-center text-center mt-3 mt-lg-0 text-lg-left ml-lg-3">----<qbsearch-input class="search-input" data-scope="repo:stipub/stixfonts" data-custom-scopes-path="/search/custom_scopes" data-delete-custom-scopes-csrf="XEQfFStPOseMWpbCTetCgNaPcX04sjx5PgZR7ugnNpF5VqA0zOERZrM09DmiY5DdsWdud0IvfkEBxWPs3eYjVA" data-max-custom-scopes="10" data-header-redesign-enabled="false" data-initial-value="" data-blackbird-suggestions-path="/search/suggestions" data-jump-to-suggestions-path="/_graphql/GetSuggestedNavigationDestinations" data-current-repository="stipub/stixfonts" data-current-org="stipub" data-current-owner="" data-logged-in="false" data-copilot-chat-enabled="false" data-nl-search-enabled="false" data-retain-scroll-position="true">- <div- class="search-input-container search-with-dialog position-relative d-flex flex-row flex-items-center mr-4 rounded"- data-action="click:qbsearch-input#searchInputContainerClicked"- >- <button- type="button"- class="header-search-button placeholder input-button form-control d-flex flex-1 flex-self-stretch flex-items-center no-wrap width-full py-0 pl-2 pr-0 text-left border-0 box-shadow-none"- data-target="qbsearch-input.inputButton"- aria-label="Search or jump to…"- aria-haspopup="dialog"- placeholder="Search or jump to..."- data-hotkey=s,/- autocapitalize="off"- data-analytics-event="{"location":"navbar","action":"searchbar","context":"global","tag":"input","label":"searchbar_input_global_navbar"}"- data-action="click:qbsearch-input#handleExpand"- >- <div class="mr-2 color-fg-muted">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-search">- <path d="M10.68 11.74a6 6 0 0 1-7.922-8.982 6 6 0 0 1 8.982 7.922l3.04 3.04a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215ZM11.5 7a4.499 4.499 0 1 0-8.997 0A4.499 4.499 0 0 0 11.5 7Z"></path>-</svg>- </div>- <span class="flex-1" data-target="qbsearch-input.inputButtonText">Search or jump to...</span>- <div class="d-flex" data-target="qbsearch-input.hotkeyIndicator">- <svg xmlns="http://www.w3.org/2000/svg" width="22" height="20" aria-hidden="true" class="mr-1"><path fill="none" stroke="#979A9C" opacity=".4" d="M3.5.5h12c1.7 0 3 1.3 3 3v13c0 1.7-1.3 3-3 3h-12c-1.7 0-3-1.3-3-3v-13c0-1.7 1.3-3 3-3z"></path><path fill="#979A9C" d="M11.8 6L8 15.1h-.9L10.8 6h1z"></path></svg>- </div>- </button>-- <input type="hidden" name="type" class="js-site-search-type-field">---<div class="Overlay--hidden " data-modal-dialog-overlay>- <modal-dialog data-action="close:qbsearch-input#handleClose cancel:qbsearch-input#handleClose" data-target="qbsearch-input.searchSuggestionsDialog" role="dialog" id="search-suggestions-dialog" aria-modal="true" aria-labelledby="search-suggestions-dialog-header" data-view-component="true" class="Overlay Overlay--width-large Overlay--height-auto">- <h1 id="search-suggestions-dialog-header" class="sr-only">Search code, repositories, users, issues, pull requests...</h1>- <div class="Overlay-body Overlay-body--paddingNone">-- <div data-view-component="true"> <div class="search-suggestions position-fixed width-full color-shadow-large border color-fg-default color-bg-default overflow-hidden d-flex flex-column query-builder-container"- style="border-radius: 12px;"- data-target="qbsearch-input.queryBuilderContainer"- hidden- >- <!-- '"` --><!-- </textarea></xmp> --></option></form><form id="query-builder-test-form" action="" accept-charset="UTF-8" method="get">- <query-builder data-target="qbsearch-input.queryBuilder" id="query-builder-query-builder-test" data-filter-key=":" data-view-component="true" class="QueryBuilder search-query-builder">- <div class="FormControl FormControl--fullWidth">- <label id="query-builder-test-label" for="query-builder-test" class="FormControl-label sr-only">- Search- </label>- <div- class="QueryBuilder-StyledInput width-fit "- data-target="query-builder.styledInput"- >- <span id="query-builder-test-leadingvisual-wrap" class="FormControl-input-leadingVisualWrap QueryBuilder-leadingVisualWrap">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-search FormControl-input-leadingVisual">- <path d="M10.68 11.74a6 6 0 0 1-7.922-8.982 6 6 0 0 1 8.982 7.922l3.04 3.04a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215ZM11.5 7a4.499 4.499 0 1 0-8.997 0A4.499 4.499 0 0 0 11.5 7Z"></path>-</svg>- </span>- <div data-target="query-builder.styledInputContainer" class="QueryBuilder-StyledInputContainer">- <div- aria-hidden="true"- class="QueryBuilder-StyledInputContent"- data-target="query-builder.styledInputContent"- ></div>- <div class="QueryBuilder-InputWrapper">- <div aria-hidden="true" class="QueryBuilder-Sizer" data-target="query-builder.sizer"></div>- <input id="query-builder-test" name="query-builder-test" value="" autocomplete="off" type="text" role="combobox" spellcheck="false" aria-expanded="false" aria-describedby="validation-1cb01cb6-e5bd-46a8-880e-4e95eb5f12d6" data-target="query-builder.input" data-action="- input:query-builder#inputChange- blur:query-builder#inputBlur- keydown:query-builder#inputKeydown- focus:query-builder#inputFocus- " data-view-component="true" class="FormControl-input QueryBuilder-Input FormControl-medium" />- </div>- </div>- <span class="sr-only" id="query-builder-test-clear">Clear</span>- <button role="button" id="query-builder-test-clear-button" aria-labelledby="query-builder-test-clear query-builder-test-label" data-target="query-builder.clearButton" data-action="- click:query-builder#clear- focus:query-builder#clearButtonFocus- blur:query-builder#clearButtonBlur- " variant="small" hidden="hidden" type="button" data-view-component="true" class="Button Button--iconOnly Button--invisible Button--medium mr-1 px-2 py-0 d-flex flex-items-center rounded-1 color-fg-muted"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-x-circle-fill Button-visual">- <path d="M2.343 13.657A8 8 0 1 1 13.658 2.343 8 8 0 0 1 2.343 13.657ZM6.03 4.97a.751.751 0 0 0-1.042.018.751.751 0 0 0-.018 1.042L6.94 8 4.97 9.97a.749.749 0 0 0 .326 1.275.749.749 0 0 0 .734-.215L8 9.06l1.97 1.97a.749.749 0 0 0 1.275-.326.749.749 0 0 0-.215-.734L9.06 8l1.97-1.97a.749.749 0 0 0-.326-1.275.749.749 0 0 0-.734.215L8 6.94Z"></path>-</svg>-</button>-- </div>- <template id="search-icon">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-search">- <path d="M10.68 11.74a6 6 0 0 1-7.922-8.982 6 6 0 0 1 8.982 7.922l3.04 3.04a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215ZM11.5 7a4.499 4.499 0 1 0-8.997 0A4.499 4.499 0 0 0 11.5 7Z"></path>-</svg>-</template>--<template id="code-icon">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-code">- <path d="m11.28 3.22 4.25 4.25a.75.75 0 0 1 0 1.06l-4.25 4.25a.749.749 0 0 1-1.275-.326.749.749 0 0 1 .215-.734L13.94 8l-3.72-3.72a.749.749 0 0 1 .326-1.275.749.749 0 0 1 .734.215Zm-6.56 0a.751.751 0 0 1 1.042.018.751.751 0 0 1 .018 1.042L2.06 8l3.72 3.72a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215L.47 8.53a.75.75 0 0 1 0-1.06Z"></path>-</svg>-</template>--<template id="file-code-icon">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-file-code">- <path d="M4 1.75C4 .784 4.784 0 5.75 0h5.586c.464 0 .909.184 1.237.513l2.914 2.914c.329.328.513.773.513 1.237v8.586A1.75 1.75 0 0 1 14.25 15h-9a.75.75 0 0 1 0-1.5h9a.25.25 0 0 0 .25-.25V6h-2.75A1.75 1.75 0 0 1 10 4.25V1.5H5.75a.25.25 0 0 0-.25.25v2.5a.75.75 0 0 1-1.5 0Zm1.72 4.97a.75.75 0 0 1 1.06 0l2 2a.75.75 0 0 1 0 1.06l-2 2a.749.749 0 0 1-1.275-.326.749.749 0 0 1 .215-.734l1.47-1.47-1.47-1.47a.75.75 0 0 1 0-1.06ZM3.28 7.78 1.81 9.25l1.47 1.47a.751.751 0 0 1-.018 1.042.751.751 0 0 1-1.042.018l-2-2a.75.75 0 0 1 0-1.06l2-2a.751.751 0 0 1 1.042.018.751.751 0 0 1 .018 1.042Zm8.22-6.218V4.25c0 .138.112.25.25.25h2.688l-.011-.013-2.914-2.914-.013-.011Z"></path>-</svg>-</template>--<template id="history-icon">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-history">- <path d="m.427 1.927 1.215 1.215a8.002 8.002 0 1 1-1.6 5.685.75.75 0 1 1 1.493-.154 6.5 6.5 0 1 0 1.18-4.458l1.358 1.358A.25.25 0 0 1 3.896 6H.25A.25.25 0 0 1 0 5.75V2.104a.25.25 0 0 1 .427-.177ZM7.75 4a.75.75 0 0 1 .75.75v2.992l2.028.812a.75.75 0 0 1-.557 1.392l-2.5-1A.751.751 0 0 1 7 8.25v-3.5A.75.75 0 0 1 7.75 4Z"></path>-</svg>-</template>--<template id="repo-icon">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-repo">- <path d="M2 2.5A2.5 2.5 0 0 1 4.5 0h8.75a.75.75 0 0 1 .75.75v12.5a.75.75 0 0 1-.75.75h-2.5a.75.75 0 0 1 0-1.5h1.75v-2h-8a1 1 0 0 0-.714 1.7.75.75 0 1 1-1.072 1.05A2.495 2.495 0 0 1 2 11.5Zm10.5-1h-8a1 1 0 0 0-1 1v6.708A2.486 2.486 0 0 1 4.5 9h8ZM5 12.25a.25.25 0 0 1 .25-.25h3.5a.25.25 0 0 1 .25.25v3.25a.25.25 0 0 1-.4.2l-1.45-1.087a.249.249 0 0 0-.3 0L5.4 15.7a.25.25 0 0 1-.4-.2Z"></path>-</svg>-</template>--<template id="bookmark-icon">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-bookmark">- <path d="M3 2.75C3 1.784 3.784 1 4.75 1h6.5c.966 0 1.75.784 1.75 1.75v11.5a.75.75 0 0 1-1.227.579L8 11.722l-3.773 3.107A.751.751 0 0 1 3 14.25Zm1.75-.25a.25.25 0 0 0-.25.25v9.91l3.023-2.489a.75.75 0 0 1 .954 0l3.023 2.49V2.75a.25.25 0 0 0-.25-.25Z"></path>-</svg>-</template>--<template id="plus-circle-icon">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-plus-circle">- <path d="M8 0a8 8 0 1 1 0 16A8 8 0 0 1 8 0ZM1.5 8a6.5 6.5 0 1 0 13 0 6.5 6.5 0 0 0-13 0Zm7.25-3.25v2.5h2.5a.75.75 0 0 1 0 1.5h-2.5v2.5a.75.75 0 0 1-1.5 0v-2.5h-2.5a.75.75 0 0 1 0-1.5h2.5v-2.5a.75.75 0 0 1 1.5 0Z"></path>-</svg>-</template>--<template id="circle-icon">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-dot-fill">- <path d="M8 4a4 4 0 1 1 0 8 4 4 0 0 1 0-8Z"></path>-</svg>-</template>--<template id="trash-icon">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-trash">- <path d="M11 1.75V3h2.25a.75.75 0 0 1 0 1.5H2.75a.75.75 0 0 1 0-1.5H5V1.75C5 .784 5.784 0 6.75 0h2.5C10.216 0 11 .784 11 1.75ZM4.496 6.675l.66 6.6a.25.25 0 0 0 .249.225h5.19a.25.25 0 0 0 .249-.225l.66-6.6a.75.75 0 0 1 1.492.149l-.66 6.6A1.748 1.748 0 0 1 10.595 15h-5.19a1.75 1.75 0 0 1-1.741-1.575l-.66-6.6a.75.75 0 1 1 1.492-.15ZM6.5 1.75V3h3V1.75a.25.25 0 0 0-.25-.25h-2.5a.25.25 0 0 0-.25.25Z"></path>-</svg>-</template>--<template id="team-icon">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-people">- <path d="M2 5.5a3.5 3.5 0 1 1 5.898 2.549 5.508 5.508 0 0 1 3.034 4.084.75.75 0 1 1-1.482.235 4 4 0 0 0-7.9 0 .75.75 0 0 1-1.482-.236A5.507 5.507 0 0 1 3.102 8.05 3.493 3.493 0 0 1 2 5.5ZM11 4a3.001 3.001 0 0 1 2.22 5.018 5.01 5.01 0 0 1 2.56 3.012.749.749 0 0 1-.885.954.752.752 0 0 1-.549-.514 3.507 3.507 0 0 0-2.522-2.372.75.75 0 0 1-.574-.73v-.352a.75.75 0 0 1 .416-.672A1.5 1.5 0 0 0 11 5.5.75.75 0 0 1 11 4Zm-5.5-.5a2 2 0 1 0-.001 3.999A2 2 0 0 0 5.5 3.5Z"></path>-</svg>-</template>--<template id="project-icon">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-project">- <path d="M1.75 0h12.5C15.216 0 16 .784 16 1.75v12.5A1.75 1.75 0 0 1 14.25 16H1.75A1.75 1.75 0 0 1 0 14.25V1.75C0 .784.784 0 1.75 0ZM1.5 1.75v12.5c0 .138.112.25.25.25h12.5a.25.25 0 0 0 .25-.25V1.75a.25.25 0 0 0-.25-.25H1.75a.25.25 0 0 0-.25.25ZM11.75 3a.75.75 0 0 1 .75.75v7.5a.75.75 0 0 1-1.5 0v-7.5a.75.75 0 0 1 .75-.75Zm-8.25.75a.75.75 0 0 1 1.5 0v5.5a.75.75 0 0 1-1.5 0ZM8 3a.75.75 0 0 1 .75.75v3.5a.75.75 0 0 1-1.5 0v-3.5A.75.75 0 0 1 8 3Z"></path>-</svg>-</template>--<template id="pencil-icon">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-pencil">- <path d="M11.013 1.427a1.75 1.75 0 0 1 2.474 0l1.086 1.086a1.75 1.75 0 0 1 0 2.474l-8.61 8.61c-.21.21-.47.364-.756.445l-3.251.93a.75.75 0 0 1-.927-.928l.929-3.25c.081-.286.235-.547.445-.758l8.61-8.61Zm.176 4.823L9.75 4.81l-6.286 6.287a.253.253 0 0 0-.064.108l-.558 1.953 1.953-.558a.253.253 0 0 0 .108-.064Zm1.238-3.763a.25.25 0 0 0-.354 0L10.811 3.75l1.439 1.44 1.263-1.263a.25.25 0 0 0 0-.354Z"></path>-</svg>-</template>--<template id="copilot-icon">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-copilot">- <path d="M7.998 15.035c-4.562 0-7.873-2.914-7.998-3.749V9.338c.085-.628.677-1.686 1.588-2.065.013-.07.024-.143.036-.218.029-.183.06-.384.126-.612-.201-.508-.254-1.084-.254-1.656 0-.87.128-1.769.693-2.484.579-.733 1.494-1.124 2.724-1.261 1.206-.134 2.262.034 2.944.765.05.053.096.108.139.165.044-.057.094-.112.143-.165.682-.731 1.738-.899 2.944-.765 1.23.137 2.145.528 2.724 1.261.566.715.693 1.614.693 2.484 0 .572-.053 1.148-.254 1.656.066.228.098.429.126.612.012.076.024.148.037.218.924.385 1.522 1.471 1.591 2.095v1.872c0 .766-3.351 3.795-8.002 3.795Zm0-1.485c2.28 0 4.584-1.11 5.002-1.433V7.862l-.023-.116c-.49.21-1.075.291-1.727.291-1.146 0-2.059-.327-2.71-.991A3.222 3.222 0 0 1 8 6.303a3.24 3.24 0 0 1-.544.743c-.65.664-1.563.991-2.71.991-.652 0-1.236-.081-1.727-.291l-.023.116v4.255c.419.323 2.722 1.433 5.002 1.433ZM6.762 2.83c-.193-.206-.637-.413-1.682-.297-1.019.113-1.479.404-1.713.7-.247.312-.369.789-.369 1.554 0 .793.129 1.171.308 1.371.162.181.519.379 1.442.379.853 0 1.339-.235 1.638-.54.315-.322.527-.827.617-1.553.117-.935-.037-1.395-.241-1.614Zm4.155-.297c-1.044-.116-1.488.091-1.681.297-.204.219-.359.679-.242 1.614.091.726.303 1.231.618 1.553.299.305.784.54 1.638.54.922 0 1.28-.198 1.442-.379.179-.2.308-.578.308-1.371 0-.765-.123-1.242-.37-1.554-.233-.296-.693-.587-1.713-.7Z"></path><path d="M6.25 9.037a.75.75 0 0 1 .75.75v1.501a.75.75 0 0 1-1.5 0V9.787a.75.75 0 0 1 .75-.75Zm4.25.75v1.501a.75.75 0 0 1-1.5 0V9.787a.75.75 0 0 1 1.5 0Z"></path>-</svg>-</template>--<template id="copilot-error-icon">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-copilot-error">- <path d="M16 11.24c0 .112-.072.274-.21.467L13 9.688V7.862l-.023-.116c-.49.21-1.075.291-1.727.291-.198 0-.388-.009-.571-.029L6.833 5.226a4.01 4.01 0 0 0 .17-.782c.117-.935-.037-1.395-.241-1.614-.193-.206-.637-.413-1.682-.297-.683.076-1.115.231-1.395.415l-1.257-.91c.579-.564 1.413-.877 2.485-.996 1.206-.134 2.262.034 2.944.765.05.053.096.108.139.165.044-.057.094-.112.143-.165.682-.731 1.738-.899 2.944-.765 1.23.137 2.145.528 2.724 1.261.566.715.693 1.614.693 2.484 0 .572-.053 1.148-.254 1.656.066.228.098.429.126.612.012.076.024.148.037.218.924.385 1.522 1.471 1.591 2.095Zm-5.083-8.707c-1.044-.116-1.488.091-1.681.297-.204.219-.359.679-.242 1.614.091.726.303 1.231.618 1.553.299.305.784.54 1.638.54.922 0 1.28-.198 1.442-.379.179-.2.308-.578.308-1.371 0-.765-.123-1.242-.37-1.554-.233-.296-.693-.587-1.713-.7Zm2.511 11.074c-1.393.776-3.272 1.428-5.43 1.428-4.562 0-7.873-2.914-7.998-3.749V9.338c.085-.628.677-1.686 1.588-2.065.013-.07.024-.143.036-.218.029-.183.06-.384.126-.612-.18-.455-.241-.963-.252-1.475L.31 4.107A.747.747 0 0 1 0 3.509V3.49a.748.748 0 0 1 .625-.73c.156-.026.306.047.435.139l14.667 10.578a.592.592 0 0 1 .227.264.752.752 0 0 1 .046.249v.022a.75.75 0 0 1-1.19.596Zm-1.367-.991L5.635 7.964a5.128 5.128 0 0 1-.889.073c-.652 0-1.236-.081-1.727-.291l-.023.116v4.255c.419.323 2.722 1.433 5.002 1.433 1.539 0 3.089-.505 4.063-.934Z"></path>-</svg>-</template>--<template id="workflow-icon">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-workflow">- <path d="M0 1.75C0 .784.784 0 1.75 0h3.5C6.216 0 7 .784 7 1.75v3.5A1.75 1.75 0 0 1 5.25 7H4v4a1 1 0 0 0 1 1h4v-1.25C9 9.784 9.784 9 10.75 9h3.5c.966 0 1.75.784 1.75 1.75v3.5A1.75 1.75 0 0 1 14.25 16h-3.5A1.75 1.75 0 0 1 9 14.25v-.75H5A2.5 2.5 0 0 1 2.5 11V7h-.75A1.75 1.75 0 0 1 0 5.25Zm1.75-.25a.25.25 0 0 0-.25.25v3.5c0 .138.112.25.25.25h3.5a.25.25 0 0 0 .25-.25v-3.5a.25.25 0 0 0-.25-.25Zm9 9a.25.25 0 0 0-.25.25v3.5c0 .138.112.25.25.25h3.5a.25.25 0 0 0 .25-.25v-3.5a.25.25 0 0 0-.25-.25Z"></path>-</svg>-</template>--<template id="book-icon">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-book">- <path d="M0 1.75A.75.75 0 0 1 .75 1h4.253c1.227 0 2.317.59 3 1.501A3.743 3.743 0 0 1 11.006 1h4.245a.75.75 0 0 1 .75.75v10.5a.75.75 0 0 1-.75.75h-4.507a2.25 2.25 0 0 0-1.591.659l-.622.621a.75.75 0 0 1-1.06 0l-.622-.621A2.25 2.25 0 0 0 5.258 13H.75a.75.75 0 0 1-.75-.75Zm7.251 10.324.004-5.073-.002-2.253A2.25 2.25 0 0 0 5.003 2.5H1.5v9h3.757a3.75 3.75 0 0 1 1.994.574ZM8.755 4.75l-.004 7.322a3.752 3.752 0 0 1 1.992-.572H14.5v-9h-3.495a2.25 2.25 0 0 0-2.25 2.25Z"></path>-</svg>-</template>--<template id="code-review-icon">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-code-review">- <path d="M1.75 1h12.5c.966 0 1.75.784 1.75 1.75v8.5A1.75 1.75 0 0 1 14.25 13H8.061l-2.574 2.573A1.458 1.458 0 0 1 3 14.543V13H1.75A1.75 1.75 0 0 1 0 11.25v-8.5C0 1.784.784 1 1.75 1ZM1.5 2.75v8.5c0 .138.112.25.25.25h2a.75.75 0 0 1 .75.75v2.19l2.72-2.72a.749.749 0 0 1 .53-.22h6.5a.25.25 0 0 0 .25-.25v-8.5a.25.25 0 0 0-.25-.25H1.75a.25.25 0 0 0-.25.25Zm5.28 1.72a.75.75 0 0 1 0 1.06L5.31 7l1.47 1.47a.751.751 0 0 1-.018 1.042.751.751 0 0 1-1.042.018l-2-2a.75.75 0 0 1 0-1.06l2-2a.75.75 0 0 1 1.06 0Zm2.44 0a.75.75 0 0 1 1.06 0l2 2a.75.75 0 0 1 0 1.06l-2 2a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042L10.69 7 9.22 5.53a.75.75 0 0 1 0-1.06Z"></path>-</svg>-</template>--<template id="codespaces-icon">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-codespaces">- <path d="M0 11.25c0-.966.784-1.75 1.75-1.75h12.5c.966 0 1.75.784 1.75 1.75v3A1.75 1.75 0 0 1 14.25 16H1.75A1.75 1.75 0 0 1 0 14.25Zm2-9.5C2 .784 2.784 0 3.75 0h8.5C13.216 0 14 .784 14 1.75v5a1.75 1.75 0 0 1-1.75 1.75h-8.5A1.75 1.75 0 0 1 2 6.75Zm1.75-.25a.25.25 0 0 0-.25.25v5c0 .138.112.25.25.25h8.5a.25.25 0 0 0 .25-.25v-5a.25.25 0 0 0-.25-.25Zm-2 9.5a.25.25 0 0 0-.25.25v3c0 .138.112.25.25.25h12.5a.25.25 0 0 0 .25-.25v-3a.25.25 0 0 0-.25-.25Z"></path><path d="M7 12.75a.75.75 0 0 1 .75-.75h4.5a.75.75 0 0 1 0 1.5h-4.5a.75.75 0 0 1-.75-.75Zm-4 0a.75.75 0 0 1 .75-.75h.5a.75.75 0 0 1 0 1.5h-.5a.75.75 0 0 1-.75-.75Z"></path>-</svg>-</template>--<template id="comment-icon">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-comment">- <path d="M1 2.75C1 1.784 1.784 1 2.75 1h10.5c.966 0 1.75.784 1.75 1.75v7.5A1.75 1.75 0 0 1 13.25 12H9.06l-2.573 2.573A1.458 1.458 0 0 1 4 13.543V12H2.75A1.75 1.75 0 0 1 1 10.25Zm1.75-.25a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h2a.75.75 0 0 1 .75.75v2.19l2.72-2.72a.749.749 0 0 1 .53-.22h4.5a.25.25 0 0 0 .25-.25v-7.5a.25.25 0 0 0-.25-.25Z"></path>-</svg>-</template>--<template id="comment-discussion-icon">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-comment-discussion">- <path d="M1.75 1h8.5c.966 0 1.75.784 1.75 1.75v5.5A1.75 1.75 0 0 1 10.25 10H7.061l-2.574 2.573A1.458 1.458 0 0 1 2 11.543V10h-.25A1.75 1.75 0 0 1 0 8.25v-5.5C0 1.784.784 1 1.75 1ZM1.5 2.75v5.5c0 .138.112.25.25.25h1a.75.75 0 0 1 .75.75v2.19l2.72-2.72a.749.749 0 0 1 .53-.22h3.5a.25.25 0 0 0 .25-.25v-5.5a.25.25 0 0 0-.25-.25h-8.5a.25.25 0 0 0-.25.25Zm13 2a.25.25 0 0 0-.25-.25h-.5a.75.75 0 0 1 0-1.5h.5c.966 0 1.75.784 1.75 1.75v5.5A1.75 1.75 0 0 1 14.25 12H14v1.543a1.458 1.458 0 0 1-2.487 1.03L9.22 12.28a.749.749 0 0 1 .326-1.275.749.749 0 0 1 .734.215l2.22 2.22v-2.19a.75.75 0 0 1 .75-.75h1a.25.25 0 0 0 .25-.25Z"></path>-</svg>-</template>--<template id="organization-icon">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-organization">- <path d="M1.75 16A1.75 1.75 0 0 1 0 14.25V1.75C0 .784.784 0 1.75 0h8.5C11.216 0 12 .784 12 1.75v12.5c0 .085-.006.168-.018.25h2.268a.25.25 0 0 0 .25-.25V8.285a.25.25 0 0 0-.111-.208l-1.055-.703a.749.749 0 1 1 .832-1.248l1.055.703c.487.325.779.871.779 1.456v5.965A1.75 1.75 0 0 1 14.25 16h-3.5a.766.766 0 0 1-.197-.026c-.099.017-.2.026-.303.026h-3a.75.75 0 0 1-.75-.75V14h-1v1.25a.75.75 0 0 1-.75.75Zm-.25-1.75c0 .138.112.25.25.25H4v-1.25a.75.75 0 0 1 .75-.75h2.5a.75.75 0 0 1 .75.75v1.25h2.25a.25.25 0 0 0 .25-.25V1.75a.25.25 0 0 0-.25-.25h-8.5a.25.25 0 0 0-.25.25ZM3.75 6h.5a.75.75 0 0 1 0 1.5h-.5a.75.75 0 0 1 0-1.5ZM3 3.75A.75.75 0 0 1 3.75 3h.5a.75.75 0 0 1 0 1.5h-.5A.75.75 0 0 1 3 3.75Zm4 3A.75.75 0 0 1 7.75 6h.5a.75.75 0 0 1 0 1.5h-.5A.75.75 0 0 1 7 6.75ZM7.75 3h.5a.75.75 0 0 1 0 1.5h-.5a.75.75 0 0 1 0-1.5ZM3 9.75A.75.75 0 0 1 3.75 9h.5a.75.75 0 0 1 0 1.5h-.5A.75.75 0 0 1 3 9.75ZM7.75 9h.5a.75.75 0 0 1 0 1.5h-.5a.75.75 0 0 1 0-1.5Z"></path>-</svg>-</template>--<template id="rocket-icon">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-rocket">- <path d="M14.064 0h.186C15.216 0 16 .784 16 1.75v.186a8.752 8.752 0 0 1-2.564 6.186l-.458.459c-.314.314-.641.616-.979.904v3.207c0 .608-.315 1.172-.833 1.49l-2.774 1.707a.749.749 0 0 1-1.11-.418l-.954-3.102a1.214 1.214 0 0 1-.145-.125L3.754 9.816a1.218 1.218 0 0 1-.124-.145L.528 8.717a.749.749 0 0 1-.418-1.11l1.71-2.774A1.748 1.748 0 0 1 3.31 4h3.204c.288-.338.59-.665.904-.979l.459-.458A8.749 8.749 0 0 1 14.064 0ZM8.938 3.623h-.002l-.458.458c-.76.76-1.437 1.598-2.02 2.5l-1.5 2.317 2.143 2.143 2.317-1.5c.902-.583 1.74-1.26 2.499-2.02l.459-.458a7.25 7.25 0 0 0 2.123-5.127V1.75a.25.25 0 0 0-.25-.25h-.186a7.249 7.249 0 0 0-5.125 2.123ZM3.56 14.56c-.732.732-2.334 1.045-3.005 1.148a.234.234 0 0 1-.201-.064.234.234 0 0 1-.064-.201c.103-.671.416-2.273 1.15-3.003a1.502 1.502 0 1 1 2.12 2.12Zm6.94-3.935c-.088.06-.177.118-.266.175l-2.35 1.521.548 1.783 1.949-1.2a.25.25 0 0 0 .119-.213ZM3.678 8.116 5.2 5.766c.058-.09.117-.178.176-.266H3.309a.25.25 0 0 0-.213.119l-1.2 1.95ZM12 5a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>-</svg>-</template>--<template id="shield-check-icon">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-shield-check">- <path d="m8.533.133 5.25 1.68A1.75 1.75 0 0 1 15 3.48V7c0 1.566-.32 3.182-1.303 4.682-.983 1.498-2.585 2.813-5.032 3.855a1.697 1.697 0 0 1-1.33 0c-2.447-1.042-4.049-2.357-5.032-3.855C1.32 10.182 1 8.566 1 7V3.48a1.75 1.75 0 0 1 1.217-1.667l5.25-1.68a1.748 1.748 0 0 1 1.066 0Zm-.61 1.429.001.001-5.25 1.68a.251.251 0 0 0-.174.237V7c0 1.36.275 2.666 1.057 3.859.784 1.194 2.121 2.342 4.366 3.298a.196.196 0 0 0 .154 0c2.245-.957 3.582-2.103 4.366-3.297C13.225 9.666 13.5 8.358 13.5 7V3.48a.25.25 0 0 0-.174-.238l-5.25-1.68a.25.25 0 0 0-.153 0ZM11.28 6.28l-3.5 3.5a.75.75 0 0 1-1.06 0l-1.5-1.5a.749.749 0 0 1 .326-1.275.749.749 0 0 1 .734.215l.97.97 2.97-2.97a.751.751 0 0 1 1.042.018.751.751 0 0 1 .018 1.042Z"></path>-</svg>-</template>--<template id="heart-icon">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-heart">- <path d="m8 14.25.345.666a.75.75 0 0 1-.69 0l-.008-.004-.018-.01a7.152 7.152 0 0 1-.31-.17 22.055 22.055 0 0 1-3.434-2.414C2.045 10.731 0 8.35 0 5.5 0 2.836 2.086 1 4.25 1 5.797 1 7.153 1.802 8 3.02 8.847 1.802 10.203 1 11.75 1 13.914 1 16 2.836 16 5.5c0 2.85-2.045 5.231-3.885 6.818a22.066 22.066 0 0 1-3.744 2.584l-.018.01-.006.003h-.002ZM4.25 2.5c-1.336 0-2.75 1.164-2.75 3 0 2.15 1.58 4.144 3.365 5.682A20.58 20.58 0 0 0 8 13.393a20.58 20.58 0 0 0 3.135-2.211C12.92 9.644 14.5 7.65 14.5 5.5c0-1.836-1.414-3-2.75-3-1.373 0-2.609.986-3.029 2.456a.749.749 0 0 1-1.442 0C6.859 3.486 5.623 2.5 4.25 2.5Z"></path>-</svg>-</template>--<template id="server-icon">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-server">- <path d="M1.75 1h12.5c.966 0 1.75.784 1.75 1.75v4c0 .372-.116.717-.314 1 .198.283.314.628.314 1v4a1.75 1.75 0 0 1-1.75 1.75H1.75A1.75 1.75 0 0 1 0 12.75v-4c0-.358.109-.707.314-1a1.739 1.739 0 0 1-.314-1v-4C0 1.784.784 1 1.75 1ZM1.5 2.75v4c0 .138.112.25.25.25h12.5a.25.25 0 0 0 .25-.25v-4a.25.25 0 0 0-.25-.25H1.75a.25.25 0 0 0-.25.25Zm.25 5.75a.25.25 0 0 0-.25.25v4c0 .138.112.25.25.25h12.5a.25.25 0 0 0 .25-.25v-4a.25.25 0 0 0-.25-.25ZM7 4.75A.75.75 0 0 1 7.75 4h4.5a.75.75 0 0 1 0 1.5h-4.5A.75.75 0 0 1 7 4.75ZM7.75 10h4.5a.75.75 0 0 1 0 1.5h-4.5a.75.75 0 0 1 0-1.5ZM3 4.75A.75.75 0 0 1 3.75 4h.5a.75.75 0 0 1 0 1.5h-.5A.75.75 0 0 1 3 4.75ZM3.75 10h.5a.75.75 0 0 1 0 1.5h-.5a.75.75 0 0 1 0-1.5Z"></path>-</svg>-</template>--<template id="globe-icon">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-globe">- <path d="M8 0a8 8 0 1 1 0 16A8 8 0 0 1 8 0ZM5.78 8.75a9.64 9.64 0 0 0 1.363 4.177c.255.426.542.832.857 1.215.245-.296.551-.705.857-1.215A9.64 9.64 0 0 0 10.22 8.75Zm4.44-1.5a9.64 9.64 0 0 0-1.363-4.177c-.307-.51-.612-.919-.857-1.215a9.927 9.927 0 0 0-.857 1.215A9.64 9.64 0 0 0 5.78 7.25Zm-5.944 1.5H1.543a6.507 6.507 0 0 0 4.666 5.5c-.123-.181-.24-.365-.352-.552-.715-1.192-1.437-2.874-1.581-4.948Zm-2.733-1.5h2.733c.144-2.074.866-3.756 1.58-4.948.12-.197.237-.381.353-.552a6.507 6.507 0 0 0-4.666 5.5Zm10.181 1.5c-.144 2.074-.866 3.756-1.58 4.948-.12.197-.237.381-.353.552a6.507 6.507 0 0 0 4.666-5.5Zm2.733-1.5a6.507 6.507 0 0 0-4.666-5.5c.123.181.24.365.353.552.714 1.192 1.436 2.874 1.58 4.948Z"></path>-</svg>-</template>--<template id="issue-opened-icon">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-issue-opened">- <path d="M8 9.5a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3Z"></path><path d="M8 0a8 8 0 1 1 0 16A8 8 0 0 1 8 0ZM1.5 8a6.5 6.5 0 1 0 13 0 6.5 6.5 0 0 0-13 0Z"></path>-</svg>-</template>--<template id="device-mobile-icon">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-device-mobile">- <path d="M3.75 0h8.5C13.216 0 14 .784 14 1.75v12.5A1.75 1.75 0 0 1 12.25 16h-8.5A1.75 1.75 0 0 1 2 14.25V1.75C2 .784 2.784 0 3.75 0ZM3.5 1.75v12.5c0 .138.112.25.25.25h8.5a.25.25 0 0 0 .25-.25V1.75a.25.25 0 0 0-.25-.25h-8.5a.25.25 0 0 0-.25.25ZM8 13a1 1 0 1 1 0-2 1 1 0 0 1 0 2Z"></path>-</svg>-</template>--<template id="package-icon">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-package">- <path d="m8.878.392 5.25 3.045c.54.314.872.89.872 1.514v6.098a1.75 1.75 0 0 1-.872 1.514l-5.25 3.045a1.75 1.75 0 0 1-1.756 0l-5.25-3.045A1.75 1.75 0 0 1 1 11.049V4.951c0-.624.332-1.201.872-1.514L7.122.392a1.75 1.75 0 0 1 1.756 0ZM7.875 1.69l-4.63 2.685L8 7.133l4.755-2.758-4.63-2.685a.248.248 0 0 0-.25 0ZM2.5 5.677v5.372c0 .09.047.171.125.216l4.625 2.683V8.432Zm6.25 8.271 4.625-2.683a.25.25 0 0 0 .125-.216V5.677L8.75 8.432Z"></path>-</svg>-</template>--<template id="credit-card-icon">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-credit-card">- <path d="M10.75 9a.75.75 0 0 0 0 1.5h1.5a.75.75 0 0 0 0-1.5h-1.5Z"></path><path d="M0 3.75C0 2.784.784 2 1.75 2h12.5c.966 0 1.75.784 1.75 1.75v8.5A1.75 1.75 0 0 1 14.25 14H1.75A1.75 1.75 0 0 1 0 12.25ZM14.5 6.5h-13v5.75c0 .138.112.25.25.25h12.5a.25.25 0 0 0 .25-.25Zm0-2.75a.25.25 0 0 0-.25-.25H1.75a.25.25 0 0 0-.25.25V5h13Z"></path>-</svg>-</template>--<template id="play-icon">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-play">- <path d="M8 0a8 8 0 1 1 0 16A8 8 0 0 1 8 0ZM1.5 8a6.5 6.5 0 1 0 13 0 6.5 6.5 0 0 0-13 0Zm4.879-2.773 4.264 2.559a.25.25 0 0 1 0 .428l-4.264 2.559A.25.25 0 0 1 6 10.559V5.442a.25.25 0 0 1 .379-.215Z"></path>-</svg>-</template>--<template id="gift-icon">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-gift">- <path d="M2 2.75A2.75 2.75 0 0 1 4.75 0c.983 0 1.873.42 2.57 1.232.268.318.497.668.68 1.042.183-.375.411-.725.68-1.044C9.376.42 10.266 0 11.25 0a2.75 2.75 0 0 1 2.45 4h.55c.966 0 1.75.784 1.75 1.75v2c0 .698-.409 1.301-1 1.582v4.918A1.75 1.75 0 0 1 13.25 16H2.75A1.75 1.75 0 0 1 1 14.25V9.332C.409 9.05 0 8.448 0 7.75v-2C0 4.784.784 4 1.75 4h.55c-.192-.375-.3-.8-.3-1.25ZM7.25 9.5H2.5v4.75c0 .138.112.25.25.25h4.5Zm1.5 0v5h4.5a.25.25 0 0 0 .25-.25V9.5Zm0-4V8h5.5a.25.25 0 0 0 .25-.25v-2a.25.25 0 0 0-.25-.25Zm-7 0a.25.25 0 0 0-.25.25v2c0 .138.112.25.25.25h5.5V5.5h-5.5Zm3-4a1.25 1.25 0 0 0 0 2.5h2.309c-.233-.818-.542-1.401-.878-1.793-.43-.502-.915-.707-1.431-.707ZM8.941 4h2.309a1.25 1.25 0 0 0 0-2.5c-.516 0-1 .205-1.43.707-.337.392-.646.975-.879 1.793Z"></path>-</svg>-</template>--<template id="code-square-icon">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-code-square">- <path d="M0 1.75C0 .784.784 0 1.75 0h12.5C15.216 0 16 .784 16 1.75v12.5A1.75 1.75 0 0 1 14.25 16H1.75A1.75 1.75 0 0 1 0 14.25Zm1.75-.25a.25.25 0 0 0-.25.25v12.5c0 .138.112.25.25.25h12.5a.25.25 0 0 0 .25-.25V1.75a.25.25 0 0 0-.25-.25Zm7.47 3.97a.75.75 0 0 1 1.06 0l2 2a.75.75 0 0 1 0 1.06l-2 2a.749.749 0 0 1-1.275-.326.749.749 0 0 1 .215-.734L10.69 8 9.22 6.53a.75.75 0 0 1 0-1.06ZM6.78 6.53 5.31 8l1.47 1.47a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215l-2-2a.75.75 0 0 1 0-1.06l2-2a.751.751 0 0 1 1.042.018.751.751 0 0 1 .018 1.042Z"></path>-</svg>-</template>--<template id="device-desktop-icon">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-device-desktop">- <path d="M14.25 1c.966 0 1.75.784 1.75 1.75v7.5A1.75 1.75 0 0 1 14.25 12h-3.727c.099 1.041.52 1.872 1.292 2.757A.752.752 0 0 1 11.25 16h-6.5a.75.75 0 0 1-.565-1.243c.772-.885 1.192-1.716 1.292-2.757H1.75A1.75 1.75 0 0 1 0 10.25v-7.5C0 1.784.784 1 1.75 1ZM1.75 2.5a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h12.5a.25.25 0 0 0 .25-.25v-7.5a.25.25 0 0 0-.25-.25ZM9.018 12H6.982a5.72 5.72 0 0 1-.765 2.5h3.566a5.72 5.72 0 0 1-.765-2.5Z"></path>-</svg>-</template>-- <div class="position-relative">- <ul- role="listbox"- class="ActionListWrap QueryBuilder-ListWrap"- aria-label="Suggestions"- data-action="- combobox-commit:query-builder#comboboxCommit- mousedown:query-builder#resultsMousedown- "- data-target="query-builder.resultsList"- data-persist-list=false- id="query-builder-test-results"- tabindex="-1"- ></ul>- </div>- <div class="FormControl-inlineValidation" id="validation-1cb01cb6-e5bd-46a8-880e-4e95eb5f12d6" hidden="hidden">- <span class="FormControl-inlineValidation--visual">- <svg aria-hidden="true" height="12" viewBox="0 0 12 12" version="1.1" width="12" data-view-component="true" class="octicon octicon-alert-fill">- <path d="M4.855.708c.5-.896 1.79-.896 2.29 0l4.675 8.351a1.312 1.312 0 0 1-1.146 1.954H1.33A1.313 1.313 0 0 1 .183 9.058ZM7 7V3H5v4Zm-1 3a1 1 0 1 0 0-2 1 1 0 0 0 0 2Z"></path>-</svg>- </span>- <span></span>-</div> </div>- <div data-target="query-builder.screenReaderFeedback" aria-live="polite" aria-atomic="true" class="sr-only"></div>-</query-builder></form>- <div class="d-flex flex-row color-fg-muted px-3 text-small color-bg-default search-feedback-prompt">- <a target="_blank" href="https://docs.github.com/search-github/github-code-search/understanding-github-code-search-syntax" data-view-component="true" class="Link color-fg-accent text-normal ml-2">Search syntax tips</a> <div class="d-flex flex-1"></div>- </div>- </div>-</div>-- </div>-</modal-dialog></div>- </div>- <div data-action="click:qbsearch-input#retract" class="dark-backdrop position-fixed" hidden data-target="qbsearch-input.darkBackdrop"></div>- <div class="color-fg-default">--<dialog-helper>- <dialog data-target="qbsearch-input.feedbackDialog" data-action="close:qbsearch-input#handleDialogClose cancel:qbsearch-input#handleDialogClose" id="feedback-dialog" aria-modal="true" aria-labelledby="feedback-dialog-title" aria-describedby="feedback-dialog-description" data-view-component="true" class="Overlay Overlay-whenNarrow Overlay--size-medium Overlay--motion-scaleFade Overlay--disableScroll">- <div data-view-component="true" class="Overlay-header">- <div class="Overlay-headerContentWrap">- <div class="Overlay-titleWrap">- <h1 class="Overlay-title " id="feedback-dialog-title">- Provide feedback- </h1>-- </div>- <div class="Overlay-actionWrap">- <button data-close-dialog-id="feedback-dialog" aria-label="Close" aria-label="Close" type="button" data-view-component="true" class="close-button Overlay-closeButton"><svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-x">- <path d="M3.72 3.72a.75.75 0 0 1 1.06 0L8 6.94l3.22-3.22a.749.749 0 0 1 1.275.326.749.749 0 0 1-.215.734L9.06 8l3.22 3.22a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215L8 9.06l-3.22 3.22a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042L6.94 8 3.72 4.78a.75.75 0 0 1 0-1.06Z"></path>-</svg></button>- </div>- </div>--</div>- <scrollable-region data-labelled-by="feedback-dialog-title">- <div data-view-component="true" class="Overlay-body"> <!-- '"` --><!-- </textarea></xmp> --></option></form><form id="code-search-feedback-form" data-turbo="false" action="/search/feedback" accept-charset="UTF-8" method="post"><input type="hidden" data-csrf="true" name="authenticity_token" value="cIY024XTzaXNjJYhsuUv9f/p4JC8t4YCaTdu539nhc6ohB3s9JcC249i+B4I7Dw2BJLFijaq67tahomH6INDeQ==" />- <p>We read every piece of feedback, and take your input very seriously.</p>- <textarea name="feedback" class="form-control width-full mb-2" style="height: 120px" id="feedback"></textarea>- <input name="include_email" id="include_email" aria-label="Include my email address so I can be contacted" class="form-control mr-2" type="checkbox">- <label for="include_email" style="font-weight: normal">Include my email address so I can be contacted</label>-</form></div>- </scrollable-region>- <div data-view-component="true" class="Overlay-footer Overlay-footer--alignEnd"> <button data-close-dialog-id="feedback-dialog" type="button" data-view-component="true" class="btn"> Cancel-</button>- <button form="code-search-feedback-form" data-action="click:qbsearch-input#submitFeedback" type="submit" data-view-component="true" class="btn-primary btn"> Submit feedback-</button>-</div>-</dialog></dialog-helper>-- <custom-scopes data-target="qbsearch-input.customScopesManager">--<dialog-helper>- <dialog data-target="custom-scopes.customScopesModalDialog" data-action="close:qbsearch-input#handleDialogClose cancel:qbsearch-input#handleDialogClose" id="custom-scopes-dialog" aria-modal="true" aria-labelledby="custom-scopes-dialog-title" aria-describedby="custom-scopes-dialog-description" data-view-component="true" class="Overlay Overlay-whenNarrow Overlay--size-medium Overlay--motion-scaleFade Overlay--disableScroll">- <div data-view-component="true" class="Overlay-header Overlay-header--divided">- <div class="Overlay-headerContentWrap">- <div class="Overlay-titleWrap">- <h1 class="Overlay-title " id="custom-scopes-dialog-title">- Saved searches- </h1>- <h2 id="custom-scopes-dialog-description" class="Overlay-description">Use saved searches to filter your results more quickly</h2>- </div>- <div class="Overlay-actionWrap">- <button data-close-dialog-id="custom-scopes-dialog" aria-label="Close" aria-label="Close" type="button" data-view-component="true" class="close-button Overlay-closeButton"><svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-x">- <path d="M3.72 3.72a.75.75 0 0 1 1.06 0L8 6.94l3.22-3.22a.749.749 0 0 1 1.275.326.749.749 0 0 1-.215.734L9.06 8l3.22 3.22a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215L8 9.06l-3.22 3.22a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042L6.94 8 3.72 4.78a.75.75 0 0 1 0-1.06Z"></path>-</svg></button>- </div>- </div>--</div>- <scrollable-region data-labelled-by="custom-scopes-dialog-title">- <div data-view-component="true" class="Overlay-body"> <div data-target="custom-scopes.customScopesModalDialogFlash"></div>-- <div hidden class="create-custom-scope-form" data-target="custom-scopes.createCustomScopeForm">- <!-- '"` --><!-- </textarea></xmp> --></option></form><form id="custom-scopes-dialog-form" data-turbo="false" action="/search/custom_scopes" accept-charset="UTF-8" method="post"><input type="hidden" data-csrf="true" name="authenticity_token" value="aiDlvuZPiVe8yNnr0XAw3ytfWHQT/2YIFFKCq+IvRNkSI3ZmbhWQNEGx0koP0YE7cwvqxNXwtoI0Xq4o5NRRgA==" />- <div data-target="custom-scopes.customScopesModalDialogFlash"></div>-- <input type="hidden" id="custom_scope_id" name="custom_scope_id" data-target="custom-scopes.customScopesIdField">-- <div class="form-group">- <label for="custom_scope_name">Name</label>- <auto-check src="/search/custom_scopes/check_name" required>- <input- type="text"- name="custom_scope_name"- id="custom_scope_name"- data-target="custom-scopes.customScopesNameField"- class="form-control"- autocomplete="off"- placeholder="github-ruby"- required- maxlength="50">- <input type="hidden" data-csrf="true" value="KfJwmjRNvH+UMWX5q4WE4ltUerP/aiqFZ2LxCi4iG1q3ENECDs/Cn4cjBKUgEQuUzDk1cV3zjr8cFnsNpV2vOQ==" />- </auto-check>- </div>-- <div class="form-group">- <label for="custom_scope_query">Query</label>- <input- type="text"- name="custom_scope_query"- id="custom_scope_query"- data-target="custom-scopes.customScopesQueryField"- class="form-control"- autocomplete="off"- placeholder="(repo:mona/a OR repo:mona/b) AND lang:python"- required- maxlength="500">- </div>-- <p class="text-small color-fg-muted">- To see all available qualifiers, see our <a class="Link--inTextBlock" href="https://docs.github.com/search-github/github-code-search/understanding-github-code-search-syntax">documentation</a>.- </p>-</form> </div>-- <div data-target="custom-scopes.manageCustomScopesForm">- <div data-target="custom-scopes.list"></div>- </div>--</div>- </scrollable-region>- <div data-view-component="true" class="Overlay-footer Overlay-footer--alignEnd Overlay-footer--divided"> <button data-action="click:custom-scopes#customScopesCancel" type="button" data-view-component="true" class="btn"> Cancel-</button>- <button form="custom-scopes-dialog-form" data-action="click:custom-scopes#customScopesSubmit" data-target="custom-scopes.customScopesSubmitButton" type="submit" data-view-component="true" class="btn-primary btn"> Create saved search-</button>-</div>-</dialog></dialog-helper>- </custom-scopes>- </div>-</qbsearch-input>--- <div class="position-relative HeaderMenu-link-wrap d-lg-inline-block">- <a- href="/login?return_to=https%3A%2F%2Fgithub.com%2Fstipub%2Fstixfonts%2F"- class="HeaderMenu-link HeaderMenu-link--sign-in HeaderMenu-button flex-shrink-0 no-underline d-none d-lg-inline-flex border border-lg-0 rounded px-2 py-1"- style="margin-left: 12px;"- data-hydro-click="{"event_type":"authentication.click","payload":{"location_in_page":"site header menu","repository_id":null,"auth_type":"SIGN_UP","originating_url":"https://github.com/stipub/stixfonts","user_id":null}}" data-hydro-click-hmac="593a19135ddfa1362b376b817f3d4cfb97274702995b6b2018b94233d5572800"- data-analytics-event="{"category":"Marketing nav","action":"click to go to homepage","label":"ref_page:Marketing;ref_cta:Sign in;ref_loc:Header"}"- >- Sign in- </a>- </div>-- <a href="/signup?ref_cta=Sign+up&ref_loc=header+logged+out&ref_page=%2F%3Cuser-name%3E%2F%3Crepo-name%3E&source=header-repo&source_repo=stipub%2Fstixfonts"- class="HeaderMenu-link HeaderMenu-link--sign-up HeaderMenu-button flex-shrink-0 d-flex d-lg-inline-flex no-underline border color-border-default rounded px-2 py-1"- data-hydro-click="{"event_type":"authentication.click","payload":{"location_in_page":"site header menu","repository_id":null,"auth_type":"SIGN_UP","originating_url":"https://github.com/stipub/stixfonts","user_id":null}}" data-hydro-click-hmac="593a19135ddfa1362b376b817f3d4cfb97274702995b6b2018b94233d5572800"- data-analytics-event="{"category":"Sign up","action":"click to sign up for account","label":"ref_page:/<user-name>/<repo-name>;ref_cta:Sign up;ref_loc:header logged out"}"- >- Sign up- </a>-- <div class="AppHeader-appearanceSettings">- <react-partial-anchor>- <button data-target="react-partial-anchor.anchor" id="icon-button-8262939e-46d5-46f5-b06e-7a72ef047e92" aria-labelledby="tooltip-ad461553-cda4-4399-b424-24e7309d17ac" type="button" disabled="disabled" data-view-component="true" class="Button Button--iconOnly Button--invisible Button--medium AppHeader-button HeaderMenu-link border cursor-wait"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-sliders Button-visual">- <path d="M15 2.75a.75.75 0 0 1-.75.75h-4a.75.75 0 0 1 0-1.5h4a.75.75 0 0 1 .75.75Zm-8.5.75v1.25a.75.75 0 0 0 1.5 0v-4a.75.75 0 0 0-1.5 0V2H1.75a.75.75 0 0 0 0 1.5H6.5Zm1.25 5.25a.75.75 0 0 0 0-1.5h-6a.75.75 0 0 0 0 1.5h6ZM15 8a.75.75 0 0 1-.75.75H11.5V10a.75.75 0 1 1-1.5 0V6a.75.75 0 0 1 1.5 0v1.25h2.75A.75.75 0 0 1 15 8Zm-9 5.25v-2a.75.75 0 0 0-1.5 0v1.25H1.75a.75.75 0 0 0 0 1.5H4.5v1.25a.75.75 0 0 0 1.5 0v-2Zm9 0a.75.75 0 0 1-.75.75h-6a.75.75 0 0 1 0-1.5h6a.75.75 0 0 1 .75.75Z"></path>-</svg>-</button><tool-tip id="tooltip-ad461553-cda4-4399-b424-24e7309d17ac" for="icon-button-8262939e-46d5-46f5-b06e-7a72ef047e92" popover="manual" data-direction="s" data-type="label" data-view-component="true" class="sr-only position-absolute">Appearance settings</tool-tip>-- <template data-target="react-partial-anchor.template">- <link crossorigin="anonymous" media="all" rel="stylesheet" href="https://github.githubassets.com/assets/primer-react.53f37102c46fd176a96b.module.css" />-<link crossorigin="anonymous" media="all" rel="stylesheet" href="https://github.githubassets.com/assets/appearance-settings.6c63a6de228d6520804d.module.css" />--<react-partial- partial-name="appearance-settings"- data-ssr="false"- data-attempted-ssr="false"- data-react-profiling="false"->-- <script type="application/json" data-target="react-partial.embeddedData">{"props":{}}</script>- <div data-target="react-partial.reactRoot"></div>-</react-partial>--- </template>- </react-partial-anchor>- </div>-- <button type="button" class="sr-only js-header-menu-focus-trap d-block d-lg-none">Resetting focus</button>- </div>- </div>- </div>- </div>-</header>-- <div hidden="hidden" data-view-component="true" class="js-stale-session-flash stale-session-flash flash flash-warn flash-full">-- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">- <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>-</svg>- <span class="js-stale-session-flash-signed-in" hidden>You signed in with another tab or window. <a class="Link--inTextBlock" href="">Reload</a> to refresh your session.</span>- <span class="js-stale-session-flash-signed-out" hidden>You signed out in another tab or window. <a class="Link--inTextBlock" href="">Reload</a> to refresh your session.</span>- <span class="js-stale-session-flash-switched" hidden>You switched accounts on another tab or window. <a class="Link--inTextBlock" href="">Reload</a> to refresh your session.</span>-- <button id="icon-button-fff931e7-6c71-410b-a1ca-c3c5ed3dcdc7" aria-labelledby="tooltip-c99e5bcd-0247-4382-b7a7-5b4d556d61e5" type="button" data-view-component="true" class="Button Button--iconOnly Button--invisible Button--medium flash-close js-flash-close"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-x Button-visual">- <path d="M3.72 3.72a.75.75 0 0 1 1.06 0L8 6.94l3.22-3.22a.749.749 0 0 1 1.275.326.749.749 0 0 1-.215.734L9.06 8l3.22 3.22a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215L8 9.06l-3.22 3.22a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042L6.94 8 3.72 4.78a.75.75 0 0 1 0-1.06Z"></path>-</svg>-</button><tool-tip id="tooltip-c99e5bcd-0247-4382-b7a7-5b4d556d61e5" for="icon-button-fff931e7-6c71-410b-a1ca-c3c5ed3dcdc7" popover="manual" data-direction="s" data-type="label" data-view-component="true" class="sr-only position-absolute">Dismiss alert</tool-tip>----</div>- </div>-- <div id="start-of-content" class="show-on-focus"></div>--------- <div id="js-flash-container" class="flash-container" data-turbo-replace>----- <template class="js-flash-template">--<div class="flash flash-full {{ className }}">- <div >- <button autofocus class="flash-close js-flash-close" type="button" aria-label="Dismiss this message">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-x">- <path d="M3.72 3.72a.75.75 0 0 1 1.06 0L8 6.94l3.22-3.22a.749.749 0 0 1 1.275.326.749.749 0 0 1-.215.734L9.06 8l3.22 3.22a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215L8 9.06l-3.22 3.22a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042L6.94 8 3.72 4.78a.75.75 0 0 1 0-1.06Z"></path>-</svg>- </button>- <div aria-atomic="true" role="alert" class="js-flash-alert">-- <div>{{ message }}</div>-- </div>- </div>-</div>- </template>-</div>---------- <div- class="application-main "- data-commit-hovercards-enabled- data-discussion-hovercards-enabled- data-issue-and-pr-hovercards-enabled- data-project-hovercards-enabled- >- <div itemscope itemtype="http://schema.org/SoftwareSourceCode" class="">- <main id="js-repo-pjax-container" >------------------- <div id="repository-container-header" class="pt-3 hide-full-screen" style="background-color: var(--page-header-bgColor, var(--color-page-header-bg));" data-turbo-replace>-- <div class="d-flex flex-nowrap flex-justify-end mb-3 px-3 px-lg-5" style="gap: 1rem;">-- <div class="flex-auto min-width-0 width-fit">-- <div class=" d-flex flex-wrap flex-items-center wb-break-word f3 text-normal">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-repo color-fg-muted mr-2">- <path d="M2 2.5A2.5 2.5 0 0 1 4.5 0h8.75a.75.75 0 0 1 .75.75v12.5a.75.75 0 0 1-.75.75h-2.5a.75.75 0 0 1 0-1.5h1.75v-2h-8a1 1 0 0 0-.714 1.7.75.75 0 1 1-1.072 1.05A2.495 2.495 0 0 1 2 11.5Zm10.5-1h-8a1 1 0 0 0-1 1v6.708A2.486 2.486 0 0 1 4.5 9h8ZM5 12.25a.25.25 0 0 1 .25-.25h3.5a.25.25 0 0 1 .25.25v3.25a.25.25 0 0 1-.4.2l-1.45-1.087a.249.249 0 0 0-.3 0L5.4 15.7a.25.25 0 0 1-.4-.2Z"></path>-</svg>-- <span class="author flex-self-stretch" itemprop="author">- <a class="url fn" rel="author" data-hovercard-type="organization" data-hovercard-url="/orgs/stipub/hovercard" data-octo-click="hovercard-link-click" data-octo-dimensions="link_type:self" href="/stipub">- stipub-</a> </span>- <span class="mx-1 flex-self-stretch color-fg-muted">/</span>- <strong itemprop="name" class="mr-2 flex-self-stretch">- <a data-pjax="#repo-content-pjax-container" data-turbo-frame="repo-content-turbo-frame" href="/stipub/stixfonts">stixfonts</a>- </strong>-- <span></span><span class="Label Label--secondary v-align-middle mr-1">Public</span>- </div>--- </div>-- <div id="repository-details-container" class="flex-shrink-0" data-turbo-replace style="max-width: 70%;">- <ul class="pagehead-actions flex-shrink-0 d-none d-md-inline" style="padding: 2px 0;">---- <li>- <a href="/login?return_to=%2Fstipub%2Fstixfonts" rel="nofollow" id="repository-details-watch-button" data-hydro-click="{"event_type":"authentication.click","payload":{"location_in_page":"notification subscription menu watch","repository_id":null,"auth_type":"LOG_IN","originating_url":"https://github.com/stipub/stixfonts","user_id":null}}" data-hydro-click-hmac="d48beb239e463aa3111864a1fedf4b6edb178af60b3ecc598f45410ff2683220" aria-label="You must be signed in to change notification settings" data-view-component="true" class="btn-sm btn"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-bell mr-2">- <path d="M8 16a2 2 0 0 0 1.985-1.75c.017-.137-.097-.25-.235-.25h-3.5c-.138 0-.252.113-.235.25A2 2 0 0 0 8 16ZM3 5a5 5 0 0 1 10 0v2.947c0 .05.015.098.042.139l1.703 2.555A1.519 1.519 0 0 1 13.482 13H2.518a1.516 1.516 0 0 1-1.263-2.36l1.703-2.554A.255.255 0 0 0 3 7.947Zm5-3.5A3.5 3.5 0 0 0 4.5 5v2.947c0 .346-.102.683-.294.97l-1.703 2.556a.017.017 0 0 0-.003.01l.001.006c0 .002.002.004.004.006l.006.004.007.001h10.964l.007-.001.006-.004.004-.006.001-.007a.017.017 0 0 0-.003-.01l-1.703-2.554a1.745 1.745 0 0 1-.294-.97V5A3.5 3.5 0 0 0 8 1.5Z"></path>-</svg>Notifications-</a> <tool-tip id="tooltip-dff6d2e1-3db0-43c3-ac5d-77ff224a1eec" for="repository-details-watch-button" popover="manual" data-direction="s" data-type="description" data-view-component="true" class="sr-only position-absolute">You must be signed in to change notification settings</tool-tip>-- </li>-- <li>- <a icon="repo-forked" id="fork-button" href="/login?return_to=%2Fstipub%2Fstixfonts" rel="nofollow" data-hydro-click="{"event_type":"authentication.click","payload":{"location_in_page":"repo details fork button","repository_id":128424630,"auth_type":"LOG_IN","originating_url":"https://github.com/stipub/stixfonts","user_id":null}}" data-hydro-click-hmac="60fac73f0cc62cc4a564058f209eea7dc3f019efc0d143c37cc8d726ccb82e31" data-view-component="true" class="btn-sm btn"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-repo-forked mr-2">- <path d="M5 5.372v.878c0 .414.336.75.75.75h4.5a.75.75 0 0 0 .75-.75v-.878a2.25 2.25 0 1 1 1.5 0v.878a2.25 2.25 0 0 1-2.25 2.25h-1.5v2.128a2.251 2.251 0 1 1-1.5 0V8.5h-1.5A2.25 2.25 0 0 1 3.5 6.25v-.878a2.25 2.25 0 1 1 1.5 0ZM5 3.25a.75.75 0 1 0-1.5 0 .75.75 0 0 0 1.5 0Zm6.75.75a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5Zm-3 8.75a.75.75 0 1 0-1.5 0 .75.75 0 0 0 1.5 0Z"></path>-</svg>Fork- <span id="repo-network-counter" data-pjax-replace="true" data-turbo-replace="true" title="49" data-view-component="true" class="Counter">49</span>-</a>- </li>-- <li>- <div data-view-component="true" class="BtnGroup d-flex">- <a href="/login?return_to=%2Fstipub%2Fstixfonts" rel="nofollow" data-hydro-click="{"event_type":"authentication.click","payload":{"location_in_page":"star button","repository_id":128424630,"auth_type":"LOG_IN","originating_url":"https://github.com/stipub/stixfonts","user_id":null}}" data-hydro-click-hmac="73cc4c3693e1d8b85b3dd53476858eb355552f849acb45454336174300e68e98" aria-label="You must be signed in to star a repository" data-view-component="true" class="tooltipped tooltipped-sw btn-sm btn"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-star v-align-text-bottom d-inline-block mr-2">- <path d="M8 .25a.75.75 0 0 1 .673.418l1.882 3.815 4.21.612a.75.75 0 0 1 .416 1.279l-3.046 2.97.719 4.192a.751.751 0 0 1-1.088.791L8 12.347l-3.766 1.98a.75.75 0 0 1-1.088-.79l.72-4.194L.818 6.374a.75.75 0 0 1 .416-1.28l4.21-.611L7.327.668A.75.75 0 0 1 8 .25Zm0 2.445L6.615 5.5a.75.75 0 0 1-.564.41l-3.097.45 2.24 2.184a.75.75 0 0 1 .216.664l-.528 3.084 2.769-1.456a.75.75 0 0 1 .698 0l2.77 1.456-.53-3.084a.75.75 0 0 1 .216-.664l2.24-2.183-3.096-.45a.75.75 0 0 1-.564-.41L8 2.694Z"></path>-</svg><span data-view-component="true" class="d-inline">- Star-</span> <span id="repo-stars-counter-star" aria-label="851 users starred this repository" data-singular-suffix="user starred this repository" data-plural-suffix="users starred this repository" data-turbo-replace="true" title="851" data-view-component="true" class="Counter js-social-count">851</span>-</a></div>- </li>--</ul>-- </div>- </div>-- <div id="responsive-meta-container" data-turbo-replace>- <div class="d-block d-md-none mb-2 px-3 px-md-4 px-lg-5">- <p class="f4 mb-3 ">- OpenType Unicode fonts for Scientific, Technical, and Mathematical texts- </p>--- <h3 class="sr-only">License</h3>- <div class="mb-2">- <a href="/stipub/stixfonts/blob/master/OFL.txt"- class="Link--muted"-- data-analytics-event="{"category":"Repository Overview","action":"click","label":"location:sidebar;file:license"}"- >- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-law mr-1 mr-sm-1 mr-md-2 mr-lg-2">- <path d="M8.75.75V2h.985c.304 0 .603.08.867.231l1.29.736c.038.022.08.033.124.033h2.234a.75.75 0 0 1 0 1.5h-.427l2.111 4.692a.75.75 0 0 1-.154.838l-.53-.53.529.531-.001.002-.002.002-.006.006-.006.005-.01.01-.045.04c-.21.176-.441.327-.686.45C14.556 10.78 13.88 11 13 11a4.498 4.498 0 0 1-2.023-.454 3.544 3.544 0 0 1-.686-.45l-.045-.04-.016-.015-.006-.006-.004-.004v-.001a.75.75 0 0 1-.154-.838L12.178 4.5h-.162c-.305 0-.604-.079-.868-.231l-1.29-.736a.245.245 0 0 0-.124-.033H8.75V13h2.5a.75.75 0 0 1 0 1.5h-6.5a.75.75 0 0 1 0-1.5h2.5V3.5h-.984a.245.245 0 0 0-.124.033l-1.289.737c-.265.15-.564.23-.869.23h-.162l2.112 4.692a.75.75 0 0 1-.154.838l-.53-.53.529.531-.001.002-.002.002-.006.006-.016.015-.045.04c-.21.176-.441.327-.686.45C4.556 10.78 3.88 11 3 11a4.498 4.498 0 0 1-2.023-.454 3.544 3.544 0 0 1-.686-.45l-.045-.04-.016-.015-.006-.006-.004-.004v-.001a.75.75 0 0 1-.154-.838L2.178 4.5H1.75a.75.75 0 0 1 0-1.5h2.234a.249.249 0 0 0 .125-.033l1.288-.737c.265-.15.564-.23.869-.23h.984V.75a.75.75 0 0 1 1.5 0Zm2.945 8.477c.285.135.718.273 1.305.273s1.02-.138 1.305-.273L13 6.327Zm-10 0c.285.135.718.273 1.305.273s1.02-.138 1.305-.273L3 6.327Z"></path>-</svg>- OFL-1.1 license- </a>- </div>--- <div class="mb-3">- <a class="Link--secondary no-underline mr-3" href="/stipub/stixfonts/stargazers">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-star mr-1">- <path d="M8 .25a.75.75 0 0 1 .673.418l1.882 3.815 4.21.612a.75.75 0 0 1 .416 1.279l-3.046 2.97.719 4.192a.751.751 0 0 1-1.088.791L8 12.347l-3.766 1.98a.75.75 0 0 1-1.088-.79l.72-4.194L.818 6.374a.75.75 0 0 1 .416-1.28l4.21-.611L7.327.668A.75.75 0 0 1 8 .25Zm0 2.445L6.615 5.5a.75.75 0 0 1-.564.41l-3.097.45 2.24 2.184a.75.75 0 0 1 .216.664l-.528 3.084 2.769-1.456a.75.75 0 0 1 .698 0l2.77 1.456-.53-3.084a.75.75 0 0 1 .216-.664l2.24-2.183-3.096-.45a.75.75 0 0 1-.564-.41L8 2.694Z"></path>-</svg>- <span class="text-bold">851</span>- stars-</a> <a class="Link--secondary no-underline mr-3" href="/stipub/stixfonts/forks">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-repo-forked mr-1">- <path d="M5 5.372v.878c0 .414.336.75.75.75h4.5a.75.75 0 0 0 .75-.75v-.878a2.25 2.25 0 1 1 1.5 0v.878a2.25 2.25 0 0 1-2.25 2.25h-1.5v2.128a2.251 2.251 0 1 1-1.5 0V8.5h-1.5A2.25 2.25 0 0 1 3.5 6.25v-.878a2.25 2.25 0 1 1 1.5 0ZM5 3.25a.75.75 0 1 0-1.5 0 .75.75 0 0 0 1.5 0Zm6.75.75a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5Zm-3 8.75a.75.75 0 1 0-1.5 0 .75.75 0 0 0 1.5 0Z"></path>-</svg>- <span class="text-bold">49</span>- forks-</a> <a class="Link--secondary no-underline mr-3 d-inline-block" href="/stipub/stixfonts/branches">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-git-branch mr-1">- <path d="M9.5 3.25a2.25 2.25 0 1 1 3 2.122V6A2.5 2.5 0 0 1 10 8.5H6a1 1 0 0 0-1 1v1.128a2.251 2.251 0 1 1-1.5 0V5.372a2.25 2.25 0 1 1 1.5 0v1.836A2.493 2.493 0 0 1 6 7h4a1 1 0 0 0 1-1v-.628A2.25 2.25 0 0 1 9.5 3.25Zm-6 0a.75.75 0 1 0 1.5 0 .75.75 0 0 0-1.5 0Zm8.25-.75a.75.75 0 1 0 0 1.5.75.75 0 0 0 0-1.5ZM4.25 12a.75.75 0 1 0 0 1.5.75.75 0 0 0 0-1.5Z"></path>-</svg>- <span>Branches</span>-</a> <a class="Link--secondary no-underline d-inline-block" href="/stipub/stixfonts/tags">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-tag mr-1">- <path d="M1 7.775V2.75C1 1.784 1.784 1 2.75 1h5.025c.464 0 .91.184 1.238.513l6.25 6.25a1.75 1.75 0 0 1 0 2.474l-5.026 5.026a1.75 1.75 0 0 1-2.474 0l-6.25-6.25A1.752 1.752 0 0 1 1 7.775Zm1.5 0c0 .066.026.13.073.177l6.25 6.25a.25.25 0 0 0 .354 0l5.025-5.025a.25.25 0 0 0 0-.354l-6.25-6.25a.25.25 0 0 0-.177-.073H2.75a.25.25 0 0 0-.25.25ZM6 5a1 1 0 1 1 0 2 1 1 0 0 1 0-2Z"></path>-</svg>- <span>Tags</span>-</a> <a class="Link--secondary no-underline d-inline-block" href="/stipub/stixfonts/activity">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-pulse mr-1">- <path d="M6 2c.306 0 .582.187.696.471L10 10.731l1.304-3.26A.751.751 0 0 1 12 7h3.25a.75.75 0 0 1 0 1.5h-2.742l-1.812 4.528a.751.751 0 0 1-1.392 0L6 4.77 4.696 8.03A.75.75 0 0 1 4 8.5H.75a.75.75 0 0 1 0-1.5h2.742l1.812-4.529A.751.751 0 0 1 6 2Z"></path>-</svg>- <span>Activity</span>-</a> </div>- <div class="d-flex flex-wrap gap-2">- <div class="flex-1">- <div data-view-component="true" class="BtnGroup d-flex">- <a href="/login?return_to=%2Fstipub%2Fstixfonts" rel="nofollow" data-hydro-click="{"event_type":"authentication.click","payload":{"location_in_page":"star button","repository_id":128424630,"auth_type":"LOG_IN","originating_url":"https://github.com/stipub/stixfonts","user_id":null}}" data-hydro-click-hmac="73cc4c3693e1d8b85b3dd53476858eb355552f849acb45454336174300e68e98" aria-label="You must be signed in to star a repository" data-view-component="true" class="tooltipped tooltipped-sw btn-sm btn btn-block"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-star v-align-text-bottom d-inline-block mr-2">- <path d="M8 .25a.75.75 0 0 1 .673.418l1.882 3.815 4.21.612a.75.75 0 0 1 .416 1.279l-3.046 2.97.719 4.192a.751.751 0 0 1-1.088.791L8 12.347l-3.766 1.98a.75.75 0 0 1-1.088-.79l.72-4.194L.818 6.374a.75.75 0 0 1 .416-1.28l4.21-.611L7.327.668A.75.75 0 0 1 8 .25Zm0 2.445L6.615 5.5a.75.75 0 0 1-.564.41l-3.097.45 2.24 2.184a.75.75 0 0 1 .216.664l-.528 3.084 2.769-1.456a.75.75 0 0 1 .698 0l2.77 1.456-.53-3.084a.75.75 0 0 1 .216-.664l2.24-2.183-3.096-.45a.75.75 0 0 1-.564-.41L8 2.694Z"></path>-</svg><span data-view-component="true" class="d-inline">- Star-</span>-</a></div>- </div>- <div class="flex-1">- <a href="/login?return_to=%2Fstipub%2Fstixfonts" rel="nofollow" id="files-overview-watch-button" data-hydro-click="{"event_type":"authentication.click","payload":{"location_in_page":"notification subscription menu watch","repository_id":null,"auth_type":"LOG_IN","originating_url":"https://github.com/stipub/stixfonts","user_id":null}}" data-hydro-click-hmac="d48beb239e463aa3111864a1fedf4b6edb178af60b3ecc598f45410ff2683220" aria-label="You must be signed in to change notification settings" data-view-component="true" class="btn-sm btn btn-block"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-bell mr-2">- <path d="M8 16a2 2 0 0 0 1.985-1.75c.017-.137-.097-.25-.235-.25h-3.5c-.138 0-.252.113-.235.25A2 2 0 0 0 8 16ZM3 5a5 5 0 0 1 10 0v2.947c0 .05.015.098.042.139l1.703 2.555A1.519 1.519 0 0 1 13.482 13H2.518a1.516 1.516 0 0 1-1.263-2.36l1.703-2.554A.255.255 0 0 0 3 7.947Zm5-3.5A3.5 3.5 0 0 0 4.5 5v2.947c0 .346-.102.683-.294.97l-1.703 2.556a.017.017 0 0 0-.003.01l.001.006c0 .002.002.004.004.006l.006.004.007.001h10.964l.007-.001.006-.004.004-.006.001-.007a.017.017 0 0 0-.003-.01l-1.703-2.554a1.745 1.745 0 0 1-.294-.97V5A3.5 3.5 0 0 0 8 1.5Z"></path>-</svg>Notifications-</a> <tool-tip id="tooltip-7fda711d-7cba-4c06-b0d8-d39dce7cbaba" for="files-overview-watch-button" popover="manual" data-direction="s" data-type="description" data-view-component="true" class="sr-only position-absolute">You must be signed in to change notification settings</tool-tip>-- </div>- <span>--- </span>- </div>- </div>--</div>--- <nav data-pjax="#js-repo-pjax-container" aria-label="Repository" data-view-component="true" class="js-repo-nav js-sidenav-container-pjax js-responsive-underlinenav overflow-hidden UnderlineNav px-3 px-md-4 px-lg-5">-- <ul data-view-component="true" class="UnderlineNav-body list-style-none">- <li data-view-component="true" class="d-inline-flex">- <a id="code-tab" href="/stipub/stixfonts" data-tab-item="i0code-tab" data-selected-links="repo_source repo_downloads repo_commits repo_releases repo_tags repo_branches repo_packages repo_deployments repo_attestations /stipub/stixfonts" data-pjax="#repo-content-pjax-container" data-turbo-frame="repo-content-turbo-frame" data-hotkey="g c" data-analytics-event="{"category":"Underline navbar","action":"Click tab","label":"Code","target":"UNDERLINE_NAV.TAB"}" aria-current="page" data-view-component="true" class="UnderlineNav-item no-wrap js-responsive-underlinenav-item js-selected-navigation-item selected">-- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-code UnderlineNav-octicon d-none d-sm-inline">- <path d="m11.28 3.22 4.25 4.25a.75.75 0 0 1 0 1.06l-4.25 4.25a.749.749 0 0 1-1.275-.326.749.749 0 0 1 .215-.734L13.94 8l-3.72-3.72a.749.749 0 0 1 .326-1.275.749.749 0 0 1 .734.215Zm-6.56 0a.751.751 0 0 1 1.042.018.751.751 0 0 1 .018 1.042L2.06 8l3.72 3.72a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215L.47 8.53a.75.75 0 0 1 0-1.06Z"></path>-</svg>- <span data-content="Code">Code</span>- <span id="code-repo-tab-count" data-pjax-replace="" data-turbo-replace="" title="Not available" data-view-component="true" class="Counter"></span>----</a></li>- <li data-view-component="true" class="d-inline-flex">- <a id="issues-tab" href="/stipub/stixfonts/issues" data-tab-item="i1issues-tab" data-selected-links="repo_issues repo_labels repo_milestones /stipub/stixfonts/issues" data-pjax="#repo-content-pjax-container" data-turbo-frame="repo-content-turbo-frame" data-hotkey="g i" data-analytics-event="{"category":"Underline navbar","action":"Click tab","label":"Issues","target":"UNDERLINE_NAV.TAB"}" data-view-component="true" class="UnderlineNav-item no-wrap js-responsive-underlinenav-item js-selected-navigation-item">-- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-issue-opened UnderlineNav-octicon d-none d-sm-inline">- <path d="M8 9.5a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3Z"></path><path d="M8 0a8 8 0 1 1 0 16A8 8 0 0 1 8 0ZM1.5 8a6.5 6.5 0 1 0 13 0 6.5 6.5 0 0 0-13 0Z"></path>-</svg>- <span data-content="Issues">Issues</span>- <span id="issues-repo-tab-count" data-pjax-replace="" data-turbo-replace="" title="90" data-view-component="true" class="Counter">90</span>----</a></li>- <li data-view-component="true" class="d-inline-flex">- <a id="pull-requests-tab" href="/stipub/stixfonts/pulls" data-tab-item="i2pull-requests-tab" data-selected-links="repo_pulls checks /stipub/stixfonts/pulls" data-pjax="#repo-content-pjax-container" data-turbo-frame="repo-content-turbo-frame" data-hotkey="g p" data-analytics-event="{"category":"Underline navbar","action":"Click tab","label":"Pull requests","target":"UNDERLINE_NAV.TAB"}" data-view-component="true" class="UnderlineNav-item no-wrap js-responsive-underlinenav-item js-selected-navigation-item">-- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-git-pull-request UnderlineNav-octicon d-none d-sm-inline">- <path d="M1.5 3.25a2.25 2.25 0 1 1 3 2.122v5.256a2.251 2.251 0 1 1-1.5 0V5.372A2.25 2.25 0 0 1 1.5 3.25Zm5.677-.177L9.573.677A.25.25 0 0 1 10 .854V2.5h1A2.5 2.5 0 0 1 13.5 5v5.628a2.251 2.251 0 1 1-1.5 0V5a1 1 0 0 0-1-1h-1v1.646a.25.25 0 0 1-.427.177L7.177 3.427a.25.25 0 0 1 0-.354ZM3.75 2.5a.75.75 0 1 0 0 1.5.75.75 0 0 0 0-1.5Zm0 9.5a.75.75 0 1 0 0 1.5.75.75 0 0 0 0-1.5Zm8.25.75a.75.75 0 1 0 1.5 0 .75.75 0 0 0-1.5 0Z"></path>-</svg>- <span data-content="Pull requests">Pull requests</span>- <span id="pull-requests-repo-tab-count" data-pjax-replace="" data-turbo-replace="" title="0" hidden="hidden" data-view-component="true" class="Counter">0</span>----</a></li>- <li data-view-component="true" class="d-inline-flex">- <a id="actions-tab" href="/stipub/stixfonts/actions" data-tab-item="i3actions-tab" data-selected-links="repo_actions /stipub/stixfonts/actions" data-pjax="#repo-content-pjax-container" data-turbo-frame="repo-content-turbo-frame" data-hotkey="g a" data-analytics-event="{"category":"Underline navbar","action":"Click tab","label":"Actions","target":"UNDERLINE_NAV.TAB"}" data-view-component="true" class="UnderlineNav-item no-wrap js-responsive-underlinenav-item js-selected-navigation-item">-- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-play UnderlineNav-octicon d-none d-sm-inline">- <path d="M8 0a8 8 0 1 1 0 16A8 8 0 0 1 8 0ZM1.5 8a6.5 6.5 0 1 0 13 0 6.5 6.5 0 0 0-13 0Zm4.879-2.773 4.264 2.559a.25.25 0 0 1 0 .428l-4.264 2.559A.25.25 0 0 1 6 10.559V5.442a.25.25 0 0 1 .379-.215Z"></path>-</svg>- <span data-content="Actions">Actions</span>- <span id="actions-repo-tab-count" data-pjax-replace="" data-turbo-replace="" title="Not available" data-view-component="true" class="Counter"></span>----</a></li>- <li data-view-component="true" class="d-inline-flex">- <a id="projects-tab" href="/stipub/stixfonts/projects" data-tab-item="i4projects-tab" data-selected-links="repo_projects new_repo_project repo_project /stipub/stixfonts/projects" data-pjax="#repo-content-pjax-container" data-turbo-frame="repo-content-turbo-frame" data-hotkey="g b" data-analytics-event="{"category":"Underline navbar","action":"Click tab","label":"Projects","target":"UNDERLINE_NAV.TAB"}" data-view-component="true" class="UnderlineNav-item no-wrap js-responsive-underlinenav-item js-selected-navigation-item">-- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-table UnderlineNav-octicon d-none d-sm-inline">- <path d="M0 1.75C0 .784.784 0 1.75 0h12.5C15.216 0 16 .784 16 1.75v12.5A1.75 1.75 0 0 1 14.25 16H1.75A1.75 1.75 0 0 1 0 14.25ZM6.5 6.5v8h7.75a.25.25 0 0 0 .25-.25V6.5Zm8-1.5V1.75a.25.25 0 0 0-.25-.25H6.5V5Zm-13 1.5v7.75c0 .138.112.25.25.25H5v-8ZM5 5V1.5H1.75a.25.25 0 0 0-.25.25V5Z"></path>-</svg>- <span data-content="Projects">Projects</span>- <span id="projects-repo-tab-count" data-pjax-replace="" data-turbo-replace="" title="0" hidden="hidden" data-view-component="true" class="Counter">0</span>----</a></li>- <li data-view-component="true" class="d-inline-flex">- <a id="security-tab" href="/stipub/stixfonts/security" data-tab-item="i5security-tab" data-selected-links="security overview alerts policy token_scanning code_scanning /stipub/stixfonts/security" data-pjax="#repo-content-pjax-container" data-turbo-frame="repo-content-turbo-frame" data-hotkey="g s" data-analytics-event="{"category":"Underline navbar","action":"Click tab","label":"Security","target":"UNDERLINE_NAV.TAB"}" data-view-component="true" class="UnderlineNav-item no-wrap js-responsive-underlinenav-item js-selected-navigation-item">-- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-shield UnderlineNav-octicon d-none d-sm-inline">- <path d="M7.467.133a1.748 1.748 0 0 1 1.066 0l5.25 1.68A1.75 1.75 0 0 1 15 3.48V7c0 1.566-.32 3.182-1.303 4.682-.983 1.498-2.585 2.813-5.032 3.855a1.697 1.697 0 0 1-1.33 0c-2.447-1.042-4.049-2.357-5.032-3.855C1.32 10.182 1 8.566 1 7V3.48a1.75 1.75 0 0 1 1.217-1.667Zm.61 1.429a.25.25 0 0 0-.153 0l-5.25 1.68a.25.25 0 0 0-.174.238V7c0 1.358.275 2.666 1.057 3.86.784 1.194 2.121 2.34 4.366 3.297a.196.196 0 0 0 .154 0c2.245-.956 3.582-2.104 4.366-3.298C13.225 9.666 13.5 8.36 13.5 7V3.48a.251.251 0 0 0-.174-.237l-5.25-1.68ZM8.75 4.75v3a.75.75 0 0 1-1.5 0v-3a.75.75 0 0 1 1.5 0ZM9 10.5a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>-</svg>- <span data-content="Security">Security</span>- <include-fragment src="/stipub/stixfonts/security/overall-count" accept="text/fragment+html" data-nonce="v2:b49ec1ff-5698-f083-23b7-2d32904b38f1" data-view-component="true">-- <div data-show-on-forbidden-error hidden>- <div class="Box">- <div class="blankslate-container">- <div data-view-component="true" class="blankslate blankslate-spacious color-bg-default rounded-2">--- <h3 data-view-component="true" class="blankslate-heading"> Uh oh!-</h3>- <p data-view-component="true"> <p class="color-fg-muted my-2 mb-2 ws-normal">There was an error while loading. <a class="Link--inTextBlock" data-turbo="false" href="" aria-label="Please reload this page">Please reload this page</a>.</p>-</p>--</div> </div>-</div> </div>-</include-fragment>---</a></li>- <li data-view-component="true" class="d-inline-flex">- <a id="insights-tab" href="/stipub/stixfonts/pulse" data-tab-item="i6insights-tab" data-selected-links="repo_graphs repo_contributors dependency_graph dependabot_updates pulse people community /stipub/stixfonts/pulse" data-pjax="#repo-content-pjax-container" data-turbo-frame="repo-content-turbo-frame" data-analytics-event="{"category":"Underline navbar","action":"Click tab","label":"Insights","target":"UNDERLINE_NAV.TAB"}" data-view-component="true" class="UnderlineNav-item no-wrap js-responsive-underlinenav-item js-selected-navigation-item">-- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-graph UnderlineNav-octicon d-none d-sm-inline">- <path d="M1.5 1.75V13.5h13.75a.75.75 0 0 1 0 1.5H.75a.75.75 0 0 1-.75-.75V1.75a.75.75 0 0 1 1.5 0Zm14.28 2.53-5.25 5.25a.75.75 0 0 1-1.06 0L7 7.06 4.28 9.78a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042l3.25-3.25a.75.75 0 0 1 1.06 0L10 7.94l4.72-4.72a.751.751 0 0 1 1.042.018.751.751 0 0 1 .018 1.042Z"></path>-</svg>- <span data-content="Insights">Insights</span>- <span id="insights-repo-tab-count" data-pjax-replace="" data-turbo-replace="" title="Not available" data-view-component="true" class="Counter"></span>----</a></li>-</ul>- <div style="visibility:hidden;" data-view-component="true" class="UnderlineNav-actions js-responsive-underlinenav-overflow position-absolute pr-3 pr-md-4 pr-lg-5 right-0"> <action-menu data-select-variant="none" data-view-component="true">- <focus-group direction="vertical" mnemonics retain>- <button id="action-menu-2f6dd63a-42e3-4ed6-a5f1-6678d3cfd579-button" popovertarget="action-menu-2f6dd63a-42e3-4ed6-a5f1-6678d3cfd579-overlay" aria-controls="action-menu-2f6dd63a-42e3-4ed6-a5f1-6678d3cfd579-list" aria-haspopup="true" aria-labelledby="tooltip-4d086d5a-8528-463d-bb81-9373a194b914" type="button" data-view-component="true" class="Button Button--iconOnly Button--secondary Button--medium UnderlineNav-item"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-kebab-horizontal Button-visual">- <path d="M8 9a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3ZM1.5 9a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3Zm13 0a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3Z"></path>-</svg>-</button><tool-tip id="tooltip-4d086d5a-8528-463d-bb81-9373a194b914" for="action-menu-2f6dd63a-42e3-4ed6-a5f1-6678d3cfd579-button" popover="manual" data-direction="s" data-type="label" data-view-component="true" class="sr-only position-absolute">Additional navigation options</tool-tip>---<anchored-position data-target="action-menu.overlay" id="action-menu-2f6dd63a-42e3-4ed6-a5f1-6678d3cfd579-overlay" anchor="action-menu-2f6dd63a-42e3-4ed6-a5f1-6678d3cfd579-button" align="start" side="outside-bottom" anchor-offset="normal" popover="auto" data-view-component="true">- <div data-view-component="true" class="Overlay Overlay--size-auto">-- <div data-view-component="true" class="Overlay-body Overlay-body--paddingNone"> <action-list>- <div data-view-component="true">- <ul aria-labelledby="action-menu-2f6dd63a-42e3-4ed6-a5f1-6678d3cfd579-button" id="action-menu-2f6dd63a-42e3-4ed6-a5f1-6678d3cfd579-list" role="menu" data-view-component="true" class="ActionListWrap--inset ActionListWrap">- <li hidden="hidden" data-menu-item="i0code-tab" data-targets="action-list.items" role="none" data-view-component="true" class="ActionListItem">--- <a tabindex="-1" id="item-fb76ed55-24fa-4125-8960-0ecb6eda0850" href="/stipub/stixfonts" role="menuitem" data-view-component="true" class="ActionListContent ActionListContent--visual16">- <span class="ActionListItem-visual ActionListItem-visual--leading">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-code">- <path d="m11.28 3.22 4.25 4.25a.75.75 0 0 1 0 1.06l-4.25 4.25a.749.749 0 0 1-1.275-.326.749.749 0 0 1 .215-.734L13.94 8l-3.72-3.72a.749.749 0 0 1 .326-1.275.749.749 0 0 1 .734.215Zm-6.56 0a.751.751 0 0 1 1.042.018.751.751 0 0 1 .018 1.042L2.06 8l3.72 3.72a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215L.47 8.53a.75.75 0 0 1 0-1.06Z"></path>-</svg>- </span>-- <span data-view-component="true" class="ActionListItem-label">- Code-</span>-</a>--</li>- <li hidden="hidden" data-menu-item="i1issues-tab" data-targets="action-list.items" role="none" data-view-component="true" class="ActionListItem">--- <a tabindex="-1" id="item-361f9dae-33f1-406e-a4a3-ba69a8f8b7a6" href="/stipub/stixfonts/issues" role="menuitem" data-view-component="true" class="ActionListContent ActionListContent--visual16">- <span class="ActionListItem-visual ActionListItem-visual--leading">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-issue-opened">- <path d="M8 9.5a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3Z"></path><path d="M8 0a8 8 0 1 1 0 16A8 8 0 0 1 8 0ZM1.5 8a6.5 6.5 0 1 0 13 0 6.5 6.5 0 0 0-13 0Z"></path>-</svg>- </span>-- <span data-view-component="true" class="ActionListItem-label">- Issues-</span>-</a>--</li>- <li hidden="hidden" data-menu-item="i2pull-requests-tab" data-targets="action-list.items" role="none" data-view-component="true" class="ActionListItem">--- <a tabindex="-1" id="item-1a6e2a1a-65ff-447f-ba37-5e7cd130af16" href="/stipub/stixfonts/pulls" role="menuitem" data-view-component="true" class="ActionListContent ActionListContent--visual16">- <span class="ActionListItem-visual ActionListItem-visual--leading">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-git-pull-request">- <path d="M1.5 3.25a2.25 2.25 0 1 1 3 2.122v5.256a2.251 2.251 0 1 1-1.5 0V5.372A2.25 2.25 0 0 1 1.5 3.25Zm5.677-.177L9.573.677A.25.25 0 0 1 10 .854V2.5h1A2.5 2.5 0 0 1 13.5 5v5.628a2.251 2.251 0 1 1-1.5 0V5a1 1 0 0 0-1-1h-1v1.646a.25.25 0 0 1-.427.177L7.177 3.427a.25.25 0 0 1 0-.354ZM3.75 2.5a.75.75 0 1 0 0 1.5.75.75 0 0 0 0-1.5Zm0 9.5a.75.75 0 1 0 0 1.5.75.75 0 0 0 0-1.5Zm8.25.75a.75.75 0 1 0 1.5 0 .75.75 0 0 0-1.5 0Z"></path>-</svg>- </span>-- <span data-view-component="true" class="ActionListItem-label">- Pull requests-</span>-</a>--</li>- <li hidden="hidden" data-menu-item="i3actions-tab" data-targets="action-list.items" role="none" data-view-component="true" class="ActionListItem">--- <a tabindex="-1" id="item-c1d0fe5e-4005-4387-8366-5fc35fa8341c" href="/stipub/stixfonts/actions" role="menuitem" data-view-component="true" class="ActionListContent ActionListContent--visual16">- <span class="ActionListItem-visual ActionListItem-visual--leading">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-play">- <path d="M8 0a8 8 0 1 1 0 16A8 8 0 0 1 8 0ZM1.5 8a6.5 6.5 0 1 0 13 0 6.5 6.5 0 0 0-13 0Zm4.879-2.773 4.264 2.559a.25.25 0 0 1 0 .428l-4.264 2.559A.25.25 0 0 1 6 10.559V5.442a.25.25 0 0 1 .379-.215Z"></path>-</svg>- </span>-- <span data-view-component="true" class="ActionListItem-label">- Actions-</span>-</a>--</li>- <li hidden="hidden" data-menu-item="i4projects-tab" data-targets="action-list.items" role="none" data-view-component="true" class="ActionListItem">--- <a tabindex="-1" id="item-a8994c5d-bc22-4a87-a305-ecedc9fafd6e" href="/stipub/stixfonts/projects" role="menuitem" data-view-component="true" class="ActionListContent ActionListContent--visual16">- <span class="ActionListItem-visual ActionListItem-visual--leading">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-table">- <path d="M0 1.75C0 .784.784 0 1.75 0h12.5C15.216 0 16 .784 16 1.75v12.5A1.75 1.75 0 0 1 14.25 16H1.75A1.75 1.75 0 0 1 0 14.25ZM6.5 6.5v8h7.75a.25.25 0 0 0 .25-.25V6.5Zm8-1.5V1.75a.25.25 0 0 0-.25-.25H6.5V5Zm-13 1.5v7.75c0 .138.112.25.25.25H5v-8ZM5 5V1.5H1.75a.25.25 0 0 0-.25.25V5Z"></path>-</svg>- </span>-- <span data-view-component="true" class="ActionListItem-label">- Projects-</span>-</a>--</li>- <li hidden="hidden" data-menu-item="i5security-tab" data-targets="action-list.items" role="none" data-view-component="true" class="ActionListItem">--- <a tabindex="-1" id="item-f58df429-a0c2-4c9c-b92c-e8318f489fcd" href="/stipub/stixfonts/security" role="menuitem" data-view-component="true" class="ActionListContent ActionListContent--visual16">- <span class="ActionListItem-visual ActionListItem-visual--leading">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-shield">- <path d="M7.467.133a1.748 1.748 0 0 1 1.066 0l5.25 1.68A1.75 1.75 0 0 1 15 3.48V7c0 1.566-.32 3.182-1.303 4.682-.983 1.498-2.585 2.813-5.032 3.855a1.697 1.697 0 0 1-1.33 0c-2.447-1.042-4.049-2.357-5.032-3.855C1.32 10.182 1 8.566 1 7V3.48a1.75 1.75 0 0 1 1.217-1.667Zm.61 1.429a.25.25 0 0 0-.153 0l-5.25 1.68a.25.25 0 0 0-.174.238V7c0 1.358.275 2.666 1.057 3.86.784 1.194 2.121 2.34 4.366 3.297a.196.196 0 0 0 .154 0c2.245-.956 3.582-2.104 4.366-3.298C13.225 9.666 13.5 8.36 13.5 7V3.48a.251.251 0 0 0-.174-.237l-5.25-1.68ZM8.75 4.75v3a.75.75 0 0 1-1.5 0v-3a.75.75 0 0 1 1.5 0ZM9 10.5a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>-</svg>- </span>-- <span data-view-component="true" class="ActionListItem-label">- Security-</span>-</a>--</li>- <li hidden="hidden" data-menu-item="i6insights-tab" data-targets="action-list.items" role="none" data-view-component="true" class="ActionListItem">--- <a tabindex="-1" id="item-fb99dd66-2f64-44f2-ae8a-ef0a9f994dba" href="/stipub/stixfonts/pulse" role="menuitem" data-view-component="true" class="ActionListContent ActionListContent--visual16">- <span class="ActionListItem-visual ActionListItem-visual--leading">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-graph">- <path d="M1.5 1.75V13.5h13.75a.75.75 0 0 1 0 1.5H.75a.75.75 0 0 1-.75-.75V1.75a.75.75 0 0 1 1.5 0Zm14.28 2.53-5.25 5.25a.75.75 0 0 1-1.06 0L7 7.06 4.28 9.78a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042l3.25-3.25a.75.75 0 0 1 1.06 0L10 7.94l4.72-4.72a.751.751 0 0 1 1.042.018.751.751 0 0 1 .018 1.042Z"></path>-</svg>- </span>-- <span data-view-component="true" class="ActionListItem-label">- Insights-</span>-</a>--</li>-</ul>-</div></action-list>---</div>--</div></anchored-position> </focus-group>-</action-menu></div>-</nav>-- </div>------<turbo-frame id="repo-content-turbo-frame" target="_top" data-turbo-action="advance" class="">- <div id="repo-content-pjax-container" class="repository-content " >------- <h1 class='sr-only'>stipub/stixfonts</h1>- <div class="clearfix container-xl px-md-4 px-lg-5 px-3">- <div>-- <div style="max-width: 100%" data-view-component="true" class="Layout Layout--flowRow-until-md react-repos-overview-margin Layout--sidebarPosition-end Layout--sidebarPosition-flowRow-end">- <div data-view-component="true" class="Layout-main"> <link crossorigin="anonymous" media="all" rel="stylesheet" href="https://github.githubassets.com/assets/primer-react.53f37102c46fd176a96b.module.css" />-<link crossorigin="anonymous" media="all" rel="stylesheet" href="https://github.githubassets.com/assets/app_assets_modules_react-partials_repos-overview_components_OverviewContent_module_css-app_as-2f8a17.163b1668fe15f05c225e.module.css" />--<react-partial- partial-name="repos-overview"- data-ssr="true"- data-attempted-ssr="true"- data-react-profiling="false"->-- <script type="application/json" data-target="react-partial.embeddedData">{"props":{"initialPayload":{"allShortcutsEnabled":false,"path":"/","repo":{"id":128424630,"defaultBranch":"master","name":"stixfonts","ownerLogin":"stipub","currentUserCanPush":false,"isFork":false,"isEmpty":false,"createdAt":"2018-04-06T17:23:37.000Z","ownerAvatar":"https://avatars.githubusercontent.com/u/12853237?v=4","public":true,"private":false,"isOrgOwned":true},"currentUser":null,"refInfo":{"name":"master","listCacheKey":"v0:1742237225.0","canEdit":false,"refType":"branch","currentOid":"c4afdf3fa5390159ef24aca1db5e957487c23897"},"tree":{"items":[{"name":"archive","path":"archive","contentType":"directory"},{"name":"docs","path":"docs","contentType":"directory"},{"name":"fonts","path":"fonts","contentType":"directory"},{"name":"source","path":"source","contentType":"directory"},{"name":"tools","path":"tools","contentType":"directory"},{"name":"zipfiles","path":"zipfiles","contentType":"directory"},{"name":".gitignore","path":".gitignore","contentType":"file"},{"name":"AUTHORS.txt","path":"AUTHORS.txt","contentType":"file"},{"name":"CONTRIBUTORS.txt","path":"CONTRIBUTORS.txt","contentType":"file"},{"name":"DESCRIPTION.en_us.html","path":"DESCRIPTION.en_us.html","contentType":"file"},{"name":"FONTLOG.txt","path":"FONTLOG.txt","contentType":"file"},{"name":"OFL-FAQ.txt","path":"OFL-FAQ.txt","contentType":"file"},{"name":"OFL.txt","path":"OFL.txt","contentType":"file"},{"name":"README.md","path":"README.md","contentType":"file"},{"name":"TRADEMARKS.txt","path":"TRADEMARKS.txt","contentType":"file"},{"name":"build.sh","path":"build.sh","contentType":"file"},{"name":"requirements.in","path":"requirements.in","contentType":"file"},{"name":"requirements.txt","path":"requirements.txt","contentType":"file"}],"templateDirectorySuggestionUrl":null,"readme":null,"totalCount":18,"showBranchInfobar":false},"fileTree":null,"fileTreeProcessingTime":null,"foldersToFetch":[],"treeExpanded":false,"symbolsExpanded":false,"copilotSWEAgentEnabled":false,"isOverview":true,"overview":{"banners":{"shouldRecommendReadme":false,"isPersonalRepo":false,"showUseActionBanner":false,"actionSlug":null,"actionId":null,"showProtectBranchBanner":false,"publishBannersInfo":{"dismissActionNoticePath":"/settings/dismiss-notice/publish_action_from_repo","releasePath":"/stipub/stixfonts/releases/new?marketplace=true","showPublishActionBanner":false},"interactionLimitBanner":null,"showInvitationBanner":false,"inviterName":null,"actionsMigrationBannerInfo":{"releaseTags":[],"showImmutableActionsMigrationBanner":false,"initialMigrationStatus":null},"showDeployBanner":false,"detectedStack":{"framework":null,"packageManager":null}},"codeButton":{"contactPath":"/contact","isEnterprise":false,"local":{"protocolInfo":{"httpAvailable":true,"sshAvailable":null,"httpUrl":"https://github.com/stipub/stixfonts.git","showCloneWarning":null,"sshUrl":null,"sshCertificatesRequired":null,"sshCertificatesAvailable":null,"ghCliUrl":"gh repo clone stipub/stixfonts","defaultProtocol":"http","newSshKeyUrl":"/settings/ssh/new","setProtocolPath":"/users/set_protocol"},"platformInfo":{"cloneUrl":"https://desktop.github.com","showVisualStudioCloneButton":false,"visualStudioCloneUrl":"https://windows.github.com","showXcodeCloneButton":false,"xcodeCloneUrl":"xcode://clone?repo=https%3A%2F%2Fgithub.com%2Fstipub%2Fstixfonts","zipballUrl":"/stipub/stixfonts/archive/refs/heads/master.zip"}},"newCodespacePath":"/codespaces/new?hide_repo_select=true\u0026repo=128424630"},"popovers":{"rename":null,"renamedParentRepo":null},"commitCount":"70","overviewFiles":[{"displayName":"README.md","repoName":"stixfonts","refName":"master","path":"README.md","preferredFileType":"readme","tabName":"README","richText":"\u003carticle class=\"markdown-body entry-content container-lg\" itemprop=\"text\"\u003e\u003cdiv class=\"markdown-heading\" dir=\"auto\"\u003e\u003ch1 tabindex=\"-1\" class=\"heading-element\" dir=\"auto\"\u003estixfonts\u003c/h1\u003e\u003ca id=\"user-content-stixfonts\" class=\"anchor\" aria-label=\"Permalink: stixfonts\" href=\"#stixfonts\"\u003e\u003csvg class=\"octicon octicon-link\" viewBox=\"0 0 16 16\" version=\"1.1\" width=\"16\" height=\"16\" aria-hidden=\"true\"\u003e\u003cpath d=\"m7.775 3.275 1.25-1.25a3.5 3.5 0 1 1 4.95 4.95l-2.5 2.5a3.5 3.5 0 0 1-4.95 0 .751.751 0 0 1 .018-1.042.751.751 0 0 1 1.042-.018 1.998 1.998 0 0 0 2.83 0l2.5-2.5a2.002 2.002 0 0 0-2.83-2.83l-1.25 1.25a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042Zm-4.69 9.64a1.998 1.998 0 0 0 2.83 0l1.25-1.25a.751.751 0 0 1 1.042.018.751.751 0 0 1 .018 1.042l-1.25 1.25a3.5 3.5 0 1 1-4.95-4.95l2.5-2.5a3.5 3.5 0 0 1 4.95 0 .751.751 0 0 1-.018 1.042.751.751 0 0 1-1.042.018 1.998 1.998 0 0 0-2.83 0l-2.5 2.5a1.998 1.998 0 0 0 0 2.83Z\"\u003e\u003c/path\u003e\u003c/svg\u003e\u003c/a\u003e\u003c/div\u003e\n\u003cp dir=\"auto\"\u003eOpenType Unicode fonts for Scientific, Technical, and Mathematical texts\u003c/p\u003e\n\u003cdiv class=\"markdown-heading\" dir=\"auto\"\u003e\u003ch2 tabindex=\"-1\" class=\"heading-element\" dir=\"auto\"\u003eOverview\u003c/h2\u003e\u003ca id=\"user-content-overview\" class=\"anchor\" aria-label=\"Permalink: Overview\" href=\"#overview\"\u003e\u003csvg class=\"octicon octicon-link\" viewBox=\"0 0 16 16\" version=\"1.1\" width=\"16\" height=\"16\" aria-hidden=\"true\"\u003e\u003cpath d=\"m7.775 3.275 1.25-1.25a3.5 3.5 0 1 1 4.95 4.95l-2.5 2.5a3.5 3.5 0 0 1-4.95 0 .751.751 0 0 1 .018-1.042.751.751 0 0 1 1.042-.018 1.998 1.998 0 0 0 2.83 0l2.5-2.5a2.002 2.002 0 0 0-2.83-2.83l-1.25 1.25a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042Zm-4.69 9.64a1.998 1.998 0 0 0 2.83 0l1.25-1.25a.751.751 0 0 1 1.042.018.751.751 0 0 1 .018 1.042l-1.25 1.25a3.5 3.5 0 1 1-4.95-4.95l2.5-2.5a3.5 3.5 0 0 1 4.95 0 .751.751 0 0 1-.018 1.042.751.751 0 0 1-1.042.018 1.998 1.998 0 0 0-2.83 0l-2.5 2.5a1.998 1.998 0 0 0 0 2.83Z\"\u003e\u003c/path\u003e\u003c/svg\u003e\u003c/a\u003e\u003c/div\u003e\n\u003cul dir=\"auto\"\u003e\n\u003cli\u003e\n\u003cp dir=\"auto\"\u003eSee \u003ca href=\"https://www.stixfonts.org/\" rel=\"nofollow\"\u003ehttps://www.stixfonts.org/\u003c/a\u003e for background on the the STIX Fonts\nproject.\u003c/p\u003e\n\u003c/li\u003e\n\u003cli\u003e\n\u003cp dir=\"auto\"\u003eDownload \u003ca href=\"/stipub/stixfonts/blob/master/zipfiles\"\u003ezip files\u003c/a\u003e with some or all of the fonts.\u003c/p\u003e\n\u003c/li\u003e\n\u003cli\u003e\n\u003cp dir=\"auto\"\u003eView \u003ca href=\"/stipub/stixfonts/blob/master/docs\"\u003ecode charts\u003c/a\u003e for the\u003c/p\u003e\n\u003cul dir=\"auto\"\u003e\n\u003cli\u003e\u003ca href=\"/stipub/stixfonts/blob/master/docs/STIXTwoMath-Regular.pdf\"\u003eMath\u003c/a\u003e,\u003c/li\u003e\n\u003cli\u003e\u003ca href=\"/stipub/stixfonts/blob/master/docs/STIXTwoText-Regular.pdf\"\u003eRegular text\u003c/a\u003e,\nfonts.\u003c/li\u003e\n\u003c/ul\u003e\n\u003c/li\u003e\n\u003c/ul\u003e\n\u003cdiv class=\"markdown-heading\" dir=\"auto\"\u003e\u003ch3 tabindex=\"-1\" class=\"heading-element\" dir=\"auto\"\u003eType 1 fonts (STIX 2.0.0 only)\u003c/h3\u003e\u003ca id=\"user-content-type-1-fonts-stix-200-only\" class=\"anchor\" aria-label=\"Permalink: Type 1 fonts (STIX 2.0.0 only)\" href=\"#type-1-fonts-stix-200-only\"\u003e\u003csvg class=\"octicon octicon-link\" viewBox=\"0 0 16 16\" version=\"1.1\" width=\"16\" height=\"16\" aria-hidden=\"true\"\u003e\u003cpath d=\"m7.775 3.275 1.25-1.25a3.5 3.5 0 1 1 4.95 4.95l-2.5 2.5a3.5 3.5 0 0 1-4.95 0 .751.751 0 0 1 .018-1.042.751.751 0 0 1 1.042-.018 1.998 1.998 0 0 0 2.83 0l2.5-2.5a2.002 2.002 0 0 0-2.83-2.83l-1.25 1.25a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042Zm-4.69 9.64a1.998 1.998 0 0 0 2.83 0l1.25-1.25a.751.751 0 0 1 1.042.018.751.751 0 0 1 .018 1.042l-1.25 1.25a3.5 3.5 0 1 1-4.95-4.95l2.5-2.5a3.5 3.5 0 0 1 4.95 0 .751.751 0 0 1-.018 1.042.751.751 0 0 1-1.042.018 1.998 1.998 0 0 0-2.83 0l-2.5 2.5a1.998 1.998 0 0 0 0 2.83Z\"\u003e\u003c/path\u003e\u003c/svg\u003e\u003c/a\u003e\u003c/div\u003e\n\u003cp dir=\"auto\"\u003eThe STIX Two fonts are OpenType fonts and are meant to be used in that\nformat. For the benefit of LaTeX users who are unable to use XeTeX or\nluaTeX, we have also provided version 2.0.0 of the STIX fonts as a\n\u003ca href=\"https://github.com/stipub/stix_type1\"\u003eset of TFM files and Type 1 fonts\u003c/a\u003e.\u003c/p\u003e\n\u003cp dir=\"auto\"\u003eNote that \u003cstrong\u003eno further updates\u003c/strong\u003e are planned to the Type 1\ndistribution; future development efforts will focus on improving the\nOpenType fonts.\u003c/p\u003e\n\u003cdiv class=\"markdown-heading\" dir=\"auto\"\u003e\u003ch2 tabindex=\"-1\" class=\"heading-element\" dir=\"auto\"\u003eAbout the STIX fonts.\u003c/h2\u003e\u003ca id=\"user-content-about-the-stix-fonts\" class=\"anchor\" aria-label=\"Permalink: About the STIX fonts.\" href=\"#about-the-stix-fonts\"\u003e\u003csvg class=\"octicon octicon-link\" viewBox=\"0 0 16 16\" version=\"1.1\" width=\"16\" height=\"16\" aria-hidden=\"true\"\u003e\u003cpath d=\"m7.775 3.275 1.25-1.25a3.5 3.5 0 1 1 4.95 4.95l-2.5 2.5a3.5 3.5 0 0 1-4.95 0 .751.751 0 0 1 .018-1.042.751.751 0 0 1 1.042-.018 1.998 1.998 0 0 0 2.83 0l2.5-2.5a2.002 2.002 0 0 0-2.83-2.83l-1.25 1.25a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042Zm-4.69 9.64a1.998 1.998 0 0 0 2.83 0l1.25-1.25a.751.751 0 0 1 1.042.018.751.751 0 0 1 .018 1.042l-1.25 1.25a3.5 3.5 0 1 1-4.95-4.95l2.5-2.5a3.5 3.5 0 0 1 4.95 0 .751.751 0 0 1-.018 1.042.751.751 0 0 1-1.042.018 1.998 1.998 0 0 0-2.83 0l-2.5 2.5a1.998 1.998 0 0 0 0 2.83Z\"\u003e\u003c/path\u003e\u003c/svg\u003e\u003c/a\u003e\u003c/div\u003e\n\u003cp dir=\"auto\"\u003eThe Scientific and Technical Information eXchange (STIX) fonts are\nintended to satisfy the demanding needs of authors, publishers,\nprinters, and others working in the scientific, medical, and technical\nfields. They combine a comprehensive Unicode-based collection of\nmathematical symbols and alphabets with a set of text faces suitable\nfor professional publishing. The fonts are available royalty-free\nunder the SIL Open Font License.\u003c/p\u003e\n\u003cp dir=\"auto\"\u003eVersion 2 of the STIX fonts, now known as \"STIX Two\", is a thorough\nrevision undertaken by the renowned type house Tiro Typeworks\nLtd. (\u003ca href=\"https://www.tiro.com\" rel=\"nofollow\"\u003ehttps://www.tiro.com\u003c/a\u003e). The STIX Two fonts consist of one Math\nfont, two variable text fonts (STIXTwoTextVF-Roman and\nSTIXTwoTextVF-Italic), and eight static text fonts (Regular, Italic,\nMedium, Medium Italic, SemiBold, SemiBold Italic, Bold, and Bold\nItalic) derived from the variable fonts. Together, they provide a\nuniform set of fonts that can be used throughout the production\nprocess, whether that be a traditional print-only process, an entirely\nelectronic one, or a combination of the two.\u003c/p\u003e\n\u003cp dir=\"auto\"\u003eThe \u003ca href=\"https://www.stixfonts.org/\" rel=\"nofollow\"\u003eSTIX project\u003c/a\u003e began through the joint\nefforts of\n\u003ca href=\"https://www.ams.org/\" rel=\"nofollow\"\u003eAmerican Mathematical Society\u003c/a\u003e (AMS),\n\u003ca href=\"https://www.aip.org/\" rel=\"nofollow\"\u003eAmerican Institute of Physics\u003c/a\u003e (AIP),\n\u003ca href=\"https://www.aps.org/\" rel=\"nofollow\"\u003eAmerican Physical Society\u003c/a\u003e (APS),\n\u003ca href=\"https://www.acs.org/\" rel=\"nofollow\"\u003eAmerican Chemical Society\u003c/a\u003e (ACS),\nThe \u003ca href=\"https://www.ieee.org/\" rel=\"nofollow\"\u003eInstitute of Electrical and Electronic\u003c/a\u003e Engineers (IEEE),\nand \u003ca href=\"https://www.elsevier.com/\" rel=\"nofollow\"\u003eElsevier\u003c/a\u003e.\nThese companies are collectively known as the STI Pub companies.\u003c/p\u003e\n\u003cdiv class=\"markdown-heading\" dir=\"auto\"\u003e\u003ch3 tabindex=\"-1\" class=\"heading-element\" dir=\"auto\"\u003eA Fresh Take on Times Roman\u003c/h3\u003e\u003ca id=\"user-content-a-fresh-take-on-times-roman\" class=\"anchor\" aria-label=\"Permalink: A Fresh Take on Times Roman\" href=\"#a-fresh-take-on-times-roman\"\u003e\u003csvg class=\"octicon octicon-link\" viewBox=\"0 0 16 16\" version=\"1.1\" width=\"16\" height=\"16\" aria-hidden=\"true\"\u003e\u003cpath d=\"m7.775 3.275 1.25-1.25a3.5 3.5 0 1 1 4.95 4.95l-2.5 2.5a3.5 3.5 0 0 1-4.95 0 .751.751 0 0 1 .018-1.042.751.751 0 0 1 1.042-.018 1.998 1.998 0 0 0 2.83 0l2.5-2.5a2.002 2.002 0 0 0-2.83-2.83l-1.25 1.25a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042Zm-4.69 9.64a1.998 1.998 0 0 0 2.83 0l1.25-1.25a.751.751 0 0 1 1.042.018.751.751 0 0 1 .018 1.042l-1.25 1.25a3.5 3.5 0 1 1-4.95-4.95l2.5-2.5a3.5 3.5 0 0 1 4.95 0 .751.751 0 0 1-.018 1.042.751.751 0 0 1-1.042.018 1.998 1.998 0 0 0-2.83 0l-2.5 2.5a1.998 1.998 0 0 0 0 2.83Z\"\u003e\u003c/path\u003e\u003c/svg\u003e\u003c/a\u003e\u003c/div\u003e\n\u003cp dir=\"auto\"\u003eThe original version of STIX was based on Times Roman, which has now\nbeen updated for the digital age.\u003c/p\u003e\n\u003cp dir=\"auto\"\u003eAs is well known, Times Roman was originally intended for printing the\n\u003cem\u003eLondon Times\u003c/em\u003e. What is not generally appreciated is that the\nproduction quality of the \u003cem\u003eTimes\u003c/em\u003e was atypically high: It was printed\non unusually high-quality paper on presses that operated more slowly\nthan most newspaper presses. This allowed for the design of a\ntypeface that could exploit this level of care: serifs could be much\nfiner and counters (enclosed areas such as that in the lowercase \u003cem\u003ee\u003c/em\u003e)\ncould be much smaller than in other newspaper typefaces. These\nfeatures of the font have not always fared well in less exacting\nenvironments. At the same time, a notable quirk of the Times Roman\nfamily is that the bold font is, in many respects, strikingly\ndissimilar to the roman font.\u003c/p\u003e\n\u003cp dir=\"auto\"\u003eTiro Typeworks explain their approach to updating the Times Roman\nbasis of STIX as follows:\u003c/p\u003e\n\u003cblockquote\u003e\n\u003cp dir=\"auto\"\u003e“Our principal goal in approaching STIX Two was to address several\ninherent deficiencies in the Times New Roman model as well as expand\nthe typographic features. This process necessarily involved\ndiverging somewhat from Times as familiar to people who have only\nknown the common digital versions, while simultaneously restoring to\nthat typeface aspects of the size-appropriate design characteristics\nthat made it so successful in newspaper, book, and journal\npublishing in it’s metal type incarnation. The essential\n‘Times-ness’ remains, but are with greater harmonisation of style\nacross the family.\u003c/p\u003e\n\u003cp dir=\"auto\"\u003e“Most digital versions of Times have been based on an optical size\nmodel that appears too light and fine when scaled down to typical\ntext sizes. In the design of STIX Two, we went back to specimens of\nsize-specific designs from the metal era, and adapted proportions,\nweights, and spacing of the 10pt and 12pt designs. The oft-noted\nmismatch between the style of different weights of Times has been\nresolved with a new bold design that matches the construction of the\nregular weight.”\u003c/p\u003e\n\u003c/blockquote\u003e\n\u003cdiv class=\"markdown-heading\" dir=\"auto\"\u003e\u003ch3 tabindex=\"-1\" class=\"heading-element\" dir=\"auto\"\u003eFont implementation decisions\u003c/h3\u003e\u003ca id=\"user-content-font-implementation-decisions\" class=\"anchor\" aria-label=\"Permalink: Font implementation decisions\" href=\"#font-implementation-decisions\"\u003e\u003csvg class=\"octicon octicon-link\" viewBox=\"0 0 16 16\" version=\"1.1\" width=\"16\" height=\"16\" aria-hidden=\"true\"\u003e\u003cpath d=\"m7.775 3.275 1.25-1.25a3.5 3.5 0 1 1 4.95 4.95l-2.5 2.5a3.5 3.5 0 0 1-4.95 0 .751.751 0 0 1 .018-1.042.751.751 0 0 1 1.042-.018 1.998 1.998 0 0 0 2.83 0l2.5-2.5a2.002 2.002 0 0 0-2.83-2.83l-1.25 1.25a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042Zm-4.69 9.64a1.998 1.998 0 0 0 2.83 0l1.25-1.25a.751.751 0 0 1 1.042.018.751.751 0 0 1 .018 1.042l-1.25 1.25a3.5 3.5 0 1 1-4.95-4.95l2.5-2.5a3.5 3.5 0 0 1 4.95 0 .751.751 0 0 1-.018 1.042.751.751 0 0 1-1.042.018 1.998 1.998 0 0 0-2.83 0l-2.5 2.5a1.998 1.998 0 0 0 0 2.83Z\"\u003e\u003c/path\u003e\u003c/svg\u003e\u003c/a\u003e\u003c/div\u003e\n\u003cul dir=\"auto\"\u003e\n\u003cli\u003e\n\u003cp dir=\"auto\"\u003eThe STIX fonts do not contain fixed-width or sans serif text faces.\u003c/p\u003e\n\u003c/li\u003e\n\u003cli\u003e\n\u003cp dir=\"auto\"\u003eThe sans serif, fraktur, script, etc., alphabets in Plane 1\n(U+1D400-U+1D4FF) are intended to be used only as technical symbols.\u003c/p\u003e\n\u003c/li\u003e\n\u003cli\u003e\n\u003cp dir=\"auto\"\u003eThese fonts are designed to support left-to-right typesetting in\nLatin-based scripts, with additional support for Greek and Cyrillic\ntext. Extensions to support other writing directions have been\nconsidered, but are currently deemed to be outside the scope of the\nSTIX project.\u003c/p\u003e\n\u003c/li\u003e\n\u003c/ul\u003e\n\u003cdiv class=\"markdown-heading\" dir=\"auto\"\u003e\u003ch3 tabindex=\"-1\" class=\"heading-element\" dir=\"auto\"\u003eNote to TeX users\u003c/h3\u003e\u003ca id=\"user-content-note-to-tex-users\" class=\"anchor\" aria-label=\"Permalink: Note to TeX users\" href=\"#note-to-tex-users\"\u003e\u003csvg class=\"octicon octicon-link\" viewBox=\"0 0 16 16\" version=\"1.1\" width=\"16\" height=\"16\" aria-hidden=\"true\"\u003e\u003cpath d=\"m7.775 3.275 1.25-1.25a3.5 3.5 0 1 1 4.95 4.95l-2.5 2.5a3.5 3.5 0 0 1-4.95 0 .751.751 0 0 1 .018-1.042.751.751 0 0 1 1.042-.018 1.998 1.998 0 0 0 2.83 0l2.5-2.5a2.002 2.002 0 0 0-2.83-2.83l-1.25 1.25a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042Zm-4.69 9.64a1.998 1.998 0 0 0 2.83 0l1.25-1.25a.751.751 0 0 1 1.042.018.751.751 0 0 1 .018 1.042l-1.25 1.25a3.5 3.5 0 1 1-4.95-4.95l2.5-2.5a3.5 3.5 0 0 1 4.95 0 .751.751 0 0 1-.018 1.042.751.751 0 0 1-1.042.018 1.998 1.998 0 0 0-2.83 0l-2.5 2.5a1.998 1.998 0 0 0 0 2.83Z\"\u003e\u003c/path\u003e\u003c/svg\u003e\u003c/a\u003e\u003c/div\u003e\n\u003cp dir=\"auto\"\u003eThese fonts have been tested with both\n\u003ca href=\"http://xetex.sourceforge.net/\" rel=\"nofollow\"\u003eXeTeX\u003c/a\u003e\nand\n\u003ca href=\"http://www.luatex.org/\" rel=\"nofollow\"\u003eluaTeX\u003c/a\u003e\nwith good results. For best results, XeTeX users will want to use\nversion 0.999992 or later of XeTeX, which ships with\n\u003ca href=\"https://www.tug.org/texlive/\" rel=\"nofollow\"\u003eTeXLive 2020\u003c/a\u003e.\nThis version fixes a number of bugs that were present in earlier\nversions. Our thanks go out to Jonathan Kew and Khaled Hosny for\ntheir generous help in identifying and fixing these bugs. LaTeX users\nshould also make sure they have the latest version of the\n\u003ca href=\"https://ctan.org/pkg/amsmath\" rel=\"nofollow\"\u003eamsmath package\u003c/a\u003e.\u003c/p\u003e\n\u003cdiv class=\"markdown-heading\" dir=\"auto\"\u003e\u003ch2 tabindex=\"-1\" class=\"heading-element\" dir=\"auto\"\u003eSummary of OpenType Features and Scripts\u003c/h2\u003e\u003ca id=\"user-content-summary-of-opentype-features-and-scripts\" class=\"anchor\" aria-label=\"Permalink: Summary of OpenType Features and Scripts\" href=\"#summary-of-opentype-features-and-scripts\"\u003e\u003csvg class=\"octicon octicon-link\" viewBox=\"0 0 16 16\" version=\"1.1\" width=\"16\" height=\"16\" aria-hidden=\"true\"\u003e\u003cpath d=\"m7.775 3.275 1.25-1.25a3.5 3.5 0 1 1 4.95 4.95l-2.5 2.5a3.5 3.5 0 0 1-4.95 0 .751.751 0 0 1 .018-1.042.751.751 0 0 1 1.042-.018 1.998 1.998 0 0 0 2.83 0l2.5-2.5a2.002 2.002 0 0 0-2.83-2.83l-1.25 1.25a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042Zm-4.69 9.64a1.998 1.998 0 0 0 2.83 0l1.25-1.25a.751.751 0 0 1 1.042.018.751.751 0 0 1 .018 1.042l-1.25 1.25a3.5 3.5 0 1 1-4.95-4.95l2.5-2.5a3.5 3.5 0 0 1 4.95 0 .751.751 0 0 1-.018 1.042.751.751 0 0 1-1.042.018 1.998 1.998 0 0 0-2.83 0l-2.5 2.5a1.998 1.998 0 0 0 0 2.83Z\"\u003e\u003c/path\u003e\u003c/svg\u003e\u003c/a\u003e\u003c/div\u003e\n\u003cp dir=\"auto\"\u003eFurther details these features can be found in the \u003ca href=\"/stipub/stixfonts/blob/master/docs\"\u003efont charts\u003c/a\u003e.\u003c/p\u003e\n\u003cp dir=\"auto\"\u003eThe text fonts implement the following OpenType script tags:\u003c/p\u003e\n\u003cdiv class=\"snippet-clipboard-content notranslate position-relative overflow-auto\" data-snippet-clipboard-copy-content=\"Regular Bold Italic BoldItalic\n\nDFLT DFLT DFLT DFLT Default\n\ncyrl cyrl cyrl cyrl Cyrillic\n cyrl.MKD cyrl.MKD Cyrillic/Macedonian\n cyrl.SRB cyrl.SRB Cyrillic/Serbian\n\ngrek grek grek grek Greek\n\nlatn latn latn latn Latin\nlatn.LTH latn.LTH latn.LTH latn.LTH Latin/Lithuanian\nlatn.ROM latn.ROM latn.ROM latn.ROM Latin/Romanian\nlatn.TRK latn.TRK latn.TRK latn.TRK Latin/Turkish\"\u003e\u003cpre class=\"notranslate\"\u003e\u003ccode\u003eRegular Bold Italic BoldItalic\n\nDFLT DFLT DFLT DFLT Default\n\ncyrl cyrl cyrl cyrl Cyrillic\n cyrl.MKD cyrl.MKD Cyrillic/Macedonian\n cyrl.SRB cyrl.SRB Cyrillic/Serbian\n\ngrek grek grek grek Greek\n\nlatn latn latn latn Latin\nlatn.LTH latn.LTH latn.LTH latn.LTH Latin/Lithuanian\nlatn.ROM latn.ROM latn.ROM latn.ROM Latin/Romanian\nlatn.TRK latn.TRK latn.TRK latn.TRK Latin/Turkish\n\u003c/code\u003e\u003c/pre\u003e\u003c/div\u003e\n\u003cp dir=\"auto\"\u003eand the following features\u003c/p\u003e\n\u003cdiv class=\"snippet-clipboard-content notranslate position-relative overflow-auto\" data-snippet-clipboard-copy-content=\"c2sc Small Capitals from Capitals\ncase Case-Sensitive Forms\nccmp Glyph Composition/Decomposition\ndnom Denominators\nfrac Fractions\nkern Kerning\nliga Standard Ligatures -- latn only\nlocl Localized Forms -- latn.ROM and Italic/BoldItalic cyrl.MKD only\nnumr Numerators\nonum Oldstyle Figures\npnum Proportional Figures\nsmcp Small Capitals\nsubs Subscript\nsups Superscript\"\u003e\u003cpre class=\"notranslate\"\u003e\u003ccode\u003ec2sc Small Capitals from Capitals\ncase Case-Sensitive Forms\nccmp Glyph Composition/Decomposition\ndnom Denominators\nfrac Fractions\nkern Kerning\nliga Standard Ligatures -- latn only\nlocl Localized Forms -- latn.ROM and Italic/BoldItalic cyrl.MKD only\nnumr Numerators\nonum Oldstyle Figures\npnum Proportional Figures\nsmcp Small Capitals\nsubs Subscript\nsups Superscript\n\u003c/code\u003e\u003c/pre\u003e\u003c/div\u003e\n\u003cp dir=\"auto\"\u003eAll four text fonts also support the following Character Variants:\u003c/p\u003e\n\u003cdiv class=\"snippet-clipboard-content notranslate position-relative overflow-auto\" data-snippet-clipboard-copy-content=\"cv01 U+019B Lambda with horizontal, not slanted stroke -- latn only\ncv02 U+0264 Rams horn with serifs -- latn only\ncv03 U+2423 OPEN BOX curved instead of straight\"\u003e\u003cpre class=\"notranslate\"\u003e\u003ccode\u003ecv01 U+019B Lambda with horizontal, not slanted stroke -- latn only\ncv02 U+0264 Rams horn with serifs -- latn only\ncv03 U+2423 OPEN BOX curved instead of straight\n\u003c/code\u003e\u003c/pre\u003e\u003c/div\u003e\n\u003cp dir=\"auto\"\u003eIn addition, the Italic and BoldItalic faces support the following\nStylistic Variants:\u003c/p\u003e\n\u003cdiv class=\"snippet-clipboard-content notranslate position-relative overflow-auto\" data-snippet-clipboard-copy-content=\"ss01 Replace two-story g by hooked g -- Italic/BoldItalic only\nss02 Upright parens, brackets, and braces -- Italic/BoldItalic only\"\u003e\u003cpre class=\"notranslate\"\u003e\u003ccode\u003ess01 Replace two-story g by hooked g -- Italic/BoldItalic only\nss02 Upright parens, brackets, and braces -- Italic/BoldItalic only\n\u003c/code\u003e\u003c/pre\u003e\u003c/div\u003e\n\u003cp dir=\"auto\"\u003eSTIX Two Math implements the following font features:\u003c/p\u003e\n\u003cdiv class=\"snippet-clipboard-content notranslate position-relative overflow-auto\" data-snippet-clipboard-copy-content=\"ccmp Glyph Composition/Decomposition\ndtls Dotless forms of i and j\nflac Flattened accents\nssty Math Script style alternates\"\u003e\u003cpre class=\"notranslate\"\u003e\u003ccode\u003eccmp Glyph Composition/Decomposition\ndtls Dotless forms of i and j\nflac Flattened accents\nssty Math Script style alternates\n\u003c/code\u003e\u003c/pre\u003e\u003c/div\u003e\n\u003cp dir=\"auto\"\u003eand the following Character Variants (note the different meaning of\ncv03 compared to the text fonts):\u003c/p\u003e\n\u003cdiv class=\"snippet-clipboard-content notranslate position-relative overflow-auto\" data-snippet-clipboard-copy-content=\"cv01 U+019B Lambda with horizontal, not slanted stroke -- latn only\ncv02 U+0264 Rams horn with serifs -- latn only\ncv03 Replace U+2205 EMPTY SET by an oblate form\ncv04 Replace U+2216 SET MINUS by a smaller form\"\u003e\u003cpre class=\"notranslate\"\u003e\u003ccode\u003ecv01 U+019B Lambda with horizontal, not slanted stroke -- latn only\ncv02 U+0264 Rams horn with serifs -- latn only\ncv03 Replace U+2205 EMPTY SET by an oblate form\ncv04 Replace U+2216 SET MINUS by a smaller form\n\u003c/code\u003e\u003c/pre\u003e\u003c/div\u003e\n\u003cp dir=\"auto\"\u003eand the following Stylistic Sets (again, note that ss01 and ss02 have\ndifferent meanings compared to the text fonts):\u003c/p\u003e\n\u003cdiv class=\"snippet-clipboard-content notranslate position-relative overflow-auto\" data-snippet-clipboard-copy-content=\"ss01 Stylistic Set 1 -- Math chancery to roundhand (\\mathcal -\u0026gt; \\mathscr)\nss02 Stylistic Set 2 -- Alternate italic forms: g, u, v, w, z\nss03 Stylistic Set 3 -- Horizontal crossbar variants\nss04 Stylistic Set 4 -- Minute, second and primes to long variants\nss05 Stylistic Set 5 -- Short arrow variants\nss06 Stylistic Set 6 -- Short/narrow variants\nss07 Stylistic Set 7 -- Alternate math symbols (product, summation, etc)\nss08 Stylistic Set 8 -- Upright integral variants; XITS compatible\nss09 Stylistic Set 9 -- Vertical slash variants; XITS compatible\nss10 Stylistic Set 10 -- Diagonal greater/lesser combination variants\nss11 Stylistic Set 11 -- Long slash not-equal combination variants\nss12 Stylistic Set 12 -- Low contrast (sans-like) variants\nss13 Stylistic Set 13 -- Horizontally flipped sine wave glyph\nss14 Stylistic Set 14 -- Tall variants\nss15 Stylistic Set 15 -- Slab serif symbol variants\nss16 Stylistic Set 16 -- Circled operator variants\nss20 Stylistic Set 20 -- Miscellaneous variants\"\u003e\u003cpre class=\"notranslate\"\u003e\u003ccode\u003ess01 Stylistic Set 1 -- Math chancery to roundhand (\\mathcal -\u0026gt; \\mathscr)\nss02 Stylistic Set 2 -- Alternate italic forms: g, u, v, w, z\nss03 Stylistic Set 3 -- Horizontal crossbar variants\nss04 Stylistic Set 4 -- Minute, second and primes to long variants\nss05 Stylistic Set 5 -- Short arrow variants\nss06 Stylistic Set 6 -- Short/narrow variants\nss07 Stylistic Set 7 -- Alternate math symbols (product, summation, etc)\nss08 Stylistic Set 8 -- Upright integral variants; XITS compatible\nss09 Stylistic Set 9 -- Vertical slash variants; XITS compatible\nss10 Stylistic Set 10 -- Diagonal greater/lesser combination variants\nss11 Stylistic Set 11 -- Long slash not-equal combination variants\nss12 Stylistic Set 12 -- Low contrast (sans-like) variants\nss13 Stylistic Set 13 -- Horizontally flipped sine wave glyph\nss14 Stylistic Set 14 -- Tall variants\nss15 Stylistic Set 15 -- Slab serif symbol variants\nss16 Stylistic Set 16 -- Circled operator variants\nss20 Stylistic Set 20 -- Miscellaneous variants\n\u003c/code\u003e\u003c/pre\u003e\u003c/div\u003e\n\u003cdiv class=\"markdown-heading\" dir=\"auto\"\u003e\u003ch2 tabindex=\"-1\" class=\"heading-element\" dir=\"auto\"\u003eBuild instructions\u003c/h2\u003e\u003ca id=\"user-content-build-instructions\" class=\"anchor\" aria-label=\"Permalink: Build instructions\" href=\"#build-instructions\"\u003e\u003csvg class=\"octicon octicon-link\" viewBox=\"0 0 16 16\" version=\"1.1\" width=\"16\" height=\"16\" aria-hidden=\"true\"\u003e\u003cpath d=\"m7.775 3.275 1.25-1.25a3.5 3.5 0 1 1 4.95 4.95l-2.5 2.5a3.5 3.5 0 0 1-4.95 0 .751.751 0 0 1 .018-1.042.751.751 0 0 1 1.042-.018 1.998 1.998 0 0 0 2.83 0l2.5-2.5a2.002 2.002 0 0 0-2.83-2.83l-1.25 1.25a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042Zm-4.69 9.64a1.998 1.998 0 0 0 2.83 0l1.25-1.25a.751.751 0 0 1 1.042.018.751.751 0 0 1 .018 1.042l-1.25 1.25a3.5 3.5 0 1 1-4.95-4.95l2.5-2.5a3.5 3.5 0 0 1 4.95 0 .751.751 0 0 1-.018 1.042.751.751 0 0 1-1.042.018 1.998 1.998 0 0 0-2.83 0l-2.5 2.5a1.998 1.998 0 0 0 0 2.83Z\"\u003e\u003c/path\u003e\u003c/svg\u003e\u003c/a\u003e\u003c/div\u003e\n\u003cp dir=\"auto\"\u003eAfter cloning the project, the fonts can be built using the \u003ccode\u003ebuild.sh\u003c/code\u003e script (use \u003ccode\u003e--verbose\u003c/code\u003e option for more detailed build log):\u003c/p\u003e\n\u003cdiv class=\"snippet-clipboard-content notranslate position-relative overflow-auto\" data-snippet-clipboard-copy-content=\"$ ./build.sh\"\u003e\u003cpre class=\"notranslate\"\u003e\u003ccode\u003e$ ./build.sh\n\u003c/code\u003e\u003c/pre\u003e\u003c/div\u003e\n\u003cp dir=\"auto\"\u003eThis may take several minutes to complete. The first time the script is called, it will create a Python virtual environment that will be also used for subsequent builds. Each time the script is called, the fonts will be rebuilt from scratch. The built fonts will be in \u003ccode\u003ebuild\u003c/code\u003e subdirectory, and should be manually copied and committed to \u003ccode\u003efonts\u003c/code\u003e subdirectory.\u003c/p\u003e\n\u003cdiv class=\"markdown-heading\" dir=\"auto\"\u003e\u003ch3 tabindex=\"-1\" class=\"heading-element\" dir=\"auto\"\u003eNotes on source formats and build process\u003c/h3\u003e\u003ca id=\"user-content-notes-on-source-formats-and-build-process\" class=\"anchor\" aria-label=\"Permalink: Notes on source formats and build process\" href=\"#notes-on-source-formats-and-build-process\"\u003e\u003csvg class=\"octicon octicon-link\" viewBox=\"0 0 16 16\" version=\"1.1\" width=\"16\" height=\"16\" aria-hidden=\"true\"\u003e\u003cpath d=\"m7.775 3.275 1.25-1.25a3.5 3.5 0 1 1 4.95 4.95l-2.5 2.5a3.5 3.5 0 0 1-4.95 0 .751.751 0 0 1 .018-1.042.751.751 0 0 1 1.042-.018 1.998 1.998 0 0 0 2.83 0l2.5-2.5a2.002 2.002 0 0 0-2.83-2.83l-1.25 1.25a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042Zm-4.69 9.64a1.998 1.998 0 0 0 2.83 0l1.25-1.25a.751.751 0 0 1 1.042.018.751.751 0 0 1 .018 1.042l-1.25 1.25a3.5 3.5 0 1 1-4.95-4.95l2.5-2.5a3.5 3.5 0 0 1 4.95 0 .751.751 0 0 1-.018 1.042.751.751 0 0 1-1.042.018 1.998 1.998 0 0 0-2.83 0l-2.5 2.5a1.998 1.998 0 0 0 0 2.83Z\"\u003e\u003c/path\u003e\u003c/svg\u003e\u003c/a\u003e\u003c/div\u003e\n\u003cp dir=\"auto\"\u003eThe design masters for the STIX Two Text fonts are the \u003cstrong\u003e.vfj\u003c/strong\u003e files, a json source format used by FontLab 7. These files contain the glyph outlines, spacing, mark anchors, kerning and associated classes, font info, and variable design space info. Changes or additions to any of these things should be made in the .vfj files.\u003c/p\u003e\n\u003cp dir=\"auto\"\u003eThe build script used to generate font files uses the \u003cstrong\u003e.ufo\u003c/strong\u003e and \u003cstrong\u003e.designspace\u003c/strong\u003e files, not the .vfj sources directly. These files can be exported from FontLab 7 using the default export profile for ‘DesignSpace + UFO’.\u003c/p\u003e\n\u003cp dir=\"auto\"\u003eThe \u003cstrong\u003e.ren\u003c/strong\u003e files are glyph name management files used by the build script to manage the relationship of development names in the sources to the build names used in the post or CFF tables of the fonts.\u003c/p\u003e\n\u003cp dir=\"auto\"\u003eBecause of issues with editing and managing OpenType Layout GPOS in variable font sources, the OTL projects for the STIX Two Text fonts are built in Microsoft’s \u003ca href=\"https://docs.microsoft.com/en-us/typography/tools/volt/\" rel=\"nofollow\"\u003eVisual OpenType Layout Tool\u003c/a\u003e (VOLT). This means changes to OTL, including updates to mark anchors and kerning implemented in the .vfj sources need to be passed through VOLT, updated in the \u003cstrong\u003e.vtp\u003c/strong\u003e VOLT project files, and compiled in \u003cstrong\u003e.input.ttf\u003c/strong\u003e which are then used by the build script as a source for the OTL tables in the fonts.\u003c/p\u003e\n\u003cp dir=\"auto\"\u003eObviously, any changes or extension to the glyph set in the .vfj design sources needs to be reflected in each of the other sources used in the build process: in the .ufo files, the .ren file glyph name lists, and especially in the .input.ttf files and .vtp project files. Fresh .input.ttf files can be exported from FontLab 7, opened in VOLT, and the .vtp project files imported and updated.\u003c/p\u003e\n\u003cp dir=\"auto\"\u003eNote that if changes or updates are made to mark anchors or kerning or associated classes in the .vfj sources, these need to be converted to VOLT format and imported into the projects, replacing or updating existing VOLT lookups and groups. This can be done using the \u003ca href=\"https://github.com/TiroTypeworks/TiroTools/tree/master/VFJtools\"\u003evfj-to-volt.py\u003c/a\u003e tool.\u003c/p\u003e\n\u003cp dir=\"auto\"\u003eThe revised .vtp files should then be exported for future use, and the .input.ttf fonts \u003cem\u003eshipped\u003c/em\u003e from VOLT (this is important, because although the fonts will work if just compiled and saved in VOLT, they will contain private VOLT source tables and unregistered OTL features that will be then end up in the fonts generated by the build script; so use the ‘Ship Font’ option in VOLT and overwrite the .input.ttf file (save a copy with the VOLT project, if you like, but so long as you remembered to export the updated .vtp you can always reimport as needed)).\u003c/p\u003e\n\u003cp dir=\"auto\"\u003e\u003cstrong\u003eIMPORTANT\u003c/strong\u003e : the STIXTwoMath-Regular.input.ttf file is also the source for the MATH table and cmap table in the final font build. Care must be taken to preserve or extend these as necessary in this file when updating OpenType Layout or other aspects of the font.\u003c/p\u003e\n\u003cp dir=\"auto\"\u003eOnce all the source files are ready, run the \u003cstrong\u003ebuild.sh\u003c/strong\u003e as described above. The build script describes what it is doing as it runs, and verbose mode can be used to get more detail. In overview, this is what it does:\u003c/p\u003e\n\u003col dir=\"auto\"\u003e\n\u003cli\u003ePre-process the UFO files to:\na) remove all features and kerning groups from the UFOs; b) rename the glyphs to match the TTFs (otherwise the binary tables can’t be grafted in with FontTools easily); c) extract the binary tables and add them under data/com.github.fonttools.ttx/ in the UFO font where ufo2ft expects them; d) save the modified files in build/masters to keep the sources unchanged.\u003c/li\u003e\n\u003cli\u003eBuild variable font with fontmake from build/masters UFOs.\u003c/li\u003e\n\u003cli\u003eBuild binary masters with fontmake (needed for the next step) from UFOs.\u003c/li\u003e\n\u003cli\u003eBuild static fonts with fontmake from UFOs, but telling it to interpolate OTL tables from the binary masters.\u003c/li\u003e\n\u003cli\u003ePost-process the fonts to fix the name tables and other final touchups.\u003c/li\u003e\n\u003c/ol\u003e\n\u003c/article\u003e","loaded":true,"timedOut":false,"errorMessage":null,"headerInfo":{"toc":[{"level":1,"text":"stixfonts","anchor":"stixfonts","htmlText":"stixfonts"},{"level":2,"text":"Overview","anchor":"overview","htmlText":"Overview"},{"level":3,"text":"Type 1 fonts (STIX 2.0.0 only)","anchor":"type-1-fonts-stix-200-only","htmlText":"Type 1 fonts (STIX 2.0.0 only)"},{"level":2,"text":"About the STIX fonts.","anchor":"about-the-stix-fonts","htmlText":"About the STIX fonts."},{"level":3,"text":"A Fresh Take on Times Roman","anchor":"a-fresh-take-on-times-roman","htmlText":"A Fresh Take on Times Roman"},{"level":3,"text":"Font implementation decisions","anchor":"font-implementation-decisions","htmlText":"Font implementation decisions"},{"level":3,"text":"Note to TeX users","anchor":"note-to-tex-users","htmlText":"Note to TeX users"},{"level":2,"text":"Summary of OpenType Features and Scripts","anchor":"summary-of-opentype-features-and-scripts","htmlText":"Summary of OpenType Features and Scripts"},{"level":2,"text":"Build instructions","anchor":"build-instructions","htmlText":"Build instructions"},{"level":3,"text":"Notes on source formats and build process","anchor":"notes-on-source-formats-and-build-process","htmlText":"Notes on source formats and build process"}],"siteNavLoginPath":"/login?return_to=https%3A%2F%2Fgithub.com%2Fstipub%2Fstixfonts%2F"}},{"displayName":"OFL.txt","repoName":"stixfonts","refName":"master","path":"OFL.txt","preferredFileType":"license","tabName":"OFL-1.1","richText":null,"loaded":false,"timedOut":false,"errorMessage":null,"headerInfo":{"toc":null,"siteNavLoginPath":"/login?return_to=https%3A%2F%2Fgithub.com%2Fstipub%2Fstixfonts%2F"}}],"overviewFilesProcessingTime":0,"copilotSWEAgentEnabled":false}},"appPayload":{"helpUrl":"https://docs.github.com","findFileWorkerPath":"/assets-cdn/worker/find-file-worker-0cea8c6113ab.js","findInFileWorkerPath":"/assets-cdn/worker/find-in-file-worker-105a4a160ddd.js","githubDevUrl":null,"enabled_features":{"copilot_workspace":null,"code_nav_ui_events":false,"react_blob_overlay":false,"accessible_code_button":true}}}}</script>- <div data-target="react-partial.reactRoot"> <!-- --> <!-- --> <div class="OverviewContent-module__Box--uNd1J"><div class="OverviewHeader-module__Box--fFKf5"></div><div class="OverviewContent-module__Box_1--RhaEy"><div class="OverviewContent-module__Box_2--uHewD"><div class="OverviewContent-module__Box_3--NEYWl"><button type="button" aria-haspopup="true" aria-expanded="false" tabindex="0" style="min-width:0" aria-label="master branch" data-testid="anchor-button" class="prc-Button-ButtonBase-c50BI overview-ref-selector width-full RefSelectorAnchoredOverlay-module__RefSelectorOverlayBtn--D34zl" data-loading="false" data-size="medium" data-variant="default" aria-describedby="ref-picker-repos-header-ref-selector-loading-announcement" id="ref-picker-repos-header-ref-selector"><span data-component="buttonContent" data-align="center" class="prc-Button-ButtonContent-HKbr-"><span data-component="text" class="prc-Button-Label-pTQ3x"><div class="RefSelectorAnchoredOverlay-module__RefSelectorOverlayContainer--mCbv8"><div class="RefSelectorAnchoredOverlay-module__RefSelectorOverlayHeader--D4cnZ"><svg aria-hidden="true" focusable="false" class="octicon octicon-git-branch" viewBox="0 0 16 16" width="16" height="16" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M9.5 3.25a2.25 2.25 0 1 1 3 2.122V6A2.5 2.5 0 0 1 10 8.5H6a1 1 0 0 0-1 1v1.128a2.251 2.251 0 1 1-1.5 0V5.372a2.25 2.25 0 1 1 1.5 0v1.836A2.493 2.493 0 0 1 6 7h4a1 1 0 0 0 1-1v-.628A2.25 2.25 0 0 1 9.5 3.25Zm-6 0a.75.75 0 1 0 1.5 0 .75.75 0 0 0-1.5 0Zm8.25-.75a.75.75 0 1 0 0 1.5.75.75 0 0 0 0-1.5ZM4.25 12a.75.75 0 1 0 0 1.5.75.75 0 0 0 0-1.5Z"></path></svg></div><div class="ref-selector-button-text-container RefSelectorAnchoredOverlay-module__RefSelectorBtnTextContainer--yO402"><span class="RefSelectorAnchoredOverlay-module__RefSelectorText--bxVhQ"> <!-- -->master</span></div></div></span><span data-component="trailingVisual" class="prc-Button-Visual-2epfX prc-Button-VisualWrap-Db-eB"><svg aria-hidden="true" focusable="false" class="octicon octicon-triangle-down" viewBox="0 0 16 16" width="16" height="16" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="m4.427 7.427 3.396 3.396a.25.25 0 0 0 .354 0l3.396-3.396A.25.25 0 0 0 11.396 7H4.604a.25.25 0 0 0-.177.427Z"></path></svg></span></span></button><button hidden="" data-testid="ref-selector-hotkey-button" data-hotkey-scope="read-only-cursor-text-area"></button></div><div class="OverviewContent-module__Box_4--rOz8J"><a type="button" href="/stipub/stixfonts/branches" class="prc-Button-ButtonBase-c50BI OverviewContent-module__Button--MDoYP" data-loading="false" data-size="medium" data-variant="invisible" aria-describedby=":Rclab:-loading-announcement"><span data-component="buttonContent" data-align="center" class="prc-Button-ButtonContent-HKbr-"><span data-component="leadingVisual" class="prc-Button-Visual-2epfX prc-Button-VisualWrap-Db-eB"><svg aria-hidden="true" focusable="false" class="octicon octicon-git-branch" viewBox="0 0 16 16" width="16" height="16" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M9.5 3.25a2.25 2.25 0 1 1 3 2.122V6A2.5 2.5 0 0 1 10 8.5H6a1 1 0 0 0-1 1v1.128a2.251 2.251 0 1 1-1.5 0V5.372a2.25 2.25 0 1 1 1.5 0v1.836A2.493 2.493 0 0 1 6 7h4a1 1 0 0 0 1-1v-.628A2.25 2.25 0 0 1 9.5 3.25Zm-6 0a.75.75 0 1 0 1.5 0 .75.75 0 0 0-1.5 0Zm8.25-.75a.75.75 0 1 0 0 1.5.75.75 0 0 0 0-1.5ZM4.25 12a.75.75 0 1 0 0 1.5.75.75 0 0 0 0-1.5Z"></path></svg></span><span data-component="text" class="prc-Button-Label-pTQ3x">Branches</span></span></a><a type="button" href="/stipub/stixfonts/tags" class="prc-Button-ButtonBase-c50BI OverviewContent-module__Button--MDoYP" data-loading="false" data-size="medium" data-variant="invisible" aria-describedby=":Rklab:-loading-announcement"><span data-component="buttonContent" data-align="center" class="prc-Button-ButtonContent-HKbr-"><span data-component="leadingVisual" class="prc-Button-Visual-2epfX prc-Button-VisualWrap-Db-eB"><svg aria-hidden="true" focusable="false" class="octicon octicon-tag" viewBox="0 0 16 16" width="16" height="16" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M1 7.775V2.75C1 1.784 1.784 1 2.75 1h5.025c.464 0 .91.184 1.238.513l6.25 6.25a1.75 1.75 0 0 1 0 2.474l-5.026 5.026a1.75 1.75 0 0 1-2.474 0l-6.25-6.25A1.752 1.752 0 0 1 1 7.775Zm1.5 0c0 .066.026.13.073.177l6.25 6.25a.25.25 0 0 0 .354 0l5.025-5.025a.25.25 0 0 0 0-.354l-6.25-6.25a.25.25 0 0 0-.177-.073H2.75a.25.25 0 0 0-.25.25ZM6 5a1 1 0 1 1 0 2 1 1 0 0 1 0-2Z"></path></svg></span><span data-component="text" class="prc-Button-Label-pTQ3x">Tags</span></span></a></div><div class="OverviewContent-module__Box_5--PPbL1"><a type="button" aria-label="Go to Branches page" href="/stipub/stixfonts/branches" class="prc-Button-ButtonBase-c50BI OverviewContent-module__Button_1--_1Ng2" data-loading="false" data-no-visuals="true" data-size="medium" data-variant="invisible" aria-describedby=":Relab:-loading-announcement"><svg aria-hidden="true" focusable="false" class="octicon octicon-git-branch" viewBox="0 0 16 16" width="16" height="16" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M9.5 3.25a2.25 2.25 0 1 1 3 2.122V6A2.5 2.5 0 0 1 10 8.5H6a1 1 0 0 0-1 1v1.128a2.251 2.251 0 1 1-1.5 0V5.372a2.25 2.25 0 1 1 1.5 0v1.836A2.493 2.493 0 0 1 6 7h4a1 1 0 0 0 1-1v-.628A2.25 2.25 0 0 1 9.5 3.25Zm-6 0a.75.75 0 1 0 1.5 0 .75.75 0 0 0-1.5 0Zm8.25-.75a.75.75 0 1 0 0 1.5.75.75 0 0 0 0-1.5ZM4.25 12a.75.75 0 1 0 0 1.5.75.75 0 0 0 0-1.5Z"></path></svg></a><a type="button" aria-label="Go to Tags page" href="/stipub/stixfonts/tags" class="prc-Button-ButtonBase-c50BI OverviewContent-module__Button_1--_1Ng2" data-loading="false" data-no-visuals="true" data-size="medium" data-variant="invisible" aria-describedby=":Rmlab:-loading-announcement"><svg aria-hidden="true" focusable="false" class="octicon octicon-tag" viewBox="0 0 16 16" width="16" height="16" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M1 7.775V2.75C1 1.784 1.784 1 2.75 1h5.025c.464 0 .91.184 1.238.513l6.25 6.25a1.75 1.75 0 0 1 0 2.474l-5.026 5.026a1.75 1.75 0 0 1-2.474 0l-6.25-6.25A1.752 1.752 0 0 1 1 7.775Zm1.5 0c0 .066.026.13.073.177l6.25 6.25a.25.25 0 0 0 .354 0l5.025-5.025a.25.25 0 0 0 0-.354l-6.25-6.25a.25.25 0 0 0-.177-.073H2.75a.25.25 0 0 0-.25.25ZM6 5a1 1 0 1 1 0 2 1 1 0 0 1 0-2Z"></path></svg></a></div></div><div class="OverviewContent-module__Box_6--wV7Tw"><div class="OverviewContent-module__Box_7--SbxdI"><div class="OverviewContent-module__Box_8--oumpR"><!--$--><div class="Box-sc-62in7e-0 OverviewContent-module__FileResultsList--irMg6"><span class="TextInput__StyledTextInput-sc-ttxlvl-0 d-flex FileResultsList-module__FilesSearchBox--fSAh3 TextInput-wrapper prc-components-TextInputWrapper-i1ofR prc-components-TextInputBaseWrapper-ueK9q" data-leading-visual="true" data-trailing-visual="true" aria-busy="false"><span class="TextInput-icon" id=":R535ab:" aria-hidden="true"><svg aria-hidden="true" focusable="false" class="octicon octicon-search" viewBox="0 0 16 16" width="16" height="16" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M10.68 11.74a6 6 0 0 1-7.922-8.982 6 6 0 0 1 8.982 7.922l3.04 3.04a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215ZM11.5 7a4.499 4.499 0 1 0-8.997 0A4.499 4.499 0 0 0 11.5 7Z"></path></svg></span><input type="text" aria-label="Go to file" role="combobox" aria-controls="file-results-list" aria-expanded="false" aria-haspopup="dialog" autoCorrect="off" spellcheck="false" placeholder="Go to file" aria-describedby=":R535ab: :R535abH1:" data-component="input" class="prc-components-Input-Ic-y8" value=""/><span class="TextInput-icon" id=":R535abH1:" aria-hidden="true"></span></span></div><!--/$--></div><div class="OverviewContent-module__Box_9--mQYON"><button type="button" class="prc-Button-ButtonBase-c50BI" data-loading="false" data-no-visuals="true" data-size="medium" data-variant="default" aria-describedby=":R1j5ab:-loading-announcement"><span data-component="buttonContent" data-align="center" class="prc-Button-ButtonContent-HKbr-"><span data-component="text" class="prc-Button-Label-pTQ3x">Go to file</span></span></button></div></div><button type="button" aria-haspopup="true" aria-expanded="false" tabindex="0" class="prc-Button-ButtonBase-c50BI" data-loading="false" data-size="medium" data-variant="primary" aria-describedby=":R75ab:-loading-announcement" id=":R75ab:"><span data-component="buttonContent" data-align="center" class="prc-Button-ButtonContent-HKbr-"><span data-component="leadingVisual" class="prc-Button-Visual-2epfX prc-Button-VisualWrap-Db-eB"><svg aria-hidden="true" focusable="false" class="octicon octicon-code hide-sm" viewBox="0 0 16 16" width="16" height="16" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="m11.28 3.22 4.25 4.25a.75.75 0 0 1 0 1.06l-4.25 4.25a.749.749 0 0 1-1.275-.326.749.749 0 0 1 .215-.734L13.94 8l-3.72-3.72a.749.749 0 0 1 .326-1.275.749.749 0 0 1 .734.215Zm-6.56 0a.751.751 0 0 1 1.042.018.751.751 0 0 1 .018 1.042L2.06 8l3.72 3.72a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215L.47 8.53a.75.75 0 0 1 0-1.06Z"></path></svg></span><span data-component="text" class="prc-Button-Label-pTQ3x">Code</span><span data-component="trailingVisual" class="prc-Button-Visual-2epfX prc-Button-VisualWrap-Db-eB"><svg aria-hidden="true" focusable="false" class="octicon octicon-triangle-down" viewBox="0 0 16 16" width="16" height="16" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="m4.427 7.427 3.396 3.396a.25.25 0 0 0 .354 0l3.396-3.396A.25.25 0 0 0 11.396 7H4.604a.25.25 0 0 0-.177.427Z"></path></svg></span></span></button><div class="OverviewContent-module__Box_10--ULKAG"><button data-component="IconButton" type="button" aria-haspopup="true" aria-expanded="false" tabindex="0" class="prc-Button-ButtonBase-c50BI prc-Button-IconButton-szpyj" data-loading="false" data-no-visuals="true" data-size="medium" data-variant="default" aria-describedby=":R95ab:-loading-announcement" aria-labelledby=":R7p5ab:" id=":R95ab:"><svg aria-hidden="true" focusable="false" class="octicon octicon-kebab-horizontal" viewBox="0 0 16 16" width="16" height="16" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M8 9a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3ZM1.5 9a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3Zm13 0a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3Z"></path></svg></button><span class="prc-TooltipV2-Tooltip-cYMVY" data-direction="n" aria-hidden="true" id=":R7p5ab:">Open more actions menu</span></div></div></div><div class="OverviewContent-module__Box_11--Tqhu2"><div data-hpc="true"><button hidden="" data-testid="focus-next-element-button" data-hotkey="j"></button><button hidden="" data-testid="focus-previous-element-button" data-hotkey="k"></button><h2 class="sr-only ScreenReaderHeading-module__userSelectNone--vlUbc prc-Heading-Heading-6CmGO" data-testid="screen-reader-heading" id="folders-and-files">Folders and files</h2><table class="Table-module__Box--KyMHK" aria-labelledby="folders-and-files"><thead class="DirectoryContent-module__OverviewHeaderRow--FlrUZ Table-module__Box_1--DkRqs"><tr class="Table-module__Box_2--l1wjV"><th colSpan="2" class="DirectoryContent-module__Box--y3Nvf"><span class="text-bold">Name</span></th><th colSpan="1" class="DirectoryContent-module__Box_1--xeAhp"><span class="text-bold">Name</span></th><th class="hide-sm"><div class="width-fit prc-Truncate-Truncate-A9Wn6" data-inline="true" title="Last commit message" style="--truncate-max-width:125px"><span class="text-bold">Last commit message</span></div></th><th colSpan="1" class="DirectoryContent-module__Box_2--h912w"><div class="width-fit prc-Truncate-Truncate-A9Wn6" data-inline="true" title="Last commit date" style="--truncate-max-width:125px"><span class="text-bold">Last commit date</span></div></th></tr></thead><tbody><tr class="DirectoryContent-module__Box_3--zI0N1"><td colSpan="3" class="bgColor-muted p-1 rounded-top-2"><div class="LatestCommit-module__Box--Fimpo"><h2 class="sr-only ScreenReaderHeading-module__userSelectNone--vlUbc prc-Heading-Heading-6CmGO" data-testid="screen-reader-heading">Latest commit</h2><div style="width:120px" class="Skeleton Skeleton--text" data-testid="loading"> </div><div class="d-flex flex-shrink-0 gap-2"><div data-testid="latest-commit-details" class="d-none d-sm-flex flex-items-center"></div><div class="d-flex gap-2"><h2 class="sr-only ScreenReaderHeading-module__userSelectNone--vlUbc prc-Heading-Heading-6CmGO" data-testid="screen-reader-heading">History</h2><a href="/stipub/stixfonts/commits/master/" class="prc-Button-ButtonBase-c50BI d-none d-lg-flex LinkButton-module__code-view-link-button--thtqc flex-items-center fgColor-default" data-loading="false" data-size="small" data-variant="invisible" aria-describedby=":Raqj8pab:-loading-announcement"><span data-component="buttonContent" data-align="center" class="prc-Button-ButtonContent-HKbr-"><span data-component="leadingVisual" class="prc-Button-Visual-2epfX prc-Button-VisualWrap-Db-eB"><svg aria-hidden="true" focusable="false" class="octicon octicon-history" viewBox="0 0 16 16" width="16" height="16" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="m.427 1.927 1.215 1.215a8.002 8.002 0 1 1-1.6 5.685.75.75 0 1 1 1.493-.154 6.5 6.5 0 1 0 1.18-4.458l1.358 1.358A.25.25 0 0 1 3.896 6H.25A.25.25 0 0 1 0 5.75V2.104a.25.25 0 0 1 .427-.177ZM7.75 4a.75.75 0 0 1 .75.75v2.992l2.028.812a.75.75 0 0 1-.557 1.392l-2.5-1A.751.751 0 0 1 7 8.25v-3.5A.75.75 0 0 1 7.75 4Z"></path></svg></span><span data-component="text" class="prc-Button-Label-pTQ3x"><span class="fgColor-default">70 Commits</span></span></span></a><div class="d-sm-none"></div><div class="d-flex d-lg-none"><span role="tooltip" aria-label="70 Commits" id="history-icon-button-tooltip" class="prc-Tooltip-Tooltip--1XZX prc-Tooltip-Tooltip--n-BOOzB tooltipped-n"><a aria-label="View commit history for this file." href="/stipub/stixfonts/commits/master/" class="prc-Button-ButtonBase-c50BI LinkButton-module__code-view-link-button--thtqc flex-items-center fgColor-default" data-loading="false" data-size="small" data-variant="invisible" aria-describedby=":R1iqj8pab:-loading-announcement history-icon-button-tooltip"><span data-component="buttonContent" data-align="center" class="prc-Button-ButtonContent-HKbr-"><span data-component="leadingVisual" class="prc-Button-Visual-2epfX prc-Button-VisualWrap-Db-eB"><svg aria-hidden="true" focusable="false" class="octicon octicon-history" viewBox="0 0 16 16" width="16" height="16" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="m.427 1.927 1.215 1.215a8.002 8.002 0 1 1-1.6 5.685.75.75 0 1 1 1.493-.154 6.5 6.5 0 1 0 1.18-4.458l1.358 1.358A.25.25 0 0 1 3.896 6H.25A.25.25 0 0 1 0 5.75V2.104a.25.25 0 0 1 .427-.177ZM7.75 4a.75.75 0 0 1 .75.75v2.992l2.028.812a.75.75 0 0 1-.557 1.392l-2.5-1A.751.751 0 0 1 7 8.25v-3.5A.75.75 0 0 1 7.75 4Z"></path></svg></span></span></a></span></div></div></div></div></td></tr><tr class="react-directory-row undefined" id="folder-row-0"><td class="react-directory-row-name-cell-small-screen" colSpan="2"><div class="react-directory-filename-column"><svg aria-hidden="true" focusable="false" class="octicon octicon-file-directory-fill icon-directory" viewBox="0 0 16 16" width="16" height="16" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M1.75 1A1.75 1.75 0 0 0 0 2.75v10.5C0 14.216.784 15 1.75 15h12.5A1.75 1.75 0 0 0 16 13.25v-8.5A1.75 1.75 0 0 0 14.25 3H7.5a.25.25 0 0 1-.2-.1l-.9-1.2C6.07 1.26 5.55 1 5 1H1.75Z"></path></svg><div class="overflow-hidden"><div class="react-directory-filename-cell"><div class="react-directory-truncate"><a title="archive" aria-label="archive, (Directory)" class="Link--primary" href="/stipub/stixfonts/tree/master/archive" data-discover="true">archive</a></div></div></div></div></td><td class="react-directory-row-name-cell-large-screen" colSpan="1"><div class="react-directory-filename-column"><svg aria-hidden="true" focusable="false" class="octicon octicon-file-directory-fill icon-directory" viewBox="0 0 16 16" width="16" height="16" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M1.75 1A1.75 1.75 0 0 0 0 2.75v10.5C0 14.216.784 15 1.75 15h12.5A1.75 1.75 0 0 0 16 13.25v-8.5A1.75 1.75 0 0 0 14.25 3H7.5a.25.25 0 0 1-.2-.1l-.9-1.2C6.07 1.26 5.55 1 5 1H1.75Z"></path></svg><div class="overflow-hidden"><div class="react-directory-filename-cell"><div class="react-directory-truncate"><a title="archive" aria-label="archive, (Directory)" class="Link--primary" href="/stipub/stixfonts/tree/master/archive" data-discover="true">archive</a></div></div></div></div></td><td class="react-directory-row-commit-cell"><div class="Skeleton Skeleton--text"> </div></td><td><div class="Skeleton Skeleton--text"> </div></td></tr><tr class="react-directory-row undefined" id="folder-row-1"><td class="react-directory-row-name-cell-small-screen" colSpan="2"><div class="react-directory-filename-column"><svg aria-hidden="true" focusable="false" class="octicon octicon-file-directory-fill icon-directory" viewBox="0 0 16 16" width="16" height="16" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M1.75 1A1.75 1.75 0 0 0 0 2.75v10.5C0 14.216.784 15 1.75 15h12.5A1.75 1.75 0 0 0 16 13.25v-8.5A1.75 1.75 0 0 0 14.25 3H7.5a.25.25 0 0 1-.2-.1l-.9-1.2C6.07 1.26 5.55 1 5 1H1.75Z"></path></svg><div class="overflow-hidden"><div class="react-directory-filename-cell"><div class="react-directory-truncate"><a title="docs" aria-label="docs, (Directory)" class="Link--primary" href="/stipub/stixfonts/tree/master/docs" data-discover="true">docs</a></div></div></div></div></td><td class="react-directory-row-name-cell-large-screen" colSpan="1"><div class="react-directory-filename-column"><svg aria-hidden="true" focusable="false" class="octicon octicon-file-directory-fill icon-directory" viewBox="0 0 16 16" width="16" height="16" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M1.75 1A1.75 1.75 0 0 0 0 2.75v10.5C0 14.216.784 15 1.75 15h12.5A1.75 1.75 0 0 0 16 13.25v-8.5A1.75 1.75 0 0 0 14.25 3H7.5a.25.25 0 0 1-.2-.1l-.9-1.2C6.07 1.26 5.55 1 5 1H1.75Z"></path></svg><div class="overflow-hidden"><div class="react-directory-filename-cell"><div class="react-directory-truncate"><a title="docs" aria-label="docs, (Directory)" class="Link--primary" href="/stipub/stixfonts/tree/master/docs" data-discover="true">docs</a></div></div></div></div></td><td class="react-directory-row-commit-cell"><div class="Skeleton Skeleton--text"> </div></td><td><div class="Skeleton Skeleton--text"> </div></td></tr><tr class="react-directory-row undefined" id="folder-row-2"><td class="react-directory-row-name-cell-small-screen" colSpan="2"><div class="react-directory-filename-column"><svg aria-hidden="true" focusable="false" class="octicon octicon-file-directory-fill icon-directory" viewBox="0 0 16 16" width="16" height="16" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M1.75 1A1.75 1.75 0 0 0 0 2.75v10.5C0 14.216.784 15 1.75 15h12.5A1.75 1.75 0 0 0 16 13.25v-8.5A1.75 1.75 0 0 0 14.25 3H7.5a.25.25 0 0 1-.2-.1l-.9-1.2C6.07 1.26 5.55 1 5 1H1.75Z"></path></svg><div class="overflow-hidden"><div class="react-directory-filename-cell"><div class="react-directory-truncate"><a title="fonts" aria-label="fonts, (Directory)" class="Link--primary" href="/stipub/stixfonts/tree/master/fonts" data-discover="true">fonts</a></div></div></div></div></td><td class="react-directory-row-name-cell-large-screen" colSpan="1"><div class="react-directory-filename-column"><svg aria-hidden="true" focusable="false" class="octicon octicon-file-directory-fill icon-directory" viewBox="0 0 16 16" width="16" height="16" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M1.75 1A1.75 1.75 0 0 0 0 2.75v10.5C0 14.216.784 15 1.75 15h12.5A1.75 1.75 0 0 0 16 13.25v-8.5A1.75 1.75 0 0 0 14.25 3H7.5a.25.25 0 0 1-.2-.1l-.9-1.2C6.07 1.26 5.55 1 5 1H1.75Z"></path></svg><div class="overflow-hidden"><div class="react-directory-filename-cell"><div class="react-directory-truncate"><a title="fonts" aria-label="fonts, (Directory)" class="Link--primary" href="/stipub/stixfonts/tree/master/fonts" data-discover="true">fonts</a></div></div></div></div></td><td class="react-directory-row-commit-cell"><div class="Skeleton Skeleton--text"> </div></td><td><div class="Skeleton Skeleton--text"> </div></td></tr><tr class="react-directory-row undefined" id="folder-row-3"><td class="react-directory-row-name-cell-small-screen" colSpan="2"><div class="react-directory-filename-column"><svg aria-hidden="true" focusable="false" class="octicon octicon-file-directory-fill icon-directory" viewBox="0 0 16 16" width="16" height="16" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M1.75 1A1.75 1.75 0 0 0 0 2.75v10.5C0 14.216.784 15 1.75 15h12.5A1.75 1.75 0 0 0 16 13.25v-8.5A1.75 1.75 0 0 0 14.25 3H7.5a.25.25 0 0 1-.2-.1l-.9-1.2C6.07 1.26 5.55 1 5 1H1.75Z"></path></svg><div class="overflow-hidden"><div class="react-directory-filename-cell"><div class="react-directory-truncate"><a title="source" aria-label="source, (Directory)" class="Link--primary" href="/stipub/stixfonts/tree/master/source" data-discover="true">source</a></div></div></div></div></td><td class="react-directory-row-name-cell-large-screen" colSpan="1"><div class="react-directory-filename-column"><svg aria-hidden="true" focusable="false" class="octicon octicon-file-directory-fill icon-directory" viewBox="0 0 16 16" width="16" height="16" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M1.75 1A1.75 1.75 0 0 0 0 2.75v10.5C0 14.216.784 15 1.75 15h12.5A1.75 1.75 0 0 0 16 13.25v-8.5A1.75 1.75 0 0 0 14.25 3H7.5a.25.25 0 0 1-.2-.1l-.9-1.2C6.07 1.26 5.55 1 5 1H1.75Z"></path></svg><div class="overflow-hidden"><div class="react-directory-filename-cell"><div class="react-directory-truncate"><a title="source" aria-label="source, (Directory)" class="Link--primary" href="/stipub/stixfonts/tree/master/source" data-discover="true">source</a></div></div></div></div></td><td class="react-directory-row-commit-cell"><div class="Skeleton Skeleton--text"> </div></td><td><div class="Skeleton Skeleton--text"> </div></td></tr><tr class="react-directory-row undefined" id="folder-row-4"><td class="react-directory-row-name-cell-small-screen" colSpan="2"><div class="react-directory-filename-column"><svg aria-hidden="true" focusable="false" class="octicon octicon-file-directory-fill icon-directory" viewBox="0 0 16 16" width="16" height="16" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M1.75 1A1.75 1.75 0 0 0 0 2.75v10.5C0 14.216.784 15 1.75 15h12.5A1.75 1.75 0 0 0 16 13.25v-8.5A1.75 1.75 0 0 0 14.25 3H7.5a.25.25 0 0 1-.2-.1l-.9-1.2C6.07 1.26 5.55 1 5 1H1.75Z"></path></svg><div class="overflow-hidden"><div class="react-directory-filename-cell"><div class="react-directory-truncate"><a title="tools" aria-label="tools, (Directory)" class="Link--primary" href="/stipub/stixfonts/tree/master/tools" data-discover="true">tools</a></div></div></div></div></td><td class="react-directory-row-name-cell-large-screen" colSpan="1"><div class="react-directory-filename-column"><svg aria-hidden="true" focusable="false" class="octicon octicon-file-directory-fill icon-directory" viewBox="0 0 16 16" width="16" height="16" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M1.75 1A1.75 1.75 0 0 0 0 2.75v10.5C0 14.216.784 15 1.75 15h12.5A1.75 1.75 0 0 0 16 13.25v-8.5A1.75 1.75 0 0 0 14.25 3H7.5a.25.25 0 0 1-.2-.1l-.9-1.2C6.07 1.26 5.55 1 5 1H1.75Z"></path></svg><div class="overflow-hidden"><div class="react-directory-filename-cell"><div class="react-directory-truncate"><a title="tools" aria-label="tools, (Directory)" class="Link--primary" href="/stipub/stixfonts/tree/master/tools" data-discover="true">tools</a></div></div></div></div></td><td class="react-directory-row-commit-cell"><div class="Skeleton Skeleton--text"> </div></td><td><div class="Skeleton Skeleton--text"> </div></td></tr><tr class="react-directory-row undefined" id="folder-row-5"><td class="react-directory-row-name-cell-small-screen" colSpan="2"><div class="react-directory-filename-column"><svg aria-hidden="true" focusable="false" class="octicon octicon-file-directory-fill icon-directory" viewBox="0 0 16 16" width="16" height="16" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M1.75 1A1.75 1.75 0 0 0 0 2.75v10.5C0 14.216.784 15 1.75 15h12.5A1.75 1.75 0 0 0 16 13.25v-8.5A1.75 1.75 0 0 0 14.25 3H7.5a.25.25 0 0 1-.2-.1l-.9-1.2C6.07 1.26 5.55 1 5 1H1.75Z"></path></svg><div class="overflow-hidden"><div class="react-directory-filename-cell"><div class="react-directory-truncate"><a title="zipfiles" aria-label="zipfiles, (Directory)" class="Link--primary" href="/stipub/stixfonts/tree/master/zipfiles" data-discover="true">zipfiles</a></div></div></div></div></td><td class="react-directory-row-name-cell-large-screen" colSpan="1"><div class="react-directory-filename-column"><svg aria-hidden="true" focusable="false" class="octicon octicon-file-directory-fill icon-directory" viewBox="0 0 16 16" width="16" height="16" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M1.75 1A1.75 1.75 0 0 0 0 2.75v10.5C0 14.216.784 15 1.75 15h12.5A1.75 1.75 0 0 0 16 13.25v-8.5A1.75 1.75 0 0 0 14.25 3H7.5a.25.25 0 0 1-.2-.1l-.9-1.2C6.07 1.26 5.55 1 5 1H1.75Z"></path></svg><div class="overflow-hidden"><div class="react-directory-filename-cell"><div class="react-directory-truncate"><a title="zipfiles" aria-label="zipfiles, (Directory)" class="Link--primary" href="/stipub/stixfonts/tree/master/zipfiles" data-discover="true">zipfiles</a></div></div></div></div></td><td class="react-directory-row-commit-cell"><div class="Skeleton Skeleton--text"> </div></td><td><div class="Skeleton Skeleton--text"> </div></td></tr><tr class="react-directory-row undefined" id="folder-row-6"><td class="react-directory-row-name-cell-small-screen" colSpan="2"><div class="react-directory-filename-column"><svg aria-hidden="true" focusable="false" class="octicon octicon-file color-fg-muted" viewBox="0 0 16 16" width="16" height="16" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M2 1.75C2 .784 2.784 0 3.75 0h6.586c.464 0 .909.184 1.237.513l2.914 2.914c.329.328.513.773.513 1.237v9.586A1.75 1.75 0 0 1 13.25 16h-9.5A1.75 1.75 0 0 1 2 14.25Zm1.75-.25a.25.25 0 0 0-.25.25v12.5c0 .138.112.25.25.25h9.5a.25.25 0 0 0 .25-.25V6h-2.75A1.75 1.75 0 0 1 9 4.25V1.5Zm6.75.062V4.25c0 .138.112.25.25.25h2.688l-.011-.013-2.914-2.914-.013-.011Z"></path></svg><div class="overflow-hidden"><div class="react-directory-filename-cell"><div class="react-directory-truncate"><a title=".gitignore" aria-label=".gitignore, (File)" class="Link--primary" href="/stipub/stixfonts/blob/master/.gitignore" data-discover="true">.gitignore</a></div></div></div></div></td><td class="react-directory-row-name-cell-large-screen" colSpan="1"><div class="react-directory-filename-column"><svg aria-hidden="true" focusable="false" class="octicon octicon-file color-fg-muted" viewBox="0 0 16 16" width="16" height="16" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M2 1.75C2 .784 2.784 0 3.75 0h6.586c.464 0 .909.184 1.237.513l2.914 2.914c.329.328.513.773.513 1.237v9.586A1.75 1.75 0 0 1 13.25 16h-9.5A1.75 1.75 0 0 1 2 14.25Zm1.75-.25a.25.25 0 0 0-.25.25v12.5c0 .138.112.25.25.25h9.5a.25.25 0 0 0 .25-.25V6h-2.75A1.75 1.75 0 0 1 9 4.25V1.5Zm6.75.062V4.25c0 .138.112.25.25.25h2.688l-.011-.013-2.914-2.914-.013-.011Z"></path></svg><div class="overflow-hidden"><div class="react-directory-filename-cell"><div class="react-directory-truncate"><a title=".gitignore" aria-label=".gitignore, (File)" class="Link--primary" href="/stipub/stixfonts/blob/master/.gitignore" data-discover="true">.gitignore</a></div></div></div></div></td><td class="react-directory-row-commit-cell"><div class="Skeleton Skeleton--text"> </div></td><td><div class="Skeleton Skeleton--text"> </div></td></tr><tr class="react-directory-row undefined" id="folder-row-7"><td class="react-directory-row-name-cell-small-screen" colSpan="2"><div class="react-directory-filename-column"><svg aria-hidden="true" focusable="false" class="octicon octicon-file color-fg-muted" viewBox="0 0 16 16" width="16" height="16" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M2 1.75C2 .784 2.784 0 3.75 0h6.586c.464 0 .909.184 1.237.513l2.914 2.914c.329.328.513.773.513 1.237v9.586A1.75 1.75 0 0 1 13.25 16h-9.5A1.75 1.75 0 0 1 2 14.25Zm1.75-.25a.25.25 0 0 0-.25.25v12.5c0 .138.112.25.25.25h9.5a.25.25 0 0 0 .25-.25V6h-2.75A1.75 1.75 0 0 1 9 4.25V1.5Zm6.75.062V4.25c0 .138.112.25.25.25h2.688l-.011-.013-2.914-2.914-.013-.011Z"></path></svg><div class="overflow-hidden"><div class="react-directory-filename-cell"><div class="react-directory-truncate"><a title="AUTHORS.txt" aria-label="AUTHORS.txt, (File)" class="Link--primary" href="/stipub/stixfonts/blob/master/AUTHORS.txt" data-discover="true">AUTHORS.txt</a></div></div></div></div></td><td class="react-directory-row-name-cell-large-screen" colSpan="1"><div class="react-directory-filename-column"><svg aria-hidden="true" focusable="false" class="octicon octicon-file color-fg-muted" viewBox="0 0 16 16" width="16" height="16" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M2 1.75C2 .784 2.784 0 3.75 0h6.586c.464 0 .909.184 1.237.513l2.914 2.914c.329.328.513.773.513 1.237v9.586A1.75 1.75 0 0 1 13.25 16h-9.5A1.75 1.75 0 0 1 2 14.25Zm1.75-.25a.25.25 0 0 0-.25.25v12.5c0 .138.112.25.25.25h9.5a.25.25 0 0 0 .25-.25V6h-2.75A1.75 1.75 0 0 1 9 4.25V1.5Zm6.75.062V4.25c0 .138.112.25.25.25h2.688l-.011-.013-2.914-2.914-.013-.011Z"></path></svg><div class="overflow-hidden"><div class="react-directory-filename-cell"><div class="react-directory-truncate"><a title="AUTHORS.txt" aria-label="AUTHORS.txt, (File)" class="Link--primary" href="/stipub/stixfonts/blob/master/AUTHORS.txt" data-discover="true">AUTHORS.txt</a></div></div></div></div></td><td class="react-directory-row-commit-cell"><div class="Skeleton Skeleton--text"> </div></td><td><div class="Skeleton Skeleton--text"> </div></td></tr><tr class="react-directory-row undefined" id="folder-row-8"><td class="react-directory-row-name-cell-small-screen" colSpan="2"><div class="react-directory-filename-column"><svg aria-hidden="true" focusable="false" class="octicon octicon-file color-fg-muted" viewBox="0 0 16 16" width="16" height="16" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M2 1.75C2 .784 2.784 0 3.75 0h6.586c.464 0 .909.184 1.237.513l2.914 2.914c.329.328.513.773.513 1.237v9.586A1.75 1.75 0 0 1 13.25 16h-9.5A1.75 1.75 0 0 1 2 14.25Zm1.75-.25a.25.25 0 0 0-.25.25v12.5c0 .138.112.25.25.25h9.5a.25.25 0 0 0 .25-.25V6h-2.75A1.75 1.75 0 0 1 9 4.25V1.5Zm6.75.062V4.25c0 .138.112.25.25.25h2.688l-.011-.013-2.914-2.914-.013-.011Z"></path></svg><div class="overflow-hidden"><div class="react-directory-filename-cell"><div class="react-directory-truncate"><a title="CONTRIBUTORS.txt" aria-label="CONTRIBUTORS.txt, (File)" class="Link--primary" href="/stipub/stixfonts/blob/master/CONTRIBUTORS.txt" data-discover="true">CONTRIBUTORS.txt</a></div></div></div></div></td><td class="react-directory-row-name-cell-large-screen" colSpan="1"><div class="react-directory-filename-column"><svg aria-hidden="true" focusable="false" class="octicon octicon-file color-fg-muted" viewBox="0 0 16 16" width="16" height="16" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M2 1.75C2 .784 2.784 0 3.75 0h6.586c.464 0 .909.184 1.237.513l2.914 2.914c.329.328.513.773.513 1.237v9.586A1.75 1.75 0 0 1 13.25 16h-9.5A1.75 1.75 0 0 1 2 14.25Zm1.75-.25a.25.25 0 0 0-.25.25v12.5c0 .138.112.25.25.25h9.5a.25.25 0 0 0 .25-.25V6h-2.75A1.75 1.75 0 0 1 9 4.25V1.5Zm6.75.062V4.25c0 .138.112.25.25.25h2.688l-.011-.013-2.914-2.914-.013-.011Z"></path></svg><div class="overflow-hidden"><div class="react-directory-filename-cell"><div class="react-directory-truncate"><a title="CONTRIBUTORS.txt" aria-label="CONTRIBUTORS.txt, (File)" class="Link--primary" href="/stipub/stixfonts/blob/master/CONTRIBUTORS.txt" data-discover="true">CONTRIBUTORS.txt</a></div></div></div></div></td><td class="react-directory-row-commit-cell"><div class="Skeleton Skeleton--text"> </div></td><td><div class="Skeleton Skeleton--text"> </div></td></tr><tr class="react-directory-row undefined" id="folder-row-9"><td class="react-directory-row-name-cell-small-screen" colSpan="2"><div class="react-directory-filename-column"><svg aria-hidden="true" focusable="false" class="octicon octicon-file color-fg-muted" viewBox="0 0 16 16" width="16" height="16" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M2 1.75C2 .784 2.784 0 3.75 0h6.586c.464 0 .909.184 1.237.513l2.914 2.914c.329.328.513.773.513 1.237v9.586A1.75 1.75 0 0 1 13.25 16h-9.5A1.75 1.75 0 0 1 2 14.25Zm1.75-.25a.25.25 0 0 0-.25.25v12.5c0 .138.112.25.25.25h9.5a.25.25 0 0 0 .25-.25V6h-2.75A1.75 1.75 0 0 1 9 4.25V1.5Zm6.75.062V4.25c0 .138.112.25.25.25h2.688l-.011-.013-2.914-2.914-.013-.011Z"></path></svg><div class="overflow-hidden"><div class="react-directory-filename-cell"><div class="react-directory-truncate"><a title="DESCRIPTION.en_us.html" aria-label="DESCRIPTION.en_us.html, (File)" class="Link--primary" href="/stipub/stixfonts/blob/master/DESCRIPTION.en_us.html" data-discover="true">DESCRIPTION.en_us.html</a></div></div></div></div></td><td class="react-directory-row-name-cell-large-screen" colSpan="1"><div class="react-directory-filename-column"><svg aria-hidden="true" focusable="false" class="octicon octicon-file color-fg-muted" viewBox="0 0 16 16" width="16" height="16" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M2 1.75C2 .784 2.784 0 3.75 0h6.586c.464 0 .909.184 1.237.513l2.914 2.914c.329.328.513.773.513 1.237v9.586A1.75 1.75 0 0 1 13.25 16h-9.5A1.75 1.75 0 0 1 2 14.25Zm1.75-.25a.25.25 0 0 0-.25.25v12.5c0 .138.112.25.25.25h9.5a.25.25 0 0 0 .25-.25V6h-2.75A1.75 1.75 0 0 1 9 4.25V1.5Zm6.75.062V4.25c0 .138.112.25.25.25h2.688l-.011-.013-2.914-2.914-.013-.011Z"></path></svg><div class="overflow-hidden"><div class="react-directory-filename-cell"><div class="react-directory-truncate"><a title="DESCRIPTION.en_us.html" aria-label="DESCRIPTION.en_us.html, (File)" class="Link--primary" href="/stipub/stixfonts/blob/master/DESCRIPTION.en_us.html" data-discover="true">DESCRIPTION.en_us.html</a></div></div></div></div></td><td class="react-directory-row-commit-cell"><div class="Skeleton Skeleton--text"> </div></td><td><div class="Skeleton Skeleton--text"> </div></td></tr><tr class="react-directory-row truncate-for-mobile" id="folder-row-10"><td class="react-directory-row-name-cell-small-screen" colSpan="2"><div class="react-directory-filename-column"><svg aria-hidden="true" focusable="false" class="octicon octicon-file color-fg-muted" viewBox="0 0 16 16" width="16" height="16" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M2 1.75C2 .784 2.784 0 3.75 0h6.586c.464 0 .909.184 1.237.513l2.914 2.914c.329.328.513.773.513 1.237v9.586A1.75 1.75 0 0 1 13.25 16h-9.5A1.75 1.75 0 0 1 2 14.25Zm1.75-.25a.25.25 0 0 0-.25.25v12.5c0 .138.112.25.25.25h9.5a.25.25 0 0 0 .25-.25V6h-2.75A1.75 1.75 0 0 1 9 4.25V1.5Zm6.75.062V4.25c0 .138.112.25.25.25h2.688l-.011-.013-2.914-2.914-.013-.011Z"></path></svg><div class="overflow-hidden"><div class="react-directory-filename-cell"><div class="react-directory-truncate"><a title="FONTLOG.txt" aria-label="FONTLOG.txt, (File)" class="Link--primary" href="/stipub/stixfonts/blob/master/FONTLOG.txt" data-discover="true">FONTLOG.txt</a></div></div></div></div></td><td class="react-directory-row-name-cell-large-screen" colSpan="1"><div class="react-directory-filename-column"><svg aria-hidden="true" focusable="false" class="octicon octicon-file color-fg-muted" viewBox="0 0 16 16" width="16" height="16" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M2 1.75C2 .784 2.784 0 3.75 0h6.586c.464 0 .909.184 1.237.513l2.914 2.914c.329.328.513.773.513 1.237v9.586A1.75 1.75 0 0 1 13.25 16h-9.5A1.75 1.75 0 0 1 2 14.25Zm1.75-.25a.25.25 0 0 0-.25.25v12.5c0 .138.112.25.25.25h9.5a.25.25 0 0 0 .25-.25V6h-2.75A1.75 1.75 0 0 1 9 4.25V1.5Zm6.75.062V4.25c0 .138.112.25.25.25h2.688l-.011-.013-2.914-2.914-.013-.011Z"></path></svg><div class="overflow-hidden"><div class="react-directory-filename-cell"><div class="react-directory-truncate"><a title="FONTLOG.txt" aria-label="FONTLOG.txt, (File)" class="Link--primary" href="/stipub/stixfonts/blob/master/FONTLOG.txt" data-discover="true">FONTLOG.txt</a></div></div></div></div></td><td class="react-directory-row-commit-cell"><div class="Skeleton Skeleton--text"> </div></td><td><div class="Skeleton Skeleton--text"> </div></td></tr><tr class="react-directory-row truncate-for-mobile" id="folder-row-11"><td class="react-directory-row-name-cell-small-screen" colSpan="2"><div class="react-directory-filename-column"><svg aria-hidden="true" focusable="false" class="octicon octicon-file color-fg-muted" viewBox="0 0 16 16" width="16" height="16" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M2 1.75C2 .784 2.784 0 3.75 0h6.586c.464 0 .909.184 1.237.513l2.914 2.914c.329.328.513.773.513 1.237v9.586A1.75 1.75 0 0 1 13.25 16h-9.5A1.75 1.75 0 0 1 2 14.25Zm1.75-.25a.25.25 0 0 0-.25.25v12.5c0 .138.112.25.25.25h9.5a.25.25 0 0 0 .25-.25V6h-2.75A1.75 1.75 0 0 1 9 4.25V1.5Zm6.75.062V4.25c0 .138.112.25.25.25h2.688l-.011-.013-2.914-2.914-.013-.011Z"></path></svg><div class="overflow-hidden"><div class="react-directory-filename-cell"><div class="react-directory-truncate"><a title="OFL-FAQ.txt" aria-label="OFL-FAQ.txt, (File)" class="Link--primary" href="/stipub/stixfonts/blob/master/OFL-FAQ.txt" data-discover="true">OFL-FAQ.txt</a></div></div></div></div></td><td class="react-directory-row-name-cell-large-screen" colSpan="1"><div class="react-directory-filename-column"><svg aria-hidden="true" focusable="false" class="octicon octicon-file color-fg-muted" viewBox="0 0 16 16" width="16" height="16" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M2 1.75C2 .784 2.784 0 3.75 0h6.586c.464 0 .909.184 1.237.513l2.914 2.914c.329.328.513.773.513 1.237v9.586A1.75 1.75 0 0 1 13.25 16h-9.5A1.75 1.75 0 0 1 2 14.25Zm1.75-.25a.25.25 0 0 0-.25.25v12.5c0 .138.112.25.25.25h9.5a.25.25 0 0 0 .25-.25V6h-2.75A1.75 1.75 0 0 1 9 4.25V1.5Zm6.75.062V4.25c0 .138.112.25.25.25h2.688l-.011-.013-2.914-2.914-.013-.011Z"></path></svg><div class="overflow-hidden"><div class="react-directory-filename-cell"><div class="react-directory-truncate"><a title="OFL-FAQ.txt" aria-label="OFL-FAQ.txt, (File)" class="Link--primary" href="/stipub/stixfonts/blob/master/OFL-FAQ.txt" data-discover="true">OFL-FAQ.txt</a></div></div></div></div></td><td class="react-directory-row-commit-cell"><div class="Skeleton Skeleton--text"> </div></td><td><div class="Skeleton Skeleton--text"> </div></td></tr><tr class="react-directory-row truncate-for-mobile" id="folder-row-12"><td class="react-directory-row-name-cell-small-screen" colSpan="2"><div class="react-directory-filename-column"><svg aria-hidden="true" focusable="false" class="octicon octicon-file color-fg-muted" viewBox="0 0 16 16" width="16" height="16" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M2 1.75C2 .784 2.784 0 3.75 0h6.586c.464 0 .909.184 1.237.513l2.914 2.914c.329.328.513.773.513 1.237v9.586A1.75 1.75 0 0 1 13.25 16h-9.5A1.75 1.75 0 0 1 2 14.25Zm1.75-.25a.25.25 0 0 0-.25.25v12.5c0 .138.112.25.25.25h9.5a.25.25 0 0 0 .25-.25V6h-2.75A1.75 1.75 0 0 1 9 4.25V1.5Zm6.75.062V4.25c0 .138.112.25.25.25h2.688l-.011-.013-2.914-2.914-.013-.011Z"></path></svg><div class="overflow-hidden"><div class="react-directory-filename-cell"><div class="react-directory-truncate"><a title="OFL.txt" aria-label="OFL.txt, (File)" class="Link--primary" href="/stipub/stixfonts/blob/master/OFL.txt" data-discover="true">OFL.txt</a></div></div></div></div></td><td class="react-directory-row-name-cell-large-screen" colSpan="1"><div class="react-directory-filename-column"><svg aria-hidden="true" focusable="false" class="octicon octicon-file color-fg-muted" viewBox="0 0 16 16" width="16" height="16" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M2 1.75C2 .784 2.784 0 3.75 0h6.586c.464 0 .909.184 1.237.513l2.914 2.914c.329.328.513.773.513 1.237v9.586A1.75 1.75 0 0 1 13.25 16h-9.5A1.75 1.75 0 0 1 2 14.25Zm1.75-.25a.25.25 0 0 0-.25.25v12.5c0 .138.112.25.25.25h9.5a.25.25 0 0 0 .25-.25V6h-2.75A1.75 1.75 0 0 1 9 4.25V1.5Zm6.75.062V4.25c0 .138.112.25.25.25h2.688l-.011-.013-2.914-2.914-.013-.011Z"></path></svg><div class="overflow-hidden"><div class="react-directory-filename-cell"><div class="react-directory-truncate"><a title="OFL.txt" aria-label="OFL.txt, (File)" class="Link--primary" href="/stipub/stixfonts/blob/master/OFL.txt" data-discover="true">OFL.txt</a></div></div></div></div></td><td class="react-directory-row-commit-cell"><div class="Skeleton Skeleton--text"> </div></td><td><div class="Skeleton Skeleton--text"> </div></td></tr><tr class="react-directory-row truncate-for-mobile" id="folder-row-13"><td class="react-directory-row-name-cell-small-screen" colSpan="2"><div class="react-directory-filename-column"><svg aria-hidden="true" focusable="false" class="octicon octicon-file color-fg-muted" viewBox="0 0 16 16" width="16" height="16" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M2 1.75C2 .784 2.784 0 3.75 0h6.586c.464 0 .909.184 1.237.513l2.914 2.914c.329.328.513.773.513 1.237v9.586A1.75 1.75 0 0 1 13.25 16h-9.5A1.75 1.75 0 0 1 2 14.25Zm1.75-.25a.25.25 0 0 0-.25.25v12.5c0 .138.112.25.25.25h9.5a.25.25 0 0 0 .25-.25V6h-2.75A1.75 1.75 0 0 1 9 4.25V1.5Zm6.75.062V4.25c0 .138.112.25.25.25h2.688l-.011-.013-2.914-2.914-.013-.011Z"></path></svg><div class="overflow-hidden"><div class="react-directory-filename-cell"><div class="react-directory-truncate"><a title="README.md" aria-label="README.md, (File)" class="Link--primary" href="/stipub/stixfonts/blob/master/README.md" data-discover="true">README.md</a></div></div></div></div></td><td class="react-directory-row-name-cell-large-screen" colSpan="1"><div class="react-directory-filename-column"><svg aria-hidden="true" focusable="false" class="octicon octicon-file color-fg-muted" viewBox="0 0 16 16" width="16" height="16" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M2 1.75C2 .784 2.784 0 3.75 0h6.586c.464 0 .909.184 1.237.513l2.914 2.914c.329.328.513.773.513 1.237v9.586A1.75 1.75 0 0 1 13.25 16h-9.5A1.75 1.75 0 0 1 2 14.25Zm1.75-.25a.25.25 0 0 0-.25.25v12.5c0 .138.112.25.25.25h9.5a.25.25 0 0 0 .25-.25V6h-2.75A1.75 1.75 0 0 1 9 4.25V1.5Zm6.75.062V4.25c0 .138.112.25.25.25h2.688l-.011-.013-2.914-2.914-.013-.011Z"></path></svg><div class="overflow-hidden"><div class="react-directory-filename-cell"><div class="react-directory-truncate"><a title="README.md" aria-label="README.md, (File)" class="Link--primary" href="/stipub/stixfonts/blob/master/README.md" data-discover="true">README.md</a></div></div></div></div></td><td class="react-directory-row-commit-cell"><div class="Skeleton Skeleton--text"> </div></td><td><div class="Skeleton Skeleton--text"> </div></td></tr><tr class="react-directory-row truncate-for-mobile" id="folder-row-14"><td class="react-directory-row-name-cell-small-screen" colSpan="2"><div class="react-directory-filename-column"><svg aria-hidden="true" focusable="false" class="octicon octicon-file color-fg-muted" viewBox="0 0 16 16" width="16" height="16" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M2 1.75C2 .784 2.784 0 3.75 0h6.586c.464 0 .909.184 1.237.513l2.914 2.914c.329.328.513.773.513 1.237v9.586A1.75 1.75 0 0 1 13.25 16h-9.5A1.75 1.75 0 0 1 2 14.25Zm1.75-.25a.25.25 0 0 0-.25.25v12.5c0 .138.112.25.25.25h9.5a.25.25 0 0 0 .25-.25V6h-2.75A1.75 1.75 0 0 1 9 4.25V1.5Zm6.75.062V4.25c0 .138.112.25.25.25h2.688l-.011-.013-2.914-2.914-.013-.011Z"></path></svg><div class="overflow-hidden"><div class="react-directory-filename-cell"><div class="react-directory-truncate"><a title="TRADEMARKS.txt" aria-label="TRADEMARKS.txt, (File)" class="Link--primary" href="/stipub/stixfonts/blob/master/TRADEMARKS.txt" data-discover="true">TRADEMARKS.txt</a></div></div></div></div></td><td class="react-directory-row-name-cell-large-screen" colSpan="1"><div class="react-directory-filename-column"><svg aria-hidden="true" focusable="false" class="octicon octicon-file color-fg-muted" viewBox="0 0 16 16" width="16" height="16" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M2 1.75C2 .784 2.784 0 3.75 0h6.586c.464 0 .909.184 1.237.513l2.914 2.914c.329.328.513.773.513 1.237v9.586A1.75 1.75 0 0 1 13.25 16h-9.5A1.75 1.75 0 0 1 2 14.25Zm1.75-.25a.25.25 0 0 0-.25.25v12.5c0 .138.112.25.25.25h9.5a.25.25 0 0 0 .25-.25V6h-2.75A1.75 1.75 0 0 1 9 4.25V1.5Zm6.75.062V4.25c0 .138.112.25.25.25h2.688l-.011-.013-2.914-2.914-.013-.011Z"></path></svg><div class="overflow-hidden"><div class="react-directory-filename-cell"><div class="react-directory-truncate"><a title="TRADEMARKS.txt" aria-label="TRADEMARKS.txt, (File)" class="Link--primary" href="/stipub/stixfonts/blob/master/TRADEMARKS.txt" data-discover="true">TRADEMARKS.txt</a></div></div></div></div></td><td class="react-directory-row-commit-cell"><div class="Skeleton Skeleton--text"> </div></td><td><div class="Skeleton Skeleton--text"> </div></td></tr><tr class="react-directory-row truncate-for-mobile" id="folder-row-15"><td class="react-directory-row-name-cell-small-screen" colSpan="2"><div class="react-directory-filename-column"><svg aria-hidden="true" focusable="false" class="octicon octicon-file color-fg-muted" viewBox="0 0 16 16" width="16" height="16" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M2 1.75C2 .784 2.784 0 3.75 0h6.586c.464 0 .909.184 1.237.513l2.914 2.914c.329.328.513.773.513 1.237v9.586A1.75 1.75 0 0 1 13.25 16h-9.5A1.75 1.75 0 0 1 2 14.25Zm1.75-.25a.25.25 0 0 0-.25.25v12.5c0 .138.112.25.25.25h9.5a.25.25 0 0 0 .25-.25V6h-2.75A1.75 1.75 0 0 1 9 4.25V1.5Zm6.75.062V4.25c0 .138.112.25.25.25h2.688l-.011-.013-2.914-2.914-.013-.011Z"></path></svg><div class="overflow-hidden"><div class="react-directory-filename-cell"><div class="react-directory-truncate"><a title="build.sh" aria-label="build.sh, (File)" class="Link--primary" href="/stipub/stixfonts/blob/master/build.sh" data-discover="true">build.sh</a></div></div></div></div></td><td class="react-directory-row-name-cell-large-screen" colSpan="1"><div class="react-directory-filename-column"><svg aria-hidden="true" focusable="false" class="octicon octicon-file color-fg-muted" viewBox="0 0 16 16" width="16" height="16" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M2 1.75C2 .784 2.784 0 3.75 0h6.586c.464 0 .909.184 1.237.513l2.914 2.914c.329.328.513.773.513 1.237v9.586A1.75 1.75 0 0 1 13.25 16h-9.5A1.75 1.75 0 0 1 2 14.25Zm1.75-.25a.25.25 0 0 0-.25.25v12.5c0 .138.112.25.25.25h9.5a.25.25 0 0 0 .25-.25V6h-2.75A1.75 1.75 0 0 1 9 4.25V1.5Zm6.75.062V4.25c0 .138.112.25.25.25h2.688l-.011-.013-2.914-2.914-.013-.011Z"></path></svg><div class="overflow-hidden"><div class="react-directory-filename-cell"><div class="react-directory-truncate"><a title="build.sh" aria-label="build.sh, (File)" class="Link--primary" href="/stipub/stixfonts/blob/master/build.sh" data-discover="true">build.sh</a></div></div></div></div></td><td class="react-directory-row-commit-cell"><div class="Skeleton Skeleton--text"> </div></td><td><div class="Skeleton Skeleton--text"> </div></td></tr><tr class="react-directory-row truncate-for-mobile" id="folder-row-16"><td class="react-directory-row-name-cell-small-screen" colSpan="2"><div class="react-directory-filename-column"><svg aria-hidden="true" focusable="false" class="octicon octicon-file color-fg-muted" viewBox="0 0 16 16" width="16" height="16" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M2 1.75C2 .784 2.784 0 3.75 0h6.586c.464 0 .909.184 1.237.513l2.914 2.914c.329.328.513.773.513 1.237v9.586A1.75 1.75 0 0 1 13.25 16h-9.5A1.75 1.75 0 0 1 2 14.25Zm1.75-.25a.25.25 0 0 0-.25.25v12.5c0 .138.112.25.25.25h9.5a.25.25 0 0 0 .25-.25V6h-2.75A1.75 1.75 0 0 1 9 4.25V1.5Zm6.75.062V4.25c0 .138.112.25.25.25h2.688l-.011-.013-2.914-2.914-.013-.011Z"></path></svg><div class="overflow-hidden"><div class="react-directory-filename-cell"><div class="react-directory-truncate"><a title="requirements.in" aria-label="requirements.in, (File)" class="Link--primary" href="/stipub/stixfonts/blob/master/requirements.in" data-discover="true">requirements.in</a></div></div></div></div></td><td class="react-directory-row-name-cell-large-screen" colSpan="1"><div class="react-directory-filename-column"><svg aria-hidden="true" focusable="false" class="octicon octicon-file color-fg-muted" viewBox="0 0 16 16" width="16" height="16" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M2 1.75C2 .784 2.784 0 3.75 0h6.586c.464 0 .909.184 1.237.513l2.914 2.914c.329.328.513.773.513 1.237v9.586A1.75 1.75 0 0 1 13.25 16h-9.5A1.75 1.75 0 0 1 2 14.25Zm1.75-.25a.25.25 0 0 0-.25.25v12.5c0 .138.112.25.25.25h9.5a.25.25 0 0 0 .25-.25V6h-2.75A1.75 1.75 0 0 1 9 4.25V1.5Zm6.75.062V4.25c0 .138.112.25.25.25h2.688l-.011-.013-2.914-2.914-.013-.011Z"></path></svg><div class="overflow-hidden"><div class="react-directory-filename-cell"><div class="react-directory-truncate"><a title="requirements.in" aria-label="requirements.in, (File)" class="Link--primary" href="/stipub/stixfonts/blob/master/requirements.in" data-discover="true">requirements.in</a></div></div></div></div></td><td class="react-directory-row-commit-cell"><div class="Skeleton Skeleton--text"> </div></td><td><div class="Skeleton Skeleton--text"> </div></td></tr><tr class="react-directory-row truncate-for-mobile" id="folder-row-17"><td class="react-directory-row-name-cell-small-screen" colSpan="2"><div class="react-directory-filename-column"><svg aria-hidden="true" focusable="false" class="octicon octicon-file color-fg-muted" viewBox="0 0 16 16" width="16" height="16" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M2 1.75C2 .784 2.784 0 3.75 0h6.586c.464 0 .909.184 1.237.513l2.914 2.914c.329.328.513.773.513 1.237v9.586A1.75 1.75 0 0 1 13.25 16h-9.5A1.75 1.75 0 0 1 2 14.25Zm1.75-.25a.25.25 0 0 0-.25.25v12.5c0 .138.112.25.25.25h9.5a.25.25 0 0 0 .25-.25V6h-2.75A1.75 1.75 0 0 1 9 4.25V1.5Zm6.75.062V4.25c0 .138.112.25.25.25h2.688l-.011-.013-2.914-2.914-.013-.011Z"></path></svg><div class="overflow-hidden"><div class="react-directory-filename-cell"><div class="react-directory-truncate"><a title="requirements.txt" aria-label="requirements.txt, (File)" class="Link--primary" href="/stipub/stixfonts/blob/master/requirements.txt" data-discover="true">requirements.txt</a></div></div></div></div></td><td class="react-directory-row-name-cell-large-screen" colSpan="1"><div class="react-directory-filename-column"><svg aria-hidden="true" focusable="false" class="octicon octicon-file color-fg-muted" viewBox="0 0 16 16" width="16" height="16" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M2 1.75C2 .784 2.784 0 3.75 0h6.586c.464 0 .909.184 1.237.513l2.914 2.914c.329.328.513.773.513 1.237v9.586A1.75 1.75 0 0 1 13.25 16h-9.5A1.75 1.75 0 0 1 2 14.25Zm1.75-.25a.25.25 0 0 0-.25.25v12.5c0 .138.112.25.25.25h9.5a.25.25 0 0 0 .25-.25V6h-2.75A1.75 1.75 0 0 1 9 4.25V1.5Zm6.75.062V4.25c0 .138.112.25.25.25h2.688l-.011-.013-2.914-2.914-.013-.011Z"></path></svg><div class="overflow-hidden"><div class="react-directory-filename-cell"><div class="react-directory-truncate"><a title="requirements.txt" aria-label="requirements.txt, (File)" class="Link--primary" href="/stipub/stixfonts/blob/master/requirements.txt" data-discover="true">requirements.txt</a></div></div></div></div></td><td class="react-directory-row-commit-cell"><div class="Skeleton Skeleton--text"> </div></td><td><div class="Skeleton Skeleton--text"> </div></td></tr><tr class="show-for-mobile DirectoryContent-module__Box_4--QyUbd" data-testid="view-all-files-row"><td colSpan="3" class="DirectoryContent-module__Box_5--OJZQU"><div><button class="prc-Link-Link-85e08">View all files</button></div></td></tr></tbody></table></div><div class="OverviewRepoFiles-module__Box_1--xSt0T"><div class="OverviewRepoFiles-module__Box_2--yIjMp"><div itemscope="" itemType="https://schema.org/abstract" class="OverviewRepoFiles-module__Box_3--Bi2jM"><h2 class="prc-src-InternalVisuallyHidden-nlR9R">Repository files navigation</h2><nav class="prc-components-UnderlineWrapper-oOh5J OverviewRepoFiles-module__UnderlineNav--BHfFi" aria-label="Repository files" data-variant="inset"><ul class="prc-components-UnderlineItemList-b23Hf" role="list"><li class="prc-UnderlineNav-UnderlineNavItem--xDk1"><a href="#" aria-current="page" class="prc-components-UnderlineItem-lJsg-"><span data-component="icon"><svg aria-hidden="true" focusable="false" class="octicon octicon-book" viewBox="0 0 16 16" width="16" height="16" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M0 1.75A.75.75 0 0 1 .75 1h4.253c1.227 0 2.317.59 3 1.501A3.743 3.743 0 0 1 11.006 1h4.245a.75.75 0 0 1 .75.75v10.5a.75.75 0 0 1-.75.75h-4.507a2.25 2.25 0 0 0-1.591.659l-.622.621a.75.75 0 0 1-1.06 0l-.622-.621A2.25 2.25 0 0 0 5.258 13H.75a.75.75 0 0 1-.75-.75Zm7.251 10.324.004-5.073-.002-2.253A2.25 2.25 0 0 0 5.003 2.5H1.5v9h3.757a3.75 3.75 0 0 1 1.994.574ZM8.755 4.75l-.004 7.322a3.752 3.752 0 0 1 1.992-.572H14.5v-9h-3.495a2.25 2.25 0 0 0-2.25 2.25Z"></path></svg></span><span data-component="text" data-content="README">README</span></a></li><li class="prc-UnderlineNav-UnderlineNavItem--xDk1"><a href="#" class="prc-components-UnderlineItem-lJsg-"><span data-component="icon"><svg aria-hidden="true" focusable="false" class="octicon octicon-law" viewBox="0 0 16 16" width="16" height="16" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M8.75.75V2h.985c.304 0 .603.08.867.231l1.29.736c.038.022.08.033.124.033h2.234a.75.75 0 0 1 0 1.5h-.427l2.111 4.692a.75.75 0 0 1-.154.838l-.53-.53.529.531-.001.002-.002.002-.006.006-.006.005-.01.01-.045.04c-.21.176-.441.327-.686.45C14.556 10.78 13.88 11 13 11a4.498 4.498 0 0 1-2.023-.454 3.544 3.544 0 0 1-.686-.45l-.045-.04-.016-.015-.006-.006-.004-.004v-.001a.75.75 0 0 1-.154-.838L12.178 4.5h-.162c-.305 0-.604-.079-.868-.231l-1.29-.736a.245.245 0 0 0-.124-.033H8.75V13h2.5a.75.75 0 0 1 0 1.5h-6.5a.75.75 0 0 1 0-1.5h2.5V3.5h-.984a.245.245 0 0 0-.124.033l-1.289.737c-.265.15-.564.23-.869.23h-.162l2.112 4.692a.75.75 0 0 1-.154.838l-.53-.53.529.531-.001.002-.002.002-.006.006-.016.015-.045.04c-.21.176-.441.327-.686.45C4.556 10.78 3.88 11 3 11a4.498 4.498 0 0 1-2.023-.454 3.544 3.544 0 0 1-.686-.45l-.045-.04-.016-.015-.006-.006-.004-.004v-.001a.75.75 0 0 1-.154-.838L2.178 4.5H1.75a.75.75 0 0 1 0-1.5h2.234a.249.249 0 0 0 .125-.033l1.288-.737c.265-.15.564-.23.869-.23h.984V.75a.75.75 0 0 1 1.5 0Zm2.945 8.477c.285.135.718.273 1.305.273s1.02-.138 1.305-.273L13 6.327Zm-10 0c.285.135.718.273 1.305.273s1.02-.138 1.305-.273L3 6.327Z"></path></svg></span><span data-component="text" data-content="OFL-1.1 license">OFL-1.1 license</span></a></li></ul></nav><button type="button" aria-label="Outline" aria-haspopup="true" aria-expanded="false" tabindex="0" class="prc-Button-ButtonBase-c50BI OverviewRepoFiles-module__ActionMenu_Button--xB9DS" data-loading="false" data-size="medium" data-variant="invisible" aria-describedby=":Rr9ab:-loading-announcement" id=":Rr9ab:"><svg aria-hidden="true" focusable="false" class="octicon octicon-list-unordered" viewBox="0 0 16 16" width="16" height="16" fill="currentColor" display="inline-block" overflow="visible" style="vertical-align:text-bottom"><path d="M5.75 2.5h8.5a.75.75 0 0 1 0 1.5h-8.5a.75.75 0 0 1 0-1.5Zm0 5h8.5a.75.75 0 0 1 0 1.5h-8.5a.75.75 0 0 1 0-1.5Zm0 5h8.5a.75.75 0 0 1 0 1.5h-8.5a.75.75 0 0 1 0-1.5ZM2 14a1 1 0 1 1 0-2 1 1 0 0 1 0 2Zm1-6a1 1 0 1 1-2 0 1 1 0 0 1 2 0ZM2 4a1 1 0 1 1 0-2 1 1 0 0 1 0 2Z"></path></svg></button></div><div class="Box-sc-62in7e-0 js-snippet-clipboard-copy-unpositioned DirectoryRichtextContent-module__SharedMarkdownContent--BTKsc" data-hpc="true"><article class="markdown-body entry-content container-lg" itemprop="text"><div class="markdown-heading" dir="auto"><h1 tabindex="-1" class="heading-element" dir="auto">stixfonts</h1><a id="user-content-stixfonts" class="anchor" aria-label="Permalink: stixfonts" href="#stixfonts"><svg class="octicon octicon-link" viewBox="0 0 16 16" version="1.1" width="16" height="16" aria-hidden="true"><path d="m7.775 3.275 1.25-1.25a3.5 3.5 0 1 1 4.95 4.95l-2.5 2.5a3.5 3.5 0 0 1-4.95 0 .751.751 0 0 1 .018-1.042.751.751 0 0 1 1.042-.018 1.998 1.998 0 0 0 2.83 0l2.5-2.5a2.002 2.002 0 0 0-2.83-2.83l-1.25 1.25a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042Zm-4.69 9.64a1.998 1.998 0 0 0 2.83 0l1.25-1.25a.751.751 0 0 1 1.042.018.751.751 0 0 1 .018 1.042l-1.25 1.25a3.5 3.5 0 1 1-4.95-4.95l2.5-2.5a3.5 3.5 0 0 1 4.95 0 .751.751 0 0 1-.018 1.042.751.751 0 0 1-1.042.018 1.998 1.998 0 0 0-2.83 0l-2.5 2.5a1.998 1.998 0 0 0 0 2.83Z"></path></svg></a></div>-<p dir="auto">OpenType Unicode fonts for Scientific, Technical, and Mathematical texts</p>-<div class="markdown-heading" dir="auto"><h2 tabindex="-1" class="heading-element" dir="auto">Overview</h2><a id="user-content-overview" class="anchor" aria-label="Permalink: Overview" href="#overview"><svg class="octicon octicon-link" viewBox="0 0 16 16" version="1.1" width="16" height="16" aria-hidden="true"><path d="m7.775 3.275 1.25-1.25a3.5 3.5 0 1 1 4.95 4.95l-2.5 2.5a3.5 3.5 0 0 1-4.95 0 .751.751 0 0 1 .018-1.042.751.751 0 0 1 1.042-.018 1.998 1.998 0 0 0 2.83 0l2.5-2.5a2.002 2.002 0 0 0-2.83-2.83l-1.25 1.25a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042Zm-4.69 9.64a1.998 1.998 0 0 0 2.83 0l1.25-1.25a.751.751 0 0 1 1.042.018.751.751 0 0 1 .018 1.042l-1.25 1.25a3.5 3.5 0 1 1-4.95-4.95l2.5-2.5a3.5 3.5 0 0 1 4.95 0 .751.751 0 0 1-.018 1.042.751.751 0 0 1-1.042.018 1.998 1.998 0 0 0-2.83 0l-2.5 2.5a1.998 1.998 0 0 0 0 2.83Z"></path></svg></a></div>-<ul dir="auto">-<li>-<p dir="auto">See <a href="https://www.stixfonts.org/" rel="nofollow">https://www.stixfonts.org/</a> for background on the the STIX Fonts-project.</p>-</li>-<li>-<p dir="auto">Download <a href="/stipub/stixfonts/blob/master/zipfiles">zip files</a> with some or all of the fonts.</p>-</li>-<li>-<p dir="auto">View <a href="/stipub/stixfonts/blob/master/docs">code charts</a> for the</p>-<ul dir="auto">-<li><a href="/stipub/stixfonts/blob/master/docs/STIXTwoMath-Regular.pdf">Math</a>,</li>-<li><a href="/stipub/stixfonts/blob/master/docs/STIXTwoText-Regular.pdf">Regular text</a>,-fonts.</li>-</ul>-</li>-</ul>-<div class="markdown-heading" dir="auto"><h3 tabindex="-1" class="heading-element" dir="auto">Type 1 fonts (STIX 2.0.0 only)</h3><a id="user-content-type-1-fonts-stix-200-only" class="anchor" aria-label="Permalink: Type 1 fonts (STIX 2.0.0 only)" href="#type-1-fonts-stix-200-only"><svg class="octicon octicon-link" viewBox="0 0 16 16" version="1.1" width="16" height="16" aria-hidden="true"><path d="m7.775 3.275 1.25-1.25a3.5 3.5 0 1 1 4.95 4.95l-2.5 2.5a3.5 3.5 0 0 1-4.95 0 .751.751 0 0 1 .018-1.042.751.751 0 0 1 1.042-.018 1.998 1.998 0 0 0 2.83 0l2.5-2.5a2.002 2.002 0 0 0-2.83-2.83l-1.25 1.25a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042Zm-4.69 9.64a1.998 1.998 0 0 0 2.83 0l1.25-1.25a.751.751 0 0 1 1.042.018.751.751 0 0 1 .018 1.042l-1.25 1.25a3.5 3.5 0 1 1-4.95-4.95l2.5-2.5a3.5 3.5 0 0 1 4.95 0 .751.751 0 0 1-.018 1.042.751.751 0 0 1-1.042.018 1.998 1.998 0 0 0-2.83 0l-2.5 2.5a1.998 1.998 0 0 0 0 2.83Z"></path></svg></a></div>-<p dir="auto">The STIX Two fonts are OpenType fonts and are meant to be used in that-format. For the benefit of LaTeX users who are unable to use XeTeX or-luaTeX, we have also provided version 2.0.0 of the STIX fonts as a-<a href="https://github.com/stipub/stix_type1">set of TFM files and Type 1 fonts</a>.</p>-<p dir="auto">Note that <strong>no further updates</strong> are planned to the Type 1-distribution; future development efforts will focus on improving the-OpenType fonts.</p>-<div class="markdown-heading" dir="auto"><h2 tabindex="-1" class="heading-element" dir="auto">About the STIX fonts.</h2><a id="user-content-about-the-stix-fonts" class="anchor" aria-label="Permalink: About the STIX fonts." href="#about-the-stix-fonts"><svg class="octicon octicon-link" viewBox="0 0 16 16" version="1.1" width="16" height="16" aria-hidden="true"><path d="m7.775 3.275 1.25-1.25a3.5 3.5 0 1 1 4.95 4.95l-2.5 2.5a3.5 3.5 0 0 1-4.95 0 .751.751 0 0 1 .018-1.042.751.751 0 0 1 1.042-.018 1.998 1.998 0 0 0 2.83 0l2.5-2.5a2.002 2.002 0 0 0-2.83-2.83l-1.25 1.25a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042Zm-4.69 9.64a1.998 1.998 0 0 0 2.83 0l1.25-1.25a.751.751 0 0 1 1.042.018.751.751 0 0 1 .018 1.042l-1.25 1.25a3.5 3.5 0 1 1-4.95-4.95l2.5-2.5a3.5 3.5 0 0 1 4.95 0 .751.751 0 0 1-.018 1.042.751.751 0 0 1-1.042.018 1.998 1.998 0 0 0-2.83 0l-2.5 2.5a1.998 1.998 0 0 0 0 2.83Z"></path></svg></a></div>-<p dir="auto">The Scientific and Technical Information eXchange (STIX) fonts are-intended to satisfy the demanding needs of authors, publishers,-printers, and others working in the scientific, medical, and technical-fields. They combine a comprehensive Unicode-based collection of-mathematical symbols and alphabets with a set of text faces suitable-for professional publishing. The fonts are available royalty-free-under the SIL Open Font License.</p>-<p dir="auto">Version 2 of the STIX fonts, now known as "STIX Two", is a thorough-revision undertaken by the renowned type house Tiro Typeworks-Ltd. (<a href="https://www.tiro.com" rel="nofollow">https://www.tiro.com</a>). The STIX Two fonts consist of one Math-font, two variable text fonts (STIXTwoTextVF-Roman and-STIXTwoTextVF-Italic), and eight static text fonts (Regular, Italic,-Medium, Medium Italic, SemiBold, SemiBold Italic, Bold, and Bold-Italic) derived from the variable fonts. Together, they provide a-uniform set of fonts that can be used throughout the production-process, whether that be a traditional print-only process, an entirely-electronic one, or a combination of the two.</p>-<p dir="auto">The <a href="https://www.stixfonts.org/" rel="nofollow">STIX project</a> began through the joint-efforts of-<a href="https://www.ams.org/" rel="nofollow">American Mathematical Society</a> (AMS),-<a href="https://www.aip.org/" rel="nofollow">American Institute of Physics</a> (AIP),-<a href="https://www.aps.org/" rel="nofollow">American Physical Society</a> (APS),-<a href="https://www.acs.org/" rel="nofollow">American Chemical Society</a> (ACS),-The <a href="https://www.ieee.org/" rel="nofollow">Institute of Electrical and Electronic</a> Engineers (IEEE),-and <a href="https://www.elsevier.com/" rel="nofollow">Elsevier</a>.-These companies are collectively known as the STI Pub companies.</p>-<div class="markdown-heading" dir="auto"><h3 tabindex="-1" class="heading-element" dir="auto">A Fresh Take on Times Roman</h3><a id="user-content-a-fresh-take-on-times-roman" class="anchor" aria-label="Permalink: A Fresh Take on Times Roman" href="#a-fresh-take-on-times-roman"><svg class="octicon octicon-link" viewBox="0 0 16 16" version="1.1" width="16" height="16" aria-hidden="true"><path d="m7.775 3.275 1.25-1.25a3.5 3.5 0 1 1 4.95 4.95l-2.5 2.5a3.5 3.5 0 0 1-4.95 0 .751.751 0 0 1 .018-1.042.751.751 0 0 1 1.042-.018 1.998 1.998 0 0 0 2.83 0l2.5-2.5a2.002 2.002 0 0 0-2.83-2.83l-1.25 1.25a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042Zm-4.69 9.64a1.998 1.998 0 0 0 2.83 0l1.25-1.25a.751.751 0 0 1 1.042.018.751.751 0 0 1 .018 1.042l-1.25 1.25a3.5 3.5 0 1 1-4.95-4.95l2.5-2.5a3.5 3.5 0 0 1 4.95 0 .751.751 0 0 1-.018 1.042.751.751 0 0 1-1.042.018 1.998 1.998 0 0 0-2.83 0l-2.5 2.5a1.998 1.998 0 0 0 0 2.83Z"></path></svg></a></div>-<p dir="auto">The original version of STIX was based on Times Roman, which has now-been updated for the digital age.</p>-<p dir="auto">As is well known, Times Roman was originally intended for printing the-<em>London Times</em>. What is not generally appreciated is that the-production quality of the <em>Times</em> was atypically high: It was printed-on unusually high-quality paper on presses that operated more slowly-than most newspaper presses. This allowed for the design of a-typeface that could exploit this level of care: serifs could be much-finer and counters (enclosed areas such as that in the lowercase <em>e</em>)-could be much smaller than in other newspaper typefaces. These-features of the font have not always fared well in less exacting-environments. At the same time, a notable quirk of the Times Roman-family is that the bold font is, in many respects, strikingly-dissimilar to the roman font.</p>-<p dir="auto">Tiro Typeworks explain their approach to updating the Times Roman-basis of STIX as follows:</p>-<blockquote>-<p dir="auto">“Our principal goal in approaching STIX Two was to address several-inherent deficiencies in the Times New Roman model as well as expand-the typographic features. This process necessarily involved-diverging somewhat from Times as familiar to people who have only-known the common digital versions, while simultaneously restoring to-that typeface aspects of the size-appropriate design characteristics-that made it so successful in newspaper, book, and journal-publishing in it’s metal type incarnation. The essential-‘Times-ness’ remains, but are with greater harmonisation of style-across the family.</p>-<p dir="auto">“Most digital versions of Times have been based on an optical size-model that appears too light and fine when scaled down to typical-text sizes. In the design of STIX Two, we went back to specimens of-size-specific designs from the metal era, and adapted proportions,-weights, and spacing of the 10pt and 12pt designs. The oft-noted-mismatch between the style of different weights of Times has been-resolved with a new bold design that matches the construction of the-regular weight.”</p>-</blockquote>-<div class="markdown-heading" dir="auto"><h3 tabindex="-1" class="heading-element" dir="auto">Font implementation decisions</h3><a id="user-content-font-implementation-decisions" class="anchor" aria-label="Permalink: Font implementation decisions" href="#font-implementation-decisions"><svg class="octicon octicon-link" viewBox="0 0 16 16" version="1.1" width="16" height="16" aria-hidden="true"><path d="m7.775 3.275 1.25-1.25a3.5 3.5 0 1 1 4.95 4.95l-2.5 2.5a3.5 3.5 0 0 1-4.95 0 .751.751 0 0 1 .018-1.042.751.751 0 0 1 1.042-.018 1.998 1.998 0 0 0 2.83 0l2.5-2.5a2.002 2.002 0 0 0-2.83-2.83l-1.25 1.25a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042Zm-4.69 9.64a1.998 1.998 0 0 0 2.83 0l1.25-1.25a.751.751 0 0 1 1.042.018.751.751 0 0 1 .018 1.042l-1.25 1.25a3.5 3.5 0 1 1-4.95-4.95l2.5-2.5a3.5 3.5 0 0 1 4.95 0 .751.751 0 0 1-.018 1.042.751.751 0 0 1-1.042.018 1.998 1.998 0 0 0-2.83 0l-2.5 2.5a1.998 1.998 0 0 0 0 2.83Z"></path></svg></a></div>-<ul dir="auto">-<li>-<p dir="auto">The STIX fonts do not contain fixed-width or sans serif text faces.</p>-</li>-<li>-<p dir="auto">The sans serif, fraktur, script, etc., alphabets in Plane 1-(U+1D400-U+1D4FF) are intended to be used only as technical symbols.</p>-</li>-<li>-<p dir="auto">These fonts are designed to support left-to-right typesetting in-Latin-based scripts, with additional support for Greek and Cyrillic-text. Extensions to support other writing directions have been-considered, but are currently deemed to be outside the scope of the-STIX project.</p>-</li>-</ul>-<div class="markdown-heading" dir="auto"><h3 tabindex="-1" class="heading-element" dir="auto">Note to TeX users</h3><a id="user-content-note-to-tex-users" class="anchor" aria-label="Permalink: Note to TeX users" href="#note-to-tex-users"><svg class="octicon octicon-link" viewBox="0 0 16 16" version="1.1" width="16" height="16" aria-hidden="true"><path d="m7.775 3.275 1.25-1.25a3.5 3.5 0 1 1 4.95 4.95l-2.5 2.5a3.5 3.5 0 0 1-4.95 0 .751.751 0 0 1 .018-1.042.751.751 0 0 1 1.042-.018 1.998 1.998 0 0 0 2.83 0l2.5-2.5a2.002 2.002 0 0 0-2.83-2.83l-1.25 1.25a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042Zm-4.69 9.64a1.998 1.998 0 0 0 2.83 0l1.25-1.25a.751.751 0 0 1 1.042.018.751.751 0 0 1 .018 1.042l-1.25 1.25a3.5 3.5 0 1 1-4.95-4.95l2.5-2.5a3.5 3.5 0 0 1 4.95 0 .751.751 0 0 1-.018 1.042.751.751 0 0 1-1.042.018 1.998 1.998 0 0 0-2.83 0l-2.5 2.5a1.998 1.998 0 0 0 0 2.83Z"></path></svg></a></div>-<p dir="auto">These fonts have been tested with both-<a href="http://xetex.sourceforge.net/" rel="nofollow">XeTeX</a>-and-<a href="http://www.luatex.org/" rel="nofollow">luaTeX</a>-with good results. For best results, XeTeX users will want to use-version 0.999992 or later of XeTeX, which ships with-<a href="https://www.tug.org/texlive/" rel="nofollow">TeXLive 2020</a>.-This version fixes a number of bugs that were present in earlier-versions. Our thanks go out to Jonathan Kew and Khaled Hosny for-their generous help in identifying and fixing these bugs. LaTeX users-should also make sure they have the latest version of the-<a href="https://ctan.org/pkg/amsmath" rel="nofollow">amsmath package</a>.</p>-<div class="markdown-heading" dir="auto"><h2 tabindex="-1" class="heading-element" dir="auto">Summary of OpenType Features and Scripts</h2><a id="user-content-summary-of-opentype-features-and-scripts" class="anchor" aria-label="Permalink: Summary of OpenType Features and Scripts" href="#summary-of-opentype-features-and-scripts"><svg class="octicon octicon-link" viewBox="0 0 16 16" version="1.1" width="16" height="16" aria-hidden="true"><path d="m7.775 3.275 1.25-1.25a3.5 3.5 0 1 1 4.95 4.95l-2.5 2.5a3.5 3.5 0 0 1-4.95 0 .751.751 0 0 1 .018-1.042.751.751 0 0 1 1.042-.018 1.998 1.998 0 0 0 2.83 0l2.5-2.5a2.002 2.002 0 0 0-2.83-2.83l-1.25 1.25a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042Zm-4.69 9.64a1.998 1.998 0 0 0 2.83 0l1.25-1.25a.751.751 0 0 1 1.042.018.751.751 0 0 1 .018 1.042l-1.25 1.25a3.5 3.5 0 1 1-4.95-4.95l2.5-2.5a3.5 3.5 0 0 1 4.95 0 .751.751 0 0 1-.018 1.042.751.751 0 0 1-1.042.018 1.998 1.998 0 0 0-2.83 0l-2.5 2.5a1.998 1.998 0 0 0 0 2.83Z"></path></svg></a></div>-<p dir="auto">Further details these features can be found in the <a href="/stipub/stixfonts/blob/master/docs">font charts</a>.</p>-<p dir="auto">The text fonts implement the following OpenType script tags:</p>-<div class="snippet-clipboard-content notranslate position-relative overflow-auto" data-snippet-clipboard-copy-content="Regular Bold Italic BoldItalic--DFLT DFLT DFLT DFLT Default--cyrl cyrl cyrl cyrl Cyrillic- cyrl.MKD cyrl.MKD Cyrillic/Macedonian- cyrl.SRB cyrl.SRB Cyrillic/Serbian--grek grek grek grek Greek--latn latn latn latn Latin-latn.LTH latn.LTH latn.LTH latn.LTH Latin/Lithuanian-latn.ROM latn.ROM latn.ROM latn.ROM Latin/Romanian-latn.TRK latn.TRK latn.TRK latn.TRK Latin/Turkish"><pre class="notranslate"><code>Regular Bold Italic BoldItalic--DFLT DFLT DFLT DFLT Default--cyrl cyrl cyrl cyrl Cyrillic- cyrl.MKD cyrl.MKD Cyrillic/Macedonian- cyrl.SRB cyrl.SRB Cyrillic/Serbian--grek grek grek grek Greek--latn latn latn latn Latin-latn.LTH latn.LTH latn.LTH latn.LTH Latin/Lithuanian-latn.ROM latn.ROM latn.ROM latn.ROM Latin/Romanian-latn.TRK latn.TRK latn.TRK latn.TRK Latin/Turkish-</code></pre></div>-<p dir="auto">and the following features</p>-<div class="snippet-clipboard-content notranslate position-relative overflow-auto" data-snippet-clipboard-copy-content="c2sc Small Capitals from Capitals-case Case-Sensitive Forms-ccmp Glyph Composition/Decomposition-dnom Denominators-frac Fractions-kern Kerning-liga Standard Ligatures -- latn only-locl Localized Forms -- latn.ROM and Italic/BoldItalic cyrl.MKD only-numr Numerators-onum Oldstyle Figures-pnum Proportional Figures-smcp Small Capitals-subs Subscript-sups Superscript"><pre class="notranslate"><code>c2sc Small Capitals from Capitals-case Case-Sensitive Forms-ccmp Glyph Composition/Decomposition-dnom Denominators-frac Fractions-kern Kerning-liga Standard Ligatures -- latn only-locl Localized Forms -- latn.ROM and Italic/BoldItalic cyrl.MKD only-numr Numerators-onum Oldstyle Figures-pnum Proportional Figures-smcp Small Capitals-subs Subscript-sups Superscript-</code></pre></div>-<p dir="auto">All four text fonts also support the following Character Variants:</p>-<div class="snippet-clipboard-content notranslate position-relative overflow-auto" data-snippet-clipboard-copy-content="cv01 U+019B Lambda with horizontal, not slanted stroke -- latn only-cv02 U+0264 Rams horn with serifs -- latn only-cv03 U+2423 OPEN BOX curved instead of straight"><pre class="notranslate"><code>cv01 U+019B Lambda with horizontal, not slanted stroke -- latn only-cv02 U+0264 Rams horn with serifs -- latn only-cv03 U+2423 OPEN BOX curved instead of straight-</code></pre></div>-<p dir="auto">In addition, the Italic and BoldItalic faces support the following-Stylistic Variants:</p>-<div class="snippet-clipboard-content notranslate position-relative overflow-auto" data-snippet-clipboard-copy-content="ss01 Replace two-story g by hooked g -- Italic/BoldItalic only-ss02 Upright parens, brackets, and braces -- Italic/BoldItalic only"><pre class="notranslate"><code>ss01 Replace two-story g by hooked g -- Italic/BoldItalic only-ss02 Upright parens, brackets, and braces -- Italic/BoldItalic only-</code></pre></div>-<p dir="auto">STIX Two Math implements the following font features:</p>-<div class="snippet-clipboard-content notranslate position-relative overflow-auto" data-snippet-clipboard-copy-content="ccmp Glyph Composition/Decomposition-dtls Dotless forms of i and j-flac Flattened accents-ssty Math Script style alternates"><pre class="notranslate"><code>ccmp Glyph Composition/Decomposition-dtls Dotless forms of i and j-flac Flattened accents-ssty Math Script style alternates-</code></pre></div>-<p dir="auto">and the following Character Variants (note the different meaning of-cv03 compared to the text fonts):</p>-<div class="snippet-clipboard-content notranslate position-relative overflow-auto" data-snippet-clipboard-copy-content="cv01 U+019B Lambda with horizontal, not slanted stroke -- latn only-cv02 U+0264 Rams horn with serifs -- latn only-cv03 Replace U+2205 EMPTY SET by an oblate form-cv04 Replace U+2216 SET MINUS by a smaller form"><pre class="notranslate"><code>cv01 U+019B Lambda with horizontal, not slanted stroke -- latn only-cv02 U+0264 Rams horn with serifs -- latn only-cv03 Replace U+2205 EMPTY SET by an oblate form-cv04 Replace U+2216 SET MINUS by a smaller form-</code></pre></div>-<p dir="auto">and the following Stylistic Sets (again, note that ss01 and ss02 have-different meanings compared to the text fonts):</p>-<div class="snippet-clipboard-content notranslate position-relative overflow-auto" data-snippet-clipboard-copy-content="ss01 Stylistic Set 1 -- Math chancery to roundhand (\mathcal -> \mathscr)-ss02 Stylistic Set 2 -- Alternate italic forms: g, u, v, w, z-ss03 Stylistic Set 3 -- Horizontal crossbar variants-ss04 Stylistic Set 4 -- Minute, second and primes to long variants-ss05 Stylistic Set 5 -- Short arrow variants-ss06 Stylistic Set 6 -- Short/narrow variants-ss07 Stylistic Set 7 -- Alternate math symbols (product, summation, etc)-ss08 Stylistic Set 8 -- Upright integral variants; XITS compatible-ss09 Stylistic Set 9 -- Vertical slash variants; XITS compatible-ss10 Stylistic Set 10 -- Diagonal greater/lesser combination variants-ss11 Stylistic Set 11 -- Long slash not-equal combination variants-ss12 Stylistic Set 12 -- Low contrast (sans-like) variants-ss13 Stylistic Set 13 -- Horizontally flipped sine wave glyph-ss14 Stylistic Set 14 -- Tall variants-ss15 Stylistic Set 15 -- Slab serif symbol variants-ss16 Stylistic Set 16 -- Circled operator variants-ss20 Stylistic Set 20 -- Miscellaneous variants"><pre class="notranslate"><code>ss01 Stylistic Set 1 -- Math chancery to roundhand (\mathcal -> \mathscr)-ss02 Stylistic Set 2 -- Alternate italic forms: g, u, v, w, z-ss03 Stylistic Set 3 -- Horizontal crossbar variants-ss04 Stylistic Set 4 -- Minute, second and primes to long variants-ss05 Stylistic Set 5 -- Short arrow variants-ss06 Stylistic Set 6 -- Short/narrow variants-ss07 Stylistic Set 7 -- Alternate math symbols (product, summation, etc)-ss08 Stylistic Set 8 -- Upright integral variants; XITS compatible-ss09 Stylistic Set 9 -- Vertical slash variants; XITS compatible-ss10 Stylistic Set 10 -- Diagonal greater/lesser combination variants-ss11 Stylistic Set 11 -- Long slash not-equal combination variants-ss12 Stylistic Set 12 -- Low contrast (sans-like) variants-ss13 Stylistic Set 13 -- Horizontally flipped sine wave glyph-ss14 Stylistic Set 14 -- Tall variants-ss15 Stylistic Set 15 -- Slab serif symbol variants-ss16 Stylistic Set 16 -- Circled operator variants-ss20 Stylistic Set 20 -- Miscellaneous variants-</code></pre></div>-<div class="markdown-heading" dir="auto"><h2 tabindex="-1" class="heading-element" dir="auto">Build instructions</h2><a id="user-content-build-instructions" class="anchor" aria-label="Permalink: Build instructions" href="#build-instructions"><svg class="octicon octicon-link" viewBox="0 0 16 16" version="1.1" width="16" height="16" aria-hidden="true"><path d="m7.775 3.275 1.25-1.25a3.5 3.5 0 1 1 4.95 4.95l-2.5 2.5a3.5 3.5 0 0 1-4.95 0 .751.751 0 0 1 .018-1.042.751.751 0 0 1 1.042-.018 1.998 1.998 0 0 0 2.83 0l2.5-2.5a2.002 2.002 0 0 0-2.83-2.83l-1.25 1.25a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042Zm-4.69 9.64a1.998 1.998 0 0 0 2.83 0l1.25-1.25a.751.751 0 0 1 1.042.018.751.751 0 0 1 .018 1.042l-1.25 1.25a3.5 3.5 0 1 1-4.95-4.95l2.5-2.5a3.5 3.5 0 0 1 4.95 0 .751.751 0 0 1-.018 1.042.751.751 0 0 1-1.042.018 1.998 1.998 0 0 0-2.83 0l-2.5 2.5a1.998 1.998 0 0 0 0 2.83Z"></path></svg></a></div>-<p dir="auto">After cloning the project, the fonts can be built using the <code>build.sh</code> script (use <code>--verbose</code> option for more detailed build log):</p>-<div class="snippet-clipboard-content notranslate position-relative overflow-auto" data-snippet-clipboard-copy-content="$ ./build.sh"><pre class="notranslate"><code>$ ./build.sh-</code></pre></div>-<p dir="auto">This may take several minutes to complete. The first time the script is called, it will create a Python virtual environment that will be also used for subsequent builds. Each time the script is called, the fonts will be rebuilt from scratch. The built fonts will be in <code>build</code> subdirectory, and should be manually copied and committed to <code>fonts</code> subdirectory.</p>-<div class="markdown-heading" dir="auto"><h3 tabindex="-1" class="heading-element" dir="auto">Notes on source formats and build process</h3><a id="user-content-notes-on-source-formats-and-build-process" class="anchor" aria-label="Permalink: Notes on source formats and build process" href="#notes-on-source-formats-and-build-process"><svg class="octicon octicon-link" viewBox="0 0 16 16" version="1.1" width="16" height="16" aria-hidden="true"><path d="m7.775 3.275 1.25-1.25a3.5 3.5 0 1 1 4.95 4.95l-2.5 2.5a3.5 3.5 0 0 1-4.95 0 .751.751 0 0 1 .018-1.042.751.751 0 0 1 1.042-.018 1.998 1.998 0 0 0 2.83 0l2.5-2.5a2.002 2.002 0 0 0-2.83-2.83l-1.25 1.25a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042Zm-4.69 9.64a1.998 1.998 0 0 0 2.83 0l1.25-1.25a.751.751 0 0 1 1.042.018.751.751 0 0 1 .018 1.042l-1.25 1.25a3.5 3.5 0 1 1-4.95-4.95l2.5-2.5a3.5 3.5 0 0 1 4.95 0 .751.751 0 0 1-.018 1.042.751.751 0 0 1-1.042.018 1.998 1.998 0 0 0-2.83 0l-2.5 2.5a1.998 1.998 0 0 0 0 2.83Z"></path></svg></a></div>-<p dir="auto">The design masters for the STIX Two Text fonts are the <strong>.vfj</strong> files, a json source format used by FontLab 7. These files contain the glyph outlines, spacing, mark anchors, kerning and associated classes, font info, and variable design space info. Changes or additions to any of these things should be made in the .vfj files.</p>-<p dir="auto">The build script used to generate font files uses the <strong>.ufo</strong> and <strong>.designspace</strong> files, not the .vfj sources directly. These files can be exported from FontLab 7 using the default export profile for ‘DesignSpace + UFO’.</p>-<p dir="auto">The <strong>.ren</strong> files are glyph name management files used by the build script to manage the relationship of development names in the sources to the build names used in the post or CFF tables of the fonts.</p>-<p dir="auto">Because of issues with editing and managing OpenType Layout GPOS in variable font sources, the OTL projects for the STIX Two Text fonts are built in Microsoft’s <a href="https://docs.microsoft.com/en-us/typography/tools/volt/" rel="nofollow">Visual OpenType Layout Tool</a> (VOLT). This means changes to OTL, including updates to mark anchors and kerning implemented in the .vfj sources need to be passed through VOLT, updated in the <strong>.vtp</strong> VOLT project files, and compiled in <strong>.input.ttf</strong> which are then used by the build script as a source for the OTL tables in the fonts.</p>-<p dir="auto">Obviously, any changes or extension to the glyph set in the .vfj design sources needs to be reflected in each of the other sources used in the build process: in the .ufo files, the .ren file glyph name lists, and especially in the .input.ttf files and .vtp project files. Fresh .input.ttf files can be exported from FontLab 7, opened in VOLT, and the .vtp project files imported and updated.</p>-<p dir="auto">Note that if changes or updates are made to mark anchors or kerning or associated classes in the .vfj sources, these need to be converted to VOLT format and imported into the projects, replacing or updating existing VOLT lookups and groups. This can be done using the <a href="https://github.com/TiroTypeworks/TiroTools/tree/master/VFJtools">vfj-to-volt.py</a> tool.</p>-<p dir="auto">The revised .vtp files should then be exported for future use, and the .input.ttf fonts <em>shipped</em> from VOLT (this is important, because although the fonts will work if just compiled and saved in VOLT, they will contain private VOLT source tables and unregistered OTL features that will be then end up in the fonts generated by the build script; so use the ‘Ship Font’ option in VOLT and overwrite the .input.ttf file (save a copy with the VOLT project, if you like, but so long as you remembered to export the updated .vtp you can always reimport as needed)).</p>-<p dir="auto"><strong>IMPORTANT</strong> : the STIXTwoMath-Regular.input.ttf file is also the source for the MATH table and cmap table in the final font build. Care must be taken to preserve or extend these as necessary in this file when updating OpenType Layout or other aspects of the font.</p>-<p dir="auto">Once all the source files are ready, run the <strong>build.sh</strong> as described above. The build script describes what it is doing as it runs, and verbose mode can be used to get more detail. In overview, this is what it does:</p>-<ol dir="auto">-<li>Pre-process the UFO files to:-a) remove all features and kerning groups from the UFOs; b) rename the glyphs to match the TTFs (otherwise the binary tables can’t be grafted in with FontTools easily); c) extract the binary tables and add them under data/com.github.fonttools.ttx/ in the UFO font where ufo2ft expects them; d) save the modified files in build/masters to keep the sources unchanged.</li>-<li>Build variable font with fontmake from build/masters UFOs.</li>-<li>Build binary masters with fontmake (needed for the next step) from UFOs.</li>-<li>Build static fonts with fontmake from UFOs, but telling it to interpolate OTL tables from the binary masters.</li>-<li>Post-process the fonts to fix the name tables and other final touchups.</li>-</ol>-</article></div></div></div></div></div> <!-- --> <!-- --> <script type="application/json" id="__PRIMER_DATA_:R0:__">{"resolvedServerColorMode":"day"}</script></div>-</react-partial>--- <input type="hidden" data-csrf="true" value="CG/UOo9oUDxdIXpqr1Ljiib4ymN3Nmp/Wz3t2GRW2xESHS3ZpYvgQObgfKPFOQsEl7D1b1mb+dEhhJLFHsmfTQ==" />-</div>- <div data-view-component="true" class="Layout-sidebar">-- <div class="BorderGrid about-margin" data-pjax>- <div class="BorderGrid-row">- <div class="BorderGrid-cell">- <div class="hide-sm hide-md">- <h2 class="mb-3 h4">About</h2>-- <p class="f4 my-3">- OpenType Unicode fonts for Scientific, Technical, and Mathematical texts- </p>--- <h3 class="sr-only">Resources</h3>- <div class="mt-2">- <a class="Link--muted" data-analytics-event="{"category":"Repository Overview","action":"click","label":"location:sidebar;file:readme"}" href="#readme-ov-file">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-book mr-2">- <path d="M0 1.75A.75.75 0 0 1 .75 1h4.253c1.227 0 2.317.59 3 1.501A3.743 3.743 0 0 1 11.006 1h4.245a.75.75 0 0 1 .75.75v10.5a.75.75 0 0 1-.75.75h-4.507a2.25 2.25 0 0 0-1.591.659l-.622.621a.75.75 0 0 1-1.06 0l-.622-.621A2.25 2.25 0 0 0 5.258 13H.75a.75.75 0 0 1-.75-.75Zm7.251 10.324.004-5.073-.002-2.253A2.25 2.25 0 0 0 5.003 2.5H1.5v9h3.757a3.75 3.75 0 0 1 1.994.574ZM8.755 4.75l-.004 7.322a3.752 3.752 0 0 1 1.992-.572H14.5v-9h-3.495a2.25 2.25 0 0 0-2.25 2.25Z"></path>-</svg>- Readme-</a> </div>--- <h3 class="sr-only">License</h3>- <div class="mt-2">- <a href="#OFL-1.1-1-ov-file"- class="Link--muted"-- data-analytics-event="{"category":"Repository Overview","action":"click","label":"location:sidebar;file:license"}"- >- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-law mr-1 mr-sm-1 mr-md-2 mr-lg-2">- <path d="M8.75.75V2h.985c.304 0 .603.08.867.231l1.29.736c.038.022.08.033.124.033h2.234a.75.75 0 0 1 0 1.5h-.427l2.111 4.692a.75.75 0 0 1-.154.838l-.53-.53.529.531-.001.002-.002.002-.006.006-.006.005-.01.01-.045.04c-.21.176-.441.327-.686.45C14.556 10.78 13.88 11 13 11a4.498 4.498 0 0 1-2.023-.454 3.544 3.544 0 0 1-.686-.45l-.045-.04-.016-.015-.006-.006-.004-.004v-.001a.75.75 0 0 1-.154-.838L12.178 4.5h-.162c-.305 0-.604-.079-.868-.231l-1.29-.736a.245.245 0 0 0-.124-.033H8.75V13h2.5a.75.75 0 0 1 0 1.5h-6.5a.75.75 0 0 1 0-1.5h2.5V3.5h-.984a.245.245 0 0 0-.124.033l-1.289.737c-.265.15-.564.23-.869.23h-.162l2.112 4.692a.75.75 0 0 1-.154.838l-.53-.53.529.531-.001.002-.002.002-.006.006-.016.015-.045.04c-.21.176-.441.327-.686.45C4.556 10.78 3.88 11 3 11a4.498 4.498 0 0 1-2.023-.454 3.544 3.544 0 0 1-.686-.45l-.045-.04-.016-.015-.006-.006-.004-.004v-.001a.75.75 0 0 1-.154-.838L2.178 4.5H1.75a.75.75 0 0 1 0-1.5h2.234a.249.249 0 0 0 .125-.033l1.288-.737c.265-.15.564-.23.869-.23h.984V.75a.75.75 0 0 1 1.5 0Zm2.945 8.477c.285.135.718.273 1.305.273s1.02-.138 1.305-.273L13 6.327Zm-10 0c.285.135.718.273 1.305.273s1.02-.138 1.305-.273L3 6.327Z"></path>-</svg>- OFL-1.1 license- </a>- </div>------- <include-fragment src="/stipub/stixfonts/hovercards/citation/sidebar_partial?tree_name=master" data-nonce="v2:b49ec1ff-5698-f083-23b7-2d32904b38f1" data-view-component="true">--- <div data-show-on-forbidden-error hidden>- <div class="Box">- <div class="blankslate-container">- <div data-view-component="true" class="blankslate blankslate-spacious color-bg-default rounded-2">--- <h3 data-view-component="true" class="blankslate-heading"> Uh oh!-</h3>- <p data-view-component="true"> <p class="color-fg-muted my-2 mb-2 ws-normal">There was an error while loading. <a class="Link--inTextBlock" data-turbo="false" href="" aria-label="Please reload this page">Please reload this page</a>.</p>-</p>--</div> </div>-</div> </div>-</include-fragment>- <div class="mt-2">- <a href="/stipub/stixfonts/activity" data-view-component="true" class="Link Link--muted"><svg text="gray" aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-pulse mr-2">- <path d="M6 2c.306 0 .582.187.696.471L10 10.731l1.304-3.26A.751.751 0 0 1 12 7h3.25a.75.75 0 0 1 0 1.5h-2.742l-1.812 4.528a.751.751 0 0 1-1.392 0L6 4.77 4.696 8.03A.75.75 0 0 1 4 8.5H.75a.75.75 0 0 1 0-1.5h2.742l1.812-4.529A.751.751 0 0 1 6 2Z"></path>-</svg>- <span class="color-fg-muted">Activity</span></a> </div>-- <div class="mt-2">- <a href="/stipub/stixfonts/custom-properties" data-view-component="true" class="Link Link--muted"><svg text="gray" aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-note mr-2">- <path d="M0 3.75C0 2.784.784 2 1.75 2h12.5c.966 0 1.75.784 1.75 1.75v8.5A1.75 1.75 0 0 1 14.25 14H1.75A1.75 1.75 0 0 1 0 12.25Zm1.75-.25a.25.25 0 0 0-.25.25v8.5c0 .138.112.25.25.25h12.5a.25.25 0 0 0 .25-.25v-8.5a.25.25 0 0 0-.25-.25ZM3.5 6.25a.75.75 0 0 1 .75-.75h7a.75.75 0 0 1 0 1.5h-7a.75.75 0 0 1-.75-.75Zm.75 2.25h4a.75.75 0 0 1 0 1.5h-4a.75.75 0 0 1 0-1.5Z"></path>-</svg>- <span class="color-fg-muted">Custom properties</span></a> </div>-- <h3 class="sr-only">Stars</h3>- <div class="mt-2">- <a href="/stipub/stixfonts/stargazers" data-view-component="true" class="Link Link--muted"><svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-star mr-2">- <path d="M8 .25a.75.75 0 0 1 .673.418l1.882 3.815 4.21.612a.75.75 0 0 1 .416 1.279l-3.046 2.97.719 4.192a.751.751 0 0 1-1.088.791L8 12.347l-3.766 1.98a.75.75 0 0 1-1.088-.79l.72-4.194L.818 6.374a.75.75 0 0 1 .416-1.28l4.21-.611L7.327.668A.75.75 0 0 1 8 .25Zm0 2.445L6.615 5.5a.75.75 0 0 1-.564.41l-3.097.45 2.24 2.184a.75.75 0 0 1 .216.664l-.528 3.084 2.769-1.456a.75.75 0 0 1 .698 0l2.77 1.456-.53-3.084a.75.75 0 0 1 .216-.664l2.24-2.183-3.096-.45a.75.75 0 0 1-.564-.41L8 2.694Z"></path>-</svg>- <strong>851</strong>- stars</a> </div>-- <h3 class="sr-only">Watchers</h3>- <div class="mt-2">- <a href="/stipub/stixfonts/watchers" data-view-component="true" class="Link Link--muted"><svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-eye mr-2">- <path d="M8 2c1.981 0 3.671.992 4.933 2.078 1.27 1.091 2.187 2.345 2.637 3.023a1.62 1.62 0 0 1 0 1.798c-.45.678-1.367 1.932-2.637 3.023C11.67 13.008 9.981 14 8 14c-1.981 0-3.671-.992-4.933-2.078C1.797 10.83.88 9.576.43 8.898a1.62 1.62 0 0 1 0-1.798c.45-.677 1.367-1.931 2.637-3.022C4.33 2.992 6.019 2 8 2ZM1.679 7.932a.12.12 0 0 0 0 .136c.411.622 1.241 1.75 2.366 2.717C5.176 11.758 6.527 12.5 8 12.5c1.473 0 2.825-.742 3.955-1.715 1.124-.967 1.954-2.096 2.366-2.717a.12.12 0 0 0 0-.136c-.412-.621-1.242-1.75-2.366-2.717C10.824 4.242 9.473 3.5 8 3.5c-1.473 0-2.825.742-3.955 1.715-1.124.967-1.954 2.096-2.366 2.717ZM8 10a2 2 0 1 1-.001-3.999A2 2 0 0 1 8 10Z"></path>-</svg>- <strong>30</strong>- watching</a> </div>-- <h3 class="sr-only">Forks</h3>- <div class="mt-2">- <a href="/stipub/stixfonts/forks" data-view-component="true" class="Link Link--muted"><svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-repo-forked mr-2">- <path d="M5 5.372v.878c0 .414.336.75.75.75h4.5a.75.75 0 0 0 .75-.75v-.878a2.25 2.25 0 1 1 1.5 0v.878a2.25 2.25 0 0 1-2.25 2.25h-1.5v2.128a2.251 2.251 0 1 1-1.5 0V8.5h-1.5A2.25 2.25 0 0 1 3.5 6.25v-.878a2.25 2.25 0 1 1 1.5 0ZM5 3.25a.75.75 0 1 0-1.5 0 .75.75 0 0 0 1.5 0Zm6.75.75a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5Zm-3 8.75a.75.75 0 1 0-1.5 0 .75.75 0 0 0 1.5 0Z"></path>-</svg>- <strong>49</strong>- forks</a> </div>--- <div class="mt-2">- <a class="Link--muted" href="/contact/report-content?content_url=https%3A%2F%2Fgithub.com%2Fstipub%2Fstixfonts&report=stipub+%28user%29">- Report repository-</a> </div>-</div>-- </div>- </div>--- <div class="BorderGrid-row">- <div class="BorderGrid-cell">- <h2 class="h4 mb-3" data-pjax="#repo-content-pjax-container" data-turbo-frame="repo-content-turbo-frame">- <a href="/stipub/stixfonts/releases" data-view-component="true" class="Link--primary no-underline Link">Releases- <span title="8" data-view-component="true" class="Counter">8</span></a></h2>-- <a class="Link--primary d-flex no-underline" data-pjax="#repo-content-pjax-container" data-turbo-frame="repo-content-turbo-frame" href="/stipub/stixfonts/releases/tag/v2.13b171">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-tag flex-shrink-0 mt-1 color-fg-success">- <path d="M1 7.775V2.75C1 1.784 1.784 1 2.75 1h5.025c.464 0 .91.184 1.238.513l6.25 6.25a1.75 1.75 0 0 1 0 2.474l-5.026 5.026a1.75 1.75 0 0 1-2.474 0l-6.25-6.25A1.752 1.752 0 0 1 1 7.775Zm1.5 0c0 .066.026.13.073.177l6.25 6.25a.25.25 0 0 0 .354 0l5.025-5.025a.25.25 0 0 0 0-.354l-6.25-6.25a.25.25 0 0 0-.177-.073H2.75a.25.25 0 0 0-.25.25ZM6 5a1 1 0 1 1 0 2 1 1 0 0 1 0-2Z"></path>-</svg>- <div class="ml-2 min-width-0">- <div class="d-flex">- <span class="css-truncate css-truncate-target text-bold mr-2" style="max-width: none;">STIX Two, v2.13 b171</span>- <span title="Label: Latest" data-view-component="true" class="Label Label--success flex-shrink-0">- Latest-</span> </div>- <div class="text-small color-fg-muted"><relative-time datetime="2021-05-26T14:01:55Z" class="no-wrap">May 26, 2021</relative-time></div>- </div>-</a> <div data-view-component="true" class="mt-3">- <a text="small" data-pjax="#repo-content-pjax-container" data-turbo-frame="repo-content-turbo-frame" href="/stipub/stixfonts/releases" data-view-component="true" class="Link">+ 7 releases</a></div>- </div>- </div>---- <div class="BorderGrid-row">- <div class="BorderGrid-cell">-- <h2 class="h4 mb-3">- <a href="/orgs/stipub/packages?repo_name=stixfonts" data-view-component="true" class="Link--primary no-underline Link d-flex flex-items-center">Packages- <span title="0" hidden="hidden" data-view-component="true" class="Counter ml-1">0</span></a></h2>--- <div class="text-small color-fg-muted" >- No packages published <br>- </div>---- </div>- </div>--- <div class="BorderGrid-row" hidden>- <div class="BorderGrid-cell">- <include-fragment src="/stipub/stixfonts/used_by_list" accept="text/fragment+html" data-nonce="v2:b49ec1ff-5698-f083-23b7-2d32904b38f1" data-view-component="true">--- <div data-show-on-forbidden-error hidden>- <div class="Box">- <div class="blankslate-container">- <div data-view-component="true" class="blankslate blankslate-spacious color-bg-default rounded-2">--- <h3 data-view-component="true" class="blankslate-heading"> Uh oh!-</h3>- <p data-view-component="true"> <p class="color-fg-muted my-2 mb-2 ws-normal">There was an error while loading. <a class="Link--inTextBlock" data-turbo="false" href="" aria-label="Please reload this page">Please reload this page</a>.</p>-</p>--</div> </div>-</div> </div>-</include-fragment>- </div>- </div>--- <div class="BorderGrid-row">- <div class="BorderGrid-cell">- <h2 class="h4 mb-3">- <a href="/stipub/stixfonts/graphs/contributors" data-view-component="true" class="Link--primary no-underline Link d-flex flex-items-center">Contributors- <span title="7" data-view-component="true" class="Counter ml-1">7</span></a></h2>--- <include-fragment aria-busy="true" aria-label="Loading contributors" src="/stipub/stixfonts/contributors_list?count=7&current_repository=stixfonts&items_to_show=7" data-nonce="v2:b49ec1ff-5698-f083-23b7-2d32904b38f1" data-view-component="true">-- <ul class="list-style-none d-flex flex-wrap mb-n2">- <li class="mb-2 ">- <div class="Skeleton avatar avatar-user mr-2" style="width:32px;height:32px;"></div>- </li>- <li class="mb-2 ">- <div class="Skeleton avatar avatar-user mr-2" style="width:32px;height:32px;"></div>- </li>- <li class="mb-2 ">- <div class="Skeleton avatar avatar-user mr-2" style="width:32px;height:32px;"></div>- </li>- <li class="mb-2 ">- <div class="Skeleton avatar avatar-user mr-2" style="width:32px;height:32px;"></div>- </li>- <li class="mb-2 ">- <div class="Skeleton avatar avatar-user mr-2" style="width:32px;height:32px;"></div>- </li>- <li class="mb-2 ">- <div class="Skeleton avatar avatar-user mr-2" style="width:32px;height:32px;"></div>- </li>- <li class="mb-2 ">- <div class="Skeleton avatar avatar-user mr-2" style="width:32px;height:32px;"></div>- </li>- </ul>-- <div data-show-on-forbidden-error hidden>- <div class="Box">- <div class="blankslate-container">- <div data-view-component="true" class="blankslate blankslate-spacious color-bg-default rounded-2">--- <h3 data-view-component="true" class="blankslate-heading"> Uh oh!-</h3>- <p data-view-component="true"> <p class="color-fg-muted my-2 mb-2 ws-normal">There was an error while loading. <a class="Link--inTextBlock" data-turbo="false" href="" aria-label="Please reload this page">Please reload this page</a>.</p>-</p>--</div> </div>-</div> </div>-</include-fragment>--- </div>- </div>---- <div class="BorderGrid-row">- <div class="BorderGrid-cell">- <h2 class="h4 mb-3">Languages</h2>-<div class="mb-2">- <span data-view-component="true" class="Progress">- <span style="background-color:#74283c !important;;width: 84.4%;" itemprop="keywords" data-view-component="true" class="Progress-item color-bg-success-emphasis"></span>- <span style="background-color:#3D6117 !important;;width: 15.4%;" itemprop="keywords" data-view-component="true" class="Progress-item color-bg-success-emphasis"></span>- <span style="background-color:#ededed !important;;width: 0.2%;" itemprop="keywords" data-view-component="true" class="Progress-item color-bg-success-emphasis"></span>-</span></div>-<ul class="list-style-none">- <li class="d-inline">- <a class="d-inline-flex flex-items-center flex-nowrap Link--secondary no-underline text-small mr-3" href="/stipub/stixfonts/search?l=prolog" data-ga-click="Repository, language stats search click, location:repo overview">- <svg style="color:#74283c;" aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-dot-fill mr-2">- <path d="M8 4a4 4 0 1 1 0 8 4 4 0 0 1 0-8Z"></path>-</svg>- <span class="color-fg-default text-bold mr-1">Prolog</span>- <span>84.4%</span>- </a>- </li>- <li class="d-inline">- <a class="d-inline-flex flex-items-center flex-nowrap Link--secondary no-underline text-small mr-3" href="/stipub/stixfonts/search?l=tex" data-ga-click="Repository, language stats search click, location:repo overview">- <svg style="color:#3D6117;" aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-dot-fill mr-2">- <path d="M8 4a4 4 0 1 1 0 8 4 4 0 0 1 0-8Z"></path>-</svg>- <span class="color-fg-default text-bold mr-1">TeX</span>- <span>15.4%</span>- </a>- </li>- <li class="d-inline">- <span class="d-inline-flex flex-items-center flex-nowrap text-small mr-3">- <svg style="color:#ededed;" aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-dot-fill mr-2">- <path d="M8 4a4 4 0 1 1 0 8 4 4 0 0 1 0-8Z"></path>-</svg>- <span class="color-fg-default text-bold mr-1">Other</span>- <span>0.2%</span>- </span>- </li>-</ul>-- </div>- </div>-- </div>-</div>--</div></div>-- </div>--- </div>--</turbo-frame>--- </main>- </div>-- </div>-- <footer class="footer pt-8 pb-6 f6 color-fg-muted p-responsive" role="contentinfo" >- <h2 class='sr-only'>Footer</h2>----- <div class="d-flex flex-justify-center flex-items-center flex-column-reverse flex-lg-row flex-wrap flex-lg-nowrap">- <div class="d-flex flex-items-center flex-shrink-0 mx-2">- <a aria-label="GitHub Homepage" class="footer-octicon mr-2" href="https://github.com">- <svg aria-hidden="true" height="24" viewBox="0 0 24 24" version="1.1" width="24" data-view-component="true" class="octicon octicon-mark-github">- <path d="M12 1C5.923 1 1 5.923 1 12c0 4.867 3.149 8.979 7.521 10.436.55.096.756-.233.756-.522 0-.262-.013-1.128-.013-2.049-2.764.509-3.479-.674-3.699-1.292-.124-.317-.66-1.293-1.127-1.554-.385-.207-.936-.715-.014-.729.866-.014 1.485.797 1.691 1.128.99 1.663 2.571 1.196 3.204.907.096-.715.385-1.196.701-1.471-2.448-.275-5.005-1.224-5.005-5.432 0-1.196.426-2.186 1.128-2.956-.111-.275-.496-1.402.11-2.915 0 0 .921-.288 3.024 1.128a10.193 10.193 0 0 1 2.75-.371c.936 0 1.871.123 2.75.371 2.104-1.43 3.025-1.128 3.025-1.128.605 1.513.221 2.64.111 2.915.701.77 1.127 1.747 1.127 2.956 0 4.222-2.571 5.157-5.019 5.432.399.344.743 1.004.743 2.035 0 1.471-.014 2.654-.014 3.025 0 .289.206.632.756.522C19.851 20.979 23 16.854 23 12c0-6.077-4.922-11-11-11Z"></path>-</svg>-</a>- <span>- © 2025 GitHub, Inc.- </span>- </div>-- <nav aria-label="Footer">- <h3 class="sr-only" id="sr-footer-heading">Footer navigation</h3>-- <ul class="list-style-none d-flex flex-justify-center flex-wrap mb-2 mb-lg-0" aria-labelledby="sr-footer-heading">-- <li class="mx-2">- <a data-analytics-event="{"category":"Footer","action":"go to Terms","label":"text:terms"}" href="https://docs.github.com/site-policy/github-terms/github-terms-of-service" data-view-component="true" class="Link--secondary Link">Terms</a>- </li>-- <li class="mx-2">- <a data-analytics-event="{"category":"Footer","action":"go to privacy","label":"text:privacy"}" href="https://docs.github.com/site-policy/privacy-policies/github-privacy-statement" data-view-component="true" class="Link--secondary Link">Privacy</a>- </li>-- <li class="mx-2">- <a data-analytics-event="{"category":"Footer","action":"go to security","label":"text:security"}" href="https://github.com/security" data-view-component="true" class="Link--secondary Link">Security</a>- </li>-- <li class="mx-2">- <a data-analytics-event="{"category":"Footer","action":"go to status","label":"text:status"}" href="https://www.githubstatus.com/" data-view-component="true" class="Link--secondary Link">Status</a>- </li>-- <li class="mx-2">- <a data-analytics-event="{"category":"Footer","action":"go to community","label":"text:community"}" href="https://github.community/" data-view-component="true" class="Link--secondary Link">Community</a>- </li>-- <li class="mx-2">- <a data-analytics-event="{"category":"Footer","action":"go to docs","label":"text:docs"}" href="https://docs.github.com/" data-view-component="true" class="Link--secondary Link">Docs</a>- </li>-- <li class="mx-2">- <a data-analytics-event="{"category":"Footer","action":"go to contact","label":"text:contact"}" href="https://support.github.com?tags=dotcom-footer" data-view-component="true" class="Link--secondary Link">Contact</a>- </li>-- <li class="mx-2" >- <cookie-consent-link>- <button- type="button"- class="Link--secondary underline-on-hover border-0 p-0 color-bg-transparent"- data-action="click:cookie-consent-link#showConsentManagement"- data-analytics-event="{"location":"footer","action":"cookies","context":"subfooter","tag":"link","label":"cookies_link_subfooter_footer"}"- >- Manage cookies- </button>- </cookie-consent-link>-</li>--<li class="mx-2">- <cookie-consent-link>- <button- type="button"- class="Link--secondary underline-on-hover border-0 p-0 color-bg-transparent text-left"- data-action="click:cookie-consent-link#showConsentManagement"- data-analytics-event="{"location":"footer","action":"dont_share_info","context":"subfooter","tag":"link","label":"dont_share_info_link_subfooter_footer"}"- >- Do not share my personal information- </button>- </cookie-consent-link>-</li>-- </ul>- </nav>- </div>-</footer>---- <ghcc-consent id="ghcc" class="position-fixed bottom-0 left-0" style="z-index: 999999"- data-locale="en"- data-initial-cookie-consent-allowed=""- data-cookie-consent-required="true"- ></ghcc-consent>----- <div id="ajax-error-message" class="ajax-error-message flash flash-error" hidden>- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert">- <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>-</svg>- <button type="button" class="flash-close js-ajax-error-dismiss" aria-label="Dismiss error">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-x">- <path d="M3.72 3.72a.75.75 0 0 1 1.06 0L8 6.94l3.22-3.22a.749.749 0 0 1 1.275.326.749.749 0 0 1-.215.734L9.06 8l3.22 3.22a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215L8 9.06l-3.22 3.22a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042L6.94 8 3.72 4.78a.75.75 0 0 1 0-1.06Z"></path>-</svg>- </button>- You can’t perform that action at this time.- </div>-- <template id="site-details-dialog">- <details class="details-reset details-overlay details-overlay-dark lh-default color-fg-default hx_rsm" open>- <summary role="button" aria-label="Close dialog"></summary>- <details-dialog class="Box Box--overlay d-flex flex-column anim-fade-in fast hx_rsm-dialog hx_rsm-modal">- <button class="Box-btn-octicon m-0 btn-octicon position-absolute right-0 top-0" type="button" aria-label="Close dialog" data-close-dialog>- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-x">- <path d="M3.72 3.72a.75.75 0 0 1 1.06 0L8 6.94l3.22-3.22a.749.749 0 0 1 1.275.326.749.749 0 0 1-.215.734L9.06 8l3.22 3.22a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215L8 9.06l-3.22 3.22a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042L6.94 8 3.72 4.78a.75.75 0 0 1 0-1.06Z"></path>-</svg>- </button>- <div class="octocat-spinner my-6 js-details-dialog-spinner"></div>- </details-dialog>- </details>-</template>-- <div class="Popover js-hovercard-content position-absolute" style="display: none; outline: none;">- <div class="Popover-message Popover-message--bottom-left Popover-message--large Box color-shadow-large" style="width:360px;">- </div>-</div>-- <template id="snippet-clipboard-copy-button">- <div class="zeroclipboard-container position-absolute right-0 top-0">- <clipboard-copy aria-label="Copy" class="ClipboardButton btn js-clipboard-copy m-2 p-0" data-copy-feedback="Copied!" data-tooltip-direction="w">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-copy js-clipboard-copy-icon m-2">- <path d="M0 6.75C0 5.784.784 5 1.75 5h1.5a.75.75 0 0 1 0 1.5h-1.5a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-1.5a.75.75 0 0 1 1.5 0v1.5A1.75 1.75 0 0 1 9.25 16h-7.5A1.75 1.75 0 0 1 0 14.25Z"></path><path d="M5 1.75C5 .784 5.784 0 6.75 0h7.5C15.216 0 16 .784 16 1.75v7.5A1.75 1.75 0 0 1 14.25 11h-7.5A1.75 1.75 0 0 1 5 9.25Zm1.75-.25a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-7.5a.25.25 0 0 0-.25-.25Z"></path>-</svg>- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-check js-clipboard-check-icon color-fg-success d-none m-2">- <path d="M13.78 4.22a.75.75 0 0 1 0 1.06l-7.25 7.25a.75.75 0 0 1-1.06 0L2.22 9.28a.751.751 0 0 1 .018-1.042.751.751 0 0 1 1.042-.018L6 10.94l6.72-6.72a.75.75 0 0 1 1.06 0Z"></path>-</svg>- </clipboard-copy>- </div>-</template>-<template id="snippet-clipboard-copy-button-unpositioned">- <div class="zeroclipboard-container">- <clipboard-copy aria-label="Copy" class="ClipboardButton btn btn-invisible js-clipboard-copy m-2 p-0 d-flex flex-justify-center flex-items-center" data-copy-feedback="Copied!" data-tooltip-direction="w">- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-copy js-clipboard-copy-icon">- <path d="M0 6.75C0 5.784.784 5 1.75 5h1.5a.75.75 0 0 1 0 1.5h-1.5a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-1.5a.75.75 0 0 1 1.5 0v1.5A1.75 1.75 0 0 1 9.25 16h-7.5A1.75 1.75 0 0 1 0 14.25Z"></path><path d="M5 1.75C5 .784 5.784 0 6.75 0h7.5C15.216 0 16 .784 16 1.75v7.5A1.75 1.75 0 0 1 14.25 11h-7.5A1.75 1.75 0 0 1 5 9.25Zm1.75-.25a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-7.5a.25.25 0 0 0-.25-.25Z"></path>-</svg>- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-check js-clipboard-check-icon color-fg-success d-none">- <path d="M13.78 4.22a.75.75 0 0 1 0 1.06l-7.25 7.25a.75.75 0 0 1-1.06 0L2.22 9.28a.751.751 0 0 1 .018-1.042.751.751 0 0 1 1.042-.018L6 10.94l6.72-6.72a.75.75 0 0 1 1.06 0Z"></path>-</svg>- </clipboard-copy>- </div>-</template>----- </div>- <div id="js-global-screen-reader-notice" class="sr-only mt-n1" aria-live="polite" aria-atomic="true" ></div>- <div id="js-global-screen-reader-notice-assertive" class="sr-only mt-n1" aria-live="assertive" aria-atomic="true"></div>- </body>-</html>-diff --git a/app/core/src/main/resources/type3/library/fonts/stix/STIXTwoMath-Regular.otf b/app/core/src/main/resources/type3/library/fonts/stix/STIXTwoMath-Regular.otfdeleted file mode 100644index 29aa3b9415..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/stix/STIXTwoMath-Regular.otf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/stix/STIXTwoText-Bold.otf b/app/core/src/main/resources/type3/library/fonts/stix/STIXTwoText-Bold.otfdeleted file mode 100644index e617a64192..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/stix/STIXTwoText-Bold.otf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/stix/STIXTwoText-Italic.otf b/app/core/src/main/resources/type3/library/fonts/stix/STIXTwoText-Italic.otfdeleted file mode 100644index 19599296e9..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/stix/STIXTwoText-Italic.otf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/fonts/stix/STIXTwoText-Regular.otf b/app/core/src/main/resources/type3/library/fonts/stix/STIXTwoText-Regular.otfdeleted file mode 100644index 630bf714c1..0000000000Binary files a/app/core/src/main/resources/type3/library/fonts/stix/STIXTwoText-Regular.otf and /dev/null differdiff --git a/app/core/src/main/resources/type3/library/index.json b/app/core/src/main/resources/type3/library/index.jsondeleted file mode 100644index b3a83d431b..0000000000--- a/app/core/src/main/resources/type3/library/index.json+++ /dev/null@@ -1,1643 +0,0 @@-[- {- "id": "dejavu-sans-regular",- "label": "DejaVu Sans",- "aliases": [- "DejaVuSans",- "dejavusans"- ],- "program": {- "resource": "type3/library/fonts/dejavu/DejaVuSans.ttf",- "format": "ttf"- },- "webProgram": {- "resource": "type3/library/fonts/dejavu/DejaVuSans.ttf",- "format": "ttf"- },- "pdfProgram": {- "resource": "type3/library/fonts/dejavu/DejaVuSans.ttf",- "format": "ttf"- },- "source": "DejaVu Fonts 2.37",- "signatures": [- "sha256:2be58b6ef1e29a83b8634d70b9e32c37a15dea2e608894439ef7224c35b77f5d",- "sha256:994c963d70041eee141fd275fa22c525a71283de2b4a952814d02e0bbfa8caea",- "sha256:93573cb1ab32b9cb09378298fb120de079f6a309908d2ee86f91392a6aba5c31",- "sha256:4febfad91e0141f9658506a0bf8fc2a449f0ea7d97b44e95fc9a970c77af4b0a",- "sha256:0386e5811612ba4b998d57cd3869d7fbc48092a79d436deda774af107a4af813",- "sha256:b95fa2a272cbc950b81320790d04fcf19ebb24050fa2139ba6a474172cac596b",- "sha256:d034d16ac69e3e1c5008e77c4c24dc3179308a2742601e89d5c8ab327e4040dd",- "sha256:ae77c4eb2c49f72c616272f3d7ac624ddb0b4db1c77acbe6b9d13531f68e1d5d",- "sha256:85e16e36ed0290c149647be7e468a7c46e7b66fd290131213040f7bad905aa44",- "sha256:3654d4d9bcbbf6ad51628082203094069a17aad3a5e6f5c7972833566e42ab6b",- "sha256:d0c6cddc416d130701395246621a0f669fc292df4097a7a74395602faf4475df",- "sha256:cadf43a2df81340368af44c76b499223931d78dcc76c70cf4b4a93d133e368af",- "sha256:f1a874c4268b1bffffc99acabbe0a60aa662611b4bac0e688e4fc0ae3f2033bb",- "sha256:e3d87c113463c8642a4f22943064fd75c133ad31fe5efebf6de6abf211b74b5a",- "sha256:d47afb7581e98f588f0e70953e8692249aaa2ec3df36fbd90985f27b1ce1cf50",- "sha256:e47b8f112a875361a43bcb6d9c6467e0296412d29e417e58a0e60c90b664d281",- "sha256:9c67df2ac5c3dcf957dfb0cd048fa450322a72b5a2dfb05f816c536b3b090607",- "sha256:3ee773a0af6fdedb9853dca9f4d8b80a421a0024bdf06bea41f15d58e3b90c87",- "sha256:4fa06c90399d80b41cb718163a5d78af2b203df6b6579246fb0b24d349b7a591",- "sha256:ac6756c76d6e43b771cc1e643dfc7891dfaaac05aa5e302190d0a662838ab031",- "sha256:bf7b95498f7d00d228c5c155db62b6c1aa7e0215cca1690c9fdb0adcfd496b10",- "sha256:39b8e5ec8e20a788cd45166baf0ab796397f152c9cd8dec1f882c635380cad92",- "sha256:27b98489865df8df55f19e4505c093501f236465885ca3bf5b66b6f047a85bb2",- "sha256:497ddd27e1f56ef6504c61613e3a159bab13314a4970a3be13b3a556648964da",- "sha256:3b41f9e5f3a7ffa6f4cdffa2a46f02781ec1b2b0c99994707cfb139aa15a11e2",- "sha256:93723fe436a1aa654db56caf133f56280444b9dc0682af50b83787c3e49ee3ec",- "sha256:a648cb0524465bcb3bf4a2f65e0761cfc5167b1871a7db9488bee11b56062727",- "sha256:2f18ed7f982aeb954aaae388ba0c75e3c676717ca324156b42bb17f3f20ef403",- "sha256:18ce863feb57f42f2b92ac85a8c55ef3eeaa15488c5d6cd8c724b085994c64fa",- "sha256:a3eb7054e426aad7d1fac1f39ad6d3f886e34c04f780def5cf22b53cb3a45b46",- "sha256:edd22119635bfb0f2bff750137c6c6400a7fae4ff80cc252d2e6f2ca88f599a7",- "sha256:aae1797f3e3ff55d71b02590333aff86663d6bb4a5768bed7550e5987f40afe8",- "sha256:0165552fad28860f2ea6079be7a87ea0833acde99309b3ef619c8f81707c46a3",- "sha256:792a1c5aaa1743ab203a363a8f6cd07c3b043e33c72e97c4ea21f5862158e6c1",- "sha256:f4bfd64f36bf33dea79800561a67f78d5ccdb436363574abf0892f58b376a2e6",- "sha256:119da04d962622c8aa46d77f6bdfccb5d4a4ef7173775275b046efd59098e5d9",- "sha256:003af1c45e3a5ab09544e226eba25e3a70abfe6e36dd48584474cc7a497685f6",- "sha256:88b3471db1978cc83233f249453806a8369c766b089b424c86c2584196ed5dbf",- "sha256:a15cc90b7fc110cef4f07fe8a692d572e1289a9ee29c95732294662fded4e042",- "sha256:fb54c23aa081562ac114676ffe43032c9c0fb63af3e5b7b3441b88872d1f2e7a",- "sha256:4b553d51d58f5891af071359fb016caf1c6137778da129a6b208dcc8cb0c4635",- "sha256:b318f65b9dc209eb6f004e3a6c20a772ebbca3d752adc10c66a6a8a479da2838",- "sha256:64f725573c1f5d90196e94ed338a7af06baf274420414befeb9693c80acd0f77",- "sha256:9a701e082ba5a779e2b20b8de0c7844b3f7838ba8cd4bd7ef366893761fb994d",- "sha256:2f6f8d63ff6235f3b7cd6f5eba8076854892037afa2ea6962953b3e7cda3736e",- "sha256:f17b5eb0ee996d1388c548f79fa50fa2d8c6076959eff189bb745d156d54547f",- "sha256:f22c75548364bb25fc3efbe11f05c56e29f07c15c3046ddbc85a64e5cc5a97bd",- "sha256:54a6c2e4bc290b48e21eece7f81cb6633c4b53a91f198fdaabfc73743b0e4499",- "sha256:059af9dbaaab27c1d660ef00de6d4fd6e1687cfe2abca0a4c07265c2b2b450c6",- "sha256:6651550d7b913850087244b7a70961989c2efc6d8c8d060d8663ff087b7723f6",- "sha256:4d4ee6f04f57a40a589741df4747990ed485c192b0fc179a415aba822f352a8d",- "sha256:e808a8ecba94bf0190ab7218bb0702698125ee2e456e82e00da709e8188e2bf8",- "sha256:b5064b202eb1dae41545eddf674ee23bd82176e76aac8eb749540c2689f2e3ec",- "sha256:f8f14410ec170248916e19f9d09120cfd786c47906b7c3735781d24e944b094e",- "sha256:c43134bebeaf8328ac299ba978d7e663e2dc4fe99463b9d7f72f72f77936204e",- "sha256:4f763d5e2cd0bdcd4650936ac505bd0e011899712ffe80ffa4b4d43f42941327",- "sha256:cb72de0c6105b9802d360c47a292a1f7bc344939a6801b879ea09dae4e45e863",- "sha256:2add5b5ad6e536f3614b75e246b49a006edbbecdd309d24bd42c874a3ae3c8ed",- "sha256:31d0e67bc63a816302c9ff6ad9c19e17603aef1a4c3677b81b1d9084caa86e03",- "sha256:4b509d2ae2cfab89783a73df2c66f0fd50949f97696079cb58f1e58b81daaa07",- "sha256:831f7012db360331ffb5a5de6a6d6e03ffaad29f48d81cabe9fc613b25aad818",- "sha256:bf790625423c5ebdf94760eb796c847af885b930d3a30861509b07f1c77c3f60",- "sha256:f7c3be2199c397a4c702dd434ac63fc9e046d749eff8cede4513fbc2774751b4",- "sha256:8f7bf7a6382e8a762c5a84f19f84f0675f61eb1b34bd42562c0b3ac6712e29ef",- "sha256:dfaf8075e13be0e51f72485f9d825cea9ad077eb2dd9d63b9922add67d7d2761",- "sha256:853422e67ac88fe7ae28d5c459dc9f5a84f24e7840eeb2d82a00719032119326",- "sha256:b42182c55ec4bd53ab0698bee5f92945921dbccb534fdb5c6b41f1782e1fe88e",- "sha256:75466035ac34f2523215e599452e32d796d7d02bc7122ed3d02fe91ebe064c25"- ],- "glyphCoverage": [- 32,- 33,- 37,- 39,- 40,- 41,- 43,- 44,- 45,- 46,- 48,- 49,- 50,- 51,- 52,- 53,- 54,- 55,- 56,- 57,- 58,- 61,- 65,- 66,- 67,- 68,- 69,- 70,- 71,- 72,- 73,- 76,- 77,- 78,- 79,- 80,- 82,- 83,- 84,- 85,- 87,- 88,- 89,- 91,- 93,- 95,- 97,- 98,- 99,- 100,- 101,- 102,- 103,- 104,- 105,- 106,- 107,- 108,- 109,- 110,- 111,- 112,- 113,- 114,- 115,- 116,- 117,- 118,- 119,- 120,- 121,- 122,- 215- ]- },- {- "id": "dejavu-sans-bold",- "label": "DejaVu Sans Bold",- "aliases": [- "DejaVuSans-Bold",- "dejavusans-bold"- ],- "program": {- "resource": "type3/library/fonts/dejavu/DejaVuSans-Bold.ttf",- "format": "ttf"- },- "webProgram": {- "resource": "type3/library/fonts/dejavu/DejaVuSans-Bold.ttf",- "format": "ttf"- },- "pdfProgram": {- "resource": "type3/library/fonts/dejavu/DejaVuSans-Bold.ttf",- "format": "ttf"- },- "source": "DejaVu Fonts 2.37",- "signatures": [- "sha256:dc03917f2edd92a7a68a46ad36f65a908e4feb85e61cb37e9026205f3986574a",- "sha256:c845063bef18f173afbfcb90fbf6773f43648c5f0666ecfa0132afe4e164068d"- ],- "glyphCoverage": [- 32,- 65,- 83,- 87,- 97,- 100,- 101,- 103,- 105,- 110,- 116,- 118,- 119- ]- },- {- "id": "dejavu-sans-oblique",- "label": "DejaVu Sans Oblique",- "aliases": [- "DejaVuSans-Oblique",- "dejavusans-oblique"- ],- "program": {- "resource": "type3/library/fonts/dejavu/DejaVuSans-Oblique.ttf",- "format": "ttf"- },- "webProgram": {- "resource": "type3/library/fonts/dejavu/DejaVuSans-Oblique.ttf",- "format": "ttf"- },- "pdfProgram": {- "resource": "type3/library/fonts/dejavu/DejaVuSans-Oblique.ttf",- "format": "ttf"- },- "source": "DejaVu Fonts 2.37",- "signatures": [- "sha256:81cd2d4d9353ee02c7ed80c2892658072b2a8bbd9ed1832b474129dfbe35d5d8",- "sha256:08864aa8e8d17cead6059d5b4f1b1eea2053fa0ea3ca64e885d6eaacb78bccaf"- ],- "glyphCoverage": [- 70,- 71,- 85,- 87,- 100,- 101,- 103,- 109,- 112,- 114,- 116,- 118,- 120- ]- },- {- "id": "dejavu-sans-boldoblique",- "label": "DejaVu Sans Bold Oblique",- "aliases": [- "DejaVuSans-BoldOblique",- "dejavusans-boldoblique"- ],- "program": {- "resource": "type3/library/fonts/dejavu/DejaVuSans-BoldOblique.ttf",- "format": "ttf"- },- "webProgram": {- "resource": "type3/library/fonts/dejavu/DejaVuSans-BoldOblique.ttf",- "format": "ttf"- },- "pdfProgram": {- "resource": "type3/library/fonts/dejavu/DejaVuSans-BoldOblique.ttf",- "format": "ttf"- },- "source": "DejaVu Fonts 2.37",- "signatures": [],- "glyphCoverage": []- },- {- "id": "dejavu-sans-condensed",- "label": "DejaVu Sans Condensed",- "aliases": [- "DejaVuSansCondensed",- "dejavusanscondensed"- ],- "program": {- "resource": "type3/library/fonts/dejavu/DejaVuSansCondensed.ttf",- "format": "ttf"- },- "webProgram": {- "resource": "type3/library/fonts/dejavu/DejaVuSansCondensed.ttf",- "format": "ttf"- },- "pdfProgram": {- "resource": "type3/library/fonts/dejavu/DejaVuSansCondensed.ttf",- "format": "ttf"- },- "source": "DejaVu Fonts 2.37",- "signatures": [],- "glyphCoverage": []- },- {- "id": "dejavu-sans-condensed-bold",- "label": "DejaVu Sans Condensed Bold",- "aliases": [- "DejaVuSansCondensed-Bold"- ],- "program": {- "resource": "type3/library/fonts/dejavu/DejaVuSansCondensed-Bold.ttf",- "format": "ttf"- },- "webProgram": {- "resource": "type3/library/fonts/dejavu/DejaVuSansCondensed-Bold.ttf",- "format": "ttf"- },- "pdfProgram": {- "resource": "type3/library/fonts/dejavu/DejaVuSansCondensed-Bold.ttf",- "format": "ttf"- },- "source": "DejaVu Fonts 2.37",- "signatures": [],- "glyphCoverage": []- },- {- "id": "dejavu-sans-condensed-oblique",- "label": "DejaVu Sans Condensed Oblique",- "aliases": [- "DejaVuSansCondensed-Oblique"- ],- "program": {- "resource": "type3/library/fonts/dejavu/DejaVuSansCondensed-Oblique.ttf",- "format": "ttf"- },- "webProgram": {- "resource": "type3/library/fonts/dejavu/DejaVuSansCondensed-Oblique.ttf",- "format": "ttf"- },- "pdfProgram": {- "resource": "type3/library/fonts/dejavu/DejaVuSansCondensed-Oblique.ttf",- "format": "ttf"- },- "source": "DejaVu Fonts 2.37",- "signatures": [],- "glyphCoverage": []- },- {- "id": "dejavu-sans-condensed-boldoblique",- "label": "DejaVu Sans Condensed Bold Oblique",- "aliases": [- "DejaVuSansCondensed-BoldOblique"- ],- "program": {- "resource": "type3/library/fonts/dejavu/DejaVuSansCondensed-BoldOblique.ttf",- "format": "ttf"- },- "webProgram": {- "resource": "type3/library/fonts/dejavu/DejaVuSansCondensed-BoldOblique.ttf",- "format": "ttf"- },- "pdfProgram": {- "resource": "type3/library/fonts/dejavu/DejaVuSansCondensed-BoldOblique.ttf",- "format": "ttf"- },- "source": "DejaVu Fonts 2.37",- "signatures": [],- "glyphCoverage": []- },- {- "id": "dejavu-serif-regular",- "label": "DejaVu Serif",- "aliases": [- "DejaVuSerif",- "dejavuserif"- ],- "program": {- "resource": "type3/library/fonts/dejavu/DejaVuSerif.ttf",- "format": "ttf"- },- "webProgram": {- "resource": "type3/library/fonts/dejavu/DejaVuSerif.ttf",- "format": "ttf"- },- "pdfProgram": {- "resource": "type3/library/fonts/dejavu/DejaVuSerif.ttf",- "format": "ttf"- },- "source": "DejaVu Fonts 2.37",- "signatures": [],- "glyphCoverage": []- },- {- "id": "dejavu-serif-bold",- "label": "DejaVu Serif Bold",- "aliases": [- "DejaVuSerif-Bold",- "dejavuserif-bold"- ],- "program": {- "resource": "type3/library/fonts/dejavu/DejaVuSerif-Bold.ttf",- "format": "ttf"- },- "webProgram": {- "resource": "type3/library/fonts/dejavu/DejaVuSerif-Bold.ttf",- "format": "ttf"- },- "pdfProgram": {- "resource": "type3/library/fonts/dejavu/DejaVuSerif-Bold.ttf",- "format": "ttf"- },- "source": "DejaVu Fonts 2.37",- "signatures": [],- "glyphCoverage": []- },- {- "id": "dejavu-serif-italic",- "label": "DejaVu Serif Italic",- "aliases": [- "DejaVuSerif-Italic",- "dejavuserif-italic"- ],- "program": {- "resource": "type3/library/fonts/dejavu/DejaVuSerif-Italic.ttf",- "format": "ttf"- },- "webProgram": {- "resource": "type3/library/fonts/dejavu/DejaVuSerif-Italic.ttf",- "format": "ttf"- },- "pdfProgram": {- "resource": "type3/library/fonts/dejavu/DejaVuSerif-Italic.ttf",- "format": "ttf"- },- "source": "DejaVu Fonts 2.37",- "signatures": [],- "glyphCoverage": []- },- {- "id": "dejavu-serif-bolditalic",- "label": "DejaVu Serif Bold Italic",- "aliases": [- "DejaVuSerif-BoldItalic"- ],- "program": {- "resource": "type3/library/fonts/dejavu/DejaVuSerif-BoldItalic.ttf",- "format": "ttf"- },- "webProgram": {- "resource": "type3/library/fonts/dejavu/DejaVuSerif-BoldItalic.ttf",- "format": "ttf"- },- "pdfProgram": {- "resource": "type3/library/fonts/dejavu/DejaVuSerif-BoldItalic.ttf",- "format": "ttf"- },- "source": "DejaVu Fonts 2.37",- "signatures": [],- "glyphCoverage": []- },- {- "id": "dejavu-serif-condensed",- "label": "DejaVu Serif Condensed",- "aliases": [- "DejaVuSerifCondensed"- ],- "program": {- "resource": "type3/library/fonts/dejavu/DejaVuSerifCondensed.ttf",- "format": "ttf"- },- "webProgram": {- "resource": "type3/library/fonts/dejavu/DejaVuSerifCondensed.ttf",- "format": "ttf"- },- "pdfProgram": {- "resource": "type3/library/fonts/dejavu/DejaVuSerifCondensed.ttf",- "format": "ttf"- },- "source": "DejaVu Fonts 2.37",- "signatures": [],- "glyphCoverage": []- },- {- "id": "dejavu-serif-condensed-bold",- "label": "DejaVu Serif Condensed Bold",- "aliases": [- "DejaVuSerifCondensed-Bold"- ],- "program": {- "resource": "type3/library/fonts/dejavu/DejaVuSerifCondensed-Bold.ttf",- "format": "ttf"- },- "webProgram": {- "resource": "type3/library/fonts/dejavu/DejaVuSerifCondensed-Bold.ttf",- "format": "ttf"- },- "pdfProgram": {- "resource": "type3/library/fonts/dejavu/DejaVuSerifCondensed-Bold.ttf",- "format": "ttf"- },- "source": "DejaVu Fonts 2.37",- "signatures": [],- "glyphCoverage": []- },- {- "id": "dejavu-serif-condensed-italic",- "label": "DejaVu Serif Condensed Italic",- "aliases": [- "DejaVuSerifCondensed-Italic"- ],- "program": {- "resource": "type3/library/fonts/dejavu/DejaVuSerifCondensed-Italic.ttf",- "format": "ttf"- },- "webProgram": {- "resource": "type3/library/fonts/dejavu/DejaVuSerifCondensed-Italic.ttf",- "format": "ttf"- },- "pdfProgram": {- "resource": "type3/library/fonts/dejavu/DejaVuSerifCondensed-Italic.ttf",- "format": "ttf"- },- "source": "DejaVu Fonts 2.37",- "signatures": [],- "glyphCoverage": []- },- {- "id": "dejavu-serif-condensed-bolditalic",- "label": "DejaVu Serif Condensed Bold Italic",- "aliases": [- "DejaVuSerifCondensed-BoldItalic"- ],- "program": {- "resource": "type3/library/fonts/dejavu/DejaVuSerifCondensed-BoldItalic.ttf",- "format": "ttf"- },- "webProgram": {- "resource": "type3/library/fonts/dejavu/DejaVuSerifCondensed-BoldItalic.ttf",- "format": "ttf"- },- "pdfProgram": {- "resource": "type3/library/fonts/dejavu/DejaVuSerifCondensed-BoldItalic.ttf",- "format": "ttf"- },- "source": "DejaVu Fonts 2.37",- "signatures": [],- "glyphCoverage": []- },- {- "id": "dejavu-sans-mono",- "label": "DejaVu Sans Mono",- "aliases": [- "DejaVuSansMono",- "dejavusansmono"- ],- "program": {- "resource": "type3/library/fonts/dejavu/DejaVuSansMono.ttf",- "format": "ttf"- },- "webProgram": {- "resource": "type3/library/fonts/dejavu/DejaVuSansMono.ttf",- "format": "ttf"- },- "pdfProgram": {- "resource": "type3/library/fonts/dejavu/DejaVuSansMono.ttf",- "format": "ttf"- },- "source": "DejaVu Fonts 2.37",- "signatures": [- "sha256:88758adf0b41a81204ed3ad63463f5d15c7c2f80e8942cee501d06fa7274dc4e",- "sha256:74e60bcb2d7975b0c7b372aca9fc25f55c9018005425a741830e7c4370b8d593"- ],- "glyphCoverage": [- 35,- 39,- 48,- 49,- 50,- 51,- 52,- 53,- 54,- 55,- 56,- 57,- 67,- 97,- 98,- 99,- 100,- 101,- 102,- 103,- 105,- 107,- 108,- 109,- 111,- 112,- 114,- 116,- 121- ]- },- {- "id": "dejavu-sans-mono-bold",- "label": "DejaVu Sans Mono Bold",- "aliases": [- "DejaVuSansMono-Bold"- ],- "program": {- "resource": "type3/library/fonts/dejavu/DejaVuSansMono-Bold.ttf",- "format": "ttf"- },- "webProgram": {- "resource": "type3/library/fonts/dejavu/DejaVuSansMono-Bold.ttf",- "format": "ttf"- },- "pdfProgram": {- "resource": "type3/library/fonts/dejavu/DejaVuSansMono-Bold.ttf",- "format": "ttf"- },- "source": "DejaVu Fonts 2.37",- "signatures": [],- "glyphCoverage": []- },- {- "id": "dejavu-sans-mono-oblique",- "label": "DejaVu Sans Mono Oblique",- "aliases": [- "DejaVuSansMono-Oblique"- ],- "program": {- "resource": "type3/library/fonts/dejavu/DejaVuSansMono-Oblique.ttf",- "format": "ttf"- },- "webProgram": {- "resource": "type3/library/fonts/dejavu/DejaVuSansMono-Oblique.ttf",- "format": "ttf"- },- "pdfProgram": {- "resource": "type3/library/fonts/dejavu/DejaVuSansMono-Oblique.ttf",- "format": "ttf"- },- "source": "DejaVu Fonts 2.37",- "signatures": [],- "glyphCoverage": []- },- {- "id": "dejavu-sans-mono-boldoblique",- "label": "DejaVu Sans Mono Bold Oblique",- "aliases": [- "DejaVuSansMono-BoldOblique"- ],- "program": {- "resource": "type3/library/fonts/dejavu/DejaVuSansMono-BoldOblique.ttf",- "format": "ttf"- },- "webProgram": {- "resource": "type3/library/fonts/dejavu/DejaVuSansMono-BoldOblique.ttf",- "format": "ttf"- },- "pdfProgram": {- "resource": "type3/library/fonts/dejavu/DejaVuSansMono-BoldOblique.ttf",- "format": "ttf"- },- "source": "DejaVu Fonts 2.37",- "signatures": [],- "glyphCoverage": []- },- {- "id": "liberation-sans-regular",- "label": "Liberation Sans",- "aliases": [- "LiberationSans",- "liberationsans"- ],- "program": {- "resource": "type3/library/fonts/liberation/LiberationSans-Regular.ttf",- "format": "ttf"- },- "webProgram": {- "resource": "type3/library/fonts/liberation/LiberationSans-Regular.ttf",- "format": "ttf"- },- "pdfProgram": {- "resource": "type3/library/fonts/liberation/LiberationSans-Regular.ttf",- "format": "ttf"- },- "source": "Liberation Fonts 2.1.5",- "signatures": [],- "glyphCoverage": []- },- {- "id": "liberation-sans-bold",- "label": "Liberation Sans Bold",- "aliases": [- "LiberationSans-Bold",- "liberationsans-bold"- ],- "program": {- "resource": "type3/library/fonts/liberation/LiberationSans-Bold.ttf",- "format": "ttf"- },- "webProgram": {- "resource": "type3/library/fonts/liberation/LiberationSans-Bold.ttf",- "format": "ttf"- },- "pdfProgram": {- "resource": "type3/library/fonts/liberation/LiberationSans-Bold.ttf",- "format": "ttf"- },- "source": "Liberation Fonts 2.1.5",- "signatures": [],- "glyphCoverage": []- },- {- "id": "liberation-sans-italic",- "label": "Liberation Sans Italic",- "aliases": [- "LiberationSans-Italic"- ],- "program": {- "resource": "type3/library/fonts/liberation/LiberationSans-Italic.ttf",- "format": "ttf"- },- "webProgram": {- "resource": "type3/library/fonts/liberation/LiberationSans-Italic.ttf",- "format": "ttf"- },- "pdfProgram": {- "resource": "type3/library/fonts/liberation/LiberationSans-Italic.ttf",- "format": "ttf"- },- "source": "Liberation Fonts 2.1.5",- "signatures": [],- "glyphCoverage": []- },- {- "id": "liberation-sans-bolditalic",- "label": "Liberation Sans Bold Italic",- "aliases": [- "LiberationSans-BoldItalic"- ],- "program": {- "resource": "type3/library/fonts/liberation/LiberationSans-BoldItalic.ttf",- "format": "ttf"- },- "webProgram": {- "resource": "type3/library/fonts/liberation/LiberationSans-BoldItalic.ttf",- "format": "ttf"- },- "pdfProgram": {- "resource": "type3/library/fonts/liberation/LiberationSans-BoldItalic.ttf",- "format": "ttf"- },- "source": "Liberation Fonts 2.1.5",- "signatures": [],- "glyphCoverage": []- },- {- "id": "liberation-serif-regular",- "label": "Liberation Serif",- "aliases": [- "LiberationSerif",- "liberationserif"- ],- "program": {- "resource": "type3/library/fonts/liberation/LiberationSerif-Regular.ttf",- "format": "ttf"- },- "webProgram": {- "resource": "type3/library/fonts/liberation/LiberationSerif-Regular.ttf",- "format": "ttf"- },- "pdfProgram": {- "resource": "type3/library/fonts/liberation/LiberationSerif-Regular.ttf",- "format": "ttf"- },- "source": "Liberation Fonts 2.1.5",- "signatures": [],- "glyphCoverage": []- },- {- "id": "liberation-serif-bold",- "label": "Liberation Serif Bold",- "aliases": [- "LiberationSerif-Bold",- "liberationserif-bold"- ],- "program": {- "resource": "type3/library/fonts/liberation/LiberationSerif-Bold.ttf",- "format": "ttf"- },- "webProgram": {- "resource": "type3/library/fonts/liberation/LiberationSerif-Bold.ttf",- "format": "ttf"- },- "pdfProgram": {- "resource": "type3/library/fonts/liberation/LiberationSerif-Bold.ttf",- "format": "ttf"- },- "source": "Liberation Fonts 2.1.5",- "signatures": [],- "glyphCoverage": []- },- {- "id": "liberation-serif-italic",- "label": "Liberation Serif Italic",- "aliases": [- "LiberationSerif-Italic"- ],- "program": {- "resource": "type3/library/fonts/liberation/LiberationSerif-Italic.ttf",- "format": "ttf"- },- "webProgram": {- "resource": "type3/library/fonts/liberation/LiberationSerif-Italic.ttf",- "format": "ttf"- },- "pdfProgram": {- "resource": "type3/library/fonts/liberation/LiberationSerif-Italic.ttf",- "format": "ttf"- },- "source": "Liberation Fonts 2.1.5",- "signatures": [],- "glyphCoverage": []- },- {- "id": "liberation-serif-bolditalic",- "label": "Liberation Serif Bold Italic",- "aliases": [- "LiberationSerif-BoldItalic"- ],- "program": {- "resource": "type3/library/fonts/liberation/LiberationSerif-BoldItalic.ttf",- "format": "ttf"- },- "webProgram": {- "resource": "type3/library/fonts/liberation/LiberationSerif-BoldItalic.ttf",- "format": "ttf"- },- "pdfProgram": {- "resource": "type3/library/fonts/liberation/LiberationSerif-BoldItalic.ttf",- "format": "ttf"- },- "source": "Liberation Fonts 2.1.5",- "signatures": [],- "glyphCoverage": []- },- {- "id": "liberation-mono-regular",- "label": "Liberation Mono",- "aliases": [- "LiberationMono",- "liberationmono"- ],- "program": {- "resource": "type3/library/fonts/liberation/LiberationMono-Regular.ttf",- "format": "ttf"- },- "webProgram": {- "resource": "type3/library/fonts/liberation/LiberationMono-Regular.ttf",- "format": "ttf"- },- "pdfProgram": {- "resource": "type3/library/fonts/liberation/LiberationMono-Regular.ttf",- "format": "ttf"- },- "source": "Liberation Fonts 2.1.5",- "signatures": [],- "glyphCoverage": []- },- {- "id": "liberation-mono-bold",- "label": "Liberation Mono Bold",- "aliases": [- "LiberationMono-Bold",- "liberationmono-bold"- ],- "program": {- "resource": "type3/library/fonts/liberation/LiberationMono-Bold.ttf",- "format": "ttf"- },- "webProgram": {- "resource": "type3/library/fonts/liberation/LiberationMono-Bold.ttf",- "format": "ttf"- },- "pdfProgram": {- "resource": "type3/library/fonts/liberation/LiberationMono-Bold.ttf",- "format": "ttf"- },- "source": "Liberation Fonts 2.1.5",- "signatures": [],- "glyphCoverage": []- },- {- "id": "liberation-mono-italic",- "label": "Liberation Mono Italic",- "aliases": [- "LiberationMono-Italic"- ],- "program": {- "resource": "type3/library/fonts/liberation/LiberationMono-Italic.ttf",- "format": "ttf"- },- "webProgram": {- "resource": "type3/library/fonts/liberation/LiberationMono-Italic.ttf",- "format": "ttf"- },- "pdfProgram": {- "resource": "type3/library/fonts/liberation/LiberationMono-Italic.ttf",- "format": "ttf"- },- "source": "Liberation Fonts 2.1.5",- "signatures": [],- "glyphCoverage": []- },- {- "id": "liberation-mono-bolditalic",- "label": "Liberation Mono Bold Italic",- "aliases": [- "LiberationMono-BoldItalic"- ],- "program": {- "resource": "type3/library/fonts/liberation/LiberationMono-BoldItalic.ttf",- "format": "ttf"- },- "webProgram": {- "resource": "type3/library/fonts/liberation/LiberationMono-BoldItalic.ttf",- "format": "ttf"- },- "pdfProgram": {- "resource": "type3/library/fonts/liberation/LiberationMono-BoldItalic.ttf",- "format": "ttf"- },- "source": "Liberation Fonts 2.1.5",- "signatures": [],- "glyphCoverage": []- },- {- "id": "cmr10",- "label": "Computer Modern Roman 10pt",- "aliases": [- "cmr10",- "Cmr10"- ],- "program": {- "resource": "type3/library/fonts/cm/cmr10.ttf",- "format": "ttf"- },- "webProgram": {- "resource": "type3/library/fonts/cm/cmr10.ttf",- "format": "ttf"- },- "pdfProgram": {- "resource": "type3/library/fonts/cm/cmr10.ttf",- "format": "ttf"- },- "source": "Computer Modern (LaTeX)",- "signatures": [- "sha256:5b535a05c982fb8ff029dfbedd5e9d28c1c4379ebac259d207f65606a94e5b15"- ],- "glyphCoverage": [- 48,- 49,- 53- ]- },- {- "id": "cmmi10",- "label": "Computer Modern Math Italic 10pt",- "aliases": [- "cmmi10",- "Cmmi10"- ],- "program": {- "resource": "type3/library/fonts/cm/cmmi10.ttf",- "format": "ttf"- },- "webProgram": {- "resource": "type3/library/fonts/cm/cmmi10.ttf",- "format": "ttf"- },- "pdfProgram": {- "resource": "type3/library/fonts/cm/cmmi10.ttf",- "format": "ttf"- },- "source": "Computer Modern (LaTeX)",- "signatures": [- "sha256:6c72170517812e39f970746f53a2ae08dafbbe7374c20bcb4d5a60adc49cb77b"- ],- "glyphCoverage": [- 100,- 120- ]- },- {- "id": "cmsy10",- "label": "Computer Modern Symbol 10pt",- "aliases": [- "cmsy10",- "Cmsy10"- ],- "program": {- "resource": "type3/library/fonts/cm/cmsy10.ttf",- "format": "ttf"- },- "webProgram": {- "resource": "type3/library/fonts/cm/cmsy10.ttf",- "format": "ttf"- },- "pdfProgram": {- "resource": "type3/library/fonts/cm/cmsy10.ttf",- "format": "ttf"- },- "source": "Computer Modern (LaTeX)",- "signatures": [- "sha256:1324cd8127143ef9023616b7911c570db3b1eb35758cdc9258ec16c0f4587775",- "sha256:2832e219b2db3bacf0d5a147d4b74ad5226fdf7562c395ef3fb12937633e037d"- ],- "glyphCoverage": [- 48,- 8734- ]- },- {- "id": "cmbx10",- "label": "Computer Modern Bold Extended 10pt",- "aliases": [- "cmbx10",- "Cmbx10"- ],- "program": {- "resource": "type3/library/fonts/cm/cmbx10.ttf",- "format": "ttf"- },- "webProgram": {- "resource": "type3/library/fonts/cm/cmbx10.ttf",- "format": "ttf"- },- "pdfProgram": {- "resource": "type3/library/fonts/cm/cmbx10.ttf",- "format": "ttf"- },- "source": "Computer Modern (LaTeX)",- "signatures": [],- "glyphCoverage": []- },- {- "id": "cmti10",- "label": "Computer Modern Text Italic 10pt",- "aliases": [- "cmti10",- "Cmti10"- ],- "program": {- "resource": "type3/library/fonts/cm/cmti10.ttf",- "format": "ttf"- },- "webProgram": {- "resource": "type3/library/fonts/cm/cmti10.ttf",- "format": "ttf"- },- "pdfProgram": {- "resource": "type3/library/fonts/cm/cmti10.ttf",- "format": "ttf"- },- "source": "Computer Modern (LaTeX)",- "signatures": [],- "glyphCoverage": []- },- {- "id": "cmtt10",- "label": "Computer Modern Typewriter 10pt",- "aliases": [- "cmtt10",- "Cmtt10"- ],- "program": {- "resource": "type3/library/fonts/cm/cmtt10.ttf",- "format": "ttf"- },- "webProgram": {- "resource": "type3/library/fonts/cm/cmtt10.ttf",- "format": "ttf"- },- "pdfProgram": {- "resource": "type3/library/fonts/cm/cmtt10.ttf",- "format": "ttf"- },- "source": "Computer Modern (LaTeX)",- "signatures": [],- "glyphCoverage": []- },- {- "id": "stix-size-three",- "label": "STIX Size Three Symbols",- "aliases": [- "STIXSizeThreeSym-Regular",- "stixsizethreesym-regular"- ],- "program": {- "resource": "type3/library/fonts/stix/STIXSizeThreeSym-Regular.otf",- "format": "otf"- },- "webProgram": {- "resource": "type3/library/fonts/stix/STIXSizeThreeSym-Regular.otf",- "format": "otf"- },- "pdfProgram": {- "resource": "type3/library/fonts/stix/STIXSizeThreeSym-Regular.otf",- "format": "otf"- },- "source": "STIX Fonts 2.0",- "signatures": [- "sha256:33d0ab9d9d72c1aed1edfc9b815dd6a2d618cbbe9084309c7f2de0f3df3073d7"- ],- "glyphCoverage": [- 91,- 93- ]- },- {- "id": "stix-two-text-regular",- "label": "STIX Two Text",- "aliases": [- "STIXTwoText-Regular",- "stixtwotext"- ],- "program": {- "resource": "type3/library/fonts/stix/STIXTwoText-Regular.otf",- "format": "otf"- },- "webProgram": {- "resource": "type3/library/fonts/stix/STIXTwoText-Regular.otf",- "format": "otf"- },- "pdfProgram": {- "resource": "type3/library/fonts/stix/STIXTwoText-Regular.otf",- "format": "otf"- },- "source": "STIX Fonts 2.0",- "signatures": [],- "glyphCoverage": []- },- {- "id": "stix-two-text-bold",- "label": "STIX Two Text Bold",- "aliases": [- "STIXTwoText-Bold",- "stixtwotext-bold"- ],- "program": {- "resource": "type3/library/fonts/stix/STIXTwoText-Bold.otf",- "format": "otf"- },- "webProgram": {- "resource": "type3/library/fonts/stix/STIXTwoText-Bold.otf",- "format": "otf"- },- "pdfProgram": {- "resource": "type3/library/fonts/stix/STIXTwoText-Bold.otf",- "format": "otf"- },- "source": "STIX Fonts 2.0",- "signatures": [],- "glyphCoverage": []- },- {- "id": "stix-two-text-italic",- "label": "STIX Two Text Italic",- "aliases": [- "STIXTwoText-Italic"- ],- "program": {- "resource": "type3/library/fonts/stix/STIXTwoText-Italic.otf",- "format": "otf"- },- "webProgram": {- "resource": "type3/library/fonts/stix/STIXTwoText-Italic.otf",- "format": "otf"- },- "pdfProgram": {- "resource": "type3/library/fonts/stix/STIXTwoText-Italic.otf",- "format": "otf"- },- "source": "STIX Fonts 2.0",- "signatures": [],- "glyphCoverage": []- },- {- "id": "stix-two-math",- "label": "STIX Two Math",- "aliases": [- "STIXTwoMath-Regular",- "stixtwomath"- ],- "program": {- "resource": "type3/library/fonts/stix/STIXTwoMath-Regular.otf",- "format": "otf"- },- "webProgram": {- "resource": "type3/library/fonts/stix/STIXTwoMath-Regular.otf",- "format": "otf"- },- "pdfProgram": {- "resource": "type3/library/fonts/stix/STIXTwoMath-Regular.otf",- "format": "otf"- },- "source": "STIX Fonts 2.0",- "signatures": [],- "glyphCoverage": []- },- {- "id": "noto-sans-thin",- "label": "Noto Sans Thin",- "aliases": [- "NotoSans-Thin"- ],- "program": {- "resource": "type3/library/fonts/noto/NotoSans-Thin.ttf",- "format": "ttf"- },- "webProgram": {- "resource": "type3/library/fonts/noto/NotoSans-Thin.ttf",- "format": "ttf"- },- "pdfProgram": {- "resource": "type3/library/fonts/noto/NotoSans-Thin.ttf",- "format": "ttf"- },- "source": "Noto Sans (Google Fonts)",- "signatures": [],- "glyphCoverage": []- },- {- "id": "noto-sans-extralight",- "label": "Noto Sans ExtraLight",- "aliases": [- "NotoSans-ExtraLight"- ],- "program": {- "resource": "type3/library/fonts/noto/NotoSans-ExtraLight.ttf",- "format": "ttf"- },- "webProgram": {- "resource": "type3/library/fonts/noto/NotoSans-ExtraLight.ttf",- "format": "ttf"- },- "pdfProgram": {- "resource": "type3/library/fonts/noto/NotoSans-ExtraLight.ttf",- "format": "ttf"- },- "source": "Noto Sans (Google Fonts)",- "signatures": [],- "glyphCoverage": []- },- {- "id": "noto-sans-light",- "label": "Noto Sans Light",- "aliases": [- "NotoSans-Light"- ],- "program": {- "resource": "type3/library/fonts/noto/NotoSans-Light.ttf",- "format": "ttf"- },- "webProgram": {- "resource": "type3/library/fonts/noto/NotoSans-Light.ttf",- "format": "ttf"- },- "pdfProgram": {- "resource": "type3/library/fonts/noto/NotoSans-Light.ttf",- "format": "ttf"- },- "source": "Noto Sans (Google Fonts)",- "signatures": [],- "glyphCoverage": []- },- {- "id": "noto-sans-regular",- "label": "Noto Sans",- "aliases": [- "NotoSans",- "NotoSans-Regular",- "notosans"- ],- "program": {- "resource": "type3/library/fonts/noto/NotoSans-Regular.ttf",- "format": "ttf"- },- "webProgram": {- "resource": "type3/library/fonts/noto/NotoSans-Regular.ttf",- "format": "ttf"- },- "pdfProgram": {- "resource": "type3/library/fonts/noto/NotoSans-Regular.ttf",- "format": "ttf"- },- "source": "Noto Sans (Google Fonts)",- "signatures": [],- "glyphCoverage": []- },- {- "id": "noto-sans-medium",- "label": "Noto Sans Medium",- "aliases": [- "NotoSans-Medium"- ],- "program": {- "resource": "type3/library/fonts/noto/NotoSans-Medium.ttf",- "format": "ttf"- },- "webProgram": {- "resource": "type3/library/fonts/noto/NotoSans-Medium.ttf",- "format": "ttf"- },- "pdfProgram": {- "resource": "type3/library/fonts/noto/NotoSans-Medium.ttf",- "format": "ttf"- },- "source": "Noto Sans (Google Fonts)",- "signatures": [],- "glyphCoverage": []- },- {- "id": "noto-sans-semibold",- "label": "Noto Sans SemiBold",- "aliases": [- "NotoSans-SemiBold"- ],- "program": {- "resource": "type3/library/fonts/noto/NotoSans-SemiBold.ttf",- "format": "ttf"- },- "webProgram": {- "resource": "type3/library/fonts/noto/NotoSans-SemiBold.ttf",- "format": "ttf"- },- "pdfProgram": {- "resource": "type3/library/fonts/noto/NotoSans-SemiBold.ttf",- "format": "ttf"- },- "source": "Noto Sans (Google Fonts)",- "signatures": [],- "glyphCoverage": []- },- {- "id": "noto-sans-bold",- "label": "Noto Sans Bold",- "aliases": [- "NotoSans-Bold",- "notosans-bold"- ],- "program": {- "resource": "type3/library/fonts/noto/NotoSans-Bold.ttf",- "format": "ttf"- },- "webProgram": {- "resource": "type3/library/fonts/noto/NotoSans-Bold.ttf",- "format": "ttf"- },- "pdfProgram": {- "resource": "type3/library/fonts/noto/NotoSans-Bold.ttf",- "format": "ttf"- },- "source": "Noto Sans (Google Fonts)",- "signatures": [],- "glyphCoverage": []- },- {- "id": "noto-sans-extrabold",- "label": "Noto Sans ExtraBold",- "aliases": [- "NotoSans-ExtraBold"- ],- "program": {- "resource": "type3/library/fonts/noto/NotoSans-ExtraBold.ttf",- "format": "ttf"- },- "webProgram": {- "resource": "type3/library/fonts/noto/NotoSans-ExtraBold.ttf",- "format": "ttf"- },- "pdfProgram": {- "resource": "type3/library/fonts/noto/NotoSans-ExtraBold.ttf",- "format": "ttf"- },- "source": "Noto Sans (Google Fonts)",- "signatures": [],- "glyphCoverage": []- },- {- "id": "noto-sans-black",- "label": "Noto Sans Black",- "aliases": [- "NotoSans-Black"- ],- "program": {- "resource": "type3/library/fonts/noto/NotoSans-Black.ttf",- "format": "ttf"- },- "webProgram": {- "resource": "type3/library/fonts/noto/NotoSans-Black.ttf",- "format": "ttf"- },- "pdfProgram": {- "resource": "type3/library/fonts/noto/NotoSans-Black.ttf",- "format": "ttf"- },- "source": "Noto Sans (Google Fonts)",- "signatures": [],- "glyphCoverage": []- },- {- "id": "noto-sans-thin-italic",- "label": "Noto Sans Thin Italic",- "aliases": [- "NotoSans-ThinItalic"- ],- "program": {- "resource": "type3/library/fonts/noto/NotoSans-ThinItalic.ttf",- "format": "ttf"- },- "webProgram": {- "resource": "type3/library/fonts/noto/NotoSans-ThinItalic.ttf",- "format": "ttf"- },- "pdfProgram": {- "resource": "type3/library/fonts/noto/NotoSans-ThinItalic.ttf",- "format": "ttf"- },- "source": "Noto Sans (Google Fonts)",- "signatures": [],- "glyphCoverage": []- },- {- "id": "noto-sans-extralight-italic",- "label": "Noto Sans ExtraLight Italic",- "aliases": [- "NotoSans-ExtraLightItalic"- ],- "program": {- "resource": "type3/library/fonts/noto/NotoSans-ExtraLightItalic.ttf",- "format": "ttf"- },- "webProgram": {- "resource": "type3/library/fonts/noto/NotoSans-ExtraLightItalic.ttf",- "format": "ttf"- },- "pdfProgram": {- "resource": "type3/library/fonts/noto/NotoSans-ExtraLightItalic.ttf",- "format": "ttf"- },- "source": "Noto Sans (Google Fonts)",- "signatures": [],- "glyphCoverage": []- },- {- "id": "noto-sans-light-italic",- "label": "Noto Sans Light Italic",- "aliases": [- "NotoSans-LightItalic"- ],- "program": {- "resource": "type3/library/fonts/noto/NotoSans-LightItalic.ttf",- "format": "ttf"- },- "webProgram": {- "resource": "type3/library/fonts/noto/NotoSans-LightItalic.ttf",- "format": "ttf"- },- "pdfProgram": {- "resource": "type3/library/fonts/noto/NotoSans-LightItalic.ttf",- "format": "ttf"- },- "source": "Noto Sans (Google Fonts)",- "signatures": [],- "glyphCoverage": []- },- {- "id": "noto-sans-italic",- "label": "Noto Sans Italic",- "aliases": [- "NotoSans-Italic"- ],- "program": {- "resource": "type3/library/fonts/noto/NotoSans-Italic.ttf",- "format": "ttf"- },- "webProgram": {- "resource": "type3/library/fonts/noto/NotoSans-Italic.ttf",- "format": "ttf"- },- "pdfProgram": {- "resource": "type3/library/fonts/noto/NotoSans-Italic.ttf",- "format": "ttf"- },- "source": "Noto Sans (Google Fonts)",- "signatures": [],- "glyphCoverage": []- },- {- "id": "noto-sans-medium-italic",- "label": "Noto Sans Medium Italic",- "aliases": [- "NotoSans-MediumItalic"- ],- "program": {- "resource": "type3/library/fonts/noto/NotoSans-MediumItalic.ttf",- "format": "ttf"- },- "webProgram": {- "resource": "type3/library/fonts/noto/NotoSans-MediumItalic.ttf",- "format": "ttf"- },- "pdfProgram": {- "resource": "type3/library/fonts/noto/NotoSans-MediumItalic.ttf",- "format": "ttf"- },- "source": "Noto Sans (Google Fonts)",- "signatures": [],- "glyphCoverage": []- },- {- "id": "noto-sans-semibold-italic",- "label": "Noto Sans SemiBold Italic",- "aliases": [- "NotoSans-SemiBoldItalic"- ],- "program": {- "resource": "type3/library/fonts/noto/NotoSans-SemiBoldItalic.ttf",- "format": "ttf"- },- "webProgram": {- "resource": "type3/library/fonts/noto/NotoSans-SemiBoldItalic.ttf",- "format": "ttf"- },- "pdfProgram": {- "resource": "type3/library/fonts/noto/NotoSans-SemiBoldItalic.ttf",- "format": "ttf"- },- "source": "Noto Sans (Google Fonts)",- "signatures": [],- "glyphCoverage": []- },- {- "id": "noto-sans-bold-italic",- "label": "Noto Sans Bold Italic",- "aliases": [- "NotoSans-BoldItalic"- ],- "program": {- "resource": "type3/library/fonts/noto/NotoSans-BoldItalic.ttf",- "format": "ttf"- },- "webProgram": {- "resource": "type3/library/fonts/noto/NotoSans-BoldItalic.ttf",- "format": "ttf"- },- "pdfProgram": {- "resource": "type3/library/fonts/noto/NotoSans-BoldItalic.ttf",- "format": "ttf"- },- "source": "Noto Sans (Google Fonts)",- "signatures": [],- "glyphCoverage": []- },- {- "id": "noto-sans-extrabold-italic",- "label": "Noto Sans ExtraBold Italic",- "aliases": [- "NotoSans-ExtraBoldItalic"- ],- "program": {- "resource": "type3/library/fonts/noto/NotoSans-ExtraBoldItalic.ttf",- "format": "ttf"- },- "webProgram": {- "resource": "type3/library/fonts/noto/NotoSans-ExtraBoldItalic.ttf",- "format": "ttf"- },- "pdfProgram": {- "resource": "type3/library/fonts/noto/NotoSans-ExtraBoldItalic.ttf",- "format": "ttf"- },- "source": "Noto Sans (Google Fonts)",- "signatures": [],- "glyphCoverage": []- },- {- "id": "noto-sans-black-italic",- "label": "Noto Sans Black Italic",- "aliases": [- "NotoSans-BlackItalic"- ],- "program": {- "resource": "type3/library/fonts/noto/NotoSans-BlackItalic.ttf",- "format": "ttf"- },- "webProgram": {- "resource": "type3/library/fonts/noto/NotoSans-BlackItalic.ttf",- "format": "ttf"- },- "pdfProgram": {- "resource": "type3/library/fonts/noto/NotoSans-BlackItalic.ttf",- "format": "ttf"- },- "source": "Noto Sans (Google Fonts)",- "signatures": [],- "glyphCoverage": []- },- {- "id": "sourcecodepro-regular",- "label": "Source Code Pro",- "aliases": [- "SourceCodePro-Regular",- "sourcecodepro-regular"- ],- "program": {- "resource": "type3/library/fonts/scp/SauceCodeProNerdFont-Regular.ttf",- "format": "ttf"- },- "webProgram": {- "resource": "type3/library/fonts/scp/SauceCodeProNerdFont-Regular.ttf",- "format": "ttf"- },- "pdfProgram": {- "resource": "type3/library/fonts/scp/SauceCodeProNerdFont-Regular.ttf",- "format": "ttf"- },- "source": "Sauce Code Pro Nerd Font",- "signatures": [- "sha256:96ba693001b2ab224ad5b5a7464cecd4d33e68f30fb23f78a8473dbb031ce246",- "sha256:72fca14e9e44fc41b0cdb1c6a088f0b07f882f9f04c51a0145f43cf8b285c5b6"- ],- "glyphCoverage": [- 46,- 48,- 49,- 50,- 51,- 52,- 53,- 54,- 55,- 56,- 57,- 67- ]- }-]\ No newline at end of filediff --git a/app/core/src/test/java/stirling/software/SPDF/config/ToolIODeclarationCoverageTest.java b/app/core/src/test/java/stirling/software/SPDF/config/ToolIODeclarationCoverageTest.javaindex f81c6cbca7..5cbdf3b8eb 100644--- a/app/core/src/test/java/stirling/software/SPDF/config/ToolIODeclarationCoverageTest.java+++ b/app/core/src/test/java/stirling/software/SPDF/config/ToolIODeclarationCoverageTest.java@@ -65,12 +65,6 @@ class ToolIODeclarationCoverageTest {*/private static final List<String> EXEMPT =List.of(- // Interactive editing sessions: page fragments and cache handles, not- // documents.- "/api/v1/convert/pdf/text-editor",- "/api/v1/convert/text-editor/pdf",- // Charcode lookup for the v2 editor: returns glyph mappings, not a document.- "/api/v1/general/pdf-text-editor",// Interactive credential helpers, hidden from pipeline discovery; restoration// requires the original protected document as well as the working result."/api/v1/security/restore-pdf-protection",diff --git a/app/core/src/test/java/stirling/software/SPDF/controller/api/EditTextControllerTest.java b/app/core/src/test/java/stirling/software/SPDF/controller/api/EditTextControllerTest.javadeleted file mode 100644index 007871fbaa..0000000000--- a/app/core/src/test/java/stirling/software/SPDF/controller/api/EditTextControllerTest.java+++ /dev/null@@ -1,664 +0,0 @@-package stirling.software.SPDF.controller.api;--import static org.junit.jupiter.api.Assertions.assertEquals;-import static org.junit.jupiter.api.Assertions.assertFalse;-import static org.junit.jupiter.api.Assertions.assertNotNull;-import static org.junit.jupiter.api.Assertions.assertNull;-import static org.junit.jupiter.api.Assertions.assertThrows;-import static org.junit.jupiter.api.Assertions.assertTrue;-import static org.mockito.ArgumentMatchers.any;-import static org.mockito.ArgumentMatchers.anyString;-import static org.mockito.Mockito.lenient;-import static org.mockito.Mockito.mock;-import static org.mockito.Mockito.when;--import java.io.ByteArrayOutputStream;-import java.io.File;-import java.io.OutputStream;-import java.nio.file.Files;-import java.util.ArrayList;-import java.util.List;--import org.apache.pdfbox.pdmodel.PDDocument;-import org.apache.pdfbox.pdmodel.PDPage;-import org.junit.jupiter.api.BeforeEach;-import org.junit.jupiter.api.Test;-import org.junit.jupiter.api.extension.ExtendWith;-import org.mockito.ArgumentCaptor;-import org.mockito.InjectMocks;-import org.mockito.Mock;-import org.mockito.junit.jupiter.MockitoExtension;-import org.springframework.core.io.Resource;-import org.springframework.http.HttpStatus;-import org.springframework.http.ResponseEntity;-import org.springframework.mock.web.MockMultipartFile;-import org.springframework.web.multipart.MultipartFile;--import stirling.software.SPDF.model.api.general.EditTextRequest;-import stirling.software.SPDF.model.json.PdfJsonDocument;-import stirling.software.SPDF.model.json.PdfJsonPage;-import stirling.software.SPDF.model.json.PdfJsonTextElement;-import stirling.software.SPDF.service.PdfJsonConversionService;-import stirling.software.common.model.api.general.EditTextOperation;-import stirling.software.common.util.TempFile;-import stirling.software.common.util.TempFileManager;--@ExtendWith(MockitoExtension.class)-class EditTextControllerTest {-- @Mock private PdfJsonConversionService pdfJsonConversionService;- @Mock private TempFileManager tempFileManager;-- @InjectMocks private EditTextController controller;-- @BeforeEach- void setUp() throws Exception {- lenient()- .when(tempFileManager.createManagedTempFile(anyString()))- .thenAnswer(- inv -> {- File f =- Files.createTempFile("test", inv.<String>getArgument(0))- .toFile();- TempFile tf = mock(TempFile.class);- lenient().when(tf.getFile()).thenReturn(f);- lenient().when(tf.getPath()).thenReturn(f.toPath());- return tf;- });- }-- private static MultipartFile pdfFile() {- return new MockMultipartFile(- "fileInput", "doc.pdf", "application/pdf", "stub-pdf-bytes".getBytes());- }-- private static EditTextOperation edit(String find, String replace) {- EditTextOperation op = new EditTextOperation();- op.setFind(find);- op.setReplace(replace);- return op;- }-- private static PdfJsonTextElement textElement(String text) {- PdfJsonTextElement el = new PdfJsonTextElement();- el.setText(text);- el.setCharCodes(new int[] {1, 2, 3});- return el;- }-- private static PdfJsonDocument documentWithElements(List<PdfJsonTextElement> elements) {- PdfJsonDocument doc = new PdfJsonDocument();- PdfJsonPage page = new PdfJsonPage();- page.setPageNumber(1);- page.setTextElements(new ArrayList<>(elements));- doc.setPages(new ArrayList<>(List.of(page)));- return doc;- }-- private static PdfJsonDocument documentWithText(String... textsByPage) {- PdfJsonDocument doc = new PdfJsonDocument();- List<PdfJsonPage> pages = new ArrayList<>();- for (int i = 0; i < textsByPage.length; i++) {- PdfJsonPage page = new PdfJsonPage();- page.setPageNumber(i + 1);- PdfJsonTextElement el = new PdfJsonTextElement();- el.setText(textsByPage[i]);- el.setCharCodes(new int[] {1, 2, 3});- page.setTextElements(new ArrayList<>(List.of(el)));- pages.add(page);- }- doc.setPages(pages);- return doc;- }-- /** Build a minimal real PDF so tests can run end-to-end without mocking the conversion. */- private static byte[] buildEmptyPdf() throws Exception {- try (PDDocument doc = new PDDocument();- ByteArrayOutputStream baos = new ByteArrayOutputStream()) {- doc.addPage(new PDPage());- doc.save(baos);- return baos.toByteArray();- }- }-- @Test- void editText_nullFileInputThrows() {- EditTextRequest request = new EditTextRequest();- request.setFileInput(null);- request.setEdits(List.of(edit("foo", "bar")));-- assertThrows(IllegalArgumentException.class, () -> controller.editText(request));- }-- @Test- void editText_emptyEditsThrows() {- EditTextRequest request = new EditTextRequest();- request.setFileInput(pdfFile());- request.setEdits(List.of());-- assertThrows(IllegalArgumentException.class, () -> controller.editText(request));- }-- @Test- void editText_nullEditsThrows() {- EditTextRequest request = new EditTextRequest();- request.setFileInput(pdfFile());- request.setEdits(null);-- assertThrows(IllegalArgumentException.class, () -> controller.editText(request));- }-- @Test- void editText_emptyFindStringThrows() {- EditTextRequest request = new EditTextRequest();- request.setFileInput(pdfFile());- request.setEdits(List.of(edit("", "replacement")));-- assertThrows(IllegalArgumentException.class, () -> controller.editText(request));- }-- @Test- void editText_findStringWithRegexMetacharsIsTreatedLiterally() throws Exception {- // Find strings are always treated as literals (Pattern.quote'd internally) — no ReDoS- // exposure from regex metacharacters supplied by the caller.- EditTextRequest request = new EditTextRequest();- request.setFileInput(pdfFile());- request.setEdits(List.of(edit("(unclosed", "fixed")));-- PdfJsonDocument input = documentWithText("text with (unclosed paren");- when(pdfJsonConversionService.convertPdfToJsonDocument(any(MultipartFile.class)))- .thenReturn(input);-- controller.editText(request);-- ArgumentCaptor<PdfJsonDocument> captor = ArgumentCaptor.forClass(PdfJsonDocument.class);- org.mockito.Mockito.verify(pdfJsonConversionService)- .convertJsonToPdf(captor.capture(), any(OutputStream.class));- assertEquals(- "text with fixed paren",- captor.getValue().getPages().get(0).getTextElements().get(0).getText());- }-- @Test- void editText_literalFindReplace_mutatesMatchingSpansAndClearsCharCodes() throws Exception {- EditTextRequest request = new EditTextRequest();- request.setFileInput(pdfFile());- request.setEdits(List.of(edit("foo", "bar")));-- PdfJsonDocument input = documentWithText("foo and foo", "no match here");- when(pdfJsonConversionService.convertPdfToJsonDocument(any(MultipartFile.class)))- .thenReturn(input);-- ResponseEntity<Resource> response = controller.editText(request);-- assertEquals(HttpStatus.OK, response.getStatusCode());- assertNotNull(response.getBody());-- ArgumentCaptor<PdfJsonDocument> captor = ArgumentCaptor.forClass(PdfJsonDocument.class);- org.mockito.Mockito.verify(pdfJsonConversionService)- .convertJsonToPdf(captor.capture(), any(OutputStream.class));- PdfJsonDocument mutated = captor.getValue();-- assertEquals("bar and bar", mutated.getPages().get(0).getTextElements().get(0).getText());- assertNull(mutated.getPages().get(0).getTextElements().get(0).getCharCodes());-- assertEquals("no match here", mutated.getPages().get(1).getTextElements().get(0).getText());- // Char codes preserved on unmodified spans.- assertNotNull(mutated.getPages().get(1).getTextElements().get(0).getCharCodes());- }-- @Test- void editText_wholeWordSearch_doesNotMatchInsideWords() throws Exception {- EditTextRequest request = new EditTextRequest();- request.setFileInput(pdfFile());- request.setEdits(List.of(edit("cat", "dog")));- request.setWholeWordSearch(true);-- PdfJsonDocument input = documentWithText("the cat is in the catalogue");- when(pdfJsonConversionService.convertPdfToJsonDocument(any(MultipartFile.class)))- .thenReturn(input);-- controller.editText(request);-- ArgumentCaptor<PdfJsonDocument> captor = ArgumentCaptor.forClass(PdfJsonDocument.class);- org.mockito.Mockito.verify(pdfJsonConversionService)- .convertJsonToPdf(captor.capture(), any(OutputStream.class));- assertEquals(- "the dog is in the catalogue",- captor.getValue().getPages().get(0).getTextElements().get(0).getText());- }-- @Test- void editText_wholeWordSearch_matchesFindStartingWithNonWordChar() throws Exception {- // Regression: \b only fires on a word/non-word transition. A find that starts with a- // non-word char (e.g. "-foo") preceded by another non-word char in the source (a space)- // would never match under \b. The lookaround-based bound handles this correctly.- EditTextRequest request = new EditTextRequest();- request.setFileInput(pdfFile());- request.setEdits(List.of(edit("-foo", "-bar")));- request.setWholeWordSearch(true);-- PdfJsonDocument input = documentWithText("space then -foo here");- when(pdfJsonConversionService.convertPdfToJsonDocument(any(MultipartFile.class)))- .thenReturn(input);-- controller.editText(request);-- ArgumentCaptor<PdfJsonDocument> captor = ArgumentCaptor.forClass(PdfJsonDocument.class);- org.mockito.Mockito.verify(pdfJsonConversionService)- .convertJsonToPdf(captor.capture(), any(OutputStream.class));- assertEquals(- "space then -bar here",- captor.getValue().getPages().get(0).getTextElements().get(0).getText());- }-- @Test- void editText_wholeWordSearch_doesNotMatchWhenAdjacentToWordChar() throws Exception {- // The lookaround bound must still reject matches that are part of a larger word.- EditTextRequest request = new EditTextRequest();- request.setFileInput(pdfFile());- request.setEdits(List.of(edit("-foo", "-bar")));- request.setWholeWordSearch(true);-- PdfJsonDocument input = documentWithText("inline-foo should not match");- when(pdfJsonConversionService.convertPdfToJsonDocument(any(MultipartFile.class)))- .thenReturn(input);-- controller.editText(request);-- ArgumentCaptor<PdfJsonDocument> captor = ArgumentCaptor.forClass(PdfJsonDocument.class);- org.mockito.Mockito.verify(pdfJsonConversionService)- .convertJsonToPdf(captor.capture(), any(OutputStream.class));- // "inline-foo" has 'e' (word) before '-foo' so the lookbehind blocks the match. The- // trailing 'o' is followed by a space (non-word) so the trailing lookahead would pass on- // its own; the leading lookbehind is what rejects it.- assertEquals(- "inline-foo should not match",- captor.getValue().getPages().get(0).getTextElements().get(0).getText());- }-- @Test- void editText_pageFilter_onlyAffectsListedPages() throws Exception {- EditTextRequest request = new EditTextRequest();- request.setFileInput(pdfFile());- request.setEdits(List.of(edit("foo", "bar")));- request.setPageNumbers("2");-- PdfJsonDocument input = documentWithText("foo on page 1", "foo on page 2", "foo on page 3");- when(pdfJsonConversionService.convertPdfToJsonDocument(any(MultipartFile.class)))- .thenReturn(input);-- controller.editText(request);-- ArgumentCaptor<PdfJsonDocument> captor = ArgumentCaptor.forClass(PdfJsonDocument.class);- org.mockito.Mockito.verify(pdfJsonConversionService)- .convertJsonToPdf(captor.capture(), any(OutputStream.class));- PdfJsonDocument mutated = captor.getValue();-- assertEquals("foo on page 1", mutated.getPages().get(0).getTextElements().get(0).getText());- assertEquals("bar on page 2", mutated.getPages().get(1).getTextElements().get(0).getText());- assertEquals("foo on page 3", mutated.getPages().get(2).getTextElements().get(0).getText());- }-- @Test- void editText_pageRange_appliesToAllPagesInRange() throws Exception {- EditTextRequest request = new EditTextRequest();- request.setFileInput(pdfFile());- request.setEdits(List.of(edit("foo", "bar")));- request.setPageNumbers("2-3");-- PdfJsonDocument input =- documentWithText("foo page 1", "foo page 2", "foo page 3", "foo page 4");- when(pdfJsonConversionService.convertPdfToJsonDocument(any(MultipartFile.class)))- .thenReturn(input);-- controller.editText(request);-- ArgumentCaptor<PdfJsonDocument> captor = ArgumentCaptor.forClass(PdfJsonDocument.class);- org.mockito.Mockito.verify(pdfJsonConversionService)- .convertJsonToPdf(captor.capture(), any(OutputStream.class));- PdfJsonDocument mutated = captor.getValue();-- assertTrue(mutated.getPages().get(0).getTextElements().get(0).getText().startsWith("foo"));- assertTrue(mutated.getPages().get(1).getTextElements().get(0).getText().startsWith("bar"));- assertTrue(mutated.getPages().get(2).getTextElements().get(0).getText().startsWith("bar"));- assertTrue(mutated.getPages().get(3).getTextElements().get(0).getText().startsWith("foo"));- }-- @Test- void editText_orderedEdits_applyInSequence() throws Exception {- EditTextRequest request = new EditTextRequest();- request.setFileInput(pdfFile());- request.setEdits(List.of(edit("foo", "bar"), edit("bar", "baz")));-- PdfJsonDocument input = documentWithText("foo");- when(pdfJsonConversionService.convertPdfToJsonDocument(any(MultipartFile.class)))- .thenReturn(input);-- controller.editText(request);-- ArgumentCaptor<PdfJsonDocument> captor = ArgumentCaptor.forClass(PdfJsonDocument.class);- org.mockito.Mockito.verify(pdfJsonConversionService)- .convertJsonToPdf(captor.capture(), any(OutputStream.class));- assertEquals("baz", captor.getValue().getPages().get(0).getTextElements().get(0).getText());- }-- @Test- void editText_replaceWithEmptyString_deletesMatch() throws Exception {- EditTextRequest request = new EditTextRequest();- request.setFileInput(pdfFile());- request.setEdits(List.of(edit("DRAFT ", "")));-- PdfJsonDocument input = documentWithText("DRAFT Confidential Memo");- when(pdfJsonConversionService.convertPdfToJsonDocument(any(MultipartFile.class)))- .thenReturn(input);-- controller.editText(request);-- ArgumentCaptor<PdfJsonDocument> captor = ArgumentCaptor.forClass(PdfJsonDocument.class);- org.mockito.Mockito.verify(pdfJsonConversionService)- .convertJsonToPdf(captor.capture(), any(OutputStream.class));- assertEquals(- "Confidential Memo",- captor.getValue().getPages().get(0).getTextElements().get(0).getText());- }-- @Test- void editText_noMatches_returnsPdfWithoutMutation() throws Exception {- EditTextRequest request = new EditTextRequest();- request.setFileInput(pdfFile());- request.setEdits(List.of(edit("notfound", "replacement")));-- PdfJsonDocument input = documentWithText("nothing to match");- int[] originalCodes = input.getPages().get(0).getTextElements().get(0).getCharCodes();- when(pdfJsonConversionService.convertPdfToJsonDocument(any(MultipartFile.class)))- .thenReturn(input);-- ResponseEntity<Resource> response = controller.editText(request);-- assertEquals(HttpStatus.OK, response.getStatusCode());- // Char codes left intact when nothing was replaced.- assertEquals(- originalCodes, input.getPages().get(0).getTextElements().get(0).getCharCodes());- assertEquals(- "nothing to match", input.getPages().get(0).getTextElements().get(0).getText());- }-- @Test- void editText_dollarInLiteralReplacement_isQuoted() throws Exception {- // Without quoting, '$1' would be interpreted as a backreference and crash.- EditTextRequest request = new EditTextRequest();- request.setFileInput(pdfFile());- request.setEdits(List.of(edit("price", "$100")));-- PdfJsonDocument input = documentWithText("the price is set");- when(pdfJsonConversionService.convertPdfToJsonDocument(any(MultipartFile.class)))- .thenReturn(input);-- controller.editText(request);-- ArgumentCaptor<PdfJsonDocument> captor = ArgumentCaptor.forClass(PdfJsonDocument.class);- org.mockito.Mockito.verify(pdfJsonConversionService)- .convertJsonToPdf(captor.capture(), any(OutputStream.class));- assertEquals(- "the $100 is set",- captor.getValue().getPages().get(0).getTextElements().get(0).getText());- }-- @Test- void editText_emptyDocument_returnsResponseWithoutErrors() throws Exception {- EditTextRequest request = new EditTextRequest();- request.setFileInput(pdfFile());- request.setEdits(List.of(edit("foo", "bar")));-- PdfJsonDocument input = new PdfJsonDocument();- input.setPages(new ArrayList<>());- when(pdfJsonConversionService.convertPdfToJsonDocument(any(MultipartFile.class)))- .thenReturn(input);-- ResponseEntity<Resource> response = controller.editText(request);-- assertEquals(HttpStatus.OK, response.getStatusCode());- assertNotNull(response.getBody());- }-- @Test- void editText_textElementWithNullText_isSkipped() throws Exception {- EditTextRequest request = new EditTextRequest();- request.setFileInput(pdfFile());- request.setEdits(List.of(edit("foo", "bar")));-- PdfJsonDocument input = new PdfJsonDocument();- PdfJsonPage page = new PdfJsonPage();- page.setPageNumber(1);- PdfJsonTextElement nullText = new PdfJsonTextElement();- nullText.setText(null);- PdfJsonTextElement realText = new PdfJsonTextElement();- realText.setText("foo here");- page.setTextElements(new ArrayList<>(List.of(nullText, realText)));- input.setPages(new ArrayList<>(List.of(page)));- when(pdfJsonConversionService.convertPdfToJsonDocument(any(MultipartFile.class)))- .thenReturn(input);-- controller.editText(request);-- ArgumentCaptor<PdfJsonDocument> captor = ArgumentCaptor.forClass(PdfJsonDocument.class);- org.mockito.Mockito.verify(pdfJsonConversionService)- .convertJsonToPdf(captor.capture(), any(OutputStream.class));- PdfJsonDocument mutated = captor.getValue();- assertNull(mutated.getPages().get(0).getTextElements().get(0).getText());- assertEquals("bar here", mutated.getPages().get(0).getTextElements().get(1).getText());- }-- @Test- void editText_crossElement_matchSpansTwoElements() throws Exception {- EditTextRequest request = new EditTextRequest();- request.setFileInput(pdfFile());- request.setEdits(List.of(edit("Hello World", "Goodbye Earth")));-- PdfJsonDocument input =- documentWithElements(List.of(textElement("Hello "), textElement("World")));- when(pdfJsonConversionService.convertPdfToJsonDocument(any(MultipartFile.class)))- .thenReturn(input);-- controller.editText(request);-- ArgumentCaptor<PdfJsonDocument> captor = ArgumentCaptor.forClass(PdfJsonDocument.class);- org.mockito.Mockito.verify(pdfJsonConversionService)- .convertJsonToPdf(captor.capture(), any(OutputStream.class));- List<PdfJsonTextElement> elements = captor.getValue().getPages().get(0).getTextElements();-- // Whole replacement lands in the first matched element; the second is emptied. The- // JSON->PDF rebuild concatenates per-token text so the font lays out the replacement as- // one run anchored at the first element's X position.- assertEquals("Goodbye Earth", elements.get(0).getText());- assertEquals("", elements.get(1).getText());- assertNull(elements.get(0).getCharCodes());- assertNull(elements.get(1).getCharCodes());- }-- @Test- void editText_crossElement_matchSpansFiveElementsLikeFragmentedTitle() throws Exception {- // Reproduces the real-world case: a multi-word title fragmented one word per text span.- EditTextRequest request = new EditTextRequest();- request.setFileInput(pdfFile());- request.setEdits(- List.of(edit("The Free Adobe Acrobat Alternative", "The PDF automation pipeline")));-- PdfJsonDocument input =- documentWithElements(- List.of(- textElement("The "),- textElement("Free "),- textElement("Adobe "),- textElement("Acrobat "),- textElement("Alternative")));- when(pdfJsonConversionService.convertPdfToJsonDocument(any(MultipartFile.class)))- .thenReturn(input);-- controller.editText(request);-- ArgumentCaptor<PdfJsonDocument> captor = ArgumentCaptor.forClass(PdfJsonDocument.class);- org.mockito.Mockito.verify(pdfJsonConversionService)- .convertJsonToPdf(captor.capture(), any(OutputStream.class));- List<PdfJsonTextElement> elements = captor.getValue().getPages().get(0).getTextElements();-- // Whole replacement is written into the first matched element; the remaining four are- // emptied. Centered titles will become left-aligned at the original first-word X position.- assertEquals("The PDF automation pipeline", elements.get(0).getText());- for (int i = 1; i < elements.size(); i++) {- assertEquals("", elements.get(i).getText(), "element " + i + " should be empty");- }- }-- @Test- void editText_crossElement_preservesPrefixAndSuffix() throws Exception {- EditTextRequest request = new EditTextRequest();- request.setFileInput(pdfFile());- request.setEdits(List.of(edit("Hello World", "Goodbye Earth")));-- PdfJsonDocument input =- documentWithElements(- List.of(textElement("Greeting: Hello "), textElement("World! And more")));- when(pdfJsonConversionService.convertPdfToJsonDocument(any(MultipartFile.class)))- .thenReturn(input);-- controller.editText(request);-- ArgumentCaptor<PdfJsonDocument> captor = ArgumentCaptor.forClass(PdfJsonDocument.class);- org.mockito.Mockito.verify(pdfJsonConversionService)- .convertJsonToPdf(captor.capture(), any(OutputStream.class));- List<PdfJsonTextElement> elements = captor.getValue().getPages().get(0).getTextElements();-- // First element keeps its prefix and gets the entire replacement; last element keeps its- // suffix only.- assertEquals("Greeting: Goodbye Earth", elements.get(0).getText());- assertEquals("! And more", elements.get(1).getText());- }-- @Test- void editText_matchInOneElementOfMany_onlyTouchesThatElement() throws Exception {- EditTextRequest request = new EditTextRequest();- request.setFileInput(pdfFile());- request.setEdits(List.of(edit("World", "Earth")));-- PdfJsonDocument input =- documentWithElements(- List.of(- textElement("Hello "),- textElement("World!"),- textElement(" Goodbye")));- when(pdfJsonConversionService.convertPdfToJsonDocument(any(MultipartFile.class)))- .thenReturn(input);-- controller.editText(request);-- ArgumentCaptor<PdfJsonDocument> captor = ArgumentCaptor.forClass(PdfJsonDocument.class);- org.mockito.Mockito.verify(pdfJsonConversionService)- .convertJsonToPdf(captor.capture(), any(OutputStream.class));- List<PdfJsonTextElement> elements = captor.getValue().getPages().get(0).getTextElements();-- assertEquals("Hello ", elements.get(0).getText());- assertEquals("Earth!", elements.get(1).getText());- assertEquals(" Goodbye", elements.get(2).getText());- // Only the modified element's char codes get cleared.- assertNotNull(elements.get(0).getCharCodes());- assertNull(elements.get(1).getCharCodes());- assertNotNull(elements.get(2).getCharCodes());- }-- @Test- void editText_crossElement_multipleMatchesAppliedRightToLeft() throws Exception {- // Two matches in the same page text. Right-to-left application keeps earlier indices- // valid as later matches are written.- EditTextRequest request = new EditTextRequest();- request.setFileInput(pdfFile());- request.setEdits(List.of(edit("foo bar", "X")));-- PdfJsonDocument input =- documentWithElements(- List.of(- textElement("foo "),- textElement("bar baz "),- textElement("foo "),- textElement("bar")));- when(pdfJsonConversionService.convertPdfToJsonDocument(any(MultipartFile.class)))- .thenReturn(input);-- controller.editText(request);-- ArgumentCaptor<PdfJsonDocument> captor = ArgumentCaptor.forClass(PdfJsonDocument.class);- org.mockito.Mockito.verify(pdfJsonConversionService)- .convertJsonToPdf(captor.capture(), any(OutputStream.class));- List<PdfJsonTextElement> elements = captor.getValue().getPages().get(0).getTextElements();-- // Joined was "foo bar baz foo bar"; both "foo bar" runs replaced with "X".- StringBuilder joined = new StringBuilder();- for (PdfJsonTextElement el : elements) {- joined.append(el.getText() == null ? "" : el.getText());- }- assertEquals("X baz X", joined.toString());- }-- @Test- void editText_subWordFragmentation_writesIntoFirstElement() throws Exception {- // When the matched text is split into many character-level spans (typical of Type3 glyph- // runs), the whole replacement is dumped into the first matched element and the rest are- // emptied. The font lays out the replacement as one run at the first glyph's X position.- EditTextRequest request = new EditTextRequest();- request.setFileInput(pdfFile());- request.setEdits(List.of(edit("Hello World", "Goodbye Earth")));-- // 11 sub-word elements covering "Hello World".- PdfJsonDocument input =- documentWithElements(- List.of(- textElement("H"),- textElement("e"),- textElement("l"),- textElement("l"),- textElement("o"),- textElement(" "),- textElement("W"),- textElement("o"),- textElement("r"),- textElement("l"),- textElement("d")));- when(pdfJsonConversionService.convertPdfToJsonDocument(any(MultipartFile.class)))- .thenReturn(input);-- controller.editText(request);-- ArgumentCaptor<PdfJsonDocument> captor = ArgumentCaptor.forClass(PdfJsonDocument.class);- org.mockito.Mockito.verify(pdfJsonConversionService)- .convertJsonToPdf(captor.capture(), any(OutputStream.class));- List<PdfJsonTextElement> elements = captor.getValue().getPages().get(0).getTextElements();-- // Entire replacement goes into the first matched element; the other 10 are emptied.- assertEquals("Goodbye Earth", elements.get(0).getText());- for (int i = 1; i < elements.size(); i++) {- assertEquals("", elements.get(i).getText(), "element " + i + " should be empty");- }- }-- @Test- void editText_outputFilenameDerivedFromInput() throws Exception {- EditTextRequest request = new EditTextRequest();- request.setFileInput(- new MockMultipartFile(- "fileInput", "report.pdf", "application/pdf", buildEmptyPdf()));- request.setEdits(List.of(edit("anything", "x")));-- PdfJsonDocument input = documentWithText("nothing matches");- when(pdfJsonConversionService.convertPdfToJsonDocument(any(MultipartFile.class)))- .thenReturn(input);-- ResponseEntity<Resource> response = controller.editText(request);- String contentDisposition =- response.getHeaders()- .getFirst(org.springframework.http.HttpHeaders.CONTENT_DISPOSITION);- assertNotNull(contentDisposition);- assertTrue(contentDisposition.contains("report_edited.pdf"));- assertFalse(contentDisposition.contains(".pdf_edited.pdf"));- }-}diff --git a/app/core/src/test/java/stirling/software/SPDF/controller/api/PdfBoxFontEncodingProbeTest.java b/app/core/src/test/java/stirling/software/SPDF/controller/api/PdfBoxFontEncodingProbeTest.javadeleted file mode 100644index e283d76e28..0000000000--- a/app/core/src/test/java/stirling/software/SPDF/controller/api/PdfBoxFontEncodingProbeTest.java+++ /dev/null@@ -1,515 +0,0 @@-package stirling.software.SPDF.controller.api;--import java.io.ByteArrayOutputStream;-import java.io.IOException;-import java.io.InputStream;-import java.nio.file.Files;-import java.nio.file.Path;-import java.nio.file.Paths;-import java.util.ArrayList;-import java.util.HashSet;-import java.util.List;-import java.util.Set;--import javax.imageio.ImageIO;--import org.apache.pdfbox.Loader;-import org.apache.pdfbox.cos.COSName;-import org.apache.pdfbox.pdmodel.PDDocument;-import org.apache.pdfbox.pdmodel.PDPage;-import org.apache.pdfbox.pdmodel.PDPageContentStream;-import org.apache.pdfbox.pdmodel.PDResources;-import org.apache.pdfbox.pdmodel.font.PDFont;-import org.apache.pdfbox.pdmodel.font.PDFontDescriptor;-import org.apache.pdfbox.pdmodel.font.PDType0Font;-import org.apache.pdfbox.pdmodel.font.PDType1Font;-import org.apache.pdfbox.pdmodel.font.PDType3Font;-import org.apache.pdfbox.pdmodel.font.Standard14Fonts;-import org.apache.pdfbox.rendering.PDFRenderer;-import org.junit.jupiter.api.Disabled;-import org.junit.jupiter.api.Test;--/**- * Probe: what can PDFBox actually do for font ENCODING on real-world PDFs. This is a diagnostic- * test (not a regression) - run with --tests PdfBoxFontEncodingProbeTest -i to see stdout.- *- * <p>Answers these questions:- *- * <ol>- * <li>Type0/CIDFontType2 subset: can we add a new glyph not in the original subset? (no, encode- * throws IllegalArgumentException).- * <li>Type1: same question.- * <li>TrueType: same question.- * <li>Can we load a fresh TTF via PDType0Font.load(doc, file) and write text with it? (yes,- * primary path).- * <li>Round-trip via getFontStream / re-embed - can it rehabilitate Type3? (no - Type3 has no- * FontFile* program at all).- * <li>What fonts ship with PDFBox / fontbox? (only LiberationSans-Regular.ttf + AFM for the 14- * standard fonts; CFF/Type1 binaries are NOT bundled - Standard14Fonts.getMappedFontName- * redirects unmappable ones to LiberationSans).- * </ol>- */-@Disabled(- "Diagnostic probe: dumps PDFBox font encoding tables to stdout and asserts nothing. Kept for font debugging; run manually.")-public class PdfBoxFontEncodingProbeTest {-- private static final Path PROJECT_ROOT =- Paths.get(System.getProperty("user.dir")).getParent().getParent();-- private static final Path SAMPLE = PROJECT_ROOT.resolve("frontend/public/samples/Sample.pdf");-- private static final Path[] EXTRA_FIXTURES = {- PROJECT_ROOT.resolve("frontend/src/editor/core/tests/test-fixtures/stirling-marketing.pdf"),- PROJECT_ROOT.resolve("frontend/src/editor/core/tests/test-fixtures/multi-page-sample.pdf"),- PROJECT_ROOT.resolve("frontend/src/editor/core/tests/test-fixtures/big-sample.pdf"),- PROJECT_ROOT.resolve("frontend/src/editor/core/tests/test-fixtures/paragraph-sample.pdf"),- PROJECT_ROOT.resolve("frontend/src/editor/core/tests/test-fixtures/user-sample.pdf"),- };-- /**- * Rasterize the Q4b output (Sample.pdf with injected Liberation text) to confirm the new text- * actually renders on top of the existing Type3 content.- */- @Test- public void probeRenderInjectedSample() throws IOException {- Path liberation =- PROJECT_ROOT.resolve(- "app/core/src/main/resources/static/fonts/LiberationSans-Regular.ttf");- byte[] pdfBytes = Files.readAllBytes(SAMPLE);- ByteArrayOutputStream out = new ByteArrayOutputStream();- try (PDDocument doc = Loader.loadPDF(pdfBytes)) {- PDPage page = doc.getPage(0);- PDType0Font ttf;- try (InputStream in = Files.newInputStream(liberation)) {- ttf = PDType0Font.load(doc, in, true);- }- try (PDPageContentStream cs =- new PDPageContentStream(- doc, page, PDPageContentStream.AppendMode.APPEND, true, true)) {- cs.beginText();- cs.setFont(ttf, 24);- cs.newLineAtOffset(50, 120);- cs.showText("INJECTED via PDType0Font.load - $@#&Z");- cs.endText();- }- doc.save(out);- }- // Rasterize page 0 to a PNG so we can eyeball it.- try (PDDocument check = Loader.loadPDF(out.toByteArray())) {- PDFRenderer renderer = new PDFRenderer(check);- java.awt.image.BufferedImage img = renderer.renderImageWithDPI(0, 100);- // Build dir, not the repo root: this render is a debugging aid and was- // twice committed by accident when it landed in the working tree.- Path png =- Paths.get(System.getProperty("user.dir"), "build", "probe-output")- .resolve("pdfbox-probe-q4b-rendered.png");- Files.createDirectories(png.getParent());- ImageIO.write(img, "PNG", png.toFile());- System.out.println(- "Rendered injected sample to "- + png- + " - "- + img.getWidth()- + "x"- + img.getHeight());- }- }-- /**- * Build a PDF in memory that uses a Type0/CIDFontType2 subset font (the kind Word / InDesign /- * LibreOffice produce), then probe whether encode() can add a glyph that wasn't in the original- * subset.- */- @Test- public void probeType0CIDFontType2Subset() throws IOException {- System.out.println(- "\n##################################################################\n"- + "Q1 probe: Type0/CIDFontType2 SUBSET can/cannot add new glyphs\n"- + "##################################################################\n");- Path liberation =- PROJECT_ROOT.resolve(- "app/core/src/main/resources/static/fonts/LiberationSans-Regular.ttf");-- // Build a PDF that contains only "abc" subsetted from LiberationSans.- ByteArrayOutputStream baos = new ByteArrayOutputStream();- try (PDDocument doc = new PDDocument()) {- PDPage page = new PDPage();- doc.addPage(page);- PDType0Font subset;- try (InputStream in = Files.newInputStream(liberation)) {- subset = PDType0Font.load(doc, in, true /* embedSubset */);- }- try (PDPageContentStream cs = new PDPageContentStream(doc, page)) {- cs.beginText();- cs.setFont(subset, 12);- cs.newLineAtOffset(100, 700);- cs.showText("abc");- cs.endText();- }- doc.save(baos);- }-- // Reload the produced PDF and try to add a NEW glyph through the embedded subset font.- byte[] subsetPdf = baos.toByteArray();- try (PDDocument doc = Loader.loadPDF(subsetPdf)) {- PDResources res = doc.getPage(0).getResources();- for (COSName fn : res.getFontNames()) {- PDFont f = res.getFont(fn);- System.out.println(- " Subset font in saved PDF: "- + f.getName()- + " ("- + f.getClass().getSimpleName()- + ", subType="- + f.getSubType()- + ")");- for (String ch : new String[] {"a", "b", "c", "Z", "z", "0", "$", "@", "X", " "}) {- try {- byte[] enc = f.encode(ch);- StringBuilder hex = new StringBuilder();- for (byte b : enc) hex.append(String.format("%02X ", b & 0xff));- System.out.println(- " encode('" + ch + "') -> [" + hex.toString().trim() + "] OK");- } catch (UnsupportedOperationException uoe) {- System.out.println(" encode('" + ch + "') UNSUPPORTED");- } catch (IllegalArgumentException iae) {- System.out.println(- " encode('" + ch + "') MISSING - " + iae.getMessage());- } catch (IOException ioe) {- System.out.println(" encode('" + ch + "') IO ERR - " + ioe.getMessage());- }- }- }- }- }-- @Test- public void probeExtraFixtures() throws IOException {- System.out.println(- "\n##################################################################\n"- + "Extra fixture font-class probe\n"- + "##################################################################\n");- for (Path fixture : EXTRA_FIXTURES) {- if (!Files.exists(fixture)) {- System.out.println("(missing) " + fixture);- continue;- }- System.out.println("\n=== " + fixture.getFileName() + " ===");- byte[] bytes = Files.readAllBytes(fixture);- try (PDDocument doc = Loader.loadPDF(bytes)) {- Set<COSName> seen = new HashSet<>();- for (int p = 0; p < doc.getNumberOfPages(); p++) {- PDPage page = doc.getPage(p);- PDResources res = page.getResources();- if (res == null) continue;- for (COSName name : res.getFontNames()) {- if (!seen.add(name)) continue;- try {- PDFont f = res.getFont(name);- if (f == null) continue;- String fontFile = "none";- PDFontDescriptor d = f.getFontDescriptor();- if (d != null) {- if (d.getFontFile() != null) fontFile = "FontFile";- else if (d.getFontFile2() != null) fontFile = "FontFile2";- else if (d.getFontFile3() != null) fontFile = "FontFile3";- }- String z = "?";- try {- f.encode("Z");- z = "OK";- } catch (UnsupportedOperationException ex) {- z = "UNSUPPORTED";- } catch (IllegalArgumentException ex) {- z = "MISSING";- } catch (IOException ex) {- z = "IO_ERR";- }- System.out.println(- " page "- + p- + " "- + name.getName()- + " -> "- + f.getName()- + " "- + f.getClass().getSimpleName()- + " ("- + f.getSubType()- + ", "- + fontFile- + ", embed="- + f.isEmbedded()- + ") encode('Z')="- + z);- } catch (IOException e) {- System.out.println(- " page "- + p- + " "- + name.getName()- + " load failed: "- + e.getMessage());- }- }- }- }- }- }-- @Test- public void probeAllQuestions() throws IOException {- System.out.println(- "\n##################################################################\n"- + "PDFBox font-encoding probe (Sample.pdf + bundled fallback fonts)\n"- + "##################################################################\n");-- // Discover every font in Sample.pdf so we have a real-world test set.- byte[] pdfBytes = Files.readAllBytes(SAMPLE);- try (PDDocument doc = Loader.loadPDF(pdfBytes)) {- List<PDFont> allFonts = new ArrayList<>();- Set<COSName> seen = new HashSet<>();- for (int p = 0; p < doc.getNumberOfPages(); p++) {- PDPage page = doc.getPage(p);- PDResources res = page.getResources();- if (res == null) continue;- for (COSName name : res.getFontNames()) {- if (!seen.add(name)) continue;- try {- PDFont f = res.getFont(name);- if (f != null) allFonts.add(f);- } catch (Exception e) {- System.out.println(- " (skipped " + name.getName() + " - " + e.getMessage() + ")");- }- }- }- System.out.println(- "Discovered " + allFonts.size() + " unique fonts across Sample.pdf:");- for (PDFont f : allFonts) {- System.out.println(- " - "- + f.getName()- + " ("- + f.getClass().getSimpleName()- + ", subType="- + f.getSubType()- + ", embedded="- + f.isEmbedded()- + ")");- }-- // Q1/Q2/Q3- // Try encoding a char that is NEVER in Sample.pdf via each font.- // 'Z' is unlikely to be in the subset for most marketing pages.- // Try several candidates to surface what each font can/can't add.- String[] candidates = {"Z", "$", "@", "#", "Q", "&", "A", "0", "M"};- for (PDFont f : allFonts) {- System.out.println("\n=== Encode-probe for font: " + f.getName() + " ===");- for (String ch : candidates) {- try {- byte[] enc = f.encode(ch);- StringBuilder hex = new StringBuilder();- for (byte b : enc) hex.append(String.format("%02X ", b & 0xff));- System.out.println(- " encode('" + ch + "') -> [" + hex.toString().trim() + "] OK");- } catch (UnsupportedOperationException uoe) {- System.out.println(- " encode('" + ch + "') UNSUPPORTED: " + uoe.getMessage());- } catch (IllegalArgumentException iae) {- System.out.println(" encode('" + ch + "') MISSING: " + iae.getMessage());- } catch (IOException ioe) {- System.out.println(" encode('" + ch + "') IO ERR: " + ioe.getMessage());- }- }- }-- // Q5- // For each font, see what's in the FontFile* stream - this is what we'd- // have to round-trip through to "rehabilitate" a Type3 font.- System.out.println("\n=== FontFile stream availability (Q5) ===");- for (PDFont f : allFonts) {- String kind = "none";- int size = 0;- PDFontDescriptor d = f.getFontDescriptor();- if (d != null) {- if (d.getFontFile() != null) {- kind = "FontFile (Type1)";- size = streamBytes(d.getFontFile().getCOSObject().createInputStream());- } else if (d.getFontFile2() != null) {- kind = "FontFile2 (TTF)";- size = streamBytes(d.getFontFile2().getCOSObject().createInputStream());- } else if (d.getFontFile3() != null) {- kind = "FontFile3 (CFF/OpenType)";- size = streamBytes(d.getFontFile3().getCOSObject().createInputStream());- }- }- System.out.println(- " "- + f.getName()- + " ("- + f.getClass().getSimpleName()- + "): "- + kind- + " ("- + size- + " bytes)");- if (f instanceof PDType3Font) {- System.out.println(- " -> Type3 has CharProc streams, NOT a FontFile binary."- + " getFontStream() returns null. Round-trip rehab is impossible:");- System.out.println(- " each glyph is a mini content stream, not a glyph outline in a"- + " standard font format. We'd need to rasterize each CharProc to"- + " glyph outlines + build a fresh TTF/CFF from scratch.");- }- }- }-- // Q4: PDType0Font.load(doc, file) round-trip- System.out.println("\n=== Q4: load fresh TTF and write text to a fresh PDF ===");- Path liberation =- PROJECT_ROOT.resolve(- "app/core/src/main/resources/static/fonts/LiberationSans-Regular.ttf");- if (!Files.exists(liberation)) {- System.out.println(" Liberation TTF not found at " + liberation);- } else {- try (PDDocument out = new PDDocument()) {- PDPage page = new PDPage();- out.addPage(page);- PDType0Font ttf;- try (InputStream in = Files.newInputStream(liberation)) {- ttf = PDType0Font.load(out, in, true /* embedSubset */);- }- System.out.println(- " Loaded TTF -> "- + ttf.getName()- + " ("- + ttf.getClass().getSimpleName()- + ")");- String testText = "Hello world! 0123 Z $ @";- byte[] encoded = ttf.encode(testText);- System.out.println(- " Encoded "- + testText.length()- + " chars -> "- + encoded.length- + " bytes (Identity-H = 2 bytes/glyph)");- try (PDPageContentStream cs = new PDPageContentStream(out, page)) {- cs.beginText();- cs.setFont(ttf, 12);- cs.newLineAtOffset(100, 700);- cs.showText(testText);- cs.endText();- }- ByteArrayOutputStream baos = new ByteArrayOutputStream();- out.save(baos);- Path tmp = Files.createTempFile("pdfbox-probe-q4-", ".pdf");- Files.write(tmp, baos.toByteArray());- System.out.println(- " Wrote fresh-TTF PDF to "- + tmp- + " ("- + baos.size()- + " bytes) - opens cleanly.");-- // Re-load to confirm the new font is embedded properly.- try (PDDocument check = Loader.loadPDF(baos.toByteArray())) {- PDResources res = check.getPage(0).getResources();- for (COSName fn : res.getFontNames()) {- PDFont f = res.getFont(fn);- System.out.println(- " embedded font: "- + f.getName()- + " ("- + f.getClass().getSimpleName()- + ", embedded="- + f.isEmbedded()- + ")");- }- }- }- }-- // Q4b: load TTF into an EXISTING PDF (Sample.pdf) and append text- System.out.println(- "\n=== Q4b: load TTF into EXISTING Sample.pdf and write text on page 0 ===");- try (PDDocument doc = Loader.loadPDF(pdfBytes)) {- PDPage page = doc.getPage(0);- PDType0Font ttf;- try (InputStream in = Files.newInputStream(liberation)) {- ttf = PDType0Font.load(doc, in, true);- }- // append-mode content stream so we don't disturb existing graphics- try (PDPageContentStream cs =- new PDPageContentStream(- doc,- page,- PDPageContentStream.AppendMode.APPEND,- true /* compress */,- true /* resetContext */)) {- cs.beginText();- cs.setFont(ttf, 12);- cs.newLineAtOffset(50, 50);- cs.showText("Injected via PDType0Font.load - $@#&");- cs.endText();- }- ByteArrayOutputStream baos = new ByteArrayOutputStream();- doc.save(baos);- Path tmp = Files.createTempFile("pdfbox-probe-q4b-", ".pdf");- Files.write(tmp, baos.toByteArray());- System.out.println(- " Wrote injected-text PDF to " + tmp + " (" + baos.size() + " bytes).");-- // Verify by re-reading: how many fonts now on page 0?- try (PDDocument check = Loader.loadPDF(baos.toByteArray())) {- PDResources res = check.getPage(0).getResources();- int count = 0;- for (COSName fn : res.getFontNames()) {- PDFont f = res.getFont(fn);- count++;- System.out.println(- " page-0 font: "- + fn.getName()- + " -> "- + f.getName()- + " ("- + f.getClass().getSimpleName()- + ")");- }- System.out.println(" Total fonts on page 0: " + count);- }- }-- // Q6: what fonts ship in PDFBox / fontbox- System.out.println("\n=== Q6: bundled fonts (Standard14 redirect probe) ===");- for (Standard14Fonts.FontName fn : Standard14Fonts.FontName.values()) {- PDType1Font f = new PDType1Font(fn);- String mapped = "" + Standard14Fonts.getMappedFontName(fn.getName());- System.out.println(- " Standard14 "- + fn.getName()- + " -> mapped='"- + mapped- + "' name="- + f.getName());- }- System.out.println(- " (PDFBox bundles ONLY LiberationSans-Regular.ttf as a binary; the AFMs cover"- + " metrics for the 14 standard fonts but rendering Helvetica/Times/Courier"- + " glyphs falls back to LiberationSans glyphs at runtime when no system font"- + " is found.)");- }-- private static int streamBytes(InputStream is) {- try (InputStream it = is) {- ByteArrayOutputStream baos = new ByteArrayOutputStream();- byte[] buf = new byte[4096];- int n;- while ((n = it.read(buf)) >= 0) baos.write(buf, 0, n);- return baos.size();- } catch (IOException e) {- return -1;- }- }-}diff --git a/app/core/src/test/java/stirling/software/SPDF/controller/api/PdfTextEditorCharcodeControllerTest.java b/app/core/src/test/java/stirling/software/SPDF/controller/api/PdfTextEditorCharcodeControllerTest.javadeleted file mode 100644index 68cb3566ea..0000000000--- a/app/core/src/test/java/stirling/software/SPDF/controller/api/PdfTextEditorCharcodeControllerTest.java+++ /dev/null@@ -1,755 +0,0 @@-package stirling.software.SPDF.controller.api;--import static org.assertj.core.api.Assertions.assertThat;-import static org.mockito.Mockito.mock;--import java.io.ByteArrayOutputStream;-import java.io.InputStream;-import java.util.Base64;--import org.apache.pdfbox.pdmodel.PDDocument;-import org.apache.pdfbox.pdmodel.PDPage;-import org.apache.pdfbox.pdmodel.PDPageContentStream;-import org.apache.pdfbox.pdmodel.font.PDType1Font;-import org.apache.pdfbox.pdmodel.font.Standard14Fonts;-import org.junit.jupiter.api.Test;-import org.springframework.http.ResponseEntity;--import stirling.software.SPDF.controller.api.PdfTextEditorCharcodeController.EncodeCharcodesRequest;-import stirling.software.SPDF.controller.api.PdfTextEditorCharcodeController.EncodeCharcodesResponse;-import stirling.software.common.service.CustomPDFDocumentFactory;-import stirling.software.common.service.PdfMetadataService;--/**- * Regression coverage for the v2 text editor "spaces render as „" bug.- *- * <p>mushroom-life.pdf is a LaTeX document whose embedded LMRoman subset font has NO real space- * glyph, yet {@code font.encode(" ")} still returns charcode 0x20 without throwing. Reusing that- * code via {@code FPDFText_SetCharcodes} paints whatever glyph sits at subset code 0x20 - the- * quotedblbase „. The controller must therefore report whitespace as {@code missing} so the- * frontend emits it as a positional gap instead of a reused glyph.- */-class PdfTextEditorCharcodeControllerTest {-- private static PdfTextEditorCharcodeController controller() {- return new PdfTextEditorCharcodeController(- new CustomPDFDocumentFactory(mock(PdfMetadataService.class)));- }-- private static String mushroomBase64() throws Exception {- try (InputStream in =- PdfTextEditorCharcodeControllerTest.class.getResourceAsStream(- "/pdftexteditor/mushroom-life.pdf")) {- assertThat(in).as("mushroom-life.pdf test resource").isNotNull();- return Base64.getEncoder().encodeToString(in.readAllBytes());- }- }-- private static EncodeCharcodesRequest request(String text) throws Exception {- EncodeCharcodesRequest req = new EncodeCharcodesRequest();- req.setPdfBase64(mushroomBase64());- req.setPageIndex(0);- // findFontByToUnicode locates the font via the ToUnicode CMap - "M" exists on page 0.- req.setLocatorChar("M");- req.setText(text);- return req;- }-- @Test- void spaceIsReportedMissingNeverEncoded() throws Exception {- PdfTextEditorCharcodeController controller = controller();- ResponseEntity<EncodeCharcodesResponse> resp = controller.encodeCharcodes(request(" "));-- EncodeCharcodesResponse body = resp.getBody();- assertThat(body).isNotNull();- assertThat(body.getError()).isNull();- // The space must be reported missing, NOT handed back as a charcode- // (0x20) the frontend would reuse into the „ glyph.- assertThat(body.getMissing()).containsExactly(" ");- assertThat(body.getCharcodes()).isNullOrEmpty();- }-- @Test- void realCharsEncodeWhileWhitespaceStaysAGap() throws Exception {- PdfTextEditorCharcodeController controller = controller();- // "M M" - both M's must encode to real charcodes; only the space is a gap.- ResponseEntity<EncodeCharcodesResponse> resp = controller.encodeCharcodes(request("M M"));-- EncodeCharcodesResponse body = resp.getBody();- assertThat(body).isNotNull();- assertThat(body.getError()).isNull();- assertThat(body.getCharcodes()).as("both M glyphs encode").hasSize(2);- assertThat(body.getMissing()).containsExactly(" ");- }-- @Test- void tabAndNewlineAreAlsoTreatedAsGaps() throws Exception {- PdfTextEditorCharcodeController controller = controller();- ResponseEntity<EncodeCharcodesResponse> resp = controller.encodeCharcodes(request("\t\n"));-- EncodeCharcodesResponse body = resp.getBody();- assertThat(body).isNotNull();- assertThat(body.getMissing()).containsExactly("\t", "\n");- assertThat(body.getCharcodes()).isNullOrEmpty();- }-- /**- * A page with two fonts that BOTH render 'A'. {@code fontName} must select which one to encode- * against - the cross-font fix. Without it the first font in resources order won wins and a- * cross-font edit got the wrong font's charcode.- */- private static String twoFontBase64() throws Exception {- try (PDDocument doc = new PDDocument()) {- PDPage page = new PDPage();- doc.addPage(page);- PDType1Font helvetica = new PDType1Font(Standard14Fonts.FontName.HELVETICA);- PDType1Font times = new PDType1Font(Standard14Fonts.FontName.TIMES_ROMAN);- try (PDPageContentStream cs = new PDPageContentStream(doc, page)) {- cs.beginText();- cs.setFont(helvetica, 12);- cs.newLineAtOffset(72, 720);- cs.showText("A");- cs.endText();- cs.beginText();- cs.setFont(times, 12);- cs.newLineAtOffset(72, 700);- cs.showText("A");- cs.endText();- }- ByteArrayOutputStream bos = new ByteArrayOutputStream();- doc.save(bos);- return Base64.getEncoder().encodeToString(bos.toByteArray());- }- }-- private static EncodeCharcodesRequest twoFontRequest(String fontName) throws Exception {- EncodeCharcodesRequest req = new EncodeCharcodesRequest();- req.setPdfBase64(twoFontBase64());- req.setPageIndex(0);- req.setLocatorChar("A");- req.setFontName(fontName);- req.setText("A");- return req;- }-- @Test- void fontNameDisambiguatesBetweenTwoFontsRenderingTheSameChar() throws Exception {- PdfTextEditorCharcodeController controller = controller();-- // Targeting Times-Roman must encode against Times-Roman, not whichever- // font happens to appear first in the page's font resources.- EncodeCharcodesResponse times =- controller.encodeCharcodes(twoFontRequest("Times-Roman")).getBody();- assertThat(times).isNotNull();- assertThat(times.getError()).isNull();- assertThat(times.getNote()).contains("Times-Roman");- assertThat(times.getCharcodes()).hasSize(1);-- // Targeting Helvetica must encode against Helvetica.- EncodeCharcodesResponse helv =- controller.encodeCharcodes(twoFontRequest("Helvetica")).getBody();- assertThat(helv).isNotNull();- assertThat(helv.getError()).isNull();- assertThat(helv.getNote()).contains("Helvetica");- assertThat(helv.getCharcodes()).hasSize(1);- }-- @Test- void unknownFontNameReportsNoFontInsteadOfWrongFont() throws Exception {- PdfTextEditorCharcodeController controller = controller();- // A name that matches no font on the page must NOT silently encode- // against a different font: the frontend writes the returned charcodes- // into the NAMED font's text object, so a first-match fallback would- // bake wrong glyphs. It must report failure so the caller falls back.- EncodeCharcodesResponse body =- controller.encodeCharcodes(twoFontRequest("DoesNotExist")).getBody();- assertThat(body).isNotNull();- assertThat(body.getError()).contains("no font");- assertThat(body.getCharcodes()).isNull();- }-- @Test- void missingRequiredFieldsReturns400() {- EncodeCharcodesRequest req = new EncodeCharcodesRequest();- req.setPdfBase64("AAAA");- req.setLocatorChar("M");- // text is null- ResponseEntity<EncodeCharcodesResponse> resp = controller().encodeCharcodes(req);- assertThat(resp.getStatusCode().value()).isEqualTo(400);- assertThat(resp.getBody()).isNotNull();- assertThat(resp.getBody().getError()).isEqualTo("missing required fields");- }-- @Test- void invalidBase64Returns400() {- EncodeCharcodesRequest req = new EncodeCharcodesRequest();- req.setPdfBase64("!!!notbase64!!!");- req.setLocatorChar("M");- req.setText("M");- ResponseEntity<EncodeCharcodesResponse> resp = controller().encodeCharcodes(req);- assertThat(resp.getStatusCode().value()).isEqualTo(400);- assertThat(resp.getBody()).isNotNull();- assertThat(resp.getBody().getError()).isEqualTo("pdfBase64 is not valid base64");- }-- @Test- void pageIndexOutOfRangeReturns400() throws Exception {- EncodeCharcodesRequest req = request("M");- req.setPageIndex(999);- ResponseEntity<EncodeCharcodesResponse> resp = controller().encodeCharcodes(req);- assertThat(resp.getStatusCode().value()).isEqualTo(400);- assertThat(resp.getBody()).isNotNull();- assertThat(resp.getBody().getError()).isEqualTo("pageIndex out of range");- }-- @Test- void nonPdfBytesReturnsGenericError() {- EncodeCharcodesRequest req = new EncodeCharcodesRequest();- req.setPdfBase64(Base64.getEncoder().encodeToString("not a pdf".getBytes()));- req.setLocatorChar("M");- req.setText("M");- // Must not throw, and must not leak the raw PDFBox parser message.- ResponseEntity<EncodeCharcodesResponse> resp = controller().encodeCharcodes(req);- assertThat(resp.getStatusCode().is4xxClientError()).isTrue();- assertThat(resp.getBody()).isNotNull();- assertThat(resp.getBody().getError()).isEqualTo("failed to load PDF");- }-- @Test- void absentLocatorCharReturns200WithError() throws Exception {- // U+FFFF never appears in the document, so no font matches.- ResponseEntity<EncodeCharcodesResponse> resp =- controller().encodeCharcodes(requestWithLocator(""));- assertThat(resp.getStatusCode().value()).isEqualTo(200);- EncodeCharcodesResponse body = resp.getBody();- assertThat(body).isNotNull();- assertThat(body.getError()).isNotNull();- assertThat(body.getCharcodes()).isNull();- }-- @Test- void oversizePdfRejected() {- EncodeCharcodesRequest req = new EncodeCharcodesRequest();- // A base64 string long enough that length/4*3 exceeds the 100MB cap, without- // ever allocating the decoded bytes (the guard runs before decode).- char[] huge = new char[140 * 1024 * 1024];- java.util.Arrays.fill(huge, 'A');- req.setPdfBase64(new String(huge));- req.setLocatorChar("M");- req.setText("M");- ResponseEntity<EncodeCharcodesResponse> resp = controller().encodeCharcodes(req);- assertThat(resp.getStatusCode().value()).isEqualTo(413);- assertThat(resp.getBody()).isNotNull();- assertThat(resp.getBody().getError()).isEqualTo("pdf too large");- }-- private static EncodeCharcodesRequest requestWithLocator(String locator) throws Exception {- EncodeCharcodesRequest req = request("M");- req.setLocatorChar(locator);- return req;- }-- /**- * Build a page whose resources declare {@code filler} fonts that do NOT render 'A' (Symbol /- * ZapfDingbats have non-Latin encodings) plus, optionally, a trailing Helvetica that does. The- * Standard14 probe upper bound is 256 so each scan is cheap.- */- private static String manyFontsBase64(int filler, boolean trailingTarget) throws Exception {- try (PDDocument doc = new PDDocument()) {- PDPage page = new PDPage();- doc.addPage(page);- org.apache.pdfbox.pdmodel.PDResources resources =- new org.apache.pdfbox.pdmodel.PDResources();- for (int n = 0; n < filler; n++) {- Standard14Fonts.FontName fn =- (n % 2 == 0)- ? Standard14Fonts.FontName.SYMBOL- : Standard14Fonts.FontName.ZAPF_DINGBATS;- resources.put(- org.apache.pdfbox.cos.COSName.getPDFName("Ff" + n), new PDType1Font(fn));- }- if (trailingTarget) {- resources.put(- org.apache.pdfbox.cos.COSName.getPDFName("Target"),- new PDType1Font(Standard14Fonts.FontName.HELVETICA));- }- page.setResources(resources);- ByteArrayOutputStream bos = new ByteArrayOutputStream();- doc.save(bos);- return Base64.getEncoder().encodeToString(bos.toByteArray());- }- }-- private static EncodeCharcodesRequest manyFontsRequest(String base64) {- EncodeCharcodesRequest req = new EncodeCharcodesRequest();- req.setPdfBase64(base64);- req.setPageIndex(0);- req.setLocatorChar("A");- req.setText("A");- return req;- }-- @Test- void targetFontFoundAmongManyFonts() throws Exception {- // 60 non-matching fonts then the Helvetica target, all within the 64-font cap.- ResponseEntity<EncodeCharcodesResponse> resp =- controller().encodeCharcodes(manyFontsRequest(manyFontsBase64(60, true)));- assertThat(resp.getStatusCode().value()).isEqualTo(200);- EncodeCharcodesResponse body = resp.getBody();- assertThat(body).isNotNull();- assertThat(body.getError()).isNull();- assertThat(body.getCharcodes()).hasSize(1);- }-- @Test- void targetBeyondFontCapReturnsGracefulNoFont() throws Exception {- // 64 non-matching fonts then the target at position 65 - the scan cap stops- // before reaching it, so we get a graceful no-font error rather than a full scan.- ResponseEntity<EncodeCharcodesResponse> resp =- controller().encodeCharcodes(manyFontsRequest(manyFontsBase64(64, true)));- assertThat(resp.getStatusCode().value()).isEqualTo(200);- EncodeCharcodesResponse body = resp.getBody();- assertThat(body).isNotNull();- assertThat(body.getError()).isNotNull();- assertThat(body.getCharcodes()).isNull();- }-- // Same-family sibling subsets. One document can embed several subsets of- // one family, each re-encoded by order of first glyph use, so a letter has- // a different charcode in each ("R" = 0x21 in one, 0x22 in its sibling).- // FPDFFont_GetBaseFontName strips the "ABCDEF+" tag, so a name-based- // lookup cannot tell them apart and borrows the wrong subset's codes.- //- // The doc below mirrors that with two TrueType subsets differing only by- // subset tag. PUA code points keep it deterministic: font.encode() cannot- // resolve them by glyph name, so the charcode can only come from the- // selected font's ToUnicode reverse map - proving WHICH font was picked.-- private static final String PUA = "";-- /** ToUnicode CMap mapping each supplied charcode to a BMP code point. */- private static byte[] toUnicodeCmap(int[][] codeToUnicode) {- StringBuilder sb =- new StringBuilder(- """- /CIDInit /ProcSet findresource begin- 12 dict begin- begincmap- /CIDSystemInfo << /Registry (Adobe) /Ordering (UCS) /Supplement 0 >> def- /CMapName /Adobe-Identity-UCS def- /CMapType 2 def- 1 begincodespacerange- <00><FF>- endcodespacerange- """);- sb.append(codeToUnicode.length).append(" beginbfchar\n");- for (int[] pair : codeToUnicode) {- sb.append(String.format("<%02X><%04X>%n", pair[0], pair[1]));- }- sb.append(- """- endbfchar- endcmap- CMapName currentdict /CMap defineresource pop- end- end- """);- return sb.toString().getBytes(java.nio.charset.StandardCharsets.US_ASCII);- }-- private static org.apache.pdfbox.cos.COSDictionary subsetFontDict(- PDDocument doc, String baseName, byte[] fontProgram, byte[] toUnicode)- throws Exception {- org.apache.pdfbox.cos.COSDictionary font = new org.apache.pdfbox.cos.COSDictionary();- font.setItem(org.apache.pdfbox.cos.COSName.TYPE, org.apache.pdfbox.cos.COSName.FONT);- font.setItem(- org.apache.pdfbox.cos.COSName.SUBTYPE, org.apache.pdfbox.cos.COSName.TRUE_TYPE);- if (baseName != null) {- font.setName(org.apache.pdfbox.cos.COSName.BASE_FONT, baseName);- }- font.setInt(org.apache.pdfbox.cos.COSName.FIRST_CHAR, 0x21);- font.setInt(org.apache.pdfbox.cos.COSName.LAST_CHAR, 0x22);- org.apache.pdfbox.cos.COSArray widths = new org.apache.pdfbox.cos.COSArray();- widths.add(org.apache.pdfbox.cos.COSInteger.get(500));- widths.add(org.apache.pdfbox.cos.COSInteger.get(500));- font.setItem(org.apache.pdfbox.cos.COSName.WIDTHS, widths);-- org.apache.pdfbox.cos.COSDictionary fd = new org.apache.pdfbox.cos.COSDictionary();- fd.setItem(org.apache.pdfbox.cos.COSName.TYPE, org.apache.pdfbox.cos.COSName.FONT_DESC);- if (baseName != null) {- fd.setName(org.apache.pdfbox.cos.COSName.FONT_NAME, baseName);- }- fd.setInt(org.apache.pdfbox.cos.COSName.FLAGS, 4);- fd.setItem(- org.apache.pdfbox.cos.COSName.FONT_BBOX,- new org.apache.pdfbox.pdmodel.common.PDRectangle(0, 0, 1000, 1000).getCOSArray());- fd.setInt(org.apache.pdfbox.cos.COSName.ITALIC_ANGLE, 0);- fd.setInt(org.apache.pdfbox.cos.COSName.ASCENT, 800);- fd.setInt(org.apache.pdfbox.cos.COSName.DESCENT, -200);- fd.setInt(org.apache.pdfbox.cos.COSName.CAP_HEIGHT, 700);- fd.setInt(org.apache.pdfbox.cos.COSName.STEM_V, 80);- if (fontProgram != null) {- org.apache.pdfbox.pdmodel.common.PDStream ff2 =- new org.apache.pdfbox.pdmodel.common.PDStream(- doc, new java.io.ByteArrayInputStream(fontProgram));- ff2.getCOSObject().setInt(org.apache.pdfbox.cos.COSName.LENGTH1, fontProgram.length);- fd.setItem(org.apache.pdfbox.cos.COSName.FONT_FILE2, ff2.getCOSObject());- }- font.setItem(org.apache.pdfbox.cos.COSName.FONT_DESC, fd);-- org.apache.pdfbox.pdmodel.common.PDStream tu =- new org.apache.pdfbox.pdmodel.common.PDStream(- doc, new java.io.ByteArrayInputStream(toUnicode));- font.setItem(org.apache.pdfbox.cos.COSName.getPDFName("ToUnicode"), tu.getCOSObject());- return font;- }-- // Distinct fake font programs - hashing distinguishes the subsets by these bytes.- private static final byte[] PROGRAM_A =- "fake-ttf-program-A".getBytes(java.nio.charset.StandardCharsets.US_ASCII);- private static final byte[] PROGRAM_B =- "fake-ttf-program-B".getBytes(java.nio.charset.StandardCharsets.US_ASCII);-- /**- * Two sibling subsets of "FakeGaramond" whose ToUnicode maps give U+E000 DIFFERENT charcodes:- * 0x22 in subset A (AAAAAC+), 0x21 in subset B (AAAAAG+) - exactly the CV's shifted-code- * layout. {@code includeSecond=false} keeps only subset A for the unambiguous-fallback case.- */- private static String siblingSubsetsBase64(boolean includeSecond) throws Exception {- try (PDDocument doc = new PDDocument()) {- PDPage page = new PDPage();- doc.addPage(page);- org.apache.pdfbox.cos.COSDictionary fonts = new org.apache.pdfbox.cos.COSDictionary();- fonts.setItem(- org.apache.pdfbox.cos.COSName.getPDFName("TTA"),- subsetFontDict(- doc,- "AAAAAC+FakeGaramond",- PROGRAM_A,- toUnicodeCmap(new int[][] {{0x21, 0xE001}, {0x22, 0xE000}})));- if (includeSecond) {- fonts.setItem(- org.apache.pdfbox.cos.COSName.getPDFName("TTB"),- subsetFontDict(- doc,- "AAAAAG+FakeGaramond",- PROGRAM_B,- toUnicodeCmap(new int[][] {{0x21, 0xE000}, {0x22, 0xE002}})));- }- org.apache.pdfbox.pdmodel.PDResources resources =- new org.apache.pdfbox.pdmodel.PDResources();- resources.getCOSObject().setItem(org.apache.pdfbox.cos.COSName.FONT, fonts);- page.setResources(resources);- ByteArrayOutputStream bos = new ByteArrayOutputStream();- doc.save(bos);- return Base64.getEncoder().encodeToString(bos.toByteArray());- }- }-- private static String sha256Hex(byte[] bytes) throws Exception {- byte[] digest = java.security.MessageDigest.getInstance("SHA-256").digest(bytes);- StringBuilder sb = new StringBuilder();- for (byte b : digest) sb.append(String.format("%02x", b));- return sb.toString();- }-- private static EncodeCharcodesRequest siblingRequest(- String base64, String fontName, String fontSha256) {- EncodeCharcodesRequest req = new EncodeCharcodesRequest();- req.setPdfBase64(base64);- req.setPageIndex(0);- req.setLocatorChar(PUA);- req.setFontName(fontName);- req.setFontSha256(fontSha256);- req.setText(PUA);- return req;- }-- @Test- void fontProgramHashSelectsTheExactSubset() throws Exception {- String base64 = siblingSubsetsBase64(true);- PdfTextEditorCharcodeController controller = controller();-- // Both requests carry the SAME tag-stripped name PDFium reports ("FakeGaramond"),- // so only the program hash can tell the subsets apart.- EncodeCharcodesResponse viaA =- controller- .encodeCharcodes(- siblingRequest(base64, "FakeGaramond", sha256Hex(PROGRAM_A)))- .getBody();- assertThat(viaA).isNotNull();- assertThat(viaA.getError()).isNull();- assertThat(viaA.getNote()).contains("AAAAAC+FakeGaramond");- assertThat(viaA.getCharcodes()).containsExactly(0x22L);-- EncodeCharcodesResponse viaB =- controller- .encodeCharcodes(- siblingRequest(base64, "FakeGaramond", sha256Hex(PROGRAM_B)))- .getBody();- assertThat(viaB).isNotNull();- assertThat(viaB.getError()).isNull();- assertThat(viaB.getNote()).contains("AAAAAG+FakeGaramond");- assertThat(viaB.getCharcodes()).containsExactly(0x21L);- }-- @Test- void ambiguousStrippedNameRefusesToGuessBetweenSiblingSubsets() throws Exception {- // No hash, and the tag-stripped name matches BOTH subsets which both render the- // locator char. Guessing here is what scrambled "RUSSELL W. MANGUM III" into- // "US EEL W. MANGS M III" - the sibling's codes hit different glyphs. The- // backend must refuse so the frontend takes its safe fallback.- EncodeCharcodesResponse body =- controller()- .encodeCharcodes(- siblingRequest(siblingSubsetsBase64(true), "FakeGaramond", null))- .getBody();- assertThat(body).isNotNull();- assertThat(body.getError()).contains("no font");- assertThat(body.getCharcodes()).isNull();- }-- @Test- void exactTaggedNameStillSelectsItsSubset() throws Exception {- // A caller that DOES know the full tagged /BaseFont name keeps working.- EncodeCharcodesResponse body =- controller()- .encodeCharcodes(- siblingRequest(- siblingSubsetsBase64(true), "AAAAAG+FakeGaramond", null))- .getBody();- assertThat(body).isNotNull();- assertThat(body.getError()).isNull();- assertThat(body.getNote()).contains("AAAAAG+FakeGaramond");- assertThat(body.getCharcodes()).containsExactly(0x21L);- }-- @Test- void strippedNameStillWorksWhenUnambiguous() throws Exception {- // With a SINGLE subset on the page, the tag-stripped name (what PDFium- // reports) must keep resolving - the ambiguity guard only bites when- // two+ siblings could answer.- EncodeCharcodesResponse body =- controller()- .encodeCharcodes(- siblingRequest(siblingSubsetsBase64(false), "FakeGaramond", null))- .getBody();- assertThat(body).isNotNull();- assertThat(body.getError()).isNull();- assertThat(body.getNote()).contains("AAAAAC+FakeGaramond");- assertThat(body.getCharcodes()).containsExactly(0x22L);- }-- @Test- void staleHashFallsBackToNameMatching() throws Exception {- // A hash matching NO font on the page (e.g. PDFium handed back a substitute- // font's bytes) must not brick the request: name matching still runs, and an- // exact tagged name resolves.- EncodeCharcodesResponse body =- controller()- .encodeCharcodes(- siblingRequest(- siblingSubsetsBase64(true),- "AAAAAC+FakeGaramond",- "0000000000000000000000000000000000000000000000000000000000000000"))- .getBody();- assertThat(body).isNotNull();- assertThat(body.getError()).isNull();- assertThat(body.getNote()).contains("AAAAAC+FakeGaramond");- assertThat(body.getCharcodes()).containsExactly(0x22L);- }-- private static final String PUA_E000 = "";- private static final String PUA_E002 = "";-- private static final byte[] SHARED_PROGRAM =- "fake-ttf-program-shared".getBytes(java.nio.charset.StandardCharsets.US_ASCII);-- private static String cacheIdentityPairBase64(String baseName, byte[] program)- throws Exception {- try (PDDocument doc = new PDDocument()) {- PDPage page = new PDPage();- doc.addPage(page);- org.apache.pdfbox.cos.COSDictionary fonts = new org.apache.pdfbox.cos.COSDictionary();- fonts.setItem(- org.apache.pdfbox.cos.COSName.getPDFName("C1"),- subsetFontDict(- doc,- baseName,- program,- toUnicodeCmap(new int[][] {{0x21, 0xE001}, {0x22, 0xE000}})));- fonts.setItem(- org.apache.pdfbox.cos.COSName.getPDFName("C2"),- subsetFontDict(- doc,- baseName,- program,- toUnicodeCmap(new int[][] {{0x21, 0xE002}, {0x22, 0xE003}})));- org.apache.pdfbox.pdmodel.PDResources resources =- new org.apache.pdfbox.pdmodel.PDResources();- resources.getCOSObject().setItem(org.apache.pdfbox.cos.COSName.FONT, fonts);- page.setResources(resources);- ByteArrayOutputStream bos = new ByteArrayOutputStream();- doc.save(bos);- return Base64.getEncoder().encodeToString(bos.toByteArray());- }- }-- private static EncodeCharcodesRequest cacheIdentityRequest(- String base64, String locator, String fontName, String fontSha256) {- EncodeCharcodesRequest req = new EncodeCharcodesRequest();- req.setPdfBase64(base64);- req.setPageIndex(0);- req.setLocatorChar(locator);- req.setFontName(fontName);- req.setFontSha256(fontSha256);- req.setText(locator);- return req;- }-- @Test- void unnamedFontsSharingOneProgramDoNotShareACachedMap() throws Exception {- String base64 = cacheIdentityPairBase64(null, SHARED_PROGRAM);- String sha = sha256Hex(SHARED_PROGRAM);- PdfTextEditorCharcodeController controller = controller();-- EncodeCharcodesResponse first =- controller- .encodeCharcodes(cacheIdentityRequest(base64, PUA_E000, null, sha))- .getBody();- assertThat(first).isNotNull();- assertThat(first.getError()).isNull();- assertThat(first.getCharcodes()).containsExactly(0x22L);-- EncodeCharcodesResponse second =- controller- .encodeCharcodes(cacheIdentityRequest(base64, PUA_E002, null, sha))- .getBody();- assertThat(second).isNotNull();- assertThat(second.getError()).isNull();- assertThat(second.getMissing()).isNullOrEmpty();- assertThat(second.getCharcodes())- .as("second font must not be served the first font's cached map")- .containsExactly(0x21L);- }-- @Test- void fontsSharingOneNameDoNotShareACachedMap() throws Exception {- String base64 = cacheIdentityPairBase64("SharedName", null);- PdfTextEditorCharcodeController controller = controller();-- EncodeCharcodesResponse first =- controller- .encodeCharcodes(cacheIdentityRequest(base64, PUA_E000, "SharedName", null))- .getBody();- assertThat(first).isNotNull();- assertThat(first.getError()).isNull();- assertThat(first.getCharcodes()).containsExactly(0x22L);-- EncodeCharcodesResponse second =- controller- .encodeCharcodes(cacheIdentityRequest(base64, PUA_E002, "SharedName", null))- .getBody();- assertThat(second).isNotNull();- assertThat(second.getError()).isNull();- assertThat(second.getMissing()).isNullOrEmpty();- assertThat(second.getCharcodes())- .as("same-name fonts must not share one cached map")- .containsExactly(0x21L);- }-- private static String formXObjectFontBase64() throws Exception {- try (PDDocument doc = new PDDocument()) {- PDPage page = new PDPage();- doc.addPage(page);-- org.apache.pdfbox.pdmodel.graphics.form.PDFormXObject outer =- new org.apache.pdfbox.pdmodel.graphics.form.PDFormXObject(doc);- outer.setBBox(new org.apache.pdfbox.pdmodel.common.PDRectangle(0, 0, 200, 200));- org.apache.pdfbox.pdmodel.graphics.form.PDFormXObject inner =- new org.apache.pdfbox.pdmodel.graphics.form.PDFormXObject(doc);- inner.setBBox(new org.apache.pdfbox.pdmodel.common.PDRectangle(0, 0, 100, 100));-- org.apache.pdfbox.pdmodel.PDResources innerResources =- new org.apache.pdfbox.pdmodel.PDResources();- innerResources.put(- org.apache.pdfbox.cos.COSName.getPDFName("F1"),- new PDType1Font(Standard14Fonts.FontName.HELVETICA));- inner.setResources(innerResources);-- org.apache.pdfbox.pdmodel.PDResources outerResources =- new org.apache.pdfbox.pdmodel.PDResources();- outerResources.put(org.apache.pdfbox.cos.COSName.getPDFName("Fm1"), inner);- outer.setResources(outerResources);-- org.apache.pdfbox.pdmodel.PDResources pageResources =- new org.apache.pdfbox.pdmodel.PDResources();- pageResources.put(org.apache.pdfbox.cos.COSName.getPDFName("Fm0"), outer);- page.setResources(pageResources);-- ByteArrayOutputStream bos = new ByteArrayOutputStream();- doc.save(bos);- return Base64.getEncoder().encodeToString(bos.toByteArray());- }- }-- private static String cyclicFormXObjectsBase64() throws Exception {- try (PDDocument doc = new PDDocument()) {- PDPage page = new PDPage();- doc.addPage(page);-- org.apache.pdfbox.pdmodel.graphics.form.PDFormXObject formA =- new org.apache.pdfbox.pdmodel.graphics.form.PDFormXObject(doc);- formA.setBBox(new org.apache.pdfbox.pdmodel.common.PDRectangle(0, 0, 100, 100));- org.apache.pdfbox.pdmodel.graphics.form.PDFormXObject formB =- new org.apache.pdfbox.pdmodel.graphics.form.PDFormXObject(doc);- formB.setBBox(new org.apache.pdfbox.pdmodel.common.PDRectangle(0, 0, 100, 100));-- org.apache.pdfbox.pdmodel.PDResources resA =- new org.apache.pdfbox.pdmodel.PDResources();- org.apache.pdfbox.pdmodel.PDResources resB =- new org.apache.pdfbox.pdmodel.PDResources();- resA.put(org.apache.pdfbox.cos.COSName.getPDFName("Self"), formA);- resA.put(org.apache.pdfbox.cos.COSName.getPDFName("Fb"), formB);- resB.put(org.apache.pdfbox.cos.COSName.getPDFName("Fa"), formA);- resB.put(- org.apache.pdfbox.cos.COSName.getPDFName("F1"),- new PDType1Font(Standard14Fonts.FontName.HELVETICA));- formA.setResources(resA);- formB.setResources(resB);-- org.apache.pdfbox.pdmodel.PDResources pageResources =- new org.apache.pdfbox.pdmodel.PDResources();- pageResources.put(org.apache.pdfbox.cos.COSName.getPDFName("Fm0"), formA);- page.setResources(pageResources);-- ByteArrayOutputStream bos = new ByteArrayOutputStream();- doc.save(bos);- return Base64.getEncoder().encodeToString(bos.toByteArray());- }- }-- @Test- void fontReachableOnlyThroughAFormXObjectIsFound() throws Exception {- ResponseEntity<EncodeCharcodesResponse> resp =- controller().encodeCharcodes(manyFontsRequest(formXObjectFontBase64()));- assertThat(resp.getStatusCode().value()).isEqualTo(200);- EncodeCharcodesResponse body = resp.getBody();- assertThat(body).isNotNull();- assertThat(body.getError()).isNull();- assertThat(body.getNote()).contains("Helvetica");- assertThat(body.getCharcodes()).containsExactly((long) 'A');- }-- @Test- @org.junit.jupiter.api.Timeout(60)- void cyclicFormXObjectResourcesTerminate() throws Exception {- ResponseEntity<EncodeCharcodesResponse> resp =- controller().encodeCharcodes(manyFontsRequest(cyclicFormXObjectsBase64()));- assertThat(resp.getStatusCode().value()).isEqualTo(200);- EncodeCharcodesResponse body = resp.getBody();- assertThat(body).isNotNull();- assertThat(body.getError()).isNull();- assertThat(body.getCharcodes()).containsExactly((long) 'A');- }-}diff --git a/app/core/src/test/java/stirling/software/SPDF/controller/api/SamplePdfFontDumpTest.java b/app/core/src/test/java/stirling/software/SPDF/controller/api/SamplePdfFontDumpTest.javadeleted file mode 100644index 1a8b09fe6a..0000000000--- a/app/core/src/test/java/stirling/software/SPDF/controller/api/SamplePdfFontDumpTest.java+++ /dev/null@@ -1,340 +0,0 @@-package stirling.software.SPDF.controller.api;--import java.io.ByteArrayInputStream;-import java.io.IOException;-import java.io.InputStream;-import java.nio.charset.StandardCharsets;-import java.nio.file.Files;-import java.nio.file.Path;-import java.nio.file.Paths;-import java.util.HashSet;-import java.util.Set;-import java.util.TreeSet;--import org.apache.pdfbox.Loader;-import org.apache.pdfbox.contentstream.PDFStreamEngine;-import org.apache.pdfbox.contentstream.operator.state.Concatenate;-import org.apache.pdfbox.contentstream.operator.state.Restore;-import org.apache.pdfbox.contentstream.operator.state.Save;-import org.apache.pdfbox.contentstream.operator.state.SetGraphicsStateParameters;-import org.apache.pdfbox.contentstream.operator.state.SetMatrix;-import org.apache.pdfbox.contentstream.operator.text.BeginText;-import org.apache.pdfbox.contentstream.operator.text.EndText;-import org.apache.pdfbox.contentstream.operator.text.SetFontAndSize;-import org.apache.pdfbox.contentstream.operator.text.SetTextHorizontalScaling;-import org.apache.pdfbox.contentstream.operator.text.SetTextLeading;-import org.apache.pdfbox.contentstream.operator.text.SetTextRenderingMode;-import org.apache.pdfbox.contentstream.operator.text.SetTextRise;-import org.apache.pdfbox.contentstream.operator.text.SetWordSpacing;-import org.apache.pdfbox.contentstream.operator.text.ShowText;-import org.apache.pdfbox.cos.COSBase;-import org.apache.pdfbox.cos.COSDictionary;-import org.apache.pdfbox.cos.COSName;-import org.apache.pdfbox.cos.COSStream;-import org.apache.pdfbox.pdmodel.PDDocument;-import org.apache.pdfbox.pdmodel.PDPage;-import org.apache.pdfbox.pdmodel.PDResources;-import org.apache.pdfbox.pdmodel.font.PDFont;-import org.apache.pdfbox.pdmodel.font.PDFontDescriptor;-import org.apache.pdfbox.pdmodel.font.PDType3CharProc;-import org.apache.pdfbox.pdmodel.font.PDType3Font;-import org.junit.jupiter.api.Disabled;-import org.junit.jupiter.api.Test;--/**- * Diagnostic test: enumerate every font referenced by Sample.pdf and dump its subtype, encoding,- * ToUnicode, and embedded font program info. For Type3 fonts also dump CharProcs glyph names and- * the content stream of one glyph (the 'M' if present).- *- * <p>Not a real regression test - run with --tests SamplePdfFontDumpTest -i to see the stdout- * output.- */-@Disabled(- "Diagnostic probe: dumps Sample.pdf font internals to stdout and asserts nothing. Kept for font debugging; run manually.")-public class SamplePdfFontDumpTest {-- private static final Path SAMPLE =- Paths.get(System.getProperty("user.dir"))- .getParent()- .getParent()- .resolve("frontend/public/samples/Sample.pdf");-- @Test- public void dumpFonts() throws IOException {- byte[] pdfBytes = Files.readAllBytes(SAMPLE);- try (PDDocument doc = Loader.loadPDF(pdfBytes)) {- int numPages = doc.getNumberOfPages();- System.out.println("Sample.pdf has " + numPages + " pages.");- Set<COSDictionary> seenFontDicts = new HashSet<>();- for (int p = 0; p < numPages; p++) {- PDPage page = doc.getPage(p);- System.out.println("\n=== Page " + p + " ===");- PDResources resources = page.getResources();- if (resources == null) {- System.out.println(" (no resources)");- continue;- }- for (COSName fontName : resources.getFontNames()) {- PDFont font;- try {- font = resources.getFont(fontName);- } catch (IOException e) {- System.out.println(- " Font "- + fontName.getName()- + ": failed to load - "- + e.getMessage());- continue;- }- if (font == null) continue;- COSDictionary dict = font.getCOSObject();- if (!seenFontDicts.add(dict)) {- System.out.println(- " Font " + fontName.getName() + " -> already seen above");- continue;- }- dumpFont(fontName.getName(), font);- }- }- // Scan: for every text-show operation, record per-font (charcode, unicode) pairs.- System.out.println("\n=== All (font, charcode, unicode) seen on page ===");- for (int p = 0; p < numPages; p++) {- PDPage page = doc.getPage(p);- AllCharsScanner scanner = new AllCharsScanner();- scanner.processPage(page);- System.out.println("\nPage " + p + ":");- for (var entry : scanner.perFont.entrySet()) {- PDFont font = entry.getKey();- var seen = entry.getValue();- System.out.println(" Font " + font.getName() + " " + font.getSubType() + ":");- var sortedSeen = new java.util.TreeMap<Integer, String>(seen);- for (var s : sortedSeen.entrySet()) {- System.out.println(- " charcode 0x"- + Integer.toHexString(s.getKey())- + " ("- + s.getKey()- + ") -> '"- + s.getValue()- + "'");- }- }- }-- // Confirm font.encode() works for Type3 fonts.- System.out.println("\n=== Can we encode existing chars in F27/F28? ===");- PDPage page0 = doc.getPage(0);- PDResources r0 = page0.getResources();- for (String fname : new String[] {"F27", "F28"}) {- PDFont f = r0.getFont(COSName.getPDFName(fname));- if (f == null) {- System.out.println(" " + fname + ": NOT FOUND on page 0");- continue;- }- System.out.println(" " + fname + ": " + f.getClass().getSimpleName());- for (String ch : new String[] {"M", "0", "1", "+", "Z", "a"}) {- try {- byte[] enc = f.encode(ch);- StringBuilder sb = new StringBuilder();- for (byte b : enc) sb.append(String.format("%02X ", b & 0xff));- System.out.println(- " encode('" + ch + "') -> [" + sb.toString().trim() + "]");- } catch (Exception e) {- System.out.println(- " encode('"- + ch- + "') FAILED: "- + e.getClass().getSimpleName()- + " "- + e.getMessage());- }- }- }-- // Dump page 0 content stream so we can see how "10M+" is composed.- System.out.println("\n=== Page 0 RAW content stream (first 4kb) ===");- try (InputStream is = doc.getPage(0).getContents()) {- byte[] bytes = is.readAllBytes();- System.out.println("Total content stream size: " + bytes.length + " bytes");- String asStr = new String(bytes, StandardCharsets.ISO_8859_1);- int idx = asStr.indexOf("F27");- if (idx >= 0) {- int start = Math.max(0, idx - 100);- int end = Math.min(asStr.length(), idx + 2500);- System.out.println("--- F27 context ---");- System.out.println(asStr.substring(start, end));- System.out.println("---");- }- int idx2 = asStr.indexOf("F28");- if (idx2 >= 0) {- int start = Math.max(0, idx2 - 200);- int end = Math.min(asStr.length(), idx2 + 600);- System.out.println("--- F28 context ---");- System.out.println(asStr.substring(start, end));- System.out.println("---");- }- }-- // Dump a CharProc for each font's first non-zero glyph, with focus on any 'M' or "0".- System.out.println("\n=== Sample CharProc dumps for Type3 fonts ===");- Set<COSDictionary> printed = new HashSet<>();- for (int p = 0; p < numPages; p++) {- PDPage page = doc.getPage(p);- PDResources resources = page.getResources();- if (resources == null) continue;- for (COSName fn : resources.getFontNames()) {- PDFont font = resources.getFont(fn);- if (!(font instanceof PDType3Font)) continue;- if (!printed.add(font.getCOSObject())) continue;- PDType3Font t3 = (PDType3Font) font;- // Iterate charcodes 0..255 looking for any that map to 'M' or '0' or '+'.- for (int cc = 0; cc < 256; cc++) {- String u = null;- try {- u = t3.toUnicode(cc);- } catch (Exception e) {- /* */- }- if (u == null) continue;- if (u.equals("M") || u.equals("0") || u.equals("+") || u.equals("1")) {- System.out.println(- "Page "- + p- + " font '"- + fn.getName()- + "' charcode "- + cc- + " maps to '"- + u- + "':");- dumpType3Glyph(t3, cc);- }- }- }- }- }- }-- private void dumpFont(String resourceName, PDFont font) {- COSDictionary dict = font.getCOSObject();- String subtype = dict.getNameAsString(COSName.SUBTYPE);- String baseFont = dict.getNameAsString(COSName.BASE_FONT);- boolean hasEncoding = dict.containsKey(COSName.ENCODING);- boolean hasToUnicode = dict.containsKey(COSName.TO_UNICODE);- PDFontDescriptor descriptor = font.getFontDescriptor();- boolean hasEmbedded = false;- String embeddedKind = "none";- if (descriptor != null) {- COSDictionary dDict = descriptor.getCOSObject();- if (dDict.containsKey(COSName.FONT_FILE)) {- hasEmbedded = true;- embeddedKind = "FontFile (Type1)";- } else if (dDict.containsKey(COSName.FONT_FILE2)) {- hasEmbedded = true;- embeddedKind = "FontFile2 (TrueType)";- } else if (dDict.containsKey(COSName.FONT_FILE3)) {- hasEmbedded = true;- COSBase ff3 = dDict.getDictionaryObject(COSName.FONT_FILE3);- if (ff3 instanceof COSStream) {- String ff3Subtype = ((COSStream) ff3).getNameAsString(COSName.SUBTYPE);- embeddedKind = "FontFile3 (" + ff3Subtype + ")";- } else {- embeddedKind = "FontFile3";- }- }- }- System.out.println(- " Font resource '"- + resourceName- + "': base='"- + baseFont- + "' subtype="- + subtype- + " hasEncoding="- + hasEncoding- + " hasToUnicode="- + hasToUnicode- + " embedded="- + hasEmbedded- + " ("- + embeddedKind- + ")");-- if (font instanceof PDType3Font) {- PDType3Font t3 = (PDType3Font) font;- COSDictionary charProcs = t3.getCharProcs();- int count = charProcs == null ? 0 : charProcs.size();- System.out.println(" Type3 CharProcs count = " + count);- if (charProcs != null) {- TreeSet<String> names = new TreeSet<>();- for (COSName k : charProcs.keySet()) names.add(k.getName());- System.out.println(" glyph names: " + names);- }- }- }-- private void dumpType3Glyph(PDType3Font font, int charcode) throws IOException {- String name = font.getEncoding() != null ? font.getEncoding().getName(charcode) : null;- System.out.println(" Type3 charcode " + charcode + " -> glyph name '" + name + "'");- PDType3CharProc proc = font.getCharProc(charcode);- if (proc == null) {- System.out.println(" (no CharProc for that charcode)");- return;- }- COSStream stream = proc.getCOSObject();- byte[] raw;- try (InputStream is = stream.createInputStream()) {- raw = is.readAllBytes();- }- System.out.println(" CharProc content stream (" + raw.length + " bytes):");- System.out.println("---");- System.out.println(new String(raw, StandardCharsets.ISO_8859_1));- System.out.println("---");- }-- /** Records every (font, charcode -> unicode) tuple seen on a page. */- static final class AllCharsScanner extends PDFStreamEngine {- final java.util.LinkedHashMap<PDFont, java.util.Map<Integer, String>> perFont =- new java.util.LinkedHashMap<>();-- AllCharsScanner() {- addOperator(new BeginText(this));- addOperator(new EndText(this));- addOperator(new SetFontAndSize(this));- addOperator(new SetTextHorizontalScaling(this));- addOperator(new SetTextLeading(this));- addOperator(new SetTextRenderingMode(this));- addOperator(new SetTextRise(this));- addOperator(new SetWordSpacing(this));- addOperator(new SetMatrix(this));- addOperator(new Save(this));- addOperator(new Restore(this));- addOperator(new Concatenate(this));- addOperator(new SetGraphicsStateParameters(this));- addOperator(new ShowText(this));- }-- @Override- protected void showText(byte[] string) throws IOException {- PDFont font = getGraphicsState().getTextState().getFont();- if (font == null) return;- var seen = perFont.computeIfAbsent(font, k -> new java.util.LinkedHashMap<>());- ByteArrayInputStream in = new ByteArrayInputStream(string);- while (in.available() > 0) {- int code;- try {- code = font.readCode(in);- } catch (IOException e) {- break;- }- String u;- try {- u = font.toUnicode(code);- } catch (RuntimeException e) {- u = null;- }- seen.putIfAbsent(code, u);- }- }- }-}diff --git a/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertPdfJsonControllerExtraTest.java b/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertPdfJsonControllerExtraTest.javadeleted file mode 100644index 6d36db1074..0000000000--- a/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertPdfJsonControllerExtraTest.java+++ /dev/null@@ -1,254 +0,0 @@-package stirling.software.SPDF.controller.api.converters;--import static org.assertj.core.api.Assertions.assertThat;-import static org.junit.jupiter.api.Assertions.assertThrows;-import static org.mockito.ArgumentMatchers.anyString;-import static org.mockito.Mockito.doThrow;-import static org.mockito.Mockito.never;-import static org.mockito.Mockito.verify;-import static org.mockito.Mockito.when;--import java.lang.reflect.Field;-import java.lang.reflect.Method;--import org.junit.jupiter.api.BeforeEach;-import org.junit.jupiter.api.DisplayName;-import org.junit.jupiter.api.Nested;-import org.junit.jupiter.api.Test;-import org.junit.jupiter.api.extension.ExtendWith;-import org.mockito.InjectMocks;-import org.mockito.Mock;-import org.mockito.junit.jupiter.MockitoExtension;-import org.mockito.junit.jupiter.MockitoSettings;-import org.mockito.quality.Strictness;--import stirling.software.SPDF.service.PdfJsonConversionService;-import stirling.software.common.service.JobOwnershipService;-import stirling.software.common.util.TempFileManager;--/**- * Coverage for the remaining {@link ConvertPdfJsonController} diagnostic helpers and the job-access- * guard on the GET endpoints. The conversion service boundary is mocked so nothing is rendered.- */-@ExtendWith(MockitoExtension.class)-@MockitoSettings(strictness = Strictness.LENIENT)-@DisplayName("ConvertPdfJsonController remaining branch coverage")-class ConvertPdfJsonControllerExtraTest {-- @Mock private PdfJsonConversionService pdfJsonConversionService;- @Mock private TempFileManager tempFileManager;- @Mock private JobOwnershipService jobOwnershipService;-- @InjectMocks private ConvertPdfJsonController controller;-- @BeforeEach- void setUp() throws Exception {- Field f = ConvertPdfJsonController.class.getDeclaredField("jobOwnershipService");- f.setAccessible(true);- f.set(controller, jobOwnershipService);- }-- private Object invoke(String name, Class<?>[] sig, Object... args) throws Exception {- Method m = ConvertPdfJsonController.class.getDeclaredMethod(name, sig);- m.setAccessible(true);- return m.invoke(controller, args);- }-- @Nested- @DisplayName("looksLikeBase64")- class LooksLikeBase64 {-- private boolean looksLikeBase64(String value) throws Exception {- return (boolean) invoke("looksLikeBase64", new Class<?>[] {String.class}, value);- }-- @Test- @DisplayName("short strings are never treated as base64")- void shortNotBase64() throws Exception {- assertThat(looksLikeBase64("short")).isFalse();- }-- @Test- @DisplayName("a long base64-like string is detected")- void longBase64Detected() throws Exception {- String b64 = "QUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVowMTIzNDU2Nzg5";- assertThat(looksLikeBase64(b64)).isTrue();- }-- @Test- @DisplayName("a long natural-language string is not base64")- void longProseNotBase64() throws Exception {- String prose = "this is a long sentence with spaces and punctuation, not base64!!";- assertThat(looksLikeBase64(prose)).isFalse();- }- }-- @Nested- @DisplayName("truncateForLog")- class TruncateForLog {-- private String truncate(String value) throws Exception {- return (String) invoke("truncateForLog", new Class<?>[] {String.class}, value);- }-- @Test- @DisplayName("short values are returned with whitespace normalised")- void shortNormalised() throws Exception {- assertThat(truncate("a\tb\nc")).isEqualTo("a b c");- }-- @Test- @DisplayName("long values are truncated with an ellipsis suffix")- void longTruncated() throws Exception {- String value = "x".repeat(100);- String result = truncate(value);- assertThat(result).endsWith("...");- assertThat(result).hasSize(67); // 64 chars + "..."- }- }-- @Nested- @DisplayName("debug/repeat-scan flag readers")- class FlagReaders {-- private boolean dumpEnabled() throws Exception {- return (boolean) invoke("isPdfJsonDebugDumpEnabled", new Class<?>[] {});- }-- private boolean repeatScanEnabled() throws Exception {- return (boolean) invoke("isPdfJsonRepeatScanEnabled", new Class<?>[] {});- }-- @Test- @DisplayName("dump flag reflects the system property")- void dumpFlagFromProperty() throws Exception {- String prev = System.getProperty("spdf.pdfjson.dump");- try {- System.clearProperty("spdf.pdfjson.dump");- assertThat(dumpEnabled()).isFalse();- System.setProperty("spdf.pdfjson.dump", "true");- assertThat(dumpEnabled()).isTrue();- } finally {- restore("spdf.pdfjson.dump", prev);- }- }-- @Test- @DisplayName("repeat-scan flag reflects the system property")- void repeatScanFromProperty() throws Exception {- String prev = System.getProperty("spdf.pdfjson.repeatScan");- try {- System.clearProperty("spdf.pdfjson.repeatScan");- assertThat(repeatScanEnabled()).isFalse();- System.setProperty("spdf.pdfjson.repeatScan", "true");- assertThat(repeatScanEnabled()).isTrue();- } finally {- restore("spdf.pdfjson.repeatScan", prev);- }- }-- private void restore(String key, String prev) {- if (prev == null) {- System.clearProperty(key);- } else {- System.setProperty(key, prev);- }- }- }-- @Nested- @DisplayName("logJsonResponse")- class LogJsonResponse {-- @Test- @DisplayName("a null path is logged without throwing")- void nullPathHandled() throws Exception {- // exercises the early null-path guard branch- invoke(- "logJsonResponse",- new Class<?>[] {String.class, java.nio.file.Path.class},- "x",- null);- }-- @Test- @DisplayName("happy path with no debug flags returns without reading the file")- void noFlagsNoRead() throws Exception {- String dumpPrev = System.getProperty("spdf.pdfjson.dump");- String scanPrev = System.getProperty("spdf.pdfjson.repeatScan");- try {- System.clearProperty("spdf.pdfjson.dump");- System.clearProperty("spdf.pdfjson.repeatScan");- // a non-existent path must not be read because all flags are off- java.nio.file.Path missing = java.nio.file.Path.of("does-not-exist-123.json");- invoke(- "logJsonResponse",- new Class<?>[] {String.class, java.nio.file.Path.class},- "label",- missing);- } finally {- if (dumpPrev != null) System.setProperty("spdf.pdfjson.dump", dumpPrev);- if (scanPrev != null) System.setProperty("spdf.pdfjson.repeatScan", scanPrev);- }- }- }-- @Nested- @DisplayName("GET endpoint job-access guard")- class JobAccessGuard {-- @Test- @DisplayName("extractSinglePage rejects an unauthorized job before doing work")- void singlePageRejected() {- doThrow(new SecurityException("denied"))- .when(jobOwnershipService)- .validateJobAccess("bad");-- assertThrows(SecurityException.class, () -> controller.extractSinglePage("bad", 1));- verifyNoConversion();- }-- @Test- @DisplayName("extractPageFonts rejects an unauthorized job before doing work")- void pageFontsRejected() {- doThrow(new SecurityException("denied"))- .when(jobOwnershipService)- .validateJobAccess("bad");-- assertThrows(SecurityException.class, () -> controller.extractPageFonts("bad", 2));- verifyNoConversion();- }-- @Test- @DisplayName("exportPartialPdf rejects an unauthorized job before doing work")- void exportPartialRejected() {- when(jobOwnershipService.validateJobAccess(anyString()))- .thenThrow(new SecurityException("denied"));-- assertThrows(- SecurityException.class,- () ->- controller.exportPartialPdf(- "bad",- new stirling.software.SPDF.model.json.PdfJsonDocument(),- "out.pdf"));- }-- private void verifyNoConversion() {- try {- verify(pdfJsonConversionService, never())- .extractSinglePage(- anyString(),- org.mockito.ArgumentMatchers.anyInt(),- org.mockito.ArgumentMatchers.any());- verify(pdfJsonConversionService, never())- .extractPageFonts(- anyString(),- org.mockito.ArgumentMatchers.anyInt(),- org.mockito.ArgumentMatchers.any());- } catch (Exception e) {- throw new AssertionError(e);- }- }- }-}diff --git a/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertPdfJsonControllerMoreTest.java b/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertPdfJsonControllerMoreTest.javadeleted file mode 100644index c809879360..0000000000--- a/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertPdfJsonControllerMoreTest.java+++ /dev/null@@ -1,606 +0,0 @@-package stirling.software.SPDF.controller.api.converters;--import static org.assertj.core.api.Assertions.assertThat;-import static org.junit.jupiter.api.Assertions.assertEquals;-import static org.junit.jupiter.api.Assertions.assertNotNull;-import static org.junit.jupiter.api.Assertions.assertThrows;-import static org.mockito.ArgumentMatchers.any;-import static org.mockito.ArgumentMatchers.anyInt;-import static org.mockito.ArgumentMatchers.anyString;-import static org.mockito.ArgumentMatchers.eq;-import static org.mockito.Mockito.doAnswer;-import static org.mockito.Mockito.doThrow;-import static org.mockito.Mockito.lenient;-import static org.mockito.Mockito.mock;-import static org.mockito.Mockito.never;-import static org.mockito.Mockito.verify;-import static org.mockito.Mockito.when;--import java.io.ByteArrayOutputStream;-import java.io.File;-import java.io.IOException;-import java.io.OutputStream;-import java.lang.reflect.Field;-import java.nio.file.Files;-import java.nio.file.Path;--import org.junit.jupiter.api.AfterEach;-import org.junit.jupiter.api.BeforeEach;-import org.junit.jupiter.api.DisplayName;-import org.junit.jupiter.api.Nested;-import org.junit.jupiter.api.Test;-import org.junit.jupiter.api.extension.ExtendWith;-import org.mockito.InjectMocks;-import org.mockito.Mock;-import org.mockito.junit.jupiter.MockitoExtension;-import org.mockito.junit.jupiter.MockitoSettings;-import org.mockito.quality.Strictness;-import org.springframework.core.io.Resource;-import org.springframework.http.HttpStatus;-import org.springframework.http.ResponseEntity;-import org.springframework.mock.web.MockMultipartFile;--import stirling.software.SPDF.model.json.PdfJsonDocument;-import stirling.software.SPDF.model.json.PdfJsonMetadata;-import stirling.software.SPDF.service.PdfJsonConversionService;-import stirling.software.common.model.api.GeneralFile;-import stirling.software.common.model.api.PDFFile;-import stirling.software.common.service.JobOwnershipService;-import stirling.software.common.util.TempFile;-import stirling.software.common.util.TempFileManager;--@ExtendWith(MockitoExtension.class)-@MockitoSettings(strictness = Strictness.LENIENT)-@DisplayName("ConvertPdfJsonController additional branch coverage")-class ConvertPdfJsonControllerMoreTest {-- @Mock private PdfJsonConversionService pdfJsonConversionService;- @Mock private TempFileManager tempFileManager;- @Mock private JobOwnershipService jobOwnershipService;-- @InjectMocks private ConvertPdfJsonController controller;-- private final java.util.List<TempFile> createdTempFiles = new java.util.ArrayList<>();-- @BeforeEach- void setUp() throws Exception {- // @InjectMocks uses the @RequiredArgsConstructor, so the @Autowired field is not- // auto-injected; wire the JobOwnershipService mock in by reflection.- setJobOwnershipService(jobOwnershipService);-- when(tempFileManager.createManagedTempFile(anyString()))- .thenAnswer(- inv -> {- File f =- Files.createTempFile("more-test", inv.<String>getArgument(0))- .toFile();- TempFile tf = mock(TempFile.class);- lenient().when(tf.getFile()).thenReturn(f);- lenient().when(tf.getPath()).thenReturn(f.toPath());- createdTempFiles.add(tf);- return tf;- });- }-- private void setJobOwnershipService(JobOwnershipService service) throws Exception {- Field f = ConvertPdfJsonController.class.getDeclaredField("jobOwnershipService");- f.setAccessible(true);- f.set(controller, service);- }-- @AfterEach- void tearDown() {- for (TempFile tf : createdTempFiles) {- try {- if (tf.getFile() != null) {- tf.getFile().delete();- }- } catch (Exception ignored) {- // best-effort cleanup- }- }- createdTempFiles.clear();- }-- private static byte[] drainBody(ResponseEntity<Resource> response) throws IOException {- ByteArrayOutputStream baos = new ByteArrayOutputStream();- try (java.io.InputStream in = response.getBody().getInputStream()) {- in.transferTo(baos);- }- return baos.toByteArray();- }-- // Disable the @Autowired(required=false) JobOwnershipService for no-auth code paths.- private void clearJobOwnershipService() throws Exception {- setJobOwnershipService(null);- }-- @Nested- @DisplayName("convertPdfToJson filename handling")- class ConvertPdfToJsonFilename {-- @Test- @DisplayName("Null original filename falls back to document.json")- void nullOriginalFilename() throws Exception {- MockMultipartFile pdfFile =- new MockMultipartFile("fileInput", null, "application/pdf", "x".getBytes());- PDFFile request = new PDFFile();- request.setFileInput(pdfFile);-- doAnswer(writeBytes(2, "{}".getBytes()))- .when(pdfJsonConversionService)- .convertPdfToJson(eq(pdfFile), eq(false), any(OutputStream.class));-- ResponseEntity<Resource> response = controller.convertPdfToJson(request, false);-- assertEquals(HttpStatus.OK, response.getStatusCode());- String cd = response.getHeaders().getFirst("Content-Disposition");- assertThat(cd).contains("document.json");- }-- @Test- @DisplayName("Blank original filename falls back to document.json")- void blankOriginalFilename() throws Exception {- MockMultipartFile pdfFile =- new MockMultipartFile("fileInput", " ", "application/pdf", "x".getBytes());- PDFFile request = new PDFFile();- request.setFileInput(pdfFile);-- doAnswer(writeBytes(2, "{}".getBytes()))- .when(pdfJsonConversionService)- .convertPdfToJson(eq(pdfFile), eq(false), any(OutputStream.class));-- ResponseEntity<Resource> response = controller.convertPdfToJson(request, false);-- assertThat(response.getHeaders().getFirst("Content-Disposition"))- .contains("document.json");- }-- @Test- @DisplayName("Named file strips extension and appends .json")- void namedFileStripsExtension() throws Exception {- MockMultipartFile pdfFile =- new MockMultipartFile(- "fileInput", "report.final.pdf", "application/pdf", "x".getBytes());- PDFFile request = new PDFFile();- request.setFileInput(pdfFile);-- doAnswer(writeBytes(2, "{}".getBytes()))- .when(pdfJsonConversionService)- .convertPdfToJson(eq(pdfFile), eq(false), any(OutputStream.class));-- ResponseEntity<Resource> response = controller.convertPdfToJson(request, false);-- assertThat(response.getHeaders().getFirst("Content-Disposition"))- .contains("report.final.json");- }-- @Test- @DisplayName("Service exception closes temp file and propagates")- void serviceExceptionClosesTempFile() throws Exception {- MockMultipartFile pdfFile =- new MockMultipartFile(- "fileInput", "doc.pdf", "application/pdf", "x".getBytes());- PDFFile request = new PDFFile();- request.setFileInput(pdfFile);-- doThrow(new IllegalStateException("boom"))- .when(pdfJsonConversionService)- .convertPdfToJson(eq(pdfFile), eq(false), any(OutputStream.class));-- assertThrows(- IllegalStateException.class, () -> controller.convertPdfToJson(request, false));- verify(createdTempFiles.get(0)).close();- }- }-- @Nested- @DisplayName("convertJsonToPdf filename handling")- class ConvertJsonToPdfFilename {-- @Test- @DisplayName("Null original filename falls back to document.pdf")- void nullOriginalFilename() throws Exception {- MockMultipartFile jsonFile =- new MockMultipartFile("fileInput", null, "application/json", "{}".getBytes());- GeneralFile request = new GeneralFile();- request.setFileInput(jsonFile);-- doAnswer(writeBytes(1, "pdf".getBytes()))- .when(pdfJsonConversionService)- .convertJsonToPdf(eq(jsonFile), any(OutputStream.class));-- ResponseEntity<Resource> response = controller.convertJsonToPdf(request);-- assertThat(response.getHeaders().getFirst("Content-Disposition"))- .contains("document.pdf");- }-- @Test- @DisplayName("Filename already ending in .pdf is preserved")- void filenameAlreadyPdf() throws Exception {- // toSimpleFileName keeps base name; extension pattern strips the trailing .pdf,- // so a base name that itself ends in .pdf exercises the endsWith branch.- MockMultipartFile jsonFile =- new MockMultipartFile(- "fileInput", "weird.pdf.json", "application/json", "{}".getBytes());- GeneralFile request = new GeneralFile();- request.setFileInput(jsonFile);-- doAnswer(writeBytes(1, "pdf".getBytes()))- .when(pdfJsonConversionService)- .convertJsonToPdf(eq(jsonFile), any(OutputStream.class));-- ResponseEntity<Resource> response = controller.convertJsonToPdf(request);-- assertThat(response.getHeaders().getFirst("Content-Disposition")).contains("weird.pdf");- }-- @Test- @DisplayName("Service exception closes temp file and propagates")- void serviceExceptionClosesTempFile() throws Exception {- MockMultipartFile jsonFile =- new MockMultipartFile(- "fileInput", "doc.json", "application/json", "{}".getBytes());- GeneralFile request = new GeneralFile();- request.setFileInput(jsonFile);-- doThrow(new IllegalStateException("boom"))- .when(pdfJsonConversionService)- .convertJsonToPdf(eq(jsonFile), any(OutputStream.class));-- assertThrows(IllegalStateException.class, () -> controller.convertJsonToPdf(request));- verify(createdTempFiles.get(0)).close();- }- }-- @Nested- @DisplayName("extractPdfMetadata job-key scoping")- class ExtractMetadataScoping {-- @Test- @DisplayName("Uses scoped job key when JobOwnershipService present")- void usesScopedKey() throws Exception {- when(jobOwnershipService.createScopedJobKey(anyString())).thenReturn("user:scoped-id");- MockMultipartFile pdfFile =- new MockMultipartFile(- "fileInput", "doc.pdf", "application/pdf", "x".getBytes());- PDFFile request = new PDFFile();- request.setFileInput(pdfFile);-- doAnswer(writeBytes(2, "{}".getBytes()))- .when(pdfJsonConversionService)- .extractDocumentMetadata(- eq(pdfFile), eq("user:scoped-id"), any(OutputStream.class));-- ResponseEntity<Resource> response = controller.extractPdfMetadata(request);-- assertEquals("user:scoped-id", response.getHeaders().getFirst("X-Job-Id"));- verify(jobOwnershipService).createScopedJobKey(anyString());- }-- @Test- @DisplayName("Uses raw job key when no JobOwnershipService")- void usesRawKeyWhenNoService() throws Exception {- clearJobOwnershipService();- MockMultipartFile pdfFile =- new MockMultipartFile(- "fileInput", "doc.pdf", "application/pdf", "x".getBytes());- PDFFile request = new PDFFile();- request.setFileInput(pdfFile);-- doAnswer(writeBytes(2, "{}".getBytes()))- .when(pdfJsonConversionService)- .extractDocumentMetadata(eq(pdfFile), anyString(), any(OutputStream.class));-- ResponseEntity<Resource> response = controller.extractPdfMetadata(request);-- assertNotNull(response.getHeaders().getFirst("X-Job-Id"));- }-- @Test- @DisplayName("Service exception closes temp file and propagates")- void serviceExceptionClosesTempFile() throws Exception {- when(jobOwnershipService.createScopedJobKey(anyString())).thenReturn("k");- MockMultipartFile pdfFile =- new MockMultipartFile(- "fileInput", "doc.pdf", "application/pdf", "x".getBytes());- PDFFile request = new PDFFile();- request.setFileInput(pdfFile);-- doThrow(new IllegalStateException("boom"))- .when(pdfJsonConversionService)- .extractDocumentMetadata(eq(pdfFile), anyString(), any(OutputStream.class));-- assertThrows(IllegalStateException.class, () -> controller.extractPdfMetadata(request));- verify(createdTempFiles.get(0)).close();- }- }-- @Nested- @DisplayName("exportPartialPdf")- class ExportPartialPdf {-- @Test- @DisplayName("Null document throws")- void nullDocumentThrows() {- assertThrows(- Exception.class, () -> controller.exportPartialPdf("job", null, "out.pdf"));- }-- @Test- @DisplayName("Explicit filename param wins over metadata title")- void filenameParamWins() throws Exception {- when(jobOwnershipService.validateJobAccess(anyString())).thenReturn(true);- PdfJsonDocument doc = new PdfJsonDocument();- doc.setMetadata(PdfJsonMetadata.builder().title("titleName").build());-- doAnswer(writeBytes(2, "pdf".getBytes()))- .when(pdfJsonConversionService)- .exportUpdatedPages(eq("job"), eq(doc), any(OutputStream.class));-- ResponseEntity<Resource> response =- controller.exportPartialPdf("job", doc, "custom.pdf");-- assertThat(response.getHeaders().getFirst("Content-Disposition"))- .contains("custom.pdf");- }-- @Test- @DisplayName("Falls back to metadata title when filename blank")- void fallbackToMetadataTitle() throws Exception {- when(jobOwnershipService.validateJobAccess(anyString())).thenReturn(true);- PdfJsonDocument doc = new PdfJsonDocument();- doc.setMetadata(PdfJsonMetadata.builder().title("MyTitle").build());-- doAnswer(writeBytes(2, "pdf".getBytes()))- .when(pdfJsonConversionService)- .exportUpdatedPages(eq("job"), eq(doc), any(OutputStream.class));-- ResponseEntity<Resource> response = controller.exportPartialPdf("job", doc, " ");-- assertThat(response.getHeaders().getFirst("Content-Disposition"))- .contains("MyTitle.pdf");- }-- @Test- @DisplayName("Falls back to document when title null/blank and no filename")- void fallbackToDocumentName() throws Exception {- when(jobOwnershipService.validateJobAccess(anyString())).thenReturn(true);- PdfJsonDocument doc = new PdfJsonDocument();- doc.setMetadata(PdfJsonMetadata.builder().title(" ").build());-- doAnswer(writeBytes(2, "pdf".getBytes()))- .when(pdfJsonConversionService)- .exportUpdatedPages(eq("job"), eq(doc), any(OutputStream.class));-- ResponseEntity<Resource> response = controller.exportPartialPdf("job", doc, null);-- assertThat(response.getHeaders().getFirst("Content-Disposition"))- .contains("document.pdf");- }-- @Test- @DisplayName("Null metadata falls back to document name")- void nullMetadataFallback() throws Exception {- when(jobOwnershipService.validateJobAccess(anyString())).thenReturn(true);- PdfJsonDocument doc = new PdfJsonDocument();- doc.setMetadata(null);-- doAnswer(writeBytes(2, "pdf".getBytes()))- .when(pdfJsonConversionService)- .exportUpdatedPages(eq("job"), eq(doc), any(OutputStream.class));-- ResponseEntity<Resource> response = controller.exportPartialPdf("job", doc, null);-- assertThat(response.getHeaders().getFirst("Content-Disposition"))- .contains("document.pdf");- }-- @Test- @DisplayName("Service exception closes temp file and propagates")- void serviceExceptionClosesTempFile() throws Exception {- when(jobOwnershipService.validateJobAccess(anyString())).thenReturn(true);- PdfJsonDocument doc = new PdfJsonDocument();-- doThrow(new IllegalStateException("boom"))- .when(pdfJsonConversionService)- .exportUpdatedPages(- anyString(), any(PdfJsonDocument.class), any(OutputStream.class));-- assertThrows(- IllegalStateException.class,- () -> controller.exportPartialPdf("job", doc, "out.pdf"));- verify(createdTempFiles.get(0)).close();- }- }-- @Nested- @DisplayName("extractSinglePage and extractPageFonts errors")- class GetPageErrors {-- @Test- @DisplayName("extractSinglePage service exception closes temp file")- void singlePageException() throws Exception {- when(jobOwnershipService.validateJobAccess(anyString())).thenReturn(true);- doThrow(new IllegalStateException("boom"))- .when(pdfJsonConversionService)- .extractSinglePage(anyString(), anyInt(), any(OutputStream.class));-- assertThrows(IllegalStateException.class, () -> controller.extractSinglePage("job", 1));- verify(createdTempFiles.get(0)).close();- }-- @Test- @DisplayName("extractPageFonts service exception closes temp file")- void pageFontsException() throws Exception {- when(jobOwnershipService.validateJobAccess(anyString())).thenReturn(true);- doThrow(new IllegalStateException("boom"))- .when(pdfJsonConversionService)- .extractPageFonts(anyString(), anyInt(), any(OutputStream.class));-- assertThrows(IllegalStateException.class, () -> controller.extractPageFonts("job", 1));- verify(createdTempFiles.get(0)).close();- }-- @Test- @DisplayName("Page docName carries page number")- void singlePageDocName() throws Exception {- when(jobOwnershipService.validateJobAccess(anyString())).thenReturn(true);- doAnswer(writeBytes(2, "{}".getBytes()))- .when(pdfJsonConversionService)- .extractSinglePage(eq("job"), eq(7), any(OutputStream.class));-- ResponseEntity<Resource> response = controller.extractSinglePage("job", 7);-- assertThat(response.getHeaders().getFirst("Content-Disposition"))- .contains("page_7.json");- }- }-- @Nested- @DisplayName("validateJobAccess and clearCache delegation")- class JobAccessDelegation {-- @Test- @DisplayName("clearCache validates and delegates when service present")- void clearCacheWithService() {- when(jobOwnershipService.validateJobAccess(anyString())).thenReturn(true);-- ResponseEntity<Void> response = controller.clearCache("job-1");-- assertEquals(HttpStatus.OK, response.getStatusCode());- verify(jobOwnershipService).validateJobAccess("job-1");- verify(pdfJsonConversionService).clearCachedDocument("job-1");- }-- @Test- @DisplayName("clearCache skips validation when no service")- void clearCacheNoService() throws Exception {- clearJobOwnershipService();-- ResponseEntity<Void> response = controller.clearCache("job-2");-- assertEquals(HttpStatus.OK, response.getStatusCode());- verify(pdfJsonConversionService).clearCachedDocument("job-2");- verify(jobOwnershipService, never()).validateJobAccess(anyString());- }-- @Test- @DisplayName("validateJobAccess propagates SecurityException from service")- void validateThrows() {- doThrow(new SecurityException("denied"))- .when(jobOwnershipService)- .validateJobAccess("bad");-- assertThrows(SecurityException.class, () -> controller.clearCache("bad"));- verify(pdfJsonConversionService, never()).clearCachedDocument(anyString());- }- }-- @Nested- @DisplayName("logJsonResponse diagnostic paths")- class LogJsonResponseDiagnostics {-- @Test- @DisplayName("Debug dump writes a copy to configured dir")- void debugDumpWritesCopy(@org.junit.jupiter.api.io.TempDir Path dumpDir) throws Exception {- String previous = System.getProperty("spdf.pdfjson.dump");- System.setProperty("spdf.pdfjson.dump", "true");- String prevDir = System.getProperty("java.io.tmpdir");- // SPDF_PDFJSON_DUMP_DIR env may be unset; controller falls back to java.io.tmpdir.- System.setProperty("java.io.tmpdir", dumpDir.toString());- try {- MockMultipartFile pdfFile =- new MockMultipartFile(- "fileInput", "doc.pdf", "application/pdf", "x".getBytes());- PDFFile request = new PDFFile();- request.setFileInput(pdfFile);-- doAnswer(writeBytes(2, "{\"k\":\"value-string-here\"}".getBytes()))- .when(pdfJsonConversionService)- .convertPdfToJson(eq(pdfFile), eq(false), any(OutputStream.class));-- ResponseEntity<Resource> response = controller.convertPdfToJson(request, false);- assertEquals(HttpStatus.OK, response.getStatusCode());-- try (var stream = Files.list(dumpDir)) {- boolean dumped =- stream.anyMatch(p -> p.getFileName().toString().startsWith("pdfjson_"));- assertThat(dumped).isTrue();- }- } finally {- restoreProp("spdf.pdfjson.dump", previous);- restoreProp("java.io.tmpdir", prevDir);- }- }-- @Test- @DisplayName("Repeat scan runs without error on repeated strings")- void repeatScanRuns() throws Exception {- String previous = System.getProperty("spdf.pdfjson.repeatScan");- System.setProperty("spdf.pdfjson.repeatScan", "true");- try {- MockMultipartFile pdfFile =- new MockMultipartFile(- "fileInput", "doc.pdf", "application/pdf", "x".getBytes());- PDFFile request = new PDFFile();- request.setFileInput(pdfFile);-- // Two repeated >=12 char strings plus a long base64-like one to exercise filters.- String json =- "{\"a\":\"repeated-string-value\",\"b\":\"repeated-string-value\","- + "\"c\":\"QUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVowMTIzNDU2Nzg5\"}";- doAnswer(writeBytes(2, json.getBytes()))- .when(pdfJsonConversionService)- .convertPdfToJson(eq(pdfFile), eq(false), any(OutputStream.class));-- ResponseEntity<Resource> response = controller.convertPdfToJson(request, false);- assertEquals(HttpStatus.OK, response.getStatusCode());- assertThat(drainBody(response)).isNotEmpty();- } finally {- restoreProp("spdf.pdfjson.repeatScan", previous);- }- }-- @Test- @DisplayName("Repeat scan handles no repeated strings")- void repeatScanNoRepeats() throws Exception {- String previous = System.getProperty("spdf.pdfjson.repeatScan");- System.setProperty("spdf.pdfjson.repeatScan", "true");- try {- MockMultipartFile pdfFile =- new MockMultipartFile(- "fileInput", "doc.pdf", "application/pdf", "x".getBytes());- PDFFile request = new PDFFile();- request.setFileInput(pdfFile);-- String json = "{\"only-key-here-unique\":\"only-value-here-unique\"}";- doAnswer(writeBytes(2, json.getBytes()))- .when(pdfJsonConversionService)- .convertPdfToJson(eq(pdfFile), eq(false), any(OutputStream.class));-- ResponseEntity<Resource> response = controller.convertPdfToJson(request, false);- assertEquals(HttpStatus.OK, response.getStatusCode());- } finally {- restoreProp("spdf.pdfjson.repeatScan", previous);- }- }- }-- private static org.mockito.stubbing.Answer<Object> writeBytes(int argIndex, byte[] data) {- return inv -> {- OutputStream os = inv.getArgument(argIndex, OutputStream.class);- os.write(data);- return null;- };- }-- private static void restoreProp(String key, String previous) {- if (previous == null) {- System.clearProperty(key);- } else {- System.setProperty(key, previous);- }- }-}diff --git a/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertPdfJsonControllerTest.java b/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertPdfJsonControllerTest.javadeleted file mode 100644index a2427538bd..0000000000--- a/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertPdfJsonControllerTest.java+++ /dev/null@@ -1,243 +0,0 @@-package stirling.software.SPDF.controller.api.converters;--import static org.junit.jupiter.api.Assertions.assertEquals;-import static org.junit.jupiter.api.Assertions.assertNotNull;-import static org.junit.jupiter.api.Assertions.assertThrows;-import static org.mockito.ArgumentMatchers.any;-import static org.mockito.ArgumentMatchers.anyInt;-import static org.mockito.ArgumentMatchers.anyString;-import static org.mockito.ArgumentMatchers.eq;-import static org.mockito.Mockito.doAnswer;-import static org.mockito.Mockito.lenient;-import static org.mockito.Mockito.mock;-import static org.mockito.Mockito.verify;--import java.io.ByteArrayOutputStream;-import java.io.File;-import java.io.IOException;-import java.io.OutputStream;-import java.nio.file.Files;--import org.junit.jupiter.api.BeforeEach;-import org.junit.jupiter.api.Test;-import org.junit.jupiter.api.extension.ExtendWith;-import org.mockito.InjectMocks;-import org.mockito.Mock;-import org.mockito.junit.jupiter.MockitoExtension;-import org.springframework.core.io.Resource;-import org.springframework.http.HttpStatus;-import org.springframework.http.MediaType;-import org.springframework.http.ResponseEntity;-import org.springframework.mock.web.MockMultipartFile;--import stirling.software.SPDF.service.PdfJsonConversionService;-import stirling.software.common.model.api.GeneralFile;-import stirling.software.common.model.api.PDFFile;-import stirling.software.common.util.TempFile;-import stirling.software.common.util.TempFileManager;--@ExtendWith(MockitoExtension.class)-class ConvertPdfJsonControllerTest {-- @Mock private PdfJsonConversionService pdfJsonConversionService;- @Mock private TempFileManager tempFileManager;-- @InjectMocks private ConvertPdfJsonController controller;-- @BeforeEach- void setUp() throws Exception {- lenient()- .when(tempFileManager.createManagedTempFile(anyString()))- .thenAnswer(- inv -> {- File f =- Files.createTempFile("test", inv.<String>getArgument(0))- .toFile();- TempFile tf = mock(TempFile.class);- lenient().when(tf.getFile()).thenReturn(f);- lenient().when(tf.getPath()).thenReturn(f.toPath());- return tf;- });- }-- private static byte[] drainBody(ResponseEntity<Resource> response) throws IOException {- ByteArrayOutputStream baos = new ByteArrayOutputStream();- try (java.io.InputStream in = response.getBody().getInputStream()) {- in.transferTo(baos);- }- return baos.toByteArray();- }-- @Test- void convertPdfToJson_nullFileInputThrows() {- PDFFile request = new PDFFile();- request.setFileInput(null);-- assertThrows(Exception.class, () -> controller.convertPdfToJson(request, false));- }-- @Test- void convertPdfToJson_success() throws Exception {- byte[] jsonBytes = "{\"pages\":[]}".getBytes();- MockMultipartFile pdfFile =- new MockMultipartFile(- "fileInput", "doc.pdf", "application/pdf", "content".getBytes());- PDFFile request = new PDFFile();- request.setFileInput(pdfFile);-- // Service writes directly to the OutputStream passed by the controller- doAnswer(- inv -> {- OutputStream os = inv.getArgument(2, OutputStream.class);- os.write(jsonBytes);- return null;- })- .when(pdfJsonConversionService)- .convertPdfToJson(eq(pdfFile), eq(false), any(OutputStream.class));-- ResponseEntity<Resource> response = controller.convertPdfToJson(request, false);-- assertEquals(HttpStatus.OK, response.getStatusCode());- assertNotNull(response.getBody());- }-- @Test- void convertPdfToJson_lightweightMode() throws Exception {- byte[] jsonBytes = "{\"pages\":[]}".getBytes();- MockMultipartFile pdfFile =- new MockMultipartFile(- "fileInput", "doc.pdf", "application/pdf", "content".getBytes());- PDFFile request = new PDFFile();- request.setFileInput(pdfFile);-- doAnswer(- inv -> {- OutputStream os = inv.getArgument(2, OutputStream.class);- os.write(jsonBytes);- return null;- })- .when(pdfJsonConversionService)- .convertPdfToJson(eq(pdfFile), eq(true), any(OutputStream.class));-- ResponseEntity<Resource> response = controller.convertPdfToJson(request, true);-- assertEquals(HttpStatus.OK, response.getStatusCode());- verify(pdfJsonConversionService)- .convertPdfToJson(eq(pdfFile), eq(true), any(OutputStream.class));- }-- @Test- void convertJsonToPdf_nullFileInputThrows() {- GeneralFile request = new GeneralFile();- request.setFileInput(null);-- assertThrows(Exception.class, () -> controller.convertJsonToPdf(request));- }-- @Test- void convertJsonToPdf_success() throws Exception {- byte[] pdfBytes = "pdf-content".getBytes();- MockMultipartFile jsonFile =- new MockMultipartFile(- "fileInput", "doc.json", "application/json", "{\"pages\":[]}".getBytes());- GeneralFile request = new GeneralFile();- request.setFileInput(jsonFile);-- doAnswer(- inv -> {- OutputStream os = inv.getArgument(1, OutputStream.class);- os.write(pdfBytes);- return null;- })- .when(pdfJsonConversionService)- .convertJsonToPdf(eq(jsonFile), any(OutputStream.class));-- ResponseEntity<Resource> response = controller.convertJsonToPdf(request);-- assertEquals(HttpStatus.OK, response.getStatusCode());- assertNotNull(response.getBody());- }-- @Test- void extractPdfMetadata_nullFileInputThrows() {- PDFFile request = new PDFFile();- request.setFileInput(null);-- assertThrows(Exception.class, () -> controller.extractPdfMetadata(request));- }-- @Test- void extractPdfMetadata_success() throws Exception {- byte[] jsonBytes = "{\"metadata\":{}}".getBytes();- MockMultipartFile pdfFile =- new MockMultipartFile(- "fileInput", "doc.pdf", "application/pdf", "content".getBytes());- PDFFile request = new PDFFile();- request.setFileInput(pdfFile);-- doAnswer(- inv -> {- OutputStream os = inv.getArgument(2, OutputStream.class);- os.write(jsonBytes);- return null;- })- .when(pdfJsonConversionService)- .extractDocumentMetadata(eq(pdfFile), any(String.class), any(OutputStream.class));-- ResponseEntity<Resource> response = controller.extractPdfMetadata(request);-- assertEquals(HttpStatus.OK, response.getStatusCode());- assertEquals(MediaType.APPLICATION_JSON, response.getHeaders().getContentType());- assertNotNull(response.getHeaders().getFirst("X-Job-Id"));- }-- @Test- void clearCache_success() {- String jobId = "test-job-id";-- ResponseEntity<Void> response = controller.clearCache(jobId);-- assertEquals(HttpStatus.OK, response.getStatusCode());- verify(pdfJsonConversionService).clearCachedDocument(jobId);- }-- @Test- void extractSinglePage_success() throws Exception {- byte[] jsonBytes = "{\"content\":[]}".getBytes();- String jobId = "test-job-id";-- doAnswer(- inv -> {- OutputStream os = inv.getArgument(2, OutputStream.class);- os.write(jsonBytes);- return null;- })- .when(pdfJsonConversionService)- .extractSinglePage(eq(jobId), anyInt(), any(OutputStream.class));-- ResponseEntity<Resource> response = controller.extractSinglePage(jobId, 1);-- assertEquals(HttpStatus.OK, response.getStatusCode());- assertNotNull(response.getBody());- }-- @Test- void extractPageFonts_success() throws Exception {- byte[] jsonBytes = "{\"fonts\":[]}".getBytes();- String jobId = "test-job-id";-- doAnswer(- inv -> {- OutputStream os = inv.getArgument(2, OutputStream.class);- os.write(jsonBytes);- return null;- })- .when(pdfJsonConversionService)- .extractPageFonts(eq(jobId), anyInt(), any(OutputStream.class));-- ResponseEntity<Resource> response = controller.extractPageFonts(jobId, 1);-- assertEquals(HttpStatus.OK, response.getStatusCode());- assertNotNull(response.getBody());- }-}diff --git a/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertPdfJsonExceptionHandlerTest.java b/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertPdfJsonExceptionHandlerTest.javadeleted file mode 100644index ed4c5a13e9..0000000000--- a/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertPdfJsonExceptionHandlerTest.java+++ /dev/null@@ -1,103 +0,0 @@-package stirling.software.SPDF.controller.api.converters;--import static org.assertj.core.api.Assertions.assertThat;-import static org.mockito.ArgumentMatchers.any;--import org.junit.jupiter.api.DisplayName;-import org.junit.jupiter.api.Nested;-import org.junit.jupiter.api.Test;-import org.mockito.Mockito;-import org.springframework.http.HttpStatus;-import org.springframework.http.MediaType;-import org.springframework.http.ResponseEntity;--import stirling.software.SPDF.exception.CacheUnavailableException;--import tools.jackson.databind.ObjectMapper;--/**- * Unit tests for {@link ConvertPdfJsonExceptionHandler}. A real ObjectMapper exercises the happy- * path; a throwing mock drives the serialization-failure fallback branches.- */-@DisplayName("ConvertPdfJsonExceptionHandler")-class ConvertPdfJsonExceptionHandlerTest {-- @Nested- @DisplayName("handleCacheUnavailable - success")- class Success {-- @Test- @DisplayName("serializes a 410 GONE JSON body with the error details")- void serializesGoneResponse() {- ConvertPdfJsonExceptionHandler handler =- new ConvertPdfJsonExceptionHandler(new ObjectMapper());-- ResponseEntity<byte[]> response =- handler.handleCacheUnavailable(new CacheUnavailableException("cache is gone"));-- assertThat(response.getStatusCode()).isEqualTo(HttpStatus.GONE);- assertThat(response.getHeaders().getContentType())- .isEqualTo(MediaType.APPLICATION_JSON);- String json = new String(response.getBody());- assertThat(json).contains("cache_unavailable");- assertThat(json).contains("reupload");- assertThat(json).contains("cache is gone");- }-- @Test- @DisplayName("tolerates a null exception message")- void toleratesNullMessage() {- ConvertPdfJsonExceptionHandler handler =- new ConvertPdfJsonExceptionHandler(new ObjectMapper());-- ResponseEntity<byte[]> response =- handler.handleCacheUnavailable(new CacheUnavailableException(null));-- assertThat(response.getStatusCode()).isEqualTo(HttpStatus.GONE);- assertThat(response.getBody()).isNotEmpty();- }- }-- @Nested- @DisplayName("handleCacheUnavailable - fallback")- class Fallback {-- @Test- @DisplayName("uses the literal JSON fallback when every serialization attempt fails")- void literalFallbackWhenAllSerializationFails() {- ObjectMapper mapper = Mockito.mock(ObjectMapper.class);- // Both the primary and the secondary writeValueAsBytes calls fail.- Mockito.when(mapper.writeValueAsBytes(any())).thenThrow(new RuntimeException("boom"));- ConvertPdfJsonExceptionHandler handler = new ConvertPdfJsonExceptionHandler(mapper);-- ResponseEntity<byte[]> response =- handler.handleCacheUnavailable(new CacheUnavailableException("nope"));-- assertThat(response.getStatusCode()).isEqualTo(HttpStatus.GONE);- assertThat(response.getHeaders().getContentType())- .isEqualTo(MediaType.APPLICATION_JSON);- // Last-ditch hand-written JSON literal.- String json = new String(response.getBody());- assertThat(json).contains("cache_unavailable");- assertThat(json).contains("Cache unavailable");- }-- @Test- @DisplayName("recovers via the second serialization attempt when only the first fails")- void secondAttemptSucceeds() {- ObjectMapper mapper = Mockito.mock(ObjectMapper.class);- byte[] fallbackJson = "{\"error\":\"cache_unavailable\"}".getBytes();- // First call throws, second returns serialized bytes.- Mockito.when(mapper.writeValueAsBytes(any()))- .thenThrow(new RuntimeException("first fails"))- .thenReturn(fallbackJson);- ConvertPdfJsonExceptionHandler handler = new ConvertPdfJsonExceptionHandler(mapper);-- ResponseEntity<byte[]> response =- handler.handleCacheUnavailable(new CacheUnavailableException("retry"));-- assertThat(response.getStatusCode()).isEqualTo(HttpStatus.GONE);- assertThat(response.getBody()).isEqualTo(fallbackJson);- }- }-}diff --git a/app/core/src/test/java/stirling/software/SPDF/controller/api/security/RedactControllerMoreTest.java b/app/core/src/test/java/stirling/software/SPDF/controller/api/security/RedactControllerMoreTest.javaindex e07b5310ae..a5f5c9ef9f 100644--- a/app/core/src/test/java/stirling/software/SPDF/controller/api/security/RedactControllerMoreTest.java+++ b/app/core/src/test/java/stirling/software/SPDF/controller/api/security/RedactControllerMoreTest.java@@ -132,8 +132,7 @@ class RedactControllerMoreTest {}private PDFont helvetica(PDDocument doc) throws IOException {- try (InputStream is =- getClass().getResourceAsStream("/type3/library/fonts/dejavu/DejaVuSans.ttf")) {+ try (InputStream is = getClass().getResourceAsStream("/static/fonts/DejaVuSans.ttf")) {if (is != null) {return PDType0Font.load(doc, is);}diff --git a/app/core/src/test/java/stirling/software/SPDF/controller/api/security/RedactControllerTest.java b/app/core/src/test/java/stirling/software/SPDF/controller/api/security/RedactControllerTest.javaindex 759ad135e4..3062c8f0c2 100644--- a/app/core/src/test/java/stirling/software/SPDF/controller/api/security/RedactControllerTest.java+++ b/app/core/src/test/java/stirling/software/SPDF/controller/api/security/RedactControllerTest.java@@ -99,8 +99,7 @@ class RedactControllerTest {private static PDFont helvetica(PDDocument doc) throws IOException {try (InputStream is =- RedactControllerTest.class.getResourceAsStream(- "/type3/library/fonts/dejavu/DejaVuSans.ttf")) {+ RedactControllerTest.class.getResourceAsStream("/static/fonts/DejaVuSans.ttf")) {if (is != null) {return PDType0Font.load(doc, is);}diff --git a/app/core/src/test/java/stirling/software/SPDF/controller/api/security/RedactExecuteServiceMoreTest.java b/app/core/src/test/java/stirling/software/SPDF/controller/api/security/RedactExecuteServiceMoreTest.javaindex 9e98a003ee..b74815a3d4 100644--- a/app/core/src/test/java/stirling/software/SPDF/controller/api/security/RedactExecuteServiceMoreTest.java+++ b/app/core/src/test/java/stirling/software/SPDF/controller/api/security/RedactExecuteServiceMoreTest.java@@ -135,8 +135,7 @@ class RedactExecuteServiceMoreTest {}private PDFont helvetica(PDDocument doc) throws IOException {- try (InputStream is =- getClass().getResourceAsStream("/type3/library/fonts/dejavu/DejaVuSans.ttf")) {+ try (InputStream is = getClass().getResourceAsStream("/static/fonts/DejaVuSans.ttf")) {if (is != null) {return PDType0Font.load(doc, is);}diff --git a/app/core/src/test/java/stirling/software/SPDF/controller/api/security/RedactExecuteServiceTest.java b/app/core/src/test/java/stirling/software/SPDF/controller/api/security/RedactExecuteServiceTest.javaindex 9d2f50a5e4..5d45cad943 100644--- a/app/core/src/test/java/stirling/software/SPDF/controller/api/security/RedactExecuteServiceTest.java+++ b/app/core/src/test/java/stirling/software/SPDF/controller/api/security/RedactExecuteServiceTest.java@@ -223,8 +223,7 @@ class RedactExecuteServiceTest {* NOT be redacted)*/private PDFont helvetica(PDDocument doc) throws IOException {- try (InputStream is =- getClass().getResourceAsStream("/type3/library/fonts/dejavu/DejaVuSans.ttf")) {+ try (InputStream is = getClass().getResourceAsStream("/static/fonts/DejaVuSans.ttf")) {if (is != null) {return PDType0Font.load(doc, is);}diff --git a/app/core/src/test/java/stirling/software/SPDF/controller/api/security/TextRedactionServiceExtraTest.java b/app/core/src/test/java/stirling/software/SPDF/controller/api/security/TextRedactionServiceExtraTest.javaindex 79c14b7e1d..150c82a807 100644--- a/app/core/src/test/java/stirling/software/SPDF/controller/api/security/TextRedactionServiceExtraTest.java+++ b/app/core/src/test/java/stirling/software/SPDF/controller/api/security/TextRedactionServiceExtraTest.java@@ -35,8 +35,7 @@ class TextRedactionServiceExtraTest {private final TextRedactionService service = new TextRedactionService();private PDFont helvetica(PDDocument doc) throws IOException {- try (InputStream is =- getClass().getResourceAsStream("/type3/library/fonts/dejavu/DejaVuSans.ttf")) {+ try (InputStream is = getClass().getResourceAsStream("/static/fonts/DejaVuSans.ttf")) {if (is != null) {return PDType0Font.load(doc, is);}diff --git a/app/core/src/test/java/stirling/software/SPDF/controller/api/security/TextRedactionServiceMoreTest.java b/app/core/src/test/java/stirling/software/SPDF/controller/api/security/TextRedactionServiceMoreTest.javaindex e0408bae55..31c54f72ce 100644--- a/app/core/src/test/java/stirling/software/SPDF/controller/api/security/TextRedactionServiceMoreTest.java+++ b/app/core/src/test/java/stirling/software/SPDF/controller/api/security/TextRedactionServiceMoreTest.java@@ -35,8 +35,7 @@ class TextRedactionServiceMoreTest {}private PDFont helvetica(PDDocument doc) throws IOException {- try (InputStream is =- getClass().getResourceAsStream("/type3/library/fonts/dejavu/DejaVuSans.ttf")) {+ try (InputStream is = getClass().getResourceAsStream("/static/fonts/DejaVuSans.ttf")) {if (is != null) {return PDType0Font.load(doc, is);}diff --git a/app/core/src/test/java/stirling/software/SPDF/controller/api/security/TextRedactionServiceTest.java b/app/core/src/test/java/stirling/software/SPDF/controller/api/security/TextRedactionServiceTest.javaindex a47f2c15ab..db346d1652 100644--- a/app/core/src/test/java/stirling/software/SPDF/controller/api/security/TextRedactionServiceTest.java+++ b/app/core/src/test/java/stirling/software/SPDF/controller/api/security/TextRedactionServiceTest.java@@ -46,8 +46,7 @@ class TextRedactionServiceTest {}private PDFont helvetica(PDDocument doc) throws IOException {- try (InputStream is =- getClass().getResourceAsStream("/type3/library/fonts/dejavu/DejaVuSans.ttf")) {+ try (InputStream is = getClass().getResourceAsStream("/static/fonts/DejaVuSans.ttf")) {if (is != null) {return PDType0Font.load(doc, is);}diff --git a/app/core/src/test/java/stirling/software/SPDF/model/api/PdfJsonConversionProgressTest.java b/app/core/src/test/java/stirling/software/SPDF/model/api/PdfJsonConversionProgressTest.javadeleted file mode 100644index 3a3dfa6eb8..0000000000--- a/app/core/src/test/java/stirling/software/SPDF/model/api/PdfJsonConversionProgressTest.java+++ /dev/null@@ -1,114 +0,0 @@-package stirling.software.SPDF.model.api;--import static org.assertj.core.api.Assertions.assertThat;--import org.junit.jupiter.api.DisplayName;-import org.junit.jupiter.api.Nested;-import org.junit.jupiter.api.Test;--class PdfJsonConversionProgressTest {-- @Nested- @DisplayName("of(percent, stage, message)")- class ThreeArgFactory {-- @Test- @DisplayName("sets fields and leaves complete false")- void buildsProgress() {- PdfJsonConversionProgress p =- PdfJsonConversionProgress.of(42, "loading", "Loading pages");-- assertThat(p.getPercent()).isEqualTo(42);- assertThat(p.getStage()).isEqualTo("loading");- assertThat(p.getMessage()).isEqualTo("Loading pages");- assertThat(p.isComplete()).isFalse();- assertThat(p.getCurrent()).isNull();- assertThat(p.getTotal()).isNull();- }- }-- @Nested- @DisplayName("of(percent, stage, message, current, total)")- class FiveArgFactory {-- @Test- @DisplayName("includes current and total counters")- void buildsProgressWithCounters() {- PdfJsonConversionProgress p =- PdfJsonConversionProgress.of(50, "pages", "Processing", 3, 6);-- assertThat(p.getPercent()).isEqualTo(50);- assertThat(p.getStage()).isEqualTo("pages");- assertThat(p.getMessage()).isEqualTo("Processing");- assertThat(p.getCurrent()).isEqualTo(3);- assertThat(p.getTotal()).isEqualTo(6);- assertThat(p.isComplete()).isFalse();- }- }-- @Nested- @DisplayName("complete()")- class CompleteFactory {-- @Test- @DisplayName("marks 100 percent complete")- void buildsComplete() {- PdfJsonConversionProgress p = PdfJsonConversionProgress.complete();-- assertThat(p.getPercent()).isEqualTo(100);- assertThat(p.getStage()).isEqualTo("complete");- assertThat(p.getMessage()).isEqualTo("Conversion complete");- assertThat(p.isComplete()).isTrue();- }- }-- @Nested- @DisplayName("builder and accessors")- class BuilderAndAccessors {-- @Test- @DisplayName("builder populates all fields")- void builder() {- PdfJsonConversionProgress p =- PdfJsonConversionProgress.builder()- .percent(10)- .stage("init")- .message("starting")- .complete(false)- .current(1)- .total(5)- .build();-- assertThat(p.getPercent()).isEqualTo(10);- assertThat(p.getStage()).isEqualTo("init");- assertThat(p.getCurrent()).isEqualTo(1);- assertThat(p.getTotal()).isEqualTo(5);- }-- @Test- @DisplayName("no-arg constructor with setters works")- void noArgConstructor() {- PdfJsonConversionProgress p = new PdfJsonConversionProgress();- p.setPercent(5);- p.setStage("s");- p.setMessage("m");- p.setComplete(true);- p.setCurrent(2);- p.setTotal(4);-- assertThat(p.getPercent()).isEqualTo(5);- assertThat(p.isComplete()).isTrue();- }-- @Test- @DisplayName("equals/hashCode/toString")- void equality() {- PdfJsonConversionProgress a = new PdfJsonConversionProgress(1, "s", "m", false, 1, 2);- PdfJsonConversionProgress b = new PdfJsonConversionProgress(1, "s", "m", false, 1, 2);-- assertThat(a).isEqualTo(b).hasSameHashCodeAs(b);- assertThat(a).isNotEqualTo(null).isNotEqualTo("x");- assertThat(a.toString()).contains("PdfJsonConversionProgress");- }- }-}diff --git a/app/core/src/test/java/stirling/software/SPDF/model/api/general/EditTextRequestTest.java b/app/core/src/test/java/stirling/software/SPDF/model/api/general/EditTextRequestTest.javadeleted file mode 100644index 0e726fd32a..0000000000--- a/app/core/src/test/java/stirling/software/SPDF/model/api/general/EditTextRequestTest.java+++ /dev/null@@ -1,94 +0,0 @@-package stirling.software.SPDF.model.api.general;--import static org.assertj.core.api.Assertions.assertThat;--import java.util.List;--import org.junit.jupiter.api.DisplayName;-import org.junit.jupiter.api.Nested;-import org.junit.jupiter.api.Test;--import stirling.software.common.model.api.general.EditTextOperation;--@DisplayName("EditTextRequest")-class EditTextRequestTest {-- private static EditTextOperation op(String find, String replace) {- EditTextOperation operation = new EditTextOperation();- operation.setFind(find);- operation.setReplace(replace);- return operation;- }-- @Nested- @DisplayName("defaults")- class Defaults {-- @Test- @DisplayName("edits and wholeWordSearch are null on a fresh instance")- void defaultValues() {- EditTextRequest req = new EditTextRequest();-- assertThat(req.getEdits()).isNull();- assertThat(req.getWholeWordSearch()).isNull();- assertThat(req.getPageNumbers()).isNull();- }- }-- @Nested- @DisplayName("accessors")- class Accessors {-- @Test- @DisplayName("setters round-trip every field including inherited pageNumbers")- void setters() {- EditTextRequest req = new EditTextRequest();- List<EditTextOperation> edits = List.of(op("foo", "bar"));- req.setEdits(edits);- req.setWholeWordSearch(true);- req.setPageNumbers("1-3");-- assertThat(req.getEdits()).isSameAs(edits);- assertThat(req.getWholeWordSearch()).isTrue();- assertThat(req.getPageNumbers()).isEqualTo("1-3");- }- }-- @Nested- @DisplayName("equals/hashCode/toString")- class Equality {-- @Test- @DisplayName("equal instances are equal and share a hashCode")- void equalInstances() {- EditTextRequest a = new EditTextRequest();- a.setEdits(List.of(op("foo", "bar")));- a.setWholeWordSearch(true);- EditTextRequest b = new EditTextRequest();- b.setEdits(List.of(op("foo", "bar")));- b.setWholeWordSearch(true);-- assertThat(a).isEqualTo(b).hasSameHashCodeAs(b);- }-- @Test- @DisplayName("differing subclass field breaks equality")- void notEqual() {- EditTextRequest a = new EditTextRequest();- a.setWholeWordSearch(false);- EditTextRequest b = new EditTextRequest();- b.setWholeWordSearch(true);-- assertThat(a).isNotEqualTo(b).isNotEqualTo(null).isNotEqualTo("string");- }-- @Test- @DisplayName("toString contains a representative field value")- void toStringContent() {- EditTextRequest req = new EditTextRequest();- req.setWholeWordSearch(true);-- assertThat(req.toString()).isNotNull().contains("wholeWordSearch=true");- }- }-}diff --git a/app/core/src/test/java/stirling/software/SPDF/model/json/PdfJsonAnnotationTest.java b/app/core/src/test/java/stirling/software/SPDF/model/json/PdfJsonAnnotationTest.javadeleted file mode 100644index 3dce3f9fa1..0000000000--- a/app/core/src/test/java/stirling/software/SPDF/model/json/PdfJsonAnnotationTest.java+++ /dev/null@@ -1,103 +0,0 @@-package stirling.software.SPDF.model.json;--import static org.assertj.core.api.Assertions.*;--import org.junit.jupiter.api.DisplayName;-import org.junit.jupiter.api.Nested;-import org.junit.jupiter.api.Test;--@DisplayName("PdfJsonAnnotation")-class PdfJsonAnnotationTest {-- @Nested- @DisplayName("construction")- class Construction {-- @Test- @DisplayName("no-arg constructor yields null fields")- void noArg() {- PdfJsonAnnotation a = new PdfJsonAnnotation();- assertThat(a.getSubtype()).isNull();- assertThat(a.getRect()).isNull();- assertThat(a.getRawData()).isNull();- }-- @Test- @DisplayName("builder sets scalar and array fields")- void builder() {- PdfJsonAnnotation a =- PdfJsonAnnotation.builder()- .subtype("Highlight")- .contents("note")- .rect(new float[] {0f, 0f, 10f, 10f})- .color(new float[] {1f, 1f, 0f})- .flags(4)- .destination("page2")- .iconName("Comment")- .subject("subj")- .author("Alice")- .creationDate("2025-01-01")- .modificationDate("2026-01-01")- .build();-- assertThat(a.getSubtype()).isEqualTo("Highlight");- assertThat(a.getContents()).isEqualTo("note");- assertThat(a.getRect()).containsExactly(0f, 0f, 10f, 10f);- assertThat(a.getColor()).containsExactly(1f, 1f, 0f);- assertThat(a.getFlags()).isEqualTo(4);- assertThat(a.getDestination()).isEqualTo("page2");- assertThat(a.getIconName()).isEqualTo("Comment");- assertThat(a.getSubject()).isEqualTo("subj");- assertThat(a.getAuthor()).isEqualTo("Alice");- assertThat(a.getCreationDate()).isEqualTo("2025-01-01");- assertThat(a.getModificationDate()).isEqualTo("2026-01-01");- assertThat(a.getRawData()).isNull();- }-- @Test- @DisplayName("setters round-trip")- void setters() {- PdfJsonAnnotation a = new PdfJsonAnnotation();- a.setSubtype("Text");- a.setAuthor("Bob");- assertThat(a.getSubtype()).isEqualTo("Text");- assertThat(a.getAuthor()).isEqualTo("Bob");- }- }-- @Nested- @DisplayName("equality")- class Equality {-- // Lombok deep-compares float[] via Arrays.equals.- @Test- @DisplayName("equal content arrays equal; different content not")- void arrayEquality() {- PdfJsonAnnotation a =- PdfJsonAnnotation.builder()- .subtype("Highlight")- .rect(new float[] {1f, 2f, 3f, 4f})- .build();- PdfJsonAnnotation b =- PdfJsonAnnotation.builder()- .subtype("Highlight")- .rect(new float[] {1f, 2f, 3f, 4f})- .build();- assertThat(a).isEqualTo(b).hasSameHashCodeAs(b);-- PdfJsonAnnotation c =- PdfJsonAnnotation.builder()- .subtype("Highlight")- .rect(new float[] {9f, 9f, 9f, 9f})- .build();- assertThat(a).isNotEqualTo(c).isNotEqualTo(null).isNotEqualTo("string");- }-- @Test- @DisplayName("toString contains class name and value")- void toStringContent() {- PdfJsonAnnotation a = PdfJsonAnnotation.builder().subtype("Stamp").build();- assertThat(a.toString()).contains("PdfJsonAnnotation").contains("Stamp");- }- }-}diff --git a/app/core/src/test/java/stirling/software/SPDF/model/json/PdfJsonDocumentMetadataTest.java b/app/core/src/test/java/stirling/software/SPDF/model/json/PdfJsonDocumentMetadataTest.javadeleted file mode 100644index 2a4c8c63ab..0000000000--- a/app/core/src/test/java/stirling/software/SPDF/model/json/PdfJsonDocumentMetadataTest.java+++ /dev/null@@ -1,95 +0,0 @@-package stirling.software.SPDF.model.json;--import static org.assertj.core.api.Assertions.*;--import java.util.List;--import org.junit.jupiter.api.DisplayName;-import org.junit.jupiter.api.Nested;-import org.junit.jupiter.api.Test;--@DisplayName("PdfJsonDocumentMetadata")-class PdfJsonDocumentMetadataTest {-- @Nested- @DisplayName("construction and defaults")- class Construction {-- @Test- @DisplayName("no-arg constructor initializes empty list fields")- void noArg() {- PdfJsonDocumentMetadata m = new PdfJsonDocumentMetadata();- assertThat(m.getFonts()).isEmpty();- assertThat(m.getPageDimensions()).isEmpty();- assertThat(m.getFormFields()).isEmpty();- assertThat(m.getMetadata()).isNull();- assertThat(m.getXmpMetadata()).isNull();- assertThat(m.getLazyImages()).isNull();- }-- @Test- @DisplayName("builder defaults produce empty lists")- void builderDefaults() {- PdfJsonDocumentMetadata m = PdfJsonDocumentMetadata.builder().build();- assertThat(m.getFonts()).isEmpty();- assertThat(m.getPageDimensions()).isEmpty();- assertThat(m.getFormFields()).isEmpty();- }-- @Test- @DisplayName("builder sets scalar and list fields")- void builder() {- PdfJsonMetadata meta = PdfJsonMetadata.builder().title("T").build();- List<PdfJsonPageDimension> dims = List.of(new PdfJsonPageDimension(1, 10f, 20f, 0));- List<PdfJsonFormField> fields = List.of(PdfJsonFormField.builder().name("f").build());-- PdfJsonDocumentMetadata m =- PdfJsonDocumentMetadata.builder()- .metadata(meta)- .xmpMetadata("base64xmp")- .lazyImages(true)- .pageDimensions(dims)- .formFields(fields)- .build();-- assertThat(m.getMetadata()).isSameAs(meta);- assertThat(m.getXmpMetadata()).isEqualTo("base64xmp");- assertThat(m.getLazyImages()).isTrue();- assertThat(m.getPageDimensions()).isEqualTo(dims);- assertThat(m.getFormFields()).isEqualTo(fields);- }- }-- @Nested- @DisplayName("accessors and equality")- class Behavior {-- @Test- @DisplayName("setters round-trip")- void roundTrip() {- PdfJsonDocumentMetadata m = new PdfJsonDocumentMetadata();- m.setXmpMetadata("xmp");- m.setLazyImages(false);- assertThat(m.getXmpMetadata()).isEqualTo("xmp");- assertThat(m.getLazyImages()).isFalse();- }-- @Test- @DisplayName("equal pair shares hashCode; differs by field")- void equality() {- PdfJsonDocumentMetadata a = PdfJsonDocumentMetadata.builder().xmpMetadata("x").build();- PdfJsonDocumentMetadata b = PdfJsonDocumentMetadata.builder().xmpMetadata("x").build();- assertThat(a).isEqualTo(b).hasSameHashCodeAs(b);-- PdfJsonDocumentMetadata c = PdfJsonDocumentMetadata.builder().xmpMetadata("y").build();- assertThat(a).isNotEqualTo(c).isNotEqualTo(null).isNotEqualTo("string");- }-- @Test- @DisplayName("toString contains class name")- void toStringContent() {- assertThat(new PdfJsonDocumentMetadata().toString())- .contains("PdfJsonDocumentMetadata");- }- }-}diff --git a/app/core/src/test/java/stirling/software/SPDF/model/json/PdfJsonFontCidSystemInfoTest.java b/app/core/src/test/java/stirling/software/SPDF/model/json/PdfJsonFontCidSystemInfoTest.javadeleted file mode 100644index 00ca70e7a8..0000000000--- a/app/core/src/test/java/stirling/software/SPDF/model/json/PdfJsonFontCidSystemInfoTest.java+++ /dev/null@@ -1,57 +0,0 @@-package stirling.software.SPDF.model.json;--import static org.assertj.core.api.Assertions.*;--import org.junit.jupiter.api.DisplayName;-import org.junit.jupiter.api.Test;--@DisplayName("PdfJsonFontCidSystemInfo")-class PdfJsonFontCidSystemInfoTest {-- @Test- @DisplayName("no-arg constructor yields null fields")- void noArg() {- PdfJsonFontCidSystemInfo info = new PdfJsonFontCidSystemInfo();- assertThat(info.getRegistry()).isNull();- assertThat(info.getOrdering()).isNull();- assertThat(info.getSupplement()).isNull();- }-- @Test- @DisplayName("all-args constructor sets every field")- void allArgs() {- PdfJsonFontCidSystemInfo info = new PdfJsonFontCidSystemInfo("Adobe", "Japan1", 6);- assertThat(info.getRegistry()).isEqualTo("Adobe");- assertThat(info.getOrdering()).isEqualTo("Japan1");- assertThat(info.getSupplement()).isEqualTo(6);- }-- @Test- @DisplayName("builder and setters round-trip")- void builderAndSetters() {- PdfJsonFontCidSystemInfo info =- PdfJsonFontCidSystemInfo.builder()- .registry("Adobe")- .ordering("Identity")- .supplement(0)- .build();- assertThat(info.getRegistry()).isEqualTo("Adobe");- assertThat(info.getOrdering()).isEqualTo("Identity");- assertThat(info.getSupplement()).isZero();-- info.setSupplement(2);- assertThat(info.getSupplement()).isEqualTo(2);- }-- @Test- @DisplayName("equals/hashCode/toString")- void equality() {- PdfJsonFontCidSystemInfo a = PdfJsonFontCidSystemInfo.builder().registry("Adobe").build();- PdfJsonFontCidSystemInfo b = PdfJsonFontCidSystemInfo.builder().registry("Adobe").build();- assertThat(a).isEqualTo(b).hasSameHashCodeAs(b);-- PdfJsonFontCidSystemInfo c = PdfJsonFontCidSystemInfo.builder().registry("MS").build();- assertThat(a).isNotEqualTo(c).isNotEqualTo(null).isNotEqualTo("string");- assertThat(a.toString()).contains("PdfJsonFontCidSystemInfo").contains("Adobe");- }-}diff --git a/app/core/src/test/java/stirling/software/SPDF/model/json/PdfJsonFontConversionCandidateTest.java b/app/core/src/test/java/stirling/software/SPDF/model/json/PdfJsonFontConversionCandidateTest.javadeleted file mode 100644index b7a32b1e1c..0000000000--- a/app/core/src/test/java/stirling/software/SPDF/model/json/PdfJsonFontConversionCandidateTest.java+++ /dev/null@@ -1,115 +0,0 @@-package stirling.software.SPDF.model.json;--import static org.assertj.core.api.Assertions.*;--import org.junit.jupiter.api.DisplayName;-import org.junit.jupiter.api.Nested;-import org.junit.jupiter.api.Test;--@DisplayName("PdfJsonFontConversionCandidate")-class PdfJsonFontConversionCandidateTest {-- @Nested- @DisplayName("construction")- class Construction {-- @Test- @DisplayName("no-arg constructor yields null fields")- void noArg() {- PdfJsonFontConversionCandidate c = new PdfJsonFontConversionCandidate();- assertThat(c.getStrategyId()).isNull();- assertThat(c.getStatus()).isNull();- assertThat(c.getGlyphCoverage()).isNull();- }-- @Test- @DisplayName("builder sets scalar, enum and array fields")- void builder() {- PdfJsonFontConversionCandidate c =- PdfJsonFontConversionCandidate.builder()- .strategyId("s1")- .strategyLabel("Strategy 1")- .status(PdfJsonFontConversionStatus.SUCCESS)- .message("ok")- .synthesizedGlyphs(10)- .missingGlyphs(0)- .widthDelta(0.5d)- .bboxDelta(1.0d)- .program("AAA")- .programFormat("ttf")- .webProgram("BBB")- .webProgramFormat("woff")- .pdfProgram("CCC")- .pdfProgramFormat("cff")- .previewImage("PNG")- .diagnostics("{}")- .glyphCoverage(new int[] {65, 66, 67})- .build();-- assertThat(c.getStrategyId()).isEqualTo("s1");- assertThat(c.getStrategyLabel()).isEqualTo("Strategy 1");- assertThat(c.getStatus()).isEqualTo(PdfJsonFontConversionStatus.SUCCESS);- assertThat(c.getMessage()).isEqualTo("ok");- assertThat(c.getSynthesizedGlyphs()).isEqualTo(10);- assertThat(c.getMissingGlyphs()).isZero();- assertThat(c.getWidthDelta()).isEqualTo(0.5d);- assertThat(c.getBboxDelta()).isEqualTo(1.0d);- assertThat(c.getProgram()).isEqualTo("AAA");- assertThat(c.getProgramFormat()).isEqualTo("ttf");- assertThat(c.getWebProgram()).isEqualTo("BBB");- assertThat(c.getWebProgramFormat()).isEqualTo("woff");- assertThat(c.getPdfProgram()).isEqualTo("CCC");- assertThat(c.getPdfProgramFormat()).isEqualTo("cff");- assertThat(c.getPreviewImage()).isEqualTo("PNG");- assertThat(c.getDiagnostics()).isEqualTo("{}");- assertThat(c.getGlyphCoverage()).containsExactly(65, 66, 67);- }-- @Test- @DisplayName("setters round-trip")- void setters() {- PdfJsonFontConversionCandidate c = new PdfJsonFontConversionCandidate();- c.setStrategyId("x");- c.setStatus(PdfJsonFontConversionStatus.FAILURE);- assertThat(c.getStrategyId()).isEqualTo("x");- assertThat(c.getStatus()).isEqualTo(PdfJsonFontConversionStatus.FAILURE);- }- }-- @Nested- @DisplayName("equality")- class Equality {-- // Lombok deep-compares int[] via Arrays.equals.- @Test- @DisplayName("equal content arrays equal; different content not")- void arrayEquality() {- PdfJsonFontConversionCandidate a =- PdfJsonFontConversionCandidate.builder()- .strategyId("s")- .glyphCoverage(new int[] {1, 2})- .build();- PdfJsonFontConversionCandidate b =- PdfJsonFontConversionCandidate.builder()- .strategyId("s")- .glyphCoverage(new int[] {1, 2})- .build();- assertThat(a).isEqualTo(b).hasSameHashCodeAs(b);-- PdfJsonFontConversionCandidate c =- PdfJsonFontConversionCandidate.builder()- .strategyId("s")- .glyphCoverage(new int[] {9})- .build();- assertThat(a).isNotEqualTo(c).isNotEqualTo(null).isNotEqualTo("string");- }-- @Test- @DisplayName("toString contains class name and value")- void toStringContent() {- PdfJsonFontConversionCandidate a =- PdfJsonFontConversionCandidate.builder().strategyId("stratId").build();- assertThat(a.toString()).contains("PdfJsonFontConversionCandidate").contains("stratId");- }- }-}diff --git a/app/core/src/test/java/stirling/software/SPDF/model/json/PdfJsonFontConversionStatusTest.java b/app/core/src/test/java/stirling/software/SPDF/model/json/PdfJsonFontConversionStatusTest.javadeleted file mode 100644index 22b2223cc0..0000000000--- a/app/core/src/test/java/stirling/software/SPDF/model/json/PdfJsonFontConversionStatusTest.java+++ /dev/null@@ -1,36 +0,0 @@-package stirling.software.SPDF.model.json;--import static org.assertj.core.api.Assertions.assertThat;-import static org.assertj.core.api.Assertions.assertThatThrownBy;--import java.util.Arrays;--import org.junit.jupiter.api.DisplayName;-import org.junit.jupiter.api.Test;-import org.junit.jupiter.params.ParameterizedTest;-import org.junit.jupiter.params.provider.EnumSource;--class PdfJsonFontConversionStatusTest {-- @Test- @DisplayName("contains exactly the expected constants")- void containsExpected() {- assertThat(Arrays.stream(PdfJsonFontConversionStatus.values()).map(Enum::name))- .containsExactlyInAnyOrder(- "SUCCESS", "WARNING", "FAILURE", "SKIPPED", "UNSUPPORTED");- }-- @ParameterizedTest- @EnumSource(PdfJsonFontConversionStatus.class)- @DisplayName("valueOf round trips every constant")- void valueOfRoundTrip(PdfJsonFontConversionStatus status) {- assertThat(PdfJsonFontConversionStatus.valueOf(status.name())).isSameAs(status);- }-- @Test- @DisplayName("valueOf throws for unknown name")- void valueOfUnknownThrows() {- assertThatThrownBy(() -> PdfJsonFontConversionStatus.valueOf("BROKEN"))- .isInstanceOf(IllegalArgumentException.class);- }-}diff --git a/app/core/src/test/java/stirling/software/SPDF/model/json/PdfJsonFontType3GlyphTest.java b/app/core/src/test/java/stirling/software/SPDF/model/json/PdfJsonFontType3GlyphTest.javadeleted file mode 100644index 332abff917..0000000000--- a/app/core/src/test/java/stirling/software/SPDF/model/json/PdfJsonFontType3GlyphTest.java+++ /dev/null@@ -1,55 +0,0 @@-package stirling.software.SPDF.model.json;--import static org.assertj.core.api.Assertions.*;--import org.junit.jupiter.api.DisplayName;-import org.junit.jupiter.api.Test;--@DisplayName("PdfJsonFontType3Glyph")-class PdfJsonFontType3GlyphTest {-- @Test- @DisplayName("no-arg constructor yields null fields")- void noArg() {- PdfJsonFontType3Glyph g = new PdfJsonFontType3Glyph();- assertThat(g.getCharCode()).isNull();- assertThat(g.getGlyphName()).isNull();- assertThat(g.getUnicode()).isNull();- assertThat(g.getCharCodeRaw()).isNull();- }-- @Test- @DisplayName("all-args constructor sets every field")- void allArgs() {- PdfJsonFontType3Glyph g = new PdfJsonFontType3Glyph(65, "A", 0x41, 200);- assertThat(g.getCharCode()).isEqualTo(65);- assertThat(g.getGlyphName()).isEqualTo("A");- assertThat(g.getUnicode()).isEqualTo(0x41);- assertThat(g.getCharCodeRaw()).isEqualTo(200);- }-- @Test- @DisplayName("builder and setters round-trip")- void builderAndSetters() {- PdfJsonFontType3Glyph g =- PdfJsonFontType3Glyph.builder().charCode(66).glyphName("B").unicode(0x42).build();- assertThat(g.getCharCode()).isEqualTo(66);- assertThat(g.getGlyphName()).isEqualTo("B");- assertThat(g.getUnicode()).isEqualTo(0x42);-- g.setCharCodeRaw(10);- assertThat(g.getCharCodeRaw()).isEqualTo(10);- }-- @Test- @DisplayName("equals/hashCode/toString")- void equality() {- PdfJsonFontType3Glyph a = PdfJsonFontType3Glyph.builder().glyphName("A").build();- PdfJsonFontType3Glyph b = PdfJsonFontType3Glyph.builder().glyphName("A").build();- assertThat(a).isEqualTo(b).hasSameHashCodeAs(b);-- PdfJsonFontType3Glyph c = PdfJsonFontType3Glyph.builder().glyphName("B").build();- assertThat(a).isNotEqualTo(c).isNotEqualTo(null).isNotEqualTo("string");- assertThat(a.toString()).contains("PdfJsonFontType3Glyph");- }-}diff --git a/app/core/src/test/java/stirling/software/SPDF/model/json/PdfJsonFormFieldTest.java b/app/core/src/test/java/stirling/software/SPDF/model/json/PdfJsonFormFieldTest.javadeleted file mode 100644index ca5aabfd70..0000000000--- a/app/core/src/test/java/stirling/software/SPDF/model/json/PdfJsonFormFieldTest.java+++ /dev/null@@ -1,104 +0,0 @@-package stirling.software.SPDF.model.json;--import static org.assertj.core.api.Assertions.*;--import java.util.List;--import org.junit.jupiter.api.DisplayName;-import org.junit.jupiter.api.Nested;-import org.junit.jupiter.api.Test;--@DisplayName("PdfJsonFormField")-class PdfJsonFormFieldTest {-- @Nested- @DisplayName("construction")- class Construction {-- @Test- @DisplayName("no-arg constructor yields null fields")- void noArg() {- PdfJsonFormField f = new PdfJsonFormField();- assertThat(f.getName()).isNull();- assertThat(f.getRect()).isNull();- assertThat(f.getSelectedIndices()).isNull();- assertThat(f.getOptions()).isNull();- }-- @Test- @DisplayName("builder sets scalar, list and array fields")- void builder() {- PdfJsonFormField f =- PdfJsonFormField.builder()- .name("form1.text1")- .partialName("text1")- .fieldType("Tx")- .value("hello")- .defaultValue("default")- .flags(2)- .alternateFieldName("alt")- .mappingName("map")- .pageNumber(1)- .rect(new float[] {0f, 0f, 100f, 20f})- .options(List.of("A", "B"))- .selectedIndices(new int[] {0, 1})- .checked(true)- .fontName("Helv")- .fontSize(12f)- .build();-- assertThat(f.getName()).isEqualTo("form1.text1");- assertThat(f.getPartialName()).isEqualTo("text1");- assertThat(f.getFieldType()).isEqualTo("Tx");- assertThat(f.getValue()).isEqualTo("hello");- assertThat(f.getDefaultValue()).isEqualTo("default");- assertThat(f.getFlags()).isEqualTo(2);- assertThat(f.getAlternateFieldName()).isEqualTo("alt");- assertThat(f.getMappingName()).isEqualTo("map");- assertThat(f.getPageNumber()).isEqualTo(1);- assertThat(f.getRect()).containsExactly(0f, 0f, 100f, 20f);- assertThat(f.getOptions()).containsExactly("A", "B");- assertThat(f.getSelectedIndices()).containsExactly(0, 1);- assertThat(f.getChecked()).isTrue();- assertThat(f.getFontName()).isEqualTo("Helv");- assertThat(f.getFontSize()).isEqualTo(12f);- }-- @Test- @DisplayName("setters round-trip")- void setters() {- PdfJsonFormField f = new PdfJsonFormField();- f.setName("n");- f.setChecked(false);- assertThat(f.getName()).isEqualTo("n");- assertThat(f.getChecked()).isFalse();- }- }-- @Nested- @DisplayName("equality")- class Equality {-- // Lombok deep-compares int[] via Arrays.equals.- @Test- @DisplayName("equal content arrays equal; different content not")- void arrayEquality() {- PdfJsonFormField a =- PdfJsonFormField.builder().name("f").selectedIndices(new int[] {1, 2}).build();- PdfJsonFormField b =- PdfJsonFormField.builder().name("f").selectedIndices(new int[] {1, 2}).build();- assertThat(a).isEqualTo(b).hasSameHashCodeAs(b);-- PdfJsonFormField c =- PdfJsonFormField.builder().name("f").selectedIndices(new int[] {9}).build();- assertThat(a).isNotEqualTo(c).isNotEqualTo(null).isNotEqualTo("string");- }-- @Test- @DisplayName("toString contains class name and value")- void toStringContent() {- PdfJsonFormField a = PdfJsonFormField.builder().name("fieldName").build();- assertThat(a.toString()).contains("PdfJsonFormField").contains("fieldName");- }- }-}diff --git a/app/core/src/test/java/stirling/software/SPDF/model/json/PdfJsonImageElementTest.java b/app/core/src/test/java/stirling/software/SPDF/model/json/PdfJsonImageElementTest.javadeleted file mode 100644index f6adf39669..0000000000--- a/app/core/src/test/java/stirling/software/SPDF/model/json/PdfJsonImageElementTest.java+++ /dev/null@@ -1,104 +0,0 @@-package stirling.software.SPDF.model.json;--import static org.assertj.core.api.Assertions.*;--import org.junit.jupiter.api.DisplayName;-import org.junit.jupiter.api.Nested;-import org.junit.jupiter.api.Test;--@DisplayName("PdfJsonImageElement")-class PdfJsonImageElementTest {-- @Nested- @DisplayName("construction")- class Construction {-- @Test- @DisplayName("no-arg constructor yields null fields")- void noArg() {- PdfJsonImageElement e = new PdfJsonImageElement();- assertThat(e.getId()).isNull();- assertThat(e.getTransform()).isNull();- }-- @Test- @DisplayName("builder sets scalar and array fields")- void builder() {- PdfJsonImageElement e =- PdfJsonImageElement.builder()- .id("img1")- .objectName("Im0")- .inlineImage(false)- .nativeWidth(100)- .nativeHeight(200)- .x(1f)- .y(2f)- .width(3f)- .height(4f)- .left(5f)- .right(6f)- .top(7f)- .bottom(8f)- .transform(new float[] {1f, 0f, 0f, 1f, 0f, 0f})- .zOrder(2)- .imageData("base64")- .imageFormat("png")- .build();-- assertThat(e.getId()).isEqualTo("img1");- assertThat(e.getObjectName()).isEqualTo("Im0");- assertThat(e.getInlineImage()).isFalse();- assertThat(e.getNativeWidth()).isEqualTo(100);- assertThat(e.getNativeHeight()).isEqualTo(200);- assertThat(e.getX()).isEqualTo(1f);- assertThat(e.getY()).isEqualTo(2f);- assertThat(e.getWidth()).isEqualTo(3f);- assertThat(e.getHeight()).isEqualTo(4f);- assertThat(e.getLeft()).isEqualTo(5f);- assertThat(e.getRight()).isEqualTo(6f);- assertThat(e.getTop()).isEqualTo(7f);- assertThat(e.getBottom()).isEqualTo(8f);- assertThat(e.getTransform()).containsExactly(1f, 0f, 0f, 1f, 0f, 0f);- assertThat(e.getZOrder()).isEqualTo(2);- assertThat(e.getImageData()).isEqualTo("base64");- assertThat(e.getImageFormat()).isEqualTo("png");- }-- @Test- @DisplayName("setters round-trip")- void setters() {- PdfJsonImageElement e = new PdfJsonImageElement();- e.setId("x");- e.setWidth(9f);- assertThat(e.getId()).isEqualTo("x");- assertThat(e.getWidth()).isEqualTo(9f);- }- }-- @Nested- @DisplayName("equality")- class Equality {-- // Lombok deep-compares float[] via Arrays.equals.- @Test- @DisplayName("equal content arrays equal; different content not")- void arrayEquality() {- PdfJsonImageElement a =- PdfJsonImageElement.builder().id("i").transform(new float[] {1f, 2f}).build();- PdfJsonImageElement b =- PdfJsonImageElement.builder().id("i").transform(new float[] {1f, 2f}).build();- assertThat(a).isEqualTo(b).hasSameHashCodeAs(b);-- PdfJsonImageElement c =- PdfJsonImageElement.builder().id("i").transform(new float[] {9f}).build();- assertThat(a).isNotEqualTo(c).isNotEqualTo(null).isNotEqualTo("string");- }-- @Test- @DisplayName("toString contains class name and value")- void toStringContent() {- PdfJsonImageElement a = PdfJsonImageElement.builder().id("imgId").build();- assertThat(a.toString()).contains("PdfJsonImageElement").contains("imgId");- }- }-}diff --git a/app/core/src/test/java/stirling/software/SPDF/model/json/PdfJsonMetadataTest.java b/app/core/src/test/java/stirling/software/SPDF/model/json/PdfJsonMetadataTest.javadeleted file mode 100644index b8a661ff9e..0000000000--- a/app/core/src/test/java/stirling/software/SPDF/model/json/PdfJsonMetadataTest.java+++ /dev/null@@ -1,100 +0,0 @@-package stirling.software.SPDF.model.json;--import static org.assertj.core.api.Assertions.*;--import org.junit.jupiter.api.DisplayName;-import org.junit.jupiter.api.Nested;-import org.junit.jupiter.api.Test;--@DisplayName("PdfJsonMetadata")-class PdfJsonMetadataTest {-- @Nested- @DisplayName("constructors and builder")- class Construction {-- @Test- @DisplayName("no-arg constructor yields null fields")- void noArg() {- PdfJsonMetadata m = new PdfJsonMetadata();- assertThat(m.getTitle()).isNull();- assertThat(m.getNumberOfPages()).isNull();- }-- @Test- @DisplayName("all-args constructor sets every field")- void allArgs() {- PdfJsonMetadata m =- new PdfJsonMetadata(- "Title",- "Author",- "Subject",- "kw",- "Creator",- "Producer",- "2025-01-01",- "2026-01-01",- "False",- 7);-- assertThat(m.getTitle()).isEqualTo("Title");- assertThat(m.getAuthor()).isEqualTo("Author");- assertThat(m.getSubject()).isEqualTo("Subject");- assertThat(m.getKeywords()).isEqualTo("kw");- assertThat(m.getCreator()).isEqualTo("Creator");- assertThat(m.getProducer()).isEqualTo("Producer");- assertThat(m.getCreationDate()).isEqualTo("2025-01-01");- assertThat(m.getModificationDate()).isEqualTo("2026-01-01");- assertThat(m.getTrapped()).isEqualTo("False");- assertThat(m.getNumberOfPages()).isEqualTo(7);- }-- @Test- @DisplayName("builder sets fields")- void builder() {- PdfJsonMetadata m =- PdfJsonMetadata.builder()- .title("BuiltTitle")- .author("BuiltAuthor")- .numberOfPages(3)- .build();-- assertThat(m.getTitle()).isEqualTo("BuiltTitle");- assertThat(m.getAuthor()).isEqualTo("BuiltAuthor");- assertThat(m.getNumberOfPages()).isEqualTo(3);- }- }-- @Nested- @DisplayName("accessors and equality")- class Behavior {-- @Test- @DisplayName("setters round-trip")- void roundTrip() {- PdfJsonMetadata m = new PdfJsonMetadata();- m.setTitle("T");- m.setNumberOfPages(2);- assertThat(m.getTitle()).isEqualTo("T");- assertThat(m.getNumberOfPages()).isEqualTo(2);- }-- @Test- @DisplayName("equal pair shares hashCode; differs by field")- void equality() {- PdfJsonMetadata a = PdfJsonMetadata.builder().title("X").build();- PdfJsonMetadata b = PdfJsonMetadata.builder().title("X").build();- assertThat(a).isEqualTo(b).hasSameHashCodeAs(b);-- PdfJsonMetadata c = PdfJsonMetadata.builder().title("Y").build();- assertThat(a).isNotEqualTo(c).isNotEqualTo(null).isNotEqualTo("string");- }-- @Test- @DisplayName("toString contains class name and value")- void toStringContent() {- PdfJsonMetadata m = PdfJsonMetadata.builder().title("Meta").build();- assertThat(m.toString()).contains("PdfJsonMetadata").contains("Meta");- }- }-}diff --git a/app/core/src/test/java/stirling/software/SPDF/model/json/PdfJsonPageDimensionTest.java b/app/core/src/test/java/stirling/software/SPDF/model/json/PdfJsonPageDimensionTest.javadeleted file mode 100644index fb27541b70..0000000000--- a/app/core/src/test/java/stirling/software/SPDF/model/json/PdfJsonPageDimensionTest.java+++ /dev/null@@ -1,61 +0,0 @@-package stirling.software.SPDF.model.json;--import static org.assertj.core.api.Assertions.*;--import org.junit.jupiter.api.DisplayName;-import org.junit.jupiter.api.Test;--@DisplayName("PdfJsonPageDimension")-class PdfJsonPageDimensionTest {-- @Test- @DisplayName("no-arg constructor yields primitive defaults")- void noArg() {- PdfJsonPageDimension d = new PdfJsonPageDimension();- assertThat(d.getPageNumber()).isZero();- assertThat(d.getWidth()).isZero();- assertThat(d.getHeight()).isZero();- assertThat(d.getRotation()).isZero();- }-- @Test- @DisplayName("all-args constructor sets every field")- void allArgs() {- PdfJsonPageDimension d = new PdfJsonPageDimension(1, 612f, 792f, 90);- assertThat(d.getPageNumber()).isEqualTo(1);- assertThat(d.getWidth()).isEqualTo(612f);- assertThat(d.getHeight()).isEqualTo(792f);- assertThat(d.getRotation()).isEqualTo(90);- }-- @Test- @DisplayName("builder and setters round-trip")- void builderAndSetters() {- PdfJsonPageDimension d =- PdfJsonPageDimension.builder()- .pageNumber(2)- .width(100f)- .height(200f)- .rotation(180)- .build();- assertThat(d.getPageNumber()).isEqualTo(2);- assertThat(d.getWidth()).isEqualTo(100f);- assertThat(d.getHeight()).isEqualTo(200f);- assertThat(d.getRotation()).isEqualTo(180);-- d.setWidth(300f);- assertThat(d.getWidth()).isEqualTo(300f);- }-- @Test- @DisplayName("equals/hashCode/toString")- void equality() {- PdfJsonPageDimension a = new PdfJsonPageDimension(1, 10f, 20f, 0);- PdfJsonPageDimension b = new PdfJsonPageDimension(1, 10f, 20f, 0);- assertThat(a).isEqualTo(b).hasSameHashCodeAs(b);-- PdfJsonPageDimension c = new PdfJsonPageDimension(2, 10f, 20f, 0);- assertThat(a).isNotEqualTo(c).isNotEqualTo(null).isNotEqualTo("string");- assertThat(a.toString()).contains("PdfJsonPageDimension");- }-}diff --git a/app/core/src/test/java/stirling/software/SPDF/model/json/PdfJsonTextColorTest.java b/app/core/src/test/java/stirling/software/SPDF/model/json/PdfJsonTextColorTest.javadeleted file mode 100644index ef759a208b..0000000000--- a/app/core/src/test/java/stirling/software/SPDF/model/json/PdfJsonTextColorTest.java+++ /dev/null@@ -1,64 +0,0 @@-package stirling.software.SPDF.model.json;--import static org.assertj.core.api.Assertions.*;--import org.junit.jupiter.api.DisplayName;-import org.junit.jupiter.api.Test;--@DisplayName("PdfJsonTextColor")-class PdfJsonTextColorTest {-- @Test- @DisplayName("no-arg constructor yields null fields")- void noArg() {- PdfJsonTextColor c = new PdfJsonTextColor();- assertThat(c.getColorSpace()).isNull();- assertThat(c.getComponents()).isNull();- }-- @Test- @DisplayName("all-args constructor and accessors round-trip")- void allArgs() {- float[] comps = {0.1f, 0.2f, 0.3f};- PdfJsonTextColor c = new PdfJsonTextColor("DeviceRGB", comps);- assertThat(c.getColorSpace()).isEqualTo("DeviceRGB");- assertThat(c.getComponents()).containsExactly(0.1f, 0.2f, 0.3f);- }-- @Test- @DisplayName("builder and setters round-trip")- void builderAndSetters() {- PdfJsonTextColor c =- PdfJsonTextColor.builder()- .colorSpace("DeviceGray")- .components(new float[] {0.5f})- .build();- assertThat(c.getColorSpace()).isEqualTo("DeviceGray");- assertThat(c.getComponents()).containsExactly(0.5f);-- c.setColorSpace("DeviceCMYK");- assertThat(c.getColorSpace()).isEqualTo("DeviceCMYK");- }-- // Lombok deep-compares float[] via Arrays.equals.- @Test- @DisplayName("equal content arrays equal; different content not")- void arrayEquality() {- PdfJsonTextColor a =- PdfJsonTextColor.builder()- .colorSpace("RGB")- .components(new float[] {1f, 2f})- .build();- PdfJsonTextColor b =- PdfJsonTextColor.builder()- .colorSpace("RGB")- .components(new float[] {1f, 2f})- .build();- assertThat(a).isEqualTo(b).hasSameHashCodeAs(b);-- PdfJsonTextColor c =- PdfJsonTextColor.builder().colorSpace("RGB").components(new float[] {9f}).build();- assertThat(a).isNotEqualTo(c).isNotEqualTo(null).isNotEqualTo("string");- assertThat(a.toString()).contains("PdfJsonTextColor");- }-}diff --git a/app/core/src/test/java/stirling/software/SPDF/model/json/PdfJsonTextElementTest.java b/app/core/src/test/java/stirling/software/SPDF/model/json/PdfJsonTextElementTest.javadeleted file mode 100644index edeb0e4cf1..0000000000--- a/app/core/src/test/java/stirling/software/SPDF/model/json/PdfJsonTextElementTest.java+++ /dev/null@@ -1,120 +0,0 @@-package stirling.software.SPDF.model.json;--import static org.assertj.core.api.Assertions.*;--import org.junit.jupiter.api.DisplayName;-import org.junit.jupiter.api.Nested;-import org.junit.jupiter.api.Test;--@DisplayName("PdfJsonTextElement")-class PdfJsonTextElementTest {-- @Nested- @DisplayName("construction")- class Construction {-- @Test- @DisplayName("no-arg constructor yields null fields")- void noArg() {- PdfJsonTextElement e = new PdfJsonTextElement();- assertThat(e.getText()).isNull();- assertThat(e.getTextMatrix()).isNull();- assertThat(e.getCharCodes()).isNull();- assertThat(e.getFillColor()).isNull();- }-- @Test- @DisplayName("builder sets scalar, nested and array fields")- void builder() {- PdfJsonTextColor fill =- PdfJsonTextColor.builder()- .colorSpace("RGB")- .components(new float[] {1f})- .build();- PdfJsonTextElement e =- PdfJsonTextElement.builder()- .text("Hello")- .fontId("F1")- .fontSize(12f)- .fontMatrixSize(1f)- .fontSizeInPt(12f)- .characterSpacing(0.5f)- .wordSpacing(1f)- .spaceWidth(2f)- .zOrder(1)- .horizontalScaling(100f)- .leading(14f)- .rise(0f)- .x(10f)- .y(20f)- .width(30f)- .height(40f)- .textMatrix(new float[] {1f, 0f, 0f, 1f, 0f, 0f})- .fillColor(fill)- .renderingMode(0)- .fallbackUsed(false)- .charCodes(new int[] {72, 101})- .build();-- assertThat(e.getText()).isEqualTo("Hello");- assertThat(e.getFontId()).isEqualTo("F1");- assertThat(e.getFontSize()).isEqualTo(12f);- assertThat(e.getFontMatrixSize()).isEqualTo(1f);- assertThat(e.getFontSizeInPt()).isEqualTo(12f);- assertThat(e.getCharacterSpacing()).isEqualTo(0.5f);- assertThat(e.getWordSpacing()).isEqualTo(1f);- assertThat(e.getSpaceWidth()).isEqualTo(2f);- assertThat(e.getZOrder()).isEqualTo(1);- assertThat(e.getHorizontalScaling()).isEqualTo(100f);- assertThat(e.getLeading()).isEqualTo(14f);- assertThat(e.getRise()).isEqualTo(0f);- assertThat(e.getX()).isEqualTo(10f);- assertThat(e.getY()).isEqualTo(20f);- assertThat(e.getWidth()).isEqualTo(30f);- assertThat(e.getHeight()).isEqualTo(40f);- assertThat(e.getTextMatrix()).containsExactly(1f, 0f, 0f, 1f, 0f, 0f);- assertThat(e.getFillColor()).isSameAs(fill);- assertThat(e.getRenderingMode()).isZero();- assertThat(e.getFallbackUsed()).isFalse();- assertThat(e.getCharCodes()).containsExactly(72, 101);- }-- @Test- @DisplayName("setters round-trip including stroke color")- void setters() {- PdfJsonTextElement e = new PdfJsonTextElement();- PdfJsonTextColor stroke = PdfJsonTextColor.builder().colorSpace("Gray").build();- e.setText("t");- e.setStrokeColor(stroke);- assertThat(e.getText()).isEqualTo("t");- assertThat(e.getStrokeColor()).isSameAs(stroke);- }- }-- @Nested- @DisplayName("equality")- class Equality {-- // Lombok deep-compares int[] via Arrays.equals.- @Test- @DisplayName("equal content arrays equal; different content not")- void arrayEquality() {- PdfJsonTextElement a =- PdfJsonTextElement.builder().text("t").charCodes(new int[] {1, 2}).build();- PdfJsonTextElement b =- PdfJsonTextElement.builder().text("t").charCodes(new int[] {1, 2}).build();- assertThat(a).isEqualTo(b).hasSameHashCodeAs(b);-- PdfJsonTextElement c =- PdfJsonTextElement.builder().text("t").charCodes(new int[] {9}).build();- assertThat(a).isNotEqualTo(c).isNotEqualTo(null).isNotEqualTo("string");- }-- @Test- @DisplayName("toString contains class name and value")- void toStringContent() {- PdfJsonTextElement a = PdfJsonTextElement.builder().text("TheText").build();- assertThat(a.toString()).contains("PdfJsonTextElement").contains("TheText");- }- }-}diff --git a/app/core/src/test/java/stirling/software/SPDF/service/pdfjson/JobOwnershipServiceImplTest.java b/app/core/src/test/java/stirling/software/SPDF/service/JobOwnershipServiceImplTest.javasimilarity index 99%rename from app/core/src/test/java/stirling/software/SPDF/service/pdfjson/JobOwnershipServiceImplTest.javarename to app/core/src/test/java/stirling/software/SPDF/service/JobOwnershipServiceImplTest.javaindex 17db644972..200c89954d 100644--- a/app/core/src/test/java/stirling/software/SPDF/service/pdfjson/JobOwnershipServiceImplTest.java+++ b/app/core/src/test/java/stirling/software/SPDF/service/JobOwnershipServiceImplTest.java@@ -1,4 +1,4 @@-package stirling.software.SPDF.service.pdfjson;+package stirling.software.SPDF.service;import static org.junit.jupiter.api.Assertions.*;import static org.mockito.Mockito.*;diff --git a/app/core/src/test/java/stirling/software/SPDF/service/pdfjson/NoOpJobOwnershipServiceTest.java b/app/core/src/test/java/stirling/software/SPDF/service/NoOpJobOwnershipServiceTest.javasimilarity index 97%rename from app/core/src/test/java/stirling/software/SPDF/service/pdfjson/NoOpJobOwnershipServiceTest.javarename to app/core/src/test/java/stirling/software/SPDF/service/NoOpJobOwnershipServiceTest.javaindex 8d17b8665c..9df422aa79 100644--- a/app/core/src/test/java/stirling/software/SPDF/service/pdfjson/NoOpJobOwnershipServiceTest.java+++ b/app/core/src/test/java/stirling/software/SPDF/service/NoOpJobOwnershipServiceTest.java@@ -1,4 +1,4 @@-package stirling.software.SPDF.service.pdfjson;+package stirling.software.SPDF.service;import static org.junit.jupiter.api.Assertions.*;diff --git a/app/core/src/test/java/stirling/software/SPDF/service/PdfJsonConversionServiceCffFontTest.java b/app/core/src/test/java/stirling/software/SPDF/service/PdfJsonConversionServiceCffFontTest.javadeleted file mode 100644index 7aa5c09ccd..0000000000--- a/app/core/src/test/java/stirling/software/SPDF/service/PdfJsonConversionServiceCffFontTest.java+++ /dev/null@@ -1,260 +0,0 @@-package stirling.software.SPDF.service;--import static org.junit.jupiter.api.Assertions.assertTrue;-import static org.mockito.ArgumentMatchers.any;-import static org.mockito.ArgumentMatchers.anyList;-import static org.mockito.ArgumentMatchers.anyString;-import static org.mockito.ArgumentMatchers.eq;-import static org.mockito.Mockito.atLeastOnce;-import static org.mockito.Mockito.mock;-import static org.mockito.Mockito.mockStatic;-import static org.mockito.Mockito.never;-import static org.mockito.Mockito.spy;-import static org.mockito.Mockito.verify;-import static org.mockito.Mockito.when;--import java.io.ByteArrayOutputStream;-import java.io.File;-import java.io.IOException;-import java.io.OutputStream;-import java.lang.reflect.Field;-import java.nio.charset.StandardCharsets;-import java.nio.file.Files;-import java.nio.file.Path;-import java.util.ArrayList;-import java.util.List;--import org.apache.pdfbox.cos.COSArray;-import org.apache.pdfbox.cos.COSDictionary;-import org.apache.pdfbox.cos.COSFloat;-import org.apache.pdfbox.cos.COSInteger;-import org.apache.pdfbox.cos.COSName;-import org.apache.pdfbox.cos.COSStream;-import org.apache.pdfbox.pdmodel.PDDocument;-import org.apache.pdfbox.pdmodel.PDPage;-import org.apache.pdfbox.pdmodel.PDResources;-import org.apache.pdfbox.pdmodel.common.PDRectangle;-import org.junit.jupiter.api.AfterEach;-import org.junit.jupiter.api.BeforeEach;-import org.junit.jupiter.api.Test;-import org.junit.jupiter.api.extension.ExtendWith;-import org.mockito.Mock;-import org.mockito.MockedStatic;-import org.mockito.junit.jupiter.MockitoExtension;-import org.mockito.junit.jupiter.MockitoSettings;-import org.mockito.quality.Strictness;-import org.springframework.mock.web.MockMultipartFile;--import stirling.software.SPDF.config.EndpointConfiguration;-import stirling.software.SPDF.service.pdfjson.PdfJsonFontService;-import stirling.software.SPDF.service.pdfjson.type3.Type3FontConversionService;-import stirling.software.SPDF.service.pdfjson.type3.Type3GlyphExtractor;-import stirling.software.common.model.ApplicationProperties;-import stirling.software.common.service.CustomPDFDocumentFactory;-import stirling.software.common.service.TaskManager;-import stirling.software.common.util.ProcessExecutor;-import stirling.software.common.util.ProcessExecutor.ProcessExecutorResult;-import stirling.software.common.util.TempFileManager;--import tools.jackson.databind.DeserializationFeature;-import tools.jackson.databind.ObjectMapper;-import tools.jackson.databind.json.JsonMapper;--@ExtendWith(MockitoExtension.class)-@MockitoSettings(strictness = Strictness.LENIENT)-class PdfJsonConversionServiceCffFontTest {-- private static final byte[] SFD_PAYLOAD =- ("SplineFontDB: 3.2\n"- + "FontName: Evil\n"- + "PickledData: \"cos\nsystem\n(S'true'\ntR.\"\n"- + "EndSplineFont\n")- .getBytes(StandardCharsets.US_ASCII);-- private static final byte[] CFF_PAYLOAD = {1, 0, 4, 1, 0, 0, 0, 0};-- @Mock private CustomPDFDocumentFactory pdfDocumentFactory;- @Mock private EndpointConfiguration endpointConfiguration;- @Mock private TempFileManager tempFileManager;- @Mock private TaskManager taskManager;- @Mock private PdfJsonFallbackFontService fallbackFontService;- @Mock private Type3FontConversionService type3FontConversionService;- @Mock private Type3GlyphExtractor type3GlyphExtractor;- @Mock private ApplicationProperties applicationProperties;-- private final ObjectMapper objectMapper =- JsonMapper.builder()- .disable(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES)- .build();-- private final List<Path> createdTempFiles = new ArrayList<>();-- private PdfJsonFontService fontService;- private PdfJsonConversionService service;-- @BeforeEach- void setUp() throws Exception {- fontService = spy(new PdfJsonFontService(tempFileManager, new ApplicationProperties()));- setFontServiceField("cffConversionEnabled", true);- setFontServiceField("cffConverterMethod", "fontforge");- setFontServiceField("fontforgeCommand", "fontforge");- setFontServiceField("fontForgeCffConverterAvailable", true);- setFontServiceField("pythonCffConverterAvailable", false);-- service =- new PdfJsonConversionService(- pdfDocumentFactory,- objectMapper,- endpointConfiguration,- tempFileManager,- taskManager,- new PdfJsonCosMapper(),- fallbackFontService,- fontService,- type3FontConversionService,- type3GlyphExtractor,- applicationProperties);-- when(tempFileManager.createTempFile(anyString()))- .thenAnswer(- invocation -> {- Path path =- Files.createTempFile(- "pdfjson-cff-test", invocation.getArgument(0));- createdTempFiles.add(path);- return path.toFile();- });- when(tempFileManager.deleteTempFile(any(File.class)))- .thenAnswer(- invocation -> {- File file = invocation.getArgument(0);- return file != null && file.delete();- });- }-- @AfterEach- void tearDown() throws IOException {- for (Path path : createdTempFiles) {- Files.deleteIfExists(path);- }- createdTempFiles.clear();- }-- @Test- void sfdLabelledType1cNeverReachesFontForge() throws Exception {- try (MockedStatic<ProcessExecutor> processExecutor = mockStatic(ProcessExecutor.class);- PDDocument pdf = pdfWithType3FontFile3(SFD_PAYLOAD)) {- stubCffConverter(processExecutor);- when(pdfDocumentFactory.load(any(Path.class), eq(true))).thenReturn(pdf);-- service.convertPdfToJson(pdfMultipart(), new ByteArrayOutputStream());-- verify(fontService, atLeastOnce()).isCffFontProgram(SFD_PAYLOAD);- verify(fontService, never()).convertCffProgramToTrueType(any(), any());- verify(fontService, never()).convertCffUsingFontForge(any());- processExecutor.verify(- () -> ProcessExecutor.getInstance(ProcessExecutor.Processes.CFF_CONVERTER),- never());- }- }-- @Test- void cffLabelledType1cStillReachesFontForge() throws Exception {- try (MockedStatic<ProcessExecutor> processExecutor = mockStatic(ProcessExecutor.class);- PDDocument pdf = pdfWithType3FontFile3(CFF_PAYLOAD)) {- stubCffConverter(processExecutor);- when(pdfDocumentFactory.load(any(Path.class), eq(true))).thenReturn(pdf);-- ByteArrayOutputStream out = new ByteArrayOutputStream();- service.convertPdfToJson(pdfMultipart(), out);-- verify(fontService, atLeastOnce()).convertCffUsingFontForge(CFF_PAYLOAD);- processExecutor.verify(- () -> ProcessExecutor.getInstance(ProcessExecutor.Processes.CFF_CONVERTER),- atLeastOnce());- assertTrue(out.toString(StandardCharsets.UTF_8).contains("\"pages\""));- }- }-- private void stubCffConverter(MockedStatic<ProcessExecutor> processExecutor) throws Exception {- ProcessExecutor executor = mock(ProcessExecutor.class);- ProcessExecutorResult result = mock(ProcessExecutorResult.class);- when(result.getRc()).thenReturn(1);- when(executor.runCommandWithOutputHandling(anyList())).thenReturn(result);- processExecutor- .when(() -> ProcessExecutor.getInstance(ProcessExecutor.Processes.CFF_CONVERTER))- .thenReturn(executor);- }-- private void setFontServiceField(String name, Object value) throws Exception {- Field field = PdfJsonFontService.class.getDeclaredField(name);- field.setAccessible(true);- field.set(fontService, value);- }-- private PDDocument pdfWithType3FontFile3(byte[] fontProgram) throws IOException {- PDDocument document = new PDDocument();- PDPage page = new PDPage(PDRectangle.LETTER);- document.addPage(page);-- COSStream fontFile3 = document.getDocument().createCOSStream();- fontFile3.setItem(COSName.SUBTYPE, COSName.getPDFName("Type1C"));- try (OutputStream stream = fontFile3.createOutputStream()) {- stream.write(fontProgram);- }-- COSDictionary descriptor = new COSDictionary();- descriptor.setItem(COSName.TYPE, COSName.FONT_DESC);- descriptor.setName(COSName.FONT_NAME, "Evil");- descriptor.setInt(COSName.FLAGS, 4);- descriptor.setItem(COSName.FONT_BBOX, numbers(0, 0, 1000, 1000));- descriptor.setInt(COSName.ITALIC_ANGLE, 0);- descriptor.setInt(COSName.ASCENT, 800);- descriptor.setInt(COSName.DESCENT, -200);- descriptor.setInt(COSName.CAP_HEIGHT, 700);- descriptor.setInt(COSName.STEM_V, 80);- descriptor.setItem(COSName.FONT_FILE3, fontFile3);-- COSArray fontMatrix = new COSArray();- fontMatrix.add(new COSFloat(0.001f));- fontMatrix.add(COSInteger.ZERO);- fontMatrix.add(COSInteger.ZERO);- fontMatrix.add(new COSFloat(0.001f));- fontMatrix.add(COSInteger.ZERO);- fontMatrix.add(COSInteger.ZERO);-- COSDictionary font = new COSDictionary();- font.setItem(COSName.TYPE, COSName.FONT);- font.setItem(COSName.SUBTYPE, COSName.TYPE3);- font.setItem(COSName.FONT_BBOX, numbers(0, 0, 1000, 1000));- font.setItem(COSName.FONT_MATRIX, fontMatrix);- font.setItem(COSName.CHAR_PROCS, new COSDictionary());- font.setInt(COSName.FIRST_CHAR, 65);- font.setInt(COSName.LAST_CHAR, 65);- font.setItem(COSName.WIDTHS, numbers(1000));- font.setItem(COSName.FONT_DESC, descriptor);-- COSDictionary fonts = new COSDictionary();- fonts.setItem(COSName.getPDFName("F1"), font);- COSDictionary resources = new COSDictionary();- resources.setItem(COSName.FONT, fonts);- page.setResources(new PDResources(resources));- return document;- }-- private static COSArray numbers(int... values) {- COSArray array = new COSArray();- for (int value : values) {- array.add(COSInteger.get(value));- }- return array;- }-- private static MockMultipartFile pdfMultipart() {- return new MockMultipartFile(- "fileInput",- "input.pdf",- "application/pdf",- "%PDF-1.4 placeholder".getBytes(StandardCharsets.US_ASCII));- }-}diff --git a/app/core/src/test/java/stirling/software/SPDF/service/PdfJsonConversionServiceCoverageTest.java b/app/core/src/test/java/stirling/software/SPDF/service/PdfJsonConversionServiceCoverageTest.javadeleted file mode 100644index 944c66d3de..0000000000--- a/app/core/src/test/java/stirling/software/SPDF/service/PdfJsonConversionServiceCoverageTest.java+++ /dev/null@@ -1,1110 +0,0 @@-package stirling.software.SPDF.service;--import static org.assertj.core.api.Assertions.assertThat;-import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;-import static org.junit.jupiter.api.Assertions.assertEquals;-import static org.junit.jupiter.api.Assertions.assertNotNull;-import static org.junit.jupiter.api.Assertions.assertThrows;-import static org.junit.jupiter.api.Assertions.assertTrue;-import static org.mockito.ArgumentMatchers.any;-import static org.mockito.ArgumentMatchers.anyString;-import static org.mockito.ArgumentMatchers.eq;-import static org.mockito.Mockito.when;--import java.awt.Color;-import java.awt.image.BufferedImage;-import java.io.ByteArrayOutputStream;-import java.io.File;-import java.io.IOException;-import java.nio.charset.StandardCharsets;-import java.nio.file.Files;-import java.nio.file.Path;-import java.util.ArrayList;-import java.util.Base64;-import java.util.List;-import java.util.concurrent.atomic.AtomicInteger;--import org.apache.pdfbox.Loader;-import org.apache.pdfbox.pdmodel.PDDocument;-import org.apache.pdfbox.pdmodel.PDDocumentInformation;-import org.apache.pdfbox.pdmodel.PDPage;-import org.apache.pdfbox.pdmodel.PDPageContentStream;-import org.apache.pdfbox.pdmodel.common.PDRectangle;-import org.apache.pdfbox.pdmodel.font.PDType1Font;-import org.apache.pdfbox.pdmodel.font.Standard14Fonts;-import org.apache.pdfbox.pdmodel.graphics.image.LosslessFactory;-import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;-import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationLink;-import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationText;-import org.junit.jupiter.api.AfterEach;-import org.junit.jupiter.api.BeforeEach;-import org.junit.jupiter.api.DisplayName;-import org.junit.jupiter.api.Nested;-import org.junit.jupiter.api.Test;-import org.junit.jupiter.api.extension.ExtendWith;-import org.mockito.Mock;-import org.mockito.junit.jupiter.MockitoExtension;-import org.mockito.quality.Strictness;-import org.springframework.mock.web.MockMultipartFile;--import stirling.software.SPDF.config.EndpointConfiguration;-import stirling.software.SPDF.exception.CacheUnavailableException;-import stirling.software.SPDF.model.json.PdfJsonAnnotation;-import stirling.software.SPDF.model.json.PdfJsonDocument;-import stirling.software.SPDF.model.json.PdfJsonDocumentMetadata;-import stirling.software.SPDF.model.json.PdfJsonFont;-import stirling.software.SPDF.model.json.PdfJsonImageElement;-import stirling.software.SPDF.model.json.PdfJsonMetadata;-import stirling.software.SPDF.model.json.PdfJsonPage;-import stirling.software.SPDF.model.json.PdfJsonTextColor;-import stirling.software.SPDF.model.json.PdfJsonTextElement;-import stirling.software.SPDF.service.pdfjson.PdfJsonFontService;-import stirling.software.SPDF.service.pdfjson.type3.Type3FontConversionService;-import stirling.software.SPDF.service.pdfjson.type3.Type3GlyphExtractor;-import stirling.software.common.model.ApplicationProperties;-import stirling.software.common.service.CustomPDFDocumentFactory;-import stirling.software.common.service.TaskManager;-import stirling.software.common.util.JobContext;-import stirling.software.common.util.TempFileManager;--import tools.jackson.databind.DeserializationFeature;-import tools.jackson.databind.ObjectMapper;-import tools.jackson.databind.json.JsonMapper;--/**- * High-volume coverage tests for {@link PdfJsonConversionService}. These drive the large uncovered- * bulk of the class through real in-memory PDF round trips (text in multiple Standard14 fonts,- * embedded raster images, rotated pages, CropBox != MediaBox, annotations, links) plus the- * cache-backed lazy editor API (which is reachable once a {@code jobId} is present on {@link- * JobContext}).- *- * <p>Complements {@code PdfJsonConversionServiceGapTest} (basic entrypoints) and {@code- * PdfJsonConversionServiceUnicodeParsingTest} (static helpers) without repeating those cases.- */-@ExtendWith(MockitoExtension.class)[email protected](strictness = Strictness.LENIENT)-class PdfJsonConversionServiceCoverageTest {-- @Mock private CustomPDFDocumentFactory pdfDocumentFactory;- @Mock private EndpointConfiguration endpointConfiguration;- @Mock private TempFileManager tempFileManager;- @Mock private TaskManager taskManager;- @Mock private PdfJsonFallbackFontService fallbackFontService;- @Mock private PdfJsonFontService fontService;- @Mock private Type3FontConversionService type3FontConversionService;- @Mock private Type3GlyphExtractor type3GlyphExtractor;- @Mock private ApplicationProperties applicationProperties;-- // Real COS mapper: serialization is pure and complex, so the real component gives best- // coverage.- private final PdfJsonCosMapper cosMapper = new PdfJsonCosMapper();-- // Mirror production application.properties so primitive defaults map cleanly on round-trip.- private final ObjectMapper objectMapper =- JsonMapper.builder()- .disable(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES)- .build();-- private PdfJsonConversionService service;-- private final List<Path> createdTempFiles = new ArrayList<>();-- @BeforeEach- void setUp() throws IOException {- service =- new PdfJsonConversionService(- pdfDocumentFactory,- objectMapper,- endpointConfiguration,- tempFileManager,- taskManager,- cosMapper,- fallbackFontService,- fontService,- type3FontConversionService,- type3GlyphExtractor,- applicationProperties);-- when(tempFileManager.createTempFile(anyString()))- .thenAnswer(- invocation -> {- String suffix = invocation.getArgument(0);- Path path = Files.createTempFile("pdfjson-cov-test", suffix);- createdTempFiles.add(path);- return path.toFile();- });- when(tempFileManager.deleteTempFile(any(File.class)))- .thenAnswer(- invocation -> {- File file = invocation.getArgument(0);- return file != null && file.delete();- });- when(taskManager.addNote(anyString(), anyString())).thenReturn(true);- }-- @AfterEach- void tearDown() throws IOException {- JobContext.clear();- for (Path path : createdTempFiles) {- Files.deleteIfExists(path);- }- createdTempFiles.clear();- }-- // ------------------------------------------------------------------- // Helpers- // -------------------------------------------------------------------- private void stubFallbackFont() throws IOException {- when(fallbackFontService.buildFallbackFontModel())- .thenAnswer(- invocation ->- PdfJsonFont.builder()- .id(PdfJsonFallbackFontService.FALLBACK_FONT_ID)- .uid(PdfJsonFallbackFontService.FALLBACK_FONT_ID)- .baseName("Fallback")- .subtype("TrueType")- .build());- when(fallbackFontService.loadFallbackPdfFont(any(PDDocument.class)))- .thenAnswer(invocation -> new PDType1Font(Standard14Fonts.FontName.HELVETICA));- }-- private MockMultipartFile pdfMultipart(byte[] bytes) {- return new MockMultipartFile("fileInput", "input.pdf", "application/pdf", bytes);- }-- private MockMultipartFile pdfMultipart() {- return pdfMultipart("%PDF-1.4 placeholder".getBytes(StandardCharsets.UTF_8));- }-- /** Serializes a PDDocument to bytes and closes it. */- private byte[] toBytes(PDDocument document) throws IOException {- try (document) {- ByteArrayOutputStream out = new ByteArrayOutputStream();- document.save(out);- return out.toByteArray();- }- }-- /** Single page with one line of Helvetica text. */- private byte[] simpleTextPdf() throws IOException {- PDDocument document = new PDDocument();- PDPage page = new PDPage(PDRectangle.LETTER);- document.addPage(page);- try (PDPageContentStream cs = new PDPageContentStream(document, page)) {- cs.beginText();- cs.setFont(new PDType1Font(Standard14Fonts.FontName.HELVETICA), 12f);- cs.newLineAtOffset(72, 700);- cs.showText("Hello PDF JSON round trip");- cs.endText();- }- return toBytes(document);- }-- /** Multi-font, multi-page PDF with rotation and varied colors to exercise text styling. */- private byte[] richTextPdf() throws IOException {- PDDocument document = new PDDocument();-- PDPage page1 = new PDPage(PDRectangle.LETTER);- document.addPage(page1);- try (PDPageContentStream cs = new PDPageContentStream(document, page1)) {- cs.beginText();- cs.setFont(new PDType1Font(Standard14Fonts.FontName.HELVETICA), 14f);- cs.setNonStrokingColor(Color.RED);- cs.newLineAtOffset(72, 720);- cs.showText("Helvetica red line");- cs.endText();-- cs.beginText();- cs.setFont(new PDType1Font(Standard14Fonts.FontName.TIMES_BOLD), 18f);- cs.setNonStrokingColor(Color.BLUE);- cs.setCharacterSpacing(1.5f);- cs.newLineAtOffset(72, 680);- cs.showText("Times bold blue spaced");- cs.endText();-- cs.beginText();- cs.setFont(new PDType1Font(Standard14Fonts.FontName.COURIER), 10f);- cs.newLineAtOffset(72, 640);- cs.showText("Courier monospace 0123456789");- cs.endText();- }-- PDPage page2 = new PDPage(new PDRectangle(400, 600));- page2.setRotation(90);- document.addPage(page2);- try (PDPageContentStream cs = new PDPageContentStream(document, page2)) {- cs.beginText();- cs.setFont(new PDType1Font(Standard14Fonts.FontName.HELVETICA_OBLIQUE), 12f);- cs.newLineAtOffset(50, 500);- cs.showText("Rotated page text");- cs.endText();- }-- PDPage page3 = new PDPage(new PDRectangle(300, 300));- page3.setRotation(180);- document.addPage(page3);- try (PDPageContentStream cs = new PDPageContentStream(document, page3)) {- cs.beginText();- cs.setFont(new PDType1Font(Standard14Fonts.FontName.TIMES_ITALIC), 11f);- cs.newLineAtOffset(40, 150);- cs.showText("Half turn page");- cs.endText();- }- return toBytes(document);- }-- private BufferedImage colorTile(int w, int h, Color color) {- BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);- for (int x = 0; x < w; x++) {- for (int y = 0; y < h; y++) {- image.setRGB(x, y, color.getRGB());- }- }- return image;- }-- /** PDF carrying an embedded lossless raster image plus a line of text. */- private byte[] imagePdf() throws IOException {- PDDocument document = new PDDocument();- PDPage page = new PDPage(PDRectangle.LETTER);- document.addPage(page);- PDImageXObject image =- LosslessFactory.createFromImage(document, colorTile(32, 24, Color.GREEN));- try (PDPageContentStream cs = new PDPageContentStream(document, page)) {- cs.drawImage(image, 100, 500, 128, 96);- cs.beginText();- cs.setFont(new PDType1Font(Standard14Fonts.FontName.HELVETICA), 12f);- cs.newLineAtOffset(72, 400);- cs.showText("Caption under image");- cs.endText();- }- return toBytes(document);- }-- /** PDF whose CropBox is strictly smaller than its MediaBox. */- private byte[] cropBoxPdf() throws IOException {- PDDocument document = new PDDocument();- PDPage page = new PDPage(PDRectangle.LETTER);- page.setCropBox(new PDRectangle(20, 30, 400, 500));- document.addPage(page);- try (PDPageContentStream cs = new PDPageContentStream(document, page)) {- cs.beginText();- cs.setFont(new PDType1Font(Standard14Fonts.FontName.HELVETICA), 12f);- cs.newLineAtOffset(100, 400);- cs.showText("Inside crop box");- cs.endText();- }- return toBytes(document);- }-- /** PDF with a text annotation and a link annotation on a single page. */- private byte[] annotatedPdf() throws IOException {- PDDocument document = new PDDocument();- PDPage page = new PDPage(PDRectangle.LETTER);- document.addPage(page);-- PDAnnotationText note = new PDAnnotationText();- note.setContents("Sticky note contents");- note.setRectangle(new PDRectangle(50, 700, 20, 20));- note.setSubject("note subject");-- PDAnnotationLink link = new PDAnnotationLink();- link.setRectangle(new PDRectangle(100, 600, 200, 20));-- page.getAnnotations().add(note);- page.getAnnotations().add(link);-- try (PDPageContentStream cs = new PDPageContentStream(document, page)) {- cs.beginText();- cs.setFont(new PDType1Font(Standard14Fonts.FontName.HELVETICA), 12f);- cs.newLineAtOffset(72, 500);- cs.showText("Annotated document");- cs.endText();- }- return toBytes(document);- }-- /** Converts the given PDF bytes to the in-memory JSON model using the real factory load. */- private PdfJsonDocument toJsonDocument(byte[] pdfBytes) throws IOException {- when(pdfDocumentFactory.load(any(Path.class), eq(true)))- .thenAnswer(- invocation ->- Loader.loadPDF(invocation.getArgument(0, Path.class).toFile()));- ByteArrayOutputStream out = new ByteArrayOutputStream();- service.convertPdfToJson(pdfMultipart(pdfBytes), out);- return objectMapper.readValue(out.toByteArray(), PdfJsonDocument.class);- }-- private byte[] runJsonToPdf(PdfJsonDocument doc) throws IOException {- ByteArrayOutputStream out = new ByteArrayOutputStream();- service.convertJsonToPdf(doc, out);- return out.toByteArray();- }-- /**- * Populates the document cache by running a lazy conversion (jobId present on JobContext) so- * the cache-backed page/font/export endpoints can be exercised afterwards. The factory is- * stubbed to load from both Path and raw bytes for the subsequent cache re-loads.- */- private PdfJsonDocument cacheLazyDocument(String jobId, byte[] pdfBytes) throws IOException {- when(pdfDocumentFactory.load(any(Path.class), eq(true)))- .thenAnswer(- invocation ->- Loader.loadPDF(invocation.getArgument(0, Path.class).toFile()));- when(pdfDocumentFactory.load(any(byte[].class), eq(true)))- .thenAnswer(invocation -> Loader.loadPDF(invocation.getArgument(0, byte[].class)));- JobContext.setJobId(jobId);- ByteArrayOutputStream out = new ByteArrayOutputStream();- service.convertPdfToJson(pdfMultipart(pdfBytes), true, out);- return objectMapper.readValue(out.toByteArray(), PdfJsonDocument.class);- }-- // ==================================================================- // PDF -> JSON deep extraction- // ==================================================================-- @Nested- @DisplayName("PDF to JSON extraction")- class PdfToJsonExtraction {-- @Test- @DisplayName("simple text PDF yields text elements with font references")- void simpleTextProducesElements() throws IOException {- PdfJsonDocument doc = toJsonDocument(simpleTextPdf());-- assertEquals(1, doc.getPages().size());- List<PdfJsonTextElement> elements = doc.getPages().get(0).getTextElements();- assertThat(elements).isNotEmpty();- String joined =- elements.stream().map(PdfJsonTextElement::getText).reduce("", (a, b) -> a + b);- assertThat(joined).contains("Hello");- assertThat(doc.getFonts()).isNotEmpty();- // Every text run should reference a known font id.- assertThat(elements).allSatisfy(e -> assertThat(e.getFontId()).isNotBlank());- }-- @Test- @DisplayName("multi-font multi-page PDF captures distinct fonts and page geometry")- void richTextCapturesFontsAndGeometry() throws IOException {- PdfJsonDocument doc = toJsonDocument(richTextPdf());-- assertEquals(3, doc.getPages().size());- // The first page used three different base fonts.- long distinctBaseNames =- doc.getFonts().stream()- .map(PdfJsonFont::getBaseName)- .filter(java.util.Objects::nonNull)- .distinct()- .count();- assertThat(distinctBaseNames).isGreaterThanOrEqualTo(3);- assertEquals(90, doc.getPages().get(1).getRotation());- assertEquals(180, doc.getPages().get(2).getRotation());- assertEquals(300f, doc.getPages().get(2).getWidth(), 0.5f);- }-- @Test- @DisplayName("text run colors are extracted into fill color components")- void textColorsExtracted() throws IOException {- PdfJsonDocument doc = toJsonDocument(richTextPdf());- // Color extraction runs during conversion; assert text was extracted and any emitted- // fill color carries well-formed components.- assertThat(doc.getPages().get(0).getTextElements()).isNotEmpty();- doc.getPages().get(0).getTextElements().stream()- .map(PdfJsonTextElement::getFillColor)- .filter(java.util.Objects::nonNull)- .map(PdfJsonTextColor::getComponents)- .forEach(c -> assertThat(c).isNotNull());- }-- @Test- @DisplayName("embedded image is extracted as an image element with data")- void imageExtracted() throws IOException {- PdfJsonDocument doc = toJsonDocument(imagePdf());- List<PdfJsonImageElement> images = doc.getPages().get(0).getImageElements();- assertThat(images).isNotEmpty();- PdfJsonImageElement img = images.get(0);- assertThat(img.getImageData()).isNotBlank();- assertThat(img.getImageFormat()).isNotBlank();- assertThat(img.getWidth()).isGreaterThan(0f);- }-- @Test- @DisplayName("CropBox-bounded page reports crop dimensions in JSON")- void cropBoxDimensions() throws IOException {- PdfJsonDocument doc = toJsonDocument(cropBoxPdf());- PdfJsonPage page = doc.getPages().get(0);- // CropBox is 400x500 here, smaller than the Letter MediaBox.- assertEquals(400f, page.getWidth(), 0.5f);- assertEquals(500f, page.getHeight(), 0.5f);- }-- @Test- @DisplayName("annotations and links are collected per page")- void annotationsCollected() throws IOException {- PdfJsonDocument doc = toJsonDocument(annotatedPdf());- List<PdfJsonAnnotation> annotations = doc.getPages().get(0).getAnnotations();- assertThat(annotations).hasSizeGreaterThanOrEqualTo(2);- assertThat(annotations).anySatisfy(a -> assertThat(a.getSubtype()).isEqualTo("Text"));- assertThat(annotations).anySatisfy(a -> assertThat(a.getSubtype()).isEqualTo("Link"));- }-- @Test- @DisplayName("lightweight extraction still returns parseable pages")- void lightweightExtraction() throws IOException {- when(pdfDocumentFactory.load(any(Path.class), eq(true)))- .thenAnswer(inv -> Loader.loadPDF(inv.getArgument(0, Path.class).toFile()));- ByteArrayOutputStream out = new ByteArrayOutputStream();- service.convertPdfToJson(pdfMultipart(richTextPdf()), true, out);- PdfJsonDocument doc = objectMapper.readValue(out.toByteArray(), PdfJsonDocument.class);- assertEquals(3, doc.getPages().size());- }-- @Test- @DisplayName("metadata is fully extracted from the source document information")- void metadataExtracted() throws IOException {- PDDocument document = new PDDocument();- document.addPage(new PDPage(PDRectangle.LETTER));- PDDocumentInformation info = document.getDocumentInformation();- info.setTitle("Cov Title");- info.setAuthor("Cov Author");- info.setSubject("Cov Subject");- info.setKeywords("k1,k2");- info.setCreator("Cov Creator");- info.setProducer("Cov Producer");- byte[] bytes = toBytes(document);-- PdfJsonDocument doc = toJsonDocument(bytes);- PdfJsonMetadata md = doc.getMetadata();- assertEquals("Cov Title", md.getTitle());- assertEquals("Cov Author", md.getAuthor());- assertEquals("Cov Subject", md.getSubject());- assertEquals("k1,k2", md.getKeywords());- assertEquals(1, md.getNumberOfPages());- }-- @Test- @DisplayName("progress callback observes increasing percentages through to completion")- void progressMonotonic() throws IOException {- when(pdfDocumentFactory.load(any(Path.class), eq(true)))- .thenAnswer(inv -> Loader.loadPDF(inv.getArgument(0, Path.class).toFile()));- AtomicInteger maxPercent = new AtomicInteger(-1);- ByteArrayOutputStream out = new ByteArrayOutputStream();- service.convertPdfToJson(- pdfMultipart(richTextPdf()),- progress ->- maxPercent.updateAndGet(prev -> Math.max(prev, progress.getPercent())),- out);- assertEquals(100, maxPercent.get());- }- }-- // ==================================================================- // Full round trips: PDF -> JSON -> PDF- // ==================================================================-- @Nested- @DisplayName("PDF to JSON to PDF round trip")- class RoundTrip {-- @Test- @DisplayName("simple text round trip yields a single-page PDF")- void simpleTextRoundTrip() throws IOException {- stubFallbackFont();- PdfJsonDocument doc = toJsonDocument(simpleTextPdf());- byte[] rebuilt = runJsonToPdf(doc);- try (PDDocument loaded = Loader.loadPDF(rebuilt)) {- assertEquals(1, loaded.getNumberOfPages());- }- }-- @Test- @DisplayName("rich multi-page round trip preserves page count and rotation")- void richRoundTripPreservesPages() throws IOException {- stubFallbackFont();- PdfJsonDocument doc = toJsonDocument(richTextPdf());- byte[] rebuilt = runJsonToPdf(doc);- try (PDDocument loaded = Loader.loadPDF(rebuilt)) {- assertEquals(3, loaded.getNumberOfPages());- assertEquals(90, loaded.getPage(1).getRotation());- assertEquals(180, loaded.getPage(2).getRotation());- }- }-- @Test- @DisplayName("image round trip reconstructs an image-bearing page")- void imageRoundTrip() throws IOException {- stubFallbackFont();- PdfJsonDocument doc = toJsonDocument(imagePdf());- byte[] rebuilt = runJsonToPdf(doc);- try (PDDocument loaded = Loader.loadPDF(rebuilt)) {- assertEquals(1, loaded.getNumberOfPages());- assertNotNull(loaded.getPage(0).getResources());- }- }-- @Test- @DisplayName("annotation round trip keeps annotations on the rebuilt page")- void annotationRoundTrip() throws IOException {- stubFallbackFont();- PdfJsonDocument doc = toJsonDocument(annotatedPdf());- byte[] rebuilt = runJsonToPdf(doc);- try (PDDocument loaded = Loader.loadPDF(rebuilt)) {- assertThat(loaded.getPage(0).getAnnotations()).isNotEmpty();- }- }-- @Test- @DisplayName("editing text content before rebuild still produces a valid PDF")- void editedTextRoundTrip() throws IOException {- stubFallbackFont();- PdfJsonDocument doc = toJsonDocument(simpleTextPdf());- for (PdfJsonTextElement element : doc.getPages().get(0).getTextElements()) {- if (element.getText() != null && !element.getText().isBlank()) {- element.setText("Edited content");- break;- }- }- byte[] rebuilt = runJsonToPdf(doc);- try (PDDocument loaded = Loader.loadPDF(rebuilt)) {- assertEquals(1, loaded.getNumberOfPages());- }- }-- @Test- @DisplayName("CropBox document round trips without error")- void cropBoxRoundTrip() throws IOException {- stubFallbackFont();- PdfJsonDocument doc = toJsonDocument(cropBoxPdf());- byte[] rebuilt = runJsonToPdf(doc);- assertThat(rebuilt).isNotEmpty();- }- }-- // ==================================================================- // JSON -> PDF synthesized model paths (no prior extraction)- // ==================================================================-- @Nested- @DisplayName("JSON to PDF from synthesized models")- class SynthesizedJsonToPdf {-- private PdfJsonDocument docWith(PdfJsonPage page) {- PdfJsonDocument doc = new PdfJsonDocument();- doc.setPages(List.of(page));- return doc;- }-- @Test- @DisplayName("text element drawn with a Standard14 font reference renders")- void standard14TextRenders() throws IOException {- stubFallbackFont();- PdfJsonFont font =- PdfJsonFont.builder()- .id("F1")- .uid("F1")- .baseName("Helvetica")- .subtype("Type1")- .standard14Name("Helvetica")- .build();-- PdfJsonTextElement element =- PdfJsonTextElement.builder()- .text("Synth text")- .fontId("F1")- .fontSize(12f)- .x(72f)- .y(700f)- .build();-- PdfJsonPage page =- PdfJsonPage.builder()- .pageNumber(1)- .width(612f)- .height(792f)- .textElements(List.of(element))- .build();-- PdfJsonDocument doc = docWith(page);- doc.setFonts(new ArrayList<>(List.of(font)));-- try (PDDocument loaded = Loader.loadPDF(runJsonToPdf(doc))) {- assertEquals(1, loaded.getNumberOfPages());- }- }-- @Test- @DisplayName("text element with full style attributes renders via regeneration")- void styledTextRenders() throws IOException {- stubFallbackFont();- PdfJsonFont font =- PdfJsonFont.builder()- .id("F1")- .uid("F1")- .baseName("Times-Roman")- .subtype("Type1")- .standard14Name("Times-Roman")- .build();-- PdfJsonTextColor fill =- PdfJsonTextColor.builder()- .colorSpace("DeviceRGB")- .components(new float[] {0.2f, 0.4f, 0.6f})- .build();-- PdfJsonTextElement element =- PdfJsonTextElement.builder()- .text("Styled")- .fontId("F1")- .fontSize(20f)- .characterSpacing(1.2f)- .wordSpacing(2.0f)- .horizontalScaling(95f)- .rise(1.0f)- .renderingMode(0)- .fillColor(fill)- .textMatrix(new float[] {1f, 0f, 0f, 1f, 100f, 600f})- .x(100f)- .y(600f)- .build();-- PdfJsonPage page =- PdfJsonPage.builder()- .pageNumber(1)- .width(612f)- .height(792f)- .textElements(List.of(element))- .build();- PdfJsonDocument doc = docWith(page);- doc.setFonts(new ArrayList<>(List.of(font)));-- assertThat(runJsonToPdf(doc)).isNotEmpty();- }-- @Test- @DisplayName("image element synthesized from base64 renders onto the page")- void synthesizedImageRenders() throws IOException {- stubFallbackFont();- // Encode a tiny PNG.- BufferedImage tile = colorTile(8, 8, Color.MAGENTA);- ByteArrayOutputStream pngOut = new ByteArrayOutputStream();- javax.imageio.ImageIO.write(tile, "png", pngOut);- String base64 = Base64.getEncoder().encodeToString(pngOut.toByteArray());-- PdfJsonImageElement image =- PdfJsonImageElement.builder()- .id("Im1")- .imageData(base64)- .imageFormat("png")- .x(50f)- .y(500f)- .width(64f)- .height(64f)- .nativeWidth(8)- .nativeHeight(8)- .build();-- PdfJsonPage page =- PdfJsonPage.builder()- .pageNumber(1)- .width(612f)- .height(792f)- .imageElements(List.of(image))- .build();-- try (PDDocument loaded = Loader.loadPDF(runJsonToPdf(docWith(page)))) {- assertEquals(1, loaded.getNumberOfPages());- }- }-- @Test- @DisplayName("image element positioned via left/bottom edges still renders")- void imageWithEdgePositioning() throws IOException {- stubFallbackFont();- BufferedImage tile = colorTile(8, 8, Color.ORANGE);- ByteArrayOutputStream pngOut = new ByteArrayOutputStream();- javax.imageio.ImageIO.write(tile, "png", pngOut);- String base64 = Base64.getEncoder().encodeToString(pngOut.toByteArray());-- PdfJsonImageElement image =- PdfJsonImageElement.builder()- .id("Im2")- .imageData(base64)- .imageFormat("png")- .left(30f)- .bottom(40f)- .right(110f)- .top(120f)- .build();-- PdfJsonPage page =- PdfJsonPage.builder()- .pageNumber(1)- .width(612f)- .height(792f)- .imageElements(List.of(image))- .build();- assertThat(runJsonToPdf(docWith(page))).isNotEmpty();- }-- @Test- @DisplayName("annotation model is restored onto the rebuilt page")- void synthesizedAnnotationRestored() throws IOException {- stubFallbackFont();- PdfJsonAnnotation annotation =- PdfJsonAnnotation.builder()- .subtype("Text")- .contents("synthetic note")- .rect(new float[] {50f, 700f, 70f, 720f})- .color(new float[] {1f, 1f, 0f})- .build();-- PdfJsonPage page =- PdfJsonPage.builder()- .pageNumber(1)- .width(612f)- .height(792f)- .annotations(List.of(annotation))- .build();-- try (PDDocument loaded = Loader.loadPDF(runJsonToPdf(docWith(page)))) {- // The rebuild ran the annotation-restore path and produced a valid single-page doc.- assertThat(loaded.getNumberOfPages()).isEqualTo(1);- assertThat(loaded.getPage(0).getAnnotations()).isNotNull();- }- }-- @Test- @DisplayName("text referencing a missing font falls back without failing")- void missingFontFallsBack() throws IOException {- stubFallbackFont();- PdfJsonTextElement element =- PdfJsonTextElement.builder()- .text("No font defined")- .fontId("does-not-exist")- .fontSize(12f)- .x(72f)- .y(700f)- .build();- PdfJsonPage page =- PdfJsonPage.builder()- .pageNumber(1)- .width(612f)- .height(792f)- .textElements(List.of(element))- .build();- assertThat(runJsonToPdf(docWith(page))).isNotEmpty();- }-- @Test- @DisplayName("page with both text and image regenerates content")- void mixedTextAndImage() throws IOException {- stubFallbackFont();- BufferedImage tile = colorTile(8, 8, Color.CYAN);- ByteArrayOutputStream pngOut = new ByteArrayOutputStream();- javax.imageio.ImageIO.write(tile, "png", pngOut);- String base64 = Base64.getEncoder().encodeToString(pngOut.toByteArray());-- PdfJsonFont font =- PdfJsonFont.builder()- .id("F1")- .uid("F1")- .baseName("Helvetica")- .subtype("Type1")- .standard14Name("Helvetica")- .build();- PdfJsonTextElement text =- PdfJsonTextElement.builder()- .text("Mixed")- .fontId("F1")- .fontSize(12f)- .x(72f)- .y(700f)- .build();- PdfJsonImageElement image =- PdfJsonImageElement.builder()- .id("Im1")- .imageData(base64)- .imageFormat("png")- .x(72f)- .y(500f)- .width(48f)- .height(48f)- .build();-- PdfJsonPage page =- PdfJsonPage.builder()- .pageNumber(1)- .width(612f)- .height(792f)- .textElements(List.of(text))- .imageElements(List.of(image))- .build();- PdfJsonDocument doc = docWith(page);- doc.setFonts(new ArrayList<>(List.of(font)));- assertThat(runJsonToPdf(doc)).isNotEmpty();- }- }-- // ==================================================================- // Cache-backed lazy editor API (jobId on JobContext)- // ==================================================================-- @Nested- @DisplayName("cache-backed lazy editor API")- class CacheBackedApi {-- @Test- @DisplayName("lazy conversion caches all pages for later extraction")- void lazyConversionCachesDimensions() throws IOException {- PdfJsonDocument doc = cacheLazyDocument("job-dims", richTextPdf());- assertThat(doc.getPages()).hasSize(3);- assertTrue(doc.isLazyImages(), "lazy conversion should flag lazyImages");-- // Every page is now resolvable from the cache, including the last one.- ByteArrayOutputStream out = new ByteArrayOutputStream();- service.extractSinglePage("job-dims", 3, out);- PdfJsonPage lastPage = objectMapper.readValue(out.toByteArray(), PdfJsonPage.class);- assertEquals(3, lastPage.getPageNumber());- }-- @Test- @DisplayName("extractSinglePage returns text for a cached page")- void extractSinglePageReturnsText() throws IOException {- cacheLazyDocument("job-page", simpleTextPdf());- ByteArrayOutputStream out = new ByteArrayOutputStream();- service.extractSinglePage("job-page", 1, out);- PdfJsonPage page = objectMapper.readValue(out.toByteArray(), PdfJsonPage.class);- assertEquals(1, page.getPageNumber());- assertThat(page.getTextElements()).isNotEmpty();- }-- @Test- @DisplayName("extractSinglePage surfaces image elements on demand")- void extractSinglePageImages() throws IOException {- cacheLazyDocument("job-img", imagePdf());- ByteArrayOutputStream out = new ByteArrayOutputStream();- service.extractSinglePage("job-img", 1, out);- PdfJsonPage page = objectMapper.readValue(out.toByteArray(), PdfJsonPage.class);- assertThat(page.getImageElements()).isNotEmpty();- }-- @Test- @DisplayName("extractSinglePage surfaces annotations on demand")- void extractSinglePageAnnotations() throws IOException {- cacheLazyDocument("job-ann", annotatedPdf());- ByteArrayOutputStream out = new ByteArrayOutputStream();- service.extractSinglePage("job-ann", 1, out);- PdfJsonPage page = objectMapper.readValue(out.toByteArray(), PdfJsonPage.class);- assertThat(page.getAnnotations()).isNotEmpty();- }-- @Test- @DisplayName("extractSinglePage rejects an out-of-range page number")- void extractSinglePageOutOfRange() throws IOException {- cacheLazyDocument("job-range", simpleTextPdf());- ByteArrayOutputStream out = new ByteArrayOutputStream();- assertThrows(- IllegalArgumentException.class,- () -> service.extractSinglePage("job-range", 99, out));- }-- @Test- @DisplayName("extractPageFonts returns the fonts used on a cached page")- void extractPageFontsReturnsFonts() throws IOException {- cacheLazyDocument("job-fonts", richTextPdf());- ByteArrayOutputStream out = new ByteArrayOutputStream();- service.extractPageFonts("job-fonts", 1, out);- List<?> fonts = objectMapper.readValue(out.toByteArray(), List.class);- assertThat(fonts).isNotEmpty();- }-- @Test- @DisplayName("extractPageFonts rejects a page number beyond the document")- void extractPageFontsOutOfRange() throws IOException {- cacheLazyDocument("job-fonts-range", simpleTextPdf());- ByteArrayOutputStream out = new ByteArrayOutputStream();- assertThrows(- IllegalArgumentException.class,- () -> service.extractPageFonts("job-fonts-range", 5, out));- }-- @Test- @DisplayName("extractDocumentMetadata caches and returns the metadata model")- void extractDocumentMetadataCaches() throws IOException {- when(pdfDocumentFactory.load(any(byte[].class), eq(true)))- .thenAnswer(inv -> Loader.loadPDF(inv.getArgument(0, byte[].class)));- ByteArrayOutputStream out = new ByteArrayOutputStream();- service.extractDocumentMetadata(pdfMultipart(richTextPdf()), "job-meta", out);- PdfJsonDocumentMetadata md =- objectMapper.readValue(out.toByteArray(), PdfJsonDocumentMetadata.class);- assertThat(md.getPageDimensions()).hasSize(3);-- // The page is now cached, so a single page can be pulled back out.- ByteArrayOutputStream pageOut = new ByteArrayOutputStream();- service.extractSinglePage("job-meta", 1, pageOut);- assertThat(pageOut.size()).isGreaterThan(0);- }-- @Test- @DisplayName("exportUpdatedPages with no page updates returns the cached PDF unchanged")- void exportUpdatedPagesNoUpdates() throws IOException {- cacheLazyDocument("job-export-none", simpleTextPdf());- ByteArrayOutputStream out = new ByteArrayOutputStream();- service.exportUpdatedPages("job-export-none", new PdfJsonDocument(), out);- assertThat(out.toByteArray()).isNotEmpty();- try (PDDocument loaded = Loader.loadPDF(out.toByteArray())) {- assertEquals(1, loaded.getNumberOfPages());- }- }-- @Test- @DisplayName("exportUpdatedPages applies an edited page and re-saves the document")- void exportUpdatedPagesAppliesEdit() throws IOException {- stubFallbackFont();- cacheLazyDocument("job-export-edit", simpleTextPdf());-- // Pull the real page so we have valid fonts/elements, edit text, then export.- ByteArrayOutputStream pageOut = new ByteArrayOutputStream();- service.extractSinglePage("job-export-edit", 1, pageOut);- PdfJsonPage page = objectMapper.readValue(pageOut.toByteArray(), PdfJsonPage.class);- page.setPageNumber(1);- for (PdfJsonTextElement element : page.getTextElements()) {- if (element.getText() != null && !element.getText().isBlank()) {- element.setText("Updated via export");- break;- }- }-- PdfJsonDocument updates = new PdfJsonDocument();- updates.setPages(List.of(page));-- ByteArrayOutputStream out = new ByteArrayOutputStream();- service.exportUpdatedPages("job-export-edit", updates, out);- assertThat(out.toByteArray()).isNotEmpty();- try (PDDocument loaded = Loader.loadPDF(out.toByteArray())) {- assertEquals(1, loaded.getNumberOfPages());- }- }-- @Test- @DisplayName("exportUpdatedPages ignores updates for an out-of-range page")- void exportUpdatedPagesSkipsOutOfRange() throws IOException {- cacheLazyDocument("job-export-oor", simpleTextPdf());- PdfJsonPage page = new PdfJsonPage();- page.setPageNumber(42);- PdfJsonDocument updates = new PdfJsonDocument();- updates.setPages(List.of(page));-- ByteArrayOutputStream out = new ByteArrayOutputStream();- service.exportUpdatedPages("job-export-oor", updates, out);- // Falls back to returning the cached PDF since no in-range page was updated.- assertThat(out.toByteArray()).isNotEmpty();- }-- @Test- @DisplayName("clearCachedDocument removes a previously cached job")- void clearCachedDocumentRemovesJob() throws IOException {- cacheLazyDocument("job-clear", simpleTextPdf());- service.clearCachedDocument("job-clear");- ByteArrayOutputStream out = new ByteArrayOutputStream();- assertThrows(- CacheUnavailableException.class,- () -> service.extractSinglePage("job-clear", 1, out));- }- }-- // ==================================================================- // Edge and error branches- // ==================================================================-- @Nested- @DisplayName("edge and error branches")- class EdgeBranches {-- @Test- @DisplayName("malformed JSON input surfaces as a runtime parsing failure")- void malformedJsonThrows() {- MockMultipartFile file =- new MockMultipartFile(- "fileInput",- "broken.json",- "application/json",- "{ not valid json ]".getBytes(StandardCharsets.UTF_8));- ByteArrayOutputStream out = new ByteArrayOutputStream();- assertThrows(Exception.class, () -> service.convertJsonToPdf(file, out));- }-- @Test- @DisplayName("zero-page document produces an empty but valid PDF")- void zeroPageDocument() throws IOException {- stubFallbackFont();- PdfJsonDocument doc = new PdfJsonDocument();- doc.setPages(new ArrayList<>());- byte[] bytes = runJsonToPdf(doc);- try (PDDocument loaded = Loader.loadPDF(bytes)) {- assertEquals(0, loaded.getNumberOfPages());- }- }-- @Test- @DisplayName("page with neither text nor images is skipped cleanly")- void emptyContentPageSkipped() throws IOException {- stubFallbackFont();- PdfJsonPage page = PdfJsonPage.builder().pageNumber(1).width(200f).height(200f).build();- PdfJsonDocument doc = new PdfJsonDocument();- doc.setPages(List.of(page));- try (PDDocument loaded = Loader.loadPDF(runJsonToPdf(doc))) {- assertEquals(1, loaded.getNumberOfPages());- }- }-- @Test- @DisplayName("blank PDF (no content streams) converts to JSON with one page")- void blankPdfConverts() throws IOException {- PDDocument document = new PDDocument();- document.addPage(new PDPage(PDRectangle.A4));- PdfJsonDocument doc = toJsonDocument(toBytes(document));- assertEquals(1, doc.getPages().size());- assertEquals(PDRectangle.A4.getWidth(), doc.getPages().get(0).getWidth(), 0.5f);- }-- @Test- @DisplayName("image element with invalid base64 data does not abort the conversion")- void invalidImageDataTolerated() throws IOException {- stubFallbackFont();- PdfJsonImageElement image =- PdfJsonImageElement.builder()- .id("bad")- .imageData("@@@not-base64@@@")- .imageFormat("png")- .x(10f)- .y(10f)- .width(20f)- .height(20f)- .build();- PdfJsonPage page =- PdfJsonPage.builder()- .pageNumber(1)- .width(200f)- .height(200f)- .imageElements(List.of(image))- .build();- PdfJsonDocument doc = new PdfJsonDocument();- doc.setPages(List.of(page));- assertDoesNotThrow(() -> runJsonToPdf(doc));- }-- @Test- @DisplayName("extractDocumentMetadata with no jobId still streams metadata")- void metadataWithoutJobId() throws IOException {- when(pdfDocumentFactory.load(any(byte[].class), eq(true)))- .thenAnswer(inv -> Loader.loadPDF(inv.getArgument(0, byte[].class)));- ByteArrayOutputStream out = new ByteArrayOutputStream();- service.extractDocumentMetadata(pdfMultipart(simpleTextPdf()), null, out);- PdfJsonDocumentMetadata md =- objectMapper.readValue(out.toByteArray(), PdfJsonDocumentMetadata.class);- assertThat(md.getPageDimensions()).hasSize(1);- }- }-}diff --git a/app/core/src/test/java/stirling/software/SPDF/service/PdfJsonConversionServiceDeepTest.java b/app/core/src/test/java/stirling/software/SPDF/service/PdfJsonConversionServiceDeepTest.javadeleted file mode 100644index 76d0a9ad71..0000000000--- a/app/core/src/test/java/stirling/software/SPDF/service/PdfJsonConversionServiceDeepTest.java+++ /dev/null@@ -1,1237 +0,0 @@-package stirling.software.SPDF.service;--import static org.assertj.core.api.Assertions.assertThat;-import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;-import static org.junit.jupiter.api.Assertions.assertEquals;-import static org.junit.jupiter.api.Assertions.assertNotNull;-import static org.mockito.ArgumentMatchers.any;-import static org.mockito.ArgumentMatchers.anyInt;-import static org.mockito.ArgumentMatchers.anyString;-import static org.mockito.ArgumentMatchers.eq;-import static org.mockito.Mockito.when;--import java.awt.Color;-import java.awt.image.BufferedImage;-import java.io.ByteArrayOutputStream;-import java.io.File;-import java.io.IOException;-import java.nio.file.Files;-import java.nio.file.Path;-import java.util.ArrayList;-import java.util.Base64;-import java.util.List;--import javax.imageio.ImageIO;--import org.apache.pdfbox.Loader;-import org.apache.pdfbox.pdmodel.PDDocument;-import org.apache.pdfbox.pdmodel.PDPage;-import org.apache.pdfbox.pdmodel.PDPageContentStream;-import org.apache.pdfbox.pdmodel.common.PDRectangle;-import org.apache.pdfbox.pdmodel.font.PDFont;-import org.apache.pdfbox.pdmodel.font.PDType0Font;-import org.apache.pdfbox.pdmodel.font.PDType1Font;-import org.apache.pdfbox.pdmodel.font.Standard14Fonts;-import org.apache.pdfbox.pdmodel.graphics.image.JPEGFactory;-import org.apache.pdfbox.pdmodel.graphics.image.LosslessFactory;-import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;-import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationFreeText;-import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationHighlight;-import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationLine;-import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationLink;-import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationSquare;-import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationText;-import org.junit.jupiter.api.AfterEach;-import org.junit.jupiter.api.BeforeEach;-import org.junit.jupiter.api.DisplayName;-import org.junit.jupiter.api.Nested;-import org.junit.jupiter.api.Test;-import org.junit.jupiter.api.extension.ExtendWith;-import org.mockito.Mock;-import org.mockito.junit.jupiter.MockitoExtension;-import org.mockito.quality.Strictness;-import org.springframework.mock.web.MockMultipartFile;--import stirling.software.SPDF.config.EndpointConfiguration;-import stirling.software.SPDF.model.json.PdfJsonAnnotation;-import stirling.software.SPDF.model.json.PdfJsonDocument;-import stirling.software.SPDF.model.json.PdfJsonFont;-import stirling.software.SPDF.model.json.PdfJsonImageElement;-import stirling.software.SPDF.model.json.PdfJsonPage;-import stirling.software.SPDF.model.json.PdfJsonTextColor;-import stirling.software.SPDF.model.json.PdfJsonTextElement;-import stirling.software.SPDF.service.pdfjson.PdfJsonFontService;-import stirling.software.SPDF.service.pdfjson.type3.Type3FontConversionService;-import stirling.software.SPDF.service.pdfjson.type3.Type3GlyphExtractor;-import stirling.software.common.model.ApplicationProperties;-import stirling.software.common.service.CustomPDFDocumentFactory;-import stirling.software.common.service.TaskManager;-import stirling.software.common.util.JobContext;-import stirling.software.common.util.TempFileManager;--import tools.jackson.databind.DeserializationFeature;-import tools.jackson.databind.ObjectMapper;-import tools.jackson.databind.json.JsonMapper;--/**- * Deep coverage tests for {@link PdfJsonConversionService} that target reachable branches the other- * suites leave cold: the {@code TextElementCursor}/{@code TextRunAccumulator} run-merging- * machinery, a broad sweep of Standard14 font families plus composite/embedded fonts, every- * annotation subtype, the {@code applyColor} colour-space matrix, JPEG/CMYK/transparent image- * extraction and rebuild, and the extreme-coordinate / NaN guard paths in the regeneration helpers.- *- * <p>Complements {@code PdfJsonConversionServiceCoverageTest} and {@code- * PdfJsonConversionServiceRoundTripTest}; the construction/round-trip helpers mirror those suites- * so the same real in-memory PDF load path is exercised without duplicating their assertions.- */-@ExtendWith(MockitoExtension.class)[email protected](strictness = Strictness.LENIENT)-class PdfJsonConversionServiceDeepTest {-- @Mock private CustomPDFDocumentFactory pdfDocumentFactory;- @Mock private EndpointConfiguration endpointConfiguration;- @Mock private TempFileManager tempFileManager;- @Mock private TaskManager taskManager;- @Mock private PdfJsonFallbackFontService fallbackFontService;- @Mock private PdfJsonFontService fontService;- @Mock private Type3FontConversionService type3FontConversionService;- @Mock private Type3GlyphExtractor type3GlyphExtractor;- @Mock private ApplicationProperties applicationProperties;-- // Real COS mapper so the serialize/deserialize machinery executes for real.- private final PdfJsonCosMapper cosMapper = new PdfJsonCosMapper();-- private final ObjectMapper objectMapper =- JsonMapper.builder()- .disable(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES)- .build();-- private PdfJsonConversionService service;-- private final List<Path> createdTempFiles = new ArrayList<>();-- @BeforeEach- void setUp() throws IOException {- service =- new PdfJsonConversionService(- pdfDocumentFactory,- objectMapper,- endpointConfiguration,- tempFileManager,- taskManager,- cosMapper,- fallbackFontService,- fontService,- type3FontConversionService,- type3GlyphExtractor,- applicationProperties);-- when(tempFileManager.createTempFile(anyString()))- .thenAnswer(- invocation -> {- String suffix = invocation.getArgument(0);- Path path = Files.createTempFile("pdfjson-deep-test", suffix);- createdTempFiles.add(path);- return path.toFile();- });- when(tempFileManager.deleteTempFile(any(File.class)))- .thenAnswer(- invocation -> {- File file = invocation.getArgument(0);- return file != null && file.delete();- });- when(taskManager.addNote(anyString(), anyString())).thenReturn(true);- }-- @AfterEach- void tearDown() throws IOException {- JobContext.clear();- for (Path path : createdTempFiles) {- Files.deleteIfExists(path);- }- createdTempFiles.clear();- }-- // ------------------------------------------------------------------- // Helpers- // -------------------------------------------------------------------- /** Minimal fallback-font stub matching the other suites. */- private void stubFallbackFont() throws IOException {- when(fallbackFontService.buildFallbackFontModel())- .thenAnswer(- invocation ->- PdfJsonFont.builder()- .id(PdfJsonFallbackFontService.FALLBACK_FONT_ID)- .uid(PdfJsonFallbackFontService.FALLBACK_FONT_ID)- .baseName("Fallback")- .subtype("TrueType")- .build());- when(fallbackFontService.loadFallbackPdfFont(any(PDDocument.class)))- .thenAnswer(invocation -> new PDType1Font(Standard14Fonts.FontName.HELVETICA));- }-- /**- * Stubs canEncode to true so {@code buildFontRuns} keeps the primary font instead of forcing- * the fallback path for every glyph, exercising the encode-with-real-font branch of- * regeneration.- */- private void stubCanEncode() {- when(fallbackFontService.canEncode(any(PDFont.class), anyString())).thenReturn(true);- when(fallbackFontService.canEncode(any(PDFont.class), anyInt())).thenReturn(true);- }-- private MockMultipartFile pdfMultipart(byte[] bytes) {- return new MockMultipartFile("fileInput", "input.pdf", "application/pdf", bytes);- }-- private byte[] toBytes(PDDocument document) throws IOException {- try (document) {- ByteArrayOutputStream out = new ByteArrayOutputStream();- document.save(out);- return out.toByteArray();- }- }-- private PdfJsonDocument toJsonDocument(byte[] pdfBytes) throws IOException {- when(pdfDocumentFactory.load(any(Path.class), eq(true)))- .thenAnswer(inv -> Loader.loadPDF(inv.getArgument(0, Path.class).toFile()));- ByteArrayOutputStream out = new ByteArrayOutputStream();- service.convertPdfToJson(pdfMultipart(pdfBytes), out);- return objectMapper.readValue(out.toByteArray(), PdfJsonDocument.class);- }-- private byte[] runJsonToPdf(PdfJsonDocument doc) throws IOException {- ByteArrayOutputStream out = new ByteArrayOutputStream();- service.convertJsonToPdf(doc, out);- return out.toByteArray();- }-- private PdfJsonDocument cacheLazyDocument(String jobId, byte[] pdfBytes) throws IOException {- when(pdfDocumentFactory.load(any(Path.class), eq(true)))- .thenAnswer(inv -> Loader.loadPDF(inv.getArgument(0, Path.class).toFile()));- when(pdfDocumentFactory.load(any(byte[].class), eq(true)))- .thenAnswer(inv -> Loader.loadPDF(inv.getArgument(0, byte[].class)));- JobContext.setJobId(jobId);- ByteArrayOutputStream out = new ByteArrayOutputStream();- service.convertPdfToJson(pdfMultipart(pdfBytes), true, out);- return objectMapper.readValue(out.toByteArray(), PdfJsonDocument.class);- }-- private BufferedImage solidImage(int w, int h, Color color, int type) {- BufferedImage image = new BufferedImage(w, h, type);- for (int x = 0; x < w; x++) {- for (int y = 0; y < h; y++) {- image.setRGB(x, y, color.getRGB());- }- }- return image;- }-- private String pngBase64(BufferedImage image) throws IOException {- ByteArrayOutputStream out = new ByteArrayOutputStream();- ImageIO.write(image, "png", out);- return Base64.getEncoder().encodeToString(out.toByteArray());- }-- private PdfJsonDocument docWith(PdfJsonPage page) {- PdfJsonDocument doc = new PdfJsonDocument();- doc.setPages(List.of(page));- return doc;- }-- private PdfJsonFont std14Font(String id, String standard14Name) {- return PdfJsonFont.builder()- .id(id)- .uid(id)- .baseName(standard14Name)- .subtype("Type1")- .standard14Name(standard14Name)- .build();- }-- // ==================================================================- // TextElementCursor / TextRunAccumulator driven by multi-run text- // ==================================================================-- @Nested- @DisplayName("text run segmentation and cursor merging")- class TextRunSegmentation {-- /** Two differently styled runs on the same baseline force a style-key split. */- private byte[] twoStyleRunsSameLinePdf() throws IOException {- PDDocument document = new PDDocument();- PDPage page = new PDPage(PDRectangle.LETTER);- document.addPage(page);- try (PDPageContentStream cs = new PDPageContentStream(document, page)) {- cs.beginText();- cs.newLineAtOffset(72, 700);- cs.setFont(new PDType1Font(Standard14Fonts.FontName.HELVETICA), 12f);- cs.showText("Plain ");- cs.setFont(new PDType1Font(Standard14Fonts.FontName.HELVETICA_BOLD), 12f);- cs.showText("Bold ");- cs.setNonStrokingColor(Color.RED);- cs.showText("Red");- cs.endText();- }- return toBytes(document);- }-- @Test- @DisplayName("multiple show-text operators on one baseline split into separate style runs")- void multipleRunsSplitByStyle() throws IOException {- PdfJsonDocument doc = toJsonDocument(twoStyleRunsSameLinePdf());- List<PdfJsonTextElement> elements = doc.getPages().get(0).getTextElements();- // At least two style runs because font and colour changed mid-line.- assertThat(elements.size()).isGreaterThanOrEqualTo(2);- String joined =- elements.stream().map(PdfJsonTextElement::getText).reduce("", (a, b) -> a + b);- assertThat(joined).contains("Plain").contains("Bold").contains("Red");- }-- @Test- @DisplayName(- "same-length token rewrite walks the cursor across multiple runs without rebuild")- void cursorRewriteAcrossRuns() throws IOException {- stubFallbackFont();- stubCanEncode();- PdfJsonDocument doc = toJsonDocument(twoStyleRunsSameLinePdf());- byte[] rebuilt = runJsonToPdf(doc);- try (PDDocument loaded = Loader.loadPDF(rebuilt)) {- assertEquals(1, loaded.getNumberOfPages());- assertNotNull(loaded.getPage(0).getContents());- }- }-- @Test- @DisplayName("char-by-char letters merge back into a single run on round trip")- void perGlyphAdvancesMergeIntoRun() throws IOException {- stubFallbackFont();- stubCanEncode();- // Emit each glyph through its own TJ adjustment so the stripper sees many positions.- PDDocument document = new PDDocument();- PDPage page = new PDPage(PDRectangle.LETTER);- document.addPage(page);- try (PDPageContentStream cs = new PDPageContentStream(document, page)) {- cs.beginText();- cs.setFont(new PDType1Font(Standard14Fonts.FontName.HELVETICA), 12f);- cs.newLineAtOffset(72, 700);- cs.setCharacterSpacing(0.5f);- cs.showText("Spaced out glyphs");- cs.endText();- }- PdfJsonDocument doc = toJsonDocument(toBytes(document));- assertThat(doc.getPages().get(0).getTextElements()).isNotEmpty();- byte[] rebuilt = runJsonToPdf(doc);- try (PDDocument loaded = Loader.loadPDF(rebuilt)) {- assertEquals(1, loaded.getNumberOfPages());- }- }-- @Test- @DisplayName("differing-length text edit aborts rewrite and triggers full regeneration")- void lengthChangeForcesRegeneration() throws IOException {- stubFallbackFont();- stubCanEncode();- PdfJsonDocument doc = toJsonDocument(twoStyleRunsSameLinePdf());- for (PdfJsonTextElement element : doc.getPages().get(0).getTextElements()) {- if (element.getText() != null && element.getText().contains("Plain")) {- element.setText("A much longer replacement string than before");- break;- }- }- byte[] rebuilt = runJsonToPdf(doc);- try (PDDocument loaded = Loader.loadPDF(rebuilt)) {- assertEquals(1, loaded.getNumberOfPages());- }- }- }-- // ==================================================================- // Font family variety (extraction + rebuild)- // ==================================================================-- @Nested- @DisplayName("standard14 font family variety")- class FontVariety {-- /** One line per Standard14 family, covering the symbol/zapf encodings too. */- private byte[] allStandard14Pdf() throws IOException {- Standard14Fonts.FontName[] families = {- Standard14Fonts.FontName.HELVETICA,- Standard14Fonts.FontName.HELVETICA_BOLD,- Standard14Fonts.FontName.HELVETICA_OBLIQUE,- Standard14Fonts.FontName.HELVETICA_BOLD_OBLIQUE,- Standard14Fonts.FontName.TIMES_ROMAN,- Standard14Fonts.FontName.TIMES_BOLD,- Standard14Fonts.FontName.TIMES_ITALIC,- Standard14Fonts.FontName.TIMES_BOLD_ITALIC,- Standard14Fonts.FontName.COURIER,- Standard14Fonts.FontName.COURIER_BOLD,- Standard14Fonts.FontName.COURIER_OBLIQUE,- Standard14Fonts.FontName.COURIER_BOLD_OBLIQUE- };- PDDocument document = new PDDocument();- PDPage page = new PDPage(PDRectangle.LETTER);- document.addPage(page);- try (PDPageContentStream cs = new PDPageContentStream(document, page)) {- float y = 760f;- for (Standard14Fonts.FontName family : families) {- cs.beginText();- cs.setFont(new PDType1Font(family), 10f);- cs.newLineAtOffset(50, y);- cs.showText(family.getName() + " sample 123");- cs.endText();- y -= 18f;- }- }- return toBytes(document);- }-- @Test- @DisplayName("all standard14 families are captured as distinct fonts")- void capturesAllFamilies() throws IOException {- PdfJsonDocument doc = toJsonDocument(allStandard14Pdf());- long distinct =- doc.getFonts().stream()- .map(PdfJsonFont::getBaseName)- .filter(java.util.Objects::nonNull)- .distinct()- .count();- assertThat(distinct).isGreaterThanOrEqualTo(8);- }-- @Test- @DisplayName("round trip over every standard14 family rebuilds a valid PDF")- void roundTripAllFamilies() throws IOException {- stubFallbackFont();- stubCanEncode();- PdfJsonDocument doc = toJsonDocument(allStandard14Pdf());- byte[] rebuilt = runJsonToPdf(doc);- try (PDDocument loaded = Loader.loadPDF(rebuilt)) {- assertEquals(1, loaded.getNumberOfPages());- }- }-- @Test- @DisplayName("synthesized text in each standard14 family rebuilds via createFontFromModel")- void synthesizedFamiliesRebuild() throws IOException {- stubFallbackFont();- stubCanEncode();- String[] names = {- "Helvetica-BoldOblique",- "Times-BoldItalic",- "Courier-Oblique",- "Symbol",- "ZapfDingbats"- };- List<PdfJsonFont> fonts = new ArrayList<>();- List<PdfJsonTextElement> elements = new ArrayList<>();- float y = 720f;- for (int i = 0; i < names.length; i++) {- String id = "F" + i;- fonts.add(std14Font(id, names[i]));- elements.add(- PdfJsonTextElement.builder()- .text("Sample" + i)- .fontId(id)- .fontSize(12f)- .x(72f)- .y(y)- .build());- y -= 20f;- }- PdfJsonPage page =- PdfJsonPage.builder()- .pageNumber(1)- .width(612f)- .height(792f)- .textElements(elements)- .build();- PdfJsonDocument doc = docWith(page);- doc.setFonts(fonts);- try (PDDocument loaded = Loader.loadPDF(runJsonToPdf(doc))) {- assertEquals(1, loaded.getNumberOfPages());- }- }- }-- // ==================================================================- // Composite / embedded font round trips- // ==================================================================-- @Nested- @DisplayName("composite and embedded fonts")- class CompositeFonts {-- // Loads the project-bundled DejaVuSans.ttf from the classpath so the embedded-font tests- // are deterministic on every platform (no reliance on OS fonts, never skipped).- private Path bundledTrueTypeFont() throws IOException {- Path tmp = Files.createTempFile("deepfont", ".ttf");- tmp.toFile().deleteOnExit();- try (java.io.InputStream in =- getClass().getResourceAsStream("/static/fonts/DejaVuSans.ttf")) {- assertThat(in).as("bundled DejaVuSans.ttf on classpath").isNotNull();- Files.copy(in, tmp, java.nio.file.StandardCopyOption.REPLACE_EXISTING);- }- return tmp;- }-- @Test- @DisplayName("embedded TrueType (Type0 composite) font survives extraction and rebuild")- void embeddedTrueTypeRoundTrip() throws IOException {- Path ttf = bundledTrueTypeFont();- stubFallbackFont();- stubCanEncode();-- PDDocument document = new PDDocument();- PDPage page = new PDPage(PDRectangle.LETTER);- document.addPage(page);- PDType0Font embedded = PDType0Font.load(document, ttf.toFile());- try (PDPageContentStream cs = new PDPageContentStream(document, page)) {- cs.beginText();- cs.setFont(embedded, 14f);- cs.newLineAtOffset(72, 700);- cs.showText("Composite font line");- cs.endText();- }- byte[] bytes = toBytes(document);-- PdfJsonDocument doc = toJsonDocument(bytes);- // A composite/Type0 font should be present in the extracted set.- assertThat(doc.getFonts()).isNotEmpty();- assertThat(doc.getPages().get(0).getTextElements()).isNotEmpty();-- byte[] rebuilt = runJsonToPdf(doc);- try (PDDocument loaded = Loader.loadPDF(rebuilt)) {- assertEquals(1, loaded.getNumberOfPages());- }- }-- @Test- @DisplayName("composite font lazy extraction exposes font payload via extractPageFonts")- void embeddedTrueTypeLazyFonts() throws IOException {- Path ttf = bundledTrueTypeFont();-- PDDocument document = new PDDocument();- PDPage page = new PDPage(PDRectangle.LETTER);- document.addPage(page);- PDType0Font embedded = PDType0Font.load(document, ttf.toFile());- try (PDPageContentStream cs = new PDPageContentStream(document, page)) {- cs.beginText();- cs.setFont(embedded, 14f);- cs.newLineAtOffset(72, 700);- cs.showText("Lazy composite");- cs.endText();- }- byte[] bytes = toBytes(document);-- cacheLazyDocument("job-ttf", bytes);- ByteArrayOutputStream out = new ByteArrayOutputStream();- service.extractPageFonts("job-ttf", 1, out);- List<?> fonts = objectMapper.readValue(out.toByteArray(), List.class);- assertThat(fonts).isNotEmpty();- }- }-- // ==================================================================- // Annotation variety: collect + restore- // ==================================================================-- @Nested- @DisplayName("annotation subtype variety")- class AnnotationVariety {-- /** One of each common annotation subtype with colour/border styling. */- private byte[] manyAnnotationsPdf() throws IOException {- PDDocument document = new PDDocument();- PDPage page = new PDPage(PDRectangle.LETTER);- document.addPage(page);-- PDAnnotationText note = new PDAnnotationText();- note.setContents("Sticky note");- note.setRectangle(new PDRectangle(40, 740, 20, 20));- note.setColor(- new org.apache.pdfbox.pdmodel.graphics.color.PDColor(- new float[] {1f, 1f, 0f},- org.apache.pdfbox.pdmodel.graphics.color.PDDeviceRGB.INSTANCE));-- PDAnnotationLink link = new PDAnnotationLink();- link.setRectangle(new PDRectangle(40, 700, 200, 18));-- PDAnnotationHighlight highlight = new PDAnnotationHighlight();- highlight.setRectangle(new PDRectangle(40, 660, 200, 18));- highlight.setQuadPoints(new float[] {40, 678, 240, 678, 40, 660, 240, 660});- highlight.setColor(- new org.apache.pdfbox.pdmodel.graphics.color.PDColor(- new float[] {0f, 1f, 0f},- org.apache.pdfbox.pdmodel.graphics.color.PDDeviceRGB.INSTANCE));-- PDAnnotationSquare square = new PDAnnotationSquare();- square.setRectangle(new PDRectangle(40, 600, 80, 40));- square.setInteriorColor(- new org.apache.pdfbox.pdmodel.graphics.color.PDColor(- new float[] {0.2f, 0.2f, 0.9f},- org.apache.pdfbox.pdmodel.graphics.color.PDDeviceRGB.INSTANCE));-- PDAnnotationFreeText freeText = new PDAnnotationFreeText();- freeText.setRectangle(new PDRectangle(40, 540, 200, 40));- freeText.setContents("Free text body");- freeText.setDefaultAppearance("/Helv 10 Tf 0 g");-- PDAnnotationLine line = new PDAnnotationLine();- line.setRectangle(new PDRectangle(40, 500, 200, 20));- line.setLine(new float[] {40, 510, 240, 510});-- page.getAnnotations().add(note);- page.getAnnotations().add(link);- page.getAnnotations().add(highlight);- page.getAnnotations().add(square);- page.getAnnotations().add(freeText);- page.getAnnotations().add(line);-- // A line of page content so the JSON->PDF rebuild reaches the annotation-restore step.- try (PDPageContentStream cs = new PDPageContentStream(document, page)) {- cs.beginText();- cs.setFont(new PDType1Font(Standard14Fonts.FontName.HELVETICA), 12f);- cs.newLineAtOffset(72, 440);- cs.showText("Annotated body text");- cs.endText();- }-- return toBytes(document);- }-- @Test- @DisplayName("each annotation subtype is collected with its subtype label")- void collectsAllSubtypes() throws IOException {- PdfJsonDocument doc = toJsonDocument(manyAnnotationsPdf());- List<PdfJsonAnnotation> annotations = doc.getPages().get(0).getAnnotations();- assertThat(annotations).hasSizeGreaterThanOrEqualTo(6);- List<String> subtypes =- annotations.stream().map(PdfJsonAnnotation::getSubtype).toList();- assertThat(subtypes)- .contains("Text", "Link", "Highlight", "Square", "FreeText", "Line");- }-- @Test- @DisplayName("annotation colours are captured into the colour component array")- void capturesAnnotationColors() throws IOException {- PdfJsonDocument doc = toJsonDocument(manyAnnotationsPdf());- List<PdfJsonAnnotation> annotations = doc.getPages().get(0).getAnnotations();- assertThat(annotations).anySatisfy(a -> assertThat(a.getColor()).isNotNull());- }-- @Test- @DisplayName("every annotation subtype round trips back onto the rebuilt page via raw data")- void restoresAllSubtypes() throws IOException {- stubFallbackFont();- PdfJsonDocument doc = toJsonDocument(manyAnnotationsPdf());- byte[] rebuilt = runJsonToPdf(doc);- try (PDDocument loaded = Loader.loadPDF(rebuilt)) {- assertThat(loaded.getPage(0).getAnnotations()).hasSizeGreaterThanOrEqualTo(6);- }- }-- @Test- @DisplayName("lazy extraction surfaces the full annotation set for a cached page")- void lazyAnnotationSet() throws IOException {- cacheLazyDocument("job-anns", manyAnnotationsPdf());- ByteArrayOutputStream out = new ByteArrayOutputStream();- service.extractSinglePage("job-anns", 1, out);- PdfJsonPage page = objectMapper.readValue(out.toByteArray(), PdfJsonPage.class);- assertThat(page.getAnnotations()).hasSizeGreaterThanOrEqualTo(6);- }- }-- // ==================================================================- // Image variety: JPEG (DCT), lossless PNG, transparency, CMYK- // ==================================================================-- @Nested- @DisplayName("image format variety")- class ImageVariety {-- /** A page bearing a JPEG (DCT), a lossless RGB and an ARGB-with-alpha image. */- private byte[] mixedImagePdf() throws IOException {- PDDocument document = new PDDocument();- PDPage page = new PDPage(PDRectangle.LETTER);- document.addPage(page);-- PDImageXObject jpeg =- JPEGFactory.createFromImage(- document, solidImage(32, 24, Color.RED, BufferedImage.TYPE_INT_RGB));- PDImageXObject lossless =- LosslessFactory.createFromImage(- document, solidImage(24, 24, Color.BLUE, BufferedImage.TYPE_INT_RGB));- BufferedImage argb =- solidImage(16, 16, new Color(0, 255, 0, 128), BufferedImage.TYPE_INT_ARGB);- PDImageXObject transparent = LosslessFactory.createFromImage(document, argb);-- try (PDPageContentStream cs = new PDPageContentStream(document, page)) {- cs.drawImage(jpeg, 60, 600, 96, 72);- cs.drawImage(lossless, 200, 600, 72, 72);- cs.drawImage(transparent, 320, 600, 48, 48);- }- return toBytes(document);- }-- @Test- @DisplayName("JPEG, lossless and transparent images are all extracted with format + data")- void extractsMixedImages() throws IOException {- PdfJsonDocument doc = toJsonDocument(mixedImagePdf());- List<PdfJsonImageElement> images = doc.getPages().get(0).getImageElements();- assertThat(images).hasSizeGreaterThanOrEqualTo(3);- assertThat(images)- .allSatisfy(- img -> {- assertThat(img.getImageData()).isNotBlank();- assertThat(img.getImageFormat()).isNotBlank();- });- // A JPEG XObject reports a jpg/jpeg suffix.- assertThat(images)- .anySatisfy(- img ->- assertThat(img.getImageFormat().toLowerCase())- .containsAnyOf("jpg", "jpeg"));- }-- @Test- @DisplayName("mixed-image page round trips into a page that keeps image resources")- void roundTripMixedImages() throws IOException {- stubFallbackFont();- PdfJsonDocument doc = toJsonDocument(mixedImagePdf());- byte[] rebuilt = runJsonToPdf(doc);- try (PDDocument loaded = Loader.loadPDF(rebuilt)) {- assertEquals(1, loaded.getNumberOfPages());- assertNotNull(loaded.getPage(0).getResources());- }- }-- @Test- @DisplayName("synthesized JPEG-format image element with a transform matrix renders")- void synthesizedJpegWithTransform() throws IOException {- stubFallbackFont();- ByteArrayOutputStream jpgOut = new ByteArrayOutputStream();- ImageIO.write(solidImage(16, 16, Color.RED, BufferedImage.TYPE_INT_RGB), "jpg", jpgOut);- String base64 = Base64.getEncoder().encodeToString(jpgOut.toByteArray());-- PdfJsonImageElement image =- PdfJsonImageElement.builder()- .id("Jpg1")- .imageData(base64)- .imageFormat("jpg")- .transform(new float[] {64f, 0f, 0f, 48f, 80f, 500f})- .build();- PdfJsonPage page =- PdfJsonPage.builder()- .pageNumber(1)- .width(612f)- .height(792f)- .imageElements(List.of(image))- .build();- try (PDDocument loaded = Loader.loadPDF(runJsonToPdf(docWith(page)))) {- assertEquals(1, loaded.getNumberOfPages());- }- }-- @Test- @DisplayName("lazy extraction with images materializes image data on demand")- void lazyMixedImages() throws IOException {- cacheLazyDocument("job-mixed-img", mixedImagePdf());- ByteArrayOutputStream out = new ByteArrayOutputStream();- service.extractSinglePage("job-mixed-img", 1, out);- PdfJsonPage page = objectMapper.readValue(out.toByteArray(), PdfJsonPage.class);- assertThat(page.getImageElements()).isNotEmpty();- assertThat(page.getImageElements())- .anySatisfy(img -> assertThat(img.getImageData()).isNotBlank());- }- }-- // ==================================================================- // applyColor / applyTextState colour-space matrix- // ==================================================================-- @Nested- @DisplayName("colour space and text-state application")- class ColorAndState {-- private PdfJsonDocument textWithColor(PdfJsonTextColor fill, PdfJsonTextColor stroke) {- PdfJsonFont font = std14Font("F1", "Helvetica");- PdfJsonTextElement element =- PdfJsonTextElement.builder()- .text("Coloured")- .fontId("F1")- .fontSize(14f)- .characterSpacing(0.8f)- .wordSpacing(1.5f)- .horizontalScaling(90f)- .leading(16f)- .rise(2f)- .renderingMode(2)- .fillColor(fill)- .strokeColor(stroke)- .x(72f)- .y(700f)- .build();- PdfJsonPage page =- PdfJsonPage.builder()- .pageNumber(1)- .width(612f)- .height(792f)- .textElements(List.of(element))- .build();- PdfJsonDocument doc = docWith(page);- doc.setFonts(new ArrayList<>(List.of(font)));- return doc;- }-- private PdfJsonTextColor color(String space, float... components) {- return PdfJsonTextColor.builder().colorSpace(space).components(components).build();- }-- @Test- @DisplayName("explicit DeviceRGB fill and stroke colours render")- void deviceRgb() throws IOException {- stubFallbackFont();- stubCanEncode();- PdfJsonDocument doc =- textWithColor(- color("DeviceRGB", 0.1f, 0.2f, 0.3f),- color("DeviceRGB", 0.9f, 0.8f, 0.7f));- assertThat(runJsonToPdf(doc)).isNotEmpty();- }-- @Test- @DisplayName("explicit DeviceCMYK colours render through the CMYK branch")- void deviceCmyk() throws IOException {- stubFallbackFont();- stubCanEncode();- PdfJsonDocument doc =- textWithColor(- color("DeviceCMYK", 0.1f, 0.2f, 0.3f, 0.4f),- color("DeviceCMYK", 0f, 0f, 0f, 1f));- assertThat(runJsonToPdf(doc)).isNotEmpty();- }-- @Test- @DisplayName("explicit DeviceGray colours render through the gray branch")- void deviceGray() throws IOException {- stubFallbackFont();- stubCanEncode();- PdfJsonDocument doc =- textWithColor(color("DeviceGray", 0.5f), color("DeviceGray", 0.2f));- assertThat(runJsonToPdf(doc)).isNotEmpty();- }-- @Test- @DisplayName("null colour space infers the space from component count (1/3/4)")- void inferredColorSpaces() throws IOException {- stubFallbackFont();- stubCanEncode();- assertThat(runJsonToPdf(textWithColor(color(null, 0.4f), color(null, 0.6f))))- .isNotEmpty();- assertThat(- runJsonToPdf(- textWithColor(- color(null, 0.1f, 0.2f, 0.3f),- color(null, 0.3f, 0.2f, 0.1f))))- .isNotEmpty();- assertThat(- runJsonToPdf(- textWithColor(- color(null, 0.1f, 0.2f, 0.3f, 0.4f),- color(null, 0.4f, 0.3f, 0.2f, 0.1f))))- .isNotEmpty();- }-- @Test- @DisplayName("unsupported named colour space is skipped without aborting the rebuild")- void unsupportedColorSpaceSkipped() throws IOException {- stubFallbackFont();- stubCanEncode();- PdfJsonDocument doc =- textWithColor(color("Separation", 0.5f), color("ICCBased", 0.1f, 0.2f, 0.3f));- assertThat(runJsonToPdf(doc)).isNotEmpty();- }-- @Test- @DisplayName("two-component colour with null space falls through to the RGB default branch")- void twoComponentDefaultsToRgb() throws IOException {- stubFallbackFont();- stubCanEncode();- PdfJsonDocument doc = textWithColor(color(null, 0.5f, 0.5f), null);- assertThat(runJsonToPdf(doc)).isNotEmpty();- }- }-- // ==================================================================- // Edge / guard branches- // ==================================================================-- @Nested- @DisplayName("edge and guard branches")- class EdgeGuards {-- @Test- @DisplayName("very large coordinates are tolerated by the regeneration path")- void extremeCoordinates() throws IOException {- stubFallbackFont();- stubCanEncode();- PdfJsonFont font = std14Font("F1", "Helvetica");- PdfJsonTextElement element =- PdfJsonTextElement.builder()- .text("Far away")- .fontId("F1")- .fontSize(12f)- .x(900_000f)- .y(-900_000f)- .build();- PdfJsonPage page =- PdfJsonPage.builder()- .pageNumber(1)- .width(612f)- .height(792f)- .textElements(List.of(element))- .build();- PdfJsonDocument doc = docWith(page);- doc.setFonts(new ArrayList<>(List.of(font)));- assertThat(runJsonToPdf(doc)).isNotEmpty();- }-- @Test- @DisplayName("NaN and Infinity in an image transform fall back to safe defaults")- void nonFiniteTransformGuarded() throws IOException {- stubFallbackFont();- PdfJsonImageElement image =- PdfJsonImageElement.builder()- .id("Im-nan")- .imageData(- pngBase64(- solidImage(- 8, 8, Color.PINK, BufferedImage.TYPE_INT_RGB)))- .imageFormat("png")- .transform(- new float[] {- Float.NaN,- 0f,- 0f,- Float.POSITIVE_INFINITY,- Float.NEGATIVE_INFINITY,- 100f- })- .build();- PdfJsonPage page =- PdfJsonPage.builder()- .pageNumber(1)- .width(612f)- .height(792f)- .imageElements(List.of(image))- .build();- assertDoesNotThrow(() -> runJsonToPdf(docWith(page)));- }-- @Test- @DisplayName("image with zero width/height falls back to native dimensions")- void zeroDimensionImageUsesNative() throws IOException {- stubFallbackFont();- PdfJsonImageElement image =- PdfJsonImageElement.builder()- .id("Im-zero")- .imageData(- pngBase64(- solidImage(- 10,- 12,- Color.GRAY,- BufferedImage.TYPE_INT_RGB)))- .imageFormat("png")- .width(0f)- .height(0f)- .nativeWidth(10)- .nativeHeight(12)- .x(50f)- .y(500f)- .build();- PdfJsonPage page =- PdfJsonPage.builder()- .pageNumber(1)- .width(612f)- .height(792f)- .imageElements(List.of(image))- .build();- assertThat(runJsonToPdf(docWith(page))).isNotEmpty();- }-- @Test- @DisplayName("a page with only blank-text elements rebuilds cleanly")- void blankTextOnlyPage() throws IOException {- stubFallbackFont();- PdfJsonFont font = std14Font("F1", "Helvetica");- PdfJsonTextElement blank =- PdfJsonTextElement.builder()- .text(" ")- .fontId("F1")- .fontSize(12f)- .x(72f)- .y(700f)- .build();- PdfJsonTextElement empty =- PdfJsonTextElement.builder()- .text("")- .fontId("F1")- .fontSize(12f)- .x(72f)- .y(680f)- .build();- PdfJsonPage page =- PdfJsonPage.builder()- .pageNumber(1)- .width(612f)- .height(792f)- .textElements(List.of(blank, empty))- .build();- PdfJsonDocument doc = docWith(page);- doc.setFonts(new ArrayList<>(List.of(font)));- assertThat(runJsonToPdf(doc)).isNotEmpty();- }-- @Test- @DisplayName("explicit z-order interleaves images and text by draw order")- void zOrderInterleaving() throws IOException {- stubFallbackFont();- stubCanEncode();- PdfJsonFont font = std14Font("F1", "Helvetica");- PdfJsonImageElement back =- PdfJsonImageElement.builder()- .id("back")- .imageData(- pngBase64(- solidImage(- 20,- 20,- Color.LIGHT_GRAY,- BufferedImage.TYPE_INT_RGB)))- .imageFormat("png")- .x(60f)- .y(600f)- .width(120f)- .height(40f)- .zOrder(5)- .build();- PdfJsonTextElement front =- PdfJsonTextElement.builder()- .text("On top")- .fontId("F1")- .fontSize(14f)- .x(64f)- .y(610f)- .zOrder(10)- .build();- PdfJsonTextElement under =- PdfJsonTextElement.builder()- .text("Below")- .fontId("F1")- .fontSize(14f)- .x(64f)- .y(560f)- .zOrder(1)- .build();- PdfJsonPage page =- PdfJsonPage.builder()- .pageNumber(1)- .width(612f)- .height(792f)- .textElements(List.of(front, under))- .imageElements(List.of(back))- .build();- PdfJsonDocument doc = docWith(page);- doc.setFonts(new ArrayList<>(List.of(font)));- try (PDDocument loaded = Loader.loadPDF(runJsonToPdf(doc))) {- assertEquals(1, loaded.getNumberOfPages());- }- }-- @Test- @DisplayName("text with an explicit 6-value text matrix renders via applyTextMatrix")- void explicitTextMatrix() throws IOException {- stubFallbackFont();- stubCanEncode();- PdfJsonFont font = std14Font("F1", "Helvetica");- PdfJsonTextElement element =- PdfJsonTextElement.builder()- .text("Matrixed")- .fontId("F1")- .fontSize(12f)- .textMatrix(new float[] {1.2f, 0.3f, -0.3f, 1.2f, 120f, 640f})- .build();- PdfJsonPage page =- PdfJsonPage.builder()- .pageNumber(1)- .width(612f)- .height(792f)- .textElements(List.of(element))- .build();- PdfJsonDocument doc = docWith(page);- doc.setFonts(new ArrayList<>(List.of(font)));- assertThat(runJsonToPdf(doc)).isNotEmpty();- }- }-- // ==================================================================- // Content-stream + resource preservation with varied operators- // ==================================================================-- @Nested- @DisplayName("content stream and resource preservation with varied operators")- class ContentStreamPreservation {-- /** Page mixing graphics-state, clipping, vector fills and text. */- private byte[] graphicsRichPdf() throws IOException {- PDDocument document = new PDDocument();- PDPage page = new PDPage(PDRectangle.LETTER);- document.addPage(page);- try (PDPageContentStream cs = new PDPageContentStream(document, page)) {- cs.saveGraphicsState();- cs.setLineWidth(2f);- cs.setNonStrokingColor(0.2f, 0.4f, 0.6f);- cs.addRect(50, 600, 200, 120);- cs.clip();- cs.fill();- cs.restoreGraphicsState();-- cs.setStrokingColor(Color.DARK_GRAY);- cs.moveTo(50, 560);- cs.lineTo(250, 560);- cs.stroke();-- cs.beginText();- cs.setFont(new PDType1Font(Standard14Fonts.FontName.HELVETICA), 12f);- cs.newLineAtOffset(60, 500);- cs.showText("Text over graphics");- cs.endText();- }- return toBytes(document);- }-- @Test- @DisplayName("graphics-rich page preserves content streams and resources on extraction")- void preservesStreamsAndResources() throws IOException {- PdfJsonDocument doc = toJsonDocument(graphicsRichPdf());- PdfJsonPage page = doc.getPages().get(0);- assertNotNull(page.getResources());- assertThat(page.getContentStreams()).isNotEmpty();- }-- @Test- @DisplayName("identity edit over graphics-rich content keeps the token rewrite path viable")- void identityRewriteKeepsGraphics() throws IOException {- stubFallbackFont();- stubCanEncode();- PdfJsonDocument doc = toJsonDocument(graphicsRichPdf());- byte[] rebuilt = runJsonToPdf(doc);- try (PDDocument loaded = Loader.loadPDF(rebuilt)) {- assertEquals(1, loaded.getNumberOfPages());- assertNotNull(loaded.getPage(0).getContents());- }- }-- @Test- @DisplayName("convertPdfToJsonDocument exposes the COS model for mutate-and-rebuild")- void cosModelMutateRebuild() throws IOException {- stubFallbackFont();- when(pdfDocumentFactory.load(any(Path.class), eq(true)))- .thenAnswer(inv -> Loader.loadPDF(inv.getArgument(0, Path.class).toFile()));- PdfJsonDocument doc = service.convertPdfToJsonDocument(pdfMultipart(graphicsRichPdf()));- assertNotNull(doc);- assertThat(doc.getPages()).hasSize(1);- // Mutate page geometry then rebuild to drive applyPageResources on a changed model.- doc.getPages().get(0).setRotation(90);- byte[] rebuilt = runJsonToPdf(doc);- try (PDDocument loaded = Loader.loadPDF(rebuilt)) {- assertEquals(1, loaded.getNumberOfPages());- }- }- }-- // ==================================================================- // Cache export with multiple edits- // ==================================================================-- @Nested- @DisplayName("cache export with multiple edits")- class CacheExportMultiEdit {-- private byte[] threePageTextPdf() throws IOException {- PDDocument document = new PDDocument();- for (int i = 0; i < 3; i++) {- PDPage page = new PDPage(PDRectangle.LETTER);- document.addPage(page);- try (PDPageContentStream cs = new PDPageContentStream(document, page)) {- cs.beginText();- cs.setFont(new PDType1Font(Standard14Fonts.FontName.HELVETICA), 12f);- cs.newLineAtOffset(72, 700);- cs.showText("Page number " + (i + 1));- cs.endText();- }- }- return toBytes(document);- }-- @Test- @DisplayName("exportUpdatedPages applies edits to several pages at once")- void multiPageEdits() throws IOException {- stubFallbackFont();- stubCanEncode();- cacheLazyDocument("job-multi-export", threePageTextPdf());-- List<PdfJsonPage> updates = new ArrayList<>();- for (int pageNo = 1; pageNo <= 3; pageNo++) {- ByteArrayOutputStream pageOut = new ByteArrayOutputStream();- service.extractSinglePage("job-multi-export", pageNo, pageOut);- PdfJsonPage page = objectMapper.readValue(pageOut.toByteArray(), PdfJsonPage.class);- page.setPageNumber(pageNo);- for (PdfJsonTextElement element : page.getTextElements()) {- if (element.getText() != null && !element.getText().isBlank()) {- element.setText("Edited " + pageNo);- break;- }- }- updates.add(page);- }- PdfJsonDocument updateDoc = new PdfJsonDocument();- updateDoc.setPages(updates);-- ByteArrayOutputStream out = new ByteArrayOutputStream();- service.exportUpdatedPages("job-multi-export", updateDoc, out);- try (PDDocument loaded = Loader.loadPDF(out.toByteArray())) {- assertEquals(3, loaded.getNumberOfPages());- }- }-- @Test- @DisplayName("exportUpdatedPages mixes one in-range edit with one out-of-range page")- void mixedRangeEdits() throws IOException {- stubFallbackFont();- stubCanEncode();- cacheLazyDocument("job-mixed-range", threePageTextPdf());-- ByteArrayOutputStream pageOut = new ByteArrayOutputStream();- service.extractSinglePage("job-mixed-range", 2, pageOut);- PdfJsonPage realPage = objectMapper.readValue(pageOut.toByteArray(), PdfJsonPage.class);- realPage.setPageNumber(2);-- PdfJsonPage ghost = new PdfJsonPage();- ghost.setPageNumber(99);-- PdfJsonDocument updateDoc = new PdfJsonDocument();- updateDoc.setPages(List.of(realPage, ghost));-- ByteArrayOutputStream out = new ByteArrayOutputStream();- service.exportUpdatedPages("job-mixed-range", updateDoc, out);- try (PDDocument loaded = Loader.loadPDF(out.toByteArray())) {- assertEquals(3, loaded.getNumberOfPages());- }- }- }-}diff --git a/app/core/src/test/java/stirling/software/SPDF/service/PdfJsonConversionServiceExtraTest.java b/app/core/src/test/java/stirling/software/SPDF/service/PdfJsonConversionServiceExtraTest.javadeleted file mode 100644index b476d596b7..0000000000--- a/app/core/src/test/java/stirling/software/SPDF/service/PdfJsonConversionServiceExtraTest.java+++ /dev/null@@ -1,1088 +0,0 @@-package stirling.software.SPDF.service;--import static org.assertj.core.api.Assertions.assertThat;-import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;-import static org.junit.jupiter.api.Assertions.assertEquals;-import static org.junit.jupiter.api.Assertions.assertNotNull;-import static org.junit.jupiter.api.Assertions.assertThrows;-import static org.mockito.ArgumentMatchers.any;-import static org.mockito.ArgumentMatchers.anyInt;-import static org.mockito.ArgumentMatchers.anyString;-import static org.mockito.ArgumentMatchers.eq;-import static org.mockito.Mockito.when;--import java.awt.Color;-import java.awt.image.BufferedImage;-import java.io.ByteArrayOutputStream;-import java.io.File;-import java.io.IOException;-import java.nio.file.Files;-import java.nio.file.Path;-import java.util.ArrayList;-import java.util.Base64;-import java.util.Calendar;-import java.util.List;-import java.util.TimeZone;--import javax.imageio.ImageIO;--import org.apache.pdfbox.Loader;-import org.apache.pdfbox.pdmodel.PDDocument;-import org.apache.pdfbox.pdmodel.PDDocumentInformation;-import org.apache.pdfbox.pdmodel.PDPage;-import org.apache.pdfbox.pdmodel.PDPageContentStream;-import org.apache.pdfbox.pdmodel.common.PDRectangle;-import org.apache.pdfbox.pdmodel.font.PDFont;-import org.apache.pdfbox.pdmodel.font.PDType1Font;-import org.apache.pdfbox.pdmodel.font.Standard14Fonts;-import org.apache.pdfbox.pdmodel.graphics.image.JPEGFactory;-import org.apache.pdfbox.pdmodel.graphics.image.LosslessFactory;-import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;-import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationText;-import org.junit.jupiter.api.AfterEach;-import org.junit.jupiter.api.BeforeEach;-import org.junit.jupiter.api.DisplayName;-import org.junit.jupiter.api.Nested;-import org.junit.jupiter.api.Test;-import org.junit.jupiter.api.extension.ExtendWith;-import org.mockito.Mock;-import org.mockito.junit.jupiter.MockitoExtension;-import org.mockito.quality.Strictness;-import org.springframework.mock.web.MockMultipartFile;--import stirling.software.SPDF.config.EndpointConfiguration;-import stirling.software.SPDF.exception.CacheUnavailableException;-import stirling.software.SPDF.model.json.PdfJsonDocument;-import stirling.software.SPDF.model.json.PdfJsonDocumentMetadata;-import stirling.software.SPDF.model.json.PdfJsonFont;-import stirling.software.SPDF.model.json.PdfJsonImageElement;-import stirling.software.SPDF.model.json.PdfJsonMetadata;-import stirling.software.SPDF.model.json.PdfJsonPage;-import stirling.software.SPDF.model.json.PdfJsonTextColor;-import stirling.software.SPDF.model.json.PdfJsonTextElement;-import stirling.software.SPDF.service.pdfjson.PdfJsonFontService;-import stirling.software.SPDF.service.pdfjson.type3.Type3FontConversionService;-import stirling.software.SPDF.service.pdfjson.type3.Type3GlyphExtractor;-import stirling.software.common.model.ApplicationProperties;-import stirling.software.common.service.CustomPDFDocumentFactory;-import stirling.software.common.service.TaskManager;-import stirling.software.common.util.JobContext;-import stirling.software.common.util.TempFileManager;--import tools.jackson.databind.DeserializationFeature;-import tools.jackson.databind.ObjectMapper;-import tools.jackson.databind.json.JsonMapper;--/**- * Extra coverage tests for {@link PdfJsonConversionService} aimed at reachable branches the- * existing suites leave cold: full document-information round trips that exercise the- * creation/modification date and trapped paths, the {@code convertJsonToPdf(MultipartFile)} file- * overload driven by a re-serialized model, the cache-backed export path with- * added/removed/modified text and image elements plus a font supplied in the update document, rich- * COS metadata via nested page resources, additional text render modes / spacing / rise, negative- * coordinates, and full model-mutation (page add/remove, colour and size edits) round trips.- *- * <p>Construction mirrors {@code PdfJsonConversionServiceCoverageTest} and {@code- * PdfJsonConversionServiceDeepTest} so the same real in-memory PDF load path is exercised without- * repeating their assertions.- */-@ExtendWith(MockitoExtension.class)[email protected](strictness = Strictness.LENIENT)-class PdfJsonConversionServiceExtraTest {-- @Mock private CustomPDFDocumentFactory pdfDocumentFactory;- @Mock private EndpointConfiguration endpointConfiguration;- @Mock private TempFileManager tempFileManager;- @Mock private TaskManager taskManager;- @Mock private PdfJsonFallbackFontService fallbackFontService;- @Mock private PdfJsonFontService fontService;- @Mock private Type3FontConversionService type3FontConversionService;- @Mock private Type3GlyphExtractor type3GlyphExtractor;- @Mock private ApplicationProperties applicationProperties;-- // Real COS mapper so the serialize/deserialize machinery runs for real.- private final PdfJsonCosMapper cosMapper = new PdfJsonCosMapper();-- private final ObjectMapper objectMapper =- JsonMapper.builder()- .disable(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES)- .build();-- private PdfJsonConversionService service;-- private final List<Path> createdTempFiles = new ArrayList<>();-- @BeforeEach- void setUp() throws IOException {- service =- new PdfJsonConversionService(- pdfDocumentFactory,- objectMapper,- endpointConfiguration,- tempFileManager,- taskManager,- cosMapper,- fallbackFontService,- fontService,- type3FontConversionService,- type3GlyphExtractor,- applicationProperties);-- when(tempFileManager.createTempFile(anyString()))- .thenAnswer(- invocation -> {- String suffix = invocation.getArgument(0);- Path path = Files.createTempFile("pdfjson-extra-test", suffix);- createdTempFiles.add(path);- return path.toFile();- });- when(tempFileManager.deleteTempFile(any(File.class)))- .thenAnswer(- invocation -> {- File file = invocation.getArgument(0);- return file != null && file.delete();- });- when(taskManager.addNote(anyString(), anyString())).thenReturn(true);- }-- @AfterEach- void tearDown() throws IOException {- JobContext.clear();- for (Path path : createdTempFiles) {- Files.deleteIfExists(path);- }- createdTempFiles.clear();- }-- // ------------------------------------------------------------------- // Helpers- // -------------------------------------------------------------------- private void stubFallbackFont() throws IOException {- when(fallbackFontService.buildFallbackFontModel())- .thenAnswer(- invocation ->- PdfJsonFont.builder()- .id(PdfJsonFallbackFontService.FALLBACK_FONT_ID)- .uid(PdfJsonFallbackFontService.FALLBACK_FONT_ID)- .baseName("Fallback")- .subtype("TrueType")- .build());- when(fallbackFontService.loadFallbackPdfFont(any(PDDocument.class)))- .thenAnswer(invocation -> new PDType1Font(Standard14Fonts.FontName.HELVETICA));- }-- private void stubCanEncode() {- when(fallbackFontService.canEncode(any(PDFont.class), anyString())).thenReturn(true);- when(fallbackFontService.canEncode(any(PDFont.class), anyInt())).thenReturn(true);- }-- private MockMultipartFile pdfMultipart(byte[] bytes) {- return new MockMultipartFile("fileInput", "input.pdf", "application/pdf", bytes);- }-- private MockMultipartFile jsonMultipart(byte[] bytes) {- return new MockMultipartFile("fileInput", "model.json", "application/json", bytes);- }-- private byte[] toBytes(PDDocument document) throws IOException {- try (document) {- ByteArrayOutputStream out = new ByteArrayOutputStream();- document.save(out);- return out.toByteArray();- }- }-- private BufferedImage solidImage(int w, int h, Color color, int type) {- BufferedImage image = new BufferedImage(w, h, type);- for (int x = 0; x < w; x++) {- for (int y = 0; y < h; y++) {- image.setRGB(x, y, color.getRGB());- }- }- return image;- }-- private String pngBase64(BufferedImage image) throws IOException {- ByteArrayOutputStream out = new ByteArrayOutputStream();- ImageIO.write(image, "png", out);- return Base64.getEncoder().encodeToString(out.toByteArray());- }-- private PdfJsonDocument toJsonDocument(byte[] pdfBytes) throws IOException {- when(pdfDocumentFactory.load(any(Path.class), eq(true)))- .thenAnswer(inv -> Loader.loadPDF(inv.getArgument(0, Path.class).toFile()));- ByteArrayOutputStream out = new ByteArrayOutputStream();- service.convertPdfToJson(pdfMultipart(pdfBytes), out);- return objectMapper.readValue(out.toByteArray(), PdfJsonDocument.class);- }-- private byte[] runJsonToPdf(PdfJsonDocument doc) throws IOException {- ByteArrayOutputStream out = new ByteArrayOutputStream();- service.convertJsonToPdf(doc, out);- return out.toByteArray();- }-- private PdfJsonDocument cacheLazyDocument(String jobId, byte[] pdfBytes) throws IOException {- when(pdfDocumentFactory.load(any(Path.class), eq(true)))- .thenAnswer(inv -> Loader.loadPDF(inv.getArgument(0, Path.class).toFile()));- when(pdfDocumentFactory.load(any(byte[].class), eq(true)))- .thenAnswer(inv -> Loader.loadPDF(inv.getArgument(0, byte[].class)));- JobContext.setJobId(jobId);- ByteArrayOutputStream out = new ByteArrayOutputStream();- service.convertPdfToJson(pdfMultipart(pdfBytes), true, out);- return objectMapper.readValue(out.toByteArray(), PdfJsonDocument.class);- }-- private PdfJsonDocument docWith(PdfJsonPage page) {- PdfJsonDocument doc = new PdfJsonDocument();- doc.setPages(new ArrayList<>(List.of(page)));- return doc;- }-- private PdfJsonFont std14Font(String id, String standard14Name) {- return PdfJsonFont.builder()- .id(id)- .uid(id)- .baseName(standard14Name)- .subtype("Type1")- .standard14Name(standard14Name)- .build();- }-- private byte[] simpleTextPdf(String text) throws IOException {- PDDocument document = new PDDocument();- PDPage page = new PDPage(PDRectangle.LETTER);- document.addPage(page);- try (PDPageContentStream cs = new PDPageContentStream(document, page)) {- cs.beginText();- cs.setFont(new PDType1Font(Standard14Fonts.FontName.HELVETICA), 12f);- cs.newLineAtOffset(72, 700);- cs.showText(text);- cs.endText();- }- return toBytes(document);- }-- // ==================================================================- // Document information / date / trapped round trips- // ==================================================================-- @Nested- @DisplayName("document information dates and trapped round trips")- class DocumentInfoRoundTrips {-- private byte[] datedPdf() throws IOException {- PDDocument document = new PDDocument();- document.addPage(new PDPage(PDRectangle.LETTER));- PDDocumentInformation info = document.getDocumentInformation();- info.setTitle("Dated Title");- info.setAuthor("Dated Author");- Calendar created = Calendar.getInstance(TimeZone.getTimeZone("UTC"));- created.set(2021, Calendar.MARCH, 4, 5, 6, 7);- created.set(Calendar.MILLISECOND, 0);- info.setCreationDate(created);- Calendar modified = Calendar.getInstance(TimeZone.getTimeZone("UTC"));- modified.set(2022, Calendar.JUNE, 8, 9, 10, 11);- modified.set(Calendar.MILLISECOND, 0);- info.setModificationDate(modified);- info.setTrapped("True");- return toBytes(document);- }-- @Test- @DisplayName("creation and modification dates are extracted as ISO instants")- void datesExtractedAsInstants() throws IOException {- PdfJsonDocument doc = toJsonDocument(datedPdf());- PdfJsonMetadata md = doc.getMetadata();- assertThat(md.getCreationDate()).isNotBlank();- assertThat(md.getModificationDate()).isNotBlank();- // formatCalendar emits Instant.toString(), so it should parse as an instant.- assertThat(md.getCreationDate()).contains("2021");- assertThat(md.getModificationDate()).contains("2022");- }-- @Test- @DisplayName("trapped flag survives extraction into the metadata model")- void trappedExtracted() throws IOException {- PdfJsonDocument doc = toJsonDocument(datedPdf());- assertThat(doc.getMetadata().getTrapped()).isEqualTo("True");- }-- @Test- @DisplayName("dates and trapped round trip back into PDDocumentInformation")- void datesRoundTripBack() throws IOException {- stubFallbackFont();- PdfJsonDocument doc = toJsonDocument(datedPdf());- byte[] rebuilt = runJsonToPdf(doc);- try (PDDocument loaded = Loader.loadPDF(rebuilt)) {- PDDocumentInformation info = loaded.getDocumentInformation();- assertEquals("Dated Title", info.getTitle());- assertEquals("True", info.getTrapped());- assertNotNull(info.getCreationDate());- assertEquals(2021, info.getCreationDate().get(Calendar.YEAR));- assertNotNull(info.getModificationDate());- assertEquals(2022, info.getModificationDate().get(Calendar.YEAR));- }- }-- @Test- @DisplayName("synthesized metadata with an unparseable date is ignored, rest applies")- void unparseableDateIgnored() throws IOException {- stubFallbackFont();- PdfJsonMetadata md =- PdfJsonMetadata.builder()- .title("Keep Title")- .creationDate("not-a-real-instant")- .modificationDate("2023-01-02T03:04:05Z")- .trapped("Unknown")- .build();- PdfJsonDocument doc = new PdfJsonDocument();- doc.setMetadata(md);- doc.setPages(new ArrayList<>());- byte[] rebuilt = runJsonToPdf(doc);- try (PDDocument loaded = Loader.loadPDF(rebuilt)) {- PDDocumentInformation info = loaded.getDocumentInformation();- assertEquals("Keep Title", info.getTitle());- assertEquals("Unknown", info.getTrapped());- // The bad creation date is dropped; the good modification date is applied.- assertNotNull(info.getModificationDate());- assertEquals(2023, info.getModificationDate().get(Calendar.YEAR));- }- }- }-- // ==================================================================- // convertJsonToPdf(MultipartFile) file overload- // ==================================================================-- @Nested- @DisplayName("convertJsonToPdf file overload round trips")- class JsonFileOverload {-- @Test- @DisplayName("re-serialized extracted model rebuilds via the file overload")- void fileOverloadRebuildsModel() throws IOException {- stubFallbackFont();- PdfJsonDocument doc = toJsonDocument(simpleTextPdf("File overload source"));- byte[] json = objectMapper.writeValueAsBytes(doc);- ByteArrayOutputStream out = new ByteArrayOutputStream();- service.convertJsonToPdf(jsonMultipart(json), out);- try (PDDocument loaded = Loader.loadPDF(out.toByteArray())) {- assertEquals(1, loaded.getNumberOfPages());- }- }-- @Test- @DisplayName("edited text re-serialized to JSON bytes rebuilds via the file overload")- void fileOverloadAppliesEdit() throws IOException {- stubFallbackFont();- stubCanEncode();- PdfJsonDocument doc = toJsonDocument(simpleTextPdf("Original line here"));- for (PdfJsonTextElement element : doc.getPages().get(0).getTextElements()) {- if (element.getText() != null && !element.getText().isBlank()) {- element.setText("Edited line text");- break;- }- }- byte[] json = objectMapper.writeValueAsBytes(doc);- ByteArrayOutputStream out = new ByteArrayOutputStream();- service.convertJsonToPdf(jsonMultipart(json), out);- assertThat(out.toByteArray()).isNotEmpty();- }- }-- // ==================================================================- // Full model mutation: add/remove pages, change colour/size/position- // ==================================================================-- @Nested- @DisplayName("model mutation round trips")- class ModelMutation {-- private byte[] twoPageTextPdf() throws IOException {- PDDocument document = new PDDocument();- for (int i = 0; i < 2; i++) {- PDPage page = new PDPage(PDRectangle.LETTER);- document.addPage(page);- try (PDPageContentStream cs = new PDPageContentStream(document, page)) {- cs.beginText();- cs.setFont(new PDType1Font(Standard14Fonts.FontName.HELVETICA), 12f);- cs.newLineAtOffset(72, 700);- cs.showText("Original page " + (i + 1));- cs.endText();- }- }- return toBytes(document);- }-- @Test- @DisplayName("removing a page from the model rebuilds with one fewer page")- void removePage() throws IOException {- stubFallbackFont();- PdfJsonDocument doc = toJsonDocument(twoPageTextPdf());- assertEquals(2, doc.getPages().size());- List<PdfJsonPage> pages = new ArrayList<>(doc.getPages());- pages.remove(1);- doc.setPages(pages);- byte[] rebuilt = runJsonToPdf(doc);- try (PDDocument loaded = Loader.loadPDF(rebuilt)) {- assertEquals(1, loaded.getNumberOfPages());- }- }-- @Test- @DisplayName("adding a synthesized page rebuilds with one more page")- void addPage() throws IOException {- stubFallbackFont();- PdfJsonDocument doc = toJsonDocument(twoPageTextPdf());- List<PdfJsonPage> pages = new ArrayList<>(doc.getPages());- PdfJsonFont font = std14Font("ExtraF", "Helvetica");- List<PdfJsonFont> fonts =- doc.getFonts() != null ? new ArrayList<>(doc.getFonts()) : new ArrayList<>();- fonts.add(font);- doc.setFonts(fonts);- PdfJsonTextElement element =- PdfJsonTextElement.builder()- .text("Brand new page")- .fontId("ExtraF")- .fontSize(14f)- .x(72f)- .y(700f)- .build();- pages.add(- PdfJsonPage.builder()- .pageNumber(3)- .width(612f)- .height(792f)- .textElements(new ArrayList<>(List.of(element)))- .build());- doc.setPages(pages);- byte[] rebuilt = runJsonToPdf(doc);- try (PDDocument loaded = Loader.loadPDF(rebuilt)) {- assertEquals(3, loaded.getNumberOfPages());- }- }-- @Test- @DisplayName("changing text colour, font size and position rebuilds a valid PDF")- void changeColorSizePosition() throws IOException {- stubFallbackFont();- stubCanEncode();- PdfJsonDocument doc = toJsonDocument(simpleTextPdf("Recolour me"));- for (PdfJsonTextElement element : doc.getPages().get(0).getTextElements()) {- element.setFontSize(28f);- element.setX(120f);- element.setY(540f);- element.setFillColor(- PdfJsonTextColor.builder()- .colorSpace("DeviceRGB")- .components(new float[] {0.9f, 0.1f, 0.4f})- .build());- }- byte[] rebuilt = runJsonToPdf(doc);- try (PDDocument loaded = Loader.loadPDF(rebuilt)) {- assertEquals(1, loaded.getNumberOfPages());- }- }- }-- // ==================================================================- // Cache export: add / remove / modify text and image elements- // ==================================================================-- @Nested- @DisplayName("cache export with element edits")- class CacheExportElementEdits {-- private byte[] textAndImagePdf() throws IOException {- PDDocument document = new PDDocument();- PDPage page = new PDPage(PDRectangle.LETTER);- document.addPage(page);- PDImageXObject image =- LosslessFactory.createFromImage(- document, solidImage(20, 16, Color.GREEN, BufferedImage.TYPE_INT_RGB));- try (PDPageContentStream cs = new PDPageContentStream(document, page)) {- cs.drawImage(image, 100, 500, 80, 64);- cs.beginText();- cs.setFont(new PDType1Font(Standard14Fonts.FontName.HELVETICA), 12f);- cs.newLineAtOffset(72, 400);- cs.showText("Caption text");- cs.endText();- }- return toBytes(document);- }-- @Test- @DisplayName("export applies an edit that adds a new image element to a cached page")- void exportAddsImage() throws IOException {- stubFallbackFont();- cacheLazyDocument("job-add-img", simpleTextPdf("Add an image here"));-- ByteArrayOutputStream pageOut = new ByteArrayOutputStream();- service.extractSinglePage("job-add-img", 1, pageOut);- PdfJsonPage page = objectMapper.readValue(pageOut.toByteArray(), PdfJsonPage.class);- page.setPageNumber(1);-- PdfJsonImageElement added =- PdfJsonImageElement.builder()- .id("AddedIm")- .imageData(- pngBase64(- solidImage(- 12, 12, Color.RED, BufferedImage.TYPE_INT_RGB)))- .imageFormat("png")- .x(60f)- .y(600f)- .width(48f)- .height(48f)- .build();- page.setImageElements(new ArrayList<>(List.of(added)));-- PdfJsonDocument updates = new PdfJsonDocument();- updates.setPages(new ArrayList<>(List.of(page)));-- ByteArrayOutputStream out = new ByteArrayOutputStream();- service.exportUpdatedPages("job-add-img", updates, out);- try (PDDocument loaded = Loader.loadPDF(out.toByteArray())) {- assertEquals(1, loaded.getNumberOfPages());- assertNotNull(loaded.getPage(0).getResources());- }- }-- @Test- @DisplayName("export applies an edit that removes all text from a cached page")- void exportRemovesText() throws IOException {- stubFallbackFont();- cacheLazyDocument("job-remove-text", textAndImagePdf());-- ByteArrayOutputStream pageOut = new ByteArrayOutputStream();- service.extractSinglePage("job-remove-text", 1, pageOut);- PdfJsonPage page = objectMapper.readValue(pageOut.toByteArray(), PdfJsonPage.class);- page.setPageNumber(1);- page.setTextElements(new ArrayList<>());-- PdfJsonDocument updates = new PdfJsonDocument();- updates.setPages(new ArrayList<>(List.of(page)));-- ByteArrayOutputStream out = new ByteArrayOutputStream();- service.exportUpdatedPages("job-remove-text", updates, out);- assertThat(out.toByteArray()).isNotEmpty();- }-- @Test- @DisplayName("export merges a font supplied in the update document")- void exportMergesUpdateFont() throws IOException {- stubFallbackFont();- stubCanEncode();- cacheLazyDocument("job-update-font", simpleTextPdf("Font merge source"));-- ByteArrayOutputStream pageOut = new ByteArrayOutputStream();- service.extractSinglePage("job-update-font", 1, pageOut);- PdfJsonPage page = objectMapper.readValue(pageOut.toByteArray(), PdfJsonPage.class);- page.setPageNumber(1);-- PdfJsonDocument updates = new PdfJsonDocument();- updates.setPages(new ArrayList<>(List.of(page)));- // A font carried on the update document drives the updates.getFonts() merge branch.- updates.setFonts(new ArrayList<>(List.of(std14Font("UpdF", "Times-Roman"))));-- ByteArrayOutputStream out = new ByteArrayOutputStream();- service.exportUpdatedPages("job-update-font", updates, out);- try (PDDocument loaded = Loader.loadPDF(out.toByteArray())) {- assertEquals(1, loaded.getNumberOfPages());- }- }-- @Test- @DisplayName("export of a cached image-bearing page surfaces image data on re-extract")- void exportThenReextractImage() throws IOException {- stubFallbackFont();- cacheLazyDocument("job-export-img", textAndImagePdf());-- ByteArrayOutputStream pageOut = new ByteArrayOutputStream();- service.extractSinglePage("job-export-img", 1, pageOut);- PdfJsonPage page = objectMapper.readValue(pageOut.toByteArray(), PdfJsonPage.class);- page.setPageNumber(1);- for (PdfJsonTextElement element : page.getTextElements()) {- if (element.getText() != null && !element.getText().isBlank()) {- element.setText("Caption edited");- break;- }- }- PdfJsonDocument updates = new PdfJsonDocument();- updates.setPages(new ArrayList<>(List.of(page)));-- ByteArrayOutputStream out = new ByteArrayOutputStream();- service.exportUpdatedPages("job-export-img", updates, out);-- // The cache is now refreshed; pulling the page back still yields image data.- ByteArrayOutputStream reOut = new ByteArrayOutputStream();- service.extractSinglePage("job-export-img", 1, reOut);- PdfJsonPage reloaded = objectMapper.readValue(reOut.toByteArray(), PdfJsonPage.class);- assertThat(reloaded.getImageElements()).isNotEmpty();- }- }-- // ==================================================================- // extractDocumentMetadata variants and downstream cache use- // ==================================================================-- @Nested- @DisplayName("metadata extraction feeding the cache")- class MetadataCacheFlow {-- @Test- @DisplayName("metadata extraction then export with no updates returns the cached PDF")- void metadataThenExportNoUpdates() throws IOException {- when(pdfDocumentFactory.load(any(byte[].class), eq(true)))- .thenAnswer(inv -> Loader.loadPDF(inv.getArgument(0, byte[].class)));- ByteArrayOutputStream metaOut = new ByteArrayOutputStream();- service.extractDocumentMetadata(- pdfMultipart(simpleTextPdf("Meta then export")), "job-meta-export", metaOut);- PdfJsonDocumentMetadata md =- objectMapper.readValue(metaOut.toByteArray(), PdfJsonDocumentMetadata.class);- assertThat(md.getPageDimensions()).hasSize(1);-- ByteArrayOutputStream out = new ByteArrayOutputStream();- service.exportUpdatedPages("job-meta-export", new PdfJsonDocument(), out);- try (PDDocument loaded = Loader.loadPDF(out.toByteArray())) {- assertEquals(1, loaded.getNumberOfPages());- }- }-- @Test- @DisplayName("metadata extraction caches fonts retrievable via extractPageFonts")- void metadataThenPageFonts() throws IOException {- when(pdfDocumentFactory.load(any(byte[].class), eq(true)))- .thenAnswer(inv -> Loader.loadPDF(inv.getArgument(0, byte[].class)));- ByteArrayOutputStream metaOut = new ByteArrayOutputStream();- service.extractDocumentMetadata(- pdfMultipart(simpleTextPdf("Fonts via metadata")), "job-meta-fonts", metaOut);-- ByteArrayOutputStream out = new ByteArrayOutputStream();- service.extractPageFonts("job-meta-fonts", 1, out);- List<?> fonts = objectMapper.readValue(out.toByteArray(), List.class);- assertThat(fonts).isNotEmpty();- }-- @Test- @DisplayName("metadata extraction carries the extracted document title")- void metadataCarriesTitle() throws IOException {- PDDocument document = new PDDocument();- document.addPage(new PDPage(PDRectangle.LETTER));- document.getDocumentInformation().setTitle("Meta Title Extra");- byte[] bytes = toBytes(document);-- when(pdfDocumentFactory.load(any(byte[].class), eq(true)))- .thenAnswer(inv -> Loader.loadPDF(inv.getArgument(0, byte[].class)));- ByteArrayOutputStream out = new ByteArrayOutputStream();- service.extractDocumentMetadata(pdfMultipart(bytes), null, out);- PdfJsonDocumentMetadata md =- objectMapper.readValue(out.toByteArray(), PdfJsonDocumentMetadata.class);- assertThat(md.getMetadata()).isNotNull();- assertEquals("Meta Title Extra", md.getMetadata().getTitle());- }- }-- // ==================================================================- // Rich COS metadata via nested page resources- // ==================================================================-- @Nested- @DisplayName("rich COS object mapping via resources")- class RichCosMapping {-- /** A page whose resource dictionary carries nested arrays/dicts/name/number/bool/null. */- private byte[] richResourcePdf() throws IOException {- PDDocument document = new PDDocument();- PDPage page = new PDPage(PDRectangle.LETTER);- document.addPage(page);- try (PDPageContentStream cs = new PDPageContentStream(document, page)) {- cs.beginText();- cs.setFont(new PDType1Font(Standard14Fonts.FontName.HELVETICA), 12f);- cs.newLineAtOffset(72, 700);- cs.showText("Resource carrier");- cs.endText();- }-- org.apache.pdfbox.cos.COSDictionary custom = new org.apache.pdfbox.cos.COSDictionary();- custom.setItem(- org.apache.pdfbox.cos.COSName.getPDFName("AName"),- org.apache.pdfbox.cos.COSName.getPDFName("SomeValue"));- custom.setItem(- org.apache.pdfbox.cos.COSName.getPDFName("AnInt"),- org.apache.pdfbox.cos.COSInteger.get(7L));- custom.setItem(- org.apache.pdfbox.cos.COSName.getPDFName("AFloat"),- new org.apache.pdfbox.cos.COSFloat(1.25f));- custom.setItem(- org.apache.pdfbox.cos.COSName.getPDFName("ABool"),- org.apache.pdfbox.cos.COSBoolean.TRUE);- custom.setItem(- org.apache.pdfbox.cos.COSName.getPDFName("ANull"),- org.apache.pdfbox.cos.COSNull.NULL);- custom.setItem(- org.apache.pdfbox.cos.COSName.getPDFName("AString"),- new org.apache.pdfbox.cos.COSString("hello string"));-- org.apache.pdfbox.cos.COSArray nested = new org.apache.pdfbox.cos.COSArray();- nested.add(org.apache.pdfbox.cos.COSInteger.get(1L));- nested.add(org.apache.pdfbox.cos.COSInteger.get(2L));- org.apache.pdfbox.cos.COSDictionary innerDict =- new org.apache.pdfbox.cos.COSDictionary();- innerDict.setItem(- org.apache.pdfbox.cos.COSName.getPDFName("Deep"),- org.apache.pdfbox.cos.COSName.getPDFName("Value"));- nested.add(innerDict);- custom.setItem(org.apache.pdfbox.cos.COSName.getPDFName("AnArray"), nested);-- // Resources dictionary is created once the content stream sets a font above.- page.getResources()- .getCOSObject()- .setItem(org.apache.pdfbox.cos.COSName.getPDFName("StirlingExtra"), custom);-- return toBytes(document);- }-- @Test- @DisplayName("nested custom resource dictionary is preserved through extraction")- void richResourcesPreserved() throws IOException {- PdfJsonDocument doc = toJsonDocument(richResourcePdf());- PdfJsonPage page = doc.getPages().get(0);- assertNotNull(page.getResources());- }-- @Test- @DisplayName("nested custom resource dictionary survives a full round trip")- void richResourcesRoundTrip() throws IOException {- stubFallbackFont();- PdfJsonDocument doc = toJsonDocument(richResourcePdf());- byte[] rebuilt = runJsonToPdf(doc);- try (PDDocument loaded = Loader.loadPDF(rebuilt)) {- assertEquals(1, loaded.getNumberOfPages());- assertNotNull(loaded.getPage(0).getResources());- }- }- }-- // ==================================================================- // Text render modes / spacing / rise / negative coords (synthesized)- // ==================================================================-- @Nested- @DisplayName("text render modes, spacing and coordinates")- class TextStateVariants {-- private PdfJsonDocument textWith(PdfJsonTextElement element) {- PdfJsonPage page =- PdfJsonPage.builder()- .pageNumber(1)- .width(612f)- .height(792f)- .textElements(new ArrayList<>(List.of(element)))- .build();- PdfJsonDocument doc = docWith(page);- doc.setFonts(new ArrayList<>(List.of(std14Font("F1", "Helvetica"))));- return doc;- }-- @Test- @DisplayName("stroke render mode (1) renders with a stroke colour")- void strokeRenderMode() throws IOException {- stubFallbackFont();- stubCanEncode();- PdfJsonTextElement element =- PdfJsonTextElement.builder()- .text("Stroked")- .fontId("F1")- .fontSize(18f)- .renderingMode(1)- .strokeColor(- PdfJsonTextColor.builder()- .colorSpace("DeviceRGB")- .components(new float[] {0.1f, 0.2f, 0.3f})- .build())- .x(72f)- .y(700f)- .build();- assertThat(runJsonToPdf(textWith(element))).isNotEmpty();- }-- @Test- @DisplayName("invisible render mode (3) still rebuilds cleanly")- void invisibleRenderMode() throws IOException {- stubFallbackFont();- stubCanEncode();- PdfJsonTextElement element =- PdfJsonTextElement.builder()- .text("Invisible")- .fontId("F1")- .fontSize(12f)- .renderingMode(3)- .x(72f)- .y(680f)- .build();- assertThat(runJsonToPdf(textWith(element))).isNotEmpty();- }-- @Test- @DisplayName("fill-stroke-clip render mode (7) rebuilds cleanly")- void fillStrokeClipRenderMode() throws IOException {- stubFallbackFont();- stubCanEncode();- PdfJsonTextElement element =- PdfJsonTextElement.builder()- .text("Clipped")- .fontId("F1")- .fontSize(12f)- .renderingMode(7)- .fillColor(- PdfJsonTextColor.builder()- .colorSpace("DeviceGray")- .components(new float[] {0.3f})- .build())- .x(72f)- .y(660f)- .build();- assertThat(runJsonToPdf(textWith(element))).isNotEmpty();- }-- @Test- @DisplayName("word spacing, horizontal scaling and rise combine without error")- void spacingScalingRise() throws IOException {- stubFallbackFont();- stubCanEncode();- PdfJsonTextElement element =- PdfJsonTextElement.builder()- .text("spaced words rise")- .fontId("F1")- .fontSize(14f)- .wordSpacing(3.5f)- .characterSpacing(0.7f)- .horizontalScaling(130f)- .rise(4f)- .leading(18f)- .x(72f)- .y(640f)- .build();- assertThat(runJsonToPdf(textWith(element))).isNotEmpty();- }-- @Test- @DisplayName("negative coordinates are tolerated by the regeneration path")- void negativeCoordinates() throws IOException {- stubFallbackFont();- stubCanEncode();- PdfJsonTextElement element =- PdfJsonTextElement.builder()- .text("Below origin")- .fontId("F1")- .fontSize(12f)- .x(-50f)- .y(-25f)- .build();- assertThat(runJsonToPdf(textWith(element))).isNotEmpty();- }-- @Test- @DisplayName("zero font size falls back without aborting the rebuild")- void zeroFontSize() throws IOException {- stubFallbackFont();- stubCanEncode();- PdfJsonTextElement element =- PdfJsonTextElement.builder()- .text("Zero size")- .fontId("F1")- .fontSize(0f)- .x(72f)- .y(620f)- .build();- assertDoesNotThrow(() -> runJsonToPdf(textWith(element)));- }- }-- // ==================================================================- // Multiple images per page + mixed content (synthesized + extracted)- // ==================================================================-- @Nested- @DisplayName("multiple images and mixed content")- class MultiImageMixed {-- @Test- @DisplayName("two synthesized images (JPEG + lossless PNG) render on one page")- void twoSynthesizedImages() throws IOException {- stubFallbackFont();- ByteArrayOutputStream jpgOut = new ByteArrayOutputStream();- ImageIO.write(solidImage(16, 16, Color.RED, BufferedImage.TYPE_INT_RGB), "jpg", jpgOut);- String jpg = Base64.getEncoder().encodeToString(jpgOut.toByteArray());-- PdfJsonImageElement jpeg =- PdfJsonImageElement.builder()- .id("Jpeg")- .imageData(jpg)- .imageFormat("jpg")- .x(60f)- .y(600f)- .width(64f)- .height(48f)- .build();- PdfJsonImageElement png =- PdfJsonImageElement.builder()- .id("Png")- .imageData(- pngBase64(- solidImage(- 16,- 16,- Color.BLUE,- BufferedImage.TYPE_INT_RGB)))- .imageFormat("png")- .x(200f)- .y(600f)- .width(48f)- .height(48f)- .build();- PdfJsonPage page =- PdfJsonPage.builder()- .pageNumber(1)- .width(612f)- .height(792f)- .imageElements(new ArrayList<>(List.of(jpeg, png)))- .build();- try (PDDocument loaded = Loader.loadPDF(runJsonToPdf(docWith(page)))) {- assertEquals(1, loaded.getNumberOfPages());- assertNotNull(loaded.getPage(0).getResources());- }- }-- @Test- @DisplayName("page mixing text, image and annotation round trips from extraction")- void mixedTextImageAnnotationExtracted() throws IOException {- stubFallbackFont();- PDDocument document = new PDDocument();- PDPage page = new PDPage(PDRectangle.LETTER);- document.addPage(page);-- PDImageXObject jpeg =- JPEGFactory.createFromImage(- document, solidImage(24, 18, Color.RED, BufferedImage.TYPE_INT_RGB));- PDImageXObject png =- LosslessFactory.createFromImage(- document, solidImage(18, 18, Color.BLUE, BufferedImage.TYPE_INT_RGB));-- PDAnnotationText note = new PDAnnotationText();- note.setContents("Mixed note");- note.setRectangle(new PDRectangle(50, 720, 18, 18));- page.getAnnotations().add(note);-- try (PDPageContentStream cs = new PDPageContentStream(document, page)) {- cs.drawImage(jpeg, 60, 600, 96, 72);- cs.drawImage(png, 200, 600, 72, 72);- cs.beginText();- cs.setFont(new PDType1Font(Standard14Fonts.FontName.HELVETICA), 12f);- cs.newLineAtOffset(72, 500);- cs.showText("Mixed content body");- cs.endText();- }- byte[] bytes = toBytes(document);-- PdfJsonDocument doc = toJsonDocument(bytes);- PdfJsonPage extracted = doc.getPages().get(0);- assertThat(extracted.getImageElements()).hasSizeGreaterThanOrEqualTo(2);- assertThat(extracted.getTextElements()).isNotEmpty();- assertThat(extracted.getAnnotations()).isNotEmpty();-- byte[] rebuilt = runJsonToPdf(doc);- try (PDDocument loaded = Loader.loadPDF(rebuilt)) {- assertEquals(1, loaded.getNumberOfPages());- }- }-- @Test- @DisplayName("lazy single-page extraction surfaces multiple images for a cached page")- void lazyMultipleImages() throws IOException {- PDDocument document = new PDDocument();- PDPage page = new PDPage(PDRectangle.LETTER);- document.addPage(page);- PDImageXObject a =- LosslessFactory.createFromImage(- document, solidImage(16, 16, Color.RED, BufferedImage.TYPE_INT_RGB));- PDImageXObject b =- LosslessFactory.createFromImage(- document, solidImage(16, 16, Color.BLUE, BufferedImage.TYPE_INT_RGB));- try (PDPageContentStream cs = new PDPageContentStream(document, page)) {- cs.drawImage(a, 60, 600, 48, 48);- cs.drawImage(b, 200, 600, 48, 48);- }- byte[] bytes = toBytes(document);-- cacheLazyDocument("job-multi-img", bytes);- ByteArrayOutputStream out = new ByteArrayOutputStream();- service.extractSinglePage("job-multi-img", 1, out);- PdfJsonPage extracted = objectMapper.readValue(out.toByteArray(), PdfJsonPage.class);- assertThat(extracted.getImageElements()).hasSizeGreaterThanOrEqualTo(2);- }- }-- // ==================================================================- // Cache lifecycle and miss paths- // ==================================================================-- @Nested- @DisplayName("cache lifecycle and miss paths")- class CacheLifecycle {-- @Test- @DisplayName("extractPageFonts on a cleared job throws CacheUnavailableException")- void pageFontsAfterClearThrows() throws IOException {- cacheLazyDocument("job-clear-fonts", simpleTextPdf("Clear fonts"));- service.clearCachedDocument("job-clear-fonts");- ByteArrayOutputStream out = new ByteArrayOutputStream();- assertThrows(- CacheUnavailableException.class,- () -> service.extractPageFonts("job-clear-fonts", 1, out));- }-- @Test- @DisplayName("exportUpdatedPages on a cleared job throws CacheUnavailableException")- void exportAfterClearThrows() throws IOException {- cacheLazyDocument("job-clear-export", simpleTextPdf("Clear export"));- service.clearCachedDocument("job-clear-export");- PdfJsonPage page = new PdfJsonPage();- page.setPageNumber(1);- PdfJsonDocument updates = new PdfJsonDocument();- updates.setPages(new ArrayList<>(List.of(page)));- ByteArrayOutputStream out = new ByteArrayOutputStream();- assertThrows(- CacheUnavailableException.class,- () -> service.exportUpdatedPages("job-clear-export", updates, out));- }-- @Test- @DisplayName("extractDocumentMetadata reusing a jobId refreshes the cached document")- void metadataReusedJobIdRefreshes() throws IOException {- when(pdfDocumentFactory.load(any(byte[].class), eq(true)))- .thenAnswer(inv -> Loader.loadPDF(inv.getArgument(0, byte[].class)));- ByteArrayOutputStream first = new ByteArrayOutputStream();- service.extractDocumentMetadata(- pdfMultipart(simpleTextPdf("First doc")), "job-reuse", first);-- // Re-run with a two-page doc under the same jobId; the cache should now report two- // pages.- PDDocument twoPager = new PDDocument();- twoPager.addPage(new PDPage(PDRectangle.LETTER));- twoPager.addPage(new PDPage(PDRectangle.LETTER));- byte[] twoBytes = toBytes(twoPager);-- ByteArrayOutputStream second = new ByteArrayOutputStream();- service.extractDocumentMetadata(pdfMultipart(twoBytes), "job-reuse", second);-- ByteArrayOutputStream pageOut = new ByteArrayOutputStream();- service.extractSinglePage("job-reuse", 2, pageOut);- PdfJsonPage page = objectMapper.readValue(pageOut.toByteArray(), PdfJsonPage.class);- assertEquals(2, page.getPageNumber());- }- }-}diff --git a/app/core/src/test/java/stirling/software/SPDF/service/PdfJsonConversionServiceGapTest.java b/app/core/src/test/java/stirling/software/SPDF/service/PdfJsonConversionServiceGapTest.javadeleted file mode 100644index 5178b779f4..0000000000--- a/app/core/src/test/java/stirling/software/SPDF/service/PdfJsonConversionServiceGapTest.java+++ /dev/null@@ -1,654 +0,0 @@-package stirling.software.SPDF.service;--import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;-import static org.junit.jupiter.api.Assertions.assertEquals;-import static org.junit.jupiter.api.Assertions.assertNotNull;-import static org.junit.jupiter.api.Assertions.assertThrows;-import static org.junit.jupiter.api.Assertions.assertTrue;-import static org.mockito.ArgumentMatchers.any;-import static org.mockito.ArgumentMatchers.anyString;-import static org.mockito.ArgumentMatchers.eq;-import static org.mockito.Mockito.when;--import java.io.ByteArrayOutputStream;-import java.io.File;-import java.io.IOException;-import java.nio.charset.StandardCharsets;-import java.nio.file.Files;-import java.nio.file.Path;-import java.util.ArrayList;-import java.util.Base64;-import java.util.List;-import java.util.concurrent.atomic.AtomicBoolean;--import org.apache.pdfbox.Loader;-import org.apache.pdfbox.pdmodel.PDDocument;-import org.apache.pdfbox.pdmodel.PDDocumentInformation;-import org.apache.pdfbox.pdmodel.PDPage;-import org.apache.pdfbox.pdmodel.common.PDRectangle;-import org.apache.pdfbox.pdmodel.font.PDType1Font;-import org.apache.pdfbox.pdmodel.font.Standard14Fonts;-import org.junit.jupiter.api.AfterEach;-import org.junit.jupiter.api.BeforeEach;-import org.junit.jupiter.api.DisplayName;-import org.junit.jupiter.api.Nested;-import org.junit.jupiter.api.Test;-import org.junit.jupiter.api.extension.ExtendWith;-import org.mockito.Mock;-import org.mockito.junit.jupiter.MockitoExtension;-import org.mockito.quality.Strictness;-import org.springframework.mock.web.MockMultipartFile;--import stirling.software.SPDF.config.EndpointConfiguration;-import stirling.software.SPDF.exception.CacheUnavailableException;-import stirling.software.SPDF.model.json.PdfJsonDocument;-import stirling.software.SPDF.model.json.PdfJsonFont;-import stirling.software.SPDF.model.json.PdfJsonMetadata;-import stirling.software.SPDF.model.json.PdfJsonPage;-import stirling.software.SPDF.service.pdfjson.PdfJsonFontService;-import stirling.software.SPDF.service.pdfjson.type3.Type3FontConversionService;-import stirling.software.SPDF.service.pdfjson.type3.Type3GlyphExtractor;-import stirling.software.common.model.ApplicationProperties;-import stirling.software.common.service.CustomPDFDocumentFactory;-import stirling.software.common.service.TaskManager;-import stirling.software.common.util.TempFileManager;--import tools.jackson.databind.DeserializationFeature;-import tools.jackson.databind.ObjectMapper;-import tools.jackson.databind.json.JsonMapper;--/**- * Gap tests for {@link PdfJsonConversionService} that exercise the public conversion entrypoints- * and the cache-backed public API. These complement {@code- * PdfJsonConversionServiceUnicodeParsingTest} (which covers the static {@code- * parseToUnicodeCodepoint} / {@code countCodesProtected} helpers) without duplicating those cases.- *- * <p>The service is constructed as a plain unit (no Spring context), so {@code @PostConstruct}- * never runs: font normalization stays disabled and Ghostscript is never invoked, keeping every- * test fully deterministic and free of external processes. {@link CustomPDFDocumentFactory#load} is- * stubbed to return real in-memory PDFBox documents, and {@code fallbackFontService} is mocked so- * the JSON to PDF path can resolve its mandatory fallback font without touching the classpath.- */-@ExtendWith(MockitoExtension.class)[email protected](strictness = Strictness.LENIENT)-class PdfJsonConversionServiceGapTest {-- @Mock private CustomPDFDocumentFactory pdfDocumentFactory;- @Mock private EndpointConfiguration endpointConfiguration;- @Mock private TempFileManager tempFileManager;- @Mock private TaskManager taskManager;- @Mock private PdfJsonFallbackFontService fallbackFontService;- @Mock private PdfJsonFontService fontService;- @Mock private Type3FontConversionService type3FontConversionService;- @Mock private Type3GlyphExtractor type3GlyphExtractor;- @Mock private ApplicationProperties applicationProperties;-- // Real collaborators: COS (de)serialization is complex and pure, so we use the real component.- private final PdfJsonCosMapper cosMapper = new PdfJsonCosMapper();-- // Mirror production: application.properties sets- // spring.jackson.deserialization.fail-on-null-for-primitives=false, so the Spring-managed- // mapper- // maps null/absent JSON values onto Java primitive defaults (e.g. the boolean lazyImages- // field).- // A naive JsonMapper.builder().build() keeps the Jackson 3 default (true) and would throw- // MismatchedInputException on round-trip, which is a test-mapper config gap, not a product bug.- private final ObjectMapper objectMapper =- JsonMapper.builder()- .disable(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES)- .build();-- private PdfJsonConversionService service;-- private final List<Path> createdTempFiles = new ArrayList<>();-- @BeforeEach- void setUp() throws IOException {- service =- new PdfJsonConversionService(- pdfDocumentFactory,- objectMapper,- endpointConfiguration,- tempFileManager,- taskManager,- cosMapper,- fallbackFontService,- fontService,- type3FontConversionService,- type3GlyphExtractor,- applicationProperties);-- // The TempFile wrapper delegates straight to the manager; back it with real temp files so- // convertPdfToJson can transferTo() and size/read the working path.- when(tempFileManager.createTempFile(anyString()))- .thenAnswer(- invocation -> {- String suffix = invocation.getArgument(0);- Path path = Files.createTempFile("pdfjson-gap-test", suffix);- createdTempFiles.add(path);- return path.toFile();- });- when(tempFileManager.deleteTempFile(any(File.class)))- .thenAnswer(- invocation -> {- File file = invocation.getArgument(0);- return file != null && file.delete();- });- }-- @AfterEach- void tearDown() throws IOException {- for (Path path : createdTempFiles) {- Files.deleteIfExists(path);- }- createdTempFiles.clear();- }-- // ------------------------------------------------------------------- // Helpers- // -------------------------------------------------------------------- /** Builds a tiny in-memory PDF with the requested page dimensions and rotations. */- private PDDocument newPdf(float[][] sizes, int[] rotations) {- PDDocument document = new PDDocument();- for (int i = 0; i < sizes.length; i++) {- PDPage page = new PDPage(new PDRectangle(sizes[i][0], sizes[i][1]));- if (rotations != null) {- page.setRotation(rotations[i]);- }- document.addPage(page);- }- return document;- }-- private PDDocument singlePagePdf(float width, float height) {- return newPdf(new float[][] {{width, height}}, null);- }-- /** Stubs the fallback font service so buildFontMap can always resolve a usable PDFont. */- private void stubFallbackFont() throws IOException {- when(fallbackFontService.buildFallbackFontModel())- .thenAnswer(- invocation ->- PdfJsonFont.builder()- .id(PdfJsonFallbackFontService.FALLBACK_FONT_ID)- .uid(PdfJsonFallbackFontService.FALLBACK_FONT_ID)- .baseName("Fallback")- .subtype("TrueType")- .build());- when(fallbackFontService.loadFallbackPdfFont(any(PDDocument.class)))- .thenAnswer(invocation -> new PDType1Font(Standard14Fonts.FontName.HELVETICA));- }-- private MockMultipartFile pdfMultipart() {- return new MockMultipartFile(- "fileInput", "input.pdf", "application/pdf", "%PDF-1.4 placeholder".getBytes());- }-- private byte[] runJsonToPdf(PdfJsonDocument doc) throws IOException {- ByteArrayOutputStream out = new ByteArrayOutputStream();- service.convertJsonToPdf(doc, out);- return out.toByteArray();- }-- // ------------------------------------------------------------------- // parseToUnicodeCodepoint - extra cases not covered by the unicode test- // -------------------------------------------------------------------- @Nested- @DisplayName("parseToUnicodeCodepoint extras")- class ParseToUnicodeExtras {-- @Test- @DisplayName("parses the maximum BMP value FFFF")- void parsesMaxBmpValue() {- assertEquals(0xFFFF, PdfJsonConversionService.parseToUnicodeCodepoint("FFFF"));- }-- @Test- @DisplayName("accepts lowercase hex digits")- void parsesLowercaseHex() {- // U+00E9 LATIN SMALL LETTER E WITH ACUTE.- assertEquals(0x00E9, PdfJsonConversionService.parseToUnicodeCodepoint("00e9"));- }-- @Test- @DisplayName("parses a 3-char value directly (length <= 4)")- void parsesThreeCharValue() {- assertEquals(0x1F4, PdfJsonConversionService.parseToUnicodeCodepoint("1f4"));- }- }-- // ------------------------------------------------------------------- // convertJsonToPdf(PdfJsonDocument, OutputStream)- // -------------------------------------------------------------------- @Nested- @DisplayName("convertJsonToPdf(document)")- class JsonToPdfDocument {-- @Test- @DisplayName("null document throws IllegalArgumentException")- void nullDocumentThrows() {- ByteArrayOutputStream out = new ByteArrayOutputStream();- assertThrows(- IllegalArgumentException.class,- () -> service.convertJsonToPdf((PdfJsonDocument) null, out));- }-- @Test- @DisplayName("single empty page produces a valid one-page PDF with correct dimensions")- void singleEmptyPage() throws IOException {- stubFallbackFont();- PdfJsonPage page = new PdfJsonPage();- page.setPageNumber(1);- page.setWidth(300f);- page.setHeight(400f);-- PdfJsonDocument doc = new PdfJsonDocument();- doc.setPages(List.of(page));-- byte[] pdfBytes = runJsonToPdf(doc);- assertTrue(pdfBytes.length > 0, "expected non-empty PDF output");-- try (PDDocument loaded = Loader.loadPDF(pdfBytes)) {- assertEquals(1, loaded.getNumberOfPages());- PDRectangle box = loaded.getPage(0).getMediaBox();- assertEquals(300f, box.getWidth(), 0.01f);- assertEquals(400f, box.getHeight(), 0.01f);- }- }-- @Test- @DisplayName("missing width/height falls back to US-Letter defaults")- void missingDimensionsUseDefaults() throws IOException {- stubFallbackFont();- PdfJsonPage page = new PdfJsonPage();- page.setPageNumber(1);- // width/height left null -> safeFloat defaults of 612x792-- PdfJsonDocument doc = new PdfJsonDocument();- doc.setPages(List.of(page));-- try (PDDocument loaded = Loader.loadPDF(runJsonToPdf(doc))) {- PDRectangle box = loaded.getPage(0).getMediaBox();- assertEquals(612f, box.getWidth(), 0.01f);- assertEquals(792f, box.getHeight(), 0.01f);- }- }-- @Test- @DisplayName("multiple pages keep their individual sizes and rotation")- void multiplePagesKeepSizesAndRotation() throws IOException {- stubFallbackFont();- PdfJsonPage first = new PdfJsonPage();- first.setPageNumber(1);- first.setWidth(200f);- first.setHeight(300f);- first.setRotation(90);-- PdfJsonPage second = new PdfJsonPage();- second.setPageNumber(2);- second.setWidth(500f);- second.setHeight(250f);- second.setRotation(180);-- PdfJsonDocument doc = new PdfJsonDocument();- doc.setPages(List.of(first, second));-- try (PDDocument loaded = Loader.loadPDF(runJsonToPdf(doc))) {- assertEquals(2, loaded.getNumberOfPages());- assertEquals(200f, loaded.getPage(0).getMediaBox().getWidth(), 0.01f);- assertEquals(90, loaded.getPage(0).getRotation());- assertEquals(500f, loaded.getPage(1).getMediaBox().getWidth(), 0.01f);- assertEquals(180, loaded.getPage(1).getRotation());- }- }-- @Test- @DisplayName("document metadata round-trips into PDDocumentInformation")- void metadataRoundTrips() throws IOException {- stubFallbackFont();- PdfJsonMetadata metadata = new PdfJsonMetadata();- metadata.setTitle("Gap Test Title");- metadata.setAuthor("Gap Author");- metadata.setSubject("Subject X");- metadata.setKeywords("alpha,beta");- metadata.setCreator("Creator App");- metadata.setProducer("Producer Lib");- metadata.setCreationDate("2020-06-15T12:00:00Z");-- PdfJsonPage page = new PdfJsonPage();- page.setPageNumber(1);- page.setWidth(300f);- page.setHeight(300f);-- PdfJsonDocument doc = new PdfJsonDocument();- doc.setMetadata(metadata);- doc.setPages(List.of(page));-- try (PDDocument loaded = Loader.loadPDF(runJsonToPdf(doc))) {- PDDocumentInformation info = loaded.getDocumentInformation();- assertEquals("Gap Test Title", info.getTitle());- assertEquals("Gap Author", info.getAuthor());- assertEquals("Subject X", info.getSubject());- assertEquals("alpha,beta", info.getKeywords());- assertEquals("Creator App", info.getCreator());- assertEquals("Producer Lib", info.getProducer());- assertNotNull(info.getCreationDate(), "creation date should be applied");- }- }-- @Test- @DisplayName("invalid creation date string is ignored without failing the conversion")- void invalidCreationDateIgnored() throws IOException {- stubFallbackFont();- PdfJsonMetadata metadata = new PdfJsonMetadata();- metadata.setTitle("Has bad date");- metadata.setCreationDate("not-a-real-instant");-- PdfJsonPage page = new PdfJsonPage();- page.setPageNumber(1);- page.setWidth(300f);- page.setHeight(300f);-- PdfJsonDocument doc = new PdfJsonDocument();- doc.setMetadata(metadata);- doc.setPages(List.of(page));-- try (PDDocument loaded = Loader.loadPDF(runJsonToPdf(doc))) {- assertEquals("Has bad date", loaded.getDocumentInformation().getTitle());- }- }-- @Test- @DisplayName("base64 XMP packet is restored onto the document catalog")- void xmpMetadataApplied() throws IOException {- stubFallbackFont();- String xmpXml =- "<?xpacket begin=\"\"?><x:xmpmeta xmlns:x=\"adobe:ns:meta/\"></x:xmpmeta>";- String base64 =- Base64.getEncoder().encodeToString(xmpXml.getBytes(StandardCharsets.UTF_8));-- PdfJsonPage page = new PdfJsonPage();- page.setPageNumber(1);- page.setWidth(300f);- page.setHeight(300f);-- PdfJsonDocument doc = new PdfJsonDocument();- doc.setXmpMetadata(base64);- doc.setPages(List.of(page));-- try (PDDocument loaded = Loader.loadPDF(runJsonToPdf(doc))) {- assertNotNull(- loaded.getDocumentCatalog().getMetadata(),- "XMP metadata stream should be present on the catalog");- }- }-- @Test- @DisplayName("null fonts list is initialised instead of causing an NPE")- void nullFontsListHandled() throws IOException {- stubFallbackFont();- PdfJsonPage page = new PdfJsonPage();- page.setPageNumber(1);- page.setWidth(300f);- page.setHeight(300f);-- PdfJsonDocument doc = new PdfJsonDocument();- doc.setFonts(null);- doc.setPages(List.of(page));-- byte[] pdfBytes = runJsonToPdf(doc);- assertTrue(pdfBytes.length > 0);- // buildFontMap mutates the (now non-null) list by appending the fallback model.- assertNotNull(doc.getFonts());- assertTrue(- doc.getFonts().stream()- .anyMatch(- f ->- PdfJsonFallbackFontService.FALLBACK_FONT_ID.equals(- f.getId())));- }- }-- // ------------------------------------------------------------------- // convertJsonToPdf(MultipartFile, OutputStream)- // -------------------------------------------------------------------- @Nested- @DisplayName("convertJsonToPdf(file)")- class JsonToPdfFile {-- @Test- @DisplayName("null file throws IllegalArgumentException")- void nullFileThrows() {- ByteArrayOutputStream out = new ByteArrayOutputStream();- assertThrows(- IllegalArgumentException.class,- () -> service.convertJsonToPdf((MockMultipartFile) null, out));- }-- @Test- @DisplayName("valid JSON payload is deserialized and rebuilt into a PDF")- void validJsonProducesPdf() throws IOException {- stubFallbackFont();- PdfJsonPage page = new PdfJsonPage();- page.setPageNumber(1);- page.setWidth(321f);- page.setHeight(123f);- PdfJsonDocument doc = new PdfJsonDocument();- doc.setPages(List.of(page));-- byte[] json = objectMapper.writeValueAsBytes(doc);- MockMultipartFile file =- new MockMultipartFile("fileInput", "doc.json", "application/json", json);-- ByteArrayOutputStream out = new ByteArrayOutputStream();- service.convertJsonToPdf(file, out);-- try (PDDocument loaded = Loader.loadPDF(out.toByteArray())) {- assertEquals(1, loaded.getNumberOfPages());- assertEquals(321f, loaded.getPage(0).getMediaBox().getWidth(), 0.01f);- }- }- }-- // ------------------------------------------------------------------- // convertPdfToJson family- // -------------------------------------------------------------------- @Nested- @DisplayName("convertPdfToJson")- class PdfToJson {-- @Test- @DisplayName("null file throws IllegalArgumentException")- void nullFileThrows() {- ByteArrayOutputStream out = new ByteArrayOutputStream();- assertThrows(IllegalArgumentException.class, () -> service.convertPdfToJson(null, out));- }-- @Test- @DisplayName("blank single-page PDF yields JSON with one page and matching dimensions")- void blankSinglePage() throws IOException {- try (PDDocument pdf = singlePagePdf(250f, 350f)) {- when(pdfDocumentFactory.load(any(Path.class), eq(true))).thenReturn(pdf);-- ByteArrayOutputStream out = new ByteArrayOutputStream();- service.convertPdfToJson(pdfMultipart(), out);-- PdfJsonDocument result =- objectMapper.readValue(out.toByteArray(), PdfJsonDocument.class);- assertEquals(1, result.getPages().size());- PdfJsonPage page = result.getPages().get(0);- assertEquals(1, page.getPageNumber());- assertEquals(250f, page.getWidth(), 0.01f);- assertEquals(350f, page.getHeight(), 0.01f);- assertNotNull(result.getMetadata());- assertEquals(1, result.getMetadata().getNumberOfPages());- }- }-- @Test- @DisplayName("multi-page PDF preserves per-page dimensions in the JSON model")- void multiPageDimensions() throws IOException {- try (PDDocument pdf =- newPdf(new float[][] {{200f, 300f}, {612f, 792f}}, new int[] {0, 90})) {- when(pdfDocumentFactory.load(any(Path.class), eq(true))).thenReturn(pdf);-- ByteArrayOutputStream out = new ByteArrayOutputStream();- service.convertPdfToJson(pdfMultipart(), out);-- PdfJsonDocument result =- objectMapper.readValue(out.toByteArray(), PdfJsonDocument.class);- assertEquals(2, result.getPages().size());- assertEquals(200f, result.getPages().get(0).getWidth(), 0.01f);- assertEquals(792f, result.getPages().get(1).getHeight(), 0.01f);- assertEquals(90, result.getPages().get(1).getRotation());- }- }-- @Test- @DisplayName("source document metadata is extracted into the JSON metadata block")- void extractsSourceMetadata() throws IOException {- try (PDDocument pdf = singlePagePdf(300f, 300f)) {- PDDocumentInformation info = pdf.getDocumentInformation();- info.setTitle("Original Title");- info.setAuthor("Original Author");- when(pdfDocumentFactory.load(any(Path.class), eq(true))).thenReturn(pdf);-- ByteArrayOutputStream out = new ByteArrayOutputStream();- service.convertPdfToJson(pdfMultipart(), out);-- PdfJsonDocument result =- objectMapper.readValue(out.toByteArray(), PdfJsonDocument.class);- assertEquals("Original Title", result.getMetadata().getTitle());- assertEquals("Original Author", result.getMetadata().getAuthor());- }- }-- @Test- @DisplayName("lightweight overload still produces a parseable JSON document")- void lightweightOverload() throws IOException {- try (PDDocument pdf = singlePagePdf(300f, 300f)) {- when(pdfDocumentFactory.load(any(Path.class), eq(true))).thenReturn(pdf);-- ByteArrayOutputStream out = new ByteArrayOutputStream();- service.convertPdfToJson(pdfMultipart(), true, out);-- PdfJsonDocument result =- objectMapper.readValue(out.toByteArray(), PdfJsonDocument.class);- assertEquals(1, result.getPages().size());- }- }-- @Test- @DisplayName("progress callback receives a terminal complete event")- void progressCallbackInvoked() throws IOException {- try (PDDocument pdf = singlePagePdf(300f, 300f)) {- when(pdfDocumentFactory.load(any(Path.class), eq(true))).thenReturn(pdf);-- AtomicBoolean sawComplete = new AtomicBoolean(false);- AtomicBoolean sawAny = new AtomicBoolean(false);-- ByteArrayOutputStream out = new ByteArrayOutputStream();- service.convertPdfToJson(- pdfMultipart(),- progress -> {- sawAny.set(true);- if (progress.getPercent() == 100 || progress.isComplete()) {- sawComplete.set(true);- }- },- out);-- assertTrue(sawAny.get(), "expected at least one progress event");- assertTrue(sawComplete.get(), "expected a terminal 100%/complete progress event");- }- }-- @Test- @DisplayName("convertPdfToJsonDocument returns an in-memory model")- void convertPdfToJsonDocumentReturnsModel() throws IOException {- try (PDDocument pdf = singlePagePdf(400f, 500f)) {- when(pdfDocumentFactory.load(any(Path.class), eq(true))).thenReturn(pdf);-- PdfJsonDocument result = service.convertPdfToJsonDocument(pdfMultipart());-- assertNotNull(result);- assertEquals(1, result.getPages().size());- assertEquals(400f, result.getPages().get(0).getWidth(), 0.01f);- }- }- }-- // ------------------------------------------------------------------- // Cache-backed public API error branches (no PDF load required)- // -------------------------------------------------------------------- @Nested- @DisplayName("cache-backed API")- class CacheApi {-- @Test- @DisplayName("extractSinglePage with unknown jobId throws CacheUnavailableException")- void extractSinglePageUnknownJob() {- ByteArrayOutputStream out = new ByteArrayOutputStream();- assertThrows(- CacheUnavailableException.class,- () -> service.extractSinglePage("missing-job", 1, out));- }-- @Test- @DisplayName("extractPageFonts with unknown jobId throws CacheUnavailableException")- void extractPageFontsUnknownJob() {- ByteArrayOutputStream out = new ByteArrayOutputStream();- assertThrows(- CacheUnavailableException.class,- () -> service.extractPageFonts("missing-job", 1, out));- }-- @Test- @DisplayName("exportUpdatedPages requires a non-null jobId")- void exportUpdatedPagesNullJob() {- ByteArrayOutputStream out = new ByteArrayOutputStream();- assertThrows(- IllegalArgumentException.class,- () -> service.exportUpdatedPages(null, new PdfJsonDocument(), out));- }-- @Test- @DisplayName("exportUpdatedPages rejects a blank jobId")- void exportUpdatedPagesBlankJob() {- ByteArrayOutputStream out = new ByteArrayOutputStream();- assertThrows(- IllegalArgumentException.class,- () -> service.exportUpdatedPages(" ", new PdfJsonDocument(), out));- }-- @Test- @DisplayName("exportUpdatedPages with unknown jobId throws CacheUnavailableException")- void exportUpdatedPagesUnknownJob() {- ByteArrayOutputStream out = new ByteArrayOutputStream();- assertThrows(- CacheUnavailableException.class,- () -> service.exportUpdatedPages("missing-job", new PdfJsonDocument(), out));- }-- @Test- @DisplayName("extractDocumentMetadata with null file throws IllegalArgumentException")- void extractDocumentMetadataNullFile() {- ByteArrayOutputStream out = new ByteArrayOutputStream();- assertThrows(- IllegalArgumentException.class,- () -> service.extractDocumentMetadata(null, "job", out));- }-- @Test- @DisplayName("clearCachedDocument on an unknown jobId is a no-op")- void clearCachedDocumentUnknownJob() {- assertDoesNotThrow(() -> service.clearCachedDocument("missing-job"));- }- }-}diff --git a/app/core/src/test/java/stirling/software/SPDF/service/PdfJsonConversionServiceMore2Test.java b/app/core/src/test/java/stirling/software/SPDF/service/PdfJsonConversionServiceMore2Test.javadeleted file mode 100644index 22ade756a8..0000000000--- a/app/core/src/test/java/stirling/software/SPDF/service/PdfJsonConversionServiceMore2Test.java+++ /dev/null@@ -1,900 +0,0 @@-package stirling.software.SPDF.service;--import static org.assertj.core.api.Assertions.assertThat;-import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;-import static org.junit.jupiter.api.Assertions.assertEquals;-import static org.junit.jupiter.api.Assertions.assertNotNull;-import static org.junit.jupiter.api.Assertions.assertThrows;-import static org.mockito.ArgumentMatchers.any;-import static org.mockito.ArgumentMatchers.anyInt;-import static org.mockito.ArgumentMatchers.anyString;-import static org.mockito.ArgumentMatchers.eq;-import static org.mockito.Mockito.when;--import java.awt.Color;-import java.awt.image.BufferedImage;-import java.io.ByteArrayOutputStream;-import java.io.File;-import java.io.IOException;-import java.nio.file.Files;-import java.nio.file.Path;-import java.util.ArrayList;-import java.util.Base64;-import java.util.List;--import javax.imageio.ImageIO;--import org.apache.pdfbox.Loader;-import org.apache.pdfbox.pdmodel.PDDocument;-import org.apache.pdfbox.pdmodel.PDPage;-import org.apache.pdfbox.pdmodel.PDPageContentStream;-import org.apache.pdfbox.pdmodel.common.PDRectangle;-import org.apache.pdfbox.pdmodel.font.PDFont;-import org.apache.pdfbox.pdmodel.font.PDType1Font;-import org.apache.pdfbox.pdmodel.font.Standard14Fonts;-import org.apache.pdfbox.pdmodel.graphics.image.JPEGFactory;-import org.apache.pdfbox.pdmodel.graphics.image.LosslessFactory;-import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;-import org.apache.pdfbox.pdmodel.interactive.action.PDActionGoTo;-import org.apache.pdfbox.pdmodel.interactive.action.PDActionURI;-import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationLink;-import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationWidget;-import org.apache.pdfbox.pdmodel.interactive.documentnavigation.destination.PDPageFitDestination;-import org.junit.jupiter.api.AfterEach;-import org.junit.jupiter.api.BeforeEach;-import org.junit.jupiter.api.DisplayName;-import org.junit.jupiter.api.Nested;-import org.junit.jupiter.api.Test;-import org.junit.jupiter.api.extension.ExtendWith;-import org.mockito.Mock;-import org.mockito.junit.jupiter.MockitoExtension;-import org.mockito.quality.Strictness;-import org.springframework.mock.web.MockMultipartFile;--import stirling.software.SPDF.config.EndpointConfiguration;-import stirling.software.SPDF.exception.CacheUnavailableException;-import stirling.software.SPDF.model.json.PdfJsonAnnotation;-import stirling.software.SPDF.model.json.PdfJsonDocument;-import stirling.software.SPDF.model.json.PdfJsonDocumentMetadata;-import stirling.software.SPDF.model.json.PdfJsonFont;-import stirling.software.SPDF.model.json.PdfJsonImageElement;-import stirling.software.SPDF.model.json.PdfJsonMetadata;-import stirling.software.SPDF.model.json.PdfJsonPage;-import stirling.software.SPDF.model.json.PdfJsonTextColor;-import stirling.software.SPDF.model.json.PdfJsonTextElement;-import stirling.software.SPDF.service.pdfjson.PdfJsonFontService;-import stirling.software.SPDF.service.pdfjson.type3.Type3FontConversionService;-import stirling.software.SPDF.service.pdfjson.type3.Type3GlyphExtractor;-import stirling.software.common.model.ApplicationProperties;-import stirling.software.common.service.CustomPDFDocumentFactory;-import stirling.software.common.service.TaskManager;-import stirling.software.common.util.JobContext;-import stirling.software.common.util.TempFileManager;--import tools.jackson.databind.DeserializationFeature;-import tools.jackson.databind.ObjectMapper;-import tools.jackson.databind.json.JsonMapper;--/**- * Additional coverage tests for {@link PdfJsonConversionService} targeting reachable branches the- * other suites leave cold: link annotations carrying URI / GoTo actions plus widget annotations,- * the {@code restoreAnnotations} structured-fallback path when no rawData is present, page rotation- * (90/180/270) combined with a CropBox that differs from the MediaBox, document- and page-level- * metadata edge cases (all-null fields, empty strings, keyword/creator/producer round trips), the- * XMP packet extract-then-apply round trip, multi-image pages mixing JPEG (DCTDecode) and lossless- * PNG with explicit-transform versus default placement, and the cache/editor API around export- * edits and clear-then-miss.- *- * <p>Construction mirrors {@code PdfJsonConversionServiceDeepTest} and {@code- * PdfJsonConversionServiceExtraTest} so the same real in-memory PDF load path runs without- * repeating their assertions.- */-@ExtendWith(MockitoExtension.class)[email protected](strictness = Strictness.LENIENT)-class PdfJsonConversionServiceMore2Test {-- @Mock private CustomPDFDocumentFactory pdfDocumentFactory;- @Mock private EndpointConfiguration endpointConfiguration;- @Mock private TempFileManager tempFileManager;- @Mock private TaskManager taskManager;- @Mock private PdfJsonFallbackFontService fallbackFontService;- @Mock private PdfJsonFontService fontService;- @Mock private Type3FontConversionService type3FontConversionService;- @Mock private Type3GlyphExtractor type3GlyphExtractor;- @Mock private ApplicationProperties applicationProperties;-- // Real COS mapper so the serialize/deserialize machinery runs for real.- private final PdfJsonCosMapper cosMapper = new PdfJsonCosMapper();-- private final ObjectMapper objectMapper =- JsonMapper.builder()- .disable(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES)- .build();-- private PdfJsonConversionService service;-- private final List<Path> createdTempFiles = new ArrayList<>();-- @BeforeEach- void setUp() throws IOException {- service =- new PdfJsonConversionService(- pdfDocumentFactory,- objectMapper,- endpointConfiguration,- tempFileManager,- taskManager,- cosMapper,- fallbackFontService,- fontService,- type3FontConversionService,- type3GlyphExtractor,- applicationProperties);-- when(tempFileManager.createTempFile(anyString()))- .thenAnswer(- invocation -> {- String suffix = invocation.getArgument(0);- Path path = Files.createTempFile("pdfjson-more2-test", suffix);- createdTempFiles.add(path);- return path.toFile();- });- when(tempFileManager.deleteTempFile(any(File.class)))- .thenAnswer(- invocation -> {- File file = invocation.getArgument(0);- return file != null && file.delete();- });- when(taskManager.addNote(anyString(), anyString())).thenReturn(true);- }-- @AfterEach- void tearDown() throws IOException {- JobContext.clear();- for (Path path : createdTempFiles) {- Files.deleteIfExists(path);- }- createdTempFiles.clear();- }-- // ------------------------------------------------------------------- // Helpers- // -------------------------------------------------------------------- private void stubFallbackFont() throws IOException {- when(fallbackFontService.buildFallbackFontModel())- .thenAnswer(- invocation ->- PdfJsonFont.builder()- .id(PdfJsonFallbackFontService.FALLBACK_FONT_ID)- .uid(PdfJsonFallbackFontService.FALLBACK_FONT_ID)- .baseName("Fallback")- .subtype("TrueType")- .build());- when(fallbackFontService.loadFallbackPdfFont(any(PDDocument.class)))- .thenAnswer(invocation -> new PDType1Font(Standard14Fonts.FontName.HELVETICA));- }-- private void stubCanEncode() {- when(fallbackFontService.canEncode(any(PDFont.class), anyString())).thenReturn(true);- when(fallbackFontService.canEncode(any(PDFont.class), anyInt())).thenReturn(true);- }-- private MockMultipartFile pdfMultipart(byte[] bytes) {- return new MockMultipartFile("fileInput", "input.pdf", "application/pdf", bytes);- }-- private byte[] toBytes(PDDocument document) throws IOException {- try (document) {- ByteArrayOutputStream out = new ByteArrayOutputStream();- document.save(out);- return out.toByteArray();- }- }-- private PdfJsonDocument toJsonDocument(byte[] pdfBytes) throws IOException {- when(pdfDocumentFactory.load(any(Path.class), eq(true)))- .thenAnswer(inv -> Loader.loadPDF(inv.getArgument(0, Path.class).toFile()));- ByteArrayOutputStream out = new ByteArrayOutputStream();- service.convertPdfToJson(pdfMultipart(pdfBytes), out);- return objectMapper.readValue(out.toByteArray(), PdfJsonDocument.class);- }-- private byte[] runJsonToPdf(PdfJsonDocument doc) throws IOException {- ByteArrayOutputStream out = new ByteArrayOutputStream();- service.convertJsonToPdf(doc, out);- return out.toByteArray();- }-- private PdfJsonDocument cacheLazyDocument(String jobId, byte[] pdfBytes) throws IOException {- when(pdfDocumentFactory.load(any(Path.class), eq(true)))- .thenAnswer(inv -> Loader.loadPDF(inv.getArgument(0, Path.class).toFile()));- when(pdfDocumentFactory.load(any(byte[].class), eq(true)))- .thenAnswer(inv -> Loader.loadPDF(inv.getArgument(0, byte[].class)));- JobContext.setJobId(jobId);- ByteArrayOutputStream out = new ByteArrayOutputStream();- service.convertPdfToJson(pdfMultipart(pdfBytes), true, out);- return objectMapper.readValue(out.toByteArray(), PdfJsonDocument.class);- }-- private BufferedImage solidImage(int w, int h, Color color, int type) {- BufferedImage image = new BufferedImage(w, h, type);- for (int x = 0; x < w; x++) {- for (int y = 0; y < h; y++) {- image.setRGB(x, y, color.getRGB());- }- }- return image;- }-- private String pngBase64(BufferedImage image) throws IOException {- ByteArrayOutputStream out = new ByteArrayOutputStream();- ImageIO.write(image, "png", out);- return Base64.getEncoder().encodeToString(out.toByteArray());- }-- private String jpgBase64(BufferedImage image) throws IOException {- ByteArrayOutputStream out = new ByteArrayOutputStream();- ImageIO.write(image, "jpg", out);- return Base64.getEncoder().encodeToString(out.toByteArray());- }-- private PdfJsonDocument docWith(PdfJsonPage page) {- PdfJsonDocument doc = new PdfJsonDocument();- doc.setPages(new ArrayList<>(List.of(page)));- return doc;- }-- private PdfJsonFont std14Font(String id, String standard14Name) {- return PdfJsonFont.builder()- .id(id)- .uid(id)- .baseName(standard14Name)- .subtype("Type1")- .standard14Name(standard14Name)- .build();- }-- private byte[] simpleTextPdf(String text) throws IOException {- PDDocument document = new PDDocument();- PDPage page = new PDPage(PDRectangle.LETTER);- document.addPage(page);- try (PDPageContentStream cs = new PDPageContentStream(document, page)) {- cs.beginText();- cs.setFont(new PDType1Font(Standard14Fonts.FontName.HELVETICA), 12f);- cs.newLineAtOffset(72, 700);- cs.showText(text);- cs.endText();- }- return toBytes(document);- }-- // ==================================================================- // Link / action / widget annotations- // ==================================================================-- @Nested- @DisplayName("link, action and widget annotation handling")- class ActionAnnotations {-- /** A page carrying a URI-action link, a GoTo-action link and a widget annotation. */- private byte[] actionAnnotationPdf() throws IOException {- PDDocument document = new PDDocument();- PDPage page = new PDPage(PDRectangle.LETTER);- document.addPage(page);-- PDAnnotationLink uriLink = new PDAnnotationLink();- uriLink.setRectangle(new PDRectangle(40, 720, 200, 18));- PDActionURI uriAction = new PDActionURI();- uriAction.setURI("https://example.com/landing");- uriLink.setAction(uriAction);-- PDAnnotationLink gotoLink = new PDAnnotationLink();- gotoLink.setRectangle(new PDRectangle(40, 690, 200, 18));- PDActionGoTo gotoAction = new PDActionGoTo();- PDPageFitDestination dest = new PDPageFitDestination();- dest.setPage(page);- gotoAction.setDestination(dest);- gotoLink.setAction(gotoAction);-- PDAnnotationWidget widget = new PDAnnotationWidget();- widget.setRectangle(new PDRectangle(40, 650, 120, 24));-- page.getAnnotations().add(uriLink);- page.getAnnotations().add(gotoLink);- page.getAnnotations().add(widget);-- try (PDPageContentStream cs = new PDPageContentStream(document, page)) {- cs.beginText();- cs.setFont(new PDType1Font(Standard14Fonts.FontName.HELVETICA), 12f);- cs.newLineAtOffset(72, 600);- cs.showText("Body with action links");- cs.endText();- }- return toBytes(document);- }-- @Test- @DisplayName("URI, GoTo and widget annotations are collected with their subtypes")- void collectsActionSubtypes() throws IOException {- PdfJsonDocument doc = toJsonDocument(actionAnnotationPdf());- List<PdfJsonAnnotation> annotations = doc.getPages().get(0).getAnnotations();- assertThat(annotations).hasSizeGreaterThanOrEqualTo(3);- List<String> subtypes =- annotations.stream().map(PdfJsonAnnotation::getSubtype).toList();- assertThat(subtypes).contains("Link", "Widget");- }-- @Test- @DisplayName("URI and GoTo action links round trip back onto the rebuilt page")- void actionLinksRoundTrip() throws IOException {- stubFallbackFont();- PdfJsonDocument doc = toJsonDocument(actionAnnotationPdf());- byte[] rebuilt = runJsonToPdf(doc);- try (PDDocument loaded = Loader.loadPDF(rebuilt)) {- assertThat(loaded.getPage(0).getAnnotations()).hasSizeGreaterThanOrEqualTo(3);- boolean hasUri =- loaded.getPage(0).getAnnotations().stream()- .anyMatch(- a ->- a instanceof PDAnnotationLink- && ((PDAnnotationLink) a).getAction()- instanceof PDActionURI);- assertThat(hasUri).isTrue();- }- }-- @Test- @DisplayName("structured annotation without rawData hits the fallback restore branch")- void structuredAnnotationFallbackRestore() throws IOException {- stubFallbackFont();- // No rawData supplied so restoreAnnotations takes the basic-reconstruction warning- // path.- PdfJsonAnnotation noRaw =- PdfJsonAnnotation.builder()- .subtype("Text")- .contents("structured only")- .rect(new float[] {40f, 700f, 60f, 720f})- .color(new float[] {1f, 0f, 0f})- .author("Author X")- .subject("Subject Y")- .destination("page-1")- .iconName("Comment")- .build();- PdfJsonFont font = std14Font("F1", "Helvetica");- PdfJsonTextElement element =- PdfJsonTextElement.builder()- .text("Body line")- .fontId("F1")- .fontSize(12f)- .x(72f)- .y(640f)- .build();- PdfJsonPage page =- PdfJsonPage.builder()- .pageNumber(1)- .width(612f)- .height(792f)- .textElements(new ArrayList<>(List.of(element)))- .annotations(new ArrayList<>(List.of(noRaw)))- .build();- PdfJsonDocument doc = docWith(page);- doc.setFonts(new ArrayList<>(List.of(font)));- // The annotation has no rawData; rebuild must not abort and the body still renders.- byte[] rebuilt = runJsonToPdf(doc);- try (PDDocument loaded = Loader.loadPDF(rebuilt)) {- assertEquals(1, loaded.getNumberOfPages());- }- }-- @Test- @DisplayName("lazy extraction surfaces action-link annotations for a cached page")- void lazyActionAnnotations() throws IOException {- cacheLazyDocument("job-action-anns", actionAnnotationPdf());- ByteArrayOutputStream out = new ByteArrayOutputStream();- service.extractSinglePage("job-action-anns", 1, out);- PdfJsonPage page = objectMapper.readValue(out.toByteArray(), PdfJsonPage.class);- assertThat(page.getAnnotations()).hasSizeGreaterThanOrEqualTo(3);- }- }-- // ==================================================================- // Rotation + CropBox geometry- // ==================================================================-- @Nested- @DisplayName("rotation combined with a non-default CropBox")- class RotationCropBox {-- /** Letter MediaBox with a smaller inset CropBox and the supplied rotation. */- private byte[] rotatedCroppedPdf(int rotation) throws IOException {- PDDocument document = new PDDocument();- PDPage page = new PDPage(PDRectangle.LETTER);- page.setRotation(rotation);- page.setCropBox(new PDRectangle(36f, 48f, 480f, 600f));- document.addPage(page);- try (PDPageContentStream cs = new PDPageContentStream(document, page)) {- cs.beginText();- cs.setFont(new PDType1Font(Standard14Fonts.FontName.HELVETICA), 12f);- cs.newLineAtOffset(100, 300);- cs.showText("Rotated and cropped " + rotation);- cs.endText();- }- return toBytes(document);- }-- @Test- @DisplayName("rotation 90 reports the CropBox dimensions and survives rebuild")- void rotation90() throws IOException {- stubFallbackFont();- PdfJsonDocument doc = toJsonDocument(rotatedCroppedPdf(90));- PdfJsonPage page = doc.getPages().get(0);- assertEquals(90, page.getRotation());- // Extraction reports CropBox geometry, not the larger MediaBox.- assertEquals(480f, page.getWidth(), 0.5f);- assertEquals(600f, page.getHeight(), 0.5f);- byte[] rebuilt = runJsonToPdf(doc);- try (PDDocument loaded = Loader.loadPDF(rebuilt)) {- assertEquals(90, loaded.getPage(0).getRotation());- }- }-- @Test- @DisplayName("rotation 180 keeps both rotation and crop geometry through a round trip")- void rotation180() throws IOException {- stubFallbackFont();- PdfJsonDocument doc = toJsonDocument(rotatedCroppedPdf(180));- assertEquals(180, doc.getPages().get(0).getRotation());- byte[] rebuilt = runJsonToPdf(doc);- try (PDDocument loaded = Loader.loadPDF(rebuilt)) {- assertEquals(180, loaded.getPage(0).getRotation());- PDRectangle box = loaded.getPage(0).getMediaBox();- assertEquals(480f, box.getWidth(), 0.5f);- assertEquals(600f, box.getHeight(), 0.5f);- }- }-- @Test- @DisplayName("rotation 270 round trips and reports crop geometry on extraction")- void rotation270() throws IOException {- stubFallbackFont();- PdfJsonDocument doc = toJsonDocument(rotatedCroppedPdf(270));- assertEquals(270, doc.getPages().get(0).getRotation());- byte[] rebuilt = runJsonToPdf(doc);- try (PDDocument loaded = Loader.loadPDF(rebuilt)) {- assertEquals(270, loaded.getPage(0).getRotation());- }- }-- @Test- @DisplayName("metadata extraction reports rotation per page from the MediaBox path")- void metadataReportsRotation() throws IOException {- when(pdfDocumentFactory.load(any(byte[].class), eq(true)))- .thenAnswer(inv -> Loader.loadPDF(inv.getArgument(0, byte[].class)));- ByteArrayOutputStream out = new ByteArrayOutputStream();- service.extractDocumentMetadata(pdfMultipart(rotatedCroppedPdf(90)), "job-rot", out);- PdfJsonDocumentMetadata md =- objectMapper.readValue(out.toByteArray(), PdfJsonDocumentMetadata.class);- assertThat(md.getPageDimensions()).hasSize(1);- assertEquals(90, md.getPageDimensions().get(0).getRotation());- }- }-- // ==================================================================- // Metadata edge cases (document and synthesized)- // ==================================================================-- @Nested- @DisplayName("metadata edge cases")- class MetadataEdgeCases {-- @Test- @DisplayName("a document with no information dictionary fields extracts blank metadata")- void emptyDocumentInfoExtractsBlanks() throws IOException {- PDDocument document = new PDDocument();- document.addPage(new PDPage(PDRectangle.LETTER));- PdfJsonDocument doc = toJsonDocument(toBytes(document));- PdfJsonMetadata md = doc.getMetadata();- assertNotNull(md);- assertThat(md.getTitle()).isNull();- assertThat(md.getAuthor()).isNull();- assertEquals(1, md.getNumberOfPages());- }-- @Test- @DisplayName("all-null synthesized metadata applies cleanly without dates")- void allNullMetadataApplies() throws IOException {- stubFallbackFont();- PdfJsonMetadata md = PdfJsonMetadata.builder().build();- PdfJsonDocument doc = new PdfJsonDocument();- doc.setMetadata(md);- doc.setPages(new ArrayList<>());- assertDoesNotThrow(() -> runJsonToPdf(doc));- }-- @Test- @DisplayName("keywords, creator and producer survive a metadata round trip")- void keywordsCreatorProducerRoundTrip() throws IOException {- stubFallbackFont();- PDDocument document = new PDDocument();- document.addPage(new PDPage(PDRectangle.LETTER));- document.getDocumentInformation().setKeywords("alpha, beta, gamma");- document.getDocumentInformation().setCreator("Creator Tool");- document.getDocumentInformation().setProducer("Producer Lib");- document.getDocumentInformation().setSubject("Round trip subject");- byte[] bytes = toBytes(document);-- PdfJsonDocument doc = toJsonDocument(bytes);- assertThat(doc.getMetadata().getKeywords()).isEqualTo("alpha, beta, gamma");-- byte[] rebuilt = runJsonToPdf(doc);- try (PDDocument loaded = Loader.loadPDF(rebuilt)) {- assertEquals("alpha, beta, gamma", loaded.getDocumentInformation().getKeywords());- assertEquals("Creator Tool", loaded.getDocumentInformation().getCreator());- assertEquals("Producer Lib", loaded.getDocumentInformation().getProducer());- assertEquals("Round trip subject", loaded.getDocumentInformation().getSubject());- }- }-- @Test- @DisplayName("empty-string metadata fields round trip without becoming null")- void emptyStringMetadataFields() throws IOException {- stubFallbackFont();- PdfJsonMetadata md =- PdfJsonMetadata.builder().title("").author("").keywords("").build();- PdfJsonDocument doc = new PdfJsonDocument();- doc.setMetadata(md);- doc.setPages(new ArrayList<>());- byte[] rebuilt = runJsonToPdf(doc);- try (PDDocument loaded = Loader.loadPDF(rebuilt)) {- assertEquals("", loaded.getDocumentInformation().getTitle());- }- }- }-- // ==================================================================- // XMP metadata extract-then-apply round trip- // ==================================================================-- @Nested- @DisplayName("XMP metadata round trip")- class XmpRoundTrip {-- private byte[] xmpPacket(String title) {- return ("<?xpacket begin=\"\uFEFF\" id=\"W5M0MpCehiHzreSzNTczkc9d\"?>"- + "<x:xmpmeta xmlns:x=\"adobe:ns:meta/\">"- + "<rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">"- + "<rdf:Description xmlns:dc=\"http://purl.org/dc/elements/1.1/\">"- + "<dc:title>"- + title- + "</dc:title>"- + "</rdf:Description></rdf:RDF></x:xmpmeta><?xpacket end=\"w\"?>")- .getBytes(java.nio.charset.StandardCharsets.UTF_8);- }-- private byte[] pdfWithXmp(String title) throws IOException {- PDDocument document = new PDDocument();- document.addPage(new PDPage(PDRectangle.LETTER));- org.apache.pdfbox.pdmodel.common.PDMetadata metadata =- new org.apache.pdfbox.pdmodel.common.PDMetadata(- document, new java.io.ByteArrayInputStream(xmpPacket(title)));- document.getDocumentCatalog().setMetadata(metadata);- return toBytes(document);- }-- @Test- @DisplayName("an XMP packet is extracted as base64 into the document model")- void xmpExtractedAsBase64() throws IOException {- PdfJsonDocument doc = toJsonDocument(pdfWithXmp("XMP Title One"));- assertThat(doc.getXmpMetadata()).isNotBlank();- byte[] decoded = Base64.getDecoder().decode(doc.getXmpMetadata());- String xml = new String(decoded, java.nio.charset.StandardCharsets.UTF_8);- assertThat(xml).contains("XMP Title One");- }-- @Test- @DisplayName("an extracted XMP packet is restored onto the rebuilt document catalog")- void xmpRestoredOnRebuild() throws IOException {- stubFallbackFont();- PdfJsonDocument doc = toJsonDocument(pdfWithXmp("XMP Title Two"));- byte[] rebuilt = runJsonToPdf(doc);- try (PDDocument loaded = Loader.loadPDF(rebuilt)) {- org.apache.pdfbox.pdmodel.common.PDMetadata restored =- loaded.getDocumentCatalog().getMetadata();- assertNotNull(restored);- try (java.io.InputStream in = restored.createInputStream()) {- String xml =- new String(in.readAllBytes(), java.nio.charset.StandardCharsets.UTF_8);- assertThat(xml).contains("XMP Title Two");- }- }- }-- @Test- @DisplayName("metadata extraction surfaces the XMP packet alongside info metadata")- void metadataExtractionIncludesXmp() throws IOException {- when(pdfDocumentFactory.load(any(byte[].class), eq(true)))- .thenAnswer(inv -> Loader.loadPDF(inv.getArgument(0, byte[].class)));- ByteArrayOutputStream out = new ByteArrayOutputStream();- service.extractDocumentMetadata(pdfMultipart(pdfWithXmp("XMP Meta")), null, out);- PdfJsonDocumentMetadata md =- objectMapper.readValue(out.toByteArray(), PdfJsonDocumentMetadata.class);- assertThat(md.getXmpMetadata()).isNotBlank();- }- }-- // ==================================================================- // Mixed JPEG + lossless images with transform variety- // ==================================================================-- @Nested- @DisplayName("mixed JPEG and lossless image placement")- class MixedImagePlacement {-- @Test- @DisplayName("an extracted JPEG and PNG pair both carry format and data")- void extractedJpegAndPng() throws IOException {- PDDocument document = new PDDocument();- PDPage page = new PDPage(PDRectangle.LETTER);- document.addPage(page);- PDImageXObject jpeg =- JPEGFactory.createFromImage(- document, solidImage(40, 30, Color.RED, BufferedImage.TYPE_INT_RGB));- PDImageXObject png =- LosslessFactory.createFromImage(- document, solidImage(30, 30, Color.BLUE, BufferedImage.TYPE_INT_RGB));- try (PDPageContentStream cs = new PDPageContentStream(document, page)) {- cs.drawImage(jpeg, 60, 600, 100, 75);- cs.drawImage(png, 220, 600, 75, 75);- }- PdfJsonDocument doc = toJsonDocument(toBytes(document));- List<PdfJsonImageElement> images = doc.getPages().get(0).getImageElements();- assertThat(images).hasSizeGreaterThanOrEqualTo(2);- assertThat(images)- .anySatisfy(- img ->- assertThat(img.getImageFormat().toLowerCase())- .containsAnyOf("jpg", "jpeg"));- assertThat(images).allSatisfy(img -> assertThat(img.getImageData()).isNotBlank());- }-- @Test- @DisplayName("explicit-transform JPEG and default-placement PNG render on one page")- void transformVsDefaultPlacement() throws IOException {- stubFallbackFont();- PdfJsonImageElement transformed =- PdfJsonImageElement.builder()- .id("JpgT")- .imageData(- jpgBase64(- solidImage(- 16, 16, Color.RED, BufferedImage.TYPE_INT_RGB)))- .imageFormat("jpg")- .transform(new float[] {72f, 0f, 0f, 54f, 90f, 560f})- .build();- PdfJsonImageElement edgePlaced =- PdfJsonImageElement.builder()- .id("PngE")- .imageData(- pngBase64(- solidImage(- 16,- 16,- Color.BLUE,- BufferedImage.TYPE_INT_RGB)))- .imageFormat("png")- .x(260f)- .y(560f)- .width(64f)- .height(48f)- .build();- PdfJsonPage page =- PdfJsonPage.builder()- .pageNumber(1)- .width(612f)- .height(792f)- .imageElements(new ArrayList<>(List.of(transformed, edgePlaced)))- .build();- try (PDDocument loaded = Loader.loadPDF(runJsonToPdf(docWith(page)))) {- assertEquals(1, loaded.getNumberOfPages());- assertNotNull(loaded.getPage(0).getResources());- }- }-- @Test- @DisplayName("a JPEG-bearing page round trips and keeps its image resources")- void jpegPageRoundTrip() throws IOException {- stubFallbackFont();- PDDocument document = new PDDocument();- PDPage page = new PDPage(PDRectangle.LETTER);- document.addPage(page);- PDImageXObject jpeg =- JPEGFactory.createFromImage(- document, solidImage(48, 36, Color.ORANGE, BufferedImage.TYPE_INT_RGB));- try (PDPageContentStream cs = new PDPageContentStream(document, page)) {- cs.drawImage(jpeg, 80, 500, 120, 90);- }- PdfJsonDocument doc = toJsonDocument(toBytes(document));- byte[] rebuilt = runJsonToPdf(doc);- try (PDDocument loaded = Loader.loadPDF(rebuilt)) {- assertEquals(1, loaded.getNumberOfPages());- assertNotNull(loaded.getPage(0).getResources());- }- }- }-- // ==================================================================- // Cache / editor API: export edits, empty edits, out of range, clear- // ==================================================================-- @Nested- @DisplayName("cache export edits and lifecycle")- class CacheExportEditsLifecycle {-- private byte[] twoPageTextPdf() throws IOException {- PDDocument document = new PDDocument();- for (int i = 0; i < 2; i++) {- PDPage page = new PDPage(PDRectangle.LETTER);- document.addPage(page);- try (PDPageContentStream cs = new PDPageContentStream(document, page)) {- cs.beginText();- cs.setFont(new PDType1Font(Standard14Fonts.FontName.HELVETICA), 12f);- cs.newLineAtOffset(72, 700);- cs.showText("Cache page " + (i + 1));- cs.endText();- }- }- return toBytes(document);- }-- @Test- @DisplayName("export changing font size and colour on a cached page re-saves the document")- void exportChangesFontSizeAndColor() throws IOException {- stubFallbackFont();- stubCanEncode();- cacheLazyDocument("job-size-color", simpleTextPdf("Resize and recolour me"));-- ByteArrayOutputStream pageOut = new ByteArrayOutputStream();- service.extractSinglePage("job-size-color", 1, pageOut);- PdfJsonPage page = objectMapper.readValue(pageOut.toByteArray(), PdfJsonPage.class);- page.setPageNumber(1);- for (PdfJsonTextElement element : page.getTextElements()) {- element.setFontSize(26f);- element.setFillColor(- PdfJsonTextColor.builder()- .colorSpace("DeviceRGB")- .components(new float[] {0.2f, 0.6f, 0.9f})- .build());- }- PdfJsonDocument updates = new PdfJsonDocument();- updates.setPages(new ArrayList<>(List.of(page)));-- ByteArrayOutputStream out = new ByteArrayOutputStream();- service.exportUpdatedPages("job-size-color", updates, out);- try (PDDocument loaded = Loader.loadPDF(out.toByteArray())) {- assertEquals(1, loaded.getNumberOfPages());- }- }-- @Test- @DisplayName("export adding a text element to one cached page rebuilds both pages")- void exportAddsTextElement() throws IOException {- stubFallbackFont();- stubCanEncode();- cacheLazyDocument("job-add-text", twoPageTextPdf());-- ByteArrayOutputStream pageOut = new ByteArrayOutputStream();- service.extractSinglePage("job-add-text", 1, pageOut);- PdfJsonPage page = objectMapper.readValue(pageOut.toByteArray(), PdfJsonPage.class);- page.setPageNumber(1);- List<PdfJsonTextElement> elements =- page.getTextElements() != null- ? new ArrayList<>(page.getTextElements())- : new ArrayList<>();- elements.add(- PdfJsonTextElement.builder()- .text("Newly added line")- .fontId(elements.isEmpty() ? null : elements.get(0).getFontId())- .fontSize(12f)- .x(72f)- .y(640f)- .build());- page.setTextElements(elements);-- PdfJsonDocument updates = new PdfJsonDocument();- updates.setPages(new ArrayList<>(List.of(page)));-- ByteArrayOutputStream out = new ByteArrayOutputStream();- service.exportUpdatedPages("job-add-text", updates, out);- try (PDDocument loaded = Loader.loadPDF(out.toByteArray())) {- assertEquals(2, loaded.getNumberOfPages());- }- }-- @Test- @DisplayName("export with an empty update document returns the cached PDF intact")- void exportEmptyUpdatesReturnsCached() throws IOException {- stubFallbackFont();- cacheLazyDocument("job-empty-updates", twoPageTextPdf());- ByteArrayOutputStream out = new ByteArrayOutputStream();- service.exportUpdatedPages("job-empty-updates", new PdfJsonDocument(), out);- try (PDDocument loaded = Loader.loadPDF(out.toByteArray())) {- assertEquals(2, loaded.getNumberOfPages());- }- }-- @Test- @DisplayName("export of only an out-of-range page leaves the cached document unchanged")- void exportOnlyOutOfRangePage() throws IOException {- stubFallbackFont();- cacheLazyDocument("job-only-ghost", twoPageTextPdf());- PdfJsonPage ghost = new PdfJsonPage();- ghost.setPageNumber(42);- PdfJsonDocument updates = new PdfJsonDocument();- updates.setPages(new ArrayList<>(List.of(ghost)));- ByteArrayOutputStream out = new ByteArrayOutputStream();- service.exportUpdatedPages("job-only-ghost", updates, out);- try (PDDocument loaded = Loader.loadPDF(out.toByteArray())) {- assertEquals(2, loaded.getNumberOfPages());- }- }-- @Test- @DisplayName("extractSinglePage after clearCachedDocument throws CacheUnavailableException")- void singlePageAfterClearThrows() throws IOException {- cacheLazyDocument("job-clear-page", simpleTextPdf("Clear single page"));- service.clearCachedDocument("job-clear-page");- ByteArrayOutputStream out = new ByteArrayOutputStream();- assertThrows(- CacheUnavailableException.class,- () -> service.extractSinglePage("job-clear-page", 1, out));- }-- @Test- @DisplayName("clearCachedDocument is idempotent when called twice")- void clearTwiceIsIdempotent() throws IOException {- cacheLazyDocument("job-clear-twice", simpleTextPdf("Clear twice"));- service.clearCachedDocument("job-clear-twice");- assertDoesNotThrow(() -> service.clearCachedDocument("job-clear-twice"));- }- }-- // ==================================================================- // Metadata extraction with and without a jobId- // ==================================================================-- @Nested- @DisplayName("metadata extraction with and without a jobId")- class MetadataJobIdVariants {-- @Test- @DisplayName("metadata extraction without a jobId does not populate the cache")- void metadataNoJobIdSkipsCache() throws IOException {- when(pdfDocumentFactory.load(any(byte[].class), eq(true)))- .thenAnswer(inv -> Loader.loadPDF(inv.getArgument(0, byte[].class)));- ByteArrayOutputStream out = new ByteArrayOutputStream();- service.extractDocumentMetadata(- pdfMultipart(simpleTextPdf("No job id meta")), null, out);- PdfJsonDocumentMetadata md =- objectMapper.readValue(out.toByteArray(), PdfJsonDocumentMetadata.class);- assertThat(md.getPageDimensions()).hasSize(1);- assertEquals(Boolean.TRUE, md.getLazyImages());- }-- @Test- @DisplayName(- "metadata extraction with a jobId caches a page retrievable by extractSinglePage")- void metadataWithJobIdCachesPage() throws IOException {- when(pdfDocumentFactory.load(any(byte[].class), eq(true)))- .thenAnswer(inv -> Loader.loadPDF(inv.getArgument(0, byte[].class)));- ByteArrayOutputStream metaOut = new ByteArrayOutputStream();- service.extractDocumentMetadata(- pdfMultipart(simpleTextPdf("Job id meta")), "job-meta-cache", metaOut);-- ByteArrayOutputStream pageOut = new ByteArrayOutputStream();- service.extractSinglePage("job-meta-cache", 1, pageOut);- PdfJsonPage page = objectMapper.readValue(pageOut.toByteArray(), PdfJsonPage.class);- assertEquals(1, page.getPageNumber());- }- }-}diff --git a/app/core/src/test/java/stirling/software/SPDF/service/PdfJsonConversionServiceRoundTripTest.java b/app/core/src/test/java/stirling/software/SPDF/service/PdfJsonConversionServiceRoundTripTest.javadeleted file mode 100644index cb4e8e7407..0000000000--- a/app/core/src/test/java/stirling/software/SPDF/service/PdfJsonConversionServiceRoundTripTest.java+++ /dev/null@@ -1,402 +0,0 @@-package stirling.software.SPDF.service;--import static org.assertj.core.api.Assertions.assertThat;-import static org.junit.jupiter.api.Assertions.assertEquals;-import static org.junit.jupiter.api.Assertions.assertNotNull;-import static org.mockito.ArgumentMatchers.any;-import static org.mockito.ArgumentMatchers.anyString;-import static org.mockito.ArgumentMatchers.eq;-import static org.mockito.Mockito.when;--import java.io.ByteArrayOutputStream;-import java.io.File;-import java.io.IOException;-import java.nio.charset.StandardCharsets;-import java.nio.file.Files;-import java.nio.file.Path;-import java.util.ArrayList;-import java.util.Base64;-import java.util.List;--import org.apache.pdfbox.Loader;-import org.apache.pdfbox.pdmodel.PDDocument;-import org.apache.pdfbox.pdmodel.PDPage;-import org.apache.pdfbox.pdmodel.PDPageContentStream;-import org.apache.pdfbox.pdmodel.PDResources;-import org.apache.pdfbox.pdmodel.common.PDMetadata;-import org.apache.pdfbox.pdmodel.common.PDRectangle;-import org.apache.pdfbox.pdmodel.font.PDType1Font;-import org.apache.pdfbox.pdmodel.font.Standard14Fonts;-import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationWidget;-import org.apache.pdfbox.pdmodel.interactive.form.PDAcroForm;-import org.apache.pdfbox.pdmodel.interactive.form.PDTextField;-import org.junit.jupiter.api.AfterEach;-import org.junit.jupiter.api.BeforeEach;-import org.junit.jupiter.api.DisplayName;-import org.junit.jupiter.api.Nested;-import org.junit.jupiter.api.Test;-import org.junit.jupiter.api.extension.ExtendWith;-import org.mockito.Mock;-import org.mockito.junit.jupiter.MockitoExtension;-import org.mockito.quality.Strictness;-import org.springframework.mock.web.MockMultipartFile;--import stirling.software.SPDF.config.EndpointConfiguration;-import stirling.software.SPDF.model.json.PdfJsonDocument;-import stirling.software.SPDF.model.json.PdfJsonFont;-import stirling.software.SPDF.model.json.PdfJsonFormField;-import stirling.software.SPDF.model.json.PdfJsonPage;-import stirling.software.SPDF.model.json.PdfJsonTextElement;-import stirling.software.SPDF.service.pdfjson.PdfJsonFontService;-import stirling.software.SPDF.service.pdfjson.type3.Type3FontConversionService;-import stirling.software.SPDF.service.pdfjson.type3.Type3GlyphExtractor;-import stirling.software.common.model.ApplicationProperties;-import stirling.software.common.service.CustomPDFDocumentFactory;-import stirling.software.common.service.TaskManager;-import stirling.software.common.util.TempFileManager;--import tools.jackson.databind.DeserializationFeature;-import tools.jackson.databind.ObjectMapper;-import tools.jackson.databind.json.JsonMapper;--/**- * Round-trip preservation tests that exercise the resource/content-stream/form-field/XMP machinery- * of {@link PdfJsonConversionService}. Each test builds a real PDF, converts it to the JSON model,- * mutates or inspects it, and rebuilds a PDF, driving the non-lightweight extraction and rebuild- * helpers (resources, content streams, token rewrite, form fields, font metadata).- */-@ExtendWith(MockitoExtension.class)[email protected](strictness = Strictness.LENIENT)-class PdfJsonConversionServiceRoundTripTest {-- @Mock private CustomPDFDocumentFactory pdfDocumentFactory;- @Mock private EndpointConfiguration endpointConfiguration;- @Mock private TempFileManager tempFileManager;- @Mock private TaskManager taskManager;- @Mock private PdfJsonFallbackFontService fallbackFontService;- @Mock private PdfJsonFontService fontService;- @Mock private Type3FontConversionService type3FontConversionService;- @Mock private Type3GlyphExtractor type3GlyphExtractor;- @Mock private ApplicationProperties applicationProperties;-- private final PdfJsonCosMapper cosMapper = new PdfJsonCosMapper();-- private final ObjectMapper objectMapper =- JsonMapper.builder()- .disable(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES)- .build();-- private PdfJsonConversionService service;-- private final List<Path> createdTempFiles = new ArrayList<>();-- @BeforeEach- void setUp() throws IOException {- service =- new PdfJsonConversionService(- pdfDocumentFactory,- objectMapper,- endpointConfiguration,- tempFileManager,- taskManager,- cosMapper,- fallbackFontService,- fontService,- type3FontConversionService,- type3GlyphExtractor,- applicationProperties);-- when(tempFileManager.createTempFile(anyString()))- .thenAnswer(- invocation -> {- String suffix = invocation.getArgument(0);- Path path = Files.createTempFile("pdfjson-rt-test", suffix);- createdTempFiles.add(path);- return path.toFile();- });- when(tempFileManager.deleteTempFile(any(File.class)))- .thenAnswer(- invocation -> {- File file = invocation.getArgument(0);- return file != null && file.delete();- });- when(fallbackFontService.buildFallbackFontModel())- .thenAnswer(- invocation ->- PdfJsonFont.builder()- .id(PdfJsonFallbackFontService.FALLBACK_FONT_ID)- .uid(PdfJsonFallbackFontService.FALLBACK_FONT_ID)- .baseName("Fallback")- .subtype("TrueType")- .build());- when(fallbackFontService.loadFallbackPdfFont(any(PDDocument.class)))- .thenAnswer(invocation -> new PDType1Font(Standard14Fonts.FontName.HELVETICA));- }-- @AfterEach- void tearDown() throws IOException {- for (Path path : createdTempFiles) {- Files.deleteIfExists(path);- }- createdTempFiles.clear();- }-- // ------------------------------------------------------------------- // Helpers- // -------------------------------------------------------------------- private MockMultipartFile pdfMultipart(byte[] bytes) {- return new MockMultipartFile("fileInput", "input.pdf", "application/pdf", bytes);- }-- private byte[] toBytes(PDDocument document) throws IOException {- try (document) {- ByteArrayOutputStream out = new ByteArrayOutputStream();- document.save(out);- return out.toByteArray();- }- }-- /** Stubs the factory to load from a Path (used by convertPdfToJson). */- private void stubFactoryFromPath() throws IOException {- when(pdfDocumentFactory.load(any(Path.class), eq(true)))- .thenAnswer(- invocation ->- Loader.loadPDF(invocation.getArgument(0, Path.class).toFile()));- }-- private PdfJsonDocument toJsonDocument(byte[] pdfBytes) throws IOException {- stubFactoryFromPath();- ByteArrayOutputStream out = new ByteArrayOutputStream();- service.convertPdfToJson(pdfMultipart(pdfBytes), out);- return objectMapper.readValue(out.toByteArray(), PdfJsonDocument.class);- }-- private byte[] runJsonToPdf(PdfJsonDocument doc) throws IOException {- ByteArrayOutputStream out = new ByteArrayOutputStream();- service.convertJsonToPdf(doc, out);- return out.toByteArray();- }-- private byte[] twoLineTextPdf() throws IOException {- PDDocument document = new PDDocument();- PDPage page = new PDPage(PDRectangle.LETTER);- document.addPage(page);- try (PDPageContentStream cs = new PDPageContentStream(document, page)) {- cs.beginText();- cs.setFont(new PDType1Font(Standard14Fonts.FontName.HELVETICA), 12f);- cs.newLineAtOffset(72, 700);- cs.showText("First line of text");- cs.newLineAtOffset(0, -16);- cs.showText("Second line of text");- cs.endText();- }- return toBytes(document);- }-- private byte[] formFieldPdf() throws IOException {- PDDocument document = new PDDocument();- PDPage page = new PDPage(PDRectangle.LETTER);- document.addPage(page);-- PDAcroForm acroForm = new PDAcroForm(document);- // A font in default resources plus a /DA string so setValue can build appearances.- PDResources dr = new PDResources();- dr.put(- org.apache.pdfbox.cos.COSName.getPDFName("Helv"),- new org.apache.pdfbox.pdmodel.font.PDType1Font(- org.apache.pdfbox.pdmodel.font.Standard14Fonts.FontName.HELVETICA));- acroForm.setDefaultResources(dr);- acroForm.setDefaultAppearance("/Helv 12 Tf 0 g");- acroForm.setNeedAppearances(true);- document.getDocumentCatalog().setAcroForm(acroForm);-- PDTextField field = new PDTextField(acroForm);- field.setPartialName("firstName");- field.setDefaultAppearance("/Helv 12 Tf 0 g");-- PDAnnotationWidget widget = new PDAnnotationWidget();- widget.setRectangle(new PDRectangle(100, 650, 200, 20));- widget.setPage(page);- List<PDAnnotationWidget> widgets = new ArrayList<>(field.getWidgets());- widgets.add(widget);- field.setWidgets(widgets);-- acroForm.getFields().add(field);- page.getAnnotations().add(widget);- field.setValue("Jane");-- return toBytes(document);- }-- // ------------------------------------------------------------------- // Content stream + resource preservation- // -------------------------------------------------------------------- @Nested- @DisplayName("content stream and resource preservation")- class ContentStreamPreservation {-- @Test- @DisplayName("non-lightweight extraction captures content streams and resources")- void capturesStreamsAndResources() throws IOException {- PdfJsonDocument doc = toJsonDocument(twoLineTextPdf());- PdfJsonPage page = doc.getPages().get(0);- assertNotNull(page.getResources(), "expected serialized resources");- assertThat(page.getContentStreams()).isNotEmpty();- }-- @Test- @DisplayName("preserved content streams enable in-place token rewrite on round trip")- void tokenRewriteRoundTrip() throws IOException {- PdfJsonDocument doc = toJsonDocument(twoLineTextPdf());- // Same-length edit keeps the rewrite path viable.- for (PdfJsonTextElement element : doc.getPages().get(0).getTextElements()) {- if (element.getText() != null && element.getText().contains("First")) {- element.setText(element.getText());- break;- }- }- byte[] rebuilt = runJsonToPdf(doc);- try (PDDocument loaded = Loader.loadPDF(rebuilt)) {- assertEquals(1, loaded.getNumberOfPages());- assertNotNull(loaded.getPage(0).getContents());- }- }-- @Test- @DisplayName("round trip preserves the two-line page intact")- void preservesTwoLines() throws IOException {- PdfJsonDocument doc = toJsonDocument(twoLineTextPdf());- byte[] rebuilt = runJsonToPdf(doc);- try (PDDocument loaded = Loader.loadPDF(rebuilt)) {- assertEquals(1, loaded.getNumberOfPages());- }- }- }-- // ------------------------------------------------------------------- // Form fields- // -------------------------------------------------------------------- @Nested- @DisplayName("form fields")- class FormFields {-- @Test- @DisplayName("AcroForm text field is extracted with name and value")- void extractsTextField() throws IOException {- PdfJsonDocument doc = toJsonDocument(formFieldPdf());- List<PdfJsonFormField> fields = doc.getFormFields();- assertThat(fields).isNotEmpty();- PdfJsonFormField field = fields.get(0);- assertThat(field.getPartialName()).isEqualTo("firstName");- // The service stores the raw COS representation of the field value.- assertThat(field.getValue()).contains("Jane");- assertThat(field.getRawData()).isNotNull();- }-- @Test- @DisplayName("form field round trips back into a rebuilt AcroForm")- void formFieldRoundTrip() throws IOException {- PdfJsonDocument doc = toJsonDocument(formFieldPdf());- byte[] rebuilt = runJsonToPdf(doc);- try (PDDocument loaded = Loader.loadPDF(rebuilt)) {- PDAcroForm acroForm = loaded.getDocumentCatalog().getAcroForm();- assertNotNull(acroForm, "rebuilt document should carry an AcroForm");- assertThat(acroForm.getFields()).isNotEmpty();- }- }- }-- // ------------------------------------------------------------------- // XMP metadata- // -------------------------------------------------------------------- @Nested- @DisplayName("XMP metadata")- class XmpMetadata {-- @Test- @DisplayName("XMP packet survives a PDF to JSON to PDF round trip")- void xmpRoundTrip() throws IOException {- PDDocument document = new PDDocument();- document.addPage(new PDPage(PDRectangle.LETTER));- String xmp =- "<?xpacket begin=\"\"?><x:xmpmeta xmlns:x=\"adobe:ns:meta/\">"- + "<rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">"- + "</rdf:RDF></x:xmpmeta><?xpacket end=\"w\"?>";- PDMetadata metadata = new PDMetadata(document);- metadata.importXMPMetadata(xmp.getBytes(StandardCharsets.UTF_8));- document.getDocumentCatalog().setMetadata(metadata);- byte[] bytes = toBytes(document);-- PdfJsonDocument doc = toJsonDocument(bytes);- assertThat(doc.getXmpMetadata()).isNotBlank();- // Round-tripped base64 should decode back to XMP content.- String decoded =- new String(- Base64.getDecoder().decode(doc.getXmpMetadata()),- StandardCharsets.UTF_8);- assertThat(decoded).contains("xmpmeta");-- byte[] rebuilt = runJsonToPdf(doc);- try (PDDocument loaded = Loader.loadPDF(rebuilt)) {- assertNotNull(loaded.getDocumentCatalog().getMetadata());- }- }- }-- // ------------------------------------------------------------------- // convertPdfToJsonDocument mutate-then-rebuild- // -------------------------------------------------------------------- @Nested- @DisplayName("convertPdfToJsonDocument workflow")- class DocumentWorkflow {-- @Test- @DisplayName("in-memory model can be mutated and rebuilt into a PDF")- void mutateAndRebuild() throws IOException {- stubFactoryFromPath();- PdfJsonDocument doc = service.convertPdfToJsonDocument(pdfMultipart(twoLineTextPdf()));- assertNotNull(doc);- assertEquals(1, doc.getPages().size());-- // Append a brand new page with synthesized text.- PdfJsonFont font =- PdfJsonFont.builder()- .id("F-new")- .uid("F-new")- .baseName("Helvetica")- .subtype("Type1")- .standard14Name("Helvetica")- .build();- doc.getFonts().add(font);-- PdfJsonTextElement element =- PdfJsonTextElement.builder()- .text("Appended page")- .fontId("F-new")- .fontSize(12f)- .x(72f)- .y(700f)- .build();- PdfJsonPage newPage =- PdfJsonPage.builder()- .pageNumber(2)- .width(612f)- .height(792f)- .textElements(List.of(element))- .build();- List<PdfJsonPage> pages = new ArrayList<>(doc.getPages());- pages.add(newPage);- doc.setPages(pages);-- byte[] rebuilt = runJsonToPdf(doc);- try (PDDocument loaded = Loader.loadPDF(rebuilt)) {- assertEquals(2, loaded.getNumberOfPages());- }- }- }-}diff --git a/app/core/src/test/java/stirling/software/SPDF/service/PdfJsonConversionServiceUnicodeParsingTest.java b/app/core/src/test/java/stirling/software/SPDF/service/PdfJsonConversionServiceUnicodeParsingTest.javadeleted file mode 100644index af81ea0474..0000000000--- a/app/core/src/test/java/stirling/software/SPDF/service/PdfJsonConversionServiceUnicodeParsingTest.java+++ /dev/null@@ -1,161 +0,0 @@-package stirling.software.SPDF.service;--import static org.junit.jupiter.api.Assertions.assertEquals;-import static org.junit.jupiter.api.Assertions.assertThrows;-import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively;--import java.io.ByteArrayInputStream;-import java.io.IOException;-import java.io.InputStream;-import java.time.Duration;--import org.junit.jupiter.api.Test;--/**- * Unit tests for {@link PdfJsonConversionService#parseToUnicodeCodepoint(String)}.- *- * <p>The function exists because PDF ToUnicode CMap entries can encode supplementary-plane- * codepoints (above U+FFFF) as UTF-16 surrogate pairs, e.g. {@code <D837DF0E>} for U+1F40E. The- * naive implementation that called {@link Integer#parseInt(String, int)} on the whole hex string- * threw {@link NumberFormatException} for any 8-char value because they overflow {@code int}. That- * triggered a fallback that left fonts with no proper CID mapping and made downstream JSON→PDF- * rebuilds slow/hung when rendering text with those fonts.- */-class PdfJsonConversionServiceUnicodeParsingTest {-- @Test- void parsesSingleBmpCodeUnit() {- // Latin capital A.- assertEquals(0x41, PdfJsonConversionService.parseToUnicodeCodepoint("0041"));- }-- @Test- void parsesShortBmpHexValue() {- // Some ToUnicode entries omit leading zeros for low codepoints.- assertEquals(0x41, PdfJsonConversionService.parseToUnicodeCodepoint("41"));- }-- @Test- void parsesSupplementaryCodepointFromSurrogatePair() {- // U+1F40E HORSE encoded as UTF-16 surrogate pair D83D DC0E. The bug we are fixing was- // that Integer.parseInt("D83DDC0E", 16) overflows because D83DDC0E > Integer.MAX_VALUE.- assertEquals(0x1F40E, PdfJsonConversionService.parseToUnicodeCodepoint("D83DDC0E"));- }-- @Test- void parsesSurrogatePairFromUserReportedHang() {- // The exact hex value from the user's hang reproducer log:- // "Failed to build Unicode mapping for font NotoSans-Regular: For input string:- // \"D837DF0E\" under radix 16"- // D837 DF0E decodes to U+1DF0E (CJK supplementary). Important assertion: it returns a- // valid codepoint instead of overflowing Integer.parseInt and throwing.- int expected = new String(new char[] {(char) 0xD837, (char) 0xDF0E}).codePointAt(0);- assertEquals(0x1DF0E, expected); // sanity check on the test setup itself- assertEquals(expected, PdfJsonConversionService.parseToUnicodeCodepoint("D837DF0E"));- }-- @Test- void parsesLigatureDecompositionAsFirstCodepoint() {- // A ToUnicode entry can map one charCode to multiple Unicode chars (a ligature). PDF- // spec allows e.g. <0041 0042> for "AB". Our best-effort behavior is to return the- // first codepoint so the mapping is at least roughly meaningful for search/copy.- assertEquals(0x41, PdfJsonConversionService.parseToUnicodeCodepoint("00410042"));- }-- @Test- void rejectsEmptyHex() {- assertThrows(- NumberFormatException.class,- () -> PdfJsonConversionService.parseToUnicodeCodepoint(""));- }-- @Test- void rejectsNullHex() {- assertThrows(- NumberFormatException.class,- () -> PdfJsonConversionService.parseToUnicodeCodepoint(null));- }-- @Test- void rejectsOddByteCountAboveBmp() {- // 6 hex chars is 3 bytes — not a valid UTF-16BE sequence.- assertThrows(- NumberFormatException.class,- () -> PdfJsonConversionService.parseToUnicodeCodepoint("D83DDC"));- }-- @Test- void countCodesProtectedTerminatesWhenReaderMakesNoProgress() {- // Reproduces the user's hang: PDFBox's CMap.readCode can return a successful code (0)- // from a stream where no bytes were consumed (corrupt codespace matching 0x00 bytes from- // the buffer's uninitialized region after EOF). Without the no-progress guard, the- // counting loop in countGlyphs ran forever.- ByteArrayInputStream stream = new ByteArrayInputStream(new byte[] {1, 2, 3, 4});- PdfJsonConversionService.CodeReader reader = in -> 0; // never reads, always "succeeds"-- int count =- assertTimeoutPreemptively(- Duration.ofSeconds(2),- () -> PdfJsonConversionService.countCodesProtected(stream, reader));-- // First iteration sees no progress and breaks immediately.- assertEquals(0, count);- }-- @Test- void countCodesProtectedTerminatesOnEmptyStream() {- ByteArrayInputStream stream = new ByteArrayInputStream(new byte[0]);- PdfJsonConversionService.CodeReader reader =- in -> {- throw new AssertionError("reader must not be called when stream is empty");- };-- int count =- assertTimeoutPreemptively(- Duration.ofSeconds(2),- () -> PdfJsonConversionService.countCodesProtected(stream, reader));-- assertEquals(0, count);- }-- @Test- void countCodesProtectedHonorsExplicitMinusOneReturn() throws IOException {- ByteArrayInputStream stream = new ByteArrayInputStream(new byte[] {1, 2, 3});- PdfJsonConversionService.CodeReader reader =- in -> {- int b = in.read();- return b == -1 ? -1 : b;- };-- int count = PdfJsonConversionService.countCodesProtected(stream, reader);-- assertEquals(3, count);- }-- @Test- void countCodesProtectedTerminatesIfReaderReadsThenStops() throws IOException {- // A reader that consumes one byte then hits a corrupt-CMap pattern returning 0 without- // consuming further must still terminate after counting the consumed bytes.- ByteArrayInputStream stream = new ByteArrayInputStream(new byte[] {1, 2, 3, 4});- PdfJsonConversionService.CodeReader reader =- new PdfJsonConversionService.CodeReader() {- boolean firstCall = true;-- @Override- public int readCode(InputStream in) throws IOException {- if (firstCall) {- firstCall = false;- return in.read();- }- return 0; // simulates corrupt CMap thereafter- }- };-- int count =- assertTimeoutPreemptively(- Duration.ofSeconds(2),- () -> PdfJsonConversionService.countCodesProtected(stream, reader));-- assertEquals(1, count);- }-}diff --git a/app/core/src/test/java/stirling/software/SPDF/service/PdfJsonCosMapperTest.java b/app/core/src/test/java/stirling/software/SPDF/service/PdfJsonCosMapperTest.javadeleted file mode 100644index a8172bf916..0000000000--- a/app/core/src/test/java/stirling/software/SPDF/service/PdfJsonCosMapperTest.java+++ /dev/null@@ -1,780 +0,0 @@-package stirling.software.SPDF.service;--import static org.junit.jupiter.api.Assertions.assertArrayEquals;-import static org.junit.jupiter.api.Assertions.assertEquals;-import static org.junit.jupiter.api.Assertions.assertFalse;-import static org.junit.jupiter.api.Assertions.assertInstanceOf;-import static org.junit.jupiter.api.Assertions.assertNotNull;-import static org.junit.jupiter.api.Assertions.assertNull;-import static org.junit.jupiter.api.Assertions.assertThrows;-import static org.junit.jupiter.api.Assertions.assertTrue;--import java.io.IOException;-import java.io.InputStream;-import java.io.OutputStream;-import java.nio.charset.StandardCharsets;-import java.util.Base64;-import java.util.LinkedHashMap;-import java.util.List;-import java.util.Map;--import org.apache.pdfbox.cos.COSArray;-import org.apache.pdfbox.cos.COSBase;-import org.apache.pdfbox.cos.COSBoolean;-import org.apache.pdfbox.cos.COSDictionary;-import org.apache.pdfbox.cos.COSFloat;-import org.apache.pdfbox.cos.COSInteger;-import org.apache.pdfbox.cos.COSName;-import org.apache.pdfbox.cos.COSNull;-import org.apache.pdfbox.cos.COSStream;-import org.apache.pdfbox.cos.COSString;-import org.apache.pdfbox.pdmodel.PDDocument;-import org.apache.pdfbox.pdmodel.common.PDStream;-import org.junit.jupiter.api.AfterEach;-import org.junit.jupiter.api.BeforeEach;-import org.junit.jupiter.api.DisplayName;-import org.junit.jupiter.api.Nested;-import org.junit.jupiter.api.Test;--import stirling.software.SPDF.model.json.PdfJsonCosValue;-import stirling.software.SPDF.model.json.PdfJsonStream;-import stirling.software.SPDF.service.PdfJsonCosMapper.SerializationContext;--/** Unit tests for {@link PdfJsonCosMapper}. */-class PdfJsonCosMapperTest {-- private PdfJsonCosMapper mapper;- private PDDocument document;-- @BeforeEach- void setUp() {- mapper = new PdfJsonCosMapper();- document = new PDDocument();- }-- @AfterEach- void tearDown() throws IOException {- if (document != null) {- document.close();- }- }-- // Helper: create a populated COSStream within the test document.- private COSStream newCosStreamWithData(byte[] data) throws IOException {- COSStream cosStream = document.getDocument().createCOSStream();- try (OutputStream out = cosStream.createRawOutputStream()) {- out.write(data);- }- cosStream.setItem(COSName.LENGTH, COSInteger.get(data.length));- return cosStream;- }-- @Nested- @DisplayName("SerializationContext.omitStreamData()")- class OmitStreamDataTests {-- @Test- @DisplayName("returns true only for lightweight contexts")- void omitStreamData() {- assertFalse(SerializationContext.DEFAULT.omitStreamData());- assertFalse(SerializationContext.ANNOTATION_RAW_DATA.omitStreamData());- assertFalse(SerializationContext.FORM_FIELD_RAW_DATA.omitStreamData());- assertTrue(SerializationContext.CONTENT_STREAMS_LIGHTWEIGHT.omitStreamData());- assertTrue(SerializationContext.RESOURCES_LIGHTWEIGHT.omitStreamData());- }- }-- @Nested- @DisplayName("serializeCosValue - primitives")- class SerializeCosValuePrimitiveTests {-- @Test- @DisplayName("null base yields null value")- void nullBase() throws IOException {- assertNull(mapper.serializeCosValue(null));- }-- @Test- @DisplayName("COSNull serializes to NULL type")- void cosNull() throws IOException {- PdfJsonCosValue value = mapper.serializeCosValue(COSNull.NULL);- assertNotNull(value);- assertEquals(PdfJsonCosValue.Type.NULL, value.getType());- }-- @Test- @DisplayName("COSBoolean serializes to BOOLEAN type with value")- void cosBoolean() throws IOException {- PdfJsonCosValue trueValue = mapper.serializeCosValue(COSBoolean.TRUE);- assertEquals(PdfJsonCosValue.Type.BOOLEAN, trueValue.getType());- assertEquals(Boolean.TRUE, trueValue.getValue());-- PdfJsonCosValue falseValue = mapper.serializeCosValue(COSBoolean.FALSE);- assertEquals(PdfJsonCosValue.Type.BOOLEAN, falseValue.getType());- assertEquals(Boolean.FALSE, falseValue.getValue());- }-- @Test- @DisplayName("COSInteger serializes to INTEGER type with long value")- void cosInteger() throws IOException {- PdfJsonCosValue value = mapper.serializeCosValue(COSInteger.get(42L));- assertEquals(PdfJsonCosValue.Type.INTEGER, value.getType());- assertEquals(42L, value.getValue());- }-- @Test- @DisplayName("COSFloat serializes to FLOAT type with float value")- void cosFloat() throws IOException {- PdfJsonCosValue value = mapper.serializeCosValue(new COSFloat(1.5f));- assertEquals(PdfJsonCosValue.Type.FLOAT, value.getType());- assertEquals(1.5f, value.getValue());- }-- @Test- @DisplayName("COSName serializes to NAME type with the name literal")- void cosName() throws IOException {- PdfJsonCosValue value = mapper.serializeCosValue(COSName.getPDFName("Foo"));- assertEquals(PdfJsonCosValue.Type.NAME, value.getType());- assertEquals("Foo", value.getValue());- }-- @Test- @DisplayName("COSString serializes to STRING type with base64 content")- void cosString() throws IOException {- byte[] raw = "héllo".getBytes(StandardCharsets.UTF_8);- PdfJsonCosValue value = mapper.serializeCosValue(new COSString(raw));- assertEquals(PdfJsonCosValue.Type.STRING, value.getType());- assertEquals(Base64.getEncoder().encodeToString(raw), value.getValue());- }- }-- @Nested- @DisplayName("serializeCosValue - containers")- class SerializeCosValueContainerTests {-- @Test- @DisplayName("COSArray serializes nested items in order")- void cosArray() throws IOException {- COSArray array = new COSArray();- array.add(COSInteger.get(1L));- array.add(COSName.getPDFName("X"));- array.add(COSBoolean.TRUE);-- PdfJsonCosValue value = mapper.serializeCosValue(array);- assertEquals(PdfJsonCosValue.Type.ARRAY, value.getType());- List<PdfJsonCosValue> items = value.getItems();- assertEquals(3, items.size());- assertEquals(PdfJsonCosValue.Type.INTEGER, items.get(0).getType());- assertEquals(PdfJsonCosValue.Type.NAME, items.get(1).getType());- assertEquals(PdfJsonCosValue.Type.BOOLEAN, items.get(2).getType());- }-- @Test- @DisplayName("COSDictionary serializes keyed entries")- void cosDictionary() throws IOException {- COSDictionary dict = new COSDictionary();- dict.setItem(COSName.getPDFName("Count"), COSInteger.get(7L));- dict.setItem(COSName.getPDFName("Type"), COSName.getPDFName("Catalog"));-- PdfJsonCosValue value = mapper.serializeCosValue(dict);- assertEquals(PdfJsonCosValue.Type.DICTIONARY, value.getType());- Map<String, PdfJsonCosValue> entries = value.getEntries();- assertEquals(2, entries.size());- assertEquals(PdfJsonCosValue.Type.INTEGER, entries.get("Count").getType());- assertEquals(7L, entries.get("Count").getValue());- assertEquals(PdfJsonCosValue.Type.NAME, entries.get("Type").getType());- assertEquals("Catalog", entries.get("Type").getValue());- }-- @Test- @DisplayName("circular dictionary reference is replaced with a __circular__ marker")- void circularReference() throws IOException {- COSDictionary dict = new COSDictionary();- dict.setItem(COSName.getPDFName("Self"), dict);-- PdfJsonCosValue value = mapper.serializeCosValue(dict);- assertEquals(PdfJsonCosValue.Type.DICTIONARY, value.getType());- PdfJsonCosValue self = value.getEntries().get("Self");- assertEquals(PdfJsonCosValue.Type.NAME, self.getType());- assertEquals("__circular__", self.getValue());- }-- @Test- @DisplayName("the same dictionary appearing twice (non-circular) is serialized both times")- void repeatedNonCircularReference() throws IOException {- COSDictionary shared = new COSDictionary();- shared.setItem(COSName.getPDFName("V"), COSInteger.get(9L));- COSArray array = new COSArray();- array.add(shared);- array.add(shared);-- PdfJsonCosValue value = mapper.serializeCosValue(array);- List<PdfJsonCosValue> items = value.getItems();- assertEquals(2, items.size());- // Because the visited set is removed in finally, the second sibling occurrence is not- // treated as circular.- assertEquals(PdfJsonCosValue.Type.DICTIONARY, items.get(0).getType());- assertEquals(PdfJsonCosValue.Type.DICTIONARY, items.get(1).getType());- }- }-- @Nested- @DisplayName("serializeStream overloads")- class SerializeStreamTests {-- @Test- @DisplayName("null PDStream returns null")- void nullPdStream() throws IOException {- assertNull(mapper.serializeStream((PDStream) null));- }-- @Test- @DisplayName("null COSStream returns null")- void nullCosStream() throws IOException {- assertNull(mapper.serializeStream((COSStream) null));- }-- @Test- @DisplayName("null COSStream with explicit context returns null")- void nullCosStreamWithContext() throws IOException {- assertNull(mapper.serializeStream((COSStream) null, SerializationContext.DEFAULT));- }-- @Test- @DisplayName("null PDStream with explicit context returns null")- void nullPdStreamWithContext() throws IOException {- assertNull(mapper.serializeStream((PDStream) null, SerializationContext.DEFAULT));- }-- @Test- @DisplayName("COSStream serializes dictionary and base64 rawData")- void cosStreamWithData() throws IOException {- byte[] data = "stream-bytes".getBytes(StandardCharsets.UTF_8);- COSStream cosStream = newCosStreamWithData(data);- cosStream.setItem(COSName.TYPE, COSName.getPDFName("XObject"));-- PdfJsonStream result = mapper.serializeStream(cosStream);- assertNotNull(result);- assertNotNull(result.getDictionary());- assertTrue(result.getDictionary().containsKey(COSName.TYPE.getName()));- assertEquals(Base64.getEncoder().encodeToString(data), result.getRawData());- }-- @Test- @DisplayName("empty COSStream yields null rawData")- void emptyCosStream() throws IOException {- COSStream cosStream = newCosStreamWithData(new byte[0]);- PdfJsonStream result = mapper.serializeStream(cosStream);- assertNotNull(result);- assertNull(result.getRawData());- }-- @Test- @DisplayName("lightweight context omits rawData even when stream has data")- void lightweightContextOmitsData() throws IOException {- byte[] data = "ignored".getBytes(StandardCharsets.UTF_8);- COSStream cosStream = newCosStreamWithData(data);- cosStream.setItem(COSName.FILTER, COSName.getPDFName("FlateDecode"));-- PdfJsonStream result =- mapper.serializeStream(- cosStream, SerializationContext.CONTENT_STREAMS_LIGHTWEIGHT);- assertNotNull(result);- assertNull(result.getRawData());- // Dictionary metadata is still preserved.- assertTrue(result.getDictionary().containsKey(COSName.FILTER.getName()));- }-- @Test- @DisplayName("null context is treated as DEFAULT and keeps rawData")- void nullContextDefaultsToDefault() throws IOException {- byte[] data = "keep".getBytes(StandardCharsets.UTF_8);- COSStream cosStream = newCosStreamWithData(data);-- PdfJsonStream result = mapper.serializeStream(cosStream, (SerializationContext) null);- assertNotNull(result);- assertEquals(Base64.getEncoder().encodeToString(data), result.getRawData());- }-- @Test- @DisplayName("PDStream overload delegates to COSStream serialization")- void pdStreamOverload() throws IOException {- byte[] data = "pdstream".getBytes(StandardCharsets.UTF_8);- PDStream pdStream = new PDStream(document, new java.io.ByteArrayInputStream(data));-- PdfJsonStream result = mapper.serializeStream(pdStream);- assertNotNull(result);- assertNotNull(result.getRawData());- }-- @Test- @DisplayName("PDStream overload with lightweight context omits rawData")- void pdStreamOverloadLightweight() throws IOException {- byte[] data = "pdstream".getBytes(StandardCharsets.UTF_8);- PDStream pdStream = new PDStream(document, new java.io.ByteArrayInputStream(data));-- PdfJsonStream result =- mapper.serializeStream(pdStream, SerializationContext.RESOURCES_LIGHTWEIGHT);- assertNotNull(result);- assertNull(result.getRawData());- }-- @Test- @DisplayName("serializeCosValue of a COSStream produces STREAM type wrapping the stream")- void serializeCosValueWrapsStream() throws IOException {- byte[] data = "abc".getBytes(StandardCharsets.UTF_8);- COSStream cosStream = newCosStreamWithData(data);-- PdfJsonCosValue value = mapper.serializeCosValue(cosStream);- assertEquals(PdfJsonCosValue.Type.STREAM, value.getType());- assertNotNull(value.getStream());- assertEquals(Base64.getEncoder().encodeToString(data), value.getStream().getRawData());- }- }-- @Nested- @DisplayName("deserializeCosValue")- class DeserializeCosValueTests {-- @Test- @DisplayName("null value returns null")- void nullValue() throws IOException {- assertNull(mapper.deserializeCosValue(null, document));- }-- @Test- @DisplayName("value with null type returns null")- void nullType() throws IOException {- PdfJsonCosValue value = PdfJsonCosValue.builder().value("x").build();- assertNull(mapper.deserializeCosValue(value, document));- }-- @Test- @DisplayName("NULL type returns COSNull")- void nullTypeValue() throws IOException {- PdfJsonCosValue value =- PdfJsonCosValue.builder().type(PdfJsonCosValue.Type.NULL).build();- assertEquals(COSNull.NULL, mapper.deserializeCosValue(value, document));- }-- @Test- @DisplayName("BOOLEAN type returns matching COSBoolean")- void booleanType() throws IOException {- PdfJsonCosValue value =- PdfJsonCosValue.builder()- .type(PdfJsonCosValue.Type.BOOLEAN)- .value(Boolean.TRUE)- .build();- COSBase result = mapper.deserializeCosValue(value, document);- assertEquals(COSBoolean.TRUE, result);- }-- @Test- @DisplayName("BOOLEAN type with non-boolean value returns null")- void booleanTypeWrongValue() throws IOException {- PdfJsonCosValue value =- PdfJsonCosValue.builder()- .type(PdfJsonCosValue.Type.BOOLEAN)- .value("not-a-boolean")- .build();- assertNull(mapper.deserializeCosValue(value, document));- }-- @Test- @DisplayName("INTEGER type returns COSInteger from a Number value")- void integerType() throws IOException {- PdfJsonCosValue value =- PdfJsonCosValue.builder()- .type(PdfJsonCosValue.Type.INTEGER)- .value(123L)- .build();- COSBase result = mapper.deserializeCosValue(value, document);- assertInstanceOf(COSInteger.class, result);- assertEquals(123L, ((COSInteger) result).longValue());- }-- @Test- @DisplayName("INTEGER type accepts an Integer value via Number")- void integerTypeFromInteger() throws IOException {- PdfJsonCosValue value =- PdfJsonCosValue.builder()- .type(PdfJsonCosValue.Type.INTEGER)- .value(Integer.valueOf(5))- .build();- COSBase result = mapper.deserializeCosValue(value, document);- assertInstanceOf(COSInteger.class, result);- assertEquals(5L, ((COSInteger) result).longValue());- }-- @Test- @DisplayName("INTEGER type with non-number returns null")- void integerTypeWrongValue() throws IOException {- PdfJsonCosValue value =- PdfJsonCosValue.builder()- .type(PdfJsonCosValue.Type.INTEGER)- .value("oops")- .build();- assertNull(mapper.deserializeCosValue(value, document));- }-- @Test- @DisplayName("FLOAT type returns COSFloat from a Number value")- void floatType() throws IOException {- PdfJsonCosValue value =- PdfJsonCosValue.builder().type(PdfJsonCosValue.Type.FLOAT).value(2.25f).build();- COSBase result = mapper.deserializeCosValue(value, document);- assertInstanceOf(COSFloat.class, result);- assertEquals(2.25f, ((COSFloat) result).floatValue());- }-- @Test- @DisplayName("FLOAT type with non-number returns null")- void floatTypeWrongValue() throws IOException {- PdfJsonCosValue value =- PdfJsonCosValue.builder()- .type(PdfJsonCosValue.Type.FLOAT)- .value("oops")- .build();- assertNull(mapper.deserializeCosValue(value, document));- }-- @Test- @DisplayName("NAME type returns COSName from a String value")- void nameType() throws IOException {- PdfJsonCosValue value =- PdfJsonCosValue.builder()- .type(PdfJsonCosValue.Type.NAME)- .value("MyName")- .build();- COSBase result = mapper.deserializeCosValue(value, document);- assertEquals(COSName.getPDFName("MyName"), result);- }-- @Test- @DisplayName("NAME type with non-string returns null")- void nameTypeWrongValue() throws IOException {- PdfJsonCosValue value =- PdfJsonCosValue.builder().type(PdfJsonCosValue.Type.NAME).value(123L).build();- assertNull(mapper.deserializeCosValue(value, document));- }-- @Test- @DisplayName("STRING type decodes base64 into COSString bytes")- void stringType() throws IOException {- byte[] raw = "round-trip".getBytes(StandardCharsets.UTF_8);- String encoded = Base64.getEncoder().encodeToString(raw);- PdfJsonCosValue value =- PdfJsonCosValue.builder()- .type(PdfJsonCosValue.Type.STRING)- .value(encoded)- .build();- COSBase result = mapper.deserializeCosValue(value, document);- assertInstanceOf(COSString.class, result);- assertArrayEquals(raw, ((COSString) result).getBytes());- }-- @Test- @DisplayName("STRING type with invalid base64 returns null")- void stringTypeInvalidBase64() throws IOException {- PdfJsonCosValue value =- PdfJsonCosValue.builder()- .type(PdfJsonCosValue.Type.STRING)- .value("!!!not base64!!!")- .build();- assertNull(mapper.deserializeCosValue(value, document));- }-- @Test- @DisplayName("STRING type with non-string value returns null")- void stringTypeWrongValue() throws IOException {- PdfJsonCosValue value =- PdfJsonCosValue.builder().type(PdfJsonCosValue.Type.STRING).value(42L).build();- assertNull(mapper.deserializeCosValue(value, document));- }-- @Test- @DisplayName("ARRAY type deserializes each item")- void arrayType() throws IOException {- PdfJsonCosValue item1 =- PdfJsonCosValue.builder().type(PdfJsonCosValue.Type.INTEGER).value(1L).build();- PdfJsonCosValue item2 =- PdfJsonCosValue.builder().type(PdfJsonCosValue.Type.NAME).value("N").build();- PdfJsonCosValue value =- PdfJsonCosValue.builder()- .type(PdfJsonCosValue.Type.ARRAY)- .items(List.of(item1, item2))- .build();-- COSBase result = mapper.deserializeCosValue(value, document);- assertInstanceOf(COSArray.class, result);- COSArray array = (COSArray) result;- assertEquals(2, array.size());- assertEquals(1L, ((COSInteger) array.get(0)).longValue());- assertEquals(COSName.getPDFName("N"), array.get(1));- }-- @Test- @DisplayName("ARRAY type substitutes COSNull for un-deserializable items")- void arrayTypeWithNullItems() throws IOException {- // An INTEGER type with a non-number value deserializes to null and is replaced by- // COSNull.NULL inside the array.- PdfJsonCosValue bad =- PdfJsonCosValue.builder()- .type(PdfJsonCosValue.Type.INTEGER)- .value("nope")- .build();- PdfJsonCosValue value =- PdfJsonCosValue.builder()- .type(PdfJsonCosValue.Type.ARRAY)- .items(List.of(bad))- .build();-- COSArray result = (COSArray) mapper.deserializeCosValue(value, document);- assertEquals(1, result.size());- assertEquals(COSNull.NULL, result.get(0));- }-- @Test- @DisplayName("ARRAY type with null items list yields empty COSArray")- void arrayTypeNullItems() throws IOException {- PdfJsonCosValue value =- PdfJsonCosValue.builder().type(PdfJsonCosValue.Type.ARRAY).build();- COSArray result = (COSArray) mapper.deserializeCosValue(value, document);- assertNotNull(result);- assertEquals(0, result.size());- }-- @Test- @DisplayName("DICTIONARY type deserializes entries by key")- void dictionaryType() throws IOException {- Map<String, PdfJsonCosValue> entries = new LinkedHashMap<>();- entries.put(- "Count",- PdfJsonCosValue.builder().type(PdfJsonCosValue.Type.INTEGER).value(3L).build());- PdfJsonCosValue value =- PdfJsonCosValue.builder()- .type(PdfJsonCosValue.Type.DICTIONARY)- .entries(entries)- .build();-- COSDictionary result = (COSDictionary) mapper.deserializeCosValue(value, document);- assertNotNull(result);- assertEquals(3L, ((COSInteger) result.getItem("Count")).longValue());- }-- @Test- @DisplayName("DICTIONARY type skips entries that deserialize to null")- void dictionaryTypeSkipsNullEntries() throws IOException {- Map<String, PdfJsonCosValue> entries = new LinkedHashMap<>();- entries.put(- "Bad",- PdfJsonCosValue.builder()- .type(PdfJsonCosValue.Type.INTEGER)- .value("nope")- .build());- PdfJsonCosValue value =- PdfJsonCosValue.builder()- .type(PdfJsonCosValue.Type.DICTIONARY)- .entries(entries)- .build();-- COSDictionary result = (COSDictionary) mapper.deserializeCosValue(value, document);- assertNotNull(result);- assertNull(result.getItem(COSName.getPDFName("Bad")));- }-- @Test- @DisplayName("DICTIONARY type with null entries map yields empty COSDictionary")- void dictionaryTypeNullEntries() throws IOException {- PdfJsonCosValue value =- PdfJsonCosValue.builder().type(PdfJsonCosValue.Type.DICTIONARY).build();- COSDictionary result = (COSDictionary) mapper.deserializeCosValue(value, document);- assertNotNull(result);- assertEquals(0, result.size());- }-- @Test- @DisplayName("STREAM type with null stream returns null")- void streamTypeNullStream() throws IOException {- PdfJsonCosValue value =- PdfJsonCosValue.builder().type(PdfJsonCosValue.Type.STREAM).build();- assertNull(mapper.deserializeCosValue(value, document));- }-- @Test- @DisplayName("STREAM type builds a COSStream from the model")- void streamType() throws IOException {- byte[] data = "stream-content".getBytes(StandardCharsets.UTF_8);- PdfJsonStream streamModel =- PdfJsonStream.builder()- .rawData(Base64.getEncoder().encodeToString(data))- .build();- PdfJsonCosValue value =- PdfJsonCosValue.builder().type(PdfJsonCosValue.Type.STREAM).stream(streamModel)- .build();-- COSBase result = mapper.deserializeCosValue(value, document);- assertInstanceOf(COSStream.class, result);- assertStreamRawEquals(data, (COSStream) result);- }- }-- @Nested- @DisplayName("buildStreamFromModel")- class BuildStreamFromModelTests {-- @Test- @DisplayName("null model returns null")- void nullModel() throws IOException {- assertNull(mapper.buildStreamFromModel(null, document));- }-- @Test- @DisplayName("model with rawData writes base64-decoded bytes and sets Length")- void withRawData() throws IOException {- byte[] data = "hello-world".getBytes(StandardCharsets.UTF_8);- PdfJsonStream model =- PdfJsonStream.builder()- .rawData(Base64.getEncoder().encodeToString(data))- .build();-- COSStream result = mapper.buildStreamFromModel(model, document);- assertNotNull(result);- assertStreamRawEquals(data, result);- assertEquals(data.length, ((COSInteger) result.getItem(COSName.LENGTH)).longValue());- }-- @Test- @DisplayName("model with dictionary entries copies them onto the stream")- void withDictionary() throws IOException {- Map<String, PdfJsonCosValue> dict = new LinkedHashMap<>();- dict.put(- "Type",- PdfJsonCosValue.builder()- .type(PdfJsonCosValue.Type.NAME)- .value("XObject")- .build());- dict.put(- "Width",- PdfJsonCosValue.builder()- .type(PdfJsonCosValue.Type.INTEGER)- .value(100L)- .build());- PdfJsonStream model = PdfJsonStream.builder().dictionary(dict).build();-- COSStream result = mapper.buildStreamFromModel(model, document);- assertNotNull(result);- assertEquals(COSName.getPDFName("XObject"), result.getItem(COSName.TYPE));- assertEquals(- 100L, ((COSInteger) result.getItem(COSName.getPDFName("Width"))).longValue());- }-- @Test- @DisplayName("model dictionary entry that deserializes to null is skipped")- void dictionaryEntryNullSkipped() throws IOException {- Map<String, PdfJsonCosValue> dict = new LinkedHashMap<>();- dict.put(- "Bad",- PdfJsonCosValue.builder()- .type(PdfJsonCosValue.Type.NAME)- .value(999L) // non-string -> null- .build());- PdfJsonStream model = PdfJsonStream.builder().dictionary(dict).build();-- COSStream result = mapper.buildStreamFromModel(model, document);- assertNotNull(result);- assertNull(result.getItem(COSName.getPDFName("Bad")));- }-- @Test- @DisplayName("model with null/blank rawData sets Length to zero and writes nothing")- void blankRawData() throws IOException {- PdfJsonStream model = PdfJsonStream.builder().rawData(" ").build();- COSStream result = mapper.buildStreamFromModel(model, document);- assertNotNull(result);- assertEquals(0L, ((COSInteger) result.getItem(COSName.LENGTH)).longValue());- // Blank rawData takes the else-branch: Length is set to 0 but createRawOutputStream()- // is- // never called, so nothing is written. PDFBox cannot open a raw InputStream on a stream- // that was never written to, which is the documented "writes nothing" behaviour.- assertThrows(IOException.class, result::createRawInputStream);- }-- @Test- @DisplayName("model with no rawData sets Length to zero")- void noRawData() throws IOException {- PdfJsonStream model = PdfJsonStream.builder().build();- COSStream result = mapper.buildStreamFromModel(model, document);- assertNotNull(result);- assertEquals(0L, ((COSInteger) result.getItem(COSName.LENGTH)).longValue());- }-- @Test- @DisplayName("model with invalid base64 rawData falls back to empty data")- void invalidBase64RawData() throws IOException {- PdfJsonStream model = PdfJsonStream.builder().rawData("###not-base64###").build();- COSStream result = mapper.buildStreamFromModel(model, document);- assertNotNull(result);- assertEquals(0L, ((COSInteger) result.getItem(COSName.LENGTH)).longValue());- assertStreamRawEquals(new byte[0], result);- }- }-- @Nested- @DisplayName("round trip serialize -> deserialize")- class RoundTripTests {-- @Test- @DisplayName("nested array/dictionary structure survives a round trip")- void nestedStructure() throws IOException {- COSDictionary original = new COSDictionary();- original.setItem(COSName.getPDFName("Int"), COSInteger.get(11L));- original.setItem(COSName.getPDFName("Name"), COSName.getPDFName("Hello"));- original.setItem(COSName.getPDFName("Bool"), COSBoolean.FALSE);- COSArray inner = new COSArray();- inner.add(new COSFloat(3.5f));- inner.add(new COSString("abc".getBytes(StandardCharsets.UTF_8)));- original.setItem(COSName.getPDFName("Arr"), inner);-- PdfJsonCosValue serialized = mapper.serializeCosValue(original);- COSBase deserialized = mapper.deserializeCosValue(serialized, document);-- assertInstanceOf(COSDictionary.class, deserialized);- COSDictionary result = (COSDictionary) deserialized;- assertEquals(11L, ((COSInteger) result.getItem(COSName.getPDFName("Int"))).longValue());- assertEquals(COSName.getPDFName("Hello"), result.getItem(COSName.getPDFName("Name")));- assertEquals(COSBoolean.FALSE, result.getItem(COSName.getPDFName("Bool")));-- COSArray resultArr = (COSArray) result.getItem(COSName.getPDFName("Arr"));- assertEquals(2, resultArr.size());- assertEquals(3.5f, ((COSFloat) resultArr.get(0)).floatValue());- assertArrayEquals(- "abc".getBytes(StandardCharsets.UTF_8),- ((COSString) resultArr.get(1)).getBytes());- }-- @Test- @DisplayName("stream data survives a round trip")- void streamRoundTrip() throws IOException {- byte[] data = "round-trip-stream".getBytes(StandardCharsets.UTF_8);- COSStream cosStream = newCosStreamWithData(data);- cosStream.setItem(COSName.TYPE, COSName.getPDFName("XObject"));-- PdfJsonCosValue serialized = mapper.serializeCosValue(cosStream);- COSBase deserialized = mapper.deserializeCosValue(serialized, document);-- assertInstanceOf(COSStream.class, deserialized);- COSStream result = (COSStream) deserialized;- assertStreamRawEquals(data, result);- assertEquals(COSName.getPDFName("XObject"), result.getItem(COSName.TYPE));- }- }-- // Reads the raw (undecoded) bytes from a COSStream and asserts equality.- private void assertStreamRawEquals(byte[] expected, COSStream cosStream) throws IOException {- try (InputStream in = cosStream.createRawInputStream()) {- byte[] actual = in.readAllBytes();- assertArrayEquals(expected, actual);- }- }-}diff --git a/app/core/src/test/java/stirling/software/SPDF/service/PdfJsonFallbackFontServiceTest.java b/app/core/src/test/java/stirling/software/SPDF/service/PdfJsonFallbackFontServiceTest.javadeleted file mode 100644index c39f79ce2c..0000000000--- a/app/core/src/test/java/stirling/software/SPDF/service/PdfJsonFallbackFontServiceTest.java+++ /dev/null@@ -1,571 +0,0 @@-package stirling.software.SPDF.service;--import static org.junit.jupiter.api.Assertions.assertEquals;-import static org.junit.jupiter.api.Assertions.assertFalse;-import static org.junit.jupiter.api.Assertions.assertNotNull;-import static org.junit.jupiter.api.Assertions.assertNull;-import static org.junit.jupiter.api.Assertions.assertSame;-import static org.junit.jupiter.api.Assertions.assertThrows;-import static org.junit.jupiter.api.Assertions.assertTrue;-import static org.mockito.Mockito.lenient;-import static org.mockito.Mockito.mock;-import static org.mockito.Mockito.when;--import java.io.IOException;-import java.lang.reflect.Method;-import java.util.Base64;--import org.apache.pdfbox.pdmodel.PDDocument;-import org.apache.pdfbox.pdmodel.font.PDFont;-import org.apache.pdfbox.pdmodel.font.PDType0Font;-import org.apache.pdfbox.pdmodel.font.PDType3Font;-import org.junit.jupiter.api.AfterAll;-import org.junit.jupiter.api.BeforeAll;-import org.junit.jupiter.api.BeforeEach;-import org.junit.jupiter.api.DisplayName;-import org.junit.jupiter.api.Nested;-import org.junit.jupiter.api.Test;-import org.springframework.core.io.DefaultResourceLoader;-import org.springframework.core.io.ResourceLoader;-import org.springframework.test.util.ReflectionTestUtils;--import stirling.software.SPDF.model.json.PdfJsonFont;-import stirling.software.common.model.ApplicationProperties;--class PdfJsonFallbackFontServiceTest {-- private PdfJsonFallbackFontService service;- private ApplicationProperties applicationProperties;-- // Parsing the real fallback TrueType fonts (the CJK font alone is ~17 MB) is the only expensive- // work in this class. Build a default-config service and parse the CJK fallback once, then- // reuse- // them across every read-only test instead of re-parsing per @BeforeEach.- private static PdfJsonFallbackFontService sharedService;- private static PDDocument sharedCjkDocument;- private static PDFont sharedCjkFont;-- @BeforeAll- static void setUpShared() throws Exception {- // Real ApplicationProperties already defaults pdfEditor.fallbackFont to the Noto Sans- // location, so no mocking is needed for the default-config path.- ResourceLoader resourceLoader = new DefaultResourceLoader();- ApplicationProperties props = new ApplicationProperties();- sharedService = new PdfJsonFallbackFontService(resourceLoader, props);- ReflectionTestUtils.setField(- sharedService,- "legacyFallbackFontLocation",- PdfJsonFallbackFontService.DEFAULT_FALLBACK_FONT_LOCATION);- Method loadConfig = PdfJsonFallbackFontService.class.getDeclaredMethod("loadConfig");- loadConfig.setAccessible(true);- loadConfig.invoke(sharedService);-- // Parse the large CJK fallback exactly once; the CanEncode tests only read this font.- sharedCjkDocument = new PDDocument();- sharedCjkFont =- sharedService.loadFallbackPdfFont(- sharedCjkDocument, PdfJsonFallbackFontService.FALLBACK_FONT_CJK_ID);- }-- @AfterAll- static void tearDownShared() throws IOException {- if (sharedCjkDocument != null) {- sharedCjkDocument.close();- }- }-- @BeforeEach- void setUp() {- // Real resource loader resolves the classpath:/static/fonts/*.ttf bundled in the module.- ResourceLoader resourceLoader = new DefaultResourceLoader();-- // Mock the properties chain so loadConfig() resolves to the default Noto Sans location.- applicationProperties = mock(ApplicationProperties.class);- ApplicationProperties.PdfEditor pdfEditor = mock(ApplicationProperties.PdfEditor.class);- lenient().when(applicationProperties.getPdfEditor()).thenReturn(pdfEditor);- lenient()- .when(pdfEditor.getFallbackFont())- .thenReturn(PdfJsonFallbackFontService.DEFAULT_FALLBACK_FONT_LOCATION);-- service = new PdfJsonFallbackFontService(resourceLoader, applicationProperties);- // The @Value field is normally injected by Spring; set it explicitly for the unit test.- ReflectionTestUtils.setField(- service,- "legacyFallbackFontLocation",- PdfJsonFallbackFontService.DEFAULT_FALLBACK_FONT_LOCATION);- }-- /** Invoke the private @PostConstruct loadConfig() to populate fallbackFontLocation. */- private void invokeLoadConfig() throws Exception {- Method loadConfig = PdfJsonFallbackFontService.class.getDeclaredMethod("loadConfig");- loadConfig.setAccessible(true);- loadConfig.invoke(service);- }-- @Nested- @DisplayName("loadConfig (@PostConstruct)")- class LoadConfig {-- @Test- @DisplayName("uses the configured pdf-editor fallback font when set")- void usesConfiguredFallbackFont() throws Exception {- when(applicationProperties.getPdfEditor().getFallbackFont())- .thenReturn("classpath:/static/fonts/DejaVuSans.ttf");-- invokeLoadConfig();-- assertEquals(- "classpath:/static/fonts/DejaVuSans.ttf",- ReflectionTestUtils.getField(service, "fallbackFontLocation"));- }-- @Test- @DisplayName("falls back to the legacy @Value location when configured value is blank")- void fallsBackToLegacyWhenBlank() throws Exception {- when(applicationProperties.getPdfEditor().getFallbackFont()).thenReturn(" ");-- invokeLoadConfig();-- assertEquals(- PdfJsonFallbackFontService.DEFAULT_FALLBACK_FONT_LOCATION,- ReflectionTestUtils.getField(service, "fallbackFontLocation"));- }-- @Test- @DisplayName("falls back to the legacy @Value location when PdfEditor is null")- void fallsBackToLegacyWhenPdfEditorNull() throws Exception {- when(applicationProperties.getPdfEditor()).thenReturn(null);-- invokeLoadConfig();-- assertEquals(- PdfJsonFallbackFontService.DEFAULT_FALLBACK_FONT_LOCATION,- ReflectionTestUtils.getField(service, "fallbackFontLocation"));- }- }-- @Nested- @DisplayName("resolveFallbackFontId(int codePoint)")- class ResolveByCodePoint {-- @Test- @DisplayName("Latin letters resolve to the generic Noto Sans fallback")- void latinResolvesToNotoSans() {- assertEquals(- PdfJsonFallbackFontService.FALLBACK_FONT_ID,- service.resolveFallbackFontId('A'));- }-- @Test- @DisplayName("CJK unified ideographs resolve to the CJK fallback")- void cjkIdeographResolvesToCjk() {- // U+4E2D (中) is a CJK Unified Ideograph.- assertEquals(- PdfJsonFallbackFontService.FALLBACK_FONT_CJK_ID,- service.resolveFallbackFontId(0x4E2D));- }-- @Test- @DisplayName("Bopomofo resolves to the Traditional Chinese fallback")- void bopomofoResolvesToTc() {- // U+3105 (ㄅ) is in the Bopomofo block.- assertEquals(- PdfJsonFallbackFontService.FALLBACK_FONT_TC_ID,- service.resolveFallbackFontId(0x3105));- }-- @Test- @DisplayName("CJK compatibility ideographs resolve to the Traditional Chinese fallback")- void compatibilityIdeographResolvesToTc() {- // U+F900 is in the CJK Compatibility Ideographs block.- assertEquals(- PdfJsonFallbackFontService.FALLBACK_FONT_TC_ID,- service.resolveFallbackFontId(0xF900));- }-- @Test- @DisplayName("Hiragana resolves to the Japanese fallback")- void hiraganaResolvesToJp() {- // U+3042 (あ) is Hiragana.- assertEquals(- PdfJsonFallbackFontService.FALLBACK_FONT_JP_ID,- service.resolveFallbackFontId(0x3042));- }-- @Test- @DisplayName("Hangul resolves to the Korean fallback")- void hangulResolvesToKr() {- // U+AC00 (가) is a Hangul syllable.- assertEquals(- PdfJsonFallbackFontService.FALLBACK_FONT_KR_ID,- service.resolveFallbackFontId(0xAC00));- }-- @Test- @DisplayName("Arabic resolves to the Arabic fallback")- void arabicResolvesToAr() {- // U+0627 (ا) is Arabic.- assertEquals(- PdfJsonFallbackFontService.FALLBACK_FONT_AR_ID,- service.resolveFallbackFontId(0x0627));- }-- @Test- @DisplayName("Thai resolves to the Thai fallback")- void thaiResolvesToTh() {- // U+0E01 (ก) is Thai.- assertEquals(- PdfJsonFallbackFontService.FALLBACK_FONT_TH_ID,- service.resolveFallbackFontId(0x0E01));- }-- @Test- @DisplayName("Devanagari resolves to the Devanagari fallback")- void devanagariResolves() {- // U+0905 (अ) is Devanagari.- assertEquals(- PdfJsonFallbackFontService.FALLBACK_FONT_DEVANAGARI_ID,- service.resolveFallbackFontId(0x0905));- }-- @Test- @DisplayName("Malayalam resolves to the Malayalam fallback")- void malayalamResolves() {- // U+0D05 (അ) is Malayalam.- assertEquals(- PdfJsonFallbackFontService.FALLBACK_FONT_MALAYALAM_ID,- service.resolveFallbackFontId(0x0D05));- }-- @Test- @DisplayName("Tibetan resolves to the Tibetan fallback")- void tibetanResolves() {- // U+0F40 (ཀ) is Tibetan.- assertEquals(- PdfJsonFallbackFontService.FALLBACK_FONT_TIBETAN_ID,- service.resolveFallbackFontId(0x0F40));- }- }-- @Nested- @DisplayName("resolveFallbackFontId(String fontName, int codePoint)")- class ResolveByNameAndCodePoint {-- @Test- @DisplayName("Arial maps to Liberation Sans")- void arialMapsToLiberationSans() {- assertEquals("fallback-liberation-sans", service.resolveFallbackFontId("Arial", 'A'));- }-- @Test- @DisplayName("Times New Roman maps to Liberation Serif")- void timesNewRomanMapsToLiberationSerif() {- // Spaces are stripped: "Times New Roman" -> "timesnewroman".- assertEquals(- "fallback-liberation-serif",- service.resolveFallbackFontId("Times New Roman", 'A'));- }-- @Test- @DisplayName("Courier New maps to Liberation Mono")- void courierNewMapsToLiberationMono() {- assertEquals(- "fallback-liberation-mono", service.resolveFallbackFontId("Courier New", 'A'));- }-- @Test- @DisplayName("Arial-Bold maps to bold Liberation Sans variant")- void arialBoldMapsToBoldVariant() {- assertEquals(- "fallback-liberation-sans-bold",- service.resolveFallbackFontId("Arial-Bold", 'A'));- }-- @Test- @DisplayName("Arial-Italic maps to italic Liberation Sans variant")- void arialItalicMapsToItalicVariant() {- assertEquals(- "fallback-liberation-sans-italic",- service.resolveFallbackFontId("Arial-Italic", 'A'));- }-- @Test- @DisplayName("Arial-BoldItalic maps to bold-italic Liberation Sans variant")- void arialBoldItalicMapsToBoldItalicVariant() {- assertEquals(- "fallback-liberation-sans-bolditalic",- service.resolveFallbackFontId("Arial-BoldItalic", 'A'));- }-- @Test- @DisplayName("numeric weight 700 is detected as bold")- void numericWeightDetectedAsBold() {- // "Arimo_700wght" -> base "arimo" -> liberation-sans, bold via 700 weight pattern.- assertEquals(- "fallback-liberation-sans-bold",- service.resolveFallbackFontId("Arimo_700wght", 'A'));- }-- @Test- @DisplayName("subset prefix is stripped before alias matching")- void subsetPrefixStripped() {- // "ABCDEF+Arial" -> subset prefix removed -> "arial".- assertEquals(- "fallback-liberation-sans", service.resolveFallbackFontId("ABCDEF+Arial", 'A'));- }-- @Test- @DisplayName("DejaVu Sans bold-italic uses the 'oblique' naming convention")- void dejaVuUsesObliqueNaming() {- assertEquals(- "fallback-dejavu-sans-boldoblique",- service.resolveFallbackFontId("DejaVuSans-BoldItalic", 'A'));- }-- @Test- @DisplayName("DejaVu Serif italic keeps the 'italic' naming convention")- void dejaVuSerifKeepsItalicNaming() {- assertEquals(- "fallback-dejavu-serif-italic",- service.resolveFallbackFontId("DejaVuSerif-Italic", 'A'));- }-- @Test- @DisplayName("Traditional Chinese aliased name ignores weight/style suffix (unsupported)")- void tcAliasIgnoresWeightStyle() {- // MingLiU maps to fallback-noto-tc, which has no bold variant registered.- assertEquals(- PdfJsonFallbackFontService.FALLBACK_FONT_TC_ID,- service.resolveFallbackFontId("MingLiU-Bold", 'A'));- }-- @Test- @DisplayName("Simplified Chinese aliased name maps to the CJK fallback")- void simsunMapsToCjk() {- assertEquals(- PdfJsonFallbackFontService.FALLBACK_FONT_CJK_ID,- service.resolveFallbackFontId("SimSun", 'A'));- }-- @Test- @DisplayName("null font name falls through to Unicode-based resolution")- void nullNameFallsThroughToUnicode() {- assertEquals(- PdfJsonFallbackFontService.FALLBACK_FONT_ID,- service.resolveFallbackFontId(null, 'A'));- }-- @Test- @DisplayName("empty font name falls through to Unicode-based resolution")- void emptyNameFallsThroughToUnicode() {- assertEquals(- PdfJsonFallbackFontService.FALLBACK_FONT_CJK_ID,- service.resolveFallbackFontId("", 0x4E2D));- }-- @Test- @DisplayName("unknown font name falls through to Unicode-based resolution")- void unknownNameFallsThroughToUnicode() {- assertEquals(- PdfJsonFallbackFontService.FALLBACK_FONT_JP_ID,- service.resolveFallbackFontId("SomeCustomFont", 0x3042));- }- }-- @Nested- @DisplayName("mapUnsupportedGlyph(int codePoint)")- class MapUnsupportedGlyph {-- @Test- @DisplayName("U+276E maps to '<'")- void heavyLeftAngleMapsToLessThan() {- assertEquals("<", service.mapUnsupportedGlyph(0x276E));- }-- @Test- @DisplayName("U+276F maps to '>'")- void heavyRightAngleMapsToGreaterThan() {- assertEquals(">", service.mapUnsupportedGlyph(0x276F));- }-- @Test- @DisplayName("unmapped code point returns null")- void unmappedReturnsNull() {- assertNull(service.mapUnsupportedGlyph('A'));- }- }-- @Nested- @DisplayName("canEncode / canEncodeFully")- class CanEncode {-- @Test- @DisplayName("null font returns false")- void nullFontReturnsFalse() {- assertFalse(service.canEncode((PDFont) null, "A"));- }-- @Test- @DisplayName("null text returns false")- void nullTextReturnsFalse() {- // Reuse the once-parsed CJK fallback; canEncode only reads the font.- assertFalse(sharedService.canEncode(sharedCjkFont, (String) null));- }-- @Test- @DisplayName("empty text returns false")- void emptyTextReturnsFalse() {- assertFalse(sharedService.canEncode(sharedCjkFont, ""));- }-- @Test- @DisplayName("PDType3Font always returns false")- void type3FontReturnsFalse() {- PDType3Font type3 = mock(PDType3Font.class);- assertFalse(service.canEncode(type3, "A"));- }-- @Test- @DisplayName("loaded TrueType fallback can encode basic Latin")- void loadedFontEncodesLatin() {- assertTrue(sharedService.canEncode(sharedCjkFont, "Hello"));- }-- @Test- @DisplayName("canEncodeFully delegates to canEncode for text")- void canEncodeFullyDelegates() {- assertTrue(sharedService.canEncodeFully(sharedCjkFont, "abc"));- assertFalse(sharedService.canEncodeFully(null, "abc"));- }-- @Test- @DisplayName("canEncode(font, codePoint) returns true for an encodable code point")- void canEncodeCodePointTrue() {- assertTrue(sharedService.canEncode(sharedCjkFont, (int) 'A'));- }-- @Test- @DisplayName("canEncode(font, codePoint) returns false for a null font")- void canEncodeCodePointNullFont() {- assertFalse(service.canEncode((PDFont) null, (int) 'A'));- }- }-- @Nested- @DisplayName("buildFallbackFontModel")- class BuildFallbackFontModel {-- @Test- @DisplayName("builds a model for a built-in CJK font with base64 program bytes")- void buildsCjkModel() throws IOException {- PdfJsonFont model =- service.buildFallbackFontModel(PdfJsonFallbackFontService.FALLBACK_FONT_CJK_ID);-- assertNotNull(model);- assertEquals(PdfJsonFallbackFontService.FALLBACK_FONT_CJK_ID, model.getId());- assertEquals(PdfJsonFallbackFontService.FALLBACK_FONT_CJK_ID, model.getUid());- assertEquals("NotoSansSC-Regular", model.getBaseName());- assertEquals("TrueType", model.getSubtype());- assertEquals(Boolean.TRUE, model.getEmbedded());- assertEquals("ttf", model.getProgramFormat());- assertNotNull(model.getProgram());- // The program must be valid, non-empty base64.- byte[] decoded = Base64.getDecoder().decode(model.getProgram());- assertTrue(decoded.length > 0);- }-- @Test- @DisplayName("no-arg overload builds the default Noto Sans model")- void noArgBuildsDefaultModel() throws Exception {- invokeLoadConfig(); // populate fallbackFontLocation for the default font id- PdfJsonFont model = service.buildFallbackFontModel();-- assertNotNull(model);- assertEquals(PdfJsonFallbackFontService.FALLBACK_FONT_ID, model.getId());- assertEquals("NotoSans-Regular", model.getBaseName());- assertEquals("ttf", model.getProgramFormat());- assertNotNull(model.getProgram());- }-- @Test- @DisplayName("unknown fallback id throws IOException")- void unknownIdThrows() {- IOException ex =- assertThrows(- IOException.class,- () -> service.buildFallbackFontModel("does-not-exist"));- assertTrue(ex.getMessage().contains("Unknown fallback font id"));- }-- @Test- @DisplayName("font bytes are cached and reused across calls")- void fontBytesAreCached() throws IOException {- PdfJsonFont first =- service.buildFallbackFontModel(PdfJsonFallbackFontService.FALLBACK_FONT_TH_ID);- PdfJsonFont second =- service.buildFallbackFontModel(PdfJsonFallbackFontService.FALLBACK_FONT_TH_ID);- // Same cached bytes -> identical base64 program payload.- assertEquals(first.getProgram(), second.getProgram());- }- }-- @Nested- @DisplayName("loadFallbackPdfFont")- class LoadFallbackPdfFont {-- @Test- @DisplayName("loads a Type0 PDFont for a built-in fallback id")- void loadsType0Font() throws IOException {- try (PDDocument document = new PDDocument()) {- PDFont font =- service.loadFallbackPdfFont(- document, PdfJsonFallbackFontService.FALLBACK_FONT_AR_ID);- assertNotNull(font);- assertTrue(font instanceof PDType0Font);- }- }-- @Test- @DisplayName("no-arg overload loads the default Noto Sans font")- void noArgLoadsDefaultFont() throws Exception {- invokeLoadConfig();- try (PDDocument document = new PDDocument()) {- PDFont font = service.loadFallbackPdfFont(document);- assertNotNull(font);- assertTrue(font instanceof PDType0Font);- }- }-- @Test- @DisplayName("unknown fallback id throws IOException")- void unknownIdThrows() throws IOException {- try (PDDocument document = new PDDocument()) {- IOException ex =- assertThrows(- IOException.class,- () -> service.loadFallbackPdfFont(document, "nope"));- assertTrue(ex.getMessage().contains("Unknown fallback font id"));- }- }-- @Test- @DisplayName("loaded font produces fresh instances per call but identical type")- void distinctInstancesPerCall() throws IOException {- // Instance-identity contract holds for any built-in font; use the tiny Thai fallback- // (~22 KB) instead of the multi-MB Korean font to keep two loads cheap.- try (PDDocument document = new PDDocument()) {- PDFont a =- service.loadFallbackPdfFont(- document, PdfJsonFallbackFontService.FALLBACK_FONT_TH_ID);- PDFont b =- service.loadFallbackPdfFont(- document, PdfJsonFallbackFontService.FALLBACK_FONT_TH_ID);- assertNotNull(a);- assertNotNull(b);- // Two independent PDType0Font wrappers loaded into the same document.- assertFalse(a == b);- assertSame(a.getClass(), b.getClass());- }- }- }-}diff --git a/app/core/src/test/java/stirling/software/SPDF/service/pdfjson/PdfJsonFontServiceMoreTest.java b/app/core/src/test/java/stirling/software/SPDF/service/pdfjson/PdfJsonFontServiceMoreTest.javadeleted file mode 100644index 3b117f4686..0000000000--- a/app/core/src/test/java/stirling/software/SPDF/service/pdfjson/PdfJsonFontServiceMoreTest.java+++ /dev/null@@ -1,577 +0,0 @@-package stirling.software.SPDF.service.pdfjson;--import static org.assertj.core.api.Assertions.assertThat;-import static org.junit.jupiter.api.Assertions.*;-import static org.mockito.Mockito.*;--import java.io.File;-import java.lang.reflect.Field;-import java.lang.reflect.Method;-import java.nio.charset.StandardCharsets;-import java.nio.file.Files;-import java.util.Base64;-import java.util.List;--import org.junit.jupiter.api.BeforeEach;-import org.junit.jupiter.api.DisplayName;-import org.junit.jupiter.api.Nested;-import org.junit.jupiter.api.Test;-import org.mockito.MockedStatic;--import stirling.software.common.model.ApplicationProperties;-import stirling.software.common.util.ProcessExecutor;-import stirling.software.common.util.ProcessExecutor.ProcessExecutorResult;-import stirling.software.common.util.TempFileManager;--/**- * Gap coverage for PdfJsonFontService - exercises loadConfiguration, isCommandAvailable,- * buildPythonCommand, the method-dispatch branches and the Python / FontForge conversion bodies- * (configured / unconfigured / rc!=0 / success) with a mocked ProcessExecutor.- */-class PdfJsonFontServiceMoreTest {-- private static final byte[] CFF_HEADER = {1, 0, 4, 1};-- private TempFileManager tempFileManager;- private ApplicationProperties applicationProperties;- private PdfJsonFontService service;-- @BeforeEach- void setUp() {- tempFileManager = mock(TempFileManager.class);- applicationProperties = mock(ApplicationProperties.class);- service = new PdfJsonFontService(tempFileManager, applicationProperties);- }-- private void setField(String name, Object value) throws Exception {- Field f = PdfJsonFontService.class.getDeclaredField(name);- f.setAccessible(true);- f.set(service, value);- }-- private Object invoke(String method, Class<?>[] sig, Object... args) throws Exception {- Method m = PdfJsonFontService.class.getDeclaredMethod(method, sig);- m.setAccessible(true);- return m.invoke(service, args);- }-- private void stubRealTempFiles() throws Exception {- when(tempFileManager.createTempFile(anyString()))- .thenAnswer(- inv -> {- String suffix = inv.getArgument(0);- File f = Files.createTempFile("fontsvc-test", suffix).toFile();- f.deleteOnExit();- return f;- });- }-- @Nested- @DisplayName("loadConfiguration / initialise")- class Configuration {-- @Test- @DisplayName("real enabled config populates fields and checks availability")- void initialise_enabledConfig() throws Exception {- ApplicationProperties props = new ApplicationProperties();- // defaults: cffConverter.enabled = true, method = python- PdfJsonFontService svc = new PdfJsonFontService(tempFileManager, props);-- Method m =- PdfJsonFontService.class.getDeclaredMethod(- "initialiseCffConverterAvailability");- m.setAccessible(true);- m.invoke(svc);-- assertTrue(svc.isCffConversionEnabled());- assertEquals("python", svc.getCffConverterMethod());- }-- @Test- @DisplayName("disabled config short-circuits availability checks")- void initialise_disabledConfig() throws Exception {- ApplicationProperties props = new ApplicationProperties();- props.getPdfEditor().getCffConverter().setEnabled(false);- PdfJsonFontService svc = new PdfJsonFontService(tempFileManager, props);-- Method m =- PdfJsonFontService.class.getDeclaredMethod(- "initialiseCffConverterAvailability");- m.setAccessible(true);- m.invoke(svc);-- assertFalse(svc.isCffConversionEnabled());- }-- @Test- @DisplayName("null pdfEditor config disables CFF conversion")- void loadConfiguration_nullPdfEditor() throws Exception {- when(applicationProperties.getPdfEditor()).thenReturn(null);- invoke("loadConfiguration", new Class<?>[] {});- assertFalse(service.isCffConversionEnabled());- }- }-- @Nested- @DisplayName("isCommandAvailable")- class CommandAvailability {-- @Test- @DisplayName("null or blank command returns false")- void nullOrBlank_false() throws Exception {- assertEquals(- false,- invoke("isCommandAvailable", new Class<?>[] {String.class}, (Object) null));- assertEquals(false, invoke("isCommandAvailable", new Class<?>[] {String.class}, " "));- }-- @Test- @DisplayName("non-existent command returns false")- void nonExistent_false() throws Exception {- assertEquals(- false,- invoke(- "isCommandAvailable",- new Class<?>[] {String.class},- "definitely-not-a-real-command-xyz123"));- }- }-- @Nested- @DisplayName("buildPythonCommand")- class BuildPythonCommand {-- @Test- @DisplayName("without toUnicode produces 6-element command")- void withoutToUnicode() throws Exception {- setField("pythonCommand", "python3");- setField("pythonScript", "/script.py");- String[] cmd =- (String[])- invoke(- "buildPythonCommand",- new Class<?>[] {String.class, String.class, String.class},- "in.cff",- "out.otf",- null);- assertThat(cmd)- .containsExactly(- "python3", "/script.py", "--input", "in.cff", "--output", "out.otf");- }-- @Test- @DisplayName("with toUnicode appends --to-unicode")- void withToUnicode() throws Exception {- setField("pythonCommand", "python3");- setField("pythonScript", "/script.py");- String[] cmd =- (String[])- invoke(- "buildPythonCommand",- new Class<?>[] {String.class, String.class, String.class},- "in.cff",- "out.otf",- "uni.txt");- assertThat(cmd).contains("--to-unicode", "uni.txt");- assertEquals(8, cmd.length);- }- }-- @Nested- @DisplayName("convertCffProgramToTrueType dispatch")- class Dispatch {-- @Test- @DisplayName("python method, available, rc!=0 returns null")- void pythonMethod_rcFailure() throws Exception {- setField("cffConversionEnabled", true);- setField("cffConverterMethod", "python");- setField("pythonCffConverterAvailable", true);- setField("pythonCommand", "python3");- setField("pythonScript", "/script.py");- stubRealTempFiles();-- try (MockedStatic<ProcessExecutor> mocked = mockStatic(ProcessExecutor.class)) {- ProcessExecutor exec = mock(ProcessExecutor.class);- ProcessExecutorResult result = mock(ProcessExecutorResult.class);- when(result.getRc()).thenReturn(1);- when(result.getMessages()).thenReturn("boom");- when(exec.runCommandWithOutputHandling(anyList())).thenReturn(result);- mocked.when(- () ->- ProcessExecutor.getInstance(- ProcessExecutor.Processes.CFF_CONVERTER))- .thenReturn(exec);-- assertNull(service.convertCffProgramToTrueType(new byte[] {1, 2, 3}, null));- }- }-- @Test- @DisplayName("python method success returns produced bytes")- void pythonMethod_success() throws Exception {- setField("cffConversionEnabled", true);- setField("cffConverterMethod", "python");- setField("pythonCffConverterAvailable", true);- setField("pythonCommand", "python3");- setField("pythonScript", "/script.py");-- // Capture the .otf temp file so the mocked process can populate it.- File[] otfHolder = new File[1];- when(tempFileManager.createTempFile(anyString()))- .thenAnswer(- inv -> {- String suffix = inv.getArgument(0);- File f = Files.createTempFile("fontsvc-test", suffix).toFile();- f.deleteOnExit();- if (".otf".equals(suffix)) {- otfHolder[0] = f;- }- return f;- });-- try (MockedStatic<ProcessExecutor> mocked = mockStatic(ProcessExecutor.class)) {- ProcessExecutor exec = mock(ProcessExecutor.class);- ProcessExecutorResult result = mock(ProcessExecutorResult.class);- when(result.getRc()).thenReturn(0);- when(exec.runCommandWithOutputHandling(anyList()))- .thenAnswer(- inv -> {- Files.write(- otfHolder[0].toPath(),- new byte[] {- (byte) 0x4F, (byte) 0x54, (byte) 0x54, (byte) 0x4F- });- return result;- });- mocked.when(- () ->- ProcessExecutor.getInstance(- ProcessExecutor.Processes.CFF_CONVERTER))- .thenReturn(exec);-- byte[] out = service.convertCffProgramToTrueType(new byte[] {1, 2, 3}, null);- assertNotNull(out);- assertEquals(4, out.length);- }- }-- @Test- @DisplayName("python conversion decodes toUnicode base64; invalid base64 returns null")- void pythonMethod_invalidToUnicode() throws Exception {- setField("cffConversionEnabled", true);- setField("cffConverterMethod", "python");- setField("pythonCffConverterAvailable", true);- setField("pythonCommand", "python3");- setField("pythonScript", "/script.py");- stubRealTempFiles();-- // No ProcessExecutor mock needed: decode fails before exec is reached.- byte[] out = service.convertCffProgramToTrueType(new byte[] {1, 2, 3}, "@@@notbase64");- assertNull(out);- }-- @Test- @DisplayName("python conversion succeeds with valid toUnicode payload")- void pythonMethod_validToUnicode() throws Exception {- setField("cffConversionEnabled", true);- setField("cffConverterMethod", "python");- setField("pythonCffConverterAvailable", true);- setField("pythonCommand", "python3");- setField("pythonScript", "/script.py");-- File[] otfHolder = new File[1];- when(tempFileManager.createTempFile(anyString()))- .thenAnswer(- inv -> {- String suffix = inv.getArgument(0);- File f = Files.createTempFile("fontsvc-test", suffix).toFile();- f.deleteOnExit();- if (".otf".equals(suffix)) {- otfHolder[0] = f;- }- return f;- });-- String toUnicode = Base64.getEncoder().encodeToString(new byte[] {10, 20, 30});-- try (MockedStatic<ProcessExecutor> mocked = mockStatic(ProcessExecutor.class)) {- ProcessExecutor exec = mock(ProcessExecutor.class);- ProcessExecutorResult result = mock(ProcessExecutorResult.class);- when(result.getRc()).thenReturn(0);- when(exec.runCommandWithOutputHandling(anyList()))- .thenAnswer(- inv -> {- Files.write(otfHolder[0].toPath(), new byte[] {1, 2, 3, 4, 5});- return result;- });- mocked.when(- () ->- ProcessExecutor.getInstance(- ProcessExecutor.Processes.CFF_CONVERTER))- .thenReturn(exec);-- byte[] out = service.convertCffProgramToTrueType(new byte[] {9, 9}, toUnicode);- assertNotNull(out);- assertEquals(5, out.length);- }- }-- @Test- @DisplayName("fontforge method, available, rc!=0 returns null")- void fontForgeMethod_rcFailure() throws Exception {- setField("cffConversionEnabled", true);- setField("cffConverterMethod", "fontforge");- setField("fontForgeCffConverterAvailable", true);- setField("fontforgeCommand", "fontforge");- stubRealTempFiles();-- try (MockedStatic<ProcessExecutor> mocked = mockStatic(ProcessExecutor.class)) {- ProcessExecutor exec = mock(ProcessExecutor.class);- ProcessExecutorResult result = mock(ProcessExecutorResult.class);- when(result.getRc()).thenReturn(2);- when(exec.runCommandWithOutputHandling(anyList())).thenReturn(result);- mocked.when(- () ->- ProcessExecutor.getInstance(- ProcessExecutor.Processes.CFF_CONVERTER))- .thenReturn(exec);-- assertNull(service.convertCffProgramToTrueType(CFF_HEADER, null));- }- }-- @Test- @DisplayName("fontforge method success returns produced bytes")- void fontForgeMethod_success() throws Exception {- setField("cffConversionEnabled", true);- setField("cffConverterMethod", "fontforge");- setField("fontForgeCffConverterAvailable", true);- setField("fontforgeCommand", "fontforge");-- File[] ttfHolder = new File[1];- when(tempFileManager.createTempFile(anyString()))- .thenAnswer(- inv -> {- String suffix = inv.getArgument(0);- File f = Files.createTempFile("fontsvc-test", suffix).toFile();- f.deleteOnExit();- if (".ttf".equals(suffix)) {- ttfHolder[0] = f;- }- return f;- });-- try (MockedStatic<ProcessExecutor> mocked = mockStatic(ProcessExecutor.class)) {- ProcessExecutor exec = mock(ProcessExecutor.class);- ProcessExecutorResult result = mock(ProcessExecutorResult.class);- when(result.getRc()).thenReturn(0);- when(exec.runCommandWithOutputHandling(anyList()))- .thenAnswer(- inv -> {- Files.write(ttfHolder[0].toPath(), new byte[] {7, 7, 7});- return result;- });- mocked.when(- () ->- ProcessExecutor.getInstance(- ProcessExecutor.Processes.CFF_CONVERTER))- .thenReturn(exec);-- byte[] out = service.convertCffProgramToTrueType(CFF_HEADER, null);- assertNotNull(out);- assertEquals(3, out.length);- }- }- }-- @Nested- @DisplayName("convertCffUsingPython direct guards")- class PythonGuards {-- @Test- @DisplayName("not available returns null")- void notAvailable() throws Exception {- setField("pythonCffConverterAvailable", false);- assertNull(- invoke(- "convertCffUsingPython",- new Class<?>[] {byte[].class, String.class},- new byte[] {1},- null));- }-- @Test- @DisplayName("blank command/script returns null")- void notConfigured() throws Exception {- setField("pythonCffConverterAvailable", true);- setField("pythonCommand", " ");- setField("pythonScript", "");- assertNull(- invoke(- "convertCffUsingPython",- new Class<?>[] {byte[].class, String.class},- new byte[] {1},- null));- }- }-- @Nested- @DisplayName("convertCffUsingFontForge direct guard")- class FontForgeGuard {-- @Test- @DisplayName("not available returns null")- void notAvailable() throws Exception {- setField("fontForgeCffConverterAvailable", false);- assertNull(service.convertCffUsingFontForge(new byte[] {1, 2, 3}));- }-- @Test- @DisplayName("rc==0 but no output file returns null")- void noOutputFile() throws Exception {- setField("fontForgeCffConverterAvailable", true);- setField("fontforgeCommand", "fontforge");- // createTempFile returns a file that we then delete so it does not exist.- when(tempFileManager.createTempFile(anyString()))- .thenAnswer(- inv -> {- File f =- Files.createTempFile("fontsvc-test", inv.getArgument(0))- .toFile();- if (".ttf".equals(inv.getArgument(0))) {- Files.deleteIfExists(f.toPath());- }- return f;- });-- try (MockedStatic<ProcessExecutor> mocked = mockStatic(ProcessExecutor.class)) {- ProcessExecutor exec = mock(ProcessExecutor.class);- ProcessExecutorResult result = mock(ProcessExecutorResult.class);- when(result.getRc()).thenReturn(0);- when(exec.runCommandWithOutputHandling(anyList())).thenReturn(result);- mocked.when(- () ->- ProcessExecutor.getInstance(- ProcessExecutor.Processes.CFF_CONVERTER))- .thenReturn(exec);-- assertNull(service.convertCffUsingFontForge(CFF_HEADER));- }- }-- @Test- @DisplayName("rc==0 but empty output file returns null")- void emptyOutputFile() throws Exception {- setField("fontForgeCffConverterAvailable", true);- setField("fontforgeCommand", "fontforge");- stubRealTempFiles(); // empty 0-byte temp files by default-- try (MockedStatic<ProcessExecutor> mocked = mockStatic(ProcessExecutor.class)) {- ProcessExecutor exec = mock(ProcessExecutor.class);- ProcessExecutorResult result = mock(ProcessExecutorResult.class);- when(result.getRc()).thenReturn(0);- when(exec.runCommandWithOutputHandling(anyList())).thenReturn(result);- mocked.when(- () ->- ProcessExecutor.getInstance(- ProcessExecutor.Processes.CFF_CONVERTER))- .thenReturn(exec);-- assertNull(service.convertCffUsingFontForge(CFF_HEADER));- }- }-- @Test- @DisplayName("input without a CFF header never reaches FontForge")- void nonCffInputRejected() throws Exception {- setField("fontForgeCffConverterAvailable", true);- setField("fontforgeCommand", "fontforge");-- try (MockedStatic<ProcessExecutor> mocked = mockStatic(ProcessExecutor.class)) {- byte[] sfd = "SplineFontDB: 3.2\n".getBytes(StandardCharsets.US_ASCII);- assertNull(service.convertCffUsingFontForge(sfd));- assertNull(service.convertCffUsingFontForge(new byte[] {1, 0, 4}));- assertNull(service.convertCffUsingFontForge(new byte[] {1, 0, 4, 5}));- assertNull(service.convertCffUsingFontForge(new byte[] {1, 2, 3}));- assertNull(service.convertCffUsingFontForge(null));- mocked.verifyNoInteractions();- verifyNoInteractions(tempFileManager);- }- }- }-- @Nested- @DisplayName("isCffFontProgram")- class CffHeader {-- @Test- @DisplayName("accepts CFF headers with hdrSize 4")- void acceptsHeaderSizeFour() {- assertTrue(service.isCffFontProgram(CFF_HEADER));- assertTrue(service.isCffFontProgram(new byte[] {1, 0, 4, 4, 0, 0}));- }-- @Test- @DisplayName("accepts CFF headers with a larger hdrSize and a nonzero minor version")- void acceptsLargerHeaderSize() {- assertTrue(service.isCffFontProgram(new byte[] {1, 0, 5, 1, 0}));- assertTrue(service.isCffFontProgram(new byte[] {1, 1, 8, 2, 0, 0, 0, 0, 0}));- }-- @Test- @DisplayName("rejects a major version other than 1")- void rejectsWrongMajorVersion() {- assertFalse(service.isCffFontProgram(new byte[] {2, 0, 5, 1, 0}));- assertFalse(service.isCffFontProgram(new byte[] {0, 0, 4, 1}));- }-- @Test- @DisplayName("rejects an invalid hdrSize or offSize")- void rejectsInvalidSizes() {- assertFalse(service.isCffFontProgram(new byte[] {1, 0, 3, 1}));- assertFalse(service.isCffFontProgram(new byte[] {1, 0, 8, 1}));- assertFalse(service.isCffFontProgram(new byte[] {1, 0, 4, 0}));- assertFalse(service.isCffFontProgram(new byte[] {1, 0, 4, 5}));- }-- @Test- @DisplayName("rejects FontForge SFD source text")- void rejectsSfd() {- assertFalse(- service.isCffFontProgram(- "SplineFontDB: 3.2\nFontName: X\n"- .getBytes(StandardCharsets.US_ASCII)));- }-- @Test- @DisplayName("rejects empty, short and null input")- void rejectsShortInput() {- assertFalse(service.isCffFontProgram(new byte[0]));- assertFalse(service.isCffFontProgram(new byte[] {1, 0, 4}));- assertFalse(service.isCffFontProgram(null));- }-- @Test- @DisplayName("rejects OpenType and TrueType wrappers")- void rejectsSfntWrappers() {- assertFalse(service.isCffFontProgram(new byte[] {'O', 'T', 'T', 'O', 0, 9, 0, 0}));- assertFalse(service.isCffFontProgram(new byte[] {0, 1, 0, 0, 0, 12}));- }- }-- @Nested- @DisplayName("detect* extra branches")- class DetectExtra {-- @Test- @DisplayName("detectFontFlavor rejects ttcf collections and recognises otf via OTTO")- void detectFlavorExtra() {- assertNull(service.detectFontFlavor(new byte[] {0x74, 0x74, 0x63, 0x66}));- List<byte[]> otfVariants = List.of(new byte[] {0x4F, 0x54, 0x54, 0x4F});- for (byte[] otf : otfVariants) {- assertEquals("otf", service.detectFontFlavor(otf));- }- }- }-}diff --git a/app/core/src/test/java/stirling/software/SPDF/service/pdfjson/PdfJsonFontServiceTest.java b/app/core/src/test/java/stirling/software/SPDF/service/pdfjson/PdfJsonFontServiceTest.javadeleted file mode 100644index ad0ed8b0af..0000000000--- a/app/core/src/test/java/stirling/software/SPDF/service/pdfjson/PdfJsonFontServiceTest.java+++ /dev/null@@ -1,199 +0,0 @@-package stirling.software.SPDF.service.pdfjson;--import static org.junit.jupiter.api.Assertions.*;-import static org.mockito.Mockito.*;--import java.lang.reflect.Field;--import org.junit.jupiter.api.BeforeEach;-import org.junit.jupiter.api.Test;--import stirling.software.common.model.ApplicationProperties;-import stirling.software.common.util.TempFileManager;--class PdfJsonFontServiceTest {-- private PdfJsonFontService service;- private TempFileManager tempFileManager;- private ApplicationProperties applicationProperties;-- @BeforeEach- void setUp() throws Exception {- tempFileManager = mock(TempFileManager.class);- applicationProperties = mock(ApplicationProperties.class);- service = new PdfJsonFontService(tempFileManager, applicationProperties);- }-- // --- detectFontFlavor tests ----- @Test- void detectFontFlavor_nullBytes_returnsNull() {- assertNull(service.detectFontFlavor(null));- }-- @Test- void detectFontFlavor_tooShort_returnsNull() {- assertNull(service.detectFontFlavor(new byte[] {0x00, 0x01}));- }-- @Test- void detectFontFlavor_ttfSignature_returnsTtf() {- byte[] ttf = {0x00, 0x01, 0x00, 0x00};- assertEquals("ttf", service.detectFontFlavor(ttf));- }-- @Test- void detectFontFlavor_trueSignature_returnsTtf() {- // 0x74727565 = "true"- byte[] trueFont = {0x74, 0x72, 0x75, 0x65};- assertEquals("ttf", service.detectFontFlavor(trueFont));- }-- @Test- void detectFontFlavor_otfSignature_returnsOtf() {- // 0x4F54544F = "OTTO"- byte[] otf = {0x4F, 0x54, 0x54, 0x4F};- assertEquals("otf", service.detectFontFlavor(otf));- }-- @Test- void detectFontFlavor_ttcSignature_returnsNull() {- byte[] ttc = {0x74, 0x74, 0x63, 0x66};- assertNull(service.detectFontFlavor(ttc));- }-- @Test- void detectFontFlavor_unknownSignature_returnsNull() {- byte[] unknown = {(byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF};- assertNull(service.detectFontFlavor(unknown));- }-- // --- detectTrueTypeFormat tests ----- @Test- void detectTrueTypeFormat_nullBytes_returnsNull() {- assertNull(service.detectTrueTypeFormat(null));- }-- @Test- void detectTrueTypeFormat_tooShort_returnsNull() {- assertNull(service.detectTrueTypeFormat(new byte[] {0x00}));- }-- @Test- void detectTrueTypeFormat_ttfSignature_returnsTtf() {- byte[] ttf = {0x00, 0x01, 0x00, 0x00};- assertEquals("ttf", service.detectTrueTypeFormat(ttf));- }-- @Test- void detectTrueTypeFormat_otfSignature_returnsOtf() {- byte[] otf = {0x4F, 0x54, 0x54, 0x4F};- assertEquals("otf", service.detectTrueTypeFormat(otf));- }-- @Test- void detectTrueTypeFormat_ttcSignature_returnsNull() {- byte[] ttc = {0x74, 0x74, 0x63, 0x66};- assertNull(service.detectTrueTypeFormat(ttc));- }-- @Test- void detectTrueTypeFormat_unknownSignature_returnsNull() {- byte[] unknown = {(byte) 0xAB, (byte) 0xCD, (byte) 0xEF, 0x01};- assertNull(service.detectTrueTypeFormat(unknown));- }-- // --- validateFontTables tests ----- @Test- void validateFontTables_nullBytes_returnsTooSmall() {- assertEquals("Font program too small", service.validateFontTables(null));- }-- @Test- void validateFontTables_tooShort_returnsTooSmall() {- assertEquals("Font program too small", service.validateFontTables(new byte[11]));- }-- @Test- void validateFontTables_zeroNumTables_returnsInvalid() {- byte[] data = new byte[12];- // bytes 4-5 = 0 -> numTables = 0- String result = service.validateFontTables(data);- assertNotNull(result);- assertTrue(result.contains("Invalid numTables"));- }-- @Test- void validateFontTables_validNumTables_returnsNull() {- byte[] data = new byte[12];- // numTables = 10 at bytes[4..5]- data[4] = 0;- data[5] = 10;- assertNull(service.validateFontTables(data));- }-- @Test- void validateFontTables_tooManyTables_returnsInvalid() {- byte[] data = new byte[12];- // numTables = 513 (> 512)- data[4] = 0x02;- data[5] = 0x01; // 513- String result = service.validateFontTables(data);- assertNotNull(result);- assertTrue(result.contains("Invalid numTables"));- }-- // --- convertCffProgramToTrueType tests ----- @Test- void convertCffProgramToTrueType_disabledConversion_returnsNull() {- // cffConversionEnabled defaults to false since no config loaded- assertNull(service.convertCffProgramToTrueType(new byte[] {1, 2, 3}, null));- }-- @Test- void convertCffProgramToTrueType_nullBytes_returnsNull() {- assertNull(service.convertCffProgramToTrueType(null, null));- }-- @Test- void convertCffProgramToTrueType_emptyBytes_returnsNull() {- assertNull(service.convertCffProgramToTrueType(new byte[0], null));- }-- @Test- void convertCffProgramToTrueType_enabledButPythonNotAvailable_returnsNull() throws Exception {- // Use reflection to set internal state for testing- setField(service, "cffConversionEnabled", true);- setField(service, "cffConverterMethod", "python");- setField(service, "pythonCffConverterAvailable", false);-- assertNull(service.convertCffProgramToTrueType(new byte[] {1, 2, 3}, null));- }-- @Test- void convertCffProgramToTrueType_enabledFontForgeNotAvailable_returnsNull() throws Exception {- setField(service, "cffConversionEnabled", true);- setField(service, "cffConverterMethod", "fontforge");- setField(service, "fontForgeCffConverterAvailable", false);-- assertNull(service.convertCffProgramToTrueType(new byte[] {1, 2, 3}, null));- }-- @Test- void convertCffProgramToTrueType_unknownMethodFallsToPython_returnsNull() throws Exception {- setField(service, "cffConversionEnabled", true);- setField(service, "cffConverterMethod", "unknown");- setField(service, "pythonCffConverterAvailable", false);-- assertNull(service.convertCffProgramToTrueType(new byte[] {1, 2, 3}, null));- }-- private void setField(Object target, String fieldName, Object value) throws Exception {- Field field = target.getClass().getDeclaredField(fieldName);- field.setAccessible(true);- field.set(target, value);- }-}diff --git a/app/core/src/test/java/stirling/software/SPDF/service/pdfjson/PdfJsonImageServiceMoreTest.java b/app/core/src/test/java/stirling/software/SPDF/service/pdfjson/PdfJsonImageServiceMoreTest.javadeleted file mode 100644index 3d84c75275..0000000000--- a/app/core/src/test/java/stirling/software/SPDF/service/pdfjson/PdfJsonImageServiceMoreTest.java+++ /dev/null@@ -1,477 +0,0 @@-package stirling.software.SPDF.service.pdfjson;--import static org.assertj.core.api.Assertions.assertThat;-import static org.junit.jupiter.api.Assertions.*;-import static org.mockito.ArgumentMatchers.any;-import static org.mockito.ArgumentMatchers.anyFloat;-import static org.mockito.Mockito.*;--import java.awt.Color;-import java.awt.image.BufferedImage;-import java.io.ByteArrayOutputStream;-import java.io.IOException;-import java.lang.reflect.Method;-import java.util.Base64;-import java.util.HashMap;-import java.util.List;-import java.util.Map;--import javax.imageio.ImageIO;--import org.apache.pdfbox.pdmodel.PDDocument;-import org.apache.pdfbox.pdmodel.PDPage;-import org.apache.pdfbox.pdmodel.PDPageContentStream;-import org.apache.pdfbox.pdmodel.common.PDRectangle;-import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;-import org.apache.pdfbox.util.Matrix;-import org.junit.jupiter.api.BeforeEach;-import org.junit.jupiter.api.DisplayName;-import org.junit.jupiter.api.Nested;-import org.junit.jupiter.api.Test;--import stirling.software.SPDF.model.json.PdfJsonImageElement;--/**- * Gap coverage for PdfJsonImageService - exercises the real draw / encode / extract paths using a- * genuine PNG image, plus transform / fallback dimension resolution and private helpers.- */-class PdfJsonImageServiceMoreTest {-- private PdfJsonImageService service;-- @BeforeEach- void setUp() {- service = new PdfJsonImageService();- }-- private byte[] pngBytes(int w, int h) throws IOException {- BufferedImage img = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);- for (int x = 0; x < w; x++) {- for (int y = 0; y < h; y++) {- img.setRGB(x, y, Color.RED.getRGB());- }- }- ByteArrayOutputStream baos = new ByteArrayOutputStream();- ImageIO.write(img, "png", baos);- return baos.toByteArray();- }-- private String pngBase64(int w, int h) throws IOException {- return Base64.getEncoder().encodeToString(pngBytes(w, h));- }-- @Nested- @DisplayName("createImageXObject")- class CreateImageXObject {-- @Test- @DisplayName("valid PNG base64 creates a real XObject")- void validPng_returnsXObject() throws IOException {- try (PDDocument doc = new PDDocument()) {- PdfJsonImageElement element = new PdfJsonImageElement();- element.setImageData(pngBase64(4, 3));- element.setId("img-1");-- PDImageXObject xobj = service.createImageXObject(doc, element);- assertNotNull(xobj);- assertEquals(4, xobj.getWidth());- assertEquals(3, xobj.getHeight());- }- }-- @Test- @DisplayName("null id falls back to random UUID name")- void nullId_randomName() throws IOException {- try (PDDocument doc = new PDDocument()) {- PdfJsonImageElement element = new PdfJsonImageElement();- element.setImageData(pngBase64(2, 2));- element.setId(null);-- PDImageXObject xobj = service.createImageXObject(doc, element);- assertNotNull(xobj);- }- }- }-- @Nested- @DisplayName("drawImageElement")- class DrawImageElement {-- @Test- @DisplayName("with 6-element transform draws via matrix")- void withTransform_drawsMatrix() throws IOException {- try (PDDocument doc = new PDDocument()) {- PDPageContentStream cs = mock(PDPageContentStream.class);- PdfJsonImageElement element = new PdfJsonImageElement();- element.setImageData(pngBase64(5, 5));- element.setId("t1");- element.setTransform(new float[] {10f, 0f, 0f, 10f, 20f, 30f});- Map<String, PDImageXObject> cache = new HashMap<>();-- service.drawImageElement(cs, doc, element, cache);-- verify(cs).drawImage(any(PDImageXObject.class), any(Matrix.class));- assertThat(cache).hasSize(1);- }- }-- @Test- @DisplayName("transform with NaN values falls back to safe defaults")- void withNaNTransform_usesSafeFloat() throws IOException {- try (PDDocument doc = new PDDocument()) {- PDPageContentStream cs = mock(PDPageContentStream.class);- PdfJsonImageElement element = new PdfJsonImageElement();- element.setImageData(pngBase64(5, 5));- element.setId("t-nan");- element.setTransform(- new float[] {Float.NaN, 0f, 0f, Float.POSITIVE_INFINITY, 0f, 0f});- Map<String, PDImageXObject> cache = new HashMap<>();-- service.drawImageElement(cs, doc, element, cache);-- verify(cs).drawImage(any(PDImageXObject.class), any(Matrix.class));- }- }-- @Test- @DisplayName("without transform uses explicit width/height/left/bottom")- void withoutTransform_explicitDims() throws IOException {- try (PDDocument doc = new PDDocument()) {- PDPageContentStream cs = mock(PDPageContentStream.class);- PdfJsonImageElement element = new PdfJsonImageElement();- element.setImageData(pngBase64(5, 5));- element.setId("d1");- element.setWidth(50f);- element.setHeight(40f);- element.setLeft(12f);- element.setBottom(13f);- Map<String, PDImageXObject> cache = new HashMap<>();-- service.drawImageElement(cs, doc, element, cache);-- verify(cs).drawImage(any(PDImageXObject.class), eq(12f), eq(13f), eq(50f), eq(40f));- }- }-- @Test- @DisplayName("without transform, zero dims fall back to native size")- void withoutTransform_zeroDimsFallBack() throws IOException {- try (PDDocument doc = new PDDocument()) {- PDPageContentStream cs = mock(PDPageContentStream.class);- PdfJsonImageElement element = new PdfJsonImageElement();- element.setImageData(pngBase64(6, 7));- element.setId("d2");- element.setWidth(0f);- element.setHeight(0f);- element.setNativeWidth(6);- element.setNativeHeight(7);- Map<String, PDImageXObject> cache = new HashMap<>();-- service.drawImageElement(cs, doc, element, cache);-- verify(cs)- .drawImage(- any(PDImageXObject.class),- anyFloat(),- anyFloat(),- anyFloat(),- anyFloat());- }- }-- @Test- @DisplayName("cache hit reuses XObject and does not recreate")- void cacheHit_reusesXObject() throws IOException {- try (PDDocument doc = new PDDocument()) {- PDPageContentStream cs = mock(PDPageContentStream.class);- PdfJsonImageElement element = new PdfJsonImageElement();- element.setImageData(pngBase64(3, 3));- element.setId("reuse");- element.setTransform(new float[] {1f, 0f, 0f, 1f, 0f, 0f});- Map<String, PDImageXObject> cache = new HashMap<>();-- service.drawImageElement(cs, doc, element, cache);- PDImageXObject first = cache.get("reuse");- service.drawImageElement(cs, doc, element, cache);- PDImageXObject second = cache.get("reuse");-- assertSame(first, second);- verify(cs, times(2)).drawImage(any(PDImageXObject.class), any(Matrix.class));- }- }-- @Test- @DisplayName("undecodable image data short-circuits without drawing")- void badImageData_noDraw() throws IOException {- try (PDDocument doc = new PDDocument()) {- PDPageContentStream cs = mock(PDPageContentStream.class);- PdfJsonImageElement element = new PdfJsonImageElement();- // valid base64 but not an image -> createImageXObject returns/throws -> no draw- element.setImageData("!!!not-base64!!!");- element.setId("bad");- Map<String, PDImageXObject> cache = new HashMap<>();-- service.drawImageElement(cs, doc, element, cache);- verifyNoInteractions(cs);- }- }-- @Test- @DisplayName("element with no id uses identity-hash cache key")- void noId_identityHashCacheKey() throws IOException {- try (PDDocument doc = new PDDocument()) {- PDPageContentStream cs = mock(PDPageContentStream.class);- PdfJsonImageElement element = new PdfJsonImageElement();- element.setImageData(pngBase64(3, 3));- element.setId(null);- element.setTransform(new float[] {1f, 0f, 0f, 1f, 0f, 0f});- Map<String, PDImageXObject> cache = new HashMap<>();-- service.drawImageElement(cs, doc, element, cache);- assertThat(cache).hasSize(1);- }- }- }-- @Nested- @DisplayName("collectImages / extractImagesForPage with real image")- class ExtractWithRealImage {-- private void drawImageOnPage(PDDocument doc, PDPage page) throws IOException {- PDImageXObject image = PDImageXObject.createFromByteArray(doc, pngBytes(8, 8), "real");- try (PDPageContentStream cs = new PDPageContentStream(doc, page)) {- cs.drawImage(image, 50, 50, 80, 80);- }- }-- @Test- @DisplayName("extractImagesForPage returns the embedded image element")- void extractImagesForPage_findsImage() throws IOException {- try (PDDocument doc = new PDDocument()) {- PDPage page = new PDPage(PDRectangle.LETTER);- doc.addPage(page);- drawImageOnPage(doc, page);-- List<PdfJsonImageElement> result = service.extractImagesForPage(doc, page, 1);- assertThat(result).hasSize(1);- PdfJsonImageElement el = result.get(0);- assertNotNull(el.getImageData());- assertNotNull(el.getImageFormat());- assertEquals(8, el.getNativeWidth());- assertEquals(8, el.getNativeHeight());- assertNotNull(el.getTransform());- assertEquals(6, el.getTransform().length);- assertFalse(el.getInlineImage());- }- }-- @Test- @DisplayName("collectImages returns image and fires progress per page")- void collectImages_findsImage() throws IOException {- try (PDDocument doc = new PDDocument()) {- PDPage page = new PDPage(PDRectangle.LETTER);- doc.addPage(page);- drawImageOnPage(doc, page);-- var progress =- new java.util.ArrayList<- stirling.software.SPDF.model.api.PdfJsonConversionProgress>();- Map<Integer, List<PdfJsonImageElement>> result =- service.collectImages(doc, 1, progress::add);-- assertThat(result).containsKey(1);- assertThat(result.get(1)).hasSize(1);- assertEquals(1, progress.size());- }- }-- @Test- @DisplayName("same image drawn twice on a page is encoded once (cache reuse)")- void collectImages_cachesRepeatImage() throws IOException {- try (PDDocument doc = new PDDocument()) {- PDPage page = new PDPage(PDRectangle.LETTER);- doc.addPage(page);- PDImageXObject image =- PDImageXObject.createFromByteArray(doc, pngBytes(8, 8), "shared");- try (PDPageContentStream cs = new PDPageContentStream(doc, page)) {- cs.drawImage(image, 10, 10, 40, 40);- cs.drawImage(image, 100, 100, 40, 40);- }-- Map<Integer, List<PdfJsonImageElement>> result =- service.collectImages(doc, 1, p -> {});- assertThat(result.get(1)).hasSize(2);- // both elements share identical base64 payload- assertEquals(- result.get(1).get(0).getImageData(), result.get(1).get(1).getImageData());- }- }- }-- @Nested- @DisplayName("private helpers via reflection")- class PrivateHelpers {-- private Object invoke(String method, Class<?>[] sig, Object... args) throws Exception {- Method m = PdfJsonImageService.class.getDeclaredMethod(method, sig);- m.setAccessible(true);- return m.invoke(service, args);- }-- @Test- @DisplayName("safeFloat replaces null / NaN / Infinity with default")- void safeFloat() throws Exception {- assertEquals(- 5f, invoke("safeFloat", new Class<?>[] {Float.class, float.class}, null, 5f));- assertEquals(- 9f,- invoke("safeFloat", new Class<?>[] {Float.class, float.class}, Float.NaN, 9f));- assertEquals(- 2f,- invoke(- "safeFloat",- new Class<?>[] {Float.class, float.class},- Float.POSITIVE_INFINITY,- 2f));- assertEquals(- 7f, invoke("safeFloat", new Class<?>[] {Float.class, float.class}, 7f, 0f));- }-- @Test- @DisplayName("fallbackWidth/Height prefer bounds, then native, then 1")- void fallbackDims() throws Exception {- PdfJsonImageElement bounds = new PdfJsonImageElement();- bounds.setLeft(10f);- bounds.setRight(40f);- bounds.setBottom(5f);- bounds.setTop(25f);- assertEquals(- 30f,- invoke("fallbackWidth", new Class<?>[] {PdfJsonImageElement.class}, bounds));- assertEquals(- 20f,- invoke("fallbackHeight", new Class<?>[] {PdfJsonImageElement.class}, bounds));-- PdfJsonImageElement nativeOnly = new PdfJsonImageElement();- nativeOnly.setNativeWidth(123);- nativeOnly.setNativeHeight(456);- assertEquals(- 123f,- invoke(- "fallbackWidth",- new Class<?>[] {PdfJsonImageElement.class},- nativeOnly));- assertEquals(- 456f,- invoke(- "fallbackHeight",- new Class<?>[] {PdfJsonImageElement.class},- nativeOnly));-- PdfJsonImageElement empty = new PdfJsonImageElement();- assertEquals(- 1f, invoke("fallbackWidth", new Class<?>[] {PdfJsonImageElement.class}, empty));- assertEquals(- 1f,- invoke("fallbackHeight", new Class<?>[] {PdfJsonImageElement.class}, empty));- }-- @Test- @DisplayName("resolveLeft prefers left, then x, then right-width, else 0")- void resolveLeft() throws Exception {- PdfJsonImageElement leftEl = new PdfJsonImageElement();- leftEl.setLeft(11f);- assertEquals(- 11f,- invoke(- "resolveLeft",- new Class<?>[] {PdfJsonImageElement.class, float.class},- leftEl,- 10f));-- PdfJsonImageElement xEl = new PdfJsonImageElement();- xEl.setX(22f);- assertEquals(- 22f,- invoke(- "resolveLeft",- new Class<?>[] {PdfJsonImageElement.class, float.class},- xEl,- 10f));-- PdfJsonImageElement rightEl = new PdfJsonImageElement();- rightEl.setRight(100f);- assertEquals(- 70f,- invoke(- "resolveLeft",- new Class<?>[] {PdfJsonImageElement.class, float.class},- rightEl,- 30f));-- PdfJsonImageElement none = new PdfJsonImageElement();- assertEquals(- 0f,- invoke(- "resolveLeft",- new Class<?>[] {PdfJsonImageElement.class, float.class},- none,- 30f));- }-- @Test- @DisplayName("resolveBottom prefers bottom, then y, then top-height, else 0")- void resolveBottom() throws Exception {- PdfJsonImageElement bottomEl = new PdfJsonImageElement();- bottomEl.setBottom(11f);- assertEquals(- 11f,- invoke(- "resolveBottom",- new Class<?>[] {PdfJsonImageElement.class, float.class},- bottomEl,- 10f));-- PdfJsonImageElement yEl = new PdfJsonImageElement();- yEl.setY(22f);- assertEquals(- 22f,- invoke(- "resolveBottom",- new Class<?>[] {PdfJsonImageElement.class, float.class},- yEl,- 10f));-- PdfJsonImageElement topEl = new PdfJsonImageElement();- topEl.setTop(100f);- assertEquals(- 60f,- invoke(- "resolveBottom",- new Class<?>[] {PdfJsonImageElement.class, float.class},- topEl,- 40f));-- PdfJsonImageElement none = new PdfJsonImageElement();- assertEquals(- 0f,- invoke(- "resolveBottom",- new Class<?>[] {PdfJsonImageElement.class, float.class},- none,- 40f));- }-- @Test- @DisplayName("toMatrixValues returns the six affine components")- void toMatrixValues() throws Exception {- Matrix m = new Matrix(2f, 0f, 0f, 3f, 4f, 5f);- float[] values = (float[]) invoke("toMatrixValues", new Class<?>[] {Matrix.class}, m);- assertEquals(6, values.length);- assertEquals(2f, values[0]);- assertEquals(3f, values[3]);- assertEquals(4f, values[4]);- assertEquals(5f, values[5]);- }- }-}diff --git a/app/core/src/test/java/stirling/software/SPDF/service/pdfjson/PdfJsonImageServiceTest.java b/app/core/src/test/java/stirling/software/SPDF/service/pdfjson/PdfJsonImageServiceTest.javadeleted file mode 100644index fd38d4285a..0000000000--- a/app/core/src/test/java/stirling/software/SPDF/service/pdfjson/PdfJsonImageServiceTest.java+++ /dev/null@@ -1,139 +0,0 @@-package stirling.software.SPDF.service.pdfjson;--import static org.junit.jupiter.api.Assertions.*;-import static org.mockito.Mockito.*;--import java.io.IOException;-import java.util.HashMap;-import java.util.Map;--import org.apache.pdfbox.pdmodel.PDDocument;-import org.apache.pdfbox.pdmodel.PDPageContentStream;-import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;-import org.junit.jupiter.api.BeforeEach;-import org.junit.jupiter.api.Test;--import stirling.software.SPDF.model.json.PdfJsonImageElement;--class PdfJsonImageServiceTest {-- private PdfJsonImageService service;-- @BeforeEach- void setUp() {- service = new PdfJsonImageService();- }-- // --- drawImageElement tests ----- @Test- void drawImageElement_nullElement_doesNothing() throws IOException {- PDPageContentStream cs = mock(PDPageContentStream.class);- PDDocument doc = mock(PDDocument.class);- Map<String, PDImageXObject> cache = new HashMap<>();-- service.drawImageElement(cs, doc, null, cache);-- verifyNoInteractions(cs);- }-- @Test- void drawImageElement_nullImageData_doesNothing() throws IOException {- PDPageContentStream cs = mock(PDPageContentStream.class);- PDDocument doc = mock(PDDocument.class);- Map<String, PDImageXObject> cache = new HashMap<>();- PdfJsonImageElement element = new PdfJsonImageElement();- element.setImageData(null);-- service.drawImageElement(cs, doc, element, cache);-- verifyNoInteractions(cs);- }-- @Test- void drawImageElement_blankImageData_doesNothing() throws IOException {- PDPageContentStream cs = mock(PDPageContentStream.class);- PDDocument doc = mock(PDDocument.class);- Map<String, PDImageXObject> cache = new HashMap<>();- PdfJsonImageElement element = new PdfJsonImageElement();- element.setImageData(" ");-- service.drawImageElement(cs, doc, element, cache);-- verifyNoInteractions(cs);- }-- // --- createImageXObject tests ----- @Test- void createImageXObject_invalidBase64_returnsNull() throws IOException {- PDDocument doc = mock(PDDocument.class);- PdfJsonImageElement element = new PdfJsonImageElement();- element.setImageData("not!!valid!!base64!!");-- PDImageXObject result = service.createImageXObject(doc, element);- assertNull(result);- }-- @Test- void createImageXObject_validBase64ButInvalidImage_throwsOrReturnsNull() throws IOException {- PDDocument doc = new PDDocument();- PdfJsonImageElement element = new PdfJsonImageElement();- // Valid base64 but not a real image- element.setImageData("AAAA");- element.setId("test-id");-- // Depending on PDFBox version, this may throw or return something- try {- PDImageXObject result = service.createImageXObject(doc, element);- // Either null or valid is acceptable for garbage data- } catch (IOException | IllegalArgumentException e) {- // Expected for invalid image data- } finally {- doc.close();- }- }-- // --- extractImagesForPage tests ----- @Test- void extractImagesForPage_emptyPage_returnsEmptyList() throws IOException {- try (PDDocument doc = new PDDocument()) {- org.apache.pdfbox.pdmodel.PDPage page = new org.apache.pdfbox.pdmodel.PDPage();- doc.addPage(page);-- var result = service.extractImagesForPage(doc, page, 1);- assertNotNull(result);- assertTrue(result.isEmpty());- }- }-- // --- collectImages tests ----- @Test- void collectImages_emptyDocument_returnsEmptyMap() throws IOException {- try (PDDocument doc = new PDDocument()) {- doc.addPage(new org.apache.pdfbox.pdmodel.PDPage());-- var result = service.collectImages(doc, 1, progress -> {});- assertNotNull(result);- // The page has no images so the map should be empty- assertTrue(- result.isEmpty() || result.values().stream().allMatch(java.util.List::isEmpty));- }- }-- @Test- void collectImages_progressCallbackInvoked() throws IOException {- try (PDDocument doc = new PDDocument()) {- doc.addPage(new org.apache.pdfbox.pdmodel.PDPage());- doc.addPage(new org.apache.pdfbox.pdmodel.PDPage());-- java.util.List<stirling.software.SPDF.model.api.PdfJsonConversionProgress>- progressList = new java.util.ArrayList<>();- service.collectImages(doc, 2, progressList::add);-- assertEquals(2, progressList.size());- }- }-}diff --git a/app/core/src/test/java/stirling/software/SPDF/service/pdfjson/PdfJsonMetadataServiceTest.java b/app/core/src/test/java/stirling/software/SPDF/service/pdfjson/PdfJsonMetadataServiceTest.javadeleted file mode 100644index 1eacf36fee..0000000000--- a/app/core/src/test/java/stirling/software/SPDF/service/pdfjson/PdfJsonMetadataServiceTest.java+++ /dev/null@@ -1,225 +0,0 @@-package stirling.software.SPDF.service.pdfjson;--import static org.junit.jupiter.api.Assertions.*;-import static org.mockito.Mockito.*;--import java.io.ByteArrayInputStream;-import java.io.IOException;-import java.util.Base64;-import java.util.Calendar;-import java.util.TimeZone;--import org.apache.pdfbox.pdmodel.PDDocument;-import org.apache.pdfbox.pdmodel.PDDocumentCatalog;-import org.apache.pdfbox.pdmodel.PDDocumentInformation;-import org.apache.pdfbox.pdmodel.common.PDMetadata;-import org.junit.jupiter.api.BeforeEach;-import org.junit.jupiter.api.Test;--import stirling.software.SPDF.model.json.PdfJsonMetadata;--class PdfJsonMetadataServiceTest {-- private PdfJsonMetadataService service;-- @BeforeEach- void setUp() {- service = new PdfJsonMetadataService();- }-- // --- extractMetadata tests ----- @Test- void extractMetadata_withAllFields_populatesMetadata() {- PDDocument document = mock(PDDocument.class);- PDDocumentInformation info = mock(PDDocumentInformation.class);- when(document.getDocumentInformation()).thenReturn(info);- when(document.getNumberOfPages()).thenReturn(5);- when(info.getTitle()).thenReturn("Test Title");- when(info.getAuthor()).thenReturn("Author");- when(info.getSubject()).thenReturn("Subject");- when(info.getKeywords()).thenReturn("key1,key2");- when(info.getCreator()).thenReturn("Creator");- when(info.getProducer()).thenReturn("Producer");- when(info.getTrapped()).thenReturn("True");-- Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));- cal.setTimeInMillis(1000000000L);- when(info.getCreationDate()).thenReturn(cal);- when(info.getModificationDate()).thenReturn(cal);-- PdfJsonMetadata result = service.extractMetadata(document);-- assertEquals("Test Title", result.getTitle());- assertEquals("Author", result.getAuthor());- assertEquals("Subject", result.getSubject());- assertEquals("key1,key2", result.getKeywords());- assertEquals("Creator", result.getCreator());- assertEquals("Producer", result.getProducer());- assertEquals("True", result.getTrapped());- assertEquals(5, result.getNumberOfPages());- assertNotNull(result.getCreationDate());- assertNotNull(result.getModificationDate());- }-- @Test- void extractMetadata_nullInfo_setsOnlyPageCount() {- PDDocument document = mock(PDDocument.class);- when(document.getDocumentInformation()).thenReturn(null);- when(document.getNumberOfPages()).thenReturn(3);-- PdfJsonMetadata result = service.extractMetadata(document);-- assertNull(result.getTitle());- assertEquals(3, result.getNumberOfPages());- }-- @Test- void extractMetadata_nullDates_returnsNullDates() {- PDDocument document = mock(PDDocument.class);- PDDocumentInformation info = mock(PDDocumentInformation.class);- when(document.getDocumentInformation()).thenReturn(info);- when(document.getNumberOfPages()).thenReturn(1);- when(info.getCreationDate()).thenReturn(null);- when(info.getModificationDate()).thenReturn(null);-- PdfJsonMetadata result = service.extractMetadata(document);-- assertNull(result.getCreationDate());- assertNull(result.getModificationDate());- }-- // --- extractXmpMetadata tests ----- @Test- void extractXmpMetadata_nullCatalog_returnsNull() {- PDDocument document = mock(PDDocument.class);- when(document.getDocumentCatalog()).thenReturn(null);-- assertNull(service.extractXmpMetadata(document));- }-- @Test- void extractXmpMetadata_nullMetadata_returnsNull() {- PDDocument document = mock(PDDocument.class);- PDDocumentCatalog catalog = mock(PDDocumentCatalog.class);- when(document.getDocumentCatalog()).thenReturn(catalog);- when(catalog.getMetadata()).thenReturn(null);-- assertNull(service.extractXmpMetadata(document));- }-- @Test- void extractXmpMetadata_withData_returnsBase64() throws IOException {- byte[] xmpData = "<xmp>test</xmp>".getBytes();- try (PDDocument document = new PDDocument()) {- document.addPage(new org.apache.pdfbox.pdmodel.PDPage());- PDMetadata metadata = new PDMetadata(document, new ByteArrayInputStream(xmpData));- document.getDocumentCatalog().setMetadata(metadata);-- String result = service.extractXmpMetadata(document);- assertNotNull(result);- assertArrayEquals(xmpData, Base64.getDecoder().decode(result));- }- }-- @Test- void extractXmpMetadata_emptyData_returnsNull() throws IOException {- try (PDDocument document = new PDDocument()) {- document.addPage(new org.apache.pdfbox.pdmodel.PDPage());- PDMetadata metadata = new PDMetadata(document, new ByteArrayInputStream(new byte[0]));- document.getDocumentCatalog().setMetadata(metadata);-- assertNull(service.extractXmpMetadata(document));- }- }-- @Test- void extractXmpMetadata_ioException_returnsNull() throws IOException {- PDDocument document = mock(PDDocument.class);- PDDocumentCatalog catalog = mock(PDDocumentCatalog.class);- PDMetadata metadata = mock(PDMetadata.class);- when(document.getDocumentCatalog()).thenReturn(catalog);- when(catalog.getMetadata()).thenReturn(metadata);- when(metadata.createInputStream()).thenThrow(new IOException("read error"));-- assertNull(service.extractXmpMetadata(document));- }-- // --- applyMetadata tests ----- @Test- void applyMetadata_nullMetadata_doesNothing() {- PDDocument document = mock(PDDocument.class);- service.applyMetadata(document, null);- verify(document, never()).getDocumentInformation();- }-- @Test- void applyMetadata_setsAllFields() {- PDDocument document = mock(PDDocument.class);- PDDocumentInformation info = mock(PDDocumentInformation.class);- when(document.getDocumentInformation()).thenReturn(info);-- PdfJsonMetadata metadata = new PdfJsonMetadata();- metadata.setTitle("T");- metadata.setAuthor("A");- metadata.setSubject("S");- metadata.setKeywords("K");- metadata.setCreator("C");- metadata.setProducer("P");- metadata.setTrapped("True");- metadata.setCreationDate("2020-01-01T00:00:00Z");- metadata.setModificationDate("2021-06-15T12:30:00Z");-- service.applyMetadata(document, metadata);-- verify(info).setTitle("T");- verify(info).setAuthor("A");- verify(info).setSubject("S");- verify(info).setKeywords("K");- verify(info).setCreator("C");- verify(info).setProducer("P");- verify(info).setTrapped("True");- verify(info).setCreationDate(any(Calendar.class));- verify(info).setModificationDate(any(Calendar.class));- }-- @Test- void applyMetadata_invalidDateFormat_doesNotSetDate() {- PDDocument document = mock(PDDocument.class);- PDDocumentInformation info = mock(PDDocumentInformation.class);- when(document.getDocumentInformation()).thenReturn(info);-- PdfJsonMetadata metadata = new PdfJsonMetadata();- metadata.setCreationDate("not-a-date");-- service.applyMetadata(document, metadata);-- verify(info, never()).setCreationDate(any(Calendar.class));- }-- // --- applyXmpMetadata tests ----- @Test- void applyXmpMetadata_nullBase64_doesNothing() {- PDDocument document = mock(PDDocument.class);- service.applyXmpMetadata(document, null);- verify(document, never()).getDocumentCatalog();- }-- @Test- void applyXmpMetadata_blankBase64_doesNothing() {- PDDocument document = mock(PDDocument.class);- service.applyXmpMetadata(document, " ");- verify(document, never()).getDocumentCatalog();- }-- @Test- void applyXmpMetadata_invalidBase64_doesNotThrow() {- PDDocument document = mock(PDDocument.class);- // Invalid base64 should be caught- service.applyXmpMetadata(document, "not!!valid!!base64");- // Should not throw- }-}diff --git a/app/core/src/test/java/stirling/software/SPDF/service/pdfjson/PdfLazyLoadingServiceMoreTest.java b/app/core/src/test/java/stirling/software/SPDF/service/pdfjson/PdfLazyLoadingServiceMoreTest.javadeleted file mode 100644index a1b144bd6a..0000000000--- a/app/core/src/test/java/stirling/software/SPDF/service/pdfjson/PdfLazyLoadingServiceMoreTest.java+++ /dev/null@@ -1,223 +0,0 @@-package stirling.software.SPDF.service.pdfjson;--import static org.assertj.core.api.Assertions.assertThat;-import static org.assertj.core.api.Assertions.assertThatThrownBy;-import static org.mockito.ArgumentMatchers.any;-import static org.mockito.ArgumentMatchers.anyBoolean;-import static org.mockito.ArgumentMatchers.eq;-import static org.mockito.Mockito.doAnswer;-import static org.mockito.Mockito.mock;-import static org.mockito.Mockito.never;-import static org.mockito.Mockito.verify;-import static org.mockito.Mockito.when;--import java.io.ByteArrayOutputStream;-import java.io.OutputStream;-import java.lang.reflect.Constructor;-import java.lang.reflect.Field;-import java.util.ArrayList;-import java.util.List;-import java.util.Map;--import org.apache.pdfbox.pdmodel.PDDocument;-import org.apache.pdfbox.pdmodel.PDPage;-import org.apache.pdfbox.pdmodel.common.PDRectangle;-import org.junit.jupiter.api.BeforeEach;-import org.junit.jupiter.api.DisplayName;-import org.junit.jupiter.api.Nested;-import org.junit.jupiter.api.Test;--import stirling.software.SPDF.model.json.PdfJsonDocumentMetadata;-import stirling.software.SPDF.model.json.PdfJsonImageElement;-import stirling.software.SPDF.model.json.PdfJsonPageDimension;-import stirling.software.common.service.CustomPDFDocumentFactory;-import stirling.software.common.service.TaskManager;--import tools.jackson.databind.ObjectMapper;--/**- * Additional branch coverage for {@link PdfLazyLoadingService}: the cache-hit page extraction path,- * out-of-range page validation (both ends), and cache removal of an existing entry. Dependencies- * are mocked; a real in-memory PDF is handed back by the factory for the happy path.- */-@DisplayName("PdfLazyLoadingService additional branch tests")-class PdfLazyLoadingServiceMoreTest {-- private PdfLazyLoadingService service;- private CustomPDFDocumentFactory pdfDocumentFactory;- private ObjectMapper objectMapper;- private TaskManager taskManager;- private PdfJsonMetadataService metadataService;- private PdfJsonImageService imageService;-- @BeforeEach- void setUp() {- pdfDocumentFactory = mock(CustomPDFDocumentFactory.class);- objectMapper = mock(ObjectMapper.class);- taskManager = mock(TaskManager.class);- metadataService = mock(PdfJsonMetadataService.class);- imageService = mock(PdfJsonImageService.class);- service =- new PdfLazyLoadingService(- pdfDocumentFactory,- objectMapper,- taskManager,- metadataService,- imageService);- }-- @SuppressWarnings("unchecked")- private Map<String, Object> cache() throws Exception {- Field f = PdfLazyLoadingService.class.getDeclaredField("documentCache");- f.setAccessible(true);- return (Map<String, Object>) f.get(service);- }-- /** Reflectively builds a CachedPdfDocument and inserts it into the document cache. */- private void seedCache(String jobId, byte[] pdfBytes, int pageCount) throws Exception {- PdfJsonDocumentMetadata metadata = new PdfJsonDocumentMetadata();- List<PdfJsonPageDimension> dims = new ArrayList<>();- for (int i = 0; i < pageCount; i++) {- PdfJsonPageDimension d = new PdfJsonPageDimension();- d.setPageNumber(i + 1);- d.setWidth(200);- d.setHeight(200);- dims.add(d);- }- metadata.setPageDimensions(dims);-- Class<?> cachedClass =- Class.forName(- "stirling.software.SPDF.service.pdfjson.PdfLazyLoadingService$CachedPdfDocument");- Constructor<?> ctor =- cachedClass.getDeclaredConstructor(byte[].class, PdfJsonDocumentMetadata.class);- ctor.setAccessible(true);- Object cached = ctor.newInstance(pdfBytes, metadata);- cache().put(jobId, cached);- }-- private static byte[] tinyPdfBytes(int pages) throws Exception {- try (PDDocument doc = new PDDocument();- ByteArrayOutputStream baos = new ByteArrayOutputStream()) {- for (int i = 0; i < pages; i++) {- doc.addPage(new PDPage(new PDRectangle(200, 200)));- }- doc.save(baos);- return baos.toByteArray();- }- }-- private static PDDocument tinyDoc(int pages) {- PDDocument doc = new PDDocument();- for (int i = 0; i < pages; i++) {- doc.addPage(new PDPage(new PDRectangle(200, 200)));- }- return doc;- }-- @Nested- @DisplayName("extractSinglePage cache hit")- class CacheHit {-- @Test- @DisplayName("extracts the requested page and writes JSON to the stream")- void extractsPage() throws Exception {- byte[] pdfBytes = tinyPdfBytes(2);- seedCache("job-hit", pdfBytes, 2);-- when(pdfDocumentFactory.load(eq(pdfBytes), eq(true))).thenReturn(tinyDoc(2));- List<PdfJsonImageElement> images = new ArrayList<>();- when(imageService.extractImagesForPage(any(), any(), eq(2))).thenReturn(images);-- doAnswer(- inv -> {- OutputStream os = inv.getArgument(0, OutputStream.class);- os.write(new byte[] {'p', 'g'});- return null;- })- .when(objectMapper)- .writeValue(any(OutputStream.class), any());-- ByteArrayOutputStream out = new ByteArrayOutputStream();- service.extractSinglePage(- "job-hit",- 2,- cos -> null,- page -> new ArrayList<>(),- cos -> cos,- (doc, pageNum) -> new ArrayList<>(),- (doc, pageNum) -> new ArrayList<>(),- out);-- assertThat(out.toByteArray()).hasSize(2);- verify(pdfDocumentFactory).load(eq(pdfBytes), eq(true));- verify(imageService).extractImagesForPage(any(), any(), eq(2));- }- }-- @Nested- @DisplayName("extractSinglePage out-of-range")- class OutOfRange {-- @Test- @DisplayName("page number above the page count is rejected")- void aboveRange() throws Exception {- seedCache("job-hi", tinyPdfBytes(1), 1);-- ByteArrayOutputStream out = new ByteArrayOutputStream();- assertThatThrownBy(- () ->- service.extractSinglePage(- "job-hi",- 5,- cos -> null,- page -> new ArrayList<>(),- cos -> cos,- (doc, pageNum) -> new ArrayList<>(),- (doc, pageNum) -> new ArrayList<>(),- out))- .isInstanceOf(IllegalArgumentException.class)- .hasMessageContaining("out of range");-- // The factory is never consulted when validation fails.- verify(pdfDocumentFactory, never()).load(any(byte[].class), anyBoolean());- }-- @Test- @DisplayName("page number below 1 is rejected")- void belowRange() throws Exception {- seedCache("job-lo", tinyPdfBytes(2), 2);-- ByteArrayOutputStream out = new ByteArrayOutputStream();- assertThatThrownBy(- () ->- service.extractSinglePage(- "job-lo",- 0,- cos -> null,- page -> new ArrayList<>(),- cos -> cos,- (doc, pageNum) -> new ArrayList<>(),- (doc, pageNum) -> new ArrayList<>(),- out))- .isInstanceOf(IllegalArgumentException.class)- .hasMessageContaining("out of range");- }- }-- @Nested- @DisplayName("clearCachedDocument")- class ClearCache {-- @Test- @DisplayName("removes an existing cached entry")- void removesExisting() throws Exception {- seedCache("job-clear", tinyPdfBytes(1), 1);- assertThat(cache()).containsKey("job-clear");-- service.clearCachedDocument("job-clear");-- assertThat(cache()).doesNotContainKey("job-clear");- }- }-}diff --git a/app/core/src/test/java/stirling/software/SPDF/service/pdfjson/PdfLazyLoadingServiceTest.java b/app/core/src/test/java/stirling/software/SPDF/service/pdfjson/PdfLazyLoadingServiceTest.javadeleted file mode 100644index e5a6d2b3f7..0000000000--- a/app/core/src/test/java/stirling/software/SPDF/service/pdfjson/PdfLazyLoadingServiceTest.java+++ /dev/null@@ -1,140 +0,0 @@-package stirling.software.SPDF.service.pdfjson;--import static org.junit.jupiter.api.Assertions.*;-import static org.mockito.ArgumentMatchers.any;-import static org.mockito.ArgumentMatchers.eq;-import static org.mockito.Mockito.*;--import java.io.ByteArrayOutputStream;-import java.io.OutputStream;-import java.lang.reflect.Field;-import java.util.HashMap;-import java.util.Map;--import org.apache.pdfbox.pdmodel.font.PDFont;-import org.junit.jupiter.api.BeforeEach;-import org.junit.jupiter.api.Test;-import org.springframework.web.multipart.MultipartFile;--import stirling.software.SPDF.model.json.PdfJsonFont;-import stirling.software.common.service.CustomPDFDocumentFactory;-import stirling.software.common.service.TaskManager;--import tools.jackson.databind.ObjectMapper;--class PdfLazyLoadingServiceTest {-- private PdfLazyLoadingService service;- private CustomPDFDocumentFactory pdfDocumentFactory;- private ObjectMapper objectMapper;- private TaskManager taskManager;- private PdfJsonMetadataService metadataService;- private PdfJsonImageService imageService;-- @BeforeEach- void setUp() {- pdfDocumentFactory = mock(CustomPDFDocumentFactory.class);- objectMapper = mock(ObjectMapper.class);- taskManager = mock(TaskManager.class);- metadataService = mock(PdfJsonMetadataService.class);- imageService = mock(PdfJsonImageService.class);-- service =- new PdfLazyLoadingService(- pdfDocumentFactory,- objectMapper,- taskManager,- metadataService,- imageService);- }-- @Test- void extractDocumentMetadata_nullFile_throwsException() {- assertThrows(- Exception.class,- () ->- service.extractDocumentMetadata(- null,- "job1",- new HashMap<>(),- new HashMap<>(),- new ByteArrayOutputStream()));- }-- @Test- void clearCachedDocument_nonExistentJob_doesNotThrow() {- service.clearCachedDocument("nonexistent");- // Should complete without error- }-- @Test- void clearCachedDocument_existingJob_removesEntry() throws Exception {- // Access the documentCache via reflection to verify behavior- Field cacheField = PdfLazyLoadingService.class.getDeclaredField("documentCache");- cacheField.setAccessible(true);- @SuppressWarnings("unchecked")- Map<String, Object> cache = (Map<String, Object>) cacheField.get(service);-- // Verify cache is initially empty- assertTrue(cache.isEmpty());-- // clearCachedDocument on nonexistent should not throw- service.clearCachedDocument("job1");- assertTrue(cache.isEmpty());- }-- @Test- void extractSinglePage_nonExistentJob_throwsIllegalArgument() {- assertThrows(- IllegalArgumentException.class,- () ->- service.extractSinglePage(- "nonexistent",- 1,- cos -> null,- page -> null,- cos -> cos,- (doc, pageNum) -> new java.util.ArrayList<>(),- (doc, pageNum) -> new java.util.ArrayList<>(),- new ByteArrayOutputStream()));- }-- @Test- void extractDocumentMetadata_withValidPdf_returnsBytes() throws Exception {- // Create a real minimal PDF document for the factory to return- org.apache.pdfbox.pdmodel.PDDocument doc = new org.apache.pdfbox.pdmodel.PDDocument();- doc.addPage(new org.apache.pdfbox.pdmodel.PDPage());-- MultipartFile file = mock(MultipartFile.class);- byte[] pdfBytes = new byte[] {0x25, 0x50, 0x44, 0x46}; // %PDF- when(file.getBytes()).thenReturn(pdfBytes);- when(pdfDocumentFactory.load(eq(pdfBytes), eq(true))).thenReturn(doc);-- stirling.software.SPDF.model.json.PdfJsonMetadata metadata =- new stirling.software.SPDF.model.json.PdfJsonMetadata();- metadata.setNumberOfPages(1);- when(metadataService.extractMetadata(any())).thenReturn(metadata);- when(metadataService.extractXmpMetadata(any())).thenReturn(null);- // Service now writes directly to the OutputStream using writeValue, not writeValueAsBytes.- // ObjectMapper.writeValue(OutputStream, Object) — the OutputStream is argument 0.- doAnswer(- inv -> {- OutputStream os = inv.getArgument(0, OutputStream.class);- os.write(new byte[] {'{', '}'});- return null;- })- .when(objectMapper)- .writeValue(any(OutputStream.class), any());- when(taskManager.addNote(any(), any())).thenReturn(true);-- Map<String, PdfJsonFont> fonts = new HashMap<>();- Map<Integer, Map<PDFont, String>> pageFontResources = new HashMap<>();- ByteArrayOutputStream out = new ByteArrayOutputStream();-- service.extractDocumentMetadata(file, "job1", fonts, pageFontResources, out);-- assertNotNull(out.toByteArray());- assertEquals(2, out.toByteArray().length);- verify(metadataService).extractMetadata(any());- }-}diff --git a/app/core/src/test/java/stirling/software/SPDF/service/pdfjson/type3/Type3FontConversionServiceTest.java b/app/core/src/test/java/stirling/software/SPDF/service/pdfjson/type3/Type3FontConversionServiceTest.javadeleted file mode 100644index ac48c6202c..0000000000--- a/app/core/src/test/java/stirling/software/SPDF/service/pdfjson/type3/Type3FontConversionServiceTest.java+++ /dev/null@@ -1,231 +0,0 @@-package stirling.software.SPDF.service.pdfjson.type3;--import static org.junit.jupiter.api.Assertions.*;-import static org.mockito.Mockito.*;--import java.io.IOException;-import java.util.Collections;-import java.util.List;--import org.apache.pdfbox.pdmodel.font.PDType3Font;-import org.junit.jupiter.api.Test;--import stirling.software.SPDF.model.json.PdfJsonFontConversionCandidate;-import stirling.software.SPDF.model.json.PdfJsonFontConversionStatus;--class Type3FontConversionServiceTest {-- @Test- void synthesize_nullRequest_returnsEmpty() {- Type3GlyphExtractor extractor = mock(Type3GlyphExtractor.class);- Type3FontConversionService service = new Type3FontConversionService(List.of(), extractor);- List<PdfJsonFontConversionCandidate> result = service.synthesize(null);- assertTrue(result.isEmpty());- }-- @Test- void synthesize_nullFont_returnsEmpty() {- Type3GlyphExtractor extractor = mock(Type3GlyphExtractor.class);- Type3FontConversionService service = new Type3FontConversionService(List.of(), extractor);- Type3ConversionRequest request = Type3ConversionRequest.builder().font(null).build();- List<PdfJsonFontConversionCandidate> result = service.synthesize(request);- assertTrue(result.isEmpty());- }-- @Test- void synthesize_noStrategies_returnsEmpty() {- Type3GlyphExtractor extractor = mock(Type3GlyphExtractor.class);- Type3FontConversionService service =- new Type3FontConversionService(Collections.emptyList(), extractor);- PDType3Font font = mock(PDType3Font.class);- Type3ConversionRequest request =- Type3ConversionRequest.builder().font(font).fontId("F1").build();- List<PdfJsonFontConversionCandidate> result = service.synthesize(request);- assertTrue(result.isEmpty());- }-- @Test- void synthesize_nullStrategiesList_returnsEmpty() {- Type3GlyphExtractor extractor = mock(Type3GlyphExtractor.class);- Type3FontConversionService service = new Type3FontConversionService(null, extractor);- PDType3Font font = mock(PDType3Font.class);- Type3ConversionRequest request =- Type3ConversionRequest.builder().font(font).fontId("F1").build();- List<PdfJsonFontConversionCandidate> result = service.synthesize(request);- assertTrue(result.isEmpty());- }-- @Test- void synthesize_unavailableStrategy_returnsSkipped() {- Type3ConversionStrategy strategy = mock(Type3ConversionStrategy.class);- when(strategy.isAvailable()).thenReturn(false);- when(strategy.getId()).thenReturn("test-strategy");- when(strategy.getLabel()).thenReturn("Test Strategy");-- Type3GlyphExtractor extractor = mock(Type3GlyphExtractor.class);- Type3FontConversionService service =- new Type3FontConversionService(List.of(strategy), extractor);- PDType3Font font = mock(PDType3Font.class);- Type3ConversionRequest request =- Type3ConversionRequest.builder().font(font).fontId("F1").pageNumber(1).build();-- List<PdfJsonFontConversionCandidate> result = service.synthesize(request);- assertEquals(1, result.size());- assertEquals(PdfJsonFontConversionStatus.SKIPPED, result.get(0).getStatus());- }-- @Test- void synthesize_unsupportedFont_returnsUnsupported() throws IOException {- Type3ConversionStrategy strategy = mock(Type3ConversionStrategy.class);- when(strategy.isAvailable()).thenReturn(true);- when(strategy.supports(any(), any())).thenReturn(false);- when(strategy.getId()).thenReturn("test-strategy");- when(strategy.getLabel()).thenReturn("Test Strategy");-- Type3GlyphExtractor extractor = mock(Type3GlyphExtractor.class);- Type3FontConversionService service =- new Type3FontConversionService(List.of(strategy), extractor);- PDType3Font font = mock(PDType3Font.class);- Type3ConversionRequest request =- Type3ConversionRequest.builder().font(font).fontId("F1").pageNumber(1).build();-- List<PdfJsonFontConversionCandidate> result = service.synthesize(request);- assertEquals(1, result.size());- assertEquals(PdfJsonFontConversionStatus.UNSUPPORTED, result.get(0).getStatus());- }-- @Test- void synthesize_successfulConversion() throws IOException {- PdfJsonFontConversionCandidate candidate =- PdfJsonFontConversionCandidate.builder()- .status(PdfJsonFontConversionStatus.SUCCESS)- .message("OK")- .build();- Type3ConversionStrategy strategy = mock(Type3ConversionStrategy.class);- when(strategy.isAvailable()).thenReturn(true);- when(strategy.supports(any(), any())).thenReturn(true);- when(strategy.convert(any(), any())).thenReturn(candidate);- when(strategy.getId()).thenReturn("test-strategy");- when(strategy.getLabel()).thenReturn("Test Strategy");-- Type3GlyphExtractor extractor = mock(Type3GlyphExtractor.class);- Type3FontConversionService service =- new Type3FontConversionService(List.of(strategy), extractor);- PDType3Font font = mock(PDType3Font.class);- Type3ConversionRequest request =- Type3ConversionRequest.builder().font(font).fontId("F1").pageNumber(1).build();-- List<PdfJsonFontConversionCandidate> result = service.synthesize(request);- assertEquals(1, result.size());- assertEquals(PdfJsonFontConversionStatus.SUCCESS, result.get(0).getStatus());- assertEquals("test-strategy", result.get(0).getStrategyId());- }-- @Test- void synthesize_strategyReturnsNull_resultsInFailure() throws IOException {- Type3ConversionStrategy strategy = mock(Type3ConversionStrategy.class);- when(strategy.isAvailable()).thenReturn(true);- when(strategy.supports(any(), any())).thenReturn(true);- when(strategy.convert(any(), any())).thenReturn(null);- when(strategy.getId()).thenReturn("test-strategy");- when(strategy.getLabel()).thenReturn("Test Strategy");-- Type3GlyphExtractor extractor = mock(Type3GlyphExtractor.class);- Type3FontConversionService service =- new Type3FontConversionService(List.of(strategy), extractor);- PDType3Font font = mock(PDType3Font.class);- Type3ConversionRequest request =- Type3ConversionRequest.builder()- .font(font)- .fontId("F1")- .fontUid("uid1")- .pageNumber(1)- .build();-- List<PdfJsonFontConversionCandidate> result = service.synthesize(request);- assertEquals(1, result.size());- assertEquals(PdfJsonFontConversionStatus.FAILURE, result.get(0).getStatus());- }-- @Test- void synthesize_strategyThrowsIOException_resultsInFailure() throws IOException {- Type3ConversionStrategy strategy = mock(Type3ConversionStrategy.class);- when(strategy.isAvailable()).thenReturn(true);- when(strategy.supports(any(), any())).thenReturn(true);- when(strategy.convert(any(), any())).thenThrow(new IOException("broken"));- when(strategy.getId()).thenReturn("test-strategy");- when(strategy.getLabel()).thenReturn("Test Strategy");-- Type3GlyphExtractor extractor = mock(Type3GlyphExtractor.class);- Type3FontConversionService service =- new Type3FontConversionService(List.of(strategy), extractor);- PDType3Font font = mock(PDType3Font.class);- Type3ConversionRequest request =- Type3ConversionRequest.builder()- .font(font)- .fontId("F1")- .fontUid("uid1")- .pageNumber(1)- .build();-- List<PdfJsonFontConversionCandidate> result = service.synthesize(request);- assertEquals(1, result.size());- assertEquals(PdfJsonFontConversionStatus.FAILURE, result.get(0).getStatus());- assertEquals("broken", result.get(0).getMessage());- }-- @Test- void synthesize_supportCheckThrowsIOException_returnsUnsupported() throws IOException {- Type3ConversionStrategy strategy = mock(Type3ConversionStrategy.class);- when(strategy.isAvailable()).thenReturn(true);- when(strategy.supports(any(), any())).thenThrow(new IOException("check failed"));- when(strategy.getId()).thenReturn("test-strategy");- when(strategy.getLabel()).thenReturn("Test Strategy");-- Type3GlyphExtractor extractor = mock(Type3GlyphExtractor.class);- Type3FontConversionService service =- new Type3FontConversionService(List.of(strategy), extractor);- PDType3Font font = mock(PDType3Font.class);- Type3ConversionRequest request =- Type3ConversionRequest.builder()- .font(font)- .fontId("F1")- .fontUid("uid1")- .pageNumber(1)- .build();-- List<PdfJsonFontConversionCandidate> result = service.synthesize(request);- assertEquals(1, result.size());- assertEquals(PdfJsonFontConversionStatus.UNSUPPORTED, result.get(0).getStatus());- assertTrue(result.get(0).getMessage().contains("check failed"));- }-- @Test- void synthesize_nullStrategyInList_isSkipped() throws IOException {- PdfJsonFontConversionCandidate candidate =- PdfJsonFontConversionCandidate.builder()- .status(PdfJsonFontConversionStatus.SUCCESS)- .message("OK")- .build();- Type3ConversionStrategy goodStrategy = mock(Type3ConversionStrategy.class);- when(goodStrategy.isAvailable()).thenReturn(true);- when(goodStrategy.supports(any(), any())).thenReturn(true);- when(goodStrategy.convert(any(), any())).thenReturn(candidate);- when(goodStrategy.getId()).thenReturn("good");- when(goodStrategy.getLabel()).thenReturn("Good");-- List<Type3ConversionStrategy> strategies = new java.util.ArrayList<>();- strategies.add(null);- strategies.add(goodStrategy);-- Type3GlyphExtractor extractor = mock(Type3GlyphExtractor.class);- Type3FontConversionService service = new Type3FontConversionService(strategies, extractor);- PDType3Font font = mock(PDType3Font.class);- Type3ConversionRequest request =- Type3ConversionRequest.builder().font(font).fontId("F1").pageNumber(1).build();-- List<PdfJsonFontConversionCandidate> result = service.synthesize(request);- assertEquals(1, result.size());- assertEquals(PdfJsonFontConversionStatus.SUCCESS, result.get(0).getStatus());- }-}diff --git a/app/core/src/test/java/stirling/software/SPDF/service/pdfjson/type3/Type3FontSignatureCalculatorTest.java b/app/core/src/test/java/stirling/software/SPDF/service/pdfjson/type3/Type3FontSignatureCalculatorTest.javadeleted file mode 100644index a212831785..0000000000--- a/app/core/src/test/java/stirling/software/SPDF/service/pdfjson/type3/Type3FontSignatureCalculatorTest.java+++ /dev/null@@ -1,131 +0,0 @@-package stirling.software.SPDF.service.pdfjson.type3;--import static org.junit.jupiter.api.Assertions.*;-import static org.mockito.Mockito.*;--import java.io.IOException;--import org.apache.pdfbox.cos.COSDictionary;-import org.apache.pdfbox.cos.COSName;-import org.apache.pdfbox.cos.COSStream;-import org.apache.pdfbox.pdmodel.common.PDRectangle;-import org.apache.pdfbox.pdmodel.font.PDType3Font;-import org.apache.pdfbox.pdmodel.font.encoding.Encoding;-import org.apache.pdfbox.util.Matrix;-import org.junit.jupiter.api.Test;--class Type3FontSignatureCalculatorTest {-- @Test- void computeSignature_nullFont_returnsNull() throws IOException {- assertNull(Type3FontSignatureCalculator.computeSignature(null));- }-- @Test- void computeSignature_returnsHashWithSha256Prefix() throws IOException {- PDType3Font font = mockMinimalFont();- String signature = Type3FontSignatureCalculator.computeSignature(font);- assertNotNull(signature);- assertTrue(signature.startsWith("sha256:"), "Signature should start with sha256:");- }-- @Test- void computeSignature_deterministic() throws IOException {- PDType3Font font = mockMinimalFont();- String sig1 = Type3FontSignatureCalculator.computeSignature(font);- String sig2 = Type3FontSignatureCalculator.computeSignature(font);- assertEquals(sig1, sig2, "Same font should produce same signature");- }-- @Test- void computeSignature_hexLength() throws IOException {- PDType3Font font = mockMinimalFont();- String signature = Type3FontSignatureCalculator.computeSignature(font);- // sha256: prefix + 64 hex chars- String hex = signature.substring("sha256:".length());- assertEquals(64, hex.length(), "SHA-256 hash should be 64 hex characters");- assertTrue(hex.matches("[0-9a-f]+"), "Hex should be lowercase hex");- }-- @Test- void computeSignature_noEncoding() throws IOException {- PDType3Font font = mockMinimalFont();- when(font.getEncoding()).thenReturn(null);- String signature = Type3FontSignatureCalculator.computeSignature(font);- assertNotNull(signature);- assertTrue(signature.startsWith("sha256:"));- }-- @Test- void computeSignature_noCharProcs() throws IOException {- PDType3Font font = mockMinimalFont();- COSDictionary cosDict = font.getCOSObject();- when(cosDict.getDictionaryObject(COSName.CHAR_PROCS)).thenReturn(null);- String signature = Type3FontSignatureCalculator.computeSignature(font);- assertNotNull(signature);- }-- @Test- void computeSignature_emptyCharProcs() throws IOException {- PDType3Font font = mockMinimalFont();- COSDictionary charProcs = new COSDictionary();- COSDictionary cosDict = font.getCOSObject();- when(cosDict.getDictionaryObject(COSName.CHAR_PROCS)).thenReturn(charProcs);- String signature = Type3FontSignatureCalculator.computeSignature(font);- assertNotNull(signature);- }-- @Test- void computeSignature_withCharProcsStream() throws Exception {- PDType3Font font = mockMinimalFont();- COSDictionary cosDict = font.getCOSObject();- COSDictionary charProcs = new COSDictionary();-- COSStream stream = new COSStream();- try (java.io.OutputStream os = stream.createOutputStream()) {- os.write(new byte[] {0x01, 0x02, 0x03});- }-- COSName glyphName = COSName.getPDFName("A");- charProcs.setItem(glyphName, stream);- when(cosDict.getDictionaryObject(COSName.CHAR_PROCS)).thenReturn(charProcs);-- Encoding encoding = mock(Encoding.class);- when(encoding.getName(65)).thenReturn("A");- when(font.getEncoding()).thenReturn(encoding);- when(font.getWidthFromFont(65)).thenReturn(600f);-- String signature = Type3FontSignatureCalculator.computeSignature(font);- assertNotNull(signature);- assertTrue(signature.startsWith("sha256:"));- }-- @Test- void computeSignature_nullMatrix() throws IOException {- PDType3Font font = mockMinimalFont();- when(font.getFontMatrix()).thenReturn(null);- String signature = Type3FontSignatureCalculator.computeSignature(font);- assertNotNull(signature);- }-- @Test- void computeSignature_nullBBox() throws IOException {- PDType3Font font = mockMinimalFont();- when(font.getFontBBox()).thenReturn(null);- String signature = Type3FontSignatureCalculator.computeSignature(font);- assertNotNull(signature);- }-- private PDType3Font mockMinimalFont() {- PDType3Font font = mock(PDType3Font.class);- COSDictionary cosDict = mock(COSDictionary.class);- when(font.getCOSObject()).thenReturn(cosDict);- when(font.getFontMatrix()).thenReturn(new Matrix());- when(font.getFontBBox()).thenReturn(new PDRectangle());- when(cosDict.getDictionaryObject(COSName.CHAR_PROCS)).thenReturn(null);-- Encoding encoding = mock(Encoding.class);- when(font.getEncoding()).thenReturn(encoding);- return font;- }-}diff --git a/app/core/src/test/java/stirling/software/SPDF/service/pdfjson/type3/Type3GlyphContextTest.java b/app/core/src/test/java/stirling/software/SPDF/service/pdfjson/type3/Type3GlyphContextTest.javadeleted file mode 100644index dafcd0c6aa..0000000000--- a/app/core/src/test/java/stirling/software/SPDF/service/pdfjson/type3/Type3GlyphContextTest.java+++ /dev/null@@ -1,122 +0,0 @@-package stirling.software.SPDF.service.pdfjson.type3;--import static org.junit.jupiter.api.Assertions.*;-import static org.mockito.Mockito.*;--import java.io.IOException;-import java.util.List;--import org.apache.pdfbox.pdmodel.PDDocument;-import org.apache.pdfbox.pdmodel.font.PDType3Font;-import org.junit.jupiter.api.Test;--import stirling.software.SPDF.service.pdfjson.type3.model.Type3GlyphOutline;--class Type3GlyphContextTest {-- @Test- void getFont_returnsFontFromRequest() {- PDType3Font font = mock(PDType3Font.class);- Type3ConversionRequest request =- Type3ConversionRequest.builder().font(font).fontId("F1").pageNumber(1).build();- Type3GlyphExtractor extractor = mock(Type3GlyphExtractor.class);- Type3GlyphContext ctx = new Type3GlyphContext(request, extractor);- assertSame(font, ctx.getFont());- }-- @Test- void getGlyphs_delegatesToExtractor() throws IOException {- PDDocument doc = mock(PDDocument.class);- PDType3Font font = mock(PDType3Font.class);- Type3ConversionRequest request =- Type3ConversionRequest.builder()- .document(doc)- .font(font)- .fontId("F1")- .pageNumber(2)- .build();- Type3GlyphExtractor extractor = mock(Type3GlyphExtractor.class);- List<Type3GlyphOutline> expected =- List.of(- Type3GlyphOutline.builder()- .glyphName("A")- .charCode(65)- .advanceWidth(500f)- .build());- when(extractor.extractGlyphs(doc, font, "F1", 2)).thenReturn(expected);-- Type3GlyphContext ctx = new Type3GlyphContext(request, extractor);- List<Type3GlyphOutline> result = ctx.getGlyphs();- assertSame(expected, result);- }-- @Test- void getGlyphs_cachesResult() throws IOException {- PDDocument doc = mock(PDDocument.class);- PDType3Font font = mock(PDType3Font.class);- Type3ConversionRequest request =- Type3ConversionRequest.builder()- .document(doc)- .font(font)- .fontId("F1")- .pageNumber(1)- .build();- Type3GlyphExtractor extractor = mock(Type3GlyphExtractor.class);- List<Type3GlyphOutline> expected = List.of();- when(extractor.extractGlyphs(doc, font, "F1", 1)).thenReturn(expected);-- Type3GlyphContext ctx = new Type3GlyphContext(request, extractor);- List<Type3GlyphOutline> first = ctx.getGlyphs();- List<Type3GlyphOutline> second = ctx.getGlyphs();- assertSame(first, second);- verify(extractor, times(1)).extractGlyphs(doc, font, "F1", 1);- }-- @Test- void getGlyphs_propagatesIOException() throws IOException {- PDDocument doc = mock(PDDocument.class);- PDType3Font font = mock(PDType3Font.class);- Type3ConversionRequest request =- Type3ConversionRequest.builder()- .document(doc)- .font(font)- .fontId("F1")- .pageNumber(1)- .build();- Type3GlyphExtractor extractor = mock(Type3GlyphExtractor.class);- when(extractor.extractGlyphs(doc, font, "F1", 1))- .thenThrow(new IOException("extraction failed"));-- Type3GlyphContext ctx = new Type3GlyphContext(request, extractor);- assertThrows(IOException.class, ctx::getGlyphs);- }-- @Test- void getGlyphs_nullDocumentInRequest() throws IOException {- PDType3Font font = mock(PDType3Font.class);- Type3ConversionRequest request =- Type3ConversionRequest.builder()- .document(null)- .font(font)- .fontId("F1")- .pageNumber(1)- .build();- Type3GlyphExtractor extractor = mock(Type3GlyphExtractor.class);- when(extractor.extractGlyphs(null, font, "F1", 1)).thenReturn(List.of());-- Type3GlyphContext ctx = new Type3GlyphContext(request, extractor);- List<Type3GlyphOutline> result = ctx.getGlyphs();- assertNotNull(result);- assertTrue(result.isEmpty());- }-- @Test- void constructor_storesRequestAndExtractor() {- PDType3Font font = mock(PDType3Font.class);- Type3ConversionRequest request =- Type3ConversionRequest.builder().font(font).fontId("F2").pageNumber(3).build();- Type3GlyphExtractor extractor = mock(Type3GlyphExtractor.class);- Type3GlyphContext ctx = new Type3GlyphContext(request, extractor);- assertSame(font, ctx.getFont());- }-}diff --git a/app/core/src/test/java/stirling/software/SPDF/service/pdfjson/type3/Type3GlyphExtractorTest.java b/app/core/src/test/java/stirling/software/SPDF/service/pdfjson/type3/Type3GlyphExtractorTest.javadeleted file mode 100644index e526d72216..0000000000--- a/app/core/src/test/java/stirling/software/SPDF/service/pdfjson/type3/Type3GlyphExtractorTest.java+++ /dev/null@@ -1,71 +0,0 @@-package stirling.software.SPDF.service.pdfjson.type3;--import static org.junit.jupiter.api.Assertions.*;-import static org.mockito.Mockito.*;--import java.io.IOException;-import java.util.List;--import org.apache.pdfbox.cos.COSDictionary;-import org.apache.pdfbox.cos.COSName;-import org.apache.pdfbox.pdmodel.PDDocument;-import org.apache.pdfbox.pdmodel.font.PDType3Font;-import org.junit.jupiter.api.Test;--import stirling.software.SPDF.service.pdfjson.type3.model.Type3GlyphOutline;--class Type3GlyphExtractorTest {-- @Test- void extractGlyphs_nullFont_throwsNPE() {- Type3GlyphExtractor extractor = new Type3GlyphExtractor();- PDDocument doc = mock(PDDocument.class);- assertThrows(NullPointerException.class, () -> extractor.extractGlyphs(doc, null, "F1", 1));- }-- @Test- void extractGlyphs_nullCharProcs_returnsEmpty() throws IOException {- Type3GlyphExtractor extractor = new Type3GlyphExtractor();- PDDocument doc = mock(PDDocument.class);- PDType3Font font = mock(PDType3Font.class);- COSDictionary cosDict = mock(COSDictionary.class);- when(font.getCOSObject()).thenReturn(cosDict);- when(cosDict.getDictionaryObject(COSName.CHAR_PROCS)).thenReturn(null);-- List<Type3GlyphOutline> result = extractor.extractGlyphs(doc, font, "F1", 1);- assertNotNull(result);- assertTrue(result.isEmpty());- }-- @Test- void extractGlyphs_emptyCharProcs_returnsEmpty() throws IOException {- Type3GlyphExtractor extractor = new Type3GlyphExtractor();- PDDocument doc = mock(PDDocument.class);- PDType3Font font = mock(PDType3Font.class);- COSDictionary cosDict = mock(COSDictionary.class);- COSDictionary charProcs = new COSDictionary();- when(font.getCOSObject()).thenReturn(cosDict);- when(cosDict.getDictionaryObject(COSName.CHAR_PROCS)).thenReturn(charProcs);-- List<Type3GlyphOutline> result = extractor.extractGlyphs(doc, font, "F1", 1);- assertNotNull(result);- assertTrue(result.isEmpty());- }-- @Test- void extractGlyphs_charProcNotStream_skipped() throws IOException {- Type3GlyphExtractor extractor = new Type3GlyphExtractor();- PDDocument doc = mock(PDDocument.class);- PDType3Font font = mock(PDType3Font.class);- COSDictionary cosDict = mock(COSDictionary.class);- COSDictionary charProcs = new COSDictionary();- // Add a non-stream entry- charProcs.setItem(COSName.getPDFName("A"), new COSDictionary());- when(font.getCOSObject()).thenReturn(cosDict);- when(cosDict.getDictionaryObject(COSName.CHAR_PROCS)).thenReturn(charProcs);-- List<Type3GlyphOutline> result = extractor.extractGlyphs(doc, font, "F1", 1);- assertNotNull(result);- assertTrue(result.isEmpty());- }-}diff --git a/app/core/src/test/java/stirling/software/SPDF/service/pdfjson/type3/Type3GraphicsEngineTest.java b/app/core/src/test/java/stirling/software/SPDF/service/pdfjson/type3/Type3GraphicsEngineTest.javadeleted file mode 100644index 99fc299457..0000000000--- a/app/core/src/test/java/stirling/software/SPDF/service/pdfjson/type3/Type3GraphicsEngineTest.java+++ /dev/null@@ -1,158 +0,0 @@-package stirling.software.SPDF.service.pdfjson.type3;--import static org.junit.jupiter.api.Assertions.*;--import java.awt.geom.GeneralPath;-import java.awt.geom.PathIterator;-import java.awt.geom.Point2D;-import java.io.IOException;--import org.apache.pdfbox.pdmodel.PDPage;-import org.apache.pdfbox.pdmodel.common.PDRectangle;-import org.junit.jupiter.api.BeforeEach;-import org.junit.jupiter.api.Test;--class Type3GraphicsEngineTest {-- private Type3GraphicsEngine engine;-- @BeforeEach- void setUp() {- engine = new Type3GraphicsEngine(new PDPage(new PDRectangle()));- }-- @Test- void initialState_noFlags() {- assertFalse(engine.isSawStroke());- assertFalse(engine.isSawFill());- assertFalse(engine.isSawImage());- assertFalse(engine.isSawText());- assertFalse(engine.isSawShading());- assertNull(engine.getWarnings());- }-- @Test- void getCurrentPoint_initiallyNull() throws IOException {- assertNull(engine.getCurrentPoint());- }-- @Test- void moveTo_setsCurrentPoint() throws IOException {- engine.moveTo(10f, 20f);- Point2D pt = engine.getCurrentPoint();- assertNotNull(pt);- assertEquals(10f, pt.getX(), 0.001);- assertEquals(20f, pt.getY(), 0.001);- }-- @Test- void lineTo_updatesCurrentPoint() throws IOException {- engine.moveTo(0f, 0f);- engine.lineTo(5f, 10f);- Point2D pt = engine.getCurrentPoint();- assertEquals(5f, pt.getX(), 0.001);- assertEquals(10f, pt.getY(), 0.001);- }-- @Test- void curveTo_updatesCurrentPoint() throws IOException {- engine.moveTo(0f, 0f);- engine.curveTo(1f, 2f, 3f, 4f, 5f, 6f);- Point2D pt = engine.getCurrentPoint();- assertEquals(5f, pt.getX(), 0.001);- assertEquals(6f, pt.getY(), 0.001);- }-- @Test- void strokePath_setsSawStrokeAndAccumulatesPath() throws IOException {- engine.moveTo(0f, 0f);- engine.lineTo(10f, 10f);- engine.strokePath();- assertTrue(engine.isSawStroke());- GeneralPath path = engine.getAccumulatedPath();- assertFalse(path.getBounds2D().isEmpty());- }-- @Test- void fillPath_setsSawFill() throws IOException {- engine.moveTo(0f, 0f);- engine.lineTo(10f, 0f);- engine.lineTo(10f, 10f);- engine.closePath();- engine.fillPath(1);- assertTrue(engine.isSawFill());- }-- @Test- void fillAndStrokePath_setsBothFlags() throws IOException {- engine.moveTo(0f, 0f);- engine.lineTo(10f, 0f);- engine.lineTo(10f, 10f);- engine.closePath();- engine.fillAndStrokePath(0);- assertTrue(engine.isSawFill());- assertTrue(engine.isSawStroke());- }-- @Test- void drawImage_setsSawImage() throws IOException {- engine.drawImage(null);- assertTrue(engine.isSawImage());- }-- @Test- void shadingFill_setsSawShading() throws IOException {- engine.shadingFill(null);- assertTrue(engine.isSawShading());- }-- @Test- void endPath_resetsCurrentPoint() throws IOException {- engine.moveTo(5f, 5f);- assertNotNull(engine.getCurrentPoint());- engine.endPath();- assertNull(engine.getCurrentPoint());- }-- @Test- void getAccumulatedPath_returnsCopy() throws IOException {- engine.moveTo(0f, 0f);- engine.lineTo(10f, 10f);- engine.strokePath();- GeneralPath p1 = engine.getAccumulatedPath();- GeneralPath p2 = engine.getAccumulatedPath();- assertNotSame(p1, p2);- }-- @Test- void appendRectangle_createsClosedPath() throws IOException {- Point2D p0 = new Point2D.Float(0f, 0f);- Point2D p1 = new Point2D.Float(10f, 0f);- Point2D p2 = new Point2D.Float(10f, 10f);- Point2D p3 = new Point2D.Float(0f, 10f);- engine.appendRectangle(p0, p1, p2, p3);- engine.strokePath();- GeneralPath path = engine.getAccumulatedPath();- assertFalse(path.getBounds2D().isEmpty());- }-- @Test- void process_withNullCharProc_doesNotThrow() throws IOException {- engine.process(null);- assertFalse(engine.isSawStroke());- assertFalse(engine.isSawFill());- }-- @Test- void fillPath_evenOddWindingRule() throws IOException {- engine.moveTo(0f, 0f);- engine.lineTo(10f, 0f);- engine.lineTo(10f, 10f);- engine.closePath();- engine.fillPath(0); // 0 -> WIND_EVEN_ODD- assertTrue(engine.isSawFill());- GeneralPath path = engine.getAccumulatedPath();- PathIterator it = path.getPathIterator(null);- assertEquals(GeneralPath.WIND_NON_ZERO, it.getWindingRule());- }-}diff --git a/app/core/src/test/java/stirling/software/SPDF/service/pdfjson/type3/Type3LibraryStrategyTest.java b/app/core/src/test/java/stirling/software/SPDF/service/pdfjson/type3/Type3LibraryStrategyTest.javadeleted file mode 100644index 44829674f0..0000000000--- a/app/core/src/test/java/stirling/software/SPDF/service/pdfjson/type3/Type3LibraryStrategyTest.java+++ /dev/null@@ -1,188 +0,0 @@-package stirling.software.SPDF.service.pdfjson.type3;--import static org.junit.jupiter.api.Assertions.*;-import static org.mockito.Mockito.*;--import java.io.IOException;--import org.apache.pdfbox.pdmodel.font.PDType3Font;-import org.junit.jupiter.api.Test;--import stirling.software.SPDF.model.json.PdfJsonFontConversionCandidate;-import stirling.software.SPDF.model.json.PdfJsonFontConversionStatus;-import stirling.software.SPDF.service.pdfjson.type3.library.Type3FontLibrary;-import stirling.software.SPDF.service.pdfjson.type3.library.Type3FontLibraryEntry;-import stirling.software.SPDF.service.pdfjson.type3.library.Type3FontLibraryMatch;-import stirling.software.SPDF.service.pdfjson.type3.library.Type3FontLibraryPayload;-import stirling.software.common.model.ApplicationProperties;--class Type3LibraryStrategyTest {-- @Test- void getId_returnsExpected() {- Type3FontLibrary lib = mock(Type3FontLibrary.class);- ApplicationProperties props = mock(ApplicationProperties.class);- Type3LibraryStrategy strategy = new Type3LibraryStrategy(lib, props);- assertEquals("type3-library", strategy.getId());- }-- @Test- void getLabel_returnsExpected() {- Type3FontLibrary lib = mock(Type3FontLibrary.class);- ApplicationProperties props = mock(ApplicationProperties.class);- Type3LibraryStrategy strategy = new Type3LibraryStrategy(lib, props);- assertEquals("Type3 Font Library", strategy.getLabel());- }-- @Test- void isAvailable_notEnabled_returnsFalse() {- Type3FontLibrary lib = mock(Type3FontLibrary.class);- ApplicationProperties props = mock(ApplicationProperties.class);- Type3LibraryStrategy strategy = new Type3LibraryStrategy(lib, props);- // enabled defaults to false since PostConstruct hasn't run- assertFalse(strategy.isAvailable());- }-- @Test- void convert_nullRequest_returnsFailure() throws IOException {- Type3FontLibrary lib = mock(Type3FontLibrary.class);- ApplicationProperties props = mock(ApplicationProperties.class);- Type3LibraryStrategy strategy = new Type3LibraryStrategy(lib, props);-- PdfJsonFontConversionCandidate result = strategy.convert(null, null);- assertEquals(PdfJsonFontConversionStatus.FAILURE, result.getStatus());- assertEquals("No font supplied", result.getMessage());- }-- @Test- void convert_nullFont_returnsFailure() throws IOException {- Type3FontLibrary lib = mock(Type3FontLibrary.class);- ApplicationProperties props = mock(ApplicationProperties.class);- Type3LibraryStrategy strategy = new Type3LibraryStrategy(lib, props);- Type3ConversionRequest request = Type3ConversionRequest.builder().font(null).build();-- PdfJsonFontConversionCandidate result = strategy.convert(request, null);- assertEquals(PdfJsonFontConversionStatus.FAILURE, result.getStatus());- }-- @Test- void convert_notAvailable_returnsSkipped() throws IOException {- Type3FontLibrary lib = mock(Type3FontLibrary.class);- ApplicationProperties props = mock(ApplicationProperties.class);- Type3LibraryStrategy strategy = new Type3LibraryStrategy(lib, props);- PDType3Font font = mock(PDType3Font.class);- Type3ConversionRequest request =- Type3ConversionRequest.builder().font(font).fontId("F1").fontUid("uid1").build();-- PdfJsonFontConversionCandidate result = strategy.convert(request, null);- assertEquals(PdfJsonFontConversionStatus.SKIPPED, result.getStatus());- assertEquals("Library disabled", result.getMessage());- }-- @Test- void convert_noMatch_returnsUnsupported() throws Exception {- Type3FontLibrary lib = mock(Type3FontLibrary.class);- when(lib.isLoaded()).thenReturn(true);- when(lib.match(any(), any())).thenReturn(null);-- ApplicationProperties props = mockEnabledProps();- Type3LibraryStrategy strategy = new Type3LibraryStrategy(lib, props);- // Manually enable by calling loadConfiguration via PostConstruct- invokePostConstruct(strategy);-- PDType3Font font = mock(PDType3Font.class);- Type3ConversionRequest request =- Type3ConversionRequest.builder().font(font).fontId("F1").fontUid("uid1").build();-- PdfJsonFontConversionCandidate result = strategy.convert(request, null);- assertEquals(PdfJsonFontConversionStatus.UNSUPPORTED, result.getStatus());- }-- @Test- void convert_matchWithPayload_returnsSuccess() throws Exception {- Type3FontLibraryPayload payload = new Type3FontLibraryPayload("AQID", "ttf");- Type3FontLibraryEntry entry =- Type3FontLibraryEntry.builder()- .id("entry1")- .label("Test Entry")- .program(payload)- .glyphCode(65)- .glyphCode(66)- .build();- Type3FontLibraryMatch match =- Type3FontLibraryMatch.builder()- .entry(entry)- .matchType("signature")- .signature("sha256:abc")- .build();-- Type3FontLibrary lib = mock(Type3FontLibrary.class);- when(lib.isLoaded()).thenReturn(true);- when(lib.match(any(), any())).thenReturn(match);-- ApplicationProperties props = mockEnabledProps();- Type3LibraryStrategy strategy = new Type3LibraryStrategy(lib, props);- invokePostConstruct(strategy);-- PDType3Font font = mock(PDType3Font.class);- Type3ConversionRequest request =- Type3ConversionRequest.builder().font(font).fontId("F1").fontUid("uid1").build();-- PdfJsonFontConversionCandidate result = strategy.convert(request, null);- assertEquals(PdfJsonFontConversionStatus.SUCCESS, result.getStatus());- assertEquals("AQID", result.getProgram());- assertEquals("ttf", result.getProgramFormat());- assertNotNull(result.getGlyphCoverage());- assertEquals(2, result.getGlyphCoverage().length);- assertTrue(result.getMessage().contains("Test Entry"));- }-- @Test- void convert_matchNoPayload_returnsFailure() throws Exception {- Type3FontLibraryEntry entry =- Type3FontLibraryEntry.builder().id("entry1").label("No Payload").build();- Type3FontLibraryMatch match =- Type3FontLibraryMatch.builder()- .entry(entry)- .matchType("alias:test")- .signature("sha256:def")- .build();-- Type3FontLibrary lib = mock(Type3FontLibrary.class);- when(lib.isLoaded()).thenReturn(true);- when(lib.match(any(), any())).thenReturn(match);-- ApplicationProperties props = mockEnabledProps();- Type3LibraryStrategy strategy = new Type3LibraryStrategy(lib, props);- invokePostConstruct(strategy);-- PDType3Font font = mock(PDType3Font.class);- Type3ConversionRequest request =- Type3ConversionRequest.builder().font(font).fontId("F1").fontUid("uid1").build();-- PdfJsonFontConversionCandidate result = strategy.convert(request, null);- assertEquals(PdfJsonFontConversionStatus.FAILURE, result.getStatus());- assertEquals("Library entry has no payloads", result.getMessage());- }-- private ApplicationProperties mockEnabledProps() {- ApplicationProperties props = mock(ApplicationProperties.class);- ApplicationProperties.PdfEditor pdfEditor = mock(ApplicationProperties.PdfEditor.class);- ApplicationProperties.PdfEditor.Type3 type3 =- mock(ApplicationProperties.PdfEditor.Type3.class);- ApplicationProperties.PdfEditor.Type3.Library library =- mock(ApplicationProperties.PdfEditor.Type3.Library.class);- when(props.getPdfEditor()).thenReturn(pdfEditor);- when(pdfEditor.getType3()).thenReturn(type3);- when(type3.getLibrary()).thenReturn(library);- when(library.isEnabled()).thenReturn(true);- return props;- }-- private void invokePostConstruct(Type3LibraryStrategy strategy) throws Exception {- java.lang.reflect.Method method =- Type3LibraryStrategy.class.getDeclaredMethod("loadConfiguration");- method.setAccessible(true);- method.invoke(strategy);- }-}diff --git a/app/core/src/test/java/stirling/software/SPDF/service/pdfjson/type3/library/Type3FontLibraryEntryTest.java b/app/core/src/test/java/stirling/software/SPDF/service/pdfjson/type3/library/Type3FontLibraryEntryTest.javadeleted file mode 100644index d73cf78116..0000000000--- a/app/core/src/test/java/stirling/software/SPDF/service/pdfjson/type3/library/Type3FontLibraryEntryTest.java+++ /dev/null@@ -1,128 +0,0 @@-package stirling.software.SPDF.service.pdfjson.type3.library;--import static org.junit.jupiter.api.Assertions.*;--import java.util.List;--import org.junit.jupiter.api.Test;--class Type3FontLibraryEntryTest {-- @Test- void hasAnyPayload_noPayloads_returnsFalse() {- Type3FontLibraryEntry entry =- Type3FontLibraryEntry.builder().id("test").label("Test").build();- assertFalse(entry.hasAnyPayload());- }-- @Test- void hasAnyPayload_withProgram_returnsTrue() {- Type3FontLibraryPayload payload = new Type3FontLibraryPayload("AQID", "ttf");- Type3FontLibraryEntry entry =- Type3FontLibraryEntry.builder().id("test").label("Test").program(payload).build();- assertTrue(entry.hasAnyPayload());- }-- @Test- void hasAnyPayload_withWebProgram_returnsTrue() {- Type3FontLibraryPayload payload = new Type3FontLibraryPayload("AQID", "woff2");- Type3FontLibraryEntry entry =- Type3FontLibraryEntry.builder()- .id("test")- .label("Test")- .webProgram(payload)- .build();- assertTrue(entry.hasAnyPayload());- }-- @Test- void hasAnyPayload_withPdfProgram_returnsTrue() {- Type3FontLibraryPayload payload = new Type3FontLibraryPayload("AQID", "otf");- Type3FontLibraryEntry entry =- Type3FontLibraryEntry.builder()- .id("test")- .label("Test")- .pdfProgram(payload)- .build();- assertTrue(entry.hasAnyPayload());- }-- @Test- void hasAnyPayload_blankBase64_returnsFalse() {- Type3FontLibraryPayload payload = new Type3FontLibraryPayload(" ", "ttf");- Type3FontLibraryEntry entry =- Type3FontLibraryEntry.builder().id("test").label("Test").program(payload).build();- assertFalse(entry.hasAnyPayload());- }-- @Test- void builder_signatures() {- Type3FontLibraryEntry entry =- Type3FontLibraryEntry.builder()- .id("test")- .label("Test")- .signature("sha256:abc")- .signature("sha256:def")- .build();- assertEquals(2, entry.getSignatures().size());- assertEquals("sha256:abc", entry.getSignatures().get(0));- }-- @Test- void builder_aliases() {- Type3FontLibraryEntry entry =- Type3FontLibraryEntry.builder()- .id("test")- .label("Test")- .alias("TimesNewRoman")- .alias("ABCDEF+TimesNewRoman")- .build();- assertEquals(2, entry.getAliases().size());- }-- @Test- void builder_glyphCoverage() {- Type3FontLibraryEntry entry =- Type3FontLibraryEntry.builder()- .id("test")- .label("Test")- .glyphCode(65)- .glyphCode(66)- .glyphCode(67)- .build();- assertEquals(List.of(65, 66, 67), entry.getGlyphCoverage());- }-- @Test- void builder_emptyCollections() {- Type3FontLibraryEntry entry =- Type3FontLibraryEntry.builder().id("test").label("Test").build();- assertNotNull(entry.getSignatures());- assertTrue(entry.getSignatures().isEmpty());- assertNotNull(entry.getAliases());- assertTrue(entry.getAliases().isEmpty());- assertNotNull(entry.getGlyphCoverage());- assertTrue(entry.getGlyphCoverage().isEmpty());- }-- @Test- void valueSemantics() {- Type3FontLibraryPayload payload = new Type3FontLibraryPayload("AQID", "ttf");- Type3FontLibraryEntry a =- Type3FontLibraryEntry.builder()- .id("test")- .label("Test")- .program(payload)- .source("manual")- .build();- Type3FontLibraryEntry b =- Type3FontLibraryEntry.builder()- .id("test")- .label("Test")- .program(payload)- .source("manual")- .build();- assertEquals(a, b);- assertEquals(a.hashCode(), b.hashCode());- }-}diff --git a/app/core/src/test/java/stirling/software/SPDF/service/pdfjson/type3/library/Type3FontLibraryMatchTest.java b/app/core/src/test/java/stirling/software/SPDF/service/pdfjson/type3/library/Type3FontLibraryMatchTest.javadeleted file mode 100644index 094da5f39b..0000000000--- a/app/core/src/test/java/stirling/software/SPDF/service/pdfjson/type3/library/Type3FontLibraryMatchTest.java+++ /dev/null@@ -1,89 +0,0 @@-package stirling.software.SPDF.service.pdfjson.type3.library;--import static org.junit.jupiter.api.Assertions.*;--import org.junit.jupiter.api.Test;--class Type3FontLibraryMatchTest {-- @Test- void builder_allFields() {- Type3FontLibraryPayload payload = new Type3FontLibraryPayload("AQID", "ttf");- Type3FontLibraryEntry entry =- Type3FontLibraryEntry.builder()- .id("entry1")- .label("Entry 1")- .program(payload)- .build();- Type3FontLibraryMatch match =- Type3FontLibraryMatch.builder()- .entry(entry)- .matchType("signature")- .signature("sha256:abc123")- .build();-- assertSame(entry, match.getEntry());- assertEquals("signature", match.getMatchType());- assertEquals("sha256:abc123", match.getSignature());- }-- @Test- void builder_nullEntry() {- Type3FontLibraryMatch match =- Type3FontLibraryMatch.builder()- .entry(null)- .matchType("alias:test")- .signature(null)- .build();-- assertNull(match.getEntry());- assertEquals("alias:test", match.getMatchType());- assertNull(match.getSignature());- }-- @Test- void valueSemantics() {- Type3FontLibraryEntry entry = Type3FontLibraryEntry.builder().id("e1").label("E1").build();- Type3FontLibraryMatch a =- Type3FontLibraryMatch.builder()- .entry(entry)- .matchType("signature")- .signature("sha256:abc")- .build();- Type3FontLibraryMatch b =- Type3FontLibraryMatch.builder()- .entry(entry)- .matchType("signature")- .signature("sha256:abc")- .build();- assertEquals(a, b);- assertEquals(a.hashCode(), b.hashCode());- }-- @Test- void toString_containsFields() {- Type3FontLibraryEntry entry = Type3FontLibraryEntry.builder().id("e1").label("E1").build();- Type3FontLibraryMatch match =- Type3FontLibraryMatch.builder()- .entry(entry)- .matchType("signature")- .signature("sha256:abc")- .build();- String str = match.toString();- assertTrue(str.contains("signature"));- assertTrue(str.contains("sha256:abc"));- }-- @Test- void builder_aliasMatchType() {- Type3FontLibraryEntry entry = Type3FontLibraryEntry.builder().id("e2").label("E2").build();- Type3FontLibraryMatch match =- Type3FontLibraryMatch.builder()- .entry(entry)- .matchType("alias:timesnewroman")- .signature("sha256:def456")- .build();-- assertEquals("alias:timesnewroman", match.getMatchType());- }-}diff --git a/app/core/src/test/java/stirling/software/SPDF/service/pdfjson/type3/library/Type3FontLibraryPayloadTest.java b/app/core/src/test/java/stirling/software/SPDF/service/pdfjson/type3/library/Type3FontLibraryPayloadTest.javadeleted file mode 100644index a3a88765bc..0000000000--- a/app/core/src/test/java/stirling/software/SPDF/service/pdfjson/type3/library/Type3FontLibraryPayloadTest.java+++ /dev/null@@ -1,88 +0,0 @@-package stirling.software.SPDF.service.pdfjson.type3.library;--import static org.junit.jupiter.api.Assertions.*;-import static org.mockito.Mockito.*;--import java.io.ByteArrayInputStream;-import java.io.IOException;--import org.junit.jupiter.api.Test;-import org.springframework.core.io.Resource;--class Type3FontLibraryPayloadTest {-- @Test- void hasPayload_validBase64_returnsTrue() {- Type3FontLibraryPayload payload = new Type3FontLibraryPayload("AQID", "ttf");- assertTrue(payload.hasPayload());- }-- @Test- void hasPayload_nullBase64_returnsFalse() {- Type3FontLibraryPayload payload = new Type3FontLibraryPayload((String) null, "ttf");- assertFalse(payload.hasPayload());- }-- @Test- void hasPayload_emptyBase64_returnsFalse() {- Type3FontLibraryPayload payload = new Type3FontLibraryPayload("", "ttf");- assertFalse(payload.hasPayload());- }-- @Test- void hasPayload_blankBase64_returnsFalse() {- Type3FontLibraryPayload payload = new Type3FontLibraryPayload(" ", "ttf");- assertFalse(payload.hasPayload());- }-- @Test- void getters() {- Type3FontLibraryPayload payload = new Type3FontLibraryPayload("AQID", "woff2");- assertEquals("AQID", payload.getBase64());- assertEquals("woff2", payload.getFormat());- }-- @Test- void nullFormat() {- Type3FontLibraryPayload payload = new Type3FontLibraryPayload("AQID", null);- assertTrue(payload.hasPayload());- assertNull(payload.getFormat());- }-- @Test- void valueSemantics() {- Type3FontLibraryPayload a = new Type3FontLibraryPayload("AQID", "ttf");- Type3FontLibraryPayload b = new Type3FontLibraryPayload("AQID", "ttf");- assertEquals(a, b);- assertEquals(a.hashCode(), b.hashCode());- }-- @Test- void getBase64_ioFailure_cooldownsThenRetries() throws Exception {- Resource resource = mock(Resource.class);- when(resource.getDescription()).thenReturn("test-resource");- when(resource.getInputStream())- .thenThrow(new IOException("first read"))- .thenReturn(new ByteArrayInputStream(new byte[] {1, 2, 3}));- Type3FontLibraryPayload payload = new Type3FontLibraryPayload(resource, "ttf");-- assertNull(payload.getBase64());- assertNull(payload.getBase64());- verify(resource, times(1)).getInputStream();-- java.lang.reflect.Field retryAfterNanos =- Type3FontLibraryPayload.class.getDeclaredField("retryAfterNanos");- retryAfterNanos.setAccessible(true);- retryAfterNanos.setLong(payload, 0);-- assertEquals("AQID", payload.getBase64());- verify(resource, times(2)).getInputStream();- }-- @Test- void valueSemantics_different() {- Type3FontLibraryPayload a = new Type3FontLibraryPayload("AQID", "ttf");- Type3FontLibraryPayload b = new Type3FontLibraryPayload("BAMC", "ttf");- assertNotEquals(a, b);- }-}diff --git a/app/core/src/test/java/stirling/software/SPDF/service/pdfjson/type3/library/Type3FontLibraryTest.java b/app/core/src/test/java/stirling/software/SPDF/service/pdfjson/type3/library/Type3FontLibraryTest.javadeleted file mode 100644index 1383bb2c5e..0000000000--- a/app/core/src/test/java/stirling/software/SPDF/service/pdfjson/type3/library/Type3FontLibraryTest.java+++ /dev/null@@ -1,568 +0,0 @@-package stirling.software.SPDF.service.pdfjson.type3.library;--import static org.assertj.core.api.Assertions.assertThat;-import static org.junit.jupiter.api.Assertions.*;-import static org.mockito.Mockito.*;--import java.io.ByteArrayInputStream;-import java.io.IOException;-import java.lang.reflect.Field;-import java.lang.reflect.Method;-import java.nio.charset.StandardCharsets;-import java.util.Base64;-import java.util.List;-import java.util.Map;--import org.apache.pdfbox.cos.COSDictionary;-import org.apache.pdfbox.cos.COSName;-import org.apache.pdfbox.pdmodel.font.PDType3Font;-import org.junit.jupiter.api.BeforeEach;-import org.junit.jupiter.api.DisplayName;-import org.junit.jupiter.api.Nested;-import org.junit.jupiter.api.Test;-import org.mockito.MockedStatic;-import org.springframework.core.io.DefaultResourceLoader;-import org.springframework.core.io.Resource;-import org.springframework.core.io.ResourceLoader;--import stirling.software.SPDF.service.pdfjson.type3.Type3FontSignatureCalculator;-import stirling.software.common.model.ApplicationProperties;--import tools.jackson.databind.ObjectMapper;-import tools.jackson.databind.json.JsonMapper;--/**- * Gap coverage for Type3FontLibrary - exercises initialise(), match() and the private payload /- * resource / alias helpers via reflection and a real classpath resource loader.- */-class Type3FontLibraryTest {-- private final ObjectMapper objectMapper = JsonMapper.builder().build();- private final ResourceLoader resourceLoader = new DefaultResourceLoader();-- private Type3FontLibrary newLibrary(ResourceLoader loader, ApplicationProperties props) {- return new Type3FontLibrary(objectMapper, loader, props);- }-- private ApplicationProperties propsWithIndex(String indexLocation) {- ApplicationProperties props = new ApplicationProperties();- props.getPdfEditor().getType3().getLibrary().setIndex(indexLocation);- return props;- }-- private void invokeInitialise(Type3FontLibrary library) throws Exception {- Method m = Type3FontLibrary.class.getDeclaredMethod("initialise");- m.setAccessible(true);- m.invoke(library);- }-- private Object invoke(Type3FontLibrary library, String method, Class<?>[] sig, Object... args)- throws Exception {- Method m = Type3FontLibrary.class.getDeclaredMethod(method, sig);- m.setAccessible(true);- return m.invoke(library, args);- }-- private Object rawPayload(Class<?> type, String resource, String format, String base64)- throws Exception {- java.lang.reflect.Constructor<?> constructor = type.getDeclaredConstructor();- constructor.setAccessible(true);- Object payload = constructor.newInstance();- java.lang.reflect.Field resourceField = type.getDeclaredField("resource");- resourceField.setAccessible(true);- resourceField.set(payload, resource);- java.lang.reflect.Field formatField = type.getDeclaredField("format");- formatField.setAccessible(true);- formatField.set(payload, format);- java.lang.reflect.Field base64Field = type.getDeclaredField("base64");- base64Field.setAccessible(true);- base64Field.set(payload, base64);- return payload;- }-- @Nested- @DisplayName("initialise()")- class Initialise {-- @Test- @DisplayName("loads real classpath index.json and populates entries / indexes")- void initialise_realIndex_loadsEntries() throws Exception {- Type3FontLibrary library =- newLibrary(- new DefaultResourceLoader(),- propsWithIndex("classpath:/type3/library/index.json"));- invokeInitialise(library);-- assertTrue(library.isLoaded());- }-- @Test- @DisplayName("missing index disables library")- void initialise_missingIndex_disabled() throws Exception {- Type3FontLibrary library =- newLibrary(- new DefaultResourceLoader(),- propsWithIndex("classpath:/type3/library/does-not-exist.json"));- invokeInitialise(library);-- assertFalse(library.isLoaded());- }-- @Test- @DisplayName("null Type3 config disables library and logs warning")- void initialise_nullConfig_disabled() throws Exception {- ApplicationProperties props = mock(ApplicationProperties.class);- ApplicationProperties.PdfEditor pdfEditor = mock(ApplicationProperties.PdfEditor.class);- when(props.getPdfEditor()).thenReturn(pdfEditor);- when(pdfEditor.getType3()).thenReturn(null);-- Type3FontLibrary library = newLibrary(new DefaultResourceLoader(), props);- invokeInitialise(library);-- assertFalse(library.isLoaded());- }-- @Test- @DisplayName("null pdfEditor disables library")- void initialise_nullPdfEditor_disabled() throws Exception {- ApplicationProperties props = mock(ApplicationProperties.class);- when(props.getPdfEditor()).thenReturn(null);-- Type3FontLibrary library = newLibrary(new DefaultResourceLoader(), props);- invokeInitialise(library);-- assertFalse(library.isLoaded());- }-- @Test- @DisplayName("malformed JSON index surfaces a Jackson read exception")- void initialise_malformedJson_throws() throws Exception {- ResourceLoader loader = mock(ResourceLoader.class);- Resource resource = mock(Resource.class);- when(loader.getResource("classpath:/bad.json")).thenReturn(resource);- when(resource.exists()).thenReturn(true);- when(resource.getInputStream())- .thenReturn(- new ByteArrayInputStream("not json".getBytes(StandardCharsets.UTF_8)));-- Type3FontLibrary library = newLibrary(loader, propsWithIndex("classpath:/bad.json"));- // Jackson 3 throws an unchecked StreamReadException which the IOException-only- // catch in initialise() does not handle, so it propagates.- java.lang.reflect.InvocationTargetException ex =- assertThrows(- java.lang.reflect.InvocationTargetException.class,- () -> invokeInitialise(library));- assertNotNull(ex.getCause());- assertFalse(library.isLoaded());- }-- @Test- @DisplayName("inline base64 program entry is loaded and indexed by signature + alias")- void initialise_inlineBase64_loaded() throws Exception {- String base64 = Base64.getEncoder().encodeToString(new byte[] {1, 2, 3, 4});- String json =- "[{\"id\":\"e1\",\"label\":\"E1\","- + "\"signatures\":[\"sha256:ABCDEF\"],"- + "\"aliases\":[\"ABCDEF+MyFont\",\" \",null],"- + "\"program\":{\"base64\":\""- + base64- + "\",\"format\":\"TTF\"},"- + "\"glyphCoverage\":[65,null,66]}]";- ResourceLoader loader = mock(ResourceLoader.class);- Resource resource = mock(Resource.class);- when(loader.getResource("classpath:/inline.json")).thenReturn(resource);- when(resource.exists()).thenReturn(true);- when(resource.getInputStream())- .thenReturn(new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8)));-- Type3FontLibrary library = newLibrary(loader, propsWithIndex("classpath:/inline.json"));- invokeInitialise(library);-- assertTrue(library.isLoaded());- }-- @Test- @DisplayName("entry with no payload is filtered out")- void initialise_noPayload_filtered() throws Exception {- String json = "[{\"id\":\"empty\",\"label\":\"Empty\"}]";- ResourceLoader loader = mock(ResourceLoader.class);- Resource resource = mock(Resource.class);- when(loader.getResource("classpath:/empty.json")).thenReturn(resource);- when(resource.exists()).thenReturn(true);- when(resource.getInputStream())- .thenReturn(new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8)));-- Type3FontLibrary library = newLibrary(loader, propsWithIndex("classpath:/empty.json"));- invokeInitialise(library);-- assertFalse(library.isLoaded());- }-- @Test- @DisplayName("entry with null id is skipped")- void initialise_nullId_skipped() throws Exception {- String base64 = Base64.getEncoder().encodeToString(new byte[] {9, 9, 9, 9});- String json = "[{\"label\":\"NoId\",\"program\":{\"base64\":\"" + base64 + "\"}}]";- ResourceLoader loader = mock(ResourceLoader.class);- Resource resource = mock(Resource.class);- when(loader.getResource("classpath:/noid.json")).thenReturn(resource);- when(resource.exists()).thenReturn(true);- when(resource.getInputStream())- .thenReturn(new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8)));-- Type3FontLibrary library = newLibrary(loader, propsWithIndex("classpath:/noid.json"));- invokeInitialise(library);-- assertFalse(library.isLoaded());- }-- @Test- @DisplayName("direct base64 payloads are not confused by a shared resource key")- void loadPayloadCached_directBase64_bypassesResourceCache() throws Exception {- Type3FontLibrary library =- newLibrary(new DefaultResourceLoader(), new ApplicationProperties());- Class<?> rawType = Class.forName(Type3FontLibrary.class.getName() + "$RawPayload");- Object first = rawPayload(rawType, "type3/library/fonts/missing.ttf", "ttf", "AQID");- Object second = rawPayload(rawType, "type3/library/fonts/missing.ttf", "ttf", "BAUG");- Method method = Type3FontLibrary.class.getDeclaredMethod("loadPayloadCached", rawType);- method.setAccessible(true);-- Type3FontLibraryPayload firstLoaded =- (Type3FontLibraryPayload) method.invoke(library, first);- Type3FontLibraryPayload secondLoaded =- (Type3FontLibraryPayload) method.invoke(library, second);-- assertEquals("AQID", firstLoaded.getBase64());- assertEquals("BAUG", secondLoaded.getBase64());- }-- @Test- @DisplayName("missing sibling resource keeps a valid direct payload")- void initialise_missingSiblingResource_keepsEntry() throws Exception {- String json =- "[{\"id\":\"mixed\",\"label\":\"Mixed\","- + "\"program\":{\"resource\":\"type3/library/fonts/missing.ttf\","- + "\"format\":\"ttf\"},"- + "\"webProgram\":{\"base64\":\"AQID\",\"format\":\"ttf\"}}]";- ResourceLoader loader = spy(new DefaultResourceLoader());- Resource indexResource = mock(Resource.class);- when(loader.getResource("classpath:/mixed.json")).thenReturn(indexResource);- when(indexResource.exists()).thenReturn(true);- when(indexResource.getInputStream())- .thenReturn(new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8)));-- Type3FontLibrary library = newLibrary(loader, propsWithIndex("classpath:/mixed.json"));- invokeInitialise(library);-- assertTrue(library.isLoaded());- }-- @Test- @DisplayName("resource-based payload is read and re-encoded to base64")- void initialise_resourcePayload_loaded() throws Exception {- String json =- "[{\"id\":\"res\",\"label\":\"Res\","- + "\"program\":{\"resource\":\"type3/library/fonts/dejavu/DejaVuSans.ttf\","- + "\"format\":\"ttf\"}}]";- ResourceLoader loader = new DefaultResourceLoader();- Resource indexResource = mock(Resource.class);- ResourceLoader spyLoader = spy(loader);- when(spyLoader.getResource("classpath:/res.json")).thenReturn(indexResource);- when(indexResource.exists()).thenReturn(true);- when(indexResource.getInputStream())- .thenReturn(new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8)));-- Type3FontLibrary library = newLibrary(spyLoader, propsWithIndex("classpath:/res.json"));- invokeInitialise(library);-- assertTrue(library.isLoaded());- }- }-- @Nested- @DisplayName("match()")- class Match {-- @Test- @DisplayName("returns null when font is null")- void match_nullFont_returnsNull() throws Exception {- Type3FontLibrary library =- newLibrary(- new DefaultResourceLoader(),- propsWithIndex("classpath:/type3/library/index.json"));- invokeInitialise(library);- assertNull(library.match(null, "uid"));- }-- @Test- @DisplayName("returns null when no entries loaded")- void match_emptyLibrary_returnsNull() throws Exception {- Type3FontLibrary library =- newLibrary(- new DefaultResourceLoader(),- propsWithIndex("classpath:/type3/library/does-not-exist.json"));- invokeInitialise(library);- PDType3Font font = mock(PDType3Font.class);- assertNull(library.match(font, "uid"));- }-- @Test- @DisplayName("matches by signature using mocked signature calculator")- void match_bySignature_returnsSignatureMatch() throws Exception {- String base64 = Base64.getEncoder().encodeToString(new byte[] {1, 2, 3, 4});- String json =- "[{\"id\":\"sig-entry\",\"label\":\"SigEntry\","- + "\"signatures\":[\"sha256:DEADBEEF\"],"- + "\"program\":{\"base64\":\""- + base64- + "\"}}]";- Type3FontLibrary library = libraryFromJson("classpath:/sig.json", json);-- PDType3Font font = mock(PDType3Font.class);- try (MockedStatic<Type3FontSignatureCalculator> mocked =- mockStatic(Type3FontSignatureCalculator.class)) {- mocked.when(() -> Type3FontSignatureCalculator.computeSignature(font))- .thenReturn("sha256:deadbeef");-- Type3FontLibraryMatch match = library.match(font, "uid-1");- assertNotNull(match);- assertEquals("signature", match.getMatchType());- assertEquals("sig-entry", match.getEntry().getId());- assertEquals("sha256:deadbeef", match.getSignature());- }- }-- @Test- @DisplayName("falls back to alias match on BaseFont name")- void match_byAlias_returnsAliasMatch() throws Exception {- String base64 = Base64.getEncoder().encodeToString(new byte[] {1, 2, 3, 4});- String json =- "[{\"id\":\"alias-entry\",\"label\":\"AliasEntry\","- + "\"aliases\":[\"ABCDEF+CoolFont\"],"- + "\"program\":{\"base64\":\""- + base64- + "\"}}]";- Type3FontLibrary library = libraryFromJson("classpath:/alias.json", json);-- PDType3Font font = mock(PDType3Font.class);- when(font.getName()).thenReturn("XYZXYZ+CoolFont");-- try (MockedStatic<Type3FontSignatureCalculator> mocked =- mockStatic(Type3FontSignatureCalculator.class)) {- mocked.when(() -> Type3FontSignatureCalculator.computeSignature(font))- .thenReturn(null);-- Type3FontLibraryMatch match = library.match(font, "uid-2");- assertNotNull(match);- assertThat(match.getMatchType()).startsWith("alias:");- assertEquals("alias-entry", match.getEntry().getId());- }- }-- @Test- @DisplayName("no signature and no alias match returns null")- void match_noMatch_returnsNull() throws Exception {- String base64 = Base64.getEncoder().encodeToString(new byte[] {1, 2, 3, 4});- String json =- "[{\"id\":\"only\",\"label\":\"Only\","- + "\"signatures\":[\"sha256:1111\"],"- + "\"program\":{\"base64\":\""- + base64- + "\"}}]";- Type3FontLibrary library = libraryFromJson("classpath:/nomatch.json", json);-- PDType3Font font = mock(PDType3Font.class);- when(font.getName()).thenReturn("Unrelated");-- try (MockedStatic<Type3FontSignatureCalculator> mocked =- mockStatic(Type3FontSignatureCalculator.class)) {- mocked.when(() -> Type3FontSignatureCalculator.computeSignature(font))- .thenReturn("sha256:9999");-- assertNull(library.match(font, "uid-3"));- }- }-- @Test- @DisplayName("alias resolution falls back to COS BASE_FONT when getName throws")- void match_baseFontFromCos_whenGetNameThrows() throws Exception {- String base64 = Base64.getEncoder().encodeToString(new byte[] {1, 2, 3, 4});- String json =- "[{\"id\":\"cos-entry\",\"label\":\"CosEntry\","- + "\"aliases\":[\"CosFont\"],"- + "\"program\":{\"base64\":\""- + base64- + "\"}}]";- Type3FontLibrary library = libraryFromJson("classpath:/cos.json", json);-- PDType3Font font = mock(PDType3Font.class);- when(font.getName()).thenThrow(new RuntimeException("boom"));- COSDictionary cos = new COSDictionary();- cos.setName(COSName.BASE_FONT, "CosFont");- when(font.getCOSObject()).thenReturn(cos);-- try (MockedStatic<Type3FontSignatureCalculator> mocked =- mockStatic(Type3FontSignatureCalculator.class)) {- mocked.when(() -> Type3FontSignatureCalculator.computeSignature(font))- .thenReturn(null);-- Type3FontLibraryMatch match = library.match(font, "uid-4");- assertNotNull(match);- assertEquals("cos-entry", match.getEntry().getId());- }- }- }-- @Nested- @DisplayName("private helpers")- class Helpers {-- private Type3FontLibrary library() {- return newLibrary(new DefaultResourceLoader(), new ApplicationProperties());- }-- @Test- @DisplayName("normalizeAlias strips subset prefix and lowercases")- void normalizeAlias_stripsPrefix() throws Exception {- Type3FontLibrary lib = library();- assertEquals(- "myfont",- invoke(lib, "normalizeAlias", new Class<?>[] {String.class}, "ABCDEF+MyFont"));- assertEquals(- "plainname",- invoke(lib, "normalizeAlias", new Class<?>[] {String.class}, " PlainName "));- assertNull(invoke(lib, "normalizeAlias", new Class<?>[] {String.class}, (Object) null));- assertNull(invoke(lib, "normalizeAlias", new Class<?>[] {String.class}, " "));- // Trailing plus keeps original since plus is at end- assertEquals(- "name+", invoke(lib, "normalizeAlias", new Class<?>[] {String.class}, "Name+"));- }-- @Test- @DisplayName("normalizeFormat trims and lowercases, null stays null")- void normalizeFormat() throws Exception {- Type3FontLibrary lib = library();- assertEquals(- "ttf", invoke(lib, "normalizeFormat", new Class<?>[] {String.class}, " TTF "));- assertNull(- invoke(lib, "normalizeFormat", new Class<?>[] {String.class}, (Object) null));- }-- @Test- @DisplayName("resolveLocation adds classpath prefix appropriately")- void resolveLocation() throws Exception {- Type3FontLibrary lib = library();- assertEquals(- "classpath:/a/b.ttf",- invoke(lib, "resolveLocation", new Class<?>[] {String.class}, "a/b.ttf"));- assertEquals(- "classpath:/abs.ttf",- invoke(lib, "resolveLocation", new Class<?>[] {String.class}, "/abs.ttf"));- assertEquals(- "file:/x.ttf",- invoke(lib, "resolveLocation", new Class<?>[] {String.class}, "file:/x.ttf"));- assertNull(- invoke(lib, "resolveLocation", new Class<?>[] {String.class}, (Object) null));- }-- @SuppressWarnings("unchecked")- @Test- @DisplayName("normalizeList trims, drops null/blank entries")- void normalizeList() throws Exception {- Type3FontLibrary lib = library();- List<String> in = java.util.Arrays.asList(" a ", null, "", "b");- List<String> out =- (List<String>) invoke(lib, "normalizeList", new Class<?>[] {List.class}, in);- assertEquals(List.of("a", "b"), out);-- List<String> empty =- (List<String>)- invoke(- lib,- "normalizeList",- new Class<?>[] {List.class},- (Object) null);- assertTrue(empty.isEmpty());- }-- @Test- @DisplayName("loadResourceBytes throws for null / missing resource")- void loadResourceBytes_errors() throws Exception {- Type3FontLibrary lib = library();- Method m = Type3FontLibrary.class.getDeclaredMethod("loadResourceBytes", String.class);- m.setAccessible(true);-- java.lang.reflect.InvocationTargetException ex1 =- assertThrows(- java.lang.reflect.InvocationTargetException.class,- () -> m.invoke(lib, (Object) null));- assertInstanceOf(IOException.class, ex1.getCause());-- java.lang.reflect.InvocationTargetException ex2 =- assertThrows(- java.lang.reflect.InvocationTargetException.class,- () -> m.invoke(lib, "type3/library/missing-font.ttf"));- assertInstanceOf(IOException.class, ex2.getCause());- }- }-- private Type3FontLibrary libraryFromJson(String location, String json) throws Exception {- ResourceLoader loader = mock(ResourceLoader.class);- Resource resource = mock(Resource.class);- when(loader.getResource(location)).thenReturn(resource);- when(resource.exists()).thenReturn(true);- when(resource.getInputStream())- .thenReturn(new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8)));- Type3FontLibrary library = newLibrary(loader, propsWithIndex(location));- invokeInitialise(library);- return library;- }-- @BeforeEach- void resetState() {- // no shared state- }-- @Nested- @DisplayName("payload edge cases")- class PayloadEdges {-- @SuppressWarnings("unused")- @Test- @DisplayName("invalid base64 payload yields null payload (entry filtered)")- void invalidBase64_filtered() throws Exception {- // '@' is not valid base64 in the 4-char probe prefix- String json =- "[{\"id\":\"badb64\",\"label\":\"Bad\","- + "\"program\":{\"base64\":\"@@@@invalid\"}}]";- Type3FontLibrary library = libraryFromJson("classpath:/badb64.json", json);- assertFalse(library.isLoaded());- }-- @Test- @DisplayName("internal index maps are populated for loaded entry")- void internalMaps_populated() throws Exception {- String base64 = Base64.getEncoder().encodeToString(new byte[] {1, 2, 3, 4});- String json =- "[{\"id\":\"mapcheck\",\"label\":\"MapCheck\","- + "\"signatures\":[\"sha256:CAFE\"],"- + "\"aliases\":[\"MapAlias\"],"- + "\"program\":{\"base64\":\""- + base64- + "\"}}]";- Type3FontLibrary library = libraryFromJson("classpath:/mapcheck.json", json);-- Field sigIndex = Type3FontLibrary.class.getDeclaredField("signatureIndex");- sigIndex.setAccessible(true);- Field aliasIndex = Type3FontLibrary.class.getDeclaredField("aliasIndex");- aliasIndex.setAccessible(true);-- @SuppressWarnings("unchecked")- Map<String, ?> sigs = (Map<String, ?>) sigIndex.get(library);- @SuppressWarnings("unchecked")- Map<String, ?> aliases = (Map<String, ?>) aliasIndex.get(library);- assertThat(sigs).containsKey("sha256:cafe");- assertThat(aliases).containsKey("mapalias");- }- }-}diff --git a/app/core/src/test/java/stirling/software/SPDF/service/pdfjson/type3/model/Type3GlyphOutlineTest.java b/app/core/src/test/java/stirling/software/SPDF/service/pdfjson/type3/model/Type3GlyphOutlineTest.javadeleted file mode 100644index d57e03409c..0000000000--- a/app/core/src/test/java/stirling/software/SPDF/service/pdfjson/type3/model/Type3GlyphOutlineTest.java+++ /dev/null@@ -1,121 +0,0 @@-package stirling.software.SPDF.service.pdfjson.type3.model;--import static org.junit.jupiter.api.Assertions.*;--import java.awt.geom.GeneralPath;--import org.apache.pdfbox.pdmodel.common.PDRectangle;-import org.junit.jupiter.api.Test;--class Type3GlyphOutlineTest {-- @Test- void builder_allFields() {- GeneralPath path = new GeneralPath();- PDRectangle bbox = new PDRectangle(0, 0, 100, 100);- Type3GlyphOutline outline =- Type3GlyphOutline.builder()- .glyphName("A")- .charCode(65)- .advanceWidth(500f)- .boundingBox(bbox)- .outline(path)- .hasFill(true)- .hasStroke(false)- .hasImages(false)- .hasText(false)- .hasShading(false)- .warnings("test warning")- .unicode(65)- .build();-- assertEquals("A", outline.getGlyphName());- assertEquals(65, outline.getCharCode());- assertEquals(500f, outline.getAdvanceWidth(), 0.001);- assertSame(bbox, outline.getBoundingBox());- assertSame(path, outline.getOutline());- assertTrue(outline.isHasFill());- assertFalse(outline.isHasStroke());- assertFalse(outline.isHasImages());- assertFalse(outline.isHasText());- assertFalse(outline.isHasShading());- assertEquals("test warning", outline.getWarnings());- assertEquals(65, outline.getUnicode());- }-- @Test- void builder_minimalFields() {- Type3GlyphOutline outline =- Type3GlyphOutline.builder()- .glyphName("space")- .charCode(32)- .advanceWidth(250f)- .build();-- assertEquals("space", outline.getGlyphName());- assertEquals(32, outline.getCharCode());- assertNull(outline.getBoundingBox());- assertNull(outline.getOutline());- assertNull(outline.getWarnings());- assertNull(outline.getUnicode());- }-- @Test- void builder_negativeCharCode() {- Type3GlyphOutline outline =- Type3GlyphOutline.builder()- .glyphName("unknown")- .charCode(-1)- .advanceWidth(0f)- .build();-- assertEquals(-1, outline.getCharCode());- }-- @Test- void builder_zeroAdvanceWidth() {- Type3GlyphOutline outline =- Type3GlyphOutline.builder().glyphName("dot").charCode(46).advanceWidth(0f).build();-- assertEquals(0f, outline.getAdvanceWidth(), 0.001);- }-- @Test- void builder_nullGlyphName() {- Type3GlyphOutline outline =- Type3GlyphOutline.builder().glyphName(null).charCode(0).advanceWidth(0f).build();-- assertNull(outline.getGlyphName());- }-- @Test- void builder_withAllFeatureFlags() {- Type3GlyphOutline outline =- Type3GlyphOutline.builder()- .glyphName("complex")- .charCode(100)- .advanceWidth(700f)- .hasFill(true)- .hasStroke(true)- .hasImages(true)- .hasText(true)- .hasShading(true)- .build();-- assertTrue(outline.isHasFill());- assertTrue(outline.isHasStroke());- assertTrue(outline.isHasImages());- assertTrue(outline.isHasText());- assertTrue(outline.isHasShading());- }-- @Test- void equals_sameValues() {- Type3GlyphOutline a =- Type3GlyphOutline.builder().glyphName("A").charCode(65).advanceWidth(500f).build();- Type3GlyphOutline b =- Type3GlyphOutline.builder().glyphName("A").charCode(65).advanceWidth(500f).build();- assertEquals(a, b);- assertEquals(a.hashCode(), b.hashCode());- }-}diff --git a/app/core/src/test/java/stirling/software/SPDF/service/pdfjson/type3/tool/Type3SignatureToolMoreTest.java b/app/core/src/test/java/stirling/software/SPDF/service/pdfjson/type3/tool/Type3SignatureToolMoreTest.javadeleted file mode 100644index 6a534ac18c..0000000000--- a/app/core/src/test/java/stirling/software/SPDF/service/pdfjson/type3/tool/Type3SignatureToolMoreTest.java+++ /dev/null@@ -1,249 +0,0 @@-package stirling.software.SPDF.service.pdfjson.type3.tool;--import static org.assertj.core.api.Assertions.assertThat;-import static org.junit.jupiter.api.Assertions.*;--import java.io.ByteArrayOutputStream;-import java.io.PrintStream;-import java.nio.file.Files;-import java.nio.file.Path;--import org.apache.pdfbox.cos.COSArray;-import org.apache.pdfbox.cos.COSDictionary;-import org.apache.pdfbox.cos.COSName;-import org.apache.pdfbox.cos.COSStream;-import org.apache.pdfbox.pdmodel.PDDocument;-import org.apache.pdfbox.pdmodel.PDPage;-import org.apache.pdfbox.pdmodel.PDPageContentStream;-import org.apache.pdfbox.pdmodel.PDResources;-import org.apache.pdfbox.pdmodel.common.PDRectangle;-import org.apache.pdfbox.pdmodel.font.PDFont;-import org.apache.pdfbox.pdmodel.font.PDType1Font;-import org.apache.pdfbox.pdmodel.font.Standard14Fonts;-import org.junit.jupiter.api.DisplayName;-import org.junit.jupiter.api.Nested;-import org.junit.jupiter.api.Test;-import org.junit.jupiter.api.io.TempDir;--/**- * Gap coverage for Type3SignatureTool - exercises the real PDF scanning path (collectType3Fonts /- * scanResources / describeFont / verifyOutput) by feeding it a PDF that embeds a Type3 font.- */-class Type3SignatureToolMoreTest {-- /** Builds a minimal-but-valid Type3 font dictionary with one glyph CharProc. */- private COSDictionary buildType3FontDict() {- COSDictionary font = new COSDictionary();- font.setItem(COSName.TYPE, COSName.FONT);- font.setItem(COSName.SUBTYPE, COSName.TYPE3);- font.setString(COSName.BASE_FONT, "ABCDEF+MyType3");-- COSArray matrix = new COSArray();- for (double v : new double[] {0.001, 0, 0, 0.001, 0, 0}) {- matrix.add(new org.apache.pdfbox.cos.COSFloat((float) v));- }- font.setItem(COSName.FONT_MATRIX, matrix);-- COSArray bbox = new COSArray();- for (int v : new int[] {0, 0, 750, 750}) {- bbox.add(org.apache.pdfbox.cos.COSInteger.get(v));- }- font.setItem(COSName.FONT_BBOX, bbox);-- font.setInt(COSName.FIRST_CHAR, 65);- font.setInt(COSName.LAST_CHAR, 65);- COSArray widths = new COSArray();- widths.add(org.apache.pdfbox.cos.COSInteger.get(600));- font.setItem(COSName.WIDTHS, widths);-- // Encoding dictionary mapping code 65 -> "A"- COSDictionary encoding = new COSDictionary();- encoding.setItem(COSName.TYPE, COSName.ENCODING);- COSArray differences = new COSArray();- differences.add(org.apache.pdfbox.cos.COSInteger.get(65));- differences.add(COSName.getPDFName("A"));- encoding.setItem(COSName.DIFFERENCES, differences);- font.setItem(COSName.ENCODING, encoding);-- // CharProcs with a tiny content stream for glyph "A"- COSDictionary charProcs = new COSDictionary();- COSStream glyphStream = new COSStream();- try (var os = glyphStream.createOutputStream()) {- os.write("600 0 0 0 750 750 d1\n".getBytes(java.nio.charset.StandardCharsets.US_ASCII));- } catch (Exception e) {- throw new RuntimeException(e);- }- charProcs.setItem(COSName.getPDFName("A"), glyphStream);- font.setItem(COSName.CHAR_PROCS, charProcs);-- return font;- }-- private Path writePdfWithType3(Path dir) throws Exception {- Path pdf = dir.resolve("type3.pdf");- try (PDDocument document = new PDDocument()) {- PDPage page = new PDPage(PDRectangle.LETTER);- document.addPage(page);- PDResources resources = new PDResources();- resources.getCOSObject().setItem(COSName.FONT, fontResourceDict());- page.setResources(resources);- document.save(pdf.toFile());- }- return pdf;- }-- private COSDictionary fontResourceDict() {- COSDictionary fonts = new COSDictionary();- fonts.setItem(COSName.getPDFName("F1"), buildType3FontDict());- return fonts;- }-- @Nested- @DisplayName("real PDF scanning")- class RealPdfScan {-- @Test- @DisplayName("writes JSON output file for a PDF containing a Type3 font")- void main_withType3Pdf_writesOutput(@TempDir Path dir) throws Exception {- Path pdf = writePdfWithType3(dir);- Path out = dir.resolve("out.json");-- PrintStream original = System.out;- ByteArrayOutputStream captured = new ByteArrayOutputStream();- System.setOut(new PrintStream(captured));- try {- Type3SignatureTool.main(- new String[] {- "--pdf", pdf.toString(), "--output", out.toString(), "--pretty"- });- } finally {- System.setOut(original);- }-- assertTrue(Files.exists(out));- String json = Files.readString(out);- assertThat(json).contains("\"fonts\"");- assertThat(json).contains("F1");- assertThat(json).contains("signature");- assertThat(captured.toString()).contains("verified");- }-- @Test- @DisplayName("writes JSON to stdout when no --output given")- void main_withType3Pdf_stdout(@TempDir Path dir) throws Exception {- Path pdf = writePdfWithType3(dir);-- PrintStream original = System.out;- ByteArrayOutputStream captured = new ByteArrayOutputStream();- System.setOut(new PrintStream(captured));- try {- Type3SignatureTool.main(new String[] {"--pdf", pdf.toString()});- } finally {- System.setOut(original);- }-- String output = captured.toString();- assertThat(output).contains("fonts");- assertThat(output).contains("F1");- }-- @Test- @DisplayName("output path with nested non-existent parent dirs is created")- void main_createsParentDirs(@TempDir Path dir) throws Exception {- Path pdf = writePdfWithType3(dir);- Path out = dir.resolve("nested/sub/out.json");-- PrintStream original = System.out;- System.setOut(new PrintStream(new ByteArrayOutputStream()));- try {- Type3SignatureTool.main(- new String[] {"--pdf", pdf.toString(), "--output", out.toString()});- } finally {- System.setOut(original);- }-- assertTrue(Files.exists(out));- }-- @Test- @DisplayName("PDF without Type3 fonts yields empty fonts array")- void main_noType3Fonts_emptyArray(@TempDir Path dir) throws Exception {- Path pdf = dir.resolve("plain.pdf");- try (PDDocument document = new PDDocument()) {- PDPage page = new PDPage(PDRectangle.LETTER);- document.addPage(page);- PDFont font = new PDType1Font(Standard14Fonts.FontName.HELVETICA);- try (PDPageContentStream cs = new PDPageContentStream(document, page)) {- cs.beginText();- cs.setFont(font, 12);- cs.newLineAtOffset(72, 700);- cs.showText("Hello");- cs.endText();- }- document.save(pdf.toFile());- }- Path out = dir.resolve("plain-out.json");-- PrintStream original = System.out;- System.setOut(new PrintStream(new ByteArrayOutputStream()));- try {- Type3SignatureTool.main(- new String[] {"--pdf", pdf.toString(), "--output", out.toString()});- } finally {- System.setOut(original);- }-- String json = Files.readString(out);- // The shared mapper always indents (INDENT_OUTPUT), so the array is "[ ]".- assertThat(json).contains("\"fonts\"");- assertThat(json.replaceAll("\\s", "")).contains("\"fonts\":[]");- }-- @Test- @DisplayName("Type3 font nested inside a form XObject is discovered")- void main_type3InFormXObject(@TempDir Path dir) throws Exception {- Path pdf = dir.resolve("nested-form.pdf");- try (PDDocument document = new PDDocument()) {- PDPage page = new PDPage(PDRectangle.LETTER);- document.addPage(page);-- // Build a form XObject whose resources contain the Type3 font.- COSStream formStream = new COSStream();- try (var os = formStream.createOutputStream()) {- os.write("".getBytes(java.nio.charset.StandardCharsets.US_ASCII));- }- formStream.setItem(COSName.TYPE, COSName.XOBJECT);- formStream.setItem(COSName.SUBTYPE, COSName.FORM);- COSArray formBBox = new COSArray();- for (int v : new int[] {0, 0, 100, 100}) {- formBBox.add(org.apache.pdfbox.cos.COSInteger.get(v));- }- formStream.setItem(COSName.BBOX, formBBox);- COSDictionary formResources = new COSDictionary();- formResources.setItem(COSName.FONT, fontResourceDict());- formStream.setItem(COSName.RESOURCES, formResources);-- COSDictionary xobjects = new COSDictionary();- xobjects.setItem(COSName.getPDFName("Fm0"), formStream);- PDResources pageResources = new PDResources();- pageResources.getCOSObject().setItem(COSName.XOBJECT, xobjects);- page.setResources(pageResources);-- document.save(pdf.toFile());- }- Path out = dir.resolve("nested-form-out.json");-- PrintStream original = System.out;- System.setOut(new PrintStream(new ByteArrayOutputStream()));- try {- Type3SignatureTool.main(- new String[] {"--pdf", pdf.toString(), "--output", out.toString()});- } finally {- System.setOut(original);- }-- String json = Files.readString(out);- assertThat(json).contains("F1");- }- }-}diff --git a/app/core/src/test/java/stirling/software/SPDF/service/pdfjson/type3/tool/Type3SignatureToolTest.java b/app/core/src/test/java/stirling/software/SPDF/service/pdfjson/type3/tool/Type3SignatureToolTest.javadeleted file mode 100644index cd1bd204ac..0000000000--- a/app/core/src/test/java/stirling/software/SPDF/service/pdfjson/type3/tool/Type3SignatureToolTest.java+++ /dev/null@@ -1,91 +0,0 @@-package stirling.software.SPDF.service.pdfjson.type3.tool;--import static org.junit.jupiter.api.Assertions.*;--import java.io.ByteArrayOutputStream;-import java.io.PrintStream;--import org.junit.jupiter.api.Test;--class Type3SignatureToolTest {-- @Test- void main_noArgs_printsUsage() throws Exception {- PrintStream originalOut = System.out;- ByteArrayOutputStream baos = new ByteArrayOutputStream();- System.setOut(new PrintStream(baos));- try {- Type3SignatureTool.main(new String[] {});- String output = baos.toString();- assertTrue(output.contains("Type3SignatureTool"));- assertTrue(output.contains("--pdf"));- } finally {- System.setOut(originalOut);- }- }-- @Test- void main_helpFlag_printsUsage() throws Exception {- PrintStream originalOut = System.out;- ByteArrayOutputStream baos = new ByteArrayOutputStream();- System.setOut(new PrintStream(baos));- try {- Type3SignatureTool.main(new String[] {"--help"});- String output = baos.toString();- assertTrue(output.contains("Type3SignatureTool"));- } finally {- System.setOut(originalOut);- }- }-- @Test- void main_nullArgs_printsUsage() throws Exception {- PrintStream originalOut = System.out;- ByteArrayOutputStream baos = new ByteArrayOutputStream();- System.setOut(new PrintStream(baos));- try {- Type3SignatureTool.main(null);- String output = baos.toString();- assertTrue(output.contains("Type3SignatureTool"));- } finally {- System.setOut(originalOut);- }- }-- @Test- void main_nonExistentPdf_throwsIOException() {- assertThrows(- Exception.class,- () ->- Type3SignatureTool.main(- new String[] {"--pdf", "/nonexistent/path/file.pdf"}));- }-- @Test- void main_shortHelpFlag_printsUsage() throws Exception {- PrintStream originalOut = System.out;- ByteArrayOutputStream baos = new ByteArrayOutputStream();- System.setOut(new PrintStream(baos));- try {- Type3SignatureTool.main(new String[] {"-h"});- String output = baos.toString();- assertTrue(output.contains("Type3SignatureTool"));- } finally {- System.setOut(originalOut);- }- }-- @Test- void main_prettyFlagWithoutPdf_printsUsage() throws Exception {- PrintStream originalOut = System.out;- ByteArrayOutputStream baos = new ByteArrayOutputStream();- System.setOut(new PrintStream(baos));- try {- Type3SignatureTool.main(new String[] {"--pretty"});- String output = baos.toString();- assertTrue(output.contains("Type3SignatureTool"));- } finally {- System.setOut(originalOut);- }- }-}diff --git a/app/core/src/test/java/stirling/software/common/controller/JobControllerUserAccessTest.java b/app/core/src/test/java/stirling/software/common/controller/JobControllerUserAccessTest.javaindex ecdaa01a16..ea1c1ce93e 100644--- a/app/core/src/test/java/stirling/software/common/controller/JobControllerUserAccessTest.java+++ b/app/core/src/test/java/stirling/software/common/controller/JobControllerUserAccessTest.java@@ -20,8 +20,8 @@ import org.springframework.test.util.ReflectionTestUtils;import jakarta.servlet.http.HttpServletRequest;-import stirling.software.SPDF.service.pdfjson.JobOwnershipServiceImpl;-import stirling.software.SPDF.service.pdfjson.NoOpJobOwnershipService;+import stirling.software.SPDF.service.JobOwnershipServiceImpl;+import stirling.software.SPDF.service.NoOpJobOwnershipService;import stirling.software.common.cluster.inprocess.InProcessClusterBackplane;import stirling.software.common.cluster.inprocess.InProcessJobStore;import stirling.software.common.cluster.inprocess.LocalDiskFileStore;diff --git a/app/proprietary/build.gradle b/app/proprietary/build.gradleindex f3bddfcb0d..ce93af4d5b 100644--- a/app/proprietary/build.gradle+++ b/app/proprietary/build.gradle@@ -124,14 +124,6 @@ processTestResources {tasks.register('prepareKotlinBuildScriptModel') {}-tasks.register('type3SignatureTool', JavaExec) {- group = 'type3'- description = 'Dump Type3 font signatures and glyph coverage for the Type3 library'- classpath = sourceSets.main.runtimeClasspath- mainClass = 'stirling.software.SPDF.service.pdfjson.type3.tool.Type3SignatureTool'- standardInput = System.in-}-// FailureKindTest asserts the enum against two files outside this project, found by walking up to// the repo root: the kind-to-code fixture the frontend also reads, and the English copy every kind// must have a key in. Gradle cannot infer either, so without this the task is up-to-date when onlydiff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PolicyExecutor.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PolicyExecutor.javaindex 3dc42a4158..5fb8753bee 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PolicyExecutor.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PolicyExecutor.java@@ -219,7 +219,7 @@ public class PolicyExecutor {for (Map.Entry<String, Object> entry : step.parameters().entrySet()) {if (entry.getValue() instanceof List<?> list) {if (containsStructuredElements(list)) {- // These endpoints (e.g. /security/redact redactions, /general/edit-text edits)+ // These endpoints (e.g. /security/redact redactions) bind a list of// bind a list of structured objects from a single JSON string field via a// property editor, so pre-serialize the whole list.body.add(entry.getKey(), objectMapper.writeValueAsString(list));diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/engine/PolicyExecutorTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/engine/PolicyExecutorTest.javaindex d87ad44eef..68ea8f9a92 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/policy/engine/PolicyExecutorTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/engine/PolicyExecutorTest.java@@ -210,34 +210,38 @@ class PolicyExecutorTest {@Testvoid structuredListParameterIsJsonEncodedAsSingleField() throws IOException {- String editText = "/api/v1/general/edit-text";- when(toolMetadataService.isMultiInput(editText)).thenReturn(false);- when(toolMetadataService.shouldUnpackZipResponse(editText)).thenReturn(false);- stubEndpoint(editText, pdf("edited", "edited.pdf"));+ String redact = "/api/v1/security/redact";+ when(toolMetadataService.isMultiInput(redact)).thenReturn(false);+ when(toolMetadataService.shouldUnpackZipResponse(redact)).thenReturn(false);+ stubEndpoint(redact, pdf("edited", "edited.pdf"));// LinkedHashMap so the serialized key order is deterministic for the assertion below.- Map<String, Object> edit = new LinkedHashMap<>();- edit.put("find", "foo");- edit.put("replace", "bar");+ Map<String, Object> redaction = new LinkedHashMap<>();+ redaction.put("page", 1);+ redaction.put("x", 10);+ redaction.put("y", 20);+ redaction.put("width", 100);+ redaction.put("height", 50);Map<String, Object> params = new LinkedHashMap<>();- params.put("edits", List.of(edit));- params.put("useRegex", false);+ params.put("redactions", List.of(redaction));+ params.put("convertPDFToImage", false);executor.execute(- definition(new PipelineStep(editText, params)),+ definition(new PipelineStep(redact, params)),PolicyInputs.of(List.of(pdf("in", "in.pdf"))),PolicyProgressListener.NOOP);@SuppressWarnings("unchecked")ArgumentCaptor<MultiValueMap<String, Object>> bodyCaptor =ArgumentCaptor.forClass(MultiValueMap.class);- verify(internalApiClient).post(eq(editText), bodyCaptor.capture());+ verify(internalApiClient).post(eq(redact), bodyCaptor.capture());MultiValueMap<String, Object> body = bodyCaptor.getValue();- List<Object> edits = body.get("edits");- assertNotNull(edits);- assertEquals(1, edits.size());- assertEquals("[{\"find\":\"foo\",\"replace\":\"bar\"}]", edits.get(0));+ List<Object> redactions = body.get("redactions");+ assertNotNull(redactions);+ assertEquals(1, redactions.size());+ assertEquals(+ "[{\"page\":1,\"x\":10,\"y\":20,\"width\":100,\"height\":50}]", redactions.get(0));}@Testdiff --git a/app/proprietary/src/test/java/stirling/software/proprietary/service/AiWorkflowServiceTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/service/AiWorkflowServiceTest.javaindex 15c07bab71..b99f7a30e2 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/service/AiWorkflowServiceTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/service/AiWorkflowServiceTest.java@@ -317,52 +317,52 @@ class AiWorkflowServiceTest {@Testvoid parameterListOfStructuredObjectsIsJsonEncodedAsSingleField() throws IOException {- // Endpoints like /general/edit-text and /security/redact bind a List<StructuredObject>- // from a single JSON form field via a property editor. The plan executor must- // pre-serialize such lists rather than splitting them into repeated form fields.- String editTextEndpoint = "/api/v1/general/edit-text";+ // Endpoints like /security/redact bind a List<StructuredObject> from a single JSON form+ // field via a property editor. The plan executor must pre-serialize such lists rather+ // than splitting them into repeated form fields.+ String redactEndpoint = "/api/v1/security/redact";MockMultipartFile input = pdf("input.pdf", "bytes");stubOrchestrator("""{"outcome":"plan",- "summary":"Find and replace",+ "summary":"Redact areas","steps":[{"tool":"%s","parameters":{- "edits":[{"find":"foo","replace":"bar"},{"find":"baz","replace":"qux"}],- "useRegex":false+ "redactions":[{"page":1,"x":10,"y":20,"width":100,"height":50},{"page":2,"x":5,"y":15,"width":80,"height":30}],+ "convertPDFToImage":false}}]}"""- .formatted(editTextEndpoint));- when(toolMetadataService.isMultiInput(editTextEndpoint)).thenReturn(false);- when(toolMetadataService.shouldUnpackZipResponse(editTextEndpoint)).thenReturn(false);- stubEndpoint(editTextEndpoint, pdfResource("edited", "edited.pdf"));+ .formatted(redactEndpoint));+ when(toolMetadataService.isMultiInput(redactEndpoint)).thenReturn(false);+ when(toolMetadataService.shouldUnpackZipResponse(redactEndpoint)).thenReturn(false);+ stubEndpoint(redactEndpoint, pdfResource("edited", "edited.pdf"));stubFileStorage();- service.orchestrate(requestFor(input, "find and replace"));+ service.orchestrate(requestFor(input, "redact areas"));@SuppressWarnings("unchecked")ArgumentCaptor<MultiValueMap<String, Object>> bodyCaptor =ArgumentCaptor.forClass(MultiValueMap.class);- verify(internalApiClient).post(eq(editTextEndpoint), bodyCaptor.capture());+ verify(internalApiClient).post(eq(redactEndpoint), bodyCaptor.capture());MultiValueMap<String, Object> body = bodyCaptor.getValue();// The structured-list field must be serialized as ONE JSON-string entry, not multiple// entries.- List<Object> editsValues = body.get("edits");- assertNotNull(editsValues);- assertEquals(1, editsValues.size());+ List<Object> redactionsValues = body.get("redactions");+ assertNotNull(redactionsValues);+ assertEquals(1, redactionsValues.size());assertEquals(- "[{\"find\":\"foo\",\"replace\":\"bar\"},{\"find\":\"baz\",\"replace\":\"qux\"}]",- editsValues.get(0));+ "[{\"page\":1,\"x\":10,\"y\":20,\"width\":100,\"height\":50},{\"page\":2,\"x\":5,\"y\":15,\"width\":80,\"height\":30}]",+ redactionsValues.get(0));// Primitive fields keep the original behavior (single value, not JSON-wrapped).- List<Object> useRegex = body.get("useRegex");- assertNotNull(useRegex);- assertEquals(1, useRegex.size());- assertEquals(false, useRegex.get(0));+ List<Object> convertPDFToImage = body.get("convertPDFToImage");+ assertNotNull(convertPDFToImage);+ assertEquals(1, convertPDFToImage.size());+ assertEquals(false, convertPDFToImage.get(0));}@Testdiff --git a/engine/pyproject.toml b/engine/pyproject.tomlindex 81298e69ca..6595928487 100644--- a/engine/pyproject.toml+++ b/engine/pyproject.toml@@ -51,7 +51,6 @@ cucumber = [tools = ["deep-translator>=1.11.4","defusedxml>=0.7.1",- "fonttools>=4.66.0","fpdf2>=2.8.8","openai>=3.19.2","requests>=2.34.2",diff --git a/engine/scripts/generate_tool_models.py b/engine/scripts/generate_tool_models.pyindex 34e2f59736..51f05b6c57 100644--- a/engine/scripts/generate_tool_models.py+++ b/engine/scripts/generate_tool_models.py@@ -130,9 +130,6 @@ class ToolDiscovery:# 1. Cert-signing family: needs certificate/key files the agent can't supply, plus# interactive session and hardware-token management. The whole subtree is dropped."/api/v1/security/cert-sign",- # 2. Interactive PDF text-editor endpoints, not one-shot operations.- "/api/v1/convert/pdf/text-editor",- "/api/v1/convert/text-editor/pdf",# 3. Introspection / query endpoints that return metadata, a listing, or a# verification verdict rather than a transformed document, so they belong to# the question path, not the edit agent. (decompress is a dev-only stream op.)diff --git a/engine/src/stirling/models/tool_io.py b/engine/src/stirling/models/tool_io.pyindex fa7ce7a29c..583a47bbf9 100644--- a/engine/src/stirling/models/tool_io.py+++ b/engine/src/stirling/models/tool_io.py@@ -175,7 +175,6 @@ TOOL_IO: dict[ToolEndpoint, ToolIOSpec] = {ToolEndpoint.EDIT_TABLE_OF_CONTENTS: ToolIOSpec(accepts=[ToolFormat.PDF], produces=ToolFormat.PDF, arity=ToolArity.SISO),- ToolEndpoint.EDIT_TEXT: ToolIOSpec(accepts=[ToolFormat.PDF], produces=ToolFormat.PDF, arity=ToolArity.SISO),ToolEndpoint.MERGE_PDFS: ToolIOSpec(accepts=[ToolFormat.PDF, ToolFormat.IMAGE], produces=ToolFormat.PDF, arity=ToolArity.MISO),diff --git a/engine/src/stirling/models/tool_models.py b/engine/src/stirling/models/tool_models.pyindex 62225cc78d..a630c2cc2c 100644--- a/engine/src/stirling/models/tool_models.py+++ b/engine/src/stirling/models/tool_models.py@@ -553,33 +553,6 @@ class EditTableOfContentsParams(ApiModel):)-class EditTextOperation(ApiModel):- """- Ordered list of find/replace operations. Each replaces every occurrence on the selected pages, in order; later operations see the result of earlier ones (so 'foo'->'foos' then 'foos'->'bars' turns 'foo' into 'bars').- """-- find: str = Field(..., description="The literal text to find.")- replace: str = Field(..., description="The replacement text. May be empty to delete the matched text.")---class EditTextParams(ApiModel):- """- Applies an ordered list of find/replace operations to the text in a PDF and returns the edited PDF. Useful for find-and-replace, bulk renames (e.g. updating a company name throughout a document), and copy editing where the AI agent has identified specific replacements. Matching is performed against the joined text of each page, so find strings can span multiple visual runs (titles split per word, kerning-broken phrases). Cross-element matches are written as a single replacement run anchored at the leftmost matched position; centered or tracked text may shift left when its content changes. Input:PDF Output:PDF Type:SISO- """-- edits: list[EditTextOperation] = Field(- ...,- description="Ordered list of find/replace operations. Each replaces every occurrence on the selected pages, in order; later operations see the result of earlier ones (so 'foo'->'foos' then 'foos'->'bars' turns 'foo' into 'bars').",- )- page_numbers: str = Field(- "all",- description="The pages to select, Supports ranges (e.g., '1,3,5-9'), or 'all' or functions in the format 'an+b' where 'a' is the multiplier of the page number 'n', and 'b' is a constant (e.g., '2n+1', '3n', '6n-5')",- )- whole_word_search: bool = Field(- False, description="Whether matches must be whole words (boundaries determined by non-word characters)"- )--class EmlToPdfParams(ApiModel):"""This endpoint converts EML (email) and MSG (Outlook) files to PDF format with extensive customization options. Features include font settings, image constraints, display modes, attachment handling, and HTML debug output. or MSG file, or HTML file. Input:EMAIL Output:PDF Type:SISO@@ -603,19 +576,6 @@ class EmlToPdfParams(ApiModel):)-class EncodeCharcodesParams(ApiModel):- """- Frontend-only helper: takes the source PDF, a locator pointing at an existing char rendered in the target font, and a Unicode string. Returns the byte sequence the target font produces for that Unicode, packed as one unsigned int per char. The frontend then calls FPDFText_SetCharcodes with the returned ints to inject new text that reuses the embedded font's actual glyphs. Chars the font can't encode are listed in `missing` so the caller can fall back per-char.- """-- font_name: str | None = None- font_sha256: str | None = None- locator_char: str | None = None- page_index: int | None = None- pdf_base64: str | None = None- text: str | None = None--class ExtractAttachmentsParams(ApiModel):"""This endpoint extracts all embedded attachments from a PDF into a ZIP archive. Input:PDF Output:ZIP Type:SISO@@ -1884,10 +1844,8 @@ class Model(| BookletImpositionParams| CropParams| EditTableOfContentsParams- | EditTextParams| MergePdfsParams| MultiPageLayoutParams- | EncodeCharcodesParams| PdfToSinglePageParams| RearrangePagesParams| RemoveImagePdfParams@@ -1965,10 +1923,8 @@ class Model(| BookletImpositionParams| CropParams| EditTableOfContentsParams- | EditTextParams| MergePdfsParams| MultiPageLayoutParams- | EncodeCharcodesParams| PdfToSinglePageParams| RearrangePagesParams| RemoveImagePdfParams@@ -2047,10 +2003,8 @@ type ParamToolModel = (| BookletImpositionParams| CropParams| EditTableOfContentsParams- | EditTextParams| MergePdfsParams| MultiPageLayoutParams- | EncodeCharcodesParams| PdfToSinglePageParams| RearrangePagesParams| RemoveImagePdfParams@@ -2130,10 +2084,8 @@ class ToolEndpoint(StrEnum):BOOKLET_IMPOSITION = "/api/v1/general/booklet-imposition"CROP = "/api/v1/general/crop"EDIT_TABLE_OF_CONTENTS = "/api/v1/general/edit-table-of-contents"- EDIT_TEXT = "/api/v1/general/edit-text"MERGE_PDFS = "/api/v1/general/merge-pdfs"MULTI_PAGE_LAYOUT = "/api/v1/general/multi-page-layout"- ENCODE_CHARCODES = "/api/v1/general/pdf-text-editor/encode-charcodes"PDF_TO_SINGLE_PAGE = "/api/v1/general/pdf-to-single-page"REARRANGE_PAGES = "/api/v1/general/rearrange-pages"REMOVE_IMAGE_PDF = "/api/v1/general/remove-image-pdf"@@ -2211,10 +2163,8 @@ OPERATIONS: dict[ToolEndpoint, ParamToolModelType] = {ToolEndpoint.BOOKLET_IMPOSITION: BookletImpositionParams,ToolEndpoint.CROP: CropParams,ToolEndpoint.EDIT_TABLE_OF_CONTENTS: EditTableOfContentsParams,- ToolEndpoint.EDIT_TEXT: EditTextParams,ToolEndpoint.MERGE_PDFS: MergePdfsParams,ToolEndpoint.MULTI_PAGE_LAYOUT: MultiPageLayoutParams,- ToolEndpoint.ENCODE_CHARCODES: EncodeCharcodesParams,ToolEndpoint.PDF_TO_SINGLE_PAGE: PdfToSinglePageParams,ToolEndpoint.REARRANGE_PAGES: RearrangePagesParams,ToolEndpoint.REMOVE_IMAGE_PDF: RemoveImagePdfParams,diff --git a/engine/tests/test_pdf_edit_agent.py b/engine/tests/test_pdf_edit_agent.pyindex 9a8a7ea037..08fbf0dc19 100644--- a/engine/tests/test_pdf_edit_agent.py+++ b/engine/tests/test_pdf_edit_agent.py@@ -25,8 +25,6 @@ from stirling.contracts import (from stirling.models import OPERATIONS, FileId, ParamToolModelfrom stirling.models.tool_models import (Angle,- EditTextOperation,- EditTextParams,FlattenParams,RotatePdfParams,SplitPagesParams,@@ -535,174 +533,6 @@ async def test_pdf_edit_agent_rejects_plan_referencing_unavailable_operations(assert parameter_selector.calls == []-async def test_pdf_edit_agent_supports_literal_find_replace(runtime: AppRuntime) -> None:- params = EditTextParams(- edits=[EditTextOperation(find="2025", replace="2026")],- page_numbers="all",- whole_word_search=False,- )- parameter_selector = RecordingParameterSelector([params])- agent = StubPdfEditAgent(- runtime,- PdfEditPlanSelection(- operations=[ToolEndpoint.EDIT_TEXT],- summary="Replace 2025 with 2026 throughout the document.",- rationale="test rationale",- ),- parameter_selector=parameter_selector,- )-- response = await agent.handle(- PdfEditRequest(- user_message="Change every 2025 to 2026.",- files=[AiFile(id=FileId("contract-id"), name="contract.pdf")],- )- )-- assert isinstance(response, EditPlanResponse)- assert len(response.steps) == 1- step = response.steps[0]- assert step.tool == ToolEndpoint.EDIT_TEXT- assert isinstance(step.parameters, EditTextParams)- assert step.parameters.edits == [EditTextOperation(find="2025", replace="2026")]---async def test_pdf_edit_agent_supports_copy_edit_using_page_text(runtime: AppRuntime) -> None:- page_text = [- ExtractedFileText(- file_name="memo.pdf",- pages=[- PdfTextSelection(- page_number=3,- text="The quick brown fox jumps over the lazy dog.",- )- ],- )- ]- params = EditTextParams(- edits=[- EditTextOperation(find="quick", replace="slow"),- EditTextOperation(find="lazy", replace="energetic"),- ],- page_numbers="3",- whole_word_search=False,- )- parameter_selector = RecordingParameterSelector([params])- agent = StubPdfEditAgent(- runtime,- PdfEditPlanSelection(- operations=[ToolEndpoint.EDIT_TEXT],- summary="Fix typos on page 3.",- rationale="test rationale",- ),- parameter_selector=parameter_selector,- )-- response = await agent.handle(- PdfEditRequest(- user_message="Fix typos on page 3.",- files=[AiFile(id=FileId("memo-id"), name="memo.pdf")],- page_text=page_text,- )- )-- assert isinstance(response, EditPlanResponse)- assert len(parameter_selector.calls) == 1- # The parameter selector receives the extracted page text, which is what enables free-form- # copy-editing: it can read the current text and propose specific edits.- assert parameter_selector.calls[0].request.page_text == page_text- step = response.steps[0]- assert step.tool == ToolEndpoint.EDIT_TEXT- assert isinstance(step.parameters, EditTextParams)- assert step.parameters.page_numbers == "3"- assert step.parameters.edits is not None- assert len(step.parameters.edits) == 2---async def test_pdf_edit_agent_supports_natural_language_directed_edit(runtime: AppRuntime) -> None:- page_text = [- ExtractedFileText(- file_name="agreement.pdf",- pages=[- PdfTextSelection(- page_number=1,- text="This agreement is between OldCompany Inc. and the client.",- )- ],- )- ]- params = EditTextParams(- edits=[EditTextOperation(find="OldCompany Inc.", replace="Acme Corp")],- page_numbers="all",- whole_word_search=False,- )- parameter_selector = RecordingParameterSelector([params])- agent = StubPdfEditAgent(- runtime,- PdfEditPlanSelection(- operations=[ToolEndpoint.EDIT_TEXT],- summary="Update the company name to Acme Corp.",- rationale="test rationale",- ),- parameter_selector=parameter_selector,- )-- response = await agent.handle(- PdfEditRequest(- user_message="Update the company name to Acme Corp.",- files=[AiFile(id=FileId("agreement-id"), name="agreement.pdf")],- page_text=page_text,- )- )-- assert isinstance(response, EditPlanResponse)- step = response.steps[0]- assert step.tool == ToolEndpoint.EDIT_TEXT- assert isinstance(step.parameters, EditTextParams)- # The exact find string came from interpreting the user's intent against the extracted text.- assert step.parameters.edits is not None- assert step.parameters.edits[0].find == "OldCompany Inc."- assert step.parameters.edits[0].replace == "Acme Corp"---async def test_pdf_edit_agent_composes_edit_text_with_other_operations(runtime: AppRuntime) -> None:- """EDIT_TEXT can appear alongside other operations in a single plan."""- edit_params = EditTextParams(- edits=[EditTextOperation(find="DRAFT", replace="")],- page_numbers="all",- whole_word_search=False,- )- parameter_selector = RecordingParameterSelector([edit_params, RotatePdfParams(angle=Angle(90))])- agent = StubPdfEditAgent(- runtime,- PdfEditPlanSelection(- operations=[ToolEndpoint.EDIT_TEXT, ToolEndpoint.ROTATE_PDF],- summary="Remove DRAFT marker, then rotate.",- rationale="test rationale",- ),- parameter_selector=parameter_selector,- )-- response = await agent.handle(- PdfEditRequest(- user_message="Remove the DRAFT watermark text and then rotate.",- files=[AiFile(id=FileId("draft-id"), name="draft.pdf")],- )- )-- assert isinstance(response, EditPlanResponse)- assert [step.tool for step in response.steps] == [- ToolEndpoint.EDIT_TEXT,- ToolEndpoint.ROTATE_PDF,- ]- assert isinstance(response.steps[0].parameters, EditTextParams)- assert isinstance(response.steps[1].parameters, RotatePdfParams)--class RecordingShortlist:"""Stands in for the runtime shortlist: the test suite has no reachable embedding provider."""diff --git a/engine/uv.lock b/engine/uv.lockindex 67f2ce56fc..81af5c4720 100644--- a/engine/uv.lock+++ b/engine/uv.lock@@ -442,7 +442,6 @@ pre-commit = [tools = [{ name = "deep-translator" },{ name = "defusedxml" },- { name = "fonttools" },{ name = "fpdf2" },{ name = "openai" },{ name = "requests" },@@ -501,7 +500,6 @@ pre-commit = [tools = [{ name = "deep-translator", specifier = ">=1.11.4" },{ name = "defusedxml", specifier = ">=0.7.1" },- { name = "fonttools", specifier = ">=4.66.0" },{ name = "fpdf2", specifier = ">=2.8.8" },{ name = "openai", specifier = ">=3.19.2" },{ name = "requests", specifier = ">=2.34.2" },diff --git a/frontend/src/editor/core/constants/convertConstants.ts b/frontend/src/editor/core/constants/convertConstants.tsindex 19995220a3..8a6ef30f49 100644--- a/frontend/src/editor/core/constants/convertConstants.ts+++ b/frontend/src/editor/core/constants/convertConstants.ts@@ -39,8 +39,6 @@ export const CONVERSION_ENDPOINTS = {"pdf-cbr": "/api/v1/convert/pdf/cbr","ebook-pdf": "/api/v1/convert/ebook/pdf","pdf-epub": "/api/v1/convert/pdf/epub",- "pdf-text-editor": "/api/v1/convert/pdf/text-editor",- "text-editor-pdf": "/api/v1/convert/text-editor/pdf",} as const;export const ENDPOINT_NAMES = {@@ -67,8 +65,6 @@ export const ENDPOINT_NAMES = {"cbr-pdf": "cbr-to-pdf","pdf-cbr": "pdf-to-cbr","pdf-epub": "pdf-to-epub",- "pdf-text-editor": "pdf-to-text-editor",- "text-editor-pdf": "text-editor-to-pdf",} as const;/** Maps conversion endpoint → [i18n key, English fallback] for display names */diff --git a/frontend/src/editor/core/tests/live/pdf-text-editor-charcode-backend.spec.ts b/frontend/src/editor/core/tests/live/pdf-text-editor-charcode-backend.spec.tsdeleted file mode 100644index 1e916dfecc..0000000000--- a/frontend/src/editor/core/tests/live/pdf-text-editor-charcode-backend.spec.ts+++ /dev/null@@ -1,206 +0,0 @@-import { test, expect } from "@editor/tests/helpers/test-base";-import { loginAndSetup } from "@editor/tests/helpers/login";-import * as path from "path";-import * as fs from "fs";--// In dev environments where the Stirling backend ships with login disabled-// (anonymous-mode), `loginAndSetup` will throw because /login doesn't render.-async function loginIfNeeded(- page: import("@playwright/test").Page,-): Promise<void> {- try {- await loginAndSetup(page);- } catch (e) {- const msg = e instanceof Error ? e.message : String(e);- if (/email|login/i.test(msg)) {- // anonymous-mode backend - nothing to log in to.- return;- }- throw e;- }-}--// Live e2e coverage for the PDF text editor's `backend` charcode strategy.--function fixture(filename: string): string {- const candidates = [- path.resolve(- process.cwd(),- "src",- "editor",- "core",- "tests",- "test-fixtures",- filename,- ),- path.resolve(- process.cwd(),- "frontend",- "src",- "editor",- "core",- "tests",- "test-fixtures",- filename,- ),- ];- for (const p of candidates) {- if (fs.existsSync(p)) return p;- }- throw new Error(- `Test fixture not found: ${filename} (tried: ${candidates.join(", ")})`,- );-}--// `user-sample.pdf` is the same file as `frontend/public/samples/Sample.pdf`,-// copied into the test fixtures dir so this suite is self-contained.-const USER_SAMPLE_PDF = fixture("user-sample.pdf");--async function gotoEditorWithBackendStrategy(- page: import("@playwright/test").Page,-): Promise<void> {- // `charcodeDebug=1` enables the HUD overlay (CharcodeDebugHud) that- // emits one row per attempt, which is what this test scrapes.- await page.goto("/pdf-text-editor?charcodeStrategy=backend&charcodeDebug=1", {- waitUntil: "domcontentloaded",- });- await expect(page.getByTestId("pdf-editor-root")).toBeVisible({- timeout: 30_000,- });-}--async function loadUserSamplePdf(- page: import("@playwright/test").Page,-): Promise<void> {- await page- .locator('[data-testid="pdf-editor-file-input"]')- .setInputFiles(USER_SAMPLE_PDF);- await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({- timeout: 60_000,- });-}--test.describe("charcode backend strategy (live PDFBox)", () => {- test.describe.configure({ timeout: 120_000 });-- test.beforeEach(async ({ page }) => {- await loginIfNeeded(page);- });-- test("Sample.pdf 10M+: typing M into the per-glyph Type3 font emits charcodes-ok on the FIRST keystroke", async ({- page,- }) => {- await gotoEditorWithBackendStrategy(page);- await loadUserSamplePdf(page);-- // Find the 10M+ run.- const runEl = page- .locator('[data-testid^="pdf-editor-run-p"]')- .filter({ hasText: /^10M\+$/ })- .first();- await expect(runEl).toBeVisible({ timeout: 15_000 });- const runTestId = (await runEl.getAttribute("data-testid")) ?? "";- expect(runTestId).toMatch(/^pdf-editor-run-p\d+-/);-- // Listen for the prewarm-complete console.debug log BEFORE we focus the- // run, so we don't race the message.- const prewarmComplete = page.waitForEvent("console", {- predicate: (msg) =>- /\[charcode\] backend prewarm pageIdx=/.test(msg.text()),- timeout: 90_000,- });-- // Surface ALL console messages to the test stdout so we can see what's- // happening if the prewarm log doesn't fire.- page.on("console", (msg) => {- if (/charcode|prewarm/.test(msg.text())) {- process.stdout.write(`[page-console-${msg.type()}] ${msg.text()}\n`);- }- });-- // Use Playwright's physical click - that dispatches real mousedown/up/click- // + focus events that React's synthetic event system catches reliably.- await runEl.click();-- // Wait for prewarm to log "[charcode] backend prewarm pageIdx=- // probes=N".- await prewarmComplete;-- // First keystroke: should hit the per-char emit branch on the FIRST try (no- // Helvetica fallback).- await page.evaluate((tid) => {- const el = document.querySelector<HTMLDivElement>(- `[data-testid="${tid}"]`,- );- if (!el) throw new Error(`run ${tid} not in DOM`);- el.focus();- const sel = window.getSelection();- if (!sel) throw new Error("no Selection api");- const range = document.createRange();- range.selectNodeContents(el);- range.collapse(false);- sel.removeAllRanges();- sel.addRange(range);- document.execCommand("insertText", false, "M");- }, runTestId);-- // The debug HUD was removed from production builds, so verify the emit- // through the window-exposed telemetry buffer instead.- type CharcodeEmitEvent = {- text: string;- outcome: string;- resolved: number[];- };- const readCharcodeEvents = () =>- page.evaluate(- () =>- (- window as unknown as {- __charcode_events?: CharcodeEmitEvent[];- }- ).__charcode_events ?? [],- );-- await expect- .poll(- async () => {- const events = await readCharcodeEvents();- return events.some(- (e) =>- e.text.includes("M") &&- e.outcome === "charcodes-ok" &&- e.resolved.length > 0,- );- },- { timeout: 10_000, intervals: [250, 500, 1000] },- )- .toBe(true);-- // Cross-check: the editor's model must reflect "10M+M" - the- // typed M became a real text run via the per-char emit branch.- const runText = await page.evaluate((tid) => {- const w = window as unknown as {- __editor_store: {- state: { pages: { runs: { id: string; text: string }[] }[] };- };- };- for (const p of w.__editor_store.state.pages) {- for (const r of p.runs) {- if (`pdf-editor-run-${r.id}` === tid) return r.text;- }- }- return "";- }, runTestId);- expect(runText).toBe("10M+M");-- // No-regression guard: the MOST RECENT emit covering "M" must be a- // source-font charcodes-ok emit, NOT a Helvetica fallback.- const events = await readCharcodeEvents();- const mEvents = events.filter((e) => e.text.includes("M"));- const lastM = mEvents[mEvents.length - 1];- expect(- lastM?.outcome,- `latest M emit must be charcodes-ok. Events:\n${JSON.stringify(events, null, 2)}`,- ).toBe("charcodes-ok");- });-});diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-combined-features.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-combined-features.spec.tsindex b339b21951..a8787c3b5f 100644--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-combined-features.spec.ts+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-combined-features.spec.ts@@ -173,12 +173,6 @@ async function undoSize(page: Page): Promise<number> {}test.describe("PDF text editor - combined feature set", () => {- // Editor edits fire encode-charcodes; with no backend an UNMOCKED call 401s- // and redirects to login, unmounting the editor.- test.beforeEach(async ({ page }) => {- await page.route("**/encode-charcodes", (route) => route.abort());- });-test("image insert (real png) adds an image, then rotate-cw changes its matrix and undo reverts", async ({page,}) => {diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-cross-font-charcode.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-cross-font-charcode.spec.tsdeleted file mode 100644index 40c2242122..0000000000--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-cross-font-charcode.spec.ts+++ /dev/null@@ -1,90 +0,0 @@-import { test, expect } from "@editor/tests/helpers/stub-test-base";-import type { Page, Route } from "@playwright/test";-import path from "path";-import type { EditorTestWindow } from "@editor/tests/stubbed/editorTestTypes";--/** Cross-font charcode disambiguation (H1H2/U). */--const SUBSET = path.join(- import.meta.dirname,- "../test-fixtures/subset-font-sample.pdf",-);--test("editor sends the run's font name to encode-charcodes", async ({- page,-}: {- page: Page;-}) => {- test.setTimeout(90_000);- const bodies: Array<Record<string, unknown>> = [];- await page.route("**/encode-charcodes", async (route: Route) => {- try {- bodies.push(route.request().postDataJSON() as Record<string, unknown>);- } catch {- /* ignore non-JSON */- }- await route.fulfill({- status: 200,- contentType: "application/json",- body: JSON.stringify({ charcodes: [65], missing: [], note: "stub" }),- });- });-- await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });- await expect(page.getByTestId("pdf-editor-root")).toBeVisible({- timeout: 20_000,- });- await page- .locator('[data-testid="pdf-editor-file-input"]')- .setInputFiles(SUBSET);- await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({- timeout: 30_000,- });- await page.waitForTimeout(800);-- // Edit a run - the cache-miss prefetch (and focus prewarm) POST to the- // endpoint, now carrying the resolved font's name.- const id = await page.evaluate(() => {- const s = (window as unknown as EditorTestWindow).__editor_store;- return s.doc.page(0).runs[0]?.id ?? null;- });- expect(id, "page 0 has a run").toBeTruthy();- await page.evaluate((rid: string) => {- const el = document.querySelector<HTMLDivElement>(- `[data-testid="pdf-editor-run-${rid}"]`,- )!;- el.focus();- const sel = window.getSelection()!;- const range = document.createRange();- range.selectNodeContents(el);- range.collapse(false);- sel.removeAllRanges();- sel.addRange(range);- document.execCommand("insertText", false, "s");- }, id);- await page.waitForTimeout(1500);-- expect(bodies.length, "endpoint was called").toBeGreaterThan(0);- const named = bodies.filter(- (b) => typeof b.fontName === "string" && b.fontName.length > 0,- );- expect(- named.length,- `at least one request carries a non-empty fontName; bodies=${JSON.stringify(- bodies.map((b) => b.fontName),- )}`,- ).toBeGreaterThan(0);-- // The program-bytes hash must ride along too: PDFium reports every- // "ABCDEF+Family" subset as bare "Family".- const hashed = bodies.filter(- (b) =>- typeof b.fontSha256 === "string" && /^[0-9a-f]{64}$/.test(b.fontSha256),- );- expect(- hashed.length,- `at least one request carries a 64-hex fontSha256; bodies=${JSON.stringify(- bodies.map((b) => b.fontSha256),- )}`,- ).toBeGreaterThan(0);-});diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-fix-image-selection.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-fix-image-selection.spec.tsindex 5d7844e671..ae3292e906 100644--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-fix-image-selection.spec.ts+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-fix-image-selection.spec.ts@@ -38,7 +38,6 @@ interface Rect {}async function openSample(page: Page): Promise<void> {- await page.route("**/encode-charcodes", (route) => route.abort());await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });await expect(page.getByTestId("pdf-editor-root")).toBeVisible({timeout: 30_000,@@ -129,10 +128,6 @@ async function gutter(page: Page): Promise<{test.describe("PDF text editor - selection survives resize, marquee never wipes blind", () => {test.setTimeout(120_000);- test.beforeEach(async ({ page }) => {- await page.route("**/encode-charcodes", (route) => route.abort());- });-// (A) Before the fix: imageIds went ["p0-i46"] -> [] the instant the corner// handle was pressed, and the overlay outline fell back from solid to none.test("corner-resizing an image keeps the image selected", async ({diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-font-coverage.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-font-coverage.spec.tsindex de25d62e2c..c4612ddff2 100644--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-font-coverage.spec.ts+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-font-coverage.spec.ts@@ -1,5 +1,5 @@import { test, expect } from "@editor/tests/helpers/stub-test-base";-import type { Page, Route } from "@playwright/test";+import type { Page } from "@playwright/test";import path from "path";// End-to-end coverage for the fonts panel's client-side glyph-coverage probe.@@ -10,7 +10,6 @@ const SUBSET = path.join();async function open(page: Page, file: string): Promise<void> {- await page.route("**/encode-charcodes", (route: Route) => route.abort());await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });await expect(page.getByTestId("pdf-editor-root")).toBeVisible({timeout: 20_000,diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-jpeg-insert.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-jpeg-insert.spec.tsindex fa658ed83e..7118b0c78f 100644--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-jpeg-insert.spec.ts+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-jpeg-insert.spec.ts@@ -1,5 +1,5 @@import { test, expect } from "@editor/tests/helpers/stub-test-base";-import type { Page, Route } from "@playwright/test";+import type { Page } from "@playwright/test";import path from "path";// Inserting a JPEG embeds the original JPEG stream instead of re-encoding@@ -20,7 +20,6 @@ test("inserting a JPEG embeds it as DCTDecode, not re-encoded RGBA", async ({page: Page;}) => {test.setTimeout(90_000);- await page.route("**/encode-charcodes", (route: Route) => route.abort());await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });await expect(page.getByTestId("pdf-editor-root")).toBeVisible({timeout: 20_000,diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-letter-spacing.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-letter-spacing.spec.tsindex d6d81a0b07..c411de31bb 100644--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-letter-spacing.spec.ts+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-letter-spacing.spec.ts@@ -1,5 +1,5 @@import { test, expect } from "@editor/tests/helpers/stub-test-base";-import type { Page, Route } from "@playwright/test";+import type { Page } from "@playwright/test";import path from "path";import type { EditorTestWindow } from "@editor/tests/stubbed/editorTestTypes";@@ -20,27 +20,6 @@ test("editing a letter-spaced heading keeps its tracking through save+reopen", aconst errs: string[] = [];page.on("pageerror", (e) => errs.push(e.message));- // Serve real charcodes for the standard-14 Helvetica: its charcode IS the- // ASCII code, so the per-char backend branch engages like production.- await page.route("**/encode-charcodes", async (route: Route) => {- let text = "";- try {- const body = route.request().postDataJSON() as { text?: string };- text = body.text ?? "";- } catch {- /* fall through with empty text */- }- await route.fulfill({- status: 200,- contentType: "application/json",- body: JSON.stringify({- charcodes: [...text].map((c) => c.codePointAt(0) ?? 0),- missing: [],- note: "stub ascii",- }),- });- });-await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });await expect(page.getByTestId("pdf-editor-root")).toBeVisible({timeout: 20_000,diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-mushroom-scramble.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-mushroom-scramble.spec.tsindex bc7a683ff3..ecebe04d63 100644--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-mushroom-scramble.spec.ts+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-mushroom-scramble.spec.ts@@ -1,5 +1,4 @@import { test, expect } from "@editor/tests/helpers/stub-test-base";-import type { Route } from "@playwright/test";import path from "path";import type { EditorTestWindow } from "@editor/tests/stubbed/editorTestTypes";@@ -10,18 +9,14 @@ const MUSHROOM = path.join("../test-fixtures/mushroom-life.pdf",);-test("mid-line paragraph edit does not scramble unchanged words (cold backend, non-subset font)", async ({+test("mid-line paragraph edit does not scramble unchanged words (non-subset font)", async ({page,}) => {test.setTimeout(120_000);- // Offline backend: every encode-charcodes call fails, so the emit path hits- // the cold-cache fallback - the exact condition that used to scramble.- await page.route("**/encode-charcodes", (route: Route) => route.abort());-const errs: string[] = [];page.on("pageerror", (e) => errs.push(e.message));- await page.goto("/pdf-text-editor?charcodeStrategy=backend", {+ await page.goto("/pdf-text-editor", {waitUntil: "domcontentloaded",});await expect(page.getByTestId("pdf-editor-root")).toBeVisible({diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-mushroom-spaces.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-mushroom-spaces.spec.tsindex 55b2ca824a..5dd64c9c0f 100644--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-mushroom-spaces.spec.ts+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-mushroom-spaces.spec.ts@@ -1,8 +1,7 @@import { test, expect } from "@editor/tests/helpers/stub-test-base";-import type { Route } from "@playwright/test";import path from "path";-// Regression for the mushroom-life.pdf reports (backend charcode strategy): 1.+// Regression for the mushroom-life.pdf whitespace reports.const MUSHROOM = path.join(import.meta.dirname,@@ -18,27 +17,10 @@ interface CharcodeEvent {test("mushroom first-line edits never reuse whitespace (no „) and keep the paragraph lines", async ({page,}) => {- // BUGGY backend: returns a charcode for every code point, even whitespace- // (space -> 0x20). The frontend must still refuse to reuse it.- await page.route("**/encode-charcodes", (route: Route) => {- let text = "";- try {- text = (route.request().postDataJSON() as { text?: string }).text ?? "";- } catch {- /* ignore */- }- const charcodes = Array.from(text).map((ch) => ch.codePointAt(0) ?? 0);- route.fulfill({- status: 200,- contentType: "application/json",- body: JSON.stringify({ charcodes, missing: [] }),- });- });-const errs: string[] = [];page.on("pageerror", (e) => errs.push(e.message));- await page.goto("/pdf-text-editor?charcodeStrategy=backend", {+ await page.goto("/pdf-text-editor", {waitUntil: "domcontentloaded",});await expect(page.getByTestId("pdf-editor-root")).toBeVisible({@@ -85,14 +67,7 @@ test("mushroom first-line edits never reuse whitespace (no „) and keep the parexpect(before.lineCount).toBeGreaterThan(1);const id = before.id;- // Focus engages the backend prewarm; wait for it to complete so the cache- // is populated before the first keystroke.- const prewarm = page.waitForEvent("console", {- predicate: (m) => /\[charcode\] backend prewarm pageIdx=/.test(m.text()),- timeout: 30_000,- });await page.locator(`[data-testid="pdf-editor-run-${id}"]`).click();- await prewarm.catch(() => undefined);// MID-LINE replace: select a span that spans several words (so it includes// spaces) and replace it.diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-protected-and-save-warning.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-protected-and-save-warning.spec.tsindex 1cb15c1a21..cc961e7838 100644--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-protected-and-save-warning.spec.ts+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-protected-and-save-warning.spec.ts@@ -1,5 +1,5 @@import { test, expect } from "@editor/tests/helpers/stub-test-base";-import type { Page, Route } from "@playwright/test";+import type { Page } from "@playwright/test";import path from "path";import { readFile, writeFile } from "node:fs/promises";import { readPdfProtection } from "@editor/tests/helpers/pdf-protection";@@ -19,7 +19,6 @@ const SAMPLE = path.join(import.meta.dirname, "../test-fixtures/sample.pdf");const ENCRYPTED_PASSWORD = "testpass123";async function gotoEditor(page: Page): Promise<void> {- await page.route("**/encode-charcodes", (route: Route) => route.abort());await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });await expect(page.getByTestId("pdf-editor-root")).toBeVisible({timeout: 20_000,@@ -36,7 +35,6 @@ test.describe("PDF text editor - encrypted PDF password prompt", () => {test("saves a protected workbench PDF without uploading it for inspection", async ({page,}) => {- await page.route("**/encode-charcodes", (route) => route.abort());await page.goto("/editor");await page.locator('[data-testid="file-input"]').setInputFiles(ENCRYPTED);await pagediff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-reported-issues.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-reported-issues.spec.tsindex 5b7da1d4e9..620fcbc15f 100644--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-reported-issues.spec.ts+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-reported-issues.spec.ts@@ -314,12 +314,6 @@ test.describe("PDF text editor - reported issue: align a single paragraph's line});test.describe("PDF text editor - reported issue: character insertion + font integrity", () => {- // Editor edits fire encode-charcodes; with no backend in the stubbed project- // an UNMOCKED call 401s and redirects to login.- test.beforeEach(async ({ page }) => {- await page.route("**/encode-charcodes", (route) => route.abort());- });-test("inserting a duplicate letter into an embedded-font run keeps text correct and emits no ydieresis tofu", async ({page,}) => {diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-rotated-text.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-rotated-text.spec.tsindex c11d2dc593..51d90bbcca 100644--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-rotated-text.spec.ts+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-rotated-text.spec.ts@@ -1,5 +1,5 @@import { test, expect } from "@editor/tests/helpers/stub-test-base";-import type { Page, Route } from "@playwright/test";+import type { Page } from "@playwright/test";import path from "path";import type { EditorTestWindow } from "@editor/tests/stubbed/editorTestTypes";@@ -32,7 +32,6 @@ test("editing rotated text keeps its rotation through save+reopen", async ({const errs: string[] = [];page.on("pageerror", (e) => errs.push(e.message));- await page.route("**/encode-charcodes", (route: Route) => route.abort());await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });await expect(page.getByTestId("pdf-editor-root")).toBeVisible({timeout: 20_000,@@ -108,7 +107,6 @@ test("inserting text on a /Rotate 90 page lands upright (counter-rotated)", asynpage: Page;}) => {test.setTimeout(90_000);- await page.route("**/encode-charcodes", (route: Route) => route.abort());await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });await expect(page.getByTestId("pdf-editor-root")).toBeVisible({timeout: 20_000,diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-scan-weight.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-scan-weight.spec.tsindex 3371163943..2686ce9327 100644--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-scan-weight.spec.ts+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-scan-weight.spec.ts@@ -20,10 +20,6 @@ for (const dpi of [96, 150, 600]) {page,}) => {test.setTimeout(150_000);- await page.route(- "**/api/v1/general/pdf-text-editor/encode-charcodes",- (route) => route.fulfill({ status: 503, body: "unavailable" }),- );await page.goto("/pdf-text-editor", {waitUntil: "domcontentloaded",timeout: 60_000,diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-shapes.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-shapes.spec.tsindex 65b44c0a6a..732caefb92 100644--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-shapes.spec.ts+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-shapes.spec.ts@@ -50,7 +50,6 @@ async function openPdf(page: Page, file: PdfFile): Promise<void> {}async function openSample(page: Page): Promise<void> {- await page.route("**/encode-charcodes", (route) => route.abort());await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });await expect(page.getByTestId("pdf-editor-root")).toBeVisible({timeout: 30_000,diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-unicode-fallback.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-unicode-fallback.spec.tsindex b4f80df2c7..4ec78653c2 100644--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-unicode-fallback.spec.ts+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-unicode-fallback.spec.ts@@ -1,5 +1,5 @@import { test, expect } from "@editor/tests/helpers/stub-test-base";-import type { Page, Route } from "@playwright/test";+import type { Page } from "@playwright/test";import path from "path";import type { EditorTestWindow } from "@editor/tests/stubbed/editorTestTypes";import {@@ -32,7 +32,6 @@ const LATIN_ANCHOR = "Acrobat";const LONE_SURROGATE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])/;async function gotoEditor(page: Page): Promise<Promise<unknown>> {- await page.route("**/encode-charcodes", (route: Route) => route.abort());await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });// Capture the fallback-font fetch (fired on mount) so we can await it before// editing - the embed is sync and needs the bytes cached.diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-vis-images.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-vis-images.spec.tsindex 950ba59b88..9341ec2dcc 100644--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-vis-images.spec.ts+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-vis-images.spec.ts@@ -227,7 +227,6 @@ async function waitForRepaint(}async function openSample(page: Page): Promise<void> {- await page.route("**/encode-charcodes", (route) => route.abort());await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });await expect(page.getByTestId("pdf-editor-root")).toBeVisible({timeout: 30_000,@@ -301,10 +300,6 @@ async function dragMouse(}test.describe("PDF text editor - image objects, validated on the rendered bitmap", () => {- test.beforeEach(async ({ page }) => {- await page.route("**/encode-charcodes", (route) => route.abort());- });-// Catches: a move that updates the overlay/model but leaves the PDFium// bitmap stale (ink still in the old box), or a CSS->PDF mapping bug that// shifts the ink by a different delta than the overlay.diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor.spec.tsindex f1b44afc45..2d6897fcdc 100644--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor.spec.ts+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor.spec.ts@@ -5988,8 +5988,8 @@ test.describe("PDF text editor - stress: overlay box width hugs the text", () =>});test.describe("PDF text editor - F-duplication regression (Sample.pdf tagline)", () => {- // This regression guards against the bug fixed by gating the per-char- // backend-emit branch on `!reuse`.+ // This regression guards against duplicate glyphs when typing into a tagline+ // run.test("typing a single F at end of tagline produces exactly one F", async ({page,}) => {diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/BackendResolver.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/BackendResolver.test.tsdeleted file mode 100644index e3472ab871..0000000000--- a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/BackendResolver.test.ts+++ /dev/null@@ -1,357 +0,0 @@-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";--/** Regression coverage for `BackendResolver`'s HTTP transport. */--// Mock apiClient BEFORE BackendResolver imports it.-vi.mock("@editor/services/apiClient", () => ({- default: { post: vi.fn() },-}));--// Stub the document serializer so the prewarm path can produce PDF bytes-// without a real PDFium file-writer.-vi.mock("@editor/tools/pdfTextEditor/pdfium/PdfiumSave", () => ({- PdfiumSave: { serialize: vi.fn(() => new Uint8Array([0, 1, 2, 3])) },-}));--import apiClient from "@editor/services/apiClient";-import {- BackendResolver,- prewarmBackendCacheForPage,- resetBackendResolverCaches,- _clearBackendCacheForTests,- _clearPrewarmGuardForTests,-} from "@editor/tools/pdfTextEditor/charcode/BackendResolver";-import {- primeFontGlyphMap,- _clearCmapCacheForTests,-} from "@editor/tools/pdfTextEditor/charcode/CmapResolver";-import { sha256Hex } from "@editor/tools/pdfTextEditor/util/sha256";-import type { ResolverContext } from "@editor/tools/pdfTextEditor/charcode/CharcodeStrategy";--const post = apiClient.post as unknown as ReturnType<typeof vi.fn>;--// Minimal stub for ResolverContext.-const fakeCtx: ResolverContext = {- module: {} as unknown as ResolverContext["module"],- pagePtr: 0,- docPtr: 0,-};--// Build a fake PDFium module that renders a single char on a page so the-// prewarm text-walk finds exactly one probe to fire. `char` is the Unicode.-function makeFakeModule(char: string, fontPtr: number) {- const cp = char.codePointAt(0) ?? 0;- const TEXT_PAGE = 555;- const TEXT_OBJ = 777;- return {- FPDFText_LoadPage: vi.fn(() => TEXT_PAGE),- FPDFText_ClosePage: vi.fn(),- FPDFText_CountChars: vi.fn(() => 1),- FPDFText_GetUnicode: vi.fn(() => cp),- FPDFText_GetTextObject: vi.fn(() => TEXT_OBJ),- FPDFTextObj_GetFont: vi.fn(() => fontPtr),- } as unknown as ResolverContext["module"];-}--// Fake PDFium module rendering an arbitrary sequence of glyphs, each with its-// own font handle. `glyphs` is a list of [char, fontPtr] in page reading order.-function makeFakeModulePage(glyphs: Array<[string, number]>) {- const TEXT_PAGE = 555;- const OBJ_BASE = 1000;- return {- FPDFText_LoadPage: vi.fn(() => TEXT_PAGE),- FPDFText_ClosePage: vi.fn(),- FPDFText_CountChars: vi.fn(() => glyphs.length),- FPDFText_GetUnicode: vi.fn(- (_tp: number, i: number) => glyphs[i][0].codePointAt(0) ?? 0,- ),- FPDFText_GetTextObject: vi.fn((_tp: number, i: number) => OBJ_BASE + i),- FPDFTextObj_GetFont: vi.fn((obj: number) => glyphs[obj - OBJ_BASE][1]),- } as unknown as ResolverContext["module"];-}--/** Poll until `predicate` is true (async prefetch settles) or time out. */-async function waitUntil(predicate: () => boolean): Promise<void> {- for (let i = 0; i < 100; i++) {- if (predicate()) return;- await new Promise((r) => setTimeout(r, 1));- }-}--// Install a fake editor document on window so `prewarmBackendCacheForPage`-// resolves a page + module instead of bailing on "no-editor-ctx".-function installEditorDocument(- module: ResolverContext["module"],- pagePtr: number,- docPtr: number,-) {- const doc = {- module,- docPtr,- loadedPages: () => [{ index: 0, pagePtr, docPtr }],- };- (window as unknown as { __editor_store?: unknown }).__editor_store = {- document: doc,- };-}--beforeEach(() => {- post.mockReset();- resetBackendResolverCaches();- _clearBackendCacheForTests();- _clearPrewarmGuardForTests();- _clearCmapCacheForTests();- delete (window as unknown as { __editor_store?: unknown }).__editor_store;-});--afterEach(() => {- post.mockReset();- vi.restoreAllMocks();- delete (window as unknown as { __editor_store?: unknown }).__editor_store;-});--describe("BackendResolver", () => {- describe("HTTP transport via shared apiClient (regression #111)", () => {- it("routes the encode POST through apiClient.post with the suppressErrorToast and skipAuthRedirect config flags", async () => {- // One glyph 'M' on the page, rendered by font handle 7. Prewarm walks- // the page, finds one probe, serializes the doc (mocked) and POSTs.- const module = makeFakeModule("M", 7);- installEditorDocument(module, 9001, 4242);- post.mockResolvedValueOnce({ data: { charcodes: [182] } });-- await prewarmBackendCacheForPage(0);-- expect(post).toHaveBeenCalledTimes(1);- expect(post).toHaveBeenCalledWith(- "/api/v1/general/pdf-text-editor/encode-charcodes",- expect.objectContaining({- pdfBase64: expect.any(String),- pageIndex: 0,- locatorChar: "M",- text: expect.stringContaining("M"),- }),- // Top-level axios config, NOT headers: handleHttpError reads- // `error.config.<flag>`, so the header spelling was inert.- { suppressErrorToast: true, skipAuthRedirect: true },- );- });-- it("never calls raw fetch() (must go through apiClient)", async () => {- const fetchSpy = vi.spyOn(globalThis, "fetch");- const module = makeFakeModule("A", 3);- installEditorDocument(module, 9002, 4242);- post.mockResolvedValueOnce({ data: { charcodes: [65] } });-- await prewarmBackendCacheForPage(0);-- expect(post).toHaveBeenCalledTimes(1);- expect(fetchSpy).not.toHaveBeenCalled();- });-- it("swallows an HTTP/network error from apiClient.post (postCharcodes -> null, no throw)", async () => {- const module = makeFakeModule("Z", 5);- installEditorDocument(module, 9003, 4242);- // A rejected probe (e.g. a 401) must not propagate: prewarm is- // best-effort and postCharcodes' catch returns null.- post.mockRejectedValueOnce(new Error("401"));-- await expect(prewarmBackendCacheForPage(0)).resolves.toBeUndefined();- expect(post).toHaveBeenCalledTimes(1);- });- });-- describe("prewarm batching + cross-font cache key", () => {- const ENDPOINT = "/api/v1/general/pdf-text-editor/encode-charcodes";-- it("batches all of a font's page chars into ONE request (H3)", async () => {- // Two glyphs 'A','B' both rendered by font 7. Prewarm must fire ONE- // request carrying "AB", not one per char.- const module = makeFakeModulePage([- ["A", 7],- ["B", 7],- ]);- installEditorDocument(module, 9100, 4242);- post.mockResolvedValueOnce({ data: { charcodes: [65, 66] } });-- await prewarmBackendCacheForPage(0);-- expect(post).toHaveBeenCalledTimes(1);- expect(post).toHaveBeenCalledWith(- ENDPOINT,- expect.objectContaining({ text: expect.stringContaining("AB") }),- // This test's subject is the request body; the transport config is- // pinned in full by the first test in this file.- expect.objectContaining({ suppressErrorToast: true }),- );- const sent = post.mock.calls[0][1] as { text: string };- // Characters the page never used must be probed too, or the first time- // the user types one it misses the cache and the font is substituted.- expect(sent.text).toContain("Z");- expect(sent.text).toContain("9");- // Both chars cached under font 7 in request order.- const r = new BackendResolver();- const res = r.resolve(7, "AB", { module, pagePtr: 9100, docPtr: 4242 });- expect(res?.charcodes).toEqual([65, 66]);- });-- it("fires one request per distinct font, not per char", async () => {- const module = makeFakeModulePage([- ["A", 7],- ["B", 8],- ]);- installEditorDocument(module, 9101, 4242);- post.mockResolvedValue({ data: { charcodes: [1] } });-- await prewarmBackendCacheForPage(0);-- expect(post).toHaveBeenCalledTimes(2);- });-- it("respects the backend's `missing` list when mapping batched charcodes", async () => {- const module = makeFakeModulePage([- ["A", 7],- ["B", 7],- ["C", 7],- ]);- installEditorDocument(module, 9102, 4242);- // Backend could encode A and C but not B: charcodes align to the- // NON-missing chars in order.- post.mockResolvedValueOnce({- data: { charcodes: [65, 67], missing: ["B"] },- });-- await prewarmBackendCacheForPage(0);-- const r = new BackendResolver();- const ctx = { module, pagePtr: 9102, docPtr: 4242 };- expect(r.resolve(7, "A", ctx)?.charcodes).toEqual([65]);- expect(r.resolve(7, "C", ctx)?.charcodes).toEqual([67]);- // 'B' was reported missing -> cached null -> reported missing, not 67.- const b = r.resolve(7, "B", ctx);- expect(b?.charcodes).toEqual([]);- expect(b?.missing).toEqual(["B"]);- });-- it("includes the primed font-program hash so the backend can pick the exact subset", async () => {- // The Mangum-CV corruption: PDFium names every "ABCDEF+Garamond" subset- // just "Garamond".- const fontBytes = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]);- // Prime the sha cache for font 7 via the CmapResolver's safe-phase read.- const heap = new Uint8Array(1 << 12);- const primeModule = {- FPDFFont_GetFontData: (- _f: number,- bufferPtr: number,- length: number,- outSizePtr: number,- ) => {- new DataView(heap.buffer).setInt32(- outSizePtr,- fontBytes.length,- true,- );- if (bufferPtr !== 0 && length > 0) heap.set(fontBytes, bufferPtr);- return true;- },- pdfium: {- wasmExports: {- malloc: (() => {- let bump = 8;- return (n: number) => {- const p = bump;- bump += n;- return p;- };- })(),- free: () => {},- },- getValue: (ptr: number) =>- new DataView(heap.buffer).getInt32(ptr, true),- HEAPU8: heap,- },- } as unknown as ResolverContext["module"];- primeFontGlyphMap(7, primeModule);-- const module = makeFakeModule("M", 7);- installEditorDocument(module, 9050, 4242);- post.mockResolvedValueOnce({ data: { charcodes: [33] } });-- await prewarmBackendCacheForPage(0);-- expect(post).toHaveBeenCalledWith(- "/api/v1/general/pdf-text-editor/encode-charcodes",- expect.objectContaining({- text: expect.stringContaining("M"),- fontSha256: sha256Hex(fontBytes),- }),- // This test's subject is the request body; the transport config is- // pinned in full by the first test in this file.- expect.objectContaining({ suppressErrorToast: true }),- );- });-- it("does not re-POST every keystroke when the queried font differs from the rendering font (H2)", async () => {- // 'A' is rendered by font 7 on the page, but the run is editing under a- // borrowed font handle 99.- const module = makeFakeModulePage([["A", 7]]);- installEditorDocument(module, 9200, 4242);- post.mockResolvedValue({ data: { charcodes: [65] } });- const r = new BackendResolver();- const ctx: ResolverContext = { module, pagePtr: 9200, docPtr: 4242 };-- r.resolve(99, "A", ctx); // miss under font 99 -> kicks prefetch- await waitUntil(() => post.mock.calls.length >= 1);- const callsAfterFirst = post.mock.calls.length;-- // More keystrokes for the same (font 99, 'A'): the null sentinel must- // short-circuit resolve() so no further prefetch fires.- r.resolve(99, "A", ctx);- r.resolve(99, "A", ctx);- await new Promise((res) => setTimeout(res, 5));- expect(post.mock.calls.length).toBe(callsAfterFirst);-- // The real charcode landed under the rendering font 7.- expect(r.resolve(7, "A", ctx)?.charcodes).toEqual([65]);- });- });-- describe("cache semantics", () => {- it("resolve() with an empty text returns null", () => {- const r = new BackendResolver();- expect(r.resolve(1, "", fakeCtx)).toBeNull();- });-- it("resolve() with a 0 font returns null", () => {- const r = new BackendResolver();- expect(r.resolve(0, "M", fakeCtx)).toBeNull();- });- });-- describe("whitespace is never charcode-reused (mushroom „ bug)", () => {- it("resolve() reports a space as missing and never round-trips it", async () => {- const r = new BackendResolver();- const result = r.resolve(99, " ", fakeCtx);- // Space must be reported missing, NOT looked up / cached / sent to the- // backend.- expect(result?.missing).toEqual([" "]);- expect(result?.charcodes).toEqual([]);- await Promise.resolve();- await Promise.resolve();- expect(post).not.toHaveBeenCalled();- });-- it("resolve() splits a mixed chunk: real chars miss the cache, whitespace stays a gap", async () => {- const r = new BackendResolver();- // "a b" - 'a' and 'b' are genuine cache misses (kick a prefetch), the- // space is reported missing WITHOUT being counted as a prefetch miss.- const result = r.resolve(99, "a b", fakeCtx);- expect(result?.missing).toEqual(["a", " ", "b"]);- expect(result?.charcodes).toEqual([]);- // The prefetch (for 'a') bails before HTTP in this no-window-doc env,- // but crucially the space alone must never be the reason it fires.- const spaceOnly = r.resolve(99, "\t\n ", fakeCtx);- expect(spaceOnly?.charcodes).toEqual([]);- expect(spaceOnly?.missing).toEqual(["\t", "\n", " "]);- });- });-});diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/FontBorrowing.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/FontBorrowing.test.tsindex 0b5297a695..f6541c6174 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/FontBorrowing.test.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/FontBorrowing.test.ts@@ -23,7 +23,7 @@ import {_clearFontForCharCacheForTests,_clearFontNameCacheForTests,_clearReusableFontCacheForTests,-} from "@editor/tools/pdfTextEditor/charcode/BackendResolver";+} from "@editor/tools/pdfTextEditor/charcode/FontHelpers";import type { ResolverContext } from "@editor/tools/pdfTextEditor/charcode/CharcodeStrategy";const TEXT_PAGE = 555;diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/sha256.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/sha256.test.tsindex e88ce80fa5..f1c9897d9f 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/sha256.test.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/sha256.test.ts@@ -4,8 +4,8 @@ import { createHash } from "node:crypto";import { sha256Hex } from "@editor/tools/pdfTextEditor/util/sha256";-// The pure-JS SHA-256 fingerprints embedded font programs so the backend can-// match the EXACT subset font a charcode request targets.+// The pure-JS SHA-256 fingerprints embedded font programs by their exact+// subset bytes.describe("sha256Hex", () => {it("matches the FIPS 180-4 vectors", () => {expect(sha256Hex(new Uint8Array(0))).toBe(diff --git a/frontend/src/editor/core/tools/pdfTextEditor/charcode/BackendResolver.ts b/frontend/src/editor/core/tools/pdfTextEditor/charcode/BackendResolver.tsdeleted file mode 100644index 9e068a14b4..0000000000--- a/frontend/src/editor/core/tools/pdfTextEditor/charcode/BackendResolver.ts+++ /dev/null@@ -1,840 +0,0 @@-import apiClient from "@editor/services/apiClient";-import type {- CharcodeResolver,- CharcodeResolveResult,- ResolverContext,-} from "@editor/tools/pdfTextEditor/charcode/CharcodeStrategy";-import { getActiveCharcodeStrategy } from "@editor/tools/pdfTextEditor/charcode/CharcodeStrategy";-import { getCachedFontProgramSha256 } from "@editor/tools/pdfTextEditor/charcode/CmapResolver";-import {- SCRATCH,- scratchPtr,-} from "@editor/tools/pdfTextEditor/util/wasmScratch";--/** Strategy 3: ask the Spring backend (PDFBox) to encode chars. */--/** Cache: per (fontPtr, char) → charcode integer (or null = missing). */-const charCache = new Map<string, number | null>();--// Expiry timestamps for TRANSIENT-failure nulls (network error, backend down,-// serialize hiccup).-const negativeUntil = new Map<string, number>();-const NEGATIVE_TTL_MS = 30_000;--function setTransientNull(key: string): void {- charCache.set(key, null);- negativeUntil.set(key, Date.now() + NEGATIVE_TTL_MS);-}--/** Track in-flight prefetches so we don't double-fire. */-const inFlight = new Set<string>();--/** Hard cap on CONCURRENT auto-prefetches. */-const MAX_CONCURRENT_AUTO_PREFETCH = 2;-// Font batches in flight within a single prefetch. Matches the cap-// prewarmPageCharcodes uses so both paths load the backend the same way.-const PREFETCH_BATCH_CONCURRENCY = 6;-let autoPrefetchActive = 0;--/** Short-lived cache of the serialized document, shared by prefetch bursts. */-let serializedCache: { bytes: Uint8Array; at: number } | null = null;-const SERIALIZE_TTL_MS = 4000;--function serializeDocCached<D>(- save: { serialize: (d: D) => Uint8Array },- doc: D,-): Uint8Array | null {- const now = Date.now();- if (serializedCache && now - serializedCache.at < SERIALIZE_TTL_MS) {- return serializedCache.bytes;- }- const bytes = save.serialize(doc);- if (!bytes || bytes.byteLength === 0) return null;- serializedCache = { bytes, at: now };- return bytes;-}--/** Endpoint config - resolved relative to current origin in dev. */-const ENDPOINT = "/api/v1/general/pdf-text-editor/encode-charcodes";--/** Shape of the encode-charcodes JSON response (mirrors the controller). */-interface EncodeCharcodesResponse {- charcodes?: number[];- missing?: string[];- note?: string;- error?: string;-}--// POST JSON to the charcode endpoint via the shared `apiClient`. `apiClient` is-// the canonical Stirling HTTP helper.-async function postCharcodes(- body: Record<string, unknown>,-): Promise<EncodeCharcodesResponse | null> {- try {- const resp = await apiClient.post<EncodeCharcodesResponse>(ENDPOINT, body, {- suppressErrorToast: true,- skipAuthRedirect: true,- });- return resp.data ?? null;- } catch {- return null;- }-}--export class BackendResolver implements CharcodeResolver {- readonly name = "backend" as const;-- resolve(- font: number,- text: string,- ctx: ResolverContext,- ): CharcodeResolveResult | null {- if (!font || !text) return null;- const charcodes: number[] = [];- const missing: string[] = [];- const cacheMisses: string[] = [];- for (const ch of text) {- // Whitespace is never charcode-reused (no real space glyph in subset- // fonts; SetCharcodes(0x20) paints garbage like „).- if (/\s/.test(ch)) {- missing.push(ch);- continue;- }- const key = cacheKey(font, ch);- if (!charCache.has(key)) {- cacheMisses.push(ch);- missing.push(ch);- continue;- }- const code = charCache.get(key);- if (code === null) {- // A transient-failure null past its TTL becomes a cache miss so- // the prefetch below retries it.- const until = negativeUntil.get(key);- if (until !== undefined && Date.now() >= until) {- charCache.delete(key);- negativeUntil.delete(key);- cacheMisses.push(ch);- }- missing.push(ch);- continue;- }- if (typeof code === "number") charcodes.push(code);- }- // Auto-kick a background prefetch for the cache-miss chars so the next time- // the user types them we have charcodes to use.- if (cacheMisses.length > 0) {- maybeAutoPrefetch(font, cacheMisses, ctx);- }- return {- charcodes,- coverage: charcodes.length,- missing,- note:- cacheMisses.length > 0- ? `backend cache miss for ${JSON.stringify(cacheMisses.join(""))} - prefetch kicked off in background, retry the keystroke in a moment`- : `backend cache served ${charcodes.length} of ${text.length} char(s)`,- };- }-}--// Fire-and-forget prefetch triggered from inside `resolve()` when the cache-// doesn't yet have the chars the user just typed.-function maybeAutoPrefetch(- fontPtr: number,- chars: string[],- ctx: ResolverContext,-): void {- // Never round-trip whitespace - it has no reusable glyph (see resolve()).- // Dedupe too: resolve() pushes one entry per occurrence, so a repeated- // character would otherwise cost one request per repeat.- chars = [...new Set(chars.filter((ch) => !/\s/.test(ch)))];- if (chars.length === 0) return;- // Concurrency cap: dropping is safe - the chars stay cache-miss and a- // later keystroke re-fires once a slot frees up.- if (autoPrefetchActive >= MAX_CONCURRENT_AUTO_PREFETCH) return;- // Avoid re-firing while a prefetch for these chars is in flight.- const reqKey = `auto:${fontPtr}:${chars.join("")}`;- if (inFlight.has(reqKey)) return;- inFlight.add(reqKey);- autoPrefetchActive += 1;- void (async () => {- try {- const { PdfiumSave } =- await import("@editor/tools/pdfTextEditor/pdfium/PdfiumSave");- const doc = getEditorDocument();- if (!doc) {- if (typeof console !== "undefined") {- console.warn(- "[charcode] backend auto-prefetch: editor document unavailable",- );- }- for (const ch of chars) setTransientNull(cacheKey(fontPtr, ch));- return;- }- const bytes = serializeDocCached(PdfiumSave, doc);- if (!bytes) {- for (const ch of chars) setTransientNull(cacheKey(fontPtr, ch));- return;- }- const pdfBase64 = uint8ToBase64(bytes);- const pageIdx = pageIdxOfPagePtr(ctx);-- // Batch by font: one request per font carrying all of that font's- // missing chars, mirroring prewarmPageCharcodes. Previously this fired- // one request per character, each re-sending the entire base64 PDF.- const byFont = new Map<number, string[]>();- for (const ch of chars) {- const perCharFont = findFontForChar(ch, ctx) || fontPtr;- const arr = byFont.get(perCharFont);- if (arr) arr.push(ch);- else byFont.set(perCharFont, [ch]);- }-- const batches = [...byFont.entries()];- let batchIdx = 0;- const workers: Promise<void>[] = [];- for (- let w = 0;- w < Math.min(PREFETCH_BATCH_CONCURRENCY, batches.length);- w++- ) {- workers.push(- (async () => {- while (true) {- const me = batchIdx++;- if (me >= batches.length) return;- const [perCharFont, fontChars] = batches[me];- const json = await postCharcodes({- pdfBase64,- pageIndex: pageIdx >= 0 ? pageIdx : 0,- // Any of this font's chars is a valid locator.- locatorChar: fontChars[0],- fontName: readFontName(ctx.module, perCharFont),- // Program-bytes hash: the only identity that survives PDFium's- // subset-tag stripping.- fontSha256:- getCachedFontProgramSha256(perCharFont) ?? undefined,- text: fontChars.join(""),- });-- if (!json || json.error) {- // Network failure / backend error: retry after the TTL. Only a- // real "encoded 0 of N" answer is a permanent miss.- for (const ch of fontChars) {- setTransientNull(cacheKey(perCharFont, ch));- }- } else {- // The backend appends one charcode per NON-missing char, in- // request order.- const missing = new Set(json.missing ?? []);- const codes = json.charcodes ?? [];- let k = 0;- for (const ch of fontChars) {- if (missing.has(ch)) {- charCache.set(cacheKey(perCharFont, ch), null);- continue;- }- const code = codes[k++];- charCache.set(- cacheKey(perCharFont, ch),- typeof code === "number" ? code : null,- );- }- }-- // Stop the per-keystroke prefetch storm. resolve looks these- // chars up under the QUERIED font, not perCharFont. Use the- // TTL'd null: this font was never actually asked, so a permanent- // null would kill the pair for the rest of the session.- if (perCharFont !== fontPtr) {- for (const ch of fontChars) {- setTransientNull(cacheKey(fontPtr, ch));- }- }- }- })(),- );- }- await Promise.all(workers);- } catch (err) {- const msg = err instanceof Error ? err.message : String(err);- if (typeof console !== "undefined") {- console.warn("[charcode] backend prefetch threw:", err);- }- // Negative-cache with TTL so we don't retry the same chars in a tight- // loop but DO recover once the backend is reachable again.- for (const ch of chars) setTransientNull(cacheKey(fontPtr, ch));- // Lazy-import charcodeRegistry to avoid the cyclic- // BackendResolver ↔ charcodeRegistry module init.- try {- const { emitCharcodeEvent } =- await import("@editor/tools/pdfTextEditor/charcode/charcodeRegistry");- emitCharcodeEvent({- strategy: getActiveCharcodeStrategy(),- text: chars.join(""),- fontPtr,- resolved: [],- missing: [...chars],- note: `backend prefetch threw: ${msg}`,- outcome: "partial-coverage-fallback",- });- } catch {- /* registry import itself failed - already logged above */- }- } finally {- inFlight.delete(reqKey);- autoPrefetchActive -= 1;- }- })();-}--interface TextPageModule {- FPDFText_LoadPage?: (page: number) => number;- FPDFText_ClosePage?: (textPage: number) => void;- FPDFText_CountChars?: (textPage: number) => number;- FPDFText_GetUnicode?: (textPage: number, idx: number) => number;- FPDFText_GetTextObject?: (textPage: number, idx: number) => number;-}--interface FontReadModule {- FPDFTextObj_GetFont?: (obj: number) => number;-}--// Find an existing char on the current page whose text object uses the given-// font.-const fontForCharCache = new Map<string, number | null>();--/** Bold/italic classification of a font, read from its /BaseFont name. */-export interface FontStyleClass {- bold: boolean;- italic: boolean;-}--/**- * Classify a font handle as bold/italic from its /BaseFont name.- *- * Borrowing a glyph from a face of a different weight is what made edited body- * text come back bold: the first "o" in document order often lives in a bold- * heading.- */-export function fontStyleClass(- m: ResolverContext["module"],- fontPtr: number,-): FontStyleClass | null {- const name = readFontName(m, fontPtr);- if (!name) return null;- return styleClassFromName(name);-}--/** Same classification from a font FAMILY name (base-14 or device font). */-export function styleClassFromName(name: string): FontStyleClass {- return {- bold: /bold|black|heavy|semibold|demi/i.test(name),- italic: /italic|oblique/i.test(name),- };-}--const reusableFontCache = new Map<number, boolean>();--/**- * Whether a font has a real font program behind it.- *- * A Type 3 face is a dictionary of content-stream procedures, so PDFium can- * report neither a glyph advance nor a usable ink box for it. Its glyphs are- * still drawable - callers may reuse one when they can measure its advance- * some other way - but laying out new text on PDFium's numbers alone stacks- * every glyph on the previous one.- */-export function fontIsReusable(- m: ResolverContext["module"],- fontPtr: number,-): boolean {- if (!fontPtr) return false;- const cached = reusableFontCache.get(fontPtr);- if (cached !== undefined) return cached;- const getData = (- m as unknown as {- FPDFFont_GetFontData?: (- font: number,- buf: number,- buflen: number,- outLen: number,- ) => boolean;- }- ).FPDFFont_GetFontData;- // No API to ask with: assume reusable so nothing regresses.- if (typeof getData !== "function") {- reusableFontCache.set(fontPtr, true);- return true;- }- // A Type 3 font is a dictionary of content-stream procedures, not a font- // program. PDFium still answers "true" for it, but reports a length of 0 -- // the length is the part that distinguishes a real face.- let ok = false;- const out = scratchPtr(m, SCRATCH.backendOut, 4);- try {- m.pdfium.setValue(out, 0, "i32");- ok = getData(fontPtr, 0, 0, out) && m.pdfium.getValue(out, "i32") > 0;- } catch {- ok = false;- }- reusableFontCache.set(fontPtr, ok);- return ok;-}--/** Test-only: clear the reusable-font cache. */-export function _clearReusableFontCacheForTests(): void {- reusableFontCache.clear();-}--export function findFontForChar(- unicodeChar: string,- ctx: ResolverContext,- // When given, only fonts with the SAME bold/italic class as this one are- // accepted, so a borrowed glyph never changes the run's weight or slant.- likeFontPtr?: number,- // Used when there is no source font handle to read a style from - notably on- // the undo path, which re-emits with `originalFontPtr: 0`. Without it the- // borrow is unconstrained again and restored body text comes back bold.- likeStyle?: FontStyleClass | null,-): number | null {- if (!unicodeChar) return null;- const cp = unicodeChar.codePointAt(0);- if (cp === undefined) return null;- const m = ctx.module;- const want =- (likeFontPtr ? fontStyleClass(m, likeFontPtr) : null) ?? likeStyle ?? null;- // The style is part of the answer, so it must be part of the cache key.- const styleK = want- ? `${want.bold ? "b" : ""}${want.italic ? "i" : ""}|`- : "";- // So is the source face: the borrow prefers the run's own family, so two- // runs of different families must not share an answer.- const likeName = likeFontPtr- ? baseFontFamily(readFontName(m, likeFontPtr))- : undefined;- const cacheK = `${ctx.pagePtr}:${styleK}${likeName ?? ""}|${cp}`;- if (fontForCharCache.has(cacheK)) return fontForCharCache.get(cacheK) ?? null;- const tpMod = m as unknown as TextPageModule;- const fontMod = m as unknown as FontReadModule;- if (- !tpMod.FPDFText_LoadPage ||- !tpMod.FPDFText_CountChars ||- !tpMod.FPDFText_GetUnicode ||- !tpMod.FPDFText_GetTextObject ||- !fontMod.FPDFTextObj_GetFont- ) {- fontForCharCache.set(cacheK, null);- return null;- }- const textPage = tpMod.FPDFText_LoadPage(ctx.pagePtr);- if (!textPage) {- fontForCharCache.set(cacheK, null);- return null;- }- try {- const count = tpMod.FPDFText_CountChars(textPage);- // The run's OWN family, wherever the page happens to draw this char in it,- // beats whichever style-compatible face comes first in content order. A- // word the document already uses otherwise came back in a near-miss face -- // right weight, slightly wrong shapes and advances.- let fallback: number | null = null;- for (let i = 0; i < count; i++) {- const u = tpMod.FPDFText_GetUnicode(textPage, i);- if (u !== cp) continue;- const obj = tpMod.FPDFText_GetTextObject(textPage, i);- if (!obj) continue;- try {- const f = fontMod.FPDFTextObj_GetFont(obj);- if (!f) continue;- if (want) {- const got = fontStyleClass(m, f);- // An unnamed font can't be vouched for; skip it rather than risk a- // weight change.- if (!got || got.bold !== want.bold || got.italic !== want.italic) {- continue;- }- }- if (!likeName || baseFontFamily(readFontName(m, f)) === likeName) {- fontForCharCache.set(cacheK, f);- return f;- }- if (fallback === null) fallback = f;- } catch {- continue;- }- }- if (fallback !== null) {- fontForCharCache.set(cacheK, fallback);- return fallback;- }- } finally {- if (tpMod.FPDFText_ClosePage) {- try {- tpMod.FPDFText_ClosePage(textPage);- } catch {- /* best-effort */- }- }- }- fontForCharCache.set(cacheK, null);- return null;-}--/** Test-only: clear the per-char-font cache. */-export function _clearFontForCharCacheForTests(): void {- fontForCharCache.clear();-}--interface FontNameModule {- FPDFFont_GetBaseFontName?: (font: number, buf: number, len: number) => number;-}--/**- * A face's family, with the subset tag and style suffix stripped:- * "ABCDEF+LMRoman12-Regular" -> "lmroman12". Two handles that agree here are- * the same design, so a glyph borrowed across them keeps the run's look.- */-function baseFontFamily(name: string | undefined): string | undefined {- if (!name) return undefined;- const family = name.replace(/^[A-Z]{6}\+/, "").split(/[-,]/)[0];- return family ? family.toLowerCase() : undefined;-}--const fontNameCache = new Map<number, string | undefined>();--/** Test-only: clear the memoised /BaseFont names. */-export function _clearFontNameCacheForTests(): void {- fontNameCache.clear();-}--// Read a font's /BaseFont name so the backend can disambiguate WHICH font to-// encode against when two fonts on the page render the same char.-function readFontName(- m: ResolverContext["module"],- fontPtr: number,-): string | undefined {- if (!fontPtr) return undefined;- if (fontNameCache.has(fontPtr)) return fontNameCache.get(fontPtr);- const name = loadFontName(m, fontPtr);- fontNameCache.set(fontPtr, name);- return name;-}--function loadFontName(- m: ResolverContext["module"],- fontPtr: number,-): string | undefined {- const fn = (m as unknown as FontNameModule).FPDFFont_GetBaseFontName;- if (typeof fn !== "function") return undefined;- try {- const len = fn(fontPtr, 0, 0);- if (len <= 1) return undefined;- const buf = scratchPtr(m, SCRATCH.readerReadTextB, len);- fn(fontPtr, buf, len);- return m.pdfium.UTF8ToString(buf) || undefined;- } catch {- return undefined;- }-}--/** Per-page idempotency guard for `prewarmBackendCacheForPage`. */-const prewarmedPages = new Set<number>();--// Pre-warm the backend cache for every Unicode char that already lives on the-// given page.-const TYPEABLE_CHARS: string[] = (() => {- const out: string[] = [];- for (let cp = 0x21; cp <= 0x7e; cp += 1) out.push(String.fromCodePoint(cp));- return out;-})();--const MAX_PREWARM_PROBES = 4000;--function addTypeableProbes(- probes: Array<{ ch: string; perCharFont: number }>,- seen: Set<string>,-): void {- const fonts = [...new Set(probes.map((p) => p.perCharFont))];- for (const font of fonts) {- for (const ch of TYPEABLE_CHARS) {- if (probes.length >= MAX_PREWARM_PROBES) return;- const key = `${font}:${ch}`;- if (seen.has(key)) continue;- seen.add(key);- if (charCache.has(cacheKey(font, ch))) continue;- probes.push({ ch, perCharFont: font });- }- }-}--export async function prewarmBackendCacheForPage(- pageIndex: number,-): Promise<void> {- // Always log entry so tests + debug have a single signal that "prewarm was at- // least invoked for page N" regardless of which early-return path the body.- if (typeof console !== "undefined") {- console.debug(`[charcode] backend prewarm-start pageIdx=${pageIndex}`);- }- const editorCtx = getEditorContextForPage(pageIndex);- if (!editorCtx) {- if (typeof console !== "undefined") {- console.debug(- `[charcode] backend prewarm pageIdx=${pageIndex} probes=0 (no-editor-ctx)`,- );- }- return;- }- const { module: m, pagePtr } = editorCtx;- if (prewarmedPages.has(pagePtr)) {- if (typeof console !== "undefined") {- console.debug(- `[charcode] backend prewarm pageIdx=${pageIndex} probes=0 (already-prewarmed)`,- );- }- return;- }-- // Walk the page text once, collecting (perCharFont, unicode) for every- // glyph. Dedupe so each (font, char) probe fires at most once per page.- const tpMod = m as unknown as TextPageModule;- const fontMod = m as unknown as FontReadModule;- if (- !tpMod.FPDFText_LoadPage ||- !tpMod.FPDFText_CountChars ||- !tpMod.FPDFText_GetUnicode ||- !tpMod.FPDFText_GetTextObject ||- !fontMod.FPDFTextObj_GetFont- )- return;-- const probes: Array<{ ch: string; perCharFont: number }> = [];- const seen = new Set<string>();- const textPage = tpMod.FPDFText_LoadPage(pagePtr);- if (!textPage) return;- try {- const count = tpMod.FPDFText_CountChars(textPage);- for (let i = 0; i < count; i++) {- const cp = tpMod.FPDFText_GetUnicode(textPage, i);- if (!cp) continue;- const ch = String.fromCodePoint(cp);- const obj = tpMod.FPDFText_GetTextObject(textPage, i);- if (!obj) continue;- let f = 0;- try {- f = fontMod.FPDFTextObj_GetFont(obj);- } catch {- continue;- }- if (!f) continue;- const key = `${f}:${ch}`;- if (seen.has(key)) continue;- seen.add(key);- // Skip whitespace - those aren't worth round-tripping and- // editTextHelpers' per-char branch bails on whitespace anyway.- if (/\s/.test(ch)) continue;- // Skip if already cached under this perChar font.- if (charCache.has(cacheKey(f, ch))) continue;- probes.push({ ch, perCharFont: f });- // Seed findFontForChar's cache so the emit-path probe doesn't- // re-walk the text page for the same char.- fontForCharCache.set(`${pagePtr}:${cp}`, f);- }- } finally {- if (tpMod.FPDFText_ClosePage) {- try {- tpMod.FPDFText_ClosePage(textPage);- } catch {- /* best-effort */- }- }- }- addTypeableProbes(probes, seen);- if (probes.length === 0) return;-- // Guard the page only once we're committed to the fetch fan-out.- prewarmedPages.add(pagePtr);-- try {- const { PdfiumSave } =- await import("@editor/tools/pdfTextEditor/pdfium/PdfiumSave");- const doc = getEditorDocument();- if (!doc) return;- const bytes = PdfiumSave.serialize(doc);- if (!bytes || bytes.byteLength === 0) return;- const pdfBase64 = uint8ToBase64(bytes);-- // Batch by font: fire ONE encode-charcodes request per font carrying ALL of- // that font's page chars, instead of one request per (font, char).- const byFont = new Map<number, string[]>();- for (const { ch, perCharFont } of probes) {- const arr = byFont.get(perCharFont);- if (arr) arr.push(ch);- else byFont.set(perCharFont, [ch]);- }- const fontBatches = [...byFont.entries()].map(([font, chars]) => ({- font,- chars,- }));-- // Cap concurrent encode-charcodes requests to avoid overwhelming the Spring- // backend's PDFBox parser (many parallel POSTs can saturate the thread pool).- const CONCURRENCY = 6;- let batchIdx = 0;- let probesSucceeded = 0;- const workers: Promise<void>[] = [];- for (let w = 0; w < CONCURRENCY; w++) {- workers.push(- (async () => {- while (true) {- const me = batchIdx++;- if (me >= fontBatches.length) return;- const { font, chars } = fontBatches[me];- const reqKey = `prewarm:${font}:${chars.join("")}`;- if (inFlight.has(reqKey)) continue;- inFlight.add(reqKey);- try {- const json = await postCharcodes({- pdfBase64,- pageIndex,- // Any of this font's chars is a valid locator (the font renders- // them all).- locatorChar: chars[0],- fontName: readFontName(m, font),- // Program-bytes hash beats the name: PDFium strips subset tags.- fontSha256: getCachedFontProgramSha256(font) ?? undefined,- text: chars.join(""),- });- if (!json || json.error) continue;- // Map returned charcodes back to chars: the backend appends one- // charcode per NON-missing char in request order.- const missing = new Set(json.missing ?? []);- const codes = json.charcodes ?? [];- let k = 0;- for (const ch of chars) {- if (missing.has(ch)) {- charCache.set(cacheKey(font, ch), null);- continue;- }- const code = codes[k++];- if (typeof code === "number") {- charCache.set(cacheKey(font, ch), code);- probesSucceeded += 1;- } else {- charCache.set(cacheKey(font, ch), null);- }- }- } finally {- inFlight.delete(reqKey);- }- }- })(),- );- }- await Promise.all(workers);- if (typeof console !== "undefined") {- console.debug(- `[charcode] backend prewarm pageIdx=${pageIndex} probes=${probes.length} succeeded=${probesSucceeded}`,- );- }- // If EVERY probe failed (auth, backend down, all 500s) un-mark the page so- // a subsequent focus can retry instead of silently returning early forever.- if (probesSucceeded === 0) {- prewarmedPages.delete(pagePtr);- }- } catch {- /* prewarm is best-effort - errors are silently swallowed */- prewarmedPages.delete(pagePtr);- }-}--/** Test-only: clear the per-page prewarm guard. */-export function _clearPrewarmGuardForTests(): void {- prewarmedPages.clear();-}--function getEditorContextForPage(pageIndex: number): {- module: import("@embedpdf/pdfium").WrappedPdfiumModule;- pagePtr: number;- docPtr: number;-} | null {- const doc = getEditorDocument();- if (!doc) return null;- const pages = doc.loadedPages?.();- if (!pages) return null;- for (const p of pages) {- if (p.index === pageIndex) {- return { module: doc.module, pagePtr: p.pagePtr, docPtr: doc.docPtr };- }- }- return null;-}--function pageIdxOfPagePtr(ctx: ResolverContext): number {- // The ResolverContext only carries pagePtr; map back to index by asking the- // doc model.- const w = window as unknown as {- __editor_store?: {- document?: {- loadedPages?: () => Iterable<{ pagePtr: number; index: number }>;- } | null;- };- };- const pages = w.__editor_store?.document?.loadedPages?.();- if (!pages) return -1;- for (const p of pages) if (p.pagePtr === ctx.pagePtr) return p.index;- return -1;-}--function getEditorDocument():- | import("@editor/tools/pdfTextEditor/model/EditorDocument").EditorDocument- | null {- // EditorStore.doc is TypeScript-private; the public surface is the- // `document` getter. Always read through that.- const w = window as unknown as {- __editor_store?: {- document?:- | import("@editor/tools/pdfTextEditor/model/EditorDocument").EditorDocument- | null;- };- };- return w.__editor_store?.document ?? null;-}--function uint8ToBase64(bytes: Uint8Array): string {- let bin = "";- const chunk = 0x8000;- // Pass the typed-array subarray straight to apply() (it is array-like) so we- // don't allocate an intermediate Array per chunk for large PDFs.- for (let i = 0; i < bytes.length; i += chunk) {- bin += String.fromCharCode.apply(- null,- bytes.subarray(i, i + chunk) as unknown as number[],- );- }- return btoa(bin);-}--function cacheKey(fontPtr: number, ch: string): string {- return `${fontPtr}:${ch}`;-}--/** Test-only: clear the per-char cache. */-export function _clearBackendCacheForTests(): void {- charCache.clear();- negativeUntil.clear();- inFlight.clear();-}--// Reset ALL module-level caches keyed by raw PDFium pointers (per-char-// charcodes, per-page prewarm guard, per-char font handles, in-flight set).-export function resetBackendResolverCaches(): void {- charCache.clear();- negativeUntil.clear();- inFlight.clear();- prewarmedPages.clear();- fontForCharCache.clear();- serializedCache = null;- autoPrefetchActive = 0;-}diff --git a/frontend/src/editor/core/tools/pdfTextEditor/charcode/CharcodeStrategy.ts b/frontend/src/editor/core/tools/pdfTextEditor/charcode/CharcodeStrategy.tsindex a0b4fb69a6..b3aa48a5cb 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/charcode/CharcodeStrategy.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/charcode/CharcodeStrategy.ts@@ -3,14 +3,12 @@export type CharcodeStrategy =| "helvetica" // Legacy: always fall back to Helvetica for new chars.| "cmap" // Parse the embedded font's cmap table.- | "content-stream" // Read raw PDF content streams to extract charcode bytes.- | "backend"; // Send to Spring backend, PDFBox encodes server-side.+ | "content-stream"; // Read raw PDF content streams to extract charcode bytes.export const CHARCODE_STRATEGIES: readonly CharcodeStrategy[] = ["helvetica","cmap","content-stream",- "backend",] as const;const STORAGE_KEY = "pdfTextEditor.charcodeStrategy";@@ -18,7 +16,7 @@ const URL_PARAM = "charcodeStrategy";// Resolve the active strategy: URL param wins over localStorage, which wins// over the default.-export const DEFAULT_CHARCODE_STRATEGY: CharcodeStrategy = "backend";+export const DEFAULT_CHARCODE_STRATEGY: CharcodeStrategy = "content-stream";export function getActiveCharcodeStrategy(): CharcodeStrategy {if (typeof window === "undefined") return DEFAULT_CHARCODE_STRATEGY;@@ -73,8 +71,8 @@ export interface CharcodeResolver {): CharcodeResolveResult | null;}-// Hooks every strategy needs: PDFium module access, the source page handle (for-// content-stream parsing), and fetch() for backend.+// Hooks every strategy needs: PDFium module access and the source page handle+// (for content-stream parsing).export interface ResolverContext {module: import("@embedpdf/pdfium").WrappedPdfiumModule;pagePtr: number;diff --git a/frontend/src/editor/core/tools/pdfTextEditor/charcode/FontHelpers.ts b/frontend/src/editor/core/tools/pdfTextEditor/charcode/FontHelpers.tsnew file mode 100644index 0000000000..afe0655ded--- /dev/null+++ b/frontend/src/editor/core/tools/pdfTextEditor/charcode/FontHelpers.ts@@ -0,0 +1,270 @@+import type { ResolverContext } from "@editor/tools/pdfTextEditor/charcode/CharcodeStrategy";+import {+ SCRATCH,+ scratchPtr,+} from "@editor/tools/pdfTextEditor/util/wasmScratch";++/**+ * Client-side font helpers for the charcode emit path.+ *+ * Font handles are PDFium pointers, only valid for the document that produced+ * them, so every cache here is pointer-keyed and dropped between documents+ * (`resetFontHelperCaches`).+ */++interface TextPageModule {+ FPDFText_LoadPage?: (page: number) => number;+ FPDFText_ClosePage?: (textPage: number) => void;+ FPDFText_CountChars?: (textPage: number) => number;+ FPDFText_GetUnicode?: (textPage: number, idx: number) => number;+ FPDFText_GetTextObject?: (textPage: number, idx: number) => number;+}++interface FontReadModule {+ FPDFTextObj_GetFont?: (obj: number) => number;+}++// Find an existing char on the current page whose text object uses the given+// font.+const fontForCharCache = new Map<string, number | null>();++/** Bold/italic classification of a font, read from its /BaseFont name. */+export interface FontStyleClass {+ bold: boolean;+ italic: boolean;+}++/**+ * Classify a font handle as bold/italic from its /BaseFont name.+ *+ * Borrowing a glyph from a face of a different weight is what made edited body+ * text come back bold: the first "o" in document order often lives in a bold+ * heading.+ */+export function fontStyleClass(+ m: ResolverContext["module"],+ fontPtr: number,+): FontStyleClass | null {+ const name = readFontName(m, fontPtr);+ if (!name) return null;+ return styleClassFromName(name);+}++/** Same classification from a font FAMILY name (base-14 or device font). */+export function styleClassFromName(name: string): FontStyleClass {+ return {+ bold: /bold|black|heavy|semibold|demi/i.test(name),+ italic: /italic|oblique/i.test(name),+ };+}++const reusableFontCache = new Map<number, boolean>();++/**+ * Whether a font has a real font program behind it.+ *+ * A Type 3 face is a dictionary of content-stream procedures, so PDFium can+ * report neither a glyph advance nor a usable ink box for it. Its glyphs are+ * still drawable - callers may reuse one when they can measure its advance+ * some other way - but laying out new text on PDFium's numbers alone stacks+ * every glyph on the previous one.+ */+export function fontIsReusable(+ m: ResolverContext["module"],+ fontPtr: number,+): boolean {+ if (!fontPtr) return false;+ const cached = reusableFontCache.get(fontPtr);+ if (cached !== undefined) return cached;+ const getData = (+ m as unknown as {+ FPDFFont_GetFontData?: (+ font: number,+ buf: number,+ buflen: number,+ outLen: number,+ ) => boolean;+ }+ ).FPDFFont_GetFontData;+ // No API to ask with: assume reusable so nothing regresses.+ if (typeof getData !== "function") {+ reusableFontCache.set(fontPtr, true);+ return true;+ }+ // A Type 3 font is a dictionary of content-stream procedures, not a font+ // program. PDFium still answers "true" for it, but reports a length of 0 -+ // the length is the part that distinguishes a real face.+ let ok = false;+ const out = scratchPtr(m, SCRATCH.backendOut, 4);+ try {+ m.pdfium.setValue(out, 0, "i32");+ ok = getData(fontPtr, 0, 0, out) && m.pdfium.getValue(out, "i32") > 0;+ } catch {+ ok = false;+ }+ reusableFontCache.set(fontPtr, ok);+ return ok;+}++/** Test-only: clear the reusable-font cache. */+export function _clearReusableFontCacheForTests(): void {+ reusableFontCache.clear();+}++export function findFontForChar(+ unicodeChar: string,+ ctx: ResolverContext,+ // When given, only fonts with the SAME bold/italic class as this one are+ // accepted, so a borrowed glyph never changes the run's weight or slant.+ likeFontPtr?: number,+ // Used when there is no source font handle to read a style from - notably on+ // the undo path, which re-emits with `originalFontPtr: 0`. Without it the+ // borrow is unconstrained again and restored body text comes back bold.+ likeStyle?: FontStyleClass | null,+): number | null {+ if (!unicodeChar) return null;+ const cp = unicodeChar.codePointAt(0);+ if (cp === undefined) return null;+ const m = ctx.module;+ const want =+ (likeFontPtr ? fontStyleClass(m, likeFontPtr) : null) ?? likeStyle ?? null;+ // The style is part of the answer, so it must be part of the cache key.+ const styleK = want+ ? `${want.bold ? "b" : ""}${want.italic ? "i" : ""}|`+ : "";+ // So is the source face: the borrow prefers the run's own family, so two+ // runs of different families must not share an answer.+ const likeName = likeFontPtr+ ? baseFontFamily(readFontName(m, likeFontPtr))+ : undefined;+ const cacheK = `${ctx.pagePtr}:${styleK}${likeName ?? ""}|${cp}`;+ if (fontForCharCache.has(cacheK)) return fontForCharCache.get(cacheK) ?? null;+ const tpMod = m as unknown as TextPageModule;+ const fontMod = m as unknown as FontReadModule;+ if (+ !tpMod.FPDFText_LoadPage ||+ !tpMod.FPDFText_CountChars ||+ !tpMod.FPDFText_GetUnicode ||+ !tpMod.FPDFText_GetTextObject ||+ !fontMod.FPDFTextObj_GetFont+ ) {+ fontForCharCache.set(cacheK, null);+ return null;+ }+ const textPage = tpMod.FPDFText_LoadPage(ctx.pagePtr);+ if (!textPage) {+ fontForCharCache.set(cacheK, null);+ return null;+ }+ try {+ const count = tpMod.FPDFText_CountChars(textPage);+ // The run's OWN family, wherever the page happens to draw this char in it,+ // beats whichever style-compatible face comes first in content order. A+ // word the document already uses otherwise came back in a near-miss face -+ // right weight, slightly wrong shapes and advances.+ let fallback: number | null = null;+ for (let i = 0; i < count; i++) {+ const u = tpMod.FPDFText_GetUnicode(textPage, i);+ if (u !== cp) continue;+ const obj = tpMod.FPDFText_GetTextObject(textPage, i);+ if (!obj) continue;+ try {+ const f = fontMod.FPDFTextObj_GetFont(obj);+ if (!f) continue;+ if (want) {+ const got = fontStyleClass(m, f);+ // An unnamed font can't be vouched for; skip it rather than risk a+ // weight change.+ if (!got || got.bold !== want.bold || got.italic !== want.italic) {+ continue;+ }+ }+ if (!likeName || baseFontFamily(readFontName(m, f)) === likeName) {+ fontForCharCache.set(cacheK, f);+ return f;+ }+ if (fallback === null) fallback = f;+ } catch {+ continue;+ }+ }+ if (fallback !== null) {+ fontForCharCache.set(cacheK, fallback);+ return fallback;+ }+ } finally {+ if (tpMod.FPDFText_ClosePage) {+ try {+ tpMod.FPDFText_ClosePage(textPage);+ } catch {+ /* best-effort */+ }+ }+ }+ fontForCharCache.set(cacheK, null);+ return null;+}++/** Test-only: clear the per-char-font cache. */+export function _clearFontForCharCacheForTests(): void {+ fontForCharCache.clear();+}++interface FontNameModule {+ FPDFFont_GetBaseFontName?: (font: number, buf: number, len: number) => number;+}++/**+ * A face's family, with the subset tag and style suffix stripped:+ * "ABCDEF+LMRoman12-Regular" -> "lmroman12". Two handles that agree here are+ * the same design, so a glyph borrowed across them keeps the run's look.+ */+function baseFontFamily(name: string | undefined): string | undefined {+ if (!name) return undefined;+ const family = name.replace(/^[A-Z]{6}\+/, "").split(/[-,]/)[0];+ return family ? family.toLowerCase() : undefined;+}++const fontNameCache = new Map<number, string | undefined>();++/** Test-only: clear the memoised /BaseFont names. */+export function _clearFontNameCacheForTests(): void {+ fontNameCache.clear();+}++// Read a font's /BaseFont name, the identity used to tell WHICH face a handle+// points at when two fonts on the page render the same char.+function readFontName(+ m: ResolverContext["module"],+ fontPtr: number,+): string | undefined {+ if (!fontPtr) return undefined;+ if (fontNameCache.has(fontPtr)) return fontNameCache.get(fontPtr);+ const name = loadFontName(m, fontPtr);+ fontNameCache.set(fontPtr, name);+ return name;+}++function loadFontName(+ m: ResolverContext["module"],+ fontPtr: number,+): string | undefined {+ const fn = (m as unknown as FontNameModule).FPDFFont_GetBaseFontName;+ if (typeof fn !== "function") return undefined;+ try {+ const len = fn(fontPtr, 0, 0);+ if (len <= 1) return undefined;+ const buf = scratchPtr(m, SCRATCH.readerReadTextB, len);+ fn(fontPtr, buf, len);+ return m.pdfium.UTF8ToString(buf) || undefined;+ } catch {+ return undefined;+ }+}++/** Drop every pointer-keyed font cache. PDFium reuses handles across documents. */+export function resetFontHelperCaches(): void {+ fontForCharCache.clear();+ reusableFontCache.clear();+ fontNameCache.clear();+}diff --git a/frontend/src/editor/core/tools/pdfTextEditor/charcode/charcodeRegistry.ts b/frontend/src/editor/core/tools/pdfTextEditor/charcode/charcodeRegistry.tsindex 9d6fe2868b..dbef7843d0 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/charcode/charcodeRegistry.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/charcode/charcodeRegistry.ts@@ -1,18 +1,11 @@import {- BackendResolver,findFontForChar,fontIsReusable,- prewarmBackendCacheForPage,styleClassFromName,-} from "@editor/tools/pdfTextEditor/charcode/BackendResolver";+} from "@editor/tools/pdfTextEditor/charcode/FontHelpers";/** Re-export so the emit path can do per-char font lookup. */-export {- findFontForChar,- fontIsReusable,- prewarmBackendCacheForPage,- styleClassFromName,-};+export { findFontForChar, fontIsReusable, styleClassFromName };import {CharcodeResolver,CharcodeStrategy,@@ -108,7 +101,6 @@ const resolvers: Record<CharcodeStrategy, CharcodeResolver | null> = {helvetica: null, // legacy: do nothing, caller falls back.cmap: new CmapResolver(),"content-stream": new ContentStreamResolver(),- backend: new BackendResolver(),};// Get the resolver for the currently active strategy. Returns null for@@ -163,8 +155,7 @@ export function tryResolveCharcodes(if (result && result.coverage === [...text].length) {return { strategy: r.name, result };}- // Active resolver (e.g. backend with a cold cache) did not fully cover the- // text.+ // Active resolver did not fully cover the text.if (allowContentStreamFallback && r.name !== "content-stream") {const cs = resolvers["content-stream"];const csResult = cs?.resolve(font, text, ctx);diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/editTextHelpers.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/editTextHelpers.tsindex 732fbfa847..c057ae71e6 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/commands/editTextHelpers.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/editTextHelpers.ts@@ -9,10 +9,7 @@ import type { WrappedPdfiumModule } from "@embedpdf/pdfium";import type { RGBA } from "@editor/tools/pdfTextEditor/types";import {emitCharcodeEvent,- findFontForChar,- fontIsReusable,setCharcodesOn,- styleClassFromName,tryResolveCharcodes,} from "@editor/tools/pdfTextEditor/charcode/charcodeRegistry";import { getActiveCharcodeStrategy } from "@editor/tools/pdfTextEditor/charcode/CharcodeStrategy";@@ -48,14 +45,14 @@ export function removeAndDestroyObject(}}-// Pointers freshly created by the per-char BACKEND emit branch in-// `emitTextLine`.+// Pointers the emit path produced from an already-validated charcode→glyph+// mapping; `isVerifiedPerCharPtr` lets callers skip re-measuring them.const perCharBranchPtrs = new Set<number>();// (fontPtr:char) pairs a read-back has PROVEN render faithfully via SetText.const readBackValidated = new Set<string>();-/** Caller check: was this ptr produced by the per-char emit branch? */+/** Caller check: is this a pointer the emit path already validated? */export function isVerifiedPerCharPtr(ptr: number): boolean {return perCharBranchPtrs.has(ptr);}@@ -149,9 +146,8 @@ export function charcodesResolveFully(ok = false;}// Only memoise a POSITIVE result. A miss here can simply mean the- // charcode cache was cold or the backend was briefly unreachable, and- // caching that as "this font cannot encode this character" made the- // failure permanent for the session.+ // charcode cache was cold, and caching that as "this font cannot encode+ // this character" made the failure permanent for the session.if (ok) perFont.set(ch, true);else return false;}@@ -772,9 +768,6 @@ export function emitTextLine(opts: CreatedTextOptions): number[] {// renders the chars; falls back to SetText internally.const strategyUsed = writeViaCharcodesOrSetText(ptr, text);applyFillAndPos(m, opts.page, ptr, opts.fill, x, opts.y);- // A whole-word SetCharcodes write via the BACKEND resolver used known-good- // (font, charcode) pairs PDFBox validated, so the glyph is real.- if (strategyUsed === "backend") return ptr;const right = measureObjRightEdgePt(m, ptr);const visible = text.replace(/\s+/g, "").length;// Narrowest base-14 glyph ("i") is ~0.22em; anything well under ~0.15em@@ -957,157 +950,6 @@ export function emitTextLine(opts: CreatedTextOptions): number[] {return null;}- // Per-char emit branch for the BACKEND strategy.- const isBackendStrategy = getActiveCharcodeStrategy() === "backend";- const hasAnyWhitespaceForBranch = /\s/.test(opts.text);- if (- isBackendStrategy &&- !hasAnyWhitespaceForBranch &&- opts.text.length > 0 &&- m2.FPDFPageObj_CreateTextObj- ) {- const ctx = {- module: m,- pagePtr: opts.page.pagePtr,- docPtr: opts.doc.docPtr,- };- // Probe per char first.- const perChar: Array<{ ch: string; font: number; charcodes: number[] }> =- [];- let allOk = true;- for (const ch of opts.text) {- // Prefer the run's OWN font when it renders this char: it is the- // authoritative font for the run's text.- let charFont = 0;- let resolved = null;- if (opts.originalFontPtr) {- const own = tryResolveCharcodes(opts.originalFontPtr, ch, ctx);- if (- own?.result &&- own.result.charcodes.length === 1 &&- own.result.missing.length === 0- ) {- charFont = opts.originalFontPtr;- resolved = own;- }- }- if (!charFont) {- // Constrained to the run's own weight/slant: an unconstrained borrow- // takes the first matching glyph in content order, which is usually a- // bold heading, and the edited body text comes back bold.- charFont =- findFontForChar(- ch,- ctx,- opts.originalFontPtr,- styleClassFromName(family),- ) || 0;- if (!charFont) {- allOk = false;- break;- }- resolved = tryResolveCharcodes(charFont, ch, ctx);- }- if (- !resolved?.result ||- resolved.result.charcodes.length !== 1 ||- resolved.result.missing.length > 0- ) {- allOk = false;- break;- }- // A Type 3 face has no font program, so PDFium can report neither a- // glyph advance nor a usable ink box for it: the only trustworthy- // advance is one measured from the glyph as the page already draws it.- // Without that, each following glyph lands on top of this one - the- // reported scramble. Substitute a real face instead.- if (- !fontIsReusable(m, charFont) &&- onPageAdvanceEm(m, opts.page.pagePtr, charFont, ch) == null- ) {- allOk = false;- break;- }- perChar.push({- ch,- font: charFont,- charcodes: resolved.result.charcodes,- });- }- if (allOk && perChar.length === [...opts.text].length) {- // Per-char emit: one text object per char, each with its OWN font.- const ptrs: number[] = [];- let cursor = opts.x;- for (const pc of perChar) {- const ptr = m2.FPDFPageObj_CreateTextObj(- opts.doc.docPtr,- pc.font,- size,- );- if (!ptr) {- // CreateTextObj failed mid-word.- for (const p of ptrs) {- perCharBranchPtrs.delete(p);- removeAndDestroyObject(m, opts.page.pagePtr, p);- }- ptrs.length = 0;- break;- }- const ok = setCharcodesOn(m, ptr, pc.charcodes);- if (!ok) {- // Couldn't set charcodes - rare but possible.- removeAndDestroyObject(m, opts.page.pagePtr, ptr);- for (const p of ptrs) {- perCharBranchPtrs.delete(p);- removeAndDestroyObject(m, opts.page.pagePtr, p);- }- ptrs.length = 0;- break;- }- applyFillAndPos(m, opts.page, ptr, opts.fill, cursor, opts.y);- // Advance by the char's REAL on-page advance width, read from the same- // font+char already on the page.- const advEm = onPageAdvanceEm(m, opts.page.pagePtr, pc.font, pc.ch);- if (advEm != null) {- cursor += advEm * size;- } else {- // Unmeasurable: step by the font metric rather than the object's ink- // box. The ink box collapses on faces PDFium can't measure (stacking- // the glyphs) and overshoots on wide ones (visible gaps mid-word);- // a metric advance is even and always moves forward.- cursor += measureAdvancePt(pc.ch, family, size);- }- // Reproduce the source run's letter-spacing: the glyph advance above is- // the font's natural width.- cursor += opts.charSpacingPt ?? 0;- emitCharcodeEvent({- timestamp: 0,- strategy: "backend",- text: pc.ch,- fontPtr: pc.font,- resolved: [...pc.charcodes],- missing: [],- note: `per-char backend emit: font=${pc.font} charcode=${pc.charcodes[0]}`,- outcome: "charcodes-ok",- });- ptrs.push(ptr);- opts.outTexts?.push(pc.ch);- // Mark this ptr as verified - it was created via the per-char branch- // with a known-good pair from the backend resolver cache.- perCharBranchPtrs.add(ptr);- }- if (ptrs.length === [...opts.text].length) return withRotation(ptrs);- // Any other incomplete outcome: destroy the partial emit before the- // fall-through path re-renders the word.- for (const p of ptrs) {- perCharBranchPtrs.delete(p);- removeAndDestroyObject(m, opts.page.pagePtr, p);- }- if (opts.outTexts) opts.outTexts.length = 0;- }- // fall through to the normal path if per-char attempt didn't work- }-// Letter-spaced runs: a single text object cannot carry Tc.const hasAnyWhitespace = /\s/.test(opts.text);const spacingPt = opts.charSpacingPt ?? 0;diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/partialEdit.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/partialEdit.tsindex 1a706685af..029946700d 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/commands/partialEdit.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/partialEdit.ts@@ -732,7 +732,7 @@ export function applyPartialEditPlan(const origWidth = origBounds.right - origBounds.x;const modText = op.text;// Read the object's own font BEFORE we touch it, so a fallback re-emit- // can reuse the same embedded font via the charcode/backend path.+ // can reuse the same embedded font via the charcode path.const modFontPtr = objFontPtr(m, ptr);setObjText(m, ptr, modText);if (Math.abs(offset) > 0.05) {@@ -870,8 +870,7 @@ export function applyPartialEditPlan(// Heuristic: a working visible glyph is at least ~0.15 * fontSize wide.const nonWhitespaceLen = insertText.replace(/\s/g, "").length;const minExpected = nonWhitespaceLen * run.fontSize * 0.15;- // Skip the tofu retry when ALL returned ptrs came from the per-char- // backend emit branch in emitTextLine.+ // Skip the tofu retry when every returned ptr is already verified.const allVerified =ptrs.length > 0 && ptrs.every((p) => isVerifiedPerCharPtr(p));if (diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/TextRunOverlay.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/TextRunOverlay.tsxindex bda60d502c..4d8f55f697 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/components/TextRunOverlay.tsx+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/TextRunOverlay.tsx@@ -941,23 +941,6 @@ export function TextRunOverlay({) {caretToEnd(el, sel);}- // Backend strategy: pre-warm the per-char charcode cache for the whole- // page in the background.- void (async () => {- try {- const [- { getActiveCharcodeStrategy },- { prewarmBackendCacheForPage },- ] = await Promise.all([- import("@editor/tools/pdfTextEditor/charcode/CharcodeStrategy"),- import("@editor/tools/pdfTextEditor/charcode/charcodeRegistry"),- ]);- if (getActiveCharcodeStrategy() !== "backend") return;- await prewarmBackendCacheForPage(run.pageIndex);- } catch {- /* prewarm is best-effort, never block focus */- }- })();}}onBlur={(e) => {setTouched(false);diff --git a/frontend/src/editor/core/tools/pdfTextEditor/store/EditorStore.ts b/frontend/src/editor/core/tools/pdfTextEditor/store/EditorStore.tsindex 3f6d8e62bc..fc5b3e11b9 100644--- a/frontend/src/editor/core/tools/pdfTextEditor/store/EditorStore.ts+++ b/frontend/src/editor/core/tools/pdfTextEditor/store/EditorStore.ts@@ -10,7 +10,7 @@ import {PdfiumModelSync,type ModelSyncResult,} from "@editor/tools/pdfTextEditor/pdfium/PdfiumModelSync";-import { resetBackendResolverCaches } from "@editor/tools/pdfTextEditor/charcode/BackendResolver";+import { resetFontHelperCaches } from "@editor/tools/pdfTextEditor/charcode/FontHelpers";import { resetCmapCache } from "@editor/tools/pdfTextEditor/charcode/CmapResolver";import { resetContentStreamCache } from "@editor/tools/pdfTextEditor/charcode/ContentStreamResolver";import {@@ -37,7 +37,7 @@ import { resetEmbeddedFaces } from "@editor/tools/pdfTextEditor/util/embeddedFac/** Drop EVERY per-document charcode/glyph cache. */function resetCharcodeCaches(): void {- resetBackendResolverCaches();+ resetFontHelperCaches();resetCmapCache();resetContentStreamCache();resetOnPageAdvCache();diff --git a/frontend/src/editor/core/types/toolApiTypes.ts b/frontend/src/editor/core/types/toolApiTypes.tsindex 9a2081959b..633b9e1afb 100644--- a/frontend/src/editor/core/types/toolApiTypes.ts+++ b/frontend/src/editor/core/types/toolApiTypes.ts@@ -340,10 +340,6 @@ export interface ConvertEbookToPdfRequest {}export type ConvertPdfHtmlRequest = Record<string, never>;export type ConvertPdfMarkdownRequest = Record<string, never>;-export type ConvertPdfTextEditorMetadataRequest = Record<string, never>;-export interface ConvertPdfTextEditorRequest {- lightweight?: boolean;-}export interface ConvertPdfToCbrRequest {/*** The DPI (Dots Per Inch) for rendering PDF pages as images@@ -471,33 +467,6 @@ export interface EditTableOfContentsRequest {*/replaceExisting?: boolean;}-export interface EditTextRequest {- /**- * Ordered list of find/replace operations. Each replaces every occurrence on the selected pages, in order; later operations see the result of earlier ones (so 'foo'->'foos' then 'foos'->'bars' turns 'foo' into 'bars').- */- edits: EditTextOperation[];- /**- * The pages to select, Supports ranges (e.g., '1,3,5-9'), or 'all' or functions in the format 'an+b' where 'a' is the multiplier of the page number 'n', and 'b' is a constant (e.g., '2n+1', '3n', '6n-5')- */- pageNumbers?: string;- /**- * Whether matches must be whole words (boundaries determined by non-word characters)- */- wholeWordSearch?: boolean;-}-/**- * Ordered list of find/replace operations. Each replaces every occurrence on the selected pages, in order; later operations see the result of earlier ones (so 'foo'->'foos' then 'foos'->'bars' turns 'foo' into 'bars').- */-export interface EditTextOperation {- /**- * The literal text to find.- */- find: string;- /**- * The replacement text. May be empty to delete the matched text.- */- replace: string;-}export interface EmlToPdfRequest {/*** Download HTML intermediate file instead of PDF@@ -516,14 +485,6 @@ export interface EmlToPdfRequest {*/maxAttachmentSizeMB?: number;}-export interface EncodeCharcodesRequest {- fontName?: string;- fontSha256?: string;- locatorChar?: string;- pageIndex?: number;- pdfBase64?: string;- text?: string;-}export type ExtractAttachmentsRequest = Record<string, never>;export interface ExtractHeaderRequest {/**@@ -1619,15 +1580,12 @@ export type ToolEndpoint =| "/api/v1/convert/pdf/pdfa"| "/api/v1/convert/pdf/presentation"| "/api/v1/convert/pdf/text"- | "/api/v1/convert/pdf/text-editor"- | "/api/v1/convert/pdf/text-editor/metadata"| "/api/v1/convert/pdf/ua"| "/api/v1/convert/pdf/vector"| "/api/v1/convert/pdf/word"| "/api/v1/convert/pdf/xlsx"| "/api/v1/convert/pdf/xml"| "/api/v1/convert/svg/pdf"- | "/api/v1/convert/text-editor/pdf"| "/api/v1/convert/url/pdf"| "/api/v1/convert/vector/pdf"| "/api/v1/docparse/ingest"@@ -1641,12 +1599,10 @@ export type ToolEndpoint =| "/api/v1/general/booklet-imposition"| "/api/v1/general/crop"| "/api/v1/general/edit-table-of-contents"- | "/api/v1/general/edit-text"| "/api/v1/general/extract-bookmarks"| "/api/v1/general/merge-pdfs"| "/api/v1/general/multi-page-layout"| "/api/v1/general/overlay-pdfs"- | "/api/v1/general/pdf-text-editor/encode-charcodes"| "/api/v1/general/pdf-to-single-page"| "/api/v1/general/rearrange-pages"| "/api/v1/general/remove-image-pdf"@@ -1730,15 +1686,12 @@ export interface ToolApiParams {"/api/v1/convert/pdf/pdfa": PdfToPdfARequest;"/api/v1/convert/pdf/presentation": PdfToPresentationRequest;"/api/v1/convert/pdf/text": PdfToTextOrRTFRequest;- "/api/v1/convert/pdf/text-editor": ConvertPdfTextEditorRequest;- "/api/v1/convert/pdf/text-editor/metadata": ConvertPdfTextEditorMetadataRequest;"/api/v1/convert/pdf/ua": PdfToPdfUaRequest;"/api/v1/convert/pdf/vector": PdfVectorExportRequest;"/api/v1/convert/pdf/word": PdfToWordRequest;"/api/v1/convert/pdf/xlsx": PDFWithPageNums;"/api/v1/convert/pdf/xml": ConvertPdfXmlRequest;"/api/v1/convert/svg/pdf": SvgToPdfRequest;- "/api/v1/convert/text-editor/pdf": GeneralFile;"/api/v1/convert/url/pdf": UrlToPdfRequest;"/api/v1/convert/vector/pdf": PdfVectorExportRequest;"/api/v1/docparse/ingest": IngestApiRequest;@@ -1752,12 +1705,10 @@ export interface ToolApiParams {"/api/v1/general/booklet-imposition": BookletImpositionRequest;"/api/v1/general/crop": CropPdfForm;"/api/v1/general/edit-table-of-contents": EditTableOfContentsRequest;- "/api/v1/general/edit-text": EditTextRequest;"/api/v1/general/extract-bookmarks": GeneralExtractBookmarksRequest;"/api/v1/general/merge-pdfs": MergePdfsRequest;"/api/v1/general/multi-page-layout": MergeMultiplePagesRequest;"/api/v1/general/overlay-pdfs": OverlayPdfsRequest;- "/api/v1/general/pdf-text-editor/encode-charcodes": EncodeCharcodesRequest;"/api/v1/general/pdf-to-single-page": GeneralPdfToSinglePageRequest;"/api/v1/general/rearrange-pages": RearrangePagesRequest;"/api/v1/general/remove-image-pdf": GeneralRemoveImagePdfRequest;@@ -1842,15 +1793,12 @@ export const TOOL_ENDPOINTS = ["/api/v1/convert/pdf/pdfa","/api/v1/convert/pdf/presentation","/api/v1/convert/pdf/text",- "/api/v1/convert/pdf/text-editor",- "/api/v1/convert/pdf/text-editor/metadata","/api/v1/convert/pdf/ua","/api/v1/convert/pdf/vector","/api/v1/convert/pdf/word","/api/v1/convert/pdf/xlsx","/api/v1/convert/pdf/xml","/api/v1/convert/svg/pdf",- "/api/v1/convert/text-editor/pdf","/api/v1/convert/url/pdf","/api/v1/convert/vector/pdf","/api/v1/docparse/ingest",@@ -1864,12 +1812,10 @@ export const TOOL_ENDPOINTS = ["/api/v1/general/booklet-imposition","/api/v1/general/crop","/api/v1/general/edit-table-of-contents",- "/api/v1/general/edit-text","/api/v1/general/extract-bookmarks","/api/v1/general/merge-pdfs","/api/v1/general/multi-page-layout","/api/v1/general/overlay-pdfs",- "/api/v1/general/pdf-text-editor/encode-charcodes","/api/v1/general/pdf-to-single-page","/api/v1/general/rearrange-pages","/api/v1/general/remove-image-pdf",diff --git a/frontend/src/editor/core/types/toolIO.ts b/frontend/src/editor/core/types/toolIO.tsindex d79548ee6e..74e452b80e 100644--- a/frontend/src/editor/core/types/toolIO.ts+++ b/frontend/src/editor/core/types/toolIO.ts@@ -456,11 +456,6 @@ export const TOOL_IO: ToolIOTable = {produces: "PDF",arity: "SISO",},- "/api/v1/general/edit-text": {- accepts: ["PDF"],- produces: "PDF",- arity: "SISO",- },"/api/v1/general/extract-bookmarks": {accepts: ["PDF"],produces: "JSON",diff --git a/scripts/analyze_pdf_json.py b/scripts/analyze_pdf_json.pydeleted file mode 100644index f397d4b505..0000000000--- a/scripts/analyze_pdf_json.py+++ /dev/null@@ -1,267 +0,0 @@-#!/usr/bin/env python3-"""-Quick inspection utility for PDF→JSON exports.--Usage:- python scripts/analyze_pdf_json.py path/to/export.json--The script prints size and font statistics so we can confirm whether the-lightweight export (no COS dictionaries) is active and how large the font-payloads are.-"""--from __future__ import annotations--import argparse-import json-import math-from collections.abc import Iterable-from dataclasses import dataclass-from pathlib import Path-from typing import Any---def human_bytes(value: float) -> str:- if value <= 0:- return "0 B"- units = ["B", "KB", "MB", "GB", "TB"]- order = min(int(math.log(value, 1024)), len(units) - 1)- scaled = value / (1024**order)- return f"{scaled:.1f} {units[order]}"---def base64_payload_size(encoded: str | None) -> int:- if not encoded:- return 0- length = len(encoded.strip())- if length == 0:- return 0- return int(length * 0.75)---@dataclass-class FontBreakdown:- total: int = 0- with_cos: int = 0- with_program: int = 0- with_web_program: int = 0- with_pdf_program: int = 0- program_bytes: int = 0- web_program_bytes: int = 0- pdf_program_bytes: int = 0- metadata_bytes: int = 0- sample_cos_ids: list[tuple[str | None, str | None]] = None---@dataclass-class PageBreakdown:- page_count: int = 0- total_text_elements: int = 0- total_image_elements: int = 0- text_payload_chars: int = 0- text_struct_bytes: int = 0- image_struct_bytes: int = 0- resources_bytes: int = 0- content_stream_bytes: int = 0- annotations_bytes: int = 0---@dataclass-class DocumentBreakdown:- total_bytes: int- fonts: FontBreakdown- pages: PageBreakdown- metadata_bytes: int- xmp_bytes: int- form_fields_bytes: int- lazy_flag_bytes: int---def approx_struct_size(obj: Any) -> int:- if obj is None:- return 0- return len(json.dumps(obj, separators=(",", ":")))---def analyze_fonts(fonts: Iterable[dict[str, Any]]) -> FontBreakdown:- total = 0- with_cos = 0- with_prog = 0- with_web_prog = 0- with_pdf_prog = 0- program_bytes = 0- web_program_bytes = 0- pdf_program_bytes = 0- metadata_bytes = 0- sample_cos_ids: list[tuple[str | None, str | None]] = []-- for font in fonts:- total += 1- font_id = font.get("id")- uid = font.get("uid")- cos_value = font.get("cosDictionary")- if cos_value:- with_cos += 1- if len(sample_cos_ids) < 5:- sample_cos_ids.append((font_id, uid))-- metadata_bytes += approx_struct_size(- {k: v for k, v in font.items() if k not in {"program", "webProgram", "pdfProgram"}}- )-- program = font.get("program")- web_program = font.get("webProgram")- pdf_program = font.get("pdfProgram")-- if program:- with_prog += 1- program_bytes += base64_payload_size(program)- if web_program:- with_web_prog += 1- web_program_bytes += base64_payload_size(web_program)- if pdf_program:- with_pdf_prog += 1- pdf_program_bytes += base64_payload_size(pdf_program)-- return FontBreakdown(- total=total,- with_cos=with_cos,- with_program=with_prog,- with_web_program=with_web_prog,- with_pdf_program=with_pdf_prog,- program_bytes=program_bytes,- web_program_bytes=web_program_bytes,- pdf_program_bytes=pdf_program_bytes,- metadata_bytes=metadata_bytes,- sample_cos_ids=sample_cos_ids,- )---def analyze_pages(pages: Iterable[dict[str, Any]]) -> PageBreakdown:- page_count = 0- total_text = 0- total_images = 0- text_chars = 0- text_struct_bytes = 0- image_struct_bytes = 0- resources_bytes = 0- stream_bytes = 0- annotations_bytes = 0-- for page in pages:- page_count += 1- texts = page.get("textElements") or []- images = page.get("imageElements") or []- resources = page.get("resources")- streams = page.get("contentStreams") or []- annotations = page.get("annotations") or []-- total_text += len(texts)- total_images += len(images)- text_struct_bytes += approx_struct_size(texts)- image_struct_bytes += approx_struct_size(images)- resources_bytes += approx_struct_size(resources)- stream_bytes += approx_struct_size(streams)- annotations_bytes += approx_struct_size(annotations)-- for elem in texts:- text = elem.get("text")- if text:- text_chars += len(text)-- return PageBreakdown(- page_count=page_count,- total_text_elements=total_text,- total_image_elements=total_images,- text_payload_chars=text_chars,- text_struct_bytes=text_struct_bytes,- image_struct_bytes=image_struct_bytes,- resources_bytes=resources_bytes,- content_stream_bytes=stream_bytes,- annotations_bytes=annotations_bytes,- )---def analyze_document(document: dict[str, Any], total_size: int) -> DocumentBreakdown:- fonts = document.get("fonts") or []- pages = document.get("pages") or []- metadata = document.get("metadata") or {}-- font_stats = analyze_fonts(fonts)- page_stats = analyze_pages(pages)-- return DocumentBreakdown(- total_bytes=total_size,- fonts=font_stats,- pages=page_stats,- metadata_bytes=approx_struct_size(metadata),- xmp_bytes=base64_payload_size(document.get("xmpMetadata")),- form_fields_bytes=approx_struct_size(document.get("formFields")),- lazy_flag_bytes=approx_struct_size(document.get("lazyImages")),- )---def main() -> None:- parser = argparse.ArgumentParser(description="Inspect a PDF JSON export.")- parser.add_argument("json_path", type=Path, help="Path to the JSON export.")- args = parser.parse_args()-- json_path = args.json_path- if not json_path.exists():- raise SystemExit(f"File not found: {json_path}")-- file_size = json_path.stat().st_size- print(f"File: {json_path}")- print(f"Size: {human_bytes(file_size)} ({file_size:,} bytes)")-- with json_path.open("r", encoding="utf-8") as handle:- document = json.load(handle)-- if not isinstance(document, dict):- raise SystemExit("Unexpected JSON structure (expected an object at root).")-- summary = analyze_document(document, file_size)- page_stats = summary.pages- print(f"Pages: {page_stats.page_count}")- print(f"Total text elements: {page_stats.total_text_elements:,}")- print(f"Total image elements: {page_stats.total_image_elements:,}")- print(- f"Page structural bytes (text arrays + images + streams + annotations): "- f"{human_bytes(page_stats.text_struct_bytes + page_stats.image_struct_bytes + page_stats.content_stream_bytes + page_stats.annotations_bytes)}"- )-- font_stats = summary.fonts- print("\nFont summary:")- print(f" Fonts total: {font_stats.total}")- print(f" Fonts with cosDictionary: {font_stats.with_cos}")- print(f" Fonts with program: {font_stats.with_program}")- print(f" Fonts with webProgram: {font_stats.with_web_program}")- print(f" Fonts with pdfProgram: {font_stats.with_pdf_program}")- print(- " Payload sizes:"- f" program={human_bytes(font_stats.program_bytes)},"- f" webProgram={human_bytes(font_stats.web_program_bytes)},"- f" pdfProgram={human_bytes(font_stats.pdf_program_bytes)},"- f" metadata={human_bytes(font_stats.metadata_bytes)}"- )- if font_stats.sample_cos_ids:- print(" Sample fonts still carrying cosDictionary:")- for idx, (font_id, uid) in enumerate(font_stats.sample_cos_ids, start=1):- print(f" {idx}. id={font_id!r}, uid={uid!r}")- else:- print(" No fonts retain cosDictionary entries.")-- print("\nOther sections:")- print(f" Metadata bytes: {human_bytes(summary.metadata_bytes)}")- print(f" XMP metadata bytes: {human_bytes(summary.xmp_bytes)}")- print(f" Form fields bytes: {human_bytes(summary.form_fields_bytes)}")- print(f" Lazy flag bytes: {summary.lazy_flag_bytes}")- print(f" Text payload characters (not counting JSON overhead): {page_stats.text_payload_chars:,}")- print(f" Approx text structure bytes: {human_bytes(page_stats.text_struct_bytes)}")- print(f" Approx image structure bytes: {human_bytes(page_stats.image_struct_bytes)}")- print(f" Approx content stream bytes: {human_bytes(page_stats.content_stream_bytes)}")- print(f" Approx annotations bytes: {human_bytes(page_stats.annotations_bytes)}")---if __name__ == "__main__":- main()diff --git a/scripts/convert_cff_to_ttf.py b/scripts/convert_cff_to_ttf.pydeleted file mode 100644index 0ae480da7a..0000000000--- a/scripts/convert_cff_to_ttf.py+++ /dev/null@@ -1,548 +0,0 @@-#!/usr/bin/env python3-"""-Wrap raw CFF/Type1C data (extracted from PDFs) as OpenType-CFF for web compatibility.-Builds proper Unicode cmap from PDF ToUnicode data.-"""--import re-import sys-from io import BytesIO-from pathlib import Path--from fontTools.cffLib import CFFFontSet-from fontTools.ttLib import TTFont, newTable-from fontTools.ttLib.tables._c_m_a_p import cmap_format_4, cmap_format_12-from fontTools.ttLib.tables._n_a_m_e import NameRecord-from fontTools.ttLib.tables.O_S_2f_2 import Panose---def parse_unicode_mapping(mapping_path):- """- Parse Unicode mapping (either JSON with CharCode→CID→GID→Unicode or raw ToUnicode CMap).-- Returns:- dict[int, int]: GID → Unicode codepoint- """- try:- with open(mapping_path, "rb") as f:- data = f.read().decode("utf-8", errors="ignore")-- # Try parsing as JSON first (CID font with complete mapping)- if data.strip().startswith("{"):- import json-- try:- mapping_data = json.loads(data)- if mapping_data.get("isCID"):- # Build GID → Unicode mapping from entries- gid_to_unicode = {}- for entry in mapping_data.get("entries", []):- gid = entry["gid"]- unicode_val = entry["unicode"]- if unicode_val > 0:- gid_to_unicode[gid] = unicode_val- print(- f"Parsed JSON mapping: {len(gid_to_unicode)} GID→Unicode entries",- file=sys.stderr,- )- return gid_to_unicode- except json.JSONDecodeError:- pass-- # Fall back to parsing raw ToUnicode CMap (non-CID fonts)- # For non-CID fonts, CID/GID is the same as array index- gid_to_unicode = {}-- # Pattern for bfchar entries- bfchar_pattern = r"<([0-9A-Fa-f]+)>\s*<([0-9A-Fa-f]+)>"- for match in re.finditer(bfchar_pattern, data):- gid = int(match.group(1), 16) # For non-CID, char code == GID- unicode_val = int(match.group(2), 16)- if unicode_val > 0:- gid_to_unicode[gid] = unicode_val-- # Pattern for bfrange entries- bfrange_pattern = r"<([0-9A-Fa-f]+)>\s*<([0-9A-Fa-f]+)>\s*<([0-9A-Fa-f]+)>"- for match in re.finditer(bfrange_pattern, data):- start_gid = int(match.group(1), 16)- end_gid = int(match.group(2), 16)- start_unicode = int(match.group(3), 16)- for i, gid in enumerate(range(start_gid, end_gid + 1)):- unicode_val = start_unicode + i- if unicode_val > 0:- gid_to_unicode[gid] = unicode_val-- print(f"Parsed ToUnicode CMap: {len(gid_to_unicode)} mappings", file=sys.stderr)- return gid_to_unicode-- except Exception as e:- print(f"Warning: Failed to parse Unicode mapping: {e}", file=sys.stderr)- return {}---def wrap_cff_as_otf(input_path, output_path, tounicode_path=None):- """- Wrap raw CFF data (from PDF font stream) as OpenType-CFF.-- Args:- input_path: Path to input CFF data file- output_path: Path to output OTF font- tounicode_path: Optional path to ToUnicode CMap file-- Returns:- True if successful, False otherwise- """- try:- # Read raw CFF data- with open(input_path, "rb") as f:- cff_data = f.read()-- # Parse raw CFF data- cff_fontset = CFFFontSet()- cff_fontset.decompile(BytesIO(cff_data), None)-- # Get the first (and usually only) font in the CFF set- if len(cff_fontset.fontNames) == 0:- print("ERROR: No fonts found in CFF data", file=sys.stderr)- return False-- cff_font = cff_fontset[cff_fontset.fontNames[0]]-- # Parse Unicode mapping (JSON or raw ToUnicode CMap) if provided- gid_to_unicode = {}- if tounicode_path:- gid_to_unicode = parse_unicode_mapping(tounicode_path)-- # Create a new OTF font- otf = TTFont(sfntVersion="OTTO") # 'OTTO' = CFF-flavored OpenType-- # Get glyph names- if hasattr(cff_font, "charset") and cff_font.charset is not None:- glyph_order = [".notdef"] + [name for name in cff_font.charset if name != ".notdef"]- else:- # Fallback to CharStrings keys- charstrings = cff_font.CharStrings- glyph_order = [".notdef"] + [name for name in charstrings.keys() if name != ".notdef"]-- otf.setGlyphOrder(glyph_order)-- # === Add CFF table (the actual font outlines) ===- cff_table = newTable("CFF ")- cff_table.cff = cff_fontset- otf["CFF "] = cff_table-- # === Calculate metrics from CFF ===- charstrings = cff_font.CharStrings-- # Get defaults from CFF Private dict- private_dict = getattr(cff_font, "Private", None)- default_width = getattr(private_dict, "defaultWidthX", 500) if private_dict else 500-- # Calculate bounding box, widths, and LSBs- x_min = 0- y_min = -200- x_max = 1000- y_max = 800- max_advance = 0- min_lsb = 0- min_rsb = 0- max_extent = 0-- widths = {}- lsbs = {}-- for glyph_name in glyph_order:- lsb = 0- width = int(default_width)-- if glyph_name in charstrings:- try:- cs = charstrings[glyph_name]-- # Get width from charstring- if hasattr(cs, "width"):- width = int(cs.width)-- # Calculate bounds for LSB and bbox- try:- bounds = cs.calcBounds(None)- if bounds:- glyph_xmin = int(bounds[0])- glyph_ymin = int(bounds[1])- glyph_xmax = int(bounds[2])- glyph_ymax = int(bounds[3])-- lsb = glyph_xmin- rsb = width - glyph_xmax- extent = lsb + glyph_xmax-- # Update global bounds- x_min = min(x_min, glyph_xmin)- y_min = min(y_min, glyph_ymin)- x_max = max(x_max, glyph_xmax)- y_max = max(y_max, glyph_ymax)-- # Update hhea metrics- min_lsb = min(min_lsb, lsb)- min_rsb = min(min_rsb, rsb)- max_extent = max(max_extent, extent)- except Exception:- pass # Some glyphs may not have outlines-- except Exception:- pass # Use defaults-- widths[glyph_name] = width- lsbs[glyph_name] = lsb- max_advance = max(max_advance, width)-- if max_advance == 0:- max_advance = 1000- if max_extent == 0:- max_extent = x_max-- units_per_em = 1000 # Standard for Type1/CFF-- # === Create head table ===- head = newTable("head")- head.tableVersion = 1.0- head.fontRevision = 1.0- head.checkSumAdjustment = 0- head.magicNumber = 0x5F0F3CF5- head.flags = 0x000B # Baseline at y=0, LSB at x=0, integer PPEM- head.unitsPerEm = units_per_em- head.created = 3600000000- head.modified = 3600000000- head.xMin = x_min- head.yMin = y_min- head.xMax = x_max- head.yMax = y_max- head.macStyle = 0- head.fontDirectionHint = 2- head.indexToLocFormat = 0- head.glyphDataFormat = 0- head.lowestRecPPEM = 8- otf["head"] = head-- # === Create hhea table with correct metrics ===- hhea = newTable("hhea")- hhea.tableVersion = 0x00010000- hhea.ascent = max(y_max, 800)- hhea.descent = min(y_min, -200)- hhea.lineGap = 0- hhea.advanceWidthMax = max_advance- hhea.minLeftSideBearing = min_lsb- hhea.minRightSideBearing = min_rsb- hhea.xMaxExtent = max_extent- hhea.caretSlopeRise = 1- hhea.caretSlopeRun = 0- hhea.caretOffset = 0- hhea.reserved0 = 0- hhea.reserved1 = 0- hhea.reserved2 = 0- hhea.reserved3 = 0- hhea.metricDataFormat = 0- hhea.numberOfHMetrics = len(glyph_order)- otf["hhea"] = hhea-- # === Create hmtx table with correct LSBs ===- hmtx = newTable("hmtx")- hmtx.metrics = {}- for glyph_name in glyph_order:- hmtx.metrics[glyph_name] = (- widths.get(glyph_name, default_width),- lsbs.get(glyph_name, 0),- )- otf["hmtx"] = hmtx-- # === Create maxp table (simpler for CFF) ===- maxp = newTable("maxp")- maxp.tableVersion = 0x00005000 # CFF version (0.5)- maxp.numGlyphs = len(glyph_order)- otf["maxp"] = maxp-- # === Build Unicode cmap from GID→Unicode mapping ===- unicode_to_glyph = {}-- if gid_to_unicode:- # Debug: Show first few glyph names to understand naming convention- sample_glyphs = glyph_order[: min(10, len(glyph_order))]- print(f"Sample glyph names: {sample_glyphs}", file=sys.stderr)-- # Debug: Show which GIDs we have mappings for- sample_gids = sorted(gid_to_unicode.keys())[:10]- print(f"Sample GIDs from mapping: {sample_gids}", file=sys.stderr)-- # For CID fonts: glyph names are "cid00123" (5-digit zero-padded)- # For non-CID fonts: glyph names vary but GID == array index- is_cid_font = any(gn.startswith("cid") for gn in glyph_order[1:6]) # Check first few non-.notdef glyphs-- for gid, unicode_val in gid_to_unicode.items():- if unicode_val > 0:- if is_cid_font:- # Build glyph name as cidNNNNN (5 digits, zero-padded)- glyph_name = f"cid{gid:05d}"- # Verify this glyph exists in glyph_order- if glyph_name in glyph_order:- unicode_to_glyph[unicode_val] = glyph_name- else:- # Try without padding (some fonts use "cid123" not "cid00123")- glyph_name_alt = f"cid{gid}"- if glyph_name_alt in glyph_order:- unicode_to_glyph[unicode_val] = glyph_name_alt- else:- # Non-CID font: GID is array index- if 0 <= gid < len(glyph_order):- glyph_name = glyph_order[gid]- unicode_to_glyph[unicode_val] = glyph_name-- print(- f"Mapped {len(unicode_to_glyph)} Unicode codepoints (isCID={is_cid_font if gid_to_unicode else 'unknown'})",- file=sys.stderr,- )-- # Also try to map from glyph names (uni0041 → U+0041)- for glyph_name in glyph_order:- if glyph_name.startswith("uni") and len(glyph_name) == 7:- try:- unicode_val = int(glyph_name[3:], 16)- if unicode_val not in unicode_to_glyph:- unicode_to_glyph[unicode_val] = glyph_name- except Exception:- pass- elif glyph_name.startswith("u") and len(glyph_name) >= 5:- try:- unicode_val = int(glyph_name[1:], 16)- if unicode_val not in unicode_to_glyph:- unicode_to_glyph[unicode_val] = glyph_name- except Exception:- pass-- # === Create cmap table ===- cmap = newTable("cmap")- cmap.tableVersion = 0- cmap_tables = []-- # Windows Unicode BMP (format 4) - required- cmap4_win = cmap_format_4(4)- cmap4_win.platformID = 3 # Windows- cmap4_win.platEncID = 1 # Unicode BMP- cmap4_win.language = 0- cmap4_win.cmap = {cp: gn for cp, gn in unicode_to_glyph.items() if cp <= 0xFFFF}- cmap_tables.append(cmap4_win)-- # Windows Unicode UCS-4 (format 12) - for >BMP- if any(cp > 0xFFFF for cp in unicode_to_glyph):- cmap12_win = cmap_format_12(12)- cmap12_win.platformID = 3 # Windows- cmap12_win.platEncID = 10 # Unicode UCS-4- cmap12_win.language = 0- cmap12_win.cmap = dict(unicode_to_glyph)- cmap_tables.append(cmap12_win)-- # Mac Unicode (format 4) - for compatibility- cmap4_mac = cmap_format_4(4)- cmap4_mac.platformID = 1 # Mac- cmap4_mac.platEncID = 0 # Roman- cmap4_mac.language = 0- cmap4_mac.cmap = {cp: gn for cp, gn in unicode_to_glyph.items() if cp <= 0xFFFF}- cmap_tables.append(cmap4_mac)-- cmap.tables = [t for t in cmap_tables if t.cmap] or [cmap4_win] # Ensure at least one- otf["cmap"] = cmap-- print(f"Built cmap with {len(unicode_to_glyph)} Unicode mappings", file=sys.stderr)-- # === Create OS/2 table with correct metrics ===- os2 = newTable("OS/2")- os2.version = 4- os2.xAvgCharWidth = int(sum(widths.values()) / len(widths)) if widths else 500- os2.usWeightClass = 400 # Normal- os2.usWidthClass = 5 # Medium- os2.fsType = 0 # Installable embedding- os2.ySubscriptXSize = 650- os2.ySubscriptYSize = 600- os2.ySubscriptXOffset = 0- os2.ySubscriptYOffset = 75- os2.ySuperscriptXSize = 650- os2.ySuperscriptYSize = 600- os2.ySuperscriptXOffset = 0- os2.ySuperscriptYOffset = 350- os2.yStrikeoutSize = 50- os2.yStrikeoutPosition = 300- os2.sFamilyClass = 0-- # PANOSE - use proper object structure- os2.panose = Panose()- os2.panose.bFamilyType = 0- os2.panose.bSerifStyle = 0- os2.panose.bWeight = 0- os2.panose.bProportion = 0- os2.panose.bContrast = 0- os2.panose.bStrokeVariation = 0- os2.panose.bArmStyle = 0- os2.panose.bLetterForm = 0- os2.panose.bMidline = 0- os2.panose.bXHeight = 0-- os2.ulUnicodeRange1 = 0- os2.ulUnicodeRange2 = 0- os2.ulUnicodeRange3 = 0- os2.ulUnicodeRange4 = 0- os2.achVendID = "SPDF"- os2.fsSelection = 0x0040 # REGULAR bit-- # Set character index range from actual cmap- if unicode_to_glyph:- codepoints = sorted(unicode_to_glyph.keys())- os2.usFirstCharIndex = codepoints[0]- os2.usLastCharIndex = codepoints[-1]- else:- os2.usFirstCharIndex = 0x20 # space- os2.usLastCharIndex = 0x7E # tilde-- # Typo metrics match hhea- os2.sTypoAscender = hhea.ascent- os2.sTypoDescender = hhea.descent- os2.sTypoLineGap = hhea.lineGap-- # Windows metrics (positive values, cover bbox)- os2.usWinAscent = max(0, y_max)- os2.usWinDescent = max(0, -y_min)-- os2.ulCodePageRange1 = 0x00000001 # Latin 1- os2.ulCodePageRange2 = 0- os2.sxHeight = 500- os2.sCapHeight = 700- os2.usDefaultChar = 0- os2.usBreakChar = 32- os2.usMaxContext = 0- otf["OS/2"] = os2-- # === Create name table with Windows and Mac records ===- name = newTable("name")- name.names = []-- # Get font name from CFF if available- font_name = cff_fontset.fontNames[0] if cff_fontset.fontNames else "Converted"-- name_strings = {- 1: font_name, # Font Family- 2: "Regular", # Subfamily- 3: f"Stirling-PDF: {font_name}", # Unique ID- 4: font_name, # Full Name- 5: "Version 1.0", # Version- 6: font_name.replace(" ", "-"), # PostScript Name- }-- # Add both Windows and Mac name records- for name_id, value in name_strings.items():- # Windows (platform 3, encoding 1, language 0x0409 = en-US)- rec_win = NameRecord()- rec_win.nameID = name_id- rec_win.platformID = 3- rec_win.platEncID = 1- rec_win.langID = 0x0409- rec_win.string = value- name.names.append(rec_win)-- # Mac (platform 1, encoding 0, language 0)- rec_mac = NameRecord()- rec_mac.nameID = name_id- rec_mac.platformID = 1- rec_mac.platEncID = 0- rec_mac.langID = 0- rec_mac.string = value- name.names.append(rec_mac)-- otf["name"] = name-- # === Create post table (format 3.0 for smaller web fonts) ===- post = newTable("post")- post.formatType = 3.0 # No glyph names (smaller, web-optimized)- post.italicAngle = 0- post.underlinePosition = -100- post.underlineThickness = 50- post.isFixedPitch = 0- post.minMemType42 = 0- post.maxMemType42 = 0- post.minMemType1 = 0- post.maxMemType1 = 0- otf["post"] = post-- # Save the OTF font- otf.save(output_path)- otf.close()-- return True-- except Exception as e:- print(f"ERROR: Conversion failed: {str(e)}", file=sys.stderr)- import traceback-- traceback.print_exc(file=sys.stderr)- return False---def main():- import argparse-- # Create argument parser that supports both named and positional arguments- parser = argparse.ArgumentParser(- description="Convert CFF font data to OpenType-CFF format",- formatter_class=argparse.RawDescriptionHelpFormatter,- epilog="""-Examples:- # Named arguments (used by Java code):- convert_cff_to_ttf.py --input font.cff --output font.otf --to-unicode mapping.tounicode-- # Positional arguments (backward compatibility):- convert_cff_to_ttf.py font.cff font.otf mapping.tounicode- """,- )-- # Add named arguments- parser.add_argument("--input", dest="input_file", help="Input CFF file path")- parser.add_argument("--output", dest="output_file", help="Output OTF file path")- parser.add_argument("--to-unicode", dest="tounicode_file", help="ToUnicode mapping file path")-- # Add positional arguments for backward compatibility- parser.add_argument("input_pos", nargs="?", help="Input CFF file (positional)")- parser.add_argument("output_pos", nargs="?", help="Output OTF file (positional)")- parser.add_argument("tounicode_pos", nargs="?", help="ToUnicode file (positional)")-- args = parser.parse_args()-- # Determine which arguments to use (named take precedence over positional)- input_path = args.input_file or args.input_pos- output_path = args.output_file or args.output_pos- tounicode_path = args.tounicode_file or args.tounicode_pos-- # Validate required arguments- if not input_path or not output_path:- parser.print_help(file=sys.stderr)- print("\nERROR: Both input and output files are required", file=sys.stderr)- sys.exit(1)-- input_path = Path(input_path)- output_path = Path(output_path)- tounicode_path = Path(tounicode_path) if tounicode_path else None-- if not input_path.exists():- print(f"ERROR: Input file not found: {input_path}", file=sys.stderr)- sys.exit(1)-- if tounicode_path and not tounicode_path.exists():- print(f"Warning: ToUnicode file not found: {tounicode_path}", file=sys.stderr)- tounicode_path = None-- success = wrap_cff_as_otf(- str(input_path),- str(output_path),- str(tounicode_path) if tounicode_path else None,- )- sys.exit(0 if success else 1)---if __name__ == "__main__":- main()diff --git a/scripts/download_pdf_samples.py b/scripts/download_pdf_samples.pydeleted file mode 100644index c2ab27a1f9..0000000000--- a/scripts/download_pdf_samples.py+++ /dev/null@@ -1,195 +0,0 @@-#!/usr/bin/env python3-"""-Download large batches of PDF URLs into a local directory so they can be fed to-scripts/harvest_type3_fonts.py (or any other processing pipeline).--Usage examples:-- # Download every URL listed in pdf_urls.txt into tmp/type3-pdfs- python scripts/download_pdf_samples.py \- --urls-file pdf_urls.txt \- --output-dir tmp/type3-pdfs-- # Mix inline URLs with a file and use 16 concurrent downloads- python scripts/download_pdf_samples.py \- --urls https://example.com/a.pdf https://example.com/b.pdf \- --urls-file more_urls.txt \- --output-dir tmp/type3-pdfs \- --workers 16-"""--from __future__ import annotations--import argparse-import concurrent.futures-import hashlib-import os-import re-import sys-from pathlib import Path-from urllib.parse import unquote, urlparse--import requests---def parse_args() -> argparse.Namespace:- parser = argparse.ArgumentParser(description="Bulk download PDF URLs.")- parser.add_argument(- "--urls",- nargs="*",- default=[],- help="Inline list of PDF URLs (can be combined with --urls-file).",- )- parser.add_argument(- "--urls-file",- action="append",- help="Text file containing one URL per line (can be repeated).",- )- parser.add_argument(- "--output-dir",- default="tmp/harvest-pdfs",- help="Directory to store downloaded PDFs (default: %(default)s).",- )- parser.add_argument(- "--workers",- type=int,- default=min(8, (os.cpu_count() or 4) * 2),- help="Number of concurrent downloads (default: %(default)s).",- )- parser.add_argument(- "--timeout",- type=int,- default=120,- help="Per-request timeout in seconds (default: %(default)s).",- )- parser.add_argument(- "--overwrite",- action="store_true",- help="Overwrite existing files (default: skip already downloaded PDFs).",- )- return parser.parse_args()---def load_urls(args: argparse.Namespace) -> list[str]:- urls: list[str] = []- seen: set[str] = set()-- def add(url: str) -> None:- clean = url.strip()- if not clean or clean.startswith("#"):- return- if clean not in seen:- seen.add(clean)- urls.append(clean)-- for url in args.urls:- add(url)- if args.urls_file:- for file in args.urls_file:- path = Path(file)- if not path.exists():- print(f"[WARN] URL file not found: {file}", file=sys.stderr)- continue- with path.open("r", encoding="utf-8") as handle:- for line in handle:- add(line)- if not urls:- raise SystemExit("No URLs supplied. Use --urls and/or --urls-file.")- return urls---def sanitize_filename(name: str) -> str:- return re.sub(r"[^A-Za-z0-9._-]+", "_", name).strip("_") or "download"---def build_filename(url: str, output_dir: Path) -> Path:- parsed = urlparse(url)- candidate = Path(unquote(parsed.path)).name- if not candidate:- candidate = "download.pdf"- candidate = sanitize_filename(candidate)- if not candidate.lower().endswith(".pdf"):- candidate += ".pdf"- target = output_dir / candidate- if not target.exists():- return target- stem = target.stem- suffix = target.suffix- digest = hashlib.sha1(url.encode("utf-8")).hexdigest()[:8]- return output_dir / f"{stem}-{digest}{suffix}"---def download_pdf(- url: str,- output_dir: Path,- timeout: int,- overwrite: bool,-) -> tuple[str, Path | None, str | None]:- try:- dest = build_filename(url, output_dir)- if dest.exists() and not overwrite:- return url, dest, "exists"-- response = requests.get(url, stream=True, timeout=timeout)- response.raise_for_status()-- content_type = response.headers.get("Content-Type", "").lower()- if "pdf" not in content_type and not url.lower().endswith(".pdf"):- # Peek into the first bytes to be safe- peek = response.raw.read(5, decode_content=True)- if not peek.startswith(b"%PDF"):- return (- url,- None,- f"Skipping non-PDF content-type ({content_type or 'unknown'})",- )- content = peek + response.content[len(peek) :]- else:- content = response.content-- output_dir.mkdir(parents=True, exist_ok=True)- dest.write_bytes(content)- return url, dest, None- except Exception as exc: # pylint: disable=broad-except- return url, None, str(exc)---def main() -> None:- args = parse_args()- urls = load_urls(args)- output_dir = Path(args.output_dir).resolve()- output_dir.mkdir(parents=True, exist_ok=True)-- print(f"Downloading {len(urls)} PDFs to {output_dir} using {args.workers} workers...")-- successes = 0- skipped = 0- failures: list[tuple[str, str]] = []-- with concurrent.futures.ThreadPoolExecutor(max_workers=args.workers) as executor:- future_to_url = {- executor.submit(download_pdf, url, output_dir, args.timeout, args.overwrite): url for url in urls- }- for future in concurrent.futures.as_completed(future_to_url):- url = future_to_url[future]- result_url, path, error = future.result()- if error == "exists":- skipped += 1- print(f"[SKIP] {url} (already downloaded)")- elif error:- failures.append((result_url, error))- print(f"[FAIL] {url} -> {error}", file=sys.stderr)- else:- successes += 1- print(f"[OK] {url} -> {path}")-- print()- print(f"Completed. Success: {successes}, Skipped: {skipped}, Failures: {len(failures)}")- if failures:- print("Failures:")- for url, error in failures:- print(f" {url} -> {error}")---if __name__ == "__main__":- main()diff --git a/scripts/harvest_type3_fonts.py b/scripts/harvest_type3_fonts.pydeleted file mode 100644index 380d332d96..0000000000--- a/scripts/harvest_type3_fonts.py+++ /dev/null@@ -1,241 +0,0 @@-#!/usr/bin/env python3-"""-Bulk-harvest Type3 font signatures from a folder full of PDFs.--The script iterates over every PDF (recursively) inside the supplied --input-paths, invokes the existing Gradle Type3SignatureTool for each document, and-collects the unique Type3 font signatures that were discovered. Signature JSON-files are stored under --signatures-dir; previously captured files are reused-so you can keep dropping new PDFs into the input directory and re-run the-harvester at any time.--Example:- python scripts/harvest_type3_fonts.py \- --input incoming-type3-pdfs \- --signatures docs/type3/signatures \- --report docs/type3/harvest_report.json-"""--from __future__ import annotations--import argparse-import datetime as dt-import hashlib-import json-import os-import re-import shlex-import subprocess-import sys-from collections.abc import Sequence-from pathlib import Path--REPO_ROOT = Path(__file__).resolve().parents[1]---def parse_args() -> argparse.Namespace:- parser = argparse.ArgumentParser(description="Bulk collect Type3 font signatures from PDFs.")- parser.add_argument(- "--input",- nargs="+",- required=True,- help="One or more PDF files or directories containing PDFs (searched recursively).",- )- parser.add_argument(- "--signatures-dir",- default="docs/type3/signatures",- help="Destination directory for per-PDF signature JSON files.",- )- parser.add_argument(- "--report",- default="docs/type3/harvest_report.json",- help="Summary JSON that lists every unique signature discovered so far.",- )- default_gradle = "gradlew.bat" if os.name == "nt" else "./gradlew"- parser.add_argument(- "--gradle-cmd",- default=default_gradle,- help=f"Path to the Gradle wrapper used to invoke the Type3SignatureTool (default: {default_gradle}).",- )- parser.add_argument(- "--force",- action="store_true",- help="Re-run the signature tool even if the output JSON already exists.",- )- parser.add_argument(- "--pretty",- action="store_true",- help="Ask the Java tool to emit pretty-printed JSON (handy for diffs).",- )- return parser.parse_args()---def discover_pdfs(paths: Sequence[str]) -> list[Path]:- pdfs: list[Path] = []- for raw in paths:- path = Path(raw).resolve()- if path.is_file():- if path.suffix.lower() == ".pdf":- pdfs.append(path)- elif path.is_dir():- pdfs.extend(sorted(path.rglob("*.pdf")))- unique = sorted(dict.fromkeys(pdfs))- if not unique:- raise SystemExit("No PDF files found under the supplied --input paths.")- return unique---def sanitize_part(part: str) -> str:- cleaned = re.sub(r"[^A-Za-z0-9._-]+", "_", part)- return cleaned or "_"---def derive_signature_path(pdf: Path, signatures_dir: Path) -> Path:- """- Mirror the PDF path under the signatures directory.- If the PDF lives outside the repo, fall back to a hashed filename.- """- try:- rel = pdf.relative_to(REPO_ROOT)- except ValueError:- digest = hashlib.sha1(str(pdf).encode("utf-8")).hexdigest()[:10]- rel = Path("__external__") / f"{sanitize_part(pdf.stem)}-{digest}.pdf"-- sanitized_parts = [sanitize_part(part) for part in rel.parts]- signature_rel = Path(*sanitized_parts).with_suffix(".json")- return signatures_dir / signature_rel---def load_signature_file(path: Path) -> dict:- with path.open("r", encoding="utf-8") as handle:- return json.load(handle)---def collect_known_signatures(signatures_dir: Path) -> dict[str, dict]:- known: dict[str, dict] = {}- if not signatures_dir.exists():- return known- for json_file in signatures_dir.rglob("*.json"):- try:- payload = load_signature_file(json_file)- except Exception:- continue- pdf = payload.get("pdf")- for font in payload.get("fonts", []):- signature = font.get("signature")- if not signature or signature in known:- continue- known[signature] = {- "signature": signature,- "alias": font.get("alias"),- "baseName": font.get("baseName"),- "glyphCount": font.get("glyphCount"),- "glyphCoverage": font.get("glyphCoverage"),- "samplePdf": pdf,- "signatureJson": str(json_file),- }- return known---def run_signature_tool(gradle_cmd: str, pdf: Path, output_path: Path, pretty: bool, cwd: Path) -> None:- output_path.parent.mkdir(parents=True, exist_ok=True)- args = f"--pdf {shlex.quote(str(pdf))} --output {shlex.quote(str(output_path))}"- if pretty:- args += " --pretty"- # Use shell invocation so the quoted --args string is parsed correctly by Gradle.- cmd = f'{gradle_cmd} -q :proprietary:type3SignatureTool --args="{args}"'- completed = subprocess.run(- cmd,- shell=True,- cwd=cwd,- stdout=subprocess.PIPE,- stderr=subprocess.PIPE,- text=True,- )- if completed.returncode != 0:- raise RuntimeError(f"Gradle Type3SignatureTool failed for {pdf}:\n{completed.stderr.strip()}")---def extract_fonts_from_payload(payload: dict) -> list[dict]:- pdf = payload.get("pdf")- fonts = []- for font in payload.get("fonts", []):- signature = font.get("signature")- if not signature:- continue- fonts.append(- {- "signature": signature,- "alias": font.get("alias"),- "baseName": font.get("baseName"),- "glyphCount": font.get("glyphCount"),- "glyphCoverage": font.get("glyphCoverage"),- "samplePdf": pdf,- }- )- return fonts---def write_report(report_path: Path, fonts_by_signature: dict[str, dict]) -> None:- ordered = sorted(fonts_by_signature.values(), key=lambda entry: entry["signature"])- report = {- "generatedAt": dt.datetime.utcnow().isoformat(timespec="seconds") + "Z",- "totalSignatures": len(ordered),- "fonts": ordered,- }- report_path.parent.mkdir(parents=True, exist_ok=True)- with report_path.open("w", encoding="utf-8") as handle:- json.dump(report, handle, indent=2)---def main() -> None:- args = parse_args()- signatures_dir = Path(args.signatures_dir).resolve()- report_path = Path(args.report).resolve()- pdfs = discover_pdfs(args.input)-- known = collect_known_signatures(signatures_dir)- newly_added: list[tuple[str, str]] = []-- for pdf in pdfs:- signature_path = derive_signature_path(pdf, signatures_dir)- if signature_path.exists() and not args.force:- try:- payload = load_signature_file(signature_path)- except Exception as exc:- print(f"[WARN] Failed to parse cached signature {signature_path}: {exc}")- payload = None- else:- try:- run_signature_tool(args.gradle_cmd, pdf, signature_path, args.pretty, REPO_ROOT)- except Exception as exc:- print(f"[ERROR] Harvest failed for {pdf}: {exc}", file=sys.stderr)- continue- payload = load_signature_file(signature_path)-- if not payload:- continue-- for font in extract_fonts_from_payload(payload):- signature = font["signature"]- if signature in known:- continue- font["signatureJson"] = str(signature_path)- known[signature] = font- newly_added.append((signature, pdf.name))-- write_report(report_path, known)-- print(- f"Processed {len(pdfs)} PDFs. "- f"Captured {len(newly_added)} new Type3 font signatures "- f"(total unique signatures: {len(known)})."- )- if newly_added:- print("New signatures:")- for signature, sample in newly_added:- print(f" {signature} ({sample})")---if __name__ == "__main__":- main()diff --git a/scripts/index_type3_catalogue.py b/scripts/index_type3_catalogue.pydeleted file mode 100644index 69e7c33e47..0000000000--- a/scripts/index_type3_catalogue.py+++ /dev/null@@ -1,76 +0,0 @@-#!/usr/bin/env python3-"""Build a Type3 font catalogue from sample PDFs."""--import argparse-import json-import subprocess-from pathlib import Path---def run(cmd, cwd=None):- result = subprocess.run(cmd, cwd=cwd, capture_output=True, text=True)- if result.returncode != 0:- raise RuntimeError(f"Command {' '.join(cmd)} failed: {result.stderr}")- return result.stdout---def parse_pdffonts(output):- lines = output.splitlines()- entries = []- for line in lines[2:]:- if not line.strip():- continue- parts = line.split()- if "Type" not in parts:- continue- idx = parts.index("Type")- type_value = parts[idx + 1] if idx + 1 < len(parts) else ""- if not type_value.startswith("3"):- continue- font_name = parts[0]- encoding = parts[-2] if len(parts) >= 2 else ""- entries.append((font_name, encoding))- return entries---def main():- parser = argparse.ArgumentParser(description="Index Type3 fonts from sample PDFs")- parser.add_argument(- "--samples",- default="app/core/src/main/resources/type3/samples",- help="Directory containing sample PDFs",- )- parser.add_argument(- "--output",- default="app/core/src/main/resources/type3/catalogue.json",- help="Output JSON file",- )- args = parser.parse_args()-- samples_dir = Path(args.samples)- out_path = Path(args.output)- out_path.parent.mkdir(parents=True, exist_ok=True)-- catalogue = []- for pdf in sorted(samples_dir.glob("*.pdf")):- try:- output = run(["pdffonts", str(pdf)])- except Exception as exc:- print(f"Skipping {pdf.name}: {exc}")- continue- for font_name, encoding in parse_pdffonts(output):- catalogue.append(- {- "source": pdf.name,- "fontName": font_name,- "encoding": encoding,- }- )-- with out_path.open("w", encoding="utf-8") as handle:- json.dump(catalogue, handle, indent=2)- print(f"Wrote {len(catalogue)} entries to {out_path}")---if __name__ == "__main__":- main()diff --git a/scripts/summarize_type3_signatures.py b/scripts/summarize_type3_signatures.pydeleted file mode 100644index 6a90e07779..0000000000--- a/scripts/summarize_type3_signatures.py+++ /dev/null@@ -1,95 +0,0 @@-#!/usr/bin/env python3-"""-Summarize captured Type3 signature dumps as a Markdown inventory.--Usage:- scripts/summarize_type3_signatures.py \- --input docs/type3/signatures \- --output docs/type3/signature_inventory.md-"""--from __future__ import annotations--import argparse-import json-from collections import defaultdict-from pathlib import Path---def parse_args() -> argparse.Namespace:- parser = argparse.ArgumentParser(description="Summarize Type3 signature JSON dumps.")- parser.add_argument(- "--input",- default="docs/type3/signatures",- help="Directory containing signature JSON files (default: %(default)s)",- )- parser.add_argument(- "--output",- default="docs/type3/signature_inventory.md",- help="Markdown file to write (default: %(default)s)",- )- return parser.parse_args()---def load_signatures(directory: Path) -> dict[str, list[dict]]:- inventory: dict[str, list[dict]] = defaultdict(list)- for path in sorted(directory.glob("*.json")):- with path.open("r", encoding="utf-8") as handle:- payload = json.load(handle)- source_pdf = payload.get("pdf") or path.name- for font in payload.get("fonts", []):- alias = (font.get("alias") or font.get("baseName") or "unknown").lower()- entry = {- "source": source_pdf,- "file": path.name,- "alias": alias,- "baseName": font.get("baseName"),- "signature": font.get("signature"),- "glyphCount": font.get("glyphCount"),- "glyphCoverage": font.get("glyphCoverage"),- }- inventory[alias].append(entry)- return inventory---def write_markdown(inventory: dict[str, list[dict]], output: Path, input_dir: Path) -> None:- lines: list[str] = []- lines.append("# Type3 Signature Inventory")- lines.append("")- lines.append(- f"_Generated from `{input_dir}`. Run `scripts/summarize_type3_signatures.py` after capturing new samples._"- )- lines.append("")-- for alias in sorted(inventory.keys()):- entries = inventory[alias]- lines.append(f"## Alias: `{alias}`")- lines.append("")- lines.append("| Signature | Samples | Glyph Count | Coverage (first 10) |")- lines.append("| --- | --- | --- | --- |")- for entry in entries:- signature = entry.get("signature") or "—"- sample = Path(entry["source"]).name- glyph_count = entry.get("glyphCount") if entry.get("glyphCount") is not None else "—"- coverage = entry.get("glyphCoverage") or []- preview = ", ".join(str(code) for code in coverage[:10])- lines.append(f"| `{signature}` | `{sample}` | {glyph_count} | {preview} |")- lines.append("")-- output.parent.mkdir(parents=True, exist_ok=True)- output.write_text("\n".join(lines), encoding="utf-8")---def main() -> None:- args = parse_args()- input_dir = Path(args.input)- if not input_dir.exists():- raise SystemExit(f"Input directory not found: {input_dir}")- inventory = load_signatures(input_dir)- output_path = Path(args.output)- write_markdown(inventory, output_path, input_dir)- print(f"Wrote inventory for {len(inventory)} aliases to {output_path}")---if __name__ == "__main__":- main()diff --git a/scripts/type3_to_cff.py b/scripts/type3_to_cff.pydeleted file mode 100644index 48fe89c70c..0000000000--- a/scripts/type3_to_cff.py+++ /dev/null@@ -1,490 +0,0 @@-#!/usr/bin/env python3-"""-Convert Stirling PDF Type3 glyph JSON into synthesised fonts using fontTools.--The input JSON is expected to contain:- - fontId, pageNumber (optional metadata)- - fontMatrix: 3x3 matrix describing the Type3 glyph transform- - glyphs: array of glyph records with keys:- name, code, advanceWidth, bbox, unicode, outline (list of commands)--The script produces an OpenType CFF font and, when requested, a companion-TrueType font for web-preview usage. Only the fontTools package is required,-avoiding heavyweight build dependencies such as fontmake/ufoLib2.-"""--from __future__ import annotations--import argparse-import json-import math-import sys-from collections.abc import Iterable, Sequence-from dataclasses import dataclass-from pathlib import Path--from fontTools.fontBuilder import FontBuilder-from fontTools.misc.fixedTools import otRound-from fontTools.pens.cu2quPen import Cu2QuPen-from fontTools.pens.t2CharStringPen import T2CharStringPen-from fontTools.pens.ttGlyphPen import TTGlyphPen--Command = dict[str, object]-Matrix = tuple[float, float, float, float, float, float]---@dataclass-class GlyphSource:- name: str- width: float- unicode: int | None- char_code: int | None- outline: Sequence[Command]---@dataclass-class GlyphBuildResult:- name: str- width: int- charstring: object- ttf_glyph: object | None- unicode: int | None- char_code: int | None- bounds: tuple[float, float, float, float] | None---def parse_args() -> argparse.Namespace:- parser = argparse.ArgumentParser(description="Synthesize fonts from Type3 glyph JSON.")- parser.add_argument("--input", required=True, help="Path to glyph JSON emitted by the backend")- parser.add_argument("--otf-output", required=True, help="Destination path for the CFF/OTF font")- parser.add_argument("--ttf-output", help="Optional destination path for a TrueType font")- parser.add_argument("--family-name", default="Type3 Synth", help="Family name for the output")- parser.add_argument("--style-name", default="Regular", help="Style name for the output")- parser.add_argument("--units-per-em", type=int, default=1000, help="Units per EM value")- parser.add_argument(- "--cu2qu-error",- type=float,- default=1.0,- help="Max error for cubic→quadratic conversion",- )- return parser.parse_args()---def load_json(path: Path) -> dict[str, object]:- try:- with path.open("r", encoding="utf-8") as handle:- return json.load(handle)- except Exception as exc: # pragma: no cover - fatal configuration error- print(f"ERROR: Failed to load glyph JSON '{path}': {exc}", file=sys.stderr)- sys.exit(2)---def parse_font_matrix(rows: Iterable[Iterable[float]] | None) -> Matrix:- """- Retrieve the raw 2×3 FontMatrix entries for diagnostics. Type3 glyph- outlines in our extractor are emitted in their native coordinate system, so- the returned matrix is currently informational only.- """- if not rows:- return (1.0, 0.0, 0.0, 1.0, 0.0, 0.0)- values: list[list[float]] = []- for row in rows:- try:- values.append([float(col) for col in row])- except (TypeError, ValueError):- return (1.0, 0.0, 0.0, 1.0, 0.0, 0.0)- if len(values) < 3 or len(values[0]) < 2 or len(values[1]) < 2:- return (1.0, 0.0, 0.0, 1.0, 0.0, 0.0)- return (- float(values[0][0]),- float(values[0][1]),- float(values[1][0]),- float(values[1][1]),- float(values[2][0]),- float(values[2][1]),- )---def resolve_width(raw_width: float, default: int) -> int:- try:- value = float(raw_width)- except (TypeError, ValueError):- return default- if not math.isfinite(value) or value <= 0:- return default- width = otRound(value)- return width if width > 0 else default---def quadratic_to_cubic(- current: tuple[float, float],- ctrl: tuple[float, float],- end: tuple[float, float],-) -> tuple[tuple[float, float], tuple[float, float], tuple[float, float]]:- """- Convert a quadratic Bézier segment to cubic control points.- """- c1 = (- current[0] + (2.0 / 3.0) * (ctrl[0] - current[0]),- current[1] + (2.0 / 3.0) * (ctrl[1] - current[1]),- )- c2 = (- end[0] + (2.0 / 3.0) * (ctrl[0] - end[0]),- end[1] + (2.0 / 3.0) * (ctrl[1] - end[1]),- )- return c1, c2, end---def iterate_glyphs(data: dict[str, object]) -> list[GlyphSource]:- glyph_records = data.get("glyphs") or []- sources: list[GlyphSource] = []- for index, record in enumerate(glyph_records, start=1):- if not isinstance(record, dict):- continue- name = record.get("name")- if not isinstance(name, str) or not name:- name = f"g{index}"- width = record.get("advanceWidth")- if not isinstance(width, (int, float)) or math.isnan(width):- width = 1000.0- unicode_value = record.get("unicode")- if not isinstance(unicode_value, int) or unicode_value <= 0:- unicode_value = None- char_code_value = record.get("charCode")- if not isinstance(char_code_value, int):- char_code_value = record.get("code")- if not isinstance(char_code_value, int):- char_code_value = record.get("charCodeRaw")- if not isinstance(char_code_value, int) or not (0 <= char_code_value <= 0x10FFFF):- char_code_value = None- outline = record.get("outline")- if not isinstance(outline, list):- outline = []- sources.append(- GlyphSource(- name=name,- width=float(width),- unicode=unicode_value,- char_code=char_code_value,- outline=outline,- )- )- return sources---def build_cff_charstring(- glyph: GlyphSource,- width: int,-) -> tuple[object, tuple[float, float, float, float] | None]:- pen = T2CharStringPen(width=width, glyphSet=None)- bounds = [math.inf, math.inf, -math.inf, -math.inf]-- def update_bounds(point: tuple[float, float]) -> None:- x, y = point- bounds[0] = min(bounds[0], x)- bounds[1] = min(bounds[1], y)- bounds[2] = max(bounds[2], x)- bounds[3] = max(bounds[3], y)-- current: tuple[float, float] | None = None- start_point: tuple[float, float] | None = None- open_path = False-- for command in glyph.outline:- if not isinstance(command, dict):- continue- op = command.get("cmd")- if op == "M":- if open_path:- pen.endPath()- open_path = False- point = (float(command.get("x", 0.0)), float(command.get("y", 0.0)))- pen.moveTo(point)- update_bounds(point)- current = point- start_point = point- open_path = True- elif op == "L" and current is not None:- point = (- float(command.get("x", current[0])),- float(command.get("y", current[1])),- )- pen.lineTo(point)- update_bounds(point)- current = point- elif op == "C" and current is not None:- ctrl1 = (- float(command.get("x1", current[0])),- float(command.get("y1", current[1])),- )- ctrl2 = (- float(command.get("x2", current[0])),- float(command.get("y2", current[1])),- )- end = (- float(command.get("x", current[0])),- float(command.get("y", current[1])),- )- pen.curveTo(ctrl1, ctrl2, end)- update_bounds(ctrl1)- update_bounds(ctrl2)- update_bounds(end)- current = end- elif op == "Q" and current is not None:- ctrl = (- float(command.get("x1", current[0])),- float(command.get("y1", current[1])),- )- end = (- float(command.get("x", current[0])),- float(command.get("y", current[1])),- )- c1, c2, end_point = quadratic_to_cubic(current, ctrl, end)- pen.curveTo(c1, c2, end_point)- update_bounds(ctrl)- update_bounds(end_point)- current = end_point- elif op == "Z" and open_path:- pen.closePath()- open_path = False- if start_point is not None:- current = start_point- # Ignore unsupported commands silently.-- if open_path:- pen.endPath()-- charstring = pen.getCharString()- bbox = None- if bounds[0] <= bounds[2] and bounds[1] <= bounds[3]:- bbox = (bounds[0], bounds[1], bounds[2], bounds[3])- return charstring, bbox---def build_ttf_glyph(glyph: GlyphSource, max_error: float) -> object | None:- pen = TTGlyphPen(glyphSet=None)- draw_pen = Cu2QuPen(pen, max_error, reverse_direction=False)-- current_exists = False-- for command in glyph.outline:- if not isinstance(command, dict):- continue- op = command.get("cmd")- if op == "M":- x = float(command.get("x", 0.0))- y = float(command.get("y", 0.0))- draw_pen.moveTo((x, y))- current_exists = True- elif op == "L" and current_exists:- x = float(command.get("x", 0.0))- y = float(command.get("y", 0.0))- draw_pen.lineTo((x, y))- elif op == "C" and current_exists:- ctrl1 = (float(command.get("x1", 0.0)), float(command.get("y1", 0.0)))- ctrl2 = (float(command.get("x2", 0.0)), float(command.get("y2", 0.0)))- end = (float(command.get("x", 0.0)), float(command.get("y", 0.0)))- draw_pen.curveTo(ctrl1, ctrl2, end)- elif op == "Q" and current_exists:- ctrl = (float(command.get("x1", 0.0)), float(command.get("y1", 0.0)))- end = (float(command.get("x", 0.0)), float(command.get("y", 0.0)))- draw_pen.qCurveTo(ctrl, end)- elif op == "Z" and current_exists:- draw_pen.closePath()- current_exists = False-- if current_exists:- draw_pen.endPath()-- try:- glyph_obj = pen.glyph()- except Exception:- return None- return glyph_obj---def synthesise_fonts(- data: dict[str, object],- otf_output: Path,- ttf_output: Path | None,- family_name: str,- style_name: str,- units_per_em: int,- cu2qu_error: float,-) -> None:- _font_matrix = parse_font_matrix(data.get("fontMatrix"))- glyphs = iterate_glyphs(data)-- results: list[GlyphBuildResult] = []- global_y_min = math.inf- global_y_max = -math.inf-- default_width = max(1, units_per_em // 2)-- for glyph in glyphs:- width = resolve_width(glyph.width, default_width)- charstring, bounds = build_cff_charstring(glyph, width)- ttf_glyph = None- if ttf_output is not None:- ttf_glyph = build_ttf_glyph(glyph, cu2qu_error)- if ttf_glyph is not None:- ttf_glyph.width = width- if bounds is not None:- global_y_min = min(global_y_min, bounds[1])- global_y_max = max(global_y_max, bounds[3])- results.append(- GlyphBuildResult(- name=glyph.name,- width=width,- charstring=charstring,- ttf_glyph=ttf_glyph,- unicode=glyph.unicode,- char_code=glyph.char_code,- bounds=bounds,- )- )-- if not results:- raise RuntimeError("No glyphs provided in input JSON")-- ascent = global_y_max if math.isfinite(global_y_max) else units_per_em * 0.8- descent = global_y_min if math.isfinite(global_y_min) else -units_per_em * 0.2- ascent = otRound(ascent)- descent = otRound(descent)- if ascent <= 0:- ascent = otRound(units_per_em * 0.8)- if descent >= 0:- descent = -otRound(units_per_em * 0.2)-- glyph_order = [".notdef"] + [result.name for result in results]- horizontal_metrics = {result.name: (result.width, 0) for result in results}- horizontal_metrics[".notdef"] = (default_width, 0)-- cmap: dict[int, str] = {}- next_private = 0xF000- for result in results:- code_point = result.unicode- if code_point is None:- raw_code = result.char_code- if raw_code is not None:- code_point = raw_code- else:- code_point = next_private- next_private += 1- cmap[code_point] = result.name-- notdef_pen = T2CharStringPen(width=default_width, glyphSet=None)- notdef_pen.endPath()- charstrings = {result.name: result.charstring for result in results}- charstrings[".notdef"] = notdef_pen.getCharString()-- name_table_entries = {- "familyName": family_name,- "styleName": style_name,- "psName": f"{family_name.replace(' ', '')}-{style_name}",- "fullName": f"{family_name} {style_name}",- }-- # Build OTF (CFF) font.- fb = FontBuilder(units_per_em, isTTF=False)- fb.setupGlyphOrder(glyph_order)- fb.setupCharacterMap(cmap)- fb.setupHorizontalMetrics(horizontal_metrics)- fb.setupHorizontalHeader(ascent=ascent, descent=descent)- fb.setupOS2(- sTypoAscender=ascent,- sTypoDescender=descent,- usWinAscent=max(ascent, 0),- usWinDescent=abs(min(descent, 0)),- sxHeight=otRound(units_per_em * 0.5),- sCapHeight=otRound(units_per_em * 0.7),- )- fb.setupNameTable(name_table_entries)- fb.setupPost()- fb.setupCFF(- name_table_entries["psName"],- {- "FullName": name_table_entries["fullName"],- "FamilyName": name_table_entries["familyName"],- "Weight": style_name,- },- charstrings,- {"BlueValues": []},- )- fb.font.save(str(otf_output))-- if ttf_output is None:- return-- glyph_objects: dict[str, object] = {}- empty_pen = TTGlyphPen(None)- empty_pen.moveTo((0, 0))- empty_pen.lineTo((0, 0))- empty_pen.closePath()- empty_glyph = empty_pen.glyph()- empty_glyph.width = default_width- glyph_objects[".notdef"] = empty_glyph- for result in results:- glyph_obj = result.ttf_glyph- if glyph_obj is None:- temp_pen = TTGlyphPen(None)- temp_pen.moveTo((0, 0))- temp_pen.lineTo((0, 0))- temp_pen.closePath()- glyph_obj = temp_pen.glyph()- glyph_obj.width = result.width- glyph_objects[result.name] = glyph_obj-- ttf_fb = FontBuilder(units_per_em, isTTF=True)- ttf_fb.setupGlyphOrder(glyph_order)- ttf_fb.setupCharacterMap(cmap)- ttf_fb.setupHorizontalMetrics(horizontal_metrics)- ttf_fb.setupHorizontalHeader(ascent=ascent, descent=descent)- ttf_fb.setupOS2(- sTypoAscender=ascent,- sTypoDescender=descent,- usWinAscent=max(ascent, 0),- usWinDescent=abs(min(descent, 0)),- sxHeight=otRound(units_per_em * 0.5),- sCapHeight=otRound(units_per_em * 0.7),- )- ttf_fb.setupNameTable(name_table_entries)- ttf_fb.setupPost()- ttf_fb.setupGlyf(glyph_objects)- ttf_fb.setupDummyDSIG()- ttf_fb.font.save(str(ttf_output))---def main() -> None:- args = parse_args()- input_path = Path(args.input).resolve()- otf_output = Path(args.otf_output).resolve()- ttf_output = Path(args.ttf_output).resolve() if args.ttf_output else None-- data = load_json(input_path)- try:- synthesise_fonts(- data=data,- otf_output=otf_output,- ttf_output=ttf_output,- family_name=args.family_name,- style_name=args.style_name,- units_per_em=args.units_per_em,- cu2qu_error=args.cu2qu_error,- )- except Exception as exc:- print(f"ERROR: Failed to generate fonts: {exc}", file=sys.stderr)- if otf_output.exists():- otf_output.unlink()- if ttf_output and ttf_output.exists():- ttf_output.unlink()- sys.exit(1)-- message = f"Generated font at {otf_output}"- if ttf_output:- message += f" and {ttf_output}"- print(message, file=sys.stderr)---if __name__ == "__main__":- main()diff --git a/scripts/update_type3_library.py b/scripts/update_type3_library.pydeleted file mode 100644index a0d5515573..0000000000--- a/scripts/update_type3_library.py+++ /dev/null@@ -1,243 +0,0 @@-#!/usr/bin/env python3-"""-Synchronize Type3 library index entries with captured signature dumps.--The script scans docs/type3/signatures/*.json (or a custom --signatures-dir),-matches each font by alias/signature to app/core/src/main/resources/type3/library/index.json,-and updates the entry's signatures / glyphCoverage / aliases / source fields.--Usage:- scripts/update_type3_library.py --apply--Run without --apply to see a dry-run summary.-"""--from __future__ import annotations--import argparse-import json-import sys-from collections.abc import Iterable-from pathlib import Path--REPO_ROOT = Path(__file__).resolve().parents[1]-DEFAULT_SIGNATURES = REPO_ROOT / "docs" / "type3" / "signatures"-DEFAULT_INDEX = REPO_ROOT / "app" / "core" / "src" / "main" / "resources" / "type3" / "library" / "index.json"---def normalize_alias(value: str | None) -> str | None:- if not value:- return None- trimmed = value.strip()- plus = trimmed.find("+")- if plus >= 0 and plus < len(trimmed) - 1:- trimmed = trimmed[plus + 1 :]- lowered = trimmed.lower()- return lowered if lowered else None---def load_json(path: Path):- with path.open("r", encoding="utf-8") as handle:- return json.load(handle)---def dump_json(path: Path, data) -> None:- path.parent.mkdir(parents=True, exist_ok=True)- with path.open("w", encoding="utf-8") as handle:- json.dump(data, handle, indent=2)- handle.write("\n")---def iter_signature_fonts(signature_file: Path):- payload = load_json(signature_file)- pdf_source = payload.get("pdf")- for font in payload.get("fonts", []):- alias = font.get("alias") or font.get("baseName")- normalized = normalize_alias(alias) or normalize_alias(font.get("baseName"))- yield {- "alias_raw": alias,- "alias": normalized,- "baseName": font.get("baseName"),- "signature": font.get("signature"),- "glyphCoverage": font.get("glyphCoverage") or [],- "pdf": pdf_source,- "file": signature_file,- }---def make_alias_index(entries: list[dict]) -> tuple[dict[str, dict], dict[str, dict]]:- alias_index: dict[str, dict] = {}- signature_index: dict[str, dict] = {}- for entry in entries:- for alias in entry.get("aliases", []) or []:- normalized = normalize_alias(alias)- if normalized:- alias_index.setdefault(normalized, entry)- base_name_alias = normalize_alias(entry.get("label"))- if base_name_alias:- alias_index.setdefault(base_name_alias, entry)- for signature in entry.get("signatures", []) or []:- signature_index.setdefault(signature.lower(), entry)- return alias_index, signature_index---def ensure_list(container: dict, key: str) -> list:- value = container.get(key)- if isinstance(value, list):- return value- value = []- container[key] = value- return value---def merge_sorted_unique(values: Iterable[int]) -> list[int]:- return sorted({int(v) for v in values if isinstance(v, int)})---def normalize_source_path(pdf_path: str | None) -> str | None:- if not pdf_path:- return None- try:- source = Path(pdf_path)- rel = source.relative_to(REPO_ROOT)- except Exception:- rel = Path(pdf_path)- return str(rel).replace("\\", "/")---def update_library(- signatures_dir: Path, index_path: Path, apply_changes: bool-) -> tuple[int, int, list[tuple[str, Path]]]:- entries = load_json(index_path)- alias_index, signature_index = make_alias_index(entries)-- modifications = 0- updated_entries = set()- unmatched: list[tuple[str, Path]] = []-- signature_files = sorted(signatures_dir.glob("*.json"))- if not signature_files:- print(f"No signature JSON files found under {signatures_dir}", file=sys.stderr)- return 0, 0, unmatched-- for sig_file in signature_files:- for font in iter_signature_fonts(sig_file):- signature = font["signature"]- norm_signature = signature.lower() if signature else None- alias = font["alias"]-- entry = None- if norm_signature and norm_signature in signature_index:- entry = signature_index[norm_signature]- elif alias and alias in alias_index:- entry = alias_index[alias]-- if entry is None:- unmatched.append(- (- font.get("baseName") or font.get("alias_raw") or "unknown",- sig_file,- )- )- continue-- entry_modified = False-- # Signatures- if signature:- signature_list = ensure_list(entry, "signatures")- if signature not in signature_list:- signature_list.append(signature)- entry_modified = True- signature_index[signature.lower()] = entry-- # Aliases- alias_raw = font.get("alias_raw")- if alias_raw:- aliases = ensure_list(entry, "aliases")- if alias_raw not in aliases:- aliases.append(alias_raw)- entry_modified = True- normalized = normalize_alias(alias_raw)- if normalized:- alias_index.setdefault(normalized, entry)-- # Glyph coverage- coverage = font.get("glyphCoverage") or []- if coverage:- existing = set(entry.get("glyphCoverage", []))- merged = merge_sorted_unique(list(existing) + coverage)- if merged != entry.get("glyphCoverage"):- entry["glyphCoverage"] = merged- entry_modified = True-- # Source PDF- pdf_source = normalize_source_path(font.get("pdf"))- if pdf_source and not entry.get("source"):- entry["source"] = pdf_source- entry_modified = True-- if entry_modified:- modifications += 1- updated_entries.add(entry.get("id", "<unknown>"))-- if apply_changes and modifications > 0:- dump_json(index_path, entries)-- return modifications, len(updated_entries), unmatched---def parse_args() -> argparse.Namespace:- parser = argparse.ArgumentParser(description="Update Type3 library index using signature dumps.")- parser.add_argument(- "--signatures-dir",- type=Path,- default=DEFAULT_SIGNATURES,- help=f"Directory containing signature JSON files (default: {DEFAULT_SIGNATURES})",- )- parser.add_argument(- "--index",- type=Path,- default=DEFAULT_INDEX,- help=f"Path to type3/library/index.json (default: {DEFAULT_INDEX})",- )- parser.add_argument(- "--apply",- action="store_true",- help="Write changes back to the index file. Without this flag the script runs in dry-run mode.",- )- return parser.parse_args()---def main() -> None:- args = parse_args()- signatures_dir = args.signatures_dir if args.signatures_dir.is_absolute() else (REPO_ROOT / args.signatures_dir)- index_path = args.index if args.index.is_absolute() else (REPO_ROOT / args.index)-- if not signatures_dir.exists():- print(f"Signature directory not found: {signatures_dir}", file=sys.stderr)- sys.exit(2)- if not index_path.exists():- print(f"Index file not found: {index_path}", file=sys.stderr)- sys.exit(2)-- modifications, updated_entries, unmatched = update_library(signatures_dir, index_path, apply_changes=args.apply)-- mode = "APPLIED" if args.apply else "DRY-RUN"- print(- f"[{mode}] Processed signatures under {signatures_dir}. "- f"Updated entries: {updated_entries}, individual modifications: {modifications}."- )-- if unmatched:- print("\nUnmatched fonts (no library entry yet):")- for alias, sig_file in unmatched:- print(f" - {alias} (from {sig_file})")- print("Add these fonts to index.json with the proper payload before rerunning.")-- if modifications == 0:- print("No changes detected; index.json already matches captured signatures.")---if __name__ == "__main__":- main()diff --git a/testing/allEndpointsRemovedSettings.yml b/testing/allEndpointsRemovedSettings.ymlindex 062e8d9a52..c0b418d85d 100644--- a/testing/allEndpointsRemovedSettings.yml+++ b/testing/allEndpointsRemovedSettings.yml@@ -328,21 +328,3 @@ aiEngine:enabled: false # Set to 'true' to enable the AI engine integrationurl: http://localhost:5001 # URL of the Python AI enginetimeoutSeconds: 120 # Timeout in seconds for AI engine requests--pdfEditor:- fallback-font: classpath:/static/fonts/NotoSans-Regular.ttf # Override to point at a custom fallback font- cache:- max-bytes: -1 # Max in-memory cache size in bytes; -1 disables byte cap- max-percent: 20 # Max in-memory cache as % of JVM max; used when max-bytes <= 0- font-normalization:- enabled: false # IMPORTANT: Disable to preserve ToUnicode CMaps for correct font rendering. Ghostscript strips Unicode mappings from CID fonts.- cff-converter:- enabled: true # Wrap CFF/Type1CFF fonts as OpenType-CFF for browser compatibility- method: python # Converter method: 'python' (fontTools, recommended - wraps as OTF), 'fontforge' (legacy - converts to TTF, may hang on CID fonts)- python-command: /opt/venv/bin/python3 # Python interpreter path- python-script: /scripts/convert_cff_to_ttf.py # Path to font wrapping script- fontforge-command: fontforge # Override if FontForge is installed under a different name/path- type3:- library:- enabled: true # Match common Type3 fonts against the built-in library of converted programs- index: classpath:/type3/library/index.json # Override to point at a custom index.json (supports http:, file:, classpath:)diff --git a/testing/cucumber/features/convert_nightly.feature b/testing/cucumber/features/convert_nightly.featureindex eb30bdbbac..f45b82f0f5 100644--- a/testing/cucumber/features/convert_nightly.feature+++ b/testing/cucumber/features/convert_nightly.feature@@ -22,16 +22,6 @@ Feature: Heavy conversion endpointsThen the response status code should be 204- @text-editor @positive- Scenario: text-editor metadata describes the document for the editor- Given I use an example file at "exampleFiles/tables.pdf" as parameter "fileInput"- When I send the API request to the endpoint "/api/v1/convert/pdf/text-editor/metadata"- And this operation is run 3 times in parallel- Then the response status code should be 200- And the response content type should be "application/json"- And the response JSON field "fonts" should not be empty--@vector @negativeScenario: vector conversion rejects an input format Ghostscript cannot readGiven I generate an SVG file as "fileInput"diff --git a/testing/cucumber/features/external.feature b/testing/cucumber/features/external.featureindex 3257657068..09f7816230 100644--- a/testing/cucumber/features/external.feature+++ b/testing/cucumber/features/external.feature@@ -251,28 +251,3 @@ Feature: API ValidationAnd the response file should have size greater than 200And the response file should have extension ".zip"And the response ZIP should contain 3 files--- @positive @pdftojson- Scenario: Convert PDF to JSON (text editor format)- Given I generate a PDF file as "fileInput"- And the pdf contains 3 pages with random text- When I send the API request to the endpoint "/api/v1/convert/pdf/text-editor"- Then the response status code should be 200- And the response content type should be "application/json"- And the response file should have size greater than 100- And the response file should have extension ".json"--- @positive @pdftojson- Scenario: Convert PDF to JSON in lightweight mode- Given I generate a PDF file as "fileInput"- And the pdf contains 2 pages with random text- And the request data includes- | parameter | value |- | lightweight | true |- When I send the API request to the endpoint "/api/v1/convert/pdf/text-editor"- Then the response status code should be 200- And the response content type should be "application/json"- And the response file should have size greater than 50- And the response file should have extension ".json"diff --git a/testing/cucumber/features/general_new.feature b/testing/cucumber/features/general_new.featureindex 6d0b31c4c6..782cede4f5 100644--- a/testing/cucumber/features/general_new.feature+++ b/testing/cucumber/features/general_new.feature@@ -313,29 +313,6 @@ Feature: General PDF Operations API ValidationAnd the response PDF should contain 3 pages- @edit-text @positive- Scenario: edit-text applies a find and replace across the document- Given I generate a PDF file as "fileInput"- And the pdf contains 3 pages- And the pdf pages all contain the text "Hello world"- And the request data includes- | parameter | value |- | edits | [{"find":"Hello","replace":"Goodbye"}] |- When I send the API request to the endpoint "/api/v1/general/edit-text"- And this operation is run 5 times in parallel- Then the response status code should be 200- And the response content type should be "application/pdf"--- @edit-text @negative- Scenario: edit-text without any operations returns 400- Given I generate a PDF file as "fileInput"- And the pdf contains 2 pages- When I send the API request to the endpoint "/api/v1/general/edit-text"- Then the response status code should be 400- And the response JSON error should contain "find/replace"--@split-for-poster-print @positiveScenario: split-for-poster-print tiles each page into an archiveGiven I generate a PDF file as "fileInput"