package fonts_test import ( "encoding/json" "math" "os" "testing" "github.com/carlosframework/docs/internal/fonts" ) // The PDF must kern the way the browser does, or its lines break in // different places (Paul's default 6). Carlito kerns "AV" and "To"; a // shaped run is narrower than the sum of its glyphs' own advances. func TestShapingKerns(t *testing.T) { face := family(t, "carlito").Face(false, false) font, err := face.Parsed() if err != nil { t.Fatal(err) } sh := fonts.NewShaper() for _, s := range []string{"AV", "To", "Wa"} { run, err := sh.Shape(face, s) if err != nil { t.Fatal(err) } nominal, _ := font.WidthEm(s) if run.Width >= nominal-0.01 { t.Errorf("%q shaped to %.4f em, unkerned %.4f em: no kerning", s, run.Width, nominal) } text := "" for _, g := range run.Glyphs { text += g.Text } if text != s { t.Errorf("%q: the glyphs say %q, so the PDF's text would copy out wrong", s, text) } } } // A ligature is one glyph standing for several characters, and the // text that copies out of the PDF must still be every character. func TestShapingLigatesAndKeepsTheText(t *testing.T) { for _, f := range fonts.Families { face := f.Face(false, false) run, err := fonts.NewShaper().Shape(face, "office") if err != nil { t.Fatal(err) } text := "" for _, g := range run.Glyphs { text += g.Text } if text != "office" { t.Errorf("%s: %q copies out as %q", f.Name, "office", text) } if len(run.Missing) > 0 { t.Errorf("%s is missing %q", f.Name, run.Missing) } } } // The PDF's shaper sets every word the way HarfBuzz, the browser's // shaper, does, in every face Docs ships: the advances are equal to the // font unit. testdata/harfbuzz.json is HarfBuzz's own answer // (scripts/harfbuzz-golden.py). go-text/typesetting v0.3.5 failed this // for Inter, applying none of its kerning, so the PDF broke Inter lines // a word early. func TestShapingMatchesHarfBuzz(t *testing.T) { raw, err := os.ReadFile("testdata/harfbuzz.json") if err != nil { t.Fatal(err) } var golden struct { Faces map[string]map[string]int `json:"faces"` } if err := json.Unmarshal(raw, &golden); err != nil { t.Fatal(err) } if len(golden.Faces) != len(fonts.All()) { t.Fatalf("the golden file covers %d faces, Docs ships %d: rerun scripts/harfbuzz-golden.py", len(golden.Faces), len(fonts.All())) } sh := fonts.NewShaper() for _, face := range fonts.All() { words, ok := golden.Faces[face.File] if !ok { t.Errorf("%s is not in the golden file", face.File) continue } font, err := face.Parsed() if err != nil { t.Fatal(err) } for w, want := range words { run, err := sh.Shape(face, w) if err != nil { t.Fatal(err) } if got := int(math.Round(run.Width * float64(font.UnitsPerEm))); got != want { t.Errorf("%s %q: the PDF sets it %d units wide, HarfBuzz %d", face.File, w, got, want) } } } }