sfnt.go 63 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002
  1. // Copyright 2016 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. //go:generate go run gen.go
  5. // Package sfnt implements a decoder for TTF (TrueType Fonts) and OTF (OpenType
  6. // Fonts). Such fonts are also known as SFNT fonts.
  7. //
  8. // This package provides a low-level API and does not depend on vector
  9. // rasterization packages. Glyphs are represented as vectors, not pixels.
  10. //
  11. // The sibling golang.org/x/image/font/opentype package provides a high-level
  12. // API, including glyph rasterization.
  13. //
  14. // This package provides a decoder in that it produces a TTF's glyphs (and
  15. // other metadata such as advance width and kerning pairs): give me the 'A'
  16. // from times_new_roman.ttf.
  17. //
  18. // Unlike the image.Image decoder functions (gif.Decode, jpeg.Decode and
  19. // png.Decode) in Go's standard library, an sfnt.Font needs ongoing access to
  20. // the TTF data (as a []byte or io.ReaderAt) after the sfnt.ParseXxx functions
  21. // return. If parsing a []byte, its elements are assumed immutable while the
  22. // sfnt.Font remains in use. If parsing an *os.File, you should not close the
  23. // file until after you're done with the sfnt.Font.
  24. //
  25. // The []byte or io.ReaderAt data given to ParseXxx can be re-written to
  26. // another io.Writer, copying the underlying TTF file, but this package does
  27. // not provide an encoder. Specifically, there is no API to build a different
  28. // TTF file, whether 'from scratch' or by modifying an existing one.
  29. package sfnt // import "golang.org/x/image/font/sfnt"
  30. // This implementation was written primarily to the
  31. // https://www.microsoft.com/en-us/Typography/OpenTypeSpecification.aspx
  32. // specification. Additional documentation is at
  33. // http://developer.apple.com/fonts/TTRefMan/
  34. //
  35. // The pyftinspect tool from https://github.com/fonttools/fonttools is useful
  36. // for inspecting SFNT fonts.
  37. //
  38. // The ttfdump tool is also useful. For example:
  39. // ttfdump -t cmap ../testdata/CFFTest.otf dump.txt
  40. import (
  41. "errors"
  42. "image"
  43. "io"
  44. "golang.org/x/image/font"
  45. "golang.org/x/image/math/fixed"
  46. "golang.org/x/text/encoding/charmap"
  47. )
  48. // These constants are not part of the specifications, but are limitations used
  49. // by this implementation.
  50. const (
  51. // This value is arbitrary, but defends against parsing malicious font
  52. // files causing excessive memory allocations. For reference, Adobe's
  53. // SourceHanSansSC-Regular.otf has 65535 glyphs and:
  54. // - its format-4 cmap table has 1581 segments.
  55. // - its format-12 cmap table has 16498 segments.
  56. //
  57. // TODO: eliminate this constraint? If the cmap table is very large, load
  58. // some or all of it lazily (at the time Font.GlyphIndex is called) instead
  59. // of all of it eagerly (at the time Font.initialize is called), while
  60. // keeping an upper bound on the memory used? This will make the code in
  61. // cmap.go more complicated, considering that all of the Font methods are
  62. // safe to call concurrently, as long as each call has a different *Buffer.
  63. maxCmapSegments = 20000
  64. // TODO: similarly, load subroutine locations lazily. Adobe's
  65. // SourceHanSansSC-Regular.otf has up to 30000 subroutines.
  66. maxNumSubroutines = 40000
  67. maxCompoundRecursionDepth = 8
  68. maxCompoundStackSize = 64
  69. maxGlyphDataLength = 64 * 1024
  70. maxHintBits = 256
  71. maxNumFontDicts = 256
  72. maxNumFonts = 256
  73. maxNumTables = 256
  74. maxRealNumberStrLen = 64 // Maximum length in bytes of the "-123.456E-7" representation.
  75. // (maxTableOffset + maxTableLength) will not overflow an int32.
  76. maxTableLength = 1 << 29
  77. maxTableOffset = 1 << 29
  78. )
  79. var (
  80. // ErrColoredGlyph indicates that the requested glyph is not a monochrome
  81. // vector glyph, such as a colored (bitmap or vector) emoji glyph.
  82. ErrColoredGlyph = errors.New("sfnt: colored glyph")
  83. // ErrNotFound indicates that the requested value was not found.
  84. ErrNotFound = errors.New("sfnt: not found")
  85. errInvalidBounds = errors.New("sfnt: invalid bounds")
  86. errInvalidCFFTable = errors.New("sfnt: invalid CFF table")
  87. errInvalidCmapTable = errors.New("sfnt: invalid cmap table")
  88. errInvalidDfont = errors.New("sfnt: invalid dfont")
  89. errInvalidFont = errors.New("sfnt: invalid font")
  90. errInvalidFontCollection = errors.New("sfnt: invalid font collection")
  91. errInvalidGPOSTable = errors.New("sfnt: invalid GPOS table")
  92. errInvalidGlyphData = errors.New("sfnt: invalid glyph data")
  93. errInvalidGlyphDataLength = errors.New("sfnt: invalid glyph data length")
  94. errInvalidHeadTable = errors.New("sfnt: invalid head table")
  95. errInvalidHheaTable = errors.New("sfnt: invalid hhea table")
  96. errInvalidHmtxTable = errors.New("sfnt: invalid hmtx table")
  97. errInvalidKernTable = errors.New("sfnt: invalid kern table")
  98. errInvalidLocaTable = errors.New("sfnt: invalid loca table")
  99. errInvalidLocationData = errors.New("sfnt: invalid location data")
  100. errInvalidMaxpTable = errors.New("sfnt: invalid maxp table")
  101. errInvalidNameTable = errors.New("sfnt: invalid name table")
  102. errInvalidOS2Table = errors.New("sfnt: invalid OS/2 table")
  103. errInvalidPostTable = errors.New("sfnt: invalid post table")
  104. errInvalidSingleFont = errors.New("sfnt: invalid single font (data is a font collection)")
  105. errInvalidSourceData = errors.New("sfnt: invalid source data")
  106. errInvalidTableOffset = errors.New("sfnt: invalid table offset")
  107. errInvalidTableTagOrder = errors.New("sfnt: invalid table tag order")
  108. errInvalidUCS2String = errors.New("sfnt: invalid UCS-2 string")
  109. errUnsupportedCFFFDSelectTable = errors.New("sfnt: unsupported CFF FDSelect table")
  110. errUnsupportedCFFVersion = errors.New("sfnt: unsupported CFF version")
  111. errUnsupportedClassDefFormat = errors.New("sfnt: unsupported class definition format")
  112. errUnsupportedCmapEncodings = errors.New("sfnt: unsupported cmap encodings")
  113. errUnsupportedCollection = errors.New("sfnt: unsupported collection")
  114. errUnsupportedCompoundGlyph = errors.New("sfnt: unsupported compound glyph")
  115. errUnsupportedCoverageFormat = errors.New("sfnt: unsupported coverage format")
  116. errUnsupportedExtensionPosFormat = errors.New("sfnt: unsupported extension positioning format")
  117. errUnsupportedGPOSTable = errors.New("sfnt: unsupported GPOS table")
  118. errUnsupportedGlyphDataLength = errors.New("sfnt: unsupported glyph data length")
  119. errUnsupportedKernTable = errors.New("sfnt: unsupported kern table")
  120. errUnsupportedNumberOfCmapSegments = errors.New("sfnt: unsupported number of cmap segments")
  121. errUnsupportedNumberOfFontDicts = errors.New("sfnt: unsupported number of font dicts")
  122. errUnsupportedNumberOfFonts = errors.New("sfnt: unsupported number of fonts")
  123. errUnsupportedNumberOfHints = errors.New("sfnt: unsupported number of hints")
  124. errUnsupportedNumberOfSubroutines = errors.New("sfnt: unsupported number of subroutines")
  125. errUnsupportedNumberOfTables = errors.New("sfnt: unsupported number of tables")
  126. errUnsupportedPlatformEncoding = errors.New("sfnt: unsupported platform encoding")
  127. errUnsupportedPostTable = errors.New("sfnt: unsupported post table")
  128. errUnsupportedRealNumberEncoding = errors.New("sfnt: unsupported real number encoding")
  129. errUnsupportedTableOffsetLength = errors.New("sfnt: unsupported table offset or length")
  130. errUnsupportedType2Charstring = errors.New("sfnt: unsupported Type 2 Charstring")
  131. )
  132. // GlyphIndex is a glyph index in a Font.
  133. type GlyphIndex uint16
  134. // NameID identifies a name table entry.
  135. //
  136. // See the "Name IDs" section of
  137. // https://www.microsoft.com/typography/otspec/name.htm
  138. type NameID uint16
  139. const (
  140. NameIDCopyright NameID = 0
  141. NameIDFamily NameID = 1
  142. NameIDSubfamily NameID = 2
  143. NameIDUniqueIdentifier NameID = 3
  144. NameIDFull NameID = 4
  145. NameIDVersion NameID = 5
  146. NameIDPostScript NameID = 6
  147. NameIDTrademark NameID = 7
  148. NameIDManufacturer NameID = 8
  149. NameIDDesigner NameID = 9
  150. NameIDDescription NameID = 10
  151. NameIDVendorURL NameID = 11
  152. NameIDDesignerURL NameID = 12
  153. NameIDLicense NameID = 13
  154. NameIDLicenseURL NameID = 14
  155. NameIDTypographicFamily NameID = 16
  156. NameIDTypographicSubfamily NameID = 17
  157. NameIDCompatibleFull NameID = 18
  158. NameIDSampleText NameID = 19
  159. NameIDPostScriptCID NameID = 20
  160. NameIDWWSFamily NameID = 21
  161. NameIDWWSSubfamily NameID = 22
  162. NameIDLightBackgroundPalette NameID = 23
  163. NameIDDarkBackgroundPalette NameID = 24
  164. NameIDVariationsPostScriptPrefix NameID = 25
  165. )
  166. // Units are an integral number of abstract, scalable "font units". The em
  167. // square is typically 1000 or 2048 "font units". This would map to a certain
  168. // number (e.g. 30 pixels) of physical pixels, depending on things like the
  169. // display resolution (DPI) and font size (e.g. a 12 point font).
  170. type Units int32
  171. // scale returns x divided by unitsPerEm, rounded to the nearest fixed.Int26_6
  172. // value (1/64th of a pixel).
  173. func scale(x fixed.Int26_6, unitsPerEm Units) fixed.Int26_6 {
  174. if x >= 0 {
  175. x += fixed.Int26_6(unitsPerEm) / 2
  176. } else {
  177. x -= fixed.Int26_6(unitsPerEm) / 2
  178. }
  179. return x / fixed.Int26_6(unitsPerEm)
  180. }
  181. func u16(b []byte) uint16 {
  182. _ = b[1] // Bounds check hint to compiler.
  183. return uint16(b[0])<<8 | uint16(b[1])<<0
  184. }
  185. func u32(b []byte) uint32 {
  186. _ = b[3] // Bounds check hint to compiler.
  187. return uint32(b[0])<<24 | uint32(b[1])<<16 | uint32(b[2])<<8 | uint32(b[3])<<0
  188. }
  189. // source is a source of byte data. Conceptually, it is like an io.ReaderAt,
  190. // except that a common source of SFNT font data is in-memory instead of
  191. // on-disk: a []byte containing the entire data, either as a global variable
  192. // (e.g. "goregular.TTF") or the result of an ioutil.ReadFile call. In such
  193. // cases, as an optimization, we skip the io.Reader / io.ReaderAt model of
  194. // copying from the source to a caller-supplied buffer, and instead provide
  195. // direct access to the underlying []byte data.
  196. type source struct {
  197. b []byte
  198. r io.ReaderAt
  199. // TODO: add a caching layer, if we're using the io.ReaderAt? Note that
  200. // this might make a source no longer safe to use concurrently.
  201. }
  202. // valid returns whether exactly one of s.b and s.r is nil.
  203. func (s *source) valid() bool {
  204. return (s.b == nil) != (s.r == nil)
  205. }
  206. // viewBufferWritable returns whether the []byte returned by source.view can be
  207. // written to by the caller, including by passing it to the same method
  208. // (source.view) on other receivers (i.e. different sources).
  209. //
  210. // In other words, it returns whether the source's underlying data is an
  211. // io.ReaderAt, not a []byte.
  212. func (s *source) viewBufferWritable() bool {
  213. return s.b == nil
  214. }
  215. // view returns the length bytes at the given offset. buf is an optional
  216. // scratch buffer to reduce allocations when calling view multiple times. A nil
  217. // buf is valid. The []byte returned may be a sub-slice of buf[:cap(buf)], or
  218. // it may be an unrelated slice. In any case, the caller should not modify the
  219. // contents of the returned []byte, other than passing that []byte back to this
  220. // method on the same source s.
  221. func (s *source) view(buf []byte, offset, length int) ([]byte, error) {
  222. if 0 > offset || offset > offset+length {
  223. return nil, errInvalidBounds
  224. }
  225. // Try reading from the []byte.
  226. if s.b != nil {
  227. if offset+length > len(s.b) {
  228. return nil, errInvalidBounds
  229. }
  230. return s.b[offset : offset+length], nil
  231. }
  232. // Read from the io.ReaderAt.
  233. if length <= cap(buf) {
  234. buf = buf[:length]
  235. } else {
  236. // Round length up to the nearest KiB. The slack can lead to fewer
  237. // allocations if the buffer is re-used for multiple source.view calls.
  238. n := length
  239. n += 1023
  240. n &^= 1023
  241. buf = make([]byte, length, n)
  242. }
  243. if n, err := s.r.ReadAt(buf, int64(offset)); n != length {
  244. return nil, err
  245. }
  246. return buf, nil
  247. }
  248. // varLenView returns bytes from the given offset for sub-tables with varying
  249. // length. The length of bytes is determined by staticLength plus n*itemLength,
  250. // where n is read as uint16 from countOffset (relative to offset). buf is an
  251. // optional scratch buffer (see source.view())
  252. func (s *source) varLenView(buf []byte, offset, staticLength, countOffset, itemLength int) ([]byte, int, error) {
  253. if 0 > offset || offset > offset+staticLength {
  254. return nil, 0, errInvalidBounds
  255. }
  256. if 0 > countOffset || countOffset+1 >= staticLength {
  257. return nil, 0, errInvalidBounds
  258. }
  259. // read static part which contains our count
  260. buf, err := s.view(buf, offset, staticLength)
  261. if err != nil {
  262. return nil, 0, err
  263. }
  264. count := int(u16(buf[countOffset:]))
  265. buf, err = s.view(buf, offset, staticLength+count*itemLength)
  266. if err != nil {
  267. return nil, 0, err
  268. }
  269. return buf, count, nil
  270. }
  271. // u16 returns the uint16 in the table t at the relative offset i.
  272. //
  273. // buf is an optional scratch buffer as per the source.view method.
  274. func (s *source) u16(buf []byte, t table, i int) (uint16, error) {
  275. if i < 0 || uint(t.length) < uint(i+2) {
  276. return 0, errInvalidBounds
  277. }
  278. buf, err := s.view(buf, int(t.offset)+i, 2)
  279. if err != nil {
  280. return 0, err
  281. }
  282. return u16(buf), nil
  283. }
  284. // u32 returns the uint32 in the table t at the relative offset i.
  285. //
  286. // buf is an optional scratch buffer as per the source.view method.
  287. func (s *source) u32(buf []byte, t table, i int) (uint32, error) {
  288. if i < 0 || uint(t.length) < uint(i+4) {
  289. return 0, errInvalidBounds
  290. }
  291. buf, err := s.view(buf, int(t.offset)+i, 4)
  292. if err != nil {
  293. return 0, err
  294. }
  295. return u32(buf), nil
  296. }
  297. // table is a section of the font data.
  298. type table struct {
  299. offset, length uint32
  300. }
  301. // ParseCollection parses an SFNT font collection, such as TTC or OTC data,
  302. // from a []byte data source.
  303. //
  304. // If passed data for a single font, a TTF or OTF instead of a TTC or OTC, it
  305. // will return a collection containing 1 font.
  306. //
  307. // The caller should not modify src while the Collection or its Fonts remain in
  308. // use. See the package documentation for details.
  309. func ParseCollection(src []byte) (*Collection, error) {
  310. c := &Collection{src: source{b: src}}
  311. if err := c.initialize(); err != nil {
  312. return nil, err
  313. }
  314. return c, nil
  315. }
  316. // ParseCollectionReaderAt parses an SFNT collection, such as TTC or OTC data,
  317. // from an io.ReaderAt data source.
  318. //
  319. // If passed data for a single font, a TTF or OTF instead of a TTC or OTC, it
  320. // will return a collection containing 1 font.
  321. //
  322. // The caller should not modify or close src while the Collection or its Fonts
  323. // remain in use. See the package documentation for details.
  324. func ParseCollectionReaderAt(src io.ReaderAt) (*Collection, error) {
  325. c := &Collection{src: source{r: src}}
  326. if err := c.initialize(); err != nil {
  327. return nil, err
  328. }
  329. return c, nil
  330. }
  331. // Collection is a collection of one or more fonts.
  332. //
  333. // All of the Collection methods are safe to call concurrently.
  334. type Collection struct {
  335. src source
  336. offsets []uint32
  337. isDfont bool
  338. }
  339. // NumFonts returns the number of fonts in the collection.
  340. func (c *Collection) NumFonts() int { return len(c.offsets) }
  341. func (c *Collection) initialize() error {
  342. // The https://www.microsoft.com/typography/otspec/otff.htm "Font
  343. // Collections" section describes the TTC header.
  344. //
  345. // https://github.com/kreativekorp/ksfl/wiki/Macintosh-Resource-File-Format
  346. // describes the dfont header.
  347. //
  348. // 16 is the maximum of sizeof(TTCHeader) and sizeof(DfontHeader).
  349. buf, err := c.src.view(nil, 0, 16)
  350. if err != nil {
  351. return err
  352. }
  353. // These cases match the switch statement in Font.initializeTables.
  354. switch u32(buf) {
  355. default:
  356. return errInvalidFontCollection
  357. case dfontResourceDataOffset:
  358. return c.parseDfont(buf, u32(buf[4:]), u32(buf[12:]))
  359. case 0x00010000, 0x4f54544f, 0x74727565: // 0x10000, "OTTO", "true"
  360. // Try parsing it as a single font instead of a collection.
  361. c.offsets = []uint32{0}
  362. case 0x74746366: // "ttcf".
  363. numFonts := u32(buf[8:])
  364. if numFonts == 0 || numFonts > maxNumFonts {
  365. return errUnsupportedNumberOfFonts
  366. }
  367. buf, err = c.src.view(nil, 12, int(4*numFonts))
  368. if err != nil {
  369. return err
  370. }
  371. c.offsets = make([]uint32, numFonts)
  372. for i := range c.offsets {
  373. o := u32(buf[4*i:])
  374. if o > maxTableOffset {
  375. return errUnsupportedTableOffsetLength
  376. }
  377. c.offsets[i] = o
  378. }
  379. }
  380. return nil
  381. }
  382. // dfontResourceDataOffset is the assumed value of a dfont file's resource data
  383. // offset.
  384. //
  385. // https://github.com/kreativekorp/ksfl/wiki/Macintosh-Resource-File-Format
  386. // says that "A Mac OS resource file... [starts with an] offset from start of
  387. // file to start of resource data section... [usually] 0x0100". In theory,
  388. // 0x00000100 isn't always a magic number for identifying dfont files. In
  389. // practice, it seems to work.
  390. const dfontResourceDataOffset = 0x00000100
  391. // parseDfont parses a dfont resource map, as per
  392. // https://github.com/kreativekorp/ksfl/wiki/Macintosh-Resource-File-Format
  393. //
  394. // That unofficial wiki page lists all of its fields as *signed* integers,
  395. // which looks unusual. The actual file format might use *unsigned* integers in
  396. // various places, but until we have either an official specification or an
  397. // actual dfont file where this matters, we'll use signed integers and treat
  398. // negative values as invalid.
  399. func (c *Collection) parseDfont(buf []byte, resourceMapOffset, resourceMapLength uint32) error {
  400. if resourceMapOffset > maxTableOffset || resourceMapLength > maxTableLength {
  401. return errUnsupportedTableOffsetLength
  402. }
  403. const headerSize = 28
  404. if resourceMapLength < headerSize {
  405. return errInvalidDfont
  406. }
  407. buf, err := c.src.view(buf, int(resourceMapOffset+24), 2)
  408. if err != nil {
  409. return err
  410. }
  411. typeListOffset := int(int16(u16(buf)))
  412. if typeListOffset < headerSize || resourceMapLength < uint32(typeListOffset)+2 {
  413. return errInvalidDfont
  414. }
  415. buf, err = c.src.view(buf, int(resourceMapOffset)+typeListOffset, 2)
  416. if err != nil {
  417. return err
  418. }
  419. typeCount := int(int16(u16(buf)))
  420. const tSize = 8
  421. if typeCount < 0 || tSize*uint32(typeCount) > resourceMapLength-uint32(typeListOffset)-2 {
  422. return errInvalidDfont
  423. }
  424. buf, err = c.src.view(buf, int(resourceMapOffset)+typeListOffset+2, tSize*typeCount)
  425. if err != nil {
  426. return err
  427. }
  428. resourceCount, resourceListOffset := 0, 0
  429. for i := 0; i < typeCount; i++ {
  430. if u32(buf[tSize*i:]) != 0x73666e74 { // "sfnt".
  431. continue
  432. }
  433. resourceCount = int(int16(u16(buf[tSize*i+4:])))
  434. if resourceCount < 0 {
  435. return errInvalidDfont
  436. }
  437. // https://github.com/kreativekorp/ksfl/wiki/Macintosh-Resource-File-Format
  438. // says that the value in the wire format is "the number of
  439. // resources of this type, minus one."
  440. resourceCount++
  441. resourceListOffset = int(int16(u16(buf[tSize*i+6:])))
  442. if resourceListOffset < 0 {
  443. return errInvalidDfont
  444. }
  445. break
  446. }
  447. if resourceCount == 0 {
  448. return errInvalidDfont
  449. }
  450. if resourceCount > maxNumFonts {
  451. return errUnsupportedNumberOfFonts
  452. }
  453. const rSize = 12
  454. if o, n := uint32(typeListOffset+resourceListOffset), rSize*uint32(resourceCount); o > resourceMapLength || n > resourceMapLength-o {
  455. return errInvalidDfont
  456. } else {
  457. buf, err = c.src.view(buf, int(resourceMapOffset+o), int(n))
  458. if err != nil {
  459. return err
  460. }
  461. }
  462. c.offsets = make([]uint32, resourceCount)
  463. for i := range c.offsets {
  464. o := 0xffffff & u32(buf[rSize*i+4:])
  465. // Offsets are relative to the resource data start, not the file start.
  466. // A particular resource's data also starts with a 4-byte length, which
  467. // we skip.
  468. o += dfontResourceDataOffset + 4
  469. if o > maxTableOffset {
  470. return errUnsupportedTableOffsetLength
  471. }
  472. c.offsets[i] = o
  473. }
  474. c.isDfont = true
  475. return nil
  476. }
  477. // Font returns the i'th font in the collection.
  478. func (c *Collection) Font(i int) (*Font, error) {
  479. if i < 0 || len(c.offsets) <= i {
  480. return nil, ErrNotFound
  481. }
  482. f := &Font{src: c.src}
  483. if err := f.initialize(int(c.offsets[i]), c.isDfont); err != nil {
  484. return nil, err
  485. }
  486. return f, nil
  487. }
  488. // Parse parses an SFNT font, such as TTF or OTF data, from a []byte data
  489. // source.
  490. //
  491. // The caller should not modify src while the Font remains in use. See the
  492. // package documentation for details.
  493. func Parse(src []byte) (*Font, error) {
  494. f := &Font{src: source{b: src}}
  495. if err := f.initialize(0, false); err != nil {
  496. return nil, err
  497. }
  498. return f, nil
  499. }
  500. // ParseReaderAt parses an SFNT font, such as TTF or OTF data, from an
  501. // io.ReaderAt data source.
  502. //
  503. // The caller should not modify or close src while the Font remains in use. See
  504. // the package documentation for details.
  505. func ParseReaderAt(src io.ReaderAt) (*Font, error) {
  506. f := &Font{src: source{r: src}}
  507. if err := f.initialize(0, false); err != nil {
  508. return nil, err
  509. }
  510. return f, nil
  511. }
  512. // Font is an SFNT font.
  513. //
  514. // Many of its methods take a *Buffer argument, as re-using buffers can reduce
  515. // the total memory allocation of repeated Font method calls, such as measuring
  516. // and rasterizing every unique glyph in a string of text. If efficiency is not
  517. // a concern, passing a nil *Buffer is valid, and implies using a temporary
  518. // buffer for a single call.
  519. //
  520. // It is valid to re-use a *Buffer with multiple Font method calls, even with
  521. // different *Font receivers, as long as they are not concurrent calls.
  522. //
  523. // All of the Font methods are safe to call concurrently, as long as each call
  524. // has a different *Buffer (or nil).
  525. //
  526. // The Font methods that don't take a *Buffer argument are always safe to call
  527. // concurrently.
  528. //
  529. // Some methods provide lengths or coordinates, e.g. bounds, font metrics and
  530. // control points. All of these methods take a ppem parameter, which is the
  531. // number of pixels in 1 em, expressed as a 26.6 fixed point value. For
  532. // example, if 1 em is 10 pixels then ppem is fixed.I(10), which equals
  533. // fixed.Int26_6(10 << 6).
  534. //
  535. // To get those lengths or coordinates in terms of font units instead of
  536. // pixels, use ppem = fixed.Int26_6(f.UnitsPerEm()) and if those methods take a
  537. // font.Hinting parameter, use font.HintingNone. The return values will have
  538. // type fixed.Int26_6, but those numbers can be converted back to Units with no
  539. // further scaling necessary.
  540. type Font struct {
  541. src source
  542. // initialOffset is the file offset of the start of the font. This may be
  543. // non-zero for fonts within a font collection.
  544. initialOffset int32
  545. // https://www.microsoft.com/typography/otspec/otff.htm#otttables
  546. // "Required Tables".
  547. cmap table
  548. head table
  549. hhea table
  550. hmtx table
  551. maxp table
  552. name table
  553. os2 table
  554. post table
  555. // https://www.microsoft.com/typography/otspec/otff.htm#otttables
  556. // "Tables Related to TrueType Outlines".
  557. //
  558. // This implementation does not support hinting, so it does not read the
  559. // cvt, fpgm gasp or prep tables.
  560. glyf table
  561. loca table
  562. // https://www.microsoft.com/typography/otspec/otff.htm#otttables
  563. // "Tables Related to PostScript Outlines".
  564. //
  565. // TODO: cff2, vorg?
  566. cff table
  567. // https://www.microsoft.com/typography/otspec/otff.htm#otttables
  568. // "Tables Related to Bitmap Glyphs".
  569. //
  570. // TODO: Others?
  571. cblc table
  572. // https://www.microsoft.com/typography/otspec/otff.htm#otttables
  573. // "Advanced Typographic Tables".
  574. //
  575. // TODO: base, gdef, gsub, jstf, math?
  576. gpos table
  577. // https://www.microsoft.com/typography/otspec/otff.htm#otttables
  578. // "Other OpenType Tables".
  579. //
  580. // TODO: hdmx, vmtx? Others?
  581. kern table
  582. cached struct {
  583. ascent int32
  584. capHeight int32
  585. finalTableOffset int32
  586. glyphData glyphData
  587. glyphIndex glyphIndexFunc
  588. bounds [4]int16
  589. descent int32
  590. indexToLocFormat bool // false means short, true means long.
  591. isColorBitmap bool
  592. isPostScript bool
  593. kernNumPairs int32
  594. kernOffset int32
  595. kernFuncs []kernFunc
  596. lineGap int32
  597. numHMetrics int32
  598. post *PostTable
  599. slope [2]int32
  600. unitsPerEm Units
  601. xHeight int32
  602. }
  603. }
  604. // NumGlyphs returns the number of glyphs in f.
  605. func (f *Font) NumGlyphs() int { return len(f.cached.glyphData.locations) - 1 }
  606. // UnitsPerEm returns the number of units per em for f.
  607. func (f *Font) UnitsPerEm() Units { return f.cached.unitsPerEm }
  608. func (f *Font) initialize(offset int, isDfont bool) error {
  609. if !f.src.valid() {
  610. return errInvalidSourceData
  611. }
  612. buf, finalTableOffset, isPostScript, err := f.initializeTables(offset, isDfont)
  613. if err != nil {
  614. return err
  615. }
  616. // The order of these parseXxx calls matters. Later calls may depend on
  617. // information parsed by earlier calls, such as the maxp table's numGlyphs.
  618. // To enforce these dependencies, such information is passed and returned
  619. // explicitly, and the f.cached fields are only set afterwards.
  620. //
  621. // When implementing new parseXxx methods, take care not to call methods
  622. // such as Font.NumGlyphs that implicitly depend on f.cached fields.
  623. buf, bounds, indexToLocFormat, unitsPerEm, err := f.parseHead(buf)
  624. if err != nil {
  625. return err
  626. }
  627. buf, numGlyphs, err := f.parseMaxp(buf, isPostScript)
  628. if err != nil {
  629. return err
  630. }
  631. buf, glyphData, isColorBitmap, err := f.parseGlyphData(buf, numGlyphs, indexToLocFormat, isPostScript)
  632. if err != nil {
  633. return err
  634. }
  635. buf, glyphIndex, err := f.parseCmap(buf)
  636. if err != nil {
  637. return err
  638. }
  639. buf, kernNumPairs, kernOffset, err := f.parseKern(buf)
  640. if err != nil {
  641. return err
  642. }
  643. buf, kernFuncs, err := f.parseGPOSKern(buf)
  644. if err != nil {
  645. return err
  646. }
  647. buf, ascent, descent, lineGap, run, rise, numHMetrics, err := f.parseHhea(buf, numGlyphs)
  648. if err != nil {
  649. return err
  650. }
  651. buf, err = f.parseHmtx(buf, numGlyphs, numHMetrics)
  652. if err != nil {
  653. return err
  654. }
  655. buf, hasXHeightCapHeight, xHeight, capHeight, err := f.parseOS2(buf)
  656. if err != nil {
  657. return err
  658. }
  659. buf, post, err := f.parsePost(buf, numGlyphs)
  660. if err != nil {
  661. return err
  662. }
  663. f.cached.ascent = ascent
  664. f.cached.capHeight = capHeight
  665. f.cached.finalTableOffset = finalTableOffset
  666. f.cached.glyphData = glyphData
  667. f.cached.glyphIndex = glyphIndex
  668. f.cached.bounds = bounds
  669. f.cached.descent = descent
  670. f.cached.indexToLocFormat = indexToLocFormat
  671. f.cached.isColorBitmap = isColorBitmap
  672. f.cached.isPostScript = isPostScript
  673. f.cached.kernNumPairs = kernNumPairs
  674. f.cached.kernOffset = kernOffset
  675. f.cached.kernFuncs = kernFuncs
  676. f.cached.lineGap = lineGap
  677. f.cached.numHMetrics = numHMetrics
  678. f.cached.post = post
  679. f.cached.slope = [2]int32{run, rise}
  680. f.cached.unitsPerEm = unitsPerEm
  681. f.cached.xHeight = xHeight
  682. if !hasXHeightCapHeight {
  683. xh, ch, err := f.initOS2VersionBelow2()
  684. if err != nil {
  685. return err
  686. }
  687. f.cached.xHeight = xh
  688. f.cached.capHeight = ch
  689. }
  690. return nil
  691. }
  692. func (f *Font) initializeTables(offset int, isDfont bool) (buf1 []byte, finalTableOffset int32, isPostScript bool, err error) {
  693. f.initialOffset = int32(offset)
  694. if int(f.initialOffset) != offset {
  695. return nil, 0, false, errUnsupportedTableOffsetLength
  696. }
  697. // https://www.microsoft.com/typography/otspec/otff.htm "Organization of an
  698. // OpenType Font" says that "The OpenType font starts with the Offset
  699. // Table", which is 12 bytes.
  700. buf, err := f.src.view(nil, offset, 12)
  701. if err != nil {
  702. return nil, 0, false, err
  703. }
  704. // When updating the cases in this switch statement, also update the
  705. // Collection.initialize method.
  706. switch u32(buf) {
  707. default:
  708. return nil, 0, false, errInvalidFont
  709. case dfontResourceDataOffset:
  710. return nil, 0, false, errInvalidSingleFont
  711. case 0x00010000:
  712. // No-op.
  713. case 0x4f54544f: // "OTTO".
  714. isPostScript = true
  715. case 0x74727565: // "true"
  716. // No-op.
  717. case 0x74746366: // "ttcf".
  718. return nil, 0, false, errInvalidSingleFont
  719. }
  720. numTables := int(u16(buf[4:]))
  721. if numTables > maxNumTables {
  722. return nil, 0, false, errUnsupportedNumberOfTables
  723. }
  724. // "The Offset Table is followed immediately by the Table Record entries...
  725. // sorted in ascending order by tag", 16 bytes each.
  726. buf, err = f.src.view(buf, offset+12, 16*numTables)
  727. if err != nil {
  728. return nil, 0, false, err
  729. }
  730. for b, first, prevTag := buf, true, uint32(0); len(b) > 0; b = b[16:] {
  731. tag := u32(b)
  732. if first {
  733. first = false
  734. } else if tag <= prevTag {
  735. return nil, 0, false, errInvalidTableTagOrder
  736. }
  737. prevTag = tag
  738. o, n := u32(b[8:12]), u32(b[12:16])
  739. // For dfont files, the offset is relative to the resource, not the
  740. // file.
  741. if isDfont {
  742. origO := o
  743. o += uint32(offset)
  744. if o < origO {
  745. return nil, 0, false, errUnsupportedTableOffsetLength
  746. }
  747. }
  748. if o > maxTableOffset || n > maxTableLength {
  749. return nil, 0, false, errUnsupportedTableOffsetLength
  750. }
  751. // We ignore the checksums, but "all tables must begin on four byte
  752. // boundries [sic]".
  753. if o&3 != 0 {
  754. return nil, 0, false, errInvalidTableOffset
  755. }
  756. if finalTableOffset < int32(o+n) {
  757. finalTableOffset = int32(o + n)
  758. }
  759. // Match the 4-byte tag as a uint32. For example, "OS/2" is 0x4f532f32.
  760. switch tag {
  761. case 0x43424c43:
  762. f.cblc = table{o, n}
  763. case 0x43464620:
  764. f.cff = table{o, n}
  765. case 0x4f532f32:
  766. f.os2 = table{o, n}
  767. case 0x636d6170:
  768. f.cmap = table{o, n}
  769. case 0x676c7966:
  770. f.glyf = table{o, n}
  771. case 0x47504f53:
  772. f.gpos = table{o, n}
  773. case 0x68656164:
  774. f.head = table{o, n}
  775. case 0x68686561:
  776. f.hhea = table{o, n}
  777. case 0x686d7478:
  778. f.hmtx = table{o, n}
  779. case 0x6b65726e:
  780. f.kern = table{o, n}
  781. case 0x6c6f6361:
  782. f.loca = table{o, n}
  783. case 0x6d617870:
  784. f.maxp = table{o, n}
  785. case 0x6e616d65:
  786. f.name = table{o, n}
  787. case 0x706f7374:
  788. f.post = table{o, n}
  789. }
  790. }
  791. if (f.src.b != nil) && (int(finalTableOffset) > len(f.src.b)) {
  792. return nil, 0, false, errInvalidSourceData
  793. }
  794. return buf, finalTableOffset, isPostScript, nil
  795. }
  796. func (f *Font) parseCmap(buf []byte) (buf1 []byte, glyphIndex glyphIndexFunc, err error) {
  797. // https://www.microsoft.com/typography/OTSPEC/cmap.htm
  798. const headerSize, entrySize = 4, 8
  799. if f.cmap.length < headerSize {
  800. return nil, nil, errInvalidCmapTable
  801. }
  802. u, err := f.src.u16(buf, f.cmap, 2)
  803. if err != nil {
  804. return nil, nil, err
  805. }
  806. numSubtables := int(u)
  807. if f.cmap.length < headerSize+entrySize*uint32(numSubtables) {
  808. return nil, nil, errInvalidCmapTable
  809. }
  810. var (
  811. bestWidth int
  812. bestOffset uint32
  813. bestLength uint32
  814. bestFormat uint16
  815. )
  816. // Scan all of the subtables, picking the widest supported one. See the
  817. // platformEncodingWidth comment for more discussion of width.
  818. for i := 0; i < numSubtables; i++ {
  819. buf, err = f.src.view(buf, int(f.cmap.offset)+headerSize+entrySize*i, entrySize)
  820. if err != nil {
  821. return nil, nil, err
  822. }
  823. pid := u16(buf)
  824. psid := u16(buf[2:])
  825. width := platformEncodingWidth(pid, psid)
  826. if width <= bestWidth {
  827. continue
  828. }
  829. offset := u32(buf[4:])
  830. if offset > f.cmap.length-4 {
  831. return nil, nil, errInvalidCmapTable
  832. }
  833. buf, err = f.src.view(buf, int(f.cmap.offset+offset), 4)
  834. if err != nil {
  835. return nil, nil, err
  836. }
  837. format := u16(buf)
  838. if !supportedCmapFormat(format, pid, psid) {
  839. continue
  840. }
  841. length := uint32(u16(buf[2:]))
  842. bestWidth = width
  843. bestOffset = offset
  844. bestLength = length
  845. bestFormat = format
  846. }
  847. if bestWidth == 0 {
  848. return nil, nil, errUnsupportedCmapEncodings
  849. }
  850. return f.makeCachedGlyphIndex(buf, bestOffset, bestLength, bestFormat)
  851. }
  852. func (f *Font) parseHead(buf []byte) (buf1 []byte, bounds [4]int16, indexToLocFormat bool, unitsPerEm Units, err error) {
  853. // https://www.microsoft.com/typography/otspec/head.htm
  854. if f.head.length != 54 {
  855. return nil, [4]int16{}, false, 0, errInvalidHeadTable
  856. }
  857. u, err := f.src.u16(buf, f.head, 18)
  858. if err != nil {
  859. return nil, [4]int16{}, false, 0, err
  860. }
  861. if u == 0 {
  862. return nil, [4]int16{}, false, 0, errInvalidHeadTable
  863. }
  864. unitsPerEm = Units(u)
  865. for i := range bounds {
  866. u, err := f.src.u16(buf, f.head, 36+2*i)
  867. if err != nil {
  868. return nil, [4]int16{}, false, 0, err
  869. }
  870. bounds[i] = int16(u)
  871. }
  872. u, err = f.src.u16(buf, f.head, 50)
  873. if err != nil {
  874. return nil, [4]int16{}, false, 0, err
  875. }
  876. indexToLocFormat = u != 0
  877. return buf, bounds, indexToLocFormat, unitsPerEm, nil
  878. }
  879. func (f *Font) parseHhea(buf []byte, numGlyphs int32) (buf1 []byte, ascent, descent, lineGap, run, rise, numHMetrics int32, err error) {
  880. // https://www.microsoft.com/typography/OTSPEC/hhea.htm
  881. if f.hhea.length != 36 {
  882. return nil, 0, 0, 0, 0, 0, 0, errInvalidHheaTable
  883. }
  884. u, err := f.src.u16(buf, f.hhea, 34)
  885. if err != nil {
  886. return nil, 0, 0, 0, 0, 0, 0, err
  887. }
  888. if int32(u) > numGlyphs || u == 0 {
  889. return nil, 0, 0, 0, 0, 0, 0, errInvalidHheaTable
  890. }
  891. a, err := f.src.u16(buf, f.hhea, 4)
  892. if err != nil {
  893. return nil, 0, 0, 0, 0, 0, 0, err
  894. }
  895. d, err := f.src.u16(buf, f.hhea, 6)
  896. if err != nil {
  897. return nil, 0, 0, 0, 0, 0, 0, err
  898. }
  899. l, err := f.src.u16(buf, f.hhea, 8)
  900. if err != nil {
  901. return nil, 0, 0, 0, 0, 0, 0, err
  902. }
  903. ru, err := f.src.u16(buf, f.hhea, 20)
  904. if err != nil {
  905. return nil, 0, 0, 0, 0, 0, 0, err
  906. }
  907. ri, err := f.src.u16(buf, f.hhea, 18)
  908. if err != nil {
  909. return nil, 0, 0, 0, 0, 0, 0, err
  910. }
  911. return buf, int32(int16(a)), int32(int16(d)), int32(int16(l)), int32(int16(ru)), int32(int16(ri)), int32(u), nil
  912. }
  913. func (f *Font) parseHmtx(buf []byte, numGlyphs, numHMetrics int32) (buf1 []byte, err error) {
  914. // https://www.microsoft.com/typography/OTSPEC/hmtx.htm
  915. // The spec says that the hmtx table's length should be
  916. // "4*numHMetrics+2*(numGlyphs-numHMetrics)". However, some fonts seen in the
  917. // wild omit the "2*(nG-nHM)". See https://github.com/golang/go/issues/28379
  918. if f.hmtx.length != uint32(4*numHMetrics) && f.hmtx.length != uint32(4*numHMetrics+2*(numGlyphs-numHMetrics)) {
  919. return nil, errInvalidHmtxTable
  920. }
  921. return buf, nil
  922. }
  923. func (f *Font) parseKern(buf []byte) (buf1 []byte, kernNumPairs, kernOffset int32, err error) {
  924. // https://www.microsoft.com/typography/otspec/kern.htm
  925. if f.kern.length == 0 {
  926. return buf, 0, 0, nil
  927. }
  928. const headerSize = 4
  929. if f.kern.length < headerSize {
  930. return nil, 0, 0, errInvalidKernTable
  931. }
  932. buf, err = f.src.view(buf, int(f.kern.offset), headerSize)
  933. if err != nil {
  934. return nil, 0, 0, err
  935. }
  936. offset := int(f.kern.offset) + headerSize
  937. length := int(f.kern.length) - headerSize
  938. switch version := u16(buf); version {
  939. case 0:
  940. if numTables := int(u16(buf[2:])); numTables == 0 {
  941. return buf, 0, 0, nil
  942. } else if numTables > 1 {
  943. // TODO: support multiple subtables. For now, fall through and use
  944. // only the first one.
  945. }
  946. return f.parseKernVersion0(buf, offset, length)
  947. case 1:
  948. if buf[2] != 0 || buf[3] != 0 {
  949. return nil, 0, 0, errUnsupportedKernTable
  950. }
  951. // Microsoft's https://www.microsoft.com/typography/otspec/kern.htm
  952. // says that "Apple has extended the definition of the 'kern' table to
  953. // provide additional functionality. The Apple extensions are not
  954. // supported on Windows."
  955. //
  956. // The format is relatively complicated, including encoding a state
  957. // machine, but rarely seen. We follow Microsoft's and FreeType's
  958. // behavior and simply ignore it. Theoretically, we could follow
  959. // https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6kern.html
  960. // but it doesn't seem worth the effort.
  961. return buf, 0, 0, nil
  962. }
  963. return nil, 0, 0, errUnsupportedKernTable
  964. }
  965. func (f *Font) parseKernVersion0(buf []byte, offset, length int) (buf1 []byte, kernNumPairs, kernOffset int32, err error) {
  966. const headerSize = 6
  967. if length < headerSize {
  968. return nil, 0, 0, errInvalidKernTable
  969. }
  970. buf, err = f.src.view(buf, offset, headerSize)
  971. if err != nil {
  972. return nil, 0, 0, err
  973. }
  974. if version := u16(buf); version != 0 {
  975. return nil, 0, 0, errUnsupportedKernTable
  976. }
  977. subtableLengthU16 := u16(buf[2:])
  978. if int(subtableLengthU16) < headerSize || length < int(subtableLengthU16) {
  979. return nil, 0, 0, errInvalidKernTable
  980. }
  981. if coverageBits := buf[5]; coverageBits != 0x01 {
  982. // We only support horizontal kerning.
  983. return nil, 0, 0, errUnsupportedKernTable
  984. }
  985. offset += headerSize
  986. length -= headerSize
  987. subtableLengthU16 -= headerSize
  988. switch format := buf[4]; format {
  989. case 0:
  990. return f.parseKernFormat0(buf, offset, length, subtableLengthU16)
  991. case 2:
  992. // If we could find such a font, we could write code to support it, but
  993. // a comment in the equivalent FreeType code (sfnt/ttkern.c) says that
  994. // they've never seen such a font.
  995. }
  996. return nil, 0, 0, errUnsupportedKernTable
  997. }
  998. func (f *Font) parseKernFormat0(buf []byte, offset, length int, subtableLengthU16 uint16) (buf1 []byte, kernNumPairs, kernOffset int32, err error) {
  999. const headerSize, entrySize = 8, 6
  1000. if length < headerSize {
  1001. return nil, 0, 0, errInvalidKernTable
  1002. }
  1003. buf, err = f.src.view(buf, offset, headerSize)
  1004. if err != nil {
  1005. return nil, 0, 0, err
  1006. }
  1007. kernNumPairs = int32(u16(buf))
  1008. // The subtable length from the kern table is only uint16. Fonts like
  1009. // Cambria, Calibri or Corbel have more then 10k kerning pairs and the
  1010. // actual subtable size is truncated to uint16. Compare size with KERN
  1011. // length and truncated size with subtable length.
  1012. n := headerSize + entrySize*int(kernNumPairs)
  1013. if (length < n) || (subtableLengthU16 != uint16(n)) {
  1014. return nil, 0, 0, errInvalidKernTable
  1015. }
  1016. return buf, kernNumPairs, int32(offset) + headerSize, nil
  1017. }
  1018. func (f *Font) parseMaxp(buf []byte, isPostScript bool) (buf1 []byte, numGlyphs int32, err error) {
  1019. // https://www.microsoft.com/typography/otspec/maxp.htm
  1020. if isPostScript {
  1021. if f.maxp.length != 6 {
  1022. return nil, 0, errInvalidMaxpTable
  1023. }
  1024. } else {
  1025. if f.maxp.length != 32 {
  1026. return nil, 0, errInvalidMaxpTable
  1027. }
  1028. }
  1029. u, err := f.src.u16(buf, f.maxp, 4)
  1030. if err != nil {
  1031. return nil, 0, err
  1032. }
  1033. return buf, int32(u), nil
  1034. }
  1035. type glyphData struct {
  1036. // The glyph data for the i'th glyph index is in
  1037. // src[locations[i+0]:locations[i+1]].
  1038. //
  1039. // The slice length equals 1 plus the number of glyphs.
  1040. locations []uint32
  1041. // For PostScript fonts, the bytecode for the i'th global or local
  1042. // subroutine is in src[x[i+0]:x[i+1]].
  1043. //
  1044. // The []uint32 slice length equals 1 plus the number of subroutines
  1045. gsubrs []uint32
  1046. singleSubrs []uint32
  1047. multiSubrs [][]uint32
  1048. fdSelect fdSelect
  1049. }
  1050. func (f *Font) parseGlyphData(buf []byte, numGlyphs int32, indexToLocFormat, isPostScript bool) (buf1 []byte, ret glyphData, isColorBitmap bool, err error) {
  1051. if isPostScript {
  1052. p := cffParser{
  1053. src: &f.src,
  1054. base: int(f.cff.offset),
  1055. offset: int(f.cff.offset),
  1056. end: int(f.cff.offset + f.cff.length),
  1057. }
  1058. ret, err = p.parse(numGlyphs)
  1059. if err != nil {
  1060. return nil, glyphData{}, false, err
  1061. }
  1062. } else if f.loca.length != 0 {
  1063. ret.locations, err = parseLoca(&f.src, f.loca, f.glyf.offset, indexToLocFormat, numGlyphs)
  1064. if err != nil {
  1065. return nil, glyphData{}, false, err
  1066. }
  1067. } else if f.cblc.length != 0 {
  1068. isColorBitmap = true
  1069. // TODO: parse the CBLC (and CBDT) tables. For now, we return a font
  1070. // with empty glyphs.
  1071. ret.locations = make([]uint32, numGlyphs+1)
  1072. }
  1073. if len(ret.locations) != int(numGlyphs+1) {
  1074. return nil, glyphData{}, false, errInvalidLocationData
  1075. }
  1076. return buf, ret, isColorBitmap, nil
  1077. }
  1078. func (f *Font) glyphTopOS2(b *Buffer, ppem fixed.Int26_6, r rune) (int32, error) {
  1079. ind, err := f.GlyphIndex(b, r)
  1080. if err != nil && err != ErrNotFound {
  1081. return 0, err
  1082. } else if ind == 0 {
  1083. return 0, nil
  1084. }
  1085. // Y axis points down
  1086. var min fixed.Int26_6
  1087. seg, err := f.LoadGlyph(b, ind, ppem, nil)
  1088. if err != nil {
  1089. return 0, err
  1090. }
  1091. for _, s := range seg {
  1092. for _, p := range s.Args {
  1093. if p.Y < min {
  1094. min = p.Y
  1095. }
  1096. }
  1097. }
  1098. return int32(min), nil
  1099. }
  1100. func (f *Font) initOS2VersionBelow2() (xHeight, capHeight int32, err error) {
  1101. ppem := fixed.Int26_6(f.UnitsPerEm())
  1102. var b Buffer
  1103. // sxHeight equal to the top of the unscaled and unhinted glyph bounding box
  1104. // of the glyph encoded at U+0078 (LATIN SMALL LETTER X).
  1105. xh, err := f.glyphTopOS2(&b, ppem, 'x')
  1106. if err != nil {
  1107. return 0, 0, err
  1108. }
  1109. // sCapHeight may be set equal to the top of the unscaled and unhinted glyph
  1110. // bounding box of the glyph encoded at U+0048 (LATIN CAPITAL LETTER H).
  1111. ch, err := f.glyphTopOS2(&b, ppem, 'H')
  1112. if err != nil {
  1113. return 0, 0, err
  1114. }
  1115. return int32(xh), int32(ch), nil
  1116. }
  1117. func (f *Font) parseOS2(buf []byte) (buf1 []byte, hasXHeightCapHeight bool, xHeight, capHeight int32, err error) {
  1118. // https://docs.microsoft.com/da-dk/typography/opentype/spec/os2
  1119. if f.os2.length == 0 {
  1120. // Apple TrueType fonts might omit the OS/2 table.
  1121. return buf, false, 0, 0, nil
  1122. } else if f.os2.length < 2 {
  1123. return nil, false, 0, 0, errInvalidOS2Table
  1124. }
  1125. vers, err := f.src.u16(buf, f.os2, 0)
  1126. if err != nil {
  1127. return nil, false, 0, 0, err
  1128. }
  1129. if vers < 2 {
  1130. // "The original TrueType specification had this table at 68 bytes long."
  1131. // https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6OS2.html
  1132. const headerSize = 68
  1133. if f.os2.length < headerSize {
  1134. return nil, false, 0, 0, errInvalidOS2Table
  1135. }
  1136. // Will resolve xHeight and capHeight later, see initOS2VersionBelow2.
  1137. return buf, false, 0, 0, nil
  1138. }
  1139. const headerSize = 96
  1140. if f.os2.length < headerSize {
  1141. return nil, false, 0, 0, errInvalidOS2Table
  1142. }
  1143. xh, err := f.src.u16(buf, f.os2, 86)
  1144. if err != nil {
  1145. return nil, false, 0, 0, err
  1146. }
  1147. ch, err := f.src.u16(buf, f.os2, 88)
  1148. if err != nil {
  1149. return nil, false, 0, 0, err
  1150. }
  1151. return buf, true, int32(int16(xh)), int32(int16(ch)), nil
  1152. }
  1153. // PostTable represents an information stored in the PostScript font section.
  1154. type PostTable struct {
  1155. // Version of the version tag of the "post" table.
  1156. Version uint32
  1157. // ItalicAngle in counter-clockwise degrees from the vertical. Zero for
  1158. // upright text, negative for text that leans to the right (forward).
  1159. ItalicAngle float64
  1160. // UnderlinePosition is the suggested distance of the top of the
  1161. // underline from the baseline (negative values indicate below baseline).
  1162. UnderlinePosition int16
  1163. // Suggested values for the underline thickness.
  1164. UnderlineThickness int16
  1165. // IsFixedPitch indicates that the font is not proportionally spaced
  1166. // (i.e. monospaced).
  1167. IsFixedPitch bool
  1168. }
  1169. // PostTable returns the information from the font's "post" table. It can
  1170. // return nil, if the font doesn't have such a table.
  1171. //
  1172. // See https://docs.microsoft.com/en-us/typography/opentype/spec/post
  1173. func (f *Font) PostTable() *PostTable {
  1174. return f.cached.post
  1175. }
  1176. func (f *Font) parsePost(buf []byte, numGlyphs int32) (buf1 []byte, post *PostTable, err error) {
  1177. // https://www.microsoft.com/typography/otspec/post.htm
  1178. const headerSize = 32
  1179. if f.post.length < headerSize {
  1180. return nil, nil, errInvalidPostTable
  1181. }
  1182. u, err := f.src.u32(buf, f.post, 0)
  1183. if err != nil {
  1184. return nil, nil, err
  1185. }
  1186. switch u {
  1187. case 0x10000:
  1188. // No-op.
  1189. case 0x20000:
  1190. if f.post.length < headerSize+2+2*uint32(numGlyphs) {
  1191. return nil, nil, errInvalidPostTable
  1192. }
  1193. case 0x30000:
  1194. // No-op.
  1195. default:
  1196. return nil, nil, errUnsupportedPostTable
  1197. }
  1198. ang, err := f.src.u32(buf, f.post, 4)
  1199. if err != nil {
  1200. return nil, nil, err
  1201. }
  1202. up, err := f.src.u16(buf, f.post, 8)
  1203. if err != nil {
  1204. return nil, nil, err
  1205. }
  1206. ut, err := f.src.u16(buf, f.post, 10)
  1207. if err != nil {
  1208. return nil, nil, err
  1209. }
  1210. fp, err := f.src.u32(buf, f.post, 12)
  1211. if err != nil {
  1212. return nil, nil, err
  1213. }
  1214. post = &PostTable{
  1215. Version: u,
  1216. ItalicAngle: float64(int32(ang)) / 0x10000,
  1217. UnderlinePosition: int16(up),
  1218. UnderlineThickness: int16(ut),
  1219. IsFixedPitch: fp != 0,
  1220. }
  1221. return buf, post, nil
  1222. }
  1223. // Bounds returns the union of a Font's glyphs' bounds.
  1224. //
  1225. // In the returned Rectangle26_6's (x, y) coordinates, the Y axis increases
  1226. // down.
  1227. func (f *Font) Bounds(b *Buffer, ppem fixed.Int26_6, h font.Hinting) (fixed.Rectangle26_6, error) {
  1228. // The 0, 3, 2, 1 indices are to flip the Y coordinates. OpenType's Y axis
  1229. // increases up. Go's standard graphics libraries' Y axis increases down.
  1230. r := fixed.Rectangle26_6{
  1231. Min: fixed.Point26_6{
  1232. X: +scale(fixed.Int26_6(f.cached.bounds[0])*ppem, f.cached.unitsPerEm),
  1233. Y: -scale(fixed.Int26_6(f.cached.bounds[3])*ppem, f.cached.unitsPerEm),
  1234. },
  1235. Max: fixed.Point26_6{
  1236. X: +scale(fixed.Int26_6(f.cached.bounds[2])*ppem, f.cached.unitsPerEm),
  1237. Y: -scale(fixed.Int26_6(f.cached.bounds[1])*ppem, f.cached.unitsPerEm),
  1238. },
  1239. }
  1240. if h == font.HintingFull {
  1241. // Quantize the Min down and Max up to a whole pixel.
  1242. r.Min.X = (r.Min.X + 0) &^ 63
  1243. r.Min.Y = (r.Min.Y + 0) &^ 63
  1244. r.Max.X = (r.Max.X + 63) &^ 63
  1245. r.Max.Y = (r.Max.Y + 63) &^ 63
  1246. }
  1247. return r, nil
  1248. }
  1249. // TODO: API for looking up glyph variants?? For example, some fonts may
  1250. // provide both slashed and dotted zero glyphs ('0'), or regular and 'old
  1251. // style' numerals, and users can direct software to choose a variant.
  1252. type glyphIndexFunc func(f *Font, b *Buffer, r rune) (GlyphIndex, error)
  1253. // GlyphIndex returns the glyph index for the given rune.
  1254. //
  1255. // It returns (0, nil) if there is no glyph for r.
  1256. // https://www.microsoft.com/typography/OTSPEC/cmap.htm says that "Character
  1257. // codes that do not correspond to any glyph in the font should be mapped to
  1258. // glyph index 0. The glyph at this location must be a special glyph
  1259. // representing a missing character, commonly known as .notdef."
  1260. func (f *Font) GlyphIndex(b *Buffer, r rune) (GlyphIndex, error) {
  1261. return f.cached.glyphIndex(f, b, r)
  1262. }
  1263. func (f *Font) viewGlyphData(b *Buffer, x GlyphIndex) (buf []byte, offset, length uint32, err error) {
  1264. xx := int(x)
  1265. if f.NumGlyphs() <= xx {
  1266. return nil, 0, 0, ErrNotFound
  1267. }
  1268. i := f.cached.glyphData.locations[xx+0]
  1269. j := f.cached.glyphData.locations[xx+1]
  1270. if j < i {
  1271. return nil, 0, 0, errInvalidGlyphDataLength
  1272. }
  1273. if j-i > maxGlyphDataLength {
  1274. return nil, 0, 0, errUnsupportedGlyphDataLength
  1275. }
  1276. buf, err = b.view(&f.src, int(i), int(j-i))
  1277. return buf, i, j - i, err
  1278. }
  1279. // LoadGlyphOptions are the options to the Font.LoadGlyph method.
  1280. type LoadGlyphOptions struct {
  1281. // TODO: transform / hinting.
  1282. }
  1283. // LoadGlyph returns the vector segments for the x'th glyph. ppem is the number
  1284. // of pixels in 1 em.
  1285. //
  1286. // If b is non-nil, the segments become invalid to use once b is re-used.
  1287. //
  1288. // In the returned Segments' (x, y) coordinates, the Y axis increases down.
  1289. //
  1290. // It returns ErrNotFound if the glyph index is out of range. It returns
  1291. // ErrColoredGlyph if the glyph is not a monochrome vector glyph, such as a
  1292. // colored (bitmap or vector) emoji glyph.
  1293. func (f *Font) LoadGlyph(b *Buffer, x GlyphIndex, ppem fixed.Int26_6, opts *LoadGlyphOptions) (Segments, error) {
  1294. if b == nil {
  1295. b = &Buffer{}
  1296. }
  1297. b.segments = b.segments[:0]
  1298. if f.cached.isColorBitmap {
  1299. return nil, ErrColoredGlyph
  1300. }
  1301. if f.cached.isPostScript {
  1302. buf, offset, length, err := f.viewGlyphData(b, x)
  1303. if err != nil {
  1304. return nil, err
  1305. }
  1306. b.psi.type2Charstrings.initialize(f, b, x)
  1307. if err := b.psi.run(psContextType2Charstring, buf, offset, length); err != nil {
  1308. return nil, err
  1309. }
  1310. if !b.psi.type2Charstrings.ended {
  1311. return nil, errInvalidCFFTable
  1312. }
  1313. } else if err := loadGlyf(f, b, x, 0, 0); err != nil {
  1314. return nil, err
  1315. }
  1316. // Scale the segments. If we want to support hinting, we'll have to push
  1317. // the scaling computation into the PostScript / TrueType specific glyph
  1318. // loading code, such as the appendGlyfSegments body, since TrueType
  1319. // hinting bytecode works on the scaled glyph vectors. For now, though,
  1320. // it's simpler to scale as a post-processing step.
  1321. //
  1322. // We also flip the Y coordinates. OpenType's Y axis increases up. Go's
  1323. // standard graphics libraries' Y axis increases down.
  1324. for i := range b.segments {
  1325. a := &b.segments[i].Args
  1326. for j := range a {
  1327. a[j].X = +scale(a[j].X*ppem, f.cached.unitsPerEm)
  1328. a[j].Y = -scale(a[j].Y*ppem, f.cached.unitsPerEm)
  1329. }
  1330. }
  1331. // TODO: look at opts to transform / hint the Buffer.segments.
  1332. return b.segments, nil
  1333. }
  1334. func (f *Font) glyphNameFormat10(x GlyphIndex) (string, error) {
  1335. if x >= numBuiltInPostNames {
  1336. return "", ErrNotFound
  1337. }
  1338. // https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6post.html
  1339. i := builtInPostNamesOffsets[x+0]
  1340. j := builtInPostNamesOffsets[x+1]
  1341. return builtInPostNamesData[i:j], nil
  1342. }
  1343. func (f *Font) glyphNameFormat20(b *Buffer, x GlyphIndex) (string, error) {
  1344. if b == nil {
  1345. b = &Buffer{}
  1346. }
  1347. // The wire format for a Version 2 post table is documented at:
  1348. // https://www.microsoft.com/typography/otspec/post.htm
  1349. const glyphNameIndexOffset = 34
  1350. buf, err := b.view(&f.src, int(f.post.offset)+glyphNameIndexOffset+2*int(x), 2)
  1351. if err != nil {
  1352. return "", err
  1353. }
  1354. u := u16(buf)
  1355. if u < numBuiltInPostNames {
  1356. i := builtInPostNamesOffsets[u+0]
  1357. j := builtInPostNamesOffsets[u+1]
  1358. return builtInPostNamesData[i:j], nil
  1359. }
  1360. // https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6post.html
  1361. // says that "32768 through 65535 are reserved for future use".
  1362. if u > 32767 {
  1363. return "", errUnsupportedPostTable
  1364. }
  1365. u -= numBuiltInPostNames
  1366. // Iterate through the list of Pascal-formatted strings. A linear scan is
  1367. // clearly O(u), which isn't great (as the obvious loop, calling
  1368. // Font.GlyphName, to get all of the glyph names in a font has quadratic
  1369. // complexity), but the wire format doesn't suggest a better alternative.
  1370. offset := glyphNameIndexOffset + 2*f.NumGlyphs()
  1371. buf, err = b.view(&f.src, int(f.post.offset)+offset, int(f.post.length)-offset)
  1372. if err != nil {
  1373. return "", err
  1374. }
  1375. for {
  1376. if len(buf) == 0 {
  1377. return "", errInvalidPostTable
  1378. }
  1379. n := 1 + int(buf[0])
  1380. if len(buf) < n {
  1381. return "", errInvalidPostTable
  1382. }
  1383. if u == 0 {
  1384. return string(buf[1:n]), nil
  1385. }
  1386. buf = buf[n:]
  1387. u--
  1388. }
  1389. }
  1390. // GlyphName returns the name of the x'th glyph.
  1391. //
  1392. // Not every font contains glyph names. If not present, GlyphName will return
  1393. // ("", nil).
  1394. //
  1395. // If present, the glyph name, provided by the font, is assumed to follow the
  1396. // Adobe Glyph List Specification:
  1397. // https://github.com/adobe-type-tools/agl-specification/blob/master/README.md
  1398. //
  1399. // This is also known as the "Adobe Glyph Naming convention", the "Adobe
  1400. // document [for] Unicode and Glyph Names" or "PostScript glyph names".
  1401. //
  1402. // It returns ErrNotFound if the glyph index is out of range.
  1403. func (f *Font) GlyphName(b *Buffer, x GlyphIndex) (string, error) {
  1404. if int(x) >= f.NumGlyphs() {
  1405. return "", ErrNotFound
  1406. }
  1407. if f.cached.post == nil {
  1408. return "", nil
  1409. }
  1410. switch f.cached.post.Version {
  1411. case 0x10000:
  1412. return f.glyphNameFormat10(x)
  1413. case 0x20000:
  1414. return f.glyphNameFormat20(b, x)
  1415. default:
  1416. return "", nil
  1417. }
  1418. }
  1419. // GlyphBounds returns the bounding box of the x'th glyph, drawn at a dot equal
  1420. // to the origin, and that glyph's advance width. ppem is the number of pixels
  1421. // in 1 em.
  1422. //
  1423. // It returns ErrNotFound if the glyph index is out of range.
  1424. //
  1425. // The glyph's ascent and descent are equal to -bounds.Min.Y and +bounds.Max.Y.
  1426. // The glyph's left-side and right-side bearings are equal to bounds.Min.X and
  1427. // advance-bounds.Max.X. A visual depiction of what these metrics are is at
  1428. // https://developer.apple.com/library/archive/documentation/TextFonts/Conceptual/CocoaTextArchitecture/Art/glyphterms_2x.png
  1429. func (f *Font) GlyphBounds(b *Buffer, x GlyphIndex, ppem fixed.Int26_6, h font.Hinting) (bounds fixed.Rectangle26_6, advance fixed.Int26_6, err error) {
  1430. if int(x) >= f.NumGlyphs() {
  1431. return fixed.Rectangle26_6{}, 0, ErrNotFound
  1432. }
  1433. if b == nil {
  1434. b = &Buffer{}
  1435. }
  1436. // https://www.microsoft.com/typography/OTSPEC/hmtx.htm says that "As an
  1437. // optimization, the number of records can be less than the number of
  1438. // glyphs, in which case the advance width value of the last record applies
  1439. // to all remaining glyph IDs."
  1440. metricIndex := x
  1441. if n := GlyphIndex(f.cached.numHMetrics - 1); x > n {
  1442. metricIndex = n
  1443. }
  1444. buf, err := b.view(&f.src, int(f.hmtx.offset)+4*int(metricIndex), 2)
  1445. if err != nil {
  1446. return fixed.Rectangle26_6{}, 0, err
  1447. }
  1448. advance = fixed.Int26_6(u16(buf))
  1449. advance = scale(advance*ppem, f.cached.unitsPerEm)
  1450. if h == font.HintingFull {
  1451. // Quantize the fixed.Int26_6 value to the nearest pixel.
  1452. advance = (advance + 32) &^ 63
  1453. }
  1454. // Ignore the hmtx LSB entries and the glyf bounding boxes. Instead, always
  1455. // calculate bounds from the segments. OpenType does contain the bounds for
  1456. // each glyph in the glyf table, but the bounds are not available for
  1457. // compound glyphs. CFF/PostScript also have no explicit bounds and must be
  1458. // obtained from the segments.
  1459. segments, err := f.LoadGlyph(b, x, ppem, &LoadGlyphOptions{
  1460. // TODO: pass h, the font.Hinting.
  1461. })
  1462. if err != nil {
  1463. return fixed.Rectangle26_6{}, 0, err
  1464. }
  1465. return segments.Bounds(), advance, nil
  1466. }
  1467. // GlyphAdvance returns the advance width for the x'th glyph. ppem is the
  1468. // number of pixels in 1 em.
  1469. //
  1470. // It returns ErrNotFound if the glyph index is out of range.
  1471. func (f *Font) GlyphAdvance(b *Buffer, x GlyphIndex, ppem fixed.Int26_6, h font.Hinting) (fixed.Int26_6, error) {
  1472. if int(x) >= f.NumGlyphs() {
  1473. return 0, ErrNotFound
  1474. }
  1475. if b == nil {
  1476. b = &Buffer{}
  1477. }
  1478. // https://www.microsoft.com/typography/OTSPEC/hmtx.htm says that "As an
  1479. // optimization, the number of records can be less than the number of
  1480. // glyphs, in which case the advance width value of the last record applies
  1481. // to all remaining glyph IDs."
  1482. if n := GlyphIndex(f.cached.numHMetrics - 1); x > n {
  1483. x = n
  1484. }
  1485. buf, err := b.view(&f.src, int(f.hmtx.offset)+4*int(x), 2)
  1486. if err != nil {
  1487. return 0, err
  1488. }
  1489. adv := fixed.Int26_6(u16(buf))
  1490. adv = scale(adv*ppem, f.cached.unitsPerEm)
  1491. if h == font.HintingFull {
  1492. // Quantize the fixed.Int26_6 value to the nearest pixel.
  1493. adv = (adv + 32) &^ 63
  1494. }
  1495. return adv, nil
  1496. }
  1497. // Kern returns the horizontal adjustment for the kerning pair (x0, x1). A
  1498. // positive kern means to move the glyphs further apart. ppem is the number of
  1499. // pixels in 1 em.
  1500. //
  1501. // It returns ErrNotFound if either glyph index is out of range.
  1502. func (f *Font) Kern(b *Buffer, x0, x1 GlyphIndex, ppem fixed.Int26_6, h font.Hinting) (fixed.Int26_6, error) {
  1503. // Use GPOS kern tables if available.
  1504. if f.cached.kernFuncs != nil {
  1505. for _, kf := range f.cached.kernFuncs {
  1506. adv, err := kf(x0, x1)
  1507. if err == ErrNotFound {
  1508. continue
  1509. }
  1510. if err != nil {
  1511. return 0, err
  1512. }
  1513. kern := fixed.Int26_6(adv)
  1514. kern = scale(kern*ppem, f.cached.unitsPerEm)
  1515. if h == font.HintingFull {
  1516. // Quantize the fixed.Int26_6 value to the nearest pixel.
  1517. kern = (kern + 32) &^ 63
  1518. }
  1519. return kern, nil
  1520. }
  1521. return 0, ErrNotFound
  1522. }
  1523. // Fallback to kern table.
  1524. // TODO: Convert kern table handling into kernFunc and decide in Parse if
  1525. // GPOS or kern should be used.
  1526. if n := f.NumGlyphs(); int(x0) >= n || int(x1) >= n {
  1527. return 0, ErrNotFound
  1528. }
  1529. // Not every font has a kern table. If it doesn't, or if that table is
  1530. // ignored, there's no need to allocate a Buffer.
  1531. if f.cached.kernNumPairs == 0 {
  1532. return 0, nil
  1533. }
  1534. if b == nil {
  1535. b = &Buffer{}
  1536. }
  1537. key := uint32(x0)<<16 | uint32(x1)
  1538. lo, hi := int32(0), f.cached.kernNumPairs
  1539. for lo < hi {
  1540. i := (lo + hi) / 2
  1541. // TODO: this view call inside the inner loop can lead to many small
  1542. // reads instead of fewer larger reads, which can be expensive. We
  1543. // should be able to do better, although we don't want to make (one)
  1544. // arbitrarily large read. Perhaps we should round up reads to 4K or 8K
  1545. // chunks. For reference, Arial.ttf's kern table is 5472 bytes.
  1546. // Times_New_Roman.ttf's kern table is 5220 bytes.
  1547. const entrySize = 6
  1548. buf, err := b.view(&f.src, int(f.cached.kernOffset+i*entrySize), entrySize)
  1549. if err != nil {
  1550. return 0, err
  1551. }
  1552. k := u32(buf)
  1553. if k < key {
  1554. lo = i + 1
  1555. } else if k > key {
  1556. hi = i
  1557. } else {
  1558. kern := fixed.Int26_6(int16(u16(buf[4:])))
  1559. kern = scale(kern*ppem, f.cached.unitsPerEm)
  1560. if h == font.HintingFull {
  1561. // Quantize the fixed.Int26_6 value to the nearest pixel.
  1562. kern = (kern + 32) &^ 63
  1563. }
  1564. return kern, nil
  1565. }
  1566. }
  1567. return 0, nil
  1568. }
  1569. // Metrics returns the metrics of this font.
  1570. func (f *Font) Metrics(b *Buffer, ppem fixed.Int26_6, h font.Hinting) (font.Metrics, error) {
  1571. m := font.Metrics{
  1572. Height: scale(fixed.Int26_6(f.cached.ascent-f.cached.descent+f.cached.lineGap)*ppem, f.cached.unitsPerEm),
  1573. Ascent: +scale(fixed.Int26_6(f.cached.ascent)*ppem, f.cached.unitsPerEm),
  1574. Descent: -scale(fixed.Int26_6(f.cached.descent)*ppem, f.cached.unitsPerEm),
  1575. XHeight: scale(fixed.Int26_6(f.cached.xHeight)*ppem, f.cached.unitsPerEm),
  1576. CapHeight: scale(fixed.Int26_6(f.cached.capHeight)*ppem, f.cached.unitsPerEm),
  1577. CaretSlope: image.Point{X: int(f.cached.slope[0]), Y: int(f.cached.slope[1])},
  1578. }
  1579. if h == font.HintingFull {
  1580. // Quantize up to a whole pixel.
  1581. m.Height = (m.Height + 63) &^ 63
  1582. m.Ascent = (m.Ascent + 63) &^ 63
  1583. m.Descent = (m.Descent + 63) &^ 63
  1584. m.XHeight = (m.XHeight + 63) &^ 63
  1585. m.CapHeight = (m.CapHeight + 63) &^ 63
  1586. }
  1587. return m, nil
  1588. }
  1589. // WriteSourceTo writes the source data (the []byte or io.ReaderAt passed to
  1590. // Parse or ParseReaderAt) to w.
  1591. //
  1592. // It returns the number of bytes written. On success, this is the final offset
  1593. // of the furthest SFNT table in the source. This may be less than the length
  1594. // of the []byte or io.ReaderAt originally passed.
  1595. func (f *Font) WriteSourceTo(b *Buffer, w io.Writer) (int64, error) {
  1596. if f.initialOffset != 0 {
  1597. // TODO: when extracting a single font (i.e. TTF) out of a font
  1598. // collection (i.e. TTC), write only the i'th font and not the (i-1)
  1599. // previous fonts. Subtly, in the file format, table offsets may be
  1600. // relative to the start of the resource (for dfont collections) or the
  1601. // start of the file (otherwise). If we were to extract a single font
  1602. // here, we might need to dynamically patch the table offsets, bearing
  1603. // in mind that f.src.b is conceptually a 'read-only' slice of bytes.
  1604. return 0, errUnsupportedCollection
  1605. }
  1606. if f.src.b != nil {
  1607. n, err := w.Write(f.src.b[:f.cached.finalTableOffset])
  1608. return int64(n), err
  1609. }
  1610. // We have an io.ReaderAt source, not a []byte. It is tempting to see if
  1611. // the io.ReaderAt optionally implements the io.WriterTo interface, but we
  1612. // don't for two reasons:
  1613. // - We want to write exactly f.cached.finalTableOffset bytes, even if the
  1614. // underlying 'file' is larger, to be consistent with the []byte flavor.
  1615. // - We document that "Font methods are safe to call concurrently" and
  1616. // while io.ReaderAt is stateless (the offset is an argument), the
  1617. // io.Reader / io.Writer abstractions are stateful (the current position
  1618. // is a field) and mutable state generally isn't concurrent-safe.
  1619. if b == nil {
  1620. b = &Buffer{}
  1621. }
  1622. finalTableOffset := int(f.cached.finalTableOffset)
  1623. numBytesWritten := int64(0)
  1624. for offset := 0; offset < finalTableOffset; {
  1625. length := finalTableOffset - offset
  1626. if length > 4096 {
  1627. length = 4096
  1628. }
  1629. view, err := b.view(&f.src, offset, length)
  1630. if err != nil {
  1631. return numBytesWritten, err
  1632. }
  1633. n, err := w.Write(view)
  1634. numBytesWritten += int64(n)
  1635. if err != nil {
  1636. return numBytesWritten, err
  1637. }
  1638. offset += length
  1639. }
  1640. return numBytesWritten, nil
  1641. }
  1642. // Name returns the name value keyed by the given NameID.
  1643. //
  1644. // It returns ErrNotFound if there is no value for that key.
  1645. func (f *Font) Name(b *Buffer, id NameID) (string, error) {
  1646. if b == nil {
  1647. b = &Buffer{}
  1648. }
  1649. const headerSize, entrySize = 6, 12
  1650. if f.name.length < headerSize {
  1651. return "", errInvalidNameTable
  1652. }
  1653. buf, err := b.view(&f.src, int(f.name.offset), headerSize)
  1654. if err != nil {
  1655. return "", err
  1656. }
  1657. numSubtables := u16(buf[2:])
  1658. if f.name.length < headerSize+entrySize*uint32(numSubtables) {
  1659. return "", errInvalidNameTable
  1660. }
  1661. stringOffset := u16(buf[4:])
  1662. seen := false
  1663. for i, n := 0, int(numSubtables); i < n; i++ {
  1664. buf, err := b.view(&f.src, int(f.name.offset)+headerSize+entrySize*i, entrySize)
  1665. if err != nil {
  1666. return "", err
  1667. }
  1668. if u16(buf[6:]) != uint16(id) {
  1669. continue
  1670. }
  1671. seen = true
  1672. var stringify func([]byte) (string, error)
  1673. switch u32(buf) {
  1674. default:
  1675. continue
  1676. case pidMacintosh<<16 | psidMacintoshRoman:
  1677. stringify = stringifyMacintosh
  1678. case pidWindows<<16 | psidWindowsUCS2:
  1679. stringify = stringifyUCS2
  1680. }
  1681. nameLength := u16(buf[8:])
  1682. nameOffset := u16(buf[10:])
  1683. buf, err = b.view(&f.src, int(f.name.offset)+int(nameOffset)+int(stringOffset), int(nameLength))
  1684. if err != nil {
  1685. return "", err
  1686. }
  1687. return stringify(buf)
  1688. }
  1689. if seen {
  1690. return "", errUnsupportedPlatformEncoding
  1691. }
  1692. return "", ErrNotFound
  1693. }
  1694. func stringifyMacintosh(b []byte) (string, error) {
  1695. for _, c := range b {
  1696. if c >= 0x80 {
  1697. // b contains some non-ASCII bytes.
  1698. s, _ := charmap.Macintosh.NewDecoder().Bytes(b)
  1699. return string(s), nil
  1700. }
  1701. }
  1702. // b contains only ASCII bytes.
  1703. return string(b), nil
  1704. }
  1705. func stringifyUCS2(b []byte) (string, error) {
  1706. if len(b)&1 != 0 {
  1707. return "", errInvalidUCS2String
  1708. }
  1709. r := make([]rune, len(b)/2)
  1710. for i := range r {
  1711. r[i] = rune(u16(b))
  1712. b = b[2:]
  1713. }
  1714. return string(r), nil
  1715. }
  1716. // Buffer holds re-usable buffers that can reduce the total memory allocation
  1717. // of repeated Font method calls.
  1718. //
  1719. // See the Font type's documentation comment for more details.
  1720. type Buffer struct {
  1721. // buf is a byte buffer for when a Font's source is an io.ReaderAt.
  1722. buf []byte
  1723. // segments holds glyph vector path segments.
  1724. segments Segments
  1725. // compoundStack holds the components of a TrueType compound glyph.
  1726. compoundStack [maxCompoundStackSize]struct {
  1727. glyphIndex GlyphIndex
  1728. dx, dy int16
  1729. hasTransform bool
  1730. transformXX int16
  1731. transformXY int16
  1732. transformYX int16
  1733. transformYY int16
  1734. }
  1735. // psi is a PostScript interpreter for when the Font is an OpenType/CFF
  1736. // font.
  1737. psi psInterpreter
  1738. }
  1739. func (b *Buffer) view(src *source, offset, length int) ([]byte, error) {
  1740. buf, err := src.view(b.buf, offset, length)
  1741. if err != nil {
  1742. return nil, err
  1743. }
  1744. // Only update b.buf if it is safe to re-use buf.
  1745. if src.viewBufferWritable() {
  1746. b.buf = buf
  1747. }
  1748. return buf, nil
  1749. }
  1750. // Segment is a segment of a vector path.
  1751. type Segment struct {
  1752. // Op is the operator.
  1753. Op SegmentOp
  1754. // Args is up to three (x, y) coordinates. The Y axis increases down.
  1755. Args [3]fixed.Point26_6
  1756. }
  1757. // SegmentOp is a vector path segment's operator.
  1758. type SegmentOp uint32
  1759. const (
  1760. SegmentOpMoveTo SegmentOp = iota
  1761. SegmentOpLineTo
  1762. SegmentOpQuadTo
  1763. SegmentOpCubeTo
  1764. )
  1765. // Segments is a slice of Segment.
  1766. type Segments []Segment
  1767. // Bounds returns s' bounding box. It returns an empty rectangle if s is empty.
  1768. func (s Segments) Bounds() (bounds fixed.Rectangle26_6) {
  1769. if len(s) == 0 {
  1770. return fixed.Rectangle26_6{}
  1771. }
  1772. bounds.Min.X = fixed.Int26_6(+(1 << 31) - 1)
  1773. bounds.Min.Y = fixed.Int26_6(+(1 << 31) - 1)
  1774. bounds.Max.X = fixed.Int26_6(-(1 << 31) + 0)
  1775. bounds.Max.Y = fixed.Int26_6(-(1 << 31) + 0)
  1776. for _, seg := range s {
  1777. n := 1
  1778. switch seg.Op {
  1779. case SegmentOpQuadTo:
  1780. n = 2
  1781. case SegmentOpCubeTo:
  1782. n = 3
  1783. }
  1784. for i := 0; i < n; i++ {
  1785. if bounds.Max.X < seg.Args[i].X {
  1786. bounds.Max.X = seg.Args[i].X
  1787. }
  1788. if bounds.Min.X > seg.Args[i].X {
  1789. bounds.Min.X = seg.Args[i].X
  1790. }
  1791. if bounds.Max.Y < seg.Args[i].Y {
  1792. bounds.Max.Y = seg.Args[i].Y
  1793. }
  1794. if bounds.Min.Y > seg.Args[i].Y {
  1795. bounds.Min.Y = seg.Args[i].Y
  1796. }
  1797. }
  1798. }
  1799. return bounds
  1800. }
  1801. // translateArgs applies a translation to args.
  1802. func translateArgs(args *[3]fixed.Point26_6, dx, dy fixed.Int26_6) {
  1803. args[0].X += dx
  1804. args[0].Y += dy
  1805. args[1].X += dx
  1806. args[1].Y += dy
  1807. args[2].X += dx
  1808. args[2].Y += dy
  1809. }
  1810. // transformArgs applies an affine transformation to args. The t?? arguments
  1811. // are 2.14 fixed point values.
  1812. func transformArgs(args *[3]fixed.Point26_6, txx, txy, tyx, tyy int16, dx, dy fixed.Int26_6) {
  1813. args[0] = tform(txx, txy, tyx, tyy, dx, dy, args[0])
  1814. args[1] = tform(txx, txy, tyx, tyy, dx, dy, args[1])
  1815. args[2] = tform(txx, txy, tyx, tyy, dx, dy, args[2])
  1816. }
  1817. func tform(txx, txy, tyx, tyy int16, dx, dy fixed.Int26_6, p fixed.Point26_6) fixed.Point26_6 {
  1818. const half = 1 << 13
  1819. return fixed.Point26_6{
  1820. X: dx +
  1821. fixed.Int26_6((int64(p.X)*int64(txx)+half)>>14) +
  1822. fixed.Int26_6((int64(p.Y)*int64(tyx)+half)>>14),
  1823. Y: dy +
  1824. fixed.Int26_6((int64(p.X)*int64(txy)+half)>>14) +
  1825. fixed.Int26_6((int64(p.Y)*int64(tyy)+half)>>14),
  1826. }
  1827. }