packages feed

nano-ui-sdl-0.2.0.0: lib/NanoUI/Sdl/Internal/Runner.hs

-- | SDL3 draw path: retained damage updates or direct continuous presentation.
module NanoUI.Sdl.Internal.Runner
  ( sdlDrawFrame
  , sdlDrawFrameSettling
  , drawFrameWith
  , askSdlDebug
  , sdlDebugSnapshot
  , setSdlUiFont
  , setSdlUiScale
  , resetRenderTextures
  ) where

import Control.Exception (mask_)
import Control.Monad (unless, void, when)
import Data.Foldable (for_)
import Data.IORef (IORef, readIORef, writeIORef)
import Data.Maybe (isJust, isNothing)
import GHC.Clock (getMonotonicTime)
import NanoUI
import NanoUI.Backend
import NanoUI.Internal.Context (withFramePaint)
import NanoUI.Internal.Monad (askContext)
import NanoUI.Internal.Debug (CoreDebugSnapshot (..), noteDebugFrame, noteDebugSkip, refreshDebugSnapshot)
import NanoUI.Sdl.Internal.Chrome.Types (ChromeState (..), defaultWindowChrome)
import NanoUI.Sdl.Internal.Debug
import NanoUI.Sdl.Internal.Display (outPair, queryMouseWindowPos, queryWindowLogicalSize, scaleMoved, sendWaylandSizeLimits)
import NanoUI.Sdl.Internal.Font
import NanoUI.Sdl.Internal.Input (syncTextInput)
import NanoUI.Sdl.Internal.NanoUIFont (NanoUIFont)
import NanoUI.Sdl.Internal.Env (dropRetainRef)
import NanoUI.Sdl.Internal.Error (sdlFail)
import NanoUI.Sdl.Internal.Frame (windowInSizeMove)
import NanoUI.Sdl.Internal.Render (glyphPageTexture, presentGpuRetain, renderDrawDataPass)
import NanoUI.Sdl.Internal.Target (setRetainTarget)
import NanoUI.Ttf.Internal.Font (beginTtfFrame, glyphAtlasFull, ttfFrameDropped)
import NanoUI.Sdl.Internal.Window (PresentProbe (..), Retain (..), SdlEnv (..), captureFrame, notePresent, windowZoom, withSdlEnv)
import Foreign.Marshal.Utils (with)
import Foreign.Ptr (Ptr, nullPtr)
import qualified NanoUI.Sdl.Internal.Image as SdlImage
import SDL3.Sys.Bindgen.Blendmode (sDL_BLENDMODE_NONE)
import SDL3.Sys.Bindgen.Pixels qualified as Pixels
import SDL3.Sys.Bindgen.Rect (SDL_FRect (..))
import SDL3.Sys.Bindgen.Render (SDL_Texture)
import SDL3.Sys.Bindgen.Render qualified as Render
import SDL3.Sys.Bindgen.Runtime.PtrConst qualified as PtrConst
import SDL3.Sys.Render
  ( createTexture
  , destroyTexture
  , getRenderOutputSize
  , renderPresentSafe
  , renderTexture
  , setRenderClipRect
  , setRenderScale
  , setRenderTarget
  , setTextureBlendMode
  )

-- | Build, draw, and present one frame on the display thread. The final flag
-- forces a full repaint. Returns whether the frame left the context dirty
-- ('NanoUI.Backend.isDirty'); a host that draws frames itself also draws
-- while 'NanoUI.Testing.anyAnimating' holds, and at
-- 'NanoUI.Backend.getWakeAt'. Use the context/input returned by
-- @syncDisplay@.
sdlDrawFrame :: Context -> NanoUI () -> SdlEnv -> Input -> Bool -> IO Bool
sdlDrawFrame ctx ui env inp forceFull = sdlDrawFrameSettling ctx ui env inp forceFull False

-- | Like 'sdlDrawFrame', with an optional settle pass before rasterising when
-- @settleDirty@ is 'True' (used during live resize so layout-reading widgets
-- never flash an unsettled width).
sdlDrawFrameSettling :: Context -> NanoUI () -> SdlEnv -> Input -> Bool -> Bool -> IO Bool
sdlDrawFrameSettling ctx ui env inp forceFull settleDirty =
  drawFrameWith ctx env inp forceFull settleDirty (\i -> (\(_, drawData, dirty) -> (drawData, dirty)) <$> runFrame ctx i ui)

-- | Draw and present a frame whose UI pass is the given action, which answers
-- the draw data and whether the context needs another frame. Both
-- application styles share atlas maintenance, retain preparation, timing,
-- and presentation; only evaluation of the UI differs. When @settleDirty@ is
-- 'True' (during live resize) and the first UI pass marks the context dirty
-- without exhausting the glyph atlas, one settle pass runs before rasterising
-- so widgets that read the previous frame's layout do not jitter a frame behind.
drawFrameWith :: Context -> SdlEnv -> Input -> Bool -> Bool -> (Input -> IO (DrawData, Bool)) -> IO Bool
drawFrameWith ctx env inp forceFull settleDirty evaluateUi = do
  SdlImage.syncImageAtlas ren (sdlImages env) ctx
  -- Glyph-atlas maintenance before any quad is recorded: if the atlas ran
  -- out of space during the previous frame, reset it now (re-warming the
  -- base fonts) so a reset can never wipe the texture underneath
  -- already-recorded text mid-frame.
  freshAtlas <- beginTtfFrame (sdlFontCache env) ctx
  scale <- readIORef (sdlScaleRef env)
  -- The frame is the backbuffer's size. One worked out from the scale can be
  -- a pixel off it at a fractional scale, where each axis rounds apart, and
  -- the copy to the window would stretch it. A NANO_FORCE_SCALE frame is
  -- drawn at a scale the window does not have, and the copy fits it.
  (outputOk, ow, oh) <- outPair (getRenderOutputSize ren)
  let Size lw lh = inputWindowSize inp
      fromOutput = outputOk && ow > 0 && oh > 0 && isNothing (sdlForcedScale env)
      pw = if fromOutput then fromIntegral ow else max 1 (round (lw * scale))
      ph = if fromOutput then fromIntegral oh else max 1 (round (lh * scale))
      -- A transparent window repaints in full on any change: a clip frame
      -- blends its backdrop over the old pixels, which would show through a
      -- translucent window colour.
      transparent = isJust (sdlTransparent env)
  -- The render target and whether to repaint everything are chosen before
  -- the UI pass, so paint can cull to damage for retained partial updates.
  --
  -- Continuous sessions and live-resize frames repaint every pixel, so
  -- retaining and copying a second framebuffer only adds an FBO reattach/check,
  -- a full-window blit, and mid-drag FBO reallocations when growing past a
  -- bucket boundary. A null target selects the window backbuffer directly.
  -- Direct drawing is equivalent to the retained blit only at the same pixel
  -- dimensions; content scale and window pixel density can differ. Transparent
  -- windows always draw retained (the copy premultiplies alpha), and SDL 3.4's
  -- GPU renderer keeps its retained texture during live resize so
  -- 'presentGpuRetain' can blit 1:1 to the swapchain. Live resize leaves any
  -- existing retained texture allocated (only marking its used size stale) so
  -- neither allocation nor destruction stalls mid-drag, and post-drag frames
  -- reuse it when the settled size still fits.
  let direct = (sdlContinuous env || (settleDirty && not (sdlHasGpu env))) && not transparent && outputOk && fromIntegral ow == pw && fromIntegral oh == ph
  (tex, retainNew) <-
    if direct
      then do
        if sdlContinuous env
          then dropRetainRef (sdlRetain env)
          else do
            r <- readIORef (sdlRetain env)
            when (retainW r /= 0 || retainH r /= 0) $
              writeIORef (sdlRetain env) r {retainW = 0, retainH = 0}
        pure (nullPtr, False)
      else ensureRetain env pw ph scale
  let presentFull = forceFull || retainNew || direct || inputWindowRedraw inp
  -- Chrome regions a view handed over lapse with the first frame whose view
  -- does not hand them over again: a title bar no longer drawn must not
  -- leave its drag region and edges answering the desktop's hit test.
  let chrome = sdlChromeState env
  viewChrome <- readIORef (chromeFromView chrome)
  writeIORef (chromeFromView chrome) False
  t0 <- getMonotonicTime
  -- A full present ignores the frame's damage (below), so the frame need not
  -- work it out beyond what reusing its last draw takes.
  (drawData0, dirty0) <- withFramePaint ctx (presentFull || transparent) presentFull (evaluateUi inp)
  (drawData, dirtyAfterUi) <-
    if settleDirty && dirty0
      then do
        tMid <- getMonotonicTime
        atlasFull0 <- glyphAtlasFull (sdlFontCache env)
        if (atlasFull0 && not freshAtlas) || (tMid - t0 >= 0.004)
          then pure (drawData0, True)
          else do
            SdlImage.syncImageAtlas ren (sdlImages env) ctx
            _ <- takeDamage ctx
            writeIORef (chromeFromView chrome) False
            withFramePaint ctx (presentFull || transparent) presentFull (evaluateUi (clearEphemeral inp) {inputDeltaTime = 0})
      else pure (drawData0, dirty0)
  when viewChrome $
    unlessM (readIORef (chromeFromView chrome)) (writeIORef (chromeRegions chrome) defaultWindowChrome)
  -- Images registered during the view (an icon rasterized the first time it
  -- shows, a thumbnail on view) moved or grew the atlas this frame's UVs
  -- point into; upload them before drawing. Nothing changed costs a
  -- generation check.
  SdlImage.syncImageAtlas ren (sdlImages env) ctx
  t1 <- getMonotonicTime
  -- Sync SDL text input with the focus and caret every frame. A skipped
  -- frame would look like a focus change mid-composition and drop it.
  zoom <- windowZoom env
  _ <- syncTextInput (sdlTextInput env) (sdlWindow env) zoom ctx inp
  dmg0 <- takeDamage ctx
  -- Frame damage from writeDamage is authoritative: a live animation whose
  -- key is out of view or scroll-clipped produces empty damage, and forcing
  -- DamageFull here would turn every skip frame into a full present. A
  -- window redraw event (expose/restore) is the exception: the backbuffer
  -- is gone, so the next present must be full.
  let damage
        | presentFull = DamageFull
        | transparent = if damageIsEmpty dmg0 then dmg0 else DamageFull
        | otherwise = snapDamage scale dmg0
  writeIORef (sdlLastPresented env) False
  -- A glyph-atlas exhaustion during the UI pass means text quads the frame
  -- could not place. Drop the frame instead of presenting it: the screen
  -- keeps the previous valid frame, and the next frame resets the atlas
  -- before it records any quads and repaints whole, so text never flickers
  -- or vanishes for a frame ('ttfFrameDropped').
  atlasReset <- ttfFrameDropped (sdlFontCache env) ctx freshAtlas
  if atlasReset || damageIsEmpty damage || lw <= 0 || lh <= 0
    then do
      noteDebugSkip (sdlDebug env)
      -- With nothing to repaint, the retained frame on screen is this one.
      -- A dropped frame's screenshots wait for the next frame, which the
      -- reset requested.
      when (not atlasReset && damageIsEmpty damage && not direct) $
        answerScreenshots ctx (captureFrame env tex)
      pure (atlasReset || dirtyAfterUi)
    else do
      presentDamagedFrame ctx env tex direct scale damage drawData settleDirty t0 t1
      pure dirtyAfterUi
  where
    ren = sdlRenderer env

-- | Rasterise @drawData@ over @damage@, copy the retained texture (if used),
-- present the backbuffer, record frame timing, and answer pending screenshots.
presentDamagedFrame ::
  Context ->
  SdlEnv ->
  Ptr SDL_Texture ->
  Bool ->
  Float ->
  Damage ->
  DrawData ->
  Bool ->
  Double ->
  Double ->
  IO ()
presentDamagedFrame ctx env tex direct scale damage drawData inResizePass t0 t1 = do
  -- A null texture draws full-repaint sessions straight to the window. The
  -- pass scales positions itself, so the renderer stays at scale 1.
  unlessM ((&&) <$> setRetainTarget env tex <*> setRenderScale ren 1 1) $
    sdlFail "SDL_SetRenderTarget/Scale failed"
  let glyphs = glyphAtlasHandle (sdlFontCache env)
  -- A transparent window draws atlas textures with its own blend mode.
  -- Set it after the UI pass, which can create atlas textures.
  for_ (sdlTransparent env) $ \(blend, _) -> do
    textures <- (:) <$> SdlImage.lookupImage (sdlImages env) atlasTextureId <*> traverse (glyphPageTexture glyphs) [0 .. glyphAtlasPages - 1]
    for_ (filter (/= nullPtr) textures) (`setTextureBlendMode` blend)
  -- Full repaints clear the target, including bare backdrop regions.
  -- Partial updates preserve the undamaged part of the retained texture.
  -- A pass that throws drops its queued geometry, so none of it reaches the
  -- next frame.
  renderDrawDataPass (sdlBatch env) ren scale drawData (sdlImages env) glyphs damage
  t2 <- getMonotonicTime
  if direct
    then do
      sendSizeLimits env
      -- Read the direct backbuffer before present, but invoke view callbacks
      -- only afterwards, just as for retained frames.
      answerScreenshotsAfter ctx (captureFrame env tex) (void (renderPresentSafe ren))
    else do
      sendSizeLimits env
      presentedDirect <-
        if sdlHasGpu env && isNothing (sdlTransparent env) && isNothing (sdlForcedScale env)
          then do
            r <- readIORef (sdlRetain env)
            inDrag <- if inResizePass then pure True else windowInSizeMove (sdlWindow env)
            presentGpuRetain (sdlBatch env) (sdlWindow env) tex (retainW r) (retainH r) inDrag (drawClear drawData)
          else pure False
      unless presentedDirect $ do
        unlessM (copyRetained env tex) $
          sdlFail "SDL window presentation preparation failed"
        void (renderPresentSafe ren)
  t3 <- getMonotonicTime
  notePresent env t3
  noteDebugFrame (sdlDebug env) t0 t1 t2 t3 drawData
  writeIORef (sdlLastPresented env) True
  unless direct $ answerScreenshots ctx (captureFrame env tex)
  where
    ren = sdlRenderer env

-- | Copy the used area of the retained texture to the window, back in the
-- window's pixel coordinates for the events polled next. Damage limits
-- updates to the retained texture, not to this copy: SDL leaves the window
-- backbuffer undefined after each present. Passes an explicit 1:1 destination
-- rect unless @NANO_FORCE_SCALE@ is active so SDL never stretches the frame
-- onto a momentarily mismatched backbuffer.
copyRetained :: SdlEnv -> Ptr SDL_Texture -> IO Bool
copyRetained env tex = do
  okTarget <- setRenderTarget ren nullPtr
  okClip <- setRenderClipRect ren (PtrConst.unsafeFromPtr nullPtr)
  void $ setRenderScale ren 1 1
  -- The texture is larger than the window: copy only the used area.
  r <- readIORef (sdlRetain env)
  okCopy <- with (SDL_FRect 0 0 (fromIntegral (retainW r)) (fromIntegral (retainH r))) $ \src ->
    let dst = if isJust (sdlForcedScale env) then nullPtr else src
     in renderTexture ren tex (PtrConst.unsafeFromPtr src) (PtrConst.unsafeFromPtr dst)
  pure (okTarget && okClip && okCopy)
  where
    ren = sdlRenderer env

-- | SDL replaces a Wayland toplevel's size limits with its own at every
-- configure, so they go again with each present, which commits them. SDL's
-- are none, so no limits are sent only to clear the ones sent before.
sendSizeLimits :: SdlEnv -> IO ()
sendSizeLimits env = for_ (sdlSizeLimits env) $ \ref -> do
  limits@(nw, nh, xw, xh) <- readIORef ref
  let some = limits /= (0, 0, 0, 0)
  whenM ((some ||) <$> readIORef (sdlSizeLimitsSent env)) $ do
    sendWaylandSizeLimits (sdlWindow env) nw nh xw xh
    writeIORef (sdlSizeLimitsSent env) some

-- | Pixels a retained texture is rounded up to, in each dimension.
retainBlock :: Int
retainBlock = 256

ensureRetain :: SdlEnv -> Int -> Int -> Float -> IO (Ptr SDL_Texture, Bool)
ensureRetain env w h scale = do
  r <- readIORef (sdlRetain env)
  inDrag <- windowInSizeMove (sdlWindow env)
  let tex = retainTexture r
      fits = w <= retainCapW r && h <= retainCapH r
      -- Give memory back once the window is well inside the texture, but never
      -- mid-drag (which would allocate a fresh GPU render target during live
      -- resize) and not for a shrink of a block or so.
      roomy = not inDrag && (retainCapW r - w > 2 * retainBlock || retainCapH r - h > 2 * retainBlock)
      -- A new used size or density holds none of the frame to be drawn.
      stale = w /= retainW r || h /= retainH r || scaleMoved (retainScale r) scale
  if tex /= nullPtr && fits && not roomy
    then do
      when stale $ writeIORef (sdlRetain env) r {retainW = w, retainH = h, retainScale = scale}
      pure (tex, stale)
    else mask_ $ do
      let cw = roundUp w
          ch = roundUp h
      -- Allocate before replacing: failure leaves the owned texture valid.
      tex' <- createTexture (sdlRenderer env) Pixels.SDL_PIXELFORMAT_RGBA32 Render.SDL_TEXTUREACCESS_TARGET (fromIntegral cw) (fromIntegral ch)
      when (tex' == nullPtr) $ sdlFail "SDL_CreateTexture(retain) failed"
      void $ setTextureBlendMode tex' (maybe (fromIntegral sDL_BLENDMODE_NONE) snd (sdlTransparent env))
      writeIORef (sdlRetain env) (Retain tex' cw ch w h scale)
      unless (tex == nullPtr) $ destroyTexture tex
      pure (tex', True)
  where
    roundUp n = max retainBlock (((n + retainBlock - 1) `div` retainBlock) * retainBlock)

-- | After a render device reset, which emptied every texture: drop the
-- retained frame, the image atlas and the glyph pages, so the next frame
-- makes and fills them again. That frame repaints whole
-- ('NanoUI.Sdl.Internal.Input.EvRenderDeviceReset' asks for it).
resetRenderTextures :: SdlEnv -> IO ()
resetRenderTextures env = do
  dropRetainRef (sdlRetain env)
  SdlImage.destroyImageAtlas (sdlImages env)
  dropGlyphTextures (sdlFontCache env)

-- | Read the open session's debug information, refreshing at most four
-- times per second; 'Nothing' outside a session. Repeated queries keep the
-- debug sampler active and can schedule periodic frames.
askSdlDebug :: NanoUI (Maybe SdlDebugSnapshot)
askSdlDebug = withSdlEnv Nothing (fmap Just . sdlDebugSnapshot)

-- | 'askSdlDebug' for an explicit session, from IO.
sdlDebugSnapshot :: SdlEnv -> IO SdlDebugSnapshot
sdlDebugSnapshot env = do
  -- The display is queried only when the snapshot refreshes.
  refreshDebugSnapshot (sdlDebug env) (sdlDebugPublished env) $ \core -> do
    scale <- readIORef (sdlScaleRef env)
    fontSource <- sdlFontCacheSource (sdlFontCache env)
    period <- readIORef (sdlRefreshPeriodRef env)
    probe <- readIORef (sdlPresentProbe env)
    Size ww wh <- queryWindowLogicalSize (sdlWindow env)
    V2 mx my <- queryMouseWindowPos
    let snap =
          SdlDebugSnapshot
            { dbgCore = core {dbgWinW = ww, dbgWinH = wh, dbgMouseX = mx, dbgMouseY = my}
            , dbgScale = scale
            , dbgFontPath = fontSourceLabel fontSource
            , dbgRenderer = sdlRendererName env
            , dbgVsync = sdlVsync env && probe /= VsyncIgnored
            , dbgRefreshHz = round (1 / period)
            }
    when (sdlFrameTrace env) (traceFrame snap)
    pure snap

-- | Request a UI font family. The SDL display thread resolves and applies it
-- before the next frame, which this asks for (see
-- 'NanoUI.Backend.Sdl.syncDisplay'), rebuilding the glyph atlas and
-- text resolver.
setSdlUiFont :: NanoUIFont -> NanoUI ()
setSdlUiFont = requestDisplay sdlFontRequestRef

-- | Set the UI scale (see 'NanoUI.Backend.Sdl.sdlAppUiScale'): a zoom on top
-- of the pixel density, or zero or less to follow the display. The display
-- thread applies it before the next frame, which this asks for.
setSdlUiScale :: Float -> NanoUI ()
-- Not a number follows the display too, and is kept as zero: it is unequal
-- even to itself, so asking for it again would ask for a frame every time.
setSdlUiScale s = requestDisplay sdlUiScaleRef (if isNaN s then 0 else s)

-- | Hand the display thread a new setting and ask for the frame it is
-- applied before. Asking for the setting already asked for asks for nothing.
--
-- The setting is the session's, and the frame asked for is this window's.
-- The others follow: the first window syncs its display on every pass of
-- the loop, which a further window's frame request makes it run, and a
-- window that draws makes the windows it declared draw.
requestDisplay :: Eq a => (SdlEnv -> IORef a) -> a -> NanoUI ()
requestDisplay field new = do
  ctx <- askContext
  withSdlEnv () $ \env -> do
    cur <- readIORef (field env)
    when (cur /= new) $ writeIORef (field env) new >> markDirty ctx