packages feed

kb-text-layout-0.3.0.0: src/KB/Text/Layout/Break.hs

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
  , LineSlice (..)
  , materializeLineRange

    -- * Inspecting layouts
  , layoutStats
  , LayoutStats (..)
  , lineStretch
  , LineStretch (..)
  , shrinkwrap
  , shrinkwrapWith
  ) where

import Data.Foldable qualified as Foldable
import Data.Maybe (isNothing, mapMaybe)
import Data.Text (Text)
import Data.Text qualified as Text
import Data.Vector (Vector)
import Data.Vector qualified as Vector

import KB.Text.Layout.Analysis (BreakKind (..))
import KB.Text.Layout.Measure (Grapheme (..), MeasuredSegment (..), PreparedText (..))

layoutGreedy :: PreparedText -> Float -> [LineRange]
layoutGreedy = layoutGreedyWith SplitWords

layoutGreedyWith :: Overflow -> PreparedText -> Float -> [LineRange]
layoutGreedyWith overflow prepared maxWidth = go (Cursor 0 0)
  where
    go cursor =
      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 = layoutOptimalWith justified SplitWords

layoutOptimalWith :: Spacing -> Overflow -> PreparedText -> Float -> [LineRange]
layoutOptimalWith spacing overflow prepared target =
  case chosen of
    Just lns -> lns
    Nothing -> layoutGreedyWith overflow prepared target
  where
    segs = prepared.segments
    total = Vector.length segs

    flowWidth seg = case seg.kind of
      SoftHyphen -> 0
      _ -> seg.width
    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 $
        concatMap breakable [0 .. total - 1] <> [Breakpoint{to = total, next = total, hyphen = False, forced = True}]
      where
        breakable i = case (segs Vector.! i).kind of
          Space -> [plain i]
          Tab -> [plain i]
          PreservedSpace -> [plain i]
          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} | 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
        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)

    badness natural stretchable free
      | slack >= 0 =
          if free then
            Just 0
          else
            if stretch <= 0 then
              Just $! if slack < 1e-4 then 0 else looseNoGlue + slack * 1000
            else
              Just $! 100 * ratio * ratio * ratio
      | negate slack > shrink + 1e-4 = Nothing
      | otherwise = Just $! 100 * tightness * tightness * tightness
      where
        looseNoGlue :: Float
        looseNoGlue = 1e7

        slack = target - natural
        stretch = spacing.stretch * stretchable
        ratio = slack / stretch
        shrink = spacing.shrink * stretchable
        tightness
          | shrink <= 1e-4 = 0
          | otherwise = negate slack / shrink

    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 (Cost, Int))
    best = Vector.generate (Vector.length candidates) bestAt
      where
        bestAt j =
          let
            cand = candidates Vector.! j
            floor_ = lastForcedBefore Vector.! j
            fromStart
              | floor_ == -1 = attempt (-1) 0
              | otherwise = Nothing
            fromPrev i
              | i < max floor_ 0 = []
              | otherwise = case best Vector.! i of
                  Nothing -> rest
                  Just (cost, _) -> maybe rest (: rest) do
                    d <- lineCost (candidates Vector.! i).next
                    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
                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
      let walk j acc
            | j == -1 = acc
            | otherwise = case best Vector.! j of
                Nothing -> acc
                Just (_, i) ->
                  let
                    cand = candidates Vector.! j
                    from = if i == -1 then 0 else (candidates Vector.! i).next
                    (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 = endOf cand
                        , overfull
                        }
                    lines'
                      | overfull && overflow == SplitWords = splitOverfull cand line
                      | otherwise = [line]
                  in
                    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)

data Cursor = Cursor
  { segment :: Int
  , grapheme :: Int
  }
  deriving stock (Eq, Ord, Show)

data LineEnd
  = Wrapped
  | Hyphenated
  | Overflowed
  | HardBroken
  | Finished
  deriving stock (Eq, Ord, Show)

data Breakpoint = Breakpoint
  { to :: Int
  , next :: Int
  , hyphen :: Bool
  , 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 = 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
    segs = prepared.segments
    total = Vector.length segs

    resume c
      | c.segment < total
      , c.grapheme == 0
      , (segs Vector.! c.segment).kind == Space =
          resume Cursor{segment = c.segment + 1, grapheme = 0}
      | otherwise = Just c

    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)
      | otherwise =
          let
            seg = segs Vector.! i
            segWidth = if g == 0 then seg.width else sum (map (.width) (dropCodepoints g seg.graphemes))
            after = Cursor (i + 1) 0
            spaceLike =
              scanSeg
                (i + 1)
                0
                (acc + segWidth)
                visible
                (if visible > 0 then Just Candidate{to = Cursor i 0, width = visible, end = Wrapped, next = after} else cand)
            fitOrBreak
              | acc + segWidth <= maxWidth + epsilon =
                  scanSeg (i + 1) 0 (acc + segWidth) (acc + segWidth) cand
              | otherwise =
                  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)
              Space -> spaceLike
              PreservedSpace -> spaceLike
              Tab -> spaceLike
              ZeroWidthBreak -> spaceLike
              SoftHyphen
                | visible + segWidth <= maxWidth + epsilon || keepsOverflowing ->
                    scanSeg (i + 1) 0 acc visible $
                      Just
                        Candidate
                          { to = Cursor i 0
                          , width = visible + segWidth
                          , end = Hyphenated
                          , 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 || 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

    emergency seg i g acc visible =
      let
        ws = dropCodepoints g seg.graphemes
        counted = countFits acc ws
        count
          | counted == 0 && visible <= epsilon = 1
          | otherwise = counted
        taken = take count ws
        g' = g + sum (map (.codepoints) taken)
        takenWidth = sum (map (.width) taken)
      in
        if count == 0 then
          (emit (Cursor i g) acc Overflowed, resume (Cursor i g))
        else
          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
        fits n w = \case
          [] -> n
          g : rest
            | w + g.width <= maxWidth + epsilon -> fits (n + 1) (w + g.width) rest
            | otherwise -> n

data Candidate = Candidate
  { to :: Cursor
  , width :: Float
  , end :: LineEnd
  , next :: Cursor
  }

epsilon :: Float
epsilon = 1e-4

materializeSlices :: PreparedText -> LineRange -> [LineSlice]
materializeSlices prepared line = mergeSlices $ mapMaybe slice [line.from.segment .. line.to.segment] <> hyphen
  where
    segs = prepared.segments
    hyphen =
      [ LineSlice
          { text = "-"
          , style = seg.style
          , width = seg.width
          , atom = False
          }
      | line.ended == Hyphenated
      , let seg = segs Vector.! line.to.segment
      ]
    slice j
      | j >= Vector.length segs = Nothing
      | otherwise =
          let
            seg = segs Vector.! j
            startG = if j == line.from.segment then line.from.grapheme else 0
            endG = if j == line.to.segment then line.to.grapheme else Text.length seg.text
            piece = Text.take (endG - startG) (Text.drop startG seg.text)
            pieceWidth
              | startG == 0 && endG == Text.length seg.text =
                  seg.width
              | otherwise =
                  sum . map (.width)
                    $ takeCodepoints (endG - startG)
                    $ dropCodepoints startG seg.graphemes
          in
            case seg.kind of
              SoftHyphen -> Nothing
              HardBreak -> Nothing
              ZeroWidthBreak -> Nothing
              _
                | Text.null piece -> Nothing
                | otherwise ->
                    Just
                      LineSlice
                        { text = piece
                        , style = seg.style
                        , width = pieceWidth
                        , atom = seg.kind == Atomic
                        }

data LineSlice = LineSlice
  { text :: Text
  , style :: Int
  , width :: Float
  , atom :: Bool
  }
  deriving stock (Eq, Show)

mergeSlices :: [LineSlice] -> [LineSlice]
mergeSlices = \case
  [] -> []
  a : b : rest
    | not a.atom
    , not b.atom
    , a.style == b.style ->
        mergeSlices $
          LineSlice
            { text = a.text <> b.text
            , style = a.style
            , width = a.width + b.width
            , atom = False
            }
            : rest
  a : rest ->
    a : mergeSlices rest

materializeLineRange :: PreparedText -> LineRange -> Text
materializeLineRange prepared line = visible <> suffix
  where
    segs = prepared.segments
    suffix = if line.ended == Hyphenated then "-" else ""
    visible = Text.concat (mapMaybe piece [line.from.segment .. line.to.segment])
    piece j
      | j >= Vector.length segs = Nothing
      | otherwise =
          let
            seg = segs Vector.! j
            startG = if j == line.from.segment then line.from.grapheme else 0
            endG = if j == line.to.segment then line.to.grapheme else Text.length seg.text
          in
            case seg.kind of
              SoftHyphen -> Nothing
              HardBreak -> Nothing
              ZeroWidthBreak -> Nothing
              _ -> Just (Text.take (endG - startG) (Text.drop startG seg.text))

layoutStats :: [LineRange] -> LayoutStats
layoutStats = Foldable.foldl' step LayoutStats{lineCount = 0, maxLineWidth = 0}
  where
    step stats line =
      LayoutStats
        { lineCount = stats.lineCount + 1
        , maxLineWidth = max stats.maxLineWidth line.width
        }

data LayoutStats = LayoutStats
  { lineCount :: Int
  , maxLineWidth :: Float
  }
  deriving stock (Eq, Show)

lineStretch :: PreparedText -> LineRange -> LineStretch
lineStretch prepared line = LineStretch{spaces = length inside, width = sum inside}
  where
    segs = prepared.segments
    upper
      | line.to.grapheme == 0 = line.to.segment - 1
      | otherwise = line.to.segment
    inside =
      [ seg.width
      | seg <- dropWhile (\seg -> seg.kind == Space) (map (segs Vector.!) [line.from.segment .. min upper (Vector.length segs - 1)])
      , seg.kind == Space
      ]

data LineStretch = LineStretch
  { spaces :: Int
  , width :: Float
  }
  deriving stock (Eq, Show)

shrinkwrap :: PreparedText -> Float -> Float
shrinkwrap = shrinkwrapWith SplitWords

shrinkwrapWith :: Overflow -> PreparedText -> Float -> Float
shrinkwrapWith overflow prepared maxWidth = go (40 :: Int) 0 maxWidth
  where
    layout = layoutGreedyWith overflow prepared
    countAt w = (layoutStats (layout w)).lineCount
    target = countAt maxWidth
    go k lo hi
      | k <= 0 = (layoutStats (layout hi)).maxLineWidth
      | countAt mid <= target = go (k - 1) lo mid
      | otherwise = go (k - 1) mid hi
      where
        mid = (lo + hi) / 2

dropCodepoints :: Int -> [Grapheme] -> [Grapheme]
dropCodepoints n xs
  | n <= 0 = xs
  | otherwise = case xs of
      [] -> []
      Grapheme{codepoints} : rest -> dropCodepoints (n - codepoints) rest

takeCodepoints :: Int -> [Grapheme] -> [Grapheme]
takeCodepoints n xs
  | n <= 0 = []
  | otherwise = case xs of
      [] -> []
      g@Grapheme{codepoints} : rest -> g : takeCodepoints (n - codepoints) rest