packages feed

nano-ui-0.2.0.0: lib/NanoUI/Widgets/RichText.hs

-- | Paragraphs of mixed-style text and links.
module NanoUI.Widgets.RichText
  ( -- * Inline pieces
    Inline
  , inlineText
  , inlineWith
  , restyle
  , strong
  , emphasis
  , inlineCode
  , inlineBackground
  , inlineTooltip
  , hyperlink

    -- * Paragraphs
  , richText
  , richText'
  , richTextWith
  , richTextWith'
  , selectableRichText
  , selectableRichText'
  , selectableRichTextWith
  , selectableRichTextWith'
  ) where

import Control.Applicative ((<|>))
import Control.Monad (filterM, forM_, foldM, unless, when)
import Data.Hashable (hashWithSalt)
import Data.IORef (IORef, newIORef, readIORef, writeIORef)
import Data.IntMap.Strict qualified as IM
import Data.List (groupBy)
import Data.Map.Strict qualified as M
import Data.Maybe (fromMaybe, isJust, listToMaybe)
import Data.Primitive.PrimArray (indexPrimArray, sizeofPrimArray)
import Data.Primitive.SmallArray (SmallArray, indexSmallArray, sizeofSmallArray, smallArrayFromList)
import Data.Text (Text)
import Data.Text qualified as T
import NanoUI.Internal.Context
import NanoUI.Internal.Host qualified as Host
import NanoUI.Internal.RichText.Types
import NanoUI.Internal.Draw (DrawOp (..), TextFont (..))
import NanoUI.Internal.Font (FontMetrics (..), ShapedText (..), prepareFontMetrics, selectionSpans, textDecorationMetrics, textIndexAtX)
import NanoUI.Internal.Font qualified as Font
import NanoUI.Internal.Frame.Node (resolveTextFont)
import NanoUI.Internal.Id (WidgetId)
import NanoUI.Internal.Input (Input (..), MouseButton (MouseLeft), UiCursorKind (..), heldIn, inputMousePos, pressedIn, releasedIn)
import NanoUI.Internal.Layout.Arena (NodeType (NodeDrawing), lookupNodeByKey)
import NanoUI.Internal.Store (eqByPtr, ptrEq, fieldRichSelection, findSlot, insertSlot)
import NanoUI.Internal.Monad (NanoUI, askDefaultLayout, askInput, freshWidget, liftIO, requestFocus, uiTheme, withKey)
import NanoUI.Internal.Style hiding (Flow (..))
import NanoUI.Internal.TextCluster (clusterLength)
import NanoUI.Internal.Types (Color (..), Rect (..), V2 (..), rectContains)
import NanoUI.Internal.Widgets.Node (Response (..), addWidget, respClicked, respHovered, respRect)
import NanoUI.Internal.Widgets.Popup (tooltip)
import NanoUI.Internal.Widgets.Behavior (keyboardFocused)
import NanoUI.Internal.Widgets.TextInput (cursorAtOffset, cursorOffset, fieldTextCommands)
import NanoUI.Widgets.TextBuffer qualified as TB
import NanoUI.Widgets.TextEditor (Editor (..), EditorMode (..), editorSelection, emptyHistory, multiLineMode, runCommandIO)
import System.IO.Unsafe (unsafeDupablePerformIO)

-- | Text styled by font modifiers (@fontBold@, @fontSize 20@,
-- @fontColor red . fontUnderline@), applied over the paragraph's layout.
inlineWith :: (Layout -> Layout) -> Text -> Inline
inlineWith f txt = Inline txt (InlineCustom f) Nothing Nothing Nothing

-- | Add font modifiers to a piece, a hyperlink included.
restyle :: (Layout -> Layout) -> Inline -> Inline
restyle f (Inline txt style target bg tip) = Inline txt (InlineCustom (f . applyInlineStyle style)) target bg tip

-- | Bold text.
strong :: Text -> Inline
strong txt = Inline txt InlineBold Nothing Nothing Nothing

-- | Italic text.
emphasis :: Text -> Inline
emphasis txt = Inline txt InlineItalic Nothing Nothing Nothing

-- | Monospaced text.
inlineCode :: Text -> Inline
inlineCode txt = Inline txt InlineMono Nothing Nothing Nothing

-- | Paint a colour behind a piece, the full line-box height, e.g. a
-- highlight or an inline code tint. Leading and trailing spaces on each line
-- are left bare.
--
-- > richText ["Run ", inlineBackground codeTint (inlineCode "cabal build"), " first."]
inlineBackground :: Color -> Inline -> Inline
inlineBackground c (Inline txt style target _ tip) = Inline txt style target (Just c) tip

-- | Attach hover tooltip text to any 'Inline' piece (code run, text, or link).
inlineTooltip :: Text -> Inline -> Inline
inlineTooltip tip (Inline txt style target bg _) = Inline txt style target bg (Just tip)

-- | @hyperlink target label@: text styled with the theme's link colour and
-- underlined on hover. Clicking the link returns @Just target@ from 'richText'.
hyperlink :: Text -> Text -> Inline
hyperlink target label = Inline label InlinePlain (Just target) Nothing Nothing

applyInlineStyle :: InlineStyle -> Layout -> Layout
applyInlineStyle = \case
  InlinePlain -> id
  InlineBold -> fontBold
  InlineItalic -> fontItalic
  InlineMono -> fontMono
  InlineCustom f -> f

-- | A paragraph of pieces, wrapped at its width. Returns the target of the
-- hyperlink clicked this frame.
richText :: [Inline] -> NanoUI (Maybe Text)
richText = richTextWith id

-- | 'richText' with a layout modifier, whose font choices are the default
-- for every piece. Horizontal alignment applies per line: with 'alignEnd'
-- every line ends at the right edge.
richTextWith :: (Layout -> Layout) -> [Inline] -> NanoUI (Maybe Text)
richTextWith f = fmap snd . richTextWith' f

-- | 'richTextWith' with read-only mouse selection and the standard text
-- commands for selecting and copying text. Link clicks still return their
-- destination.
selectableRichTextWith :: (Layout -> Layout) -> [Inline] -> NanoUI (Maybe Text)
selectableRichTextWith f = fmap snd . selectableRichTextWith' f

-- | A selectable paragraph at its default layout.
selectableRichText :: [Inline] -> NanoUI (Maybe Text)
selectableRichText = selectableRichTextWith id

-- | 'selectableRichText' with its response, for focus and geometry.
selectableRichText' :: [Inline] -> NanoUI (Response, Maybe Text)
selectableRichText' = selectableRichTextWith' id

-- | 'selectableRichTextWith' with its response.
selectableRichTextWith' :: (Layout -> Layout) -> [Inline] -> NanoUI (Response, Maybe Text)
selectableRichTextWith' = richTextWithMode' True

-- | 'richText' returning the paragraph response and a link target clicked
-- this frame, or 'Nothing' when no link was activated.
richText' :: [Inline] -> NanoUI (Response, Maybe Text)
richText' = richTextWith' id

-- | 'richTextWith' returning the paragraph response and optional clicked link target.
richTextWith' :: (Layout -> Layout) -> [Inline] -> NanoUI (Response, Maybe Text)
richTextWith' = richTextWithMode' False

richTextWithMode' :: Bool -> (Layout -> Layout) -> [Inline] -> NanoUI (Response, Maybe Text)
richTextWithMode' selectable f pieces = do
  (wid, ctx) <- freshWidget
  inp <- askInput
  base <- f <$> askDefaultLayout
  theme <- uiTheme
  let !baseSize = ctxFontSize ctx
      !align = layoutAlignX base
  Paragraphs cacheRef <- liftIO $ Host.hostOrInit (ctxParagraphs ctx) (Paragraphs <$> newIORef (ParagraphCache 0 paragraphBound IM.empty))
  gen <- liftIO (readIORef (ctxMetricGen ctx))
  cached <- liftIO ((\(ParagraphCache _ _ m) -> IM.lookup (intKey wid) m) <$> readIORef cacheRef)
  sameInputs <- case cached of
    Nothing -> pure False
    Just para -> liftIO $ do
      Inputs pieces0 base0 theme0 gen0 selectable0 <- readIORef (paraInputs para)
      pure (ptrEq pieces pieces0 && gen == gen0 && eqByPtr base base0 && eqByPtr theme theme0 && selectable == selectable0)
  let !key = case cached of
        Just para | sameInputs -> paraKey para
        _ -> hashPieces baseSize base theme align gen selectable pieces
  para0 <- case cached of
    Just para | paraKey para == key ->
      liftIO (para <$ unless sameInputs (writeIORef (paraInputs para) (Inputs pieces base theme gen selectable)))
    _ -> liftIO $ do
      let styled =
            [ (piece, pieceFont baseSize l, pieceColor theme l target, layoutTextBreak l)
            | piece@(Inline _ style target _ _) <- pieces
            , let l = applyInlineStyle style base
            ]
          plainInput = T.concat [txt | Inline txt _ _ _ _ <- pieces]
          starts = scanl (+) 0 [T.length txt | Inline txt _ _ _ _ <- pieces]
      resolved <- mapM (measurePiece ctx) (zip3 [0 ..] starts styled)
      let runs = smallArrayFromList (map fst resolved)
          tokens = concatMap snd resolved
          emptyLine = case resolved of
            (run, _) : _ -> (runLineHeight run, runAscent run)
            [] -> (fmLineHeight (ctxFontMetrics ctx), fmAscent (ctxFontMetrics ctx))
          hasGlyphs = any (\(_, _, _, brk) -> brk == BreakAnywhere) styled
          tooltipRuns =
            [ (runIdx, tip)
            | runIdx <- [0 .. sizeofSmallArray runs - 1]
            , Just tip <- [runTooltip (indexSmallArray runs runIdx)]
            ]
          hasInteractive =
            not (null tooltipRuns)
              || any (\runIdx -> isJust (runTarget (indexSmallArray runs runIdx))) [0 .. sizeofSmallArray runs - 1]
      measured <- newIORef Unmeasured
      inputsRef <- newIORef (Inputs pieces base theme gen selectable)
      pure
        ( Paragraph
            key
            inputsRef
            runs
            tokens
            emptyLine
            (lineBoxes (layoutLines runs emptyLine AlignStart 1e9 tokens))
            (-1)
            []
            []
            tooltipRuns
            hasInteractive
            hasGlyphs
            measured
            (if selectable then plainInput else T.empty)
            (TB.fromText plainInput)
        )
  -- Forced, so selection sync compares this address rather than a selector thunk.
  let !plain = paraText para0
  when (selectable && not (T.null plain)) (liftIO (registerFocusable ctx wid))
  resp <- addWidget wid NodeDrawing T.empty 0 base
  let Rect rx ry rw _ = respRect resp
      runs = paraRuns para0
      layoutAt width = layoutLines runs (paraEmptyLine para0) align width (paraTokens para0)
      para
        | paraWidth para0 == rw = para0
        | otherwise =
            let ls = layoutAt rw
                inter = if paraHasInteractive para0 then interactivePieces runs ls else []
             in para0 {paraWidth = rw, paraLines = ls, paraInteractive = inter}
      linesAt width
        | width == paraWidth para = paraLines para
        | otherwise = layoutAt width
  focused <- if selectable then keyboardFocused wid else pure False
  (selection, dragReleased) <-
    if selectable
      then do
        (current, dragged) <- updateSelection ctx inp wid resp focused plain (paraBuffer para0) (paraLines para)
        -- Drawn only while focused, as a text field's selection goes when
        -- the field loses focus.
        pure (if focused then Just current else Nothing, dragged)
      else pure (Nothing, False)
  let mouse = inputMousePos inp
      interPieces = paraInteractive para
      hovered = respHovered resp && paraHasInteractive para
      hoveredRun = if hovered then linkRunAt runs rx ry interPieces mouse else Nothing
      draw = drawParagraph runs (paraHasGlyphs para) theme hoveredRun selection linesAt
      drawKey = key `hashWithSalt` fromMaybe (-1) hoveredRun `hashWithSalt` fmap (\s -> (selectionStart s, selectionEnd s)) selection
  liftIO $ do
    -- A move onto or off a link or tooltipped run inside the hovered paragraph
    -- changes no hot widget, so each interactive piece registers a hover zone.
    when hovered $
      forM_ interPieces $ \(InteractivePiece _ x y w h) ->
        registerHoverZone ctx False (Rect (rx + x) (ry + y) w h)
    unless (paraWidth para0 == rw && fmap paraKey cached == Just key) $
      cacheParagraph ctx cacheRef wid (isJust cached) para
    registerCustomMeasure ctx wid $ \_ (availW, _) ->
      if availW >= 1e9 then paraNatural para else measureAt (paraMeasured para) (lineBoxes . linesAt) availW
    registerCustomEntry ctx wid $
      CustomDrawingEntry
        (if drawKey == 0 then 1 else drawKey)
        draw
        (Just (\_ _ _ -> if isJust hoveredRun then UiCursorPointer else if selectable then UiCursorText else UiCursorDefault))
        0
        False
        (if selectable then KeysReadOnly else KeysNone)
  forM_ (paraTooltipRuns para) $ \(runIdx, tip) ->
    withKey ("rt-tip" :: Text, runIdx) $ do
      let runRects =
            [ Rect (rx + x) (ry + y) w h
            | InteractivePiece ri x y w h <- interPieces
            , ri == runIdx
            ]
          mTargetRect = listToMaybe [r | r <- runRects, rectContains r mouse] <|> listToMaybe runRects
      forM_ mTargetRect $ \pieceR ->
        tooltip (resp {rawRespRect = pieceR}) tip
  clicked <-
    if respClicked resp && not dragReleased && paraHasInteractive para
      then do
        -- The press must have gone down on the link too; its point stays
        -- recorded through the release frame.
        presses <- liftIO (readIORef (ctxPressPos ctx))
        pure $
          if maybe True ((== hoveredRun) . linkRunAt runs rx ry interPieces . ppPos) (M.lookup MouseLeft presses)
            then hoveredRun >>= runTarget . indexSmallArray runs
            else Nothing
      else pure Nothing
  pure (resp, clicked)
  where
    lineBoxes lines' = (maximum (0 : map lineWidth lines'), sum (map lineHeight lines'))

-- | Hash a paragraph's pieces directly against the base layout and theme
-- without allocating intermediate 'Layout' or 'TextFont' records on cache hits.
hashPieces :: Float -> Layout -> Theme -> AlignX -> Int -> Bool -> [Inline] -> Int
hashPieces !baseSize base theme align !gen !selectable = go h0
  where
    !h0 = gen `hashWithSalt` fromEnum align `hashWithSalt` selectable
    !baseResolvedSize = resolveFontSize baseSize (layoutFontSize base)
    !baseVariant = fromEnum (layoutFontVariant base)
    !baseWeight = fromEnum (layoutFontWeight base)
    !baseStyle = fromEnum (layoutFontStyle base)
    !baseDeco = fromEnum (layoutTextDecoration base)
    !baseTab = layoutFontTabular base
    !baseBrk = fromEnum (layoutTextBreak base)
    !baseToneCol = textToneColor theme (layoutFontTone base)
    !baseFontColor = layoutFontColor base
    !linkCol = themeLink theme
    go !h [] = h
    go !h (Inline txt style target bg tip : rest) =
      let !h' = case style of
            InlineCustom f ->
              let l = f base
                  TextFont size variant weight fstyle deco tabular = pieceFont baseSize l
                  Color rgba = pieceColor theme l target
               in hashOne h txt size (fromEnum variant) (fromEnum weight) (fromEnum fstyle) (fromEnum deco) tabular rgba target bg tip (fromEnum (layoutTextBreak l))
            _ ->
              let !variant = case style of InlineMono -> fromEnum FontMono; _ -> baseVariant
                  !weight = case style of InlineBold -> fromEnum WeightBold; _ -> baseWeight
                  !fstyle = case style of InlineItalic -> fromEnum FontStyleItalic; _ -> baseStyle
                  Color rgba = case baseFontColor of
                    Just c -> c
                    Nothing -> if isJust target then linkCol else baseToneCol
               in hashOne h txt baseResolvedSize variant weight fstyle baseDeco baseTab rgba target bg tip baseBrk
       in go h' rest
    {-# INLINE hashOne #-}
    hashOne !h txt !size !variant !weight !fstyle !deco !tabular !rgba target bg tip !brk =
      let !bgHash = case bg of
            Nothing -> h `hashWithSalt` (0 :: Int)
            Just (Color c) -> h `hashWithSalt` (1 :: Int) `hashWithSalt` c
       in bgHash `hashWithSalt` txt `hashWithSalt` size `hashWithSalt` variant
            `hashWithSalt` weight `hashWithSalt` fstyle `hashWithSalt` deco
            `hashWithSalt` tabular `hashWithSalt` rgba `hashWithSalt` target
            `hashWithSalt` tip `hashWithSalt` brk

interactivePieces :: SmallArray Run -> [Line] -> [InteractivePiece]
interactivePieces runs ls =
  [ InteractivePiece runIdx x1 (lineTop line) (x2 - x1) (lineHeight line)
  | line <- ls
  , (run, runIdx, x1, x2) <- pieceSpans runs line
  , isJust (runTarget run) || isJust (runTooltip run)
  ]

linkRunAt :: SmallArray Run -> Float -> Float -> [InteractivePiece] -> V2 -> Maybe Int
linkRunAt runs !rx !ry pieces (V2 px py) = go pieces
  where
    !lx = px - rx
    !ly = py - ry
    go [] = Nothing
    go (InteractivePiece runIdx x y w h : rest)
      | lx >= x && lx < x + w && ly >= y && ly < y + h && isJust (runTarget (indexSmallArray runs runIdx)) =
          Just runIdx
      | otherwise = go rest

-- | Words are drawn separately, so backgrounds and decorations are drawn once
-- per piece per line, spanning the inner spaces. Backgrounds go underneath.
drawParagraph ::
  SmallArray Run ->
  Bool ->
  Theme ->
  Maybe Int ->
  Maybe RichSelection ->
  (Float -> [Line]) ->
  CustomDrawContext ->
  Rect ->
  SmallArray DrawOp
drawParagraph runs hasGlyphs theme hoveredRun selection linesAt _cdc (Rect x0 y0 w _) =
  smallArrayFromList $
    concatMap lineOps (linesAt w)
  where
    selected = selection >>= selectionOffsets
    lineOps line =
      let spans = pieceSpans runs line
          highlights = maybe [] (\(lo, hi) -> selectionOps x0 y0 line lo hi (themeSelection theme)) selected
          glyphDraw =
            if hasGlyphs
              then [(x, runIdx, T.concat [tokenText tok | (_, tok) <- group]) | group@((x, Token _ runIdx _ _ _ _) : _) <- glyphGroups line]
              else []
       in [ FillRect (Rect (x0 + x1) (y0 + lineTop line) (x2 - x1) (lineHeight line)) bg
          | (run, _, x1, x2) <- spans
          , Just bg <- [runBackground run]
          ]
            ++ highlights
            ++ [ DrawTextStyled (x0 + x) (lineY line run) ((runFont run) {textFontDecoration = DecorationNone}) txt (runColor run)
               | (x, runIdx, txt) <-
                   [(x, runIdx, txt) | (x, Token txt runIdx Word _ _ _) <- lineTokens line]
                     ++ glyphDraw
               , let run = indexSmallArray runs runIdx
               ]
            ++ [ FillRect (Rect (x0 + x1) (lineY line run + offset) (x2 - x1) thick) (runColor run)
               | (run, runIdx, x1, x2) <- spans
               , let deco = decorationOf runIdx
                     (thick, under, strike) = textDecorationMetrics (runLineHeight run) (runAscent run)
               , deco /= DecorationNone
               , offset <- decorationOffsets deco under strike
               ]
    lineY line run = y0 + lineTop line + lineAscent line - runAscent run
    glyphGroups line =
      groupBy joinsGlyphs [(x, tok) | (x, tok) <- lineTokens line, tokenKind tok == Glyph || tokenKind tok == GlyphSpace]
    decorationOf runIdx =
      (if Just runIdx == hoveredRun then addUnderline else id)
        (textFontDecoration (runFont (indexSmallArray runs runIdx)))
    decorationOffsets deco under strike =
      case deco of
        DecorationUnderline -> [under]
        DecorationStrikethrough -> [strike]
        DecorationUnderlineStrike -> [under, strike]
        DecorationNone -> []

-- | Each piece's stretch of a line without the spaces at its ends: its run,
-- the run's index, and its left and right edges. Computed in a single scan
-- without intermediate grouping lists.
pieceSpans :: SmallArray Run -> Line -> [(Run, Int, Float, Float)]
pieceSpans runs line = go (lineTokens line)
  where
    isSpaceTok tok = tokenKind tok == Space || tokenKind tok == GlyphSpace
    go [] = []
    go ((x, tok) : rest) = scanRun (tokenRun tok) (if isSpaceTok tok then (-1) else x) (if isSpaceTok tok then 0 else x + tokenWidth tok) rest
    scanRun !ri !startX !endX toks = case toks of
      (x, tok) : rest | tokenRun tok == ri ->
        if isSpaceTok tok
          then scanRun ri startX endX rest
          else scanRun ri (if startX < 0 then x else startX) (x + tokenWidth tok) rest
      _ ->
        let tailSpans = go toks
         in if startX < 0 then tailSpans else (indexSmallArray runs ri, ri, startX, endX) : tailSpans

-- | Whether two placed tokens belong to the same piece.
joinsGlyphs :: (Float, Token) -> (Float, Token) -> Bool
joinsGlyphs (_, a) (_, b) = tokenRun a == tokenRun b

-- | Store @para@ under @wid@, pruning entries neither drawn last frame nor yet
-- this frame once the cache grows past its bound.
cacheParagraph :: Context -> IORef ParagraphCache -> WidgetId -> Bool -> Paragraph -> IO ()
cacheParagraph ctx cacheRef wid hadEntry para = do
  ParagraphCache n bound m <- readIORef cacheRef
  let n' = if hadEntry then n else n + 1
  writeIORef cacheRef
    =<< if n' <= bound
      then pure $! ParagraphCache n' bound (IM.insert (intKey wid) para m)
      else do
        prev <- getsDamage ctx (pfRects . dsPrev)
        -- A paragraph declared this pass has registered its custom drawing.
        let declared k = maybe (pure False) (fmap isJust . lookupCustomDrawingAt ctx) =<< lookupNodeByKey (ctxNodeArena ctx) k
        live <- filterM (\(k, _) -> if IM.member k prev then pure True else declared k) (IM.toAscList m)
        let kept = IM.insert (intKey wid) para (IM.fromDistinctAscList live)
            size = IM.size kept
        pure $! ParagraphCache size (max paragraphBound (2 * size)) kept

-- | Keep the paragraph's selection in document coordinates, so it survives
-- rewrapping when the widget's width changes.
updateSelection :: Context -> Input -> WidgetId -> Response -> Bool -> Text -> TB.TextBuffer -> [Line] -> NanoUI (RichSelection, Bool)
updateSelection ctx inp wid resp focused plain buffer lines' = do
  let key = intKey wid
      initial = RichSelection plain (TB.Cursor 0 0) (TB.Cursor 0 0) False False 0 0
  !stored <- liftIO (findSlot fieldRichSelection initial key <$> getStore ctx)
  let synced = syncSelection plain stored
  commands <- if focused then liftIO (fieldTextCommands ctx readOnlyMode inp) else pure []
  afterKeys <-
    if null commands
      then pure synced
      else do
        editor <- liftIO (foldM (flip (runCommandIO ctx readOnlyMode)) (selectionEditor buffer synced) commands)
        let (a, c) = editorSelection editor
        pure (selectionIn plain a c (selectionDragging synced) (selectionMoved synced))
  let mouse = inputMousePos inp
      press = pressedIn MouseLeft inp && respHovered resp
      held = heldIn MouseLeft inp
      released = releasedIn MouseLeft inp
      (next, dragReleased)
        | press =
            let pos = pointAt plain lines' (respRect resp) mouse
             in (selectionAt plain pos pos held False, False)
        | selectionDragging afterKeys && (held || released) =
            let pos = pointAt plain lines' (respRect resp) mouse
                dragAnchor = (selectionAnchor afterKeys, anchorOffset afterKeys)
                didMove = selectionMoved afterKeys || fst pos /= fst dragAnchor
             in (selectionAt plain dragAnchor pos held (didMove && held), released && didMove)
        -- A drag that ended elsewhere stops; an idle pass keeps the stored
        -- selection object, so it writes nothing.
        | selectionDragging afterKeys = (afterKeys {selectionDragging = False, selectionMoved = False}, False)
        | otherwise = (afterKeys, False)
  when press (requestFocus wid)
  unless (ptrEq stored next) $
    liftIO (modifyStore ctx (insertSlot fieldRichSelection key next))
  pure (next, dragReleased)

readOnlyMode :: EditorMode
readOnlyMode = multiLineMode {modeEditable = False}

-- | The stored selection over the paragraph's current text. Changed text
-- keeps the selection's offsets, clamped to its length, without building a
-- text buffer.
syncSelection :: Text -> RichSelection -> RichSelection
syncSelection plain previous
  | ptrEq (selectionText previous) plain = previous
  -- A rebuilt paragraph has equal text at a new address: adopt it once, so
  -- later passes compare by pointer rather than by content.
  | selectionText previous == plain = previous {selectionText = plain}
  | otherwise =
      let clamped o = let o' = min (T.length plain) o in (cursorAtOffset plain o', o')
          cursorOff = if selectionCursor previous < selectionAnchor previous then selectionStart previous else selectionEnd previous
       in selectionAt plain (clamped (anchorOffset previous)) (clamped cursorOff) False False

selectionEditor :: TB.TextBuffer -> RichSelection -> Editor
selectionEditor buffer selection =
  Editor (TB.withCursor (selectionCursor selection) buffer) (selectionAnchor selection) emptyHistory

-- | A selection between two positions whose document offsets are known, so
-- drawing reads them rather than walking the text each pass.
selectionAt :: Text -> (TB.Cursor, Int) -> (TB.Cursor, Int) -> Bool -> Bool -> RichSelection
selectionAt txt (anchor, a) (cursor, c) dragging moved =
  RichSelection txt anchor cursor dragging moved (min a c) (max a c)

-- | 'selectionAt' for positions a text command left, which carry no offset.
selectionIn :: Text -> TB.Cursor -> TB.Cursor -> Bool -> Bool -> RichSelection
selectionIn txt anchor cursor = selectionAt txt (anchor, cursorOffset txt anchor) (cursor, cursorOffset txt cursor)

-- | The anchor's document offset: whichever end of the range it is.
anchorOffset :: RichSelection -> Int
anchorOffset s = if selectionAnchor s <= selectionCursor s then selectionStart s else selectionEnd s

selectionOffsets :: RichSelection -> Maybe (Int, Int)
selectionOffsets s
  | selectionStart s == selectionEnd s = Nothing
  | otherwise = Just (selectionStart s, selectionEnd s)

-- | Highlight the selected range of each token using its per-run 'FontMetrics'.
selectionOps :: Float -> Float -> Line -> Int -> Int -> Color -> [DrawOp]
selectionOps x0 y0 line lo hi color = concatMap drawToken (lineTokens line)
  where
    drawToken (x, tok) =
      let Token txt _ kind w start fm = tok
          end = start + T.length txt
          a = max lo start
          b = min hi end
       in if b <= a
            then []
            else
              [ FillRect
                  (Rect (x0 + x + sx) (y0 + lineTop line) (ex - sx) (lineHeight line))
                  color
              | (sx, ex) <-
                  -- A token that may break anywhere is one cluster, as wide
                  -- as the shaped line draws it.
                  if kind == Glyph || kind == GlyphSpace then [(0, w)] else selectionSpans fm txt (a - start) (b - start)
              ]

-- | The position under a point, and its document offset.
pointAt :: Text -> [Line] -> Rect -> V2 -> (TB.Cursor, Int)
pointAt plain lines' (Rect rx ry _ _) (V2 px py) =
  let line = lineAtY (py - ry) lines'
      offset = max 0 (min (T.length plain) (tokenIndexAtX line (px - rx)))
   in (cursorAtOffset plain offset, offset)

lineAtY :: Float -> [Line] -> Line
lineAtY y = go
  where
    go [] = Line 0 0 0 0 0 []
    go (line : rest)
      | null rest || y < lineTop line + lineHeight line = line
      | otherwise = go rest

tokenIndexAtX :: Line -> Float -> Int
tokenIndexAtX line x = go (lineTokens line)
  where
    go [] = lineStart line
    go ((tokenX, tok) : rest)
      | x <= tokenX = tokenStart tok
      | null rest && x >= tokenX + tokenWidth tok = tokenStart tok + T.length (tokenText tok)
      | x <= tokenX + tokenWidth tok = indexWithin tokenX tok
      | otherwise = go rest
    indexWithin tokenX tok =
      let txt = tokenText tok
          kind = tokenKind tok
       in tokenStart tok
            + if kind == Glyph || kind == GlyphSpace
              then (if x - tokenX < tokenWidth tok / 2 then 0 else T.length txt)
              else textIndexAtX (tokenMetrics tok) txt (x - tokenX)

-- | @measureAt ref extentAt width@ is @extentAt width@, reused from @ref@
-- when it holds the extent at that width, and otherwise computed and left
-- there. A paragraph keeps its reference while its pieces stay the same, so
-- the solver's check of last frame's layout, which measures the paragraph
-- again at the width it offered then, costs nothing even when that width is a
-- cap the paragraph stays under, and its second measure at a new width reuses
-- the first. Only the extent is kept, never the lines. Reading and writing
-- the reference from pure code is safe because @extentAt@ is a pure function
-- of the width for those pieces: the reference only decides what is shared.
measureAt :: IORef Measured -> (Float -> (Float, Float)) -> Float -> (Float, Float)
measureAt ref extentAt width = unsafeDupablePerformIO $ do
  kept <- readIORef ref
  case kept of
    Measured w ew eh | w == width -> pure (ew, eh)
    _ -> case extentAt width of
      (!ew, !eh) -> (ew, eh) <$ writeIORef ref (Measured width ew eh)
{-# NOINLINE measureAt #-}

-- | Cache size at which stale paragraphs are first pruned.
paragraphBound :: Int
paragraphBound = 4096

-- | Extract 'TextFont' from a 'Layout', resolving relative 'fontSizeScale'
-- factors against @baseSize@. Colour-only variants resolve to the regular face
-- in 'resolveTextFont'.
pieceFont :: Float -> Layout -> TextFont
pieceFont baseSize l =
  TextFont
    (resolveFontSize baseSize (layoutFontSize l))
    (layoutFontVariant l)
    (layoutFontWeight l)
    (layoutFontStyle l)
    (layoutTextDecoration l)
    (layoutFontTabular l)

-- | A piece's colour: its own, else the link colour for a link, else its
-- colour for its tone and face, as for a label.
pieceColor :: Theme -> Layout -> Maybe Text -> Color
pieceColor theme l target =
  let toneCol = textToneColor theme (layoutFontTone l)
   in fromMaybe (maybe toneCol (const (themeLink theme)) target) (layoutFontColor l)

-- | A piece's line metrics and its tokens measured in its font. A piece that
-- may break anywhere is measured a character cluster at a time.
measurePiece :: Context -> (Int, Int, (Inline, TextFont, Color, TextBreak)) -> IO (Run, [Token])
measurePiece ctx (i, start, (Inline txt _ target bg tip, font, color, brk)) = do
  (fm, _) <- resolveTextFont ctx font
  let anywhere = brk == BreakAnywhere
      parts
        | anywhere = clusters txt
        | otherwise = T.groupBy (\a b -> kindOf False a == kindOf False b && kindOf False a /= Break) txt
  wholeMetrics <- if anywhere then prepareFontMetrics fm txt else pure fm
  -- A cluster is as wide as its share of the shaped piece, as the line
  -- holding it is drawn: alone it would miss the kerning, the fallback font
  -- and a mark drawn over the letter before it.
  let carets = if anywhere then stCarets <$> fmShape wholeMetrics txt else Nothing
  tokens <- reverse . snd <$> foldM (measure fm anywhere wholeMetrics carets) (start, []) parts
  pure (Run font color (fmLineHeight fm) (fmAscent fm) target bg tip, tokens)
  where
    kindOf anywhere c
      | c == '\n' = Break
      | anywhere && (c == ' ' || c == '\t') = GlyphSpace
      | anywhere = Glyph
      | c == ' ' || c == '\t' = Space
      | otherwise = Word
    measure fm anywhere wholeMetrics carets (at, acc) part = do
      let kind = kindOf anywhere (T.head part)
      prepared <- if anywhere then pure wholeMetrics else prepareFontMetrics fm part
      let w = case carets of
            _ | kind == Break -> 0
            Just cs
              | let i0 = at - start
                    i1 = i0 + T.length part
                    lenCs = sizeofPrimArray cs
              , i0 >= 0 && i1 < lenCs ->
                  abs (indexPrimArray cs i1 - indexPrimArray cs i0)
            _ -> Font.lineWidth prepared part
          token = Token part i kind w at prepared
      pure (at + T.length part, token : acc)

-- | Text split into user-perceived characters ('clusterLength'), closely
-- enough for wrapping.
clusters :: Text -> [Text]
clusters t = case clusterLength t of
  0 -> []
  n -> T.take n t : clusters (T.drop n t)

-- | Greedy line breaking at @width@, aligned by @align@. Breaks only at
-- spaces or newlines, drops spaces at a wrap, and gives an overlong word its
-- own line.
layoutLines :: SmallArray Run -> (Float, Float) -> AlignX -> Float -> [Token] -> [Line]
layoutLines runs (emptyH, emptyAscent) align width = go 0 0 [] 0 []
  where
    -- @placed@ holds the line's tokens in reverse, @pending@ the spaces since
    -- its last word. A wrapped line starts at its first word, so it has none.
    go top start placed x pending toks = case toks of
      [] -> [finish start top placed x]
      tok : rest -> case tokenKind tok of
        Break ->
          let line = finish start top placed x
              nextStart = tokenStart tok + T.length (tokenText tok)
           in line : go (top + lineHeight line) nextStart [] 0 [] rest
        Space -> go top start placed x (tok : pending) rest
        Glyph -> placeGroup top start placed x pending [tok] rest
        GlyphSpace -> placeGroup top start placed x pending [tok] rest
        Word ->
          let (word, rest') = span (\t -> tokenKind t == Word) toks
           in placeGroup top start placed x pending word rest'
    placeGroup top start placed x pending group rest
      | not (null placed) && x + spaceW + groupW > width =
          let line = finish start top placed x
           in line : go (top + lineHeight line) firstStart [] 0 [] (group ++ rest)
      | otherwise =
          let (placed', x') = foldl' place (placed, x) (reverse pending)
              (placed'', x'') = foldl' place (placed', x') group
           in go top start placed'' x'' [] rest
      where
        groupW = sum (map tokenWidth group)
        spaceW = sum (map tokenWidth pending)
        firstStart = maybe start tokenStart (listToMaybe group)
    place (acc, x) tok = ((x, tok) : acc, x + tokenWidth tok)
    finish start top placed x =
      -- An overlong word's line starts at the left edge, as with
      -- 'AlignStart', rather than before it.
      let shift = max 0 (width - x) * alignXFraction align
          toks = reverse (if shift == 0 then placed else [(tx + shift, tok) | (tx, tok) <- placed])
          metrics = [indexSmallArray runs (tokenRun tok) | (_, tok) <- toks]
          (h, ascent) = case metrics of
            [] -> (emptyH, emptyAscent)
            _ ->
              let ascent' = maximum (map runAscent metrics)
                  descent = maximum [runLineHeight r - runAscent r | r <- metrics]
               in (ascent' + descent, ascent')
       in Line start top h ascent x toks