oficina / slides Public

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

Plain git — no account needed to clone.

Download

Download this file

1package fonts
2
3import (
4 "encoding/binary"
5 "fmt"
6 "sort"
7 "strings"
8 "unicode/utf16"
9)
10
11// uploaded.go is the one way a face outside this package's twelve
12// reaches the layout engine and the PDF: a static TrueType face a
13// person uploaded to a deck (meta.fontFiles), read and parsed for one
14// render and dropped with it. Nothing here caches one across renders —
15// the bytes are the person's, and they stay in the object store.
16
17// Uploaded is one uploaded face a picture can be drawn with: the CSS
18// family the deck names it by, the weight (400 or 700) and slope it is
19// set for, and the parsed font. Fallback is the rest of the deck's
20// stack after the uploaded name, as the deck wrote it, so a picture
21// names the stack the deck chose.
22type Uploaded struct {
23 CSS string
24 Weight int
25 Italic bool
26 Font *Font
27 Fallback string
28
29 // family is the faces of the same upload by slot (see slot), shared
30 // by all of them, so a face that turns bold or italic part-way
31 // through a paragraph finds its sibling — or finds there is none,
32 // and is drawn in the fallback.
33 family *[4]*Uploaded
34}
35
36func slot(bold, italic bool) int {
37 n := 0
38 if bold {
39 n |= 2
40 }
41 if italic {
42 n |= 1
43 }
44 return n
45}
46
47// UploadedFamily links the faces of one uploaded family (nil entries
48// are skipped) and returns one of them to put in Face.Uploaded, or nil
49// when there are none. Each face takes the slot its Weight and Italic
50// name; a second face for a slot already taken is ignored.
51func UploadedFamily(faces ...*Uploaded) *Uploaded {
52 family := new([4]*Uploaded)
53 var first *Uploaded
54 for _, u := range faces {
55 if u == nil {
56 continue
57 }
58 i := slot(u.Weight == 700, u.Italic)
59 if family[i] != nil {
60 continue
61 }
62 family[i] = u
63 u.family = family
64 if first == nil {
65 first = u
66 }
67 }
68 return first
69}
70
71// Upload is the uploaded face f is drawn in, or nil when it is drawn
72// in its Family. f.Uploaded names the uploaded family; which of its
73// faces is wanted depends on f.Bold and f.Italic, which a caller sets
74// after choosing the family (a bold run, an italic quote), so the
75// choice is made here, every time, rather than once.
76func (f Face) Upload() *Uploaded {
77 u := f.Uploaded
78 if u == nil {
79 return nil
80 }
81 if u.family != nil {
82 return u.family[slot(f.Bold, f.Italic)]
83 }
84 if u.Weight == f.Weight() && u.Italic == f.Italic {
85 return u
86 }
87 return nil
88}
89
90// Stack is the CSS font-family a picture writes for f. Drawn in an
91// upload, it is the deck's own stack — the uploaded family, then the
92// fallbacks the deck named after it — so a browser that has the font
93// shows it and one that does not falls back as the deck said. Drawn in
94// a built-in face, it is that face's stack, as it always was.
95func (f Face) Stack() string {
96 if u := f.Upload(); u != nil {
97 if u.Fallback == "" {
98 return "'" + u.CSS + "'"
99 }
100 return "'" + u.CSS + "', " + u.Fallback
101 }
102 return f.Family.Stack()
103}
104
105// Name is how a paint list writes f: the PostScript name of a built-in
106// face, or the uploaded family's CSS name with its weight and slope.
107func (f Face) Name() string {
108 u := f.Upload()
109 if u == nil {
110 return f.PostScriptName()
111 }
112 name := u.CSS + " 400"
113 if u.Weight == 700 {
114 name = u.CSS + " 700"
115 }
116 if u.Italic {
117 name += " italic"
118 }
119 return name
120}
121
122// font is the parsed font f measures with.
123func (f Face) font() (*Font, error) {
124 if u := f.Upload(); u != nil && u.Font != nil {
125 return u.Font, nil
126 }
127 return f.Parsed()
128}
129
130// Variable reports a variable font (one with an fvar table). The
131// layout engine measures a font at its default instance only, so a
132// variable face is never drawn with, whatever its upload record says.
133func (f *Font) Variable() bool {
134 _, ok := f.tables["fvar"]
135 return ok
136}
137
138// Embeddable reports whether the font's licence flags (OS/2 fsType)
139// let a PDF embed a subset of it: not restricted-licence (0x0002), not
140// "no subsetting" (0x0100), not bitmap-only (0x0200). A font without an
141// OS/2 table carries no restriction.
142func (f *Font) Embeddable() bool {
143 os2, ok := f.tables["OS/2"]
144 if !ok {
145 return true
146 }
147 if len(os2) < 10 {
148 return false
149 }
150 fsType := binary.BigEndian.Uint16(os2[8:])
151 return fsType&(0x0002|0x0100|0x0200) == 0
152}
153
154// Renamed is the whole font file with its family name replaced by
155// family and its OS/2 weight and slope set to weight and italic.
156//
157// The PDF module matches an SVG's font-family against the family name
158// inside each font it is given (core/pdf/src/lib.rs), case for case,
159// then weight and style. A picture names an uploaded face by the CSS
160// name the deck gave it, which need not be the name the font calls
161// itself — and the font's own name may even be one of the built-in
162// families. Renaming the copy handed to the PDF makes the two agree,
163// and keeps an upload from shadowing a built-in face. Every other name
164// stays, the PostScript name among them, which is what the PDF writes
165// as the face's /BaseFont.
166//
167// The copy is never more than twice the file (errTooLarge otherwise),
168// checked before anything is copied: a file whose tables share bytes
169// would otherwise be copied once per table that names them.
170func (f *Font) Renamed(family string, weight int, italic bool) ([]byte, error) {
171 tables := make(map[string][]byte, len(f.tables))
172 for tag, b := range f.tables {
173 tables[tag] = b
174 }
175 name, err := renameTable(f.tables["name"], family)
176 if err != nil {
177 return nil, err
178 }
179 tables["name"] = name
180 if os2 := f.restyled(weight, italic); os2 != nil {
181 tables["OS/2"] = os2
182 }
183 head := append([]byte(nil), tables["head"]...)
184 binary.BigEndian.PutUint32(head[8:], 0) // checkSumAdjustment, set by buildSfnt
185 tables["head"] = head
186 return buildSfnt(tables, 2*len(f.data))
187}
188
189// restyled is a copy of the font's OS/2 table with its weight and slope
190// set to weight and italic, or nil when it has none to copy.
191func (f *Font) restyled(weight int, italic bool) []byte {
192 os2, ok := f.tables["OS/2"]
193 if !ok || len(os2) < 64 {
194 return nil
195 }
196 os2 = append([]byte(nil), os2...)
197 binary.BigEndian.PutUint16(os2[4:], uint16(weight))
198 sel := binary.BigEndian.Uint16(os2[62:])
199 sel &^= 0x0001 | 0x0200 // italic, oblique
200 if italic {
201 sel |= 0x0001
202 }
203 binary.BigEndian.PutUint16(os2[62:], sel)
204 return os2
205}
206
207// WebSubset is a font a browser can load holding only the glyphs text
208// draws (Subset's, ids unchanged), called family, at weight and slope:
209// for a slide picture shown in an <img>, which sees none of the page's
210// fonts and so carries its uploaded faces itself (svg.Options.EmbedFonts;
211// final review, I2). To Subset's tables it adds the ones a browser's
212// font sanitiser requires: a cmap of text's characters to their glyphs,
213// the renamed name table, the OS/2 table restyled as Renamed does, and a
214// post table without glyph names. Never more than twice the file.
215func (f *Font) WebSubset(text, family string, weight int, italic bool) ([]byte, error) {
216 keep := map[uint16]bool{}
217 chars := map[rune]uint16{}
218 for _, r := range text {
219 if g := f.GlyphIndex(r); g != 0 {
220 keep[g] = true
221 chars[r] = g
222 }
223 }
224 tables, err := f.subsetTables(keep)
225 if err != nil {
226 return nil, err
227 }
228 if tables["name"], err = renameTable(f.tables["name"], family); err != nil {
229 return nil, err
230 }
231 os2 := f.restyled(weight, italic)
232 if os2 == nil {
233 return nil, fmt.Errorf("%w: OS/2", errNoTable)
234 }
235 tables["OS/2"] = os2
236 post := make([]byte, 32)
237 binary.BigEndian.PutUint32(post, 0x00030000) // version 3: no glyph names
238 if old := f.tables["post"]; len(old) >= 16 {
239 copy(post[4:16], old[4:16]) // italic angle, underline position and thickness
240 }
241 tables["post"] = post
242 tables["cmap"] = cmapOf(chars)
243 return buildSfnt(tables, 2*len(f.data))
244}
245
246// cmapOf is a cmap table mapping chars to their glyphs: a format 4
247// subtable (Windows, BMP) for the characters below U+FFFF, while they
248// fit one, and a format 12 subtable (Windows, full repertoire) for all.
249func cmapOf(chars map[rune]uint16) []byte {
250 runes := make([]rune, 0, len(chars))
251 for r := range chars {
252 runes = append(runes, r)
253 }
254 sort.Slice(runes, func(i, j int) bool { return runes[i] < runes[j] })
255
256 // Format 12: one group per character.
257 f12 := make([]byte, 16+12*len(runes))
258 binary.BigEndian.PutUint16(f12, 12)
259 binary.BigEndian.PutUint32(f12[4:], uint32(len(f12)))
260 binary.BigEndian.PutUint32(f12[12:], uint32(len(runes)))
261 for i, r := range runes {
262 at := 16 + 12*i
263 binary.BigEndian.PutUint32(f12[at:], uint32(r))
264 binary.BigEndian.PutUint32(f12[at+4:], uint32(r))
265 binary.BigEndian.PutUint32(f12[at+8:], uint32(chars[r]))
266 }
267
268 // Format 4: one segment per BMP character, then the 0xFFFF one.
269 var bmp []rune
270 for _, r := range runes {
271 if r < 0xFFFF {
272 bmp = append(bmp, r)
273 }
274 }
275 var f4 []byte
276 if n := len(bmp) + 1; 16+8*n <= 0xFFFF {
277 f4 = make([]byte, 16+8*n)
278 binary.BigEndian.PutUint16(f4, 4)
279 binary.BigEndian.PutUint16(f4[2:], uint16(len(f4)))
280 binary.BigEndian.PutUint16(f4[6:], uint16(2*n))
281 sel := 0
282 for 1<<(sel+1) <= n {
283 sel++
284 }
285 binary.BigEndian.PutUint16(f4[8:], uint16(2<<sel))
286 binary.BigEndian.PutUint16(f4[10:], uint16(sel))
287 binary.BigEndian.PutUint16(f4[12:], uint16(2*n-2<<sel))
288 ends, starts, deltas := 14, 16+2*n, 16+4*n // idRangeOffset stays 0
289 for i, r := range append(bmp, 0xFFFF) {
290 binary.BigEndian.PutUint16(f4[ends+2*i:], uint16(r))
291 binary.BigEndian.PutUint16(f4[starts+2*i:], uint16(r))
292 delta := uint16(1) // 0xFFFF to glyph 0
293 if r != 0xFFFF {
294 delta = chars[r] - uint16(r)
295 }
296 binary.BigEndian.PutUint16(f4[deltas+2*i:], delta)
297 }
298 }
299
300 type sub struct {
301 encoding uint16
302 data []byte
303 }
304 var subs []sub
305 if f4 != nil {
306 subs = append(subs, sub{1, f4})
307 }
308 subs = append(subs, sub{10, f12})
309 out := make([]byte, 4+8*len(subs))
310 binary.BigEndian.PutUint16(out[2:], uint16(len(subs)))
311 for i, s := range subs {
312 binary.BigEndian.PutUint16(out[4+8*i:], 3)
313 binary.BigEndian.PutUint16(out[4+8*i+2:], s.encoding)
314 binary.BigEndian.PutUint32(out[4+8*i+4:], uint32(len(out)))
315 out = append(out, s.data...)
316 }
317 return out
318}
319
320// nameRecord is one string of a name table.
321type nameRecord struct {
322 platform, encoding, language, id uint16
323 value []byte
324}
325
326// Bounds on a renamed name table: string offsets are 16 bits, and a
327// real table has a few dozen records.
328const (
329 maxNameStorage = 0xffff
330 maxNameRecords = 4096
331)
332
333// renameTable is a format 0 name table holding old's records except
334// its family names (1, 16 and 21), any language-tagged record and any
335// repeat of a record already kept, plus family as the Windows Unicode
336// English family name, and one PostScript name: old's (Windows English
337// first), or one made from family should old carry none, because a font
338// without one is a font the PDF module will not load.
339//
340// Every record counts against the bounds, the PostScript names among
341// them: old's records may share one string, and each is copied here, so
342// a table of a thousand records over one long string would otherwise
343// grow a thousandfold. The family and the one PostScript name go in
344// first; what does not fit after them is dropped.
345func renameTable(old []byte, family string) ([]byte, error) {
346 var recs []nameRecord
347 seen := map[[4]uint16]bool{}
348 if len(old) >= 6 {
349 count := int(binary.BigEndian.Uint16(old[2:]))
350 base := int(binary.BigEndian.Uint16(old[4:]))
351 for i := 0; i < count; i++ {
352 at := 6 + i*12
353 if at+12 > len(old) {
354 break
355 }
356 r := nameRecord{
357 platform: binary.BigEndian.Uint16(old[at:]),
358 encoding: binary.BigEndian.Uint16(old[at+2:]),
359 language: binary.BigEndian.Uint16(old[at+4:]),
360 id: binary.BigEndian.Uint16(old[at+6:]),
361 }
362 length := int(binary.BigEndian.Uint16(old[at+8:]))
363 off := base + int(binary.BigEndian.Uint16(old[at+10:]))
364 key := [4]uint16{r.platform, r.encoding, r.language, r.id}
365 if off+length > len(old) || r.language >= 0x8000 || seen[key] {
366 continue
367 }
368 switch r.id {
369 case 1, 16, 21:
370 continue
371 }
372 seen[key] = true
373 r.value = old[off : off+length]
374 recs = append(recs, r)
375 }
376 }
377 less := func(a, b nameRecord) bool {
378 if a.platform != b.platform {
379 return a.platform < b.platform
380 }
381 if a.encoding != b.encoding {
382 return a.encoding < b.encoding
383 }
384 if a.language != b.language {
385 return a.language < b.language
386 }
387 return a.id < b.id
388 }
389 sort.SliceStable(recs, func(i, j int) bool { return less(recs[i], recs[j]) })
390
391 fam := nameRecord{3, 1, 0x409, 1, utf16BE(family)}
392 if len(fam.value) > maxNameStorage/2 {
393 return nil, fmt.Errorf("fonts: family name of %d bytes", len(fam.value))
394 }
395 // The PostScript name kept: Windows English, else the first.
396 ps := -1
397 for i, r := range recs {
398 if r.id == 6 && (ps < 0 || (r.platform == 3 && r.language == 0x409 && recs[ps].language != 0x409)) {
399 ps = i
400 }
401 }
402 kept := []nameRecord{fam}
403 size := len(fam.value)
404 if ps >= 0 && size+len(recs[ps].value) <= maxNameStorage {
405 kept = append(kept, recs[ps])
406 size += len(recs[ps].value)
407 } else {
408 r := nameRecord{3, 1, 0x409, 6, utf16BE(postScriptFrom(family))}
409 kept = append(kept, r)
410 size += len(r.value)
411 ps = -1
412 }
413 for i, r := range recs {
414 if i == ps {
415 continue
416 }
417 if len(kept) >= maxNameRecords || size+len(r.value) > maxNameStorage {
418 continue
419 }
420 kept = append(kept, r)
421 size += len(r.value)
422 }
423 recs = kept
424 sort.SliceStable(recs, func(i, j int) bool { return less(recs[i], recs[j]) })
425
426 head := make([]byte, 6+12*len(recs))
427 binary.BigEndian.PutUint16(head[2:], uint16(len(recs)))
428 binary.BigEndian.PutUint16(head[4:], uint16(len(head)))
429 store := make([]byte, 0, size)
430 for i, r := range recs {
431 at := 6 + i*12
432 binary.BigEndian.PutUint16(head[at:], r.platform)
433 binary.BigEndian.PutUint16(head[at+2:], r.encoding)
434 binary.BigEndian.PutUint16(head[at+4:], r.language)
435 binary.BigEndian.PutUint16(head[at+6:], r.id)
436 binary.BigEndian.PutUint16(head[at+8:], uint16(len(r.value)))
437 binary.BigEndian.PutUint16(head[at+10:], uint16(len(store)))
438 store = append(store, r.value...)
439 }
440 return append(head, store...), nil
441}
442
443func utf16BE(s string) []byte {
444 units := utf16.Encode([]rune(s))
445 out := make([]byte, 2*len(units))
446 for i, u := range units {
447 binary.BigEndian.PutUint16(out[2*i:], u)
448 }
449 return out
450}
451
452// postScriptFrom is family without the characters a PostScript name
453// may not carry.
454func postScriptFrom(family string) string {
455 ps := strings.Map(func(r rune) rune {
456 if r > ' ' && r < 0x7f && !strings.ContainsRune("[](){}<>/%", r) {
457 return r
458 }
459 return -1
460 }, family)
461 if ps == "" {
462 ps = "Uploaded"
463 }
464 return ps
465}
466