packages feed

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

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

-- | The 'Context' a view runs against, and the operations on its state:
-- focus, dirty flags and damage, the widget store, drawing and measure
-- caches, overlays, and host hooks. Backends and advanced widgets use this
-- module; views normally only need "NanoUI".
module NanoUI.Internal.Context
  ( Context (..)
  , withBackendSession
  , setBackendSession
  , backendSession
  , frameNumber
  -- Accessors, interaction, damage and wakes ("NanoUI.Internal.Context.Core")
  , getsInteraction
  , modifyInteraction
  , getsOverlay
  , modifyOverlay
  , getsDamage
  , modifyDamage
  -- Interaction
  , takeTextEditLastAction
  , pointerHeldOffLayers
  -- Damage
  , markDirty
  , recordLayoutRead
  , settleLayoutReads
  , clearDirty
  , isDirty
  , setWakeLoop
  , setWakeLoopChecked
  , wakeAction
  , wakeFromThread
  , takeWakes
  , takeThreadWake
  , requestWakeAt
  , requestWakeAfter
  , getWakeAt
  , clearWakeAt
  , takeDamage
  , takeDamagePieces
  , requestDamage
  , damageWidget
  , damageKey
  , damageRect
  , damagePeers
  , damageFull
  , traceDamage
  , getPrevRect
  , getPrevRectAt
  , pointerCovered
  , getPrevClipRect
  -- Store
  , getStore
  , setStore
  , modifyStore
  , writeSlots
  , publishLayoutSlots
  , writeSlot
  , adoptSlot
  , recordSlot
  , writeStoreBool
  , isDisabled
  , isInert
  -- Theme scopes
  , newThemeScopes
  , beginThemeScopes
  , pushThemeScope
  , themeScopesChanged
  , scopeTheme
  , scopeRawTheme
  , currentTheme
  , nodeTheme
  , widgetTheme
  -- Scroll offsets ("NanoUI.Internal.Context.Scroll")
  , getScrollOffset
  , setScrollOffset
  , getScrollOffset2D
  , setScrollOffset2D
  , linkScrollAxes
  -- Scroll tuning
  , ScrollTuning (..)
  , defaultScrollTuning
  , getScrollTuning
  , setScrollTuning
  , getScrollStep
  , setScrollStep
  , resolveScrollStep
  -- Scroll geometry
  , ScrollAxes (..)
  , ScrollMetrics (..)
  , getScrollMetrics
  , readScrollMetrics
  , cacheScrollMetrics
  , placeScrollContent
  , beginScrollMetrics
  , getScrollOffsetIn
  , setScrollOffsetIn
  , setScrollOffsetPending
  , applyPendingScrollOffset
  -- Scroll commands
  , ScrollBehavior (..)
  , ScrollAlign (..)
  , scrollTo
  , scrollBy
  , scrollPages
  , scrollToStart
  , scrollToEnd
  , scrollIntoView
  , scrollRectIntoView
  -- Scroll glide
  , applyScrollTarget
  , scrollTargetOffset
  , scrollGliding
  , clampScrollGlide
  , clampScrollOffset
  , stepScrollGlides
  -- Animations ("NanoUI.Internal.Context.Animation")
  , anyAnimating
  , liveAnimationKeys
  , isAnimatingKey
  , takeAnimSettled
  , lookupAnimation
  , startAnimation
  , startAnimationEase
  , startAnimationEaseDelay
  , startSpring
  , keepAnimationAlive
  , repaintIfOrphan
  , setAnimationValue
  , tickAnimations
  , getAnimationValue
  , getViewAnimationValue
  -- Popups, hover zones, drawing caches ("NanoUI.Internal.Context.Drawing")
  , registerPopupConfig
  , lookupPopupConfig
  , registerDropdownPopup
  , dropdownPopups
  , registerHoverZone
  , hoverZoneCrossed
  , registerDrawing
  , lookupDrawingAt
  , cachedDrawingOps
  , cachedWidgetLayout
  , lookupDrawFitEnvelope
  , pruneDrawOpCache
  , registerCustomDrawing
  , registerCustomEntry
  , lookupCustomDrawing
  , lookupCustomDrawingAt
  , customDrawingOffNode
  , cachedCustomDrawingOps
  , refreshCustomDrawingOps
  , drawingOpsStale
  , registerCustomMeasure
  , lookupCustomMeasure
  , lookupCustomMeasureAt
  , customMeasureHooks
  , lookupCustomDamageSlop
  , resetDrawingScopeCache
  , registerNodeShaderAt
  , lookupNodeShaderAt
  , registerShaderEffectAt
  , lookupShaderEffectAt
  , activeEffectNodes
  , getShaderCapabilities
  , setShaderCapabilities
  -- Overlays, modals and key routing ("NanoUI.Internal.Context.Overlay")
  , textInputEditActive
  , modalActive
  , overlayConsumesQuit
  , escapeReserved
  , markEscapeConsumed
  , markTabConsumed
  , tabConsumed
  , pointerBlockedByModal
  , routedInput
  , floatingLayerAt
  , beginModal
  , endModal
  , beginFrameModal
  , modalDamageFlip
  , takeKeyPress
  -- State records ("NanoUI.Internal.Context.Types"), images, fonts, theme,
  -- the layout overlay and host hooks
  , TextInputMenu (..)
  , TextInputDrag (..)
  , TextFieldClickCell (..)
  , WindowResizeEdge (..)
  , WindowResizeDrag (..)
  , DamageState (..)
  , PrevFrame (..)
  , emptyPrevFrame
  , PrevWalk (..)
  , PressPoint (..)
  , OverlayState (..)
  , DrawingCacheState (..)
  , NodeCustom (..)
  , DrawingEntry (..)
  , SpanCacheEntry (..)
  , SpanLines (..)
  , WidgetTextCacheEntry (..)
  , WidgetTextPlacement (..)
  , InteractionState (..)
  , PointerRoute (..)
  , FocusKind (..)
  , KeyClaim (..)
  , InputMethodRequest (..)
  , FocusRequest (..)
  , intKey
  , DamageRequest (..)
  , CustomMeasureFn
  , CustomDrawContext (..)
  , CustomDrawBuild
  , CustomDrawingEntry (..)
  , DropdownPopup (..)
  , atlasTextureId
  , registerImage
  , releaseImage
  , registerImages
  , lookupImageUv
  , lookupImageSize
  , withImageSlot
  , atlasSnapshot
  , atlasChanges
  , AtlasUpload (..)
  , withFontMetrics
  , withMonoFontMetrics
  , withFontSize
  , withMeasureText
  , withFontResolver
  , wrapMeasureCache
  , clearMeasureCache
  , cachedWrapText
  , ensureMetricCaches
  , withTheme
  , setTheme
  , getTheme
  , ExplainState (..)
  , DrawReuse (..)
  , DrawReuseKey (..)
  , ExplainedNode (..)
  , setExplainLayout
  , setDrawReuse
  , getExplainLayout
  , getExplainedNode
  , followSystemTheme
  , setThemeInView
  , settleViewTheme
  , setSystemAppearance
  , getSystemAppearance
  , withClipboard
  , enableMeasureCache
  , setHost
  , Host
  , newHost
  , withFramePaint
  , retainedFrameStale
  , setDrawSnapScale
  , setDrawPixelScale
  , setDrawSquareGeometry
  , setDrawExternalText
  , setDrawRecordOps
  , getDrawRecordOps
  , drawRecordedOps
  , RecordedOp (..)
  , askHostIO
  , hostOrInit
  -- Constructors
  , newContext
  , newPixelContext
  -- Focus
  , getFocusId
  , getFocusVisible
  , getHotId
  , registerFocusable
  , getFocusables
  , isFocusable
  , requestInputMethod
  , fieldComposition
  , AnimationState (..)
  , WidgetStore (..)
  , slotKey
  , Slot (..)
  , intBool
  , anySelectOpen
  , isSelectOpen
  , setSelectOpen
  , closeSelects
  , Ease (..)
  , Animation (..)
  , SpringParams (..)
  , presetBouncy
  , presetSmooth
  , presetStiff
  , applyEase
  , easeSameSpec
  , approxEq
  )
where

import Control.Monad (foldM, forM, unless, when)
import Data.Bits ((.&.))
import Data.ByteString (ByteString)
import NanoUI.Internal.Derived (emptyDerivedCache)
import NanoUI.Internal.Resource (Held (..), newHeld)
import Data.Primitive.Array (newArray)
import Data.Primitive.PrimVar (readPrimVar)
import NanoUI.Internal.Host (Host, newHost, setHost, clearHost, askHostIO, hostOrInit)
import Data.List (find)
import Control.Exception (bracket, finally)
import NanoUI.Internal.BackendSession (BackendSession, SBackend, SomeBackendSession (..), sessionFor)
import Data.Maybe (fromMaybe, isJust)
import Data.HashMap.Strict qualified as HashMap
import Data.IORef (IORef, modifyIORef', newIORef, readIORef, writeIORef)
import Data.IntMap.Strict qualified as IM
import Data.Map.Strict qualified as Map
import Data.Primitive.PrimArray
  ( newPrimArray
  , readPrimArray
  , writePrimArray
  , getSizeofMutablePrimArray
  , resizeMutablePrimArray
  )
import Data.Primitive.PrimVar (newPrimVar, writePrimVar)
import Data.Text (Text)
import Data.Word (Word8)
import Foreign.ForeignPtr (ForeignPtr)

import NanoUI.Internal.Animation
import NanoUI.Internal.Atlas (AtlasUpload (..), atlasTextureId)
import NanoUI.Internal.Atlas qualified as Atlas
import NanoUI.Internal.Context.Animation
import NanoUI.Internal.Context.Core
import NanoUI.Internal.Context.Drawing
import NanoUI.Internal.Context.Overlay
import NanoUI.Internal.Context.Scroll
import NanoUI.Internal.Context.Types
import NanoUI.Internal.Draw (RecordedOp (..), newDrawArena)
import NanoUI.Internal.Draw qualified as Draw
import NanoUI.Internal.Font (FontMetrics, WrapResult (..), fmLineHeight, measureTextIO, monospaceMetrics, scaleFontMetrics, wrapTextIO)
import NanoUI.Internal.Frame.SpanArena (newSpanArena)
import NanoUI.Internal.Id (WidgetId (..), hashWidgetId, initialIdContext)
import NanoUI.Internal.Id.Cursor (newIdCursor)
import NanoUI.Internal.Input (Composition, Input (..), InputPurpose)
import NanoUI.Internal.Shader (ShaderCapabilities)
import NanoUI.Internal.Layout.Arena (getArenaScope, newNodeArena)
import NanoUI.Internal.Shader (noShaderCapabilities)
import NanoUI.Internal.Store
import NanoUI.Internal.Style (Appearance (..), FontStyle, FontVariant (..), FontWeight, Theme, defaultTheme)
import NanoUI.Internal.Types (ImageId, Rect, newZeroedPrimArray)
import NanoUI.Internal.Var.Cell (frameSlots, newStamps)

-- | Register tightly packed RGBA8 pixels under an image id. Width and height
-- are positive pixel counts. Returns 'False' for invalid data or atlas limits;
-- success requests a full repaint and wakes the loop. An id registered at
-- another size is rejected; release it first.
{-# INLINE registerImage #-}
registerImage :: Context -> ImageId -> Int -> Int -> ByteString -> IO Bool
registerImage ctx iid w h px = do
  ok <- Atlas.registerImage (ctxImageAtlas ctx) iid w h px
  -- New pixels under an id already on screen change no rect or text, and
  -- packing can move other images' texels, so nothing narrower is safe.
  when ok (damageFull ctx >> markDirty ctx)
  pure ok

-- | Remove an image from the atlas and free its space for later
-- registrations. Anything still using the id draws the unknown-image
-- placeholder. Releasing a registered image requests a full repaint and
-- wakes the loop, as registering one does.
{-# INLINE releaseImage #-}
releaseImage :: Context -> ImageId -> IO ()
releaseImage ctx iid = do
  released <- Atlas.releaseImage (ctxImageAtlas ctx) iid
  -- The id may still be on screen, drawn by a node whose rect is unchanged.
  when released (damageFull ctx >> markDirty ctx)

-- | Register every image and return whether all succeeded. Successful earlier
-- registrations remain in place if another image fails.
registerImages :: Foldable f => Context -> f (ImageId, Int, Int, ByteString) -> IO Bool
registerImages ctx =
  foldM (\ok (iid, w, h, px) -> (ok &&) <$> registerImage ctx iid w h px) True

-- | Current normalised atlas UV bounds, or 'Nothing' for an unknown image.
-- Atlas growth can change these coordinates; do not cache them across uploads.
{-# INLINE lookupImageUv #-}
lookupImageUv :: Context -> ImageId -> IO (Maybe (Float, Float, Float, Float))
lookupImageUv ctx = Atlas.lookupImageUv (ctxImageAtlas ctx)

-- | A registered image's size in pixels, or 'Nothing' if unknown.
{-# INLINE lookupImageSize #-}
lookupImageSize :: Context -> ImageId -> IO (Maybe (Int, Int))
lookupImageSize ctx = Atlas.lookupImageSize (ctxImageAtlas ctx)

-- | A registered image's size in pixels and atlas UV bounds, passed to @k@,
-- or @none@ if unknown ('Atlas.withImageSlot').
{-# INLINE withImageSlot #-}
withImageSlot :: Context -> ImageId -> IO r -> (Int -> Int -> Float -> Float -> Float -> Float -> IO r) -> IO r
withImageSlot ctx = Atlas.withImageSlot (ctxImageAtlas ctx)

-- | What a texture of the image atlas uploaded at generation @since@ (0 for
-- none) needs, with the atlas's size, pixels and generation.
{-# INLINE atlasChanges #-}
atlasChanges :: Context -> Int -> IO (Maybe (Int, Int, ForeignPtr Word8, Int, AtlasUpload))
atlasChanges ctx = Atlas.atlasChanges (ctxImageAtlas ctx)

-- | Atlas width, height, RGBA8 buffer, and revision for backend upload.
-- 'Nothing' until the first image is registered. Treat the buffer as
-- borrowed mutable storage and upload it before further image registration.
{-# INLINE atlasSnapshot #-}
atlasSnapshot :: Context -> IO (Maybe (Int, Int, ForeignPtr Word8, Int))
atlasSnapshot ctx = Atlas.atlasSnapshot (ctxImageAtlas ctx)

-- | Metrics for a font variant scaled to line height @sz@, and the scale
-- factor applied (1 when @sz@ or the base line height is not positive).
{-# INLINE resolveScale #-}
resolveScale :: Context -> Float -> FontVariant -> (FontMetrics, Float)
resolveScale ctx sz var =
  let baseFm = if var == FontMono then ctxMonoFontMetrics ctx else ctxFontMetrics ctx
      scale =
        if sz > 0 && fmLineHeight baseFm > 0
          then sz / fmLineHeight baseFm
          else 1.0
   in (if scale /= 1.0 then scaleFontMetrics scale baseFm else baseFm, scale)

defaultResolveFont :: Context -> Float -> FontWeight -> FontStyle -> FontVariant -> IO (FontMetrics, Bool)
defaultResolveFont ctx sz _w _st var = pure (fst (resolveScale ctx sz var), False)

defaultResolveMeasure :: Context -> Float -> FontWeight -> FontStyle -> FontVariant -> Text -> IO (Float, Float)
defaultResolveMeasure ctx sz _w _st var txt
  | var == FontMono = measureTextIO textFm txt
  | scale /= 1.0 = (\(w, h) -> (w * scale, h * scale)) <$> ctxMeasureText ctx txt
  | otherwise = ctxMeasureText ctx txt
  where
    (textFm, scale) = resolveScale ctx sz var

-- | Return a context with size/weight/style/variant font and measurement
-- callbacks. Use the returned context for later frames; shared text caches
-- are invalidated at the next frame boundary.
{-# INLINE withFontResolver #-}
withFontResolver ::
  Context ->
  (Float -> FontWeight -> FontStyle -> FontVariant -> IO (FontMetrics, Bool)) ->
  (Float -> FontWeight -> FontStyle -> FontVariant -> Text -> IO (Float, Float)) ->
  Context
withFontResolver ctx rf rm = trackMetricSource ctx {ctxResolveFont = rf, ctxResolveMeasure = rm}

-- | Replace base metrics and rebuild default measurement/resolution callbacks.
-- These replace any installed with 'withFontResolver', and the measurement is
-- uncached ('enableMeasureCache').
-- Returns a configured context sharing the original session state. The
-- default resolver treats a font size as a line height, so the default size
-- becomes the metrics' line height ('withFontSize').
withFontMetrics :: Context -> FontMetrics -> Context
withFontMetrics ctx fm =
  withDefaultResolvers ctx {ctxFontMetrics = fm, ctxMeasureText = measureTextIO fm, ctxFontSize = fmLineHeight fm}

-- | Set the default text size, in the font resolver's units. Backends whose
-- base font size differs from its line height call this.
withFontSize :: Context -> Float -> Context
withFontSize ctx size = trackMetricSource ctx {ctxFontSize = size}

-- | Replace monospace metrics and rebuild default font-resolution callbacks.
withMonoFontMetrics :: Context -> FontMetrics -> Context
withMonoFontMetrics ctx mono = withDefaultResolvers ctx {ctxMonoFontMetrics = mono}

-- | Rebuild the default font and measurement resolvers over @ctx@'s metrics.
withDefaultResolvers :: Context -> Context
withDefaultResolvers ctx =
  trackMetricSource ctx
    { ctxResolveFont = defaultResolveFont ctx
    , ctxResolveMeasure = defaultResolveMeasure ctx
    }

-- | Replace proportional text measurement, returning logical width/height.
-- The callback must agree with the font used for painting. Sized, bold and
-- italic text goes back to the default measurement, scaled from this one,
-- while a 'withFontResolver' font resolver stays: install that after this.
withMeasureText :: Context -> (Text -> IO (Float, Float)) -> Context
withMeasureText ctx fn =
  let ctx' = ctx {ctxMeasureText = fn}
   in trackMetricSource ctx'
        { ctxResolveMeasure = defaultResolveMeasure ctx'
        }

-- Keep the identity boxed. No structural callback comparison or unsafe pure
-- mutation is needed, and repeated frames with the same Context do no work.
trackMetricSource :: Context -> Context
trackMetricSource ctx =
  ctx {ctxMetricSource = MetricSource
    (ctxFontMetrics ctx) (ctxMonoFontMetrics ctx) (ctxMeasureText ctx)
    (ctxResolveFont ctx) (ctxResolveMeasure ctx)}

-- | Called once before building a frame. Context configuration remains pure;
-- cache invalidation happens at the IO boundary, including when alternating
-- between differently configured Contexts that share their backing stores.
ensureMetricCaches :: Context -> IO ()
ensureMetricCaches ctx = do
  -- Compare evaluated identities: passed unevaluated, the selector application
  -- is a fresh thunk without optimisation, so the check would miss every
  -- frame and force full damage with cleared caches.
  let !current = ctxMetricSource ctx
  previous <- readIORef (ctxLastMetricSource ctx)
  case previous of
    Just source | ptrEq source current -> pure ()
    _ -> do
      clearMeasureCache ctx
      damageFull ctx
      markDirty ctx

cacheMeasureText ::
  IORef MeasureCache ->
  Float ->
  (Text -> IO (Float, Float)) ->
  Text ->
  IO (Float, Float)
cacheMeasureText ref scale base txt = cachedGen measureCacheCap (const 1) ref (txt, scale) (base txt)

-- | Measurements per generation of the measure cache.
measureCacheCap :: Int
measureCacheCap = 4096

-- | 'wrapTextIO' through the context's wrap cache ('ctxWrapCache'). @font@
-- names the font @lineW@ measures in ('NanoUI.Internal.WidgetText.textNodeFontKey').
-- Caches the last few wrapped widths per text along with the width range
-- each result holds for, so wrapping again at a width with the same line
-- breaks (e.g. while dragging a window or pane edge) skips measurement,
-- and the layout solve and text spans share one wrap. A change of font metrics
-- ('ctxMetricGen') clears the cache.
cachedWrapText :: Context -> Int -> (Text -> IO Float) -> Text -> Float -> IO WrapResult
cachedWrapText ctx font lineW txt maxW
  | maxW <= 0 = wrapTextIO lineW txt maxW
  | otherwise = do
      gen <- readIORef (ctxMetricGen ctx)
      WrapCache wrapGen cache0 <- readIORef (ctxWrapCache ctx)
      let key = (txt, font)
          holds r = wrFitW r <= maxW && maxW < wrBreakW r
          cache@(GenCache young _ old)
            | wrapGen == gen = cache0
            | otherwise = emptyGenCache
          mine = HashMap.lookup key young
      case mine >>= find holds of
        Just r -> pure r
        Nothing -> do
          -- A hit in the old generation moves up to the young one.
          r <- maybe (wrapTextIO lineW txt maxW) pure (HashMap.lookup key old >>= find holds)
          let entries = r : take (wrapsPerText - 1) (fromMaybe [] mine)
          writeIORef (ctxWrapCache ctx) $!
            WrapCache gen (insertGen wrapCacheCap (if isJust mine then 0 else 1) key entries cache)
          pure r

-- | Texts per generation of the wrap cache.
wrapCacheCap :: Int
wrapCacheCap = 1024

-- | Widths the wrap cache keeps for one text.
wrapsPerText :: Int
wrapsPerText = 8

-- | Install measurement under a scale-specific cache key when caching is
-- enabled. Otherwise install the callback directly.
wrapMeasureCache :: Float -> Context -> (Text -> IO (Float, Float)) -> Context
wrapMeasureCache scale ctx measure =
  withMeasureText ctx $
    case ctxMeasureCache ctx of
      Nothing -> measure
      Just ref -> cacheMeasureText ref scale measure

-- | Drop text span, widget text and whole-layout caches and bump the metric
-- generation, for changes that alter how text lays out.
invalidateTextCaches :: Context -> IO ()
invalidateTextCaches ctx = do
  writeIORef (ctxSpanCache ctx) IM.empty
  writeIORef (ctxWidgetTextCache ctx) IM.empty
  writeIORef (ctxDerivedCache ctx) emptyDerivedCache
  writeIORef (ctxLayoutCache ctx) Nothing
  modifyIORef' (ctxMetricGen ctx) (+ 1)

-- | Clear measurement, text-placement, and whole-layout caches and advance the
-- metric generation. Does not itself request a repaint or wake the loop.
clearMeasureCache :: Context -> IO ()
clearMeasureCache ctx = do
  -- Store the evaluated source so 'ensureMetricCaches' can match its identity.
  let !source = ctxMetricSource ctx
  writeIORef (ctxLastMetricSource ctx) (Just source)
  invalidateTextCaches ctx
  mapM_ (`writeIORef` emptyGenCache) (ctxMeasureCache ctx)

-- | Apply 'setTheme' and return the same context for configuration pipelines.
withTheme :: Context -> Theme -> IO Context
withTheme ctx theme = ctx <$ setTheme ctx theme

-- | Set a fixed base theme, invalidate text/layout caches, and request a
-- full repaint. Setting the same theme is a no-op. Stops
-- 'followSystemTheme'.
setTheme :: Context -> Theme -> IO ()
setTheme ctx th = do
  writeIORef (ctxThemeFor ctx) Nothing
  applyBaseTheme ctx th

-- | 'setTheme' without leaving 'followSystemTheme'.
applyBaseTheme :: Context -> Theme -> IO ()
applyBaseTheme ctx th = do
  cur <- readIORef (ctxTheme ctx)
  when (cur /= th) $ do
    writeIORef (ctxTheme ctx) th
    repaintForTheme ctx

-- | Drop text caches, repaint the whole window and request a frame.
repaintForTheme :: Context -> IO ()
repaintForTheme ctx = do
  invalidateTextCaches ctx
  damageFull ctx
  markDirty ctx

-- | 'setTheme' from a view. The new theme is visible immediately, but the
-- repaint waits until the view is built ('settleViewTheme') and happens only
-- if the frame ends on a different theme than it began with. A view can set
-- the theme every frame, even twice, without repainting.
setThemeInView :: Context -> Theme -> IO ()
setThemeInView ctx th = do
  writeIORef (ctxThemeFor ctx) Nothing
  writeIORef (ctxTheme ctx) th

-- | Repaint if a view changed the base theme ('setThemeInView') this frame.
settleViewTheme :: Context -> Theme -> IO ()
settleViewTheme ctx before = do
  now <- readIORef (ctxTheme ctx)
  when (now /= before) (repaintForTheme ctx)

-- | Base session theme. Use 'currentTheme' to include the current paint scope.
getTheme :: Context -> IO Theme
getTheme ctx = readIORef (ctxTheme ctx)

-- | Whether a full frame with no damage, built from the same view output
-- as the last, takes the last frame's draw data instead of painting again
-- (on by default). A benchmark that times paint on a still scene turns it
-- off.
setDrawReuse :: Context -> Bool -> IO ()
setDrawReuse ctx on = writeIORef (ctxDrawReuse ctx) (DrawReuse on Nothing)

-- | Set the shader capabilities supported by the active backend. When the
-- capabilities change, invalidate cached draw reuse and force a full repaint.
setShaderCapabilities :: Context -> ShaderCapabilities -> IO ()
setShaderCapabilities ctx caps = do
  cur <- readIORef (ctxShaderCaps ctx)
  when (cur /= caps) $ do
    writeIORef (ctxShaderCaps ctx) caps
    modifyIORef' (ctxDrawReuse ctx) (\dr -> dr {drLast = Nothing})
    damageFull ctx
    markDirty ctx

-- | Toggle the layout overlay ("NanoUI.Internal.Frame.Explain"): a one-pixel
-- outline inside every layout node, coloured by depth, and a tint on the
-- hovered node. A change repaints the window and wakes the loop.
setExplainLayout :: Context -> Bool -> IO ()
setExplainLayout ctx on = do
  cur <- getExplainLayout ctx
  when (cur /= on) $ do
    writeIORef (ctxExplain ctx) initialExplainState {esOn = on}
    damageFull ctx
    markDirty ctx

-- | Whether the layout overlay is on ('setExplainLayout').
{-# INLINE getExplainLayout #-}
getExplainLayout :: Context -> IO Bool
getExplainLayout ctx = esOn <$> readIORef (ctxExplain ctx)

-- | The node under the pointer at the end of the last frame, while the layout
-- overlay is on. 'Nothing' when it is off or no node is hovered.
getExplainedNode :: Context -> IO (Maybe ExplainedNode)
getExplainedNode ctx = fmap fst . esHover <$> readIORef (ctxExplain ctx)

-- | Derive the base theme from the system appearance ('Nothing' when the
-- backend cannot tell), e.g. with @'NanoUI.lightDark' light
-- dark@. Applies now and on every 'setSystemAppearance' change, until
-- 'setTheme' sets a fixed theme. A view can instead pick the theme itself
-- each frame:
--
-- > setTheme . lightDark defaultLightTheme defaultTheme =<< systemAppearance
followSystemTheme :: Context -> (Maybe Appearance -> Theme) -> IO ()
followSystemTheme ctx pick = do
  writeIORef (ctxThemeFor ctx) (Just pick)
  applyBaseTheme ctx . pick =<< readIORef (ctxSystemAppearance ctx)

-- | Record the system's light or dark preference ('Nothing' if unknown).
-- Backends call this on the UI thread; SDL reports at startup and on change,
-- RGFW does not report it. A change repaints the window, wakes the loop, and
-- updates a theme set by 'followSystemTheme'. The same value again is a no-op.
setSystemAppearance :: Context -> Maybe Appearance -> IO ()
setSystemAppearance ctx appearance = do
  cur <- readIORef (ctxSystemAppearance ctx)
  when (cur /= appearance) $ do
    writeIORef (ctxSystemAppearance ctx) appearance
    readIORef (ctxThemeFor ctx) >>= mapM_ (\pick -> applyBaseTheme ctx (pick appearance))
    -- Repaint even without followSystemTheme: views may read the appearance.
    damageFull ctx
    markDirty ctx

-- | The system appearance the backend last reported.
getSystemAppearance :: Context -> IO (Maybe Appearance)
getSystemAppearance ctx = readIORef (ctxSystemAppearance ctx)

-- | Install clipboard read/write callbacks. 'Nothing' means no text is
-- available; a write returns 'False' when refused or unsupported.
withClipboard :: Context -> IO (Maybe Text) -> (Text -> IO Bool) -> Context
withClipboard ctx getter setter = ctx {ctxClipboardGet = getter, ctxClipboardSet = setter}

-- | Enable memoised text measurement, or return an already cached context.
-- Use the returned context for subsequent frames. It wraps the measurement
-- installed so far, which a later 'withFontMetrics' or 'withMeasureText'
-- replaces with an uncached one; a context that has a cache already (from
-- 'newPixelContext') is returned unchanged, so install measurement on it
-- with 'wrapMeasureCache'.
enableMeasureCache :: Context -> IO Context
enableMeasureCache ctx =
  case ctxMeasureCache ctx of
    Just _ -> pure ctx
    Nothing -> do
      ref <- newIORef emptyGenCache
      let ctx' = ctx {ctxMeasureCache = Just ref, ctxMeasureText = cacheMeasureText ref 0 (ctxMeasureText ctx)}
      pure (trackMetricSource ctx' {ctxResolveMeasure = defaultResolveMeasure ctx'})

-- | Run a frame's UI pass for a host that draws it whole when @paintFull@
-- holds ('ctxPaintFull'), and repaints the whole window, whatever the
-- frame's damage, when @presentFull@ holds. A frame presented whole works
-- out no damage ('ctxDamageWanted' is off for its pass), since the host
-- would not read it. The context wants damage again after the pass, even
-- one that throws, so frames run outside a draw still work it out.
{-# INLINE withFramePaint #-}
withFramePaint :: Context -> Bool -> Bool -> IO a -> IO a
withFramePaint ctx paintFull presentFull pass = do
  writeIORef (ctxPaintFull ctx) paintFull
  writeIORef (ctxDamageWanted ctx) (not presentFull)
  pass `finally` writeIORef (ctxDamageWanted ctx) True

-- | Whether a host that keeps its last presented frame must paint this one
-- whole: the caller forces it, the window asked to be redrawn
-- ('inputWindowRedraw'), or the kept frame's pixel width, height and scale
-- (@presented@) differ from this frame's (@current@), so it holds nothing
-- this frame can keep.
{-# INLINE retainedFrameStale #-}
retainedFrameStale :: Bool -> Input -> (Int, Int, Float) -> (Int, Int, Float) -> Bool
retainedFrameStale force inp presented current = force || inputWindowRedraw inp || presented /= current

-- | Set the device pixel scale used to snap geometry origins/endpoints to
-- whole pixels. The SDL backend calls this when the window pixel density is synced.
{-# INLINE setDrawSnapScale #-}
setDrawSnapScale :: Context -> Float -> IO ()
setDrawSnapScale ctx s = Draw.setDrawSnapScale (ctxDrawArena ctx) s

-- | Set the device pixel scale forwarded to shaders (@uMeta.x@) without
-- enabling pixel-grid snapping.
{-# INLINE setDrawPixelScale #-}
setDrawPixelScale :: Context -> Float -> IO ()
setDrawPixelScale ctx s = Draw.setDrawPixelScale (ctxDrawArena ctx) s

-- | Emit rounded shapes and AA strokes as flat, axis-aligned fills. Software
-- framebuffer hosts enable this so every primitive is a solid quad.
{-# INLINE setDrawSquareGeometry #-}
setDrawSquareGeometry :: Context -> Bool -> IO ()
setDrawSquareGeometry ctx = Draw.setDrawSquareGeometry (ctxDrawArena ctx)

-- | Skip text quads in the draw buffer. Hosts that rasterize text from the
-- collected text spans enable this; drawing text ops are then returned by
-- 'NanoUI.Internal.Frame.Spans.collectRasterSpans' instead of drawn as quads.
{-# INLINE setDrawExternalText #-}
setDrawExternalText :: Context -> Bool -> IO ()
setDrawExternalText ctx = Draw.setDrawExternalText (ctxDrawArena ctx)

-- | Record the shapes and images each paint draws, as ops, for exporters that
-- redraw a frame as vectors ('drawRecordedOps').
{-# INLINE setDrawRecordOps #-}
setDrawRecordOps :: Context -> Bool -> IO ()
setDrawRecordOps ctx = Draw.setDrawRecordOps (ctxDrawArena ctx)

-- | Whether 'setDrawRecordOps' is on.
{-# INLINE getDrawRecordOps #-}
getDrawRecordOps :: Context -> IO Bool
getDrawRecordOps ctx = Draw.getDrawRecordOps (ctxDrawArena ctx)

-- | The shapes and images the last paint drew while 'setDrawRecordOps' was on, in
-- paint order, each with its layer and clip.
drawRecordedOps :: Context -> IO [RecordedOp]
drawRecordedOps ctx = Draw.recordedOps (ctxDrawArena ctx)

-- =============================================================================
-- Constructors
-- =============================================================================

-- | Fresh headless context with default theme, 12-unit monospace metrics,
-- empty state, and no native clipboard or wake callbacks. Backends configure
-- it before the first frame; each independent session needs its own context.
newContext :: IO Context
newContext = do
  nodeArena <- newNodeArena
  drawArena <- newDrawArena
  ctxHotId <- newIORef (WidgetId 0)
  ctxLastHotId <- newIORef (WidgetId 0)
  ctxPointerReach <- newIORef Nothing
  ctxActiveId <- newIORef (WidgetId 0)
  ctxClickedId <- newIORef (WidgetId 0)
  ctxPressPos <- newIORef Map.empty
  ctxFocusId <- newIORef (WidgetId 0)
  ctxFocusVisible <- newIORef False
  ctxFocusRequest <- newIORef Nothing
  ctxInputMethod <- newIORef Nothing
  ctxStore <- newIORef emptyWidgetStore
  ctxDamageState <- newIORef initialDamageState
  ctxPrevWalk <- newIORef =<< newPrevWalk 0
  ctxStoreOwners <- newIORef IM.empty
  ctxOverlayState <- newIORef initialOverlayState
  ctxAnimationState <- newIORef initialAnimationState
  ctxScrollState <- newIORef initialScrollState
  ctxDrawingCache <- newIORef initialDrawingCacheState
  ctxNodeCustom <- newIORef =<< newArray 64 noNodeCustom
  ctxCustomPass <- newZeroedPrimArray customPassWords
  ctxIdCursor <- newIdCursor initialIdContext
  ctxVarFrame <- newStamps frameSlots
  ctxVarSlots <- newIORef IM.empty
  ctxContainerStack <- newContainerStack
  ctxFocusables <- newIORef =<< newPrimArray 64
  ctxFocusablesCount <- newPrimVar 0
  ctxSpanBase <- newSpanArena
  ctxSpanOverlay <- newSpanArena
  ctxInteractionState <- newIORef initialInteractionState
  ctxCursorZones <- newIORef []
  ctxCursorRegions <- newIORef []
  ctxImageAtlas <- Atlas.newImageAtlas
  ctxWakeLoop <- newIORef Nothing
  ctxWoken <- newIORef False
  ctxWakePending <- newIORef False
  ctxLoopThread <- newIORef Nothing
  ctxWakeAt <- newIORef 0
  ctxChildWindows <- newIORef []
  ctxShaderCaps <- newIORef noShaderCapabilities
  ctxEffectNodes <- newIORef (0, [])
  ctxTheme <- newIORef defaultTheme
  ctxThemeScopes <- newIORef =<< newThemeScopes
  ctxSystemAppearance <- newIORef Nothing
  ctxThemeFor <- newIORef Nothing
  ctxSpanCache <- newIORef IM.empty
  ctxWidgetTextCache <- newIORef IM.empty
  ctxDerivedCache <- newIORef emptyDerivedCache
  ctxHeld <- newHeld
  ctxNativeWindow <- newHost
  ctxBackendSession <- newHost
  ctxSensors <- newHost
  ctxParagraphs <- newHost
  ctxSvgRasters <- newIORef Map.empty
  ctxLayoutCache <- newIORef Nothing
  ctxMetricGen <- newIORef 0
  ctxWrapCache <- newIORef (WrapCache 0 emptyGenCache)
  ctxLastMetricSource <- newIORef Nothing
  ctxPaintFull <- newIORef True
  ctxDrawReuse <- newIORef (DrawReuse True Nothing)
  ctxDamageWanted <- newIORef True
  ctxExplain <- newIORef initialExplainState
  -- References above use their field names; font-dependent defaults stay
  -- explicit, including the resolvers that close over this context.
  let fm0 = monospaceMetrics 12
      ctx = Context
        { ctxNodeArena = nodeArena
        , ctxDrawArena = drawArena
        , ctxFontMetrics = fm0
        , ctxMonoFontMetrics = fm0
        , ctxFontSize = fmLineHeight fm0
        , ctxMeasureText = measureTextIO fm0
        , ctxResolveFont = defaultResolveFont ctx
        , ctxResolveMeasure = defaultResolveMeasure ctx
        , ctxMeasureCache = Nothing
        , ctxMetricSource = InitialMetricSource
        , ctxClipboardGet = pure Nothing
        , ctxClipboardSet = \_ -> pure False
        , ..
        }
  pure ctx

-- | Headless context with 16-unit monospace metrics, a measure cache for
-- 'wrapMeasureCache' to install measurement through (the monospace
-- measurement itself is not cached), and the default theme: for tests, and
-- the starting point of pixel-based hosts.
newPixelContext :: IO Context
newPixelContext = do
  ctx <- enableMeasureCache =<< newContext
  pure (withFontMetrics ctx (monospaceMetrics 16))

-- =============================================================================
-- Focus
-- =============================================================================

-- | Keyboard-focused widget, or @WidgetId 0@ when none has focus.
{-# INLINE getFocusId #-}
getFocusId :: Context -> IO WidgetId
getFocusId ctx = readIORef (ctxFocusId ctx)

-- | Whether the focused widget shows its focus ring: focus moved by keyboard
-- since the last pointer press.
{-# INLINE getFocusVisible #-}
getFocusVisible :: Context -> IO Bool
getFocusVisible ctx = readIORef (ctxFocusVisible ctx)

-- | Hovered widget selected by the frame, or @WidgetId 0@ for none.
{-# INLINE getHotId #-}
getHotId :: Context -> IO WidgetId
getHotId ctx = readIORef (ctxHotId ctx)

-- | Add @wid@ to this frame's keyboard focus order, unless it is declared in a
-- disabled or display-only scope.
registerFocusable :: Context -> WidgetId -> IO ()
registerFocusable ctx wid = do
  scope <- getArenaScope (ctxNodeArena ctx)
  when (scope .&. 3 == 0) $ do
    idx <- readPrimVar (ctxFocusablesCount ctx)
    arr <- readIORef (ctxFocusables ctx)
    cap <- getSizeofMutablePrimArray arr
    arr' <-
      if idx >= cap
        then do
          grown <- resizeMutablePrimArray arr (max 16 (cap * 2))
          writeIORef (ctxFocusables ctx) grown
          pure grown
        else pure arr
    writePrimArray arr' idx wid
    writePrimVar (ctxFocusablesCount ctx) (idx + 1)

-- | Enable the input method this frame for the focused widget @wid@, with its
-- caret in window coordinates ('Nothing' for a text field; the frame finds
-- its caret) and the input purpose. Next frame @wid@ gets the composition
-- ('fieldComposition'); backends read the text area from
-- 'NanoUI.Internal.Frame.TextArea.textInputArea'. With no request the input
-- method stays off; the last request of a build wins.
requestInputMethod :: Context -> WidgetId -> Maybe Rect -> InputPurpose -> IO ()
requestInputMethod ctx wid caret purpose = do
  inert <- isInert ctx wid
  disabled <- isDisabled ctx wid
  unless (inert || disabled) $
    writeIORef (ctxInputMethod ctx) $! Just (InputMethodRequest wid caret purpose)

-- | The frame's composition, if @wid@ has focus and owns it
-- ('NanoUI.Internal.Frame.TextInput.claimComposition').
fieldComposition :: Context -> WidgetId -> IO (Maybe Composition)
fieldComposition ctx wid = do
  focus <- readIORef (ctxFocusId ctx)
  getsInteraction ctx $ \s -> case isComposition s of
    Just (c, owner) | owner == wid && owner == focus && hashWidgetId owner /= 0 -> Just c
    _ -> Nothing

-- | Copy this frame's registered focus ids in declaration order. Modal
-- filtering is applied separately when moving focus.
{-# INLINE getFocusables #-}
getFocusables :: Context -> IO [WidgetId]
getFocusables ctx = do
  count <- readPrimVar (ctxFocusablesCount ctx)
  arr <- readIORef (ctxFocusables ctx)
  forM [0 .. count - 1] (readPrimArray arr)

-- | Whether @wid@ registered as focusable this frame ('registerFocusable'),
-- without copying the list.
isFocusable :: Context -> WidgetId -> IO Bool
isFocusable ctx wid = do
  count <- readPrimVar (ctxFocusablesCount ctx)
  arr <- readIORef (ctxFocusables ctx)
  let go i
        | i >= count = pure False
        | otherwise = readPrimArray arr i >>= \w -> if w == wid then pure True else go (i + 1)
  go 0

-- | Run a backend's session with its value installed on the context, where
-- the backend's view-side operations find it ('backendSession'). Every copy
-- of the context shares it, and a separate context has its own. Restores the
-- previous value on exit, including on exception.
withBackendSession :: Context -> SBackend b -> BackendSession b -> IO a -> IO a
withBackendSession ctx backend session act =
  bracket
    (askHostIO slot <* setHost slot (SomeBackendSession backend session))
    (maybe (clearHost slot) (setHost slot))
    (const act)
  where
    slot = ctxBackendSession ctx

-- | 'withBackendSession' for a session that ends with its context rather
-- than a scope, such as a further window's.
setBackendSession :: Context -> SBackend b -> BackendSession b -> IO ()
setBackendSession ctx backend session = setHost (ctxBackendSession ctx) (SomeBackendSession backend session)

-- | The session value of the backend driving this context, if it is the
-- backend asked for.
backendSession :: SBackend b -> Context -> IO (Maybe (BackendSession b))
backendSession backend ctx = (>>= sessionFor backend) <$> askHostIO (ctxBackendSession ctx)

-- | Current frame number: advances once per frame and is shared across passes
-- within the same frame.
frameNumber :: Context -> IO Int
frameNumber = readPrimVar . heldFrame . ctxHeld