packages feed

nano-ui-0.2.0.0: lib/NanoUI/Runner.hs

-- | The event loop the backends share: event waiting and frame pacing, click
-- counting, the redraw decision, quit handling, and the drawing lock. A
-- backend supplies a 'SessionDriver' for event translation and presentation.
module NanoUI.Runner
  ( -- * Drawing Lock
    DrawingLock (..)
  , newDrawingLock
  , tryWithDrawingLock
    -- * Redraw Decision
  , shouldRedrawFrame
  , ClickTracker
  , newClickTracker
  , stampClicks
  , maxFrameDt
  , wakeTimeoutMs
  , shorterWait
  , windowTimeoutMs
  , takeDueWake
    -- * Frame pacing
  , pacingMsFor
  , waitUntil
    -- * Session loop
  , SessionDriver (..)
  , LoopWindows (..)
  , DebugSamplerRef
  , newDebugSampler
  , runSessionLoop
  ) where

import Control.Concurrent (myThreadId, threadDelay)
import Control.Exception (finally, mask)
import Control.Monad (forM_, unless, when)
import Data.Maybe (isJust)
import Data.Text qualified as T
import Numeric (showFFloat)
import System.Environment (lookupEnv)
import System.IO (BufferMode (LineBuffering), hFlush, hPutStrLn, hSetBuffering, stderr)
import Data.IORef
  ( IORef
  , atomicModifyIORef'
  , atomicWriteIORef
  , newIORef
  , readIORef
  , writeIORef
  )
import GHC.Clock (getMonotonicTime)
import NanoUI.Internal.Context
import NanoUI.Internal.Debug
import NanoUI.Internal.Frame.Input (needsRedraw)
import NanoUI.Internal.Input
import NanoUI.Internal.NativeWindow (closeWindowSlot, quitRequested, requestWindowClose)
import NanoUI.Internal.Tasks (cancelTasksOf)
import NanoUI.Internal.Widgets.Shortcut (hardQuitUsed)
import NanoUI.Internal.Types (V2 (..))

-- | Standard upper bound for single-frame delta-time (50ms).
maxFrameDt :: Float
maxFrameDt = 0.05

-- | Wind forward to the next frame boundary after a timed-out event wait.
-- When pacing is active the backend requests a wait of ~period, but a one-shot
-- sleep lets frame starts drift by the scheduler's timer granularity (and land
-- late whenever the event waiter overruns), which reads as choppy animation on
-- uneven frame times. 'waitUntil' sleeps the bulk and spins the tail, so frame
-- starts fall on uniform slices of the pacing period. The spin only runs when
-- an animation is actively presenting without vsync, and is bounded to about a
-- millisecond.
--
-- The grid starts at @lastT@, when the loop took the previous pass's events.
-- SDL aligns in its own 'sdPacedWait' instead, from when its pass began and
-- by the refresh period of the display the window is on now, which a fixed
-- 'sdAlignSec' cannot follow.
alignFrameStart :: Double -> Double -> IO ()
alignFrameStart periodSec lastT = waitUntil (lastT + periodSec)

-- | Wait until a 'getMonotonicTime' time: sleep for most of it, then spin
-- the last quarter millisecond, which a sleep overshoots. Returns at once for
-- a time already past.
waitUntil :: Double -> IO ()
waitUntil target = do
  t0 <- getMonotonicTime
  let bulkUs = round ((target - t0 - tailSlack) * 1e6) :: Int
  when (bulkUs > 0) (threadDelay bulkUs)
  spin
  where
    tailSlack = 2.5e-4
    spin = do
      now <- getMonotonicTime
      when (now < target) spin

-- | The event wait, in milliseconds, between the frames of an animation
-- whose presents do not wait for the display, for a refresh period in
-- seconds: 2 ms short of the period, at least 1. An event wait can overrun
-- by about a millisecond, and a wait that returns past the frame boundary
-- makes the frame late; the loop spins the rest of the way to the boundary
-- ('waitUntil').
pacingMsFor :: Double -> Int
pacingMsFor period = max 1 (floor (period * 1000) - 2)

-- | The previous press's time, position, buttons and click count.
type ClickTracker = IORef (Double, V2, MouseButtons, Int)

-- | Allocate an empty multi-click state tracker for 'stampClicks'.
newClickTracker :: IO ClickTracker
newClickTracker = newIORef (0, V2 (-999) (-999), noButtons, 0)

-- | Stamp multi-click counts into an 'Input'. A press of the same buttons
-- within 5 pixels and 0.4 seconds of the previous press counts up, to a
-- triple click at most.
stampClicks :: ClickTracker -> Input -> IO Input
stampClicks ref inp
  | not (anyButtonPressed inp) = pure inp
  | otherwise = do
      now <- getMonotonicTime
      (t, V2 px py, prevButtons, n) <- readIORef ref
      let pos@(V2 x y) = inputMousePos inp
          buttons = inputButtonsPressed inp
          close = (x - px) * (x - px) + (y - py) * (y - py) <= 25
          !n' = if close && buttons == prevButtons && now - t <= 0.4 then min 3 (n + 1) else 1
      writeIORef ref (now, pos, buttons, n')
      pure (inp {inputMouseClicks = n'})

-- | Concurrency lock for drawing vs async callbacks (e.g. resize watchers).
newtype DrawingLock = DrawingLock (IORef Bool)

-- | Create a new unacquired drawing lock.
newDrawingLock :: IO DrawingLock
newDrawingLock = DrawingLock <$> newIORef False

-- | Attempt to execute an action under the drawing lock without blocking.
tryWithDrawingLock :: DrawingLock -> IO a -> IO (Maybe a)
tryWithDrawingLock (DrawingLock ref) act = mask $ \restore -> do
  ok <- atomicModifyIORef' ref $ \busy -> (True, not busy)
  if ok
    then Just <$> (restore act `finally` atomicWriteIORef ref False)
    else pure Nothing

-- | Centralized decision predicate: should the host backend redraw this frame?
shouldRedrawFrame ::
  Context ->
  Input ->       -- ^ Previous input
  Input ->       -- ^ Current input
  Bool ->        -- ^ Was animating on previous frame?
  Bool ->        -- ^ Continuous redraw requested?
  Bool ->        -- ^ A frame is due without input: a timed wake or a debug readout refresh?
  IO Bool
shouldRedrawFrame ctx prevInp curInp wasAnim continuous refreshDue = do
  if continuous || refreshDue
    then pure True
    else do
      -- 'needsRedraw' already covers a dirty context and running animations,
      -- so an animation that just ended is the only animation case left: it
      -- needs one final frame.
      need <- needsRedraw ctx prevInp curInp
      -- A 'NanoUI.Internal.Context.wakeFromThread' not yet taken by a frame:
      -- a background job has published something the view reads. The frame
      -- takes it ('takeThreadWake'), so only peek here.
      woken <- readIORef (ctxWoken ctx)
      let pointerEdge = anyButtonPressed curInp || anyButtonReleased curInp
          scrollEdge = inputScroll curInp /= V2 0 0
          -- Two auto-repeats of a held key, or one character typed twice,
          -- arrive as equal inputs, which 'needsRedraw' cannot tell apart.
          keyEdge =
            not (inputKeysNull (inputKeys curInp) && inputKeysNull (inputKeysReleased curInp))
              || not (T.null (inputChars curInp) && null (inputDrops curInp))
      pure (need || woken || wasAnim || pointerEdge || scrollEdge || keyEdge)

-- | What a backend provides to 'runSessionLoop'.
data SessionDriver ev = SessionDriver
  { sdPollEvents    :: IO [ev]
    -- ^ Non-blocking poll for pending backend events.
  , sdWaitEvents    :: Int -> IO [ev]
    -- ^ Wait for events with a timeout in milliseconds (-1 indicates blocking wait).
  , sdPacedWait     :: Maybe (Int -> IO [ev])
    -- ^ The backend's own wait between the frames of a running animation,
    -- if it has one. The loop calls it in place of 'sdWaitEvents' when its
    -- timeout is this window's 'sdPacingMs' wait for an animation (or a
    -- continuous session paced by time), and does not wind a frame it
    -- times out of onto 'sdAlignSec': the backend's wait starts the next
    -- frame on its own grid. With 'Nothing' the loop calls 'sdWaitEvents'
    -- and aligns the frame itself.
  , sdApplyEvent    :: Input -> ev -> Input
    -- ^ Fold an event into the 'Input' state.
  , sdIsButtonEdge  :: ev -> Bool
    -- ^ Predicate identifying click/press boundaries where the event stream
    -- should be split. 'NanoUI.Internal.Input.takeFrame' also splits after a
    -- command key whose order relative to other input matters.
  , sdIsSessionQuit :: ev -> Bool
    -- ^ Predicate for window close requests. A request ends the session
    -- unless 'NanoUI.wsExitOnCloseRequest' is off, in which case it is
    -- reported on the next frame via 'NanoUI.winCloseRequested'.
  , sdSyncDisplay   :: Context -> Input -> IO (Context, Input)
    -- ^ Backend-specific display synchronization (window dimensions, DPI scale).
  , sdDebug         :: DebugSamplerRef
    -- ^ The session's debug sampler: loop timing, skips, and the 4 Hz
    -- readout refresh.
  , sdContinuous    :: !Bool
    -- ^ Redraw every pass without waiting for events. The loop waits 0 ms
    -- between passes while 'sdPresentPaces' holds or 'sdVsyncOff' is set,
    -- and 'sdPacingMs' otherwise, as for an animation.
  , sdVsyncOff      :: !Bool
    -- ^ Whether the backend turned vertical sync off on purpose, so a
    -- continuous session draws as fast as it can. With this 'False', a
    -- continuous session whose presents stop waiting for the display (a
    -- driver ignoring vsync) is paced at 'sdPacingMs' instead.
  , sdPacingMs      :: !Int
    -- ^ Event wait in milliseconds while something animates.
  , sdPresentPaces  :: IO Bool
    -- ^ Whether the last present waited for the display (vsync), so a running
    -- animation can loop without waiting and still be frame-locked.
  , sdAlignSec      :: Double
    -- ^ Frame pacing period in seconds for the timed-out wait path. Frame
    -- starts are wound onto a uniform grid of this period so animation
    -- cadence matches the host, instead of drifting with the event waiter's
    -- timer granularity.
  , sdShouldDraw    :: Context -> Input -> Input -> Bool -> Bool -> IO Bool
    -- ^ Decision predicate: (ctx, prevInp, curInp, wasAnimating, refreshDue) ->
    -- should this frame be rendered? Usually 'shouldRedrawFrame' with the
    -- driver's 'sdContinuous' as its continuous flag:
    -- @\\c p i a r -> shouldRedrawFrame c p i a continuous r@.
  , sdDraw          :: Context -> Input -> Bool -> IO Bool
    -- ^ Render frame: (ctx, curInp, forceFull) -> dirtyAfterRender.
  , sdOnCursor      :: Context -> Input -> IO ()
    -- ^ Sync the host cursor icon after every pass.
  , sdShouldQuit    :: Input -> Bool
    -- ^ Application-level quit predicate.
  , sdWindows       :: Maybe LoopWindows
    -- ^ Further windows the session runs beside this one
    -- ("NanoUI.Runner.Windows"), if the backend has them.
  }

-- | What the loop needs of a session's further windows.
data LoopWindows = LoopWindows
  { lwWait :: IO Int
    -- ^ The longest wait, in milliseconds, they allow; -1 for no limit.
  , lwFirstDue :: IO Bool
    -- ^ Whether this window must run its view: a 'NanoUI.Var' it may read
    -- changed since it last did.
  , lwDrew :: IO ()
    -- ^ This window just ran its view.
  , lwAfterPass :: Context -> IO ()
    -- ^ Run their passes, after each of this window's.
  }

-- | NANO_LOOP_TRACE: on the first pass a second or more after the last line,
-- print to stderr the time covered, how many passes the loop made in it, how
-- many of them drew, and why. A busy loop prints a line a second. An idle
-- window prints nothing, and the line after a quiet spell covers all of it,
-- so whatever prints steadily is what keeps the process awake. The
-- reasons are @D@ a dirty context, @A@ an animation, @R@ a window redraw
-- request, and @T@ a timed wake or a debug readout refresh; a pass with none
-- of them was caused by input.
data LoopTraceState = LoopTraceState !Double !Int !Int !Int ![String]

type LoopTrace = Maybe (IORef LoopTraceState)

newLoopTrace :: Double -> IO LoopTrace
newLoopTrace now = do
  on <- isJust <$> lookupEnv "NANO_LOOP_TRACE"
  -- stderr is unbuffered by default, which writes a line a character at a
  -- time: enough system calls to show up in the measurement being taken.
  when on (hSetBuffering stderr LineBuffering)
  if on then Just <$> newIORef (LoopTraceState now 0 0 0 []) else pure Nothing

traceLoopPass :: LoopTrace -> Int -> Bool -> String -> IO ()
traceLoopPass lt nEvents drew why = forM_ lt $ \ref -> do
  now <- getMonotonicTime
  LoopTraceState t0 passes draws events whys <- readIORef ref
  let !passes' = passes + 1
      !draws' = if drew then draws + 1 else draws
      !events' = events + nEvents
      whys' = if passes < 24 then (if null why then "-" else why) : whys else whys
  if now - t0 >= 1
    then do
      hPutStrLn stderr $
        "LOOP " ++ showFFloat (Just 1) (now - t0) "s passes=" ++ show passes' ++ " draws=" ++ show draws'
          ++ " events=" ++ show events' ++ " why=" ++ unwords (reverse whys')
      hFlush stderr
      writeIORef ref $! LoopTraceState now 0 0 0 []
    else writeIORef ref $! LoopTraceState t0 passes' draws' events' whys'

-- | Added to the wait for a timed wake, so the wait ends at or after the time
-- asked for. An OS wait can return a millisecond or two early, and a backend
-- that counts its timeout in whole milliseconds turns the fraction then left
-- into a wait of zero: without the pad the loop spins through that last
-- millisecond, dozens of empty passes for every wake. The frame comes this
-- much late instead, which nothing scheduled to the millisecond can notice;
-- animation is paced separately.
wakePadMs :: Int
wakePadMs = 2

-- | The event wait, in milliseconds, until a timed wake at @wakeAt@ (0 for
-- none, which waits without limit) from @now@. An hour at most: the backends
-- take a 32-bit timeout, and the loop waits again when it runs out.
wakeTimeoutMs :: Double -> Double -> Int
wakeTimeoutMs wakeAt now
  | wakeAt <= 0 = -1
  | wakeAt <= now = 0
  | otherwise = ceiling (min 3600 (wakeAt - now) * 1000) + wakePadMs

-- | The shorter of two waits, where -1 is no limit.
shorterWait :: Int -> Int -> Int
shorterWait a b
  | a < 0 = b
  | b < 0 = a
  | otherwise = min a b

-- | Milliseconds a window may sleep before its next frame: @pacingMs@ when an
-- animation is active or just ended, else the remaining time until 'getWakeAt'.
windowTimeoutMs :: Bool -> Int -> Context -> IO Int
windowTimeoutMs wasAnim pacingMs ctx = do
  animating <- (wasAnim ||) <$> anyAnimating ctx
  if animating
    then pure pacingMs
    else wakeTimeoutMs <$> getWakeAt ctx <*> getMonotonicTime

-- | Check whether a scheduled wake deadline has arrived; if so, clear it so a
-- skipped frame does not spin on an expired timestamp, and return 'True'.
takeDueWake :: Context -> IO Bool
takeDueWake ctx = do
  wakeAt <- getWakeAt ctx
  due <- if wakeAt > 0 then (>= wakeAt) <$> getMonotonicTime else pure False
  when due (clearWakeAt ctx)
  pure due

-- | Event wait while only the debug readout needs frames: its refresh period.
debugHudTimeout :: Int
debugHudTimeout = round (debugRefreshSec * 1000)

-- | Run an event-driven session loop until the window is closed, a view
-- calls 'NanoUI.quit', or 'sdShouldQuit' returns 'True'. Ctrl+C closes the
-- window too, after its frame, unless a shortcut took it or the focused
-- widget uses it, as a text field does to copy. Background tasks started by
-- the view are cancelled on exit.
runSessionLoop ::
  SessionDriver ev ->
  Context ->
  Input ->
  IO ()
runSessionLoop drv ctx0 inp0 = do
  clickTracker <- newClickTracker
  startT <- getMonotonicTime
  trace <- newLoopTrace startT

  let -- A paced wait is one a running animation times out of, so the frame it
      -- ends on is wound onto the pacing grid. Any other wait ends whenever
      -- its event or deadline arrives.
      waitForEvents timeout paced lastT
        | timeout < 0 = sdWaitEvents drv (-1)
        | otherwise = do
            polled <- sdPollEvents drv
            if not (null polled)
              then pure polled
              else case sdPacedWait drv of
                Just pacedWait | paced && timeout > 0 -> pacedWait timeout
                _ -> do
                  events <- sdWaitEvents drv timeout
                  when (paced && timeout > 0 && null events) $
                    alignFrameStart (sdAlignSec drv) lastT
                  pure events

      nextBatch ctx queued lastT pendingDirty wasAnim
        | not (null queued) = pure (queued, False)
        | pendingDirty = (,False) <$> waitForEvents 0 False lastT
        | otherwise = do
            (debugActive, dueNow) <- debugCadence (sdDebug drv)
            animating <- anyAnimating ctx
            dirty <- isDirty ctx
            woken <- readIORef (ctxWoken ctx)
            presentPaces <- sdPresentPaces drv
            wakeAt <- getWakeAt ctx
            waitT <- if wakeAt > 0 then getMonotonicTime else pure 0
            others <- maybe (pure (-1)) lwWait (sdWindows drv)
            let wakeMs = wakeTimeoutMs wakeAt waitT
                idleMs = if debugActive then shorterWait debugHudTimeout wakeMs else wakeMs
                -- A continuous session whose presents do not wait for the
                -- display, though vsync was asked for, is paced by time.
                continuousPaced = sdContinuous drv && not presentPaces && not (sdVsyncOff drv)
                own
                  | dueNow || dirty || woken || (animating && presentPaces) = 0
                  | sdContinuous drv && not continuousPaced = 0
                  | wasAnim || animating || continuousPaced = sdPacingMs drv
                  | otherwise = idleMs
                timeout = shorterWait own others
                -- A wait another window shortened ends off this one's grid.
                paced = (wasAnim || animating || continuousPaced) && timeout == own
            events <- waitForEvents timeout paced lastT
            wakeDue <- takeDueWake ctx
            let hudDue = timeout == debugHudTimeout && debugActive && null events
            firstDue <- maybe (pure False) lwFirstDue (sdWindows drv)
            pure (events, dueNow || wakeDue || hudDue || firstDue)

      loop ctx inp queued lastT pendingDirty wasAnim = do
        (pending, refreshDue) <- nextBatch ctx queued lastT pendingDirty wasAnim
        -- Reset the wake latch before reading state updated by background
        -- threads, so a subsequent wake triggers the callback again.
        takeWakes ctx

        now <- getMonotonicTime
        let !dt = min maxFrameDt (realToFrac (now - lastT))
            (frameInp, group, rest) =
              takeFrame (sdApplyEvent drv) (sdIsButtonEdge drv) (clearEphemeral inp {inputDeltaTime = dt}) pending
        let closing = any (sdIsSessionQuit drv) group
        closeNow <- if closing then requestWindowClose ctx else pure False
        unless closeNow $ do
          noteDebugLoop (sdDebug drv) dt
          inpStamped <- stampClicks clickTracker frameInp
          (ctx', inpSynced) <- sdSyncDisplay drv ctx inpStamped
          shouldDraw <- if pendingDirty
            then pure True
            else sdShouldDraw drv ctx' inp inpSynced wasAnim refreshDue
          -- Force a full present only on the settle frame where an
          -- animation just finished (wasAnim && not animNow), so running
          -- animations keep clip damage.
          animNow <- anyAnimating ctx'
          dirtyOut <- if shouldDraw
            then sdDraw drv ctx' inpSynced (wasAnim && not animNow) <* mapM_ lwDrew (sdWindows drv)
            else pendingDirty <$ noteDebugSkip (sdDebug drv)
          sdOnCursor drv ctx' inpSynced
          mapM_ (`lwAfterPass` ctx') (sdWindows drv)
          animAfter <- anyAnimating ctx'
          traceLoopPass trace (length group) shouldDraw $
            (if pendingDirty then "D" else "")
              ++ (if wasAnim || animAfter then "A" else "")
              ++ (if inputWindowRedraw inpSynced then "R" else "")
              ++ (if refreshDue then "T" else "")
          -- Ctrl+C closes the window as its close button does, once the frame
          -- has shown that nothing in the view used it.
          used <- if isHardQuitInput frameInp then hardQuitUsed ctx' inpSynced else pure True
          hardQuit <- if used then pure False else requestWindowClose ctx'
          overlayQuit <- overlayConsumesQuit ctx' inpSynced
          quit <- quitRequested ctx'
          -- The next pass was animating if this frame was, even when this
          -- frame's tick finished the animation: its view read the value
          -- before that tick, so one more (settle) frame draws the end value.
          unless (quit || hardQuit || (sdShouldQuit drv inpSynced && not overlayQuit)) $
            loop ctx' inpSynced rest now dirtyOut animNow

  -- The session's end needs only refs that every copy of the context shares.
  -- Holding 'ctx0' until then would keep its font metrics, and their caches,
  -- alive after a font reload hands the loop a new context.
  let !window = ctxNativeWindow ctx0
      !wake = ctxWakeLoop ctx0
      !held = ctxHeld ctx0
      !loopThread = ctxLoopThread ctx0
  -- This thread's dirty marks need no wake action ('markDirty').
  myThreadId >>= writeIORef loopThread . Just
  -- An opening frame the backend drew before the loop may have called
  -- 'NanoUI.quit' already; waiting first could block for good.
  (quitRequested ctx0 >>= \quit -> unless quit (loop ctx0 inp0 [] startT False False))
    `finally` (closeWindowSlot window `finally` cancelTasksOf wake held `finally` writeIORef loopThread Nothing)