ktx-font 0.3.0.0 → 0.4.0.0
raw patch · 7 files changed
+777/−44 lines, 7 filesdep +halfdep ~kb-text-layoutPVP ok
version bump matches the API change (PVP)
Dependencies added: half
Dependency ranges changed: kb-text-layout
API changes (from Hackage documentation)
+ Codec.Ktx2.Font: SlugBundle :: Vector (Maybe Glyph) -> ByteString -> SlugBundle
+ Codec.Ktx2.Font: [bandsZstd] :: SlugBundle -> ByteString
+ Codec.Ktx2.Font: [glyphs] :: SlugBundle -> Vector (Maybe Glyph)
+ Codec.Ktx2.Font: [slug] :: Bundle -> Maybe SlugBundle
+ Codec.Ktx2.Font: bundleSlug :: FilePath -> Tables -> FilePath -> FilePath -> IO ()
+ Codec.Ktx2.Font: data SlugBundle
+ Codec.Ktx2.Font: instance GHC.Classes.Eq Codec.Ktx2.Font.SlugBundle
+ Codec.Ktx2.Font: instance GHC.Show.Show Codec.Ktx2.Font.SlugBundle
+ Codec.Ktx2.Font: packSlugFont :: FilePath -> [Shape] -> IO Packed
+ Codec.Ktx2.Font: pattern KTX_KEY_slug_bands :: Text
+ Codec.Ktx2.Font: pattern KTX_KEY_slug_glyphs :: Text
+ Codec.Ktx2.Font: pattern KTX_KEY_slug_version :: Text
+ Codec.Ktx2.Font: slugVersion :: Text
+ Codec.Ktx2.Font.Layout: AlignJustify :: Align
+ Codec.Ktx2.Font.Layout: KeepWords :: Overflow
+ Codec.Ktx2.Font.Layout: SplitWords :: Overflow
+ Codec.Ktx2.Font.Layout: [overflow] :: LayoutOptions -> !Overflow
+ Codec.Ktx2.Font.Layout: [overfull] :: PlacedLine -> Bool
+ Codec.Ktx2.Font.Layout: data Overflow
+ Codec.Ktx2.Font.Slug: Curve :: Point -> Point -> Point -> Curve
+ Codec.Ktx2.Font.Slug: EvenOdd :: FillRule
+ Codec.Ktx2.Font.Slug: Glyph :: Box -> Int -> Int -> Int -> FillRule -> Glyph
+ Codec.Ktx2.Font.Slug: NonZero :: FillRule
+ Codec.Ktx2.Font.Slug: Packed :: Vector Half -> Tables -> Packed
+ Codec.Ktx2.Font.Slug: Point :: Float -> Float -> Point
+ Codec.Ktx2.Font.Slug: Shape :: FillRule -> [Contour] -> Shape
+ Codec.Ktx2.Font.Slug: Tables :: Vector Float -> Vector (Maybe Glyph) -> Tables
+ Codec.Ktx2.Font.Slug: [bandsOffset] :: Glyph -> Int
+ Codec.Ktx2.Font.Slug: [bands] :: Tables -> Vector Float
+ Codec.Ktx2.Font.Slug: [contours] :: Shape -> [Contour]
+ Codec.Ktx2.Font.Slug: [curves] :: Packed -> Vector Half
+ Codec.Ktx2.Font.Slug: [fillRule] :: Shape -> FillRule
+ Codec.Ktx2.Font.Slug: [glyphs] :: Tables -> Vector (Maybe Glyph)
+ Codec.Ktx2.Font.Slug: [horizontalBands] :: Glyph -> Int
+ Codec.Ktx2.Font.Slug: [p1] :: Curve -> Point
+ Codec.Ktx2.Font.Slug: [p2] :: Curve -> Point
+ Codec.Ktx2.Font.Slug: [p3] :: Curve -> Point
+ Codec.Ktx2.Font.Slug: [plane] :: Glyph -> Box
+ Codec.Ktx2.Font.Slug: [tables] :: Packed -> Tables
+ Codec.Ktx2.Font.Slug: [verticalBands] :: Glyph -> Int
+ Codec.Ktx2.Font.Slug: [x] :: Point -> Float
+ Codec.Ktx2.Font.Slug: [y] :: Point -> Float
+ Codec.Ktx2.Font.Slug: bandTransform :: Glyph -> (Float, Float, Float, Float)
+ Codec.Ktx2.Font.Slug: data Curve
+ Codec.Ktx2.Font.Slug: data FillRule
+ Codec.Ktx2.Font.Slug: data Glyph
+ Codec.Ktx2.Font.Slug: data Packed
+ Codec.Ktx2.Font.Slug: data Point
+ Codec.Ktx2.Font.Slug: data Shape
+ Codec.Ktx2.Font.Slug: data Tables
+ Codec.Ktx2.Font.Slug: dataWidth :: Int
+ Codec.Ktx2.Font.Slug: dataWidthLog2 :: Int
+ Codec.Ktx2.Font.Slug: decodeBands :: ByteString -> Either String (Vector Float)
+ Codec.Ktx2.Font.Slug: encodeBands :: Vector Float -> ByteString
+ Codec.Ktx2.Font.Slug: encodeCurves :: Vector Half -> ByteString
+ Codec.Ktx2.Font.Slug: instance Data.Aeson.Types.FromJSON.FromJSON Codec.Ktx2.Font.Slug.FillRule
+ Codec.Ktx2.Font.Slug: instance Data.Aeson.Types.FromJSON.FromJSON Codec.Ktx2.Font.Slug.Glyph
+ Codec.Ktx2.Font.Slug: instance Data.Aeson.Types.ToJSON.ToJSON Codec.Ktx2.Font.Slug.FillRule
+ Codec.Ktx2.Font.Slug: instance Data.Aeson.Types.ToJSON.ToJSON Codec.Ktx2.Font.Slug.Glyph
+ Codec.Ktx2.Font.Slug: instance GHC.Base.Monoid Codec.Ktx2.Font.Slug.Bounds
+ Codec.Ktx2.Font.Slug: instance GHC.Base.Semigroup Codec.Ktx2.Font.Slug.Bounds
+ Codec.Ktx2.Font.Slug: instance GHC.Classes.Eq Codec.Ktx2.Font.Slug.Curve
+ Codec.Ktx2.Font.Slug: instance GHC.Classes.Eq Codec.Ktx2.Font.Slug.FillRule
+ Codec.Ktx2.Font.Slug: instance GHC.Classes.Eq Codec.Ktx2.Font.Slug.Glyph
+ Codec.Ktx2.Font.Slug: instance GHC.Classes.Eq Codec.Ktx2.Font.Slug.Packed
+ Codec.Ktx2.Font.Slug: instance GHC.Classes.Eq Codec.Ktx2.Font.Slug.Point
+ Codec.Ktx2.Font.Slug: instance GHC.Classes.Eq Codec.Ktx2.Font.Slug.Shape
+ Codec.Ktx2.Font.Slug: instance GHC.Classes.Eq Codec.Ktx2.Font.Slug.Tables
+ Codec.Ktx2.Font.Slug: instance GHC.Classes.Ord Codec.Ktx2.Font.Slug.FillRule
+ Codec.Ktx2.Font.Slug: instance GHC.Classes.Ord Codec.Ktx2.Font.Slug.Point
+ Codec.Ktx2.Font.Slug: instance GHC.Enum.Bounded Codec.Ktx2.Font.Slug.FillRule
+ Codec.Ktx2.Font.Slug: instance GHC.Enum.Enum Codec.Ktx2.Font.Slug.FillRule
+ Codec.Ktx2.Font.Slug: instance GHC.Generics.Generic Codec.Ktx2.Font.Slug.FillRule
+ Codec.Ktx2.Font.Slug: instance GHC.Generics.Generic Codec.Ktx2.Font.Slug.Glyph
+ Codec.Ktx2.Font.Slug: instance GHC.Show.Show Codec.Ktx2.Font.Slug.Curve
+ Codec.Ktx2.Font.Slug: instance GHC.Show.Show Codec.Ktx2.Font.Slug.FillRule
+ Codec.Ktx2.Font.Slug: instance GHC.Show.Show Codec.Ktx2.Font.Slug.Glyph
+ Codec.Ktx2.Font.Slug: instance GHC.Show.Show Codec.Ktx2.Font.Slug.Packed
+ Codec.Ktx2.Font.Slug: instance GHC.Show.Show Codec.Ktx2.Font.Slug.Point
+ Codec.Ktx2.Font.Slug: instance GHC.Show.Show Codec.Ktx2.Font.Slug.Shape
+ Codec.Ktx2.Font.Slug: instance GHC.Show.Show Codec.Ktx2.Font.Slug.Tables
+ Codec.Ktx2.Font.Slug: line :: Point -> Point -> Curve
+ Codec.Ktx2.Font.Slug: pack :: [Shape] -> Packed
+ Codec.Ktx2.Font.Slug: scaleShape :: Float -> Shape -> Shape
+ Codec.Ktx2.Font.Slug: type Contour = [Curve]
- Codec.Ktx2.Font: Bundle :: FontData -> Compact -> Bundle
+ Codec.Ktx2.Font: Bundle :: FontData -> Compact -> Maybe SlugBundle -> Bundle
- Codec.Ktx2.Font.Layout: LayoutOptions :: Cursor -> Strategy -> Align -> LayoutOptions
+ Codec.Ktx2.Font.Layout: LayoutOptions :: Cursor -> Strategy -> Align -> !Overflow -> LayoutOptions
- Codec.Ktx2.Font.Layout: PlacedLine :: [PlacedRun] -> Text -> Float -> LineEnd -> (Float, Float) -> PlacedLine
+ Codec.Ktx2.Font.Layout: PlacedLine :: [PlacedRun] -> Text -> Float -> LineEnd -> Bool -> (Float, Float) -> PlacedLine
- Codec.Ktx2.Font.Layout: shrinkwrapText :: StackContext a -> TextStyle -> Float -> Text -> IO Float
+ Codec.Ktx2.Font.Layout: shrinkwrapText :: Overflow -> StackContext a -> TextStyle -> Float -> Text -> IO Float
Files
- CHANGELOG.md +31/−0
- demo/Main.hs +1/−0
- ktx-font.cabal +9/−3
- src/Codec/Ktx2/Font.hs +108/−15
- src/Codec/Ktx2/Font/Layout.hs +54/−17
- src/Codec/Ktx2/Font/Slug.hs +359/−0
- test/Spec.hs +215/−9
CHANGELOG.md view
@@ -6,6 +6,37 @@ and this project adheres to the [Haskell Package Versioning Policy](https://pvp.haskell.org/). +## 0.4.0.0 - 2026-12-02++- Added `Codec.Ktx2.Font.Slug` to pack quadratic outlines into curve and band data for the Slug renderer.+ Planes are `Box`es in the outline units, which are cap heights for Keid fonts.+ The data uses linear indices into 4096-texel rows. Curve runs and band lists may cross rows.+- Added Slug bundles.+ `packSlugFont` scales font-unit outlines by the cap height that shaping uses. `bundleSlug` writes the bundle.+ The KTX2 image holds the curves as `R16G16B16A16_SFLOAT`.+ The `slug-glyphs` entry holds the glyph table, and `slug-bands` the little-endian band values. `slug-version` pins the layout.+- Breaking: `Bundle` gains `slug`, a `SlugBundle` with the glyph table and the band values.+ The bands stay zstd-compressed. Renderers can unpack them straight into staging memory.+ `loadBundle` accepts Slug bundles and gives them a plane-only `atlas` for shaping.+ Its `glyphs` boxes are empty and its `_type` is a placeholder. Don't feed it to MSDF pipelines.+- Breaking: `Layout.Align` gains `AlignJustify`.+ `placeText` spreads the slack of wrapped and hyphenated lines over the spaces between their words, in proportion to the space widths.+ Leading spaces keep their width. Lines that end a paragraph or a hard break keep their natural spacing.+- `placeText` with the `Optimal` strategy breaks with `ragged` spacing unless it justifies.+ Left, centered and right-aligned lines no longer come out wider than the maximum width.+- `PlacedLine.width` is the placed width, including any spread.+- Breaking: `LayoutOptions` gains a strict `overflow` field.+ Its `Overflow` comes from `KB.Text.Layout.Break`. `Codec.Ktx2.Font.Layout` re-exports it.+ `SplitWords` breaks a word wider than the line between graphemes, as before. `layoutText` keeps it.+ `KeepWords` lets the word run past the line instead. Placed at zero width, the text then puts one whole word on each line. Its widest line is the narrowest the text can go.+- Breaking: `PlacedLine` gains `overfull`. It marks a line that runs past the maximum width further than its spacing allows.+ `Overflowed` now only marks a line cut where no break was allowed, as in `kb-text-layout` 0.3.+ A lone glyph or ligature wider than the line ends like any other line. Check `overfull` to catch it.+- Breaking: `shrinkwrapText` takes an `Overflow` first.+ With `KeepWords` it can return more than the given width to fit the widest word.+- Require `kb-text-layout` 0.3.+ Its optimal layout no longer counts a paragraph's indentation as space to stretch or shrink.+ ## 0.3.0.0 - 2026-11-17 - Migrated to `kb-text-shape >= 0.3` and `kb-text-layout >= 0.2`.
demo/Main.hs view
@@ -133,6 +133,7 @@ { cursor = Shaping.initialCursorDown lineHeight , strategy , align = Layout.AlignLeft+ , overflow = Layout.SplitWords } ctx style (wrapPx / targetSize) txt pure w{placed = results}
ktx-font.cabal view
@@ -5,7 +5,7 @@ -- see: https://github.com/sol/hpack name: ktx-font-version: 0.3.0.0+version: 0.4.0.0 synopsis: GPU-ready rasterized fonts category: Graphics author: IC Rainbow@@ -36,6 +36,7 @@ Codec.Ktx2.Font Codec.Ktx2.Font.Layout Codec.Ktx2.Font.Shaping+ Codec.Ktx2.Font.Slug other-modules: Paths_ktx_font autogen-modules:@@ -69,7 +70,8 @@ , base >=4.11 && <5 , bytestring , containers- , kb-text-layout ==0.2.*+ , half+ , kb-text-layout ==0.3.* , kb-text-shape ==0.3.* , ktx-codec >=0.1 , msdf-atlas@@ -153,15 +155,19 @@ ViewPatterns ghc-options: -Wall -Wcompat -Widentities -Wincomplete-record-updates -Wincomplete-uni-patterns -Wmissing-home-modules -Wpartial-fields -Wredundant-constraints -threaded -rtsopts -with-rtsopts=-N build-depends:- base >=4.11 && <5+ aeson+ , base >=4.11 && <5+ , bytestring , directory >=1.3 && <2 , filepath >=1.4 && <2+ , half , ktx-font , msdf-atlas , tasty , tasty-hunit , text , vector+ , zstd default-language: Haskell2010 if !flag(tests) buildable: False
src/Codec/Ktx2/Font.hs view
@@ -8,6 +8,9 @@ , loadBundleFile , freeBundle , bundleFont+ , SlugBundle(..)+ , packSlugFont+ , bundleSlug -- * Shaping context , StackContext(..) , createStackContext@@ -23,11 +26,17 @@ , pattern KTX_KEY_kbts , pattern KTX_KEY_kbts_version , kbtsVersion+ , pattern KTX_KEY_slug_glyphs+ , pattern KTX_KEY_slug_bands+ , pattern KTX_KEY_slug_version+ , slugVersion ) where import Codec.Compression.Zstd qualified as Zstd import Codec.Ktx.KeyValue qualified as KVD import Codec.Ktx2 qualified as Ktx2+import Codec.Ktx2.Font.Slug qualified as Slug+import Codec.Ktx2.Header (Header(..)) import Codec.Ktx2.Read qualified as Ktx2 import Codec.Ktx2.Write qualified as Ktx2 import Control.Concurrent (MVar, newMVar, takeMVar)@@ -43,10 +52,12 @@ import Data.Text (Text) import Data.Text qualified as Text import Data.Traversable (for)+import Data.Vector (Vector) import Data.Vector.Generic qualified as Vector+import Data.Vector.Storable qualified as Storable import Foreign.ForeignPtr.Unsafe (unsafeForeignPtrToPtr) import GHC.Generics (Generic, Generic1)-import Graphics.MSDF.Atlas.Compact (Compact, compact)+import Graphics.MSDF.Atlas.Compact (Box(..), Compact, compact) import Graphics.MSDF.Atlas.Compact qualified as Compact import Graphics.MSDF.Atlas.Layout qualified as Layout import KB.Text.Layout.Measure qualified as Measure@@ -68,6 +79,18 @@ kbtsVersion :: Text kbtsVersion = Text.pack $ show KBTS.VERSION_CURRENT <> "," <> show KBTS.BLOB_VERSION_CURRENT +pattern KTX_KEY_slug_glyphs :: Text+pattern KTX_KEY_slug_glyphs = "slug-glyphs"++pattern KTX_KEY_slug_bands :: Text+pattern KTX_KEY_slug_bands = "slug-bands"++pattern KTX_KEY_slug_version :: Text+pattern KTX_KEY_slug_version = "slug-version"++slugVersion :: Text+slugVersion = Text.pack $ "1," <> show Slug.dataWidthLog2+ bundleFont :: FilePath -- ^ Source font (ttf etc) -> FilePath -- ^ Atlas JSON@@ -98,6 +121,39 @@ KVD.setWriterWith (writerTag <>) sourceKtx.kvd Ktx2.toFile pathKtxf sourceKtx{Ktx2.kvd} +packSlugFont :: FilePath -> [Slug.Shape] -> IO Slug.Packed+packSlugFont pathTtf shapes = do+ scale <- withSourceFont pathTtf \font ->+ withFontData font $ capsScaleOf pathTtf+ pure . Slug.pack $ map (Slug.scaleShape scale) shapes++bundleSlug :: FilePath -> Slug.Tables -> FilePath -> FilePath -> IO ()+bundleSlug pathTtf tables pathKtx2 pathKtxf = do+ kbtsData <- withSourceFont pathTtf $ loadedBlob pathTtf++ sourceKtx <- Ktx2.fromFile pathKtx2+ let+ glyphsData = ByteString.toStrict . encode $ Vector.toList tables.glyphs+ kvd =+ KVD.insertBytes KTX_KEY_slug_glyphs (Zstd.compress 19 glyphsData) $+ KVD.insertBytes KTX_KEY_slug_bands (Zstd.compress 19 $ Slug.encodeBands tables.bands) $+ KVD.insertText KTX_KEY_slug_version slugVersion $+ KVD.insertBytes KTX_KEY_kbts (Zstd.compress 19 kbtsData) $+ KVD.insertText KTX_KEY_kbts_version kbtsVersion $+ KVD.setWriterWith (writerTag <>) sourceKtx.kvd+ Ktx2.toFile pathKtxf sourceKtx{Ktx2.kvd}++withSourceFont :: FilePath -> (FontData -> IO a) -> IO a+withSourceFont pathTtf =+ bracket (ByteString.readFile pathTtf >>= flip createFont 0) destroyFont++capsScaleOf :: FilePath -> Font -> IO Float+capsScaleOf pathTtf font = do+ info <- Font.getFontInfo font+ if info.capitalHeight <= 0+ then fail $ "No cap height in " <> pathTtf <> " (missing or truncated OS/2 table)"+ else pure $ 1 / fromIntegral info.capitalHeight+ {- | The kbts blob that loading the source produced as a side effect. A source that was a blob already is kept as is.@@ -146,9 +202,16 @@ data Bundle = Bundle { fontData :: FontData -- ^ The bundle holds the font memory too. , atlas :: Compact -- ^ Glyph atlas data for the texture.+ , slug :: Maybe SlugBundle } deriving (Eq) +data SlugBundle = SlugBundle+ { glyphs :: Vector (Maybe Slug.Glyph)+ , bandsZstd :: ByteString+ }+ deriving (Eq, Show)+ loadBundleFile :: FilePath -> IO Bundle loadBundleFile fontFile = bracket (Ktx2.open fontFile) Ktx2.close loadBundle@@ -162,13 +225,17 @@ loadBundle ktx = do kvd <- Ktx2.keyValueData ktx let- bundled = (,,)- <$> (Map.lookup KTX_KEY_atlas kvd >>= KVD.fromValue)- <*> (Map.lookup KTX_KEY_kbts kvd >>= KVD.fromValue)- <*> (Map.lookup KTX_KEY_kbts_version kvd >>= KVD.fromValue)+ lookupValue key = Map.lookup key kvd >>= KVD.fromValue+ fontKeys = (,)+ <$> lookupValue KTX_KEY_kbts+ <*> lookupValue KTX_KEY_kbts_version+ slugKeys = (,,)+ <$> lookupValue KTX_KEY_slug_version+ <*> lookupValue KTX_KEY_slug_glyphs+ <*> lookupValue KTX_KEY_slug_bands - (mtsdfZstd, kbtsZstd, kbtsVer) <-- case bundled of+ (kbtsZstd, kbtsVer) <-+ case fontKeys of Nothing -> error "Missing KTXF metadata" Just compressed ->@@ -177,14 +244,19 @@ unless (kbtsVer == kbtsVersion) $ error $ "KBTS blob version mismatch: " <> show kbtsVer <> ", expected " <> show kbtsVersion - atlas <-- case Zstd.decompress mtsdfZstd of- Zstd.Decompress json ->- either error pure $ eitherDecodeStrict json- Zstd.Skip ->- error "Empty atlas data"- Zstd.Error err ->- error $ "Atlas decompression error: " <> err+ (atlas, slug) <-+ case (lookupValue KTX_KEY_atlas, slugKeys) of+ (Just mtsdfZstd, _) -> do+ atlas <- either error pure $ decompressed "Atlas" mtsdfZstd >>= eitherDecodeStrict+ pure (atlas, Nothing)+ (Nothing, Just (slugVer, glyphsZstd, bandsZstd)) -> do+ unless (slugVer == slugVersion) $+ error $ "Slug layout version mismatch: " <> show slugVer <> ", expected " <> show (slugVersion :: Text)+ glyphs <- either error pure $ decompressed "Slug glyph" glyphsZstd >>= eitherDecodeStrict+ let slugBundle = SlugBundle{glyphs = Vector.fromList glyphs, bandsZstd}+ pure (planeAtlas ktx.header slugBundle.glyphs, Just slugBundle)+ (Nothing, Nothing) ->+ error "Missing KTXF metadata" fontData <- case Zstd.decompress kbtsZstd of@@ -196,6 +268,27 @@ error $ "Font decompression error: " <> err pure Bundle{..}++decompressed :: String -> ByteString -> Either String ByteString+decompressed what compressed =+ case Zstd.decompress compressed of+ Zstd.Decompress bytes -> Right bytes+ Zstd.Skip -> Left $ "Empty " <> what <> " data"+ Zstd.Error err -> Left $ what <> " decompression error: " <> err++planeAtlas :: Header -> Vector (Maybe Slug.Glyph) -> Compact+planeAtlas header glyphs = Compact.Compact+ { Compact._atlasSize = (fromIntegral header.pixelWidth, fromIntegral header.pixelHeight)+ , Compact._size = 1+ , Compact._type = Layout.Softmask+ , Compact._yOrigin = Layout.Bottom+ , Compact._distanceLower = 0+ , Compact._distanceRange = 0+ , Compact.glyphs = Storable.replicate (Vector.length glyphs) emptyBox+ , Compact.planes = Storable.fromList [maybe emptyBox (.plane) glyph | glyph <- Vector.toList glyphs]+ }+ where+ emptyBox = Box 0 0 0 0 freeBundle :: Bundle -> IO () freeBundle Bundle{fontData} = destroyFont fontData
src/Codec/Ktx2/Font/Layout.hs view
@@ -20,6 +20,7 @@ , LayoutOptions(..) , Strategy(..) , Align(..)+ , Break.Overflow(..) -- * All at once , layoutText , layoutTextWith@@ -85,13 +86,14 @@ | Optimal -- ^ Minimize raggedness across the whole paragraph. deriving stock (Eq, Show) -data Align = AlignLeft | AlignCenter | AlignRight+data Align = AlignLeft | AlignCenter | AlignRight | AlignJustify deriving stock (Eq, Show) data LayoutOptions = LayoutOptions { cursor :: Shaping.Cursor , strategy :: Strategy , align :: Align+ , overflow :: !Break.Overflow } deriving stock (Eq, Show) @@ -152,44 +154,54 @@ data PlacedLine = PlacedLine { runs :: [Shaping.PlacedRun] , text :: Text -- ^ What landed on the line, including the trailing @-@ when hyphenated.- , width :: Float -- ^ Visible line width, excluding trailing spaces.+ , width :: Float -- ^ Placed line width, excluding trailing spaces and including the justification spread. , ended :: Break.LineEnd+ , overfull :: Bool , origin :: (Float, Float) -- ^ Line pen start, after alignment. } {- | Break the shaped text to fit the maximum width and place the lines. -Each line is a run of visible pieces shifted as a whole to the line start,-closing up over the invisible segments between them, so the glyphs keep-their shaped positions relative to each other.+Each line is a run of visible pieces shifted to the line start.+The pieces close up over the invisible segments between them.+Glyphs keep their shaped positions relative to each other,+except where a justified line widens the spaces between its words. -} placeText :: LayoutOptions -> Float -> ShapedText -> [PlacedLine] placeText opts maxWidth st = zipWith placeLine [0 :: Int ..] ranges where ranges = case opts.strategy of- Greedy -> Break.layoutGreedy st.prepared maxWidth- Optimal -> Break.layoutOptimal st.prepared maxWidth+ Greedy -> Break.layoutGreedyWith opts.overflow st.prepared maxWidth+ Optimal -> Break.layoutOptimalWith spacing opts.overflow st.prepared maxWidth + spacing =+ if opts.align == AlignJustify then+ Break.justified+ else+ Break.ragged+ segments = st.prepared.segments lastSegment = Vector.length segments - 1 placeLine line range = PlacedLine { runs = lineRuns <> hyphenRuns , text = Break.materializeLineRange st.prepared range- , width = range.width+ , width = range.width + spread , ended = range.ended+ , overfull = range.overfull , origin = (x0, y) } where x0 = opts.cursor.curX + case opts.align of AlignLeft -> 0- AlignCenter -> max 0 (maxWidth - range.width) / 2- AlignRight -> max 0 (maxWidth - range.width)+ AlignCenter -> max 0 (maxWidth - range.width - spread) / 2+ AlignRight -> max 0 (maxWidth - range.width - spread)+ AlignJustify -> 0 y = opts.cursor.curY + fromIntegral line * opts.cursor.lineHeight * opts.cursor.ySign - pieces =- [ (c0, c1)+ indexed =+ [ (j, (c0, c1)) | j <- [range.from.segment .. min range.to.segment lastSegment] , visible (segments ! j).kind , let c0 = st.offsets ! j + if j == range.from.segment then range.from.grapheme else 0@@ -197,9 +209,34 @@ , c0 < c1 ] + pieces = map snd indexed++ inked = [k | (k, (j, _)) <- zip [0 :: Int ..] indexed, (segments ! j).kind /= Space]++ firstInk = foldl' min maxBound inked++ lastInk = foldl' max minBound inked++ interior =+ [ if firstInk < k && k < lastInk && (segments ! j).kind == Space then (segments ! j).width else 0+ | (k, (j, _)) <- zip [0 ..] indexed+ ]++ spaces = sum interior++ slack = maxWidth - range.width++ spread+ | spaces <= 0 = 0+ | slack < 0 = max slack (negate $ spacing.shrink * spaces)+ | opts.align == AlignJustify && range.ended `elem` [Break.Wrapped, Break.Hyphenated] = slack+ | otherwise = 0++ widened = scanl (+) 0 [if spaces > 0 then spread * w / spaces else 0 | w <- interior]+ shifts = case pieces of [] -> []- (c0, _) : _ -> scanl (-) (x0 - st.advances ! c0) gaps+ (c0, _) : _ -> zipWith (+) widened $ scanl (-) (x0 - st.advances ! c0) gaps gaps = zipWith (\(_, c1) (c0, _) -> st.advances ! c0 - st.advances ! c1) pieces (drop 1 pieces) @@ -236,7 +273,7 @@ Left-aligned greedy layout. Use 'layoutTextWith' for more options. -} layoutText :: Shaping.Cursor -> Font.StackContext a -> TextStyle -> Float -> Text -> IO [PlacedLine]-layoutText cursor = layoutTextWith LayoutOptions{cursor, strategy = Greedy, align = AlignLeft}+layoutText cursor = layoutTextWith LayoutOptions{cursor, strategy = Greedy, align = AlignLeft, overflow = Break.SplitWords} -- | 'shapeText' followed by 'placeText'. layoutTextWith :: LayoutOptions -> Font.StackContext a -> TextStyle -> Float -> Text -> IO [PlacedLine]@@ -254,11 +291,11 @@ Measure.measure ctx.layout ts.style t -- | The smallest maximum width that doesn't add more lines than the given one.-shrinkwrapText :: Font.StackContext a -> TextStyle -> Float -> Text -> IO Float-shrinkwrapText ctx ts maxWidth t =+shrinkwrapText :: Break.Overflow -> Font.StackContext a -> TextStyle -> Float -> Text -> IO Float+shrinkwrapText overflow ctx ts maxWidth t = withMVar ctx.shapeContext \_kbts -> do prep <- Measure.prepare ctx.layout ts.style t- pure $ Break.shrinkwrap prep maxWidth+ pure $ Break.shrinkwrapWith overflow prep maxWidth -- | Drop the measurement caches, e.g. after evicting some fonts. clearLayoutCache :: Font.StackContext a -> IO ()
+ src/Codec/Ktx2/Font/Slug.hs view
@@ -0,0 +1,359 @@+module Codec.Ktx2.Font.Slug+ ( pack+ , Packed(..)+ , Tables(..)+ , Glyph(..)+ , bandTransform+ , encodeCurves+ , encodeBands+ , decodeBands+ , Shape(..)+ , scaleShape+ , FillRule(..)+ , Contour+ , Curve(..)+ , Point(..)+ , line+ , dataWidth+ , dataWidthLog2+ ) where++import Data.Aeson (FromJSON, ToJSON)+import Data.Bifunctor (bimap)+import Data.ByteString (ByteString)+import Data.ByteString qualified as ByteString+import Data.ByteString.Builder qualified as Builder+import Data.ByteString.Lazy qualified as Lazy+import Data.Bits (shiftL, (.|.))+import Data.List qualified as List+import Data.Map.Strict qualified as Map+import Data.Ord (Down(..), comparing)+import Data.Vector (Vector)+import Data.Vector qualified as Vector+import Data.Vector.Storable qualified as Storable+import Foreign.C.Types (CUShort(..))+import GHC.Float (castWord32ToFloat)+import GHC.Generics (Generic)+import Graphics.MSDF.Atlas.Compact (Box(..))+import Numeric.Half (Half)+import Numeric.Half qualified as Half++pack :: [Shape] -> Packed+pack shapes = Packed+ { curves = padRows 4 . Storable.fromList $ concat curveChunks+ , tables = Tables+ { bands = padRows 1 . Storable.fromList $ concat bandChunks+ , glyphs = Vector.fromList glyphs+ }+ }+ where+ (curveChunks, bandChunks, glyphs) =+ List.unzip3 . snd $ List.mapAccumL packShape (0, 0) shapes++data Packed = Packed+ { curves :: Storable.Vector Half+ , tables :: Tables+ }+ deriving (Eq, Show)++data Tables = Tables+ { bands :: Storable.Vector Float+ , glyphs :: Vector (Maybe Glyph)+ }+ deriving (Eq, Show)++data Glyph = Glyph+ { plane :: Box+ , bandsOffset :: Int+ , horizontalBands :: Int+ , verticalBands :: Int+ , fillRule :: FillRule+ }+ deriving (Eq, Show, Generic)++instance ToJSON Glyph+instance FromJSON Glyph++bandTransform :: Glyph -> (Float, Float, Float, Float)+bandTransform glyph = (scaleX, scaleY, negate left * scaleX, negate bottom * scaleY)+ where+ Box{x, y, w, h} = glyph.plane+ left = x - w / 2+ bottom = y - h / 2+ scaleX = bandScale glyph.verticalBands w+ scaleY = bandScale glyph.horizontalBands h++data Shape = Shape+ { fillRule :: FillRule+ , contours :: [Contour]+ }+ deriving (Eq, Show)++data FillRule+ = NonZero+ | EvenOdd+ deriving (Eq, Ord, Show, Enum, Bounded, Generic)++instance ToJSON FillRule+instance FromJSON FillRule++scaleShape :: Float -> Shape -> Shape+scaleShape factor shape = shape {contours = map (map scaleCurve) shape.contours}+ where+ scaleCurve (Curve a b c) = Curve (scalePoint a) (scalePoint b) (scalePoint c)++ scalePoint :: Point -> Point+ scalePoint p = Point (p.x * factor) (p.y * factor)++encodeCurves :: Storable.Vector Half -> ByteString+encodeCurves =+ Lazy.toStrict . Builder.toLazyByteString . Storable.foldMap (\(Half.Half (CUShort bits)) -> Builder.word16LE bits)++encodeBands :: Storable.Vector Float -> ByteString+encodeBands =+ Lazy.toStrict . Builder.toLazyByteString . Storable.foldMap Builder.floatLE++decodeBands :: ByteString -> Either String (Storable.Vector Float)+decodeBands bytes =+ if ByteString.length bytes `mod` 4 == 0 then+ Right $ Storable.generate (ByteString.length bytes `div` 4) valueAt+ else+ Left "Band data is not a whole number of float32 values"+ where+ valueAt i = castWord32ToFloat $ List.foldl' (.|.) 0+ [ fromIntegral (ByteString.index bytes (4 * i + k)) `shiftL` (8 * k)+ | k <- [0 .. 3]+ ]++type Contour = [Curve]++data Curve = Curve+ { p1 :: Point+ , p2 :: Point+ , p3 :: Point+ }+ deriving (Eq, Show)++data Point = Point+ { x :: Float+ , y :: Float+ }+ deriving (Eq, Ord, Show)++line :: Point -> Point -> Curve+line start end = Curve start end end++dataWidth :: Int+dataWidth = 2 ^ dataWidthLog2++dataWidthLog2 :: Int+dataWidthLog2 = 12++packShape :: (Int, Int) -> Shape -> ((Int, Int), ([Half], [Float], Maybe Glyph))+packShape (curveBase, bandBase) shape =+ case indexed of+ [] ->+ ((curveBase, bandBase), ([], [], Nothing))+ _ ->+ ( (curveBase + length texels, bandBase + length bandValues)+ , (concatMap texelHalves texels, bandValues, Just glyph)+ )+ where+ (texels, indexed) = layoutRuns curveBase $ concatMap (runs . map quantize) shape.contours++ Bounds{minX, minY, maxX, maxY} = foldMap (curveBounds . snd) indexed++ horizontal = chooseBands (minY, maxY) $ bandsAlong+ (minY, maxY)+ (filter (not . flatY . snd) indexed)+ (\c -> extent3 c.p1.y c.p2.y c.p3.y)+ (\c -> max3 c.p1.x c.p2.x c.p3.x)++ vertical = chooseBands (minX, maxX) $ bandsAlong+ (minX, maxX)+ (filter (not . flatX . snd) indexed)+ (\c -> extent3 c.p1.x c.p2.x c.p3.x)+ (\c -> max3 c.p1.y c.p2.y c.p3.y)++ (headers, listValues) =+ layoutLists (2 * (length horizontal + length vertical)) (horizontal <> vertical)++ bandValues =+ map fromIntegral $+ concatMap (\(count, offset) -> [count, offset]) headers <> listValues++ glyph = Glyph+ { plane = Box+ { x = (minX + maxX) / 2+ , y = (minY + maxY) / 2+ , w = maxX - minX+ , h = maxY - minY+ }+ , bandsOffset = bandBase+ , horizontalBands = length horizontal+ , verticalBands = length vertical+ , fillRule = shape.fillRule+ }++runs :: Contour -> [[Curve]]+runs = \case+ [] -> []+ begin : rest -> go [begin] rest+ where+ go acc = \case+ [] ->+ [reverse acc]+ next : rest+ | connected acc next -> go (next : acc) rest+ | otherwise -> reverse acc : go [next] rest++ connected :: [Curve] -> Curve -> Bool+ connected acc next =+ case acc of+ prev : _ -> prev.p3 == next.p1+ [] -> False++layoutRuns :: Int -> [[Curve]] -> ([(Point, Point)], [(Int, Curve)])+layoutRuns base =+ bimap concat concat . List.unzip . snd . List.mapAccumL place base+ where+ place :: Int -> [Curve] -> (Int, ([(Point, Point)], [(Int, Curve)]))+ place offset run =+ ( offset + length texels+ , (texels, zip [offset ..] run)+ )+ where+ texels = map (\c -> (c.p1, c.p2)) run <> lastPoint+ lastPoint = take 1 [(c.p3, Point 0 0) | c <- reverse run]++texelHalves :: (Point, Point) -> [Half]+texelHalves (a, b) = map Half.toHalf [a.x, a.y, b.x, b.y]++quantize :: Curve -> Curve+quantize Curve{p1, p2, p3} = Curve (quantizePoint p1) (quantizePoint p2) (quantizePoint p3)+ where+ quantizePoint :: Point -> Point+ quantizePoint p = Point (roundHalf p.x) (roundHalf p.y)++ roundHalf :: Float -> Float+ roundHalf = Half.fromHalf . Half.toHalf++data Bounds = Bounds+ { minX :: Float+ , minY :: Float+ , maxX :: Float+ , maxY :: Float+ }++instance Semigroup Bounds where+ a <> b = Bounds+ { minX = min a.minX b.minX+ , minY = min a.minY b.minY+ , maxX = max a.maxX b.maxX+ , maxY = max a.maxY b.maxY+ }++instance Monoid Bounds where+ mempty = Bounds+ { minX = 1 / 0+ , minY = 1 / 0+ , maxX = -1 / 0+ , maxY = -1 / 0+ }++curveBounds :: Curve -> Bounds+curveBounds c = Bounds+ { minX = min3 c.p1.x c.p2.x c.p3.x+ , minY = min3 c.p1.y c.p2.y c.p3.y+ , maxX = max3 c.p1.x c.p2.x c.p3.x+ , maxY = max3 c.p1.y c.p2.y c.p3.y+ }++flatX :: Curve -> Bool+flatX c = c.p1.x == c.p2.x && c.p2.x == c.p3.x++flatY :: Curve -> Bool+flatY c = c.p1.y == c.p2.y && c.p2.y == c.p3.y++extent3 :: Float -> Float -> Float -> (Float, Float)+extent3 a b c = (min3 a b c, max3 a b c)++min3 :: Float -> Float -> Float -> Float+min3 a b c = min a (min b c)++max3 :: Float -> Float -> Float -> Float+max3 a b c = max a (max b c)++bandsAlong+ :: (Float, Float)+ -> [(Int, Curve)]+ -> (Curve -> (Float, Float))+ -> (Curve -> Float)+ -> Int+ -> [[Int]]+bandsAlong (lo, hi) eligible extent sortKey count =+ map curvesIn [0 .. count - 1]+ where+ step = (hi - lo) / fromIntegral count++ curvesIn band =+ map fst . List.sortOn (Down . sortKey . snd) $+ filter (overlaps . extent . snd) eligible+ where+ bandLo = lo + fromIntegral band * step+ bandHi = bandLo + step+ overlaps (curveLo, curveHi) =+ curveLo <= bandHi + bandOverlap && curveHi >= bandLo - bandOverlap++bandOverlap :: Float+bandOverlap = 1 / 1024++chooseBands :: (Float, Float) -> (Int -> [[Int]]) -> [[Int]]+chooseBands (lo, hi) bandsFor =+ snd $ List.minimumBy (comparing fst)+ [ (List.foldl' max 0 (map length bands), bands)+ | count <- candidates+ , let bands = bandsFor count+ ]+ where+ candidates =+ if hi > lo then+ [1 .. maxBands]+ else+ [1]++maxBands :: Int+maxBands = 16++bandScale :: Int -> Float -> Float+bandScale count size =+ if size > 0 then+ fromIntegral count / size+ else+ 0++layoutLists :: Int -> [[Int]] -> ([(Int, Int)], [Int])+layoutLists start =+ finish . List.foldl' place (start, Map.empty, [], [])+ where+ place (next, seen, headers, chunks) list =+ case Map.lookup list seen of+ Just offset ->+ (next, seen, (length list, offset) : headers, chunks)+ Nothing ->+ ( next + length list+ , Map.insert list next seen+ , (length list, next) : headers+ , list : chunks+ )++ finish (_next, _seen, headers, chunks) =+ (reverse headers, concat $ reverse chunks)++padRows :: (Storable.Storable a, Num a) => Int -> Storable.Vector a -> Storable.Vector a+padRows components items =+ items <> Storable.replicate padding 0+ where+ rowSize = components * dataWidth+ rows = max 1 $ (Storable.length items + rowSize - 1) `div` rowSize+ padding = rows * rowSize - Storable.length items
test/Spec.hs view
@@ -5,8 +5,15 @@ import Data.List (isSuffixOf, nub) import Data.Text qualified as Text import Data.Traversable (for)+import Codec.Compression.Zstd qualified as Zstd+import Data.Aeson qualified as Aeson+import Data.ByteString qualified as ByteString+import Data.Either (isLeft)+import Data.Maybe (isJust)+import Data.Vector qualified as Vector import Data.Vector.Storable qualified as Storable-import System.Directory (doesFileExist, listDirectory)+import Numeric.Half qualified as Half+import System.Directory (doesDirectoryExist, doesFileExist, listDirectory) import System.FilePath ((</>)) import Test.Tasty (TestTree, defaultMain, testGroup, withResource) import Test.Tasty.HUnit (assertBool, assertFailure, testCase, (@?=))@@ -16,6 +23,8 @@ import Codec.Ktx2.Font.Layout qualified as Layout import Codec.Ktx2.Font.Shaping (Box(..), Compact(..), PlacedGlyph(..)) import Codec.Ktx2.Font.Shaping qualified as Shaping+import Codec.Ktx2.Font.Slug (Glyph(..), Packed(..), Point(..), Shape(..))+import Codec.Ktx2.Font.Slug qualified as Slug {- | Font bundles built from @assets.yaml@. @@ -28,6 +37,9 @@ main = do entries <- listDirectory bundlesPath let sources = [bundlesPath </> entry | entry <- entries, ".ktxf" `isSuffixOf` entry]+ slugBuilt <- doesDirectoryExist slugBundlesPath+ slugEntries <- if slugBuilt then listDirectory slugBundlesPath else pure []+ let slugSources = [slugBundlesPath </> entry | entry <- slugEntries, ".ktxf" `isSuffixOf` entry] unless (null sources) $ putStrLn $ "Found " <> show (length sources) <> " bundles in " <> bundlesPath @@ -52,6 +64,16 @@ , withStack [ligatureBundle] ligatureTests , withBuriedStyle buriedStyleTests++ , slugTests++ , testCase "slug bundles are built" $+ doesFileExist slugBundle >>=+ assertBool (slugBundle <> " is missing, run the ktx-build asset build")++ , testGroup "slug bundles" $ map slugBundleTests slugSources++ , if null slugSources then testGroup "slug shaping" [] else withStack [slugBundle] slugShapingTests ] bundleTests :: FilePath -> TestTree@@ -156,7 +178,7 @@ lns <- layout ctx style 3.0 "one two three four five" assertBool "text did not wrap" $ length lns > 1 for_ lns \line ->- unless (line.ended == Layout.Overflowed) $+ unless line.overfull $ assertBool ("line too wide: " <> show (line.text, line.width)) $ line.width <= 3.001 @@ -188,7 +210,7 @@ , testCase "right alignment pushes the origin to the edge" do (ctx, style) <- getStack lns <- Layout.layoutTextWith- Layout.LayoutOptions{cursor, strategy = Layout.Greedy, align = Layout.AlignRight}+ Layout.LayoutOptions{cursor, strategy = Layout.Greedy, align = Layout.AlignRight, overflow = Layout.SplitWords} ctx style 10 "H" case lns of [line] -> do@@ -202,7 +224,7 @@ (ctx, style) <- getStack shaped <- Layout.shapeText ctx style "one two three four five" let- place w = Layout.placeText Layout.LayoutOptions{cursor, strategy = Layout.Greedy, align = Layout.AlignLeft} w shaped+ place w = Layout.placeText Layout.LayoutOptions{cursor, strategy = Layout.Greedy, align = Layout.AlignLeft, overflow = Layout.SplitWords} w shaped wide = place 1e6 narrow = place 3.0 length wide @?= 1@@ -214,12 +236,77 @@ plain <- Shaping.shapeText cursor{Shaping.curX = x0, Shaping.curY = y0} ctx line.text planesOf line.runs `closeTo` planesOf plain + , testCase "kept words put one whole word on each line at zero width" do+ (ctx, style) <- getStack+ let source = "one two three four five"+ shaped <- Layout.shapeText ctx style source+ widths <- traverse (Layout.measureText ctx style) (Text.words source)+ for_ [Layout.Greedy, Layout.Optimal] \strategy -> do+ let lns = Layout.placeText Layout.LayoutOptions{cursor, strategy, align = Layout.AlignLeft, overflow = Layout.KeepWords} 0 shaped+ map (Text.strip . (.text)) lns @?= Text.words source+ assertBool ("widest line is not the widest word: " <> show (map (.width) lns, widths)) $+ abs (maximum (map (.width) lns) - maximum widths) < 0.001++ , testCase "optimal breaks keep ragged lines inside the width" do+ (ctx, style) <- getStack+ shaped <- Layout.shapeText ctx style pangrams+ for_ [4.0, 4.37 .. 14.0] \w -> do+ let lns = Layout.placeText Layout.LayoutOptions{cursor, strategy = Layout.Optimal, align = Layout.AlignLeft, overflow = Layout.SplitWords} w shaped+ for_ lns \line ->+ unless line.overfull $+ assertBool ("line too wide at " <> show w <> ": " <> show (line.text, line.width)) $+ line.width <= w + 0.001++ , testCase "justified lines fill the width" do+ (ctx, style) <- getStack+ shaped <- Layout.shapeText ctx style pangrams+ let+ w = 14.0+ place align = Layout.placeText Layout.LayoutOptions{cursor, strategy = Layout.Greedy, align, overflow = Layout.SplitWords} w shaped+ ragged = place Layout.AlignLeft+ justified = place Layout.AlignJustify+ rightmost :: Layout.PlacedLine -> Float+ rightmost line = maximum (map (.plane.x) (concatMap snd line.runs))+ map (.text) justified @?= map (.text) ragged+ assertBool "text did not wrap" $ length justified > 2+ assertBool "no wrapped line to fill" $+ any (\line -> line.ended == Layout.Wrapped && Text.any (== ' ') (Text.strip line.text)) justified+ for_ (zip ragged justified) \(natural, filled) ->+ case filled.ended of+ Layout.Wrapped | Text.any (== ' ') (Text.strip filled.text) -> do+ assertBool ("wrapped line not filled: " <> show (filled.text, filled.width)) $+ abs (filled.width - w) < 0.001+ assertBool ("last glyph did not move by the slack: " <> show filled.text) $+ abs (rightmost filled - rightmost natural - (w - natural.width)) < 0.001+ _ ->+ filled.width @?= natural.width++ , testCase "justified lines keep the paragraph indent" do+ (ctx, style) <- getStack+ shaped <- Layout.shapeText ctx style (" " <> pangrams)+ let+ place align = Layout.placeText Layout.LayoutOptions{cursor, strategy = Layout.Greedy, align, overflow = Layout.SplitWords} 14.0 shaped+ firstInk :: [Layout.PlacedLine] -> [Float]+ firstInk lns = take 1 [g.plane.x | line <- take 1 lns, g <- concatMap snd line.runs, g.codepoint /= ' ']+ map (.ended) (take 1 $ place Layout.AlignJustify) @?= [Layout.Wrapped]+ firstInk (place Layout.AlignJustify) @?= firstInk (place Layout.AlignLeft)++ , testCase "optimal justified lines don't squeeze the indent" do+ (ctx, style) <- getStack+ shaped <- Layout.shapeText ctx style (" " <> pangrams)+ for_ [4.0, 4.37 .. 14.0] \w -> do+ let lns = Layout.placeText Layout.LayoutOptions{cursor, strategy = Layout.Optimal, align = Layout.AlignJustify, overflow = Layout.SplitWords} w shaped+ for_ lns \line ->+ unless line.overfull $+ assertBool ("line too wide at " <> show w <> ": " <> show (line.text, line.width)) $+ line.width <= w + 0.001+ , testCase "soft hyphens break with a visible hyphen" do (ctx, style) <- getStack shaped <- Layout.shapeText ctx style "hyphen\173ation" w <- Layout.measureText ctx style "hyphenation" let- lns = Layout.placeText Layout.LayoutOptions{cursor, strategy = Layout.Greedy, align = Layout.AlignLeft} (w * 0.75) shaped+ lns = Layout.placeText Layout.LayoutOptions{cursor, strategy = Layout.Greedy, align = Layout.AlignLeft, overflow = Layout.SplitWords} (w * 0.75) shaped map (.ended) lns @?= [Layout.Hyphenated, Layout.Finished] case lns of [top, bottom] -> do@@ -237,8 +324,16 @@ (ctx, style) <- getStack w <- Layout.measureText ctx style "H" assertBool ("H has no width: " <> show w) $ w > 0- shrunk <- Layout.shrinkwrapText ctx style 3.0 "one two three four five"+ shrunk <- Layout.shrinkwrapText Layout.SplitWords ctx style 3.0 "one two three four five" assertBool ("shrinkwrap exceeded the limit: " <> show shrunk) $ shrunk <= 3.001++ , testCase "shrinkwrapping kept words fits the widest word" do+ (ctx, style) <- getStack+ let source = "one two three four five"+ widest <- maximum <$> traverse (Layout.measureText ctx style) (Text.words source)+ shrunk <- Layout.shrinkwrapText Layout.KeepWords ctx style 0 source+ assertBool ("shrinkwrap is not the widest word: " <> show (shrunk, widest)) $+ abs (shrunk - widest) < 0.001 ] where layout = Layout.layoutText cursor@@ -269,7 +364,8 @@ for_ [w / 2, w * 0.9] \width -> do let lns = place shaped width map (.text) lns @?= [ligature]- map (.ended) lns @?= [Layout.Overflowed]+ map (.ended) lns @?= [Layout.Finished]+ map (.overfull) lns @?= [True] map (.plane) (glyphsOf lns) `closeTo` map (.plane) whole , testCase "wrapping after the ligature keeps the following text" do@@ -285,7 +381,7 @@ ] where ligature = "ffi"- place shaped width = Layout.placeText Layout.LayoutOptions{cursor, strategy = Layout.Greedy, align = Layout.AlignLeft} width shaped+ place shaped width = Layout.placeText Layout.LayoutOptions{cursor, strategy = Layout.Greedy, align = Layout.AlignLeft, overflow = Layout.SplitWords} width shaped glyphsOf lns = concatMap snd (Layout.placedRuns lns) withBuriedStyle :: (IO (Font.StackContext FilePath, Layout.TextStyle) -> TestTree) -> TestTree@@ -319,13 +415,16 @@ (ctx, style) <- getStack shaped <- Layout.shapeText ctx style "hyphen\173ation" w <- Layout.measureText ctx style "hyphenation"- let lns = Layout.placeText Layout.LayoutOptions{cursor, strategy = Layout.Greedy, align = Layout.AlignLeft} (w * 0.75) shaped+ let lns = Layout.placeText Layout.LayoutOptions{cursor, strategy = Layout.Greedy, align = Layout.AlignLeft, overflow = Layout.SplitWords} (w * 0.75) shaped map (.ended) lns @?= [Layout.Hyphenated, Layout.Finished] bundlesOf ctx lns @?= [Just ligatureBundle] ] where bundlesOf ctx lns = nub [Font.lookupBundled font ctx | ((font, _atlas), _glyphs) <- Layout.placedRuns lns] +pangrams :: Text.Text+pangrams = "Sphinx of black quartz, judge my vow. The quick brown fox jumps over the lazy dog. Pack my box with five dozen liquor jugs."+ cursor :: Shaping.Cursor cursor = Shaping.initialCursorDown 2.0 @@ -338,3 +437,110 @@ for_ (zip actual expected) \(a, e) -> assertBool ("planes differ: " <> show (a, e)) $ all (< 0.001) [abs (a.x - e.x), abs (a.y - e.y), abs (a.w - e.w), abs (a.h - e.h)]++slugTests :: TestTree+slugTests =+ testGroup "slug"+ [ testCase "outline-less shapes have no glyph" do+ let packed = Slug.pack [Shape Slug.NonZero []]+ packed.tables.glyphs @?= Vector.fromList [Nothing]+ Storable.length packed.curves @?= 4 * Slug.dataWidth+ Storable.length packed.tables.bands @?= Slug.dataWidth++ , testCase "a square shares endpoints and sorts its bands" do+ let packed = Slug.pack [square]+ packed.tables.glyphs @?= Vector.fromList [Just squareGlyph {bandsOffset = 0}]+ Storable.take 20 packed.curves @?= Storable.fromList (map Half.toHalf [0, 0, 1, 0, 1, 0, 1, 1, 1, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0])+ Storable.take 8 packed.tables.bands @?= Storable.fromList [2, 4, 2, 6, 1, 3, 2, 0]++ , testCase "later shapes offset their curves and bands" do+ let packed = Slug.pack [square, square]+ packed.tables.glyphs Vector.!? 1 @?= Just (Just squareGlyph {bandsOffset = 8})+ Storable.toList (Storable.slice 8 8 packed.tables.bands) @?= [2, 4, 2, 6, 6, 8, 7, 5]++ , testCase "band transform maps the plane onto the bands" do+ Slug.bandTransform squareGlyph {horizontalBands = 4, verticalBands = 2} @?= (2, 4, 0, 0)++ , testCase "bands round-trip through little-endian bytes" do+ let bands = (Slug.pack [square, square]).tables.bands+ Slug.decodeBands (Slug.encodeBands bands) @?= Right bands+ ByteString.unpack (Slug.encodeBands (Storable.fromList [1])) @?= [0x00, 0x00, 0x80, 0x3F]+ assertBool "truncated band data is rejected" $ isLeft (Slug.decodeBands (ByteString.pack [0, 0, 0]))++ , testCase "curves encode as little-endian halfs" do+ ByteString.unpack (Slug.encodeCurves (Storable.fromList [1, -2])) @?= [0x00, 0x3C, 0x00, 0xC0]++ , testCase "glyph tables round-trip through JSON" do+ let glyphs = Vector.toList (Slug.pack [Shape Slug.NonZero [], square]).tables.glyphs+ Aeson.eitherDecode (Aeson.encode glyphs) @?= Right glyphs++ , testCase "shapes scale about the origin" do+ Slug.scaleShape 0.5 square @?= Shape Slug.NonZero+ [ [ Slug.line (Point 0 0) (Point 0.5 0)+ , Slug.line (Point 0.5 0) (Point 0.5 0.5)+ , Slug.line (Point 0.5 0.5) (Point 0 0.5)+ , Slug.line (Point 0 0.5) (Point 0 0)+ ]+ ]+ ]+ where+ square = Shape Slug.NonZero+ [ [ Slug.line (Point 0 0) (Point 1 0)+ , Slug.line (Point 1 0) (Point 1 1)+ , Slug.line (Point 1 1) (Point 0 1)+ , Slug.line (Point 0 1) (Point 0 0)+ ]+ ]++ squareGlyph = Glyph+ { plane = Box {x = 0.5, y = 0.5, w = 1, h = 1}+ , bandsOffset = 0+ , horizontalBands = 1+ , verticalBands = 1+ , fillRule = Slug.NonZero+ }++slugBundlesPath :: FilePath+slugBundlesPath = ".." </> "assets" </> "slug"++slugBundle :: FilePath+slugBundle = slugBundlesPath </> "NotoSans-Regular.ktxf"++slugBundleTests :: FilePath -> TestTree+slugBundleTests source =+ withResource (Font.loadBundleFile source) Font.freeBundle \getBundle ->+ testGroup source+ [ testCase "carries Slug tables" do+ Bundle{slug} <- getBundle+ case slug of+ Nothing -> assertFailure "no Slug tables"+ Just stored -> do+ assertBool "no outlined glyphs" $ any isJust stored.glyphs+ case Zstd.decompress stored.bandsZstd of+ Zstd.Decompress bytes -> do+ bands <- either assertFailure pure $ Slug.decodeBands bytes+ assertBool "no band data" $ not (Storable.null bands)+ Storable.length bands `mod` Slug.dataWidth @?= 0+ _ ->+ assertFailure "band data doesn't decompress"++ , testCase "the plane table follows the Slug glyphs" do+ Bundle{atlas, slug} <- getBundle+ stored <- maybe (assertFailure "no Slug tables") pure slug+ Vector.length stored.glyphs @?= Storable.length atlas.planes+ for_ (zip [0 ..] (Vector.toList stored.glyphs)) \(glyphId, glyph) ->+ for_ glyph \Glyph{plane} ->+ Storable.indexM atlas.planes glyphId >>= (@?= plane)+ ]++slugShapingTests :: IO (Font.StackContext (), Layout.TextStyle) -> TestTree+slugShapingTests getStack =+ testCase "capitals span the baseline to the cap height" do+ (ctx, _style) <- getStack+ runs <- Shaping.shapeText (Shaping.initialCursorUp 1.5) ctx "H"+ case concatMap snd runs of+ [PlacedGlyph{plane = Box{y, h}}] -> do+ y - h / 2 @?= 0+ y + h / 2 @?= 1+ huh ->+ assertFailure $ "expected one glyph, got " <> show huh