kb-text-layout 0.2.0.0 → 0.3.0.0
raw patch · 8 files changed
+417/−106 lines, 8 filesPVP ok
version bump matches the API change (PVP)
API changes (from Hackage documentation)
+ KB.Text.Layout.Break: KeepWords :: Overflow
+ KB.Text.Layout.Break: Spacing :: Float -> Float -> Spacing
+ KB.Text.Layout.Break: SplitWords :: Overflow
+ KB.Text.Layout.Break: [overfull] :: LineRange -> Bool
+ KB.Text.Layout.Break: [shrink] :: Spacing -> Float
+ KB.Text.Layout.Break: [stretch] :: Spacing -> Float
+ KB.Text.Layout.Break: data Overflow
+ KB.Text.Layout.Break: data Spacing
+ KB.Text.Layout.Break: instance GHC.Base.Semigroup KB.Text.Layout.Break.Cost
+ KB.Text.Layout.Break: instance GHC.Classes.Eq KB.Text.Layout.Break.Cost
+ KB.Text.Layout.Break: instance GHC.Classes.Eq KB.Text.Layout.Break.Overflow
+ KB.Text.Layout.Break: instance GHC.Classes.Eq KB.Text.Layout.Break.Spacing
+ KB.Text.Layout.Break: instance GHC.Classes.Ord KB.Text.Layout.Break.Cost
+ KB.Text.Layout.Break: instance GHC.Show.Show KB.Text.Layout.Break.Overflow
+ KB.Text.Layout.Break: instance GHC.Show.Show KB.Text.Layout.Break.Spacing
+ KB.Text.Layout.Break: justified :: Spacing
+ KB.Text.Layout.Break: layoutGreedyWith :: Overflow -> PreparedText -> Float -> [LineRange]
+ KB.Text.Layout.Break: layoutNextLineRangeWith :: Overflow -> PreparedText -> Float -> Cursor -> Maybe (LineRange, Maybe Cursor)
+ KB.Text.Layout.Break: layoutOptimalWith :: Spacing -> Overflow -> PreparedText -> Float -> [LineRange]
+ KB.Text.Layout.Break: ragged :: Spacing
+ KB.Text.Layout.Break: shrinkwrapWith :: Overflow -> PreparedText -> Float -> Float
- KB.Text.Layout.Break: LineRange :: Cursor -> Cursor -> Float -> LineEnd -> LineRange
+ KB.Text.Layout.Break: LineRange :: Cursor -> Cursor -> Float -> LineEnd -> Bool -> LineRange
Files
- CHANGELOG.md +19/−0
- README.md +2/−2
- demos/justify/Main.hs +17/−24
- demos/lib/KB/Text/Layout/Html.hs +48/−20
- demos/obstacles/Main.hs +6/−3
- kb-text-layout.cabal +1/−1
- src/KB/Text/Layout/Break.hs +176/−54
- test/Spec.hs +148/−2
CHANGELOG.md view
@@ -6,6 +6,25 @@ and this project adheres to the [Haskell Package Versioning Policy](https://pvp.haskell.org/). +## 0.3.0.0 - 2026-12-01++- Breaking: `LineRange` gets an `overfull` field for a line that runs past the target further than its spacing allows.+ Check it instead of comparing `width` with the target. `justified` optimal layouts shrink some lines past the target on purpose.+- Breaking: `Overflowed` only marks a line cut where no break was allowed, such as between the graphemes of a word.+ A lone atom or grapheme wider than the line now ends like any other line. Check `overfull` to catch it.+- Add `Overflow` with `layoutGreedyWith`, `layoutNextLineRangeWith` and `shrinkwrapWith`. It says what happens to a word wider than the line.+ `SplitWords` breaks it between graphemes, as before. `KeepWords` keeps it whole on an overfull line. Soft hyphens still break it.+ With `KeepWords`, `shrinkwrapWith` can return more than the given width.+- Add `layoutOptimalWith`, taking an `Overflow` and a `Spacing` that says how far spaces may stretch and shrink.+ `justified` lets them shrink by a third, as `layoutOptimal` does. `ragged` never shrinks them.+ Its lines only run past the target to fit a word, atom or glued run wider than the line.+- `layoutOptimal` no longer falls back to greedy layout for the whole text when a word, atom or glued run is wider than the line.+ It puts that piece on lines of its own and keeps the rest optimal.+- Fix `layoutOptimal` resizing the indentation after a hard break or leaving it on a line of its own.+- Fix `layoutOptimal` around atoms. It could drop an atom at the end of a line or end a line with the space before one.+- Fix greedy layout hyphenating a word before an atom when the whole word fits.+- Fix greedy layout adding a blank line after an atom or grapheme wider than the line when a hard break follows.+ ## 0.2.0.0 - 2026-11-17 - Require kb-text-shape 0.3.
README.md view
@@ -29,8 +29,8 @@ putStrLn "Ranges:" mapM_ print ranges- -- LineRange {from = Cursor {segment = 0, grapheme = 0}, to = Cursor {segment = 9, grapheme = 0}, width = 13.909091, ended = Wrapped}- -- LineRange {from = Cursor {segment = 10, grapheme = 0}, to = Cursor {segment = 15, grapheme = 0}, width = 13.470421, ended = Finished}+ -- LineRange {from = Cursor {segment = 0, grapheme = 0}, to = Cursor {segment = 9, grapheme = 0}, width = 13.909091, ended = Wrapped, overfull = False}+ -- LineRange {from = Cursor {segment = 10, grapheme = 0}, to = Cursor {segment = 15, grapheme = 0}, width = 13.470421, ended = Finished, overfull = False} putStrLn "" putStrLn "Lines:"
demos/justify/Main.hs view
@@ -1,6 +1,7 @@ module Main (main) where import Data.Foldable (for_)+import Data.Maybe (fromMaybe) import Data.Text qualified as Text import Data.Text.IO qualified as Text.IO import Data.Vector qualified as Vector@@ -10,7 +11,7 @@ import Demo qualified import KB.Text.Layout.Analysis (BreakKind (..))-import KB.Text.Layout.Break (LineEnd (..), LineRange)+import KB.Text.Layout.Break (LineRange) import KB.Text.Layout.Break qualified as Break import KB.Text.Layout.Html qualified as Html import KB.Text.Layout.Measure (PreparedText)@@ -22,35 +23,27 @@ lineHeight = 2 colW = 300 -gapsOf :: PreparedText -> Float -> LineRange -> [(Float, Float)]-gapsOf prep target line+gapsOf :: Html.Options -> PreparedText -> LineRange -> [(Float, Float)]+gapsOf opts prep line | line.from.grapheme /= 0 || line.to.grapheme /= 0 = []- | otherwise = go 0 line.from.segment []+ | otherwise = go 0 False line.from.segment [] where segs = prep.segments- exempt = line.ended == HardBroken || line.ended == Finished- separators =- sum- [ Text.length s.text- | j <- [line.from.segment .. line.to.segment - 1]- , let s = segs Vector.! j- , s.kind == Space- ]- extraPerChar- | exempt || separators == 0 = 0- | otherwise = (target - line.width) / fromIntegral separators- go x j acc+ extra = fromMaybe 0 (Html.wordSpacing opts prep line)+ go x started j acc | j >= line.to.segment = reverse acc | otherwise = let s = segs Vector.! j in case s.kind of- Space ->- let x' = x + s.width + extraPerChar * fromIntegral (Text.length s.text)- in go x' (j + 1) ((x, x') : acc)- SoftHyphen -> go x (j + 1) acc- HardBreak -> go x (j + 1) acc- ZeroWidthBreak -> go x (j + 1) acc- _ -> go (x + s.width) (j + 1) acc+ Space+ | started ->+ let x' = x + s.width + extra * fromIntegral (Text.count " " s.text)+ in go x' started (j + 1) ((x, x') : acc)+ | otherwise -> go (x + s.width) started (j + 1) acc+ SoftHyphen -> go x started (j + 1) acc+ HardBreak -> go x started (j + 1) acc+ ZeroWidthBreak -> go x started (j + 1) acc+ _ -> go (x + s.width) True (j + 1) acc riverJoins :: [[(Float, Float)]] -> Int riverJoins rows = sum (zipWith joins rows (drop 1 rows))@@ -84,7 +77,7 @@ cssFont = Demo.fontCss unit body ["Body"] opts = (Demo.options unit w body cssFont){Html.justify = True} metrics (_, prep, ranges) =- let rows = map (gapsOf prep w) ranges+ let rows = map (gapsOf opts prep) ranges in (riverJoins rows, widestGap rows * unit) column title content = "<div>" <> Demo.captionWidth colW title <> content <> "</div>" engineColumn v@(name, prep, ranges) =
demos/lib/KB/Text/Layout/Html.hs view
@@ -1,6 +1,7 @@ module KB.Text.Layout.Html ( -- * Rendering laid-out lines render+ , wordSpacing , Options (..) , height @@ -9,6 +10,7 @@ , escape ) where +import Data.List (mapAccumL) import Data.Text (Text) import Data.Text qualified as Text import Text.Printf (printf)@@ -38,30 +40,56 @@ , ";text-box-trim:trim-both;text-box-edge:cap alphabetic" , ";white-space:pre" <> spacing <> ";" <> escape opts.baseCss <> "\">" ]- , map renderSlice slices+ , zipWith renderSlice (runsOf slices) slices , ["</div>"] ] where slices = materializeSlices prepared range- separators = sum [Text.count " " s.text + Text.count "\xA0" s.text | s <- slices, not s.atom]- slack = opts.width - range.width- spacing- | opts.justify- , range.ended /= HardBroken- , range.ended /= Finished- , abs slack > 1e-4- , separators > 0 =- ";word-spacing:" <> pxAbs (slack * opts.unit / fromIntegral separators)- | otherwise = ""- renderSlice slice =- Text.concat- [ "<span style=\""- , if slice.atom then "display:inline-block;width:" <> px slice.width <> ";word-spacing:normal;" else ""- , escape (opts.styleCss slice.style)- , "\">"- , escape slice.text- , "</span>"- ]+ spacing = maybe "" (\extra -> ";word-spacing:" <> px extra) (wordSpacing opts prepared range)+ renderSlice runs slice =+ Text.concat+ [ "<span style=\""+ , if slice.atom then "display:inline-block;width:" <> px slice.width <> ";word-spacing:normal;" else ""+ , escape (opts.styleCss slice.style)+ , "\">"+ , if slice.atom then escape slice.text else Text.concat (map renderRun runs)+ , "</span>"+ ]+ renderRun run+ | run.stretches || Text.null spacing = escape run.text+ | otherwise = "<span style=\"word-spacing:normal\">" <> escape run.text <> "</span>"++wordSpacing :: Options -> PreparedText -> LineRange -> Maybe Float+wordSpacing opts prepared range+ | opts.justify+ , not range.overfull+ , slack < -1e-4 || slack > 1e-4 && not lastInParagraph+ , separators > 0 =+ Just (slack / fromIntegral separators)+ | otherwise = Nothing+ where+ runs = concat (runsOf (materializeSlices prepared range))+ separators = sum [Text.count " " run.text | run <- runs, run.stretches]+ slack = opts.width - range.width+ lastInParagraph = range.ended == HardBroken || range.ended == Finished++data Run = Run+ { text :: Text+ , stretches :: Bool+ }++runsOf :: [LineSlice] -> [[Run]]+runsOf = snd . mapAccumL spaceRuns True++spaceRuns :: Bool -> LineSlice -> (Bool, [Run])+spaceRuns indenting slice+ | slice.atom = (False, [])+ | otherwise = (indenting && Text.null rest, indentRun <> map glueAware (Text.groupBy sameGlue rest))+ where+ (indent, rest) = if indenting then Text.span (== ' ') slice.text else ("", slice.text)+ indentRun = [Run{text = indent, stretches = False} | not (Text.null indent)]+ sameGlue a b = (a == '\xA0') == (b == '\xA0')+ glueAware run = Run{text = run, stretches = not (Text.any (== '\xA0') run)} data Options = Options { width :: Float
demos/obstacles/Main.hs view
@@ -79,9 +79,12 @@ | otherwise -> go (max x hi) rest widest :: [(Float, Float)] -> Maybe (Float, Float)-widest = \case- [] -> Nothing- xs -> Just (last (sortOn (\(lo, hi) -> hi - lo) xs))+widest gaps+ | null gaps = Nothing+ | otherwise = Just (last [gap | gap <- gaps, width gap >= best - 0.5])+ where+ width (lo, hi) = hi - lo+ best = maximum (map width gaps) main :: IO () main = do
kb-text-layout.cabal view
@@ -5,7 +5,7 @@ -- see: https://github.com/sol/hpack name: kb-text-layout-version: 0.2.0.0+version: 0.3.0.0 synopsis: Multiline text measurement & layout. category: Text author: IC Rainbow
src/KB/Text/Layout/Break.hs view
@@ -1,13 +1,20 @@ module KB.Text.Layout.Break ( -- * Breaking prepared text into lines layoutGreedy+ , layoutGreedyWith , layoutOptimal+ , layoutOptimalWith+ , Overflow (..)+ , Spacing (..)+ , justified+ , ragged , LineRange (..) , Cursor (..) , LineEnd (..) -- * Breaking one line at a time , layoutNextLineRange+ , layoutNextLineRangeWith -- * Extracting line contents , materializeSlices@@ -20,10 +27,11 @@ , lineStretch , LineStretch (..) , shrinkwrap+ , shrinkwrapWith ) where import Data.Foldable qualified as Foldable-import Data.Maybe (mapMaybe)+import Data.Maybe (isNothing, mapMaybe) import Data.Text (Text) import Data.Text qualified as Text import Data.Vector (Vector)@@ -33,19 +41,42 @@ import KB.Text.Layout.Measure (Grapheme (..), MeasuredSegment (..), PreparedText (..)) layoutGreedy :: PreparedText -> Float -> [LineRange]-layoutGreedy prepared maxWidth = go (Cursor 0 0)+layoutGreedy = layoutGreedyWith SplitWords++layoutGreedyWith :: Overflow -> PreparedText -> Float -> [LineRange]+layoutGreedyWith overflow prepared maxWidth = go (Cursor 0 0) where go cursor =- case layoutNextLineRange prepared maxWidth cursor of+ case layoutNextLineRangeWith overflow prepared maxWidth cursor of Nothing -> [] Just (line, Nothing) -> [line] Just (line, Just next) -> line : go next +data Overflow+ = SplitWords+ | KeepWords+ deriving stock (Eq, Show)++data Spacing = Spacing+ { stretch :: Float+ , shrink :: Float+ }+ deriving stock (Eq, Show)++justified :: Spacing+justified = Spacing{stretch = 0.5, shrink = 1 / 3}++ragged :: Spacing+ragged = Spacing{stretch = 0.5, shrink = 0}+ layoutOptimal :: PreparedText -> Float -> [LineRange]-layoutOptimal prepared target =+layoutOptimal = layoutOptimalWith justified SplitWords++layoutOptimalWith :: Spacing -> Overflow -> PreparedText -> Float -> [LineRange]+layoutOptimalWith spacing overflow prepared target = case chosen of Just lns -> lns- Nothing -> layoutGreedy prepared target+ Nothing -> layoutGreedyWith overflow prepared target where segs = prepared.segments total = Vector.length segs@@ -56,9 +87,17 @@ spaceWidth seg = case seg.kind of Space -> seg.width _ -> 0+ visibleCount seg = case seg.kind of+ Word -> 1+ Glue -> 1+ Atomic -> 1+ _ -> 0 :: Int prefixFlow = Vector.scanl' (\acc seg -> acc + flowWidth seg) 0 segs prefixSpace = Vector.scanl' (\acc seg -> acc + spaceWidth seg) 0 segs+ prefixVisible = Vector.scanl' (\acc seg -> acc + visibleCount seg) 0 segs + hasVisible a b = b > a && prefixVisible Vector.! b > prefixVisible Vector.! a+ candidates :: Vector Breakpoint candidates = Vector.fromList $@@ -71,20 +110,37 @@ ZeroWidthBreak -> [plain i] SoftHyphen -> [Breakpoint{to = i, next = skipSpaces (i + 1), hyphen = True, forced = False}] HardBreak -> [Breakpoint{to = i, next = i + 1, hyphen = False, forced = True}]- Atomic -> [Breakpoint{to = i, next = i, hyphen = False, forced = False}, plain i]+ Atomic ->+ [Breakpoint{to = i, next = i, hyphen = False, forced = False} | attachedToPrevious i]+ <> [Breakpoint{to = i + 1, next = skipSpaces (i + 1), hyphen = False, forced = False}] Word -> [] Glue -> [] plain i = Breakpoint{to = i, next = skipSpaces (i + 1), hyphen = False, forced = False}+ attachedToPrevious i = i > 0 && (segs Vector.! (i - 1)).kind `elem` [Word, Glue, SoftHyphen] skipSpaces i | i < total, (segs Vector.! i).kind == Space = skipSpaces (i + 1) | otherwise = i + endsPiece cand = overflow == KeepWords || not cand.hyphen++ lastStopBefore :: Vector Int+ lastStopBefore = Vector.generate (Vector.length candidates) \j ->+ let+ stop = (candidates Vector.! j).to+ earlier k = let c = candidates Vector.! k in c.to < stop && endsPiece c+ in+ case filter earlier [j - 1, j - 2 .. 0] of+ k : _ -> (candidates Vector.! k).to+ [] -> 0++ hyphenWidthOf cand = if cand.hyphen then (segs Vector.! cand.to).width else 0+ lineOf a cand = let- hyphenWidth = if cand.hyphen then (segs Vector.! cand.to).width else 0- natural = prefixFlow Vector.! cand.to - prefixFlow Vector.! a + hyphenWidth- stretchable = prefixSpace Vector.! cand.to - prefixSpace Vector.! a+ natural = prefixFlow Vector.! cand.to - prefixFlow Vector.! a + hyphenWidthOf cand+ content = min cand.to (skipSpaces a)+ stretchable = prefixSpace Vector.! cand.to - prefixSpace Vector.! content in (a, natural, stretchable) @@ -93,7 +149,7 @@ if free then Just 0 else- if stretchable <= 0 then+ if stretch <= 0 then Just $! if slack < 1e-4 then 0 else looseNoGlue + slack * 1000 else Just $! 100 * ratio * ratio * ratio@@ -104,18 +160,21 @@ looseNoGlue = 1e7 slack = target - natural- ratio = slack / (0.5 * stretchable)- shrink = stretchable / 3- tightness = negate slack / max shrink 1e-6+ stretch = spacing.stretch * stretchable+ ratio = slack / stretch+ shrink = spacing.shrink * stretchable+ tightness+ | shrink <= 1e-4 = 0+ | otherwise = negate slack / shrink - demerits b hyphen = (10 + b) * (10 + b) + (if hyphen then 2500 else 0)+ demeritsOf b hyphen = (10 + b) * (10 + b) + (if hyphen then 2500 else 0) lastForcedBefore :: Vector Int lastForcedBefore = Vector.fromList $ scanl step (-1) [0 .. Vector.length candidates - 2] where step acc j = if (candidates Vector.! j).forced then j else acc - best :: Vector (Maybe (Float, Int))+ best :: Vector (Maybe (Cost, Int)) best = Vector.generate (Vector.length candidates) bestAt where bestAt j =@@ -131,19 +190,35 @@ Nothing -> rest Just (cost, _) -> maybe rest (: rest) do d <- lineCost (candidates Vector.! i).next- pure (cost + d, i)+ pure (cost <> d, i) where rest = fromPrev (i - 1) attempt i from = (\d -> (d, i)) <$> lineCost from lineCost from =- let (_a, natural, stretchable) = lineOf from cand- in demerits <$> badness natural stretchable cand.forced <*> pure cand.hyphen+ let+ (a, natural, stretchable) = lineOf from cand+ blank = not (hasVisible a cand.to)+ alone = not (hasVisible a (lastStopBefore Vector.! j))+ in+ if blank && not cand.forced then+ Nothing+ else case badness natural stretchable cand.forced of+ Just b -> Just Cost{overfullLines = 0, demerits = demeritsOf b cand.hyphen}+ Nothing+ | alone && endsPiece cand -> Just Cost{overfullLines = 1, demerits = demeritsOf 0 cand.hyphen}+ | otherwise -> Nothing options = maybe [] (: []) fromStart <> fromPrev (j - 1) in case options of [] -> Nothing _ -> Just $! minimum options + endOf cand+ | cand.hyphen = Hyphenated+ | cand.to >= total = Finished+ | cand.forced = HardBroken+ | otherwise = Wrapped+ chosen = do let final = Vector.length candidates - 1 _ <- best Vector.! final@@ -155,28 +230,48 @@ let cand = candidates Vector.! j from = if i == -1 then 0 else (candidates Vector.! i).next- (a, natural, _) = lineOf from cand- ended- | cand.hyphen = Hyphenated- | cand.to >= total = Finished- | cand.forced = HardBroken- | otherwise = Wrapped+ (a, natural, stretchable) = lineOf from cand+ overfull = isNothing (badness natural stretchable cand.forced) line = LineRange { from = Cursor a 0 , to = Cursor cand.to 0 , width = natural- , ended+ , ended = endOf cand+ , overfull }+ lines'+ | overfull && overflow == SplitWords = splitOverfull cand line+ | otherwise = [line] in- walk i $ if a >= total then acc else (line : acc)+ walk i $ if a >= total then acc else lines' <> acc pure $! walk final [] + splitOverfull cand line =+ let+ start = line.from.segment+ piece = PreparedText{segments = Vector.slice start (cand.to - start) segs}+ shift c = Cursor{segment = c.segment + start, grapheme = c.grapheme}+ fragments =+ [ LineRange{from = shift l.from, to = shift l.to, width = l.width, ended = l.ended, overfull = l.overfull}+ | l <- layoutGreedyWith SplitWords piece target+ ]+ settle l =+ let width = l.width + hyphenWidthOf cand+ in LineRange{from = l.from, to = line.to, width, ended = endOf cand, overfull = width > target + epsilon}+ settleLast = \case+ [] -> [line]+ [l] -> [settle l]+ l : rest -> l : settleLast rest+ in+ settleLast fragments+ data LineRange = LineRange { from :: Cursor , to :: Cursor , width :: Float , ended :: LineEnd+ , overfull :: Bool } deriving stock (Eq, Show) @@ -201,8 +296,20 @@ , forced :: Bool } +data Cost = Cost+ { overfullLines :: Int+ , demerits :: Float+ }+ deriving stock (Eq, Ord)++instance Semigroup Cost where+ x <> y = Cost{overfullLines = x.overfullLines + y.overfullLines, demerits = x.demerits + y.demerits}+ layoutNextLineRange :: PreparedText -> Float -> Cursor -> Maybe (LineRange, Maybe Cursor)-layoutNextLineRange prepared maxWidth cursor+layoutNextLineRange = layoutNextLineRangeWith SplitWords++layoutNextLineRangeWith :: Overflow -> PreparedText -> Float -> Cursor -> Maybe (LineRange, Maybe Cursor)+layoutNextLineRangeWith overflow prepared maxWidth cursor | cursor.segment >= total = Nothing | otherwise = Just (scanSeg cursor.segment cursor.grapheme 0 0 Nothing) where@@ -216,7 +323,14 @@ resume Cursor{segment = c.segment + 1, grapheme = 0} | otherwise = Just c - emit to width ended = LineRange{from = cursor, to, width, ended}+ emit to width ended =+ LineRange+ { from = cursor+ , to+ , width+ , ended+ , overfull = width > maxWidth + epsilon+ } scanSeg i g acc visible cand | i >= total = (emit (Cursor total 0) visible Finished, Nothing)@@ -236,9 +350,10 @@ | acc + segWidth <= maxWidth + epsilon = scanSeg (i + 1) 0 (acc + segWidth) (acc + segWidth) cand | otherwise =- case cand of- Just c -> (emit c.to c.width c.end, resume c.next)- Nothing -> emergency seg i g acc visible+ case (cand, overflow) of+ (Just c, _) -> (emit c.to c.width c.end, resume c.next)+ (Nothing, SplitWords) -> emergency seg i g acc visible+ (Nothing, KeepWords) -> scanSeg (i + 1) 0 (acc + segWidth) (acc + segWidth) cand in case seg.kind of HardBreak -> (emit (Cursor i 0) visible HardBroken, Just after)@@ -247,7 +362,7 @@ Tab -> spaceLike ZeroWidthBreak -> spaceLike SoftHyphen- | visible + segWidth <= maxWidth + epsilon ->+ | visible + segWidth <= maxWidth + epsilon || keepsOverflowing -> scanSeg (i + 1) 0 acc visible $ Just Candidate@@ -257,18 +372,22 @@ , next = after } | otherwise -> scanSeg (i + 1) 0 acc visible cand+ where+ keepsOverflowing = overflow == KeepWords && null cand && visible > 0 Atomic ->- let candBefore- | acc > 0- , maybe True (\c -> c.width < visible) cand =- Just Candidate{to = Cursor i 0, width = visible, end = Wrapped, next = Cursor i 0}- | otherwise = cand- in if acc + segWidth <= maxWidth + epsilon then- scanSeg (i + 1) 0 (acc + segWidth) (acc + segWidth) $- Just Candidate{to = after, width = acc + segWidth, end = Wrapped, next = after}- else case candBefore of- Just c -> (emit c.to c.width c.end, resume c.next)- Nothing -> (emit after (acc + segWidth) Overflowed, resume after)+ let+ candBefore+ | acc > 0+ , maybe True (\c -> c.width < visible || c.end == Hyphenated) cand =+ Just Candidate{to = Cursor i 0, width = visible, end = Wrapped, next = Cursor i 0}+ | otherwise = cand+ takeAtom =+ scanSeg (i + 1) 0 (acc + segWidth) (acc + segWidth) $+ Just Candidate{to = after, width = acc + segWidth, end = Wrapped, next = after}+ in+ case candBefore of+ Just c | acc + segWidth > maxWidth + epsilon -> (emit c.to c.width c.end, resume c.next)+ _ -> takeAtom Word -> fitOrBreak Glue -> fitOrBreak @@ -286,7 +405,10 @@ if count == 0 then (emit (Cursor i g) acc Overflowed, resume (Cursor i g)) else- (emit (Cursor i g') (acc + takenWidth) Overflowed, resume (advanceCursor seg i g'))+ if g' >= Text.length seg.text then+ scanSeg (i + 1) 0 (acc + takenWidth) (acc + takenWidth) Nothing+ else+ (emit (Cursor i g') (acc + takenWidth) Overflowed, resume (Cursor i g')) countFits = fits 0 where@@ -296,10 +418,6 @@ | w + g.width <= maxWidth + epsilon -> fits (n + 1) (w + g.width) rest | otherwise -> n - advanceCursor seg i g'- | g' >= Text.length seg.text = Cursor (i + 1) 0- | otherwise = Cursor i g'- data Candidate = Candidate { to :: Cursor , width :: Float@@ -336,9 +454,9 @@ | startG == 0 && endG == Text.length seg.text = seg.width | otherwise =- sum . map (.width) $- takeCodepoints (endG - startG) $- dropCodepoints startG seg.graphemes+ sum . map (.width)+ $ takeCodepoints (endG - startG)+ $ dropCodepoints startG seg.graphemes in case seg.kind of SoftHyphen -> Nothing@@ -436,12 +554,16 @@ deriving stock (Eq, Show) shrinkwrap :: PreparedText -> Float -> Float-shrinkwrap prepared maxWidth = go (40 :: Int) 0 maxWidth+shrinkwrap = shrinkwrapWith SplitWords++shrinkwrapWith :: Overflow -> PreparedText -> Float -> Float+shrinkwrapWith overflow prepared maxWidth = go (40 :: Int) 0 maxWidth where- countAt w = (layoutStats (layoutGreedy prepared w)).lineCount+ layout = layoutGreedyWith overflow prepared+ countAt w = (layoutStats (layout w)).lineCount target = countAt maxWidth go k lo hi- | k <= 0 = (layoutStats (layoutGreedy prepared hi)).maxLineWidth+ | k <= 0 = (layoutStats (layout hi)).maxLineWidth | countAt mid <= target = go (k - 1) lo mid | otherwise = go (k - 1) mid hi where
test/Spec.hs view
@@ -131,6 +131,86 @@ ends hyphenated 30 @?= [Hyphenated, Finished] ends broken 1000 @?= [HardBroken, Finished] ends rhythm 70 @?= [Wrapped, Finished]+ , testCase "kept words overflow whole" do+ kept prepared 30 @?= ["hello", "world"]+ map (\l -> l.ended) (Break.layoutGreedyWith Break.KeepWords (fromSegments prepared) 30) @?= [Wrapped, Finished]+ , testCase "a wide atom ends its line like any other piece" do+ let+ prep = fromSegments [atom 50 "[A]", seg HardBreak 0 "\n", word 10 "x", space, atom 50 "[B]"]+ lns = Break.layoutGreedy prep 30+ map (\l -> (Break.materializeLineRange prep l, l.ended, l.overfull)) lns+ @?= [("[A]", HardBroken, True), ("x", Wrapped, False), ("[B]", Finished, True)]+ , testCase "kept words at zero width put one word on each line" do+ kept rhythm 0 @?= ["aaa", "bbb", "ccc"]+ , testCase "kept glue holds its whole run" do+ kept glued 60 @?= ["aaa\xA0\&bbb"]+ , testCase "kept words still break at soft hyphens" do+ kept hyphenated 30 @?= ["hy-", "phen"]+ kept hyphenated 0 @?= ["hy-", "phen"]+ , testCase "kept words agree with split words when everything fits" do+ for_ [70, 100, 200] \w -> kept rhythm w @?= materialized rhythm w+ , testCase "optimal layout keeps overlong words whole" do+ let prep = fromSegments prepared+ map (Break.materializeLineRange prep) (Break.layoutOptimalWith Break.ragged Break.KeepWords prep 30)+ @?= ["hello", "world"]+ , testCase "optimal kept words agree with greedy around overlong words" do+ let optimalKept xs w = map (Break.materializeLineRange (fromSegments xs)) (Break.layoutOptimalWith Break.justified Break.KeepWords (fromSegments xs) w)+ for_ [wideHyphen <> [space, word 10 "x"], indented, [seg Tab 20 "\t", space, word 80 "longword", space, word 30 "next"]] \xs ->+ optimalKept xs 90 @?= kept xs 90+ optimalKept (wideHyphen <> [space, word 10 "x"]) 30 @?= ["hyphen", "x"]+ , testCase "an overlong word leaves the other paragraphs optimal" do+ let+ paragraphs = [word 60 "aaaaaa", space, word 10 "b", space, word 10 "c", space, word 60 "dddddd", seg HardBreak 0 "\n", word 100 "longlonglong"]+ prep = fromSegments paragraphs+ layout overflow = Break.layoutOptimalWith Break.justified overflow prep 77+ map (Break.materializeLineRange prep) (layout Break.KeepWords) @?= ["aaaaaa b", "c dddddd", "longlonglong"]+ map (\l -> l.overfull) (layout Break.KeepWords) @?= [False, False, True]+ map (Break.materializeLineRange prep) (layout Break.SplitWords) @?= ["aaaaaa b", "c dddddd", "longlongl", "ong"]+ , testCase "every layout keeps every word and atom" do+ let+ strip = Text.filter (`notElem` [' ', '\t', '\xA0', '-'])+ content xs = strip (Text.concat [s.text | s <- xs, s.kind `elem` [Word, Glue, Atomic]])+ layouts =+ [Break.layoutGreedyWith overflow | overflow <- [Break.SplitWords, Break.KeepWords]]+ <> [Break.layoutOptimalWith spacing overflow | spacing <- [Break.justified, Break.ragged], overflow <- [Break.SplitWords, Break.KeepWords]]+ atoms = [[atom 40 "[pill]", word 50 "word"], [word 30 "abc", space, atom 100 "[wide]"], [word 30 "abc", atom 40 "[pill]", word 30 "def"]]+ for_ ([prepared, hyphenated, wideHyphen, broken, glued, rhythm, indented] <> atoms) \xs ->+ for_ layouts \layout ->+ for_ [0, 25, 30, 60, 90, 200] \w -> do+ let prep = fromSegments xs+ strip (Text.concat (map (Break.materializeLineRange prep) (layout prep w))) @?= content xs+ , testCase "optimal split words overflow only where greedy does" do+ let atoms = [[atom 40 "[pill]", word 50 "word"], [word 30 "abc", space, atom 100 "[wide]"], [word 30 "abc", atom 40 "[pill]", word 30 "def"]]+ for_ ([prepared, hyphenated, wideHyphen, broken, glued, rhythm, indented] <> atoms) \xs ->+ for_ [Break.justified, Break.ragged] \spacing ->+ for_ [0, 10, 25, 30, 60, 90, 200] \w -> do+ let+ prep = fromSegments xs+ overflowing lns = any (\l -> l.overfull) lns+ assertBool ("overflow at " <> show w) $+ not (overflowing (Break.layoutOptimalWith spacing Break.SplitWords prep w)) || overflowing (Break.layoutGreedy prep w)+ , testCase "optimal split words split a hyphenated word that doesn't fit" do+ let optimal xs w = map (Break.materializeLineRange (fromSegments xs)) (Break.layoutOptimal (fromSegments xs) w)+ optimal wideHyphen 25 @?= ["hyph", "en"]+ optimal [word 25 "abc", seg SoftHyphen 10 "\xAD", word 6 "def"] 30 @?= ["abcde", "f"]+ , testCase "greedy lines flag overflow past the target" do+ map (\l -> l.overfull) (Break.layoutGreedyWith Break.KeepWords (fromSegments prepared) 30) @?= [True, True]+ map (\l -> l.overfull) (Break.layoutGreedy (fromSegments prepared) 30) @?= [False, False, False, False]+ map (\l -> l.overfull) (Break.layoutGreedyWith Break.KeepWords (fromSegments hyphenated) 0) @?= [True, True]+ , testCase "stepping kept words matches the walk" do+ let+ prep = fromSegments prepared+ go Nothing = []+ go (Just cursor) =+ case Break.layoutNextLineRangeWith Break.KeepWords prep 30 cursor of+ Nothing -> []+ Just (line, next) -> Break.materializeLineRange prep line : go next+ go (Just (Cursor 0 0)) @?= kept prepared 30+ , testCase "kept words prefer a fitting break before an atom to an overflowing hyphen" do+ kept [word 20 "hy", seg SoftHyphen 15 "\xAD", word 9 "phen", atom 40 "[pill]"] 30 @?= ["hyphen", "[pill]"]+ kept [word 50 "hello", space, atom 10 "[x]"] 30 @?= ["hello", "[x]"]+ , testCase "a fitting word before an atom keeps its soft hyphen unused" do+ materialized [word 20 "hy", seg SoftHyphen 5 "\xAD", word 3 "p", atom 40 "[pill]"] 30 @?= ["hyp", "[pill]"] , testCase "line stretch counts interior spaces only" do let prep = fromSegments rhythm@@ -157,18 +237,57 @@ Break.shrinkwrap (fromSegments rhythm) 80 @?= 70 Break.shrinkwrap (fromSegments rhythm) 200 @?= 110 Break.shrinkwrap (fromSegments prepared) 45 @?= 30+ , testCase "shrinkwrap with kept words widens to the widest word" do+ Break.shrinkwrapWith Break.KeepWords (fromSegments prepared) 45 @?= 50+ Break.shrinkwrapWith Break.KeepWords (fromSegments rhythm) 80 @?= 70 , testCase "optimal layout beats greedy on loose middle lines" do let squeeze = [word 60 "aaaaaa", space, word 10 "b", space, word 10 "c", space, word 60 "dddddd"] prep = fromSegments squeeze materialized squeeze 77 @?= ["aaaaaa", "b c", "dddddd"] map (Break.materializeLineRange prep) (Break.layoutOptimal prep 77) @?= ["aaaaaa b", "c dddddd"]+ , testCase "ragged glue never shrinks a line past the target" do+ let+ squeeze = [word 60 "aaaaaa", space, word 10 "b", space, word 10 "c", space, word 60 "dddddd"]+ prep = fromSegments squeeze+ lines' = Break.layoutOptimalWith Break.ragged Break.SplitWords prep 77+ map (Break.materializeLineRange prep) lines' @?= ["aaaaaa", "b c", "dddddd"]+ assertBool "every line fits" $ all (\line -> line.width <= 77) lines'+ , testCase "justified glue is the default optimal layout" do+ let+ squeeze = [word 60 "aaaaaa", space, word 10 "b", space, word 10 "c", space, word 60 "dddddd"]+ prep = fromSegments squeeze+ map (Break.materializeLineRange prep) (Break.layoutOptimalWith Break.justified Break.SplitWords prep 77)+ @?= ["aaaaaa b", "c dddddd"]+ , testCase "ragged glue takes an exact fit despite float noise" do+ let+ noisy = [word 20 "aa", space, word 20 "bb", space, word 10.00005 "c", space, word 30 "ddd", space, word 20 "ee"]+ prep = fromSegments noisy+ map (Break.materializeLineRange prep) (Break.layoutOptimalWith Break.ragged Break.SplitWords prep 70)+ @?= ["aa bb c", "ddd ee"]+ , testCase "rigid glue does not scatter words across lines" do+ let+ prep = fromSegments [word 30 "aaa", space, word 10 "b", space, word 40 "cccc", space, word 20 "dd", space, word 30 "eee", space, word 10 "f", space, word 50 "ggggg", space, word 20 "hh"]+ rigid = Break.Spacing{stretch = 0, shrink = 0}+ length (Break.layoutOptimalWith rigid Break.SplitWords prep 70) @?= length (Break.layoutGreedy prep 70)+ , testCase "optimal layout keeps atoms" do+ let optimal xs w = map (Break.materializeLineRange (fromSegments xs)) (Break.layoutOptimal (fromSegments xs) w)+ optimal [atom 40 "[pill]", word 50 "word"] 60 @?= ["[pill]", "word"]+ optimal [word 50 "word", atom 40 "[pill]"] 60 @?= ["word", "[pill]"]+ optimal [word 30 "abc", atom 40 "[pill]", word 30 "def"] 200 @?= ["abc[pill]def"]+ optimal [word 30 "abc", atom 40 "[pill]", word 30 "def"] 75 @?= ["abc[pill]", "def"]+ , testCase "optimal layout leaves the space before an atom off the line" do+ let prep = fromSegments [word 30 "abc", space, atom 100 "[wide]"]+ map (\l -> (Break.materializeLineRange prep l, l.width)) (Break.layoutOptimal prep 60) @?= [("abc", 30), ("[wide]", 100)]+ , testCase "optimal layout keeps indentation rigid" do+ let prep = fromSegments [word 40 "main", seg HardBreak 0 "\n", indent, word 30 "aaa", space, word 35 "bbb", space, word 30 "ccc"]+ map (Break.materializeLineRange prep) (Break.layoutOptimal prep 90) @?= ["main", " aaa", "bbb ccc"] , testCase "optimal layout agrees with greedy where greedy is fine" do let optimal xs w = map (Break.materializeLineRange (fromSegments xs)) (Break.layoutOptimal (fromSegments xs) w) optimal rhythm 70 @?= ["aaa bbb", "ccc"] optimal hyphenated 30 @?= ["hy-", "phen"] optimal broken 1000 @?= ["one", "two"]- , testCase "optimal layout falls back to greedy when infeasible" do+ , testCase "optimal layout splits an overlong glued run like greedy" do map (Break.materializeLineRange (fromSegments glued)) (Break.layoutOptimal (fromSegments glued) 60) @?= materialized glued 60 , testCase "html renderer escapes and anchors baselines" do@@ -196,6 +315,27 @@ html = Html.render opts prep (Break.layoutGreedy prep 80) Text.count "word-spacing" html @?= 1 Text.isInfixOf "word-spacing:10.00px" html @?= True+ , testCase "html renderer shrinks tight last lines" do+ let+ prep = fromSegments rhythm+ opts = Html.Options{width = 105, lineHeight = 20, unit = 1, baseCap = 1, justify = True, baseCss = "", styleCss = const ""}+ html = Html.render opts prep (Break.layoutOptimal prep 105)+ Text.isInfixOf "word-spacing:-2.50px" html @?= True+ , testCase "html renderer stretches interior spaces only" do+ let+ prep = fromSegments [word 40 "main", seg HardBreak 0 "\n", indent, word 30 "aaa", space, word 30 "bbb", seg Glue 10 "\xA0", word 30 "ccc", space, word 30 "ddd"]+ opts = Html.Options{width = 150, lineHeight = 20, unit = 1, baseCap = 1, justify = True, baseCss = "", styleCss = const ""}+ html = Html.render opts prep (Break.layoutGreedy prep 150)+ Text.isInfixOf "word-spacing:20.00px" html @?= True+ Text.isInfixOf "<span style=\"word-spacing:normal\"> </span>aaa bbb" html @?= True+ Text.isInfixOf "bbb<span style=\"word-spacing:normal\">\xA0</span>ccc" html @?= True+ , testCase "html renderer leaves overflowing lines unjustified" do+ let+ overflowing = [seg Tab 20 "\t", space, word 80 "longword", space, word 30 "next"]+ prep = fromSegments overflowing+ opts = Html.Options{width = 90, lineHeight = 20, unit = 1, baseCap = 1, justify = True, baseCss = "", styleCss = const ""}+ html = Html.render opts prep (Break.layoutGreedyWith Break.KeepWords prep 90)+ Text.isInfixOf "word-spacing" html @?= False ] faceTests :: LayoutContext -> Style -> TextShape.Font -> TestTree@@ -304,7 +444,7 @@ map (.graphemes) (toList prep.segments) @?= [[Grapheme 3 (Storable.head advances)]] let narrow = Break.layoutGreedy prep (Storable.head advances / 2) map (Break.materializeLineRange prep) narrow @?= ["ffi"]- map (.ended) narrow @?= [Overflowed]+ map (\l -> (l.ended, l.overfull)) narrow @?= [(Finished, True)] , testCase "soft hyphens and tabs take their widths from the style" do spaceWidth <- Measure.measure ctx body " " hyphenWidth <- Measure.measure ctx body "-"@@ -350,6 +490,12 @@ materialized :: [MeasuredSegment] -> Float -> [Text] materialized xs maxWidth = map (Break.materializeLineRange prep) (Break.layoutGreedy prep maxWidth)+ where+ prep = fromSegments xs++kept :: [MeasuredSegment] -> Float -> [Text]+kept xs maxWidth =+ map (Break.materializeLineRange prep) (Break.layoutGreedyWith Break.KeepWords prep maxWidth) where prep = fromSegments xs