Skip to content

Commit e0df93b

Browse files
author
Kevin Arthur
committed
fix(import): keep vertical PDF writing vertical
Identity-V (and any CMap whose /WMode is 1) advances glyphs down the page. The importer advanced every run horizontally, so a Japanese or Chinese column arrived as one long line: the characters all existed, which made it a wrong document rather than a reported fidelity loss. The font record now carries the writing mode (name suffix -V, or an embedded CMap declaring /WMode 1), the interpreter advances down for those runs, and the node is created with writingMode vertical-rl, which Varve already renders and edits natively. The per-glyph advance is one em because /W2 is not read; the Import Report states that rather than implying exact metrics. Evidence: PDFCraft 3216 (vertical Identity-V measured as horizontal), 3711 (tate-chu-yoko digits), 3712 (upright glyphs read as horizontal rows). Unit tests cover Identity-V, CMap /WMode 1 and an Identity-H control; the browser test imports the fixture through File > Import and asserts the rendered ink is a column (38x96 at 100%), not a line. Also stops the import-integrity browser test writing evidence screenshots into the checkout: that dirtied the source tree mid-run, and the CI lane runner requires an unchanged clean source at the planned commit. Screenshots go to a temp directory unless VARVE_SHOT_DIR says otherwise.
1 parent 6ddf02e commit e0df93b

11 files changed

Lines changed: 333 additions & 12 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,12 @@ update, not for someone reading the commit log.
7878

7979
### Fixed
8080

81+
- **PDF import keeps vertical writing vertical.** A PDF set in a vertical
82+
writing mode (`Identity-V`, or a CMap with `/WMode 1`) imported as one long
83+
horizontal line, so a Japanese or Chinese column arrived as the wrong
84+
document. Those runs now become Varve vertical text (`vertical-rl`), with the
85+
Import Report stating that each glyph advances one em because the font's
86+
vertical metrics are not read.
8187
- **PDF export names characters the chosen font cannot draw.** The canvas falls
8288
back per glyph, but the PDF writer outlines the authored face, so a character
8389
that face does not map exported as a blank box while the editor showed it

‎docs/architecture/import-system.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -107,7 +107,7 @@ server (`tests/e2e/canvas/file-import.spec.ts`, snapshots inspected).
107107
| AVIF | Full | `ispe` box probe now recurses through `iprp`/`ipco` |
108108
| SVG / SVGZ | Editable vector | See fidelity matrix; `.svgz` is gunzipped by content sniff and retains the `svgz` source label in the Import Results report, including bounded malformed-input failures |
109109
| PSD / PSB | Partial | Version 1/2 `8BPS` files import a bounded layer tree (groups, bounds, visibility, opacity, and representable masks), and the asynchronous service path materializes supported layer pixels as embedded PNG image fills; header, dimension, encoded-size, and pixel budgets are checked before parsing; invalid or sentinel mask rectangles are omitted with a warning; effects, adjustment layers, smart objects, and exact text editing are reported as unsupported, with detected smart-object layers counted explicitly (imported as rendered pixels only; embedded artwork, warps, and re-editability are not extracted) |
110-
| PDF | Partial | Text and axis-aligned rectangle fills, per page. Content streams are decoded (zlib `FlateDecode`, ASCIIHex, ASCII85) and tokenized, so text positions come from the text matrix composed with the CTM and are mapped into page space (top-left origin, `/Rotate` applied, crop box used when it differs). Character codes resolve through the font's `/ToUnicode` CMap, otherwise the named base encoding plus `/Differences`. Page order follows the `/Kids` tree, with/inherited `/MediaBox`, `/Rotate` and `/Resources`. **Content the page does not show is not imported:** text in an invisible or clip-only render mode (`3 Tr`/`7 Tr`, the shape of a searchable OCR layer) and content inside an optional-content group the document's default configuration hides (a PDF "layer", as layered CAD exports ship) are counted and named in `unsupportedFeatures` instead of being painted as visible artwork. **An encrypted document is refused with an explanation**, never imported as ciphertext that looks like an empty page. Everything else — images, form XObjects, curves, strokes, gradients, CMYK and pattern paints, composite-font runs with no mapping — is counted and named in `unsupportedFeatures`, never approximated. Bounded: 32 MB file, 16 MB per decoded stream, 50 pages |
110+
| PDF | Partial | Text and axis-aligned rectangle fills, per page. Content streams are decoded (zlib `FlateDecode`, ASCIIHex, ASCII85) and tokenized, so text positions come from the text matrix composed with the CTM and are mapped into page space (top-left origin, `/Rotate` applied, crop box used when it differs). Character codes resolve through the font's `/ToUnicode` CMap, otherwise the named base encoding plus `/Differences`. Page order follows the `/Kids` tree, with/inherited `/MediaBox`, `/Rotate` and `/Resources`. **Content the page does not show is not imported:** text in an invisible or clip-only render mode (`3 Tr`/`7 Tr`, the shape of a searchable OCR layer) and content inside an optional-content group the document's default configuration hides (a PDF "layer", as layered CAD exports ship) are counted and named in `unsupportedFeatures` instead of being painted as visible artwork. Vertical writing is preserved: a Type0 font whose CMap selects `/WMode 1` (`Identity-V`, or an embedded CMap that says so) is imported as a Varve vertical text node (`writingMode: vertical-rl`) instead of a single horizontal line. The per-glyph advance is one em because the font's `/W2` metrics are not read, and the capability note says so. **An encrypted document is refused with an explanation**, never imported as ciphertext that looks like an empty page. Everything else — images, form XObjects, curves, strokes, gradients, CMYK and pattern paints, composite-font runs with no mapping — is counted and named in `unsupportedFeatures`, never approximated. Bounded: 32 MB file, 16 MB per decoded stream, 50 pages |
111111
| AI | Partial | `.ai` files with a PDF-compatible wrapper or legacy EPS header use the AI adapter; complex Illustrator effects, meshes, and native semantics are reported as losses; header-only or over-budget wrappers fail without fabricated nodes |
112112
| EPS | Partial | Basic paths |
113113
| Sketch | Partial | Symbols, shared styles and constraints not preserved |

‎docs/audits/pdfcraft/README.md‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,7 @@ signature and Office interchange, all of which remain outside Varve's scope.
125125
| 6 | Page rotation, page count and output size surviving save/reopen/export | **verified for save/reopen** — Varve's page-rotation model is per-page width/height, and a mixed-orientation document round-trips with order and node positions intact (commit `340262b60`). Export page geometry is the native writer's contract and is covered by `tests/e2e/export/native-pdf-contract.spec.ts`, not by a browser unit test |
126126
| 7 | Text edit identity (paragraph indices, property loss on re-edit) | already handled upstream: edits target authored node ids (ADR-0242), and the draft/target-switch paths are covered by `context/pendingEdits.ts` with `tests/e2e/save/text-draft-save.spec.ts` and `text-target-switch.spec.ts` |
127127
| 8 | Autosave scheduling tied to repaint; failed-autosave retry suppression | deferred — `packages/editor/src/context/usePersistence.ts` belongs to another session; two writers on one file is worse than a delay |
128+
| 10 | Vertical writing (`Identity-V`) imported as one horizontal line, so a CJK column became the wrong document | **implemented and validated** — `/WMode 1` (name or embedded CMap) is detected and the run becomes a `vertical-rl` text node; unit tests cover detection and the browser test asserts the rendered ink is a column. Per-glyph advance is one em (`/W2` unread) and disclosed in the Import Report. Commit `codex/pdfcraft-remainder-20261022` |
128129
| 9 | PDF import invents content the page does not show: invisible/clip-only text, hidden optional-content layers, encrypted files imported as blank pages, and an inline image whose `EI` is followed by a delimiter | **implemented and validated** — `/OCProperties` visibility, `Tr` render modes, `/Encrypt` refusal with a failure status, and delimiter-terminated `EI`. Commits `3bdd3e336`, `bb2f53d24`; browser evidence in `tests/e2e/import/pdf-import-integrity.spec.ts` and `docs/screenshots/pdfcraft/` |
129130

130131
## Limitations (unresolved)
@@ -163,9 +164,9 @@ These are honest gaps, not completions:
163164
Cutoff 2 is taken and reconciled; batches 1–6 and 9 are complete or recorded
164165
with reasons. What remains, in priority order:
165166

166-
1. **Vertical-writing import** (rows 3216/3711/3712): map `Identity-V` runs and
167-
`Tz`-upright placement into Varve's vertical text model, with a round-trip
168-
test. This is the largest remaining fidelity gap found in the corpus.
167+
1. ~~Vertical-writing import (rows 3216/3711/3712)~~ — landed as batch 10. The
168+
remaining refinement is `/W2` per-glyph vertical metrics (currently one em)
169+
and `Tz`-upright placement inside a vertical run.
169170
2. **Batch 8 (interaction)**: verify cursor ownership over chrome (rows 3001,
170171
3383, 3871), overlay placement with two menus (3190), and small-window
171172
clipping (3097, 3557, 3559). Each is a verification first; no UI change is

‎docs/audits/pdfcraft/issue-ledger-cutoff2.tsv‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -140,7 +140,7 @@
140140
3213 open high priority: high pdf-structure implemented-validated Flatten draws annotations on hidden layers: no annotation model; hidden OC content is not imported (batch 9). cutoff2
141141
3214 open medium priority: medium pdf-structure implemented-validated Edit lists pictures on hidden layers: no PDF-object editing surface; hidden content is not imported. cutoff2
142142
3215 open high priority: high,multiple issues pdf-structure implemented-validated Whole line redrawn in the first run's state: Varve imports positioned runs, not a re-writable line; text state is applied per run at import. cutoff2
143-
3216 open critical priority: critical fonts-glyphs candidate Vertical (Identity-V) text measured as horizontal: Varve has vertical text authoring, but PDF import maps codes to horizontal runs. A vertical-writing import path is a real gap; queued, not implemented. cutoff2
143+
3216 open critical priority: critical fonts-glyphs implemented-validated Vertical writing imported as a column: /Identity-V and /WMode 1 are detected and the run becomes a vertical-rl text node (packages/import/src/pdf/encoding.ts, contentInterpreter.ts, index.ts), with a unit test and a browser test asserting the ink box is a column. Per-glyph advance is one em because /W2 is not read; the capability note discloses it. cutoff2
144144
3217 open high priority: high,multiple issues page-geometry cluster-assessed Page geometry and order round-trip is verified (batch 6); page editing of a PDF container is out of scope. cutoff2
145145
3218 open high priority: high forms outside-varve-scope No Varve form model and none planned; the text-metric and glyph-coverage mechanisms inside form reports are routed to the fonts-glyphs rows. cutoff2
146146
3219 open high priority: high pdf-structure cluster-assessed Varve imports PDF content into its own model and does not rewrite PDF structure; the transferable content-visibility classes are fixed in batch 9. cutoff2
@@ -399,8 +399,8 @@
399399
3701 open low enhancement,priority: low interaction cluster-assessed Cursor/overlay ownership and small-window layout are queued candidates, not assumed defects. cutoff2
400400
3707 open high priority: high fonts-glyphs implemented-validated Japanese kana rejected on macOS: coverage report (batch 2). cutoff2
401401
3709 open low priority: low digital-signature outside-varve-scope No signature or certificate surface. cutoff2
402-
3711 open medium priority: medium fonts-glyphs candidate tate-chu-yoko digits dropped on copy: same vertical-writing gap as 3216. cutoff2
403-
3712 open high priority: high fonts-glyphs candidate Upright glyphs placed one by one read as horizontal rows: same vertical-writing gap. cutoff2
402+
3711 open medium priority: medium fonts-glyphs implemented-validated Vertical writing imported as a column: /Identity-V and /WMode 1 are detected and the run becomes a vertical-rl text node (packages/import/src/pdf/encoding.ts, contentInterpreter.ts, index.ts), with a unit test and a browser test asserting the ink box is a column. Per-glyph advance is one em because /W2 is not read; the capability note discloses it. cutoff2
403+
3712 open high priority: high fonts-glyphs implemented-validated Vertical writing imported as a column: /Identity-V and /WMode 1 are detected and the run becomes a vertical-rl text node (packages/import/src/pdf/encoding.ts, contentInterpreter.ts, index.ts), with a unit test and a browser test asserting the ink box is a column. Per-glyph advance is one em because /W2 is not read; the capability note discloses it. cutoff2
404404
3713 open medium priority: medium fonts-glyphs candidate Character spacing splits copied Chinese: PDF import emits one run per Tj/TJ, so authored spacing is preserved in the node text; search/copy normalisation is queued. cutoff2
405405
3715 open high priority: high digital-signature outside-varve-scope No signature or certificate surface. cutoff2
406406
3724 open medium priority: medium,multiple issues interaction cluster-assessed Cursor/overlay ownership and small-window layout are queued candidates, not assumed defects. cutoff2

‎packages/import/src/pdf/content.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,12 @@ export interface TextRun {
2323
readonly fontBase: string | null;
2424
/** True when the font published no widths and the advance was estimated. */
2525
readonly estimatedAdvance: boolean;
26+
/**
27+
* True when the run is set in a vertical writing mode (`Identity-V`, or a
28+
* CMap whose `/WMode` is 1). Its glyphs advance down the page, so importing
29+
* it as a horizontal run would put a column of text on one line.
30+
*/
31+
readonly vertical: boolean;
2632
}
2733

2834
export interface RectFill {
@@ -49,6 +55,8 @@ export interface ContentDiagnostics {
4955
undecodableRuns: number;
5056
/** Runs the document paints with nothing (`3 Tr` invisible, `7 Tr` clip). */
5157
invisibleRuns: number;
58+
/** Runs set in a vertical writing mode, imported as vertical text. */
59+
verticalRuns: number;
5260
/**
5361
* Runs and fills inside an optional-content group the document's default
5462
* configuration hides. They are not imported, because the page does not
@@ -92,6 +100,7 @@ export function createDiagnostics(): ContentDiagnostics {
92100
unmappedCodes: 0,
93101
undecodableRuns: 0,
94102
invisibleRuns: 0,
103+
verticalRuns: 0,
95104
hiddenRuns: 0,
96105
hiddenRects: 0,
97106
unresolvedOptionalContent: 0,

‎packages/import/src/pdf/contentInterpreter.ts‎

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -475,6 +475,7 @@ export class ContentInterpreter {
475475
return;
476476
}
477477
const position = this.displayPosition();
478+
const vertical = font.vertical === true;
478479
const items = fromArray && Array.isArray(this.operands[0]) ? this.operands[0] : this.operands;
479480

480481
let content = '';
@@ -519,6 +520,7 @@ export class ContentInterpreter {
519520
return;
520521
}
521522
if (this.runs.length >= MAX_RUNS) return;
523+
if (vertical) this.diagnostics.verticalRuns += 1;
522524
const display = toDisplaySpace(this.pageBox, position.x, position.y);
523525
this.emissions.push({ kind: 'run', at: this.runs.length });
524526
this.runs.push({
@@ -529,6 +531,7 @@ export class ContentInterpreter {
529531
fontResource: font.resourceName,
530532
fontBase: font.baseFont,
531533
estimatedAdvance: estimated,
534+
vertical,
532535
});
533536
if (this.isOutsidePage(display.x, display.y)) this.outsidePageCount += 1;
534537
}
@@ -565,6 +568,7 @@ export class ContentInterpreter {
565568
return { text: decoded, unmapped: 0, estimated: true };
566569
}
567570
const step = text.font?.twoByteCodes ? 2 : 1;
571+
const vertical = text.font?.vertical === true;
568572
let out = '';
569573
let unmapped = 0;
570574
let estimated = false;
@@ -575,16 +579,28 @@ export class ContentInterpreter {
575579
if (width === null) estimated = true;
576580
if (mapped.length === 0) unmapped += 1;
577581
else out += mapped;
578-
let advance = ((width ?? FALLBACK_WIDTH) / 1000) * text.fontSize + text.charSpacing;
579-
if (text.font && code === text.font.spaceCode) advance += text.wordSpacing;
582+
// A vertical run advances by the vertical displacement (`/W2` in the
583+
// CIDFont, one em by default). The importer does not read `/W2`, so the
584+
// advance is one em and the run is marked estimated.
585+
const advance = vertical
586+
? text.fontSize + text.charSpacing
587+
: ((width ?? FALLBACK_WIDTH) / 1000) * text.fontSize + text.charSpacing;
588+
if (vertical) estimated = true;
589+
if (text.font && code === text.font.spaceCode) {
590+
this.advanceInTextSpace((advance + text.wordSpacing) * text.horizScale);
591+
continue;
592+
}
580593
this.advanceInTextSpace(advance * text.horizScale);
581594
}
582595
return { text: out, unmapped, estimated };
583596
}
584597

585598
private advanceInTextSpace(amount: number): void {
586599
if (amount === 0) return;
587-
this.state.text.matrix = multiply(translation(amount, 0), this.state.text.matrix);
600+
// Vertical writing advances down the page (negative y in text space), so a
601+
// column of text is not laid out as one horizontal line.
602+
const step = this.state.text.font?.vertical ? translation(0, -amount) : translation(amount, 0);
603+
this.state.text.matrix = multiply(step, this.state.text.matrix);
588604
}
589605

590606
// ── Paths ─────────────────────────────────────────────────────────────

‎packages/import/src/pdf/encoding.ts‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,8 @@ export interface PdfFont {
3030
readonly baseFont: string | null;
3131
/** True for composite fonts whose codes are 2 bytes (Type0/Identity-H). */
3232
readonly twoByteCodes: boolean;
33+
/** True when the font's CMap selects vertical writing (`/WMode 1`). */
34+
readonly vertical: boolean;
3335
/** False when the font publishes no usable encoding; textFor returns ''. */
3436
readonly decodable: boolean;
3537
/** Glyph advance in 1/1000 em, or null when the font publishes no widths. */
@@ -161,6 +163,7 @@ export function buildFont(
161163
const subtype = dictName(fontObject.header, 'Subtype');
162164
const baseFont = dictName(fontObject.header, 'BaseFont');
163165
const twoByteCodes = subtype === 'Type0';
166+
const vertical = readVerticalWriting(index, fontObject, report);
164167
const toUnicode = loadToUnicode(index, fontObject, report);
165168
const widthOf = loadWidths(index, fontObject, twoByteCodes);
166169

@@ -170,6 +173,7 @@ export function buildFont(
170173
subtype,
171174
baseFont,
172175
twoByteCodes,
176+
vertical,
173177
decodable: true,
174178
widthOf,
175179
spaceCode: toUnicode.spaceCode,
@@ -188,6 +192,7 @@ export function buildFont(
188192
subtype,
189193
baseFont,
190194
twoByteCodes: false,
195+
vertical: false,
191196
decodable: true,
192197
widthOf,
193198
spaceCode: simple.spaceCode,
@@ -204,6 +209,28 @@ function sanitizeMapped(mapped: string): string {
204209
return mapped.includes(REPLACEMENT) ? '' : mapped;
205210
}
206211

212+
/**
213+
* A composite font's `/Encoding` is a CMap, and the CMap decides the writing
214+
* mode: `Identity-V` (or any name ending in `-V`) is vertical, and an embedded
215+
* CMap stream states it as `/WMode 1`. Vertical text advances down the page,
216+
* so treating it as horizontal turns a column into one long line.
217+
*/
218+
function readVerticalWriting(
219+
index: PdfIndex,
220+
fontObject: PdfObject,
221+
report: DecodeReport,
222+
): boolean {
223+
const name = dictName(fontObject.header, 'Encoding');
224+
if (name !== null && /-V$/.test(name)) return true;
225+
const reference = /\/Encoding\s+(\d+)\s+\d+\s+R/.exec(fontObject.header);
226+
if (!reference) return false;
227+
const cmap = index.objects.get(Number(reference[1]));
228+
if (!cmap?.stream) return false;
229+
const bytes = decodeStream(index, cmap, report);
230+
if (!bytes) return false;
231+
return /\/WMode\s+1\b/.test(latin1(bytes));
232+
}
233+
207234
function nonDecodableFont(
208235
resourceName: string,
209236
subtype: string | null,
@@ -214,6 +241,7 @@ function nonDecodableFont(
214241
subtype,
215242
baseFont,
216243
twoByteCodes: subtype === 'Type0',
244+
vertical: false,
217245
decodable: false,
218246
widthOf: () => null,
219247
spaceCode: 32,

‎packages/import/src/pdf/index.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -303,6 +303,10 @@ function textNodeFor(
303303
name: family ? `Text (${family})` : 'Text',
304304
transform: [1, 0, 0, 1, run.x * POINTS_TO_PX * scale, run.y * POINTS_TO_PX * scale] as Affine,
305305
fontSize: Math.max(run.fontSize * POINTS_TO_PX * scale, 0.1),
306+
// A vertical run is a column, not a line. Varve authors vertical text
307+
// natively, so the run keeps its writing mode instead of arriving as one
308+
// long horizontal string.
309+
...(run.vertical ? { writingMode: 'vertical-rl' as const } : {}),
306310
});
307311
return { node, document: next };
308312
}
@@ -455,6 +459,11 @@ function capabilityNotes(
455459
if (collection.pages.some((page) => page.cropBoxApplied)) {
456460
notes.push('The crop box was used as the page box where it differs from the media box');
457461
}
462+
if (diagnostics.verticalRuns > 0) {
463+
notes.push(
464+
`${diagnostics.verticalRuns} vertical text run(s) were imported as vertical text; their per-glyph advance is one em because the font's /W2 metrics are not read`,
465+
);
466+
}
458467
if (report.unsupportedFilters.size > 0) notes.push('Unsupported stream filters were reported');
459468
if (diagnostics.outsidePage > 0) {
460469
notes.push(

0 commit comments

Comments
 (0)