nano-ui-0.2.0.0: lib/NanoUI/Internal/Context/Core.hs
-- | Accessors the other Context modules build on: interaction, overlay and
-- damage state, damage requests, the dirty flag, and widget store writes.
module 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
)
where
import Control.Concurrent (myThreadId)
import Control.Monad (forM_, unless, when, (<$!>))
import Data.Bits (shiftL, shiftR, (.&.), (.|.))
import Data.IORef (IORef, atomicModifyIORef', atomicWriteIORef, modifyIORef', readIORef, writeIORef)
import Data.Primitive.Array (readArray)
import Data.Primitive.PrimArray (readPrimArray)
import Data.Primitive.PrimVar (readPrimVar)
import Data.Primitive.SmallArray (SmallMutableArray, copySmallMutableArray, newSmallArray, readSmallArray, getSizeofSmallMutableArray, writeSmallArray)
import Data.IntMap.Strict qualified as IM
import Data.Foldable (foldlM)
import Data.Maybe (fromMaybe, isJust)
import Data.IntSet qualified as IS
import GHC.Clock (getMonotonicTime)
import GHC.Exts (RealWorld)
import System.Environment (lookupEnv)
import System.IO (hPutStrLn, stderr)
import System.IO.Unsafe (unsafePerformIO)
import NanoUI.Internal.Context.Types
import NanoUI.Internal.Id (WidgetId (..), hashWidgetId)
import NanoUI.Internal.Layout.Arena (NodeIdx, getArenaScope, getNodeScope, getScopeSignature, lookupNodeByWidgetId)
import NanoUI.Internal.Store
import NanoUI.Internal.Store.Slots (slotSeen)
import NanoUI.Internal.Style (Theme, disabledTheme)
import NanoUI.Internal.Types (Damage, DamageBounds (..), Rect (..), defaultDamageSlop, rectH, rectW)
import NanoUI.Widgets.TextCommand (TextCommand)
-- =============================================================================
-- State records
-- =============================================================================
-- | Read a projection of the interaction state.
{-# INLINE getsInteraction #-}
getsInteraction :: Context -> (InteractionState -> a) -> IO a
getsInteraction ctx f = f <$> readIORef (ctxInteractionState ctx)
-- | Strictly update interaction state on the UI thread. Does not request repaint.
{-# INLINE modifyInteraction #-}
modifyInteraction :: Context -> (InteractionState -> InteractionState) -> IO ()
modifyInteraction ctx = modifyIORef' (ctxInteractionState ctx)
-- | Read a projection of the overlay state.
{-# INLINE getsOverlay #-}
getsOverlay :: Context -> (OverlayState -> a) -> IO a
getsOverlay ctx f = f <$> readIORef (ctxOverlayState ctx)
-- | Strictly update overlay state on the UI thread. Does not request repaint.
{-# INLINE modifyOverlay #-}
modifyOverlay :: Context -> (OverlayState -> OverlayState) -> IO ()
modifyOverlay ctx = modifyIORef' (ctxOverlayState ctx)
-- | Read a projection of the damage bookkeeping.
{-# INLINE getsDamage #-}
getsDamage :: Context -> (DamageState -> a) -> IO a
getsDamage ctx f = f <$> readIORef (ctxDamageState ctx)
-- | Strictly update damage bookkeeping without waking the event loop.
{-# INLINE modifyDamage #-}
modifyDamage :: Context -> (DamageState -> DamageState) -> IO ()
modifyDamage ctx = modifyIORef' (ctxDamageState ctx)
-- =============================================================================
-- Interaction
-- =============================================================================
-- | Read and clear the last command run by a text-edit menu, with its target id.
takeTextEditLastAction :: Context -> IO (Maybe (WidgetId, TextCommand))
takeTextEditLastAction ctx = do
act <- getsInteraction ctx isTextEditLastAction
modifyInteraction ctx (\s -> s {isTextEditLastAction = Nothing})
pure act
-- | Whether a held button went down on a menu or dropdown rather than on a
-- layer's widgets. Nothing in the layers is hot while it lasts.
{-# INLINE pointerHeldOffLayers #-}
pointerHeldOffLayers :: Context -> IO Bool
pointerHeldOffLayers ctx =
getsInteraction ctx $ \s ->
isPointerHeld s && case isPointerRoute s of
RouteLayer _ -> False
_ -> True
-- =============================================================================
-- Damage
-- =============================================================================
-- | Queue repaint bounds for the frame's damage pass. Does not wake the loop;
-- call 'markDirty' as well when a new frame must be scheduled.
{-# INLINE requestDamage #-}
requestDamage :: Context -> DamageRequest -> IO ()
requestDamage ctx req = modifyDamage ctx (\ds -> ds {dsRequests = req : dsRequests ds})
-- | Queue damage relative to a widget's previous and current bounds. Zero ids
-- are ignored. Does not itself schedule a frame.
{-# INLINE damageWidget #-}
damageWidget :: Context -> WidgetId -> DamageBounds -> IO ()
damageWidget ctx wid bounds
| hashWidgetId wid == 0 = pure ()
| otherwise = requestDamage ctx (ReqWidget wid bounds)
-- | Queue widget damage by integer store key. Zero keys are ignored.
{-# INLINE damageKey #-}
damageKey :: Context -> Int -> DamageBounds -> IO ()
damageKey ctx k bounds
| k == 0 = pure ()
| otherwise = requestDamage ctx (ReqKey k bounds)
-- | Queue an explicit logical window rectangle. Empty rectangles are ignored.
{-# INLINE damageRect #-}
damageRect :: Context -> Rect -> IO ()
damageRect ctx r
| rectW r <= 0 || rectH r <= 0 = pure ()
| otherwise = requestDamage ctx (ReqRect r)
-- | Queue the same damage rule for a group of nonzero widget ids.
{-# INLINE damagePeers #-}
damagePeers :: Context -> [WidgetId] -> DamageBounds -> IO ()
damagePeers ctx wids bounds =
case filter (\w -> hashWidgetId w /= 0) wids of
[] -> pure ()
valid -> requestDamage ctx (ReqPeers valid bounds)
-- | Queue a whole-window repaint. Call 'markDirty' if the loop also needs waking.
{-# INLINE damageFull #-}
damageFull :: Context -> IO ()
damageFull ctx = requestDamage ctx ReqFull
-- | Whether @NANO_DAMAGE_TRACE@ is set, read once per process.
{-# NOINLINE damageTraceOn #-}
damageTraceOn :: Bool
damageTraceOn = unsafePerformIO (isJust <$> lookupEnv "NANO_DAMAGE_TRACE")
-- | With @NANO_DAMAGE_TRACE@ set, write a line to stderr. Each frame's damage
-- pass writes @DAMAGE clip@ or @DAMAGE full@ with the check that chose a
-- whole-window repaint; the fallbacks that queue one write @DAMAGE-REQ@ with
-- their name. Counting the lines over a test run shows which checks repaint
-- the window most.
traceDamage :: String -> IO ()
traceDamage msg = when damageTraceOn (hPutStrLn stderr msg)
-- | Request another view pass and wake the event loop, unless this is the
-- loop's own thread, which checks the flag before it waits.
-- Dirty state schedules work; damage determines which pixels are repainted.
-- The follow-up frame repaints what its diff finds changed: nodes whose
-- rect or paint inputs changed, store keys, and the hot, active and focused
-- widgets. A change to anything else nano-ui paints from also needs
-- 'damageFull'.
--
-- Call it on the thread that runs frames, or on one that thread is blocked
-- on (as SDL's resize watch is): the flag shares a plain 'IORef' with the
-- frame's damage bookkeeping. Other threads publish their change and call
-- 'wakeFromThread' (the action from 'NanoUI.askWake'), which is atomic.
{-# INLINE markDirty #-}
markDirty :: Context -> IO ()
markDirty ctx = do
modifyDamage ctx (\ds -> ds {dsDirty = True})
wakeOffLoop ctx
-- | Record a layout read for key @k@ during view construction. After layout
-- completes, 'settleLayoutReads' runs @stale@ to check whether the newly
-- computed layout differs from the value read, and schedules a follow-up frame
-- if so. Unread layout changes do not schedule a frame. Only the first read
-- of each key per settle cycle is retained.
recordLayoutRead :: Context -> Int -> IO Bool -> IO ()
recordLayoutRead ctx k stale =
modifyDamage ctx (\ds -> ds {dsLayoutReads = IM.insertWith (\_ old -> old) k stale (dsLayoutReads ds)})
-- | Run all pending 'recordLayoutRead' checks against the completed layout
-- and clear the table. Every check is executed so callbacks can also publish
-- measured geometry ('publishLayoutSlots'). Any stale read schedules a
-- damage-covered follow-up frame.
settleLayoutReads :: Context -> IO ()
settleLayoutReads ctx = do
pending <- getsDamage ctx dsLayoutReads
unless (IM.null pending) $ do
modifyDamage ctx (\ds -> ds {dsLayoutReads = IM.empty})
stale <- foldlM (\acc check -> (acc ||) <$> check) False pending
when stale (markDirty ctx)
-- | Clear the follow-up-frame request without clearing queued repaint bounds.
-- The whole-window repaint a 'markDirty' queued stays for the next frame.
{-# INLINE clearDirty #-}
clearDirty :: Context -> IO ()
clearDirty ctx = modifyDamage ctx (\ds -> ds {dsDirty = False})
-- | Whether state changes require another view pass.
{-# INLINE isDirty #-}
isDirty :: Context -> IO Bool
isDirty ctx = getsDamage ctx dsDirty
-- | Install the backend action that interrupts an event wait. A background
-- producer should invoke the wake action after publishing synchronised data.
-- The action runs once for a run of wakes until the loop takes them
-- ('takeWakes'), and not for the loop thread's own dirty marks, so it need
-- not filter or coalesce calls itself.
{-# INLINE setWakeLoop #-}
setWakeLoop :: Context -> IO () -> IO ()
setWakeLoop ctx wake = setWakeLoopChecked ctx (True <$ wake)
-- | 'setWakeLoop' for an action that can fail to reach the loop, such as a
-- push onto a full event queue. It returns whether it did; after a failure
-- the next wake runs it again instead of taking the loop as woken.
{-# INLINE setWakeLoopChecked #-}
setWakeLoopChecked :: Context -> IO Bool -> IO ()
setWakeLoopChecked ctx wake = writeIORef (ctxWakeLoop ctx) (Just wake)
-- | Run @loopRef@ unless @pendingRef@ already marks a wake in flight.
-- Resets @pendingRef@ when no callback is installed or the callback reports
-- delivery failure, so a later wake is not swallowed.
{-# INLINE triggerWake #-}
triggerWake :: IORef Bool -> IORef (Maybe (IO Bool)) -> IO ()
triggerWake pendingRef loopRef = do
wasPending <- atomicModifyIORef' pendingRef (True,)
unless wasPending $ do
delivered <- readIORef loopRef >>= fromMaybe (pure False)
unless delivered (atomicWriteIORef pendingRef False)
-- | Run the wake action, unless an earlier wake ran it and the loop has not
-- taken that one yet: the loop reads what both changed when it does. A wake
-- the action did not deliver, or made with no action installed, leaves
-- nothing pending, so a later wake is not swallowed waiting for it.
wakeLoop :: Context -> IO ()
wakeLoop ctx = triggerWake (ctxWakePending ctx) (ctxWakeLoop ctx)
-- | 'wakeLoop' for a dirty mark. The thread running
-- 'NanoUI.Runner.runSessionLoop' checks the dirty flag before waiting, so
-- its own marks during a frame need not wake the event wait.
wakeOffLoop :: Context -> IO ()
wakeOffLoop ctx =
readIORef (ctxLoopThread ctx) >>= \case
Nothing -> wakeLoop ctx
Just loop -> myThreadId >>= \me -> unless (me == loop) (wakeLoop ctx)
-- | Clear 'ctxWakePending' so the next wake invokes the backend wake callback
-- again. Called after each event wait and at the start of every frame
-- ('takeThreadWake').
{-# INLINE takeWakes #-}
takeWakes :: Context -> IO ()
takeWakes ctx = atomicWriteIORef (ctxWakePending ctx) False
-- | Build a thread-safe wake action that retains only the wake 'IORef's and
-- never the full 'Context', preventing background jobs and callbacks from
-- pinning stale font metrics or caches across font reloads.
wakeAction :: Context -> IO ()
wakeAction ctx =
let !wokenRef = ctxWoken ctx
!pendingRef = ctxWakePending ctx
!loopRef = ctxWakeLoop ctx
in do
atomicWriteIORef wokenRef True
triggerWake pendingRef loopRef
-- | Wake the loop from any thread after changing state the view reads.
-- Publish the change first. The next frame runs the view, and its diff
-- repaints what the change altered.
wakeFromThread :: Context -> IO ()
wakeFromThread = wakeAction
-- | At frame start, before the view runs: take the wakes so far
-- ('takeWakes'), and clear the record of a 'wakeFromThread' call. Calls made
-- while the view runs are left for the frame they wake.
{-# INLINE takeThreadWake #-}
takeThreadWake :: Context -> IO ()
takeThreadWake ctx = do
takeWakes ctx
atomicWriteIORef (ctxWoken ctx) False
-- | Schedule a frame at a monotonic timestamp ('getMonotonicTime') even if no
-- input arrives. The earliest deadline wins. Cleared at the start of each
-- frame ('clearWakeAt'), so active widgets must re-register their deadline on
-- each view pass. UI thread only; background threads use 'wakeFromThread'.
requestWakeAt :: Context -> Double -> IO ()
requestWakeAt ctx t = do
cur <- readIORef (ctxWakeAt ctx)
when (t > 0 && (cur <= 0 || t < cur)) $ writeIORef (ctxWakeAt ctx) t
-- | 'requestWakeAt', in seconds from now.
requestWakeAfter :: Context -> Double -> IO ()
requestWakeAfter ctx sec = do
now <- getMonotonicTime
requestWakeAt ctx (now + max 0 sec)
-- | Pending wake timestamp, or 0 if none.
{-# INLINE getWakeAt #-}
getWakeAt :: Context -> IO Double
getWakeAt ctx = readIORef (ctxWakeAt ctx)
-- | Clear the timed wake request at frame start; live widgets request it again.
{-# INLINE clearWakeAt #-}
clearWakeAt :: Context -> IO ()
clearWakeAt ctx = writeIORef (ctxWakeAt ctx) 0
-- | Read the last computed damage. Despite the name, this does not clear it.
{-# INLINE takeDamage #-}
takeDamage :: Context -> IO Damage
takeDamage ctx = getsDamage ctx dsDamage
-- | The disjoint rects a 'NanoUI.Backend.DamageClip' frame repaints, when its damage lies in
-- two or more places far apart; empty when the whole clip repaints. A
-- backend that draws text itself must clip it to each; draw commands
-- already are.
{-# INLINE takeDamagePieces #-}
takeDamagePieces :: Context -> IO [Rect]
takeDamagePieces ctx = getsDamage ctx dsDamagePieces
-- | Last recorded widget bounds in logical window coordinates, with scrolling
-- applied. 'Nothing' means the damage pass recorded no bounds for this id.
{-# INLINE getPrevRect #-}
getPrevRect :: Context -> WidgetId -> IO (Maybe Rect)
getPrevRect ctx wid = getsDamage ctx (IM.lookup (intKey wid) . pfRects . dsPrev)
-- | 'getPrevRect' of @wid@, declared as node @idx@, or an empty rect. A
-- widget declared where it was last frame, as views rebuilt in the same
-- order are, is read by node index from the last walk's record
-- ('ctxPrevWalk'); any other from the map, whose lookup misses the cache in
-- a large view. The bang on the id keeps it unboxed in callers.
{-# NOINLINE getPrevRectAt #-}
getPrevRectAt :: Context -> NodeIdx -> WidgetId -> IO Rect
getPrevRectAt ctx !idx (WidgetId !w) = do
walk <- readIORef (ctxPrevWalk ctx)
valid <- readPrimVar (pwValid walk)
let !k = fromIntegral w
here <- if k /= 0 && idx >= 0 && idx < valid then (== k) <$> readPrimArray (pwKeys walk) idx else pure False
if here
then readArray (pwRects walk) idx
else fromMaybe (Rect 0 0 0 0) <$!> getsDamage ctx (IM.lookup k . pfRects . dsPrev)
-- | Whether a pointer-taking node drawn over @wid@ (by layers or a pin) has
-- the pointer instead, in the frame the user saw ('ctxPointerReach'). Only
-- meaningful for a widget under the pointer. Widgets that hit-test presses
-- against their own rect, rather than via
-- 'NanoUI.Internal.Widgets.Node.Response', must check this too.
{-# INLINE pointerCovered #-}
pointerCovered :: Context -> WidgetId -> IO Bool
pointerCovered ctx wid = maybe False (not . IS.member (intKey wid)) <$> readIORef (ctxPointerReach ctx)
-- | Last recorded widget clip in logical window coordinates, or 'Nothing'.
{-# INLINE getPrevClipRect #-}
getPrevClipRect :: Context -> WidgetId -> IO (Maybe Rect)
getPrevClipRect ctx wid = getsDamage ctx (IM.lookup (intKey wid) . pfClips . dsPrev)
-- =============================================================================
-- Store
-- =============================================================================
-- | Current immutable store value. Mutations must be published through store
-- operations so the context can track damage and follow-up frames.
{-# INLINE getStore #-}
getStore :: Context -> IO WidgetStore
getStore ctx = readIORef (ctxStore ctx)
-- | Replace the store, diff changed slots for damage, and wake on a change.
setStore :: Context -> WidgetStore -> IO ()
setStore ctx store = modifyStore ctx (const store)
-- | Apply @f@ to the store, damage any keys whose values changed, and mark the
-- context dirty.
modifyStore :: Context -> (WidgetStore -> WidgetStore) -> IO ()
modifyStore ctx f = do
prev <- readIORef (ctxStore ctx)
-- WHNF-force the new record: record-update arguments are unevaluated
-- thunks, and writeIORef would otherwise park one in the long-lived store
-- every frame.
let !store = f prev
writeIORef (ctxStore ctx) store
let changedKeys =
slotChangedKeys prev store
++ diffKeys (storeFloat prev) (storeFloat store)
++ diffKeys (storePoint prev) (storePoint store)
-- The key diff doubles as the store comparison: checking 'prev /= store'
-- first would walk every changed map twice. Its lazy concatenation stops at
-- the first changed key and allocates less than a list per map.
when
( storeOpenSelect prev /= storeOpenSelect store
|| not (null changedKeys)
)
$ do
forM_ changedKeys $ \k -> damageKey ctx k (DamageInflated defaultDamageSlop)
markDirty ctx
-- | Run slot writes, unless every slot already holds its value: an idle
-- widget then neither rebuilds the store nor has it diffed.
{-# INLINE writeSlots #-}
writeSlots :: Context -> SlotWrites -> IO ()
writeSlots ctx (SlotWrites same f) = do
st <- readIORef (ctxStore ctx)
unless (same st) (setStore ctx (f st))
-- | Write layout-derived slots (such as scroll geometry) for the next view
-- pass without marking the context dirty; views that depend on these values
-- schedule a follow-up frame via 'recordLayoutRead'. Store diffing in
-- 'NanoUI.Internal.Damage.writeDamage' still records paint damage.
publishLayoutSlots :: Context -> SlotWrites -> IO ()
publishLayoutSlots ctx (SlotWrites same f) = do
st <- readIORef (ctxStore ctx)
unless (same st) (writeIORef (ctxStore ctx) $! f st)
-- | Targeted single-slot write: compares only the target slot, updates one map
-- field, damages the owning widget and wakes the loop. Unlike 'setStore' it
-- never diffs the whole store, and an equal write is a no-op.
{-# INLINE writeSlot #-}
writeSlot :: Eq a => Field a -> Context -> WidgetId -> Int -> a -> IO ()
writeSlot field ctx owner k v = do
st <- readIORef (ctxStore ctx)
case lookupSlot field k st of
Just old | old == v -> pure ()
_ -> do
writeIORef (ctxStore ctx) $! insertSlot field k v st
damageWidget ctx owner DamageSelf
markDirty ctx
-- | Write a boolean at the owner's base integer key, with change detection.
{-# INLINE writeStoreBool #-}
writeStoreBool :: Context -> WidgetId -> Bool -> IO ()
writeStoreBool ctx owner v = writeSlot fieldInt ctx owner (intKey owner) (boolInt v)
-- | Controlled widgets take their value from the caller every frame. The
-- caller's value replaces the stored one only when it differs from the value
-- the widget last returned ('recordSlot'). An edit applied between frames,
-- such as a menu cut, then survives a caller that passes the previous result
-- back, while a value changed by the application still wins. Returns the
-- value of the owner's slot after adopting.
{-# INLINE adoptSlot #-}
adoptSlot :: Eq a => Field a -> Context -> WidgetId -> a -> IO a
adoptSlot field ctx owner v = do
st <- readIORef (ctxStore ctx)
let k = intKey owner
if lookupSpec (slotSeen field) k st == Just v
then pure $! findSlot field v k st
else do
writeIORef (ctxStore ctx) $! insertSpec (slotSeen field) k v (insertSlot field k v st)
when (lookupSlot field k st /= Just v) $ do
damageWidget ctx owner DamageSelf
markDirty ctx
pure v
-- | Remember the value a controlled widget returned this frame.
{-# INLINE recordSlot #-}
recordSlot :: Eq a => Field a -> Context -> Int -> a -> IO ()
recordSlot field ctx k v = do
st <- readIORef (ctxStore ctx)
when (lookupSpec (slotSeen field) k st /= Just v) $
writeIORef (ctxStore ctx) $! insertSpec (slotSeen field) k v st
-- | Whether @wid@ is in a disabled scope. Falls back to the arena's active
-- scope when called before the widget's node is allocated.
{-# INLINE isDisabled #-}
isDisabled :: Context -> WidgetId -> IO Bool
isDisabled ctx wid = do
ts <- readIORef (ctxThemeScopes ctx)
if tsDisabled ts then scopeDisabled ctx wid else pure False
{-# INLINE widgetScope #-}
widgetScope :: Context -> WidgetId -> IO Int
widgetScope Context {ctxNodeArena = na} wid =
lookupNodeByWidgetId na wid >>= maybe (getArenaScope na) (getNodeScope na)
{-# NOINLINE scopeDisabled #-}
scopeDisabled :: Context -> WidgetId -> IO Bool
scopeDisabled ctx wid = (/= 0) . (.&. 1) <$> widgetScope ctx wid
-- =============================================================================
-- Theme scopes
-- =============================================================================
-- | Display-only descendants cannot acquire focus or handle input. Before a
-- widget is added, inspect the open scope instead of its not-yet-built node.
{-# INLINE isInert #-}
isInert :: Context -> WidgetId -> IO Bool
isInert ctx wid = (/= 0) . (.&. 2) <$> widgetScope ctx wid
-- | Allocate empty current/previous scope arrays. Only entries below their
-- recorded counts are initialised and may be read.
newThemeScopes :: IO ThemeScopes
newThemeScopes = do
let unset = error "theme scope: unset"
cur <- newSmallArray 8 unset
raw <- newSmallArray 8 unset
prev <- newSmallArray 8 unset
pure
ThemeScopes
{ tsCount = 0
, tsThemes = cur
, tsRaw = raw
, tsPrevCount = 0
, tsPrev = prev
, tsDisabled = False
, tsChanged = False
, tsPrevSig = 0
}
-- | Start a view pass with no pushed themes. The first pass of a frame keeps
-- last frame's themes to compare against; a rebuild pass keeps comparing
-- against the same ones.
beginThemeScopes :: Context -> Bool -> IO ()
beginThemeScopes ctx newFrame = do
ts <- readIORef (ctxThemeScopes ctx)
if newFrame
then do
sig <- getScopeSignature (ctxNodeArena ctx)
writeIORef (ctxThemeScopes ctx) $!
ts
{ tsCount = 0
, tsThemes = tsPrev ts
, tsPrevCount = tsCount ts
, tsPrev = tsThemes ts
, tsDisabled = False
, tsChanged = False
, tsPrevSig = sig
}
else writeIORef (ctxThemeScopes ctx) $! ts {tsCount = 0, tsDisabled = False, tsChanged = False}
-- | Add a scope with its disabled status and raw theme, painted faded
-- ('disabledTheme') when disabled. Returns the packed arena scope (the
-- one-based theme index and the disabled bit) and records whether the painted
-- theme differs from the previous frame's theme at that index.
pushThemeScope :: Context -> Bool -> Theme -> IO Int
pushThemeScope ctx disabled raw = do
ts <- readIORef (ctxThemeScopes ctx)
let !i = tsCount ts
theme = if disabled then disabledTheme raw else raw
-- The two arrays grow separately: 'tsThemes' trades places with
-- 'tsPrev' each frame, so its capacity can differ from that of 'tsRaw'.
withRoom arr fill = do
cap <- getSizeofSmallMutableArray arr
if i < cap
then pure arr
else do
grown <- newSmallArray (cap * 2) fill
copySmallMutableArray grown 0 arr 0 i
pure grown
themes <- withRoom (tsThemes ts) theme
raws <- withRoom (tsRaw ts) raw
same <-
if i < tsPrevCount ts
then (== theme) <$> readSmallArray (tsPrev ts) i
else pure False
writeSmallArray themes i theme
writeSmallArray raws i raw
writeIORef (ctxThemeScopes ctx) $!
ts {tsCount = i + 1, tsThemes = themes, tsRaw = raws, tsDisabled = tsDisabled ts || disabled, tsChanged = tsChanged ts || not same}
pure (((i + 1) `shiftL` 2) .|. fromEnum disabled)
-- | Whether this frame's scopes look different from last frame's: a theme
-- changed, scopes were added or dropped, or nodes moved between scopes.
themeScopesChanged :: Context -> IO Bool
themeScopesChanged ctx = do
ts <- readIORef (ctxThemeScopes ctx)
sig <- getScopeSignature (ctxNodeArena ctx)
pure (tsChanged ts || tsCount ts /= tsPrevCount ts || sig /= tsPrevSig ts)
-- | Painted theme for a packed arena scope. Theme index zero uses the base
-- theme; other indices must name a scope registered during this view pass.
{-# INLINE scopeTheme #-}
scopeTheme :: Context -> Int -> IO Theme
scopeTheme = scopeThemeIn tsThemes
-- | A scope's theme before any disabled scope faded it.
scopeRawTheme :: Context -> Int -> IO Theme
scopeRawTheme = scopeThemeIn tsRaw
-- | The theme a packed arena scope names in one of the scope arrays, or the
-- base theme for theme index zero.
{-# INLINE scopeThemeIn #-}
scopeThemeIn :: (ThemeScopes -> SmallMutableArray RealWorld Theme) -> Context -> Int -> IO Theme
scopeThemeIn arr ctx scope
| ti == 0 = readIORef (ctxTheme ctx)
| otherwise = do
ts <- readIORef (ctxThemeScopes ctx)
readSmallArray (arr ts) (ti - 1)
where
!ti = scope `shiftR` 2
-- | Active theme for the current arena scope.
{-# INLINE currentTheme #-}
currentTheme :: Context -> IO Theme
currentTheme ctx = getArenaScope (ctxNodeArena ctx) >>= scopeTheme ctx
-- | Painted theme recorded on a live node, including disabled styling.
{-# INLINE nodeTheme #-}
nodeTheme :: Context -> NodeIdx -> IO Theme
nodeTheme ctx idx = getNodeScope (ctxNodeArena ctx) idx >>= scopeTheme ctx
-- | The theme of @wid@'s node, or of the current scope before it has one.
widgetTheme :: Context -> WidgetId -> IO Theme
widgetTheme ctx wid = do
ts <- readIORef (ctxThemeScopes ctx)
if tsCount ts == 0
then readIORef (ctxTheme ctx)
else widgetScope ctx wid >>= scopeTheme ctx