packages feed

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

-- | Complete headless frames: view construction, layout, input resolution,
-- damage, and draw-buffer generation. Backends own event waits and presentation.
module NanoUI.Internal.Frame
  ( runFrame
  , runFrameEff
  )
where

import Control.Monad (unless, when, (<$!>))
import Data.IORef (modifyIORef', readIORef, writeIORef)
import Data.IntMap.Strict qualified as IM
import Data.Maybe (isJust, isNothing)
import Data.Primitive.PrimArray (readPrimArray)
import Data.Primitive.PrimVar (writePrimVar)
import Effectful (Eff, IOE, runEff, type (:>))
import NanoUI.Internal.Atlas (atlasToken)
import NanoUI.Internal.Context
import NanoUI.Internal.Context.Types (resetContainerStack)
import NanoUI.Internal.Damage (captureFrameSnapshot, pruneUnmountedCaches, updatePrevRects, writeDamage)
import NanoUI.Internal.Draw
import NanoUI.Internal.Frame.Input
import NanoUI.Internal.Frame.Chrome (floatingSurface, paintMenuPanel)
import NanoUI.Internal.Frame.Explain (explainFrame, paintExplainHover, paintExplainLayer, paintExplainPage)
import NanoUI.Internal.Frame.Paint (lowerShapes, walkChildren)
import NanoUI.Internal.Frame.Scroll
import NanoUI.Internal.Frame.Select
import NanoUI.Internal.Frame.TextArea (finalizeTextFieldMouse)
import NanoUI.Internal.Frame.TextEdit
import NanoUI.Internal.Frame.TextInput (claimComposition, settleInputMethod)
import NanoUI.Internal.Frame.Window
import NanoUI.Internal.Id (WidgetId (..))
import NanoUI.Internal.Id.Cursor (resetIdCursor)
import NanoUI.Internal.Input (Input (..), Key (..), MouseButton (..), Pressable (..), inputKeysNull, stripInteractionInput, withoutPointer)
import NanoUI.Internal.Layout.Arena
import NanoUI.Internal.Layout.Solve (measuredHeightAt, placeFloatingNodesWith, runCustomMeasure, solveLayout)
import NanoUI.Internal.Monad (NanoUI (..), Ui, embedNanoUI, runUi, whenM)
import NanoUI.Internal.NativeWindow (clearWindowClose)
import NanoUI.Internal.Store (ptrEq)
import NanoUI.Internal.Style (Padding (..), Theme (..), pageBackground, themeOverlayDim, themeSeparator)
import NanoUI.Internal.Tasks (sweepHeld)
import NanoUI.Internal.Types (Color, Damage (..), Rect (..), Size (..), colorA, damageIsEmpty, fadeAlpha, lerpColor, rectInflate, rectNonEmpty)
import NanoUI.Internal.Widgets.Overlay (windowChromeSepH, windowTitleBarH)
import NanoUI.Internal.Var (beginVarPass, endVarFrame, takeVarRerun)
import NanoUI.Internal.Widgets.Sensor (beginSensors, updateSensors)

-- | Build, lay out, resolve input, and paint one headless frame. Returns the
-- view result, borrowed draw buffers, and whether state
-- needs a follow-up frame. A local-state change can rebuild the view within
-- this call, with one-shot input removed. Native presentation is the host's job.
runFrame :: Context -> Input -> NanoUI a -> IO (a, DrawData, Bool)
runFrame ctx inp ui = runFrameEff runEff ctx inp (unNanoUI ui)

-- | 'runFrame' with a runner for the effects remaining after 'Ui'. Run frames
-- serially on a context; its arenas and stores are mutable and reused.
runFrameEff ::
  IOE :> es =>
  (forall x. Eff es x -> IO x)
  -> Context
  -> Input
  -> Eff (Ui : es) a
  -> IO (a, DrawData, Bool)
runFrameEff unlift ctx rawInp ui = do
  ensureMetricCaches ctx
  snap <- captureFrameSnapshot ctx
  themeBefore <- readIORef (ctxTheme ctx)
  modifyDamage ctx (\ds -> ds {dsDirty = False})
  -- Timed wakes are re-requested by whatever is still built this frame.
  clearWakeAt ctx
  takeThreadWake ctx
  -- The focused field gets any IME composition, and while one shows, the IME
  -- owns the keys.
  (frameInp, imeKeys) <- claimComposition ctx rawInp
  -- Route pointer input before the view runs, against the previous frame's
  -- geometry. Each pass below receives input filtered to its target layer
  -- ('withoutPointer' when the pointer is routed elsewhere): @layerInp@ for
  -- scrolling, windows, presses, focus and text fields. @frameInp@ retains the
  -- unmasked pointer for window-wide checks (outside-click dismissal, hover,
  -- and overlay painting).
  route <- routePointer ctx frameInp
  -- A widget covered by another gets no pointer.
  recordCoveredWidgets ctx route frameInp
  let routedIf mine = if mine then frameInp else withoutPointer frameInp
      layerInp = routedIf (case route of RouteLayer _ -> True; _ -> False)
  -- Wheel and thumb-drag input targets the previous frame's layout, so apply
  -- it while that arena is still intact, before it is reset for the new
  -- build. Settling offsets before the UI pass keeps build-time
  -- virtualization (table body rows) materialized for the range that will
  -- actually be visible, without a second build pass.
  updateScrollWheel ctx layerInp
  -- A glide advances with the wheel, before the build, for the same reason:
  -- the offset this frame renders at is the one virtualization must see.
  stepScrollGlides ctx (inputDeltaTime frameInp)
  updateScrollDrag ctx layerInp
  -- Read from the last frame's nodes, before the build resets them.
  recordFocusKind ctx imeKeys
  armPointerPress ctx frameInp
  -- A left press makes active the widget the user saw under the pointer. A
  -- press on a menu or dropdown leaves nothing active, whatever a release
  -- that never arrived left behind.
  when (pressedIn MouseLeft frameInp && not (pressedIn MouseLeft layerInp)) $
    writeIORef (ctxActiveId ctx) (WidgetId 0)
  targets <- pressTargets ctx layerInp
  armPointerTarget ctx targets
  resetUiBuild ctx True
  escTaken <- getsOverlay ctx osEscapeConsumed
  beginFrameModal ctx
  -- An Escape the IME consumed must not also quit the app.
  when (inputKeysNull (inputKeys frameInp) && pressedIn KeyEscape rawInp) $
    markEscapeConsumed ctx
  -- One whose press was taken stays taken while it repeats and on its
  -- release, so no key listener acts on the rest of it.
  when (escTaken && not (pressedOnceIn KeyEscape rawInp) && (heldIn KeyEscape rawInp || releasedIn KeyEscape rawInp)) $
    markEscapeConsumed ctx
  focusBefore <- readIORef (ctxFocusId ctx)
  result <- runViewPasses unlift ctx frameInp ui
  -- Clear the one-shot close request ('NanoUI.winCloseRequested') after the
  -- view has run.
  clearWindowClose ctx
  -- Scopes only change how nodes look, which the rect and text diffs below
  -- do not track, and custom widgets' cached ops hold the old theme's colours.
  -- Nothing measured depends on a theme, so the caches that follow the font
  -- metrics ('ctxMetricGen') stand.
  whenM (themeScopesChanged ctx) $ do
    damageFull ctx
    modifyIORef' (ctxDrawingCache ctx) (\dc -> dc {dcsCustomDrawOpCache = IM.empty})
  settleViewTheme ctx themeBefore
  let
    size@(Size w h) = inputWindowSize frameInp
  layoutArena ctx size True
  -- A press that starts a window gesture hit-tests the page where it is
  -- drawn, scrolled and clipped.
  applyScrollOffsets ctx size
  settleDropdowns ctx size
  movedResize <- updateWindowResize ctx layerInp w h
  movedWindow <- updateWindowDrag ctx layerInp
  -- A window moved or resized changes only where the floating panels go:
  -- the solve before placement stands, so place them again over it.
  when (movedResize || movedWindow) $ do
    layoutArena ctx size False
    applyScrollOffsets ctx size
    settleDropdowns ctx size
  persistWindowPositions ctx
  finalizeFrameInput ctx frameInp layerInp targets focusBefore
  settleDropdowns ctx size
  -- Layout is final, so the sensors record what the next view reads.
  updateSensors ctx size
  pruneUnmountedCaches ctx =<< updatePrevRects ctx size
  -- With the layout recorded, what the view read of the last one is checked
  -- against it. A check that publishes a float it measured (a tab strip's
  -- range) marks the frame as a layout change, not a scroll, for its damage.
  -- Both maps are forced: 'ptrEq' on an unforced selection compares a fresh
  -- thunk, which never matches, and every frame would be a layout change.
  !floatsBefore <- storeFloat <$> getStore ctx
  settleLayoutReads ctx
  !floatsAfter <- storeFloat <$> getStore ctx
  let !layoutFloats = not (ptrEq floatsBefore floatsAfter)
  refreshHover ctx frameInp
  refreshScrollBarHover ctx layerInp
  tickAnimations ctx (inputDeltaTime frameInp)
  sweepHeld ctx
  pruneDrawOpCache ctx
  -- The layout overlay damages its own outlines, since the rect diffs below
  -- miss rows and columns that moved.
  explain <- getExplainLayout ctx
  when explain (explainFrame ctx frameInp)
  -- The draw this frame may reuse is decided before its damage: a frame
  -- that may reuse it needs its damage worked out even for a host that does
  -- not read it ('ctxDamageWanted'). A frame that paints only a clip, or
  -- shows the layout overlay, can neither keep its draw nor reuse one.
  reuse <- readIORef (ctxDrawReuse ctx)
  paintFull <- readIORef (ctxPaintFull ctx)
  clear <- frameClearColor ctx
  key <- if drOn reuse && paintFull && not explain then drawReuseKey ctx size clear else pure Nothing
  let !mayReuse = case (key, drLast reuse) of
        (Just k, Just (lastKey, _)) -> k == lastKey
        _ -> False
  writeDamage ctx frameInp snap mayReuse layoutFloats
  drawData <- paintOrReuse ctx size explain paintFull clear reuse key mayReuse
  dirtyAfterUi <- isDirty ctx
  pure (result, drawData, dirtyAfterUi)

-- | Run the view pass, and re-run without interaction input if a backwards
-- 'Var' write invalidated what pass 1 drew.
{-# INLINE runViewPasses #-}
runViewPasses ::
  IOE :> es =>
  (forall x. Eff es x -> IO x) ->
  Context ->
  Input ->
  Eff (Ui : es) a ->
  IO a
runViewPasses unlift ctx frameInp ui = do
  beginVarPass ctx 1
  -- Opened only after layout, so whether it shows is known before the view.
  menuOpen <- isJust <$> getsInteraction ctx isTextInputMenu
  -- Two calls rather than a wrapper chosen at run time, so the usual one
  -- runs the view as it is.
  let runPass inp = if menuOpen then unlift (runUi ctx inp (withTextEditMenu ui)) else unlift (runUi ctx inp ui)
  result0 <- runPass frameInp
  -- Pending click is one-shot. Clear before a rerun so toggles do not fire twice.
  writeIORef (ctxClickedId ctx) (WidgetId 0)
  rerun <- takeVarRerun ctx
  r <-
    if rerun
      then do
        resetUiBuild ctx False
        -- A modal is active only if this pass builds it.
        modifyOverlay ctx (\os -> os {osModalActive = False, osModalDepth = 0})
        beginVarPass ctx 2
        runPass (stripInteractionInput frameInp)
      else pure result0
  endVarFrame ctx
  pure r

-- | The view, then the open text-edit menu ('textEditMenuView'), which
-- belongs to no widget of the view.
{-# INLINE withTextEditMenu #-}
withTextEditMenu :: Eff (Ui : es) a -> Eff (Ui : es) a
withTextEditMenu ui = ui <* embedNanoUI textEditMenuView

-- | Settle pointer presses/releases, focus transitions, IME, text-edit menu,
-- and select dropdowns against the solved layout.
--
-- The steps run in this order because each reads what the ones before it
-- settled:
--
-- 1. The release step clears the active widget, which the press set before
--    the view from the layout the user saw ('pressTargets', which also
--    gives @targets@ for the focus steps).
-- 2. 'finalizeTextInputFocus' clears focus for a press outside every text
--    field, so 'finalizeSelectFocus' and 'finalizeDrawingFocus' after it can
--    give focus to the select or custom widget the press landed on.
-- 3. The text-edit menu steps close the menu on an outside press before a
--    right press opens it again, and take a pick before Escape closes it.
-- 4. 'finalizeFocusRequest' applies focus asked for from code after the
--    pointer has moved focus, so a request in the view wins over the press.
-- 5. 'constrainFocusToModal' then drops focus a modal hides or no widget
--    holds, before 'finalizeTabFocus' moves it, so Tab starts from a widget
--    that is there.
-- 6. The select steps act on the dropdown focus now points at.
-- 7. 'settleInputMethod' runs last: it moves the input-method request to
--    wherever focus ended up.
{-# INLINE finalizeFrameInput #-}
finalizeFrameInput ::
  Context -> Input -> Input -> PressTargets -> WidgetId -> IO ()
finalizeFrameInput ctx frameInp layerInp targets focusBefore = do
  finalizePointerRelease ctx layerInp
  disarmPointerPress ctx frameInp
  finalizeTextInputFocus ctx layerInp targets
  finalizeSelectFocus ctx targets
  finalizeDrawingFocus ctx targets
  finalizeScrollFocus ctx layerInp targets
  finalizeTextFieldMouse ctx layerInp (ptFieldControl targets)
  closeTextEditMenuOnOutsideClick ctx frameInp
  openTextEditMenu ctx layerInp
  closeTextEditMenuOnEscape ctx frameInp
  finalizeFocusRequest ctx
  constrainFocusToModal ctx
  finalizeTabFocus ctx frameInp
  finalizeSelectKeyboard ctx frameInp
  closeSelectOnOutsideClick ctx frameInp
  settleInputMethod ctx focusBefore

-- | The frame's draw data. A full frame with no damage whose 'DrawReuseKey'
-- (@key@) matches the last full frame's (@mayReuse@) returns the previous
-- frame's 'DrawData' without repainting: an idle continuous frame paints
-- nothing. Other frames paint, and a full frame caches its output for the
-- next. Paint that reads state nano-ui does not track must call 'damageFull'
-- when that state changes.
paintOrReuse :: Context -> Size -> Bool -> Bool -> Color -> DrawReuse -> Maybe DrawReuseKey -> Bool -> IO DrawData
paintOrReuse ctx size explain paintFull clear reuse key mayReuse = do
  damage <- getsDamage ctx dsDamage
  case drLast reuse of
    Just (_, lastDraw) | mayReuse && damageIsEmpty damage -> pure lastDraw
    _ -> do
      -- The kept draw borrows the draw arena's buffers, which paint
      -- overwrites: drop it first, so a paint that throws leaves none behind.
      when (isJust (drLast reuse)) $ writeIORef (ctxDrawReuse ctx) $! reuse {drLast = Nothing}
      drawData <- paintFrame ctx size explain paintFull clear
      -- Nothing to keep now or before: leave the state as it is.
      unless (isNothing key && isNothing (drLast reuse)) $
        writeIORef (ctxDrawReuse ctx) $! reuse {drLast = (\k -> (k, drawData)) <$!> key}
      pure drawData

-- | What a full frame's draw follows besides its damage ('DrawReuseKey'), or
-- 'Nothing' when it cannot be reused: paint builds a custom drawing on a
-- node that is not a drawing (a pane grid's focus ring) afresh, and no
-- damage says when it changes.
drawReuseKey :: Context -> Size -> Color -> IO (Maybe DrawReuseKey)
drawReuseKey ctx@Context {ctxNodeArena = na, ctxDrawArena = da} size clear = do
  offNode <- customDrawingOffNode ctx
  if offNode
    then pure Nothing
    else
      fmap Just $
        DrawReuseKey size
          <$> getDrawSnapScale da
          <*> readIORef (daSquareGeometry da)
          <*> readIORef (daExternalText da)
          <*> readIORef (ctxMetricGen ctx)
          <*> readIORef (ctxFocusId ctx)
          <*> readIORef (ctxFocusVisible ctx)
          <*> readIORef (ctxHotId ctx)
          <*> readIORef (ctxActiveId ctx)
          <*> getPaintSignature na
          <*> atlasToken (ctxImageAtlas ctx)
          <*> pure clear

-- | The colour of the page surface this frame: the root node's theme, so a
-- scope around the whole view applies, or the base theme's for an empty view.
framePageBackground :: Context -> IO Color
framePageBackground ctx = do
  base <- readIORef (ctxTheme ctx)
  n <- arenaCount (ctxNodeArena ctx)
  if n > 0
    then pageBackground <$> nodeTheme ctx 0
    else pure (pageBackground base)

-- | The colour a full frame clears to ('drawClear'): the page surface laid
-- over the window colour as the backends blend a draw, so an opaque page
-- replaces the window's and a translucent one tints it. The default page is
-- the window itself, so a translucent window keeps its own alpha.
frameClearColor :: Context -> IO Color
frameClearColor ctx = do
  page <- framePageBackground ctx
  window <- themeWindow <$> readIORef (ctxTheme ctx)
  pure (if page == window then window else blendOver page window)

-- | @top@ over @bottom@ with straight alpha, as SDL's and the GL backend's
-- blend lays a draw over the target: the colour mixed by the top's alpha,
-- and the alphas combined.
blendOver :: Color -> Color -> Color
blendOver top bottom = fadeAlpha (lerpColor bottom top ta) (round (255 * (ta + ba * (1 - ta))))
  where
    unit c = fromIntegral c / 255 :: Float
    ta = unit (colorA top)
    ba = unit (colorA bottom)

-- | Paint the frame. Clip frames repaint the damaged region of the retained
-- texture, which preserves the other pixels ('paintDamageClip'). Full-present
-- frames (fresh retain, forced full, continuous) paint everything.
paintFrame :: Context -> Size -> Bool -> Bool -> Color -> IO DrawData
paintFrame ctx size explain paintFull clear = do
  let da = ctxDrawArena ctx
  resetDrawArena da
  setDrawClear da clear
  beginLayer da LayerBackground
  unless paintFull $ do
    damage <- takeDamage ctx
    paintDamageClip da clear damage =<< takeDamagePieces ctx
  lowerShapes ctx
  -- Page outlines go above the page's scrollbars and below floating panels.
  when explain $ do
    beginLayer da LayerContent
    paintExplainPage ctx
  beginLayer da LayerOverlay
  drawFloatingPanels ctx size explain
  when explain (paintExplainHover ctx)
  finishDraw da

-- | Reset what a view run builds: the node arena, sensors, input method
-- request, and the container, id, focus, hover, cursor-zone, drawing and
-- layout-overlay scopes. A second run after a backwards Var write
-- (@newFrame@ 'False') keeps the store, animations, prev rects, and the
-- theme scopes it compares against.
--
-- Each 'Context' field this resets in full ends its Haddock with the
-- sentence "Reset by" and this function's qualified name. A field added
-- here gets that sentence and an entry in the nano-ui-test case
-- @per-build-reset@, which counts the sentences.
resetUiBuild :: Context -> Bool -> IO ()
resetUiBuild ctx newFrame = do
  beginThemeScopes ctx newFrame
  resetNodeArena (ctxNodeArena ctx)
  resetContainerStack (ctxContainerStack ctx)
  resetIdCursor (ctxIdCursor ctx)
  writePrimVar (ctxFocusablesCount ctx) 0
  -- The view re-requests the input method each run while a widget takes text.
  readIORef (ctxInputMethod ctx) >>= mapM_ (\_ -> writeIORef (ctxInputMethod ctx) Nothing)
  writeIORef (ctxHotId ctx) (WidgetId 0)
  writeIORef (ctxCursorZones ctx) []
  writeIORef (ctxCursorRegions ctx) []
  readIORef (ctxChildWindows ctx) >>= \ws -> unless (null ws) (writeIORef (ctxChildWindows ctx) [])
  resetDrawingScopeCache ctx
  -- The layout overlay's scopes are ranges of the arena just emptied.
  explain <- readIORef (ctxExplain ctx)
  unless (null (esScopes explain)) $ writeIORef (ctxExplain ctx) explain {esScopes = []}
  beginSensors ctx

-- | Paint the floating panels over the page: windows with their title-bar
-- separator, the modal backdrop and the modals, then popups. Each is a
-- menu-style panel in its node's theme with its subtree clipped inside.
-- With @explain@, the layout overlay's outlines are drawn over each.
drawFloatingPanels :: Context -> Size -> Bool -> IO ()
drawFloatingPanels ctx@Context {ctxNodeArena = na, ctxDrawArena = da} (Size ww wh) explain = do
  let panels nt after = forFloatingNodes_ na nt $ \idx -> do
        rect <- getNodeRect na idx
        theme <- nodeTheme ctx idx
        paintMenuPanel da theme (floatingSurface theme nt) rect
        withClip da rect (walkChildren ctx idx)
        after theme idx rect
        when explain (paintExplainLayer ctx idx)
      plain _ _ _ = pure ()
  panels NodeWindow $ \theme idx (Rect x y w _) -> do
    pad <- getPadding na idx
    let sepY = y + padT pad + windowTitleBarH - windowChromeSepH
        sepW = max 0 (w - padL pad - padR pad)
    pushRect da (Rect (x + padL pad) sepY sepW windowChromeSepH) (themeSeparator theme)
  whenM (isJust <$> topModalNode na) $ do
    theme <- readIORef (ctxTheme ctx)
    pushRect da (Rect 0 0 ww wh) (themeOverlayDim theme)
    panels NodeModal plain
  panels NodePopup plain

-- | Start a clip frame from the page surface, as a full frame lays it over the
-- window clear. Widgets with a transparent fill, such as an idle menu-bar
-- title, draw nothing over the pixels they covered, so without the backdrop a
-- hover that just ended would stay in the retain texture. Damage in pieces
-- paints a backdrop over each, and every command is cut to them. Each is
-- inflated by a logical pixel to cover the runner's outward snap. An empty clip
-- stays empty, so a frame with nothing damaged paints nothing.
paintDamageClip :: DrawArena -> Color -> Damage -> [Rect] -> IO ()
paintDamageClip _ _ DamageFull _ = pure ()
paintDamageClip da clear (DamageClip r) pieces = do
  let clip = if rectNonEmpty r then rectInflate 1 r else r
      pieceClips = map (rectInflate 1) pieces
      backdrops = if null pieces then [clip] else pieceClips
  setClip da clip
  setClipPieces da pieceClips
  when (rectNonEmpty r) $ mapM_ (flip (pushRect da) clear) backdrops

-- | Lay out the arena and place the floating panels over it. The cached solve
-- is restored when it was taken at this size and font generation and @check@
-- accepts it ('layoutReuseValid'); otherwise the arena is solved and the
-- result, before placement, captured for the next frame. The solve measures
-- only the nodes whose restore keys changed since the cache's capture; the
-- keys are folded here, so frames that reuse the whole layout never compute
-- them. A cache taken under other font metrics measured text differently, so
-- none of it is restored. Floating panels depend on state outside the arena
-- (window positions, popup anchors), so each is placed after the solve, or,
-- over a reused solve, restores the cached placement ('lcPlaced') when its
-- inputs are unchanged.
layoutArena :: Context -> Size -> Bool -> IO ()
layoutArena ctx@Context {ctxNodeArena = na} size@(Size w h) check = do
  let ms = contextMeasurers ctx
  gen <- readIORef (ctxMetricGen ctx)
  cached <- readIORef (ctxLayoutCache ctx)
  reused <- case cached of
    Just (c, cachedSize, cachedGen)
      | cachedSize == size && cachedGen == gen -> do
          ok <- if check then layoutReuseValid ctx c else pure True
          when ok (restoreLayoutCache na c)
          pure ok
    _ -> pure False
  unless reused $ do
    computeSubtreeHashes na
    measures <- solveLayout na ms w h $ case cached of
      Just (c, _, cachedGen) | cachedGen == gen -> Just c
      _ -> Nothing
    n <- arenaCount na
    if n <= 0
      then writeIORef (ctxLayoutCache ctx) Nothing
      else do
        c <- captureLayoutCache na =<< maybe (newLayoutCache 64) (\(old, _, _) -> pure old) cached
        -- The registered hooks, so reuse can tell when one appears or goes.
        hooks <- customMeasureHooks ctx
        let c' = c {lcMeasures = measures, lcMeasureHooks = hooks}
        writeIORef (ctxLayoutCache ctx) (Just (c', size, gen))
  floating <- floatingNodeCount na
  when (floating > 0) $ do
    -- Placing over a solve is kept once a frame reuses it: content that
    -- changes every frame solves every frame, and would keep what no frame
    -- puts back.
    placed <- if reused then fmap (\(c, _, _) -> lcPlaced c) <$> readIORef (ctxLayoutCache ctx) else pure Nothing
    placeFloatingNodesWith na ms w h (lookupWindowPos ctx) (lookupWindowSize ctx) (lookupPopupConfig ctx) (dropdownPlacement ctx size) placed

-- | Layout reuse is sound when the frame's layout inputs hash to what the
-- cache captured, the same widgets register custom measures, and every custom
-- measure still returns the sizes the captured solve recorded. The signature
-- covers the measure's declared inputs, but neither a hook's presence nor
-- what its closure reads is arena state, which only comparing the hooks and
-- running them again can check.
layoutReuseValid :: Context -> LayoutCache -> IO Bool
layoutReuseValid ctx@Context {ctxNodeArena = na} lc = do
  okSig <- layoutSigMatches na lc
  hooks <- customMeasureHooks ctx
  -- A matching signature means the same node count, so every recorded index
  -- is in range. Each recorded measure runs again and must match: the
  -- drawing node's measure as 'runCustomMeasure' records it.
  let measureOf idx = do
        nt <- getNodeType na idx
        if nt /= NodeDrawing
          then pure Nothing
          else do
            mFn <- lookupCustomMeasureAt ctx idx
            traverse (\fn -> runCustomMeasure na (ctxFontMetrics ctx) fn idx) mFn
      stable (idx, r) rest = measureOf idx >>= \c -> if c == Just r then placedStable idx >>= \ok -> if ok then rest else pure False else pure False
      -- The solve also ran the measure at the width the drawing was placed
      -- at, when that differs from its measured width ('drawingHeightAt'),
      -- and a closure reading outside state can answer differently there
      -- with the same answer at the offered width.
      placedStable idx = do
        hAx <- getHeightSizing na idx
        mFn <- lookupCustomMeasureAt ctx idx
        case mFn of
          Just fn | axTag hAx == SizingFit -> do
            measuredW <- readPrimArray (lcMeasured lc) (idx * 2)
            placedW <- readPrimArray (lcUnsnapped lc) (idx * 4 + 2)
            placedH <- readPrimArray (lcUnsnapped lc) (idx * 4 + 3)
            pure (placedW == measuredW || measuredHeightAt (ctxFontMetrics ctx) fn placedW hAx == placedH)
          _ -> pure True
  if not okSig || hooks /= lcMeasureHooks lc
    then pure False
    else foldr stable (pure True) (IM.toList (lcMeasures lc))