diff --git a/apps/app/src/app/routes/EditorRoute.tsx b/apps/app/src/app/routes/EditorRoute.tsx index 525f99a2..c21b07e5 100644 --- a/apps/app/src/app/routes/EditorRoute.tsx +++ b/apps/app/src/app/routes/EditorRoute.tsx @@ -34,8 +34,10 @@ import { pickLabel } from '@/i18n/pickLocaleLabel' import type { ViewStates } from '@/anatomy/drawing' import { exportReportToPdf } from '@/pdf/export' import { downloadBlob } from '@/lib/download' -import type { ExportWarning } from '@faunosteo/pdf' -import type { RebaseOutcome } from '@faunosteo/core-wasm/types' +import type { + ExportWarning, + RebaseOutcome, +} from '@faunosteo/core-wasm/types' import { useT } from '@/i18n/useT' import { DEFAULT_SPECIES_ID } from './NewReportRoute' import { coreFailureMessage } from '@/core/failure' @@ -95,6 +97,8 @@ export default function EditorRoute() { const heldAttempt = useRef(null) const [disclaimer, setDisclaimer] = useState(null) const [exporting, setExporting] = useState(false) + // Leaving the editor mid-export cancels it: the core's session is freed, no file results. + const exportAbort = useRef(null) const [editDraft, setEditDraft] = useState(null) // One alert per restore, even if the effect runs again before the re-render. const rebaseAlerted = useRef(false) @@ -103,6 +107,10 @@ export default function EditorRoute() { window.scrollTo({ top: 0, left: 0, behavior: 'auto' }) }, []) + useEffect(() => { + return () => exportAbort.current?.abort() + }, []) + // No report in memory: restore the per-tab draft once the sheet is known. // A draft rebased on another sheet is announced with its unresolved count, // an unreadable one is set aside. While the core cannot run, nothing is @@ -233,14 +241,14 @@ export default function EditorRoute() { async function onExport(index: SheetIndex) { if (!report) return setExporting(true) + const abort = new AbortController() + exportAbort.current = abort try { const { pdf, warnings } = await exportReportToPdf(report, index, { locale, + signal: abort.signal, }) - downloadBlob( - new Blob([pdf as BlobPart], { type: 'application/pdf' }), - `bilan-${report.animal.name}-${report.date}.pdf`, - ) + downloadBlob(pdf, `bilan-${report.animal.name}-${report.date}.pdf`) const missing = missingItemsOf(warnings) if (missing.length) { window.alert( @@ -248,9 +256,12 @@ export default function EditorRoute() { ) } } catch (err) { + // A cancelled export (the editor left) ends silently. + if (abort.signal.aborted) return console.error('PDF export failed', err) window.alert(coreFailureMessage(t, 'editor.export_failed')) } finally { + if (exportAbort.current === abort) exportAbort.current = null setExporting(false) } } diff --git a/apps/app/src/pdf/browserRasterizer.ts b/apps/app/src/pdf/browserRasterizer.ts index 9913621e..0ad166f6 100644 --- a/apps/app/src/pdf/browserRasterizer.ts +++ b/apps/app/src/pdf/browserRasterizer.ts @@ -1,12 +1,19 @@ -import type { Rasterizer } from '@faunosteo/pdf' - /** - * The browser side of the engine's rasterizer adapter: the engine has fixed - * the pixel size, this module only stamps it on the SVG root and lets the - * browser draw the SVG through an Image / canvas pair, which renders exactly - * what the practitioner sees in the inline anatomy canvas. + * The browser side of the core's raster requests (R4.6; the engine's adapter + * before): the core has fixed the pixel size, this module only stamps it on + * the SVG root and lets the browser draw the SVG through an Image / canvas + * pair, which renders exactly what the practitioner sees in the inline + * anatomy canvas. */ +export interface RasterSize { + widthPx: number + heightPx: number +} + +/** Draws `svg` at `size` as a PNG. */ +export type Rasterizer = (svg: string, size: RasterSize) => Promise + const SVG_NS = 'http://www.w3.org/2000/svg' const PNG_SIGNATURE = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a] diff --git a/apps/app/src/pdf/export.ts b/apps/app/src/pdf/export.ts index f33024d6..83858013 100644 --- a/apps/app/src/pdf/export.ts +++ b/apps/app/src/pdf/export.ts @@ -1,33 +1,97 @@ -import type { Report } from '@faunosteo/core-wasm/types' import { - defaultPdfLabels, - exportReportArchive, - type ExportInput, - type ExportWarning, -} from '@faunosteo/pdf' + openExportSession, + type CoreExportSession, + type CoreOutcome, +} from '@faunosteo/core-wasm' +import type { + ExportInput, + ExportWarning, + RasterRequest, + Report, +} from '@faunosteo/core-wasm/types' +import { coreRuntime } from '@/core/runtime' import type { Locale } from '@/i18n/types' import type { SheetIndex } from '@/services/sheetIndex' import { loadBranding } from './branding' import { browserRasterizer } from './browserRasterizer' +import { defaultPdfLabels } from './labels' export interface PdfExportOptions { locale: Locale + /** Aborting frees the session (the editor leaving mid-export); no file results. */ + signal?: AbortSignal } export interface PdfExportResult { - pdf: Uint8Array - /** Non-fatal engine warnings: a logo or a view that failed to embed. */ + /** The file, from the parts the core handed out (never concatenated in memory). */ + pdf: Blob + /** Non-fatal warnings: a logo or a view that failed to embed. */ warnings: ExportWarning[] } +/** A core call the export could not go past: its closed kind, for the DEV console. */ +export class ExportFailure extends Error { + constructor( + public readonly kind: string, + detail?: string, + ) { + super(detail ? `${kind}: ${detail}` : kind) + this.name = 'ExportFailure' + } +} + +function unwrap(outcome: CoreOutcome): T { + if (!outcome.ok) throw new ExportFailure(outcome.kind, outcome.detail) + return outcome.value +} + +function assertNotAborted(signal: AbortSignal | undefined): void { + if (signal?.aborted) throw new DOMException('export aborted', 'AbortError') +} + /** - * Exports the report as an archive PDF through the engine: the core builds - * the snapshot of the loaded sheet the pages are drawn from and the - * attachment carries (R2), the branding comes from the bundled logos, the - * browser rasterises the views, the TypeScript engine writes the file (the - * writer moves to the core at R4). The core's report and snapshot are the - * same JSON contracts the engine's Zod types describe. Warnings are logged - * and returned for the caller to surface. + * One batch of the session's requests rasterised under `Promise.all`, as the engine did: + * a raster that fails is reported as it rejects (the warning order the engine recorded), + * the others are given in request order once the batch has settled (the embedding order, + * so the file's bytes do not depend on which raster finished first). The PNG bytes are + * copied into the core and dropped as each `addRaster` returns. + */ +async function answerBatch( + session: CoreExportSession, + requests: RasterRequest[], + signal: AbortSignal | undefined, +): Promise { + const settled = await Promise.all( + requests.map(async (request) => { + try { + const png = await browserRasterizer(request.svg, { + widthPx: request.widthPx, + heightPx: request.heightPx, + }) + return { key: request.key, png } + } catch { + assertNotAborted(signal) + unwrap(session.rasterFailed(request.key)) + return { key: request.key, png: null } + } + }), + ) + for (const { key, png } of settled) { + if (!png) continue + assertNotAborted(signal) + unwrap(session.addRaster(key, png)) + } +} + +/** + * Exports the report as an archive PDF through the core's session (R4.6, plan §B.1.6): + * the core builds the snapshot of the loaded sheet the pages are drawn from and the + * attachment carries, the branding comes from the bundled logos, the labels from + * `labels.ts`, the export time from the clock; the core then asks for each raster it + * needs (the SVG logos, then the views of each observation), the browser draws it, and + * the core writes the file as the rasters arrive. The session is freed whatever happens. + * A refused input or a core failure throws (`ExportFailure`, or the `AbortError` of a + * cancelled export); warnings are returned for the caller to surface. */ export async function exportReportToPdf( report: Report, @@ -35,18 +99,34 @@ export async function exportReportToPdf( opts: PdfExportOptions, ): Promise { const snapshot = index.ops.snapshot(report) - if (!snapshot.ok) throw new Error(`snapshot failed: ${snapshot.kind}`) - const result = await exportReportArchive({ - report: report as ExportInput['report'], - sheet: snapshot.value as ExportInput['sheet'], + if (!snapshot.ok) throw new ExportFailure(snapshot.kind, snapshot.detail) + const input: ExportInput = { + report, + sheetSnapshot: snapshot.value, branding: await loadBranding(), labels: defaultPdfLabels, locale: opts.locale, - rasterizer: browserRasterizer, - exportedAt: new Date(), - }) - for (const warning of result.warnings) { - console.warn('PDF export warning', warning) + exportedAt: new Date().toISOString(), + } + assertNotAborted(opts.signal) + const session = unwrap(openExportSession(coreRuntime(), JSON.stringify(input))) + try { + for (;;) { + assertNotAborted(opts.signal) + const step = unwrap(session.next()) + if (step.step === 'done') break + await answerBatch(session, step.requests, opts.signal) + } + const parts = unwrap(session.finish()) + const warnings = unwrap(session.warnings()) + for (const warning of warnings) { + console.warn('PDF export warning', warning) + } + return { + pdf: new Blob(parts as BlobPart[], { type: 'application/pdf' }), + warnings, + } + } finally { + session.free() } - return { pdf: result.pdf, warnings: result.warnings } } diff --git a/apps/app/src/pdf/labels.ts b/apps/app/src/pdf/labels.ts new file mode 100644 index 00000000..dfd2e8be --- /dev/null +++ b/apps/app/src/pdf/labels.ts @@ -0,0 +1,67 @@ +import type { PdfLabelSet, PdfLabels } from '@faunosteo/core-wasm/types' + +/** + * The static wording of the PDF (section headings, metadata), frozen into every archive + * the export writes (R4.6: moved verbatim from `packages/pdf/src/i18n`, same key order, + * which is the order every shipped attachment carries; the app dictionaries hold no + * `pdf.*` key). A wording change here changes new exports only: an old archive keeps the + * labels it was written with. + */ + +const fr: PdfLabels = { + 'pdf.eyebrow.observation': 'OBSERVATION', + 'pdf.eyebrow.synthesis': 'SYNTHÈSE', + 'pdf.title.conclusion': 'Conclusion', + 'pdf.section.zones': 'ZONES', + 'pdf.section.findings_prefix': 'CONSTATS — ', + 'pdf.section.free_findings': 'CONSTATS LIBRES', + 'pdf.section.severity': 'SÉVÉRITÉ', + 'pdf.section.comment': 'COMMENTAIRE', + 'pdf.section.conclusion': 'CONCLUSION', + 'pdf.section.recommendations': 'RECOMMANDATIONS', + 'pdf.section.next_appointment': 'PROCHAIN RENDEZ-VOUS', + 'pdf.view.general': 'VUE GÉNÉRALE', + 'pdf.view.detail_prefix': 'VUE DÉTAIL — ', + 'pdf.empty': '—', + 'pdf.owner_prefix': 'Propriétaire : ', + 'pdf.siret_prefix': 'SIRET ', + 'pdf.title.suffix.bilan': 'Bilan ostéo — ', + 'pdf.subject': "Bilan d'ostéopathie animalière", + 'severity.mild': 'légère', + 'severity.moderate': 'modérée', + 'severity.severe': 'sévère', + 'lateral.left': 'Gauche', + 'lateral.right': 'Droite', + 'footer.powered_by': 'Propulsé par', + 'footer.in_partnership': 'En partenariat avec', +} + +const en: PdfLabels = { + 'pdf.eyebrow.observation': 'OBSERVATION', + 'pdf.eyebrow.synthesis': 'SYNTHESIS', + 'pdf.title.conclusion': 'Conclusion', + 'pdf.section.zones': 'ZONES', + 'pdf.section.findings_prefix': 'FINDINGS — ', + 'pdf.section.free_findings': 'FREE FINDINGS', + 'pdf.section.severity': 'SEVERITY', + 'pdf.section.comment': 'COMMENT', + 'pdf.section.conclusion': 'CONCLUSION', + 'pdf.section.recommendations': 'RECOMMENDATIONS', + 'pdf.section.next_appointment': 'NEXT APPOINTMENT', + 'pdf.view.general': 'GENERAL VIEW', + 'pdf.view.detail_prefix': 'DETAIL VIEW — ', + 'pdf.empty': '—', + 'pdf.owner_prefix': 'Owner: ', + 'pdf.siret_prefix': 'SIRET ', + 'pdf.title.suffix.bilan': 'Osteo report — ', + 'pdf.subject': 'Animal osteopathic report', + 'severity.mild': 'mild', + 'severity.moderate': 'moderate', + 'severity.severe': 'severe', + 'lateral.left': 'Left', + 'lateral.right': 'Right', + 'footer.powered_by': 'Powered by', + 'footer.in_partnership': 'In partnership with', +} + +export const defaultPdfLabels: PdfLabelSet = { fr, en } diff --git a/apps/app/tests/fixtures/goldens/r4/pdf.demo.en.logos.sha256 b/apps/app/tests/fixtures/goldens/r4/pdf.demo.en.logos.sha256 index 7e4b6c46..af2b85e9 100644 --- a/apps/app/tests/fixtures/goldens/r4/pdf.demo.en.logos.sha256 +++ b/apps/app/tests/fixtures/goldens/r4/pdf.demo.en.logos.sha256 @@ -1 +1 @@ -2b9a359c078f5fa1b623ee4db45407209b662909044a6a9f6d02eef4d103d72e +2bf8290a85caa5c7e51fee3804de647858633b9cb1d29c950d50e9ce91ae0f18 diff --git a/apps/app/tests/fixtures/goldens/r4/pdf.demo.en.nologos.sha256 b/apps/app/tests/fixtures/goldens/r4/pdf.demo.en.nologos.sha256 index 19df2bde..a41b91b1 100644 --- a/apps/app/tests/fixtures/goldens/r4/pdf.demo.en.nologos.sha256 +++ b/apps/app/tests/fixtures/goldens/r4/pdf.demo.en.nologos.sha256 @@ -1 +1 @@ -3d76027dc76f799c3a9cb3e9ac5d082a27e58b2ef1e631e2003ba9fee6903b6b +6a405c4579dffaa06625ee363f406def86f70783e74551441b394b35ffb6b4d0 diff --git a/apps/app/tests/fixtures/goldens/r4/pdf.demo.fr.logos.sha256 b/apps/app/tests/fixtures/goldens/r4/pdf.demo.fr.logos.sha256 index 5248fa00..cbc317b0 100644 --- a/apps/app/tests/fixtures/goldens/r4/pdf.demo.fr.logos.sha256 +++ b/apps/app/tests/fixtures/goldens/r4/pdf.demo.fr.logos.sha256 @@ -1 +1 @@ -52999af79a82a426ed76e6268388dd641e7eb233f826dab6f87d47c5ecc267ca +03b7e41957e39a68e9349231186710a05e4e0b92b1e791879401e78b5c073993 diff --git a/apps/app/tests/fixtures/goldens/r4/pdf.demo.fr.nologos.sha256 b/apps/app/tests/fixtures/goldens/r4/pdf.demo.fr.nologos.sha256 index 78de66b2..f0472d1f 100644 --- a/apps/app/tests/fixtures/goldens/r4/pdf.demo.fr.nologos.sha256 +++ b/apps/app/tests/fixtures/goldens/r4/pdf.demo.fr.nologos.sha256 @@ -1 +1 @@ -e8ee3238a5c4df10c8564c67148abcdb7b2d282b5f7de3ee5dffbc72ff662247 +3f89ff74fcec00b79d143a6e435bdb3fd70a81371daf5c73918997c703aabd9e diff --git a/apps/app/tests/fixtures/goldens/r4/pdf.real.v2full-obs1.fr.logos.sha256 b/apps/app/tests/fixtures/goldens/r4/pdf.real.v2full-obs1.fr.logos.sha256 index 4b6b60f5..f0c2b33a 100644 --- a/apps/app/tests/fixtures/goldens/r4/pdf.real.v2full-obs1.fr.logos.sha256 +++ b/apps/app/tests/fixtures/goldens/r4/pdf.real.v2full-obs1.fr.logos.sha256 @@ -1 +1 @@ -287f608e77d0d41b15494e72db8415292058f8e65e0e61c4201c76b106763ba3 +87f7a6095e38164ee7b06d452fb5eb00a266ffd6da4d77fa84999052ee8396c3 diff --git a/apps/app/tests/fixtures/goldens/r4/pdf.store-path.fr.nologos.sha256 b/apps/app/tests/fixtures/goldens/r4/pdf.store-path.fr.nologos.sha256 index e8636839..140f3a35 100644 --- a/apps/app/tests/fixtures/goldens/r4/pdf.store-path.fr.nologos.sha256 +++ b/apps/app/tests/fixtures/goldens/r4/pdf.store-path.fr.nologos.sha256 @@ -1 +1 @@ -54a0472c39791c1b5426bf17dbf824ba3079acde66f3062b43643163cc869841 +400652e30e0d85d6bf1fbec68630bed743b147745d55d7c3b25000d821b7b447 diff --git a/apps/app/tests/fixtures/goldens/r4/pdf.v2full.en.logos.sha256 b/apps/app/tests/fixtures/goldens/r4/pdf.v2full.en.logos.sha256 index f8df71e6..ef50e153 100644 --- a/apps/app/tests/fixtures/goldens/r4/pdf.v2full.en.logos.sha256 +++ b/apps/app/tests/fixtures/goldens/r4/pdf.v2full.en.logos.sha256 @@ -1 +1 @@ -8ff84417d542cd200b5364844f382a21f19392284f0f7a61040e7e7269fc32dc +73580fb43b3505356547e6a1ed18c5412eca7427aacc9daf356b9bcf7f1f9f78 diff --git a/apps/app/tests/fixtures/goldens/r4/pdf.v2full.en.nologos.sha256 b/apps/app/tests/fixtures/goldens/r4/pdf.v2full.en.nologos.sha256 index 8c1bb760..751f436c 100644 --- a/apps/app/tests/fixtures/goldens/r4/pdf.v2full.en.nologos.sha256 +++ b/apps/app/tests/fixtures/goldens/r4/pdf.v2full.en.nologos.sha256 @@ -1 +1 @@ -6fe8ee50a6c6bda2eab48412f607181b23098cff7132747f623637cb9975c0a0 +d4b6bc2af9286ebe870198e14ab60e82e54f48ee6027ee16dfee8b442caa2821 diff --git a/apps/app/tests/fixtures/goldens/r4/pdf.v2full.fr.logos.sha256 b/apps/app/tests/fixtures/goldens/r4/pdf.v2full.fr.logos.sha256 index d991d503..6f346def 100644 --- a/apps/app/tests/fixtures/goldens/r4/pdf.v2full.fr.logos.sha256 +++ b/apps/app/tests/fixtures/goldens/r4/pdf.v2full.fr.logos.sha256 @@ -1 +1 @@ -58adc70d9de66848bd84a932edce590e1e151444ec063122a5b4eb67343b16f8 +08a962fb15dbdf9a1064fa176a7c674b882d14d9321344fe4ded7480ce963f99 diff --git a/apps/app/tests/fixtures/goldens/r4/pdf.v2full.fr.nologos.sha256 b/apps/app/tests/fixtures/goldens/r4/pdf.v2full.fr.nologos.sha256 index f3715c5e..a5c0f8a1 100644 --- a/apps/app/tests/fixtures/goldens/r4/pdf.v2full.fr.nologos.sha256 +++ b/apps/app/tests/fixtures/goldens/r4/pdf.v2full.fr.nologos.sha256 @@ -1 +1 @@ -b65b6289ee4c5252a32172b97241af253be73d8030dd92d090e18f9ca88b1d80 +284d4a3b579da2c0cad3f90ca96909ca4901856387669d35d8949c16e81305e1 diff --git a/apps/app/tests/fixtures/goldens/r4/pdf.v2unresolved.en.logos.sha256 b/apps/app/tests/fixtures/goldens/r4/pdf.v2unresolved.en.logos.sha256 index da9fcc95..64df26e3 100644 --- a/apps/app/tests/fixtures/goldens/r4/pdf.v2unresolved.en.logos.sha256 +++ b/apps/app/tests/fixtures/goldens/r4/pdf.v2unresolved.en.logos.sha256 @@ -1 +1 @@ -138c6ca5c9513b5e03b2db76e6b085a0b1fe35a3afedb21f4fd5762049d2b82a +503ec265cab6d5c8a776fae458cf782c3bb51db3a9c0edf06e93b2365c41350e diff --git a/apps/app/tests/fixtures/goldens/r4/pdf.v2unresolved.en.nologos.sha256 b/apps/app/tests/fixtures/goldens/r4/pdf.v2unresolved.en.nologos.sha256 index ecc413c4..72211fdc 100644 --- a/apps/app/tests/fixtures/goldens/r4/pdf.v2unresolved.en.nologos.sha256 +++ b/apps/app/tests/fixtures/goldens/r4/pdf.v2unresolved.en.nologos.sha256 @@ -1 +1 @@ -b842ceafdefacea26b376ab443b3c6b69a9466e853e640b3138f7f788ff781a5 +cdac37b198552778e9afbc62a3b74a7868c61cd9c43800d41a689a389f2b6077 diff --git a/apps/app/tests/fixtures/goldens/r4/pdf.v2unresolved.fr.logos.sha256 b/apps/app/tests/fixtures/goldens/r4/pdf.v2unresolved.fr.logos.sha256 index bfcc2785..75be5e55 100644 --- a/apps/app/tests/fixtures/goldens/r4/pdf.v2unresolved.fr.logos.sha256 +++ b/apps/app/tests/fixtures/goldens/r4/pdf.v2unresolved.fr.logos.sha256 @@ -1 +1 @@ -0cf6d48786c388b1c1d2d48b2e78f854f92af378f22dcd2dcbafdb2650b676a3 +0da6e80c849c040ca3584c208320412ddf6d2131fd9836e14c0584b44e2c49fd diff --git a/apps/app/tests/fixtures/goldens/r4/pdf.v2unresolved.fr.nologos.sha256 b/apps/app/tests/fixtures/goldens/r4/pdf.v2unresolved.fr.nologos.sha256 index 21731205..3b7000e5 100644 --- a/apps/app/tests/fixtures/goldens/r4/pdf.v2unresolved.fr.nologos.sha256 +++ b/apps/app/tests/fixtures/goldens/r4/pdf.v2unresolved.fr.nologos.sha256 @@ -1 +1 @@ -59569ab96f4a022bd70a2a1d260bda13daedb810f80744afc6b719b9f5a3f6d3 +828c8250593af1133738843489205242e80804c9ebee76cdeda22bea75406188 diff --git a/apps/app/tests/helpers/core.ts b/apps/app/tests/helpers/core.ts index 584b6319..e6e466bc 100644 --- a/apps/app/tests/helpers/core.ts +++ b/apps/app/tests/helpers/core.ts @@ -56,6 +56,7 @@ export async function trappingCoreRuntime(marker: string) { call: glue.call, SheetHandle: Trapping, FileBytes: glue.FileBytes, + ExportSession: glue.ExportSession, } }, } diff --git a/apps/app/tests/helpers/pdfRead.ts b/apps/app/tests/helpers/pdfRead.ts new file mode 100644 index 00000000..d114e7d0 --- /dev/null +++ b/apps/app/tests/helpers/pdfRead.ts @@ -0,0 +1,140 @@ +import { + decodePDFRawStream, + PDFArray, + PDFDict, + PDFDocument, + PDFName, + PDFRawStream, + type PDFPage, +} from 'pdf-lib' +import { round2, type ImageEntry, type TextEntry } from './goldens' + +/** + * The drawing facts of a saved PDF, read back from its content streams (R4.6: the core + * writes the file, so nothing is recorded at draw time any more; pdf-lib still reads the + * file in the tests until R4.8). The streams are the operator sequences pdf-lib emitted + * and the core reproduces: one operator per line, `q BT rg Tf TL Tm (Tj T*)+ ET Q` per + * text call, `q cm cm cm cm Do Q` per image. Positions are rounded like the recorder did. + */ + +/** WinAnsi is Windows-1252 for every glyph the engine prints. */ +const winAnsi = new TextDecoder('windows-1252') + +function hexBytes(token: string): Uint8Array { + const hex = token.slice(1, -1) + const out = new Uint8Array(hex.length / 2) + for (let i = 0; i < out.length; i += 1) { + out[i] = Number.parseInt(hex.slice(i * 2, i * 2 + 2), 16) + } + return out +} + +function contentOf(page: PDFPage): string { + const contents = page.node.Contents() + const streams: PDFRawStream[] = [] + if (contents instanceof PDFRawStream) streams.push(contents) + else if (contents instanceof PDFArray) { + for (let i = 0; i < contents.size(); i += 1) { + streams.push(contents.lookup(i, PDFRawStream)) + } + } + return streams + .map((stream) => + new TextDecoder('latin1').decode(decodePDFRawStream(stream).decode()), + ) + .join('\n') +} + +/** `/F1` → `Helvetica`, through the page's font resources. */ +function fontNames(page: PDFPage): Map { + const names = new Map() + const resources = page.node.lookup(PDFName.of('Resources'), PDFDict) + const fonts = resources.lookupMaybe(PDFName.of('Font'), PDFDict) + if (!fonts) return names + for (const [key, ref] of fonts.entries()) { + const font = fonts.context.lookup(ref, PDFDict) + const base = font.lookup(PDFName.of('BaseFont')) + names.set(key.decodeText(), String(base).replace(/^\//, '')) + } + return names +} + +interface PageFacts { + texts: TextEntry[] + images: ImageEntry[] +} + +function readPage(page: PDFPage, index: number): PageFacts { + const fonts = fontNames(page) + const texts: TextEntry[] = [] + const images: ImageEntry[] = [] + let font: string | null = null + let size: number | null = null + let x: number | null = null + let y: number | null = null + let lines: string[] = [] + let matrices: number[][] = [] + for (const line of contentOf(page).split('\n')) { + const tokens = line.trim().split(' ') + const op = tokens[tokens.length - 1] + const operands = tokens.slice(0, -1) + switch (op) { + case 'q': + matrices = [] + break + case 'BT': + lines = [] + break + case 'Tf': + font = fonts.get(operands[0]!.slice(1)) ?? operands[0]! + size = round2(Number(operands[1])) + break + case 'Tm': + x = round2(Number(operands[4])) + y = round2(Number(operands[5])) + break + case 'Tj': + lines.push(winAnsi.decode(hexBytes(operands[0]!))) + break + case 'ET': + texts.push({ page: index, text: lines.join('\n'), x, y, size, font }) + break + case 'cm': + matrices.push(operands.map(Number)) + break + case 'Do': { + const translate = matrices[0] ?? [] + const scale = matrices[2] ?? [] + images.push({ + page: index, + x: round2(translate[4]), + y: round2(translate[5]), + width: round2(scale[0]), + height: round2(scale[3]), + }) + break + } + default: + break + } + } + return { texts, images } +} + +/** Every text and image call of the file, page by page, in stream order. */ +export async function readDrawing(bytes: Uint8Array): Promise { + const doc = await PDFDocument.load(bytes) + const texts: TextEntry[] = [] + const images: ImageEntry[] = [] + doc.getPages().forEach((page, index) => { + const facts = readPage(page, index) + texts.push(...facts.texts) + images.push(...facts.images) + }) + return { texts, images } +} + +/** The bytes of a Blob the export produced. */ +export async function bytesOf(blob: Blob): Promise { + return new Uint8Array(await blob.arrayBuffer()) +} diff --git a/apps/app/tests/unit/archive.envelopes.test.ts b/apps/app/tests/unit/archive.envelopes.test.ts index ae6b687c..8db97d37 100644 --- a/apps/app/tests/unit/archive.envelopes.test.ts +++ b/apps/app/tests/unit/archive.envelopes.test.ts @@ -62,7 +62,8 @@ async function exportedAttachment( const { pdf } = await exportReportToPdf(golden.reports[name], sheet, { locale: 'fr', }) - return new TextDecoder().decode(await readAttachmentBytes(pdf)) + const bytes = new Uint8Array(await pdf.arrayBuffer()) + return new TextDecoder().decode(await readAttachmentBytes(bytes)) } describe.each(GOLDEN_REPORTS)('archive envelope of %s', (name) => { diff --git a/apps/app/tests/unit/migration.leaves.test.ts b/apps/app/tests/unit/migration.leaves.test.ts index 8dd0542c..57288fa2 100644 --- a/apps/app/tests/unit/migration.leaves.test.ts +++ b/apps/app/tests/unit/migration.leaves.test.ts @@ -55,9 +55,8 @@ describe('the 612 legacy leaves in the application', () => { }) it('keeps every finding, resolved or not, through an archive PDF export and import', async () => { - const { pdf: bytes } = await exportReportToPdf(report, sheet, { - locale: 'fr', - }) + const { pdf } = await exportReportToPdf(report, sheet, { locale: 'fr' }) + const bytes = new Uint8Array(await pdf.arrayBuffer()) const { read: back } = await importReportFromPdf(bytes, sheet) expect(back.migrated).toBe(false) expect(back.origin).toBe('envelope_v1') diff --git a/apps/app/tests/unit/n-1.reader.test.ts b/apps/app/tests/unit/n-1.reader.test.ts index 35a37839..91b9c003 100644 --- a/apps/app/tests/unit/n-1.reader.test.ts +++ b/apps/app/tests/unit/n-1.reader.test.ts @@ -179,8 +179,9 @@ describe('archives exported from core-built reports', () => { async (name) => { const { report } = importAttachment(fixture(name), sheet).read const { pdf } = await exportReportToPdf(report, sheet, { locale: 'fr' }) + const bytes = new Uint8Array(await pdf.arrayBuffer()) const data: unknown = JSON.parse( - new TextDecoder().decode(await readAttachmentBytes(pdf)), + new TextDecoder().decode(await readAttachmentBytes(bytes)), ) expect(ReportArchiveEnvelopeSchema.safeParse(data).success).toBe(true) const outcome = readArchiveDocument(data, await bundledMigrationMap()) diff --git a/apps/app/tests/unit/pdf.export.app.test.ts b/apps/app/tests/unit/pdf.export.app.test.ts index 4fff1cbd..4f5727e9 100644 --- a/apps/app/tests/unit/pdf.export.app.test.ts +++ b/apps/app/tests/unit/pdf.export.app.test.ts @@ -37,12 +37,12 @@ import { FIXTURES_DIR, ONE_PX_PNG, readLinks, - recordDrawing, snapshotViews, type ImageEntry, type LinkEntry, type TextEntry, } from '../helpers/goldens' +import { bytesOf, readDrawing } from '../helpers/pdfRead' // Same fixed raster for every view and logo: images then depend on the // branding and the layout only. @@ -84,18 +84,18 @@ interface Facts { links: LinkEntry[] } -/** Runs an export under the drawing recorder and reads the links back. */ -async function recorded( +/** + * Runs an export and reads its facts back from the file (R4.6: the app export is the + * core's, the re-export the engine's; both files are read the same way). + */ +async function recorded( run: () => Promise, -): Promise { - const recording = recordDrawing() - try { - const result = await run() - const { texts, images } = recording - return { ...result, texts, images, links: await readLinks(result.pdf) } - } finally { - recording.stop() - } +): Promise & { pdf: Uint8Array } & Facts> { + const result = await run() + const pdf = + result.pdf instanceof Uint8Array ? result.pdf : await bytesOf(result.pdf) + const { texts, images } = await readDrawing(pdf) + return { ...result, pdf, texts, images, links: await readLinks(pdf) } } const facts = ({ texts, images, links }: Facts): Facts => ({ diff --git a/apps/app/tests/unit/pdf.goldens.test.ts b/apps/app/tests/unit/pdf.goldens.test.ts index 9eef44ac..c7ac0080 100644 --- a/apps/app/tests/unit/pdf.goldens.test.ts +++ b/apps/app/tests/unit/pdf.goldens.test.ts @@ -1,12 +1,15 @@ /** * Step 6 Phase 0 freeze (STEP6_PDF_ARCHIVE_ANALYSIS.md §17) replayed on the - * application export path: `exportReportToPdf` now runs the engine with the - * bundled sheet snapshotted, the bundled branding (mocked to every slot empty - * for the `nologos` mode, the real module for `logos`) and the browser - * rasterizer (mocked to fixed PNGs, as the Phase 0 stub was). Text, - * images and links goldens are asserted as frozen; `MAKE_GOLDEN=1` rewrites - * them, never without a user decision. Never regenerate `report-v3.bare.pdf`: - * it is the Step 5 bare export, an import fixture only. + * application export path: `exportReportToPdf` runs the core's session (R4.6) + * with the bundled sheet snapshotted, the bundled branding (mocked to every + * slot empty for the `nologos` mode, the real module for `logos`) and the + * browser rasterizer (mocked to fixed PNGs, as the Phase 0 stub was). Text, + * images and links goldens are read back from the file's content streams and + * asserted as frozen; `MAKE_GOLDEN=1` rewrites them, never without a user + * decision. At the fixed export time the file's bytes are the R4 digests the + * cargo suite froze (`goldens/r4/pdf.*.sha256`): the app path writes what the + * native core writes. Never regenerate `report-v3.bare.pdf`: it is the Step 5 + * bare export, an import fixture only. */ import { describe, it, expect, vi, beforeAll, afterAll } from 'vitest' import { PDFDocument } from 'pdf-lib' @@ -29,7 +32,6 @@ import { ONE_PX_PNG, readGolden, readLinks, - recordDrawing, snapshotViews, TWO_BY_ONE_PNG, type ImageEntry, @@ -38,6 +40,8 @@ import { type TextEntry, type ViewSnapshot, } from '../helpers/goldens' +import { bytesOf, readDrawing } from '../helpers/pdfRead' +import { FIXED_EXPORTED_AT, R4_GOLDEN_DIR, sha256 } from '../helpers/r4-draw' const raster = vi.hoisted(() => ({ png: new Uint8Array() })) vi.mock('@/pdf/browserRasterizer', () => ({ @@ -61,8 +65,13 @@ beforeAll(async () => { sheet = await loadTestSheet() ;({ reports, unresolvedOfV2Unresolved } = buildGoldenReports(sheet)) vi.spyOn(console, 'warn').mockImplementation(() => undefined) + vi.useFakeTimers({ toFake: ['Date'] }) + vi.setSystemTime(FIXED_EXPORTED_AT) +}) +afterAll(() => { + vi.useRealTimers() + vi.restoreAllMocks() }) -afterAll(() => vi.restoreAllMocks()) interface Exported { bytes: Uint8Array @@ -78,14 +87,29 @@ async function exportWith( ): Promise { raster.png = mode === 'logos' ? TWO_BY_ONE_PNG : ONE_PX_PNG logoMode.current = mode - const recording = recordDrawing() - try { - const { pdf: bytes } = await exportReportToPdf(report, sheet, { locale }) - const { texts, images } = recording - return { bytes, texts, images, links: await readLinks(bytes) } - } finally { - recording.stop() - } + const { pdf, warnings } = await exportReportToPdf(report, sheet, { locale }) + expect(warnings).toEqual([]) + const bytes = await bytesOf(pdf) + const { texts, images } = await readDrawing(bytes) + return { bytes, texts, images, links: await readLinks(bytes) } +} + +/** + * The goldens were recorded in call order: every page's content, then the footers of + * every page (the engine drew them last). Read back from the file, the facts come page + * by page, each page's footer after its content: the golden in page order, stably, is + * the same sequence. + */ +function inPageOrder(name: string): T[] { + return [...readGolden(name)].sort((a, b) => a.page - b.page) +} + +/** The R4 digest of this run, frozen by the cargo suite from the native writer. */ +function r4Digest(name: string, locale: Locale, mode: LogoMode): string { + return readFileSync( + resolve(R4_GOLDEN_DIR, `pdf.${name}.${locale}.${mode}.sha256`), + 'utf8', + ).trim() } const pagesOf = (entries: readonly { page: number }[]) => @@ -133,16 +157,22 @@ describe.each(REPORTS)('goldens of %s', (name) => { // Images and links are recorded per locale too: the footer centres the // "powered by" block on the label width, so the ZenQuality link (and its // logo) shift between FR and EN. Only the pagination is locale-free. - it('text, images and links per locale; same pagination across locales', async () => { + it('text, images and links per locale; same pagination across locales; app-path bytes = native digest', async () => { const fr = await exportWith(reports[name], mode, 'fr') const en = await exportWith(reports[name], mode, 'en') for (const [locale, out] of [ ['fr', fr], ['en', en], ] as const) { - checkGolden(`text.${name}.${locale}.${mode}.json`, out.texts) - checkGolden(`images.${name}.${locale}.${mode}.json`, out.images) - checkGolden(`links.${name}.${locale}.${mode}.json`, out.links) + const id = `${name}.${locale}.${mode}` + expect(out.texts, `text.${id}`).toEqual(inPageOrder(`text.${id}.json`)) + expect(out.images, `images.${id}`).toEqual( + inPageOrder(`images.${id}.json`), + ) + checkGolden(`links.${id}.json`, out.links) + expect(sha256(out.bytes), id).toBe( + r4Digest(name, locale, mode), + ) } expect(pagesOf(en.images)).toEqual(pagesOf(fr.images)) expect(pagesOf(en.links)).toEqual(pagesOf(fr.links)) diff --git a/apps/app/tests/unit/pdf.roundtrip.test.ts b/apps/app/tests/unit/pdf.roundtrip.test.ts index 5dc7c1f6..98c533a9 100644 --- a/apps/app/tests/unit/pdf.roundtrip.test.ts +++ b/apps/app/tests/unit/pdf.roundtrip.test.ts @@ -1,30 +1,25 @@ /** * Replaces char.pdfFull / pdf.roundtrip / pdf.zoneLabels: the application - * export path on the engine with the bundled sheet (drawn strings from the - * document, envelope attachment, roundtrip FR/EN) and the import of the - * frozen v2 archive PDFs, migrated without silent loss. + * export path on the core's session with the bundled sheet (drawn strings + * from the document, read back from the file's content streams since R4.6, + * envelope attachment, roundtrip FR/EN) and the import of the frozen v2 + * archive PDFs, migrated without silent loss. */ -import { - describe, - it, - expect, - vi, - beforeAll, - beforeEach, - afterAll, -} from 'vitest' -import { AFRelationship, PDFDocument, PDFPage } from 'pdf-lib' +import { describe, it, expect, vi, beforeAll, afterAll } from 'vitest' +import { AFRelationship, PDFDocument } from 'pdf-lib' import { readFileSync } from 'node:fs' import { fileURLToPath } from 'node:url' import { dirname, resolve } from 'node:path' import type { Observation, Report } from '@faunosteo/core-wasm/types' -import { composeHighlightedViewSvg, defaultPdfLabels } from '@faunosteo/pdf' +import { composeHighlightedViewSvg } from '@faunosteo/pdf' import { exportReportToPdf } from '@/pdf/export' +import { defaultPdfLabels } from '@/pdf/labels' import { importReportFromPdf, ImportError } from '@/pdf/import' import { formatDate } from '@/lib/dates' import type { Locale } from '@/i18n/types' import type { SheetIndex } from '@/services/sheetIndex' import { loadTestSheet, minimalReport, sheetSnapshot } from '../helpers/sheet' +import { bytesOf, readDrawing } from '../helpers/pdfRead' // The factory runs when the engine first loads the adapter: fixed 1×1 PNG. vi.mock('@/pdf/browserRasterizer', async () => { @@ -40,12 +35,19 @@ async function readBack(bytes: Uint8Array) { return (await importReportFromPdf(bytes, sheet)).read } -/** The static PDF strings now belong to the engine's label set. */ +/** The static PDF strings belong to the app's label set. */ const { fr, en } = defaultPdfLabels -/** The bytes of an app export (its warnings are not under test here). */ +/** + * The bytes of an app export (its warnings are not under test here); `drawn` holds the + * texts of its content streams, in draw order. + */ async function exportPdf(report: Report, locale: Locale): Promise { - return (await exportReportToPdf(report, sheet, { locale })).pdf + const bytes = await bytesOf( + (await exportReportToPdf(report, sheet, { locale })).pdf, + ) + drawn = (await readDrawing(bytes)).texts.map((t) => t.text) + return bytes } const HERE = dirname(fileURLToPath(import.meta.url)) @@ -60,15 +62,6 @@ beforeAll(async () => { vi.spyOn(console, 'warn').mockImplementation(() => undefined) }) afterAll(() => vi.restoreAllMocks()) -beforeEach(() => { - drawn = [] - vi.spyOn(PDFPage.prototype, 'drawText').mockImplementation(function ( - this: PDFPage, - text: string, - ) { - drawn.push(text) - } as never) -}) /** A full v3 observation: plain zone, bilateral both sides, spine with vertebrae, head zone, findings. */ function fullObservation(): Observation { @@ -208,7 +201,7 @@ function fullReport() { describe('PDF content on a two-observation report', () => { it('prints the empty marker for a zoneless observation and keeps its findings', async () => { - await exportReportToPdf(fullReport(), sheet, { locale: 'fr' }) + await exportPdf(fullReport(), 'fr') expect(drawn).toContain(fr['pdf.empty']) const prefix = fr['pdf.section.findings_prefix']! const occurrences = drawn.filter( @@ -231,14 +224,14 @@ describe('PDF content on a two-observation report', () => { ], } const report = minimalReport(sheet, { observations: [stale] }) - await exportReportToPdf(report, sheet, { locale: 'fr' }) + await exportPdf(report, 'fr') expect(drawn).toContain('point-gone') expect(drawn).toContain(`${fr['pdf.section.findings_prefix']}ZONE-GONE`) expect(drawn).toContain('Snapshot FR') }) it('draws the EN dictionary, annotation names and finding snapshots', async () => { - await exportReportToPdf(fullReport(), sheet, { locale: 'en' }) + await exportPdf(fullReport(), 'en') expect(drawn).toContain(en['pdf.section.zones']) expect(drawn.some((l) => l.includes('Hip joint'))).toBe(true) expect(drawn).toContain('Junction fixation') @@ -282,7 +275,7 @@ describe('PDF content on a two-observation report', () => { }) expect(fetchSpy).not.toHaveBeenCalled() expect(warnings).toEqual([]) - const out = await readBack(pdf) + const out = await readBack(await bytesOf(pdf)) const branding = out.archive!.branding expect(branding.headerLogo?.kind).toBe('png') expect(branding.footerLogo?.kind).toBe('png') diff --git a/apps/app/tests/unit/r4.writer-oracles.test.ts b/apps/app/tests/unit/r4.writer-oracles.test.ts index b9eee6e2..f77c53d5 100644 --- a/apps/app/tests/unit/r4.writer-oracles.test.ts +++ b/apps/app/tests/unit/r4.writer-oracles.test.ts @@ -16,11 +16,14 @@ import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest' import { AFRelationship, PageSizes, PDFDocument, StandardFonts } from 'pdf-lib' import type { Branding, Practitioner, Report } from '@faunosteo/core-wasm/types' import { + exportReportArchive, readAttachedDocument, readAttachmentBytes, + type ExportInput, type Rasterizer, } from '@faunosteo/pdf' -import { exportReportToPdf } from '@/pdf/export' +import { loadBranding } from '@/pdf/branding' +import { defaultPdfLabels } from '@/pdf/labels' import { importAttachment } from '@/pdf/import' import type { SheetIndex } from '@/services/sheetIndex' import type { Locale } from '@/i18n/types' @@ -113,14 +116,26 @@ const fixedRaster = async () => mode === 'logos' ? TWO_BY_ONE_PNG : ONE_PX_PNG -/** One export through `@/pdf/export`, drawn under the full recorder. */ +/** + * One export through the TypeScript engine with the application's inputs (the snapshot + * the core builds, the bundled branding of the mode, the app's labels, the fixed export + * time), drawn under the full recorder. R4.6 moved `@/pdf/export` onto the core's + * session: the oracles stay those of the R3 build, so the engine is called directly, as + * the app export called it until then (same inputs, same order). + */ async function exportRun(run: Run): Promise { raster.rasterize = run.rasterize logoMode.current = run.mode const recorder = recordFullDrawing() try { - const { pdf, warnings } = await exportReportToPdf(run.report, sheet, { + const { pdf, warnings } = await exportReportArchive({ + report: run.report as ExportInput['report'], + sheet: sheetSnapshot(sheet, run.report) as ExportInput['sheet'], + branding: await loadBranding(), + labels: defaultPdfLabels, locale: run.locale, + rasterizer: run.rasterize, + exportedAt: new Date(), }) expect(warnings).toEqual([]) expect(recorder.unexpectedCalls()).toEqual([]) diff --git a/apps/app/tests/unit/routes.EditorRoute.export.test.tsx b/apps/app/tests/unit/routes.EditorRoute.export.test.tsx index 7d20d875..10f12e70 100644 --- a/apps/app/tests/unit/routes.EditorRoute.export.test.tsx +++ b/apps/app/tests/unit/routes.EditorRoute.export.test.tsx @@ -27,7 +27,9 @@ import { loadTestSheet, minimalReport } from '../helpers/sheet' vi.mock('@/pdf/export', () => ({ exportReportToPdf: vi.fn() })) const exportMock = vi.mocked(exportReportToPdf) -const PDF_BYTES = new Uint8Array([37, 80, 68, 70]) +const PDF_BYTES = new Blob([new Uint8Array([37, 80, 68, 70])], { + type: 'application/pdf', +}) let sheet: SheetIndex const downloads: string[] = [] @@ -69,25 +71,32 @@ afterEach(() => { URL.revokeObjectURL = realRevokeObjectURL }) -async function mountAndExport(label: string): Promise { - render( +async function mountAndExport(label: string): Promise<() => void> { + const { unmount } = render( , ) const button = await screen.findByRole('button', { name: label }) await userEvent.setup().click(button) + return unmount } +/** The options the route passes: the locale and the signal it aborts on unmount. */ +const options = (locale: 'fr' | 'en') => ({ + locale, + signal: expect.any(AbortSignal) as AbortSignal, +}) + describe('EditorRoute export', () => { it('calls exportReportToPdf with the store report, the loaded index and the FR locale', async () => { exportMock.mockResolvedValue({ pdf: PDF_BYTES, warnings: [] }) await mountAndExport(fr['editor.export']!) await waitFor(() => expect(exportMock).toHaveBeenCalledTimes(1)) - const [report, index, options] = exportMock.mock.calls[0]! + const [report, index, passed] = exportMock.mock.calls[0]! expect(report).toBe(useReportStore.getState().report) expect(index).toBe(sheet) - expect(options).toEqual({ locale: 'fr' }) + expect(passed).toEqual(options('fr')) }) it('passes the active locale (EN)', async () => { @@ -95,7 +104,7 @@ describe('EditorRoute export', () => { exportMock.mockResolvedValue({ pdf: PDF_BYTES, warnings: [] }) await mountAndExport(en['editor.export']!) await waitFor(() => expect(exportMock).toHaveBeenCalledTimes(1)) - expect(exportMock.mock.calls[0]![2]).toEqual({ locale: 'en' }) + expect(exportMock.mock.calls[0]![2]).toEqual(options('en')) }) it('downloads bilan--.pdf through a blob URL it revokes after a delay', async () => { @@ -131,6 +140,28 @@ describe('EditorRoute export', () => { ) }) + it('aborts the export when the editor unmounts mid-way: no download, no alert', async () => { + let settle: (() => void) | null = null + exportMock.mockImplementation( + (_report, _index, opts) => + new Promise((_, reject) => { + settle = () => + reject(new DOMException('export aborted', 'AbortError')) + opts.signal?.addEventListener('abort', () => settle?.()) + }), + ) + const unmount = await mountAndExport(fr['editor.export']!) + await waitFor(() => expect(exportMock).toHaveBeenCalledTimes(1)) + const signal = exportMock.mock.calls[0]![2].signal! + expect(signal.aborted).toBe(false) + unmount() + expect(signal.aborted).toBe(true) + await Promise.resolve() + await Promise.resolve() + expect(downloads).toHaveLength(0) + expect(window.alert).not.toHaveBeenCalled() + }) + it('alerts editor.export_failed when the export rejects', async () => { vi.spyOn(console, 'error').mockImplementation(() => undefined) exportMock.mockRejectedValue(new Error('render exploded')) diff --git a/crates/core/src/pdf/write/objects.rs b/crates/core/src/pdf/write/objects.rs index 258b0aba..b26d654e 100644 --- a/crates/core/src/pdf/write/objects.rs +++ b/crates/core/src/pdf/write/objects.rs @@ -230,11 +230,11 @@ pub fn name(text: &str) -> String { out } -/// `PDFHexString.fromText`: UTF-16BE with a BOM, lowercase hex. +/// `PDFHexString.fromText`: UTF-16BE with a BOM, upper-case hex as pdf-lib printed it. pub fn hex_text(text: &str) -> String { - let mut out = String::from("'); out