oficina / docs Public

Clone
git clone https://amadan.net/oficina/docs

Plain git — no account needed to clone.

Download

Download this file

1package export_test
2
3import (
4 "bytes"
5 "encoding/json"
6 "fmt"
7 "math"
8 "os/exec"
9 "regexp"
10 "sort"
11 "strconv"
12 "strings"
13 "testing"
14
15 "github.com/carlosframework/docs/internal/export"
16 "github.com/carlosframework/docs/internal/fonts"
17)
18
19func mustPDF(t *testing.T, doc export.Document) ([]byte, export.Report) {
20 t.Helper()
21 out, report, err := export.PDF(doc)
22 if err != nil {
23 t.Fatalf("PDF: %v", err)
24 }
25 return out, report
26}
27
28// The one that matters: the words a person typed have to be the words
29// they get when they select the exported PDF and copy it. Everything
30// between — glyph ids, the subset, the CMap — is machinery in service
31// of this.
32func TestPDFTextCanBeCopiedBackOut(t *testing.T) {
33 js := `{"type":"doc","content":[
34 {"type":"heading","attrs":{"level":2},"content":[{"type":"text","text":"A heading"}]},
35 {"type":"paragraph","content":[
36 {"type":"text","text":"Plain then "},
37 {"type":"text","text":"bold","marks":[{"type":"strong"}]},
38 {"type":"text","text":" and a caf"},
39 {"type":"text","text":"é."}
40 ]}
41 ]}`
42 data, report := mustPDF(t, mustParse(t, "Notes", js))
43 if !report.Empty() {
44 t.Errorf("unexpected substitutions: %s", report)
45 }
46
47 f := readPDF(t, data)
48 pages := f.pages(t)
49 if len(pages) != 1 {
50 t.Fatalf("got %d pages, want 1", len(pages))
51 }
52 got := f.text(t, pages[0])
53
54 for _, want := range []string{"Notes", "A heading", "Plain then", "bold", "café."} {
55 if !strings.Contains(got, want) {
56 t.Errorf("copied text is missing %q; got %q", want, got)
57 }
58 }
59}
60
61// Bold and italic are separate font programs, not a synthesised slant,
62// so a document using both must embed both and a page must declare
63// both in its resources.
64func TestPDFEmbedsAFaceForEachStyleUsed(t *testing.T) {
65 js := `{"type":"doc","content":[{"type":"paragraph","content":[
66 {"type":"text","text":"regular "},
67 {"type":"text","text":"bold ","marks":[{"type":"strong"}]},
68 {"type":"text","text":"italic ","marks":[{"type":"em"}]},
69 {"type":"text","text":"mono","marks":[{"type":"font_mono"}]}
70 ]}]}`
71 data, _ := mustPDF(t, mustParse(t, "", js))
72 f := readPDF(t, data)
73
74 var descriptors, files int
75 for _, o := range f.objects {
76 if strings.Contains(o.dict, "/Type /FontDescriptor") {
77 descriptors++
78 if !strings.Contains(o.dict, "/FontFile2") {
79 t.Error("a font descriptor with no embedded font file")
80 }
81 }
82 if strings.Contains(o.dict, "/Length1") {
83 files++
84 }
85 }
86 // Regular, bold, italic and mono: four distinct faces. (The title
87 // is empty here, so nothing pulls in a bold serif of its own.)
88 if descriptors != 4 {
89 t.Errorf("got %d font descriptors, want 4 (regular, bold, italic, mono)", descriptors)
90 }
91 if files != descriptors {
92 t.Errorf("got %d embedded font files for %d descriptors", files, descriptors)
93 }
94}
95
96// The face a run is actually drawn in, read back off the paper: an
97// unmarked run in Carlito, the default (Paul, 2026-10-24); a
98// font_caladea run in Caladea; a font_serif run in Liberation Serif,
99// which is what that mark has always meant. /BaseFont is read out of the
100// file, and each named face must have its program embedded.
101func TestPDFDrawsTheDefaultFaceAndTheMarkedOnes(t *testing.T) {
102 js := `{"type":"doc","content":[
103 {"type":"paragraph","content":[{"type":"text","text":"Unmarked"}]},
104 {"type":"paragraph","content":[{"type":"text","text":"Cambria twin","marks":[{"type":"font_caladea"}]}]},
105 {"type":"paragraph","content":[{"type":"text","text":"Serif","marks":[{"type":"font_serif"}]}]}
106 ]}`
107 data, _ := mustPDF(t, mustParse(t, "", js))
108 f := readPDF(t, data)
109
110 faces := map[string]bool{}
111 for _, o := range f.objects {
112 for _, m := range regexp.MustCompile(`/FontName /[A-Z]{6}\+([^ />]+)[^>]*/FontFile2 \d+ 0 R`).FindAllStringSubmatch(o.dict, -1) {
113 faces[m[1]] = true
114 }
115 }
116 if len(faces) == 0 {
117 t.Fatal("the PDF embeds no faces at all — the font dictionaries were restructured and this test can no longer see what it is checking")
118 }
119 for _, want := range []string{"Carlito-Regular", "Caladea-Regular", "LiberationSerif-Regular"} {
120 if !faces[want] {
121 t.Errorf("%s is not embedded; the PDF embeds %v", want, sortedKeys(faces))
122 }
123 }
124 if len(faces) != 3 {
125 t.Errorf("the PDF embeds %v, want exactly the three faces the text is in", sortedKeys(faces))
126 }
127}
128
129func sortedKeys(m map[string]bool) []string {
130 out := make([]string, 0, len(m))
131 for k := range m {
132 out = append(out, k)
133 }
134 sort.Strings(out)
135 return out
136}
137
138// The embedded font must be a subset, not the whole face — an export
139// that embeds four full faces is a megabyte and a half of font for a
140// page of text.
141func TestPDFEmbedsSubsetsNotWholeFaces(t *testing.T) {
142 js := `{"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"Hello"}]}]}`
143 data, _ := mustPDF(t, mustParse(t, "", js))
144 f := readPDF(t, data)
145
146 found := false
147 for _, o := range f.objects {
148 if !strings.Contains(o.dict, "/Length1") {
149 continue
150 }
151 found = true
152 // Liberation Serif is about 385KB whole. A subset holding the
153 // glyphs of "Hello" plus loca and hmtx is far below a tenth of
154 // that; the threshold is deliberately loose so this fails on a
155 // subsetter that stopped subsetting, not on one that got a bit
156 // less efficient.
157 if len(o.stream) > 100_000 {
158 t.Errorf("embedded font is %d bytes — that is not a subset", len(o.stream))
159 }
160 if len(o.stream) < 1_000 {
161 t.Errorf("embedded font is %d bytes — that is too small to be a font", len(o.stream))
162 }
163 }
164 if !found {
165 t.Fatal("no embedded font file in the PDF")
166 }
167}
168
169// Text longer than a page has to become more pages, and no text may be
170// lost at the break.
171func TestPDFPaginatesLongDocuments(t *testing.T) {
172 var paras []string
173 for i := 0; i < 120; i++ {
174 paras = append(paras, `{"type":"paragraph","content":[{"type":"text","text":"Paragraph number `+
175 strings.Repeat("x", 3)+` of a document long enough to need more than one page."}]}`)
176 }
177 js := `{"type":"doc","content":[` + strings.Join(paras, ",") + `]}`
178
179 data, _ := mustPDF(t, mustParse(t, "Long", js))
180 f := readPDF(t, data)
181 pages := f.pages(t)
182 if len(pages) < 3 {
183 t.Fatalf("120 paragraphs produced %d pages", len(pages))
184 }
185
186 var all strings.Builder
187 for _, p := range pages {
188 all.WriteString(f.text(t, p))
189 }
190 if n := strings.Count(all.String(), "Paragraph number"); n != 120 {
191 t.Errorf("found %d paragraphs across %d pages, want 120", n, len(pages))
192 }
193}
194
195// A word wider than the text column must be broken rather than run off
196// the edge of the paper — a URL is the ordinary case.
197func TestPDFBreaksAWordTooLongForTheLine(t *testing.T) {
198 long := strings.Repeat("supercalifragilistic", 12)
199 js := `{"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"` + long + `"}]}]}`
200 data, _ := mustPDF(t, mustParse(t, "", js))
201 f := readPDF(t, data)
202 got := f.text(t, f.pages(t)[0])
203 if len(got) < len(long) {
204 t.Errorf("the long word lost characters: %d of %d survived", len(got), len(long))
205 }
206}
207
208// A character no core face has a glyph for must be reported, not
209// silently dropped — §11.2's degrade-loudly rule, and the only form of
210// infidelity this exporter can currently produce.
211func TestPDFReportsCharactersItHasNoGlyphFor(t *testing.T) {
212 js := `{"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"hello 漢字"}]}]}`
213 _, report := mustPDF(t, mustParse(t, "", js))
214 if report.Empty() {
215 t.Fatal("CJK is outside the core font set (§11.1) and must be reported as a substitution")
216 }
217 if !strings.Contains(report.String(), "漢") {
218 t.Errorf("report does not name the character: %s", report)
219 }
220}
221
222// The same document exported twice must produce the same bytes. Go's
223// map iteration is randomised, and a PDF whose object order varies run
224// to run cannot be diffed, cached or compared by anyone.
225func TestPDFIsDeterministic(t *testing.T) {
226 js := `{"type":"doc","content":[{"type":"paragraph","content":[
227 {"type":"text","text":"one "},
228 {"type":"text","text":"two","marks":[{"type":"strong"}]},
229 {"type":"text","text":" three","marks":[{"type":"font_sans"}]}
230 ]}]}`
231 doc := mustParse(t, "Same", js)
232 a, _ := mustPDF(t, doc)
233 b, _ := mustPDF(t, doc)
234 // bytes.Equal, NOT strings.EqualFold. This test compared with
235 // EqualFold and could not see what it claimed to: a PDF is mostly
236 // Flate-compressed, which is mostly invalid UTF-8, and every
237 // invalid byte decodes to U+FFFD on both sides — so two files whose
238 // compressed bodies differed byte-for-byte compared equal, in the
239 // test whose whole subject is bytes. The check answered "yes"
240 // because it could not see, which is the failure shape AGENTS.md
241 // names, in the one test written to rule it out.
242 if !bytes.Equal(a, b) {
243 t.Error("two exports of the same document produced different bytes")
244 }
245}
246
247// A run carrying two size marks at once — which ProseMirror's schema
248// forbids but a client posting raw Yjs bytes can still produce — must
249// resolve to the SAME size every time. styleFor picked one by ranging
250// a map and breaking, and Go randomises map order, so the same document
251// exported twice could differ. The test above cannot catch it (the
252// fixture has no such run), which is why this is its own case.
253func TestPDFIsDeterministicForARunWithTwoSizeMarks(t *testing.T) {
254 js := `{"type":"doc","content":[{"type":"paragraph","content":[
255 {"type":"text","text":"ambiguous","marks":[{"type":"size_sm"},{"type":"size_xl"}]}
256 ]}]}`
257 doc := mustParse(t, "Ambiguous", js)
258 first, _ := mustPDF(t, doc)
259 for i := 0; i < 8; i++ {
260 again, _ := mustPDF(t, doc)
261 if !bytes.Equal(first, again) {
262 t.Fatalf("export %d differed: a run with two size marks resolves nondeterministically", i+2)
263 }
264 }
265}
266
267// Every indirect reference in the file must resolve, and the trailer
268// must agree with the cross-reference table about how many objects
269// there are.
270//
271// This is where the honesty of this package's PDF testing sits. No
272// third-party reader has opened these files — none is available in
273// this build — so the reader in pdfread_test.go is both the writer's
274// only checker and something written by the same hand, which is
275// exactly the arrangement that can be consistently wrong. What this
276// test adds is the set of properties that do not depend on agreeing
277// with that reader: a dangling reference, an off-by-one /Size, or an
278// xref offset that points at the wrong object are the three ways a
279// hand-written PDF writer breaks a real reader, and none of them can
280// be true here without failing.
281func TestPDFStructureIsInternallyConsistent(t *testing.T) {
282 js := `{"type":"doc","content":[
283 {"type":"heading","attrs":{"level":1},"content":[{"type":"text","text":"H"}]},
284 {"type":"paragraph","content":[{"type":"text","text":"body","marks":[{"type":"strong"}]}]},
285 {"type":"blockquote","content":[{"type":"paragraph","content":[{"type":"text","text":"q"}]}]}
286 ]}`
287 data, _ := mustPDF(t, mustParse(t, "Structure", js))
288
289 // readPDF already follows every xref offset and fails if one does
290 // not land on the object it claims.
291 f := readPDF(t, data)
292
293 refRe := regexp.MustCompile(`(\d+) 0 R`)
294 for num, o := range f.objects {
295 for _, m := range refRe.FindAllStringSubmatch(o.dict, -1) {
296 target, _ := strconv.Atoi(m[1])
297 if _, ok := f.objects[target]; !ok {
298 t.Errorf("object %d references object %d, which does not exist", num, target)
299 }
300 }
301 }
302
303 var size int
304 if _, err := fmt.Sscanf(
305 string(data[bytes.LastIndex(data, []byte("trailer")):]), "trailer\n<< /Size %d", &size); err != nil {
306 t.Fatalf("unreadable trailer: %v", err)
307 }
308 if want := len(f.objects) + 1; size != want {
309 t.Errorf("trailer says /Size %d, the xref lists %d objects plus the free head", size, want)
310 }
311}
312
313func TestPDFCarriesTheTitleAsMetadata(t *testing.T) {
314 data, _ := mustPDF(t, mustParse(t, "Café notes", `{"type":"doc","content":[]}`))
315 f := readPDF(t, data)
316 found := false
317 for _, o := range f.objects {
318 if strings.Contains(o.dict, "/Producer") {
319 found = true
320 // UTF-16BE with a BOM: "C" is 0043.
321 if !strings.Contains(o.dict, "/Title <FEFF0043") {
322 t.Errorf("title is not UTF-16BE encoded: %s", o.dict)
323 }
324 }
325 }
326 if !found {
327 t.Error("no document information dictionary")
328 }
329}
330
331// Every item of an ordered list keeps its number, including the item
332// whose first line falls on a new page.
333//
334// That item used to lose its marker entirely: the marker was placed at
335// a cursor remembered before the item was laid out, guarded by a
336// comparison between an offset on the old page and one on the new,
337// which is meaningless — so when the guard failed nothing was drawn at
338// all. A missing "7." in a numbered list is a document saying something
339// its author did not write.
340func TestPDFNumbersEveryListItemAcrossAPageBreak(t *testing.T) {
341 const items = 70
342 var li []string
343 for i := 0; i < items; i++ {
344 li = append(li, `{"type":"list_item","content":[{"type":"paragraph","content":[`+
345 `{"type":"text","text":"An item with enough words in it that the list is taller than one page."}]}]}`)
346 }
347 js := `{"type":"doc","content":[{"type":"ordered_list","content":[` + strings.Join(li, ",") + `]}]}`
348
349 data, _ := mustPDF(t, mustParse(t, "", js))
350 f := readPDF(t, data)
351 pages := f.pages(t)
352 if len(pages) < 2 {
353 t.Fatalf("%d items produced %d pages; the test needs a page break to be meaningful", items, len(pages))
354 }
355
356 var all strings.Builder
357 for _, p := range pages {
358 all.WriteString(f.text(t, p))
359 }
360 text := all.String()
361 for n := 1; n <= items; n++ {
362 if !strings.Contains(text, strconv.Itoa(n)+".") {
363 t.Errorf("list item %d has no number in the exported PDF", n)
364 }
365 }
366}
367
368// Text inside a node this build has never heard of must reach the PDF,
369// the same guarantee the core and the Markdown writer make.
370func TestPDFKeepsTextInsideUnknownNodes(t *testing.T) {
371 js := `{"type":"doc","content":[
372 {"type":"table","content":[{"type":"paragraph","content":[{"type":"text","text":"kept"}]}]}
373 ]}`
374 data, _ := mustPDF(t, mustParse(t, "", js))
375 f := readPDF(t, data)
376 if got := f.text(t, f.pages(t)[0]); !strings.Contains(got, "kept") {
377 t.Errorf("text inside an unknown node was lost: %q", got)
378 }
379}
380
381// An empty document still has to be a valid one-page PDF rather than
382// an error or a zero-page file no reader will open.
383func TestPDFOfAnEmptyDocument(t *testing.T) {
384 data, _ := mustPDF(t, mustParse(t, "Untitled document", `{"type":"doc","content":[]}`))
385 f := readPDF(t, data)
386 if n := len(f.pages(t)); n != 1 {
387 t.Errorf("got %d pages, want 1", n)
388 }
389}
390
391// Lists and quotes have to reach the page with their markers and their
392// text — a bullet drawn at a negative x, or a marker skipped, is
393// invisible in a byte comparison.
394func TestPDFDrawsListMarkersAndQuotedText(t *testing.T) {
395 js := `{"type":"doc","content":[
396 {"type":"bullet_list","content":[
397 {"type":"list_item","content":[{"type":"paragraph","content":[{"type":"text","text":"One"}]}]}
398 ]},
399 {"type":"ordered_list","content":[
400 {"type":"list_item","content":[{"type":"paragraph","content":[{"type":"text","text":"First"}]}]}
401 ]},
402 {"type":"blockquote","content":[{"type":"paragraph","content":[{"type":"text","text":"Quoted"}]}]}
403 ]}`
404 data, _ := mustPDF(t, mustParse(t, "", js))
405 f := readPDF(t, data)
406 got := f.text(t, f.pages(t)[0])
407 for _, want := range []string{"•", "One", "1.", "First", "Quoted"} {
408 if !strings.Contains(got, want) {
409 t.Errorf("missing %q from the page; got %q", want, got)
410 }
411 }
412}
413
414// Where the ink actually starts.
415//
416// Every other test in this file asks what the PDF says; none of them
417// asked where it says it, and a whole-page horizontal offset shipped
418// through all of them — body text was drawn at x=0, flush against the
419// left edge of the paper, while line breaking still used the correct
420// 6.5in column, so every page also carried a two-inch gutter on the
421// right. The words all copied back out perfectly. That is exactly the
422// shape of defect a text-only assertion cannot see, which is why this
423// reads the text matrix (pdfread_test.go's runs) rather than the text.
424//
425// The three x-coordinates the layout computes are all here: the text
426// draw, the blockquote's rule, and the list marker. A list marker is
427// the one thing deliberately drawn to the LEFT of its own text — it
428// sits in the list's indent — so it is the tightest check that "no ink
429// in the margin" is a real bound rather than a slack one.
430func TestPDFStartsTextAtTheLeftMargin(t *testing.T) {
431 js := `{"type":"doc","content":[
432 {"type":"paragraph","content":[{"type":"text","text":"Body text."}]},
433 {"type":"bullet_list","content":[
434 {"type":"list_item","content":[{"type":"paragraph","content":[{"type":"text","text":"Item"}]}]}
435 ]},
436 {"type":"blockquote","content":[{"type":"paragraph","content":[{"type":"text","text":"Quoted"}]}]}
437 ]}`
438 // No title: the first thing drawn has to be the first paragraph,
439 // with nothing above it to borrow a position from.
440 data, _ := mustPDF(t, mustParse(t, "", js))
441 f := readPDF(t, data)
442 page := f.pages(t)[0]
443
444 runs := f.runs(t, page)
445 if len(runs) == 0 {
446 t.Fatal("nothing was drawn on the page")
447 }
448 if got := runs[0].text; got != "Body" {
449 t.Fatalf("the first drawn run is %q, want %q — this test is no longer looking at the paragraph it thinks it is", got, "Body")
450 }
451 if math.Abs(runs[0].x-export.MarginPt) > 0.01 {
452 t.Errorf("body text starts at x=%v, want the page margin %v", runs[0].x, export.MarginPt)
453 }
454
455 rules := f.rules(t, page)
456 if len(rules) != 1 {
457 t.Fatalf("got %d filled rectangles, want 1 (the blockquote's edge)", len(rules))
458 }
459 if math.Abs(rules[0].x-export.MarginPt) > 0.01 {
460 t.Errorf("the blockquote rule starts at x=%v, want the page margin %v", rules[0].x, export.MarginPt)
461 }
462
463 // Nothing at all may be drawn in the margin — including the bullet,
464 // which sits left of its own text and is the closest thing to the
465 // edge on the page.
466 for _, r := range runs {
467 if r.x < export.MarginPt-0.01 {
468 t.Errorf("%q is drawn at x=%v, inside the %v page margin", r.text, r.x, export.MarginPt)
469 }
470 }
471}
472
473// Shift+Enter's line break has to end the line in the PDF too — and
474// end only the line, not the block.
475//
476// This reads the positions rather than the text for the same reason
477// the margin test does: a dropped break loses no words at all, it just
478// runs two lines together, so a text-only assertion sees nothing wrong.
479// The two halves of the paragraph have to sit on different baselines
480// and both start at the left margin; the break must not indent, split
481// or paginate anything.
482func TestPDFEndsTheLineAtAHardBreak(t *testing.T) {
483 js := `{"type":"doc","content":[{"type":"paragraph","content":[
484 {"type":"text","text":"first"},
485 {"type":"hard_break"},
486 {"type":"text","text":"second"}
487 ]}]}`
488 data, _ := mustPDF(t, mustParse(t, "", js))
489 f := readPDF(t, data)
490 runs := f.runs(t, f.pages(t)[0])
491 if len(runs) != 2 {
492 t.Fatalf("got %d drawn runs, want 2 (%v)", len(runs), runs)
493 }
494 if runs[0].text != "first" || runs[1].text != "second" {
495 t.Fatalf("drew %q then %q, want %q then %q", runs[0].text, runs[1].text, "first", "second")
496 }
497 if runs[0].y == runs[1].y {
498 t.Errorf("both halves are on the same baseline (y=%v) — the break was dropped", runs[0].y)
499 }
500 // Down the page, by exactly one line, and back to the left margin:
501 // PDF's y grows upward, so the second line's baseline is lower.
502 if gap := runs[0].y - runs[1].y; math.Abs(gap-export.BodySizePt*export.BodyLeading) > 0.01 {
503 t.Errorf("the second line is %v below the first, want one line of %v",
504 gap, export.BodySizePt*export.BodyLeading)
505 }
506 if math.Abs(runs[1].x-export.MarginPt) > 0.01 {
507 t.Errorf("the line after the break starts at x=%v, want the margin %v", runs[1].x, export.MarginPt)
508 }
509}
510
511// Two breaks in a row leave a blank line between the two halves, the
512// way `<br><br>` does on screen — the second one has an empty line to
513// end, and ending an empty line is what a blank line is.
514func TestPDFDrawsABlankLineForConsecutiveHardBreaks(t *testing.T) {
515 js := `{"type":"doc","content":[{"type":"paragraph","content":[
516 {"type":"text","text":"first"},
517 {"type":"hard_break"},
518 {"type":"hard_break"},
519 {"type":"text","text":"second"}
520 ]}]}`
521 data, _ := mustPDF(t, mustParse(t, "", js))
522 f := readPDF(t, data)
523 runs := f.runs(t, f.pages(t)[0])
524 if len(runs) != 2 {
525 t.Fatalf("got %d drawn runs, want 2 (%v)", len(runs), runs)
526 }
527 want := 2 * export.BodySizePt * export.BodyLeading
528 if gap := runs[0].y - runs[1].y; math.Abs(gap-want) > 0.01 {
529 t.Errorf("the two halves are %v apart, want two lines (%v)", gap, want)
530 }
531}
532
533// --- paragraph alignment ---
534
535// alignmentLine is the three paragraphs these tests lay out: the same
536// tokens three times, once per alignment, so every position below is
537// read off the file rather than recomputed from pdf.go's own
538// arithmetic. A test that restated the formula would agree with the
539// code by construction and would have agreed with the wrong formula
540// just as readily.
541//
542// Two identical words with a space between them is deliberate: it makes
543// three drawn runs per line, and three runs are what let the left-
544// aligned copy hand over the line's width without this file measuring a
545// font. See lineWidthFrom.
546const alignmentLine = `{"type":"text","text":"Widthful Widthful"}`
547
548// lineWidthFrom derives the drawn width of an alignmentLine from a
549// LEFT-aligned copy of it, using nothing but the positions in the file.
550//
551// The three runs are the word, the space and the word again, each drawn
552// at the x the one before it ended at. So the first gap is the word's
553// width and the second is the space's, and the line is word + space +
554// word wide. Nothing here knows what face or size that was set in,
555// which is the point.
556func lineWidthFrom(t *testing.T, line []run) float64 {
557 t.Helper()
558 if len(line) != 3 {
559 t.Fatalf("expected 3 runs (word, space, word), got %d: %v", len(line), line)
560 }
561 word := line[1].x - line[0].x
562 space := line[2].x - line[1].x
563 return word + space + word
564}
565
566// Alignment in a PDF is arithmetic, not a property: a centred line has
567// to be measured and offset by hand. This is the test for the thing
568// that arithmetic is most likely to get wrong — offsetting against the
569// PAGE rather than against the text column.
570//
571// The two are an inch apart on each side, so a page-relative
572// implementation puts a right-aligned line's right edge an inch off the
573// right of the paper and every word of it into (or past) the margin.
574// Every assertion below is therefore about the content column: the box
575// between the two margins, which is the box the screen wraps text in
576// and the box `contentWidthPt` names.
577func TestPDFAlignsWithinTheContentWidthNotThePage(t *testing.T) {
578 js := `{"type":"doc","content":[
579 {"type":"paragraph","content":[` + alignmentLine + `]},
580 {"type":"paragraph","attrs":{"align":"center"},"content":[` + alignmentLine + `]},
581 {"type":"paragraph","attrs":{"align":"right"},"content":[` + alignmentLine + `]}
582 ]}`
583 data, _ := mustPDF(t, mustParse(t, "", js))
584 f := readPDF(t, data)
585 runs := f.runs(t, f.pages(t)[0])
586 if len(runs) != 9 {
587 t.Fatalf("got %d drawn runs, want 9 (three lines of three): %v", len(runs), runs)
588 }
589 left, centre, right := runs[0:3], runs[3:6], runs[6:9]
590
591 width := lineWidthFrom(t, left)
592 content := export.PageWidthPt - 2*export.MarginPt
593 if width <= 0 || width >= content {
594 t.Fatalf("the sample line measures %v against a %v content width — it must fit on one line, unwrapped, for the offsets below to mean anything", width, content)
595 }
596
597 // Left is unchanged: the default alignment is where text already
598 // was, and the whole feature has to cost an unaligned paragraph
599 // nothing.
600 if math.Abs(left[0].x-export.MarginPt) > 0.01 {
601 t.Errorf("the left-aligned line starts at x=%v, want the page margin %v", left[0].x, export.MarginPt)
602 }
603
604 // Centred: equal air on both sides of the text column. Stated as
605 // the two gaps rather than as a formula, because "the same distance
606 // from each margin" is what centred MEANS and a formula is only one
607 // way of arriving at it.
608 leftGap := centre[0].x - export.MarginPt
609 rightGap := (export.PageWidthPt - export.MarginPt) - (centre[0].x + width)
610 if math.Abs(leftGap-rightGap) > 0.01 {
611 t.Errorf("the centred line has %v of air on its left and %v on its right — centred against the page, not the text column?", leftGap, rightGap)
612 }
613
614 // Right: the line's right edge sits exactly on the right margin.
615 // This is the assertion a page-relative implementation fails by a
616 // whole inch.
617 if edge := right[0].x + width; math.Abs(edge-(export.PageWidthPt-export.MarginPt)) > 0.01 {
618 t.Errorf("the right-aligned line ends at x=%v, want the right margin %v", edge, export.PageWidthPt-export.MarginPt)
619 }
620
621 // And nothing ends up in either margin, on any of the three.
622 for _, r := range runs {
623 if r.x < export.MarginPt-0.01 {
624 t.Errorf("%q is drawn at x=%v, inside the %v left margin", r.text, r.x, export.MarginPt)
625 }
626 if r.x > export.PageWidthPt-export.MarginPt+0.01 {
627 t.Errorf("%q is drawn at x=%v, past the right margin %v", r.text, r.x, export.PageWidthPt-export.MarginPt)
628 }
629 }
630}
631
632// The column a line is centred in is the one it WRAPS in, which inside
633// a blockquote or a list is narrower than the content width and starts
634// further in. Getting this wrong is invisible at the top level and
635// obvious the moment anything is indented: text centred against the
636// full column inside a quote sits left of centre and can cross the
637// quote's own rule.
638//
639// The indent is read off the file too — it is whatever the quote's
640// left-aligned line was drawn at — so this stays a test of the
641// relationship rather than a second copy of the constant.
642func TestPDFAlignsInsideAQuoteAgainstTheIndentedColumn(t *testing.T) {
643 js := `{"type":"doc","content":[{"type":"blockquote","content":[
644 {"type":"paragraph","content":[` + alignmentLine + `]},
645 {"type":"paragraph","attrs":{"align":"center"},"content":[` + alignmentLine + `]},
646 {"type":"paragraph","attrs":{"align":"right"},"content":[` + alignmentLine + `]}
647 ]}]}`
648 data, _ := mustPDF(t, mustParse(t, "", js))
649 f := readPDF(t, data)
650 runs := f.runs(t, f.pages(t)[0])
651 if len(runs) != 9 {
652 t.Fatalf("got %d drawn runs, want 9 (three lines of three): %v", len(runs), runs)
653 }
654 left, centre, right := runs[0:3], runs[3:6], runs[6:9]
655
656 width := lineWidthFrom(t, left)
657 indent := left[0].x - export.MarginPt
658 if indent <= 0 {
659 t.Fatalf("the quoted line starts at x=%v, which is not indented past the %v margin — this test can no longer see what it is checking", left[0].x, export.MarginPt)
660 }
661 // The column runs from the indented left edge to the right margin.
662 columnStart := export.MarginPt + indent
663 columnEnd := export.PageWidthPt - export.MarginPt
664
665 leftGap := centre[0].x - columnStart
666 rightGap := columnEnd - (centre[0].x + width)
667 if math.Abs(leftGap-rightGap) > 0.01 {
668 t.Errorf("inside the quote the centred line has %v of air on its left and %v on its right — centred against the full content width rather than the indented column?", leftGap, rightGap)
669 }
670 if edge := right[0].x + width; math.Abs(edge-columnEnd) > 0.01 {
671 t.Errorf("inside the quote the right-aligned line ends at x=%v, want the right margin %v", edge, columnEnd)
672 }
673 if centre[0].x < columnStart-0.01 {
674 t.Errorf("the centred line starts at x=%v, left of the quote's own indent %v", centre[0].x, columnStart)
675 }
676}
677
678// The exporter is a second binary's worth of trust away from the core,
679// exactly as headingLevel's second clamp is — the JSON has crossed the
680// ABI by the time it gets here, and this package decodes whatever it is
681// handed. An alignment it does not know is dropped, and a dropped
682// alignment is left: the words land where they would have with no
683// attribute at all.
684func TestPDFDropsAnAlignmentItDoesNotKnow(t *testing.T) {
685 js := `{"type":"doc","content":[
686 {"type":"paragraph","attrs":{"align":"justify"},"content":[` + alignmentLine + `]},
687 {"type":"paragraph","attrs":{"align":"CENTER"},"content":[` + alignmentLine + `]},
688 {"type":"paragraph","attrs":{"align":"left"},"content":[` + alignmentLine + `]}
689 ]}`
690 data, _ := mustPDF(t, mustParse(t, "", js))
691 f := readPDF(t, data)
692 runs := f.runs(t, f.pages(t)[0])
693 if len(runs) != 9 {
694 t.Fatalf("got %d drawn runs, want 9: %v", len(runs), runs)
695 }
696 for i, line := range [][]run{runs[0:3], runs[3:6], runs[6:9]} {
697 if math.Abs(line[0].x-export.MarginPt) > 0.01 {
698 t.Errorf("line %d starts at x=%v, want the page margin %v — an alignment this build does not know must lay out as left", i, line[0].x, export.MarginPt)
699 }
700 }
701}
702
703// The PDF draws what it measured: kerned. Each glyph's own advance is
704// in the font's /W array, and the shaped one differs by a TJ adjustment
705// between glyphs, so "AVATAR" in Carlito carries adjustments and a run
706// in a pair-free string carries none. Without them the PDF would wrap
707// at the screen's line breaks and then draw the words wider than the
708// line it put them on.
709func TestPDFDrawsKernedText(t *testing.T) {
710 js := `{"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"AVATAR"}]}]}`
711 data, _ := mustPDF(t, mustParse(t, "", js))
712 f := readPDF(t, data)
713 content := f.content(t, f.pages(t)[0])
714 m := regexp.MustCompile(`\[([^\]]*)\] TJ`).FindStringSubmatch(content)
715 if m == nil {
716 t.Fatalf("no TJ in the page: %s", content)
717 }
718 if !regexp.MustCompile(`> -?[\d.]+ <`).MatchString(m[1]) {
719 t.Errorf("AVATAR is drawn with no kerning adjustments: %s", m[1])
720 }
721 if got := f.text(t, f.pages(t)[0]); got != "AVATAR" {
722 t.Errorf("the kerned run copies out as %q", got)
723 }
724}
725
726// The gate waits for what FacesUsed lists, so it must list every face
727// the document's marks and blocks put text or line boxes in, not just
728// the faces that happen to draw a glyph (branch review 3, finding 1).
729// A run of spaces in Caveat sets those spaces' widths; a marked hard
730// break and an empty heading set a line's height; the block's own face
731// is the strut every line box starts from.
732func TestFacesUsedCountsEveryFaceTheMarksAndBlocksUse(t *testing.T) {
733 doc := mustParse(t, "", `{"type":"doc","content":[
734 {"type":"paragraph","content":[
735 {"type":"text","text":"words"},
736 {"type":"text","text":" ","marks":[{"type":"font_caveat"}]},
737 {"type":"text","text":"more"},
738 {"type":"hard_break","marks":[{"type":"font_playfair"}]}
739 ]},
740 {"type":"heading","attrs":{"level":2}},
741 {"type":"blockquote","content":[{"type":"paragraph"}]}
742 ]}`)
743 got := map[string]bool{}
744 for f := range export.FacesUsed(doc) {
745 got[f.ID()] = true
746 }
747 for _, want := range []string{"carlito:r", "caveat:r", "playfair:r", "carlito:b", "carlito:i"} {
748 if !got[want] {
749 t.Errorf("FacesUsed leaves out %s; it has %v", want, got)
750 }
751 }
752}
753
754// FamiliesUsed is every family a document references, wrappers
755// included: bold Caveat is drawn in Caveat Bold, but its <span> is an
756// inline box in Caveat Regular (branch review 4). Two font marks on one
757// run nest as two spans, so both families are on screen. Code brings in
758// the code family; the default is always there.
759func TestFamiliesUsedCountsEveryFamilyReferenced(t *testing.T) {
760 doc := mustParse(t, "", `{"type":"doc","content":[
761 {"type":"paragraph","content":[
762 {"type":"text","text":"bold caveat","marks":[{"type":"font_caveat"},{"type":"strong"}]},
763 {"type":"text","text":"two","marks":[{"type":"font_inter"},{"type":"font_zilla"}]},
764 {"type":"text","text":"code","marks":[{"type":"code"}]}
765 ]}]}`)
766 var got []string
767 for f := range export.FamiliesUsed(doc) {
768 got = append(got, f.Key)
769 }
770 sort.Strings(got)
771 if strings.Join(got, " ") != "carlito caveat inter mono zilla" {
772 t.Errorf("FamiliesUsed is %v, want carlito caveat inter mono zilla", got)
773 }
774}
775
776// A code block's text is code, on screen (<pre><code>) and so in the
777// gate's families and on paper.
778func TestACodeBlockIsSetInTheCodeFamily(t *testing.T) {
779 doc := mustParse(t, "", `{"type":"doc","content":[{"type":"code_block","content":[{"type":"text","text":"x := 1"}]}]}`)
780 if !export.FamiliesUsed(doc)[fonts.Code] {
781 t.Error("a code block's family is not among the families the document uses")
782 }
783 faces := export.FacesUsed(doc)
784 if faces[fonts.Code.Face(false, false)] == 0 {
785 t.Errorf("a code block's text is not set in the code face: %v", faces)
786 }
787}
788
789// CodeNodes is the schema's code nodes, read from fixtures/schema.mjs
790// itself (Go cannot import it, so node prints them).
791func TestCodeNodesAreTheSchemasCodeNodes(t *testing.T) {
792 out, err := exec.Command("node", "--input-type=module", "-e",
793 `const { schema } = await import('../../fixtures/schema.mjs'); console.log(JSON.stringify(Object.values(schema.nodes).filter((n) => n.spec.code).map((n) => n.name).sort()))`).Output()
794 if err != nil {
795 t.Fatalf("node: %v", err)
796 }
797 var want []string
798 if err := json.Unmarshal(out, &want); err != nil {
799 t.Fatal(err)
800 }
801 var got []string
802 for k := range export.CodeNodes {
803 got = append(got, k)
804 }
805 sort.Strings(got)
806 if strings.Join(got, ",") != strings.Join(want, ",") {
807 t.Errorf("CodeNodes is %v, the schema's code nodes are %v", got, want)
808 }
809}
810