oficina / slides Public

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

Plain git — no account needed to clone.

Download

Download this file

1// export.go turns a deck into a PDF (spec §4.3): one 1920 by 1080 pt
2// page per slide, and when asked, the speaker notes as a page after
3// each slide.
4//
5// The pipeline is the one the plan's global constraints lay down and
6// nothing here shortcuts it: layout.Layout draws each slide into a
7// paint list, svg.Encode writes that paint list as an SVG, and the Rust
8// module under internal/slides/pdfcore turns the SVGs into a PDF with
9// the text as glyphs from the same faces the layout engine measured
10// with: the Liberation set, and any static TrueType face uploaded to
11// the deck that its stacks name first. The PDF path never reads a
12// deck; a notes page is a paint list too, built here from the notes
13// text and typeset with the same fonts package, so it goes through the
14// same two steps.
15//
16// # Self-contained
17//
18// A PDF is a file somebody emails. Every image is inlined into its
19// page's SVG before the module sees it, and an image that cannot be
20// inlined — the bytes are not there, or are not a picture this build
21// can decode, or are bigger than the cap — is left out with a Warning
22// that says so, never replaced by a URL the reader's machine would have
23// to fetch. Images are downscaled to maxImageEdge on the long edge
24// first (§4.3), because a 6000 px photograph on a 1920 pt page is bytes
25// nobody sees.
26//
27// The routes, the job and the status page are in the export handlers;
28// this file is the function they call.
29package slides
30
31import (
32 "bytes"
33 "context"
34 "errors"
35 "fmt"
36 "image"
37 "image/draw"
38 "image/jpeg"
39 "image/png"
40 "strings"
41
42 // The decoders Assets can hand back. Registering them is what makes
43 // image.Decode recognise the bytes; a format nobody registered is
44 // "not a picture this build can decode" and is dropped with a
45 // warning rather than sent to the module, which would fail the
46 // whole render on it (core/pdf/src/lib.rs).
47 _ "image/gif"
48
49 // WebP is one of the four types the upload path admits (§2.7):
50 // registering the decoder is what sends it down the
51 // decode-and-re-encode path below, where it comes out as a PNG.
52 // Without it a picture somebody uploaded from a phone was simply
53 // missing from their handout. (krilla-svg does decode WebP, unlike
54 // the svg2pdf it replaced, so the re-encode is belt and braces on
55 // the PDF side now; dropping it is its own change, with its own
56 // tests, not a side effect of swapping the converter.)
57 _ "golang.org/x/image/webp"
58
59 "amadan.net/oficina/slides/internal/slides/deck"
60 "amadan.net/oficina/slides/internal/slides/fonts"
61 "amadan.net/oficina/slides/internal/slides/layout"
62 "amadan.net/oficina/slides/internal/slides/pdfcore"
63 "amadan.net/oficina/slides/internal/slides/svg"
64)
65
66// MaxExportSlides is the most slides one export will take (§4.3). A
67// deck past it is refused before any work is done, with
68// ErrTooManySlides.
69const MaxExportSlides = 200
70
71// ErrTooManySlides is Export's refusal of a deck over MaxExportSlides.
72var ErrTooManySlides = errors.New("slides: the deck has more slides than an export will take")
73
74// maxExportAsset bounds one image's stored bytes: 20 MiB, the plan's
75// cap. Bigger is dropped with a warning, not decoded.
76const maxExportAsset = 20 << 20
77
78// maxImagePixels bounds what one image is allowed to decode to. The
79// byte cap above says nothing about pixels — a 20 MiB PNG can be a
80// hundred thousand pixels a side — and decoding is where the memory
81// goes. Fifty megapixels is an 8000 by 6000 photograph; anything larger
82// is dropped with a warning. One budget with the thumbnail's and the
83// agent upload's (svg.MaxDecodePixels).
84const maxImagePixels = svg.MaxDecodePixels
85
86// maxImageEdge is the long edge an inlined image is scaled down to
87// (§4.3). Slightly over the page's own 1920, so a full-bleed picture is
88// not upscaled by the reader.
89const maxImageEdge = 2000
90
91// ExportOptions is what Export needs beyond the deck.
92type ExportOptions struct {
93 // WithNotes puts a page of speaker notes after every slide (a slide
94 // with long notes gets more than one). Every slide gets one, notes
95 // or not, so the pages pair up slide, notes, slide, notes all the
96 // way through and a printed handout is predictable.
97 WithNotes bool
98
99 // Assets returns an image's stored bytes and MIME type by the
100 // deck's asset id (layout.Image.Asset). It is the caller's because
101 // where the bytes live — the object store, a directory — is the
102 // app's business and not the PDF's. ok=false is "not available",
103 // which is a warning and an omitted image. nil means no image can
104 // be fetched at all: every image is omitted, each with a warning.
105 Assets func(asset string) (data []byte, mime string, ok bool)
106
107 // Runtime is the compiled PDF module this export renders through.
108 // Required. Compiling one costs the best part of a second and a
109 // Runtime is safe for concurrent use, so it belongs to whatever
110 // owns the process — the app builds one and closes it (exports.go's
111 // pdfRuntime), a test builds one per package — and never to a
112 // single export. Nil is an error rather than a module compiled
113 // here: a function that quietly compiles a wasm module per call is
114 // a function whose cost nobody can see.
115 Runtime *pdfcore.Runtime
116
117 // Progress, when set, is called before each slide is laid out, with
118 // the slide's 1-based number and the total. It is how an export
119 // running as a job tells its status page how far along it is. The
120 // words are the caller's: they are a person's words, and this
121 // package has no locale.
122 Progress func(slide, total int)
123
124 // Fonts reads a face uploaded to the deck by its ref
125 // (deck.FontFace.Ref) — the app's object store, as Assets is. Nil
126 // reads none: every uploaded family falls back to the rest of its
127 // stack, in the pages and the PDF alike (layout.Options.Fonts).
128 Fonts func(ref string) ([]byte, error)
129
130 // QR is the follow-along codes the pages may draw
131 // (layout.Options.QR): the app's followCodes for a member. Nil draws
132 // none.
133 QR map[string]string
134}
135
136// Export renders d as a PDF. The warnings are everything worth telling
137// the person who asked — a block that overflowed, an image that was
138// left out, a character no face can draw — and never stop the export;
139// the error is what does: a deck over MaxExportSlides, a renderer that
140// refused or trapped, a deadline.
141func Export(ctx context.Context, d *deck.Deck, o ExportOptions) ([]byte, []layout.Warning, error) {
142 if d == nil {
143 return nil, nil, errors.New("slides: export: no deck")
144 }
145 d = d.ForReaders()
146 if len(d.Slides) > MaxExportSlides {
147 return nil, nil, fmt.Errorf("%w: %d slides, the most is %d", ErrTooManySlides, len(d.Slides), MaxExportSlides)
148 }
149 if len(d.Slides) == 0 {
150 return nil, nil, errors.New("slides: export: the deck has no slides")
151 }
152 if o.Runtime == nil {
153 return nil, nil, errors.New("slides: export: no PDF runtime (ExportOptions.Runtime)")
154 }
155
156 x := &exporter{deck: d, opts: o}
157 // One render for every page: each uploaded face is read and parsed
158 // once for the whole export, and dropped with it.
159 lay := layout.New(d, layout.Options{Fonts: o.Fonts, QR: o.QR})
160 var pages [][]byte
161 for i := range d.Slides {
162 if err := ctx.Err(); err != nil {
163 return nil, x.warnings, err
164 }
165 // The slide every warning from here on is about — the ones the
166 // layout engine stamps for itself, and the ones this file makes
167 // about an image it could not use.
168 x.slide = d.Slides[i].ID
169 if o.Progress != nil {
170 o.Progress(i+1, len(d.Slides))
171 }
172 p, warnings, err := lay.Layout(i)
173 if err != nil {
174 return nil, x.warnings, fmt.Errorf("slides: export: slide %d: %w", i+1, err)
175 }
176 x.warnings = append(x.warnings, warnings...)
177 title := slideTitle(d.Slides[i])
178 if title == "" {
179 title = d.Meta.Title
180 }
181 pages = append(pages, x.encode(p, title))
182 if o.WithNotes {
183 for _, np := range x.notesPages(d.Slides[i], title) {
184 pages = append(pages, x.encode(np, title))
185 }
186 }
187 }
188
189 var faces [][]byte
190 for _, f := range fonts.All() {
191 faces = append(faces, fonts.Data(f))
192 }
193 // The uploaded faces some run was drawn in, each renamed to the
194 // family the pages' SVG names it by: the module matches a
195 // font-family against the name inside the font (fonts.Renamed).
196 for _, u := range lay.Uploaded() {
197 b, err := u.Font.Renamed(u.CSS, u.Weight, u.Italic)
198 if err != nil {
199 return nil, x.warnings, fmt.Errorf("slides: export: %s: %w", u.CSS, err)
200 }
201 faces = append(faces, b)
202 }
203 pdf, err := o.Runtime.Render(ctx, pages, faces)
204 if err != nil {
205 return nil, x.warnings, fmt.Errorf("slides: export: %w", err)
206 }
207 return pdf, x.warnings, nil
208}
209
210// exporter is one Export call: the deck, the options, and what has
211// been noticed so far.
212type exporter struct {
213 deck *deck.Deck
214 opts ExportOptions
215 warnings []layout.Warning
216
217 // slide is the id of the slide being rendered, stamped onto every
218 // warning made here so the status page can say which slide lost
219 // its picture (layout.Warning.Slide).
220 slide string
221
222 // inlined caches an asset's inlined form for the length of one
223 // export, so a picture on ten slides is fetched and scaled once.
224 inlined map[string]inlinedImage
225}
226
227type inlinedImage struct {
228 data []byte
229 mime string
230 ok bool
231}
232
233func (x *exporter) warn(kind, block, detail string) {
234 x.warnings = append(x.warnings, layout.Warning{
235 Kind: kind, Slide: x.slide, Block: block, Detail: detail,
236 })
237}
238
239// encode writes one paint list as a self-contained SVG page.
240func (x *exporter) encode(p layout.Paint, title string) []byte {
241 return svg.Encode(p, svg.Options{
242 Title: title,
243 InlineImages: x.inline,
244 // No AssetURL: an image that is not inlined is not drawn. A URL
245 // in a PDF is a picture the reader's machine has to fetch, and
246 // the module would refuse it anyway.
247 })
248}
249
250// slideTitle is the slide's first heading, as plain text, or "".
251func slideTitle(s deck.Slide) string {
252 for _, b := range s.Blocks {
253 if b.Type == "heading" {
254 return strings.TrimSpace(b.Text.Plain())
255 }
256 }
257 return ""
258}
259
260// ── Images ───────────────────────────────────────────────────────────
261
262// inline is the svg.Options.InlineImages hook: the asset's bytes,
263// decoded, scaled down to maxImageEdge if they are bigger, and handed
264// back as a picture the PDF module accepts. ok=false is "leave it out",
265// and every path to it has already recorded why.
266func (x *exporter) inline(asset string) ([]byte, string, bool) {
267 if x.inlined == nil {
268 x.inlined = map[string]inlinedImage{}
269 }
270 if c, done := x.inlined[asset]; done {
271 return c.data, c.mime, c.ok
272 }
273 data, mime, ok := x.fetchImage(asset)
274 x.inlined[asset] = inlinedImage{data, mime, ok}
275 return data, mime, ok
276}
277
278func (x *exporter) fetchImage(asset string) ([]byte, string, bool) {
279 if x.opts.Assets == nil {
280 x.warn(layout.WarnAsset, "", fmt.Sprintf("image %q: no way to read assets was given; left out of the PDF", asset))
281 return nil, "", false
282 }
283 data, mime, ok := x.opts.Assets(asset)
284 if !ok {
285 x.warn(layout.WarnAsset, "", fmt.Sprintf("image %q could not be read; left out of the PDF", asset))
286 return nil, "", false
287 }
288 if len(data) > maxExportAsset {
289 x.warn(layout.WarnAsset, "", fmt.Sprintf("image %q is %d bytes, over the %d byte cap; left out of the PDF", asset, len(data), maxExportAsset))
290 return nil, "", false
291 }
292 if mime == "image/svg+xml" {
293 // A vector picture is already what the page is made of: the
294 // encoder nests it into the slide (it was sanitised on
295 // registration, svg.go). The one it will not nest is a picture
296 // carrying a stylesheet, which would restyle the slide around
297 // it; the encoder falls back to the asset's URL, and this
298 // export gives it none, so say why the picture is missing
299 // rather than letting it vanish.
300 if bytes.Contains(bytes.ToLower(data), []byte("<style")) {
301 x.warn(layout.WarnAsset, "", fmt.Sprintf("image %q is an SVG with a stylesheet, which cannot be nested into a page; left out of the PDF", asset))
302 return nil, "", false
303 }
304 return data, mime, true
305 }
306
307 cfg, format, err := image.DecodeConfig(bytes.NewReader(data))
308 if err != nil {
309 x.warn(layout.WarnAsset, "", fmt.Sprintf("image %q (%s) is not a picture this build can decode; left out of the PDF", asset, mime))
310 return nil, "", false
311 }
312 if cfg.Width <= 0 || cfg.Height <= 0 || cfg.Width*cfg.Height > maxImagePixels {
313 x.warn(layout.WarnAsset, "", fmt.Sprintf("image %q is %d by %d pixels, more than the PDF will take; left out", asset, cfg.Width, cfg.Height))
314 return nil, "", false
315 }
316 if max(cfg.Width, cfg.Height) <= maxImageEdge && (format == "png" || format == "jpeg" || format == "gif") {
317 // Small enough and in a format the module reads: the stored
318 // bytes go in untouched, which for a JPEG means DCTDecode
319 // passthrough rather than a second lossy generation.
320 return data, "image/" + format, true
321 }
322
323 img, _, err := image.Decode(bytes.NewReader(data))
324 if err != nil {
325 x.warn(layout.WarnAsset, "", fmt.Sprintf("image %q (%s) could not be decoded: %v; left out of the PDF", asset, mime, err))
326 return nil, "", false
327 }
328 scaled := downscale(img, maxImageEdge)
329 var buf bytes.Buffer
330 if format == "jpeg" {
331 // A photograph stays a photograph: JPEG in, JPEG out, at a
332 // quality the eye does not separate from the original on a
333 // page.
334 if err := jpeg.Encode(&buf, scaled, &jpeg.Options{Quality: 88}); err != nil {
335 x.warn(layout.WarnAsset, "", fmt.Sprintf("image %q could not be re-encoded: %v; left out of the PDF", asset, err))
336 return nil, "", false
337 }
338 return buf.Bytes(), "image/jpeg", true
339 }
340 if err := png.Encode(&buf, scaled); err != nil {
341 x.warn(layout.WarnAsset, "", fmt.Sprintf("image %q could not be re-encoded: %v; left out of the PDF", asset, err))
342 return nil, "", false
343 }
344 return buf.Bytes(), "image/png", true
345}
346
347// downscale returns img no larger than edge on its long side, or img
348// itself if it already is.
349//
350// A box filter, written here because golang.org/x/image/draw is not
351// the standard library and the stdlib's image/draw only copies. Each
352// target pixel is the mean of the source rectangle it covers, in
353// premultiplied RGBA so a transparent edge does not bleed its colour
354// into its neighbours. For a reduction — the only direction this is
355// used in — a box filter is the right filter: it is what "average the
356// pixels you are merging" means, and it does not ring.
357func downscale(img image.Image, edge int) image.Image {
358 b := img.Bounds()
359 sw, sh := b.Dx(), b.Dy()
360 if sw <= edge && sh <= edge {
361 return img
362 }
363 tw, th := edge, edge
364 if sw >= sh {
365 th = max(1, sh*edge/sw)
366 } else {
367 tw = max(1, sw*edge/sh)
368 }
369
370 src := image.NewRGBA(image.Rect(0, 0, sw, sh))
371 draw.Draw(src, src.Bounds(), img, b.Min, draw.Src)
372 dst := image.NewRGBA(image.Rect(0, 0, tw, th))
373 for ty := 0; ty < th; ty++ {
374 y0, y1 := ty*sh/th, (ty+1)*sh/th
375 if y1 <= y0 {
376 y1 = y0 + 1
377 }
378 for tx := 0; tx < tw; tx++ {
379 x0, x1 := tx*sw/tw, (tx+1)*sw/tw
380 if x1 <= x0 {
381 x1 = x0 + 1
382 }
383 var r, g, bl, a uint64
384 for y := y0; y < y1; y++ {
385 row := src.Pix[y*src.Stride+x0*4 : y*src.Stride+x1*4]
386 for i := 0; i < len(row); i += 4 {
387 r += uint64(row[i])
388 g += uint64(row[i+1])
389 bl += uint64(row[i+2])
390 a += uint64(row[i+3])
391 }
392 }
393 n := uint64((y1 - y0) * (x1 - x0))
394 o := ty*dst.Stride + tx*4
395 dst.Pix[o] = uint8((r + n/2) / n)
396 dst.Pix[o+1] = uint8((g + n/2) / n)
397 dst.Pix[o+2] = uint8((bl + n/2) / n)
398 dst.Pix[o+3] = uint8((a + n/2) / n)
399 }
400 }
401 return dst
402}
403
404// ── Notes pages ──────────────────────────────────────────────────────
405
406// The notes page's geometry, in the layout engine's own units (1920 by
407// 1080, the padded scale from layout/sizes.go: 1 cqw = 16.8 px inside a
408// section with the stylesheet's 6.25% padding). The sizes are the
409// stylesheet's t-3 and body-m, so a notes page reads as the deck's own
410// type rather than as a different document stapled to it.
411const (
412 notesPad = 0.0625 * layout.FrameW // --slides-pad
413 notesCqw = (layout.FrameW - 2*notesPad) / 100
414 notesTitle = 4.0 * notesCqw // --slides-t-3
415 notesBody = 2.8 * notesCqw // --slides-body-m
416 notesGap = 2.6 * notesCqw // --slides-gap, title to text
417 notesLead = 1.3 // the section's line-height
418 notesLeadT = 1.1 // a heading's line-height
419 notesParaGap = 0.6 // em between paragraphs, as slides.css
420 notesBg = layout.Fill("#ffffff")
421 notesFg = layout.Fill("#111111")
422)
423
424// notesPages typesets s's speaker notes: the slide's title at t-3, then
425// the notes at body-m in Liberation Sans, greedily wrapped and broken
426// across as many 1920 by 1080 pages as they need. A slide with no notes
427// still gets its page (see ExportOptions.WithNotes).
428//
429// Plain text: marks are dropped, as §2.6's notes are read aloud, not
430// looked at. Nothing is ever clipped — a word wider than the page runs
431// past the margin, the same rule the layout engine keeps.
432func (x *exporter) notesPages(s deck.Slide, title string) []layout.Paint {
433 titleFace := fonts.Face{Family: fonts.Sans, Bold: true}
434 bodyFace := fonts.Face{Family: fonts.Sans}
435 colW := layout.FrameW - 2*notesPad
436 bottom := layout.FrameH - notesPad
437
438 var pages []layout.Paint
439 cur := layout.Paint{W: layout.FrameW, H: layout.FrameH, Background: notesBg}
440 top := notesPad
441
442 // place puts one wrapped block on the page, breaking to a new page
443 // wherever the next line would cross the bottom margin.
444 place := func(lines []string, face fonts.Face, size, lead float64) {
445 asc, desc, _ := fonts.Metrics(face, size)
446 lineH := lead * size
447 for _, ln := range lines {
448 if top+lineH > bottom && len(cur.Ops) > 0 {
449 pages = append(pages, cur)
450 cur = layout.Paint{W: layout.FrameW, H: layout.FrameH, Background: notesBg}
451 top = notesPad
452 }
453 baseline := top + (lineH-(asc+desc))/2 + asc
454 if ln != "" {
455 cur.Ops = append(cur.Ops, layout.Text{X: notesPad, Y: baseline, Runs: []layout.Run{
456 {S: ln, Face: face, Size: size, Fill: notesFg},
457 }})
458 }
459 top += lineH
460 }
461 }
462
463 if title != "" {
464 place(x.wrapNotes(s.ID, title, titleFace, notesTitle, colW), titleFace, notesTitle, notesLeadT)
465 top += notesGap
466 }
467 for i, para := range s.Notes {
468 if i > 0 {
469 top += notesParaGap * notesBody
470 }
471 text := strings.TrimSpace(plainParagraph(para))
472 if text == "" {
473 // An empty paragraph is an empty line box, as <p></p> is.
474 top += notesLead * notesBody
475 continue
476 }
477 place(x.wrapNotes(s.ID, text, bodyFace, notesBody, colW), bodyFace, notesBody, notesLead)
478 }
479 return append(pages, cur)
480}
481
482// plainParagraph is one paragraph's runs concatenated, marks dropped.
483func plainParagraph(para []deck.Run) string {
484 var b strings.Builder
485 for _, r := range para {
486 b.WriteString(r.T)
487 }
488 return b.String()
489}
490
491// wrapNotes breaks text into lines no wider than w, greedily, measured
492// with the same fonts package the layout engine measures with. A rune
493// no face has a glyph for is reported once per slide.
494func (x *exporter) wrapNotes(block, text string, face fonts.Face, size, w float64) []string {
495 space, _ := fonts.Advance(face, size, " ")
496 var lines []string
497 var cur strings.Builder
498 var curW float64
499 var missing []rune
500 for _, word := range strings.Fields(text) {
501 ww, miss := fonts.Advance(face, size, word)
502 missing = append(missing, miss...)
503 switch {
504 case cur.Len() == 0:
505 cur.WriteString(word)
506 curW = ww
507 case curW+space+ww > w:
508 lines = append(lines, cur.String())
509 cur.Reset()
510 cur.WriteString(word)
511 curW = ww
512 default:
513 cur.WriteByte(' ')
514 cur.WriteString(word)
515 curW += space + ww
516 }
517 }
518 if cur.Len() > 0 {
519 lines = append(lines, cur.String())
520 }
521 if len(missing) > 0 {
522 seen := map[rune]bool{}
523 var fresh []string
524 for _, r := range missing {
525 if !seen[r] {
526 seen[r] = true
527 fresh = append(fresh, fmt.Sprintf("%q", r))
528 }
529 }
530 x.warn(layout.WarnGlyph, block, fmt.Sprintf(
531 "the notes use %s, which no embedded face has a glyph for; drawn at the width of a box",
532 strings.Join(fresh, ", ")))
533 }
534 return lines
535}
536