kb-text-layout 0.1.2.0 → 0.2.0.0
raw patch · 11 files changed
+177/−36 lines, 11 filesdep +filepathdep ~kb-text-shapePVP ok
version bump matches the API change (PVP)
Dependencies added: filepath
Dependency ranges changed: kb-text-shape
API changes (from Hackage documentation)
+ KB.Text.Layout.Measure: Face :: Font -> [Variation] -> [(FeatureTag, Int)] -> Face
+ KB.Text.Layout.Measure: [face] :: Style -> Face
+ KB.Text.Layout.Measure: [features] :: Face -> [(FeatureTag, Int)]
+ KB.Text.Layout.Measure: [variations] :: Face -> [Variation]
+ KB.Text.Layout.Measure: data Face
+ KB.Text.Layout.Measure: face :: Font -> Face
+ KB.Text.Layout.Measure: instance GHC.Classes.Eq KB.Text.Layout.Measure.Face
+ KB.Text.Layout.Measure: instance GHC.Show.Show KB.Text.Layout.Measure.Face
+ KB.Text.Layout.Measure: newStyleWith :: LayoutContext -> Face -> Float -> IO Style
- KB.Text.Layout.Measure: Style :: Int -> Font -> Float -> Float -> Float -> Float -> Float -> Float -> Style
+ KB.Text.Layout.Measure: Style :: Int -> Face -> Float -> Float -> Float -> Float -> Float -> Float -> Style
- KB.Text.Layout.Measure: [font] :: Style -> Font
+ KB.Text.Layout.Measure: [font] :: Face -> Font
Files
- CHANGELOG.md +12/−0
- README.md +18/−0
- demos/bubbles/Main.hs +4/−4
- demos/demo/Main.hs +5/−5
- demos/justify/Main.hs +3/−3
- demos/lib/Demo.hs +33/−4
- demos/masonry/Main.hs +3/−3
- demos/obstacles/Main.hs +3/−3
- kb-text-layout.cabal +3/−2
- src/KB/Text/Layout/Measure.hs +39/−11
- test/Spec.hs +54/−1
CHANGELOG.md view
@@ -6,6 +6,18 @@ and this project adheres to the [Haskell Package Versioning Policy](https://pvp.haskell.org/). +## 0.2.0.0 - 2026-11-17++- Require kb-text-shape 0.3.+ Shaping failures in `prepare`, `prepareStyled`, `measure`, `charAdvances`, `newStyle` and `newStyleWith` now throw its `ShapeException`.+ A `ContextError` leaves the shaping context unusable, and every `LayoutContext` built over it.+- Add `Face`, a font together with variation axis values and OpenType feature overrides.+ `newStyleWith` makes a style from a face, and `face` makes a plain one from a font.+ `newStyle` still takes a bare font.+- Breaking: `Style.font` is replaced by `Style.face`. Read the font as `style.face.font`.+- Fix measuring in the wrong font when the style's font is not on top of the shaping context's font stack.+ The tail of each shaped text used to take its advances from the font on top.+ ## 0.1.2.0 - 2026-09-04 - Add `ShapedSpan` for runs with caller-supplied per-codepoint advances.
README.md view
@@ -53,6 +53,23 @@ > ⚠️ Fonts without a cap-height metric fail at load time. +## Faces++`newStyleWith` takes a `Face`, a font together with variation axis values and OpenType feature overrides.+Axes the face leaves out keep their defaults, and static fonts ignore axes.+A tag listed twice keeps its last value, as in CSS.++```haskell+import KB.Text.Shape.FFI.Enums.FeatureTag qualified as FeatureTag++bold <- Measure.newStyleWith ctx (Measure.face font){Measure.variations = [KBTS.Variation (KBTS.fourcc 'w' 'g' 'h' 't') 700]} 1.0+digits <- Measure.newStyleWith ctx (Measure.face font){Measure.features = [(FeatureTag.FEATURE_TAG_tnum, 1)]} 1.0+```++The renderer has to apply the same settings, for example with CSS `font-variation-settings` and `font-feature-settings`.+The cap height always comes from the font's default instance.+Axis values never change `Style.scale`.+ ## Demos The demo executables live in `demos/` behind the `demos` package flag (off by default).@@ -79,3 +96,4 @@ - Pretext's preprocessing rules are largely subsumed by kbts line breaking. `Analysis` adds the two missing tailorings: URL query-separator splits scoped to slash-containing tokens, and en/em-dash digit-range suppression. - `prepare` needs the open `TextShape.Context`; the `PreparedText` does not. Prepared texts can be laid out, sliced, and emergency-broken after the context closes. - `pushFontFromFile` and `pushFontFromMemory` reject missing files and fonts without `unitsPerEm` or a cap-height metric at load time, so bad fonts fail fast.+- Shaping failures throw kb-text-shape's `ShapeException`. After a `ContextError` the shaping context is unusable, along with every `LayoutContext` built over it.
demos/bubbles/Main.hs view
@@ -29,8 +29,8 @@ a : b : _ -> (a, b) [a] -> (a, a) [] ->- ( "assets/NotoSans-Regular.kbts.zst"- , "assets/NotoColorEmoji.kbts.zst"+ ( "demos/assets/NotoSans-Regular.kbts.zst"+ , "demos/assets/NotoColorEmoji.kbts.zst" ) TextShape.withContext \shape -> do bodyFont <- Demo.pushFont shape bodyFile@@ -85,9 +85,9 @@ (bubbleDivs, totalH) = stack 0 (map bubble prepped) fontFace = Demo.fontFaces [("Body", bodyFile), ("Emoji", emojiFile)] container = Demo.canvas (containerW * unit) totalH (Text.concat bubbleDivs)- Text.IO.writeFile "bubbles.html" $+ Text.IO.writeFile "demos/bubbles.html" $ Html.page "kb-text-layout bubbles" (fontFace <> container)- printf "wrote bubbles.html (%d bubbles)\n" (length prepped)+ printf "wrote demos/bubbles.html (%d bubbles)\n" (length prepped) conversation :: Style -> Span -> [(Side, [Span])] conversation body pill =
demos/demo/Main.hs view
@@ -31,15 +31,15 @@ a : b : _ -> (a, b) [a] -> (a, a) [] ->- ( "assets/Ubuntu-R.kbts.zst"- , "assets/Ubuntu-R.kbts.zst"+ ( "demos/assets/Ubuntu-R.kbts.zst"+ , "demos/assets/Ubuntu-R.kbts.zst" ) TextShape.withContext \shape -> do bodyFont <- Demo.pushFont shape bodyFile accentFont <- Demo.pushFont shape accentFile ctx <- Measure.createLayoutContext shape body <- Measure.newStyle ctx bodyFont 1.0- accent <- Measure.newStyle ctx accentFont 1.0+ accent <- Measure.newStyleWith ctx (Measure.face accentFont){Measure.variations = [TextShape.Variation (TextShape.fourcc 'w' 'g' 'h' 't') 700]} 1.0 let pxSize = 11 :: Float @@ -92,6 +92,6 @@ <> [block rich 180] <> [Demo.caption "same line ranges, laid out once, rendered at unit 8 / 11 / 14"] <> map scaled [8, 11, 14]- Text.IO.writeFile "demo.html" $+ Text.IO.writeFile "demos/demo.html" $ Html.page "kb-text-layout demo" (fontFace <> Text.intercalate "<hr>" blocks)- printf "wrote demo.html\n"+ printf "wrote demos/demo.html\n"
demos/justify/Main.hs view
@@ -65,7 +65,7 @@ args <- getArgs let fontFile = case args of a : _ -> a- [] -> "assets/NotoSans-Regular.kbts.zst"+ [] -> "demos/assets/NotoSans-Regular.kbts.zst" TextShape.withContext \shape -> do font <- Demo.pushFont shape fontFile ctx <- Measure.createLayoutContext shape@@ -113,6 +113,6 @@ for_ variants \v@(name, _, ranges) -> do let (joins, widest) = metrics v printf "%-34s %2d lines, %2d river joins, widest gap %5.1fpx\n" (Text.unpack name) (length ranges) joins widest- Text.IO.writeFile "justify.html" $+ Text.IO.writeFile "demos/justify.html" $ Html.page "kb-text-layout justification" (fontFace <> columns)- printf "wrote justify.html\n"+ printf "wrote demos/justify.html\n"
demos/lib/Demo.hs view
@@ -18,19 +18,23 @@ ) where import Codec.Compression.Zstd qualified as Zstd+import Data.Bits (shiftR, (.&.)) import Data.ByteString qualified as ByteString-import Data.Char (isLetter)-import Data.List (isSuffixOf)+import Data.Char (chr, isLetter)+import Data.List (intercalate, isSuffixOf) import Data.Maybe (mapMaybe) import Data.Text (Text) import Data.Text qualified as Text+import Data.Word (Word32)+import System.FilePath (isAbsolute, normalise, splitDirectories) import Text.Hyphenation (english_US, hyphenate) import Text.Printf (printf) import KB.Text.Layout.Html qualified as Html-import KB.Text.Layout.Measure (Style)+import KB.Text.Layout.Measure (Face, Style) import KB.Text.Layout.Measure qualified import KB.Text.Shape qualified as TextShape+import KB.Text.Shape.FFI.Enums.FeatureTag (FeatureTag (..)) rivers :: Text rivers =@@ -79,13 +83,38 @@ [] -> packed where strip suffix = Text.stripSuffix suffix packed- packed = Text.pack path+ packed = Text.pack (pageRelative path) +pageRelative :: FilePath -> FilePath+pageRelative path+ | isAbsolute path = path+ | otherwise = case splitDirectories (normalise path) of+ "demos" : inside -> intercalate "/" inside+ outside -> intercalate "/" (".." : outside)+ fontCss :: Float -> Style -> [Text] -> Text fontCss unit style families = Text.pack (printf "font:%.2fpx " (style.em * unit)) <> Text.concat ["\"" <> family <> "\"," | family <- families] <> "sans-serif"+ <> faceCss style.face++faceCss :: Face -> Text+faceCss typeface =+ settings "font-variation-settings" [(v.tag, axisValue v.value) | v <- typeface.variations]+ <> settings "font-feature-settings" [(tag, Text.pack (show value)) | (FeatureTag tag, value) <- typeface.features]+ where+ settings property = \case+ [] -> ""+ entries -> ";" <> property <> ":" <> Text.intercalate "," ["\"" <> tagText tag <> "\" " <> value | (tag, value) <- entries]+ axisValue v+ | v == fromIntegral whole = Text.pack (show whole)+ | otherwise = Text.pack (show v)+ where+ whole = round v :: Int++tagText :: Word32 -> Text+tagText tag = Text.pack [chr (fromIntegral (tag `shiftR` (8 * i) .&. 0xff)) | i <- [0 .. 3]] options :: Float -> Float -> Style -> Text -> Html.Options options unit width base css =
demos/masonry/Main.hs view
@@ -26,7 +26,7 @@ let (headFile, bodyFile) = case args of a : b : _ -> (a, b) [a] -> (a, a)- [] -> ("assets/Ubuntu-B.kbts.zst", "assets/NotoSans-Regular.kbts.zst")+ [] -> ("demos/assets/Ubuntu-B.kbts.zst", "demos/assets/NotoSans-Regular.kbts.zst") TextShape.withContext \shape -> do headFont <- Demo.pushFont shape headFile bodyFont <- Demo.pushFont shape bodyFile@@ -81,9 +81,9 @@ ] fontFace = Demo.fontFaces [("Head", headFile), ("Body", bodyFile)] sections = [section 3 820, section 2 544, section 1 268, section 2 360]- Text.IO.writeFile "masonry.html" $+ Text.IO.writeFile "demos/masonry.html" $ Html.page "kb-text-layout masonry" (fontFace <> Text.intercalate "<hr>" sections)- printf "wrote masonry.html (%d cards)\n" (length prepped)+ printf "wrote demos/masonry.html (%d cards)\n" (length prepped) pack :: Int -> Float -> [(Float, Text)] -> ([(Int, Float, Float, Text)], Float) pack cols spacing measured = (reverse placed, maximum ended - spacing)
demos/obstacles/Main.hs view
@@ -88,7 +88,7 @@ args <- getArgs let fontFile = case args of a : _ -> a- [] -> "assets/NotoSans-Regular.kbts.zst"+ [] -> "demos/assets/NotoSans-Regular.kbts.zst" TextShape.withContext \shape -> do font <- Demo.pushFont shape fontFile ctx <- Measure.createLayoutContext shape@@ -133,6 +133,6 @@ _ -> (fromIntegral (maximum [b | (b, _, _, _) <- routed]) + 1) * lineHeight * unit fontFace = Demo.fontFaces [("Body", fontFile)] canvas = Demo.canvas canvasW totalH (Text.concat (map obstacleDiv obstacles) <> Text.concat (map lineDiv routed))- Text.IO.writeFile "obstacles.html" $+ Text.IO.writeFile "demos/obstacles.html" $ Html.page "kb-text-layout obstacle routing" (fontFace <> canvas)- printf "wrote obstacles.html (%d lines over %d bands)\n" (length routed) (1 + maximum [b | (b, _, _, _) <- routed])+ printf "wrote demos/obstacles.html (%d lines over %d bands)\n" (length routed) (1 + maximum [b | (b, _, _, _) <- routed])
kb-text-layout.cabal view
@@ -5,7 +5,7 @@ -- see: https://github.com/sol/hpack name: kb-text-layout-version: 0.1.2.0+version: 0.2.0.0 synopsis: Multiline text measurement & layout. category: Text author: IC Rainbow@@ -55,7 +55,7 @@ build-depends: base >=4.18 && <5 , containers- , kb-text-shape >=0.2.1.0 && <0.3+ , kb-text-shape ==0.3.* , text , vector default-language: GHC2021@@ -86,6 +86,7 @@ build-depends: base >=4.18 && <5 , bytestring+ , filepath , hyphenation , kb-text-layout , kb-text-shape
src/KB/Text/Layout/Measure.hs view
@@ -20,9 +20,13 @@ -- * Styles , newStyle+ , newStyleWith , Style (..)+ , Face (..)+ , face ) where +import Data.Containers.ListUtils (nubOrdOn) import Data.IORef (IORef, atomicModifyIORef', modifyIORef', newIORef, readIORef, writeIORef) import Data.Map.Strict (Map) import Data.Map.Strict qualified as Map@@ -34,6 +38,7 @@ import KB.Text.Layout.Analysis (BreakKind (..), Segment (..), analyze) import KB.Text.Layout.Segmentation qualified as Segmentation import KB.Text.Shape qualified as TextShape+import KB.Text.Shape.FFI.Enums.FeatureTag (FeatureTag) import KB.Text.Shape.Font qualified as Font prepare :: LayoutContext -> Style -> Text -> IO PreparedText@@ -141,7 +146,7 @@ charAdvances ctx style t | Text.null t = pure Storable.empty | otherwise = do- runs <- TextShape.run ctx.shape (TextShape.withFont_ style.font (TextShape.text_ t))+ runs <- shapeRuns ctx style.face t contributions <- concat <$> traverse runContributions runs pure (Storable.map (* style.scale) (Storable.accum (+) (Storable.replicate n 0) contributions)) where@@ -163,32 +168,42 @@ Map.lookup (style.key, t) <$> readIORef ctx.metrics >>= \case Just w -> pure w Nothing -> do- w <- shapedWidth ctx style.font style.grid style.scale t+ w <- shapedWidth ctx style.face style.grid style.scale t modifyIORef' ctx.metrics (Map.insert (style.key, t) w) pure w -shapedWidth :: LayoutContext -> Font.Font -> Float -> Float -> Text -> IO Float-shapedWidth ctx font grid scale t = do- runs <- TextShape.run ctx.shape (TextShape.withFont_ font (TextShape.text_ t))+shapedWidth :: LayoutContext -> Face -> Float -> Float -> Text -> IO Float+shapedWidth ctx typeface grid scale t = do+ runs <- shapeRuns ctx typeface t let runWidth (run, glyphs) = do info <- Font.getFontInfo run.font let toGrid = grid / fromIntegral info.unitsPerEm pure (sum [fromIntegral g.advanceX | g <- glyphs] * toGrid) (* scale) . sum <$> traverse runWidth runs +shapeRuns :: LayoutContext -> Face -> Text -> IO [(TextShape.Run, [TextShape.Glyph])]+shapeRuns ctx typeface t =+ TextShape.withFontVariations ctx.shape typeface.font typeface.variations+ $ TextShape.run ctx.shape+ $ foldr (uncurry TextShape.withFeature_) (TextShape.text_ t) typeface.features+ newStyle :: LayoutContext -> Font.Font -> Float -> IO Style-newStyle ctx font size = do- info <- Font.getFontInfo font+newStyle ctx = newStyleWith ctx . face++newStyleWith :: LayoutContext -> Face -> Float -> IO Style+newStyleWith ctx requested size = do+ let typeface = requested{variations = lastPerTag (.tag) requested.variations, features = lastPerTag fst requested.features}+ info <- Font.getFontInfo typeface.font key <- atomicModifyIORef' ctx.styleKeys \n -> (n + 1, n) let scale = size / fromIntegral info.capitalHeight grid = fromIntegral info.unitsPerEm- spaceWidth <- shapedWidth ctx font grid scale " "- hyphenWidth <- shapedWidth ctx font grid scale "-"+ spaceWidth <- shapedWidth ctx typeface grid scale " "+ hyphenWidth <- shapedWidth ctx typeface grid scale "-" pure Style { key- , font+ , face = typeface , size , em = size * Font.emToCaps info , scale@@ -199,7 +214,7 @@ data Style = Style { key :: Int- , font :: Font.Font+ , face :: Face , size :: Float , em :: Float , scale :: Float@@ -207,6 +222,19 @@ , spaceWidth :: Float , hyphenWidth :: Float }++data Face = Face+ { font :: Font.Font+ , variations :: [TextShape.Variation]+ , features :: [(FeatureTag, Int)]+ }+ deriving stock (Eq, Show)++face :: Font.Font -> Face+face font = Face{font, variations = [], features = []}++lastPerTag :: (Ord tag) => (a -> tag) -> [a] -> [a]+lastPerTag tag = reverse . nubOrdOn tag . reverse createLayoutContext :: TextShape.Context -> IO LayoutContext createLayoutContext shape = do
test/Spec.hs view
@@ -14,15 +14,17 @@ import KB.Text.Layout.Break (Cursor (..), LineEnd (..), LineStretch (..)) import KB.Text.Layout.Break qualified as Break import KB.Text.Layout.Html qualified as Html-import KB.Text.Layout.Measure (Grapheme (..), LayoutContext, MeasuredSegment (..), PreparedText (..), Span (..), Style)+import KB.Text.Layout.Measure (Face (..), Grapheme (..), LayoutContext, MeasuredSegment (..), PreparedText (..), Span (..), Style) import KB.Text.Layout.Measure qualified as Measure import KB.Text.Layout.Segmentation qualified as Segmentation import KB.Text.Shape qualified as TextShape+import KB.Text.Shape.FFI.Enums.FeatureTag qualified as FeatureTag main :: IO () main = TextShape.withContext \shape -> do font <- TextShape.pushFontFromFile shape "demos/assets/NotoSans-Regular.ttf" 0+ variable <- TextShape.pushFontFromFile shape "demos/assets/Ubuntu-R.ttf" 0 ctx <- Measure.createLayoutContext shape body <- Measure.newStyle ctx font 1.0 accent <- Measure.newStyle ctx font 1.5@@ -31,6 +33,7 @@ "kb-text-layout" [ layoutTests , prepareTests ctx body accent+ , faceTests ctx body variable ] layoutTests :: TestTree@@ -193,6 +196,56 @@ html = Html.render opts prep (Break.layoutGreedy prep 80) Text.count "word-spacing" html @?= 1 Text.isInfixOf "word-spacing:10.00px" html @?= True+ ]++faceTests :: LayoutContext -> Style -> TextShape.Font -> TestTree+faceTests ctx body variable =+ testGroup+ "faces"+ [ testCase "styles shape in their own font, not the one on top of the stack" do+ let t = "Hamburgefonstiv"+ alone <- TextShape.withContext \shape -> do+ font <- TextShape.pushFontFromFile shape "demos/assets/NotoSans-Regular.ttf" 0+ aloneCtx <- Measure.createLayoutContext shape+ aloneStyle <- Measure.newStyle aloneCtx font 1.0+ Measure.charAdvances aloneCtx aloneStyle t+ stacked <- Measure.charAdvances ctx body t+ stacked @?= alone+ , testCase "feature overrides reach the shaper and stay in their style" do+ proportional <- Measure.newStyleWith ctx (Measure.face body.face.font){features = [(FeatureTag.FEATURE_TAG_pnum, 1)]} 1.0+ before <- Measure.charAdvances ctx body "1111"+ narrowed <- Measure.charAdvances ctx proportional "1111"+ after <- Measure.charAdvances ctx body "1111"+ assertBool "pnum narrows every digit" (Storable.and (Storable.zipWith (<) narrowed before))+ after @?= before+ , testCase "variation axes reach the shaper and stay in their style" do+ regular <- Measure.newStyle ctx variable 1.0+ bold <- Measure.newStyleWith ctx (Measure.face variable){variations = [TextShape.Variation (TextShape.fourcc 'w' 'g' 'h' 't') 800]} 1.0+ before <- Measure.charAdvances ctx regular "Abc"+ widened <- Measure.charAdvances ctx bold "Abc"+ after <- Measure.charAdvances ctx regular "Abc"+ assertBool "wght 800 widens every letter" (Storable.and (Storable.zipWith (<) before widened))+ after @?= before+ assertClose bold.scale regular.scale+ , testCase "a repeated tag keeps its last value and spares the other tags" do+ let+ pnum = FeatureTag.FEATURE_TAG_pnum+ kern = FeatureTag.FEATURE_TAG_kern+ wght = TextShape.Variation (TextShape.fourcc 'w' 'g' 'h' 't')+ advancesWith typeface t = Measure.newStyleWith ctx typeface 1.0 >>= \style -> Measure.charAdvances ctx style t+ withFeatures font features = (Measure.face font){features}+ withVariations font variations = (Measure.face font){variations}+ proportional <- advancesWith (withFeatures body.face.font [(pnum, 1)]) "1111"+ tabular <- advancesWith (withFeatures body.face.font []) "1111"+ repeatedKern <- advancesWith (withFeatures body.face.font [(kern, 1), (kern, 1), (pnum, 1)]) "1111"+ overridden <- advancesWith (withFeatures body.face.font [(pnum, 1), (pnum, 0)]) "1111"+ repeatedKern @?= proportional+ overridden @?= tabular+ bold <- advancesWith (withVariations variable [wght 800]) "Abc"+ reweighted <- advancesWith (withVariations variable [wght 400, wght 800]) "Abc"+ reweighted @?= bold+ normalized <- Measure.newStyleWith ctx (withFeatures body.face.font [(pnum, 1), (kern, 0), (pnum, 0)]) 1.0+ normalized.face.features @?= [(kern, 0), (pnum, 0)] ] prepareTests :: LayoutContext -> Style -> Style -> TestTree