nano-ui-0.2.0.0: lib/NanoUI/Backend.hs
-- |
-- Module : NanoUI.Backend
-- Description : What a window backend is built from
-- Copyright : (c) 2026 Zachary Churchill
-- License : MIT
-- Maintainer : zacharyachurchill@gmail.com
--
-- The parts of nano-ui a backend needs and a view does not: filling in a
-- frame's 'Input', measuring and shaping text for the widgets, reading back
-- the rectangles a frame changed, and running a view against a context.
-- @NanoUI.Backend.Sdl@ and @NanoUI.Backend.Rgfw@ are written against this
-- module; so is anything else that drives frames itself, such as a recorder,
-- a benchmark, or a test harness.
--
-- Writing a GUI needs none of it: "NanoUI" has the widgets, layout, styling
-- and state, and a backend's own runner (@runSdlApp@, @runRgfwApp@) starts
-- the loop. Nothing here shadows a name in "NanoUI": the names the two
-- share (the input types, 'FontMetrics', 'lineWidth', 'Appearance' and
-- 'WindowState') are the same entities in both, so importing both is safe.
--
-- A backend's frame is: collect events into an 'Input', run the view with
-- 'runFrame', take the 'Damage' and present the rectangles it names. 'Context'
-- holds state that outlives a frame. "NanoUI.Runner" supplies a reusable loop;
-- "NanoUI.Testing" adds assertions and inspection helpers for tests.
module NanoUI.Backend
( -- * Running a view
-- | Run the view only. 'runFrame' additionally solves layout and paints.
runNanoUI
, runFrame
-- ** Context setup
, Context
, newContext
, newPixelContext
, withFontMetrics
, withMonoFontMetrics
, withMeasureText
, withFontResolver
, withFontSize
, withClipboard
, withTheme
, setThemeIO
, getThemeIO
, followSystemThemeIO
-- ** Loop pacing and dirty state
, markDirty
, clearDirty
, isDirty
, requestWakeAt
, requestWakeAfter
, getWakeAt
-- ** Layout and color helpers
, Layout (..)
, onGrid
, roundHalfUp
, colorToWord32
, scrollBarTrackColor
, scrollBarThumbColor
, scrollBarThumbHoverColor
-- * Rendering a frame
-- ** Draw buffers and commands
, DrawData (..)
, DrawCmd (..)
, Layer (..)
, drawCmdNull
, drawCmdElems
, forDrawCmdsInLayer_
, drawCmdCount
, cmdEffectiveClip
, vertexSize
, indexSize
, collectRasterSpans
-- ** Shaders and effects
, ShaderCall (..)
, EffectSpan (..)
, EffectPassDraw (..)
, EffectDriver (..)
, spanEffectiveClip
, shiftClip
, execEffectSpans
, withEffectUniforms
, emptyShaderCalls
, emptyEffectSpans
, emptyUniformBytes
, ShaderProgram (..)
, ShaderCapabilities (..)
, noShaderCapabilities
, setShaderCapabilities
, getShaderCapabilities
, setDrawPixelScale
, sysUniformBytes
-- ** Frame caches
, IntGenCache
, newIntGenCache
, intGenCacheStartFrame
, intGenCacheLookup
, intGenCacheTouch
, intGenCacheInsert
, intGenCacheSize
-- ** Images and texture atlases
, registerImage
, registerImages
, releaseImage
, atlasTextureId
, atlasSnapshot
, atlasChanges
, AtlasUpload (..)
, backdropDimTextureId
, glyphAtlasTextureId
, glyphAtlasPages
, glyphPageTextureId
, textureGlyphPage
-- * Input
-- | Start from 'emptyInput' once. Each later frame carries the last
-- frame's input forward through 'clearEphemeral', which drops the
-- one-shot events (keys, typed text, clicks, scroll, drops) and keeps
-- what is held (buttons, pointer, modifiers, window size), then folds the
-- window's new events into it. Starting from 'emptyInput' every frame
-- instead loses held buttons and pointer position between events.
--
-- Keys go through 'applyKey', which tracks presses, releases and held
-- keys; mouse buttons through 'applyMouseButton' (numbered with
-- 'mouseButtonNumber'); dropped files through 'appendDropEvent'. When the
-- pointer leaves the window, 'applyPointerLeave' moves it off every
-- widget, unless a button is held. While one is, the backend keeps
-- delivering motion and the release from outside the window (capturing
-- the mouse where the platform allows), so a drag follows the pointer out
-- and back. When the window loses keyboard focus, 'releaseAllKeys'
-- releases the held keys, whose release events go elsewhere.
--
-- Every key goes in as a 'Key' whatever the modifiers; a key that types a
-- character is the 'KeyChar' it types with no modifier held. The typed
-- text also goes in 'inputChars'; a chord such as Ctrl+C types none.
-- Auto-repeats go in as presses, which 'applyKey' keeps out of
-- 'inputKeysNew'. 'keypadKey' maps keypad keys.
--
-- A frame does not keep the order of its text, keys and modifiers, so
-- 'NanoUI.Runner.runSessionLoop' ends a frame after a command key when
-- text, another key or a modifier change follows. A frame's text thus
-- comes before its one command key ('inputKeys'). A backend's own loop
-- should batch events the same way.
, Input (..)
, Key (..)
, Modifiers (..)
, MouseButton (..)
, mouseButtonNumber
, MouseButtons
, DropEvent (..)
, DropType (..)
, emptyInput
, applyMouseButton
, applyPointerLeave
, noButtons
, buttonsMember
, buttonsNull
, buttonsInsert
, buttonsDelete
, buttonsToList
, buttonsFromList
, clearEphemeral
, appendInputKey
, appendDropEvent
, inputInteracted
, inputPointerHeld
, inputKeysFromList
, inputKeysNull
, foldInputKeys
, applyKey
, releaseAllKeys
, keypadKey
, noModifiers
, modifiersFromBits
-- * Input methods
-- | An input method (IME) composes text before committing it, such as
-- Japanese kana before conversion to kanji. Fold each composition update
-- into the input with 'applyComposition'. The composition is held, like
-- a button, until the next update ends or replaces it, and the focused
-- text field draws it at its caret. Committed text arrives as typed text
-- in 'inputChars'.
--
-- After a frame, 'textInputArea' reports whether a text widget is active,
-- the candidate window placement, and the 'InputPurpose'. Enable platform
-- text input only while it returns 'Just', so the IME and on-screen
-- keyboard are active only during text entry. 'getFocusId' returns the
-- focused widget; drop any composition in progress when focus changes.
, Composition (..)
, applyComposition
, InputPurpose (..)
, TextInputArea (..)
, textInputArea
, getFocusId
-- * Cursors
, uiCursorKind
, UiCursorKind (..)
, cursorFallback
, syncCursorKind
-- * Fonts
-- | A backend configures the context with 'FontMetrics' containing a
-- 'FontBackend' for text measurement and shaping. 'prepareFontMetrics'
-- returns a snapshot with shaped metrics for a specific 'Data.Text.Text' (or the
-- original metrics when 'fmBackend' is 'Nothing'). 'drawShaped' shapes a
-- run into 'ShapedGlyphs', and 'drawGlyph' looks up a single glyph's
-- 'GlyphQuad' from the snapshot. A backend that loads other fonts or
-- rasterizes at a new scale calls 'clearMeasureCache', so text is
-- measured again with the new metrics.
, FontMetrics (..)
, FontBackend (..)
, prepareFontMetrics
, prepareFontMetricsMany
, scaleFontMetrics
, monospaceMetrics
, uiFontMetrics
, measureTextIO
, lineWidthIO
, lineWidth
, drawShaped
, drawGlyph
, drawTextBox
, GlyphQuad (..)
, ShapedText (..)
, ShapedGlyphs (..)
, clearMeasureCache
, wrapMeasureCache
, textNodeFontVariant
, textNodeFontTone
, textNodeFontWeight
, textNodeFontStyle
, textNodeTextDecoration
-- * Damage
-- | What changed since the last frame, so a backend can present part of
-- the window instead of all of it. 'takeDamage'
-- reads the frame's damage; the @Now@ functions mark a rectangle from
-- inside a view, which a custom widget that paints outside its own node
-- needs. 'damageFull' queues a whole-window repaint from outside a view,
-- as after a font change, when glyphs change under rects that did not.
, Damage (..)
, DamageBounds (..)
, takeDamage
, takeDamagePieces
, damagePieces
, damageIsEmpty
, pixelEdges
, clipPixelEdges
, snapDamage
, defaultDamageSlop
, sliderDamageSlop
, haloDamageSlop
, resolveDamageRect
, damageWidgetNow
, damageKeyNow
, damageRectNow
, damageGroupNow
, damageFullNow
, damageFull
-- * Frame metrics
-- | Standard widget padding and scrollbar dimensions, exposed for backends
-- that draw window chrome and for layout tests.
, widgetContentInset
, widgetPadding
, treeItemPadding
, ScrollBarSlot (..)
, scrollBarGutter
, scrollBarWidth
, windowPad
, windowMargin
-- * Widget ids
-- | How a @WidgetId@ is derived. A view uses @scope@, @withKey@ and
-- @nextId@ from "NanoUI" instead; this is for code that hashes ids the
-- same way nano-ui does. The operations on an 'IdContext' (the next
-- sibling's id, entering a scope or a key) are in "NanoUI.Internal.Id",
-- which can change without notice.
, IdContext
, initialIdContext
, widgetId
, hashWidgetId
, mix64
, mixFnv
, burstNextIds
-- * Compact allocation
-- | The compact region long-lived host state is kept in, so the
-- collector does not walk it every frame.
, Compact
, compactHost
, askCompact
-- * Debugging
-- | Control the @explainLayout@ overlay from outside the view, for a
-- backend option or a test harness.
, setExplainLayout
, getExplainLayout
, getExplainedNode
-- * System appearance
-- | A backend that can read the desktop's light or dark setting reports
-- it with 'setSystemAppearance' before the first frame and whenever it
-- changes. Views read it with @systemAppearance@; a context set up with
-- @followSystemTheme@ switches theme to match.
, Appearance (..)
, setSystemAppearance
, getSystemAppearance
-- * The native window
-- | A backend opens its window from a 'NanoUI.WindowSettings' with its
-- title, size, mode, resizability and transparency, then calls
-- 'installWindowHost', which applies the remaining settings through the
-- 'WindowHost'. The host carries out view requests such as
-- 'NanoUI.setWindowTitle' and 'NanoUI.moveWindow'. Build it by
-- updating 'defaultWindowHost', so fields added later are no-ops, and
-- set 'hostCapabilities' to the operations it carries out, which views
-- read with 'NanoUI.askWindowCapabilities'.
--
-- Each frame, before the view runs, report the window's scale, position,
-- focus and mode with 'reportWindowState' (views read it with
-- 'NanoUI.askWindow'). Once the frame is on screen, call
-- 'answerScreenshots' with a capture of it.
-- For a direct backbuffer use 'answerScreenshotsAfter' to capture before
-- presentation but deliver callbacks afterwards. Bracket the whole session
-- (including its opening frames) with 'closeWindowHost' and 'cancelTasks'
-- before releasing native resources. Both cleanups are idempotent.
--
-- @runSessionLoop@ in "NanoUI.Runner" handles closing: a close request
-- either ends the session or, per the settings, is passed to the view,
-- and 'NanoUI.quit' ends it. A backend's own loop does the same with
-- 'requestWindowClose' and 'quitRequested'; the next frame to run the
-- view clears the request ('clearWindowClose').
, WindowHost (..)
, defaultWindowHost
, WindowCapabilities (..)
, noWindowCapabilities
, allWindowCapabilities
, installWindowHost
, closeWindowHost
, sizeLimitAt
, WindowState (..)
, defaultWindowState
, reportWindowState
, answerScreenshots
, answerScreenshotsAfter
, requestWindowClose
, clearWindowClose
, quitRequested
-- ** More windows
-- | A view declares further windows with 'NanoUI.nativeWindow'. After a
-- frame, 'childWindows' lists those the view declared open; a backend
-- opens a window for each new key, runs 'childView' as its view on a
-- context of its own, and closes windows whose key stopped appearing.
-- Each window's loop also runs its view when 'varChangeCount' has moved
-- since that view last began, so a 'NanoUI.Var' written in one window
-- shows in the others.
, ChildWindow (..)
, childWindows
, childView
, varChangeCount
-- * The backend's session
-- | Each backend names itself in the 'Backend' kind, gives a
-- 'BackendSession' type family instance, and installs its session state
-- with 'withBackendSession'. SDL has its own constructor; every other
-- backend, RGFW included, uses @'Custom "name"@. Backend-specific view
-- operations retrieve the session with 'askBackendSession' and the
-- 'SBackend' singleton (returning 'Nothing' under other backends).
--
-- > type instance BackendSession 'Sdl = SdlEnv
-- > askSdlEnv = askBackendSession SSdl
-- >
-- > type instance BackendSession ('Custom "mine") = MyEnv
-- > askMyEnv = askBackendSession (SCustom (SSymbol @"mine"))
, Backend (..)
, SBackend (..)
, BackendSession
, withBackendSession
, setBackendSession
, backendSession
, askBackendSession
-- * Background work
-- | Background jobs (@useTaskStatus@, @useTask@, @useStream@) and
-- threads calling the action from @askWake@ wake the loop through the
-- action installed with 'setWakeLoop' before the first frame. It must be
-- callable from any thread and end the loop's wait for events, or make
-- the next wait return at once, for example by pushing a custom event
-- onto the platform queue. The core runs it once for a run of wakes until
-- the loop takes them, and not for dirty marks made on the thread running
-- @runSessionLoop@, so it needs no filtering of its own. Without it, a
-- blocking loop shows a job's result only when other input arrives.
--
-- 'markDirty' belongs to the thread that runs frames, or to a callback
-- that thread is blocked on, such as a resize watch. Any other thread
-- publishes its change and then calls the action from @askWake@, which
-- is safe from every thread.
--
-- Jobs run until their hooks stop being called. @runSessionLoop@ in
-- "NanoUI.Runner" cancels the rest when it returns; a host that runs
-- frames itself calls 'cancelTasks' when it closes the session.
, setWakeLoop
, setWakeLoopChecked
, cancelTasks
-- * Threads
, inBoundThread
)
where
import Control.Concurrent (rtsSupportsBoundThreads, runInBoundThread)
import NanoUI.Internal.Compact (Compact, askCompact, compactHost)
import NanoUI.Internal.BackendSession (Backend (..), BackendSession, SBackend (..))
import NanoUI.Internal.Context
( Context, newContext, newPixelContext, withFontMetrics, withMonoFontMetrics
, withMeasureText, withFontResolver, withFontSize, withClipboard, withTheme
, clearMeasureCache, wrapMeasureCache, damageFull
, markDirty, clearDirty, isDirty, requestWakeAt, requestWakeAfter, getWakeAt
, takeDamage, takeDamagePieces, registerImage, registerImages, releaseImage
, atlasTextureId, atlasSnapshot, atlasChanges, AtlasUpload (..)
, getExplainLayout, getExplainedNode, getFocusId, getSystemAppearance
, setExplainLayout, setSystemAppearance, setWakeLoop, setWakeLoopChecked
, withBackendSession, setBackendSession, backendSession
, setShaderCapabilities, getShaderCapabilities, setDrawPixelScale
)
import NanoUI.Internal.Context qualified as Ctx
import NanoUI.Internal.Shader (ShaderCapabilities (..), ShaderProgram (..), noShaderCapabilities)
import NanoUI.Internal.Uniforms (sysUniformBytes)
import NanoUI.Internal.Frame (runFrame)
import NanoUI.Internal.ChildWindow (ChildWindow (..), childView, childWindows)
import NanoUI.Internal.Var.Cell (varChangeCount)
import NanoUI.Internal.Frame.Spans (collectRasterSpans)
import NanoUI.Internal.Frame.Cursor (uiCursorKind)
import NanoUI.Internal.Damage (clipPixelEdges, damagePieces, pixelEdges, snapDamage)
import NanoUI.Internal.Frame.TextArea (TextInputArea (..), textInputArea)
import NanoUI.Internal.Draw hiding (setDrawPixelScale)
import NanoUI.Internal.EffectDriver
( EffectDriver (..)
, EffectPassDraw (..)
, execEffectSpans
, withEffectUniforms
)
import NanoUI.Internal.Font
import NanoUI.Internal.GenCache
( IntGenCache
, intGenCacheInsert
, intGenCacheLookup
, intGenCacheSize
, intGenCacheStartFrame
, intGenCacheTouch
, newIntGenCache
)
import NanoUI.Internal.Id
import NanoUI.Internal.Input
import NanoUI.Internal.Monad
import NanoUI.Internal.NativeWindow
( WindowHost (..)
, WindowCapabilities (..)
, WindowState (..)
, allWindowCapabilities
, noWindowCapabilities
, answerScreenshots
, answerScreenshotsAfter
, closeWindowHost
, clearWindowClose
, defaultWindowHost
, defaultWindowState
, installWindowHost
, quitRequested
, reportWindowState
, requestWindowClose
, sizeLimitAt
)
import NanoUI.Internal.Style (Appearance (..), Layout (..), Theme, scrollBarThumbColor, scrollBarThumbHoverColor, scrollBarTrackColor, windowMargin, windowPad)
import NanoUI.Internal.Tasks (cancelTasks)
import NanoUI.Internal.Types
import NanoUI.Internal.WidgetText (textNodeFontStyle, textNodeFontTone, textNodeFontVariant, textNodeFontWeight, textNodeTextDecoration)
-- | Set a fixed theme on a context from outside a view.
setThemeIO :: Context -> Theme -> IO ()
setThemeIO = Ctx.setTheme
-- | Read the context's current base theme from outside a view.
getThemeIO :: Context -> IO Theme
getThemeIO = Ctx.getTheme
-- | Configure a context to follow OS light/dark changes from outside a view.
followSystemThemeIO :: Context -> (Maybe Appearance -> Theme) -> IO ()
followSystemThemeIO = Ctx.followSystemTheme
-- | Run an action on a bound thread, one OS thread for the whole run, or
-- as it is under the non-threaded runtime, which runs Haskell on one OS
-- thread anyway. A backend runs its session in it when native state belongs
-- to the OS thread that made it: an OpenGL context is current only on the
-- thread that made it current, and on Windows the thread that creates a
-- window pumps its messages. An unbound Haskell thread can move to another
-- OS thread across a safe foreign call.
inBoundThread :: IO a -> IO a
inBoundThread act = if rtsSupportsBoundThreads then runInBoundThread act else act