packages feed

nano-ui-0.2.0.0: lib/NanoUI/Internal/Damage.hs

{-# LANGUAGE DerivingVia #-}

-- | Compare completed frames and explicit invalidations to choose repaint bounds.
-- Damage is computed before painting so retained backends can redraw only a clip.
module NanoUI.Internal.Damage
  ( updatePrevRects
  , pruneUnmountedCaches
  , floatingPanelRects
  , FrameSnapshot (..)
  , captureFrameSnapshot
  , writeDamage
  , damagePieces
  , pixelEdges
  , clipPixelEdges
  , snapDamage
  ) where

import Control.Applicative ((<|>))
import Control.Exception (evaluate)
import Control.Monad (filterM, foldM, forM_, unless, when)
import Control.Monad.IO.Class (MonadIO (..))
import Control.Monad.Trans.Reader (ReaderT (..))
import Data.Bits (xor)
import Data.IORef (IORef, modifyIORef', newIORef, readIORef, writeIORef)
import Data.IntMap.Strict qualified as IM
import Data.IntSet qualified as IS
import Data.List (partition, tails)
import Data.Maybe (catMaybes, fromMaybe, isJust, isNothing)
import Data.Hashable (hashWithSalt)
import Data.Primitive.Array (readArray, sizeofMutableArray, writeArray)
import Data.Primitive.PrimArray (MutablePrimArray, readPrimArray, writePrimArray)
import Data.Primitive.PrimVar (readPrimVar, writePrimVar)
import Data.Word (Word64)
import GHC.Exts (RealWorld)
import NanoUI.Internal.Context
import NanoUI.Internal.Context.Types (ScrollState (..), newPrevWalk)
import NanoUI.Internal.Id (WidgetId (..), hashWidgetId)
import NanoUI.Internal.Input
import NanoUI.Internal.Store (diffKeys, eqByPtr, ptrEq, slotChangedKeys)
import NanoUI.Internal.Layout.Arena
import NanoUI.Internal.Frame.Chrome (menuPanelBounds)
import NanoUI.Internal.Layout.ScrollGeometry (decodeScrollConfig, scrollBare)
import NanoUI.Internal.Shader (ShaderEffectEntry (..))
import NanoUI.Internal.Style (PointerMode (..))
import NanoUI.Internal.WidgetText (containerFlagClip, hasFlag)
import NanoUI.Internal.Widgets.Custom (mkCustomDrawContext)
import NanoUI.Internal.Types

layoutSettleMinArea :: Float
layoutSettleMinArea = 0.25

-- Partial retain clears with the page colour. Expand interaction clips to the
-- painted panel/page backdrop so slop pixels get the correct fill, not the
-- page colour.
backdropRectFromNode :: Context -> Int -> IO (Maybe Rect)
backdropRectFromNode Context {ctxNodeArena = na} idx = walkAncestors na idx $ \i -> do
  nt <- getNodeType na i
  paints <- if isFloatingNode nt then pure True else containerPaints na i nt
  if paints then getNonzeroRect na i else pure Nothing

-- | Whether a container paints its own backdrop: a panel, or a scroll
-- container with a well (one that is not bare and does not grow on both axes).
{-# INLINE containerPaints #-}
containerPaints :: NodeArena -> NodeIdx -> NodeType -> IO Bool
containerPaints na i nt = case nt of
  NodeScrollContainer -> do
    wTag <- axTag <$> getWidthSizing na i
    hTag <- axTag <$> getHeightSizing na i
    si <- getStyleIdx na i
    pure (not ((wTag == SizingGrow && hTag == SizingGrow) || scrollBare (decodeScrollConfig si)))
  _ -> pure (nt == NodePanel)

-- | Damage key for a painting container with no widget id: its nearest keyed
-- ancestor's key mixed with its arena offset from that ancestor. It is stable
-- while nothing before it in that ancestor is added or removed. Otherwise it
-- changes and is treated as a removed and added container. An
-- ancestor whose key a later node reuses ('getIdSuperseded') is passed over,
-- or a container in each would take the same key.
containerKey :: NodeArena -> NodeIdx -> IO Int
containerKey na idx = go idx
  where
    go i = do
      p <- getParent na i
      if p < 0
        then pure (mix 0 idx)
        else do
          w <- getWidgetId na p
          keyed <- if hashWidgetId w == 0 then pure False else not <$> getIdSuperseded na p
          if keyed then pure (mix (intKey w) (idx - p)) else go p
    -- Key 0 means no widget.
    mix k off = let h = hashWithSalt k off `xor` 0x3C6EF372FE94F82A in if h == 0 then 1 else h

-- | The clip node @idx@ is painted in: its parent's content clip
-- ('NanoUI.Internal.Frame.Scroll.applyScrollOffsets'). For a scroll container
-- or panel this is wider than the node's own clip, which is the clip it gives
-- its content (its viewport or inside).
outerClip :: NodeArena -> Rect -> NodeIdx -> IO Rect
outerClip na window idx = do
  p <- getParent na idx
  if p < 0
    then pure window
    else do
      clip <- fromMaybe window <$> getClipBounds na p
      pt <- getNodeType na p
      -- A widget or clipContainer also clips its content to its own rect.
      clipSelf <-
        if isWidgetNode pt
          then pure True
          else if pt == NodeContainer then hasFlag containerFlagClip <$> getStyleIdx na p else pure False
      if clipSelf
        then do
          r <- getNodeRect na p
          pure (fromMaybe (Rect (rectX r) (rectY r) 0 0) (rectIntersect clip r))
        else pure clip

{-# INLINE getNonzeroRect #-}
getNonzeroRect :: NodeArena -> Int -> IO (Maybe Rect)
getNonzeroRect arena i = do
  r <- getNodeRect arena i
  pure (if rectNonEmpty r then Just r else Nothing)

-- | First pass of 'updatePrevRects', over scroll containers and panels
-- ('BackdropNodes'): record the clip each is painted in, and for a painting
-- container with no widget id (such as a panel) record its rect and paint
-- hash under 'containerKey', so moving, resizing or restyling it repaints
-- where it was.
{-# INLINE scanBackdropPrevRects #-}
scanBackdropPrevRects ::
  NodeArena ->
  Rect ->
  IM.IntMap Rect ->
  IM.IntMap Rect ->
  IM.IntMap Word64 ->
  IO (IM.IntMap Rect, IM.IntMap Rect, IM.IntMap Word64, Int, Int, Bool)
scanBackdropPrevRects na window oldRects oldOuters oldHashes = do
  (containerCount, containerAt) <- classNodes na BackdropNodes
  let containers !j !m !om !hm !foundOld !foundOuter !dropped
        | j >= containerCount = pure (m, om, hm, foundOld, foundOuter, dropped)
        | otherwise = do
            idx <- containerAt j
            wid <- getWidgetId na idx
            let keyless = hashWidgetId wid == 0
            skip <- if keyless then not <$> (containerPaints na idx =<< getNodeType na idx) else getIdSuperseded na idx
            if skip
              then containers (j + 1) m om hm foundOld foundOuter dropped
              else do
                k <- if keyless then containerKey na idx else pure (intKey wid)
                let isOld = keyless && IM.member k oldRects
                mRect <- getNonzeroRect na idx
                (m', om', hm', fOld', fOuter', drop') <- case mRect of
                  Nothing ->
                    pure
                      ( if isOld then IM.delete k m else m
                      , dropKey k om
                      , if keyless then dropKey k hm else hm
                      , foundOld
                      , foundOuter
                      , dropped || isOld
                      )
                  Just r -> do
                    o <- outerClip na window idx
                    h <- if keyless then getNodePaintHash na idx else pure 0
                    pure
                      ( if keyless then putNew k r m else m
                      , putNew k o om
                      , if keyless then putNew k h hm else hm
                      , foundOld + if isOld then 1 else 0
                      , foundOuter + if IM.member k oldOuters then 1 else 0
                      , dropped
                      )
                containers (j + 1) m' om' hm' fOld' fOuter' drop'
  containers 0 oldRects oldOuters oldHashes 0 0 False

-- | Record this frame's solved rects, clips and paint hashes by widget key
-- ('dsPrev') for the next frame's damage to diff against. Returns the rects
-- of the widgets this frame mounted, by key: the map 'dsPrev' now holds, or
-- an empty map for an empty arena. 'pruneUnmountedCaches' takes it.
updatePrevRects :: Context -> Size -> IO (IM.IntMap Rect)
updatePrevRects ctx@Context {ctxNodeArena = na} size@(Size winW winH) = do
  PrevFrame oldRects oldClips oldOuters oldHashes oldEffects <- getsDamage ctx dsPrev
  count <- arenaCount na
  let setPrev p = modifyDamage ctx (\ds -> ds {dsPrev = p})
  if count <= 0
    then IM.empty <$ (setPrev emptyPrevFrame >> prevWalkFor ctx 0 IM.empty)
    else do
      (m0, om, hm0, foundContainers, foundOuter, droppedContainer) <-
        scanBackdropPrevRects na (Rect 0 0 winW winH) oldRects oldOuters oldHashes
      (walk, known) <- prevWalkFor ctx count oldRects
      a <- arenaArrays na
      let !geom = naArrGeom a
          !hashes = naArrPaintHash a
          go !i !m !cm !hm !foundOld !dropped
            | i >= count =
                if dropped || foundOld /= IM.size oldRects || foundOuter /= IM.size oldOuters
                  then setPrev emptyPrevFrame >> updatePrevRects ctx size
                  else do
                    effRects <- collectEffectRects ctx oldEffects
                    writeIORef (pwFor walk) m
                    writePrimVar (pwValid walk) count
                    unless
                      ( ptrEq m oldRects
                          && ptrEq cm oldClips
                          && ptrEq om oldOuters
                          && ptrEq hm oldHashes
                          && ptrEq effRects oldEffects
                      )
                      (setPrev (PrevFrame m cm om hm effRects))
                    pure m
            | otherwise = do
                !k <- readTree a i TreeWidgetId
                superseded <- if k == 0 then pure True else readTagEnum a i TagIdSuperseded
                if superseded
                  then forgetAt walk i >> go (i + 1) m cm hm foundOld dropped
                  else do
                    let !gOff = i * geomStride
                    !rx <- readPrimArray geom gOff
                    !ry <- readPrimArray geom (gOff + 1)
                    !rw <- readPrimArray geom (gOff + 2)
                    !rh <- readPrimArray geom (gOff + 3)
                    if not (rw > 0 && rh > 0)
                      then do
                        forgetAt walk i
                        let !isOld = IM.member k oldRects
                        go (i + 1) (if isOld then IM.delete k m else m) (dropKey k cm) (dropKey k hm) foundOld (dropped || isOld)
                      else do
                        !cx <- readPrimArray geom (gOff + 4)
                        !cy <- readPrimArray geom (gOff + 5)
                        !cwRaw <- readPrimArray geom (gOff + 6)
                        !chRaw <- readPrimArray geom (gOff + 7)
                        let !posClip = cwRaw > 0 && chRaw > 0
                            !hasClip = posClip || cwRaw < 0
                            !cw = if posClip then cwRaw else 0
                            !ch = if posClip then chRaw else 0
                        same <- keepKeyAt walk known i k (if hasClip then 1 else 0)
                        -- An unchanged rect keeps the object already
                        -- stored, so a still frame allocates nothing; a new
                        -- one is boxed only when coordinates changed.
                        was@(Rect wx wy ww wh) <- readArray (pwRects walk) i
                        let !rectMoved = rx /= wx || ry /= wy || rw /= ww || rh /= wh
                        now <-
                          if not rectMoved
                            then pure was
                            else do
                              let !r = Rect rx ry rw rh
                              writeArray (pwRects walk) i r
                              pure r
                        clipMoved <- if hasClip then swapClip (pwClips walk) i cx cy cw ch else pure False
                        !h <- readPrimArray hashes i
                        !h0 <- readPrimArray (pwHashes walk) i
                        unless (h == h0) (writePrimArray (pwHashes walk) i h)
                        let !m'
                              | not same = putNew k now m
                              | rectMoved = IM.insert k now m
                              | otherwise = m
                            !cm'
                              | not same = if hasClip then putNew k (Rect cx cy cw ch) cm else dropKey k cm
                              | clipMoved = IM.insert k (Rect cx cy cw ch) cm
                              | otherwise = cm
                            !fOld'
                              | not same = foundOld + if IM.member k oldRects then 1 else 0
                              | otherwise = foundOld + 1
                            !hm'
                              | not same || h /= h0 = putHash k h hm
                              | otherwise = hm
                        go (i + 1) m' cm' hm' fOld' dropped
      go 0 m0 oldClips hm0 foundContainers droppedContainer

-- | Drop the scroll views ('ssViews') and rich-text selections
-- ('storeRichSelection') of widgets not in @live@, the map
-- 'updatePrevRects' returned. Those maps keep an entry for every widget
-- ever shown. The limit scales with @live@, so a view with more than 256
-- mounted widgets does not intersect the maps every frame. An empty arena
-- prunes nothing.
pruneUnmountedCaches :: Context -> IM.IntMap Rect -> IO ()
pruneUnmountedCaches ctx live = do
  count <- arenaCount (ctxNodeArena ctx)
  when (count > 0) $ do
    let !pruneLimit = max 256 (2 * IM.size live)
    ss <- readIORef (ctxScrollState ctx)
    when (IM.size (ssViews ss) > pruneLimit) $
      writeIORef (ctxScrollState ctx) $! ss {ssViews = IM.intersection (ssViews ss) live}
    st <- readIORef (ctxStore ctx)
    when (IM.size (storeRichSelection st) > pruneLimit) $
      writeIORef (ctxStore ctx) $! st {storeRichSelection = IM.intersection (storeRichSelection st) live}

-- | The last walk's record, with room for @count@ nodes, and how many of its
-- indices describe @oldRects@. It reads as empty until this walk completes,
-- so a walk that restarts or throws leaves nothing stale behind. Clears
-- entries past @count@.
{-# INLINE prevWalkFor #-}
prevWalkFor :: Context -> Int -> IM.IntMap Rect -> IO (PrevWalk, Int)
prevWalkFor ctx count oldRects = do
  lastWalk <- readIORef (ctxPrevWalk ctx)
  valid <- readPrimVar (pwValid lastWalk)
  for <- readIORef (pwFor lastWalk)
  if sizeofMutableArray (pwRects lastWalk) >= count
    then do
      writePrimVar (pwValid lastWalk) 0
      forgetFrom lastWalk count valid
      pure (lastWalk, if ptrEq for oldRects then valid else 0)
    else do
      walk <- newPrevWalk (max 64 (2 * count))
      writeIORef (ctxPrevWalk ctx) walk
      pure (walk, 0)

-- | 'forgetAt' each node from @i@ up to @n@.
forgetFrom :: PrevWalk -> Int -> Int -> IO ()
forgetFrom walk !i !n = when (i < n) (forgetAt walk i >> forgetFrom walk (i + 1) n)

-- | Record that the walk made no entries for node @i@.
{-# INLINE forgetAt #-}
forgetAt :: PrevWalk -> Int -> IO ()
forgetAt walk i = do
  k0 <- readPrimArray (pwKeys walk) i
  unless (k0 == 0) $ do
    writePrimArray (pwKeys walk) i 0
    writePrimArray (pwTags walk) i 0

-- | Record key @k@, and @tag@ (1 when the node has a clip), for node @i@,
-- returning whether the last walk recorded the same there (below @known@).
{-# INLINE keepKeyAt #-}
keepKeyAt :: PrevWalk -> Int -> Int -> Int -> Int -> IO Bool
keepKeyAt walk known i k tag = do
  k0 <- readPrimArray (pwKeys walk) i
  t0 <- readPrimArray (pwTags walk) i
  if k0 == k && t0 == tag
    then pure $! i < known
    else do
      writePrimArray (pwKeys walk) i k
      writePrimArray (pwTags walk) i tag
      pure False

-- | Write node @i@'s clip if it changed, and return whether it changed.
{-# INLINE swapClip #-}
swapClip :: MutablePrimArray RealWorld Float -> Int -> Float -> Float -> Float -> Float -> IO Bool
swapClip clips i x y w h = do
  let !o = 4 * i
  same <- eqRectAt clips o x y w h
  if same then pure False else True <$ writeRectAt clips o x y w h

-- | Insert, returning @m@ itself when @k@ already maps to @v@, so pointer
-- equality survives an unchanged frame.
{-# INLINE putNew #-}
putNew :: Eq a => Int -> a -> IM.IntMap a -> IM.IntMap a
putNew k v m = if IM.lookup k m == Just v then m else IM.insert k v m

-- | 'putNew' for a paint hash. Not inlined: inlined, the walk boxed every
-- node's hash whether or not it was stored.
{-# NOINLINE putHash #-}
putHash :: Int -> Word64 -> IM.IntMap Word64 -> IM.IntMap Word64
putHash = putNew

-- | Delete, returning @m@ itself when @k@ is absent.
{-# INLINE dropKey #-}
dropKey :: Int -> IM.IntMap a -> IM.IntMap a
dropKey k m = if IM.member k m then IM.delete k m else m

-- | Keyed floating panels in paint order, bottom first (every window, then
-- every modal, then every popup): key, solved rect, and whether the panel
-- intercepts pointer events (excluding 'PointerPass' panels such as tooltips).
floatingPanels :: Context -> IO [(Int, Rect, Bool)]
floatingPanels Context {ctxNodeArena = na} = do
  n <- floatingNodeCount na
  if n == 0
    then pure []
    else catMaybes <$> (mapM step =<< floatingNodesInPaintOrder na)
  where
    step idx = do
      wid <- getWidgetId na idx
      if hashWidgetId wid == 0
        then pure Nothing
        else do
          r <- getNodeRect na idx
          mode <- getPointerMode na idx
          pure (Just (intKey wid, r, mode /= PointerPass))

-- | Current floating-panel bounds keyed by widget id, in logical window coordinates.
floatingPanelRects :: Context -> IO (IM.IntMap Rect)
floatingPanelRects ctx = IM.fromList . map (\(k, r, _) -> (k, r)) <$> floatingPanels ctx

-- | State 'NanoUI.Internal.Frame' captures before the UI pass; 'writeDamage' compares
-- it against the finished frame.
data FrameSnapshot = FrameSnapshot
  { fsSize :: !Size
  , fsStore :: !WidgetStore
  , fsHot :: !WidgetId
  , fsActive :: !WidgetId
  , fsFocus :: !WidgetId
  , fsFocusVisible :: !Bool
  , fsFloatingRects :: !(IM.IntMap Rect)
  , fsPrev :: !PrevFrame
  , fsAnimKeys :: !IS.IntSet
  }

-- | Read the 'FrameSnapshot' before the UI pass.
captureFrameSnapshot :: Context -> IO FrameSnapshot
captureFrameSnapshot ctx = do
  ds <- readIORef (ctxDamageState ctx)
  evaluate
    =<< FrameSnapshot (dsLastWindowSize ds)
      <$> getStore ctx
      <*> readIORef (ctxLastHotId ctx)
      <*> readIORef (ctxActiveId ctx)
      <*> readIORef (ctxFocusId ctx)
      <*> readIORef (ctxFocusVisible ctx)
      <*> getsOverlay ctx osPrevFloatingRects
      <*> pure (dsPrev ds)
      <*> liveAnimationKeys ctx

-- | What the finished frame looks like and what changed since the snapshot.
-- Derived fields stay lazy: a frame that is already 'DamageFull' for a cheap
-- reason never pays for them.
data FrameDelta = FrameDelta
  { fdWinSize :: !Size
  , fdStore :: !WidgetStore
  , fdPrev :: !PrevFrame
  -- ^ This frame's 'dsPrev'.
  , fdFloatingRects :: !(IM.IntMap Rect)
  , fdModalFlip :: !Bool
  , fdLiveAnims :: !IS.IntSet
  , fdWindowLive :: !Bool
  , fdRequests :: ![DamageRequest]
  , fdAnimLive :: Bool
  , fdFloatingChanged :: Bool
  , fdScrollChanged :: Bool
  , fdPointsChanged :: Bool
  , fdScrollOnly :: Bool
  -- ^ Only 'storeFloat' (and the 'storeQuiet' bookkeeping) changed in the
  -- store, e.g. a floating pane scrolled, and not by a float the frame
  -- measured of its own layout.
  , fdSettledMoved :: !RectGroup
  -- ^ Changed key rects, clipped to their scroll viewports, that cover some
  -- area.
  , fdChurn :: !RectGroup
  -- ^ Rects of keys that left or joined the arena.
  , fdRedrawn :: ![Int]
  -- ^ Keys of drawings whose ops changed at an unchanged rect.
  }

-- | Work out the frame's damage against @snap@ and record it, with what the
-- next frame compares against. @mayReuse@: the frame may take the last
-- frame's draw ('NanoUI.Internal.Frame.paintOrReuse'), which it does only
-- when nothing is damaged. @layoutFloats@: the frame published a float it
-- measured of its own layout ('NanoUI.Internal.Context.Core.publishLayoutSlots'),
-- so its float change is no scroll: widgets moved with it.
writeDamage :: Context -> Input -> FrameSnapshot -> Bool -> Bool -> IO ()
writeDamage ctx inp snap mayReuse layoutFloats = do
  newStore <- getStore ctx
  panels <- floatingPanels ctx
  new <- getsDamage ctx dsPrev
  modalFlip <- modalDamageFlip ctx
  liveAnims <- liveAnimationKeys ctx
  settled <- takeAnimSettled ctx
  windowLive <- getsInteraction ctx (\s -> isJust (isWindowDrag s) || isJust (isWindowResize s))
  requests <- getsDamage ctx dsRequests
  redrawn <- refreshCustomDrawings ctx
  wanted <- readIORef (ctxDamageWanted ctx)
  let oldStore = fsStore snap
      newFloatingRects = if null panels then IM.empty else IM.fromList [(k, r) | (k, r, _) <- panels]
      floatingChanged = not (IM.null (fsFloatingRects snap) && IM.null newFloatingRects) && fsFloatingRects snap /= newFloatingRects
      changes = do
        (settledMoved, churn) <- rectDeltas (if null panels then [] else [r | (_, r, _) <- panels]) (fsPrev snap) new
        let scrollChanged = not (eqByPtr (storeFloat oldStore) (storeFloat newStore))
            pointsChanged = not (eqByPtr (storePoint oldStore) (storePoint newStore))
        let delta =
              FrameDelta
                { fdWinSize = inputWindowSize inp
                , fdStore = newStore
                , fdPrev = new
                , fdFloatingRects = newFloatingRects
                , fdModalFlip = modalFlip
                , fdLiveAnims = liveAnims
                , fdWindowLive = windowLive
                , fdRequests = requests
                , fdAnimLive = not (IS.null liveAnims) || settled
                , fdFloatingChanged = floatingChanged
                , fdScrollChanged = scrollChanged
                , fdPointsChanged = pointsChanged
                , fdScrollOnly =
                    scrollChanged
                      && not layoutFloats
                      && not pointsChanged
                      && storeOpenSelect oldStore == storeOpenSelect newStore
                      && null (slotChangedKeys oldStore newStore)
                , fdSettledMoved = settledMoved
                , fdChurn = churn
                , fdRedrawn = redrawn
                }
        -- The store diff runs only once the cheap checks would clip: a frame
        -- already repainting whole needs no per-key damage.
        case fullDamageCause snap delta of
          cause@(_ : _) -> (DamageFull, []) <$ traceDamage ("DAMAGE full " <> cause)
          [] -> do
            (misses, owners) <- storeKeyChanges ctx oldStore newStore
            -- A changed key that resolves to no node (a widget-internal key
            -- nothing in the arena carries) may have changed
            -- paint state no diff describes, so nothing narrower than the window
            -- is known to cover it. Key 0 names no widget and is damaged by
            -- nothing, so its writes cannot escalate a frame.
            if any (\k -> k /= 0 && IM.notMember k owners) misses
              then (DamageFull, []) <$ traceDamage "DAMAGE full store-key-without-owner"
              else clipDamage ctx snap delta owners
  -- A host repainting the whole window whatever changed does not read the
  -- damage, so nothing is diffed ('ctxDamageWanted'), unless the frame may
  -- reuse the last draw: that takes damage known to be empty. A frame whose
  -- recorded rects, clips, texts or images changed ('updatePrevRects' kept
  -- no record unchanged) almost always has damage, and one that redrew a
  -- drawing in view has it for sure ('clipDamage'), so those paint instead
  -- of diffing. An idle frame diffs cheaply: its maps and store compare by
  -- pointer. A drawing redrawn out of view (an animation scrolled away)
  -- leaves the frame to the diff, which finds nothing to repaint.
  let Size winW winH = inputWindowSize inp
      inView k = maybe False (rectNonEmpty . clipRectToWindow winW winH . clipToViewport (ownClip new k)) (IM.lookup k (pfRects new))
      diff = wanted || (mayReuse && samePrev (fsPrev snap) new && not (any inView redrawn))
  (dmg, pieces) <- if diff then changes else (DamageFull, []) <$ traceDamage "DAMAGE full not-diffed"
  modifyDamage ctx $ \ds ->
    ds
      { dsDamage = dmg
      , dsDamagePieces = pieces
      , dsLastWindowSize = inputWindowSize inp
      , dsRequests = []
      }
  -- Most frames have no panel now or before, and then there is nothing to write.
  prevEmpty <- getsOverlay ctx (IM.null . osPrevFloatingRects)
  unless (null panels && prevEmpty) $
    modifyOverlay ctx $ \os ->
      os {osPrevFloatingRects = newFloatingRects, osPrevFloatingOrder = [k | (k, _, True) <- panels]}
  -- The follow-up frames these request only settle placement: the flip made
  -- this frame repaint whole, and a floating change did too or, on a frame
  -- that only scrolled, damaged each moved panel where it was and is, so
  -- their pixels are not waiting on the next frame.
  when modalFlip (markDirty ctx)
  when (floatingChanged && not (IM.null (fsFloatingRects snap) && not (IM.null newFloatingRects))) $
    markDirty ctx
  -- A popup placed by its anchor's last rect ('NanoUI.respRect') is a frame
  -- behind an anchor this frame moved (a widget last had the anchor's rect
  -- and now has another), and nothing else may ask for the frame that
  -- catches it up.
  -- Forced: 'ptrEq' on a selector thunk never matches.
  let !oldRects = pfRects (fsPrev snap)
      !newRects = pfRects new
      moved a = IM.foldrWithKey (\k r rest -> (r == a && IM.lookup k newRects /= Just a) || rest) False oldRects
      anchorMoved idx =
        getNodeType (ctxNodeArena ctx) idx >>= \case
          NodePopup ->
            (\case Just (AnchorRect a, _, _) -> moved a; _ -> False)
              <$> (lookupPopupConfig ctx =<< getWidgetId (ctxNodeArena ctx) idx)
          _ -> pure False
  unless (ptrEq oldRects newRects) $
    findClassNodeM (ctxNodeArena ctx) FloatingNodes anchorMoved >>= \found ->
      when (isJust found) (markDirty ctx)

-- | Whether 'updatePrevRects' left every map of @old@ as it was. Compared by
-- map, not by record: GHC may rebuild a record passed unboxed.
samePrev :: PrevFrame -> PrevFrame -> Bool
samePrev (PrevFrame !r0 !c0 !o0 !h0 !e0) (PrevFrame !r1 !c1 !o1 !h1 !e1) =
  ptrEq r0 r1 && ptrEq c0 c1 && ptrEq o0 o1 && ptrEq h0 h1 && ptrEq e0 e1

-- | Settle every drawing's ops for this frame and return the keys of those
-- that now draw something else at an unchanged rect. A drawing follows state
-- the arena does not hold, so nothing else damages it, and paint must not
-- replay the previous frame's ops for it. What this costs per widget is the
-- widget's own choice: see 'refreshCustomDrawingOps'.
refreshCustomDrawings :: Context -> IO [Int]
refreshCustomDrawings ctx@Context {ctxNodeArena = na} =
  -- The walk visits only the drawing nodes, so a view without any skips it.
  foldClassNodesM na DrawingNodes step []
  where
    step acc i = do
      wid <- getWidgetId na i
      rect <- getNodeRect na i
      mCustom <- lookupCustomDrawingAt ctx i
      changed <- case mCustom of
        Just CustomDrawingEntry {cdrContent = content, cdrBuild = build} -> do
          cdc <- mkCustomDrawContext ctx (ctxFontMetrics ctx) wid
          refreshCustomDrawingOps ctx wid content rect cdc build
        Nothing -> do
          -- A versioned drawing rebuilds in paint once its version
          -- changes, but the pixels it covered still need damage. An
          -- unversioned one is cached by contract, so it stays put.
          mDrawing <- lookupDrawingAt ctx i
          case mDrawing of
            Just (DrawingEntry content _) | content /= 0 -> drawingOpsStale ctx wid content rect
            _ -> pure False
      pure (if changed then intKey wid : acc else acc)

-- | The check that makes the frame repaint the whole window rather than a
-- clip, or the empty string for none. 'traceDamage' prints it.
--
-- Store writes and nodes whose paint inputs changed are repainted per key
-- instead ('storeKeyChanges', 'clipDamage'); 'writeDamage' escalates a
-- frame whose changed store keys do not all resolve to a node after this
-- check.
fullDamageCause :: FrameSnapshot -> FrameDelta -> String
fullDamageCause snap d
  | ReqFull `elem` fdRequests d = "request"
  | neverPainted = "first"
  -- A resize, a modal opening or closing (its dim covers the window, and a
  -- Var-bound modal writes nothing to the store) and a live window drag are
  -- window-wide whatever scrolled in the same frame.
  | sizeChanged = "resize"
  | fdModalFlip d = "modal"
  | fdWindowLive d = "window-gesture"
  | not (fdScrollOnly d) && fdFloatingChanged d = "floating"
  | not (fdScrollOnly d) && orphanAnim && fdAnimLive d = "orphan-animation"
  | not (fdScrollOnly d) && keysChanged = "key-churn"
  | not (fdScrollOnly d) && layoutSettle = "layout"
  | missingAnim && fdAnimLive d = "missing-animation"
  | otherwise = ""
  where
    oldRects = pfRects (fsPrev snap)
    newRects = pfRects (fdPrev d)
    oldSize = fsSize snap
    -- Before any frame there is nothing to diff against, and the window
    -- backdrop outside every widget rect was never painted.
    neverPainted = oldSize == Size 0 0
    sizeChanged = oldSize /= fdWinSize d
    -- A live animation repaints whole on its first frame without a rect: its
    -- widget just left, or it has none and started this frame. After that it
    -- is clipped like the rest, so a perpetual animation whose widget has
    -- left the arena (@keepAnimating@ behind a tab switch) stops repainting
    -- the window.
    animKeys = IS.toList (fdLiveAnims d)
    firstRectless k =
      IM.notMember k newRects && (IM.member k oldRects || IS.notMember k (fsAnimKeys snap))
    orphanAnim = any firstRectless animKeys
    -- One with no rect last frame either is not clipped even when only a
    -- scroller moved: the retain texture may never have shown it.
    missingAnim =
      any (\k -> k /= 0 && IM.notMember k oldRects && IM.notMember k newRects && IS.notMember k (fsAnimKeys snap)) animKeys
    keysChanged =
      not (IM.null oldRects)
        && rgAny (fdChurn d)
        && not (rgInPanels (fdChurn d))
    layoutSettle =
      not (IM.null oldRects)
        && rgAny (fdSettledMoved d)
        && not (fdAnimLive d)
        && not (fdScrollChanged d)
        && not (rgInPanels (fdSettledMoved d))

-- | Monadic builder for collecting damage rects across frames.
newtype DamageCollector a = DamageCollector (RectUnion -> IO a)
  deriving (Functor, Applicative, Monad, MonadIO) via (ReaderT RectUnion IO)

{-# INLINE collectDamage #-}
collectDamage :: DamageCollector () -> IO [Rect]
collectDamage (DamageCollector act) = do
  ref <- newIORef []
  act ref
  readIORef ref

{-# INLINE addDamageRect #-}
addDamageRect :: Rect -> DamageCollector ()
addDamageRect r = DamageCollector (`addRect` r)

{-# INLINE addDamageKey #-}
addDamageKey :: PrevFrame -> Int -> Rect -> Rect -> DamageCollector ()
addDamageKey p k r d = DamageCollector $ \ref -> addKeyDamage ref p k r d

{-# INLINE addDamageKeyGrow #-}
addDamageKeyGrow :: PrevFrame -> Int -> (Rect -> Rect) -> DamageCollector ()
addDamageKeyGrow p k grow =
  forM_ (IM.lookup k (pfRects p)) $ \r -> addDamageKey p k r (grow r)

{-# INLINE addDamageGroup #-}
addDamageGroup :: RectGroup -> DamageCollector ()
addDamageGroup g = when (rgAny g) $ addDamageRect (rgBounds g)

-- | The clip covering everything that changed, with the pieces it splits
-- into ('damagePieces'), or 'DamageFull' once the pieces cover over half the
-- window.
clipDamage ::
  Context -> FrameSnapshot -> FrameDelta -> IM.IntMap NodeIdx -> IO (Damage, [Rect])
clipDamage ctx snap d owners = do
  let old = fsPrev snap
      new = fdPrev d
      Size winW winH = fdWinSize d
      rectIn p wid = IM.lookup (intKey wid) (pfRects p)
      damageBoth k grow = addDamageKeyGrow old k grow >> addDamageKeyGrow new k grow
      resolveKey k = damageBoth k . resolveDamageRect
      resolveSlop k = resolveKey k (DamageInflated defaultDamageSlop)
      addBackdrop k = unless (k == 0) $ do
        mbNode <- liftIO (lookupNodeByKey (ctxNodeArena ctx) k)
        forM_ mbNode $ \idx ->
          liftIO (backdropRectFromNode ctx idx) >>= mapM_ addDamageRect
      hadRole wid = wid == fsHot snap || wid == fsActive snap || wid == fsFocus snap
      addInteraction wid = unless (k == 0) $ do
        slop <- fromMaybe defaultDamageSlop <$> liftIO (lookupCustomDamageSlop ctx wid)
        forM_ (if hadRole wid then rectIn old wid else Nothing) $ \r -> addDamageKey old k r (rectInflate slop r)
        forM_ (rectIn new wid) $ \r -> addDamageKey new k r (rectInflate slop r)
        addBackdrop k
        where
          k = intKey wid
      -- A parked pointer must not re-damage its hot widget every frame: only
      -- an id change (hover in/out, press, focus move) or a rect move
      -- repaints. Unchanged interaction rects kept the steady state at
      -- DamageFull whenever the hot widget sat inside a panel whose backdrop
      -- covered over half the window.
      role oldW newW = when (oldW /= newW || rectIn old oldW /= rectIn new newW) $ addInteraction oldW >> addInteraction newW
      !newHashes = pfHashes new
      !oldHashes = pfHashes old
  added <- collectDamage $ do
    forM_ (fdRequests d) $ \case
      ReqFull -> pure ()
      ReqRect r -> addDamageRect r
      ReqWidget wid bounds -> resolveKey (intKey wid) bounds
      ReqKey k bounds -> resolveKey k bounds >> addBackdrop k
      ReqPeers wids bounds -> forM_ wids $ \wid -> resolveKey (intKey wid) bounds
    role (fsHot snap) =<< liftIO (getHotId ctx)
    role (fsActive snap) =<< liftIO (readIORef (ctxActiveId ctx))
    focus <- liftIO (readIORef (ctxFocusId ctx))
    role (fsFocus snap) focus
    -- The focus ring shows or hides on the same widget.
    focusVisible <- liftIO (readIORef (ctxFocusVisible ctx))
    when (focusVisible /= fsFocusVisible snap && focus == fsFocus snap) (addInteraction focus)
    when (fdScrollChanged d || fdPointsChanged d) $
      scrollOffsetDamage ctx (fsStore snap) (fdStore d)
    forM_ (IS.toList (IS.fromList (IM.elems owners))) $ \idx ->
      resolveSlop . intKey =<< liftIO (getWidgetId (ctxNodeArena ctx) idx)
    forM_ (IS.toList (fsAnimKeys snap <> fdLiveAnims d)) $ \k ->
      unless (k == 0) (resolveSlop k)
    -- A node the view gave other paint inputs (text, value, style, colour,
    -- scope, image) repaints. A widget repaints with its halo, where it was
    -- and where it is; text, a box or an image paints inside its rect, which
    -- a move damages already.
    let repaintNode k = do
          halo <- liftIO (lookupNodeByKey (ctxNodeArena ctx) k >>= maybe (pure False) (fmap isWidgetNode . getNodeType (ctxNodeArena ctx)))
          if halo then resolveSlop k else addDamageKeyGrow new k id
    unless (ptrEq newHashes oldHashes) $
      forM_ (IM.keys (IM.differenceWith (\n o -> if n /= o then Just n else Nothing) newHashes oldHashes)) repaintNode
    forM_ (fdRedrawn d) $ \k -> addDamageKeyGrow new k id
    -- Also on a scroll-only frame: 'storeFloat' holds slider values too, and
    -- a label showing one can shrink or move what follows it. A scroll's own
    -- moves are clipped to the viewport its offset damage already covers.
    addDamageGroup (fdSettledMoved d)
    addDamageGroup (fdChurn d)
    -- A panel paints its offset shadow past its rect ('menuPanelBounds'), and
    -- Tier 2 shader effects paint halos out to their margin-expanded bounds.
    let addMapDiff f a b =
          IM.foldrWithKey (\k r rest -> unless (IM.lookup k b == Just r) (addDamageRect (f r)) >> rest) (pure ()) a
        diffBoth f a b = addMapDiff f a b >> addMapDiff f b a
    diffBoth menuPanelBounds (fsFloatingRects snap) (fdFloatingRects d)
    let oldEffects = pfEffectRects old
        newEffects = pfEffectRects new
    unless (ptrEq oldEffects newEffects) $ diffBoth id oldEffects newEffects
  -- Only what lands in the window counts: an empty rect, or one off the
  -- window, would stretch the bounds over pixels nothing changed.
  let added' = if null added then added else expandEffectDamage old new added
  let visible = filter rectNonEmpty (map (clipRectToWindow winW winH) added')
      clip = rectBounds visible
      winArea = winW * winH
      -- A frame with more rects than this repaints their bounds.
      pieces
        | null (drop 64 visible) = damagePieces visible
        | otherwise = []
      area = if null pieces then rectArea clip else sum (map rectArea pieces)
  -- A live animation with an empty clip is not DamageFull: its
  -- key was either scroll-clipped out of view (nothing visible
  -- changes; scrolling back in damages via the scroll delta) or
  -- rect-less, which missingAnim already promoted to full.
  if winArea > 0 && area > winArea * 0.5
    then (DamageFull, []) <$ traceDamage "DAMAGE full area"
    else (DamageClip clip, pieces) <$ traceDamage "DAMAGE clip"

-- | Collect margin-expanded bounds of every active Tier 2 'NanoUI.withShader'
-- container, reusing @oldEffects@ when unchanged so still frames allocate
-- nothing and frames without effects return 'IM.empty' immediately.
{-# NOINLINE collectEffectRects #-}
collectEffectRects :: Context -> IM.IntMap Rect -> IO (IM.IntMap Rect)
collectEffectRects ctx oldEffects = do
  effNodes <- activeEffectNodes ctx
  if null effNodes
    then pure (if IM.null oldEffects then oldEffects else IM.empty)
    else do
      let na = ctxNodeArena ctx
          inflateXY (V2 mx my) (Rect x y w h) = Rect (x - mx) (y - my) (w + 2 * mx) (h + 2 * my)
          step acc idx = do
            mEntry <- lookupShaderEffectAt ctx idx
            case mEntry of
              Nothing -> pure acc
              Just entry -> do
                r <- inflateXY (seeMargin entry) <$> getNodeRect na idx
                wid <- getWidgetId na idx
                let !k = intKey wid
                pure (if k /= 0 && rectNonEmpty r then IM.insert k r acc else acc)
      effs <- foldM step IM.empty effNodes
      pure (if effs == oldEffects then oldEffects else effs)

-- | When either the previous or current frame uses Tier 2 shader effects
-- ('NanoUI.withShader'), expand any damage rect touching an effect container
-- to cover its full margin-expanded bounds (at both its new and previous
-- positions) so blurs, shadows, and distortions repaint without clipped halos
-- or stale trails.
expandEffectDamage :: PrevFrame -> PrevFrame -> [Rect] -> [Rect]
expandEffectDamage old new rects
  | IM.null oldEffs && IM.null newEffs = rects
  | otherwise =
      let touches rs r = any (isJust . rectIntersect r) rs
          expandWith acc k curR =
            let mOldR = IM.lookup k oldEffs
             in if touches acc curR || maybe False (touches acc) mOldR
                  then curR : maybe acc (: acc) mOldR
                  else acc
          acc1 = IM.foldlWithKey' expandWith rects newEffs
          expandOld acc k oldR
            | IM.member k newEffs = acc
            | touches acc oldR = oldR : acc
            | otherwise = acc
       in IM.foldlWithKey' expandOld acc1 oldEffs
  where
    oldEffs = pfEffectRects old
    newEffs = pfEffectRects new

-- | Most rects a frame's damage splits into.
maxDamagePieces :: Int
maxDamagePieces = 4

-- | Rects closer than this, in logical pixels, merge into one piece. It is
-- more than the backdrop's inflation on both sides, so pieces stay disjoint
-- once each is painted a pixel past its edge.
pieceMergeGap :: Float
pieceMergeGap = 16

-- | Split damage into at most 'maxDamagePieces' disjoint rects: rects that
-- overlap or lie within 'pieceMergeGap' of each other merge, and then the
-- pair whose union grows least merges until few enough remain. Returns no
-- pieces when one or none remain, or when they cover most of their bounding
-- box, since painting the box costs about the same.
damagePieces :: [Rect] -> [Rect]
damagePieces [] = []
damagePieces [_] = []
damagePieces rects =
  case shrink (settle (filter rectNonEmpty rects)) of
    ps@(_ : _ : _)
      | sum (map rectArea ps) < 0.7 * rectArea (foldr1 rectUnion ps) -> ps
    _ -> []
  where
    near a b = isJust (rectIntersect (rectInflate pieceMergeGap a) b)
    -- Merge the first near pair until no pair is near.
    settle ps = maybe ps settle (mergeNear ps)
    mergeNear [] = Nothing
    mergeNear (p : ps) = case break (near p) ps of
      (before, q : after) -> Just (rectUnion p q : before ++ after)
      (_, []) -> (p :) <$> mergeNear ps
    shrink ps
      | length ps <= maxDamagePieces = ps
      | otherwise =
          let indexed = zip [0 :: Int ..] ps
              cost a b = rectArea (rectUnion a b) - rectArea a - rectArea b
              (_, i, j) = minimum [(cost a b, i', j') | ((i', a) : later) <- tails indexed, (j', b) <- later]
              (pair, rest) = partition (\(k, _) -> k == i || k == j) indexed
           in shrink (settle (foldr1 rectUnion (map snd pair) : map snd rest))

-- | Add damage @d@ for key @k@'s rect @r@ in frame @p@, clipped to the clip
-- @r@ is painted in there ('ownClip'). For a scroll container or panel (a key
-- in 'pfOuterClips') @d@ is also kept inside @r@: slop is for a widget's
-- halo, which those lack, and their wider outer clip would let it spill.
addKeyDamage :: RectUnion -> PrevFrame -> Int -> Rect -> Rect -> IO ()
addKeyDamage acc p k r d =
  when (rectNonEmpty clipped) $ addRect acc clipped
  where
    clipped = clipToViewport (ownClip p k) (if IM.member k (pfOuterClips p) then clipToViewport (Just r) d else d)

-- | The rects damage gathers, newest first.
type RectUnion = IORef [Rect]

{-# INLINE addRect #-}
addRect :: RectUnion -> Rect -> IO ()
addRect acc r = modifyIORef' acc (r :)

-- | The bounds of @rects@, empty ones included, or the zero rect for none.
rectBounds :: [Rect] -> Rect
rectBounds [] = Rect 0 0 0 0
rectBounds (r : rs) = foldl' rectUnion r rs

-- | A set of rects reduced to what damage needs from it.
data RectGroup = RectGroup
  { rgAny :: !Bool
  , rgInPanels :: !Bool
  -- ^ Some floating panel fully contains each rect; False for an empty group.
  , rgBounds :: !Rect
  }

-- | One pass over keys whose rect changed, split into settled moves (each
-- side clipped to its viewport in its own frame, kept above
-- 'layoutSettleMinArea') and keys that left or joined the arena.
rectDeltas :: [Rect] -> PrevFrame -> PrevFrame -> IO (RectGroup, RectGroup)
rectDeltas panelRects oldP newP
  | ptrEq old new = pure (emptyGroup, emptyGroup)
  | otherwise =
      pure $
        let (settled, churn) =
              IM.foldrWithKey
                ( \k r (!accS, !accC) ->
                    if rectNonEmpty r
                      then
                        let !accC' = if IM.notMember k new || IM.notMember k old then r : accC else accC
                            oldClip = ownClip oldP k
                            newClip = ownClip newP k
                            side clip = maybe (Rect 0 0 0 0) (clipToViewport clip)
                            clipped
                              | oldClip == newClip = clipToViewport newClip r
                              | otherwise = unionNonEmpty (side oldClip (IM.lookup k old)) (side newClip (IM.lookup k new))
                            !accS' = if rectArea clipped >= layoutSettleMinArea then clipped : accS else accS
                         in (accS', accC')
                      else (accS, accC)
                )
                ([], [])
                (IM.mergeWithKey (\_ a b -> if a /= b then Just (rectUnion a b) else Nothing) id id old new)
         in (group settled, group churn)
  where
    -- Forced, so an unchanged frame's maps compare by pointer ('ptrEq').
    !old = pfRects oldP
    !new = pfRects newP
    emptyGroup = RectGroup False False (Rect 0 0 0 0)
    unionNonEmpty a b
      | not (rectNonEmpty a) = b
      | not (rectNonEmpty b) = a
      | otherwise = rectUnion a b
    inPanels r = any (rectFullyInside r) panelRects
    group rs = RectGroup (not (null rs)) (not (null rs || null panelRects) && all inPanels rs) (rectBounds rs)

-- | The clip key @k@'s rect is painted in, in frame @p@: the outer clip for a
-- scroll container or panel, otherwise its viewport clip. Each rect uses its
-- own frame's clip because the current viewport can be smaller than the old
-- one (an enclosing widget or scroller shrank), which would cut the vacated
-- pixels out of the damage.
{-# INLINE ownClip #-}
ownClip :: PrevFrame -> Int -> Maybe Rect
ownClip p k = IM.lookup k (pfOuterClips p) <|> IM.lookup k (pfClips p)

clipToViewport :: Maybe Rect -> Rect -> Rect
clipToViewport clip r = maybe r (fromMaybe (Rect 0 0 0 0) . rectIntersect r) clip

clipRectToWindow :: Float -> Float -> Rect -> Rect
clipRectToWindow winW winH = clipToViewport (Just (Rect 0 0 winW winH))

scrollOffsetDamage :: Context -> WidgetStore -> WidgetStore -> DamageCollector ()
scrollOffsetDamage Context {ctxNodeArena = na} oldStore newStore =
  unless (null changedKeys) $ do
    -- Every store key that holds a scroll node's offset, mapped to the first
    -- such node, and every scroll range, mapped to each node with that id.
    -- Built once, only on frames where an offset or range changed.
    owners <- liftIO $ foldClassNodeRevM na PointerNodes addOwner IM.empty
    forM_ changedKeys $ \k ->
      forM_ (IM.findWithDefault [] k owners) $ \idx -> do
        -- The scroll node's rect covers the content viewport AND the
        -- scrollbar lane: offset changes move the thumb, which paints
        -- outside the content clip.
        liftIO (getNonzeroRect na idx) >>= mapM_ addDamageRect
        liftIO (walkFloatingAncestors na idx (\i _ -> getNonzeroRect na i)) >>= mapM_ addDamageRect
  where
    -- Floating-pane offsets live in storeFloat; wheel/keyboard offsets
    -- live under the SlotTextAreaScroll slot in storePoint. Both move the
    -- scroller's content and its chrome. New or removed float offsets only
    -- count when nonzero. The range the scroll pass publishes to storePoint
    -- changes with the content's size, which resizes the thumb and can show
    -- or hide a bar; content that changes but still fits keeps a zero range
    -- and repaints nothing here. Two scrollers can share an id (a table's
    -- frozen pane and body), and only the first publishes, so a range change
    -- repaints every scroller with the id.
    (oldF, newF) = (storeFloat oldStore, storeFloat newStore)
    changedKeys =
      filter (\k -> IM.findWithDefault 0 k oldF /= IM.findWithDefault 0 k newF) (diffKeys oldF newF)
        ++ diffKeys (storePoint oldStore) (storePoint newStore)
    addOwner m idx = do
      nt <- getNodeType na idx
      if not (isScrollNode nt)
        then pure m
        else do
          wid <- getWidgetId na idx
          let widKey = intKey wid
              one = [idx]
          pure $
            IM.insertWith (++) widKey one $
              IM.insertWith (++) (slotKey SlotScrollCross widKey) one $
                IM.insertWith (++) (slotKey SlotScrollRange widKey) one m

-- | The store keys (outside the scroll offsets) whose value changed and that
-- are not themselves widget keys, with the node that owns each through a
-- sub-slot spelling. Changed widget keys were already damaged by their
-- 'ReqKey' requests. An owner comes from 'ctxStoreOwners' when the widget
-- it names is in the arena; only keys it does not answer cost a walk
-- ('storeKeyOwners'), whose finds it keeps.
storeKeyChanges :: Context -> WidgetStore -> WidgetStore -> IO ([Int], IM.IntMap NodeIdx)
storeKeyChanges ctx oldStore newStore = do
  let na = ctxNodeArena ctx
  misses <- filterM (\k -> isNothing <$> lookupNodeByKey na k) (slotChangedKeys oldStore newStore)
  if null misses
    then pure ([], IM.empty)
    else do
      known <- readIORef (ctxStoreOwners ctx)
      cached <- mapM (\k -> (k,) <$> maybe (pure Nothing) (lookupNodeByKey na) (IM.lookup k known)) misses
      let hits = IM.fromList [(k, i) | (k, Just i) <- cached]
          rest = [k | (k, Nothing) <- cached]
      found <- if null rest then pure IM.empty else storeKeyOwners na (IS.fromList rest)
      unless (IM.null found) $ do
        owners <- traverse (fmap intKey . getWidgetId na) found
        writeIORef (ctxStoreOwners ctx) $! IM.union owners known
      pure (misses, IM.union hits found)

-- | Each of @wanted@ that maps to a node this frame, keyed to the node that
-- owns it: each widget's base key plus the sub-slot spellings its reads and
-- writes use. Walks the arena, so 'storeKeyChanges' runs it only for keys
-- whose owner it has not found before.
storeKeyOwners :: NodeArena -> IS.IntSet -> IO (IM.IntMap NodeIdx)
storeKeyOwners na wanted = do
  n <- arenaCount na
  -- Stops once every wanted key has an owner.
  let target = IS.size wanted
      go !i !found !m
        | i < 0 || found == target = pure m
        | otherwise = do
            wid <- getWidgetId na i
            if hashWidgetId wid == 0
              then go (i - 1) found m
              else do
                nt <- getNodeType na i
                if nt == NodeText || nt == NodeSpacer || nt == NodeSeparator || nt == NodeImage || nt == NodeBox || nt == NodeShader
                  then go (i - 1) found m
                  else do
                    let !k = intKey wid
                        add (!c, !m') sk
                          | IS.member sk wanted && IM.notMember sk m' = (c + 1, IM.insert sk i m')
                          | otherwise = (c, m')
                        -- The widget's own key first, then each sub-slot spelling.
                        (found', m'') =
                          foldl' (\acc s -> add acc (slotKey s k)) (add (found, m) k) ownerSlots
                    go (i - 1) found' m''
  go (n - 1) (0 :: Int) IM.empty

-- | The sub-slots whose writes repaint from the store at paint time: carets and
-- anchors in text fields, a text area's buffer (its document and caret),
-- line widths (its scrollbars) and history, drag targets, a colour picker's opening colour, and the seen/mode
-- records a controlled edit co-writes. Shared, so resolving an owner does not
-- build a key list per node per frame.
ownerSlots :: [Slot]
ownerSlots =
  [ SlotSeen
  , SlotCursor
  , SlotAnchor
  , SlotTextMode
  , SlotTextHistory
  , SlotSearchCommitted
  , SlotSearchAge
  , SlotTextAreaAnchorRow
  , SlotTextAreaAnchorCol
  , SlotTextAreaChanged
  , SlotTextAreaText
  , SlotTextAreaBuffer
  , SlotTextAreaWidths
  , SlotDrop
  , SlotDrag
  , SlotScrollAxes
  , SlotScrollLinkX
  , SlotScrollLinkY
  , SlotNumericHeld
  , SlotNumericRepeat
  , SlotMenuOpen
  , SlotColorBase
  ]

-- | The pixel edges of a rect at a scale, rounded outwards: left, top, right
-- and bottom.
{-# INLINE pixelEdges #-}
pixelEdges :: Float -> Rect -> (Int, Int, Int, Int)
pixelEdges s (Rect x y w h) =
  (floor (x * s), floor (y * s), ceiling ((x + w) * s), ceiling ((y + h) * s))

-- | The device pixels a clip covers at a scale, as left, top, right and
-- bottom edges: 'pixelEdges' with a tolerance of a thousandth of a pixel.
-- An edge 'snapDamage' put on a pixel comes back from layout units a
-- rounding error to either side of it, and 'pixelEdges' would then round it
-- out to take in the next pixel, past the repainted damage. This rule keeps
-- such an edge on its pixel; an edge further inside a pixel still rounds
-- outwards. The SDL and web backends clip with it.
{-# INLINE clipPixelEdges #-}
clipPixelEdges :: Float -> Rect -> (Int, Int, Int, Int)
clipPixelEdges s (Rect x y w h) =
  (lower (x * s), lower (y * s), upper ((x + w) * s), upper ((y + h) * s))
  where
    lower v = floor (v + 1.0e-3)
    upper v = ceiling (v - 1.0e-3)

-- | Grow damage to whole device pixels so its clip covers every pixel the
-- changed rect touches.
{-# INLINE snapDamage #-}
snapDamage :: Float -> Damage -> Damage
snapDamage _ DamageFull = DamageFull
snapDamage scale (DamageClip r) =
  let (x0, y0, x1, y1) = pixelEdges scale r
      at v = fromIntegral v / scale
   in DamageClip (Rect (at x0) (at y0) (at x1 - at x0) (at y1 - at y0))