oficina / docs Public

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

Plain git — no account needed to clone.

Download

Download this file

1package export
2
3import (
4 "errors"
5 "sort"
6 "strconv"
7 "strings"
8
9 "github.com/carlosframework/docs/internal/fonts"
10 "github.com/carlosframework/docs/internal/pdf"
11)
12
13// The page, in points. These are the numbers views/show.html sets on
14// [docs-page] and [docs-text], restated here because the exporter has
15// to lay text out in Go and the browser has to lay it out in CSS, and
16// the two must agree about the shape of a page or the PDF is of a
17// different document.
18//
19// Restated, not shared: there is no mechanism today that lets one
20// definition drive both, and inventing one (rendering the stylesheet
21// from these constants) would put a template expansion in the path of
22// every page load to solve a problem a test can solve instead —
23// internal/docs's TestPageGeometryMatchesTheStylesheet reads show.html
24// and fails if the two ever drift.
25//
26// §11.3 wants the PDF to come from "the same box tree the screen
27// renders". That box tree is the layout engine's, and the layout
28// engine does not exist yet (spec §13). This is the honest version
29// until it does: one set of numbers, asserted equal in both places,
30// and line breaking that measures with the same font programs the
31// browser is served.
32const (
33 PageWidthPt = 8.5 * 72 // US Letter
34 PageHeightPt = 11 * 72
35 MarginPt = 72 // 1in
36 BodySizePt = 12
37 BodyLeading = 1.4 // line-height
38
39 contentWidthPt = PageWidthPt - 2*MarginPt
40 contentBottom = PageHeightPt - MarginPt
41)
42
43// Block-level proportions, all mirroring show.html's stylesheet. The
44// heading scale is h1 1.6em down to h4-h6 at 1em italic; a heading's
45// own margins are in its own em, exactly as CSS resolves them.
46var headingScale = map[int]float64{1: 1.6, 2: 1.3, 3: 1.1, 4: 1, 5: 1, 6: 1}
47
48const (
49 headingLeading = 1.3
50 headingSpaceAbove = 1.5 // em of the heading's own size
51 headingSpaceBelow = 0.5
52
53 // Zero, and named rather than deleted: a paragraph, a list and a
54 // list item all stack with no margin at all, the way show.html's
55 // own rules now say and for the reason its comment on them gives
56 // (Google Docs' "Normal text" is 0pt before and 0pt after, so
57 // consecutive paragraphs stack like lines). Keeping the constants
58 // and the l.space calls that read them keeps this file's mirror of
59 // the stylesheet complete — every block-level margin the screen has
60 // is named here — and keeps a future change to any of them one
61 // edit rather than a re-derivation.
62 paragraphSpaceBelow = 0.0 // em of body size
63
64 listIndentEm = 1.4 // padding-inline-start
65 listItemSpace = 0.0 // an li has no margin of its own
66 listSpaceBelow = 0.0
67
68 quoteSpaceAround = 1.0
69 quoteIndentEm = 1.0
70 quoteRulePt = 3 * 0.75 // 3px at 96dpi is 2.25pt
71 quoteGray = 0.29 // #4a4a4a
72 quoteRuleGray = 0.78 // #c8c8c8
73
74 codeScale = 0.85 // [docs-text] code { font-size: 0.85em }
75)
76
77// IndentStepPt is one indent level, in points: half an inch, which is
78// what Docs, Word and Pages all use. views/show.html states the same
79// step in inches (.docs-indent-N), and
80// TestPageGeometryMatchesTheStylesheet is what holds the two equal.
81// Written 36.0 rather than 36 so it is an untyped FLOAT constant. As an
82// integer it made TestPageGeometryMatchesTheStylesheet's
83// `IndentStepPt / 72` integer-divide to 0, and the test compared the
84// stylesheet's real 0.5in against a zero — reporting a disagreement
85// that did not exist, which is the more fortunate half of that mistake.
86// The other half is what the same expression would do in layout code.
87const IndentStepPt = 36.0
88
89// MaxIndent is the deepest level this exporter lays out. The core
90// clamps to the same number (core/src/fragment.rs's MAX_INDENT) and so
91// does the editor (fixtures/indent.mjs); clamping again here is
92// deliberate and matches what headingLevel already does — a document
93// must not indent one distance on screen and another on paper, and the
94// exporter does not get to assume the core it was fed by is this build.
95const MaxIndent = 8
96
97// IndentOf is the extra left inset a block asks for, in points.
98//
99// Exported for TestPageGeometryMatchesTheStylesheet, which compares it
100// against the stylesheet's own inches. Zero for an un-indented block,
101// which is every block in every document written before indent existed.
102func IndentOf(n Node) float64 {
103 level := n.Attrs.Indent
104 if level < 1 {
105 return 0
106 }
107 if level > MaxIndent {
108 level = MaxIndent
109 }
110 return float64(level) * IndentStepPt
111}
112
113// sizeScale is what each size mark multiplies the body size by. The
114// same numbers appear in show.html's .docs-size-* rules; the geometry
115// test holds them equal.
116var sizeScale = map[string]float64{"size_sm": 0.85, "size_lg": 1.25, "size_xl": 1.5}
117
118// sizePt is what each size mark means, absolutely, in points.
119//
120// ABSOLUTE, where sizeScale above was a multiplier, and the difference
121// is the point of the change rather than a tidy-up. A multiplier
122// compounds with a heading's own scale, so 14pt inside a heading came
123// out at 1.6 x 14 — which is not what anyone means by setting a run to
124// 14pt. views/show.html states the same numbers as absolute pt, and
125// TestPageGeometryMatchesTheStylesheet holds the two equal.
126//
127// The three legacy marks map onto the nearest ladder step: the old
128// scale was 0.85, 1.25 and 1.5 of a 12pt body, so 10.2, 15 and 18pt.
129// Ten and eighteen are exact; fifteen rounds to fourteen. sizeScale is
130// kept above only because SizeScale() is still exported for the
131// stylesheet comparison of the legacy rules, and deleting a used symbol
132// is a separate change.
133var sizePt = map[string]float64{
134 "size_8": 8,
135 "size_9": 9,
136 "size_10": 10,
137 "size_11": 11,
138 "size_14": 14,
139 "size_18": 18,
140 "size_24": 24,
141 "size_36": 36,
142 "size_48": 48,
143 "size_72": 72,
144 "size_sm": 10,
145 "size_lg": 14,
146 "size_xl": 18,
147}
148
149// sizeOrder is the order styleFor consults them in. A map has no order,
150// and this decision has to be the same on every run — see styleFor.
151//
152// The ladder comes before the three legacy names, so a run carrying
153// both a new mark and an old one is measured at the new one — the same
154// rule fixtures/sizes.mjs's sizeForMarks applies, stated in both places
155// because neither can import the other.
156var sizeOrder = []string{
157 "size_8", "size_9", "size_10", "size_11", "size_14",
158 "size_18", "size_24", "size_36", "size_48", "size_72",
159 "size_sm", "size_lg", "size_xl",
160}
161
162// SizePt is one size mark's absolute size in points, and whether it is
163// a mark this build knows.
164//
165// Two return values, unlike SizeScale below. That is BlockSpace's
166// reasoning rather than symmetry-breaking: SizeScale could report an
167// unknown mark as 0 because 0 is not a multiplier any real mark has, so
168// a wrong answer was conspicuous. Nothing protects a size the same way
169// — a misspelled mark returning a bare 0 would compare equal to nothing
170// in particular, and the geometry test would report agreement while
171// checking a size no document has.
172func SizePt(mark string) (float64, bool) {
173 pt, ok := sizePt[mark]
174 return pt, ok
175}
176
177// SizeMarks is every size mark this build measures, in the order
178// styleFor consults them. For internal/docs's tests, which hold this
179// list against the stylesheet's own rules and against
180// fixtures/sizes.mjs.
181func SizeMarks() []string { return append([]string(nil), sizeOrder...) }
182
183// SizeScale exposes one size mark's multiplier. It exists for
184// internal/docs's TestPageGeometryMatchesTheStylesheet, which is the
185// mechanism keeping these numbers equal to the ones in show.html —
186// an unknown mark returns 0, so a renamed mark fails that test loudly
187// rather than quietly comparing nothing.
188func SizeScale(mark string) float64 { return sizeScale[mark] }
189
190// BlockSpace exposes one block-level bottom margin, in em, for the same
191// test and the same reason: these three numbers restate show.html's
192// stylesheet and nothing but a test can hold them to it.
193//
194// Two return values, unlike SizeScale above, and that is not
195// symmetry-breaking for its own sake. SizeScale can report an unknown
196// mark as 0 because 0 is not a multiplier any real mark has, so the
197// wrong answer is conspicuous. Every one of these three margins IS
198// zero today, so a misspelled name returning a bare 0 would compare
199// equal to the right answer and the test would report nothing while
200// checking nothing.
201func BlockSpace(name string) (float64, bool) {
202 switch name {
203 case "paragraph":
204 return paragraphSpaceBelow, true
205 case "list":
206 return listSpaceBelow, true
207 case "list_item":
208 return listItemSpace, true
209 }
210 return 0, false
211}
212
213// FontCSSName is the CSS family name of the face this exporter lays a
214// run carrying these marks out in — no marks meaning an unmarked run,
215// which is the case that matters most, since it is what most of the
216// text in most documents is.
217//
218// It exists for internal/docs's TestPageGeometryMatchesTheStylesheet,
219// which is the only thing holding these faces equal to the
220// font-family declarations in views/show.html. Nothing else can: the
221// stylesheet is CSS in a template and this is a switch in Go, they name
222// the same faces in two languages, and a document paginates the same on
223// screen and on paper only while they agree.
224//
225// It resolves through styleFor rather than restating the answer, so it
226// reports what the exporter actually does and not what this file says
227// elsewhere that it does. A block context of scale 1 with no marks is
228// exactly an ordinary body paragraph.
229func FontCSSName(marks ...string) string {
230 m := make([]Mark, 0, len(marks))
231 for _, name := range marks {
232 m = append(m, Mark{Type: name})
233 }
234 return (&layout{}).styleFor(m, blockContext{scale: 1}).face.Family.CSSName()
235}
236
237// FacesUsed is every face a document's marks and blocks set it in, with
238// how many characters each draws: what the screen needs loaded before it
239// shows the document (NO-FOUT §2). A face counts even where it draws no
240// glyph: a run of spaces, a marked line break, a block's own face, all
241// set widths or line heights. The walk is the same styleFor the exporter
242// lays out with, so the two cannot disagree about which faces those are.
243// The title is chrome on screen, so a Document passed here has none.
244//
245// An empty document still has a caret, which is in the default regular.
246func FacesUsed(doc Document) map[*fonts.Face]int {
247 l := &layout{facesOnly: map[*fonts.Face]int{}}
248 l.facesOnly[fonts.Default.Face(false, false)] += 0
249 for _, n := range doc.Root.Content {
250 l.block(n, blockContext{scale: 1})
251 }
252 return l.facesOnly
253}
254
255// CodeNodes is every node type whose text is set in the code family: the
256// schema's nodes with code: true (fixtures/schema.mjs).
257// TestCodeNodesAreTheSchemasCodeNodes holds this to the schema, so a node
258// type added there cannot be set in the code face on screen while the
259// gate and the PDF set it in the body face.
260var CodeNodes = map[string]bool{"code_block": true}
261
262// FamiliesUsed is every family a document references anywhere: the
263// default, which every block's strut and every unmarked run is in; each
264// font mark on any run or line break, including one wrapped round
265// another mark (its <span> is an inline box in that family's regular,
266// whatever the text inside is drawn in); and the code family if any run
267// is code. The page gate waits for every style of each, so no
268// combination of marks, wrappers and blocks can paint a face that has
269// not loaded (branch review 4, which found the wrapper case after the
270// review before found a space-only run: the class, not the instance).
271func FamiliesUsed(doc Document) map[*fonts.Family]bool {
272 used := map[*fonts.Family]bool{fonts.Default: true}
273 var walk func(nodes []Node)
274 walk = func(nodes []Node) {
275 for _, n := range nodes {
276 if CodeNodes[n.Type] {
277 used[fonts.Code] = true
278 }
279 for _, m := range n.Marks {
280 if key, ok := strings.CutPrefix(m.Type, "font_"); ok {
281 if f, ok := fonts.ByKey(key); ok {
282 used[f] = true
283 }
284 }
285 if m.Type == "code" {
286 used[fonts.Code] = true
287 }
288 }
289 walk(n.Content)
290 }
291 }
292 walk(doc.Root.Content)
293 return used
294}
295
296// Lines is the text of every line the PDF of doc sets, in order, with
297// the spaces a line ends on removed. It exists so a test can hold the
298// exporter's line breaks against the browser's.
299func Lines(doc Document) []string {
300 var out []string
301 l := &layout{
302 b: pdf.New(PageWidthPt, PageHeightPt),
303 missing: map[rune]bool{},
304 shaper: fonts.NewShaper(),
305 lineText: func(s string) {
306 out = append(out, s)
307 },
308 }
309 l.newPage()
310 l.document(doc)
311 return out
312}
313
314// Report is what an export could not do faithfully — §11.2's
315// degrade-loudly rule, in the one form this exporter can currently
316// fail: a character none of the core faces has a glyph for. A document
317// in an unshipped script (§11.1 puts CJK and the wider locale set
318// outside the core payload) exports with .notdef boxes, and the person
319// who asked for it is entitled to know that rather than discover it.
320type Report struct {
321 // MissingRunes is sorted and deduplicated.
322 MissingRunes []rune
323 // LayoutOverflow reports text beyond its available line width. Ordinary
324 // export remains permissive; contract previews must refuse this report.
325 // Empty retains its existing meaning: no glyph substitutions.
326 LayoutOverflow bool
327}
328
329// Empty reports whether the export was fully faithful.
330func (r Report) Empty() bool { return len(r.MissingRunes) == 0 }
331
332// String renders the report, naming the characters.
333//
334// NOT for a log line, and not for an error a handler returns. This
335// renders document content, and spec §2.1's leak list (item 5) is
336// categorical that neither may carry any: an instance's logs reach the
337// platform's own store, and for a short document in an unshipped script
338// the deduplicated set of its characters approximates the document
339// itself. Use Blocks below for anything that leaves the process. This
340// exists for a test, and for the import/export report §11.2 describes —
341// a screen shown to the person whose document it already is.
342func (r Report) String() string {
343 if r.Empty() {
344 return "no substitutions"
345 }
346 var b strings.Builder
347 b.WriteString("no glyph for: ")
348 for i, ru := range r.MissingRunes {
349 if i > 0 {
350 b.WriteString(" ")
351 }
352 b.WriteString(strconv.QuoteRune(ru))
353 }
354 return b.String()
355}
356
357// Blocks names the Unicode blocks the missing characters fall in,
358// sorted and deduplicated — what an operator can act on (which faces to
359// add) with nothing of the document in it.
360//
361// Coarse on purpose. A block name is a property of the script, not of
362// the text: "CJK" says add a CJK face, and says it whether the document
363// was one character or ten thousand.
364func (r Report) Blocks() []string {
365 seen := map[string]bool{}
366 var out []string
367 for _, ru := range r.MissingRunes {
368 name := unicodeBlock(ru)
369 if !seen[name] {
370 seen[name] = true
371 out = append(out, name)
372 }
373 }
374 sort.Strings(out)
375 return out
376}
377
378// unicodeBlock is a deliberately coarse bucketing — enough to say which
379// face is missing, not enough to say anything about the text. Ranges
380// are the common scripts a document might arrive in; anything else is
381// reported by plane, which still names no character.
382func unicodeBlock(r rune) string {
383 switch {
384 case r < 0x0250:
385 return "Latin"
386 case r >= 0x0370 && r <= 0x03FF:
387 return "Greek"
388 case r >= 0x0400 && r <= 0x04FF:
389 return "Cyrillic"
390 case r >= 0x0590 && r <= 0x05FF:
391 return "Hebrew"
392 case r >= 0x0600 && r <= 0x06FF:
393 return "Arabic"
394 case r >= 0x0900 && r <= 0x097F:
395 return "Devanagari"
396 case r >= 0x0E00 && r <= 0x0E7F:
397 return "Thai"
398 case r >= 0x1100 && r <= 0x11FF, r >= 0xAC00 && r <= 0xD7AF:
399 return "Hangul"
400 case r >= 0x3040 && r <= 0x30FF:
401 return "Kana"
402 case r >= 0x3400 && r <= 0x9FFF, r >= 0xF900 && r <= 0xFAFF:
403 return "CJK"
404 case r >= 0x2000 && r <= 0x2BFF:
405 return "Punctuation and symbols"
406 case r > 0xFFFF:
407 return "Supplementary planes"
408 }
409 return "Other"
410}
411
412// style is one run's resolved typography.
413type style struct {
414 face *fonts.Face
415 size float64 // points
416 gray float64
417}
418
419// blockContext is what a block inherits from the blocks it sits
420// inside: an indent, and whether it is inside a blockquote (which
421// makes its text italic and grey, and draws a rule beside every line).
422type blockContext struct {
423 // indent is EXTRA indent beyond the page margin, never an absolute
424 // x — a blockquote's or a list's own inset, and zero for ordinary
425 // body text. MarginPt is added at draw time, in the three places
426 // below that compute an x. Keeping it relative is what makes
427 // `maxWidth := contentWidthPt - ctx.indent` in paragraph correct:
428 // contentWidthPt is already the column between the two margins, so
429 // an absolute indent would subtract the left margin from the
430 // column a second time and wrap every line an inch early.
431 indent float64
432 quoted bool
433 // align is "", alignCentre or alignRight — the block's own
434 // alignment, already through document.go's allowlist. Empty is
435 // left, which is where text is drawn when nobody has said
436 // otherwise.
437 align string
438 // scale multiplies the base font size — headings set it for their
439 // own content.
440 scale float64
441 bold bool
442 italic bool
443 // code is a code block's: every run in it is set as code.
444 code bool
445}
446
447// PDF lays a document out and returns the file.
448func PDF(doc Document) ([]byte, Report, error) {
449 return renderPDF(doc, 0)
450}
451
452// ErrPageLimit means a bounded export did not fit. No truncated PDF is returned.
453var ErrPageLimit = errors.New("pdf: page limit exceeded")
454
455// PDFBounded bounds page allocation for interactive contract previews.
456// Normal exports continue to use PDF without this cap.
457func PDFBounded(doc Document, maxPages int) ([]byte, Report, error) {
458 if maxPages <= 0 {
459 return nil, Report{}, ErrPageLimit
460 }
461 return renderPDF(doc, maxPages)
462}
463
464func renderPDF(doc Document, maxPages int) ([]byte, Report, error) {
465 l := &layout{
466 b: pdf.New(PageWidthPt, PageHeightPt),
467 missing: map[rune]bool{},
468 shaper: fonts.NewShaper(),
469 stopAfterPage: maxPages,
470 }
471 l.b.Title = doc.Title
472 l.newPage()
473 l.document(doc)
474 if l.stopped {
475 return nil, l.report(), ErrPageLimit
476 }
477
478 out, err := l.b.Bytes()
479 if err != nil {
480 return nil, Report{}, err
481 }
482 return out, l.report(), nil
483}
484
485// document lays out a whole Document: its title, then its content.
486//
487// Shared by PDF and PageOne rather than written out in both, so a
488// change to what a first page contains reaches the thumbnail too. The
489// two did duplicate it, which meant something added here would have
490// reached the thumbnail only if it happened to move a run in the
491// agreement test's fixture.
492//
493// The title is set as a level-1 heading at the top of the first page.
494// It is not part of the CRDT and so not part of the box tree the
495// screen renders — the screen puts it in the shell bar beside the
496// brand link, which is chrome around the paper rather than on it (it
497// was a page header until the chrome moved to the topbar shell; either
498// way it is not on the paper). A PDF has no chrome: a file that does
499// not say which document it is, is worse than one that occasionally
500// repeats a heading its author also typed. Markdown does the same
501// thing for the same reason.
502//
503// A caller wanting the paper WITHOUT that chrome — the document list's
504// thumbnail does, and preview.go says why — passes a Document with an
505// empty Title, which is why this branches rather than always laying
506// one.
507func (l *layout) document(doc Document) {
508 if doc.Title != "" {
509 l.block(Node{
510 Type: "heading",
511 Attrs: Attrs{Level: 1},
512 Content: []Node{{Type: "text", Text: doc.Title}},
513 }, blockContext{scale: 1})
514 }
515 for _, n := range doc.Root.Content {
516 l.block(n, blockContext{scale: 1})
517 }
518}
519
520type layout struct {
521 b *pdf.Builder
522 page *pdf.Page
523
524 // cursor is the distance from the top of the page to the top of
525 // the next line box. Measuring downward from the top is how the
526 // document itself is shaped; PDF's own origin is at the bottom
527 // left, and the single conversion happens at draw time.
528 cursor float64
529
530 // pending is the collapsed margin waiting to be applied before the
531 // next block — CSS collapses adjacent vertical margins to the
532 // larger of the two, and a paragraph after a heading must not get
533 // both margins stacked.
534 pending float64
535
536 // atPageTop suppresses a collapsed margin at the top of a page and
537 // at the very start of the document, mirroring show.html's
538 // `[docs-text] > :first-child { margin-block-start: 0 }`.
539 atPageTop bool
540
541 // captureNextLine asks drawLine to record where the next line it
542 // draws actually landed — the page and the offset down it. A list
543 // item needs that to put its marker beside its own first line,
544 // which may be on a page the item did not start on. Cleared by the
545 // capture; capturedPage nil means no line was drawn.
546 captureNextLine bool
547 capturedPage *pdf.Page
548 capturedTop float64
549
550 // sink, when set, is told where every line box landed as it is
551 // placed (pageone.go). PDF export leaves it nil, and leaves
552 // stopAfterPage 0, so no guard below ever fires and no PDF byte
553 // moves.
554 //
555 // That is a claim by inspection, and it is worth being straight
556 // about what does and does not hold it. A test that exported the
557 // same document before and after a PageOne run was written for
558 // exactly this and then deleted: the two calls share no state, so
559 // only a package-level global could ever have made it red. It
560 // passed unchanged while a deliberate `l.cursor += 100` inside
561 // this block reddened the agreement test — a check that could not
562 // distinguish "no" from "I can't see it" (AGENTS.md). What covers
563 // the exporter is its own suite, which measures real output, and
564 // TestPageOneMatchesTheFirstPageOfThePDF for the reverse
565 // direction.
566 sink func(LineBox)
567
568 // pages counts the pages started so far, and stopAfterPage — zero
569 // for "never stop", which is every PDF export — ends the layout
570 // once that many are complete. Nothing is drawn or reported after
571 // stopped is set, so a caller that wants one page pays for one page
572 // of layout rather than for all of a long document's.
573 pages int
574 stopAfterPage int
575 stopped bool
576 layoutOverflow bool
577
578 missing map[rune]bool
579
580 // shaper kerns and ligates every word the way the browser does.
581 shaper *fonts.Shaper
582
583 // facesOnly, when set, turns the layout into FacesUsed's walk: every
584 // run's face is counted and nothing is measured or drawn.
585 facesOnly map[*fonts.Face]int
586
587 // lineText, when set, is told each drawn line's text (Lines).
588 lineText func(string)
589}
590
591// shape is one word in one style, kerned. A face that will not shape
592// (internal/fonts' own tests prove none of the embedded ones fails)
593// measures as nothing rather than failing the export.
594func (l *layout) shape(s string, st style) fonts.Run {
595 if l.shaper == nil {
596 l.shaper = fonts.NewShaper()
597 }
598 run, err := l.shaper.Shape(st.face, s)
599 if err != nil {
600 return fonts.Run{}
601 }
602 return run
603}
604
605// textWidth measures a string in points.
606func (l *layout) textWidth(s string, st style) float64 {
607 return l.shape(s, st).Width * st.size
608}
609
610func (l *layout) newPage() {
611 if l.stopAfterPage > 0 && l.pages >= l.stopAfterPage {
612 // The page just finished was the last one asked for. Stop
613 // before allocating another: every drawing path checks stopped
614 // and returns, so the layout unwinds without drawing again.
615 l.stopped = true
616 return
617 }
618 l.pages++
619 l.page = l.b.AddPage()
620 l.cursor = MarginPt
621 l.pending = 0
622 l.atPageTop = true
623}
624
625func (l *layout) report() Report {
626 out := Report{LayoutOverflow: l.layoutOverflow}
627 for r := range l.missing {
628 out.MissingRunes = append(out.MissingRunes, r)
629 }
630 sort.Slice(out.MissingRunes, func(i, j int) bool { return out.MissingRunes[i] < out.MissingRunes[j] })
631 return out
632}
633
634// space queues a vertical margin, collapsed against whatever is
635// already queued.
636func (l *layout) space(pt float64) {
637 if pt > l.pending {
638 l.pending = pt
639 }
640}
641
642// applyPending consumes the queued margin. At the top of a page it is
643// dropped rather than applied, which is both what the stylesheet says
644// for the first child and what stops a page break from opening with a
645// band of white the reader cannot account for.
646func (l *layout) applyPending() {
647 if !l.atPageTop {
648 l.cursor += l.pending
649 }
650 l.pending = 0
651}
652
653// block lays out one node.
654func (l *layout) block(n Node, ctx blockContext) {
655 if l.stopped {
656 return
657 }
658 switch kindOf(n) {
659 case blockHeading:
660 level := headingLevel(n)
661 scale := headingScale[level]
662 size := BodySizePt * scale
663 l.space(size * headingSpaceAbove)
664 hctx := ctx
665 // The block's own indent, ADDED to whatever a surrounding quote
666 // or list has already inset. ctx.indent is extra indent beyond
667 // the page margin (see its own comment), so accumulating is
668 // exactly right: an indented paragraph inside a list sits in
669 // from the list's marker, not back at the page edge.
670 hctx.indent += IndentOf(n)
671 hctx.scale = scale
672 hctx.bold = true
673 // h4-h6 are italic in the stylesheet — they are the same size
674 // as body text, so slope is the only thing distinguishing
675 // them.
676 hctx.italic = ctx.italic || level >= 4
677 l.paragraph(n.Content, hctx, size*headingLeading)
678 l.space(size * headingSpaceBelow)
679
680 case blockParagraph:
681 // Alignment is the paragraph's own, never inherited from the
682 // block around it: a centred paragraph inside a quote is
683 // centred, and its neighbours in that quote are not.
684 pctx := ctx
685 pctx.align = alignOf(n)
686 pctx.indent += IndentOf(n)
687 l.paragraph(n.Content, pctx, BodySizePt*ctx.scale*BodyLeading)
688 l.space(BodySizePt * paragraphSpaceBelow)
689
690 case blockBulletList:
691 l.list(n, ctx, false)
692
693 case blockOrderedList:
694 l.list(n, ctx, true)
695
696 case blockQuote:
697 l.space(BodySizePt * quoteSpaceAround)
698 inner := ctx
699 inner.indent += BodySizePt * quoteIndentEm
700 inner.quoted = true
701 inner.italic = true
702 for i, child := range n.Content {
703 l.block(child, inner)
704 if i == len(n.Content)-1 {
705 // The quote's own bottom margin replaces the last
706 // child's, rather than stacking with it.
707 l.pending = 0
708 }
709 }
710 l.space(BodySizePt * quoteSpaceAround)
711
712 case blockListItem:
713 // A list item outside a list — not producible through
714 // ProseMirror's schema, but a client can post any Yjs bytes it
715 // likes. Laid out as its own content rather than dropped.
716 for _, child := range n.Content {
717 l.block(child, ctx)
718 }
719
720 case blockCode:
721 // A code block's every run is code: the <pre><code> the screen
722 // draws it as.
723 cctx := ctx
724 cctx.code = true
725 l.paragraph(n.Content, cctx, BodySizePt*ctx.scale*BodyLeading)
726 l.space(BodySizePt * paragraphSpaceBelow)
727
728 default:
729 if n.IsText() {
730 l.paragraph([]Node{n}, ctx, BodySizePt*ctx.scale*BodyLeading)
731 l.space(BodySizePt * paragraphSpaceBelow)
732 return
733 }
734 // An unknown element: lay out its children. Same rule as the
735 // core's renderers and the Markdown writer — never lose the
736 // words.
737 for _, child := range n.Content {
738 l.block(child, ctx)
739 }
740 }
741}
742
743func (l *layout) list(list Node, ctx blockContext, ordered bool) {
744 inner := ctx
745 inner.indent += BodySizePt * listIndentEm
746
747 for i, item := range list.Content {
748 marker := "• " // bullet
749 if ordered {
750 marker = strconv.Itoa(i+1) + ". "
751 }
752 l.applyPending()
753 // The marker sits in the list's own indent, to the left of the
754 // item's text, on the item's FIRST line — wherever that line
755 // actually ends up. captureNextLine asks the line-drawer to
756 // report the page and offset of the next line it draws, which
757 // is the only way to know: the item's content may push onto a
758 // new page before its first line is placed, and the marker has
759 // to follow it there.
760 //
761 // This was a guess before — the marker was drawn at the cursor
762 // remembered before the item was laid out, guarded by a
763 // comparison between an offset on the old page and one on the
764 // new. When an item's first block landed on the next page that
765 // guard failed and the marker was drawn nowhere at all: in an
766 // ordered list, a silently missing number, in a file whose own
767 // module rule is never to lose the words.
768 markerStyle := l.styleFor(nil, inner)
769 if l.facesOnly != nil {
770 l.facesOnly[markerStyle.face] += len(marker)
771 }
772 l.captureNextLine = true
773
774 for j, child := range item.Content {
775 l.block(child, inner)
776 if j == len(item.Content)-1 {
777 l.pending = 0
778 }
779 }
780 l.captureNextLine = false
781
782 // An item that drew no line at all (empty content) gets no
783 // marker, which is right: there is nothing for it to sit
784 // beside.
785 if l.capturedPage != nil {
786 asc, _ := ascentDescent(markerStyle)
787 baseline := l.capturedTop + halfLeading(markerStyle, BodySizePt*BodyLeading) + asc
788 run := l.shape(marker, markerStyle)
789 l.draw(l.capturedPage, MarginPt+inner.indent-run.Width*markerStyle.size, baseline, markerStyle, run)
790 l.capturedPage = nil
791 }
792 l.space(BodySizePt * listItemSpace)
793 }
794 l.pending = 0
795 l.space(BodySizePt * listSpaceBelow)
796}
797
798// token is one word or one run of whitespace, with the style it is set
799// in. Splitting into tokens before wrapping is what lets a line break
800// fall between two runs with different marks — "very **bold** words"
801// wraps between "very" and "bold" like any other text.
802type token struct {
803 text string
804 st style
805 space bool
806 width float64
807 // brk is a hard break (core/src/fragment.rs's `hard_break`,
808 // Shift+Enter, `<br>` on screen): not a word and not whitespace,
809 // but a place the line must end. It carries a style because an
810 // empty line still has a height, and that height comes from the
811 // run the break sits in.
812 brk bool
813 // run is the word shaped in its style: what width measures and what
814 // draw sets, so a line is drawn exactly as it was measured.
815 run fonts.Run
816}
817
818// paragraph lays out a run of inline content as wrapped lines.
819func (l *layout) paragraph(content []Node, ctx blockContext, lineHeight float64) {
820 if l.facesOnly != nil {
821 // The block's own face is the strut every one of its line boxes
822 // starts from, so it sets the line's height even where no glyph
823 // of it is drawn: an empty paragraph, an empty heading.
824 l.facesOnly[l.styleFor(nil, ctx).face] += 0
825 l.tokenize(content, ctx)
826 return
827 }
828 tokens := l.tokenize(content, ctx)
829 if len(tokens) == 0 {
830 // An empty paragraph is a blank line on screen (fragment_html
831 // preserves `<p></p>`), so it is one here too.
832 l.applyPending()
833 l.advance(lineHeight, ctx)
834 return
835 }
836
837 maxWidth := contentWidthPt - ctx.indent
838 if maxWidth <= 0 {
839 l.layoutOverflow = true
840 }
841 var line []token
842 var lineWidth float64
843
844 flush := func() {
845 for len(line) > 0 && line[len(line)-1].space {
846 line = line[:len(line)-1]
847 }
848 if len(line) == 0 {
849 return
850 }
851 l.drawLine(line, ctx, lineHeight)
852 line = nil
853 lineWidth = 0
854 }
855
856 for _, t := range tokens {
857 if t.brk {
858 // The line ends here and the block carries on. A break
859 // with nothing on the line yet still consumes a line box —
860 // that is what makes two breaks in a row a blank line, the
861 // same as `<br><br>` on screen — and it goes through
862 // applyPending/advance rather than flush, which draws
863 // nothing when the line is empty.
864 if len(line) == 0 {
865 l.applyPending()
866 l.advance(lineHeight, ctx)
867 continue
868 }
869 flush()
870 continue
871 }
872 if t.space {
873 if len(line) == 0 {
874 continue // a line never opens with a space
875 }
876 line = append(line, t)
877 lineWidth += t.width
878 continue
879 }
880 if lineWidth+t.width > maxWidth && len(line) > 0 {
881 flush()
882 }
883 // A single word wider than the whole line: break it. Letting
884 // it overflow would run it off the edge of the paper, where a
885 // URL or a long identifier is exactly the case that produces
886 // one.
887 for t.width > maxWidth {
888 head, rest := l.splitToWidth(t, maxWidth)
889 if head.text == "" {
890 break // cannot make progress; draw it and overflow
891 }
892 l.drawLine([]token{head}, ctx, lineHeight)
893 t = rest
894 }
895 line = append(line, t)
896 lineWidth += t.width
897 }
898 flush()
899}
900
901// drawLine places one assembled line and moves the cursor past it.
902func (l *layout) drawLine(line []token, ctx blockContext, lineHeight float64) {
903 if l.stopped {
904 return
905 }
906 l.applyPending()
907 if l.cursor+lineHeight > contentBottom {
908 l.newPage()
909 if l.stopped {
910 return
911 }
912 }
913 if l.captureNextLine {
914 l.capturedPage = l.page
915 l.capturedTop = l.cursor
916 l.captureNextLine = false
917 }
918
919 // The baseline sits where CSS puts it: the text's own content box
920 // is centred in the line box (half the leading above, half below),
921 // and the baseline is one ascent down from the top of that box.
922 // Getting this from real font metrics rather than a fraction of
923 // the line height is what makes a heading in the PDF sit where the
924 // heading on screen sits.
925 var ascent, descent float64
926 for _, t := range line {
927 a, d := ascentDescent(t.st)
928 if a > ascent {
929 ascent = a
930 }
931 if d > descent {
932 descent = d
933 }
934 }
935 baseline := l.cursor + (lineHeight-(ascent+descent))/2 + ascent
936
937 if ctx.quoted {
938 // One rule segment per line, so a quote that breaks across a
939 // page gets a rule on both halves and none in the gap.
940 l.page.Rule(MarginPt+ctx.indent-BodySizePt*quoteIndentEm, PageHeightPt-l.cursor-lineHeight,
941 quoteRulePt, lineHeight, quoteRuleGray)
942 }
943
944 // Alignment is arithmetic here, not a CSS property: the line has
945 // already been measured, so an offset is all a centred or
946 // right-aligned line is.
947 //
948 // The width it is offset within is the COLUMN, not the page:
949 // contentWidthPt is already the box between the two margins, and
950 // ctx.indent takes off whatever a quote or a list has inset on top
951 // of that. It is the identical expression `paragraph` wraps to
952 // (`maxWidth := contentWidthPt - ctx.indent`), and it has to be —
953 // a line centred in one box and wrapped in another is centred
954 // wrong by exactly the difference. Offsetting against PageWidthPt
955 // instead would put a right-aligned line's right edge an inch off
956 // the paper.
957 x := MarginPt + ctx.indent
958 var measuredWidth float64
959 for _, t := range line {
960 measuredWidth += t.width
961 }
962 // A tiny tolerance absorbs floating-point sums, not a visible glyph.
963 if measuredWidth > contentWidthPt-ctx.indent+0.001 {
964 l.layoutOverflow = true
965 }
966 if ctx.align != "" {
967 var lineWidth float64
968 for _, t := range line {
969 lineWidth += t.width
970 }
971 free := (contentWidthPt - ctx.indent) - lineWidth
972 // A line wider than its column (one unbreakable word that
973 // splitToWidth could not make progress on) would otherwise be
974 // pushed LEFT of the margin by a negative offset. Overflowing
975 // to the right is what the left-aligned case already does with
976 // it, and it keeps the rule that nothing is ever drawn in the
977 // margin.
978 if free > 0 {
979 switch ctx.align {
980 case alignCentre:
981 x += free / 2
982 case alignRight:
983 x += free
984 }
985 }
986 }
987 if l.sink != nil {
988 // Reported from inside drawLine, after alignment has been
989 // resolved and before the pen moves, so what the sink hears is
990 // where the line really went — not where a second pass would
991 // calculate that it ought to have gone.
992 var width, size float64
993 for _, t := range line {
994 width += t.width
995 if t.st.size > size {
996 size = t.st.size
997 }
998 }
999 l.sink(LineBox{Left: x, Top: l.cursor, Width: width, Height: lineHeight, Size: size})
1000 }
1001
1002 var text strings.Builder
1003 for _, t := range line {
1004 l.draw(l.page, x, baseline, t.st, t.run)
1005 x += t.width
1006 text.WriteString(t.text)
1007 }
1008 if l.lineText != nil {
1009 l.lineText(text.String())
1010 }
1011 l.cursor += lineHeight
1012 l.atPageTop = false
1013}
1014
1015// advance moves past a line box without drawing anything — an empty
1016// paragraph.
1017func (l *layout) advance(lineHeight float64, ctx blockContext) {
1018 if l.stopped {
1019 return
1020 }
1021 if l.cursor+lineHeight > contentBottom {
1022 l.newPage()
1023 if l.stopped {
1024 return
1025 }
1026 }
1027 l.cursor += lineHeight
1028 l.atPageTop = false
1029}
1030
1031// draw is the one place a top-down cursor becomes a PDF coordinate.
1032func (l *layout) draw(page *pdf.Page, x, baselineFromTop float64, st style, run fonts.Run) {
1033 if err := page.Text(x, PageHeightPt-baselineFromTop, st.face, st.size, st.gray, run); err != nil {
1034 // Text only fails if a face will not parse, which
1035 // internal/fonts' own test proves cannot happen for the twelve
1036 // embedded ones. Dropping the run rather than failing the
1037 // whole export: a PDF missing one run is recoverable by the
1038 // person reading it, a 500 on export is not.
1039 return
1040 }
1041 for _, r := range run.Missing {
1042 l.missing[r] = true
1043 }
1044}
1045
1046// tokenize flattens inline content into words and spaces.
1047func (l *layout) tokenize(content []Node, ctx blockContext) []token {
1048 var out []token
1049 var walk func(nodes []Node)
1050 walk = func(nodes []Node) {
1051 for _, n := range nodes {
1052 if n.Type == "hard_break" {
1053 out = append(out, token{brk: true, st: l.styleFor(n.Marks, ctx)})
1054 if l.facesOnly != nil {
1055 l.facesOnly[l.styleFor(n.Marks, ctx).face] += 0
1056 }
1057 // Children are impossible through the editor's schema
1058 // and possible through raw Yjs bytes; laid out rather
1059 // than lost, as everywhere else in this package.
1060 walk(n.Content)
1061 continue
1062 }
1063 if !n.IsText() {
1064 walk(n.Content)
1065 continue
1066 }
1067 if n.Text == "" {
1068 continue
1069 }
1070 st := l.styleFor(n.Marks, ctx)
1071 for _, piece := range splitWords(n.Text) {
1072 if l.facesOnly != nil {
1073 // Every run's face, spaces included: a space set in
1074 // Caveat is Caveat's width, and moves every word after
1075 // it when Caveat arrives (branch review 3). Only
1076 // glyphs count towards which faces are preloaded.
1077 n := 0
1078 if !piece.space {
1079 n = len([]rune(piece.text))
1080 }
1081 l.facesOnly[st.face] += n
1082 continue
1083 }
1084 run := l.shape(piece.text, st)
1085 out = append(out, token{
1086 text: piece.text,
1087 st: st,
1088 space: piece.space,
1089 width: run.Width * st.size,
1090 run: run,
1091 })
1092 }
1093 }
1094 }
1095 walk(content)
1096 return out
1097}
1098
1099type piece struct {
1100 text string
1101 space bool
1102}
1103
1104// splitWords divides a run into alternating words and whitespace,
1105// keeping both — the whitespace has a width and has to be measured,
1106// and its width depends on the style it is set in.
1107func splitWords(s string) []piece {
1108 var out []piece
1109 var cur strings.Builder
1110 inSpace := false
1111 for _, r := range s {
1112 isSpace := r == ' ' || r == '\t' || r == '\n' || r == '\r'
1113 if cur.Len() > 0 && isSpace != inSpace {
1114 out = append(out, piece{text: cur.String(), space: inSpace})
1115 cur.Reset()
1116 }
1117 inSpace = isSpace
1118 cur.WriteRune(r)
1119 }
1120 if cur.Len() > 0 {
1121 out = append(out, piece{text: cur.String(), space: inSpace})
1122 }
1123 return out
1124}
1125
1126// splitToWidth cuts a token at the last character that fits.
1127func (l *layout) splitToWidth(t token, maxWidth float64) (head, rest token) {
1128 runes := []rune(t.text)
1129 for i := 1; i < len(runes); i++ {
1130 w := l.textWidth(string(runes[:i+1]), t.st)
1131 if w > maxWidth {
1132 h := token{text: string(runes[:i]), st: t.st}
1133 h.run = l.shape(h.text, h.st)
1134 h.width = h.run.Width * h.st.size
1135 r := token{text: string(runes[i:]), st: t.st}
1136 r.run = l.shape(r.text, r.st)
1137 r.width = r.run.Width * r.st.size
1138 return h, r
1139 }
1140 }
1141 return t, token{st: t.st}
1142}
1143
1144// styleFor resolves a run's marks and its block context into a face, a
1145// size and a colour. This is the mirror of show.html's stylesheet, and
1146// the order matters: the block's own scale first, then a size mark,
1147// then code's own reduction — the same order the cascade applies them
1148// in.
1149func (l *layout) styleFor(marks []Mark, ctx blockContext) style {
1150 has := func(name string) bool {
1151 for _, m := range marks {
1152 if m.Type == name {
1153 return true
1154 }
1155 }
1156 return false
1157 }
1158
1159 // fonts.ForMarks, not a face named here: an unmarked run is
1160 // whatever the manifest's default is, which is also what the
1161 // generated stylesheet's [docs-text] rule sets, and a run with two
1162 // font marks (only raw Yjs bytes can make one) resolves the way the
1163 // cascade does.
1164 names := make([]string, len(marks))
1165 for i, m := range marks {
1166 names[i] = m.Type
1167 }
1168 family := fonts.ForMarks(names)
1169
1170 size := BodySizePt * ctx.scale
1171 // sizeOrder, not a range over the sizeScale map. A run carrying two
1172 // size marks is impossible through the editor's schema (they
1173 // exclude each other) but perfectly possible through
1174 // POST /d/{sqid}/updates, which takes raw Yjs bytes — and ranging a
1175 // map with a break picks whichever Go's randomised iteration
1176 // reached first, so the same document exported twice could differ.
1177 // A fixed order makes the choice arbitrary but stable, which is
1178 // what determinism needs.
1179 //
1180 // (The screen compounds such a run instead — nested spans multiply
1181 // — so the two disagree for a document neither can be produced by
1182 // the editor. Noted rather than reconciled: making them agree means
1183 // deciding what two sizes at once MEANS, which is a schema
1184 // question.)
1185 for _, mark := range sizeOrder {
1186 if has(mark) {
1187 // SET, not multiplied. A size mark now names an absolute
1188 // point size, so it REPLACES the size the context would
1189 // otherwise have given this run — including a heading's
1190 // scale. That is what a person means by setting a run to
1191 // 14pt, and it is the one behavioural difference between
1192 // this ladder and the four-step scale it replaced.
1193 size, _ = SizePt(mark)
1194 break
1195 }
1196 }
1197
1198 bold := ctx.bold || has("strong")
1199 italic := ctx.italic || has("em")
1200
1201 if has("code") || ctx.code {
1202 // A code run is monospace and smaller, whatever else it says —
1203 // exactly as the stylesheet's `[docs-text] code` rule wins over
1204 // the inherited family. The background tint the screen draws
1205 // behind it is not reproduced: a filled rectangle behind every
1206 // code run would have to be measured and drawn per line
1207 // fragment, and its absence costs a reader nothing a PDF is
1208 // for.
1209 family = fonts.Code
1210 size *= codeScale
1211 }
1212
1213 gray := 0.0
1214 if ctx.quoted {
1215 gray = quoteGray
1216 }
1217 return style{face: family.Face(bold, italic), size: size, gray: gray}
1218}
1219
1220// ascentDescent is the face's own vertical extent at this size, in
1221// points. Descent comes back positive — the table stores it negative,
1222// and every caller here wants a height.
1223func ascentDescent(st style) (ascent, descent float64) {
1224 font, err := st.face.Parsed()
1225 if err != nil {
1226 return st.size * 0.8, st.size * 0.2
1227 }
1228 upm := float64(font.UnitsPerEm)
1229 return float64(font.Ascender) / upm * st.size, -float64(font.Descender) / upm * st.size
1230}
1231
1232// halfLeading is the space CSS puts above the text's content box
1233// inside a taller line box.
1234func halfLeading(st style, lineHeight float64) float64 {
1235 a, d := ascentDescent(st)
1236 return (lineHeight - (a + d)) / 2
1237}
1238