packages feed

nano-ui-0.2.0.0: lib/NanoUI/Internal/Context/Types.hs

{-# LANGUAGE StrictData #-}
{-# OPTIONS_HADDOCK not-home #-}

-- | Record types behind 'Context': interaction, damage, overlay, animation,
-- scroll and drawing-cache state, theme scopes, and frame messages.
module NanoUI.Internal.Context.Types
  ( Context (..)
  , GenCache (..)
  , emptyGenCache
  , insertGen
  , cachedGen
  , MeasureCache
  , WrapCache (..)
  , MetricSource (..)
  , TextInputMenu (..)
  , TextInputDrag (..)
  , TextFieldClickCell (..)
  , WindowResizeEdge (..)
  , WindowResizeDrag (..)
  , DamageRequest (..)
  , PressPoint (..)
  , DamageState (..)
  , initialDamageState
  , PrevFrame (..)
  , emptyPrevFrame
  , PrevWalk (..)
  , newPrevWalk
  , OverlayState (..)
  , initialOverlayState
  , ExplainState (..)
  , DrawReuse (..)
  , DrawReuseKey (..)
  , initialExplainState
  , ExplainedNode (..)
  , AnimationState (..)
  , initialAnimationState
  , ScrollTuning (..)
  , defaultScrollTuning
  , ScrollAxes (..)
  , ScrollGlide (..)
  , ScrollView (..)
  , ScrollState (..)
  , initialScrollState
  , DrawFitCache (..)
  , DrawingEntry (..)
  , DrawingCacheState (..)
  , NodeCustom (..)
  , noNodeCustom
  , customPassWords
  , PopupConfig (..)
  , DropdownPopup (..)
  , HoverZone (..)
  , DrawOpCacheEntry (..)
  , CustomDrawingEntry (..)
  , CustomDrawOpCacheEntry (..)
  , SpanCacheEntry (..)
  , SpanLines (..)
  , WidgetTextCacheEntry (..)
  , WidgetTextPlacement (..)
  , initialDrawingCacheState
  , InteractionState (..)
  , PointerRoute (..)
  , FocusKind (..)
  , KeyClaim (..)
  , InputMethodRequest (..)
  , FocusRequest (..)
  , initialInteractionState
  , CustomMeasureFn
  , CustomDrawContext (..)
  , CustomDrawBuild
  , ThemeScopes (..)
  , ContainerStack
  , newContainerStack
  , resetContainerStack
  , pushContainer
  , popContainer
  , peekContainer
  , readContainerStack
  , writeContainerStack
  , intKey
  , ChildWindow (..)
  ) where

import Control.Concurrent (ThreadId)
import NanoUI.Internal.Derived (DerivedCache)
import NanoUI.Internal.Resource (Held)
import NanoUI.Internal.Host (Host)
import NanoUI.Internal.BackendSession (SomeBackendSession)
import NanoUI.Internal.NativeWindow.Types (NativeWindow, WindowSettings)
import NanoUI.Internal.Sensor.Types (Sensors)
import NanoUI.Internal.RichText.Types (Paragraphs)
import Data.HashMap.Strict (HashMap)
import Data.HashMap.Strict qualified as HashMap
import Data.Hashable (Hashable)
import Data.IORef (IORef, modifyIORef', newIORef, readIORef, writeIORef)
import Data.IntMap.Strict (IntMap)
import Data.IntMap.Strict qualified as IM
import Data.IntSet (IntSet)
import Data.IntSet qualified as IS
import Data.Map.Strict (Map)
import Control.Monad (when)
import Data.Primitive.Array (MutableArray, newArray)
import Data.Primitive.PrimArray
  ( MutablePrimArray
  , getSizeofMutablePrimArray
  , newPrimArray
  , readPrimArray
  , resizeMutablePrimArray
  , writePrimArray
  )
import Data.Primitive.PrimVar (PrimVar, newPrimVar, readPrimVar, writePrimVar)
import Data.Primitive.SmallArray (SmallArray, SmallMutableArray)
import Data.Word (Word32, Word64)
import Data.Text (Text)
import GHC.Exts (RealWorld)

import NanoUI.Internal.Animation (Animation)
import NanoUI.Internal.Atlas (AtlasToken, ImageAtlas)
import NanoUI.Internal.Draw.Types (DrawArena, DrawData, DrawOp, DrawingBuild)
import NanoUI.Internal.Font (CustomMeasureFn, FontMetrics, WrapResult)
import NanoUI.Internal.Frame.SpanArena (SpanArena)
import NanoUI.Internal.Id (WidgetId, hashWidgetId)
import NanoUI.Internal.Id.Cursor (IdCursor)
import NanoUI.Internal.Var.Types (SlotVar, Var)
import NanoUI.Internal.Input (Composition, Input, InputPurpose, MouseButton, UiCursorKind)
import NanoUI.Internal.Shader (ShaderCapabilities, ShaderEffectEntry, ShaderNodeEntry)
import NanoUI.Internal.Shortcut (Shortcut)
import NanoUI.Internal.Layout.Arena (DirTag, LayoutCache, NodeArena)
import NanoUI.Internal.Store (WidgetStore)
import NanoUI.Internal.Style (Appearance, Direction, Flow, FontStyle, FontVariant, FontWeight, Layout, Padding, PointerMode, Sizing, Theme)
import NanoUI.Widgets.TextBuffer (Cursor)
import NanoUI.Widgets.TextCommand (TextCommand)
import NanoUI.Internal.Types

-- | Growable unboxed stack of open container node indices. Pushing and
-- popping allocate nothing in steady state.
data ContainerStack
  = ContainerStack
      !(IORef (MutablePrimArray RealWorld Int))
      {-# UNPACK #-} !(PrimVar RealWorld Int)

-- | Create an empty container stack with initial room for 32 nested levels.
newContainerStack :: IO ContainerStack
newContainerStack = ContainerStack <$> (newPrimArray 32 >>= newIORef) <*> newPrimVar 0

-- | Empty the container stack without releasing its backing buffer.
{-# INLINE resetContainerStack #-}
resetContainerStack :: ContainerStack -> IO ()
resetContainerStack (ContainerStack _ dep) = writePrimVar dep 0

{-# NOINLINE growContainerStack #-}
growContainerStack :: IORef (MutablePrimArray RealWorld Int) -> Int -> IO (MutablePrimArray RealWorld Int)
growContainerStack ref needed = do
  arr <- readIORef ref
  cap <- getSizeofMutablePrimArray arr
  let !newCap = max needed (cap * 2)
  grown <- resizeMutablePrimArray arr newCap
  writeIORef ref grown
  pure grown

-- | Push a container node index onto the stack.
{-# INLINE pushContainer #-}
pushContainer :: ContainerStack -> Int -> IO ()
pushContainer (ContainerStack bufRef depVar) !idx = do
  d <- readPrimVar depVar
  arr0 <- readIORef bufRef
  cap <- getSizeofMutablePrimArray arr0
  arr <- if d < cap then pure arr0 else growContainerStack bufRef (d + 1)
  writePrimArray arr d idx
  writePrimVar depVar (d + 1)

-- | Pop the innermost container node index.
{-# INLINE popContainer #-}
popContainer :: ContainerStack -> IO ()
popContainer (ContainerStack _ depVar) = do
  d <- readPrimVar depVar
  when (d > 0) $ writePrimVar depVar (d - 1)

-- | Innermost open container node index, or @-1@ when the stack is empty.
{-# INLINE peekContainer #-}
peekContainer :: ContainerStack -> IO Int
peekContainer (ContainerStack bufRef depVar) = do
  d <- readPrimVar depVar
  if d <= 0
    then pure (-1)
    else readIORef bufRef >>= \arr -> readPrimArray arr (d - 1)

-- | Snapshot the stack as a list, innermost first.
readContainerStack :: ContainerStack -> IO [Int]
readContainerStack (ContainerStack bufRef depVar) = do
  d <- readPrimVar depVar
  arr <- readIORef bufRef
  let go !i !acc
        | i >= d = pure acc
        | otherwise = do
            x <- readPrimArray arr i
            go (i + 1) (x : acc)
  go 0 []

-- | Replace the stack contents from a list ordered innermost first.
writeContainerStack :: ContainerStack -> [Int] -> IO ()
writeContainerStack (ContainerStack bufRef depVar) xs = do
  let rev = reverse xs
      !n = length rev
  arr0 <- readIORef bufRef
  cap <- getSizeofMutablePrimArray arr0
  arr <- if n <= cap then pure arr0 else growContainerStack bufRef n
  let fill !i [] = writePrimVar depVar i
      fill !i (x : rest) = writePrimArray arr i x >> fill (i + 1) rest
  fill 0 rev

-- | Themes the view's @styled@ scopes pushed this frame, and last frame's, to
-- tell whether a frame changed only how its scopes look. A node's scope holds
-- an index into 'tsThemes' plus one; index 0 is the context theme.
data ThemeScopes = ThemeScopes
  { tsCount :: {-# UNPACK #-} !Int
  , tsThemes :: !(SmallMutableArray RealWorld Theme)
  -- ^ What each scope is drawn with.
  , tsRaw :: !(SmallMutableArray RealWorld Theme)
  -- ^ Each scope's theme before a disabled scope faded it, which nested
  -- @styled@ scopes modify.
  , tsPrevCount :: {-# UNPACK #-} !Int
  , tsPrev :: !(SmallMutableArray RealWorld Theme)
  , tsDisabled :: !Bool
  -- ^ A disabled scope was entered this pass, so some widget may be disabled.
  , tsChanged :: !Bool
  -- ^ A pushed theme differs from the one at its index last frame.
  , tsPrevSig :: {-# UNPACK #-} !Word64
  -- ^ Last frame's scope signature ('NanoUI.Internal.Layout.Arena.getScopeSignature').
  }

-- | A memo table in two generations: the young map, its size, and the old
-- map. A full young map replaces the old one, so an entry that stops being
-- used (a clock's text, a log line) is dropped while one used every
-- generation stays. It is a cheap stand-in for least recently used: inserts
-- go to the young map and a hit in the old map moves the entry up, so an
-- entry survives however many one-off keys (wrap probes, table cells) pass
-- through. Plain insertion order evicted the oldest key even when every frame
-- used it. Hashing a text key once beats comparing it at every level of a
-- tree.
data GenCache k v = GenCache !(HashMap k v) !Int !(HashMap k v)

-- | A cache with both generations empty.
emptyGenCache :: GenCache k v
emptyGenCache = GenCache HashMap.empty 0 HashMap.empty

-- | Insert an entry of weight @w@ into a cache of @cap@ per generation. The
-- young map's size is the sum of its entries' weights; an entry heavier than
-- a whole generation is not kept.
{-# INLINE insertGen #-}
insertGen :: Hashable k => Int -> Int -> k -> v -> GenCache k v -> GenCache k v
insertGen cap w k v cache@(GenCache young n old)
  | w > cap = cache
  | n + w > cap = GenCache (HashMap.singleton k v) w young
  | otherwise = GenCache (HashMap.insert k v young) (n + w) old

-- | The entry for @k@, or what @make@ returns, which is kept. Entries weigh
-- @w k@; an old one used again moves to the young map. Inlined so a hit
-- returns the stored value without boxing it in a 'Just' on the way: the SDL
-- bench's warm-lookup gate measures exactly that.
{-# INLINE cachedGen #-}
cachedGen :: Hashable k => Int -> (k -> Int) -> IORef (GenCache k v) -> k -> IO v -> IO v
cachedGen cap w ref k make = do
  cache@(GenCache young _ old) <- readIORef ref
  case HashMap.lookup k young of
    Just v -> pure v
    Nothing -> case HashMap.lookup k old of
      Just v -> do
        writeIORef ref $! insertGen cap (w k) k v cache
        pure v
      Nothing -> do
        v <- make
        modifyIORef' ref (insertGen cap (w k) k v)
        pure v

-- | Memoised measurements by text and measurement scale.
type MeasureCache = GenCache (Text, Float) (Float, Float)

-- | Wrapped text by text and font ('NanoUI.Internal.WidgetText.textNodeFontKey'),
-- each with the widths it holds for, newest first, under the metric generation
-- the results were measured in.
data WrapCache = WrapCache !Int !(GenCache (Text, Int) [WrapResult])

-- | Identity of a font/measurement configuration. Pure Context modifiers
-- replace this value; the next frame invalidates shared caches if its identity
-- differs. Holding the current inputs (not a revision counter/history) also
-- distinguishes two differently configured Contexts derived from one parent.
data MetricSource
  = InitialMetricSource
  | MetricSource
      !FontMetrics
      !FontMetrics
      !(Text -> IO (Float, Float))
      !(Float -> FontWeight -> FontStyle -> FontVariant -> IO (FontMetrics, Bool))
      !(Float -> FontWeight -> FontStyle -> FontVariant -> Text -> IO (Float, Float))

-- | Where a button went down, in the frame the user saw.
data PressPoint = PressPoint
  { ppPos :: !V2
  , ppOwner :: !(Maybe WidgetId)
  -- ^ The widget the press reached, @WidgetId 0@ for a node that takes the
  -- pointer with no widget of its own, or 'Nothing' when it reached none:
  -- passive content, whose mouse area judges the press by its rect.
  , ppReached :: !IntSet
  -- ^ The keys of the reached node and its ancestors ('ppOwner'), which
  -- the press went down on: a left click belongs to these.
  }

-- | Explicit damage invalidation request queued during frame evaluation.
data DamageRequest
  = ReqWidget !WidgetId !DamageBounds      -- ^ Invalidate widget layout bounds (old & new)
  | ReqKey !Int !DamageBounds              -- ^ Invalidate widget bounds by integer key
  | ReqRect !Rect                          -- ^ Invalidate an explicit window-space rectangle
  | ReqPeers ![WidgetId] !DamageBounds     -- ^ Invalidate a collection of widgets
  | ReqFull                                -- ^ Force full window invalidation
  deriving (Eq, Show)

-- | The text field an open edit menu belongs to, the point the menu opened
-- at, and the rect its popup was drawn at (empty before it is drawn), in
-- logical window coordinates.
data TextInputMenu = TextInputMenu
  { textInputMenuWidget :: WidgetId
  , textInputMenuAt :: V2
  , textInputMenuRect :: Rect
  }
  deriving (Eq, Show)

-- | Selection-drag anchor, a position in the field's document (row 0 in a
-- single-line field). Click count selects character, word, or line selection
-- behaviour.
data TextInputDrag = TextInputDrag
  { textInputDragWidget :: WidgetId
  , textInputDragAnchor :: {-# UNPACK #-} !Cursor
  , textInputDragClicks :: {-# UNPACK #-} !Int
  }
  deriving (Eq, Show)

-- | Text position of the last click, used to group repeated clicks on one cell.
-- Positions are character indices, not UTF-8 byte offsets.
data TextFieldClickCell = TextFieldClickCell
  { textFieldClickWidget :: WidgetId
  , textFieldClickAt :: {-# UNPACK #-} !Cursor
  }
  deriving (Eq, Show)

-- | Edge or corner captured by a floating-window resize gesture, as the side
-- of each axis it moves, horizontal then vertical: -1 the left or top, 1 the
-- right or bottom, 0 neither.
data WindowResizeEdge = WindowResizeEdge Int Int
  deriving (Eq, Show)

-- | Resize gesture's initial pointer position, window bounds, and size limits.
-- All coordinates and lengths use logical pixels.
data WindowResizeDrag = WindowResizeDrag
  { wrdWidget :: WidgetId
  , wrdEdge :: WindowResizeEdge
  , wrdGrabX :: {-# UNPACK #-} !Float
  , wrdGrabY :: {-# UNPACK #-} !Float
  , wrdStartX :: {-# UNPACK #-} !Float
  , wrdStartY :: {-# UNPACK #-} !Float
  , wrdStartW :: {-# UNPACK #-} !Float
  , wrdStartH :: {-# UNPACK #-} !Float
  , wrdMinW :: {-# UNPACK #-} !Float
  , wrdMinH :: {-# UNPACK #-} !Float
  , wrdMaxW :: {-# UNPACK #-} !Float
  , wrdMaxH :: {-# UNPACK #-} !Float
  }
  deriving (Eq, Show)

-- | Frame scheduling and repaint state, including previous visible geometry
-- keyed by widget id. Dirty state and pixel damage are tracked separately.
data DamageState = DamageState
  { dsDirty :: !Bool
  , dsDamage :: !Damage
  , dsDamagePieces :: ![Rect]
  -- ^ Disjoint rects inside a 'DamageClip' that together hold all of its
  -- damage, when two or more are much smaller than the clip; otherwise empty,
  -- and the clip is the one piece.
  , dsRequests :: ![DamageRequest]
  , dsLastWindowSize :: !Size
  , dsPrev :: !PrevFrame
  , dsLayoutReads :: !(IntMap (IO Bool))
  -- ^ Layout queries recorded during the frame, by key, each with an action
  -- that checks after layout whether the read is stale
  -- ('NanoUI.Internal.Context.Core.recordLayoutRead').
  }

-- | The last finished frame's layout by widget key, for the next frame's
-- damage to diff against ('NanoUI.Internal.Damage.updatePrevRects').
data PrevFrame = PrevFrame
  { pfRects :: !(IntMap Rect)
  , pfClips :: !(IntMap Rect)
  -- ^ Viewport clip, for keys that have one.
  , pfOuterClips :: !(IntMap Rect)
  -- ^ Scroll containers and panels: the enclosing clip they paint in.
  -- 'pfClips' holds their inner content clip.
  , pfHashes :: !(IntMap Word64)
  -- ^ What the view gave each key's node that paint reads
  -- ('NanoUI.Internal.Layout.Arena.getNodePaintHash'): its text, value,
  -- style, colours, scope, image and options. A key whose hash changed is
  -- repainted.
  , pfEffectRects :: !(IntMap Rect)
  -- ^ Margin-expanded bounds of each active Tier 2 'NanoUI.withShader'
  -- container by widget key, so unmounting or shrinking a shader margin
  -- damages the full previous halo. Empty when no effects are active.
  }

-- | A 'PrevFrame' with no recorded nodes, as before the first frame.
emptyPrevFrame :: PrevFrame
emptyPrevFrame = PrevFrame IM.empty IM.empty IM.empty IM.empty IM.empty

-- | What the last completed 'NanoUI.Internal.Damage.updatePrevRects' walk
-- recorded at each arena index: the key and the rect, clip and paint hash it
-- gave the 'PrevFrame' maps. A node that has not changed since skips the
-- maps, which already hold its entries, and a widget declared where it was
-- reads its last rect here ('NanoUI.Internal.Context.Core.getPrevRectAt').
-- The first 'pwValid' indices hold the walk that built 'dsPrev' (its rects
-- are 'pwFor'); none do while a walk is under way. Updated in place, so a
-- frame allocates none of it.
data PrevWalk = PrevWalk
  { pwKeys :: !(MutablePrimArray RealWorld Int)
  -- ^ The node's key, or 0 where the walk made no entries.
  , pwTags :: !(MutablePrimArray RealWorld Int)
  -- ^ Whether the node has a clip.
  , pwRects :: !(MutableArray RealWorld Rect)
  -- ^ The node's rect, the object its 'pfRects' entry holds unless the
  -- entry was already equal.
  , pwClips :: !(MutablePrimArray RealWorld Float)
  -- ^ Four per index: the node's clip.
  , pwHashes :: !(MutablePrimArray RealWorld Word64)
  -- ^ The node's paint hash.
  , pwValid :: !(PrimVar RealWorld Int)
  -- ^ How many indices hold the walk: none while a walk is under way.
  , pwFor :: !(IORef (IntMap Rect))
  }

-- | Room for @n@ nodes, with no entries.
newPrevWalk :: Int -> IO PrevWalk
newPrevWalk n = do
  keys <- newZeroedPrimArray n
  tags <- newZeroedPrimArray n
  rects <- newArray n (Rect 0 0 0 0)
  clips <- newZeroedPrimArray (4 * n)
  hashes <- newZeroedPrimArray n
  PrevWalk keys tags rects clips hashes <$> newPrimVar 0 <*> newIORef IM.empty

-- | Require a first frame and full repaint, with no previous geometry.
initialDamageState :: DamageState
initialDamageState = DamageState
  { dsDirty = True
  , dsDamage = DamageFull
  , dsDamagePieces = []
  , dsRequests = []
  , dsLastWindowSize = Size 0 0
  , dsPrev = emptyPrevFrame
  , dsLayoutReads = IM.empty
  }

-- | Current modal nesting and previous floating-panel bounds/order used for
-- routing input before the next view is built.
data OverlayState = OverlayState
  { osModalWasActive :: {-# UNPACK #-} !Bool
  , osModalActive :: {-# UNPACK #-} !Bool
  , osModalDepth :: {-# UNPACK #-} !Int
  , osEscapeConsumed :: {-# UNPACK #-} !Bool
  , osTabConsumed :: {-# UNPACK #-} !Bool
  -- | Indices into the frame's 'NanoUI.Internal.Input.inputKeys' already
  -- taken by a shortcut, so no other shortcut acts on the same press.
  , osKeysTaken :: !IntSet
  , osPrevFloatingRects :: !(IntMap Rect)
  , osPrevFloatingOrder :: ![Int]
  }

-- | No modals, floating panels, or consumed key events.
initialOverlayState :: OverlayState
initialOverlayState = OverlayState
  { osModalWasActive = False
  , osModalActive = False
  , osModalDepth = 0
  , osEscapeConsumed = False
  , osTabConsumed = False
  , osKeysTaken = IS.empty
  , osPrevFloatingRects = IM.empty
  , osPrevFloatingOrder = []
  }

-- | The last full frame's draw data and what it was drawn from, reused when
-- a full frame would draw the same output ('NanoUI.Internal.Frame.runFrameEff').
-- A reused frame returns the same 'DrawData' buffers, so the host must treat
-- them as read-only.
data DrawReuse = DrawReuse
  { drOn :: !Bool
  -- ^ Whether frames may reuse a draw at all
  -- ('NanoUI.Internal.Context.setDrawReuse').
  , drLast :: !(Maybe (DrawReuseKey, DrawData))
  -- ^ The last frame's draw, while that frame painted in full and may be
  -- reused.
  }

-- | What a full frame's draw follows besides what its damage covers.
data DrawReuseKey = DrawReuseKey
  { drkSize :: !Size
  , drkSnapScale :: !Float
  , drkSquareGeometry :: !Bool
  , drkExternalText :: !Bool
  , drkMetricGen :: !Int
  , drkFocus :: !WidgetId
  , drkFocusVisible :: !Bool
  , drkHot :: !WidgetId
  , drkActive :: !WidgetId
  , drkArena :: !Word64
  -- ^ 'NanoUI.Internal.Layout.Arena.getPaintSignature'.
  , drkAtlas :: !AtlasToken
  , drkClear :: !Color
  -- ^ The frame's clear colour ('NanoUI.Internal.Draw.Types.drawClear'):
  -- the base theme's window colour is not in the arena's signature.
  }
  deriving (Eq)

-- | Layout overlay state ('NanoUI.Internal.Frame.Explain'): whether it is on,
-- and what the last frame drew, for the next frame to diff against.
data ExplainState = ExplainState
  { esOn :: !Bool
  , esLayers :: ![(Int, [(Rect, Rect, Int)])]
  -- ^ Outlines per layer in paint order: the page (key -1) first, then
  -- floating panels keyed by root node. Each outline is (rect, clip, depth).
  , esHover :: !(Maybe (ExplainedNode, Rect))
  -- ^ The node under the pointer and its highlight's clip.
  , esScopes :: ![(Int, Int)]
  -- ^ Arena index ranges [from, below) added by @explainScope@ this build.
  -- When non-empty, only these nodes are outlined. Subtrees are contiguous
  -- in the arena, so each range covers whole subtrees.
  }

-- | Overlay off.
initialExplainState :: ExplainState
initialExplainState = ExplainState {esOn = False, esLayers = [], esHover = Nothing, esScopes = []}

-- | The innermost node under the pointer in the topmost layer, while the
-- layout overlay is on. Holds the node's requested layout next to its
-- result, so a debug panel can explain its size.
data ExplainedNode = ExplainedNode
  { explainedKind :: !Text
  -- ^ Display name such as @Container@, @Text@ or @ScrollContainer@. A
  -- container adds its flow after commas: @Container, row@,
  -- @Container, layered@, @Container, row, wrap@.
  , explainedWidget :: !(Maybe WidgetId)
  -- ^ The owning widget ('NanoUI.respId'); 'Nothing' for id-less nodes such
  -- as spacers.
  , explainedDepth :: !Int
  -- ^ Nesting depth from the layer root (0). Picks the outline colour.
  , explainedRect :: !Rect
  -- ^ Laid-out rect in logical window coordinates, after scrolling.
  , explainedPadding :: !Padding
  , explainedWidth :: !Sizing
  , explainedHeight :: !Sizing
  , explainedMin :: !V2
  , explainedMax :: !V2
  -- ^ 1e8 or more means unbounded.
  , explainedGap :: !Float
  , explainedDirection :: !Direction
  -- ^ 'NanoUI.Column' for layered containers.
  , explainedFlow :: !Flow
  -- ^ 'NanoUI.Line' for non-containers, scroll containers and grids, which
  -- place children their own way.
  , explainedPin :: !(Maybe V2)
  -- ^ Pin offset ('NanoUI.pinAt').
  , explainedPointer :: !PointerMode
  -- ^ Effective mode: 'NanoUI.PointerPass' when inside a node that passes
  -- the pointer, otherwise the node's own.
  }
  deriving (Eq, Show)

-- | Running animations, settled values with their leases, and per-frame
-- keep-alive requests, keyed by widget or animation id.
data AnimationState = AnimationState
  { asAnimations :: !(IntMap Animation)
  , asAnimRest :: !(IntMap Float)
  -- ^ Settled nonzero values.
  , asRestHeld :: !IntSet
  -- ^ Resting keys read or set since the last sweep of 'asAnimRest'. The
  -- sweep keeps these and those of laid-out widgets, drops the rest, and
  -- starts the set again.
  , asRestFrames :: {-# UNPACK #-} !Int
  -- ^ Frames with resting values since the last sweep.
  , asAnimSettled :: {-# UNPACK #-} !Bool
  , asKeepAlive :: !IntSet
  -- ^ Keys whose perpetual animation a @keepAnimating@ call holds open.
  , asKeepTouched :: !IntSet
  -- ^ The keys that asked again this frame. A held key missing from it at
  -- the end of the frame lapses: its widget is no longer built, and nothing
  -- else would ever end its animation.
  , asViewAnims :: !IntSet
  -- ^ Keys of the running animations a view hook (@animate@, @animateTo@)
  -- read last frame.
  , asViewTouched :: !IntSet
  -- ^ Those it read this frame. One missing at the end of the frame rests at
  -- its value: nothing reads it any more, and it may never end by itself.
  }

-- | Empty animation maps with no pending animation frame.
initialAnimationState :: AnimationState
initialAnimationState = AnimationState
  { asAnimations = IM.empty
  , asAnimRest = IM.empty
  , asRestHeld = IS.empty
  , asRestFrames = 0
  , asAnimSettled = False
  , asKeepAlive = IS.empty
  , asKeepTouched = IS.empty
  , asViewAnims = IS.empty
  , asViewTouched = IS.empty
  }

-- | How far one wheel notch scrolls, and how long a scroll takes to settle.
-- One setting for the whole context; a single scroller can take its own step
-- (see @setScrollStep@).
data ScrollTuning = ScrollTuning
  { scrollWheelStep :: Float
  -- ^ Pixels one wheel notch scrolls. The default, 60 logical pixels, is
  -- about three text lines, which is what Windows and most desktops send a
  -- notch as.
  , scrollSmoothTime :: Float
  -- ^ Seconds a scroll takes to cover most of the distance to its target.
  -- @0@ (the default) lands on it in the same frame.
  }
  deriving (Eq, Show)

-- | Immediate scrolling by 60 logical pixels per wheel step. An app may set a
-- font-relative step ('NanoUI.setScrollTuning').
defaultScrollTuning :: ScrollTuning
defaultScrollTuning =
  ScrollTuning
    { scrollWheelStep = 60
    , scrollSmoothTime = 0
    }

-- | Which axes a scroller moves on, and how an offset in window axes (x
-- rightwards, y downwards) maps onto its stored offset. A 1D row scroller
-- keeps its offset in the main-axis slot, so its horizontal offset is the one
-- that needs swapping.
data ScrollAxes
  = ScrollAxisY
  | ScrollAxisX
  | ScrollAxisXY
  deriving (Eq, Show, Enum)

-- | A scroller on its way to an offset it has not reached yet. The target is
-- in window axes and already clamped to the scroller's range.
data ScrollGlide = ScrollGlide
  { sgWidget :: WidgetId
  , sgTarget :: V2
  , sgAxes :: ScrollAxes
  }
  deriving (Eq, Show)

-- | Where the last layout placed a scroller: its viewport in window
-- coordinates, and the offset, in window axes, its content was placed at.
data ScrollView = ScrollView
  { svViewport :: !Rect
  , svPlaced :: !V2
  }
  deriving (Eq, Show)

-- | Context-wide scroll tuning, active glides, and geometry-publication keys.
data ScrollState = ScrollState
  { ssTuning :: !ScrollTuning
  , ssGlides :: !(IntMap ScrollGlide)
  , ssCached :: !IntSet
  -- ^ Scrollers whose geometry has been published this frame. Two scroll
  -- nodes can share a widget id (a table's frozen pane and its body), and
  -- without this the second would overwrite the first every frame, churning
  -- the store and flipping the geometry the commands read.
  , ssViews :: !(IntMap ScrollView)
  -- ^ Each scroller's last placement. Kept out of the store: a nested
  -- scroller's viewport moves whenever one around it scrolls, and a store
  -- change would keep that frame from repainting as a scroll.
  }

-- | Default tuning with no glides or published scroller geometry.
initialScrollState :: ScrollState
initialScrollState =
  ScrollState
    { ssTuning = defaultScrollTuning
    , ssGlides = IM.empty
    , ssCached = IS.empty
    , ssViews = IM.empty
    }

-- | Drawing's fitted layout keyed by envelope size, line height, content key,
-- and the caller's input layout.
data DrawFitCache = DrawFitCache
  { dfcDw :: {-# UNPACK #-} !Double
  , dfcDh :: {-# UNPACK #-} !Double
  , dfcLh :: {-# UNPACK #-} !Float
  , dfcContent :: {-# UNPACK #-} !Int
  , dfcIn :: !Layout
  , dfcOut :: !Layout
  }

-- | Cached text-span layout for one arena node. Key fields are every input
-- that changes the produced spans; 'sceSpans' is the shared result. The whole
-- cache is dropped on theme or font-scale changes.
data SpanCacheEntry = SpanCacheEntry
  { sceText :: !Text
  , sceFg :: {-# UNPACK #-} !Color
  , sceBg :: {-# UNPACK #-} !Color
  , sceStyle :: {-# UNPACK #-} !Word64
  , sceFontSize :: {-# UNPACK #-} !Float
  , sceAlign :: {-# UNPACK #-} !Int
  , sceWidthTag :: {-# UNPACK #-} !Int
  , sceRect :: !Rect
  , sceLaidW :: {-# UNPACK #-} !Float
  -- ^ The width the lines were wrapped for ('GeomLaidW').
  , sceEffMaxW :: {-# UNPACK #-} !Float
  , sceRowChild :: {-# UNPACK #-} !Bool
  , sceInset :: {-# UNPACK #-} !Float
  , sceFont :: !FontMetrics
  -- ^ The font the text is set in.
  , sceLines :: !SpanLines
  -- ^ The text laid out for the rect's width, before it is placed, so a node
  -- that only moved places the same lines again.
  , sceSpans :: ![(Rect, Text, Color, Color)]
  }

-- | A text node's lines for its width, with the metrics prepared for each.
data SpanLines
  = SpanWrapped ![(Text, FontMetrics)]
  -- ^ Wrapped lines, stacked from the node's top.
  | SpanSingle !Text !FontMetrics
  -- ^ One line, possibly truncated, centred in the node's height.

-- | A cacheable widget label is a single line (or absent for close buttons).
-- Coordinates are relative to the node origin; paint translates them without
-- rebuilding a list or invalidating the cache when a widget scrolls.
data WidgetTextPlacement = WidgetTextPlacement
  !Text
  {-# UNPACK #-} !Float
  {-# UNPACK #-} !Float
  {-# UNPACK #-} !Float
  {-# UNPACK #-} !Float

-- | Widget-label measurement inputs and optional node-relative placement.
-- Position is excluded so scrolling can reuse the measurement.
data WidgetTextCacheEntry = WidgetTextCacheEntry
  { wtcNodeType :: {-# UNPACK #-} !Int
  , wtcStyle :: {-# UNPACK #-} !Word64
  , wtcFontSize :: {-# UNPACK #-} !Float
  , wtcText :: !Text
  , wtcWidth :: {-# UNPACK #-} !Float
  , wtcHeight :: {-# UNPACK #-} !Float
  , wtcAlign :: {-# UNPACK #-} !Int
  , wtcPlacement :: {-# NOUNPACK #-} !(Maybe WidgetTextPlacement)
  }

-- | Interaction and styling snapshot supplied to a custom widget's painter.
-- Theme includes scoped/disabled styling; font metrics describe its text.
data CustomDrawContext = CustomDrawContext
  { cdcHovered  :: {-# UNPACK #-} !Bool
    -- ^ The pointer is over the widget, which is enabled.
  , cdcPressed  :: {-# UNPACK #-} !Bool
    -- ^ The left button went down on the widget, which is enabled, and is
    -- still held. When drawing, this holds wherever the pointer goes; in
    -- 'NanoUI.Widgets.Custom.widgetInteract', only while it is over the widget.
  , cdcFocused  :: {-# UNPACK #-} !Bool
    -- ^ The widget has keyboard focus.
  , cdcActive   :: {-# UNPACK #-} !Bool
    -- ^ The widget holds the left press wherever the pointer goes, even when
    -- disabled. In 'NanoUI.Widgets.Custom.widgetInteract' it is set from the
    -- frame after the press.
  , cdcDisabled :: {-# UNPACK #-} !Bool
    -- ^ The widget is in a disabled scope.
  , cdcTheme    :: !Theme
  , cdcFont     :: !FontMetrics
  }

-- | Pure draw-op builder for a solved rectangle in logical window coordinates.
-- Include changing external inputs in the widget's content key when caching.
type CustomDrawBuild = CustomDrawContext -> Rect -> SmallArray DrawOp

-- | A registered custom drawing: its content key plus the op builder. A
-- non-zero key is the author's promise that the ops follow it, so a frame
-- whose key is unchanged neither rebuilds nor repaints them. Key 0 means the
-- drawing carries no key and is rebuilt every frame and compared.
data CustomDrawingEntry = CustomDrawingEntry
  { cdrContent :: {-# UNPACK #-} !Int
  , cdrBuild :: !CustomDrawBuild
  , cdrCursor :: !(Maybe (CustomDrawContext -> Rect -> V2 -> UiCursorKind))
    -- ^ Cursor for a given widget rect and pointer position.
  , cdrDamageSlop :: {-# UNPACK #-} !Float
    -- ^ Repaint margin in logical pixels; anything but a positive value
    -- leaves the default margin in place.
  , cdrTracked :: !Bool
    -- ^ Whether pointer motion over the widget always schedules a frame.
  , cdrKeys :: !KeyClaim
    -- ^ The widget's actual claims, rather than a lossy style-index encoding.
  }

-- | A registered drawing: content version plus the op builder. The version
-- participates in the draw-op cache key, so a builder whose output changes
-- without its size changing must bump the version to invalidate.
data DrawingEntry = DrawingEntry
  { deContent :: {-# UNPACK #-} !Int
  , deBuild :: !DrawingBuild
  }

-- | What a node registered in this view pass ('ctxNodeCustom'): its
-- drawing, its custom drawing and its custom measure. Entries are kept for
-- the arena epoch ('NanoUI.Internal.Layout.Arena.naEpoch') they were
-- written in, so the arena's reset empties every one without a write.
data NodeCustom = NodeCustom
  { ncEpoch :: {-# UNPACK #-} !Word32
  , ncDrawing :: !(Maybe DrawingEntry)
  , ncCustom :: !(Maybe CustomDrawingEntry)
  , ncMeasure :: !(Maybe CustomMeasureFn)
  , ncShader :: !(Maybe ShaderNodeEntry)
  , ncEffect :: !(Maybe ShaderEffectEntry)
  }

-- | No registrations, in no epoch.
noNodeCustom :: NodeCustom
noNodeCustom = NodeCustom 0 Nothing Nothing Nothing Nothing Nothing

-- | Words of 'ctxCustomPass': whether a custom drawing was registered on a
-- node that is no drawing (0 or 1), a signature of the nodes that registered
-- a custom measure, and how many drawings and custom drawings registered.
customPassWords :: Int
customPassWords = 4

-- | Compiled-op and layout caches of the drawings, by widget key, kept
-- across frames. Registrations themselves are per node ('ctxNodeCustom').
data DrawingCacheState = DrawingCacheState
  { dcsPopupConfigs :: !(IntMap PopupConfig)
  , dcsDropdowns :: !(IntMap DropdownPopup)
  -- ^ Dropdown popups by key: placed by their field's rect this frame
  -- rather than by an anchor.
  , dcsDrawOpCache :: !(IntMap DrawOpCacheEntry)
  , dcsCustomDrawOpCache :: !(IntMap CustomDrawOpCacheEntry)
  , dcsDrawFitCache :: !(IntMap DrawFitCache)
  , dcsHoverZones :: ![HoverZone]
  -- ^ Tooltip targets: entering or leaving them needs a frame even when the
  -- hover probe finds no widget there.
  }

-- | What the view drew a dropdown popup from.
data DropdownPopup = DropdownPopup
  { dpField :: !WidgetId
  -- ^ The select or combo box the dropdown belongs to.
  , dpPicked :: {-# UNPACK #-} !Int
  -- ^ The row drawn picked: the select's value, or the combo's highlight
  -- within its window; -1 for none.
  , dpCombo :: !Bool
  , dpScrollX :: {-# UNPACK #-} !Float
  -- ^ How far a combo's rows are scrolled left.
  }

-- | A rect whose enter and exit need a frame. The flag is set when every
-- move inside also needs one (an open tooltip that follows the pointer).
data HoverZone = HoverZone {-# UNPACK #-} !Rect !Bool

-- | Strict cache entry for a popup's anchor configuration.
data PopupConfig = PopupConfig
  { pcAnchor :: !PopupAnchor
  , pcPlacement :: !PopupPlacement
  , pcOffset :: {-# UNPACK #-} !Float
  }

-- | Strict cache entry for a drawing's compiled draw ops.
data DrawOpCacheEntry = DrawOpCacheEntry
  { doeContent :: {-# UNPACK #-} !Int
  , doeBounds :: !Rect
  , doeOps :: !(SmallArray DrawOp)
  }

-- | Strict cache entry for a custom drawing's compiled draw ops. The key is
-- the content key, the rect, the interaction state the draw context exposes,
-- and the metric generation, which a base theme or font change bumps. A theme
-- scope change bumps nothing: the frame empties the cache instead.
data CustomDrawOpCacheEntry = CustomDrawOpCacheEntry
  { cdeContent :: {-# UNPACK #-} !Int
  , cdeBounds :: !Rect
  , cdeHovered :: {-# UNPACK #-} !Bool
  , cdePressed :: {-# UNPACK #-} !Bool
  , cdeFocused :: {-# UNPACK #-} !Bool
  , cdeActive :: {-# UNPACK #-} !Bool
  , cdeDisabled :: {-# UNPACK #-} !Bool
  , cdeGen :: {-# UNPACK #-} !Int
  , cdeOps :: !(SmallArray DrawOp)
  }

-- | No registered drawings, popup configurations, or cached results.
initialDrawingCacheState :: DrawingCacheState
initialDrawingCacheState = DrawingCacheState
  { dcsPopupConfigs = IM.empty
  , dcsDropdowns = IM.empty
  , dcsDrawOpCache = IM.empty
  , dcsCustomDrawOpCache = IM.empty
  , dcsDrawFitCache = IM.empty
  , dcsHoverZones = []
  }

-- | Target layer for a frame's pointer events (press, drag, release, wheel,
-- and hover), selected before the view runs from the topmost layer under the
-- pointer (or retained while a button is held). Other layers receive
-- 'NanoUI.Internal.Input.withoutPointer'.
data PointerRoute
  = -- | The widgets of one layer: 0 is the page, anything else the key of the
    -- floating panel (window, popup or modal) on top under the pointer.
    RouteLayer !Int
  | -- | The popup of an open select or combo dropdown, by key: its own
    -- layer gets the pointer, and the page's pointer steps see none of it,
    -- as for a menu ('NanoUI.Internal.Context.registerDropdownPopup').
    RouteDropdown !Int
  deriving (Eq, Show)

-- | Pointer route and active drag/menu gestures shared by the view and frame passes.
data InteractionState = InteractionState
  { isScrollDrag :: !(Maybe (WidgetId, DirTag, Float))
  -- | The scrollbar under the pointer, or whose thumb is being dragged: its
  -- scroller's id, its axis and its track. Its thumb paints brighter.
  , isScrollHover :: !(Maybe (WidgetId, DirTag, Rect))
  , isTextInputDrag :: !(Maybe TextInputDrag)
  , isTextFieldClickCell :: !(Maybe TextFieldClickCell)
  , isTextInputMenu :: !(Maybe TextInputMenu)
  , isTextEditLastAction :: !(Maybe (WidgetId, TextCommand))
  , isPointerRoute :: !PointerRoute
  -- | A button was down when the route was last decided, so it stands.
  , isPointerHeld :: {-# UNPACK #-} !Bool
  , isWindowDrag :: !(Maybe (WidgetId, Float, Float))
  , isWindowResize :: !(Maybe WindowResizeDrag)
  -- | A table header is resizing a column. Set by the table on the frames it
  -- does, cleared on mouse release.
  , isColumnResize :: {-# UNPACK #-} !Bool
  -- | Kind of the focused widget at frame start.
  , isFocusKind :: !FocusKind
  -- | The focused widget at frame start is a combo box showing its list (a
  -- text input carrying options), which closes on Escape. Read from last
  -- frame's nodes, like 'isFocusKind', so the view can ask before the combo
  -- is declared.
  , isFocusCombo :: !Bool
  -- | This frame's IME composition and the text field showing it (widget id
  -- 0 when unclaimed). See 'NanoUI.Internal.Frame.TextInput.claimComposition'.
  , isComposition :: !(Maybe (Composition, WidgetId))
  }
  deriving (Eq, Show)

-- | Kind of the focused widget, read from last frame's nodes before the view
-- runs. Shortcuts skip the keys it claims ('NanoUI.Internal.Widgets.Shortcut').
data FocusKind
  = FocusNone
  | -- | A control and the keys it claims. A text area claims 'KeysType'.
    FocusControl !KeyClaim
  | -- | A single-line text field: 'KeysType' plus Enter.
    FocusTextLine
  | -- | A read-only selectable text: caret motion, select-all and copy.
    FocusTextSelectable
  | -- | A text field with an active IME composition or commit this frame.
    -- The keys belong to the IME, so it claims every key and its typed
    -- text regardless of modifiers.
    FocusComposing
  deriving (Eq, Show)

-- | A focus move requested by the view: a widget, the next or previous Tab
-- stop, or no focus.
data FocusRequest = FocusOn !WidgetId | FocusNext | FocusPrevious | FocusNowhere
  deriving (Eq, Show)

-- | A widget taking IME text this frame. The caret is in window coordinates;
-- 'Nothing' for a text field, whose caret the frame derives from its node.
data InputMethodRequest = InputMethodRequest
  { imrWidget :: !WidgetId
  , imrCaret :: !(Maybe Rect)
  , imrPurpose :: !InputPurpose
  }
  deriving (Eq, Show)

-- | Keys a focused control handles itself, which shortcuts and key listeners
-- ('NanoUI.keyPressed') then skip. Enter, Space and arrows are claimed only
-- bare or with Shift ('NanoUI.Internal.Input.shiftAtMost'); with Ctrl, Alt
-- or Super they stay chords for shortcuts.
data KeyClaim
  = -- | Enter, Space, arrows, Home, End, Page Up, Page Down: a slider, list
    -- or select.
    KeysNavigate
  | -- | Enter and Space: a button, checkbox or switch.
    KeysActivate
  | -- | Multi-line text field: typing keys plus editing keys and shortcuts,
    -- under any modifiers.
    KeysType
  | -- | Every key: a terminal, or an editor with its own chords. Tab too,
    -- which then does not move focus off the widget.
    KeysAll
  | -- | No keys: focus alone does not reserve application shortcuts.
    KeysNone
  | -- | Read-only text selection: movement, select-all and copy, but no edits.
    KeysReadOnly
  | -- | Exactly these chords, including their modifiers. A chord without a
    -- key claims nothing. Presets remain available for ordinary controls.
    KeysOnly ![Shortcut]
  deriving (Eq, Show)

-- | Pointer routed to the page, with no held gesture, menu, or pending edit command.
initialInteractionState :: InteractionState
initialInteractionState = InteractionState
  { isScrollDrag = Nothing
  , isScrollHover = Nothing
  , isTextInputDrag = Nothing
  , isTextFieldClickCell = Nothing
  , isTextInputMenu = Nothing
  , isTextEditLastAction = Nothing
  , isPointerRoute = RouteLayer 0
  , isPointerHeld = False
  , isWindowDrag = Nothing
  , isWindowResize = Nothing
  , isColumnResize = False
  , isFocusKind = FocusNone
  , isFocusCombo = False
  , isComposition = Nothing
  }

-- | Mutable state for one UI session. Construct with @newContext@ and use it
-- serially on the UI thread. Record copies share arenas, stores, and IORefs;
-- a font-configured copy is not an independent session.
--
-- A field whose comment ends with the tag sentence naming
-- @resetUiBuild@ holds what one view run builds:
-- that function writes the field's initial value before each run. The
-- nano-ui-test case @per-build-reset@ checks each tagged field and fails
-- when the number of tags here differs from the fields it checks.
data Context = Context
  { ctxNodeArena :: NodeArena
  -- ^ The nodes the view declares, which layout solves and the paint pass
  -- walks. Reset by @resetUiBuild@.
  , ctxDrawArena :: DrawArena
  -- ^ The frame's draw commands and vertices, emptied before each paint.
  , ctxHotId :: IORef WidgetId
  -- ^ The widget under the pointer after this frame's layout
  -- ('NanoUI.Internal.Frame.Input.refreshHover'), or @WidgetId 0@ for none.
  -- It is @WidgetId 0@ while the view runs, and the paint pass and the
  -- draw-reuse key read it. Reset by @resetUiBuild@.
  , ctxLastHotId :: IORef WidgetId
  -- ^ The same widget as 'ctxHotId', kept through the next view run: the
  -- next 'NanoUI.Internal.Frame.Input.refreshHover' compares against it to
  -- start hover fades, and the idle check probes the pointer against it.
  -- | 'intKey's of the topmost pointer-taking node under the pointer and its
  -- ancestors, in the frame the user saw
  -- ('NanoUI.Internal.Frame.Input.recordCoveredWidgets'). Other nodes under
  -- the pointer are covered by layers or pins and get no pointer this view
  -- ('NanoUI.Internal.Context.Core.pointerCovered'). 'Nothing' when nothing
  -- is covered.
  , ctxPointerReach :: !(IORef (Maybe IntSet))
  , ctxActiveId :: IORef WidgetId
  -- ^ The widget holding the left button: set on a press before the view
  -- ('NanoUI.Internal.Frame.Input.armPointerTarget') or by a drag, and
  -- cleared to @WidgetId 0@ on the release
  -- ('NanoUI.Internal.Frame.Input.finalizePointerRelease'). While it is set,
  -- no other widget is hovered.
  , ctxClickedId :: IORef WidgetId
  -- ^ A click the view missed: a release on the active widget's solved rect
  -- that its last-frame rect did not contain. The widget reports it on the
  -- next view run ('NanoUI.Internal.Widgets.Node.resolveInteraction'),
  -- which clears it after the first pass.
  -- | The press of each held button, updated on press and release
  -- ('NanoUI.Internal.Frame.Input.armPointerPress'). Clicks and holds belong
  -- to the widget pressed, so widgets check this as well as the pointer. A
  -- button with no entry (release without a press) is judged alone.
  , ctxPressPos :: IORef (Map MouseButton PressPoint)
  , ctxFocusId :: IORef WidgetId
  -- ^ The widget with keyboard focus, or @WidgetId 0@ for none.
  -- | Focus last moved by keyboard or code, so the focused widget shows its
  -- ring. A pointer press hides it.
  , ctxFocusVisible :: IORef Bool
  -- | Focus move requested this frame ('NanoUI.Internal.Monad.requestFocus'),
  -- applied after layout ('NanoUI.Internal.Frame.Input.finalizeFocusRequest').
  , ctxFocusRequest :: IORef (Maybe FocusRequest)
  -- | The focused widget's IME request from the last view run
  -- ('NanoUI.Internal.Context.requestInputMethod'); reset each build. The
  -- next frame routes the composition to it
  -- ('NanoUI.Internal.Frame.TextInput.claimComposition'), and backends read
  -- the text input area from it ('NanoUI.Internal.Frame.TextArea.textInputArea').
  -- Reset by @resetUiBuild@.
  , ctxInputMethod :: !(IORef (Maybe InputMethodRequest))
  , ctxStore :: IORef WidgetStore
  , ctxDamageState :: IORef DamageState
  , ctxPrevWalk :: !(IORef PrevWalk)
  , ctxStoreOwners :: !(IORef (IntMap Int))
  -- ^ The widget key that owns each sub-slot store key the damage pass has
  -- resolved ('NanoUI.Internal.Damage.storeKeyChanges'). A sub-slot key is
  -- a hash of its widget's key, so an owner found once stays the owner.
  , ctxOverlayState :: IORef OverlayState
  , ctxAnimationState :: IORef AnimationState
  , ctxScrollState :: !(IORef ScrollState)
  , ctxDrawingCache :: IORef DrawingCacheState
  , ctxNodeCustom :: !(IORef (MutableArray RealWorld NodeCustom))
  -- ^ Each node's registrations ('NodeCustom'), by arena index.
  , ctxCustomPass :: !(MutablePrimArray RealWorld Word64)
  -- ^ The view pass's registration totals ('customPassWords').
  , ctxIdCursor :: !IdCursor
  -- ^ The id path and sibling position the next declared widget takes its
  -- id from. Starts at 'NanoUI.Internal.Id.initialIdContext'. Reset by
  -- @resetUiBuild@.
  , ctxVarFrame :: !(MutablePrimArray RealWorld Word64)
  -- ^ Var bookkeeping for the frame being built: current pass tick, frame
  -- base tick, pass number, flags, and the passes the last frame ran
  -- ("NanoUI.Internal.Var").
  , ctxVarSlots :: !(IORef (IntMap SlotVar))
  -- ^ Positional Vars ('NanoUI.Var.useVar'), by Var key.
  , ctxFontMetrics :: FontMetrics
  -- ^ Base proportional-font metrics used by layout and drawing.
  , ctxMonoFontMetrics :: FontMetrics
  , ctxFontSize :: !Float
  -- ^ Backend default text size, used when a layout sets none. Same units
  -- as 'NanoUI.fontSize'.
  , ctxMeasureText :: Text -> IO (Float, Float)
  , ctxResolveFont :: !(Float -> FontWeight -> FontStyle -> FontVariant -> IO (FontMetrics, Bool))
  , ctxResolveMeasure :: !(Float -> FontWeight -> FontStyle -> FontVariant -> Text -> IO (Float, Float))
  , ctxMeasureCache :: Maybe (IORef MeasureCache)
  , ctxWrapCache :: !(IORef WrapCache)
  -- ^ Wrapped text, shared by the solve and the text spans across frames.
  -- See 'NanoUI.Internal.Context.cachedWrapText'.
  , ctxSpanCache :: !(IORef (IntMap SpanCacheEntry))
  , ctxWidgetTextCache :: !(IORef (IntMap WidgetTextCacheEntry))
  -- | What widgets derive from their arguments and keep between frames
  -- (a table's column widths and sort), by widget key. It is not state, so
  -- a write neither damages nor wakes the loop. Cleared with the text caches.
  , ctxDerivedCache :: !(IORef DerivedCache)
  , ctxHeld :: !Held
  , ctxNativeWindow :: !(Host NativeWindow)
  , ctxBackendSession :: !(Host SomeBackendSession)
  -- ^ What the backend driving this context keeps for its session
  -- ('NanoUI.Internal.Context.withBackendSession').
  , ctxSensors :: !(Host Sensors)
  , ctxParagraphs :: !(Host Paragraphs)
  , ctxSvgRasters :: !(IORef (Map (Int, Int, Int, Word32, (Int, Int, Int, Int)) (ImageId, Int, PrimVar RealWorld Int)))
  -- ^ SVG rasters by document, pixel size, colour and content rect (in
  -- eighths of a raster pixel), with the atlas's release count
  -- ('NanoUI.Internal.Atlas.atlasReleases') when each was made and the frame
  -- that last drew it. One no frame drew since the one before gives its room
  -- to the next raster made; one the atlas had no room for is kept as id 0
  -- until an image leaves the atlas.
  , ctxLayoutCache :: !(IORef (Maybe (LayoutCache, Size, Int)))
  -- ^ Whole-layout reuse cache: cached signature and solved rects,
  -- with the window size and font/theme generation it was captured under.
  , ctxMetricGen :: !(IORef Int)
  , ctxMetricSource :: {-# NOUNPACK #-} !MetricSource
  , ctxLastMetricSource :: !(IORef (Maybe MetricSource))
  -- | True when the next present must repaint the whole window (fresh retain
  -- texture, forced full, continuous present, or window expose). When False,
  -- a DamageClip frame culls the paint pass to the damaged region. A backend
  -- that sets it clears the target to the frame's
  -- 'NanoUI.Internal.Draw.Types.drawClear' (the page surface laid over
  -- 'NanoUI.themeWindow') before it draws the frame; the frame paints that
  -- colour as the clip backdrop otherwise.
  , ctxPaintFull :: !(IORef Bool)
  , ctxDrawReuse :: !(IORef DrawReuse)
  -- | Whether the host reads this frame's damage
  -- ('NanoUI.Internal.Context.Core.takeDamage'). A host that repaints the
  -- whole window whatever changed (a continuous session) clears it, and the
  -- frame reports 'DamageFull' without diffing anything, unless it may reuse
  -- the last frame's draw ('ctxDrawReuse'), which needs to know that nothing
  -- is damaged. A host that clears it while 'ctxPaintFull' is off gets
  -- 'DamageFull' too, so its clip frames repaint the whole window. True by
  -- default.
  , ctxDamageWanted :: !(IORef Bool)
  -- | Layout overlay state. Its 'esScopes' are ranges of this run's node
  -- arena. Reset by @resetUiBuild@.
  , ctxExplain :: !(IORef ExplainState)
  , ctxTheme :: !(IORef Theme)
  -- ^ Base theme; scoped themes live in 'ctxThemeScopes'.
  , ctxThemeScopes :: !(IORef ThemeScopes)
  , ctxSystemAppearance :: !(IORef (Maybe Appearance))
  -- ^ Last system light/dark preference reported by the backend; 'Nothing'
  -- when unknown.
  , ctxThemeFor :: !(IORef (Maybe (Maybe Appearance -> Theme)))
  -- ^ Base theme per system appearance when following the system
  -- ('NanoUI.Internal.Context.followSystemTheme'); 'Nothing' for a fixed
  -- base theme.
  , ctxContainerStack :: !ContainerStack
  -- ^ Node indices of the containers open at this point of the view,
  -- innermost first; a widget's parent is the head. Reset by
  -- @resetUiBuild@.
  , ctxFocusables :: IORef (MutablePrimArray RealWorld WidgetId)
  -- ^ The run's focus order ('NanoUI.Internal.Context.registerFocusable'),
  -- in its first 'ctxFocusablesCount' slots. The array is kept between runs
  -- and grows by doubling.
  , ctxFocusablesCount :: !(PrimVar RealWorld Int)
  -- ^ How many slots of 'ctxFocusables' this run filled. Reset by
  -- @resetUiBuild@.
  , ctxSpanBase :: SpanArena
  -- ^ Base-layer text spans for the current frame, reused on the next frame.
  , ctxSpanOverlay :: SpanArena
  -- ^ Overlay text spans for the current frame, reused on the next frame.
  , ctxInteractionState :: !(IORef InteractionState)
  -- | Rects the view asked a cursor for this build, newest first: a table's
  -- column edges. Reset by @resetUiBuild@.
  , ctxCursorZones :: !(IORef [(Rect, UiCursorKind)])
  -- | Node ranges [from, below) of this build's
  -- 'NanoUI.withCursorShape' scopes, newest first.
  -- Scopes are pushed when they end, so an outer scope precedes its inner
  -- ones. Reset by @resetUiBuild@.
  , ctxCursorRegions :: !(IORef [(Int, Int, UiCursorKind)])
  , ctxClipboardGet :: IO (Maybe Text)
  , ctxClipboardSet :: Text -> IO Bool
  , ctxImageAtlas :: ImageAtlas
  , ctxWakeLoop :: IORef (Maybe (IO Bool))
  -- ^ Wakes the event loop and returns whether the wake reached it
  -- ('NanoUI.Internal.Context.Core.setWakeLoopChecked').
  , ctxWoken :: !(IORef Bool)
  -- ^ Set from any thread by 'NanoUI.Internal.Context.Core.wakeFromThread'
  -- when view inputs changed. The next frame repaints fully and clears it.
  , ctxWakePending :: !(IORef Bool)
  -- ^ A wake ran the wake action and the loop has not taken it yet. Later
  -- wakes skip the action until a loop pass or frame takes it
  -- ('NanoUI.Internal.Context.Core.takeWakes').
  , ctxLoopThread :: !(IORef (Maybe ThreadId))
  -- ^ The thread in 'NanoUI.Runner.runSessionLoop', if one runs. Its dirty
  -- marks run no wake action: the loop checks the dirty flag before it waits.
  , ctxWakeAt :: !(IORef Double)
  -- ^ Monotonic time ('GHC.Clock.getMonotonicTime') of the earliest scheduled
  -- wake timer, or 0 for none. Reset to 0 at the start of each frame so active
  -- timers re-register each frame and the loop can sleep until the next timer.
  , ctxChildWindows :: !(IORef [ChildWindow])
  -- ^ The open native windows the last view run declared
  -- ('NanoUI.nativeWindow'), newest first. Reset by @resetUiBuild@.
  , ctxShaderCaps :: !(IORef ShaderCapabilities)
  -- ^ Shader capabilities reported by the active backend.
  , ctxEffectNodes :: !(IORef (Word32, [Int]))
  -- ^ Epoch-stamped container node indices with Tier 2 shader effects this
  -- build, so damage expansion skips scanning frames with no effects.
  }

-- | A native window a view declared open this frame, for the backend to open
-- or keep. The key is the declaring call's widget id. The view is kept run
-- against a context and input rather than as a 'NanoUI.NanoUI' action,
-- which this module cannot name.
data ChildWindow = ChildWindow
  { childKey :: !WidgetId
  , childOpen :: !(Var Bool)
  , childSettings :: !WindowSettings
  , childRun :: Context -> Input -> IO ()
  -- ^ The declared body, as @\\c inp -> 'NanoUI.Backend.runNanoUI' c inp body@
  -- ('NanoUI.nativeWindow'). A function field because
  -- the 'NanoUI.NanoUI' type is defined in @NanoUI.Internal.Monad.Core@,
  -- which imports "NanoUI.Internal.Context", which imports this module: a
  -- @NanoUI ()@ field here would make an import cycle. The backend runs it
  -- through 'NanoUI.Backend.childView'.
  }

-- | Convert a widget's hash to its store key. The representation assumes a
-- 64-bit 'Int' when preserving all identity bits.
{-# INLINE intKey #-}
intKey :: WidgetId -> Int
intKey = fromIntegral . hashWidgetId