packages feed

ktx-build-0.1.0.0: app/Build/Slug.hs

module Build.Slug
  ( outlines
  ) where

import Codec.Ktx2.Font.Slug (Curve(..), FillRule(..), Point(..), Shape(..))
import Codec.TTF.Reader qualified as TTF
import Control.DeepSeq (force)
import Control.Exception (evaluate, throw, try)
import Control.Monad (unless)
import Data.ByteString qualified as ByteString
import Data.Foldable (for_)
import Data.Traversable (for)

outlines :: FilePath -> IO [Shape]
outlines path = do
  bytes <- ByteString.readFile path
  let
    tables = TTF.readTableDirectory bytes
    record tag = TTF.lookupTableRecord tables tag
    table tag = TTF.getTableData bytes (record tag)
    numGlyphs = TTF.readNumGlyphs (table TTF.TableTag_maxp)
    loca = TTF.readLoca (TTF.readIndexToLocFormat (table TTF.TableTag_head)) numGlyphs (table TTF.TableTag_loca)
    glyf = table TTF.TableTag_glyf
    glyphIds = [0 .. numGlyphs - 1]
    segmentsOf glyphId =
      maybe (throw TTF.MalformedTTF) (map TTF.contourSegments) $
        TTF.readGlyphOutline loca glyf glyphId

  unless (TTF.readFontFormat bytes == Just TTF.TrueType && hasTable (record TTF.TableTag_glyf)) $
    fail $ path <> ": no TrueType glyf outlines"

  for_ [("loca", () <$ evaluate loca), ("glyf", () <$ evaluate glyf)] \(name, check) ->
    try @TTF.TTFException check >>= \case
      Left err -> fail $ path <> ": " <> show err <> " in the " <> name <> " table"
      Right () -> pure ()

  parsed <- for glyphIds \glyphId ->
    try @TTF.TTFException . evaluate . force $ segmentsOf glyphId

  let malformed = [glyphId | (glyphId, Left _) <- zip glyphIds parsed]
  unless (null malformed) $
    fail $ path <> ": malformed outlines for glyphs " <> show malformed

  pure [toShape segments | Right segments <- parsed]
  where
    hasTable = \case
      TTF.NoTableRecord -> False
      _ -> True

toShape :: [[TTF.Segment]] -> Shape
toShape = Shape NonZero . filter (not . null) . map (map toCurve)

toCurve :: TTF.Segment -> Curve
toCurve = \case
  TTF.LineSegment a b -> Curve (toPoint a) (toPoint b) (toPoint b)
  TTF.QuadraticSegment a c b -> Curve (toPoint a) (toPoint c) (toPoint b)

toPoint :: TTF.Point -> Point
toPoint p = Point (realToFrac p.x) (realToFrac p.y)