nano-ui-sdl 0.1.0.1 → 0.2.0.0
raw patch · 66 files changed
+9120/−5362 lines, 66 filesdep +nano-ui-emitdep +nano-ui-shaderdep +nano-ui-ttfdep −dir-traversedep −effectful-coredep −file-embeddep ~basedep ~containersdep ~nano-uinew-component:exe:nano-ui-sdl-idlePVP ok
version bump matches the API change (PVP)
Dependencies added: nano-ui-emit, nano-ui-shader, nano-ui-ttf, resourcet, vector
Dependencies removed: dir-traverse, effectful-core, file-embed, hashable, unordered-containers
Dependency ranges changed: base, containers, nano-ui, sdl3-bindgen-sys, text
API changes (from Hackage documentation)
- NanoUI.Backend.Sdl: FileDialogId :: Int -> FileDialogId
- NanoUI.Backend.Sdl: SdlEnv :: Ptr SDL_Window -> Ptr SDL_Renderer -> Text -> RenderBatch -> IORef NanoUIFont -> IORef NanoUIFont -> Maybe Float -> IORef Float -> IORef Float -> GlyphAtlas -> ImageAtlas -> SdlCursors -> SdlDebugSampler -> IORef Retain -> IORef Bool -> Bool -> Double -> Bool -> IORef Context -> SdlFontCache -> DialogState -> SdlEnv
- NanoUI.Backend.Sdl: [sdlBatch] :: SdlEnv -> RenderBatch
- NanoUI.Backend.Sdl: [sdlCachedCtx] :: SdlEnv -> IORef Context
- NanoUI.Backend.Sdl: [sdlContinuous] :: SdlEnv -> Bool
- NanoUI.Backend.Sdl: [sdlCursors] :: SdlEnv -> SdlCursors
- NanoUI.Backend.Sdl: [sdlDebug] :: SdlEnv -> SdlDebugSampler
- NanoUI.Backend.Sdl: [sdlDialogState] :: SdlEnv -> DialogState
- NanoUI.Backend.Sdl: [sdlFontAppliedRef] :: SdlEnv -> IORef NanoUIFont
- NanoUI.Backend.Sdl: [sdlFontCache] :: SdlEnv -> SdlFontCache
- NanoUI.Backend.Sdl: [sdlFontRequestRef] :: SdlEnv -> IORef NanoUIFont
- NanoUI.Backend.Sdl: [sdlForcedScale] :: SdlEnv -> Maybe Float
- NanoUI.Backend.Sdl: [sdlGlyphAtlas] :: SdlEnv -> GlyphAtlas
- NanoUI.Backend.Sdl: [sdlImages] :: SdlEnv -> ImageAtlas
- NanoUI.Backend.Sdl: [sdlLastPresented] :: SdlEnv -> IORef Bool
- NanoUI.Backend.Sdl: [sdlRefreshPeriod] :: SdlEnv -> Double
- NanoUI.Backend.Sdl: [sdlRendererName] :: SdlEnv -> Text
- NanoUI.Backend.Sdl: [sdlRenderer] :: SdlEnv -> Ptr SDL_Renderer
- NanoUI.Backend.Sdl: [sdlRetain] :: SdlEnv -> IORef Retain
- NanoUI.Backend.Sdl: [sdlScaleRef] :: SdlEnv -> IORef Float
- NanoUI.Backend.Sdl: [sdlUiScaleRef] :: SdlEnv -> IORef Float
- NanoUI.Backend.Sdl: [sdlVsync] :: SdlEnv -> Bool
- NanoUI.Backend.Sdl: [sdlWindowBorderless] :: SdlOptions -> Bool
- NanoUI.Backend.Sdl: [sdlWindowFullscreen] :: SdlOptions -> Bool
- NanoUI.Backend.Sdl: [sdlWindowHidden] :: SdlOptions -> Bool
- NanoUI.Backend.Sdl: [sdlWindowResizable] :: SdlOptions -> Bool
- NanoUI.Backend.Sdl: [sdlWindowSize] :: SdlOptions -> Size
- NanoUI.Backend.Sdl: [sdlWindowTitle] :: SdlOptions -> Text
- NanoUI.Backend.Sdl: [sdlWindow] :: SdlEnv -> Ptr SDL_Window
- NanoUI.Backend.Sdl: newtype FileDialogId
- NanoUI.Sdl.Input: EvDisplayScale :: SdlEvent
- NanoUI.Sdl.Input: EvDrop :: DropEvent -> SdlEvent
- NanoUI.Sdl.Input: EvKey :: Key -> Modifiers -> SdlEvent
- NanoUI.Sdl.Input: EvMouseMotion :: V2 -> Modifiers -> SdlEvent
- NanoUI.Sdl.Input: EvMousePress :: V2 -> Modifiers -> SdlEvent
- NanoUI.Sdl.Input: EvMouseRelease :: V2 -> Modifiers -> SdlEvent
- NanoUI.Sdl.Input: EvMouseRightPress :: V2 -> Modifiers -> SdlEvent
- NanoUI.Sdl.Input: EvMouseRightRelease :: V2 -> Modifiers -> SdlEvent
- NanoUI.Sdl.Input: EvQuit :: SdlEvent
- NanoUI.Sdl.Input: EvRefresh :: SdlEvent
- NanoUI.Sdl.Input: EvResize :: Int -> Int -> SdlEvent
- NanoUI.Sdl.Input: EvScroll :: V2 -> SdlEvent
- NanoUI.Sdl.Input: EvText :: Text -> Modifiers -> SdlEvent
- NanoUI.Sdl.Input: EvWindowRedraw :: SdlEvent
- NanoUI.Sdl.Input: applyEvent :: Input -> SdlEvent -> Input
- NanoUI.Sdl.Input: data SdlEvent
- NanoUI.Sdl.Input: instance GHC.Internal.Classes.Eq NanoUI.Sdl.Input.SdlEvent
- NanoUI.Sdl.Input: instance GHC.Internal.Show.Show NanoUI.Sdl.Input.SdlEvent
- NanoUI.Sdl.Input: isButtonEdge :: SdlEvent -> Bool
- NanoUI.Sdl.Input: isHardQuit :: SdlEvent -> Bool
- NanoUI.Sdl.Input: pollEvents :: IO [SdlEvent]
- NanoUI.Sdl.Input: waitEvent :: IO (Maybe SdlEvent)
- NanoUI.Sdl.Input: waitEventTimeout :: Int -> IO (Maybe SdlEvent)
- NanoUI.Sdl.NanoUIFont: DefaultFont :: NanoUIFont
- NanoUI.Sdl.NanoUIFont: FontFilePath :: FilePath -> NanoUIFont
- NanoUI.Sdl.NanoUIFont: FontSearch :: [String] -> NanoUIFont
- NanoUI.Sdl.NanoUIFont: data NanoUIFont
- NanoUI.Sdl.NanoUIFont: instance GHC.Internal.Classes.Eq NanoUI.Sdl.NanoUIFont.NanoUIFont
- NanoUI.Sdl.NanoUIFont: instance GHC.Internal.Show.Show NanoUI.Sdl.NanoUIFont.NanoUIFont
+ NanoUI.Backend.Sdl: CaptionOptions :: CaptionConfig -> Float -> Float -> CaptionOptions
+ NanoUI.Backend.Sdl: CoreDebugSnapshot :: Double -> Double -> Double -> Double -> Double -> Double -> Word64 -> Word64 -> Int -> Int -> Int -> Float -> Float -> Float -> Float -> [(Text, Text)] -> CoreDebugSnapshot
+ NanoUI.Backend.Sdl: DecorationsFrame :: WindowDecorations
+ NanoUI.Backend.Sdl: DecorationsFull :: WindowDecorations
+ NanoUI.Backend.Sdl: DecorationsNone :: WindowDecorations
+ NanoUI.Backend.Sdl: Fullscreen :: WindowMode
+ NanoUI.Backend.Sdl: Hidden :: WindowMode
+ NanoUI.Backend.Sdl: RenderDriverAuto :: RenderDriver
+ NanoUI.Backend.Sdl: RenderDriverGpu :: RenderDriver
+ NanoUI.Backend.Sdl: RenderDriverNamed :: ByteString -> RenderDriver
+ NanoUI.Backend.Sdl: RenderDriverSdlDefault :: RenderDriver
+ NanoUI.Backend.Sdl: WindowChrome :: [Rect] -> Float -> Float -> WindowChrome
+ NanoUI.Backend.Sdl: WindowPositionAt :: Int -> Int -> WindowPosition
+ NanoUI.Backend.Sdl: WindowPositionCentered :: WindowPosition
+ NanoUI.Backend.Sdl: WindowPositionDefault :: WindowPosition
+ NanoUI.Backend.Sdl: WindowSettings :: Text -> Size -> WindowPosition -> Maybe Size -> Maybe Size -> Maybe RgbaPixels -> Bool -> WindowMode -> Bool -> Float -> Bool -> WindowSettings
+ NanoUI.Backend.Sdl: Windowed :: WindowMode
+ NanoUI.Backend.Sdl: [capButtons] :: CaptionOptions -> CaptionConfig
+ NanoUI.Backend.Sdl: [capResizeBorder] :: CaptionOptions -> Float
+ NanoUI.Backend.Sdl: [capResizeTop] :: CaptionOptions -> Float
+ NanoUI.Backend.Sdl: [chromeDrag] :: WindowChrome -> [Rect]
+ NanoUI.Backend.Sdl: [chromeResizeBorder] :: WindowChrome -> Float
+ NanoUI.Backend.Sdl: [chromeResizeTop] :: WindowChrome -> Float
+ NanoUI.Backend.Sdl: [dbgCmds] :: CoreDebugSnapshot -> Int
+ NanoUI.Backend.Sdl: [dbgFrameMs] :: CoreDebugSnapshot -> Double
+ NanoUI.Backend.Sdl: [dbgIndices] :: CoreDebugSnapshot -> Int
+ NanoUI.Backend.Sdl: [dbgLoopFps] :: CoreDebugSnapshot -> Double
+ NanoUI.Backend.Sdl: [dbgMouseX] :: CoreDebugSnapshot -> Float
+ NanoUI.Backend.Sdl: [dbgMouseY] :: CoreDebugSnapshot -> Float
+ NanoUI.Backend.Sdl: [dbgPresentFps] :: CoreDebugSnapshot -> Double
+ NanoUI.Backend.Sdl: [dbgPresentMs] :: CoreDebugSnapshot -> Double
+ NanoUI.Backend.Sdl: [dbgPresents] :: CoreDebugSnapshot -> Word64
+ NanoUI.Backend.Sdl: [dbgRenderMs] :: CoreDebugSnapshot -> Double
+ NanoUI.Backend.Sdl: [dbgRts] :: CoreDebugSnapshot -> [(Text, Text)]
+ NanoUI.Backend.Sdl: [dbgSkips] :: CoreDebugSnapshot -> Word64
+ NanoUI.Backend.Sdl: [dbgUiMs] :: CoreDebugSnapshot -> Double
+ NanoUI.Backend.Sdl: [dbgVerts] :: CoreDebugSnapshot -> Int
+ NanoUI.Backend.Sdl: [dbgWinH] :: CoreDebugSnapshot -> Float
+ NanoUI.Backend.Sdl: [dbgWinW] :: CoreDebugSnapshot -> Float
+ NanoUI.Backend.Sdl: [sdlAppThemeFor] :: SdlOptions -> Maybe (Maybe Appearance -> Theme)
+ NanoUI.Backend.Sdl: [sdlExplainLayout] :: SdlOptions -> Bool
+ NanoUI.Backend.Sdl: [sdlRenderDriver] :: SdlOptions -> RenderDriver
+ NanoUI.Backend.Sdl: [sdlWindowDecorations] :: SdlOptions -> WindowDecorations
+ NanoUI.Backend.Sdl: [sdlWindowSettings] :: SdlOptions -> WindowSettings
+ NanoUI.Backend.Sdl: [wsExitOnCloseRequest] :: WindowSettings -> Bool
+ NanoUI.Backend.Sdl: [wsIcon] :: WindowSettings -> Maybe RgbaPixels
+ NanoUI.Backend.Sdl: [wsMaxSize] :: WindowSettings -> Maybe Size
+ NanoUI.Backend.Sdl: [wsMinSize] :: WindowSettings -> Maybe Size
+ NanoUI.Backend.Sdl: [wsMode] :: WindowSettings -> WindowMode
+ NanoUI.Backend.Sdl: [wsOpacity] :: WindowSettings -> Float
+ NanoUI.Backend.Sdl: [wsPosition] :: WindowSettings -> WindowPosition
+ NanoUI.Backend.Sdl: [wsResizable] :: WindowSettings -> Bool
+ NanoUI.Backend.Sdl: [wsSize] :: WindowSettings -> Size
+ NanoUI.Backend.Sdl: [wsTitle] :: WindowSettings -> Text
+ NanoUI.Backend.Sdl: [wsTransparent] :: WindowSettings -> Bool
+ NanoUI.Backend.Sdl: askSdlEnv :: NanoUI (Maybe SdlEnv)
+ NanoUI.Backend.Sdl: captureScreenshot :: SdlEnv -> IO (Maybe Screenshot)
+ NanoUI.Backend.Sdl: clearWindowChrome :: SdlEnv -> IO ()
+ NanoUI.Backend.Sdl: clearWindowChromeUi :: NanoUI ()
+ NanoUI.Backend.Sdl: data CaptionOptions
+ NanoUI.Backend.Sdl: data CoreDebugSnapshot
+ NanoUI.Backend.Sdl: data FileDialogId
+ NanoUI.Backend.Sdl: data RenderDriver
+ NanoUI.Backend.Sdl: data WindowChrome
+ NanoUI.Backend.Sdl: data WindowDecorations
+ NanoUI.Backend.Sdl: data WindowMode
+ NanoUI.Backend.Sdl: data WindowPosition
+ NanoUI.Backend.Sdl: data WindowSettings
+ NanoUI.Backend.Sdl: defaultCaptionOptions :: CaptionOptions
+ NanoUI.Backend.Sdl: defaultResizeBorder :: Float
+ NanoUI.Backend.Sdl: defaultWindowChrome :: WindowChrome
+ NanoUI.Backend.Sdl: defaultWindowSettings :: WindowSettings
+ NanoUI.Backend.Sdl: formatDrawRows :: CoreDebugSnapshot -> [(Text, Text)]
+ NanoUI.Backend.Sdl: formatExplainRows :: Maybe ExplainedNode -> [(Text, Text)]
+ NanoUI.Backend.Sdl: formatFpsRows :: CoreDebugSnapshot -> [(Text, Text)]
+ NanoUI.Backend.Sdl: openUrl :: Text -> IO Bool
+ NanoUI.Backend.Sdl: peekFileDialogUi :: FileDialogId -> NanoUI FileDialogResult
+ NanoUI.Backend.Sdl: resetRenderTextures :: SdlEnv -> IO ()
+ NanoUI.Backend.Sdl: sdlDebugSnapshot :: SdlEnv -> IO SdlDebugSnapshot
+ NanoUI.Backend.Sdl: setWindowChrome :: SdlEnv -> WindowChrome -> IO ()
+ NanoUI.Backend.Sdl: setWindowChromeUi :: WindowChrome -> NanoUI ()
+ NanoUI.Backend.Sdl: setWindowDecorations :: SdlEnv -> WindowDecorations -> IO ()
+ NanoUI.Backend.Sdl: setWindowDecorationsUi :: WindowDecorations -> NanoUI ()
+ NanoUI.Backend.Sdl: setWindowShadow :: SdlEnv -> Bool -> IO ()
+ NanoUI.Backend.Sdl: setWindowShadowUi :: Bool -> NanoUI ()
+ NanoUI.Backend.Sdl: useFileDialog :: Var (Maybe FileDialogId) -> ([FilePath] -> NanoUI ()) -> NanoUI ()
+ NanoUI.Backend.Sdl: windowCaption :: [Rect] -> NanoUI Bool
+ NanoUI.Backend.Sdl: windowCaptionWith :: CaptionOptions -> [Rect] -> NanoUI Bool
+ NanoUI.Backend.Sdl: windowResizable :: SdlEnv -> IO Bool
+ NanoUI.Backend.Sdl: windowZoom :: SdlEnv -> IO Float
+ NanoUI.Sdl.Internal.Cursor: SdlCursors :: Ptr SDL_Cursor -> IORef [(SDL_SystemCursor, Ptr SDL_Cursor)] -> IORef UiCursorKind -> Bool -> SdlCursors
+ NanoUI.Sdl.Internal.Cursor: [scCurrent] :: SdlCursors -> IORef UiCursorKind
+ NanoUI.Sdl.Internal.Cursor: [scDefault] :: SdlCursors -> Ptr SDL_Cursor
+ NanoUI.Sdl.Internal.Cursor: [scSystem] :: SdlCursors -> IORef [(SDL_SystemCursor, Ptr SDL_Cursor)]
+ NanoUI.Sdl.Internal.Cursor: [scTrace] :: SdlCursors -> Bool
+ NanoUI.Sdl.Internal.Cursor: data SdlCursors
+ NanoUI.Sdl.Internal.Cursor: destroyCursors :: SdlCursors -> IO ()
+ NanoUI.Sdl.Internal.Cursor: initCursors :: IO SdlCursors
+ NanoUI.Sdl.Internal.Cursor: sdlSystemCursor :: UiCursorKind -> Maybe SDL_SystemCursor
+ NanoUI.Sdl.Internal.Cursor: showCursorKind :: SdlCursors -> UiCursorKind -> IO ()
+ NanoUI.Sdl.Internal.Cursor: syncPointerCursor :: SdlCursors -> Context -> Input -> IO ()
+ NanoUI.Sdl.Internal.DialogState: FileDialogCancelled :: FileDialogResult
+ NanoUI.Sdl.Internal.DialogState: FileDialogFailed :: FileDialogResult
+ NanoUI.Sdl.Internal.DialogState: FileDialogPending :: FileDialogResult
+ NanoUI.Sdl.Internal.DialogState: FileDialogSelected :: [FilePath] -> FileDialogResult
+ NanoUI.Sdl.Internal.DialogState: FileDialogUnknown :: FileDialogResult
+ NanoUI.Sdl.Internal.DialogState: completeResult :: IORef FileDialogResult -> FileDialogResult -> IO ()
+ NanoUI.Sdl.Internal.DialogState: data FileDialogResult
+ NanoUI.Sdl.Internal.DialogState: instance GHC.Internal.Classes.Eq NanoUI.Sdl.Internal.DialogState.FileDialogResult
+ NanoUI.Sdl.Internal.DialogState: instance GHC.Internal.Show.Show NanoUI.Sdl.Internal.DialogState.FileDialogResult
+ NanoUI.Sdl.Internal.DialogState: takeResult :: IORef FileDialogResult -> IO FileDialogResult
+ NanoUI.Sdl.Internal.Error: sdlErrorText :: IO String
+ NanoUI.Sdl.Internal.Error: sdlFail :: String -> IO a
+ NanoUI.Sdl.Internal.Error: withSdlError :: String -> IO String
+ NanoUI.Sdl.Internal.Image: data ImageAtlas
+ NanoUI.Sdl.Internal.Image: destroyImageAtlas :: ImageAtlas -> IO ()
+ NanoUI.Sdl.Internal.Image: lookupImage :: ImageAtlas -> Int -> IO (Ptr SDL_Texture)
+ NanoUI.Sdl.Internal.Image: newImageAtlas :: IO ImageAtlas
+ NanoUI.Sdl.Internal.Image: syncImageAtlas :: Ptr SDL_Renderer -> ImageAtlas -> Context -> IO ()
+ NanoUI.Sdl.Internal.Input: EvCloseRequested :: SdlEvent
+ NanoUI.Sdl.Internal.Input: EvDisplayChanged :: SdlEvent
+ NanoUI.Sdl.Internal.Input: EvDrop :: DropEvent -> SdlEvent
+ NanoUI.Sdl.Internal.Input: EvEditing :: Text -> Int -> Int -> SdlEvent
+ NanoUI.Sdl.Internal.Input: EvFocusLost :: SdlEvent
+ NanoUI.Sdl.Internal.Input: EvKey :: Key -> Bool -> Modifiers -> SdlEvent
+ NanoUI.Sdl.Internal.Input: EvModifiers :: Modifiers -> SdlEvent
+ NanoUI.Sdl.Internal.Input: EvMouseButton :: MouseButton -> Bool -> V2 -> Modifiers -> SdlEvent
+ NanoUI.Sdl.Internal.Input: EvMouseLeave :: SdlEvent
+ NanoUI.Sdl.Internal.Input: EvMouseMotion :: V2 -> Modifiers -> SdlEvent
+ NanoUI.Sdl.Internal.Input: EvQuit :: SdlEvent
+ NanoUI.Sdl.Internal.Input: EvRefresh :: SdlEvent
+ NanoUI.Sdl.Internal.Input: EvRenderDeviceReset :: SdlEvent
+ NanoUI.Sdl.Internal.Input: EvScroll :: V2 -> SdlEvent
+ NanoUI.Sdl.Internal.Input: EvSystemThemeChanged :: SdlEvent
+ NanoUI.Sdl.Internal.Input: EvText :: Text -> SdlEvent
+ NanoUI.Sdl.Internal.Input: EvWindowChanged :: SdlEvent
+ NanoUI.Sdl.Internal.Input: EvWindowRedraw :: SdlEvent
+ NanoUI.Sdl.Internal.Input: applyEvent :: Input -> SdlEvent -> Input
+ NanoUI.Sdl.Internal.Input: data SdlEvent
+ NanoUI.Sdl.Internal.Input: data TextInputSync
+ NanoUI.Sdl.Internal.Input: hasPointerEvent :: [SdlEvent] -> Bool
+ NanoUI.Sdl.Internal.Input: instance GHC.Internal.Classes.Eq NanoUI.Sdl.Internal.Input.SdlEvent
+ NanoUI.Sdl.Internal.Input: instance GHC.Internal.Show.Show NanoUI.Sdl.Internal.Input.SdlEvent
+ NanoUI.Sdl.Internal.Input: isButtonEdge :: SdlEvent -> Bool
+ NanoUI.Sdl.Internal.Input: newTextInputSync :: IO TextInputSync
+ NanoUI.Sdl.Internal.Input: pollEvents :: IO [SdlEvent]
+ NanoUI.Sdl.Internal.Input: pollWindowEvents :: IO [(Word32, SdlEvent)]
+ NanoUI.Sdl.Internal.Input: scaleEventPositions :: Float -> [SdlEvent] -> [SdlEvent]
+ NanoUI.Sdl.Internal.Input: sdlKey :: CUInt -> SDL_Keymod -> Maybe Key
+ NanoUI.Sdl.Internal.Input: syncTextInput :: TextInputSync -> Ptr SDL_Window -> Float -> Context -> Input -> IO Bool
+ NanoUI.Sdl.Internal.Input: waitEvent :: Int -> IO (Maybe SdlEvent)
+ NanoUI.Sdl.Internal.Input: waitWindowEvent :: Int -> IO (Maybe (Word32, SdlEvent))
+ NanoUI.Sdl.Internal.NanoUIFont: DefaultFont :: NanoUIFont
+ NanoUI.Sdl.Internal.NanoUIFont: FontFilePath :: FilePath -> NanoUIFont
+ NanoUI.Sdl.Internal.NanoUIFont: FontSearch :: [String] -> NanoUIFont
+ NanoUI.Sdl.Internal.NanoUIFont: data NanoUIFont
+ NanoUI.Sdl.Internal.NanoUIFont: instance GHC.Internal.Classes.Eq NanoUI.Sdl.Internal.NanoUIFont.NanoUIFont
+ NanoUI.Sdl.Internal.NanoUIFont: instance GHC.Internal.Show.Show NanoUI.Sdl.Internal.NanoUIFont.NanoUIFont
+ NanoUI.Sdl.Internal.Render: data RenderBatch
+ NanoUI.Sdl.Internal.Render: destroyRenderBatch :: RenderBatch -> IO ()
+ NanoUI.Sdl.Internal.Render: discardRenderBatch :: RenderBatch -> IO ()
+ NanoUI.Sdl.Internal.Render: flushRenderBatch :: RenderBatch -> IO ()
+ NanoUI.Sdl.Internal.Render: glyphPageTexture :: Ptr () -> Int -> IO (Ptr SDL_Texture)
+ NanoUI.Sdl.Internal.Render: newRenderBatch :: Ptr SDL_Renderer -> IO RenderBatch
+ NanoUI.Sdl.Internal.Render: presentGpuRetain :: RenderBatch -> Ptr SDL_Window -> Ptr SDL_Texture -> Int -> Int -> Bool -> Color -> IO Bool
+ NanoUI.Sdl.Internal.Render: renderDrawDataPass :: RenderBatch -> Ptr SDL_Renderer -> Float -> DrawData -> ImageAtlas -> Ptr () -> Damage -> IO ()
+ NanoUI.Sdl.Internal.Render: snapDamage :: Float -> Damage -> Damage
+ NanoUI.Sdl.Internal.Window: PresentProbe :: Double -> Int -> PresentProbe
+ NanoUI.Sdl.Internal.Window: RenderDriverAuto :: RenderDriver
+ NanoUI.Sdl.Internal.Window: RenderDriverGpu :: RenderDriver
+ NanoUI.Sdl.Internal.Window: RenderDriverNamed :: ByteString -> RenderDriver
+ NanoUI.Sdl.Internal.Window: RenderDriverSdlDefault :: RenderDriver
+ NanoUI.Sdl.Internal.Window: Retain :: Ptr SDL_Texture -> Int -> Int -> Int -> Int -> Float -> Retain
+ NanoUI.Sdl.Internal.Window: RgbaImage :: ImageId -> Int -> Int -> ByteString -> RgbaImage
+ NanoUI.Sdl.Internal.Window: SdlEnv :: Ptr SDL_Window -> Ptr SDL_Renderer -> Text -> Bool -> RenderBatch -> IORef NanoUIFont -> IORef NanoUIFont -> Maybe Float -> IORef Float -> IORef Float -> IORef Bool -> ImageAtlas -> SdlCursors -> DebugSamplerRef -> IORef (Maybe SdlDebugSnapshot) -> Bool -> IORef Retain -> IORef Bool -> Bool -> Double -> IORef Double -> IORef PresentProbe -> Bool -> Maybe (SDL_BlendMode, SDL_BlendMode) -> IORef Context -> SdlFontCache -> ChromeState -> TextInputSync -> Maybe (IORef (Int32, Int32, Int32, Int32)) -> IORef Bool -> SdlEnv
+ NanoUI.Sdl.Internal.Window: SdlOptions :: WindowSettings -> WindowDecorations -> Bool -> Bool -> RenderDriver -> Bool -> Bool -> NanoUIFont -> NanoUIFont -> Float -> Maybe Theme -> Maybe (Maybe Appearance -> Theme) -> (Input -> Bool) -> SmallArray RgbaImage -> Float -> SdlOptions
+ NanoUI.Sdl.Internal.Window: VsyncIgnored :: PresentProbe
+ NanoUI.Sdl.Internal.Window: [retainCapH] :: Retain -> Int
+ NanoUI.Sdl.Internal.Window: [retainCapW] :: Retain -> Int
+ NanoUI.Sdl.Internal.Window: [retainH] :: Retain -> Int
+ NanoUI.Sdl.Internal.Window: [retainScale] :: Retain -> Float
+ NanoUI.Sdl.Internal.Window: [retainTexture] :: Retain -> Ptr SDL_Texture
+ NanoUI.Sdl.Internal.Window: [retainW] :: Retain -> Int
+ NanoUI.Sdl.Internal.Window: [rgbaImageHeight] :: RgbaImage -> Int
+ NanoUI.Sdl.Internal.Window: [rgbaImageId] :: RgbaImage -> ImageId
+ NanoUI.Sdl.Internal.Window: [rgbaImagePixels] :: RgbaImage -> ByteString
+ NanoUI.Sdl.Internal.Window: [rgbaImageWidth] :: RgbaImage -> Int
+ NanoUI.Sdl.Internal.Window: [sdlAppContinuous] :: SdlOptions -> Bool
+ NanoUI.Sdl.Internal.Window: [sdlAppFontSize] :: SdlOptions -> Float
+ NanoUI.Sdl.Internal.Window: [sdlAppFont] :: SdlOptions -> NanoUIFont
+ NanoUI.Sdl.Internal.Window: [sdlAppImages] :: SdlOptions -> SmallArray RgbaImage
+ NanoUI.Sdl.Internal.Window: [sdlAppMonoFont] :: SdlOptions -> NanoUIFont
+ NanoUI.Sdl.Internal.Window: [sdlAppShouldQuit] :: SdlOptions -> Input -> Bool
+ NanoUI.Sdl.Internal.Window: [sdlAppThemeFor] :: SdlOptions -> Maybe (Maybe Appearance -> Theme)
+ NanoUI.Sdl.Internal.Window: [sdlAppTheme] :: SdlOptions -> Maybe Theme
+ NanoUI.Sdl.Internal.Window: [sdlAppUiScale] :: SdlOptions -> Float
+ NanoUI.Sdl.Internal.Window: [sdlAppVsync] :: SdlOptions -> Bool
+ NanoUI.Sdl.Internal.Window: [sdlBatch] :: SdlEnv -> RenderBatch
+ NanoUI.Sdl.Internal.Window: [sdlCachedCtx] :: SdlEnv -> IORef Context
+ NanoUI.Sdl.Internal.Window: [sdlChromeState] :: SdlEnv -> ChromeState
+ NanoUI.Sdl.Internal.Window: [sdlContinuous] :: SdlEnv -> Bool
+ NanoUI.Sdl.Internal.Window: [sdlCursors] :: SdlEnv -> SdlCursors
+ NanoUI.Sdl.Internal.Window: [sdlDebugPublished] :: SdlEnv -> IORef (Maybe SdlDebugSnapshot)
+ NanoUI.Sdl.Internal.Window: [sdlDebug] :: SdlEnv -> DebugSamplerRef
+ NanoUI.Sdl.Internal.Window: [sdlExplainLayout] :: SdlOptions -> Bool
+ NanoUI.Sdl.Internal.Window: [sdlFontAppliedRef] :: SdlEnv -> IORef NanoUIFont
+ NanoUI.Sdl.Internal.Window: [sdlFontCache] :: SdlEnv -> SdlFontCache
+ NanoUI.Sdl.Internal.Window: [sdlFontRequestRef] :: SdlEnv -> IORef NanoUIFont
+ NanoUI.Sdl.Internal.Window: [sdlForcedScale] :: SdlEnv -> Maybe Float
+ NanoUI.Sdl.Internal.Window: [sdlFrameTrace] :: SdlEnv -> Bool
+ NanoUI.Sdl.Internal.Window: [sdlHasGpu] :: SdlEnv -> Bool
+ NanoUI.Sdl.Internal.Window: [sdlImages] :: SdlEnv -> ImageAtlas
+ NanoUI.Sdl.Internal.Window: [sdlLastPresented] :: SdlEnv -> IORef Bool
+ NanoUI.Sdl.Internal.Window: [sdlPointerSeen] :: SdlEnv -> IORef Bool
+ NanoUI.Sdl.Internal.Window: [sdlPresentProbe] :: SdlEnv -> IORef PresentProbe
+ NanoUI.Sdl.Internal.Window: [sdlRefreshPeriodRef] :: SdlEnv -> IORef Double
+ NanoUI.Sdl.Internal.Window: [sdlRefreshPeriod] :: SdlEnv -> Double
+ NanoUI.Sdl.Internal.Window: [sdlRenderDriver] :: SdlOptions -> RenderDriver
+ NanoUI.Sdl.Internal.Window: [sdlRendererName] :: SdlEnv -> Text
+ NanoUI.Sdl.Internal.Window: [sdlRenderer] :: SdlEnv -> Ptr SDL_Renderer
+ NanoUI.Sdl.Internal.Window: [sdlRetain] :: SdlEnv -> IORef Retain
+ NanoUI.Sdl.Internal.Window: [sdlScaleRef] :: SdlEnv -> IORef Float
+ NanoUI.Sdl.Internal.Window: [sdlSizeLimitsSent] :: SdlEnv -> IORef Bool
+ NanoUI.Sdl.Internal.Window: [sdlSizeLimits] :: SdlEnv -> Maybe (IORef (Int32, Int32, Int32, Int32))
+ NanoUI.Sdl.Internal.Window: [sdlTextInput] :: SdlEnv -> TextInputSync
+ NanoUI.Sdl.Internal.Window: [sdlTransparent] :: SdlEnv -> Maybe (SDL_BlendMode, SDL_BlendMode)
+ NanoUI.Sdl.Internal.Window: [sdlUiScaleRef] :: SdlEnv -> IORef Float
+ NanoUI.Sdl.Internal.Window: [sdlVsync] :: SdlEnv -> Bool
+ NanoUI.Sdl.Internal.Window: [sdlWindowAlwaysOnTop] :: SdlOptions -> Bool
+ NanoUI.Sdl.Internal.Window: [sdlWindowDecorations] :: SdlOptions -> WindowDecorations
+ NanoUI.Sdl.Internal.Window: [sdlWindowSettings] :: SdlOptions -> WindowSettings
+ NanoUI.Sdl.Internal.Window: [sdlWindow] :: SdlEnv -> Ptr SDL_Window
+ NanoUI.Sdl.Internal.Window: askSdlEnv :: NanoUI (Maybe SdlEnv)
+ NanoUI.Sdl.Internal.Window: captureFrame :: SdlEnv -> Ptr SDL_Texture -> IO (Maybe RgbaPixels)
+ NanoUI.Sdl.Internal.Window: captureScreenshot :: SdlEnv -> IO (Maybe Screenshot)
+ NanoUI.Sdl.Internal.Window: data PresentProbe
+ NanoUI.Sdl.Internal.Window: data RenderDriver
+ NanoUI.Sdl.Internal.Window: data Retain
+ NanoUI.Sdl.Internal.Window: data RgbaImage
+ NanoUI.Sdl.Internal.Window: data SdlEnv
+ NanoUI.Sdl.Internal.Window: data SdlOptions
+ NanoUI.Sdl.Internal.Window: defaultSdlOptions :: SdlOptions
+ NanoUI.Sdl.Internal.Window: instance GHC.Internal.Classes.Eq NanoUI.Sdl.Internal.Window.RenderDriver
+ NanoUI.Sdl.Internal.Window: instance GHC.Internal.Classes.Eq NanoUI.Sdl.Internal.Window.RgbaImage
+ NanoUI.Sdl.Internal.Window: instance GHC.Internal.Show.Show NanoUI.Sdl.Internal.Window.RenderDriver
+ NanoUI.Sdl.Internal.Window: notePresent :: SdlEnv -> Double -> IO ()
+ NanoUI.Sdl.Internal.Window: openChildWindow :: SdlOptions -> SdlEnv -> Context -> WindowSettings -> IO (Context, SdlEnv, IO ())
+ NanoUI.Sdl.Internal.Window: presentPaces :: SdlEnv -> IO Bool
+ NanoUI.Sdl.Internal.Window: refreshDisplayRate :: SdlEnv -> IO ()
+ NanoUI.Sdl.Internal.Window: registerAppImages :: SdlOptions -> Context -> IO ()
+ NanoUI.Sdl.Internal.Window: restartPresentProbe :: SdlEnv -> IO ()
+ NanoUI.Sdl.Internal.Window: saveScreenshot :: SdlEnv -> FilePath -> IO Bool
+ NanoUI.Sdl.Internal.Window: sdlLivePacingMs :: SdlEnv -> IO Int
+ NanoUI.Sdl.Internal.Window: sdlPacingMs :: SdlEnv -> Int
+ NanoUI.Sdl.Internal.Window: syncDisplay :: Context -> SdlEnv -> Input -> IO (Context, Input)
+ NanoUI.Sdl.Internal.Window: windowZoom :: SdlEnv -> IO Float
+ NanoUI.Sdl.Internal.Window: withSdl :: SdlOptions -> Context -> (Context -> SdlEnv -> IO a) -> IO a
+ NanoUI.Sdl.Internal.Window: withSdlBench :: Context -> (Context -> SdlEnv -> IO a) -> IO a
+ NanoUI.Sdl.Internal.Window: withSdlEnv :: a -> (SdlEnv -> IO a) -> NanoUI a
- NanoUI.Backend.Sdl: SdlOptions :: Text -> Size -> Bool -> Bool -> Bool -> Bool -> Bool -> Bool -> Bool -> NanoUIFont -> NanoUIFont -> Float -> Maybe Theme -> (Input -> Bool) -> SmallArray RgbaImage -> Float -> SdlOptions
+ NanoUI.Backend.Sdl: SdlOptions :: WindowSettings -> WindowDecorations -> Bool -> Bool -> RenderDriver -> Bool -> Bool -> NanoUIFont -> NanoUIFont -> Float -> Maybe Theme -> Maybe (Maybe Appearance -> Theme) -> (Input -> Bool) -> SmallArray RgbaImage -> Float -> SdlOptions
- NanoUI.Backend.Sdl: askOpenFileDialog :: forall (es :: [Effect]). Ui :> es => FileDialogOptions -> Eff es (Maybe FileDialogId)
+ NanoUI.Backend.Sdl: askOpenFileDialog :: FileDialogOptions -> NanoUI FileDialogId
- NanoUI.Backend.Sdl: askOpenFolderDialog :: forall (es :: [Effect]). Ui :> es => FileDialogOptions -> Eff es (Maybe FileDialogId)
+ NanoUI.Backend.Sdl: askOpenFolderDialog :: FileDialogOptions -> NanoUI FileDialogId
- NanoUI.Backend.Sdl: askSaveFileDialog :: forall (es :: [Effect]). Ui :> es => FileDialogOptions -> Eff es (Maybe FileDialogId)
+ NanoUI.Backend.Sdl: askSaveFileDialog :: FileDialogOptions -> NanoUI FileDialogId
- NanoUI.Backend.Sdl: askSdlDebug :: forall (es :: [Effect]). Ui :> es => Eff es SdlDebugSnapshot
+ NanoUI.Backend.Sdl: askSdlDebug :: NanoUI (Maybe SdlDebugSnapshot)
- NanoUI.Backend.Sdl: pollFileDialogUi :: forall (es :: [Effect]). Ui :> es => FileDialogId -> Eff es FileDialogResult
+ NanoUI.Backend.Sdl: pollFileDialogUi :: FileDialogId -> NanoUI FileDialogResult
- NanoUI.Backend.Sdl: runSdlAppReduce :: (Typeable msg, Eq model) => SdlOptions -> (msg -> model -> model) -> model -> (model -> NanoUI ()) -> IO ()
+ NanoUI.Backend.Sdl: runSdlAppReduce :: Eq model => SdlOptions -> (msg -> model -> model) -> model -> (model -> NanoUIE msg ()) -> IO ()
- NanoUI.Backend.Sdl: sdlDrawFrame :: Context -> NanoUI () -> SdlEnv -> Input -> Bool -> IO (Bool, Input)
+ NanoUI.Backend.Sdl: sdlDrawFrame :: Context -> NanoUI () -> SdlEnv -> Input -> Bool -> IO Bool
- NanoUI.Backend.Sdl: setSdlUiFont :: forall (es :: [Effect]). Ui :> es => NanoUIFont -> Eff es ()
+ NanoUI.Backend.Sdl: setSdlUiFont :: NanoUIFont -> NanoUI ()
- NanoUI.Backend.Sdl: setSdlUiScale :: forall (es :: [Effect]). Ui :> es => Float -> Eff es ()
+ NanoUI.Backend.Sdl: setSdlUiScale :: Float -> NanoUI ()
Files
- CHANGELOG.md +88/−5
- README.md +39/−15
- benchmark/SdlBench.hs +31/−38
- cbits/nano_ui_batch.c +0/−176
- cbits/nano_ui_batch.h +0/−27
- cbits/nano_ui_display.c +152/−17
- cbits/nano_ui_frame.c +240/−0
- cbits/nano_ui_render.c +860/−0
- cbits/nano_ui_simd.h +0/−44
- cbits/nano_ui_text_atlas.c +151/−109
- cbits/nano_ui_text_atlas.h +17/−5
- cbits/nano_ui_ttf.c +0/−475
- data/inter.ttf binary
- examples/SdlAnim.hs +55/−53
- examples/SdlIdle.hs +146/−0
- lib/NanoUI/Backend/Sdl.hs +129/−82
- lib/NanoUI/Sdl/Clipboard.hs +0/−25
- lib/NanoUI/Sdl/Cursor.hs +0/−114
- lib/NanoUI/Sdl/Debug.hs +0/−77
- lib/NanoUI/Sdl/Dialog.hs +0/−285
- lib/NanoUI/Sdl/Dialog/Types.hs +0/−101
- lib/NanoUI/Sdl/Display.hs +0/−150
- lib/NanoUI/Sdl/Font.hs +0/−1446
- lib/NanoUI/Sdl/Font/Inter.hs +0/−17
- lib/NanoUI/Sdl/Font/Resolve.hs +0/−43
- lib/NanoUI/Sdl/Font/Search.hs +0/−231
- lib/NanoUI/Sdl/Image.hs +0/−70
- lib/NanoUI/Sdl/Input.hs +0/−325
- lib/NanoUI/Sdl/Internal/Children.hs +122/−0
- lib/NanoUI/Sdl/Internal/Chrome.hs +320/−0
- lib/NanoUI/Sdl/Internal/Chrome/Types.hs +93/−0
- lib/NanoUI/Sdl/Internal/Cursor.hs +119/−0
- lib/NanoUI/Sdl/Internal/Debug.hs +45/−0
- lib/NanoUI/Sdl/Internal/Dialog.hs +276/−0
- lib/NanoUI/Sdl/Internal/DialogState.hs +34/−0
- lib/NanoUI/Sdl/Internal/Display.hs +271/−0
- lib/NanoUI/Sdl/Internal/Env.hs +135/−0
- lib/NanoUI/Sdl/Internal/Error.hs +31/−0
- lib/NanoUI/Sdl/Internal/Font.hs +164/−0
- lib/NanoUI/Sdl/Internal/Font/Search.hs +273/−0
- lib/NanoUI/Sdl/Internal/Frame.hs +243/−0
- lib/NanoUI/Sdl/Internal/Gpu.hs +443/−0
- lib/NanoUI/Sdl/Internal/Image.hs +114/−0
- lib/NanoUI/Sdl/Internal/Input.hs +442/−0
- lib/NanoUI/Sdl/Internal/NanoUIFont.hs +21/−0
- lib/NanoUI/Sdl/Internal/Pacing.hs +81/−0
- lib/NanoUI/Sdl/Internal/Render.hs +634/−0
- lib/NanoUI/Sdl/Internal/Runner.hs +386/−0
- lib/NanoUI/Sdl/Internal/Screenshot.hs +90/−0
- lib/NanoUI/Sdl/Internal/Session.hs +308/−0
- lib/NanoUI/Sdl/Internal/Target.hs +36/−0
- lib/NanoUI/Sdl/Internal/TargetPool.hs +166/−0
- lib/NanoUI/Sdl/Internal/Url.hs +24/−0
- lib/NanoUI/Sdl/Internal/Window.hs +679/−0
- lib/NanoUI/Sdl/Internal/WindowOptions.hs +116/−0
- lib/NanoUI/Sdl/NanoUIFont.hs +0/−16
- lib/NanoUI/Sdl/Render.hs +0/−243
- lib/NanoUI/Sdl/Runner.hs +0/−317
- lib/NanoUI/Sdl/Session.hs +0/−187
- lib/NanoUI/Sdl/Window.hs +0/−490
- nano-ui-sdl.cabal +120/−62
- test/FontEffects.hs +136/−73
- test/FontSearch.hs +84/−44
- test/Input.hs +125/−0
- test/Rendering.hs +595/−0
- test/WindowChecks.hs +486/−0
CHANGELOG.md view
@@ -1,9 +1,96 @@ # Changelog -## Unreleased+## 0.2.0.0 -- 2026-12-02 +See the [0.1 to 0.2 migration guide](https://goolord.github.io/nano-ui/book/getting-started/migrating-0.2.html)+for upgrade examples.++### Breaking changes++- **Concrete `NanoUI` monad and session-owned `SdlEnv`:** Views use `NanoUI`+ instead of `Ui :> es => Eff es` (dropping the `effectful-core` dependency)+ and never thread an `SdlEnv` handle. `askOpenFileDialog`,+ `askSaveFileDialog`, `askOpenFolderDialog`, `pollFileDialogUi`,+ `setSdlUiFont`, `setSdlUiScale`, `windowCaption`, `windowCaptionWith`,+ `setWindowChromeUi`, and `askSdlDebug` find the active session on the+ `Context`. Removed `runSdlAppWith` and `runSdlAppReduceWith`; allocate state+ once in `IO` and pass it to `runSdlApp` or `runSdlAppReduce`. `SdlEnv` is+ exported opaquely (`askSdlEnv` opts into IO-level helpers; fields moved to+ `NanoUI.Sdl.Internal.Window`).+- **Opaque `FileDialogId`:** Dialog launch helpers return `FileDialogId`+ directly (failures report as `FileDialogFailed` on poll). `pollFileDialogUi`+ consumes a result once and restores window focus; use `peekFileDialogUi` to+ observe without consuming.+- **Window settings and decorations:** Replaced `sdlWindowTitle`,+ `sdlWindowSize`, `sdlWindowResizable`, `sdlWindowFullscreen`, and+ `sdlWindowHidden` with `sdlWindowSettings :: WindowSettings`. Replaced+ `sdlWindowBorderless` with `sdlWindowDecorations :: WindowDecorations`+ (`DecorationsFull`, `DecorationsFrame`, `DecorationsNone`).+- **Typed reducer runner:** `runSdlAppReduce` takes `model -> NanoUIE msg ()`+ from `nano-ui-emit`.+- **Shared TTF text layer (`nano-ui-ttf`):** Extracted SDL3_ttf shaping, font+ discovery, the glyph atlas, and bundled Inter (`LICENSE-Inter`) into+ `nano-ui-ttf`. Moved `NanoUI.Sdl.Input` and `NanoUI.Sdl.NanoUIFont` to+ `NanoUI.Sdl.Internal.*` (`NanoUIFont` stays exported from+ `NanoUI.Backend.Sdl`).+- **Removed `+simd` flag:** Replaced the AVX2-only damage culler with a+ portable triangle culler; remove `+simd`/`-simd` from local project files.+ ### Added +- **GPU fragment shaders (`nano-ui-shader`):** Tier 1 (`shaderBox`) and+ Tier 2 (`withShader`) shader execution on OpenGL 3.2 / GLSL 150 and SDL3's+ GPU renderer, with straight-alpha blending and unshaded fallback on compile+ failure.+- **Custom title bars and native chrome:** `windowCaption`,+ `windowCaptionWith`, `CaptionOptions`, `WindowChrome`, `setWindowChrome`,+ `clearWindowChrome`, `setWindowChromeUi`, `clearWindowChromeUi`,+ `DecorationsFrame` (native Win32 resize frame and DWM shadow without a title+ bar), `setWindowDecorationsUi`, `setWindowShadowUi`, `windowResizable`, and+ `windowZoom`.+- **Platform integration:** Full core `WindowSettings` and view-side window+ commands, `captureScreenshot`, `nativeWindow` live-resize support on+ Windows, IME text composition (`useInputMethod`), full `Key` and+ `MouseButton` support, system light/dark theme following (`sdlAppThemeFor`),+ `sdlRenderDriver` (`RenderDriverAuto`, `RenderDriverSdlDefault`,+ `RenderDriverNamed`), `sdlExplainLayout`, `CoreDebugSnapshot` formatters+ (`formatFpsRows`, `formatDrawRows`, `formatExplainRows`),+ `resetRenderTextures`, and the `nano-ui-sdl-idle` measurement tool.++### Changed++- **Windows OpenGL default and smooth live resize:** `RenderDriverAuto` picks+ `"opengl"` on Windows (with native GLSL 150 shaders) and installs a Win32+ resize subclass to avoid D3D11 flip-model resize stalls and Vulkan WSI+ stretch artifacts.+- **Typography and font search:** Uses real bold faces when available beside+ the regular font, applies full hinting to monospace fonts, splits line gap+ above and below glyphs like CSS, searches XDG/fontconfig directories on Unix,+ walks font directories in the background, skips unreadable folders, and+ includes Windows/macOS fallback aliases for CJK, Indic, symbols, and serif.+- **Performance and dependencies:** Dynamic per-font shaping caches, caching+ for lines over 4096 bytes, dirty-rect CPU atlas uploads with fast resets,+ SDL 3.4 clamp texture addressing, skipping damage diffs on continuous frames,+ `Data.Acquire` session teardown, and support for GHC 9.10 through 9.14 and+ `sdl3-bindgen-sys >=0.0.1.0 && <0.0.2`. Added `vector ^>=0.13` and dropped+ `dir-traverse`, `hashable`, and `unordered-containers`.++### Fixed++- Paced animations and continuous sessions by the active display's refresh+ rate (including fractional rates and monitor moves) when drivers disable+ vsync.+- Fixed OpenGL ES 2 framebuffer errors after closing secondary windows,+ Direct3D render device resets (`EvRenderDeviceReset`), fractional-DPI+ retained framebuffer and clip alignment, Wayland-to-X11 driver fallback,+ un-clamped Wayland tiling resizes, UTF-8 file-dialog filters under C+ locales, coalesced cross-thread wakes, color-emoji tinting, and exception+ propagation out of live-resize callbacks.++## 0.1.0.1 -- 2026-09-18++### Added+ - Shaped text. Lines are laid out by SDL_ttf and HarfBuzz with ligatures, contextual forms and marks, and drawn glyph by glyph from the atlas. Arabic, Hebrew, Devanagari, CJK and other scripts the UI font lacks are@@ -51,10 +138,6 @@ - The font debugging exports `saveFontRenderText`, `queryFontKerning`, `queryFontPairKerning`, `debugFontPair` and `dumpFontLayout`. - `NanoUI.Sdl.Session` is no longer an exposed module.--## 0.1.0.1 -- 2026-09-18--* ## 0.1.0.0
README.md view
@@ -1,9 +1,6 @@ # nano-ui-sdl -SDL3 window backend for [nano-ui](https://github.com/goolord/nano-ui). Text is-shaped with SDL_ttf and HarfBuzz, drawn from the bundled Inter font or installed-fonts looked up by family name, with fallback fonts for other scripts. The-backend also opens native file dialogs.+Desktop SDL3 backend for [nano-ui](https://github.com/goolord/nano-ui). Shapes TrueType text with SDL3_ttf and HarfBuzz using the bundled Inter font or installed system fonts (with script fallbacks), and provides non-blocking native file dialogs, custom title bars, and screenshots. ```haskell {-# LANGUAGE OverloadedStrings #-}@@ -15,21 +12,48 @@ main = runSdlApp defaultSdlOptions (label "Hello") ``` -`runSdlAppReduce` runs a view against a model and an update function, for use-with `NanoUI.Emit`. `SdlOptions` sets the window, fonts, font size, theme, and-vsync.+For Elm-style views, `runSdlAppReduce` pairs a `model -> NanoUIE msg ()` view with `msg -> model -> model` (via `nano-ui-emit`). Configure initial window settings, fonts, base font size, theme, and vsync through `SdlOptions`. -## Running+SDL view helpers find the active session inside `NanoUI`, so you do not pass a backend handle through your views (and they become no-ops in headless tests): +```haskell+main :: IO ()+main = do+ picker <- FilePicker <$> newVar Nothing+ runSdlApp defaultSdlOptions (filePicker picker)++newtype FilePicker = FilePicker (Var (Maybe FileDialogId))++filePicker :: FilePicker -> NanoUI ()+filePicker (FilePicker pending) =+ whenM (button "Open") $+ writeVar pending . Just =<< askOpenFileDialog defaultFileDialogOptions+```++Check dialog completion with `pollFileDialogUi` (consumes the result and restores window focus) or `peekFileDialogUi`. When you need low-level `IO` operations (`saveScreenshot`, `setWindowChrome`, raw dialog calls), obtain the `SdlEnv` handle via `askSdlEnv` and call them on the display thread.++## Windows, fonts, and DPI++`sdlWindowSettings` takes core `WindowSettings` (shared with `nano-ui-rgfw`): title, logical size, position, min/max bounds, icon, window mode, transparency (`wsTransparent`), opacity, and close-request handling. Combine `sdlWindowDecorations` with `windowCaption` for frameless custom title bars, and use `captureScreenshot` or `saveScreenshot` to read back the last presented frame.++Set the starting font in `SdlOptions` or switch at runtime with `setSdlUiFont`. `NanoUIFont` supports the bundled Inter default and searching installed system families by name.++Views always work in logical pixels. macOS and Wayland scale per monitor automatically; on Windows, SDL reports density `1` by default, so set `sdlAppUiScale = 0` to follow the desktop scale. Recoverable render device resets rebuild textures automatically.++## System requirements++Requires SDL3, SDL3_ttf 3.2+, and `pkg-config`:+ ```sh-cabal run nano-ui-sdl-anim # tween and spring animations-cabal bench nano-ui-sdl-bench # runFrame and SDL drawing timings+pkg-config --modversion sdl3 sdl3-ttf ``` -## Requirements+Link executables with `-threaded` so background tasks keep running while the SDL event wait sleeps. -SDL3 and SDL3_ttf 3.2 or later, and pkg-config. The backend is behind the `sdl`-flag, which is on by default.+## Documentation -On x86-64, `-f simd` compiles the draw-batch culler with AVX2. A binary built-that way needs an AVX2 CPU.+- [The nano-ui Book](https://goolord.github.io/nano-ui/book/): Tutorials, widget gallery, window management, and backend reference.++## License++MIT. The bundled Inter font ships through `nano-ui-ttf` under the SIL Open Font License 1.1 (`LICENSE-Inter`). Because binaries built with `nano-ui-sdl` embed Inter, include `LICENSE-Inter` alongside distributed applications.
benchmark/SdlBench.hs view
@@ -1,14 +1,13 @@-{-# LANGUAGE OverloadedStrings #-}- module Main (main) where import Control.Monad (replicateM_, void, when) import GHC.IO.Encoding (setLocaleEncoding, utf8) import GHC.Conc (getAllocationCounter) import NanoUI-import NanoUI.Context (Context (..))-import NanoUI.Testing (newPixelContext, runFrame)-import NanoUI.Backend.Sdl (SdlEnv (..), sdlDrawFrame, syncDisplay, withSdlBench)+import NanoUI.Backend+import NanoUI.Internal.Context (Context (..))+import NanoUI.Testing (setDrawReuse)+import NanoUI.Backend.Sdl (SdlEnv, sdlDrawFrame, syncDisplay, withSdlBench) import System.Exit (exitFailure) import System.IO (hSetEncoding, stderr, stdout) import System.Mem (performGC)@@ -26,7 +25,7 @@ emptyInput { inputWindowSize = benchWindowSize , inputMousePos = V2 400 300- , inputMouseDown = True+ , inputButtonsHeld = buttonsFromList [MouseLeft] } smallUi, mediumUi, largeUi :: NanoUI ()@@ -65,40 +64,39 @@ void $ setConsoleOutputCP 65001 #endif --- | Warm ASCII glyph lookups must not allocate: the atlas UV/bearing record--- is cached and shared per font, so a steady-state 'fmGlyph' hit is array--- reads and a pointer return. This gate catches reintroducing a--- per-character 'GlyphQuad' / 'Just' allocation on the text hot path.+-- | Warm shaped-line lookups must not allocate: a drawn line's quads are+-- cached per text and returned as the shared cached value, so a steady-state+-- hit is a hash lookup and a pointer return. This gate catches reintroducing+-- a per-draw allocation on the text hot path. ----- The probe walks a shared 'Char' list rather than 'T.index', because--- 'T.index' allocates in this context and would mask the lookup cost.-glyphLookupAlloc :: Context -> IO Integer+-- The probe walks a shared list of lines so selecting one allocates nothing.+-- It answers the bytes allocated per lookup.+glyphLookupAlloc :: Context -> IO Double glyphLookupAlloc ctx = do (fm, _) <- ctxResolveFont ctx 16 WeightNormal FontStyleNormal FontRegular- let sample = "The quick brown fox jumps over the lazy dog 0123456789!?.,;:"- chars = sample- len = length chars+ let sample = ["The quick brown fox", "jumps over", "the lazy dog", "0123456789!?.,;:"]+ len = length sample lookups = 20000 :: Int- step :: Int -> Float -> IO Float+ step :: Int -> Int -> IO Int step !n !acc = if n <= 0- then pure acc+ then pure acc else- -- Force selection before the indirect glyph call; otherwise the- -- benchmark allocates a character-selection thunk per lookup.- let !c = chars !! (n `mod` len)- in drawGlyph fm c >>= \case- Just gq -> step (n - 1) (acc + gqW gq)+ -- Force selection before the indirect call; otherwise the+ -- benchmark allocates a selection thunk per lookup.+ let !txt = sample !! (n `mod` len)+ in drawShaped fm txt >>= \case+ Just _ -> step (n - 1) (acc + 1) Nothing -> step (n - 1) acc- -- Warm every character so every lookup shares a cached 'Maybe'.- mapM_ (drawGlyph fm) chars+ -- Warm every line so every lookup hits the cache.+ mapM_ (drawShaped fm) sample performGC -- The thread allocation counter is current even if this probe never fills -- the nursery. RTSStats.allocated_bytes only catches up at a GC. before <- getAllocationCounter _ <- step lookups 0 after <- getAllocationCounter- pure (fromIntegral before - fromIntegral after)+ pure (fromIntegral (before - after) / fromIntegral lookups) -- | Bytes per warm lookup tolerated before the gate trips. The cached path -- should be zero; a reintroduced per-hit record would cost tens of bytes.@@ -107,21 +105,23 @@ glyphLookupGate :: Context -> IO () glyphLookupGate ctx = do- bytes <- glyphLookupAlloc ctx- let lookups = 20000 :: Int- perLookup = fromIntegral bytes / fromIntegral lookups :: Double+ perLookup <- glyphLookupAlloc ctx printf "glyph-lookup: %.3f B/lookup (budget %.1f)\n" perLookup glyphLookupAllocBudget when (perLookup > glyphLookupAllocBudget) $ do- putStrLn "FAIL: warm glyph lookups allocate; expected the cached quad to be shared"+ putStrLn "FAIL: warm shaped lookups allocate; expected the cached quads to be shared" exitFailure main :: IO () main = do configureBenchIO ctx0 <- newPixelContext+ -- The benchmarks repeat one scene: time their paint instead of reusing it.+ setDrawReuse ctx0 False withSdlBench ctx0 $ \ctx sdlEnv -> do (ctx', inp) <- syncDisplay ctx sdlEnv benchInput- warmup ctx' sdlEnv inp+ replicateM_ 2 $ do+ void (runFrame ctx' inp mediumUi)+ void (sdlDrawFrame ctx' mediumUi sdlEnv inp False) glyphLookupGate ctx' configureBenchIO defaultMain@@ -138,13 +138,6 @@ , benchDraw ctx' sdlEnv inp largeUi "large" ] ]--warmup :: Context -> SdlEnv -> Input -> IO ()-warmup ctx sdlEnv inp = do- void (runFrame ctx inp mediumUi)- void (sdlDrawFrame ctx mediumUi sdlEnv inp False)- void (runFrame ctx inp mediumUi)- void (sdlDrawFrame ctx mediumUi sdlEnv inp False) benchRunFrame :: Context -> Input -> NanoUI () -> String -> Benchmark benchRunFrame ctx inp ui name =
− cbits/nano_ui_batch.c
@@ -1,176 +0,0 @@-#include "nano_ui_batch.h"-#include "nano_ui_simd.h"--#include <stdlib.h>--struct NanoUiBatch {- SDL_Renderer *renderer;- const uint8_t *verts;- int vert_count;- const uint8_t *indices;- SDL_Texture *pending_texture;- int pending_start;- int pending_n;-};--NanoUiBatch *nano_ui_batch_create(SDL_Renderer *renderer)-{- if (!renderer) {- return NULL;- }- NanoUiBatch *batch = (NanoUiBatch *)calloc(1, sizeof(NanoUiBatch));- if (!batch) {- return NULL;- }- batch->renderer = renderer;- return batch;-}--void nano_ui_batch_destroy(NanoUiBatch *batch)-{- if (batch) {- nano_ui_batch_flush(batch);- free(batch);- }-}--void nano_ui_batch_flush(NanoUiBatch *batch)-{- if (!batch || !batch->renderer || batch->pending_n < 3) {- if (batch) {- batch->pending_n = 0;- batch->pending_start = 0;- batch->pending_texture = NULL;- }- return;- }- const SDL_Vertex *sdl_verts = (const SDL_Vertex *)batch->verts;- const int *idx = (const int *)batch->indices + batch->pending_start;- SDL_RenderGeometry(batch->renderer, batch->pending_texture, sdl_verts, batch->vert_count, idx, batch->pending_n);- batch->pending_n = 0;- batch->pending_start = 0;- batch->pending_texture = NULL;-}--void nano_ui_batch_draw_range(- NanoUiBatch *batch,- const uint8_t *verts,- int vert_count,- const uint8_t *indices,- int index_start,- int index_n,- SDL_Texture *texture,- int has_damage,- float dmg_x,- float dmg_y,- float dmg_w,- float dmg_h)-{- if (!batch || !verts || !indices || vert_count <= 0 || index_n < 3) {- return;- }- if (index_start < 0) {- index_start = 0;- }-- if (has_damage && dmg_w > 0.f && dmg_h > 0.f && index_n >= 6) {- const SDL_Vertex *sdl_verts = (const SDL_Vertex *)verts;- const int *idx = (const int *)indices + index_start;- float dx0 = dmg_x;- float dy0 = dmg_y;- float dx1 = dmg_x + dmg_w;- float dy1 = dmg_y + dmg_h;-- bool any_visible = false;- int q = 0;-#if defined(NANO_UI_HAS_AVX2)- // 8 quads per iteration: the 8-wide AABB test amortizes the- // gather + compares, which matters on partial-redraw frames where- // long runs of quads fall entirely outside the damage rect.- {- const __m256 vdx0 = _mm256_set1_ps(dx0);- const __m256 vdy0 = _mm256_set1_ps(dy0);- const __m256 vdx1 = _mm256_set1_ps(dx1);- const __m256 vdy1 = _mm256_set1_ps(dy1);- float qx0[8], qy0[8], qx1[8], qy1[8];- for (; q + 48 <= index_n; q += 48) {- bool all_valid = true;- for (int k = 0; k < 8; k++) {- int i0 = idx[q + k * 6];- int i2 = idx[q + k * 6 + 2];- if (i0 < 0 || i0 >= vert_count || i2 < 0 || i2 >= vert_count) {- all_valid = false;- break;- }- float x0 = sdl_verts[i0].position.x;- float y0 = sdl_verts[i0].position.y;- float x1 = sdl_verts[i2].position.x;- float y1 = sdl_verts[i2].position.y;- qx0[k] = x0 < x1 ? x0 : x1;- qx1[k] = x0 > x1 ? x0 : x1;- qy0[k] = y0 < y1 ? y0 : y1;- qy1[k] = y0 > y1 ? y0 : y1;- }- if (!all_valid) {- any_visible = true;- break;- }- uint32_t mask = nano_ui_cull_8_quads_avx2(- _mm256_loadu_ps(qx0), _mm256_loadu_ps(qy0),- _mm256_loadu_ps(qx1), _mm256_loadu_ps(qy1),- vdx0, vdy0, vdx1, vdy1);- if (mask != 0) {- any_visible = true;- break;- }- }- }-#endif- for (; q + 6 <= index_n; q += 6) {- int i0 = idx[q];- int i2 = idx[q + 2];- if (i0 >= 0 && i0 < vert_count && i2 >= 0 && i2 < vert_count) {- float x0 = sdl_verts[i0].position.x;- float y0 = sdl_verts[i0].position.y;- float x1 = sdl_verts[i2].position.x;- float y1 = sdl_verts[i2].position.y;- float qx0 = x0 < x1 ? x0 : x1;- float qx1 = x0 > x1 ? x0 : x1;- float qy0 = y0 < y1 ? y0 : y1;- float qy1 = y0 > y1 ? y0 : y1;- if (nano_ui_aabb_intersects(qx0, qy0, qx1, qy1, dx0, dy0, dx1, dy1)) {- any_visible = true;- break;- }- } else {- any_visible = true;- break;- }- }- if (!any_visible && q > 0) {- return;- }- }-- if (batch->pending_n > 0 &&- batch->verts == verts &&- batch->indices == indices &&- batch->pending_texture == texture &&- batch->pending_start + batch->pending_n == index_start)- {- batch->pending_n += index_n;- if (vert_count > batch->vert_count) {- batch->vert_count = vert_count;- }- return;- }-- nano_ui_batch_flush(batch);-- batch->verts = verts;- batch->vert_count = vert_count;- batch->indices = indices;- batch->pending_texture = texture;- batch->pending_start = index_start;- batch->pending_n = index_n;-}
− cbits/nano_ui_batch.h
@@ -1,27 +0,0 @@-#ifndef NANO_UI_BATCH_H-#define NANO_UI_BATCH_H--#include <SDL3/SDL.h>-#include <stdint.h>--typedef struct NanoUiBatch NanoUiBatch;--NanoUiBatch *nano_ui_batch_create(SDL_Renderer *renderer);-void nano_ui_batch_destroy(NanoUiBatch *batch);-void nano_ui_batch_flush(NanoUiBatch *batch);--void nano_ui_batch_draw_range(- NanoUiBatch *batch,- const uint8_t *verts,- int vert_count,- const uint8_t *indices,- int index_start,- int index_n,- SDL_Texture *texture,- int has_damage,- float dmg_x,- float dmg_y,- float dmg_w,- float dmg_h);--#endif
cbits/nano_ui_display.c view
@@ -1,8 +1,12 @@ #include <SDL3/SDL.h> #include <stddef.h> #include <stdbool.h>+#include <stdint.h>+#if !defined(_WIN32) && !defined(__APPLE__)+#include <dlfcn.h>+#endif -int nano_ui_window_refresh_rate(SDL_Window *window)+float nano_ui_window_refresh_rate(SDL_Window *window) { if (!window) { return 0;@@ -19,7 +23,7 @@ * panels, compositors that report a base rate). Fall back to the highest * refresh among display modes at the current size so pacing still * targets the panel's real cadence instead of the 60 Hz default. */- int best = 0;+ float best = 0; int cw = current ? current->w : 0; int ch = current ? current->h : 0; if (cw <= 0 || ch <= 0) {@@ -38,14 +42,36 @@ return best; } +/* Whether the pointer is over the window, by SDL's mouse focus. After the+ * pointer leaves, SDL_GetMouseState keeps answering the last position inside+ * the window. */+bool nano_ui_pointer_in_window(SDL_Window *window)+{+ return window && SDL_GetMouseFocus() == window;+}++/* The window's position as the desktop reports it; false when it does not.+ * On Wayland SDL answers a position the compositor never told it. */+bool nano_ui_window_position(SDL_Window *window, int *x, int *y)+{+ const char *driver = SDL_GetCurrentVideoDriver();+ if (driver && SDL_strcmp(driver, "wayland") == 0) {+ return false;+ }+ return SDL_GetWindowPosition(window, x, y);+}+ typedef void (*nano_ui_resize_cb)(void); -static nano_ui_resize_cb g_resize_cb = NULL;+typedef struct {+ nano_ui_resize_cb cb;+ SDL_WindowID window_id;+} nano_ui_resize_watch_data; static bool nano_ui_resize_watch(void *userdata, SDL_Event *event) {- (void)userdata;- if (!g_resize_cb || !event) {+ nano_ui_resize_watch_data *data = (nano_ui_resize_watch_data *)userdata;+ if (!data || !data->cb || !event) { return true; } /* Not SDL_EVENT_WINDOW_RESIZED: SDL sends it just before the pixel size@@ -53,25 +79,134 @@ * frame drawn on RESIZED goes to the old-size backbuffer, shown cropped * or with a bare strip, and the size then counts as drawn, so the window * trails the drag by a step. */- if (event->type == SDL_EVENT_WINDOW_PIXEL_SIZE_CHANGED- || event->type == SDL_EVENT_WINDOW_DISPLAY_SCALE_CHANGED) {- g_resize_cb();+ if ((event->type == SDL_EVENT_WINDOW_PIXEL_SIZE_CHANGED+ || event->type == SDL_EVENT_WINDOW_DISPLAY_SCALE_CHANGED)+ && (data->window_id == 0 || event->window.windowID == data->window_id)) {+ data->cb(); } return true; } -bool nano_ui_install_resize_watch(nano_ui_resize_cb cb)+void *nano_ui_install_resize_watch(SDL_Window *window, nano_ui_resize_cb cb) {- if (!SDL_AddEventWatch(nano_ui_resize_watch, NULL)) {- g_resize_cb = NULL;- return false;+ if (!cb) {+ return NULL; }- g_resize_cb = cb;- return true;+ nano_ui_resize_watch_data *data =+ (nano_ui_resize_watch_data *)SDL_malloc(sizeof(nano_ui_resize_watch_data));+ if (!data) {+ return NULL;+ }+ data->cb = cb;+ data->window_id = window ? SDL_GetWindowID(window) : 0;+ if (!SDL_AddEventWatch(nano_ui_resize_watch, data)) {+ SDL_free(data);+ return NULL;+ }+ return data; } -void nano_ui_remove_resize_watch(void)+void nano_ui_remove_resize_watch(void *handle) {- SDL_RemoveEventWatch(nano_ui_resize_watch, NULL);- g_resize_cb = NULL;+ if (!handle) {+ return;+ }+ SDL_RemoveEventWatch(nano_ui_resize_watch, handle);+ SDL_free(handle); }++/* Suppress window events nano-ui never consumes so title-bar hover hit tests+ * and pure window moves do not flood SDL's event queue or wake the event loop.+ * SDL still updates internal window coordinates and monitor tracking. */+void nano_ui_disable_unused_window_events(void)+{+ SDL_SetEventEnabled(SDL_EVENT_WINDOW_HIT_TEST, false);+ SDL_SetEventEnabled(SDL_EVENT_WINDOW_MOVED, false);+}++/* Size limits for a Wayland window, sent to the compositor by nano-ui rather+ * than by SDL.+ *+ * SDL both hints its minimum and maximum to the compositor and clamps every+ * configure to them. A compositor that ignores the hint (sway's tiling does)+ * then configures a size SDL turns back into the current one: SDL acks the+ * configure and reports nothing, so no frame is drawn and nothing commits the+ * ack. sway holds the resize for its 200 ms transaction timeout, on every step+ * of a drag past the limit. With the limits kept from SDL, such a configure+ * is a real resize, drawn and committed like any other; the compositor still+ * gets the hint, which a floating window's resize honours.+ *+ * SDL loads libwayland-client itself, so the copy it loaded is used rather+ * than linking one. */++#if !defined(_WIN32) && !defined(__APPLE__)+struct wl_proxy;++static struct {+ bool loaded;+ struct wl_proxy *(*marshal_flags)(struct wl_proxy *, uint32_t, const void *, uint32_t, uint32_t, ...);+ uint32_t (*get_version)(struct wl_proxy *);+ void *(*get_user_data)(struct wl_proxy *);+} g_wl;++/* xdg_toplevel request opcodes, from xdg-shell.xml. */+enum { XDG_TOPLEVEL_SET_MAX_SIZE = 7, XDG_TOPLEVEL_SET_MIN_SIZE = 8 };++/* The window's xdg_toplevel when SDL made it itself, or NULL: not Wayland, not+ * shown yet, or a libdecor frame's, whose limits libdecor sets with its+ * decorations added. SDL listens on its own toplevel with the same window data+ * it keeps on the surface. */+static struct wl_proxy *sdl_toplevel(SDL_Window *window)+{+ if (!g_wl.loaded) {+ g_wl.loaded = true;+ void *lib = dlopen("libwayland-client.so.0", RTLD_NOW | RTLD_NOLOAD);+ if (lib) {+ *(void **)&g_wl.marshal_flags = dlsym(lib, "wl_proxy_marshal_flags");+ *(void **)&g_wl.get_version = dlsym(lib, "wl_proxy_get_version");+ *(void **)&g_wl.get_user_data = dlsym(lib, "wl_proxy_get_user_data");+ }+ }+ if (!window || !g_wl.marshal_flags || !g_wl.get_version || !g_wl.get_user_data) {+ return NULL;+ }+ SDL_PropertiesID props = SDL_GetWindowProperties(window);+ struct wl_proxy *toplevel = SDL_GetPointerProperty(props, SDL_PROP_WINDOW_WAYLAND_XDG_TOPLEVEL_POINTER, NULL);+ struct wl_proxy *surface = SDL_GetPointerProperty(props, SDL_PROP_WINDOW_WAYLAND_SURFACE_POINTER, NULL);+ if (!toplevel || !surface || g_wl.get_user_data(toplevel) != g_wl.get_user_data(surface)) {+ return NULL;+ }+ return toplevel;+}++bool nano_ui_wayland_toplevel(SDL_Window *window)+{+ return sdl_toplevel(window) != NULL;+}++/* SDL sends its own limits (none) with every configure, so these are sent+ * again before each commit, while there are any. Zero is no limit. A window that cannot be resized+ * or is fullscreen keeps what SDL sends: its size, or nothing. */+void nano_ui_wayland_size_limits(SDL_Window *window, int min_w, int min_h, int max_w, int max_h)+{+ struct wl_proxy *toplevel = sdl_toplevel(window);+ SDL_WindowFlags flags = SDL_GetWindowFlags(window);+ if (!toplevel || !(flags & SDL_WINDOW_RESIZABLE) || (flags & SDL_WINDOW_FULLSCREEN)) {+ return;+ }+ uint32_t version = g_wl.get_version(toplevel);+ g_wl.marshal_flags(toplevel, XDG_TOPLEVEL_SET_MIN_SIZE, NULL, version, 0, min_w, min_h);+ g_wl.marshal_flags(toplevel, XDG_TOPLEVEL_SET_MAX_SIZE, NULL, version, 0, max_w, max_h);+}+#else+bool nano_ui_wayland_toplevel(SDL_Window *window)+{+ (void)window;+ return false;+}++void nano_ui_wayland_size_limits(SDL_Window *window, int min_w, int min_h, int max_w, int max_h)+{+ (void)window; (void)min_w; (void)min_h; (void)max_w; (void)max_h;+}+#endif
+ cbits/nano_ui_frame.c view
@@ -0,0 +1,240 @@+/* Win32 window subclass for live-resize smoothness and optional native sizing+ * frame on windows that draw their own chrome.+ *+ * Every Windows window installs this procedure so WM_WINDOWPOSCHANGING sets+ * SWP_NOCOPYBITS on size changes (stopping Windows from BitBlt-shifting stale+ * client pixels to the new top-left corner during border drags), WM_ERASEBKGND+ * suppresses GDI background flashes, and WM_ENTERSIZEMOVE / WM_EXITSIZEMOVE+ * track active modal resize drags so retained textures do not shrink mid-drag.+ *+ * When DecorationsFrame is enabled on a borderless resizable window, the same+ * procedure answers WM_NCCALCSIZE with the sizing frame left outside the client+ * area, restoring the invisible outer resize border and DWM drop shadow without+ * shrinking the client area (the outer window rectangle is expanded instead).+ *+ * The window procedure is here rather than in Haskell because Windows calls+ * it from inside SetWindowPos, DefWindowProc and the modal loop a border+ * drag runs in, and a Haskell callback reached that way re-enters the+ * runtime from a foreign call that is already running.+ *+ * Only Windows has any of this; the Haskell side does not call in elsewhere.+ */++#ifdef _WIN32++#include <windows.h>++/* Properties stored on each subclassed HWND so multiple windows work+ * independently: the previous WndProc, whether DecorationsFrame WM_NCCALCSIZE+ * is active, and whether Win32's modal size/move loop is currently running. */+static const WCHAR *NANO_UI_OLD_PROC = L"NanoUIOldWndProc";+static const WCHAR *NANO_UI_NATIVE_FRAME = L"NanoUINativeFrame";+static const WCHAR *NANO_UI_IN_SIZEMOVE = L"NanoUIInSizeMove";++/* How far the frame reaches beyond the window you can see, across and down.+ * The per-monitor calls are Windows 10 and later, so they are looked up+ * rather than linked against; the desktop-wide ones stand in for them. */+static void nano_ui_frame_metrics(HWND hwnd, int *across, int *down)+{+ typedef UINT(WINAPI * dpi_for_window_fn)(HWND);+ typedef int(WINAPI * metrics_for_dpi_fn)(int, UINT);+ static dpi_for_window_fn dpi_for_window = NULL;+ static metrics_for_dpi_fn metrics_for_dpi = NULL;+ static int looked_up = 0;++ if (!looked_up) {+ HMODULE user32 = GetModuleHandleW(L"user32.dll");+ if (user32) {+ dpi_for_window = (dpi_for_window_fn)(void *)GetProcAddress(user32, "GetDpiForWindow");+ metrics_for_dpi = (metrics_for_dpi_fn)(void *)GetProcAddress(user32, "GetSystemMetricsForDpi");+ }+ looked_up = 1;+ }++ if (dpi_for_window && metrics_for_dpi) {+ UINT dpi = dpi_for_window(hwnd);+ if (dpi == 0) {+ dpi = 96;+ }+ *across = metrics_for_dpi(SM_CXFRAME, dpi) + metrics_for_dpi(SM_CXPADDEDBORDER, dpi);+ *down = metrics_for_dpi(SM_CYFRAME, dpi) + metrics_for_dpi(SM_CXPADDEDBORDER, dpi);+ } else {+ *across = GetSystemMetrics(SM_CXFRAME) + GetSystemMetrics(SM_CXPADDEDBORDER);+ *down = GetSystemMetrics(SM_CYFRAME) + GetSystemMetrics(SM_CXPADDEDBORDER);+ }+}++/* Whether the window has a sizing frame at all. SDL gives a borderless+ * window WS_THICKFRAME only while it is resizable and not fullscreen, so+ * fullscreen windows skip the custom WM_NCCALCSIZE adjustment and cover the+ * entire screen. */+static int nano_ui_has_sizing_frame(HWND hwnd)+{+ return (GetWindowLongPtrW(hwnd, GWL_STYLE) & WS_THICKFRAME) != 0;+}++static LRESULT CALLBACK nano_ui_frame_proc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam)+{+ WNDPROC old = (WNDPROC)GetPropW(hwnd, NANO_UI_OLD_PROC);++ /* Suppress GDI background erasure during resizes and exposes: nano-ui+ * paints the entire client area itself. */+ if (msg == WM_ERASEBKGND) {+ return 1;+ }++ if (msg == WM_ENTERSIZEMOVE) {+ SetPropW(hwnd, NANO_UI_IN_SIZEMOVE, (HANDLE)(INT_PTR)1);+ } else if (msg == WM_EXITSIZEMOVE) {+ RemovePropW(hwnd, NANO_UI_IN_SIZEMOVE);+ }++ /* Stop Windows from BitBlt-copying stale client bits when a resize also+ * moves the window origin (dragging the left or top edge), which shifts+ * old pixels across the client area before the new frame swaps. Resizes+ * that keep the top-left corner fixed (SWP_NOMOVE, right/bottom drags)+ * keep existing top-left pixels intact without flashing. */+ if (msg == WM_WINDOWPOSCHANGING && lparam) {+ LRESULT res = old ? CallWindowProcW(old, hwnd, msg, wparam, lparam)+ : DefWindowProcW(hwnd, msg, wparam, lparam);+ WINDOWPOS *wp = (WINDOWPOS *)lparam;+ if (!(wp->flags & SWP_NOSIZE) && !(wp->flags & SWP_NOMOVE)) {+ RECT cur;+ if (!GetWindowRect(hwnd, &cur) || wp->x != cur.left || wp->y != cur.top) {+ wp->flags |= SWP_NOCOPYBITS;+ }+ }+ return res;+ }++ /* Inset the client area by the sizing frame on the left, right, and bottom+ * only when DecorationsFrame is active. The default handler also insets+ * the top by the caption height, and Windows paints that top strip even+ * when the window has no title bar; SDL's borderless handler instead makes+ * the client area cover the entire window rectangle, leaving no outer+ * resize border. Leaving the top edge at the top of the window rectangle+ * gives the top strip to the client area while keeping native resize+ * borders on the other three sides.+ *+ * A maximized window positions its sizing frame outside the monitor bounds,+ * so in that case the top must also be inset by the frame height to keep+ * the client area on screen. */+ if (msg == WM_NCCALCSIZE && wparam == TRUE+ && GetPropW(hwnd, NANO_UI_NATIVE_FRAME)+ && nano_ui_has_sizing_frame(hwnd)) {+ NCCALCSIZE_PARAMS *params = (NCCALCSIZE_PARAMS *)lparam;+ int across = 0;+ int down = 0;+ nano_ui_frame_metrics(hwnd, &across, &down);+ params->rgrc[0].left += across;+ params->rgrc[0].right -= across;+ params->rgrc[0].bottom -= down;+ if (IsZoomed(hwnd)) {+ params->rgrc[0].top += down;+ }+ return 0;+ }++ /* Restore the previous window procedure and remove window properties+ * before destruction. */+ if (msg == WM_NCDESTROY && old) {+ SetWindowLongPtrW(hwnd, GWLP_WNDPROC, (LONG_PTR)old);+ RemovePropW(hwnd, NANO_UI_OLD_PROC);+ RemovePropW(hwnd, NANO_UI_NATIVE_FRAME);+ RemovePropW(hwnd, NANO_UI_IN_SIZEMOVE);+ }++ if (old) {+ return CallWindowProcW(old, hwnd, msg, wparam, lparam);+ }+ return DefWindowProcW(hwnd, msg, wparam, lparam);+}++static int nano_ui_ensure_subclass(HWND hwnd)+{+ if (!hwnd) {+ return 0;+ }+ if (GetPropW(hwnd, NANO_UI_OLD_PROC)) {+ return 1;+ }+ WNDPROC old = (WNDPROC)(LONG_PTR)SetWindowLongPtrW(hwnd, GWLP_WNDPROC, (LONG_PTR)nano_ui_frame_proc);+ if (!old) {+ return 0;+ }+ SetPropW(hwnd, NANO_UI_OLD_PROC, (HANDLE)old);+ return 1;+}++void nano_ui_install_win32_resize_hook(void *window)+{+ nano_ui_ensure_subclass((HWND)window);+}++int nano_ui_window_in_sizemove(void *window)+{+ HWND hwnd = (HWND)window;+ return (hwnd && GetPropW(hwnd, NANO_UI_IN_SIZEMOVE) != NULL) ? 1 : 0;+}++/* Expand or shrink the outer window rectangle by the frame thickness and+ * trigger a frame recalculation via SWP_FRAMECHANGED. */+static void nano_ui_refit(HWND hwnd, int sign)+{+ RECT r;+ int across = 0;+ int down = 0;+ if (!GetWindowRect(hwnd, &r)) {+ return;+ }+ if (nano_ui_has_sizing_frame(hwnd) && !IsZoomed(hwnd)) {+ nano_ui_frame_metrics(hwnd, &across, &down);+ }+ SetWindowPos(+ hwnd,+ NULL,+ 0,+ 0,+ (r.right - r.left) + sign * 2 * across,+ (r.bottom - r.top) + sign * down,+ SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE | SWP_FRAMECHANGED);+}++void nano_ui_set_native_frame(void *window, int on)+{+ HWND hwnd = (HWND)window;+ int was_on;+ if (!hwnd) {+ return;+ }+ was_on = GetPropW(hwnd, NANO_UI_NATIVE_FRAME) != NULL;+ if (on && !was_on) {+ if (!nano_ui_ensure_subclass(hwnd)) {+ return;+ }+ SetPropW(hwnd, NANO_UI_NATIVE_FRAME, (HANDLE)(INT_PTR)1);+ nano_ui_refit(hwnd, 1);+ } else if (!on && was_on) {+ RemovePropW(hwnd, NANO_UI_NATIVE_FRAME);+ nano_ui_refit(hwnd, -1);+ }+}++/* How much larger than its view the frame makes the window right now, in+ * window coordinates: the frame twice across and once down, or nothing for a+ * window without it, or one maximized or fullscreen, where it is off the+ * screen or not there. SDL sizes a borderless window as though its client+ * area were the whole of it, so whatever asks SDL for a size adds this. */+void nano_ui_native_frame_outset(void *window, int *across, int *down)+{+ HWND hwnd = (HWND)window;+ *across = 0;+ *down = 0;+ if (!hwnd || !GetPropW(hwnd, NANO_UI_NATIVE_FRAME) || !nano_ui_has_sizing_frame(hwnd) || IsZoomed(hwnd)) {+ return;+ }+ nano_ui_frame_metrics(hwnd, across, down);+ *across *= 2;+}++#endif
+ cbits/nano_ui_render.c view
@@ -0,0 +1,860 @@+#define SDL_OPENGL_1_NO_PROTOTYPES+#include <SDL3/SDL.h>+#include <SDL3/SDL_opengl.h>+#include <stddef.h>+#include <stdint.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>++#include "nano_ui_ttf_shared.h"++/* The batch reads the core's draw buffer in place as SDL_Vertex: x and y,+ * then red, green, blue and alpha, then u and v, as 32-bit floats. */+_Static_assert(sizeof(SDL_Vertex) == NANO_UI_VERTEX_BYTES, "SDL_Vertex must be the core's 32-byte vertex");+_Static_assert(offsetof(SDL_Vertex, position) == 0, "SDL_Vertex starts with its position");+_Static_assert(offsetof(SDL_Vertex, color) == 8, "SDL_Vertex colour follows the 2-float position");+_Static_assert(offsetof(SDL_Vertex, tex_coord) == 24, "SDL_Vertex UV follows the 4-float colour");+_Static_assert(sizeof(SDL_FColor) == 16, "SDL_Vertex colour is four floats");++/* OpenGL 3.2 functions loaded dynamically via SDL_GL_GetProcAddress so+ * nano-ui-sdl needs no GL link libraries. GL 1.0/1.1 entries carry explicit+ * signatures (SDL 3.2/3.4.0's SDL_opengl.h omits their PFNGL typedefs);+ * GL 1.2+ entries reuse the PFNGL*PROC typedefs from SDL_opengl_glext.h. */+#define NUI_GL_FUNCS(C, E) \+ C(const GLubyte *, GetString, (GLenum)) \+ C(void, Viewport, (GLint, GLint, GLsizei, GLsizei)) \+ C(void, Scissor, (GLint, GLint, GLsizei, GLsizei)) \+ C(void, Enable, (GLenum)) \+ C(void, Disable, (GLenum)) \+ C(void, DrawElements, (GLenum, GLsizei, GLenum, const void *)) \+ C(void, DrawArrays, (GLenum, GLint, GLsizei)) \+ C(void, GenTextures, (GLsizei, GLuint *)) \+ C(void, BindTexture, (GLenum, GLuint)) \+ C(void, TexParameteri, (GLenum, GLenum, GLint)) \+ C(void, TexImage2D, (GLenum, GLint, GLint, GLsizei, GLsizei, GLint, GLenum, GLenum, const void *)) \+ C(void, DeleteTextures, (GLsizei, const GLuint *)) \+ E(ACTIVETEXTURE, ActiveTexture) \+ E(BLENDFUNCSEPARATE, BlendFuncSeparate) \+ E(BLENDEQUATION, BlendEquation) \+ E(CREATESHADER, CreateShader) \+ E(SHADERSOURCE, ShaderSource) \+ E(COMPILESHADER, CompileShader) \+ E(GETSHADERIV, GetShaderiv) \+ E(GETSHADERINFOLOG, GetShaderInfoLog) \+ E(DELETESHADER, DeleteShader) \+ E(CREATEPROGRAM, CreateProgram) \+ E(ATTACHSHADER, AttachShader) \+ E(BINDATTRIBLOCATION, BindAttribLocation) \+ E(LINKPROGRAM, LinkProgram) \+ E(GETPROGRAMIV, GetProgramiv) \+ E(GETPROGRAMINFOLOG, GetProgramInfoLog) \+ E(DELETEPROGRAM, DeleteProgram) \+ E(USEPROGRAM, UseProgram) \+ E(GETUNIFORMLOCATION, GetUniformLocation) \+ E(GETUNIFORMBLOCKINDEX, GetUniformBlockIndex) \+ E(UNIFORMBLOCKBINDING, UniformBlockBinding) \+ E(BINDBUFFERBASE, BindBufferBase) \+ E(UNIFORM4F, Uniform4f) \+ E(GENVERTEXARRAYS, GenVertexArrays) \+ E(BINDVERTEXARRAY, BindVertexArray) \+ E(DELETEVERTEXARRAYS, DeleteVertexArrays) \+ E(GENBUFFERS, GenBuffers) \+ E(BINDBUFFER, BindBuffer) \+ E(BUFFERDATA, BufferData) \+ E(BUFFERSUBDATA, BufferSubData) \+ E(DELETEBUFFERS, DeleteBuffers) \+ E(ENABLEVERTEXATTRIBARRAY, EnableVertexAttribArray) \+ E(VERTEXATTRIBPOINTER, VertexAttribPointer)++typedef struct {+#define NUI_C(ret, name, args) ret (APIENTRY *name) args;+#define NUI_E(UP, name) PFNGL##UP##PROC name;+ NUI_GL_FUNCS(NUI_C, NUI_E)+#undef NUI_C+#undef NUI_E+} NanoUiGlApi;++typedef struct {+ uint64_t hash;+ GLuint program;+ GLint uXform;+} NanoUiGlShaderEntry;++typedef struct {+ SDL_Renderer *renderer;+ int index_total;+ /* Device pixels per layout unit and logical origin subtracted when drawing+ * into an offscreen Tier 2 effect target (0, 0 on the main target). */+ float scale;+ float origin_x, origin_y;+ /* Current renderer clip state mirrored from Haskell so GL scissor matches. */+ int has_clip;+ SDL_Rect clip;+ /* Scaled x, y pairs of the pass's vertices for SDL_RenderGeometryRaw when+ * scale != 1 or origin != (0, 0); [xy_lo, xy_hi) of xy_verts are filled. */+ float *xy;+ int xy_cap, xy_lo, xy_hi;+ const uint8_t *xy_verts;+#if !SDL_VERSION_ATLEAST(3, 4, 0)+ /* Rebased indices for SDL 3.2 vertex narrowing (see narrow). */+ int *rebased;+ int rebased_cap;+#endif+ /* OpenGL 3.2 / GLSL 150 direct batching and shader state (active only when+ * SDL uses the "opengl" driver). */+ int init_state; /* 0 = unchecked, 1 = ready, -1 = unavailable */+ SDL_Window *win;+ SDL_GLContext ctx;+ NanoUiGlApi api;+ GLuint vs;+ GLuint vao, vbo, ebo;+ size_t vbo_cap, ebo_cap;+ GLuint quad_vao, quad_vbo;+ GLuint ubo, white_tex;+ NanoUiGlShaderEntry plain;+ const uint8_t *uploaded_verts;+ int uploaded_vert_count;+ const uint8_t *uploaded_indices;+ int uploaded_index_count;+ int pass_active;+ int cur_w, cur_h, is_target;+ int blend_enabled;+ int xform_valid;+ float xform_ox, xform_oy, xform_scale;+ GLuint bound_prog, bound_tex, bound_vao;+ NanoUiGlShaderEntry *shaders;+ int shader_count, shader_cap;+} NanoUiGl;++/* ---- Shared helpers and tight raw-buffer loops ---- */++static int is_opengl_renderer(SDL_Renderer *renderer)+{+ const char *name = renderer ? SDL_GetRendererName(renderer) : NULL;+ return name && strcmp(name, "opengl") == 0;+}++static void index_bounds(const int *idx, int n, int *out_lo, int *out_hi)+{+ int lo = idx[0], hi = idx[0];+ for (int k = 1; k < n; k++) {+ if (idx[k] < lo) lo = idx[k];+ if (idx[k] > hi) hi = idx[k];+ }+ *out_lo = lo;+ *out_hi = hi;+}++/* Commands may contain independent triangles, not just axis-aligned quads.+ * Reject a range only when every triangle is outside the damage bounds. SDL+ * clips intersecting triangles; this just avoids submitting invisible ranges. */+int nano_ui_range_visible(+ const uint8_t *verts, int vert_count, const uint8_t *indices, int index_start, int count,+ float x, float y, float w, float h)+{+ const SDL_Vertex *v = (const SDL_Vertex *)verts;+ const int *ix = (const int *)indices + index_start;+ const float rx = x + w, ry = y + h;+ for (int i = 0; i + 2 < count; i += 3) {+ if ((unsigned)ix[i] >= (unsigned)vert_count ||+ (unsigned)ix[i + 1] >= (unsigned)vert_count ||+ (unsigned)ix[i + 2] >= (unsigned)vert_count) {+ return 1;+ }+ const SDL_FPoint a = v[ix[i]].position;+ const SDL_FPoint b = v[ix[i + 1]].position;+ const SDL_FPoint c = v[ix[i + 2]].position;+ if (!((a.x < x && b.x < x && c.x < x) ||+ (a.x >= rx && b.x >= rx && c.x >= rx) ||+ (a.y < y && b.y < y && c.y < y) ||+ (a.y >= ry && b.y >= ry && c.y >= ry))) {+ return 1;+ }+ }+ return 0;+}++#if !SDL_VERSION_ATLEAST(3, 4, 0)+/* Narrow a batch's vertices to the range its indices use, rebasing indices to+ * its start. SDL 3.2 scans every vertex a textured call is given, and batches+ * share one frame buffer, so passing all of it makes a frame cost draws * verts. */+static void narrow(NanoUiGl *g, const SDL_Vertex **v, const int **idx, int n, int *nv)+{+ const int *ix = *idx;+ int lo, hi;+ index_bounds(ix, n, &lo, &hi);+ if (lo < 0 || hi >= *nv) return;+ *nv = hi + 1;+ if (lo == 0) return;+ if (g->rebased_cap < n) {+ int *grown = (int *)realloc(g->rebased, sizeof(int) * (size_t)n * 2);+ if (!grown) return;+ g->rebased = grown;+ g->rebased_cap = n * 2;+ }+ for (int k = 0; k < n; k++) {+ g->rebased[k] = ix[k] - lo;+ }+ *idx = g->rebased;+ *v += lo;+ *nv = hi - lo + 1;+}+#endif++static void scale_range(NanoUiGl *g, const SDL_Vertex *v, int from, int to)+{+ const float s = g->scale, ox = g->origin_x, oy = g->origin_y;+ for (int i = from; i < to; i++) {+ g->xy[2 * i] = (v[i].position.x - ox) * s;+ g->xy[2 * i + 1] = (v[i].position.y - oy) * s;+ }+}++/* Scaled positions covering the vertices the n indices idx use, counting from+ * vertex off of verts; NULL on allocation failure. */+static const float *scaled_positions(+ NanoUiGl *g, const uint8_t *verts, int total, int off, const int *idx, int n)+{+ if (g->xy_cap < total) {+ float *grown = (float *)realloc(g->xy, sizeof(float) * 2 * (size_t)total);+ if (!grown) return NULL;+ g->xy = grown;+ g->xy_cap = total;+ }+ int lo, hi;+ index_bounds(idx, n, &lo, &hi);+ lo += off;+ hi += off + 1;+ if (lo < 0) lo = 0;+ if (hi > total) hi = total;+ const SDL_Vertex *all = (const SDL_Vertex *)verts;+ if (g->xy_verts != verts || g->xy_lo >= g->xy_hi) {+ scale_range(g, all, lo, hi);+ g->xy_verts = verts;+ g->xy_lo = lo;+ g->xy_hi = hi;+ } else {+ if (lo < g->xy_lo) {+ scale_range(g, all, lo, g->xy_lo);+ g->xy_lo = lo;+ }+ if (hi > g->xy_hi) {+ scale_range(g, all, g->xy_hi, hi);+ g->xy_hi = hi;+ }+ }+ return g->xy + 2 * (size_t)off;+}++/* Submit an indexed range from the core's interleaved SDL_Vertex buffer via+ * SDL_RenderGeometryRaw, applying scale/origin transform on CPU when needed.+ * Untextured calls pass UVs too (every vertex has the white texel's UV):+ * SDL 3.4.0's software renderer reads UVs while merging triangles into rects+ * without checking for NULL, and segfaults. */+int nano_ui_sdl_draw_raw(+ NanoUiGl *g, SDL_Texture *tex,+ const uint8_t *verts, int vert_count,+ const uint8_t *indices, int index_start, int index_n)+{+ if (!g || !g->renderer || !verts || !indices || vert_count <= 0 || index_n < 3) return 0;+ const SDL_Vertex *v = (const SDL_Vertex *)verts;+ const int *idx = (const int *)indices + index_start;+ int nv = vert_count;+#if !SDL_VERSION_ATLEAST(3, 4, 0)+ narrow(g, &v, &idx, index_n, &nv);+#endif+ const int stride = (int)sizeof(SDL_Vertex);+ const float *xy = &v->position.x;+ int xy_stride = stride;+ if (g->scale != 1.f || g->origin_x != 0.f || g->origin_y != 0.f) {+ int off = (int)(v - (const SDL_Vertex *)verts);+ xy = scaled_positions(g, verts, vert_count, off, idx, index_n);+ xy_stride = (int)(2 * sizeof(float));+ if (!xy) return 0;+ }+ return SDL_RenderGeometryRaw(g->renderer, tex,+ xy, xy_stride, &v->color, stride,+ &v->tex_coord.x, stride,+ nv, idx, index_n, (int)sizeof(int)) ? 1 : 0;+}++/* ---- OpenGL 3.2 / GLSL 150 backend ---- */++/* Parse "major.minor..." from GL_VERSION and require OpenGL 3.2+ for GLSL 150. */+static int nui_gl_load(NanoUiGlApi *gl)+{+#define NUI_C(ret, name, args) \+ if (!(gl->name = (ret (APIENTRY *) args)SDL_GL_GetProcAddress("gl" #name))) return 0;+#define NUI_E(UP, name) \+ if (!(gl->name = (PFNGL##UP##PROC)SDL_GL_GetProcAddress("gl" #name))) return 0;+ NUI_GL_FUNCS(NUI_C, NUI_E)+#undef NUI_C+#undef NUI_E+ const GLubyte *ver = gl->GetString(GL_VERSION);+ int major = 0, minor = 0;+ return ver && sscanf((const char *)ver, "%d.%d", &major, &minor) >= 1 &&+ (major > 3 || (major == 3 && minor >= 2));+}++int nano_ui_gl_probe(SDL_Renderer *renderer)+{+ if (!is_opengl_renderer(renderer)) return 0;+ NanoUiGlApi tmp;+ return nui_gl_load(&tmp);+}++static const char *nui_gl_vertex_src =+ "#version 150\n"+ "in vec2 aPos;\n"+ "in vec4 aColor;\n"+ "in vec2 aUV;\n"+ "uniform vec4 uXform;\n"+ "out vec4 vColor;\n"+ "out vec2 vUV;\n"+ "void main() {\n"+ " gl_Position = vec4(aPos * uXform.xy + uXform.zw, 0.0, 1.0);\n"+ " vColor = aColor;\n"+ " vUV = aUV;\n"+ "}\n";++/* Sampler uniform uInput defaults to texture unit 0 on link per OpenGL 3.2. */+static const char *nui_gl_plain_frag_src =+ "#version 150\n"+ "in vec4 vColor;\n"+ "in vec2 vUV;\n"+ "uniform sampler2D uInput;\n"+ "out vec4 fragColor;\n"+ "void main() {\n"+ " fragColor = vColor * texture(uInput, vUV);\n"+ "}\n";++static int nui_gl_make_current(NanoUiGl *g)+{+ if (g->ctx && g->win && SDL_GL_GetCurrentContext() != g->ctx) {+ return SDL_GL_MakeCurrent(g->win, g->ctx) ? 1 : 0;+ }+ return 1;+}++static void nui_gl_set_linear_clamp(NanoUiGlApi *gl)+{+ gl->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);+ gl->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);+ gl->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);+ gl->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);+}++static void nui_gl_init_vao(NanoUiGlApi *gl, GLuint *vao, GLuint *vbo, GLuint *ebo)+{+ gl->GenVertexArrays(1, vao);+ gl->GenBuffers(1, vbo);+ gl->BindVertexArray(*vao);+ gl->BindBuffer(GL_ARRAY_BUFFER, *vbo);+ if (ebo) {+ gl->GenBuffers(1, ebo);+ gl->BindBuffer(GL_ELEMENT_ARRAY_BUFFER, *ebo);+ }+ const GLsizei stride = (GLsizei)sizeof(SDL_Vertex);+ gl->EnableVertexAttribArray(0);+ gl->VertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, stride, (const void *)offsetof(SDL_Vertex, position));+ gl->EnableVertexAttribArray(1);+ gl->VertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, stride, (const void *)offsetof(SDL_Vertex, color));+ gl->EnableVertexAttribArray(2);+ gl->VertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, stride, (const void *)offsetof(SDL_Vertex, tex_coord));+}++static GLuint nui_gl_compile(NanoUiGlApi *gl, GLenum type, const char *src, GLint len)+{+ GLuint sh = gl->CreateShader(type);+ GLint ok = 0;+ gl->ShaderSource(sh, 1, &src, len >= 0 ? &len : NULL);+ gl->CompileShader(sh);+ gl->GetShaderiv(sh, GL_COMPILE_STATUS, &ok);+ if (!ok) {+ char log[1024];+ gl->GetShaderInfoLog(sh, (GLsizei)sizeof(log), NULL, log);+ fprintf(stderr, "nano-ui-sdl: OpenGL shader compile failed: %s\n", log);+ gl->DeleteShader(sh);+ return 0;+ }+ return sh;+}++static void nui_gl_link_program(+ NanoUiGlApi *gl, GLuint vs, const char *frag_src, GLint frag_len, NanoUiGlShaderEntry *out)+{+ out->program = 0;+ out->uXform = -1;+ if (!vs || !frag_src || frag_len == 0) return;+ GLuint fs = nui_gl_compile(gl, GL_FRAGMENT_SHADER, frag_src, frag_len);+ if (!fs) return;+ GLuint prog = gl->CreateProgram();+ gl->AttachShader(prog, vs);+ gl->AttachShader(prog, fs);+ gl->BindAttribLocation(prog, 0, "aPos");+ gl->BindAttribLocation(prog, 1, "aColor");+ gl->BindAttribLocation(prog, 2, "aUV");+ gl->LinkProgram(prog);+ gl->DeleteShader(fs);+ GLint ok = 0;+ gl->GetProgramiv(prog, GL_LINK_STATUS, &ok);+ if (!ok) {+ char log[1024];+ gl->GetProgramInfoLog(prog, (GLsizei)sizeof(log), NULL, log);+ fprintf(stderr, "nano-ui-sdl: OpenGL shader link failed: %s\n", log);+ gl->DeleteProgram(prog);+ return;+ }+ GLuint blk = gl->GetUniformBlockIndex(prog, "NanoShaderBlock");+ if (blk != GL_INVALID_INDEX) gl->UniformBlockBinding(prog, blk, 0);+ out->program = prog;+ out->uXform = gl->GetUniformLocation(prog, "uXform");+}++static int nui_gl_ensure_init(NanoUiGl *g)+{+ if (g->init_state) return g->init_state > 0;+ if (!is_opengl_renderer(g->renderer)) {+ g->init_state = -1;+ return 0;+ }+ SDL_FlushRenderer(g->renderer);+ if (!g->win) g->win = SDL_GetRenderWindow(g->renderer);+ if (g->ctx) {+ if (!nui_gl_make_current(g)) return 0;+ } else {+ /* Only bind the current context when it belongs to this window, so a+ * multi-window session never attaches another window's GL context. */+ SDL_GLContext cur = SDL_GL_GetCurrentContext();+ if (!cur || (g->win && SDL_GL_GetCurrentWindow() != g->win)) return 0;+ g->ctx = cur;+ }+ g->init_state = -1;+ if (!nui_gl_load(&g->api)) return 0;++ NanoUiGlApi *gl = &g->api;+ nui_gl_init_vao(gl, &g->vao, &g->vbo, &g->ebo);+ nui_gl_init_vao(gl, &g->quad_vao, &g->quad_vbo, NULL);+ gl->BindVertexArray(0);+ gl->BindBuffer(GL_ARRAY_BUFFER, 0);+ gl->BindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);+ gl->GenBuffers(1, &g->ubo);++ gl->GenTextures(1, &g->white_tex);+ gl->ActiveTexture(GL_TEXTURE0);+ gl->BindTexture(GL_TEXTURE_2D, g->white_tex);+ nui_gl_set_linear_clamp(gl);+ const uint32_t white = 0xFFFFFFFFu;+ gl->TexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, 1, 1, 0, GL_RGBA, GL_UNSIGNED_BYTE, &white);+ gl->BindTexture(GL_TEXTURE_2D, 0);++ g->vs = nui_gl_compile(gl, GL_VERTEX_SHADER, nui_gl_vertex_src, -1);+ nui_gl_link_program(gl, g->vs, nui_gl_plain_frag_src, -1, &g->plain);+ SDL_FlushRenderer(g->renderer);+ g->init_state = 1;+ return 1;+}++static void nui_gl_apply_scissor(NanoUiGl *g)+{+ NanoUiGlApi *gl = &g->api;+ if (g->has_clip) {+ int sw = g->clip.w > 0 ? g->clip.w : 0;+ int sh = g->clip.h > 0 ? g->clip.h : 0;+ int sy = g->is_target ? g->clip.y : (g->cur_h - g->clip.y - sh);+ gl->Enable(GL_SCISSOR_TEST);+ gl->Scissor(g->clip.x, sy, sw, sh);+ } else {+ gl->Disable(GL_SCISSOR_TEST);+ }+}++static GLuint nui_gl_texture_id(SDL_Texture *tex)+{+ SDL_PropertiesID props = tex ? SDL_GetTextureProperties(tex) : 0;+ return props ? (GLuint)SDL_GetNumberProperty(props, SDL_PROP_TEXTURE_OPENGL_TEXTURE_NUMBER, 0) : 0;+}++/* Resolve the GL texture id and blend state for a standard plain batch,+ * returning 0 when a custom blend mode or texture format requires SDL's+ * fallback geometry path (such as transparent windows). */+static int nui_gl_plain_texture_id(NanoUiGl *g, SDL_Texture *tex, GLuint *out_tex, int *out_blend)+{+ SDL_BlendMode bm = SDL_BLENDMODE_NONE;+ bool got_bm = tex ? SDL_GetTextureBlendMode(tex, &bm)+ : SDL_GetRenderDrawBlendMode(g->renderer, &bm);+ if (!got_bm || (bm != SDL_BLENDMODE_BLEND && bm != SDL_BLENDMODE_NONE)) return 0;+ *out_blend = (bm == SDL_BLENDMODE_BLEND);+ if (!tex) {+ *out_tex = g->white_tex;+ return 1;+ }+ SDL_PropertiesID props = SDL_GetTextureProperties(tex);+ if (!props ||+ SDL_GetNumberProperty(props, SDL_PROP_TEXTURE_OPENGL_TEXTURE_TARGET_NUMBER, 0) != GL_TEXTURE_2D ||+ SDL_GetFloatProperty(props, SDL_PROP_TEXTURE_OPENGL_TEX_W_FLOAT, 0.0f) != 1.0f ||+ SDL_GetFloatProperty(props, SDL_PROP_TEXTURE_OPENGL_TEX_H_FLOAT, 0.0f) != 1.0f) {+ return 0;+ }+ GLuint id = (GLuint)SDL_GetNumberProperty(props, SDL_PROP_TEXTURE_OPENGL_TEXTURE_NUMBER, 0);+ if (!id) return 0;+ *out_tex = id;+ return 1;+}++/* Take ownership of the OpenGL context from SDL for one or more consecutive+ * plain or shader draws against the current render target. */+static int nui_gl_enter_pass(NanoUiGl *g)+{+ if (g->pass_active) return 1;+ SDL_FlushRenderer(g->renderer);+ if (!nui_gl_make_current(g)) return 0;++ int cur_w = 0, cur_h = 0, is_target = 0;+ SDL_Texture *cur = SDL_GetRenderTarget(g->renderer);+ if (cur) {+ float tw = 0.f, th = 0.f;+ SDL_GetTextureSize(cur, &tw, &th);+ cur_w = (int)tw;+ cur_h = (int)th;+ is_target = 1;+ } else {+ SDL_GetRenderOutputSize(g->renderer, &cur_w, &cur_h);+ }+ if (cur_w <= 0 || cur_h <= 0) return 0;++ NanoUiGlApi *gl = &g->api;+ g->cur_w = cur_w;+ g->cur_h = cur_h;+ g->is_target = is_target;+ gl->Viewport(0, 0, cur_w, cur_h);+ gl->Disable(GL_DEPTH_TEST);+ gl->Disable(GL_CULL_FACE);+ nui_gl_apply_scissor(g);+ gl->BlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);+ gl->BlendEquation(GL_FUNC_ADD);+ gl->ActiveTexture(GL_TEXTURE0);+ g->bound_prog = 0;+ g->bound_tex = 0;+ g->bound_vao = 0;+ g->blend_enabled = -1;+ g->xform_valid = 0;+ g->pass_active = 1;+ return 1;+}++/* Leave the OpenGL 3.2 pass and hand GL state back to SDL. */+void nano_ui_gl_leave_pass(NanoUiGl *g)+{+ if (!g || !g->pass_active) return;+ g->pass_active = 0;+ if (nui_gl_make_current(g)) {+ NanoUiGlApi *gl = &g->api;+ gl->UseProgram(0);+ gl->BindVertexArray(0);+ gl->BindBuffer(GL_ARRAY_BUFFER, 0);+ gl->BindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);+ gl->BindBuffer(GL_UNIFORM_BUFFER, 0);+ gl->ActiveTexture(GL_TEXTURE0);+ gl->BindTexture(GL_TEXTURE_2D, 0);+ gl->Disable(GL_SCISSOR_TEST);+ SDL_FlushRenderer(g->renderer);+ }+ if (g->renderer) {+ SDL_SetRenderClipRect(g->renderer, g->has_clip ? &g->clip : NULL);+ }+}++static NanoUiGlShaderEntry *nui_gl_resolve_shader(+ NanoUiGl *g, uint64_t hash, const uint8_t *glsl, int glsl_len)+{+ if (!glsl || glsl_len <= 0 || !nui_gl_ensure_init(g) || !nui_gl_enter_pass(g)) return NULL;+ for (int i = 0; i < g->shader_count; i++) {+ if (g->shaders[i].hash == hash) {+ return g->shaders[i].program ? &g->shaders[i] : NULL;+ }+ }+ if (g->shader_count == g->shader_cap) {+ int new_cap = g->shader_cap > 0 ? g->shader_cap * 2 : 16;+ NanoUiGlShaderEntry *grown = (NanoUiGlShaderEntry *)realloc(+ g->shaders, (size_t)new_cap * sizeof(*grown));+ if (!grown) return NULL;+ g->shaders = grown;+ g->shader_cap = new_cap;+ }+ NanoUiGlShaderEntry *entry = &g->shaders[g->shader_count++];+ entry->hash = hash;+ nui_gl_link_program(&g->api, g->vs, (const char *)glsl, (GLint)glsl_len, entry);+ return entry->program ? entry : NULL;+}++/* Bind program, affine transform, blend state, texture, and optional UBO+ * inside the active GL pass, skipping redundant state transitions. */+static int nui_gl_bind_draw(+ NanoUiGl *g, const NanoUiGlShaderEntry *entry,+ float ox, float oy, float scale, GLuint gl_tex, int want_blend,+ const uint8_t *uniform_bytes, int uniform_len)+{+ if (!nui_gl_enter_pass(g)) return 0;+ NanoUiGlApi *gl = &g->api;+ if (g->bound_prog != entry->program) {+ gl->UseProgram(entry->program);+ g->bound_prog = entry->program;+ g->xform_valid = 0;+ }+ if (!g->xform_valid || ox != g->xform_ox || oy != g->xform_oy || scale != g->xform_scale) {+ if (entry->uXform >= 0) {+ float flip = g->is_target ? 1.0f : -1.0f;+ float sx = 2.0f * scale / (float)g->cur_w;+ float sy = flip * 2.0f * scale / (float)g->cur_h;+ gl->Uniform4f(entry->uXform, sx, sy, -ox * sx - 1.0f, -oy * sy - flip);+ }+ g->xform_ox = ox;+ g->xform_oy = oy;+ g->xform_scale = scale;+ g->xform_valid = 1;+ }+ if (want_blend != g->blend_enabled) {+ if (want_blend) gl->Enable(GL_BLEND);+ else gl->Disable(GL_BLEND);+ g->blend_enabled = want_blend;+ }+ GLuint tex = gl_tex ? gl_tex : g->white_tex;+ if (tex != g->bound_tex) {+ gl->BindTexture(GL_TEXTURE_2D, tex);+ g->bound_tex = tex;+ }+ if (uniform_len > 0 && uniform_bytes != NULL) {+ gl->BindBuffer(GL_UNIFORM_BUFFER, g->ubo);+ gl->BufferData(GL_UNIFORM_BUFFER, (GLsizeiptr)uniform_len, uniform_bytes, GL_STREAM_DRAW);+ gl->BindBufferBase(GL_UNIFORM_BUFFER, 0, g->ubo);+ }+ return 1;+}++/* Orphan-and-subdata upload with power-of-two capacity so resizing frames do+ * not free/reallocate variable-sized driver buffer storage on every pixel. */+static void nui_gl_upload_buffer(+ NanoUiGlApi *gl, GLenum target, GLuint buf,+ size_t *cap, size_t min_cap, const void *data, size_t bytes)+{+ gl->BindBuffer(target, buf);+ if (bytes == 0) return;+ size_t c = *cap;+ if (c < bytes) {+ if (c < min_cap) c = min_cap;+ while (c < bytes && c <= SIZE_MAX / 2) c *= 2;+ if (c < bytes) c = bytes;+ *cap = c;+ }+ gl->BufferData(target, (GLsizeiptr)c, NULL, GL_STREAM_DRAW);+ gl->BufferSubData(target, 0, (GLsizeiptr)bytes, data);+}++/* Upload pass vertices and indices into the pooled VBO/EBO at most once per+ * pass, then issue one indexed triangle draw using the given shader entry. */+static int nui_gl_draw_indexed(+ NanoUiGl *g, const NanoUiGlShaderEntry *entry,+ GLuint gl_tex, int want_blend,+ const uint8_t *verts, int vert_count,+ const uint8_t *indices, int index_start, int index_n,+ const uint8_t *uniform_bytes, int uniform_len)+{+ if (!nui_gl_bind_draw(g, entry, g->origin_x, g->origin_y, g->scale,+ gl_tex, want_blend, uniform_bytes, uniform_len)) {+ return 0;+ }+ NanoUiGlApi *gl = &g->api;+ if (g->bound_vao != g->vao) {+ gl->BindVertexArray(g->vao);+ g->bound_vao = g->vao;+ }+ if (g->uploaded_verts != verts || g->uploaded_vert_count != vert_count) {+ nui_gl_upload_buffer(gl, GL_ARRAY_BUFFER, g->vbo, &g->vbo_cap, 65536,+ verts, (size_t)vert_count * sizeof(SDL_Vertex));+ g->uploaded_verts = verts;+ g->uploaded_vert_count = vert_count;+ }+ const void *index_offset;+ if (g->index_total > 0 && index_start >= 0 && index_n <= g->index_total - index_start) {+ if (g->uploaded_indices != indices || g->uploaded_index_count != g->index_total) {+ nui_gl_upload_buffer(gl, GL_ELEMENT_ARRAY_BUFFER, g->ebo, &g->ebo_cap, 32768,+ indices, (size_t)g->index_total * sizeof(int));+ g->uploaded_indices = indices;+ g->uploaded_index_count = g->index_total;+ }+ index_offset = (const void *)((size_t)index_start * sizeof(int));+ } else {+ nui_gl_upload_buffer(gl, GL_ELEMENT_ARRAY_BUFFER, g->ebo, &g->ebo_cap, 32768,+ (const int *)indices + index_start, (size_t)index_n * sizeof(int));+ g->uploaded_indices = NULL;+ g->uploaded_index_count = 0;+ index_offset = (const void *)0;+ }+ gl->DrawElements(GL_TRIANGLES, (GLsizei)index_n, GL_UNSIGNED_INT, index_offset);+ return 1;+}++/* ---- Public C entry points called by NanoUI.Sdl.Internal.Render ---- */++NanoUiGl *nano_ui_gl_create(SDL_Renderer *renderer)+{+ if (!renderer) return NULL;+ NanoUiGl *g = (NanoUiGl *)calloc(1, sizeof(NanoUiGl));+ if (!g) return NULL;+ g->renderer = renderer;+ g->scale = 1.f;+ if (is_opengl_renderer(renderer)) {+ g->win = SDL_GetRenderWindow(renderer);+ if (g->win && SDL_GL_GetCurrentWindow() == g->win) {+ g->ctx = SDL_GL_GetCurrentContext();+ }+ }+ return g;+}++void nano_ui_gl_destroy(NanoUiGl *g)+{+ if (!g) return;+ nano_ui_gl_leave_pass(g);+ if (g->init_state > 0 && nui_gl_make_current(g)) {+ NanoUiGlApi *gl = &g->api;+ for (int i = 0; i < g->shader_count; i++) {+ gl->DeleteProgram(g->shaders[i].program);+ }+ gl->DeleteProgram(g->plain.program);+ gl->DeleteShader(g->vs);+ gl->DeleteTextures(1, &g->white_tex);+ const GLuint bufs[] = { g->vbo, g->ebo, g->quad_vbo, g->ubo };+ const GLuint vaos[] = { g->vao, g->quad_vao };+ gl->DeleteBuffers(4, bufs);+ gl->DeleteVertexArrays(2, vaos);+ }+ free(g->shaders);+#if !SDL_VERSION_ATLEAST(3, 4, 0)+ free(g->rebased);+#endif+ free(g->xy);+ free(g);+}++void nano_ui_gl_begin_pass(NanoUiGl *g, float scale, int index_total)+{+ if (!g) return;+ nano_ui_gl_leave_pass(g);+ g->scale = scale > 0.f ? scale : 1.f;+ g->origin_x = 0.f;+ g->origin_y = 0.f;+ g->index_total = index_total > 0 ? index_total : 0;+ g->xy_verts = NULL;+ g->xy_lo = g->xy_hi = 0;+ g->uploaded_verts = NULL;+ g->uploaded_vert_count = 0;+ g->uploaded_indices = NULL;+ g->uploaded_index_count = 0;+ g->has_clip = 0;+ if (g->renderer) SDL_SetRenderClipRect(g->renderer, NULL);+}++void nano_ui_gl_end_pass(NanoUiGl *g)+{+ if (!g) return;+ g->has_clip = 0;+ if (g->pass_active) {+ nano_ui_gl_leave_pass(g);+ } else if (g->renderer) {+ SDL_SetRenderClipRect(g->renderer, NULL);+ }+}++void nano_ui_gl_set_clip(NanoUiGl *g, int has_clip, int x, int y, int w, int h)+{+ if (!g || !g->renderer) return;+ g->has_clip = has_clip != 0;+ g->clip = (SDL_Rect){ x, y, w, h };+ if (g->pass_active) {+ nui_gl_apply_scissor(g);+ } else {+ SDL_SetRenderClipRect(g->renderer, g->has_clip ? &g->clip : NULL);+ }+}++void nano_ui_gl_set_origin(NanoUiGl *g, float ox, float oy)+{+ if (!g) return;+ nano_ui_gl_leave_pass(g);+ g->origin_x = ox;+ g->origin_y = oy;+ g->xy_verts = NULL;+ g->xy_lo = g->xy_hi = 0;+}++/* Draw one coalesced plain range through OpenGL 3.2 VAO/VBO/EBO when available,+ * falling back to SDL_RenderGeometryRaw otherwise. */+void nano_ui_gl_draw_plain(+ NanoUiGl *g, const uint8_t *verts, int vert_count,+ const uint8_t *indices, int index_start, int index_n, SDL_Texture *texture)+{+ if (!g || !g->renderer || !verts || !indices || vert_count <= 0 || index_n < 3) return;+ if (nui_gl_ensure_init(g) && g->plain.program) {+ GLuint gl_tex = 0;+ int want_blend = 1;+ if (nui_gl_plain_texture_id(g, texture, &gl_tex, &want_blend)) {+ if (nui_gl_draw_indexed(g, &g->plain, gl_tex, want_blend,+ verts, vert_count, indices, index_start, index_n, NULL, 0)) {+ return;+ }+ } else {+ nano_ui_gl_leave_pass(g);+ }+ }+ nano_ui_sdl_draw_raw(g, texture, verts, vert_count, indices, index_start, index_n);+}++/* Draw one Tier 1 GLSL 150 custom shader range inside the active GL pass. */+int nano_ui_gl_draw_shader(+ NanoUiGl *g, const uint8_t *verts, int vert_count,+ const uint8_t *indices, int index_start, int index_n,+ SDL_Texture *texture, uint64_t hash,+ const uint8_t *glsl, int glsl_len,+ const uint8_t *uniform_bytes, int uniform_len)+{+ if (!g || !g->renderer || !verts || !indices || vert_count <= 0 || index_n < 3) return 0;+ NanoUiGlShaderEntry *entry = nui_gl_resolve_shader(g, hash, glsl, glsl_len);+ if (!entry) return 0;+ return nui_gl_draw_indexed(g, entry, nui_gl_texture_id(texture), 1,+ verts, vert_count, indices, index_start, index_n,+ uniform_bytes, uniform_len);+}++/* Composite one Tier 2 offscreen texture quad through a cached GLSL 150 shader. */+int nano_ui_gl_composite_effect(+ NanoUiGl *g, SDL_Texture *src_tex,+ float px, float py, float pw, float ph,+ float u0, float v0, float u1, float v1,+ uint64_t hash, const uint8_t *glsl, int glsl_len,+ const uint8_t *uniform_bytes, int uniform_len)+{+ if (!g || !g->renderer || !src_tex) return 0;+ GLuint gl_src = nui_gl_texture_id(src_tex);+ NanoUiGlShaderEntry *entry = gl_src ? nui_gl_resolve_shader(g, hash, glsl, glsl_len) : NULL;+ if (!entry || !nui_gl_bind_draw(g, entry, 0.0f, 0.0f, 1.0f, gl_src, 1, uniform_bytes, uniform_len)) {+ return 0;+ }+ const SDL_FColor white = { 1.f, 1.f, 1.f, 1.f };+ const SDL_Vertex quad[4] = {+ { { px, py }, white, { u0, v0 } },+ { { px + pw, py }, white, { u1, v0 } },+ { { px + pw, py + ph }, white, { u1, v1 } },+ { { px, py + ph }, white, { u0, v1 } },+ };+ NanoUiGlApi *gl = &g->api;+ nui_gl_set_linear_clamp(gl);+ gl->BindVertexArray(g->quad_vao);+ g->bound_vao = g->quad_vao;+ gl->BindBuffer(GL_ARRAY_BUFFER, g->quad_vbo);+ gl->BufferData(GL_ARRAY_BUFFER, (GLsizeiptr)sizeof(quad), quad, GL_STREAM_DRAW);+ gl->DrawArrays(GL_TRIANGLE_FAN, 0, 4);+ return 1;+}
− cbits/nano_ui_simd.h
@@ -1,44 +0,0 @@-#ifndef NANO_UI_SIMD_H-#define NANO_UI_SIMD_H--#include <stdint.h>-#include <stdbool.h>--#if defined(__AVX2__)-#include <immintrin.h>-#define NANO_UI_HAS_AVX2 1-#endif--// Returns true if quad AABB [qx0, qy0, qx1, qy1] intersects [dx0, dy0, dx1, dy1]-static inline bool nano_ui_aabb_intersects(- float qx0, float qy0, float qx1, float qy1,- float dx0, float dy0, float dx1, float dy1)-{- return !(qx1 < dx0 || qx0 > dx1 || qy1 < dy0 || qy0 > dy1);-}--#if defined(NANO_UI_HAS_AVX2)--// Tests 8 quad bounding boxes against damage rect [dx0, dy0, dx1, dy1].-// Returns an 8-bit mask where bit i is 1 if quad i intersects the damage rectangle.-static inline uint32_t nano_ui_cull_8_quads_avx2(- __m256 qx0, __m256 qy0, __m256 qx1, __m256 qy1,- __m256 dx0, __m256 dy0, __m256 dx1, __m256 dy1)-{- __m256 outside = _mm256_or_ps(- _mm256_cmp_ps(qx1, dx0, _CMP_LT_OQ),- _mm256_or_ps(- _mm256_cmp_ps(qx0, dx1, _CMP_GT_OQ),- _mm256_or_ps(- _mm256_cmp_ps(qy1, dy0, _CMP_LT_OQ),- _mm256_cmp_ps(qy0, dy1, _CMP_GT_OQ)- )- )- );- uint32_t out_mask = (uint32_t)_mm256_movemask_ps(outside);- return (~out_mask) & 0xFF;-}--#endif--#endif // NANO_UI_SIMD_H
cbits/nano_ui_text_atlas.c view
@@ -1,56 +1,71 @@ #include "nano_ui_text_atlas.h" #include <SDL3/SDL.h>+#include <stdint.h> #include <stdlib.h> #include <string.h> -enum {- NANO_UI_TEXT_ATLAS_SIZE = 2048,- NANO_UI_TEXT_ATLAS_PAD = 1,- NANO_UI_WHITE_PATCH_SIZE = 4-};+/* Glyphs fill page 0, then each later page in turn, placed by+ * nano_ui_ttf_shared.h as nano-ui-sdl-web's atlas places them. Each opened+ * page keeps a CPU RGBA32 backing buffer and a dirty bounding rectangle so+ * bursts of glyph insertions copy into RAM and flush to the GPU texture in a+ * single SDL_UpdateTexture when nano_ui_text_atlas_texture is queried. A+ * reset clears only the previously used rows of page 0 and leaves the rest+ * untouched. */+typedef struct {+ SDL_Texture *tex;+ uint8_t *pixels;+ int used_h;+ int dirty_x0;+ int dirty_y0;+ int dirty_x1;+ int dirty_y1;+ bool dirty;+} NanoUiAtlasPage; struct NanoUiTextAtlas { SDL_Renderer *renderer;- SDL_Texture *tex;- Uint8 *pixels;- int w;- int h;- int x;- int y;- int row_h;+ NanoUiAtlasPage pages[NANO_UI_TEXT_ATLAS_PAGES];+ NanoUiAtlasCursor cur; }; -static void init_white_pixel(NanoUiTextAtlas *atlas)+static void mark_dirty(NanoUiAtlasPage *p, int x0, int y0, int x1, int y1) {- if (!atlas || !atlas->pixels || atlas->w <= 0 || atlas->h <= 0) {+ if (x0 >= x1 || y0 >= y1) { return; }- for (int y = 0; y < NANO_UI_WHITE_PATCH_SIZE && y < atlas->h; y++) {- for (int x = 0; x < NANO_UI_WHITE_PATCH_SIZE && x < atlas->w; x++) {- size_t off = ((size_t)y * (size_t)atlas->w + (size_t)x) * 4;- atlas->pixels[off + 0] = 255;- atlas->pixels[off + 1] = 255;- atlas->pixels[off + 2] = 255;- atlas->pixels[off + 3] = 255;- }+ if (!p->dirty) {+ p->dirty_x0 = x0;+ p->dirty_y0 = y0;+ p->dirty_x1 = x1;+ p->dirty_y1 = y1;+ p->dirty = true;+ } else {+ if (x0 < p->dirty_x0) p->dirty_x0 = x0;+ if (y0 < p->dirty_y0) p->dirty_y0 = y0;+ if (x1 > p->dirty_x1) p->dirty_x1 = x1;+ if (y1 > p->dirty_y1) p->dirty_y1 = y1; } } -static bool upload_all(NanoUiTextAtlas *atlas)+static void write_white_patch(uint8_t *pixels) {- if (!atlas->tex || !atlas->pixels || atlas->w <= 0 || atlas->h <= 0) {- return false;+ const int pitch = NANO_UI_GLYPH_ATLAS_SIZE * 4;+ for (int y = 0; y < NANO_UI_WHITE_PATCH_SIZE; y++) {+ memset(pixels + (size_t)y * (size_t)pitch, 0xff, (size_t)NANO_UI_WHITE_PATCH_SIZE * 4); }- return SDL_UpdateTexture(atlas->tex, NULL, atlas->pixels, atlas->w * 4); } -static bool create_texture(NanoUiTextAtlas *atlas, int w, int h)+static SDL_Texture *create_texture(NanoUiTextAtlas *atlas) {- SDL_Texture *tex =- SDL_CreateTexture(atlas->renderer, SDL_PIXELFORMAT_RGBA32, SDL_TEXTUREACCESS_STREAMING, w, h);+ SDL_Texture *tex = SDL_CreateTexture(+ atlas->renderer,+ SDL_PIXELFORMAT_RGBA32,+ SDL_TEXTUREACCESS_STREAMING,+ NANO_UI_GLYPH_ATLAS_SIZE,+ NANO_UI_GLYPH_ATLAS_SIZE); if (!tex) {- return false;+ return NULL; } SDL_SetTextureBlendMode(tex, SDL_BLENDMODE_BLEND); /* Bilinear filtering keeps glyph quads smooth when a quad lands off a@@ -58,62 +73,73 @@ * shaped-run placement). NEAREST snaps to the closest texel and makes * scaled/slightly-misaligned text look blocky and pixelated. */ SDL_SetTextureScaleMode(tex, SDL_SCALEMODE_LINEAR);- Uint8 *px = (Uint8 *)calloc((size_t)w * (size_t)h, 4);- if (!px) {- SDL_DestroyTexture(tex);- return false;- }- atlas->tex = tex;- atlas->pixels = px;- atlas->w = w;- atlas->h = h;- init_white_pixel(atlas);- return upload_all(atlas);+ return tex; } -static bool slot_for(NanoUiTextAtlas *atlas, int gw, int gh, int *out_x, int *out_y)+static bool flush_page(NanoUiAtlasPage *p) {- int pad = NANO_UI_TEXT_ATLAS_PAD;- if (gw + 2 * pad > NANO_UI_TEXT_ATLAS_SIZE || gh + 2 * pad > NANO_UI_TEXT_ATLAS_SIZE) {- return false;+ if (!p->dirty || !p->tex || !p->pixels) {+ return true; }- if (!atlas->tex) {- if (!create_texture(atlas, NANO_UI_TEXT_ATLAS_SIZE, NANO_UI_TEXT_ATLAS_SIZE)) {+ const int size = NANO_UI_GLYPH_ATLAS_SIZE;+ const int pitch = size * 4;+ int x0 = p->dirty_x0 < 0 ? 0 : p->dirty_x0;+ int y0 = p->dirty_y0 < 0 ? 0 : p->dirty_y0;+ int x1 = p->dirty_x1 > size ? size : p->dirty_x1;+ int y1 = p->dirty_y1 > size ? size : p->dirty_y1;+ if (x0 < x1 && y0 < y1) {+ SDL_Rect rect = {x0, y0, x1 - x0, y1 - y0};+ const uint8_t *src = p->pixels + (size_t)y0 * (size_t)pitch + (size_t)x0 * 4;+ if (!SDL_UpdateTexture(p->tex, &rect, src, pitch)) { return false; }- atlas->x = NANO_UI_WHITE_PATCH_SIZE + pad;- atlas->y = pad;- atlas->row_h = NANO_UI_WHITE_PATCH_SIZE; }- if (atlas->x + gw + pad <= atlas->w && atlas->y + gh + pad <= atlas->h) {- *out_x = atlas->x;- *out_y = atlas->y;- return true;- }- int next_y = atlas->y + (atlas->row_h > 0 ? atlas->row_h + pad : pad);- if (next_y + gh + pad <= atlas->h && gw + 2 * pad <= atlas->w) {- atlas->y = next_y;- atlas->x = pad;- atlas->row_h = 0;- *out_x = atlas->x;- *out_y = atlas->y;- return true;- }- return false;+ p->dirty = false;+ return true; } -/* Glyph surfaces arrive as RGBA32 (glyph_image_to_rgba in nano_ui_ttf.c). */-static bool blit_surface(NanoUiTextAtlas *atlas, SDL_Surface *surface, int x, int y)+/* Start glyphs on page `page`: allocate or clear only the previously used+ * rows of its CPU buffer, ensure its GPU texture exists, and put the cursor+ * after its white patch. The atlas is a void pointer for+ * nano_ui_atlas_slot_for. */+static bool open_page(void *self, int page) {- const Uint8 *src = (const Uint8 *)surface->pixels;- int w = surface->w;- int h = surface->h;- for (int row = 0; row < h; row++) {- Uint8 *dst = atlas->pixels + ((y + row) * atlas->w + x) * 4;- memcpy(dst, src + (size_t)row * (size_t)surface->pitch, (size_t)w * 4);+ NanoUiTextAtlas *atlas = (NanoUiTextAtlas *)self;+ NanoUiAtlasPage *p = &atlas->pages[page];+ const int size = NANO_UI_GLYPH_ATLAS_SIZE;+ const int pitch = size * 4;+ bool fresh_tex = false;+ if (!p->tex) {+ p->tex = create_texture(atlas);+ if (!p->tex) {+ return false;+ }+ fresh_tex = true; }- SDL_Rect rect = {x, y, w, h};- return SDL_UpdateTexture(atlas->tex, &rect, atlas->pixels + (y * atlas->w + x) * 4, atlas->w * 4);+ int clear_h = p->used_h;+ if (!p->pixels) {+ p->pixels = (uint8_t *)calloc((size_t)size * (size_t)size, 4);+ if (!p->pixels) {+ return false;+ }+ clear_h = size;+ } else if (clear_h > 0) {+ if (clear_h > size) clear_h = size;+ memset(p->pixels, 0, (size_t)clear_h * (size_t)pitch);+ }+ write_white_patch(p->pixels);+ const int min_h = NANO_UI_WHITE_PATCH_SIZE + NANO_UI_GLYPH_ATLAS_PAD;+ p->used_h = min_h;+ if (fresh_tex) {+ /* A newly created GPU texture has undefined contents everywhere,+ * including the bottom-row padding texel sampled for missing glyphs. */+ mark_dirty(p, 0, 0, size, size);+ } else {+ int dirty_h = clear_h > min_h ? clear_h : min_h;+ mark_dirty(p, 0, 0, size, dirty_h);+ }+ nano_ui_atlas_cursor_open(&atlas->cur, page);+ return true; } NanoUiTextAtlas *nano_ui_text_atlas_create(SDL_Renderer *renderer)@@ -134,27 +160,32 @@ if (!atlas) { return; }- if (atlas->tex) {- SDL_DestroyTexture(atlas->tex);+ nano_ui_text_atlas_drop_textures(atlas);+ for (int i = 0; i < NANO_UI_TEXT_ATLAS_PAGES; i++) {+ free(atlas->pages[i].pixels);+ atlas->pages[i].pixels = NULL; }- free(atlas->pixels); free(atlas); } -SDL_Texture *nano_ui_text_atlas_texture(NanoUiTextAtlas *atlas)+SDL_Texture *nano_ui_text_atlas_texture(NanoUiTextAtlas *atlas, int page) {- return atlas ? atlas->tex : NULL;+ if (!atlas || page < 0 || page >= NANO_UI_TEXT_ATLAS_PAGES) {+ return NULL;+ }+ NanoUiAtlasPage *p = &atlas->pages[page];+ if (p->tex && p->dirty) {+ flush_page(p);+ }+ return p->tex; } bool nano_ui_text_atlas_insert_surface( NanoUiTextAtlas *atlas, SDL_Surface *surface,- float *out_x,- float *out_y,- float *out_w,- float *out_h)+ float uv[4]) {- if (!atlas || !surface) {+ if (!atlas || !surface || !uv) { return false; } int gw = surface->w;@@ -162,31 +193,43 @@ if (gw <= 0 || gh <= 0) { return false; }+ int page = 0; int x = 0; int y = 0;- if (!slot_for(atlas, gw, gh, &x, &y)) {- return false;- }- if (!blit_surface(atlas, surface, x, y)) {+ if (!nano_ui_atlas_slot_for(&atlas->cur, atlas, open_page, gw, gh, &page, &x, &y)) { return false; }- atlas->x = x + gw + NANO_UI_TEXT_ATLAS_PAD;- if (gh > atlas->row_h) {- atlas->row_h = gh;- }- if (out_x) {- *out_x = (float)x;+ NanoUiAtlasPage *p = &atlas->pages[page];+ const int dst_pitch = NANO_UI_GLYPH_ATLAS_SIZE * 4;+ const size_t row_bytes = (size_t)gw * 4;+ const uint8_t *src = (const uint8_t *)surface->pixels;+ uint8_t *dst = p->pixels + (size_t)y * (size_t)dst_pitch + (size_t)x * 4;+ for (int row = 0; row < gh; row++) {+ memcpy(dst + (size_t)row * (size_t)dst_pitch, src + (size_t)row * (size_t)surface->pitch, row_bytes); }- if (out_y) {- *out_y = (float)y;+ int bottom = y + gh + NANO_UI_GLYPH_ATLAS_PAD;+ if (bottom > p->used_h) {+ p->used_h = bottom; }- if (out_w) {- *out_w = (float)gw;+ mark_dirty(p, x, y, x + gw, y + gh);+ nano_ui_atlas_commit(&atlas->cur, page, x, y, gw, gh, uv);+ return true;+}++void nano_ui_text_atlas_drop_textures(NanoUiTextAtlas *atlas)+{+ if (!atlas) {+ return; }- if (out_h) {- *out_h = (float)gh;+ for (int i = 0; i < NANO_UI_TEXT_ATLAS_PAGES; i++) {+ NanoUiAtlasPage *p = &atlas->pages[i];+ if (p->tex) {+ SDL_DestroyTexture(p->tex);+ p->tex = NULL;+ }+ p->dirty = false; }- return true;+ atlas->cur.pages = 0; } void nano_ui_text_atlas_reset(NanoUiTextAtlas *atlas)@@ -194,12 +237,11 @@ if (!atlas) { return; }- atlas->x = NANO_UI_WHITE_PATCH_SIZE + NANO_UI_TEXT_ATLAS_PAD;- atlas->y = NANO_UI_TEXT_ATLAS_PAD;- atlas->row_h = NANO_UI_WHITE_PATCH_SIZE;- if (atlas->pixels && atlas->w > 0 && atlas->h > 0) {- memset(atlas->pixels, 0, (size_t)atlas->w * (size_t)atlas->h * 4);- init_white_pixel(atlas);- upload_all(atlas);+ /* Page 0 keeps its texture and clears its previously used rows now; the+ * others clear lazily when glyphs reach them again. */+ if (atlas->pages[0].tex) {+ open_page(atlas, 0);+ } else {+ atlas->cur.pages = 0; } }
cbits/nano_ui_text_atlas.h view
@@ -4,21 +4,33 @@ #include <SDL3/SDL.h> #include <stdbool.h> +#include "nano_ui_ttf_shared.h"++/* Pages the atlas opens before it is out of space: nano-ui-ttf's, which+ * nano-ui-sdl-web's atlas uses too. */+#define NANO_UI_TEXT_ATLAS_PAGES NANO_UI_GLYPH_ATLAS_PAGES+ typedef struct NanoUiTextAtlas NanoUiTextAtlas; NanoUiTextAtlas *nano_ui_text_atlas_create(SDL_Renderer *renderer); void nano_ui_text_atlas_destroy(NanoUiTextAtlas *atlas); -SDL_Texture *nano_ui_text_atlas_texture(NanoUiTextAtlas *atlas);+/* The texture of page `page`, or NULL for a page never opened. */+SDL_Texture *nano_ui_text_atlas_texture(NanoUiTextAtlas *atlas, int page); +/* Copy a glyph surface into the atlas, on a new page once the last one is+ * full, and write its u0, v0, u1 and v1: normalised to [0,1] within the page,+ * plus the page's number in u. False when no page has room or the copy+ * fails. */ bool nano_ui_text_atlas_insert_surface( NanoUiTextAtlas *atlas, SDL_Surface *surface,- float *out_x,- float *out_y,- float *out_w,- float *out_h);+ float uv[4]); void nano_ui_text_atlas_reset(NanoUiTextAtlas *atlas);++/* Destroy every page's texture and empty the atlas, after a render device+ * reset emptied the textures; pages are made again as glyphs reach them. */+void nano_ui_text_atlas_drop_textures(NanoUiTextAtlas *atlas); #endif
− cbits/nano_ui_ttf.c
@@ -1,475 +0,0 @@-#include <SDL3/SDL.h>-#include <SDL3_ttf/SDL_ttf.h>-#include <SDL3_ttf/SDL_textengine.h>-#include <stddef.h>-#include <stdbool.h>-#include <stdint.h>--bool nano_ui_ttf_init(void)-{- return TTF_Init();-}--void nano_ui_ttf_quit(void)-{- TTF_Quit();-}--/* Kerning is on by default; pin it so shaping survives defaults changing.- * Direction and script stay unset: shaping detects them per run, so- * right-to-left and complex scripts shape as themselves. Light grid-fitting- * snaps stems to whole pixels the way terminals (alacritty/kitty) rasterize,- * giving crisp edges instead of soft, grey antialiased outlines. NORMAL keeps- * fractional outlines. */-static TTF_Font *pin_font_rendering(TTF_Font *font)-{- if (font) {- TTF_SetFontKerning(font, true);- TTF_SetFontHinting(font, TTF_HINTING_LIGHT);- }- return font;-}--TTF_Font *nano_ui_ttf_open_font(const char *path, float ptsize)-{- return pin_font_rendering(TTF_OpenFont(path, ptsize));-}--/* A font at another size over the same source as @font@: the copy shares- * its file or memory stream, so any number of sizes read one source. */-TTF_Font *nano_ui_ttf_copy_font(TTF_Font *font, float ptsize)-{- TTF_Font *copy = font ? TTF_CopyFont(font) : NULL;- if (copy) {- TTF_SetFontSize(copy, ptsize);- }- return pin_font_rendering(copy);-}--void nano_ui_ttf_remove_fallback(TTF_Font *font, TTF_Font *fallback)-{- if (font && fallback) {- TTF_RemoveFallbackFont(font, fallback);- }-}--TTF_Font *nano_ui_ttf_open_font_memory(const void *data, size_t size, float ptsize)-{- /* The font reads this stream after the Haskell ByteString callback ends.- * Give the stream its own storage, released by its autoclose lifetime. */- SDL_IOStream *stream = SDL_IOFromDynamicMem();- if (!stream) {- return NULL;- }- if (SDL_WriteIO(stream, data, size) != size ||- SDL_SeekIO(stream, 0, SDL_IO_SEEK_SET) < 0) {- SDL_CloseIO(stream);- return NULL;- }- SDL_PropertiesID props = SDL_CreateProperties();- if (!props) {- SDL_CloseIO(stream);- return NULL;- }- SDL_SetPointerProperty(props, TTF_PROP_FONT_CREATE_IOSTREAM_POINTER, stream);- SDL_SetBooleanProperty(props, TTF_PROP_FONT_CREATE_IOSTREAM_AUTOCLOSE_BOOLEAN, true);- SDL_SetFloatProperty(props, TTF_PROP_FONT_CREATE_SIZE_FLOAT, ptsize);- TTF_Font *font = TTF_OpenFontWithProperties(props);- SDL_DestroyProperties(props);- return pin_font_rendering(font);-}--void nano_ui_ttf_close_font(TTF_Font *font)-{- if (font) {- TTF_CloseFont(font);- }-}--float nano_ui_ttf_line_skip(TTF_Font *font)-{- return (float)TTF_GetFontLineSkip(font);-}--float nano_ui_ttf_ascent(TTF_Font *font)-{- return (float)TTF_GetFontAscent(font);-}--float nano_ui_ttf_space_advance(TTF_Font *font)-{- int w = 0;- int h = 0;- if (TTF_GetStringSize(font, " ", 1, &w, &h) && w > 0) {- return (float)w;- }- int advance = 0;- if (TTF_GetGlyphMetrics(font, ' ', NULL, NULL, NULL, NULL, &advance) && advance > 0) {- return (float)advance;- }- return 0.f;-}--bool nano_ui_ttf_glyph_metrics(- TTF_Font *font,- Uint32 codepoint,- int *out_minx,- int *out_maxx,- int *out_miny,- int *out_maxy,- int *out_advance)-{- if (!font) {- return false;- }- int minx = 0, maxx = 0, miny = 0, maxy = 0, advance = 0;- if (!TTF_GetGlyphMetrics(font, codepoint, &minx, &maxx, &miny, &maxy, &advance)) {- return false;- }- if (out_minx) *out_minx = minx;- if (out_maxx) *out_maxx = maxx;- if (out_miny) *out_miny = miny;- if (out_maxy) *out_maxy = maxy;- if (out_advance) *out_advance = advance;- return true;-}--static Uint8 glyph_channel_max(Uint8 r, Uint8 g, Uint8 b)-{- Uint8 m = r;- if (g > m) {- m = g;- }- if (b > m) {- m = b;- }- return m;-}--static void force_white_rgb(SDL_Surface *surf)-{- if (!surf || !surf->pixels || surf->format != SDL_PIXELFORMAT_RGBA32) {- return;- }- Uint8 *base = (Uint8 *)surf->pixels;- int pitch = surf->pitch;- for (int y = 0; y < surf->h; y++) {- Uint8 *row = base + y * pitch;- for (int x = 0; x < surf->w; x++) {- Uint8 *px = row + x * 4;- px[0] = 255;- px[1] = 255;- px[2] = 255;- }- }-}--static void invert_glyph_alpha(SDL_Surface *surf)-{- if (!surf || !surf->pixels || surf->format != SDL_PIXELFORMAT_RGBA32) {- return;- }- Uint8 *base = (Uint8 *)surf->pixels;- int pitch = surf->pitch;- for (int y = 0; y < surf->h; y++) {- Uint8 *row = base + y * pitch;- for (int x = 0; x < surf->w; x++) {- row[x * 4 + 3] = (Uint8)(255 - row[x * 4 + 3]);- }- }-}--static SDL_Surface *glyph_image_to_rgba(SDL_Surface *raw, TTF_ImageType image_type)-{- if (!raw) {- return NULL;- }-- SDL_Surface *out = SDL_ConvertSurface(raw, SDL_PIXELFORMAT_RGBA32);- if (!out) {- return NULL;- }-- if (image_type == TTF_IMAGE_ALPHA || image_type == TTF_IMAGE_SDF) {- /* Spec: color channels are white, alpha is coverage. Transparent- * white (a=0, rgb=255) must stay transparent. Do not use luma. */- force_white_rgb(out);- return out;- }-- Uint8 *base = (Uint8 *)out->pixels;- int pitch = out->pitch;- Uint32 opaque_sum = 0;- Uint32 count = 0;- for (int y = 0; y < out->h; y++) {- Uint8 *row = base + y * pitch;- for (int x = 0; x < out->w; x++) {- Uint8 *px = row + x * 4;- Uint8 luma = glyph_channel_max(px[0], px[1], px[2]);- Uint8 a = px[3];- Uint8 cov = a > luma ? a : luma;- px[0] = 255;- px[1] = 255;- px[2] = 255;- px[3] = cov;- opaque_sum += cov;- count += 1;- }- }- if (count > 0 && opaque_sum > (255u * count) / 2u) {- invert_glyph_alpha(out);- }- return out;-}--bool nano_ui_ttf_render_glyph_surface(- TTF_Font *font,- Uint32 codepoint,- SDL_Surface **out_surface)-{- if (!font || !out_surface) {- return false;- }-- TTF_ImageType image_type = TTF_IMAGE_INVALID;- SDL_Surface *raw = TTF_GetGlyphImage(font, codepoint, &image_type);- if (!raw) {- SDL_Color white = {255, 255, 255, 255};- raw = TTF_RenderGlyph_Blended(font, codepoint, white);- image_type = TTF_IMAGE_ALPHA;- }- if (!raw) {- return false;- }-- SDL_Surface *converted = glyph_image_to_rgba(raw, image_type);- SDL_DestroySurface(raw);- if (!converted) {- return false;- }-- *out_surface = converted;- return true;-}--int nano_ui_ttf_get_kerning(TTF_Font *font, Uint32 prev_cp, Uint32 cp)-{- if (!font) {- return 0;- }- int k = 0;- TTF_GetGlyphKerning(font, prev_cp, cp, &k);- return k;-}--/* ------------------------------------------------------------------------ */-/* Shaping */-/* ------------------------------------------------------------------------ */--/* One shaped line, copied out of SDL_ttf's text layout: per glyph- * (text offset, glyph index, dst x y w h, src x y w h) and its font; per- * cluster (byte offset, byte length, x, width, flags). Coordinates are- * pixels from the top left of the line. */-typedef struct NanoUIShaped {- int w;- int h;- int num_glyphs;- int *glyphs;- TTF_Font **glyph_fonts;- int num_clusters;- int *clusters;- /* Bytes of the caller's text; anything after is the sentinel. */- int text_len;-} NanoUIShaped;--static bool SDLCALL nano_ui_capture_text(void *userdata, TTF_Text *text)-{- NanoUIShaped *out = (NanoUIShaped *)userdata;- TTF_TextData *d = text->internal;- int copies = 0;- for (int i = 0; i < d->num_ops; i++) {- if (d->ops[i].cmd == TTF_DRAW_COMMAND_COPY) {- copies++;- }- }- out->w = d->w;- out->h = d->h;- out->glyphs = (int *)SDL_calloc(copies > 0 ? copies : 1, 10 * sizeof(int));- out->glyph_fonts = (TTF_Font **)SDL_calloc(copies > 0 ? copies : 1, sizeof(TTF_Font *));- out->clusters = (int *)SDL_calloc(d->num_clusters > 0 ? d->num_clusters : 1, 5 * sizeof(int));- if (!out->glyphs || !out->glyph_fonts || !out->clusters) {- return false;- }- /* The sentinel ends a left-to-right line and starts a right-to-left- * one, which then shifts back by its advance. */- int shift = 0;- for (int i = 0; i < d->num_clusters; i++) {- TTF_SubString *c = &d->clusters[i];- if (c->offset >= out->text_len && c->length > 0) {- int advance = 0;- TTF_GetGlyphMetrics(d->font, '|', NULL, NULL, NULL, NULL, &advance);- out->w = d->w - advance;- if ((c->flags & TTF_SUBSTRING_DIRECTION_MASK) == TTF_DIRECTION_RTL) {- shift = advance;- }- }- }- int g = 0;- for (int i = 0; i < d->num_ops; i++) {- TTF_DrawOperation *op = &d->ops[i];- if (op->cmd != TTF_DRAW_COMMAND_COPY || op->copy.text_offset >= out->text_len) {- continue;- }- int *slot = out->glyphs + g * 10;- slot[0] = op->copy.text_offset;- slot[1] = (int)op->copy.glyph_index;- slot[2] = op->copy.dst.x - shift;- /* SDL_ttf places a fallback font's glyphs from that font's own- * ascent; align them to the line's font's baseline instead. */- slot[3] = op->copy.dst.y - (TTF_GetFontAscent(op->copy.glyph_font) - TTF_GetFontAscent(d->font));- slot[4] = op->copy.dst.w;- slot[5] = op->copy.dst.h;- slot[6] = op->copy.src.x;- slot[7] = op->copy.src.y;- slot[8] = op->copy.src.w;- slot[9] = op->copy.src.h;- out->glyph_fonts[g] = op->copy.glyph_font;- g++;- }- out->num_glyphs = g;- int k = 0;- for (int i = 0; i < d->num_clusters; i++) {- TTF_SubString *c = &d->clusters[i];- if (c->offset >= out->text_len) {- continue;- }- int *slot = out->clusters + k * 5;- slot[0] = c->offset;- slot[1] = c->length;- slot[2] = c->rect.x - shift;- slot[3] = c->rect.w;- slot[4] = (int)c->flags;- k++;- }- out->num_clusters = k;- d->engine_text = out;- return true;-}--static void SDLCALL nano_ui_release_text(void *userdata, TTF_Text *text)-{- (void)userdata;- (void)text;-}--/* Shape one line with the font and its fallbacks, in a direction (0 lets- * SDL_ttf pick, TTF_DIRECTION_LTR or TTF_DIRECTION_RTL). The caller frees- * the result with nano_ui_ttf_shaped_free.- *- * The line is shaped with a '|' after it, whose glyph and cluster are then- * dropped. SDL_ttf 3.2 cuts a fallback span that ends the text one character- * past its last cluster, losing a vowel sign merged into that cluster, and- * trims the width of trailing spaces. */-bool nano_ui_ttf_shape(TTF_Font *font, const char *text, size_t len, int direction, NanoUIShaped *out)-{- SDL_zerop(out);- if (!font || !text || len == 0) {- return font != NULL;- }- TTF_TextEngine engine;- SDL_INIT_INTERFACE(&engine);- engine.userdata = out;- engine.CreateText = nano_ui_capture_text;- engine.DestroyText = nano_ui_release_text;- out->text_len = (int)len;- bool sentinel = TTF_FontHasGlyph(font, '|');- char *padded = SDL_malloc(len + 1);- if (!padded) {- return false;- }- SDL_memcpy(padded, text, len);- padded[len] = '|';- TTF_Text *t = TTF_CreateText(&engine, font, padded, sentinel ? len + 1 : len);- SDL_free(padded);- if (!t) {- return false;- }- if (direction != 0) {- TTF_SetTextDirection(t, (TTF_Direction)direction);- }- /* Laying the text out hands it to the engine, which copies it. */- int w = 0, h = 0;- bool ok = TTF_GetTextSize(t, &w, &h);- if (ok && out->glyphs == NULL) {- ok = TTF_UpdateText(t) && out->glyphs != NULL;- }- TTF_DestroyText(t);- return ok;-}--void nano_ui_ttf_shaped_free(NanoUIShaped *shaped)-{- if (shaped) {- SDL_free(shaped->glyphs);- SDL_free(shaped->glyph_fonts);- SDL_free(shaped->clusters);- SDL_zerop(shaped);- }-}--size_t nano_ui_ttf_shaped_size(void)-{- return sizeof(NanoUIShaped);-}--/* Fields of a shaped line: 0 width, 1 height, 2 glyph count, 3 cluster count. */-int nano_ui_ttf_shaped_int(const NanoUIShaped *shaped, int field)-{- switch (field) {- case 0: return shaped->w;- case 1: return shaped->h;- case 2: return shaped->num_glyphs;- case 3: return shaped->num_clusters;- default: return 0;- }-}--/* 0 glyphs, 1 glyph fonts, 2 clusters. */-void *nano_ui_ttf_shaped_ptr(const NanoUIShaped *shaped, int field)-{- switch (field) {- case 0: return shaped->glyphs;- case 1: return (void *)shaped->glyph_fonts;- case 2: return shaped->clusters;- default: return NULL;- }-}--bool nano_ui_ttf_render_glyph_index_surface(TTF_Font *font, Uint32 glyph_index, SDL_Surface **out_surface)-{- if (!font || !out_surface) {- return false;- }- TTF_ImageType image_type = TTF_IMAGE_INVALID;- SDL_Surface *raw = TTF_GetGlyphImageForIndex(font, glyph_index, &image_type);- if (!raw) {- return false;- }- SDL_Surface *converted = glyph_image_to_rgba(raw, image_type);- SDL_DestroySurface(raw);- if (!converted) {- return false;- }- *out_surface = converted;- return true;-}--bool nano_ui_ttf_has_glyph(TTF_Font *font, Uint32 ch)-{- return font && TTF_FontHasGlyph(font, ch);-}--bool nano_ui_ttf_add_fallback(TTF_Font *font, TTF_Font *fallback)-{- return font && fallback && TTF_AddFallbackFont(font, fallback);-}
− data/inter.ttf
binary file changed (18884 → absent bytes)
examples/SdlAnim.hs view
@@ -11,7 +11,7 @@ runSdlApp defaultSdlOptions { sdlAppTheme = Just benchTheme- , sdlAppShouldQuit = \inp -> inputKeysElem KeyEscape (inputKeys inp)+ , sdlAppShouldQuit = pressedOnceIn KeyEscape } animUi @@ -27,11 +27,13 @@ , styleCornerRadius = 1 , styleHoverBg = colorRGBA 222 216 204 255 , styleActiveBg = colorRGBA 196 190 178 255+ , styleBorderSides = 15 } in defaultTheme { themeWindow = formica , themePanel = plate , themeFloatingWindow = plate+ , themePopup = plate , themeButton = Style { styleBg = colorRGBA 196 190 176 255@@ -41,6 +43,7 @@ , styleCornerRadius = 1 , styleHoverBg = colorRGBA 228 222 208 255 , styleActiveBg = colorRGBA 168 162 148 255+ , styleBorderSides = 15 } , themeInput = Style@@ -51,6 +54,7 @@ , styleCornerRadius = 1 , styleHoverBg = colorRGBA 186 180 166 255 , styleActiveBg = colorRGBA 158 152 138 255+ , styleBorderSides = 15 } , themeSeparator = colorRGBA 92 86 76 255 , themeAccent = ruby@@ -68,13 +72,20 @@ animUi :: NanoUI () animUi = do- (exposed, setExposed) <- useFlag False- (rewinding, setRewinding) <- useFlag False- (lampOn, setLamp) <- useFlag False- (bellowsOpen, setBellows) <- useFlag False- (tossed, setTossed) <- useFlag False- (stiffSpring, setStiffSpring) <- useFlag False- (throwRaw, setThrowRaw) <- useFloat 75+ exposure <- useVar False+ rewind <- useVar False+ lampSwitch <- useVar False+ bellows <- useVar False+ toss <- useVar False+ spring <- useVar False+ throwRaw <- useVar (75 :: Float)+ -- The animations below start from these, so they are read up front.+ exposed <- readVar exposure+ rewinding <- readVar rewind+ lampOn <- readVar lampSwitch+ bellowsOpen <- readVar bellows+ tossed <- readVar toss+ stiffSpring <- readVar spring tossT <- withKey ("toss" :: String) ( animateTo@@ -101,22 +112,21 @@ lampGlow = sin (lampT * pi) scrollWith (tight . grow) $ columnWith (padAll 28 . gap 18 . fillW) $ do- rowWith (tight . gap 10 . alignMid . fillW) $ do+ rowWith (tight . gap 10 . alignMiddle . fillW) $ do heading "16mm" flex withKey ("footage" :: String) (muted footage)- rowWith (tight . gap 8 . alignMid . fillW) $ do- whenM (button "Expose") (setExposed True >> setRewinding False)- whenM (button "Rewind") (setExposed False >> setRewinding True)- whenM (button (if lampOn then "Lamp off" else "Lamp on")) (setLamp (not lampOn))+ rowWith (tight . gap 8 . alignMiddle . fillW) $ do+ whenM (button "Expose") (writeVar exposure True >> writeVar rewind False)+ whenM (button "Rewind") (writeVar exposure False >> writeVar rewind True)+ whenM (button (if lampOn then "Lamp off" else "Lamp on")) (modifyVar lampSwitch not) flex- whenM (button (if tossed then "Catch" else "Toss")) (setTossed (not tossed))- whenM (button (if stiffSpring then "Stiff" else "Bouncy")) (setStiffSpring (not stiffSpring))+ whenM (button (if tossed then "Catch" else "Toss")) (modifyVar toss not)+ whenM (button (if stiffSpring then "Stiff" else "Bouncy")) (modifyVar spring not) throwSec <- do label "Throw"- newThrow <- slider 35 140 throwRaw- setThrowRaw newThrow- pure (newThrow / 100)+ slider 35 140 throwRaw+ (/ 100) <$> readVar throwRaw cycleThrow <- lockThrow exposed throwSec let cycleLen = pullCycleLen cycleThrow pullPhase <-@@ -124,30 +134,30 @@ then withKey ("pulldown" :: String) (animate (Tween EaseLinear cycleLen 0) 0 1) else pure 0 let time = pullPhase * cycleLen- tossRail tossT+ trackRow "Spring" tossT ruby laneTs <- transport exposed rewinding cycleThrow time wash lampGlow when- (rewinding && not exposed && abs clock < 0.001 && all settled laneTs)- (setRewinding False)+ (rewinding && not exposed && abs clock < 0.001 && all ((< 0.001) . abs) laneTs)+ (writeVar rewind False) panelWith (padXY 12 10 . gap 8 . fixedW (220 + 180 * bellowsT)) $ do- rowWith (tight . gap 10 . alignMid . fillW) $ do+ rowWith (tight . gap 10 . alignMiddle . fillW) $ do whenM (button (if bellowsOpen then "Collapse" else "Extend"))- (setBellows (not bellowsOpen))+ (modifyVar bellows not) flex let iris = 12 + 22 * bellowsT irisCol = lerpColor film (lerpColor paper ruby 0.18) bellowsT box (fixedWH iris iris) irisCol -settled :: Float -> Bool-settled x = abs x < 0.001-+-- | The throw the pull-down cycle runs at: while exposed, the one it had+-- when exposure began, so dragging the slider does not restart the cycle. lockThrow :: Bool -> Float -> NanoUI Float-lockThrow exposed throwSec =- withKey ("cycleThrow" :: String) $- if exposed- then pure throwSec- else animateTo (Tween EaseLinear 0.35 0) 0 >> pure throwSec+lockThrow exposed throwSec = do+ locked <- useVar (0 :: Float)+ held <- readVar locked+ if not exposed+ then throwSec <$ writeVar locked 0+ else if held > 0 then pure held else throwSec <$ writeVar locked throwSec transport :: Bool -> Bool -> Float -> Float -> Float -> Float -> NanoUI [Float] transport exposed rewinding throwSec time wash glow = do@@ -171,7 +181,7 @@ perfs :: NanoUI () perfs =- rowWith (tight . gap 0 . alignMid . fillW) $ do+ rowWith (tight . gap 0 . alignMiddle . fillW) $ do withKey ("perfL" :: String) (box (fixedWH 12 18) film) forM_ [0 .. 16 :: Int] $ \i -> withKey i $ do@@ -187,25 +197,17 @@ pullCycleLen throwSec = 3 * pullHoldSec + 2 * throwSec laneT :: Ease -> Float -> Float -> Float-laneT ease throwSec time =- let hold = pullHoldSec- out0 = hold- out1 = out0 + throwSec- topHold1 = out1 + hold- in0 = topHold1- in1 = in0 + throwSec- in if time < out0- then 0- else if time < out1- then applyEase ease ((time - out0) / throwSec)- else if time < in0- then 1- else if time < in1- then 1 - applyEase ease ((time - in0) / throwSec)- else 0--tossRail :: Float -> NanoUI ()-tossRail t = trackRow "Spring" t ruby+laneT ease throwSec time+ | time < out0 = 0+ | time < out1 = applyEase ease ((time - out0) / throwSec)+ | time < in0 = 1+ | time < in1 = 1 - applyEase ease ((time - in0) / throwSec)+ | otherwise = 0+ where+ out0 = pullHoldSec+ out1 = out0 + throwSec+ in0 = out1 + pullHoldSec+ in1 = in0 + throwSec lane :: Bool -> Bool -> Float -> Float -> T.Text -> Ease -> NanoUI Float lane exposed rewinding throwSec time name ease = do@@ -222,11 +224,11 @@ trackRow :: T.Text -> Float -> Color -> NanoUI () trackRow name t shuttle = withKey name $- rowWith (tight . gap 12 . alignMid . fillW) $ do+ rowWith (tight . gap 12 . alignMiddle . fillW) $ do labelWith (tight . fixedW 72) name columnWith (tight . gap 0 . fillW) $ do let travel = 394.0 :: Float- rowWith (tight . alignMid . fillW) $ do+ rowWith (tight . alignMiddle . fillW) $ do box (fixedWH 4 22) film spacer (Fixed (max 0 (t * travel))) Fit box (fixedWH 16 16) shuttle
+ examples/SdlIdle.hs view
@@ -0,0 +1,146 @@+-- | Idle probe: a window that should cost nothing while nobody touches it.+--+-- @cabal run nano-ui-sdl-idle -- <scene> [hidden]@ opens one of the scenes+-- below. @hidden@ keeps the window off screen, where no pointer can reach it:+-- the loop runs the same, so a check that must see no input can rely on it.+--+-- * @static@ labels, buttons and a list: nothing to animate or edit+-- * @focus@ the same, with the search field holding keyboard focus+-- * @wake@ the same, with a thread calling the loop's wake every second+-- * @spinner@ the same, with a spinner for the first three seconds only+-- * @clock@ the same, with a label of whole seconds kept by 'wakeAfter'+-- * @type@ @focus@, then a character typed into the field two seconds+-- in; prints how long the search took to report the change+-- * @startup@ the first ten frames each ask for the next, by marking the+-- context dirty or by waking the loop, and the tenth prints: a+-- frame asked for while the window opens must be drawn without+-- waiting for input+--+-- Watch the process in a profiler or Task Manager, or set @NANO_LOOP_TRACE@+-- to print how many passes and frames the session loop ran each second. An+-- idle scene should print nothing once it has settled. @type@ should print a+-- delay close to the search field's 300 ms debounce: the field sleeps through+-- it and is woken to commit, where it once polled at the display rate.+{-# LANGUAGE OverloadedRecordDot #-}++module Main (main) where++import Control.Concurrent (forkIO, threadDelay)+import Control.Monad (forM_, forever, void, when)+import Data.IORef (IORef, newIORef, readIORef, writeIORef)+import Foreign.C.String (newCString)+import Foreign.Marshal.Alloc (callocBytes)+import Foreign.Ptr (Ptr)+import Foreign.Storable (poke, sizeOf)+import GHC.Clock (getMonotonicTime)+import NanoUI+import NanoUI.Backend.Sdl (SdlOptions (..), defaultSdlOptions, runSdlApp)+import NanoUI.Internal.Context (Context (..))+import NanoUI.Testing (askContext, markDirty)+import SDL3.Sys.Bindgen.Events (SDL_Event, SDL_TextInputEvent (..))+import SDL3.Sys.Bindgen.Events qualified as Events+import SDL3.Sys.Bindgen.Runtime.PtrConst qualified as PtrConst+import SDL3.Sys.Bindgen.Stdinc (Uint32 (..), Uint64 (..))+import SDL3.Sys.Bindgen.Video (SDL_WindowID (..))+import SDL3.Sys.Events (pushEvent)+import System.Environment (getArgs)+import System.IO (hFlush, stdout)+import Text.Printf (printf)+import qualified Data.Text as T++main :: IO ()+main = do+ args <- getArgs+ let scene = case args of+ (s : _) -> s+ [] -> "static"+ frames <- newIORef (0 :: Int)+ started <- newIORef False+ typedAt <- newIORef (0 :: Double)+ runSdlApp+ defaultSdlOptions+ { sdlWindowSettings =+ defaultWindowSettings+ { wsTitle = "nano-ui idle: " <> T.pack scene+ , wsSize = Size 900 600+ , wsMode = if "hidden" `elem` drop 1 args then Hidden else Windowed+ }+ , sdlAppShouldQuit = pressedOnceIn KeyEscape+ }+ (idleUi scene frames started typedAt)++idleUi :: String -> IORef Int -> IORef Bool -> IORef Double -> NanoUI ()+idleUi scene frames started typedAt = do+ n <- liftIO (readIORef frames)+ liftIO (writeIORef frames (n + 1))+ ctx <- askContext+ -- Background work starts once, from the first frame.+ first <- liftIO (not <$> readIORef started)+ when first $ liftIO $ do+ writeIORef started True+ when (scene == "wake") $ do+ mWake <- readIORef (ctxWakeLoop ctx)+ forM_ mWake $ \wake -> void $ forkIO $ forever $ threadDelay 1000000 >> wake+ when (scene == "type") $ void $ forkIO $ do+ threadDelay 2000000+ getMonotonicTime >>= writeIORef typedAt+ pushTextInput "a"+ -- Ask for the next frame both ways a view can: by marking the context+ -- dirty, and by waking the loop as a background thread would.+ when (scene == "startup" && n < 10) $ liftIO $ do+ if even n+ then markDirty ctx+ else readIORef (ctxWakeLoop ctx) >>= sequence_+ when (n == 9) $ putStrLn "startup: reached frame 10 without input" >> hFlush stdout+ columnWith (gap 8 . padAll 16 . fillW . fillH) $ do+ heading "Idle probe"+ label "This window should use no CPU or GPU while it is left alone."+ query <- useVar ("" :: T.Text)+ resp <- searchInput' "Search" query+ -- Hold keyboard focus without a click, as an app's search box would.+ when (scene `elem` ["focus", "type"] && n < 4) $+ requestFocus (respId resp)+ when (scene == "type" && respChanged resp) $ do+ committed <- readVar query+ liftIO $ do+ now <- getMonotonicTime+ sent <- readIORef typedAt+ printf "search %s committed %.0f ms after the key\n" (show committed) ((now - sent) * 1000)+ hFlush stdout+ t <- uiTime+ -- The first frame's time.+ startTime <- useVar (0 :: Double)+ modifyVar startTime (\t0 -> if t0 == 0 then t else t0)+ t0 <- readVar startTime+ -- A loading indicator that goes away, as an app's would after startup.+ when (scene == "spinner" && t0 > 0 && t - t0 < 3) spinner+ when (scene == "clock") $ do+ let up = t - t0+ whole = floor up :: Int+ label ("Up " <> T.pack (show whole) <> " s")+ wakeAfter (fromIntegral (whole + 1) - up)+ checkbox "A checkbox" =<< useVar True+ row $ do+ void (button "One")+ void (button "Two")+ void (button "Three")+ matching <- readVar query+ forM_ [1 :: Int .. 12] $ \i ->+ label ("Row " <> T.pack (show i) <> (if T.null matching then "" else " matching " <> matching))++-- | Queue an SDL_EVENT_TEXT_INPUT, as the keyboard would. The event and its+-- string are leaked: SDL reads the text pointer when the loop takes the+-- event, and a probe types once.+pushTextInput :: String -> IO ()+pushTextInput str = do+ typed <- newCString str+ ev <- callocBytes (sizeOf (undefined :: SDL_Event)) :: IO (Ptr SDL_Event)+ poke ev.text+ SDL_TextInputEvent+ { type' = Events.SDL_EVENT_TEXT_INPUT+ , reserved = Uint32 0+ , timestamp = Uint64 0 -- SDL stamps an event pushed with none+ , windowID = SDL_WindowID (Uint32 0)+ , text = PtrConst.unsafeFromPtr typed+ }+ void (pushEvent ev)
lib/NanoUI/Backend/Sdl.hs view
@@ -1,104 +1,151 @@--- | SDL3 backend: event loop, rendering, and application runners.+-- |+-- Module : NanoUI.Backend.Sdl+-- Description : SDL3 desktop backend for nano-ui+-- Copyright : (c) 2026 Zachary Churchill+-- License : MIT+-- Maintainer : zacharyachurchill@gmail.com+--+-- Desktop SDL3 backend with HarfBuzz/SDL3_ttf TrueType font rendering,+-- system font discovery, native file dialogs, client-side window chrome,+-- and GPU fragment shader support.+--+-- Call 'runSdlApp' with 'defaultSdlOptions' and a 'NanoUI' view to open a+-- window, or 'runSdlAppReduce' for an Elm-style "NanoUI.Emit" reducer loop. module NanoUI.Backend.Sdl- ( RgbaImage (..)- , SdlDebugSnapshot (..)- , SdlEnv (..)+ ( -- * Running+ runSdlApp+ , runSdlAppReduce , SdlOptions (..)- , askSdlDebug+ , defaultSdlOptions+ , RenderDriver (..)+ , RgbaImage (..)++ -- * Fonts and scale+ , NanoUIFont (..)+ , listFontFamilies , setSdlUiFont , setSdlUiScale- , defaultSdlOptions++ -- * File dialogs , FileFilter (..) , FileDialogOptions (..)- , FileDialogId (..)+ , FileDialogId , FileDialogResult (..) , defaultFileDialogOptions+ , askOpenFileDialog+ , askSaveFileDialog+ , askOpenFolderDialog+ , pollFileDialogUi+ , peekFileDialogUi+ , useFileDialog , openFileDialog , saveFileDialog , openFolderDialog , pollFileDialog , cancelFileDialog- , askOpenFileDialog- , askSaveFileDialog- , askOpenFolderDialog- , pollFileDialogUi- , NanoUIFont (..)- , listFontFamilies- , runSdlApp- , runSdlAppReduce- , sdlDrawFrame- , syncDisplay++ -- * External URLs+ , openUrl++ -- * The window++ -- | 'WindowSettings' and the view-side window functions come from the+ -- core ("NanoUI"): 'NanoUI.askWindow', 'NanoUI.setWindowTitle',+ -- 'NanoUI.moveWindow', 'NanoUI.quit' and others. The rest of this+ -- section is specific to SDL.+ , WindowSettings (..)+ , defaultWindowSettings+ , WindowPosition (..)+ , WindowMode (..)+ , windowZoom+ , windowResizable+ , WindowDecorations (..)+ , setWindowDecorations+ , setWindowDecorationsUi+ , setWindowShadow+ , setWindowShadowUi++ -- * Window chrome+ , WindowChrome (..)+ , defaultWindowChrome+ , defaultResizeBorder+ , setWindowChrome+ , clearWindowChrome+ , clearWindowChromeUi+ , CaptionOptions (..)+ , defaultCaptionOptions+ , windowCaption+ , windowCaptionWith+ , setWindowChromeUi++ -- * Debugging+ , SdlDebugSnapshot (..)+ , CoreDebugSnapshot (..)+ , askSdlDebug+ , sdlDebugSnapshot+ , formatFpsRows+ , formatDrawRows+ , formatExplainRows++ -- * Screenshots+ , saveScreenshot+ , captureScreenshot++ -- * Explicit sessions++ -- | View-side operations look up the active session from the context.+ -- For the IO-level operations above ('openFileDialog', 'pollFileDialog',+ -- 'setWindowChrome', 'saveScreenshot' and others), retrieve it with+ -- 'askSdlEnv'. They call SDL, so call them on the session's display+ -- thread; only 'cancelFileDialog' is safe from another thread.+ , SdlEnv+ , askSdlEnv , withSdl , withSdlBench- , saveScreenshot+ , syncDisplay+ , sdlDrawFrame+ , resetRenderTextures ) where -import Control.Monad (unless)-import Data.Foldable (foldlM)-import Data.IORef (newIORef)-import Data.Primitive.SmallArray (SmallArray)-import Data.Typeable (Typeable)-import NanoUI (NanoUI)-import NanoUI.Sdl.Runner (askSdlDebug, drawReduceEff, sdlDrawFrame, setSdlUiFont, setSdlUiScale)-import NanoUI.Sdl.Session (runSdlSession)-import NanoUI.Sdl.Debug (SdlDebugSnapshot (..))-import NanoUI.Sdl.Window (RgbaImage (..), SdlEnv (..), SdlOptions (..), defaultSdlOptions, saveScreenshot, syncDisplay, withSdl, withSdlBench)-import NanoUI.Sdl.Dialog- ( FileDialogId (..)- , FileDialogOptions (..)- , FileDialogResult (..)- , FileFilter (..)- , askOpenFileDialog- , askOpenFolderDialog- , askSaveFileDialog- , defaultFileDialogOptions- , openFileDialog- , openFolderDialog- , pollFileDialog- , cancelFileDialog- , pollFileDialogUi- , saveFileDialog- )-import NanoUI.Sdl.NanoUIFont (NanoUIFont (..))-import NanoUI.Sdl.Font.Search (listFontFamilies)-import NanoUI.Testing (Context, newPixelContext, registerImage, runEff, withTheme)+import NanoUI (NanoUI, WindowMode (..), WindowPosition (..), WindowSettings (..), defaultWindowSettings)+import NanoUI.Internal.Debug (CoreDebugSnapshot (..), formatDrawRows, formatExplainRows, formatFpsRows)+import NanoUI.Sdl.Internal.Runner (askSdlDebug, drawFrameWith, resetRenderTextures, sdlDebugSnapshot, sdlDrawFrame, sdlDrawFrameSettling, setSdlUiFont, setSdlUiScale)+import NanoUI.Sdl.Internal.Session (runSdlSession)+import NanoUI.Sdl.Internal.Debug (SdlDebugSnapshot (..))+import NanoUI.Sdl.Internal.Window (RenderDriver (..), RgbaImage (..), SdlEnv, SdlOptions (..), askSdlEnv, captureScreenshot, defaultSdlOptions, saveScreenshot, syncDisplay, windowZoom, withSdl, withSdlBench)+import NanoUI.Sdl.Internal.Dialog+import NanoUI.Sdl.Internal.Chrome+import NanoUI.Sdl.Internal.NanoUIFont (NanoUIFont (..))+import NanoUI.Sdl.Internal.Font.Search (listFontFamilies)+import NanoUI.Sdl.Internal.Url (openUrl)+import NanoUI.Emit (NanoUIE, newReducer, reduceFrame) +-- | Open an SDL window and run a view until close or the quit predicate fires.+-- Owns and releases the native resources. Call from the application's display+-- thread; the view is rebuilt for each requested frame. Allocate owned state+-- once in IO first and pass it to the view:+--+-- > main = do+-- > state <- newEditor+-- > runSdlApp defaultSdlOptions (editorUi state)+--+-- SDL-specific view operations (file dialogs, fonts, window chrome, debug+-- data) act on this session without taking it as an explicit argument. runSdlApp :: SdlOptions -> NanoUI () -> IO ()-runSdlApp options ui = do- ctx <- sdlContext options- runSdlSession options ctx (const (pure ())) (sdlAppShouldQuit options) $ \c ->- sdlDrawFrame c ui+runSdlApp options ui = runSdlSession options (`sdlDrawFrameSettling` ui) +-- | Run a model-driven view, folding emitted messages through the update+-- function in emission order. Use the adapters in "NanoUI.Emit" to emit+-- changes from ordinary widgets. runSdlAppReduce ::- (Typeable msg, Eq model) =>- SdlOptions ->- (msg -> model -> model) ->- model ->- (model -> NanoUI ()) ->- IO ()+ Eq model =>+ SdlOptions+ -> (msg -> model -> model)+ -> model+ -> (model -> NanoUIE msg ())+ -> IO () runSdlAppReduce options update model view = do- ctx <- sdlContext options- modelRef <- newIORef model- runSdlSession options ctx (const (pure ())) (sdlAppShouldQuit options) $- drawReduceEff runEff update modelRef view--sdlContext :: SdlOptions -> IO Context-sdlContext options = do- ctx0 <- newPixelContext- themed <- maybe (pure ctx0) (withTheme ctx0) (sdlAppTheme options)- ok <- registerImages themed (sdlAppImages options)- unless ok $ fail "registerImage failed"- pure themed--registerImages :: Context -> SmallArray RgbaImage -> IO Bool-registerImages ctx images =- foldlM (\ok img -> if ok then registerRgbaImage ctx img else pure False) True images--registerRgbaImage :: Context -> RgbaImage -> IO Bool-registerRgbaImage ctx img =- registerImage- ctx- (rgbaImageId img)- (rgbaImageWidth img)- (rgbaImageHeight img)- (rgbaImagePixels img)+ reducer <- newReducer update model+ runSdlSession options $ \ctx env inp forceFull settleResize ->+ drawFrameWith ctx env inp forceFull settleResize $ \i ->+ (\(_, drawData, dirty) -> (drawData, dirty)) <$> reduceFrame reducer ctx i view
− lib/NanoUI/Sdl/Clipboard.hs
@@ -1,25 +0,0 @@-module NanoUI.Sdl.Clipboard- ( withSdlClipboard- ) where--import qualified Data.Text as T-import Data.Text.Foreign (peekCString, withCString)-import Foreign.Ptr (castPtr, nullPtr)-import NanoUI.Testing (Context, withClipboard)-import SDL3.Sys.Bindgen.Runtime.PtrConst qualified as PtrConst-import SDL3.Sys.Clipboard (getClipboardText, setClipboardText)-import SDL3.Sys.Stdinc (free)---- | Route the context's clipboard through SDL (UTF-8 text both ways).-withSdlClipboard :: Context -> Context-withSdlClipboard ctx = withClipboard ctx readClipboard writeClipboard- where- writeClipboard txt = withCString txt (setClipboardText . PtrConst.unsafeFromPtr)- readClipboard = do- ptr <- getClipboardText- if ptr == nullPtr- then pure Nothing- else do- txt <- peekCString ptr- free (castPtr ptr)- pure (if T.null txt then Nothing else Just txt)
− lib/NanoUI/Sdl/Cursor.hs
@@ -1,114 +0,0 @@-module NanoUI.Sdl.Cursor- ( SdlCursors (..)- , initCursors- , destroyCursors- , syncPointerCursor- ) where--import Control.Monad (void, when)-import Data.IORef (IORef, newIORef, readIORef, writeIORef)-import Foreign.Ptr (Ptr, nullPtr)-import NanoUI (Input (..))-import NanoUI.Testing (Context, UiCursorKind (..), uiCursorKind)-import System.Environment (lookupEnv)-import System.IO (hPutStrLn, stderr)-import qualified SDL3.Sys.Bindgen.Mouse as Mouse-import SDL3.Sys.Mouse- ( createSystemCursorSafe- , destroyCursorSafe- , getDefaultCursorSafe- , setCursorSafe- )--data SdlCursors = SdlCursors- { scDefault :: Ptr Mouse.SDL_Cursor- , scPointer :: Ptr Mouse.SDL_Cursor- , scText :: Ptr Mouse.SDL_Cursor- , scMoveFallback :: Ptr Mouse.SDL_Cursor- , scGrab :: Ptr Mouse.SDL_Cursor- , scGrabbing :: Ptr Mouse.SDL_Cursor- , scNsResize :: Ptr Mouse.SDL_Cursor- , scEwResize :: Ptr Mouse.SDL_Cursor- , scNwseResize :: Ptr Mouse.SDL_Cursor- , scNeswResize :: Ptr Mouse.SDL_Cursor- , scCurrent :: IORef UiCursorKind- , scTrace :: Bool- }--initCursors :: IO SdlCursors-initCursors = do- def <- getDefaultCursorSafe- ptr <- createSystemCursorSafe Mouse.SDL_SYSTEM_CURSOR_POINTER- text <- createSystemCursorSafe Mouse.SDL_SYSTEM_CURSOR_TEXT- moveFallback <- createSystemCursorSafe Mouse.SDL_SYSTEM_CURSOR_MOVE- ns <- createSystemCursorSafe Mouse.SDL_SYSTEM_CURSOR_NS_RESIZE- ew <- createSystemCursorSafe Mouse.SDL_SYSTEM_CURSOR_EW_RESIZE- nwse <- createSystemCursorSafe Mouse.SDL_SYSTEM_CURSOR_NWSE_RESIZE- nesw <- createSystemCursorSafe Mouse.SDL_SYSTEM_CURSOR_NESW_RESIZE- -- SDL_SYSTEM_CURSOR_GRAB (27) and GRABBING (28) have no bindgen patterns.- -- Where SDL or the platform lacks them creation returns NULL, and the move- -- cursor stands in.- grab <- createSystemCursorSafe (Mouse.SDL_SystemCursor 27)- grabbing <- createSystemCursorSafe (Mouse.SDL_SystemCursor 28)- current <- newIORef UiCursorDefault- -- Debug aid, read once here so cursor changes stay allocation-free:- -- NANO_CURSOR_TRACE=1 logs every cursor change to stderr.- trace <- (== Just "1") <$> lookupEnv "NANO_CURSOR_TRACE"- -- NULL cursors are tolerated: SDL_SetCursor(NULL) selects the platform- -- default arrow, which keeps us running on headless/dummy video drivers- -- where system cursor shapes are unavailable.- pure- SdlCursors- { scDefault = def- , scPointer = ptr- , scText = text- , scMoveFallback = moveFallback- , scGrab = if grab == nullPtr then moveFallback else grab- , scGrabbing = if grabbing == nullPtr then moveFallback else grabbing- , scNsResize = ns- , scEwResize = ew- , scNwseResize = nwse- , scNeswResize = nesw- , scCurrent = current- , scTrace = trace- }--destroyOwnedCursor :: Ptr Mouse.SDL_Cursor -> Ptr Mouse.SDL_Cursor -> IO ()-destroyOwnedCursor cur shared =- when (cur /= nullPtr && cur /= shared) $- destroyCursorSafe cur--destroyCursors :: SdlCursors -> IO ()-destroyCursors cursors = do- let fb = scMoveFallback cursors- destroyOwnedCursor (scPointer cursors) nullPtr- destroyOwnedCursor (scText cursors) nullPtr- destroyOwnedCursor (scNsResize cursors) nullPtr- destroyOwnedCursor (scEwResize cursors) nullPtr- destroyOwnedCursor (scNwseResize cursors) nullPtr- destroyOwnedCursor (scNeswResize cursors) nullPtr- destroyOwnedCursor (scGrab cursors) fb- destroyOwnedCursor (scGrabbing cursors) fb- destroyCursorSafe fb--cursorPtr :: SdlCursors -> UiCursorKind -> Ptr Mouse.SDL_Cursor-cursorPtr cursors = \case- UiCursorDefault -> scDefault cursors- UiCursorPointer -> scPointer cursors- UiCursorText -> scText cursors- UiCursorGrab -> scGrab cursors- UiCursorGrabbing -> scGrabbing cursors- UiCursorNsResize -> scNsResize cursors- UiCursorEwResize -> scEwResize cursors- UiCursorNwseResize -> scNwseResize cursors- UiCursorNeswResize -> scNeswResize cursors--syncPointerCursor :: SdlCursors -> Context -> Input -> IO ()-syncPointerCursor cursors ctx inp = do- want <- uiCursorKind ctx inp- cur <- readIORef (scCurrent cursors)- when (want /= cur) $ do- when (scTrace cursors) $- hPutStrLn stderr ("cursor: " ++ show want ++ " at " ++ show (inputMousePos inp))- void $ setCursorSafe (cursorPtr cursors want)- writeIORef (scCurrent cursors) want
− lib/NanoUI/Sdl/Debug.hs
@@ -1,77 +0,0 @@-module NanoUI.Sdl.Debug- ( SdlDebugSnapshot (..)- , SdlDebugSampler (..)- , newSdlDebugSampler- , emptySdlDebug- , traceFrame- ) where--import Data.IORef (IORef, newIORef)-import Data.Maybe (isJust)-import Data.Text (Text, unpack)-import NanoUI.Debug- ( CoreDebugSnapshot (..)- , DebugSamplerRef- , emptyCoreDebugSnapshot- , newDebugSampler- )-import System.Environment (lookupEnv)-import Text.Printf (printf)--data SdlDebugSnapshot = SdlDebugSnapshot- { dbgCore :: !CoreDebugSnapshot- , dbgScale :: !Float- , dbgFontPath :: !FilePath- , dbgRenderer :: !Text- , dbgVsync :: !Bool- , dbgRefreshHz :: !Int- }- deriving (Eq, Show)---- | The core sampler, the last published snapshot, and whether--- NANO_FRAME_TRACE (read once at creation) is set.-data SdlDebugSampler = SdlDebugSampler- { sdsSampler :: !DebugSamplerRef- , sdsSnapshot :: !(IORef SdlDebugSnapshot)- , sdsTrace :: !Bool- }--newSdlDebugSampler :: IO SdlDebugSampler-newSdlDebugSampler =- SdlDebugSampler- <$> newDebugSampler- <*> newIORef emptySdlDebug- <*> (isJust <$> lookupEnv "NANO_FRAME_TRACE")--emptySdlDebug :: SdlDebugSnapshot-emptySdlDebug =- SdlDebugSnapshot- { dbgCore = emptyCoreDebugSnapshot- , dbgScale = 1- , dbgFontPath = ""- , dbgRenderer = ""- , dbgVsync = True- , dbgRefreshHz = 0- }---- | Per-refresh timing trace (NANO_FRAME_TRACE). Prints the snapshot's phase--- EMAs so live-loop costs can be compared across builds.-traceFrame :: SdlDebugSnapshot -> IO ()-traceFrame s =- printf- "TRACE refreshHz=%3d rend=%s vsync=%d presentFps=%6.0f loopFps=%6.0f frameMs=%6.3f uiMs=%6.3f renderMs=%6.3f presentMs=%6.3f verts=%5d cmds=%2d presents=%d skips=%d\n"- (dbgRefreshHz s)- (unpack (dbgRenderer s))- (if dbgVsync s then 1 else 0 :: Int)- (dbgPresentFps c)- (dbgLoopFps c)- (dbgFrameMs c)- (dbgUiMs c)- (dbgRenderMs c)- (dbgPresentMs c)- (dbgVerts c)- (dbgCmds c)- (dbgPresents c)- (dbgSkips c)- where- c = dbgCore s
− lib/NanoUI/Sdl/Dialog.hs
@@ -1,285 +0,0 @@--- | SDL3 native file dialogs.------ These wrap SDL3's asynchronous dialog API ('SDL_ShowOpenFileDialog',--- 'SDL_ShowSaveFileDialog', and 'SDL_ShowOpenFolderDialog') into a--- non-blocking, poll-based interface. Launching a dialog returns a--- 'FileDialogId' immediately and the app keeps running its normal event loop;--- poll the handle on later frames to observe completion.------ Threading: SDL3 may invoke the dialog callback on a background thread, so--- the callback here does little: it decodes the result, frees the--- FFI buffers it owned, wakes the event loop, and records the outcome. All--- UI-affecting work ('markDirty', releasing the callback 'FunPtr') is deferred--- to the thread that polls the result.-module NanoUI.Sdl.Dialog- ( FileFilter (..)- , FileDialogOptions (..)- , defaultFileDialogOptions- , FileDialogId (..)- , FileDialogResult (..)- , openFileDialog- , saveFileDialog- , openFolderDialog- , pollFileDialog- , cancelFileDialog- , clearDialogState- , askOpenFileDialog- , askSaveFileDialog- , askOpenFolderDialog- , pollFileDialogUi- ) where--import Control.Monad (forM, forM_, unless, void)-import Data.Int (Int32)-import Data.IntMap.Strict qualified as IM-import Data.IORef (atomicModifyIORef', readIORef)-import Data.Text (Text)-import qualified Data.Text as T-import Effectful (Eff, type (:>))-import Foreign.C.String (CString, newCString, peekCString)-import Foreign.C.Types (CChar)-import Foreign.Marshal.Alloc (free)-import Foreign.Marshal.Array (mallocArray, peekArray0)-import Foreign.Ptr (FunPtr, Ptr, castFunPtr, castPtr, nullPtr)-import Foreign.Storable (pokeElemOff)-import NanoUI.Sdl.Dialog.Types- ( DialogCallback- , DialogCallbackFunPtr- , DialogState (..)- , FileDialogId (..)- , FileDialogResult (..)- , PendingDialog (..)- , clearDialogState- , drainRetired- , retireDialogCallback- )-import NanoUI.Sdl.Display (pushRefreshEvent)-import NanoUI.Sdl.Window (SdlEnv (..))-import NanoUI.Testing (Ui, askHost, markDirty, uiIO)-import SDL3.Sys.Bindgen.Dialog- ( SDL_DialogFileCallback (..)- , SDL_DialogFileCallback_Aux- , SDL_DialogFileFilter (..)- )-import SDL3.Sys.Bindgen.Runtime.PtrConst qualified as PtrConst-import SDL3.Sys.Dialog- ( showOpenFileDialogSafe- , showOpenFolderDialogSafe- , showSaveFileDialogSafe- )-import SDL3.Sys.Video (raiseWindowSafe, restoreWindowSafe)-import System.IO (hPutStrLn, stderr)---- | A file type filter shown in open/save dialogs.-data FileFilter = FileFilter- { filterName :: !Text- -- ^ Human-readable label, e.g. @"Haskell source"@.- , filterPattern :: !Text- -- ^ Semicolon-separated extension list, e.g. @"hs;lhs"@, or @"*"@.- }- deriving (Eq, Show)---- | Common options for native file dialogs.-data FileDialogOptions = FileDialogOptions- { dialogFilters :: ![FileFilter]- -- ^ File filters (ignored by folder dialogs).- , dialogDefaultLocation :: !(Maybe FilePath)- -- ^ Starting folder or file.- , dialogAllowMany :: !Bool- -- ^ Allow selecting more than one entry (ignored by save dialogs).- }- deriving (Eq, Show)---- | Sensible defaults: no filters, no default location, single selection.-defaultFileDialogOptions :: FileDialogOptions-defaultFileDialogOptions = FileDialogOptions [] Nothing False---- | Launch an open-file dialog. Returns a handle to poll for completion.-openFileDialog :: SdlEnv -> FileDialogOptions -> IO FileDialogId-openFileDialog env opts =- launchDialog env OpenDialog (dialogFilters opts) (dialogDefaultLocation opts) (dialogAllowMany opts)---- | Launch a save-file dialog. Returns a handle to poll for completion.-saveFileDialog :: SdlEnv -> FileDialogOptions -> IO FileDialogId-saveFileDialog env opts =- launchDialog env SaveDialog (dialogFilters opts) (dialogDefaultLocation opts) (dialogAllowMany opts)---- | Launch a folder-selection dialog. Returns a handle to poll for completion.-openFolderDialog :: SdlEnv -> FileDialogOptions -> IO FileDialogId-openFolderDialog env opts =- launchDialog env FolderDialog [] (dialogDefaultLocation opts) (dialogAllowMany opts)---- | Poll a previously launched dialog without blocking.------ Each result is delivered exactly once: after the dialog completes, the--- first poll that observes the finished state returns it and forgets the--- handle, so later polls return 'FileDialogUnknown'.-pollFileDialog :: SdlEnv -> FileDialogId -> IO FileDialogResult-pollFileDialog env (FileDialogId did) = do- let st = sdlDialogState env- -- Callbacks retired by an earlier poll are now certainly returned.- drainRetired st- (mcb, result) <-- atomicModifyIORef' (dsPending st) $ \pending ->- case IM.lookup did pending of- Nothing -> (pending, (Nothing, FileDialogUnknown))- Just (PendingDialog FileDialogPending _) -> (pending, (Nothing, FileDialogPending))- Just (PendingDialog status cb) -> (IM.delete did pending, (Just cb, status))- case result of- FileDialogPending -> pure ()- FileDialogUnknown -> pure ()- _ -> do- -- Retire the callback for a later poll to free; the callback thread may- -- still be unwinding right now, and freeing a running wrapper is unsafe.- forM_ mcb (retireDialogCallback st)- -- The native dialog stole window focus; reclaim it so the app keeps- -- receiving hover/motion/wheel events without an extra click.- -- Restoration is a best-effort no-op when the window was never- -- minimized (its result is platform-dependent, so it is not a reliable- -- failure signal); only a failed raise means the window may still lack- -- focus and worth an audible warning.- void (restoreWindowSafe (sdlWindow env))- raised <- raiseWindowSafe (sdlWindow env)- unless raised $- hPutStrLn stderr "nano-ui: dialog completed but window raise failed; input may need a click"- -- The dialog finished; request a redraw so the caller can reflect the- -- result. Safe here: this runs on the polling (UI) thread.- ctx <- readIORef (sdlCachedCtx env)- markDirty ctx- pure result---- | Stop tracking a dialog handle without waiting for the native dialog to--- finish. The handle returns 'FileDialogUnknown' if polled afterwards.--- The native dialog keeps running until the user dismisses it; its result is--- discarded. If a dialog is abandoned while still open, its small FFI--- callback is left to be reclaimed at teardown or process exit.-cancelFileDialog :: SdlEnv -> FileDialogId -> IO ()-cancelFileDialog env (FileDialogId did) =- atomicModifyIORef' (dsPending (sdlDialogState env)) $ \m -> (IM.delete did m, ())---- | Open-file dialog, usable from within 'NanoUI' widget code. Returns--- 'Nothing' when there is no SDL host to launch a dialog.-askOpenFileDialog :: Ui :> es => FileDialogOptions -> Eff es (Maybe FileDialogId)-askOpenFileDialog opts = askHost >>= traverse (uiIO . (`openFileDialog` opts))---- | Save-file dialog, usable from within 'NanoUI' widget code. Returns--- 'Nothing' when there is no SDL host to launch a dialog.-askSaveFileDialog :: Ui :> es => FileDialogOptions -> Eff es (Maybe FileDialogId)-askSaveFileDialog opts = askHost >>= traverse (uiIO . (`saveFileDialog` opts))---- | Folder dialog, usable from within 'NanoUI' widget code. Returns--- 'Nothing' when there is no SDL host to launch a dialog.-askOpenFolderDialog :: Ui :> es => FileDialogOptions -> Eff es (Maybe FileDialogId)-askOpenFolderDialog opts = askHost >>= traverse (uiIO . (`openFolderDialog` opts))---- | Poll a dialog from within 'NanoUI' widget code.-pollFileDialogUi :: Ui :> es => FileDialogId -> Eff es FileDialogResult-pollFileDialogUi did = do- menv <- askHost- case menv of- Nothing -> pure FileDialogUnknown- Just env -> uiIO (pollFileDialog env did)--data DialogKind = OpenDialog | SaveDialog | FolderDialog--launchDialog ::- SdlEnv ->- DialogKind ->- [FileFilter] ->- Maybe FilePath ->- Bool ->- IO FileDialogId-launchDialog env kind filters mDefault allowMany = do- (filtersPtr, filterStrs) <- allocFilters filters- (defaultPtr, defaultStr) <- allocDefault mDefault- let st = sdlDialogState env- -- Free callbacks from dialogs that finished earlier.- drainRetired st- did <- nextDialogId st- rawFp <- mkDialogCallback (onResult did st filterStrs filtersPtr defaultStr)- -- Register the handle before showing: the callback may fire before this- -- function returns, and it must find its entry.- atomicModifyIORef' (dsPending st) $ \m ->- (IM.insert did (PendingDialog FileDialogPending rawFp) m, ())- let cb = SDL_DialogFileCallback (castFunPtr rawFp :: FunPtr SDL_DialogFileCallback_Aux)- filtersConst = PtrConst.unsafeFromPtr filtersPtr- nfilters = fromIntegral (length filters)- case kind of- OpenDialog ->- showOpenFileDialogSafe cb nullPtr (sdlWindow env) filtersConst nfilters defaultPtr allowMany- SaveDialog ->- showSaveFileDialogSafe cb nullPtr (sdlWindow env) filtersConst nfilters defaultPtr- FolderDialog ->- showOpenFolderDialogSafe cb nullPtr (sdlWindow env) defaultPtr allowMany- pure (FileDialogId did)--nextDialogId :: DialogState -> IO Int-nextDialogId st = atomicModifyIORef' (dsNextId st) $ \n -> (n + 1, n + 1)---- | SDL invoked the callback: decode the file list, release the FFI buffers--- this launch owned, record the outcome, and only then wake the (possibly idle)--- event loop. The status must be visible before the wake, or the woken frame--- polls 'FileDialogPending', skips, and the result waits for an unrelated--- event.-onResult ::- Int ->- DialogState ->- [CString] ->- Ptr SDL_DialogFileFilter ->- Maybe CString ->- Ptr () ->- Ptr () ->- Int32 ->- IO ()-onResult did st filterStrs filtersPtr defaultStr _userdata filelistRaw _filterIdx = do- paths <- peekFileListRaw filelistRaw- let outcome =- case paths of- Nothing -> FileDialogFailed- Just [] -> FileDialogCancelled- Just ps -> FileDialogSelected ps- forM_ filterStrs free- free filtersPtr- forM_ defaultStr free- atomicModifyIORef' (dsPending st) $ \pending ->- (IM.adjust (\pl -> pl {pendingStatus = outcome}) did pending, ())- pushRefreshEvent---- | Decode SDL's null-terminated file list into a plain list of paths.------ A null list pointer means SDL hit an error; a null first entry means the--- user canceled.-peekFileListRaw :: Ptr () -> IO (Maybe [FilePath])-peekFileListRaw filelistRaw- | filelistRaw == nullPtr = pure Nothing- | otherwise = Just <$> (peekArray0 nullPtr (castPtr filelistRaw) >>= traverse peekCString)--allocFilters :: [FileFilter] -> IO (Ptr SDL_DialogFileFilter, [CString])-allocFilters [] = pure (nullPtr, [])-allocFilters fs = do- arr <- mallocArray (length fs)- strs <-- fmap concat $- forM (zip [0 ..] fs) $ \(i, FileFilter name pattern_) -> do- namePtr <- newCString (T.unpack name)- patternPtr <- newCString (T.unpack pattern_)- pokeElemOff- arr- i- ( SDL_DialogFileFilter- (PtrConst.unsafeFromPtr namePtr)- (PtrConst.unsafeFromPtr patternPtr)- )- pure [namePtr, patternPtr]- pure (arr, strs)--allocDefault :: Maybe FilePath -> IO (PtrConst.PtrConst CChar, Maybe CString)-allocDefault Nothing = pure (PtrConst.unsafeFromPtr nullPtr, Nothing)-allocDefault (Just path) = do- cstr <- newCString path- pure (PtrConst.unsafeFromPtr cstr, Just cstr)---- SDL_DialogFileCallback is `void (*)(void *, const char * const *, int)`,--- flattened to `void *` pointers at the FFI boundary.-foreign import ccall "wrapper"- mkDialogCallback :: DialogCallback -> IO DialogCallbackFunPtr
− lib/NanoUI/Sdl/Dialog/Types.hs
@@ -1,101 +0,0 @@--- | Types and pending-dialog state shared between the SDL dialog backend and--- the SDL window lifecycle.-module NanoUI.Sdl.Dialog.Types- ( FileDialogId (..)- , FileDialogResult (..)- , PendingDialog (..)- , DialogCallback- , DialogCallbackFunPtr- , DialogState (..)- , newDialogState- , clearDialogState- , drainRetired- , retireDialogCallback- ) where--import Data.Int (Int32)-import Data.IntMap.Strict (IntMap)-import Data.IntMap.Strict qualified as IM-import Data.IORef (IORef, atomicModifyIORef', newIORef, writeIORef)-import Foreign.Ptr (FunPtr, Ptr, freeHaskellFunPtr)---- | Opaque handle returned by a non-blocking dialog launch. @0@ is never a--- valid handle.-newtype FileDialogId = FileDialogId Int- deriving (Eq, Ord, Show)---- | Lifecycle state of a launched file dialog.-data FileDialogResult- = FileDialogPending- -- ^ Still waiting for the user.- | FileDialogCancelled- -- ^ The user dismissed the dialog without choosing.- | FileDialogFailed- -- ^ SDL reported an error.- | FileDialogSelected [FilePath]- -- ^ The user chose one or more paths.- | FileDialogUnknown- -- ^ No dialog with this handle is being tracked. A handle becomes unknown- -- once its result has been delivered and consumed by 'pollFileDialog', or- -- after the dialog was abandoned via 'cancelFileDialog'. Never poll a- -- handle that returns 'FileDialogUnknown' again.- deriving (Eq, Show)---- | Shape of the SDL3 dialog callback, flattened to 'Ptr' at the FFI--- boundary.-type DialogCallback = Ptr () -> Ptr () -> Int32 -> IO ()---- | A marshalled 'DialogCallback' allocated once per dialog launch.-type DialogCallbackFunPtr = FunPtr DialogCallback---- | A tracked dialog: its current status plus the FFI callback that owns its--- completion. The callback is released only after the dialog completes and a--- poll consumes the result, so it is never freed while SDL could still invoke--- it.-data PendingDialog = PendingDialog- { pendingStatus :: !FileDialogResult- , pendingCallback :: !DialogCallbackFunPtr- }---- | Pending dialogs, keyed by 'FileDialogId'.-data DialogState = DialogState- { dsNextId :: !(IORef Int)- , dsPending :: !(IORef (IntMap PendingDialog))- , dsRetiredCur :: !(IORef [DialogCallbackFunPtr])- , dsRetiredPrev :: !(IORef [DialogCallbackFunPtr])- }---- | Create an empty dialog state.-newDialogState :: IO DialogState-newDialogState =- DialogState- <$> newIORef 0- <*> newIORef IM.empty- <*> newIORef []- <*> newIORef []---- | Forget every pending dialog. Used during SDL teardown: dialogs still--- open on the OS side keep running and their callbacks are left to the--- process, but all handles become 'FileDialogUnknown'. Entries still in the--- current retirement batch are not freed here: SDL may still be--- unwinding their wrappers during teardown; they leak to process exit.-clearDialogState :: DialogState -> IO ()-clearDialogState st = do- writeIORef (dsPending st) IM.empty- drainRetired st---- | Retire a consumed dialog callback for freeing on a later poll.-retireDialogCallback :: DialogState -> DialogCallbackFunPtr -> IO ()-retireDialogCallback st cb =- atomicModifyIORef' (dsRetiredCur st) (\cbs -> (cb : cbs, ()))---- | Free callback 'FunPtr's retired before the previous poll. Retiring parks--- them for one full poll first so the dialog callback thread has certainly--- returned before 'freeHaskellFunPtr' runs (freeing a wrapper while it--- executes is unsafe).-drainRetired :: DialogState -> IO ()-drainRetired st = do- cbs <- atomicModifyIORef' (dsRetiredPrev st) (\cbs -> ([], cbs))- mapM_ freeHaskellFunPtr cbs- cur <- atomicModifyIORef' (dsRetiredCur st) (\cur -> ([], cur))- writeIORef (dsRetiredPrev st) cur
− lib/NanoUI/Sdl/Display.hs
@@ -1,150 +0,0 @@-{-# LANGUAGE OverloadedRecordDot #-}--module NanoUI.Sdl.Display- ( defaultFontSize- , queryWindowPixelDensity- , queryWindowRefreshHz- , queryWindowLogicalSize- , queryMouseWindowPos- , zoomWindow- , installResizeWatch- , refreshEventType- , initRefreshEvent- , pushRefreshEvent- ) where--import Control.Monad (unless, void)-import Data.IORef (IORef, newIORef, readIORef, writeIORef)-import Foreign.C.Types (CInt (..))-import Foreign.Marshal.Alloc (alloca, callocBytes)-import Foreign.Ptr (FunPtr, Ptr, freeHaskellFunPtr)-import Foreign.Storable (peek, poke, sizeOf)-import Data.Word (Word32)-import NanoUI (Size (..), V2 (..))-import SDL3.Sys.Bindgen.Events (SDL_Event)-import SDL3.Sys.Bindgen.Stdinc (Uint32 (..))-import SDL3.Sys.Bindgen.Video (SDL_Window)-import SDL3.Sys.Events (pushEvent, registerEvents)-import SDL3.Sys.Mouse (getMouseState)-import SDL3.Sys.Bindgen.Rect (SDL_Rect (..))-import SDL3.Sys.Video (getDisplayForWindow, getDisplayUsableBounds, getWindowPixelDensity, getWindowSize, setWindowPosition, setWindowSize)-import System.IO.Unsafe (unsafePerformIO)--defaultFontSize :: Float-defaultFontSize = 16---- | Backbuffer pixels per window coordinate: the factor the retained--- framebuffer, glyph rasterization and snapping need. This is not--- 'SDL_GetWindowDisplayScale', which also folds in the desktop's content--- scale. On Windows window coordinates are already pixels, so at 125%--- scaling the display scale is 1.25 while the density is 1; sizing the--- framebuffer by the display scale rendered 1.56x the window's pixels and--- squeezed them back down on every present.-queryWindowPixelDensity :: Ptr SDL_Window -> IO Float-queryWindowPixelDensity win = do- s <- getWindowPixelDensity win- pure (if s > 0 then s else 1)---- | Vertical refresh rate of the window's current display mode, in Hz--- (0 when unavailable).-queryWindowRefreshHz :: Ptr SDL_Window -> IO Int-queryWindowRefreshHz win = do- hz <- windowRefreshRateC win- pure (max 0 (fromIntegral hz))---- | Window size in window (logical) coordinates; 0x0 when SDL cannot say.--- SDL_GetWindowSize already returns the window-coordinate size, not pixels.--- Dividing by the display scale would shrink the logical size on DPI-scaled--- displays, making the retained framebuffer too small.-queryWindowLogicalSize :: Ptr SDL_Window -> IO Size-queryWindowLogicalSize win =- alloca $ \wp ->- alloca $ \hp -> do- ok <- getWindowSize win wp hp- if ok- then do- w <- peek wp- h <- peek hp- pure (Size (fromIntegral w) (fromIntegral h))- else pure (Size 0 0)---- | Pointer position relative to the window with mouse focus, in window--- coordinates. Uses 'SDL_GetMouseState' rather than the global pointer +--- window position: the latter is unreliable on Wayland (window position is not--- exposed) and breaks hover/wheel targeting.-queryMouseWindowPos :: IO V2-queryMouseWindowPos =- alloca $ \xp ->- alloca $ \yp -> do- void (getMouseState xp yp)- x <- peek xp- y <- peek yp- pure (V2 (realToFrac x) (realToFrac y))---- Windows runs a modal loop while the user drags the border, so the app--- event watch does not run. SDL still delivers resize events to this watch.-installResizeWatch :: IO () -> IO (IO ())-installResizeWatch act = do- fp <- mkResizeCb act- ok <- installResizeWatchC fp- unless ok $ fail "SDL_AddEventWatch failed"- pure $ do- removeResizeWatchC- freeHaskellFunPtr fp---- | The user event type that wakes the event loop, registered once per--- process by 'initRefreshEvent'; 0 until then.-{-# NOINLINE refreshEventType #-}-refreshEventType :: IORef Word32-refreshEventType = unsafePerformIO (newIORef 0)---- | The event 'pushRefreshEvent' sends, filled in once by 'initRefreshEvent'.--- The core wakes the loop on every 'markDirty', so a push must not allocate.-{-# NOINLINE refreshEvent #-}-refreshEvent :: Ptr SDL_Event-refreshEvent = unsafePerformIO (callocBytes (sizeOf (undefined :: SDL_Event)))--initRefreshEvent :: IO Bool-initRefreshEvent = do- registered <- readIORef refreshEventType- if registered /= 0- then pure True- else do- ty <- registerEvents 1- poke refreshEvent.type' (Uint32 ty)- writeIORef refreshEventType ty- pure (ty /= 0)--pushRefreshEvent :: IO ()-pushRefreshEvent = do- ty <- readIORef refreshEventType- unless (ty == 0) $ void (pushEvent refreshEvent)--foreign import ccall unsafe "nano_ui_window_refresh_rate"- windowRefreshRateC :: Ptr SDL_Window -> IO CInt--foreign import ccall "wrapper"- mkResizeCb :: IO () -> IO (FunPtr (IO ()))--foreign import ccall safe "nano_ui_install_resize_watch"- installResizeWatchC :: FunPtr (IO ()) -> IO Bool--foreign import ccall safe "nano_ui_remove_resize_watch"- removeResizeWatchC :: IO ()---- | Grow a window just opened at a logical size by the UI zoom, as far as--- the usable area of its display allows, and centre it again.-zoomWindow :: Ptr SDL_Window -> Size -> Float -> IO ()-zoomWindow win (Size w h) zoom = do- display <- getDisplayForWindow win- usable <- alloca $ \rp -> do- ok <- getDisplayUsableBounds display rp- if ok then Just <$> peek rp else pure Nothing- let fit want avail = case avail of- Just a | a > 0 -> min want (fromIntegral a)- _ -> want- zw = fit (w * zoom) ((.w) <$> usable)- zh = fit (h * zoom) ((.h) <$> usable)- centred = 0x2FFF0000 -- SDL_WINDOWPOS_CENTERED- void $ setWindowSize win (round zw) (round zh)- void $ setWindowPosition win centred centred
− lib/NanoUI/Sdl/Font.hs
@@ -1,1446 +0,0 @@-module NanoUI.Sdl.Font- ( FontSource (..)- , GlyphAtlas- , withTtf- , fontSourceLabel- , newGlyphAtlas- , destroyGlyphAtlas- , prepareGlyphAtlasForFrame- , takeGlyphAtlasResetFlag- , glyphAtlasTexture- , SdlFontCache- , newSdlFontCache- , destroySdlFontCache- , reloadSdlFontCache- , sdlFontCacheSource- , withSdlFontCache- ) where--import Control.Exception (SomeException, bracket, catch, throwIO)-import Control.Monad (forM, forM_, unless, void, when)-import Data.Bits ((.&.), (.|.), shiftL)-import Foreign.Marshal.Alloc (alloca, allocaBytes)-import Foreign.Marshal.Array (advancePtr, allocaArray)-import Data.Char (isPrint, isSpace, ord)-import NanoUI.Bidi (BidiRun (..), bidiRuns, needsBidi)-import NanoUI.Sdl.Font.Search (searchFontFamilies)-import System.IO.Unsafe (unsafePerformIO)-import Data.ByteString (ByteString)-import Data.ByteString.Unsafe (unsafeUseAsCStringLen)-import Data.IORef (IORef, atomicModifyIORef', modifyIORef', newIORef, readIORef, writeIORef)-import qualified Data.HashMap.Strict as HM-import Data.Hashable (Hashable (..))-import qualified Data.IntSet as IS-import Data.Primitive.SmallArray- ( SmallArray- , indexSmallArray- , newSmallArray- , readSmallArray- , sizeofSmallArray- , smallArrayFromList- , writeSmallArray- )-import Data.Primitive.PrimArray (PrimArray, indexPrimArray, newPrimArray, primArrayFromList, readPrimArray, setPrimArray, sizeofPrimArray, unsafeFreezePrimArray, writePrimArray)-import Data.Int (Int32)-import Data.Word (Word64)-import Data.Text (Text)-import qualified Data.Sequence as Seq-import qualified Data.Text as T-import qualified Data.ByteString.Short as SBS-import qualified GHC.Foreign as GHC-import GHC.IO.Encoding (getFileSystemEncoding)-import Data.Text.Unsafe (lengthWord8)-import Foreign.C.String (CString, withCString)-import Foreign.C.Types (CFloat (..), CInt (..), CSize (..), CUInt (..))-import Foreign.Ptr (IntPtr (..), Ptr, castPtr, intPtrToPtr, nullPtr, plusPtr, ptrToIntPtr)-import Foreign.Storable (peek, peekElemOff, poke, sizeOf)-import Data.Unique (hashUnique, newUnique)-import qualified Data.ByteString as BS-import System.Directory (getTemporaryDirectory, removeFile)-import System.IO (hClose, openTempFile)-import NanoUI- ( FontMetrics (..)- , FontBackend (..)- , FontStyle (..)- , FontVariant (..)- , FontWeight (..)- , GlyphQuad (..)- , ShapedGlyphs (..)- , ShapedText (..)- , monospaceMetrics- )-import NanoUI.Testing- ( Context- , withExternalText- , withFontMetrics- , withFontResolver- , withMeasureText- , withMonoFontMetrics- , wrapMeasureCache- )-import SDL3.Sys.Bindgen.Render (SDL_Renderer, SDL_Texture)-import qualified Data.IntMap.Strict as IM-import qualified Data.Text.Foreign as TF--data SdlFont = SdlFont- { sfId :: !Word64- , sfFont :: Ptr ()- , sfLineSkip :: Float- , sfAscent :: Float- , sfSpaceAdvance :: Float- , sfTempPath :: !(Maybe FilePath)- , sfAlive :: !(IORef Bool)- , sfPointSize :: !Float- -- ^ The size the font was opened at, which its fallbacks open at too.- , sfFallbacks :: !(IORef (IM.IntMap SdlFont))- -- ^ Fonts shaping falls back to for characters this one lacks, by their- -- place in 'coverageFamilies': each is attached, at this font's size, the- -- first time a text needs a character only it covers.- }--data FontSource- = FontFromPath !FilePath- | FontFromMemory !ByteString !FilePath- deriving (Show)--fontSourceLabel :: FontSource -> FilePath-fontSourceLabel (FontFromPath p) = p-fontSourceLabel (FontFromMemory _ label) = label---- | Per-glyph atlas slot. UVs are normalised to [0,1] within the atlas texture.-data GlyphSlot = GlyphSlot- { gsW :: {-# UNPACK #-} !Float -- pixel width of glyph image- , gsH :: {-# UNPACK #-} !Float -- pixel height of glyph image- , gsU0 :: {-# UNPACK #-} !Float- , gsV0 :: {-# UNPACK #-} !Float- , gsU1 :: {-# UNPACK #-} !Float- , gsV1 :: {-# UNPACK #-} !Float- , gsOffX :: {-# UNPACK #-} !Float -- bearing x (pixels, at font scale)- , gsOffY :: {-# UNPACK #-} !Float -- bearing y (pixels, at font scale)- , gsAdvX :: {-# UNPACK #-} !Float -- horizontal advance (pixels, at font scale)- }--data GlyphAtlas = GlyphAtlas- { gaAtlas :: !(Ptr ())- , -- | Glyph slots by font id, then codepoint. Closing a font drops its inner- -- map instead of scanning every glyph.- gaEntries :: !(IORef (IM.IntMap (IM.IntMap (Maybe GlyphSlot))))- , gaEpoch :: !(IORef Word64)- , -- | An insertion failed (atlas out of space) during the last frame; the- -- atlas must be reset at the next frame start, before any quad is- -- recorded, so the reset can never wipe the texture underneath- -- already-recorded text.- gaNeedsReset :: !(IORef Bool)- , -- | The atlas was reset (or ran out of space) since the flag was last- -- cleared at frame start. Observed by the runner after the UI pass: a- -- set flag means the frame being built holds stale-UV or unplaceable- -- text quads and must not be presented.- gaResetFlag :: !(IORef Bool)- , -- | Glyph slots by font id, then glyph index: what shaped text draws.- gaIndexEntries :: !(IORef (IM.IntMap (IM.IntMap (Maybe GlyphSlot))))- , -- | Actions to run after every reset (re-warming the base fonts).- gaRewarmHooks :: !(IORef [IO ()])- , gaAlive :: !(IORef Bool)- }--newFontId :: IO Word64-newFontId = fromIntegral . hashUnique <$> newUnique---- Backend effects are confined to the owning SDL thread. Retained snapshots--- may outlive a window or a cache entry, but must never query a freed handle.-ensureFontAlive :: SdlFont -> IO ()-ensureFontAlive sf = do- alive <- readIORef (sfAlive sf)- unless alive (fail "font backend used after closeFont")--ensureAtlasAlive :: GlyphAtlas -> IO ()-ensureAtlasAlive ga = do- alive <- readIORef (gaAlive ga)- unless alive (fail "font backend used after destroyGlyphAtlas")---- | Maximum number of shaped-run cache entries per 'FontMetrics'. Dynamic,--- ever-changing text (FPS counters, timers, percentages, mouse positions)--- generates unique strings over time; without a bound the run cache (and--- the atlas rectangles its renders occupy) would grow without limit. The--- cap sits well above a realistic frame's string working set so steady--- static text is never evicted (re-rendering an evicted run leaks its old--- atlas rectangle); atlas exhaustion itself is recovered by the deferred--- reset in 'prepareGlyphAtlasForFrame', which also clears the whole cache.-runCacheCap :: Int-runCacheCap = 1024---- Entry-count limits alone do not bound retained text: edited oversized lines--- can otherwise keep thousands of full-document versions alive per font.-cacheableText :: Text -> Bool-cacheableText txt = T.compareLength txt 4096 /= GT---- | A hash map bounded by entry count: 'insertBounded' into a full cache evicts--- the first key of 'bcOrder' and returns its value so the owner can release--- it. Hashing a text key once beats comparing it at every level of a tree.-data BoundedCache k v = BoundedCache- { bcEntries :: !(HM.HashMap k v)- , bcOrder :: !(Seq.Seq k)- -- ^ Each key once, oldest first. Its length is the entry count, which- -- 'HM.size' would have to count.- }--emptyBounded :: BoundedCache k v-emptyBounded = BoundedCache HM.empty Seq.empty--insertBounded :: Hashable k => Int -> k -> v -> BoundedCache k v -> (BoundedCache k v, Maybe v)-insertBounded cap k v (BoundedCache m order) =- case HM.alterF (\old -> (old, Just v)) k m of- (Just _, m') -> (BoundedCache m' order, Nothing)- (Nothing, m')- | Seq.length order >= cap- , victim Seq.:<| rest <- order ->- let (evicted, m'') = HM.alterF (\old -> (old, Nothing)) victim m'- in (BoundedCache m'' (rest Seq.|> k), evicted)- | otherwise -> (BoundedCache m' (order Seq.|> k), Nothing)---- Native glyph measurements have one representation, shared by metric-only--- preparation and atlas placement. Pixel bearings are unscaled here.-data GlyphMetrics = GlyphMetrics- { gmMinX :: !Float- , gmMaxX :: !Float- , gmMinY :: !Float- , gmMaxY :: !Float- , gmAdvance :: !Float- }--getGlyphMetrics :: SdlFont -> CUInt -> IO (Maybe GlyphMetrics)-getGlyphMetrics sf cp = allocaArray 5 $ \p -> do- ok <-- ttfGlyphMetrics- (sfFont sf)- cp- p- (p `advancePtr` 1)- (p `advancePtr` 2)- (p `advancePtr` 3)- (p `advancePtr` 4)- let- metric i = fromIntegral <$> peekElemOff p i- if ok- then- Just- <$> (GlyphMetrics <$> metric 0 <*> metric 1 <*> metric 2 <*> metric 3 <*> metric 4)- else pure Nothing--getGlyphAdvance :: SdlFont -> CUInt -> IO (Maybe Float)-getGlyphAdvance sf cp = fmap gmAdvance <$> getGlyphMetrics sf cp---- Metric-only geometry has no atlas lifetime and never rasterises a surface.-getGlyphGeometry :: SdlFont -> Float -> Char -> IO (Maybe GlyphQuad)-getGlyphGeometry sf inv c =- fmap (metricsGlyphQuad sf inv) <$> getGlyphMetrics sf (fromIntegral (ord c))--metricsGlyphQuad :: SdlFont -> Float -> GlyphMetrics -> GlyphQuad-metricsGlyphQuad sf inv metrics =- GlyphQuad- (gmMinX metrics / inv)- ((sfAscent sf - gmMaxY metrics) / inv)- ((gmMaxX metrics - gmMinX metrics) / inv)- ((gmMaxY metrics - gmMinY metrics) / inv)- 0- 0- 0- 0--newGlyphAtlas :: Ptr SDL_Renderer -> IO GlyphAtlas-newGlyphAtlas ren = do- atlas <- textAtlasCreate ren- when (atlas == nullPtr) $ fail "nano_ui_text_atlas_create failed (glyph)"- entries <- newIORef IM.empty- indexEntries <- newIORef IM.empty- epoch <- newIORef 0- needsReset <- newIORef False- resetFlag <- newIORef False- rewarms <- newIORef []- alive <- newIORef True- pure- GlyphAtlas- { gaAtlas = atlas- , gaEntries = entries- , gaIndexEntries = indexEntries- , gaEpoch = epoch- , gaNeedsReset = needsReset- , gaResetFlag = resetFlag- , gaRewarmHooks = rewarms- , gaAlive = alive- }--destroyGlyphAtlas :: GlyphAtlas -> IO ()-destroyGlyphAtlas ga = do- alive <- atomicModifyIORef' (gaAlive ga) (\open -> (False, open))- when alive $ textAtlasDestroy (gaAtlas ga)---- | Register an action to run after every atlas reset (DPI change, font--- switch, exhaustion recovery). 'newSdlFontCache' registers one that re-warms--- the base fonts' ASCII glyphs, so the next frame pays no cold glyph misses.-registerGlyphAtlasRewarm :: GlyphAtlas -> IO () -> IO ()-registerGlyphAtlasRewarm ga hook = modifyIORef' (gaRewarmHooks ga) (hook :)--resetGlyphAtlas :: GlyphAtlas -> IO ()-resetGlyphAtlas ga = do- modifyIORef' (gaEpoch ga) (+1)- writeIORef (gaEntries ga) IM.empty- writeIORef (gaIndexEntries ga) IM.empty- writeIORef (gaNeedsReset ga) False- textAtlasReset (gaAtlas ga)- hooks <- readIORef (gaRewarmHooks ga)- mapM_ id hooks- writeIORef (gaResetFlag ga) True---- | An atlas insertion failed: the atlas is out of space. The reset is--- deferred to the next frame start ('prepareGlyphAtlasForFrame') so quads--- already recorded this frame keep sampling valid pixels, and the frame--- itself is marked invalid so the runner drops it instead of presenting--- text that could not be placed.-markAtlasExhausted :: GlyphAtlas -> IO ()-markAtlasExhausted ga = do- writeIORef (gaNeedsReset ga) True- writeIORef (gaResetFlag ga) True---- | Frame-start atlas maintenance: reset the atlas if an insertion failed--- during the previous frame, then clear the mid-frame reset flag. Must run--- before the frame's UI pass records any quads.-prepareGlyphAtlasForFrame :: GlyphAtlas -> IO ()-prepareGlyphAtlasForFrame ga = do- needs <- readIORef (gaNeedsReset ga)- when needs $ resetGlyphAtlas ga- writeIORef (gaResetFlag ga) False---- | Test-and-clear the mid-frame reset flag. 'True' means the atlas was--- reset (or ran out of space) while the frame was being built, so quads--- recorded before that point may hold stale UVs; the caller must not--- present that frame.-takeGlyphAtlasResetFlag :: GlyphAtlas -> IO Bool-takeGlyphAtlasResetFlag ga = atomicModifyIORef' (gaResetFlag ga) (\v -> (False, v))---- | Pre-rasterise printable ASCII into the glyph atlas to avoid cold misses--- on the first rendered frame.-warmGlyphAtlas :: GlyphAtlas -> SdlFont -> IO ()-warmGlyphAtlas ga sf =- mapM_ (\c -> lookupOrInsertGlyph ga sf c) [' ' .. '~']---- | Look up or insert a glyph into the atlas. Returns 'Nothing' for--- characters that have no glyph (e.g. control characters).-lookupOrInsertGlyph :: GlyphAtlas -> SdlFont -> Char -> IO (Maybe GlyphSlot)-lookupOrInsertGlyph ga sf c = do- entries <- readIORef (gaEntries ga)- case IM.lookup (fromIntegral (sfId sf)) entries >>= IM.lookup (ord c) of- Just mSlot -> pure mSlot- Nothing -> do- let !cp = fromIntegral (ord c) :: CUInt- mMetrics <- getGlyphMetrics sf cp- mSlot <- case mMetrics of- Nothing -> pure Nothing- Just metrics ->- placeGlyphImage ga (ttfRenderGlyphSurface (sfFont sf) cp) >>= \case- Nothing -> pure Nothing- Just slot -> do- -- TTF_GetGlyphImage is a tight bitmap. Place it with the font- -- bearings: pen + minX, lineTop + (ascent - maxY). Do not clamp- -- minX; monospace glyphs are often centered (minX > 0).- let !placed = slot {gsOffX = gmMinX metrics, gsOffY = sfAscent sf - gmMaxY metrics, gsAdvX = gmAdvance metrics}- pure (Just placed)- modifyIORef' (gaEntries ga) (IM.insertWith IM.union (fromIntegral (sfId sf)) (IM.singleton (ord c) mSlot))- pure mSlot---- | Look up or insert a glyph by font and glyph index, the way shaped text--- names glyphs. Glyphs are keyed by the font's id, which is never reused, and--- rendered through its handle.-lookupOrInsertGlyphIndex :: GlyphAtlas -> Int -> Int -> Int -> IO (Maybe GlyphSlot)-lookupOrInsertGlyphIndex ga fontKey handle gi = do- entries <- readIORef (gaIndexEntries ga)- case IM.lookup fontKey entries >>= IM.lookup gi of- Just mSlot -> pure mSlot- Nothing -> do- mSlot <- placeGlyphImage ga (ttfRenderGlyphIndexSurface (intPtrToPtr (IntPtr handle)) (fromIntegral gi))- modifyIORef' (gaIndexEntries ga) (IM.insertWith IM.union fontKey (IM.singleton gi mSlot))- pure mSlot---- | Render a glyph image into a surface and copy it into the atlas, as a slot--- with no bearings or advance. 'Nothing' when there is no image or no room.--- A full atlas is reset at the next frame start (see 'markAtlasExhausted'):--- wiping the texture here would leave quads already recorded this frame--- sampling blank pixels. The glyph is unavailable for the rest of the frame,--- which is dropped.-placeGlyphImage :: GlyphAtlas -> (Ptr (Ptr ()) -> IO Bool) -> IO (Maybe GlyphSlot)-placeGlyphImage ga render = do- surf <- alloca $ \sp -> do- poke sp nullPtr- ok <- render sp- if ok then peek sp else pure nullPtr- if surf == nullPtr- then pure Nothing- else do- mPos <- tryInsert (gaAtlas ga) surf- freeSurface surf- case mPos of- Nothing -> do- markAtlasExhausted ga- pure Nothing- Just (px, py, tw, th) -> do- let !slot =- GlyphSlot- { gsW = tw- , gsH = th- , gsU0 = px / glyphAtlasSize- , gsV0 = py / glyphAtlasSize- , gsU1 = (px + tw) / glyphAtlasSize- , gsV1 = (py + th) / glyphAtlasSize- , gsOffX = 0- , gsOffY = 0- , gsAdvX = 0- }- pure (Just slot)---- | Width and height of the glyph atlas texture; mirrors--- NANO_UI_TEXT_ATLAS_SIZE in nano_ui_text_atlas.c.-glyphAtlasSize :: Float-glyphAtlasSize = 2048---- | A line shaped by SDL_ttf: its layout for measuring and caret placement,--- its measured width and height, and per glyph nine numbers (glyph index, destination x y w h,--- source x y w h, in raster pixels) with the index of the font that has it--- among the line's font and its fallbacks.-data Shaped = Shaped- { shapedText :: !ShapedText- , shapedSize :: !(Float, Float)- -- ^ Kept whole so measuring a cached line allocates nothing.- , _shapedGlyphs :: !(PrimArray Int32)- , _shapedFontIndices :: !(PrimArray Int32)- , _shapedFonts :: !(SmallArray SdlFont)- }---- | The pieces of a line shaped one at a time, in visual order: character--- start, end, and the SDL_ttf direction (0 for a line in one direction).--- SDL_ttf keeps a right-to-left text's edge spaces on the side they are--- stored, so they are shaped apart and placed on the side they read.-shapingRuns :: Text -> [(Int, Int, CInt)]-shapingRuns txt- | needsBidi txt = concatMap directed (bidiRuns txt)- | otherwise = [(0, T.length txt, 0)]- where- directed r- | not (runRightToLeft r) = [(runStart r, runEnd r, 4)]- | otherwise =- let run = T.take (runEnd r - runStart r) (T.drop (runStart r) txt)- lead = T.length (T.takeWhile isSpace run)- trail = T.length (T.takeWhileEnd isSpace run)- coreStart = runStart r + lead- coreEnd = runEnd r - trail- in if coreStart >= coreEnd- then [(runStart r, runEnd r, 4)]- else- [(coreEnd, runEnd r, 4) | trail > 0]- ++ [(coreStart, coreEnd, 5)]- ++ [(runStart r, coreStart, 4) | lead > 0]---- | Shape one line with the font and its fallbacks. A line mixing--- directions is split into direction runs, each shaped on its own and placed--- in visual order, since SDL_ttf shapes a text in one direction. Caret--- positions come from the clusters: a cluster's characters share its width,--- from its left edge in a left-to-right run and from its right edge in a--- right-to-left one.-shapeLine :: SdlFont -> Float -> Text -> IO Shaped-shapeLine sf inv txt = do- ensureFontAlive sf- fallbacks <- IM.elems <$> readIORef (sfFallbacks sf)- let fontList = sf : fallbacks- n = T.length txt- totalBytes = lengthWord8 txt- runs = shapingRuns txt- pieceCount = length runs- ascii = totalBytes == n- -- The byte each character starts at, and the character starting at each- -- byte (n inside a character and at the end). ASCII needs neither.- byteOfChar <- newPrimArray (if ascii then 0 else n + 1)- charOfByte <- newPrimArray (if ascii then 0 else totalBytes + 1)- let byteAt i = if ascii then pure i else readPrimArray byteOfChar i- charAt b = if ascii then pure (min n b) else readPrimArray charOfByte (min totalBytes b)- indexChars !i !b t = do- writePrimArray byteOfChar i b- case T.uncons t of- Nothing -> pure ()- Just (c, rest) -> do- writePrimArray charOfByte b i- indexChars (i + 1) (b + utf8Length c) rest- unless ascii $ do- setPrimArray charOfByte 0 (totalBytes + 1) n- indexChars 0 0 txt- size <- fromIntegral <$> ttfShapedSize- allocaBytes (size * max 1 pieceCount) $ \outs -> do- let resultOf p = outs `plusPtr` (p * size)- -- Shape every piece first, so the output arrays are sized once.- let shapeAll !_ [] = pure ()- shapeAll !p ((start, end, dir) : rest) = do- withUtf8 (T.take (end - start) (T.drop start txt)) $ \cstr len -> do- ok <- ttfShape (sfFont sf) cstr len dir (resultOf p)- unless ok $ ttfShapedFree (resultOf p)- shapeAll (p + 1) rest- shapeAll 0 runs- let countGlyphs !p !acc- | p >= pieceCount = pure acc- | otherwise = do- g <- ttfShapedInt (resultOf p) 2- countGlyphs (p + 1) (acc + fromIntegral g)- glyphCount <- countGlyphs 0 0- glyphs <- newPrimArray (glyphCount * 9)- fontIndices <- newPrimArray glyphCount- -- Caret stops by character in raster pixels, NaN where no cluster- -- starts; a later cluster covering a character wins.- stops <- newPrimArray n- setPrimArray stops 0 n (0 / 0 :: Float)- let fillPieces !p !pen !height !g0 !inkEnd !endStop pieces = case pieces of- [] -> pure (pen, height, inkEnd, endStop)- (start, _, _) : rest -> do- let result = resultOf p- byteStart <- byteAt start- w <- fromIntegral <$> ttfShapedInt result 0- h <- fromIntegral <$> ttfShapedInt result 1- nGlyphs <- fromIntegral <$> ttfShapedInt result 2- nClusters <- fromIntegral <$> ttfShapedInt result 3- glyphPtr <- castPtr <$> ttfShapedPtr result 0- fontPtr <- castPtr <$> ttfShapedPtr result 1- clusterPtr <- castPtr <$> ttfShapedPtr result 2- let glyphInt :: Int -> IO Int32- glyphInt k = fromIntegral <$> peekElemOff (glyphPtr :: Ptr CInt) k- fontIndex ptr = go 0 fontList- where- go !k (f : fs) = if sfFont f == ptr then k else go (k + 1) fs- go !_ [] = 0- -- SDL_ttf's ten numbers a glyph start with its text offset,- -- which carets take from the clusters instead.- copyGlyphs !i !ink- | i >= nGlyphs = pure ink- | otherwise = do- let o = (g0 + i) * 9- field !k- | k > 9 = pure ()- | otherwise = do- v <- glyphInt (i * 10 + k)- writePrimArray glyphs (o + k - 1) (if k == 2 then v + fromIntegral pen else v)- field (k + 1)- field 1- x <- glyphInt (i * 10 + 2)- gw <- glyphInt (i * 10 + 4)- ptr <- peekElemOff (fontPtr :: Ptr (Ptr ())) i- writePrimArray fontIndices (g0 + i) (fontIndex ptr)- copyGlyphs (i + 1) (max ink (fromIntegral x + pen + fromIntegral gw))- clusterInt :: Int -> IO Int- clusterInt k = fromIntegral <$> peekElemOff (clusterPtr :: Ptr CInt) k- -- A cluster's characters share its width, from its left edge- -- left to right and from its right edge right to left.- placeClusters !i !end- | i >= nClusters = pure end- | otherwise = do- off0 <- clusterInt (i * 5)- len <- clusterInt (i * 5 + 1)- x0 <- clusterInt (i * 5 + 2)- cw <- clusterInt (i * 5 + 3)- flags <- clusterInt (i * 5 + 4)- if len <= 0- then placeClusters (i + 1) end- else do- let off = off0 + byteStart- x = fromIntegral (x0 + pen) :: Float- fw = fromIntegral cw- rtl = flags .&. 0xFF == 5- c0 <- charAt off- c1 <- charAt (off + len)- let k = max 1 (c1 - c0)- stop j- | c0 + j >= n = pure ()- | rtl = writePrimArray stops (c0 + j) (x + fw - fw * fromIntegral j / fromIntegral k)- | otherwise = writePrimArray stops (c0 + j) (x + fw * fromIntegral j / fromIntegral k)- forM_ [0 .. k - 1] stop- let end'- | isNaN end && c1 == n = if rtl then x else x + fw- | otherwise = end- placeClusters (i + 1) end'- ink <- if glyphPtr == nullPtr then pure inkEnd else copyGlyphs 0 inkEnd- end <- if clusterPtr == nullPtr then pure endStop else placeClusters 0 endStop- ttfShapedFree result- fillPieces (p + 1) (pen + w) (max height h) (g0 + nGlyphs) ink end rest- (total, height, inkEnd, endStop) <- fillPieces 0 0 (0 :: Int) 0 0 (0 / 0) runs- carets <- newPrimArray (n + 1)- let fillCarets !i !prev- | i >= n = pure ()- | otherwise = do- v <- readPrimArray stops i- let v' = if isNaN v then prev else v / inv- writePrimArray carets i v'- fillCarets (i + 1) v'- fillCarets 0 0- writePrimArray carets n ((if isNaN endStop then fromIntegral total else endStop) / inv)- caretArr <- unsafeFreezePrimArray carets- glyphArr <- unsafeFreezePrimArray glyphs- indexArr <- unsafeFreezePrimArray fontIndices- let !width = fromIntegral total / inv- !measured = (width, fromIntegral height / inv)- pure (Shaped (ShapedText width (fromIntegral inkEnd / inv) caretArr) measured glyphArr indexArr (smallArrayFromList fontList))- where- utf8Length c- | ord c < 0x80 = 1- | ord c < 0x800 = 2- | ord c < 0x10000 = 3- | otherwise = 4 :: Int---- | Open the fonts that cover what this one lacks, the first time a text--- has a character it cannot draw.-ensureCoverage :: SdlFont -> Text -> IO ()-ensureCoverage sf txt =- unless (T.all (\c -> ord c < 128) txt) $- forM_ (T.unpack txt) $ \c ->- when (ord c >= 128 && isPrint c) $ do- -- Whether the font or a fallback it already has draws the character.- has <- ttfHasGlyph (sfFont sf) (fromIntegral (ord c))- unless has $- coverageSourceFor c >>= \case- Just (source, probe) -> attachFallback sf source probe- Nothing -> pure ()---- | Open the coverage source @source@ at the font's size, sharing the--- source's stream with its probe, and attach it. Fallbacks stay in--- 'coverageFamilies' order, so a character two of them draw comes from the--- one listed first whichever was attached first.-attachFallback :: SdlFont -> Int -> Ptr () -> IO ()-attachFallback sf source probe = do- attached <- readIORef (sfFallbacks sf)- unless (IM.member source attached) $ do- copy <- ttfCopyFont probe (realToFrac (sfPointSize sf))- unless (copy == nullPtr) $ do- fallback <- readSdlFont (sfPointSize sf) Nothing copy- let attached' = IM.insert source fallback attached- case IM.lookupMax attached of- Just (lastSource, _) | lastSource > source -> do- forM_ attached $ \f -> ttfRemoveFallback (sfFont sf) (sfFont f)- forM_ attached' $ \f -> ttfAddFallback (sfFont sf) (sfFont f)- _ -> void (ttfAddFallback (sfFont sf) copy)- writeIORef (sfFallbacks sf) attached'---- | What the process knows about coverage fonts: the installed files, found--- once; a probe font for each opened so far (null when it failed to open),--- which every size copies from; and the first source drawing each character--- asked about (-1 for none).-data Coverage = Coverage- { covSources :: !(SmallArray SBS.ShortByteString)- -- ^ Paths as the file system's bytes, kept compactly for the session and- -- handed to SDL_ttf as they are.- , covProbes :: !(IM.IntMap (Ptr ()))- , covChars :: !(IM.IntMap Int)- }--{-# NOINLINE coverageRef #-}-coverageRef :: IORef (Maybe Coverage)-coverageRef = unsafePerformIO (newIORef Nothing)---- | The first coverage source, in 'coverageFamilies' order, that draws the--- character, and its probe. Probes open only as far down the list as a--- search goes, once a session, whatever the number of font sizes.-coverageSourceFor :: Char -> IO (Maybe (Int, Ptr ()))-coverageSourceFor c = do- cov0 <-- readIORef coverageRef >>= \case- Just cov -> pure cov- Nothing -> do- files <- searchFontFamilies coverageFamilies `catch` \(_ :: SomeException) -> pure []- -- The file system encoding turns a path back into the bytes it was- -- read from, including bytes that are not valid in that encoding.- enc <- getFileSystemEncoding- sources <- forM files $ \path -> GHC.withCStringLen enc path $ \cstr -> SBS.toShort <$> BS.packCStringLen cstr- pure (Coverage (smallArrayFromList sources) IM.empty IM.empty)- let cp = ord c- probeOf cov i = case IM.lookup i (covProbes cov) of- Just probe -> pure (probe, cov)- Nothing -> do- probe <- SBS.useAsCString (indexSmallArray (covSources cov) i) $ \cpath -> ttfOpenFont cpath 12- pure (probe, cov {covProbes = IM.insert i probe (covProbes cov)})- search cov i- | i >= sizeofSmallArray (covSources cov) = pure (-1, cov)- | otherwise = do- (probe, cov') <- probeOf cov i- has <- if probe == nullPtr then pure False else ttfHasGlyph probe (fromIntegral cp)- if has then pure (i, cov') else search cov' (i + 1)- (source, cov1) <- case IM.lookup cp (covChars cov0) of- Just known -> pure (known, cov0)- Nothing -> do- (found, cov') <- search cov0 0- pure (found, cov' {covChars = IM.insert cp found (covChars cov')})- writeIORef coverageRef (Just cov1)- pure $ case IM.lookup source (covProbes cov1) of- Just probe | source >= 0 -> Just (source, probe)- _ -> Nothing---- | Close the coverage probes, before SDL_ttf shuts down. Fallbacks copied--- from them keep their shared streams open until they close themselves.-closeCoverageProbes :: IO ()-closeCoverageProbes =- readIORef coverageRef >>= \case- Nothing -> pure ()- Just cov -> do- forM_ (covProbes cov) $ \probe -> unless (probe == nullPtr) (ttfCloseFont probe)- writeIORef coverageRef (Just cov {covProbes = IM.empty})---- | Fallback families in the order shaping tries them: broad Latin, Greek--- and Cyrillic first, then scripts, then symbols, across Linux, Windows and--- macOS names.-coverageFamilies :: [String]-coverageFamilies =- [ "Noto Sans", "DejaVu Sans"- , "Noto Sans Arabic", "Noto Sans Hebrew", "Noto Sans Devanagari", "Noto Sans Bengali"- , "Noto Sans Tamil", "Noto Sans Telugu", "Noto Sans Gujarati", "Noto Sans Gurmukhi"- , "Noto Sans Kannada", "Noto Sans Malayalam", "Noto Sans Sinhala", "Noto Sans Thai"- , "Noto Sans Lao", "Noto Sans Khmer", "Noto Sans Myanmar", "Noto Sans Armenian"- , "Noto Sans Georgian", "Noto Sans Ethiopic", "Noto Sans CJK", "Noto Sans CJK SC", "Noto Sans CJK JP"- , "Noto Sans Symbols", "Noto Sans Symbols 2", "Noto Sans Math"- , "Segoe UI", "Segoe UI Symbol", "Nirmala UI", "Leelawadee UI", "Microsoft YaHei"- , "Yu Gothic", "Malgun Gothic", "Arial Unicode MS"- , "Geeza Pro", "Kohinoor Devanagari", "Thonburi", "PingFang SC", "Hiragino Sans"- , "Apple SD Gothic Neo", "Apple Symbols"- ]---- | ASCII glyph-cache slot. The cached 'Maybe' is shared on every hit, so a--- warm lookup returns the same heap object instead of rebuilding--- @Just GlyphQuad@ on each character.-data CachedQuad- = UncachedQuad- -- Preserve the cached object even with -funbox-strict-fields: unpacking it- -- defeats sharing and reconstructs the lookup result on every hit.- | Cached {-# NOUNPACK #-} !(Maybe GlyphQuad)---- | Build immutable metric snapshots and explicit IO rasterisation callbacks.--- Font queries happen in 'fbPrepare'; atlas insertion happens in 'fbDrawShaped'--- and 'fbDrawGlyph'. All coordinates are logical (unscaled).------ Standard ASCII (0..127) lookups are backed by a 'SmallMutableArray'--- fast path for branchless O(1) in-memory indexing, with automatic cache invalidation--- whenever the underlying glyph atlas is reset.-{-# NOINLINE buildGlyphFontMetrics #-}-buildGlyphFontMetrics :: GlyphAtlas -> SdlFont -> Float -> IO (FontMetrics, Text -> IO (Float, Float))-buildGlyphFontMetrics ga sf scale = do- let !inv = if scale > 0 then scale else 1- baseFm = ttfFontMetricsScaled sf scale-- -- Query ASCII metrics once for both advances and geometry, without atlas rasterization.- asciiMetrics <- mapM (getGlyphMetrics sf) [0 .. 127 :: CUInt]- -- Reuse fixed ASCII geometry across dynamic labels, so preparing a fresh- -- counter string does not query native glyph metrics for each character.- let !asciiGeometry = smallArrayFromList (map (fmap (metricsGlyphQuad sf inv)) asciiMetrics)- !asciiAdvances =- primArrayFromList- [ case metrics of- Nothing -> sfSpaceAdvance sf / inv- Just m -> gmAdvance m / inv- | metrics <- asciiMetrics- ]-- -- Cache of ASCII 0..127 glyph quads with epoch-based invalidation- asciiCacheArr <- newSmallArray 128 UncachedQuad- initEpoch <- readIORef (gaEpoch ga)- asciiEpochRef <- newIORef initEpoch-- -- Non-ASCII glyph quads are memoised per font here (keyed by codepoint) so- -- repeated text still hits a shared value instead of rebuilding the record- -- on every character. Invalidated with the atlas epoch.- nonAsciiCacheRef <- newIORef IM.empty- nonAsciiEpochRef <- newIORef initEpoch-- -- Kerning pairs are sparse and each miss costs a shaped 2-glyph- -- layout, so a pair cache keeps the hot pen loops off the FFI- -- boundary after first contact. Keyed by packed codepoint pair on this- -- 'FontMetrics' (the font id is implicit).- kernCacheRef <- newIORef emptyBounded-- -- Shaped lines: SDL3_ttf lays each string out with its kerning,- -- ligatures, contextual forms, fallback fonts and right-to-left runs. A- -- line's layout is kept with its metric snapshot, which survives atlas- -- resets; the glyph quads drawn from it hold atlas UVs, so their cache is- -- dropped with the atlas epoch. Both caches are bounded by 'runCacheCap'.- preparedRef <- newIORef emptyBounded- shapedRef <- newIORef emptyBounded- quadCacheRef <- newIORef emptyBounded- initQuadEpoch <- readIORef (gaEpoch ga)- quadEpochRef <- newIORef initQuadEpoch-- let- slotToQuad !gs =- GlyphQuad- { gqX = gsOffX gs / inv- , gqY = gsOffY gs / inv- , gqW = gsW gs / inv- , gqH = gsH gs / inv- , gqU0 = gsU0 gs- , gqV0 = gsV0 gs- , gqU1 = gsU1 gs- , gqV1 = gsV1 gs- }-- resetAsciiCache !epoch = do- writeIORef asciiEpochRef epoch- mapM_ (\i -> writeSmallArray asciiCacheArr i UncachedQuad) [0 .. 127 :: Int]-- lookupAsciiQuad !cp = do- curEpoch <- readIORef (gaEpoch ga)- lastEpoch <- readIORef asciiEpochRef- when (curEpoch /= lastEpoch) $ resetAsciiCache curEpoch- cached <- readSmallArray asciiCacheArr cp- case cached of- Cached mq -> pure mq- UncachedQuad -> do- mSlot <- lookupOrInsertGlyph ga sf (toEnum cp)- newEpoch <- readIORef (gaEpoch ga)- if newEpoch /= curEpoch- then do- -- The atlas was reset during insertion: this slot's UVs are- -- already stale, so do not cache them.- resetAsciiCache newEpoch- pure (fmap slotToQuad mSlot)- else do- let !mq = fmap slotToQuad mSlot- writeSmallArray asciiCacheArr cp (Cached mq)- pure mq-- lookupNonAsciiQuad !c = do- curEpoch <- readIORef (gaEpoch ga)- lastEpoch <- readIORef nonAsciiEpochRef- when (curEpoch /= lastEpoch) $ do- writeIORef nonAsciiEpochRef curEpoch- writeIORef nonAsciiCacheRef IM.empty- m <- readIORef nonAsciiCacheRef- case IM.lookup (ord c) m of- Just mq -> pure mq- Nothing -> do- mSlot <- lookupOrInsertGlyph ga sf c- newEpoch <- readIORef (gaEpoch ga)- if newEpoch /= curEpoch- then pure (fmap slotToQuad mSlot)- else do- let !mq = fmap slotToQuad mSlot- modifyIORef' nonAsciiCacheRef (IM.insert (ord c) mq)- pure mq-- {-# NOINLINE glyphLookup #-}- glyphLookup !c = do- ensureFontAlive sf- ensureAtlasAlive ga- let !cp = ord c- if (fromIntegral cp :: Word) < 128- then lookupAsciiQuad cp- else lookupNonAsciiQuad c-- {-# NOINLINE advanceLookup #-}- advanceLookup !c =- let !cp = ord c- in if (fromIntegral cp :: Word) < 128- then pure (indexPrimArray asciiAdvances cp)- else do- mAdv <- getGlyphAdvance sf (fromIntegral cp)- pure $! case mAdv of- Nothing -> sfSpaceAdvance sf / inv- Just adv -> adv / inv-- {-# NOINLINE kernLookup #-}- kernLookup !prev !c = do- -- The cache lives on this 'FontMetrics', so the font id is constant and- -- the pair can be packed into a single Int key: no tuple on the hot path.- let !pk = (ord prev `shiftL` 21) .|. ord c- cache <- readIORef kernCacheRef- case HM.lookup pk (bcEntries cache) of- Just k -> pure k- Nothing -> do- raw <- ttfGetKerning (sfFont sf) (fromIntegral (ord prev) :: CUInt) (fromIntegral (ord c) :: CUInt)- let !k = fromIntegral raw / inv- -- At most 4096 pairs per font.- writeIORef kernCacheRef $! fst (insertBounded 4096 pk k cache)- pure k-- -- The glyph quads of a shaped line, from the atlas. Quads are cached per- -- text and dropped with the atlas epoch, when their UVs go stale.- {-# NOINLINE shapedLookup #-}- shapedLookup !txt- | T.null txt = pure Nothing- | otherwise = do- ensureFontAlive sf- ensureAtlasAlive ga- ep <- readIORef (gaEpoch ga)- quadEp <- readIORef quadEpochRef- when (quadEp /= ep) $ do- writeIORef quadEpochRef ep- writeIORef quadCacheRef emptyBounded- cache <- readIORef quadCacheRef- -- Entries are kept wrapped so a hit returns them without allocating.- case HM.lookup txt (bcEntries cache) of- Just quads -> pure quads- Nothing -> do- shaped <- shapeOf txt- quads <- Just <$> placeGlyphs shaped- epAfter <- readIORef (gaEpoch ga)- when (cacheableText txt && epAfter == ep) $- modifyIORef' quadCacheRef (fst . insertBounded runCacheCap txt quads)- pure quads-- -- Put a shaped line's glyphs in the atlas. A glyph the atlas has no room- -- for draws nothing, and the atlas resets before the next frame.- placeGlyphs (Shaped _ _ glyphs fontIndices fonts) = do- let !count = sizeofPrimArray fontIndices- out <- newPrimArray (count * 8)- let go !i- | i >= count = pure ()- | otherwise = do- let g k = fromIntegral (indexPrimArray glyphs (i * 9 + k)) :: Float- o = i * 8- write k v = writePrimArray out (o + k) v- font = indexSmallArray fonts (fromIntegral (indexPrimArray fontIndices i))- IntPtr handle = ptrToIntPtr (sfFont font)- mSlot <- lookupOrInsertGlyphIndex ga (fromIntegral (sfId font)) handle (fromIntegral (indexPrimArray glyphs (i * 9)))- write 0 (g 1 / inv)- write 1 (g 2 / inv)- write 2 (g 3 / inv)- write 3 (g 4 / inv)- case mSlot of- Just slot -> do- -- A glyph drawn in part samples only its source rect.- let sx = g 5- sy = g 6- sw = g 7- sh = g 8- u0 = gsU0 slot + sx / glyphAtlasSize- v0 = gsV0 slot + sy / glyphAtlasSize- u1 = if sw > 0 then u0 + sw / glyphAtlasSize else gsU1 slot- v1 = if sh > 0 then v0 + sh / glyphAtlasSize else gsV1 slot- write 4 u0- write 5 v0- write 6 u1- write 7 v1- Nothing -> do- let (u, v, _, _) = deadUv- write 4 u- write 5 v- write 6 u- write 7 v- go (i + 1)- go 0- ShapedGlyphs <$> unsafeFreezePrimArray out-- -- A UV rect that always samples transparent pixels: column 4 sits- -- right of the 4px white patch (columns 0..3) and left of the first- -- slot (allocations start at x = 5), and the final row is never- -- written because every slot keeps 1px of padding.- deadUv :: (Float, Float, Float, Float)- deadUv =- let !u = 4.5 / glyphAtlasSize- !v = (glyphAtlasSize - 0.5) / glyphAtlasSize- in (u, v, u, v)-- -- The shaped layout of a line, shared by measuring, preparing and- -- drawing it. Fonts that cover characters this one lacks join it before- -- the line is shaped.- shapeOf !txt = do- shapedCache <- readIORef shapedRef- case HM.lookup txt (bcEntries shapedCache) of- Just shaped -> pure shaped- Nothing -> do- ensureCoverage sf txt- shaped <- shapeLine sf inv txt- when (cacheableText txt) $- writeIORef shapedRef $! fst (insertBounded runCacheCap txt shaped shapedCache)- pure shaped-- -- The width shaping draws with, so layout and drawing agree.- measure !txt- | T.null txt = pure emptySize- | otherwise = shapedSize <$> shapeOf txt- !emptySize = (0, sfLineSkip sf / inv)-- glyphGeometry c- | ord c < 128 = pure (indexSmallArray asciiGeometry (ord c))- | otherwise = getGlyphGeometry sf inv c-- backend = FontBackend prepareText shapedLookup glyphLookup-- prepareText txt = do- ensureFontAlive sf- prepared <- readIORef preparedRef- case HM.lookup txt (bcEntries prepared) of- Just fm -> pure fm- Nothing -> do- let insertChar m c = IM.insert (ord c) c m- chars = T.foldl' insertChar (T.foldl' insertChar IM.empty " HxM") txt- advances <- traverse advanceLookup chars- geometry <- traverse glyphGeometry chars- let gather !pairs !previous remaining = case T.uncons remaining of- Nothing -> pure pairs- Just (c, rest) -> do- let key = (ord previous `shiftL` 21) .|. ord c- pairs' <- if IM.member key pairs then pure pairs else do- k <- kernLookup previous c- pure $! IM.insert key k pairs- gather pairs' c rest- seedKerns <- gather IM.empty ' ' "xM"- kerns <- gather seedKerns 'M' txt- shaped <- if T.null txt then pure Nothing else Just <$> shapeOf txt- let !layout = fmap shapedText shaped- let !fm = baseFm- { fmAdvance = \c ->- let cp = ord c- in if cp < 128 then indexPrimArray asciiAdvances cp- else IM.findWithDefault (sfSpaceAdvance sf / inv) cp advances- , fmKerning = \a b -> IM.findWithDefault 0 ((ord a `shiftL` 21) .|. ord b) kerns- , fmGlyph = \c -> IM.findWithDefault Nothing (ord c) geometry- , fmShape = \t -> if t == txt then layout else Nothing- , fmBackend = Just backend- , fmSnapScale = inv- }- when (cacheableText txt) $- writeIORef preparedRef $! fst (insertBounded runCacheCap txt fm prepared)- pure fm-- fm <- prepareText ""- pure (fm, measure)---- | Return the SDL_Texture backing the glyph atlas, for passing to the renderer.-glyphAtlasTexture :: GlyphAtlas -> IO (Ptr SDL_Texture)-glyphAtlasTexture ga = textAtlasTexture (gaAtlas ga)---- ----------------------------------------------------------------------------withTtf :: IO a -> IO a-withTtf act =- bracket startup shutdown $ \_ -> act- where- startup = do- ok <- ttfInit- when (not ok) $ fail "TTF_Init failed"- shutdown _ = closeCoverageProbes >> ttfQuit--openFont :: FilePath -> Float -> IO SdlFont-openFont path ptsize =- withCString path $ \cpath -> do- font <- ttfOpenFont cpath (realToFrac ptsize)- when (font == nullPtr) $- fail ("TTF_OpenFont failed for " ++ path)- readSdlFont ptsize Nothing font--openFontFromMemory :: ByteString -> FilePath -> Float -> IO SdlFont-openFontFromMemory bs label ptsize =- unsafeUseAsCStringLen bs $ \(ptr, len) -> do- (fontPtr, mTemp) <-- ttfOpenFontMemory (castPtr ptr) (fromIntegral len) (realToFrac ptsize) >>= \f ->- if f /= nullPtr- then pure (f, Nothing)- else openFontFromMemoryTemp bs ptsize- when (fontPtr == nullPtr) $- fail ("TTF_OpenFont failed for in-memory font " ++ label)- readSdlFont ptsize mTemp fontPtr--openFontFromMemoryTemp :: ByteString -> Float -> IO (Ptr (), Maybe FilePath)-openFontFromMemoryTemp bs openPt = do- tmpDir <- getTemporaryDirectory- (path, h) <- openTempFile tmpDir "nano-ui-font-"- BS.hPut h bs- hClose h- withCString path $ \cpath -> do- font <- ttfOpenFont cpath (realToFrac openPt)- if font == nullPtr- then removeFile path >> pure (nullPtr, Nothing)- else pure (font, Just path)---- | Wrap an open TTF font; @mTemp@ is a temp file to delete on close.-readSdlFont :: Float -> Maybe FilePath -> Ptr () -> IO SdlFont-readSdlFont ptsize mTemp font = do- fid <- newFontId- alive <- newIORef True- fallbacks <- newIORef IM.empty- lineSkip <- ttfLineSkip font- ascent <- ttfAscent font- spaceAdv <- ttfSpaceAdvance font- pure- SdlFont- { sfId = fid- , sfAlive = alive- , sfFont = font- , sfLineSkip = realToFrac lineSkip- , sfAscent = realToFrac ascent- , sfSpaceAdvance = realToFrac spaceAdv- , sfTempPath = mTemp- , sfPointSize = ptsize- , sfFallbacks = fallbacks- }--openFontSource :: FontSource -> Float -> IO SdlFont-openFontSource (FontFromPath path) ptsize = openFont path ptsize-openFontSource (FontFromMemory bs label) ptsize =- openFontFromMemory bs label ptsize--openFontSourceWithFallback :: FontSource -> FontSource -> Float -> IO SdlFont-openFontSourceWithFallback primary fallback ptsize =- openFontSource primary ptsize- `catch` \(e :: SomeException) ->- if fontSourcesSame primary fallback- then throwIO e- else openFontSource fallback ptsize- `catch` \(_ :: SomeException) -> throwIO e--fontSourcesSame :: FontSource -> FontSource -> Bool-fontSourcesSame (FontFromPath a) (FontFromPath b) = a == b-fontSourcesSame (FontFromMemory _ la) (FontFromMemory _ lb) = la == lb-fontSourcesSame _ _ = False--closeFont :: SdlFont -> IO ()-closeFont sf = do- alive <- atomicModifyIORef' (sfAlive sf) (\open -> (False, open))- when alive $ do- ttfCloseFont (sfFont sf)- mapM_ removeFile (sfTempPath sf)- readIORef (sfFallbacks sf) >>= mapM_ closeFont---- | Install glyph-atlas-backed 'FontMetrics' (from 'buildGlyphFontMetrics')--- so that 'pushText' emits per-glyph textured quads into the draw arena.--- Text measurement uses the primary font's shaped lines.-withTtfMeasureGlyph ::- Context ->- (Text -> IO (Float, Float)) -> -- ^ primary font measurement- FontMetrics -> -- ^ glyph-atlas fm for primary font- FontMetrics -> -- ^ glyph-atlas fm for mono font- Float ->- Context-withTtfMeasureGlyph ctx measure fm monoFm scale =- let ctx1 =- withExternalText- ( withMeasureText- (withMonoFontMetrics (withFontMetrics ctx fm) monoFm)- measure- )- False- in wrapMeasureCache scale ctx1 measure--ttfFontMetricsScaled :: SdlFont -> Float -> FontMetrics-ttfFontMetricsScaled sf scale =- let inv = if scale > 0 then scale else 1- in (monospaceMetrics (sfLineSkip sf / inv))- { fmAscent = sfAscent sf / inv- , fmAdvance = const (sfSpaceAdvance sf / inv)- }--tryInsert :: Ptr () -> Ptr () -> IO (Maybe (Float, Float, Float, Float))-tryInsert atlas surf =- allocaBytes (4 * sizeOf (0 :: CFloat)) $ \px -> do- let py = plusPtr px (sizeOf (0 :: CFloat))- tw = plusPtr py (sizeOf (0 :: CFloat))- th = plusPtr tw (sizeOf (0 :: CFloat))- ok <- textAtlasInsertSurface atlas surf px py tw th- if ok- then do- x <- realToFrac <$> peek px- y <- realToFrac <$> peek py- w <- realToFrac <$> peek tw- h <- realToFrac <$> peek th- pure (Just (x, y, w, h))- else pure Nothing--withUtf8 :: Text -> (CString -> CSize -> IO a) -> IO a-withUtf8 txt act =- TF.useAsPtr txt $ \ptr len ->- act (castPtr ptr) (fromIntegral len)--foreign import ccall unsafe "nano_ui_ttf_init"- ttfInit :: IO Bool--foreign import ccall unsafe "nano_ui_ttf_quit"- ttfQuit :: IO ()--foreign import ccall unsafe "nano_ui_ttf_open_font"- ttfOpenFont :: CString -> CFloat -> IO (Ptr ())--foreign import ccall unsafe "nano_ui_ttf_open_font_memory"- ttfOpenFontMemory :: Ptr () -> CSize -> CFloat -> IO (Ptr ())--foreign import ccall unsafe "nano_ui_ttf_close_font"- ttfCloseFont :: Ptr () -> IO ()--foreign import ccall unsafe "nano_ui_ttf_line_skip"- ttfLineSkip :: Ptr () -> IO CFloat--foreign import ccall unsafe "nano_ui_ttf_ascent"- ttfAscent :: Ptr () -> IO CFloat--foreign import ccall unsafe "nano_ui_ttf_space_advance"- ttfSpaceAdvance :: Ptr () -> IO CFloat--foreign import ccall unsafe "nano_ui_text_atlas_create"- textAtlasCreate :: Ptr SDL_Renderer -> IO (Ptr ())--foreign import ccall unsafe "nano_ui_text_atlas_destroy"- textAtlasDestroy :: Ptr () -> IO ()--foreign import ccall unsafe "nano_ui_text_atlas_reset"- textAtlasReset :: Ptr () -> IO ()--foreign import ccall unsafe "nano_ui_text_atlas_texture"- textAtlasTexture :: Ptr () -> IO (Ptr SDL_Texture)--foreign import ccall unsafe "nano_ui_text_atlas_insert_surface"- textAtlasInsertSurface ::- Ptr () ->- Ptr () ->- Ptr CFloat ->- Ptr CFloat ->- Ptr CFloat ->- Ptr CFloat ->- IO Bool--foreign import ccall unsafe "SDL_DestroySurface"- freeSurface :: Ptr () -> IO ()--foreign import ccall unsafe "nano_ui_ttf_glyph_metrics"- ttfGlyphMetrics ::- Ptr () -> -- font- CUInt -> -- codepoint- Ptr CInt -> -- out_minx- Ptr CInt -> -- out_maxx- Ptr CInt -> -- out_miny- Ptr CInt -> -- out_maxy- Ptr CInt -> -- out_advance- IO Bool--foreign import ccall unsafe "nano_ui_ttf_render_glyph_surface"- ttfRenderGlyphSurface ::- Ptr () -> -- font- CUInt -> -- codepoint- Ptr (Ptr ()) -> -- out_surface- IO Bool--foreign import ccall unsafe "nano_ui_ttf_shape"- ttfShape :: Ptr () -> CString -> CSize -> CInt -> Ptr () -> IO Bool--foreign import ccall unsafe "nano_ui_ttf_shaped_free"- ttfShapedFree :: Ptr () -> IO ()--foreign import ccall unsafe "nano_ui_ttf_shaped_size"- ttfShapedSize :: IO CSize--foreign import ccall unsafe "nano_ui_ttf_shaped_int"- ttfShapedInt :: Ptr () -> CInt -> IO CInt--foreign import ccall unsafe "nano_ui_ttf_shaped_ptr"- ttfShapedPtr :: Ptr () -> CInt -> IO (Ptr ())--foreign import ccall unsafe "nano_ui_ttf_render_glyph_index_surface"- ttfRenderGlyphIndexSurface :: Ptr () -> CUInt -> Ptr (Ptr ()) -> IO Bool--foreign import ccall unsafe "nano_ui_ttf_has_glyph"- ttfHasGlyph :: Ptr () -> CUInt -> IO Bool--foreign import ccall unsafe "nano_ui_ttf_add_fallback"- ttfAddFallback :: Ptr () -> Ptr () -> IO Bool--foreign import ccall unsafe "nano_ui_ttf_remove_fallback"- ttfRemoveFallback :: Ptr () -> Ptr () -> IO ()--foreign import ccall unsafe "nano_ui_ttf_copy_font"- ttfCopyFont :: Ptr () -> CFloat -> IO (Ptr ())--foreign import ccall unsafe "nano_ui_ttf_get_kerning"- ttfGetKerning :: Ptr () -> CUInt -> CUInt -> IO CInt---- ------------------------------------------------------------------------------ Font cache: the base sans and mono faces, plus fonts opened per size and--- variant on demand---- | A font variant and its point size key, @round (targetPt * 2)@.-data FontCacheKey = FontCacheKey !FontVariant !Int- deriving (Eq)--instance Hashable FontCacheKey where- hashWithSalt s (FontCacheKey variant ptKey) =- s `hashWithSalt` fromEnum variant `hashWithSalt` ptKey--data CachedFontEntry = CachedFontEntry- { cfeFont :: !SdlFont- , cfeFm :: !FontMetrics- , cfeMeasure :: !(Text -> IO (Float, Float))- }--data SdlFontCache = SdlFontCache- { sfcPrimarySourceRef :: !(IORef FontSource)- , sfcFallbackSource :: !FontSource- , sfcMonoSource :: !FontSource- , sfcMonoFallback :: !FontSource- , sfcGlyphAtlas :: !GlyphAtlas- , sfcBasePt :: !Float- , sfcScaleRef :: !(IORef Float)- -- ^ The window pixel density, owned by the window and read here.- , sfcBaseEntries :: !(IORef (CachedFontEntry, CachedFontEntry))- , sfcDynamicCache :: !(IORef (BoundedCache FontCacheKey CachedFontEntry))- }---- | Open the base sans and mono fonts at the pixel density, and re-warm them--- into the glyph atlas after every atlas reset.-newSdlFontCache ::- FontSource -> -- ^ primary font source- FontSource -> -- ^ fallback font source- FontSource -> -- ^ mono font source- FontSource -> -- ^ mono fallback font source- GlyphAtlas ->- Float -> -- ^ base font size (pt)- IORef Float -> -- ^ pixel density- IO SdlFontCache-newSdlFontCache primary fallback mono monoFb ga basePt scaleRef = do- scale <- readIORef scaleRef- primaryRef <- newIORef primary- sansEntry <- openCachedFont ga scale primary fallback basePt- monoEntry <- openCachedFont ga scale mono monoFb basePt- baseEntriesRef <- newIORef (sansEntry, monoEntry)- cacheRef <- newIORef emptyBounded- -- The hook reads the base entries when it runs, so a reset always warms the- -- live fonts, never ones already closed.- let rewarm = do- (sans, monoBase) <- readIORef baseEntriesRef- warmGlyphAtlas ga (cfeFont sans)- warmGlyphAtlas ga (cfeFont monoBase)- registerGlyphAtlasRewarm ga rewarm- rewarm- pure- SdlFontCache- { sfcPrimarySourceRef = primaryRef- , sfcFallbackSource = fallback- , sfcMonoSource = mono- , sfcMonoFallback = monoFb- , sfcGlyphAtlas = ga- , sfcBasePt = basePt- , sfcScaleRef = scaleRef- , sfcBaseEntries = baseEntriesRef- , sfcDynamicCache = cacheRef- }---- | A font from a source (or its fallback) at a point size, rasterised at--- the pixel density, with its glyph metrics.-openCachedFont :: GlyphAtlas -> Float -> FontSource -> FontSource -> Float -> IO CachedFontEntry-openCachedFont ga scale primary fallback pt = do- font <- openFontSourceWithFallback primary fallback (pt * scale)- (fm, measure) <- buildGlyphFontMetrics ga font scale- pure (CachedFontEntry font fm measure)---- | The primary (sans) family's source, for the debug readout.-sdlFontCacheSource :: SdlFontCache -> IO FontSource-sdlFontCacheSource cache = readIORef (sfcPrimarySourceRef cache)---- | Close fonts and drop their glyphs from the shared atlas index.-closeCachedFonts :: GlyphAtlas -> [SdlFont] -> IO ()-closeCachedFonts ga fonts = do- fallbacks <- concat <$> mapM (fmap IM.elems . readIORef . sfFallbacks) fonts- let handles = IS.fromList [fromIntegral (sfId f) | f <- fonts ++ fallbacks]- mapM_ closeFont fonts- modifyIORef' (gaEntries ga) (`IM.withoutKeys` IS.fromList (map (fromIntegral . sfId) fonts))- modifyIORef' (gaIndexEntries ga) (`IM.withoutKeys` handles)---- | Close every open font, base and dynamic.-destroySdlFontCache :: SdlFontCache -> IO ()-destroySdlFontCache cache = do- dynamic <- atomicModifyIORef' (sfcDynamicCache cache) (\c -> (emptyBounded, c))- (sans, mono) <- readIORef (sfcBaseEntries cache)- closeCachedFonts (sfcGlyphAtlas cache) (cfeFont sans : cfeFont mono : map cfeFont (HM.elems (bcEntries dynamic)))---- | Reopen the base fonts from @source@ at the current pixel density, close--- every dynamic size, and reset the glyph atlas, which re-warms the new base--- fonts.-reloadSdlFontCache :: SdlFontCache -> FontSource -> IO ()-reloadSdlFontCache cache source = do- destroySdlFontCache cache- writeIORef (sfcPrimarySourceRef cache) source- scale <- readIORef (sfcScaleRef cache)- let ga = sfcGlyphAtlas cache- sansEntry <- openCachedFont ga scale source (sfcFallbackSource cache) (sfcBasePt cache)- monoEntry <- openCachedFont ga scale (sfcMonoSource cache) (sfcMonoFallback cache) (sfcBasePt cache)- writeIORef (sfcBaseEntries cache) (sansEntry, monoEntry)- resetGlyphAtlas ga---- | Install the cache's base fonts as the context's measurement and glyph--- metrics, and its sizes and variants as the font resolver.-withSdlFontCache :: SdlFontCache -> Context -> IO Context-withSdlFontCache cache ctx = do- scale <- readIORef (sfcScaleRef cache)- (sans, mono) <- readIORef (sfcBaseEntries cache)- pure (withFontResolver (withTtfMeasureGlyph ctx (cfeMeasure sans) (cfeFm sans) (cfeFm mono) scale) (resolveSdlFont cache) (resolveSdlMeasure cache))---- | The open font for a size and variant. Weight and style pick nothing--- here: they are drawn synthetically over the regular face, because SDL_ttf's--- style flags change its layout boxes but not the glyph images shaped text--- draws, so a styled face would not line up.-getOrLoadCachedFont ::- SdlFontCache ->- Float ->- FontWeight ->- FontStyle ->- FontVariant ->- IO CachedFontEntry-getOrLoadCachedFont cache sz _weight _style var = do- let basePt = sfcBasePt cache- rawPt = if sz > 0 then sz else basePt- -- Quantize dynamic sizes to 0.5 pt increments so dragging sliders- -- doesn't create hundreds of redundant TTF_Font instances.- targetPt = fromIntegral (round (rawPt * 2.0) :: Int) / 2.0- ptKey = round (targetPt * 2.0) :: Int- basePtKey = round (basePt * 2.0) :: Int- isBase =- ptKey == basePtKey- if isBase- then do- (sansEntry, monoEntry) <- readIORef (sfcBaseEntries cache)- pure (if var == FontMono then monoEntry else sansEntry)- else do- let key = FontCacheKey var ptKey- dynamic <- readIORef (sfcDynamicCache cache)- case HM.lookup key (bcEntries dynamic) of- Just entry -> do- -- Least recently used goes first: move a hit to the back of the- -- eviction order, so fonts drawn every frame are never closed.- case Seq.viewr (bcOrder dynamic) of- _ Seq.:> newest | newest == key -> pure ()- _ ->- -- Each key appears in the order once, and a hot key sits near- -- the back, so search from the right and delete that one entry.- let order = bcOrder dynamic- in writeIORef (sfcDynamicCache cache) $!- dynamic {bcOrder = maybe order (`Seq.deleteAt` order) (Seq.elemIndexR key order) Seq.|> key}- pure entry- Nothing -> do- scale <- readIORef (sfcScaleRef cache)- primarySans <- readIORef (sfcPrimarySourceRef cache)- let (primary, fallback) =- if var == FontMono- then (sfcMonoSource cache, sfcMonoFallback cache)- else (primarySans, sfcFallbackSource cache)- -- Dynamic fonts are not warmed: they insert only glyphs drawn.- entry <- openCachedFont (sfcGlyphAtlas cache) scale primary fallback targetPt- -- At most 48 dynamic sizes stay open.- let (dynamic', evicted) = insertBounded 48 key entry dynamic- writeIORef (sfcDynamicCache cache) $! dynamic'- mapM_ (closeCachedFonts (sfcGlyphAtlas cache) . pure . cfeFont) evicted- pure entry--resolveSdlFont ::- SdlFontCache ->- Float ->- FontWeight ->- FontStyle ->- FontVariant ->- IO (FontMetrics, Bool)-resolveSdlFont cache sz weight style var = do- entry <- getOrLoadCachedFont cache sz weight style var- pure (cfeFm entry, False)--resolveSdlMeasure ::- SdlFontCache ->- Float ->- FontWeight ->- FontStyle ->- FontVariant ->- Text ->- IO (Float, Float)-resolveSdlMeasure cache sz weight style var txt = do- entry <- getOrLoadCachedFont cache sz weight style var- cfeMeasure entry txt
− lib/NanoUI/Sdl/Font/Inter.hs
@@ -1,17 +0,0 @@-{-# LANGUAGE TemplateHaskell #-}---- | Embedded default UI font. Import only from font bootstrap code.-module NanoUI.Sdl.Font.Inter- ( fontInterBytes- , fontInterLabel- ) where--import Data.ByteString (ByteString)-import Data.FileEmbed (embedFileRelative)--fontInterLabel :: FilePath-fontInterLabel = "inter.ttf"--{-# NOINLINE fontInterBytes #-}-fontInterBytes :: ByteString-fontInterBytes = $(embedFileRelative "data/inter.ttf")
− lib/NanoUI/Sdl/Font/Resolve.hs
@@ -1,43 +0,0 @@-module NanoUI.Sdl.Font.Resolve- ( embeddedFontSource- , resolveNanoUIFont- , defaultFontSearch- , defaultFontSearchMono- ) where--import NanoUI.Sdl.Font (FontSource (..))-import NanoUI.Sdl.Font.Inter (fontInterBytes, fontInterLabel)-import NanoUI.Sdl.Font.Search (searchFonts)-import NanoUI.Sdl.NanoUIFont (NanoUIFont (..))--embeddedFontSource :: FontSource-embeddedFontSource = FontFromMemory fontInterBytes fontInterLabel--defaultFontSearch :: NanoUIFont-defaultFontSearch =- FontSearch- [ "Inter"- , "Montserrat"- , "Work Sans"- , "Roboto"- , "Open Sans"- , "Helvetica Neue"- ]--defaultFontSearchMono :: NanoUIFont-defaultFontSearchMono =- FontSearch- [ "Consolas"- , "Courier New"- , "Liberation Mono"- , "DejaVu Sans Mono"- , "monospace"- ]--resolveNanoUIFont :: NanoUIFont -> IO FontSource-resolveNanoUIFont DefaultFont = pure embeddedFontSource-resolveNanoUIFont (FontFilePath path) = pure (FontFromPath path)-resolveNanoUIFont (FontSearch names) =- searchFonts names >>= \case- Just path -> pure (FontFromPath path)- Nothing -> pure embeddedFontSource
− lib/NanoUI/Sdl/Font/Search.hs
@@ -1,231 +0,0 @@--- | Locate system font files by walking the standard font directories for the--- current platform, without fontconfig. Each candidate file is matched--- against the requested family name using a normalised-filename heuristic.-module NanoUI.Sdl.Font.Search- ( searchFonts- , searchFontFamilies- , listFontFamilies- ) where--import Control.Exception (IOException, catch)-import Data.Containers.ListUtils (nubOrd)-import Data.IORef (IORef, newIORef, readIORef, writeIORef)-import Data.Char (isDigit, isLower, isSpace, isUpper, toLower)-import Data.List (isInfixOf, minimumBy, sort, stripPrefix)-import Data.Maybe (fromMaybe, listToMaybe, mapMaybe)-import Data.Ord (Down (..), comparing)-import qualified Data.Set as Set-import System.Directory (getHomeDirectory)-import System.Directory.Recursive (getFilesRecursive)-import System.Environment (lookupEnv)-import System.FilePath (takeBaseName, takeExtension, (</>))-import System.Info (os)-import System.IO.Unsafe (unsafePerformIO)---- | Try each family name in order, returning the first font file that--- matches. Generic families like @monospace@ are expanded to a list of--- concrete families first.-searchFonts :: [String] -> IO (Maybe FilePath)-searchFonts names = case concatMap families names of- [] -> pure Nothing- candidates -> do- files <- fontStems- pure (listToMaybe (mapMaybe (`bestMatch` files) candidates))- where- families name =- let norm = normalize name- in if null norm then [] else maybe [norm] (concatMap families) (expandGeneric norm)---- | The file for each family that is installed, in the order asked, reading--- the font directories once.-searchFontFamilies :: [String] -> IO [FilePath]-searchFontFamilies names = do- files <- fontStems- pure (nubOrd (mapMaybe (\name -> bestMatch (normalize name) files) names))---- | Human-readable names for every installed font family, deduped and sorted.--- Each name is a usable 'searchFonts' token: the same normalization is applied--- to both the requested family and the file stem, so a listed name always--- resolves back to (at least) the file it came from. Non-text faces (icons,--- colour emoji) are included; callers that need sans families can filter the--- result themselves.-listFontFamilies :: IO [String]-listFontFamilies = do- files <- fontStems- pure (Set.toAscList (Set.fromList (map (prettyFamily . takeBaseName . snd) files)))---- | Filename stem -> display family. Everything from the first @-@ is treated--- as style (\"Regular\", \"Bold Italic\", ...); camel case is split so--- @NotoSansArabic@ reads as @Noto Sans Arabic@. Kept case-insensitively--- compatible with 'normalize'.-prettyFamily :: String -> String-prettyFamily = separateCamel . stripStyle- where- stripStyle s = case break (== '-') s of- (base, _) -> base- separateCamel = go- where- go [] = []- go (c : cs) = c : goTail c cs- goTail _ [] = []- goTail prev (c : cs)- | isUpper c && (isLower prev || isDigit prev) = ' ' : c : goTail c cs- | otherwise = c : goTail c cs---- ------------------------------------------------------------------------------ Directory traversal---- | Every font file under every standard font directory for this platform,--- with its normalised name, normalised once for all the families matched--- against it. User directories come first so that user-installed fonts win--- over system ones; missing or unreadable roots are skipped. The directories--- are walked once per process.-fontStems :: IO [(String, FilePath)]-fontStems =- readIORef fontStemsRef >>= \case- Just stems -> pure stems- Nothing -> do- roots <- defaultFontDirs- files <- concat <$> mapM (fmap (sort . filter isFontFile) . filesBelow) roots- let stems = map (\path -> (normalize (takeBaseName path), path)) files- writeIORef fontStemsRef (Just stems)- pure stems--{-# NOINLINE fontStemsRef #-}-fontStemsRef :: IORef (Maybe [(String, FilePath)])-fontStemsRef = unsafePerformIO (newIORef Nothing)--filesBelow :: FilePath -> IO [FilePath]-filesBelow root =- getFilesRecursive root `catch` \(_ :: IOException) -> pure []--defaultFontDirs :: IO [FilePath]-defaultFontDirs =- case os of- "darwin" -> macDirs- "mingw32" -> winDirs- _ -> linuxDirs- where- linuxDirs :: IO [FilePath]- linuxDirs = do- home <- getHomeDirectory- pure- [ home </> ".local/share/fonts"- , "/usr/local/share/fonts"- , "/usr/share/fonts"- ]-- macDirs :: IO [FilePath]- macDirs = do- home <- getHomeDirectory- pure- [ home </> "Library/Fonts"- , "/Library/Fonts"- , "/System/Library/Fonts"- ]-- winDirs :: IO [FilePath]- winDirs = do- mRoot <- lookupEnv "SystemRoot"- let systemDir = fromMaybe "C:\\Windows" mRoot </> "Fonts"- mLocal <- lookupEnv "LOCALAPPDATA"- let userDirs =- maybe [] (\l -> [l </> "Microsoft" </> "Windows" </> "Fonts"]) mLocal- pure (userDirs ++ [systemDir])--isFontFile :: FilePath -> Bool-isFontFile path =- map toLower (takeExtension path) `elem` [".ttf", ".otf", ".ttc", ".otc"]---- ------------------------------------------------------------------------------ Family matching---- | Pick the highest-scoring file for @norm@ (a normalised family name).-bestMatch :: String -> [(String, FilePath)] -> Maybe FilePath-bestMatch norm files =- case [(score, path) | (stem, path) <- files, Just score <- [maximum (Nothing : map (`matchScore` stem) candidates)]] of- [] -> Nothing- scored ->- -- minimumBy keeps the first tie; descending scores prefer the best face.- let (_, best) = minimumBy (comparing (Down . fst)) scored- in Just best- where- candidates = norm : familyAliases norm--matchScore :: String -> String -> Maybe Int-matchScore "" _ = Nothing-matchScore norm stem- | stem == norm = Just 100- | otherwise =- case stripPrefix norm stem of- Nothing -> Nothing- Just t- | t `elem` regularTails -> Just 90- | t `elem` otherTails -> Just 70- | "variable" `isInfixOf` t -> Just 20- | otherwise -> Just 60---- | Style tails that indicate the regular weight of a family.-regularTails :: [String]-regularTails = ["regular", "r", "normal", "medium", "text"]---- | Style tails for non-regular weights; still worth preferring over an--- unrelated font, but a regular (or exact) match wins.-otherTails :: [String]-otherTails =- [ "bold"- , "italic"- , "light"- , "semibold"- , "semibolditalic"- , "extrabold"- , "thin"- , "black"- , "regularitalic"- , "bolditalic"- , "mediumitalic"- , "oblique"- ]---- | Windows ships @Consolas@ as @consola.ttf@ and @Courier New@ as--- @cour.ttf@, so those families need filename aliases that prefix-match--- differently than their family names.-familyAliases :: String -> [String]-familyAliases "consolas" = ["consola"]-familyAliases "couriernew" = ["cour"]-familyAliases _ = []---- | Expand a generic CSS family into concrete families to search in order.-expandGeneric :: String -> Maybe [String]-expandGeneric "monospace" =- Just- [ "DejaVu Sans Mono"- , "Liberation Mono"- , "Ubuntu Mono"- , "Noto Sans Mono"- , "Consolas"- , "Courier New"- ]-expandGeneric "sansserif" =- Just- [ "DejaVu Sans"- , "Liberation Sans"- , "Noto Sans"- , "Open Sans"- , "Helvetica Neue"- ]-expandGeneric "serif" =- Just- [ "DejaVu Serif"- , "Liberation Serif"- , "Noto Serif"- , "Times New Roman"- ]-expandGeneric _ = Nothing---- | Fold case, drop whitespace and separators, so family \/ file names can be--- compared loosely ("DejaVu Sans Mono" vs @DejaVuSansMono.ttf@).-normalize :: String -> String-normalize =- map toLower- . filter (\c -> not (isSpace c) && c /= '-' && c /= '_')
− lib/NanoUI/Sdl/Image.hs
@@ -1,70 +0,0 @@-module NanoUI.Sdl.Image- ( ImageAtlas- , newImageAtlas- , destroyImageAtlas- , syncImageAtlas- , lookupImage- )-where--import Control.Exception (mask_)-import Control.Monad (when)-import Data.IORef (IORef, newIORef, readIORef, writeIORef)-import Data.Word (Word8)-import Foreign.ForeignPtr (ForeignPtr, withForeignPtr)-import Foreign.Ptr (Ptr, castPtr, nullPtr)-import NanoUI.Testing (Context, atlasSnapshot, atlasTextureId)-import SDL3.Sys.Bindgen.Blendmode (sDL_BLENDMODE_BLEND)-import SDL3.Sys.Bindgen.Pixels (data SDL_PIXELFORMAT_RGBA32)-import SDL3.Sys.Bindgen.Render (SDL_Renderer, SDL_Texture, data SDL_TEXTUREACCESS_STATIC)-import SDL3.Sys.Bindgen.Runtime.PtrConst qualified as PtrConst-import SDL3.Sys.Render (createTextureSafe, destroyTexture, setTextureBlendMode, updateTextureSafe)---- A texture and its metadata have one lifetime; publish them together.-newtype ImageAtlas = ImageAtlas (IORef (Maybe AtlasTexture))--data AtlasTexture = AtlasTexture- { atTexture :: !(Ptr SDL_Texture)- , atGeneration :: !Int- }--newImageAtlas :: IO ImageAtlas-newImageAtlas = ImageAtlas <$> newIORef Nothing--destroyImageAtlas :: ImageAtlas -> IO ()-destroyImageAtlas (ImageAtlas ref) = mask_ $ do- old <- readIORef ref- writeIORef ref Nothing- mapM_ (destroyTexture . atTexture) old--syncImageAtlas :: Ptr SDL_Renderer -> ImageAtlas -> Context -> IO ()-syncImageAtlas ren atlas@(ImageAtlas ref) ctx = do- snap <- atlasSnapshot ctx- case snap of- Nothing -> pure ()- Just (w, h, pixels, gen) -> do- old <- readIORef ref- when (Just gen /= fmap atGeneration old) $- uploadAtlas ren atlas w h pixels gen--uploadAtlas ::- Ptr SDL_Renderer -> ImageAtlas -> Int -> Int -> ForeignPtr Word8 -> Int -> IO ()-uploadAtlas ren (ImageAtlas ref) w h pixels gen = mask_ $- withForeignPtr pixels $ \ptr -> do- tex <- createTextureSafe ren SDL_PIXELFORMAT_RGBA32 SDL_TEXTUREACCESS_STATIC (fromIntegral w) (fromIntegral h)- ok <-- if tex == nullPtr- then pure False- else do- _ <- setTextureBlendMode tex (fromIntegral sDL_BLENDMODE_BLEND)- uploaded <- updateTextureSafe tex (PtrConst.unsafeFromPtr nullPtr) (PtrConst.unsafeFromPtr (castPtr ptr)) (fromIntegral (w * 4))- if uploaded then pure True else destroyTexture tex >> pure False- when ok $ do- old <- readIORef ref- writeIORef ref (Just (AtlasTexture tex gen))- mapM_ (destroyTexture . atTexture) old--lookupImage :: ImageAtlas -> Int -> IO (Maybe (Ptr SDL_Texture))-lookupImage (ImageAtlas ref) tid- | tid == atlasTextureId = fmap atTexture <$> readIORef ref- | otherwise = pure Nothing
− lib/NanoUI/Sdl/Input.hs
@@ -1,325 +0,0 @@-{-# LANGUAGE OverloadedRecordDot #-}-{-# LANGUAGE NoFieldSelectors #-}---- | SDL3 event polling and waiting, and translation of SDL events into--- 'NanoUI.Input.Input'.-module NanoUI.Sdl.Input- ( SdlEvent (..)- , pollEvents- , waitEvent- , waitEventTimeout- , applyEvent- , isHardQuit- , isButtonEdge- ) where--import Data.Bits ((.&.))-import Data.IORef (readIORef)-import qualified Data.Text as T-import Data.Text (Text)-import qualified Data.Text.Foreign as TF-import Data.Word (Word32)-import Foreign.C.Types (CFloat)-import Foreign.Marshal.Alloc (alloca)-import Foreign.Ptr (Ptr, nullPtr)-import Foreign.Storable (Storable (..))-import GHC.Records.Compat (getField)-import SDL3.Sys.Bindgen.Runtime.CBool qualified as CBool-import SDL3.Sys.Bindgen.Runtime.PtrConst qualified as PtrConst-import NanoUI- ( Input (..)- , Key (..)- , Modifiers (..)- , DropEvent (..)- , DropType (..)- , V2 (..)- , appendInputKey- , v2Add- )-import NanoUI.Input (MouseButton (..), appendDropEvent, applyMouseButton)-import NanoUI.Sdl.Display (refreshEventType)-import SDL3.Sys.Bindgen.Events- ( SDL_Event (..)- , SDL_EventType (..)- , SDL_KeyboardEvent- , data SDL_EVENT_DROP_BEGIN- , data SDL_EVENT_DROP_COMPLETE- , data SDL_EVENT_DROP_FILE- , data SDL_EVENT_DROP_POSITION- , data SDL_EVENT_DROP_TEXT- , data SDL_EVENT_KEY_DOWN- , data SDL_EVENT_MOUSE_BUTTON_DOWN- , data SDL_EVENT_MOUSE_BUTTON_UP- , data SDL_EVENT_MOUSE_MOTION- , data SDL_EVENT_MOUSE_WHEEL- , data SDL_EVENT_QUIT- , data SDL_EVENT_TEXT_INPUT- , data SDL_EVENT_WINDOW_DISPLAY_SCALE_CHANGED- , data SDL_EVENT_WINDOW_EXPOSED- , data SDL_EVENT_WINDOW_PIXEL_SIZE_CHANGED- , data SDL_EVENT_WINDOW_RESIZED- , data SDL_EVENT_WINDOW_RESTORED- )-import SDL3.Sys.Events (pollEventSafe, waitEventSafe, waitEventTimeoutSafe)-import SDL3.Sys.Bindgen.Keycode- ( SDL_Keycode (..)- , SDL_Keymod (..)- , sDLK_BACKSPACE- , sDLK_DELETE- , sDLK_DOWN- , sDLK_END- , sDLK_ESCAPE- , sDLK_HOME- , sDLK_LEFT- , sDLK_RETURN- , sDLK_RIGHT- , sDLK_TAB- , sDLK_UP- , sDL_KMOD_ALT- , sDL_KMOD_CTRL- , sDL_KMOD_SHIFT- )-import SDL3.Sys.Bindgen.Mouse (sDL_BUTTON_LEFT, sDL_BUTTON_RIGHT)-import SDL3.Sys.Bindgen.Stdinc (Sint32 (..), Uint32 (..))-import SDL3.Sys.Keyboard (getModState)--data SdlEvent- = EvQuit- | EvResize Int Int- | EvDisplayScale- | EvKey Key Modifiers- | EvText Text Modifiers- | EvMouseMotion V2 Modifiers- | EvMousePress V2 Modifiers- | EvMouseRelease V2 Modifiers- | EvMouseRightPress V2 Modifiers- | EvMouseRightRelease V2 Modifiers- | EvScroll V2- | EvDrop DropEvent- | EvRefresh- | EvWindowRedraw- deriving (Eq, Show)---- | Drain every pending event, oldest first.-pollEvents :: IO [SdlEvent]-pollEvents =- alloca $ \(p :: Ptr SDL_Event) -> do- refreshTy <- readIORef refreshEventType- let drain acc = do- got <- pollEventSafe p- if got- then decodeEvent refreshTy p >>= \ev -> drain (maybe acc (: acc) ev)- else pure (reverse acc)- drain []--waitEvent :: IO (Maybe SdlEvent)-waitEvent =- alloca $ \p -> do- got <- waitEventSafe p- if got then readIORef refreshEventType >>= \ty -> decodeEvent ty p else pure Nothing--waitEventTimeout :: Int -> IO (Maybe SdlEvent)-waitEventTimeout ms =- alloca $ \p -> do- got <- waitEventTimeoutSafe p (fromIntegral ms)- if got then readIORef refreshEventType >>= \ty -> decodeEvent ty p else pure Nothing---- | Translate one SDL event, given the refresh event type; 'Nothing' for--- events the UI ignores.-decodeEvent :: Word32 -> Ptr SDL_Event -> IO (Maybe SdlEvent)-decodeEvent refreshTy p = do- Uint32 w <- peek p.type'- if refreshTy /= 0 && w == refreshTy- then pure (Just EvRefresh)- else case SDL_EventType (fromIntegral w) of- SDL_EVENT_QUIT -> pure (Just EvQuit)- SDL_EVENT_WINDOW_RESIZED -> Just <$> windowResized p- -- Pixel size changes are ignored here; syncDisplay re-queries logical size.- SDL_EVENT_WINDOW_PIXEL_SIZE_CHANGED -> pure (Just EvDisplayScale)- SDL_EVENT_WINDOW_DISPLAY_SCALE_CHANGED -> pure (Just EvDisplayScale)- -- The window manager damaged our window surface (occlusion, compositor- -- effects, restore). The backbuffer contents are gone; the next present- -- must be full or stale regions flash.- SDL_EVENT_WINDOW_EXPOSED -> pure (Just EvWindowRedraw)- SDL_EVENT_WINDOW_RESTORED -> pure (Just EvWindowRedraw)- SDL_EVENT_KEY_DOWN -> keyDown p- SDL_EVENT_TEXT_INPUT -> textInput p- SDL_EVENT_MOUSE_MOTION -> Just <$> mouseMotion p- SDL_EVENT_MOUSE_BUTTON_DOWN -> mouseButton p True- SDL_EVENT_MOUSE_BUTTON_UP -> mouseButton p False- SDL_EVENT_MOUSE_WHEEL -> Just <$> mouseWheel p- SDL_EVENT_DROP_FILE -> Just <$> dropEvent p DropFile- SDL_EVENT_DROP_TEXT -> Just <$> dropEvent p DropText- SDL_EVENT_DROP_BEGIN -> Just <$> dropEvent p DropBegin- SDL_EVENT_DROP_COMPLETE -> Just <$> dropEvent p DropComplete- SDL_EVENT_DROP_POSITION -> Just <$> dropEvent p DropPosition- _ -> pure Nothing--keyDown :: Ptr SDL_Event -> IO (Maybe SdlEvent)-keyDown p = do- ke <- peek p.key- let mods = keyModifiers ke- code = fromIntegral (getField @"key" ke :: SDL_Keycode) :: Word32- repeating = CBool.toBool (getField @"repeat" ke)- pure $- case mapSpecialKey code of- Just k- | not repeating || isRepeatableKey k -> Just (EvKey k mods)- | otherwise -> Nothing- Nothing- -- Ctrl chords produce no text-input event; report the printable key- -- symbol (SDL folds Shift into it, so Ctrl+Shift+= arrives as '+').- | modCtrl mods && code >= 32 && code <= 126 ->- Just (EvText (T.singleton (toEnum (fromIntegral code))) mods)- | otherwise -> Nothing--textInput :: Ptr SDL_Event -> IO (Maybe SdlEvent)-textInput p = do- te <- peek p.text- mods <- peekModifiers- let textPtr = PtrConst.unsafeToPtr (getField @"text" te)- if textPtr == nullPtr- then pure Nothing- else do- txt <- TF.peekCString textPtr- pure (if T.null txt then Nothing else Just (EvText txt mods))--mouseMotion :: Ptr SDL_Event -> IO SdlEvent-mouseMotion p = do- me <- peek p.motion- mods <- peekModifiers- let x = getField @"x" me :: CFloat- y = getField @"y" me :: CFloat- pure (EvMouseMotion (V2 (realToFrac x) (realToFrac y)) mods)--mouseButton :: Ptr SDL_Event -> Bool -> IO (Maybe SdlEvent)-mouseButton p down = do- be <- peek p.button- mods <- peekModifiers- let x = getField @"x" be :: CFloat- y = getField @"y" be :: CFloat- pos = V2 (realToFrac x) (realToFrac y)- btn = getField @"button" be- pure $- if btn == fromIntegral sDL_BUTTON_LEFT- then Just (if down then EvMousePress pos mods else EvMouseRelease pos mods)- else- if btn == fromIntegral sDL_BUTTON_RIGHT- then Just (if down then EvMouseRightPress pos mods else EvMouseRightRelease pos mods)- else Nothing--mouseWheel :: Ptr SDL_Event -> IO SdlEvent-mouseWheel p = do- we <- peek p.wheel- let x = getField @"x" we :: CFloat- y = getField @"y" we :: CFloat- pure (EvScroll (V2 (realToFrac x) (negate (realToFrac y))))--windowResized :: Ptr SDL_Event -> IO SdlEvent-windowResized p = do- we <- peek p.window- let Sint32 w = getField @"data1" we- Sint32 h = getField @"data2" we- pure (EvResize (fromIntegral w) (fromIntegral h))--dropEvent :: Ptr SDL_Event -> DropType -> IO SdlEvent-dropEvent p ty = do- de <- peek p.drop- let x = getField @"x" de :: CFloat- y = getField @"y" de :: CFloat- at = Just (V2 (realToFrac x) (realToFrac y))- pos =- case ty of- DropPosition -> at- DropFile -> at- DropText -> at- _ -> Nothing- dataPtr = PtrConst.unsafeToPtr (getField @"data'" de)- payload <-- if dataPtr == nullPtr- then pure ""- else TF.peekCString dataPtr- pure (EvDrop (DropEvent ty pos payload))--peekModifiers :: IO Modifiers-peekModifiers = modFromKeymod <$> getModState--modFromKeymod :: SDL_Keymod -> Modifiers-modFromKeymod km =- let m = word32 km- in Modifiers- { modShift = m .&. word32 sDL_KMOD_SHIFT /= 0- , modCtrl = m .&. word32 sDL_KMOD_CTRL /= 0- , modAlt = m .&. word32 sDL_KMOD_ALT /= 0- }--keyModifiers :: SDL_KeyboardEvent -> Modifiers-keyModifiers ke = modFromKeymod (getField @"mod" ke)--word32 :: Integral a => a -> Word32-word32 = fromIntegral--mapSpecialKey :: Word32 -> Maybe Key-mapSpecialKey k- | k == word32 sDLK_ESCAPE = Just KeyEscape- | k == word32 sDLK_RETURN = Just KeyEnter- | k == word32 sDLK_TAB = Just KeyTab- | k == word32 sDLK_BACKSPACE = Just KeyBackspace- | k == word32 sDLK_DELETE = Just KeyDelete- | k == word32 sDLK_LEFT = Just KeyLeft- | k == word32 sDLK_RIGHT = Just KeyRight- | k == word32 sDLK_UP = Just KeyUp- | k == word32 sDLK_DOWN = Just KeyDown- | k == word32 sDLK_HOME = Just KeyHome- | k == word32 sDLK_END = Just KeyEnd- | otherwise = Nothing--isRepeatableKey :: Key -> Bool-isRepeatableKey KeyBackspace = True-isRepeatableKey KeyDelete = True-isRepeatableKey KeyLeft = True-isRepeatableKey KeyRight = True-isRepeatableKey KeyUp = True-isRepeatableKey KeyDown = True-isRepeatableKey KeyHome = True-isRepeatableKey KeyEnd = True-isRepeatableKey _ = False--applyEvent :: Input -> SdlEvent -> Input-applyEvent inp ev =- case ev of- EvQuit -> inp- EvDisplayScale -> inp- EvResize _ _ -> inp- EvKey k mods -> inp {inputKeys = appendInputKey k (inputKeys inp), inputModifiers = mods}- EvText txt mods ->- inp {inputChars = inputChars inp <> txt, inputModifiers = mods}- EvMouseMotion pos mods ->- inp {inputMousePos = pos, inputModifiers = mods}- EvMousePress pos mods ->- (applyMouseButton MouseLeft True inp) {inputMousePos = pos, inputModifiers = mods}- EvMouseRelease pos mods ->- (applyMouseButton MouseLeft False inp) {inputMousePos = pos, inputModifiers = mods}- EvMouseRightPress pos mods ->- (applyMouseButton MouseRight True inp) {inputMousePos = pos, inputModifiers = mods}- EvMouseRightRelease pos mods ->- (applyMouseButton MouseRight False inp) {inputMousePos = pos, inputModifiers = mods}- EvScroll delta -> inp {inputScroll = v2Add (inputScroll inp) delta}- EvDrop dropEv -> inp {inputDrops = appendDropEvent dropEv (inputDrops inp)}- EvRefresh -> inp {inputWindowRedraw = True}- EvWindowRedraw -> inp {inputWindowRedraw = True}--isButtonEdge :: SdlEvent -> Bool-isButtonEdge ev =- case ev of- EvMousePress _ _ -> True- EvMouseRelease _ _ -> True- EvMouseRightPress _ _ -> True- EvMouseRightRelease _ _ -> True- _ -> False--isHardQuit :: SdlEvent -> Bool-isHardQuit ev =- case ev of- EvText txt mods -> (txt == "c" && modCtrl mods) || txt == "\ETX"- _ -> False
+ lib/NanoUI/Sdl/Internal/Children.hs view
@@ -0,0 +1,122 @@+-- | A session's further windows ('NanoUI.nativeWindow') under SDL: how to+-- open, draw and close one ("NanoUI.Runner.Windows" does the rest), and the+-- routing of SDL's single event queue to the windows its events are for.+module NanoUI.Sdl.Internal.Children+ ( SdlWindows (..)+ , newSdlWindows+ , afterFirstPass+ , sdlLoopWindows+ , decodeForWindow+ , routeEvents+ , syncFirstCursor+ ) where++import Control.Monad (forM_, unless, void, when)+import Data.IORef (writeIORef)+import Data.Word (Word32)+import NanoUI (whenM)+import NanoUI.Backend (Context, Input)+import NanoUI.Runner (LoopWindows (..), tryWithDrawingLock)+import NanoUI.Runner.Windows (WindowOps (..), Windows, afterMainPass, hasWindows, loopWindows, newWindows, openWindows)+import NanoUI.Sdl.Internal.Cursor (syncPointerCursor)+import NanoUI.Sdl.Internal.Display (ResizeWatches (..), pointerInWindow, watchResizes)+import NanoUI.Sdl.Internal.Input+import NanoUI.Sdl.Internal.Runner (resetRenderTextures, sdlDrawFrame)+import NanoUI.Sdl.Internal.Window (SdlEnv (..), SdlOptions, openChildWindow, refreshDisplayRate, sdlPacingMs, syncDisplay, windowZoom)+import SDL3.Sys.Bindgen.Stdinc (Uint32 (..))+import SDL3.Sys.Bindgen.Video (SDL_WindowID (..))+import SDL3.Sys.Video (getWindowID)++-- | A further SDL window: its environment, SDL id, and the action that+-- closes it.+data SdlChild = SdlChild+ { scEnv :: !SdlEnv+ , scId :: !Word32+ , scClose :: IO ()+ }++data SdlWindows = SdlWindows+ { swFirst :: !SdlEnv+ , swFirstId :: !Word32+ , swWindows :: !(Windows SdlChild SdlEvent)+ , swWatches :: !ResizeWatches+ -- ^ The session's resize watches, the first window's among them.+ }++-- | The further windows of the session whose first window is @first@. Each+-- has a resize watch from @watches@, which draws it while Windows' modal+-- size loop holds the event loop, as the first window's watch does.+newSdlWindows :: SdlOptions -> SdlEnv -> ResizeWatches -> IO SdlWindows+newSdlWindows opts first watches = (\wid ws -> SdlWindows first wid ws watches) <$> windowId first <*> newWindows ops+ where+ ops =+ WindowOps+ { -- Every further window takes its fonts and scale from the first.+ woOpen = \parentCtx settings -> do+ (ctx, env, close) <- openChildWindow opts first parentCtx settings+ (\wid -> (SdlChild env wid close, ctx)) <$> windowId env+ , woClose = scClose+ , woApplyEvent = applyEvent+ , woIsButtonEdge = isButtonEdge+ , woIsClose = (== EvCloseRequested)+ , woSync = \c ctx inp -> syncDisplay ctx (scEnv c) inp+ , woDraw = \c ctx view inp force -> sdlDrawFrame ctx view (scEnv c) inp force+ , woCursor = \c ctx inp -> syncCursorIn (scEnv c) ctx inp+ , woPacingMs = sdlPacingMs . scEnv+ -- A further window has vsync off, so its watch frames need no+ -- vsync pause.+ , woWatchResize = watchResizes watches . sdlWindow . scEnv+ }++-- | 'afterMainPass' under the drawing lock: a further window's frame drawn+-- by the loop and one drawn by its resize watch exclude each other, as the+-- first window's do.+afterFirstPass :: SdlWindows -> Context -> IO ()+afterFirstPass w ctx = void (tryWithDrawingLock (rwDrawing (swWatches w)) (afterMainPass (swWindows w) ctx))++-- | The windows for 'NanoUI.Runner.sdWindows', running their passes with+-- 'afterFirstPass'.+sdlLoopWindows :: SdlWindows -> LoopWindows+sdlLoopWindows w = (loopWindows (swWindows w)) {lwAfterPass = afterFirstPass w}++windowId :: SdlEnv -> IO Word32+windowId env = (\(SDL_WindowID (Uint32 w)) -> w) <$> getWindowID (sdlWindow env)++-- | A batch of a window's events in layout units, as each had them, after+-- noting what they mean for the window: a pointer seen, a render device+-- reset, which the frame it asks for answers by making the textures again,+-- or another display, whose refresh rate the window paces by from now on.+decodeForWindow :: SdlEnv -> [SdlEvent] -> IO [SdlEvent]+decodeForWindow env evs = do+ zoom <- windowZoom env+ when (hasPointerEvent evs) (writeIORef (sdlPointerSeen env) True)+ when (EvRenderDeviceReset `elem` evs) (resetRenderTextures env)+ when (EvDisplayChanged `elem` evs) (refreshDisplayRate env)+ pure (scaleEventPositions zoom evs)++-- | Keep the first window's events and queue the others' on their windows.+-- With none open, every event is the first window's, as in a session of+-- one; a close request there is followed by SDL's quit. With some open, the+-- first window's close request ends the session (SDL quits only after the+-- last window), events for every window go to each, and those for a window+-- just closed go nowhere.+routeEvents :: SdlWindows -> [(Word32, SdlEvent)] -> IO [SdlEvent]+routeEvents w evs = do+ kids <- openWindows (swWindows w)+ if null kids+ then pure [ev | (_, ev) <- evs, ev /= EvCloseRequested]+ else do+ forM_ kids $ \(c, queue) -> do+ let mine = [ev | (wid, ev) <- evs, wid == scId c || (wid == 0 && ev /= EvQuit && ev /= EvRefresh)]+ unless (null mine) $ decodeForWindow (scEnv c) mine >>= mapM_ queue+ pure [if ev == EvCloseRequested then EvQuit else ev | (wid, ev) <- evs, wid == 0 || wid == swFirstId w]++-- | Sync the cursor from the first window: from the window the pointer is+-- over only, while others are open.+syncFirstCursor :: SdlWindows -> Context -> Input -> IO ()+syncFirstCursor w ctx inp = do+ others <- hasWindows (swWindows w)+ if others then syncCursorIn (swFirst w) ctx inp else syncPointerCursor (sdlCursors (swFirst w)) ctx inp++syncCursorIn :: SdlEnv -> Context -> Input -> IO ()+syncCursorIn env ctx inp = whenM ((/= 0) <$> pointerInWindow (sdlWindow env)) $ syncPointerCursor (sdlCursors env) ctx inp
+ lib/NanoUI/Sdl/Internal/Chrome.hs view
@@ -0,0 +1,320 @@+-- | Support for windows that draw their own title bar. Title, size, mode and+-- maximizing work on any backend and live in the core+-- ('NanoUI.setWindowTitle', 'NanoUI.resizeWindow',+-- 'NanoUI.toggleMaximized', ...).+--+-- A window without the desktop's title bar ('DecorationsFrame' or+-- 'DecorationsNone') has no native caption buttons or drag bar. 'windowCaption'+-- replaces them: it draws the minimize, maximize, and close buttons, handles+-- minimize and maximize clicks directly, and registers the remaining title bar+-- spans and window edges for native drag and resize hit testing.+--+-- > titleBar :: NanoUI ()+-- > titleBar =+-- > rowWith (fillW . fixedH captionBarHeight . alignMiddle) $ do+-- > menus <- appMenus+-- > flex+-- > label "My App"+-- > flex+-- > closing <- windowCaption menus+-- > when closing quit+module NanoUI.Sdl.Internal.Chrome+ ( -- * The window+ windowResizable+ , WindowDecorations (..)+ , setWindowDecorations+ , setWindowDecorationsUi+ , setWindowShadow+ , setWindowShadowUi++ -- * A window that draws its own chrome+ , WindowChrome (..)+ , defaultWindowChrome+ , defaultResizeBorder+ , setWindowChrome+ , clearWindowChrome+ , clearWindowChromeUi++ -- * From a view+ , CaptionOptions (..)+ , defaultCaptionOptions+ , windowCaption+ , windowCaptionWith+ , setWindowChromeUi+ ) where++import Control.Monad (unless, void, when)+import Data.IntMap.Strict qualified as IM+import Data.IORef (readIORef, writeIORef)+import Data.Maybe (isNothing)+-- The constructor under 'SDL_HitTestResult', which the callback returns.+import Foreign.C.Types (CUInt (..))+import Foreign.Ptr (FunPtr, castFunPtr, castPtr, nullFunPtr, nullPtr)+import Foreign.Storable (peekElemOff)+import NanoUI+import NanoUI.Chrome+import NanoUI.Internal.Context (OverlayState (osPrevFloatingRects), getsOverlay)+import NanoUI.Monad (askContext)+import NanoUI.Sdl.Internal.Chrome.Types+import NanoUI.Sdl.Internal.Display (outPair)+import NanoUI.Sdl.Internal.Frame+import NanoUI.Sdl.Internal.Window (SdlEnv (..), windowZoom, withSdlEnv)+import SDL3.Sys.Bindgen.Video (SDL_HitTest (..), SDL_HitTestResult (..), SDL_WindowFlags)+import SDL3.Sys.Video qualified as SDL++--------------------------------------------------------------------------------+-- The window+--------------------------------------------------------------------------------++-- Everything here that makes Windows dispatch messages goes through the safe+-- binding rather than the unsafe one, as in "NanoUI.Sdl.Internal.WindowOptions".+-- Changing the decorations or the hit test runs the window procedure+-- synchronously, which calls the hit test below. A callback into the runtime+-- from inside an unsafe call cannot run and wedges the message pump.++-- | Whether the window may be resized at all.+windowResizable :: SdlEnv -> IO Bool+windowResizable env = hasFlag SDL.SDL_WINDOW_RESIZABLE <$> windowFlagsOf env++windowFlagsOf :: SdlEnv -> IO SDL_WindowFlags+windowFlagsOf = SDL.getWindowFlags . sdlWindow++-- | Change how much of the desktop's decoration the window keeps, from+-- whatever 'NanoUI.Backend.Sdl.sdlWindowDecorations' or an earlier call+-- gave it. Going back to 'DecorationsFull' also takes off whatever+-- 'setWindowChrome' put on the window: the desktop's own title bar is the+-- desktop's to answer for. Asking for the decorations the window has does+-- nothing, so a view may ask every frame. The sizing frame of+-- 'DecorationsFrame' goes only on a window that can be resized and is not+-- fullscreen, so asking for it again after either changed puts it on, or+-- takes it off, to suit.+setWindowDecorations :: SdlEnv -> WindowDecorations -> IO ()+setWindowDecorations env decorations = do+ framed <- framedWindow <$> windowFlagsOf env+ (old, oldFramed) <- readIORef (chromeDecorations st)+ unless (old == decorations && (decorations /= DecorationsFrame || oldFramed == framed)) $ do+ writeIORef (chromeDecorations st) (decorations, framed)+ when (decorations == DecorationsFull) (clearWindowChrome env)+ applyDecorations (sdlWindow env) decorations+ -- That set the shadow too.+ writeIORef (chromeShadow st) Nothing+ where+ st = sdlChromeState env++-- | Put the desktop's drop shadow under the window, or take it away: for a+-- 'DecorationsNone' window that wants one. A 'DecorationsFrame' window has+-- the desktop's shadow already. Windows only: elsewhere the compositor+-- decides, and this does nothing. Asking for the shadow last asked for does+-- nothing either.+setWindowShadow :: SdlEnv -> Bool -> IO ()+setWindowShadow env on = do+ old <- readIORef (chromeShadow st)+ unless (old == Just on) $ do+ writeIORef (chromeShadow st) (Just on)+ applyWindowShadow (sdlWindow env) on+ where+ st = sdlChromeState env++--------------------------------------------------------------------------------+-- A window that draws its own chrome+--------------------------------------------------------------------------------++-- | Register hit-test regions for a borderless window. The first call installs+-- the SDL hit-test callback on the window; subsequent calls only update the+-- stored regions, so a view can call this every frame for the cost of an+-- 'Data.IORef.IORef' write.+--+-- The rectangles are in layout coordinates and are scaled here by the window's+-- zoom to match the window coordinates used by the hit-test callback.+setWindowChrome :: SdlEnv -> WindowChrome -> IO ()+setWindowChrome env chrome = do+ zoom <- windowZoom env+ let scaled+ | zoom == 1 = chrome+ | otherwise =+ chrome+ { chromeDrag = map (scaleRect zoom) (chromeDrag chrome)+ , chromeResizeBorder = chromeResizeBorder chrome * zoom+ , chromeResizeTop = chromeResizeTop chrome * zoom+ }+ old <- readIORef (chromeRegions st)+ unless (old == scaled) $ writeIORef (chromeRegions st) scaled+ whenM (isNothing <$> readIORef (chromeCallback st)) $ do+ callback <- mkHitTest (hitTest st)+ writeIORef (chromeCallback st) (Just callback)+ void (SDL.setWindowHitTestSafe (sdlWindow env) (SDL_HitTest (castFunPtr callback)) nullPtr)+ where+ st = sdlChromeState env+ scaleRect z (Rect x y w h) = Rect (x * z) (y * z) (w * z) (h * z)++-- | Take the hit test off the window again: every part of it goes back to+-- being the application's.+clearWindowChrome :: SdlEnv -> IO ()+clearWindowChrome env = do+ void (SDL.setWindowHitTestSafe (sdlWindow env) (SDL_HitTest nullFunPtr) nullPtr)+ writeIORef (chromeRegions st) defaultWindowChrome+ clearChromeState st+ where+ st = sdlChromeState env++foreign import ccall "wrapper"+ mkHitTest :: HitTestCallback -> IO (FunPtr HitTestCallback)++-- | What is under the pointer, as far as the desktop is concerned: an edge+-- that resizes the window, a part of it that drags the window, or nothing in+-- particular, which is everything the view itself draws.+--+-- The edges are answered first, so the topmost pixels of a title bar resize+-- the window rather than reaching whatever is drawn there. That is the+-- bargain a window with its own chrome makes, and the reason+-- 'NanoUI.captionBarHeight' leaves room for it.+hitTest :: ChromeState -> HitTestCallback+hitTest st win area _ = do+ x <- fromIntegral <$> peekElemOff area 0+ y <- fromIntegral <$> peekElemOff area 1+ WindowChrome drag border top <- readIORef (chromeRegions st)+ (ok, pw, ph) <- outPair (SDL.getWindowSize (castPtr win))+ let edge+ -- With no edges at all, even a point in the desktop's frame outside+ -- the view is answered as part of it.+ | ok && (border > 0 || top > 0) =+ edgeHit (x < border) (x >= fromIntegral pw - border) (y < top) (y >= fromIntegral ph - border)+ | otherwise = SDL.SDL_HITTEST_NORMAL+ answer+ | edge /= SDL.SDL_HITTEST_NORMAL = edge+ | any (`rectContains` V2 x y) drag = SDL.SDL_HITTEST_DRAGGABLE+ | otherwise = SDL.SDL_HITTEST_NORMAL+ pure answer++-- | The @SDL_HitTestResult@ for an edge or corner, from the sides of the+-- window the point is near.+edgeHit :: Bool -> Bool -> Bool -> Bool -> SDL_HitTestResult+edgeHit left right top bottom+ | top && left = SDL.SDL_HITTEST_RESIZE_TOPLEFT+ | top && right = SDL.SDL_HITTEST_RESIZE_TOPRIGHT+ | top = SDL.SDL_HITTEST_RESIZE_TOP+ | bottom && right = SDL.SDL_HITTEST_RESIZE_BOTTOMRIGHT+ | bottom && left = SDL.SDL_HITTEST_RESIZE_BOTTOMLEFT+ | bottom = SDL.SDL_HITTEST_RESIZE_BOTTOM+ | left = SDL.SDL_HITTEST_RESIZE_LEFT+ | right = SDL.SDL_HITTEST_RESIZE_RIGHT+ | otherwise = SDL.SDL_HITTEST_NORMAL++--------------------------------------------------------------------------------+-- From a view+--------------------------------------------------------------------------------++-- | Draw the minimize, maximize, and close caption buttons and register the+-- remaining title bar area as the window's drag region.+--+-- @taken@ lists the rectangles of other interactive widgets in the title bar+-- (such as menu buttons or tabs); the spans of the bar between them, and+-- outside the floating panels over it, become draggable. The title bar is+-- assumed to span the full window width at the vertical position and height+-- of the caption buttons. On a resizable+-- borderless window, resize hit testing takes precedence along the outer edges;+-- when maximized, fullscreen, or non-resizable, edge resizing is disabled (and+-- dragging is also disabled in fullscreen).+--+-- On a natively decorated window ('DecorationsFull'), only the buttons are+-- drawn and no custom hit-test regions are registered. A frame that does not+-- call this takes the drag region and the edges away again+-- ('setWindowChromeUi').+--+-- Returns 'True' when the close button is clicked (minimize and maximize are+-- handled directly).+--+-- Outside an SDL session, the buttons still draw and dispatch core window+-- requests, and no drag region is registered.+windowCaption :: [Rect] -> NanoUI Bool+windowCaption = windowCaptionWith defaultCaptionOptions++-- | Options for 'windowCaptionWith': button styling and resize border widths.+data CaptionOptions = CaptionOptions+ { capButtons :: !CaptionConfig+ -- ^ How the three buttons are drawn.+ , capResizeBorder :: !Float+ -- ^ Resize hit-test thickness along the left, right, and bottom edges+ -- ('chromeResizeBorder'). Zero leaves those edges to the native sizing frame+ -- if present.+ , capResizeTop :: !Float+ -- ^ Resize hit-test thickness along the top edge ('chromeResizeTop').+ }+ deriving (Eq, Show)++-- | 'defaultCaptionConfig' buttons and 'defaultResizeBorder' edges.+defaultCaptionOptions :: CaptionOptions+defaultCaptionOptions =+ CaptionOptions+ { capButtons = defaultCaptionConfig+ , capResizeBorder = defaultResizeBorder+ , capResizeTop = defaultResizeBorder+ }++-- | 'windowCaption' with custom 'CaptionOptions'.+windowCaptionWith :: CaptionOptions -> [Rect] -> NanoUI Bool+windowCaptionWith opts taken = do+ width <- windowWidth+ -- Maximized and fullscreen come from the state every backend reports; only+ -- handing the drag region over needs the SDL session.+ win <- askWindow+ let maxed = winMaximized win+ fullscreen = winFullscreen win+ -- The close button's corner is the window's, and a window that fills+ -- the screen has square ones.+ cfg+ | maxed || fullscreen = (capButtons opts) {capCornerRadius = 0}+ | otherwise = capButtons opts+ (action, buttons) <- captionButtonsConfigured cfg maxed+ ctx <- askContext+ withSdlEnv () $ \env -> do+ flags <- windowFlagsOf env+ -- Floating panels over the bar (a window placed at the top, a tall+ -- modal), where they were last frame like the buttons: a press on one+ -- is the panel's, not a drag of the window.+ floats <- getsOverlay ctx (IM.elems . osPrevFloatingRects)+ let immovable = maxed || fullscreen || not (hasFlag SDL.SDL_WINDOW_RESIZABLE flags)+ when (hasFlag SDL.SDL_WINDOW_BORDERLESS flags) $+ setViewChrome+ env+ WindowChrome+ { chromeDrag =+ if fullscreen+ then []+ else dragSpans (Rect 0 (rectY buttons) width (rectH buttons)) (buttons : taken ++ floats)+ , chromeResizeBorder = if immovable then 0 else capResizeBorder opts+ , chromeResizeTop = if immovable then 0 else capResizeTop opts+ }+ case action of+ Just CaptionMinimize -> minimizeWindow+ Just CaptionToggleMaximize -> toggleMaximized+ _ -> pure ()+ pure (action == Just CaptionClose)++-- | Update the window's chrome hit-test regions from within a view.+-- 'windowCaption' calls this automatically when drawing standard caption+-- buttons; use this directly for custom title bar layouts. The regions hold+-- while the view hands them over every frame: after a frame whose view does+-- not, as when the title bar is no longer drawn, the window has none. A drag+-- region drags the window from under whatever is drawn over it, so leave out+-- floating panels and popups that can cover the title bar.+setWindowChromeUi :: WindowChrome -> NanoUI ()+setWindowChromeUi chrome = withSdlEnv () (`setViewChrome` chrome)++-- | 'setWindowChrome' for this frame's view ('setWindowChromeUi').+setViewChrome :: SdlEnv -> WindowChrome -> IO ()+setViewChrome env chrome = do+ setWindowChrome env chrome+ writeIORef (chromeFromView (sdlChromeState env)) True++-- | 'clearWindowChrome' from a view.+clearWindowChromeUi :: NanoUI ()+clearWindowChromeUi = withSdlEnv () clearWindowChrome++-- | 'setWindowDecorations' from a view.+setWindowDecorationsUi :: WindowDecorations -> NanoUI ()+setWindowDecorationsUi d = withSdlEnv () (`setWindowDecorations` d)++-- | 'setWindowShadow' from a view.+setWindowShadowUi :: Bool -> NanoUI ()+setWindowShadowUi on = withSdlEnv () (`setWindowShadow` on)
+ lib/NanoUI/Sdl/Internal/Chrome/Types.hs view
@@ -0,0 +1,93 @@+-- | Hit-test regions for custom window chrome, shared between the chrome API+-- and the SDL window lifecycle.+module NanoUI.Sdl.Internal.Chrome.Types+ ( WindowChrome (..)+ , defaultWindowChrome+ , defaultResizeBorder+ , HitTestCallback+ , ChromeState (..)+ , newChromeState+ , clearChromeState+ ) where++import Data.IORef (IORef, atomicModifyIORef', newIORef)+import Foreign.C.Types (CInt (..))+import Foreign.Ptr (FunPtr, Ptr, freeHaskellFunPtr)+import NanoUI (Rect (..))+import NanoUI.Sdl.Internal.Frame (WindowDecorations)+import SDL3.Sys.Bindgen.Video (SDL_HitTestResult (..))++-- | Hit-test regions for a borderless window. A natively decorated window does+-- not use this, since the window manager handles its title bar and resize+-- borders directly.+data WindowChrome = WindowChrome+ { chromeDrag :: ![Rect]+ -- ^ Client-area rectangles that act as a draggable title bar, in layout+ -- coordinates. Because the window manager handles the drag, these regions+ -- also support aero snap, double-click to maximize, and the system context+ -- menu. 'NanoUI.dragSpans' computes these rectangles from a title bar row+ -- and its interactive child widgets.+ , chromeResizeBorder :: !Float+ -- ^ Resize hit-test thickness along the left, right, and bottom edges.+ -- Set to zero when edge resizing is disabled (including when maximized).+ , chromeResizeTop :: !Float+ -- ^ Resize hit-test thickness along the top edge. Under+ -- 'NanoUI.Backend.Sdl.DecorationsFrame', the native sizing frame extends+ -- outside the left, right, and bottom edges, but not the top (because+ -- Windows paints a top frame inset as a caption). The top resize border must+ -- therefore live inside the client area.+ --+ -- When both 'chromeResizeBorder' and 'chromeResizeTop' are zero, all resize+ -- hit testing is disabled and any outer frame area is treated as normal+ -- client area.+ }+ deriving (Eq, Show)++-- | Empty chrome configuration with no drag regions and no resize borders.+defaultWindowChrome :: WindowChrome+defaultWindowChrome = WindowChrome [] 0 0++-- | Six layout units (wider than a standard 4px native border so it is easier+-- to grab inside the client area).+defaultResizeBorder :: Float+defaultResizeBorder = 6++-- | @SDL_HitTest@: the window, the point being tested (an @SDL_Point@ of two+-- @CInt@s), and the user data pointer registered with the callback.+type HitTestCallback = Ptr () -> Ptr CInt -> Ptr () -> IO SDL_HitTestResult++-- | Active hit-test state read by the SDL hit-test callback. Because the window+-- manager queries hit testing from inside the event pump before pointer events+-- reach the application, each frame writes the current regions here (converted+-- to window coordinates once when set) for the callback to read.+data ChromeState = ChromeState+ { chromeRegions :: !(IORef WindowChrome)+ , chromeCallback :: !(IORef (Maybe (FunPtr HitTestCallback)))+ , chromeFromView :: !(IORef Bool)+ -- ^ Whether a view handed the regions over in the frame being drawn, or+ -- else in the one before: they lapse after a frame whose view did not.+ , chromeDecorations :: !(IORef (WindowDecorations, Bool))+ -- ^ The decorations the window has, and whether it could have the sizing+ -- frame when they were put on ('NanoUI.Sdl.Internal.Frame.framedWindow'):+ -- asking for the same again does nothing.+ , chromeShadow :: !(IORef (Maybe Bool))+ -- ^ The shadow last asked for, or 'Nothing' since the decorations, which+ -- set it, last changed.+ }++-- | The state of a window opened with the given decorations, and whether it+-- opened able to have the sizing frame.+newChromeState :: WindowDecorations -> Bool -> IO ChromeState+newChromeState decorations framed =+ ChromeState+ <$> newIORef defaultWindowChrome+ <*> newIORef Nothing+ <*> newIORef False+ <*> newIORef (decorations, framed)+ <*> newIORef Nothing++-- | Release the marshalled callback. The session acquires this state before+-- the window and so releases it after the window is destroyed: nothing can+-- ask again once this has run.+clearChromeState :: ChromeState -> IO ()+clearChromeState st = atomicModifyIORef' (chromeCallback st) (Nothing,) >>= mapM_ freeHaskellFunPtr
+ lib/NanoUI/Sdl/Internal/Cursor.hs view
@@ -0,0 +1,119 @@+{-# OPTIONS_HADDOCK not-home #-}++-- | Own SDL system cursors and apply nano-ui cursor requests on the display thread.+module NanoUI.Sdl.Internal.Cursor+ ( SdlCursors (..)+ , initCursors+ , destroyCursors+ , syncPointerCursor+ , showCursorKind+ , sdlSystemCursor+ ) where++import Control.Monad (void, when)+import Data.IORef (IORef, modifyIORef', newIORef, readIORef)+import Data.Maybe (isJust)+import Foreign.Ptr (Ptr, nullPtr)+import NanoUI (Input (..))+import NanoUI.Backend (cursorFallback, syncCursorKind)+import NanoUI.Backend (Context, UiCursorKind (..), uiCursorKind)+import System.Environment (lookupEnv)+import System.IO (hPutStrLn, stderr)+import qualified SDL3.Sys.Bindgen.Mouse as Mouse+import SDL3.Sys.Mouse+ ( createSystemCursorSafe+ , destroyCursorSafe+ , getDefaultCursorSafe+ , hideCursorSafe+ , setCursorSafe+ , showCursorSafe+ )++-- | Session-owned cache of SDL system cursors and the cursor kind currently+-- shown on screen.+data SdlCursors = SdlCursors+ { scDefault :: Ptr Mouse.SDL_Cursor+ -- ^ The platform's default arrow, which SDL owns.+ , scSystem :: IORef [(Mouse.SDL_SystemCursor, Ptr Mouse.SDL_Cursor)]+ -- ^ System cursors created so far, each on first use. A NULL entry is one+ -- the platform could not create (headless and dummy video drivers have+ -- none) and is not retried.+ , scCurrent :: IORef UiCursorKind+ , scTrace :: Bool+ }++-- | Initialize the session's cursor cache from the platform default arrow.+initCursors :: IO SdlCursors+initCursors =+ SdlCursors+ <$> getDefaultCursorSafe+ <*> newIORef []+ <*> newIORef UiCursorDefault+ -- Debug aid, read once here so cursor changes stay allocation-free:+ -- NANO_CURSOR_TRACE, set to anything, logs every cursor change to stderr.+ <*> (isJust <$> lookupEnv "NANO_CURSOR_TRACE")++-- | Destroy the cursors this session created. SDL owns the default one.+destroyCursors :: SdlCursors -> IO ()+destroyCursors SdlCursors {scSystem} =+ mapM_ destroyCursorSafe . filter (/= nullPtr) . map snd =<< readIORef scSystem++-- | The SDL system cursor for @kind@ (or its 'cursorFallback'); 'Nothing'+-- for the default arrow. Platforms without one-way resize arrows show+-- two-way ones; SDL handles that.+sdlSystemCursor :: UiCursorKind -> Maybe Mouse.SDL_SystemCursor+sdlSystemCursor kind = case cursorFallback kind of+ UiCursorPointer -> Just Mouse.SDL_SYSTEM_CURSOR_POINTER+ UiCursorText -> Just Mouse.SDL_SYSTEM_CURSOR_TEXT+ UiCursorNsResize -> Just Mouse.SDL_SYSTEM_CURSOR_NS_RESIZE+ UiCursorEwResize -> Just Mouse.SDL_SYSTEM_CURSOR_EW_RESIZE+ UiCursorNwseResize -> Just Mouse.SDL_SYSTEM_CURSOR_NWSE_RESIZE+ UiCursorNeswResize -> Just Mouse.SDL_SYSTEM_CURSOR_NESW_RESIZE+ UiCursorNotAllowed -> Just Mouse.SDL_SYSTEM_CURSOR_NOT_ALLOWED+ UiCursorWait -> Just Mouse.SDL_SYSTEM_CURSOR_WAIT+ UiCursorProgress -> Just Mouse.SDL_SYSTEM_CURSOR_PROGRESS+ UiCursorCrosshair -> Just Mouse.SDL_SYSTEM_CURSOR_CROSSHAIR+ UiCursorMove -> Just Mouse.SDL_SYSTEM_CURSOR_MOVE+ UiCursorNResize -> Just Mouse.SDL_SYSTEM_CURSOR_N_RESIZE+ UiCursorNeResize -> Just Mouse.SDL_SYSTEM_CURSOR_NE_RESIZE+ UiCursorEResize -> Just Mouse.SDL_SYSTEM_CURSOR_E_RESIZE+ UiCursorSeResize -> Just Mouse.SDL_SYSTEM_CURSOR_SE_RESIZE+ UiCursorSResize -> Just Mouse.SDL_SYSTEM_CURSOR_S_RESIZE+ UiCursorSwResize -> Just Mouse.SDL_SYSTEM_CURSOR_SW_RESIZE+ UiCursorWResize -> Just Mouse.SDL_SYSTEM_CURSOR_W_RESIZE+ UiCursorNwResize -> Just Mouse.SDL_SYSTEM_CURSOR_NW_RESIZE+ _ -> Nothing++-- | The cursor for @kind@: its 'sdlSystemCursor', created on first use, or+-- the default arrow if the platform lacks it.+cursorFor :: SdlCursors -> UiCursorKind -> IO (Ptr Mouse.SDL_Cursor)+cursorFor SdlCursors {scDefault, scSystem} kind = case sdlSystemCursor kind of+ Nothing -> pure scDefault+ Just sys -> do+ c <- maybe (create sys) pure . lookup sys =<< readIORef scSystem+ pure (if c == nullPtr then scDefault else c)+ where+ create sys = do+ c <- createSystemCursorSafe sys+ c <$ modifyIORef' scSystem ((sys, c) :)++-- | Resolve the frame's desired pointer cursor and update the active SDL+-- cursor when it changes.+syncPointerCursor :: SdlCursors -> Context -> Input -> IO ()+syncPointerCursor cursors ctx inp = do+ want <- uiCursorKind ctx inp+ when (scTrace cursors) $ do+ cur <- readIORef (scCurrent cursors)+ when (want /= cur) $+ hPutStrLn stderr ("cursor: " ++ show want ++ " at " ++ show (inputMousePos inp))+ showCursorKind cursors want++-- | Show the cursor for @kind@ unless it is the one shown, or hide it for+-- 'UiCursorHidden' until another kind is shown ('syncCursorKind'). If even+-- the default arrow is NULL, SDL_SetCursor(NULL) just redraws the current+-- cursor.+showCursorKind :: SdlCursors -> UiCursorKind -> IO ()+showCursorKind cursors =+ syncCursorKind (scCurrent cursors)+ (\visible -> void (if visible then showCursorSafe else hideCursorSafe))+ (\kind -> void . setCursorSafe =<< cursorFor cursors kind)
+ lib/NanoUI/Sdl/Internal/Debug.hs view
@@ -0,0 +1,45 @@+-- | SDL display facts combined with the core frame-timing sampler.+module NanoUI.Sdl.Internal.Debug+ ( SdlDebugSnapshot (..)+ , traceFrame+ ) where++import Data.Text (Text, unpack)+import NanoUI.Internal.Debug (CoreDebugSnapshot (..))+import Text.Printf (printf)++-- | Published timing, font, renderer, and display information. Scale is+-- physical pixels per layout unit and refresh rate is in hertz.+data SdlDebugSnapshot = SdlDebugSnapshot+ { dbgCore :: !CoreDebugSnapshot+ , dbgScale :: !Float+ , dbgFontPath :: !FilePath+ , dbgRenderer :: !Text+ , dbgVsync :: !Bool+ , dbgRefreshHz :: !Int+ }+ deriving (Eq, Show)++-- | Per-refresh timing trace (NANO_FRAME_TRACE). Prints the snapshot's phase+-- EMAs so live-loop costs can be compared across builds. The snapshot+-- refreshes only while a view reads 'NanoUI.Backend.Sdl.askSdlDebug', so+-- nothing is printed otherwise.+traceFrame :: SdlDebugSnapshot -> IO ()+traceFrame s =+ printf+ "TRACE refreshHz=%3d rend=%s vsync=%d presentFps=%6.0f loopFps=%6.0f frameMs=%6.3f uiMs=%6.3f renderMs=%6.3f presentMs=%6.3f verts=%5d cmds=%2d presents=%d skips=%d\n"+ (dbgRefreshHz s)+ (unpack (dbgRenderer s))+ (fromEnum (dbgVsync s))+ (dbgPresentFps c)+ (dbgLoopFps c)+ (dbgFrameMs c)+ (dbgUiMs c)+ (dbgRenderMs c)+ (dbgPresentMs c)+ (dbgVerts c)+ (dbgCmds c)+ (dbgPresents c)+ (dbgSkips c)+ where+ c = dbgCore s
+ lib/NanoUI/Sdl/Internal/Dialog.hs view
@@ -0,0 +1,276 @@+-- | SDL3 native file dialogs.+--+-- These wrap SDL3's asynchronous dialog API (@SDL_ShowOpenFileDialog@,+-- @SDL_ShowSaveFileDialog@, and @SDL_ShowOpenFolderDialog@) into a+-- non-blocking, poll-based interface. Launching a dialog returns a+-- 'FileDialogId' immediately and the app keeps running its normal event loop;+-- poll the handle on later frames to observe completion.+--+-- Threading: SDL3 may invoke the dialog callback on a background thread, so+-- the callback here does little: it decodes the result, frees the FFI+-- buffers the launch allocated, records the outcome, and wakes the event+-- loop. All UI-affecting work ('markDirty', reclaiming focus) is deferred to+-- the thread that polls the result.+module NanoUI.Sdl.Internal.Dialog+ ( FileFilter (..)+ , FileDialogOptions (..)+ , defaultFileDialogOptions+ , FileDialogId+ , FileDialogResult (..)+ , openFileDialog+ , saveFileDialog+ , openFolderDialog+ , pollFileDialog+ , cancelFileDialog+ , askOpenFileDialog+ , askSaveFileDialog+ , askOpenFolderDialog+ , pollFileDialogUi+ , peekFileDialogUi+ , useFileDialog+ ) where++import Control.Exception (SomeException, onException, try)+import Control.Monad (unless, void, when, (>=>))+import Control.Monad.Trans.Resource (allocate, closeInternalState, createInternalState, runInternalState)+import Data.Foldable (for_)+import Data.Int (Int32)+import Data.IORef (IORef, atomicWriteIORef, newIORef, readIORef)+import Data.Text (Text)+import qualified Data.Text as T+import qualified GHC.Foreign as GHC+import GHC.IO.Encoding (utf8)+import Foreign.Marshal.Alloc (free)+import Foreign.Marshal.Array (newArray, peekArray0)+import Foreign.Marshal.Utils (maybePeek)+import Foreign.Ptr (FunPtr, Ptr, castFunPtr, castPtr, nullPtr)+import Foreign.StablePtr (castPtrToStablePtr, castStablePtrToPtr, deRefStablePtr, freeStablePtr, newStablePtr)+import NanoUI.Sdl.Internal.Display (pushRefreshEvent)+import NanoUI.Sdl.Internal.DialogState+import NanoUI.Sdl.Internal.Font (sdlPathEncoding)+import NanoUI.Sdl.Internal.Window (SdlEnv (..), askSdlEnv)+import NanoUI.Sdl.Internal.WindowOptions (queryWindowState)+import NanoUI.Backend (WindowState (..))++import NanoUI.Internal.Monad (NanoUI, askContext)+import NanoUI.Backend (Context, markDirty)+import Control.Monad.IO.Class (liftIO)+import NanoUI.Var (Var, readVar, writeVar)+import SDL3.Sys.Bindgen.Dialog (SDL_DialogFileCallback (..), SDL_DialogFileFilter (..))+import SDL3.Sys.Bindgen.Runtime.PtrConst qualified as PtrConst+import SDL3.Sys.Dialog+ ( showOpenFileDialogSafe+ , showOpenFolderDialogSafe+ , showSaveFileDialogSafe+ )+import SDL3.Sys.Video (raiseWindowSafe, restoreWindowSafe)+import System.IO (hPutStrLn, stderr)+import System.IO.Unsafe (unsafePerformIO)++-- | A file type filter shown in open/save dialogs.+data FileFilter = FileFilter+ { filterName :: !Text+ -- ^ Human-readable label, e.g. @"Haskell source"@.+ , filterPattern :: !Text+ -- ^ Semicolon-separated extension list, e.g. @"hs;lhs"@, or @"*"@.+ }+ deriving (Eq, Show)++-- | Common options for native file dialogs.+data FileDialogOptions = FileDialogOptions+ { dialogFilters :: ![FileFilter]+ -- ^ File filters (ignored by folder dialogs).+ , dialogDefaultLocation :: !(Maybe FilePath)+ -- ^ Starting folder or file.+ , dialogAllowMany :: !Bool+ -- ^ Allow selecting more than one entry (ignored by save dialogs).+ }+ deriving (Eq, Show)++-- | Sensible defaults: no filters, no default location, single selection.+defaultFileDialogOptions :: FileDialogOptions+defaultFileDialogOptions = FileDialogOptions [] Nothing False++-- | Opaque handle owned by the session that launched it. Passing it to a+-- different session does not consume its result or touch either window.+data FileDialogId = FileDialogId !(IORef Context) !(IORef FileDialogResult)+ deriving (Eq)++-- | Launch an open-file dialog, on the display thread. Returns a handle to+-- poll for completion.+openFileDialog :: SdlEnv -> FileDialogOptions -> IO FileDialogId+openFileDialog env = launchDialog env OpenDialog++-- | Launch a save-file dialog, on the display thread. Returns a handle to+-- poll for completion.+saveFileDialog :: SdlEnv -> FileDialogOptions -> IO FileDialogId+saveFileDialog env = launchDialog env SaveDialog++-- | Launch a folder-selection dialog, on the display thread. Returns a+-- handle to poll for completion.+openFolderDialog :: SdlEnv -> FileDialogOptions -> IO FileDialogId+openFolderDialog env = launchDialog env FolderDialog++-- | Poll a previously launched dialog without blocking, on the display+-- thread, since a finished dialog hands the window its focus back.+--+-- Each result is delivered exactly once: after the dialog completes, the+-- first poll that observes the finished state returns it and forgets the+-- handle, so later polls return 'FileDialogUnknown'.+pollFileDialog :: SdlEnv -> FileDialogId -> IO FileDialogResult+pollFileDialog env (FileDialogId owner ref)+ | owner /= sdlCachedCtx env = pure FileDialogUnknown+ | otherwise = do+ -- Only the poll that takes a finished result out delivers it.+ result <- takeResult ref+ unless (result == FileDialogPending || result == FileDialogUnknown) $ do+ -- The native dialog stole window focus; reclaim it so the app keeps+ -- receiving hover/motion/wheel events without an extra click. Only a+ -- minimized window is restored: SDL_RestoreWindow also takes a+ -- maximized one back to its normal size. Only a failed raise signals+ -- a possible focus failure.+ minimized <- winMinimized <$> queryWindowState (sdlWindow env) 1+ when minimized $ void (restoreWindowSafe (sdlWindow env))+ raised <- raiseWindowSafe (sdlWindow env)+ unless raised $+ hPutStrLn stderr "nano-ui: dialog completed but window raise failed; input may need a click"+ markDirty =<< readIORef (sdlCachedCtx env)+ pure result++-- | Stop tracking a dialog handle without waiting for the native dialog to+-- finish. The handle returns 'FileDialogUnknown' if polled afterwards.+-- The native dialog keeps running until the user dismisses it; its result is+-- discarded. Unlike the other operations here, this is safe from any thread.+cancelFileDialog :: SdlEnv -> FileDialogId -> IO ()+cancelFileDialog env (FileDialogId owner ref) =+ when (owner == sdlCachedCtx env) (atomicWriteIORef ref FileDialogUnknown)++-- | Open an open-file dialog from a view, owned by the open SDL session.+-- Outside a session the handle reports 'FileDialogFailed'.+askOpenFileDialog :: FileDialogOptions -> NanoUI FileDialogId+askOpenFileDialog = askDialog OpenDialog++-- | 'askOpenFileDialog' for a save-file dialog.+askSaveFileDialog :: FileDialogOptions -> NanoUI FileDialogId+askSaveFileDialog = askDialog SaveDialog++-- | 'askOpenFileDialog' for a folder dialog.+askOpenFolderDialog :: FileDialogOptions -> NanoUI FileDialogId+askOpenFolderDialog = askDialog FolderDialog++askDialog :: DialogKind -> FileDialogOptions -> NanoUI FileDialogId+askDialog kind opts = do+ ctx <- askContext+ askSdlEnv >>= liftIO . \case+ Just env -> launchDialog env kind opts+ Nothing -> FileDialogId <$> newIORef ctx <*> newIORef FileDialogFailed++-- | Consuming poll from a view, with the same focus restoration as+-- 'pollFileDialog'. Outside a session it consumes the handle's result+-- without touching a window.+pollFileDialogUi :: FileDialogId -> NanoUI FileDialogResult+pollFileDialogUi did@(FileDialogId _ ref) =+ liftIO . maybe (takeResult ref) (`pollFileDialog` did) =<< askSdlEnv++-- | Observe without consuming or restoring focus. Repeated peeks report the+-- same result until 'pollFileDialogUi' consumes it. Use polling for actions+-- that must happen only once, such as opening the selected file.+peekFileDialogUi :: FileDialogId -> NanoUI FileDialogResult+peekFileDialogUi (FileDialogId _ ref) = liftIO (readIORef ref)++-- | Poll the dialog held in a 'Var' once a frame. When it finishes, clear the+-- 'Var' and pass the chosen paths on; a cancel or failure just clears it. The+-- 'Var' is cleared first, so the callback may launch another dialog into it.+--+-- > useFileDialog openDlg (traverse_ openFile . listToMaybe)+-- > whenM (button "Open…") $+-- > writeVar openDlg . Just =<< askOpenFileDialog defaultFileDialogOptions+useFileDialog :: Var (Maybe FileDialogId) -> ([FilePath] -> NanoUI ()) -> NanoUI ()+useFileDialog dialog onPaths =+ readVar dialog >>= \pending -> for_ pending $+ pollFileDialogUi >=> \case+ FileDialogPending -> pure ()+ FileDialogSelected paths -> writeVar dialog Nothing >> onPaths paths+ _ -> writeVar dialog Nothing++data DialogKind = OpenDialog | SaveDialog | FolderDialog+ deriving (Eq)++launchDialog :: SdlEnv -> DialogKind -> FileDialogOptions -> IO FileDialogId+launchDialog env kind opts = do+ -- SDL reads the filters and the location until it runs the callback, which+ -- frees them. It takes the filters as UTF-8 everywhere, and the location+ -- as a path ('sdlPathEncoding'): UTF-8 on Windows too, not the code page+ -- Foreign.C.String would use.+ enc <- sdlPathEncoding+ st <- createInternalState+ flip onException (closeInternalState st) $ do+ let hold alloc = snd <$> allocate alloc free+ holdCStr e s = hold (GHC.newCString e s)+ rawFilters = if kind == FolderDialog then [] else dialogFilters opts+ (cs, filters, location) <- flip runInternalState st $ do+ cs <-+ mapM+ ( \(FileFilter n p) -> do+ cn <- holdCStr utf8 (T.unpack n)+ cp <- holdCStr utf8 (T.unpack p)+ pure (SDL_DialogFileFilter (PtrConst.unsafeFromPtr cn) (PtrConst.unsafeFromPtr cp))+ )+ rawFilters+ filters <- if null cs then pure nullPtr else hold (newArray cs)+ location <- maybe (pure nullPtr) (holdCStr enc) (dialogDefaultLocation opts)+ pure (cs, filters, location)+ result <- newIORef FileDialogPending+ let finish outcome = closeInternalState st >> completeResult result outcome >> pushRefreshEvent+ sp <- newStablePtr finish+ let userdata = castPtr (castStablePtrToPtr sp)+ win = sdlWindow env+ filtersConst = PtrConst.unsafeFromPtr filters+ nfilters = fromIntegral (length cs)+ locationConst = PtrConst.unsafeFromPtr location+ showDlg = case kind of+ OpenDialog ->+ showOpenFileDialogSafe dialogCallback userdata win filtersConst nfilters locationConst (dialogAllowMany opts)+ SaveDialog ->+ showSaveFileDialogSafe dialogCallback userdata win filtersConst nfilters locationConst+ FolderDialog ->+ showOpenFolderDialogSafe dialogCallback userdata win locationConst (dialogAllowMany opts)+ showDlg `onException` freeStablePtr sp+ pure (FileDialogId (sdlCachedCtx env) result)++-- | The callback every dialog shares, made once a process. A launch's+-- userdata carries what finishes it (releasing its buffers, recording the+-- outcome, waking the loop), so there is no callback to free while SDL might+-- still call it.+{-# NOINLINE dialogCallback #-}+dialogCallback :: SDL_DialogFileCallback+dialogCallback = unsafePerformIO (SDL_DialogFileCallback . castFunPtr <$> mkDialogCallback onResult)++-- | SDL invoked the callback: decode the file list, release the FFI buffers+-- the launch owned, record the outcome, and only then wake the (possibly+-- idle) event loop. The status must be visible before the wake, or the woken+-- frame polls 'FileDialogPending', skips, and the result waits for an+-- unrelated event. A null list pointer means SDL hit an error; a null first+-- entry means the user canceled.+onResult :: Ptr () -> Ptr () -> Int32 -> IO ()+onResult userdata filelist _filterIdx = do+ let launch = castPtrToStablePtr userdata+ finish <- deRefStablePtr launch+ freeStablePtr launch+ decoded <- try @SomeException $ do+ enc <- sdlPathEncoding+ maybePeek (peekArray0 nullPtr >=> traverse (GHC.peekCString enc)) (castPtr filelist)+ -- A handle abandoned with 'cancelFileDialog' keeps 'FileDialogUnknown'+ -- ('completeResult'). Always run 'finish' even if path decoding throws, so+ -- buffers are freed and the event loop wakes.+ finish $ case decoded of+ Left _ -> FileDialogFailed+ Right Nothing -> FileDialogFailed+ Right (Just []) -> FileDialogCancelled+ Right (Just ps) -> FileDialogSelected ps++-- SDL_DialogFileCallback is `void (*)(void *, const char * const *, int)`,+-- flattened to `void *` pointers at the FFI boundary.+foreign import ccall "wrapper"+ mkDialogCallback ::+ (Ptr () -> Ptr () -> Int32 -> IO ()) -> IO (FunPtr (Ptr () -> Ptr () -> Int32 -> IO ()))
+ lib/NanoUI/Sdl/Internal/DialogState.hs view
@@ -0,0 +1,34 @@+{-# OPTIONS_HADDOCK not-home #-}++-- | Thread-safe dialog completion and one-shot consumption, independent of SDL.+module NanoUI.Sdl.Internal.DialogState+ ( FileDialogResult (..)+ , takeResult+ , completeResult+ ) where++import Data.IORef (IORef, atomicModifyIORef')++-- | Lifecycle state of a launched file dialog.+data FileDialogResult+ = FileDialogPending+ -- ^ Still waiting for the user.+ | FileDialogCancelled+ -- ^ The user dismissed the dialog.+ | FileDialogFailed+ -- ^ SDL reported an error.+ | FileDialogSelected [FilePath]+ -- ^ The selected paths.+ | FileDialogUnknown+ -- ^ The handle was consumed, abandoned, or belongs to another session.+ deriving (Eq, Show)++-- | A pending result can be polled again; a completion is delivered once.+takeResult :: IORef FileDialogResult -> IO FileDialogResult+takeResult ref = atomicModifyIORef' ref $ \r ->+ (if r == FileDialogPending then r else FileDialogUnknown, r)++-- | Publish a completion unless the application abandoned the dialog.+completeResult :: IORef FileDialogResult -> FileDialogResult -> IO ()+completeResult ref result = atomicModifyIORef' ref $ \r ->+ (if r == FileDialogPending then result else r, ())
+ lib/NanoUI/Sdl/Internal/Display.hs view
@@ -0,0 +1,271 @@+{-# LANGUAGE OverloadedRecordDot #-}++-- | SDL window dimensions, display scale, refresh timing, and event-loop wake support.+--+-- FFI conventions. nano-ui-sdl calls SDL through the @sdl3@ bindings, and its+-- own C in @cbits@ through the @foreign import@s here and in+-- "NanoUI.Sdl.Internal.Font", "NanoUI.Sdl.Internal.Render",+-- "NanoUI.Sdl.Internal.Frame", "NanoUI.Sdl.Internal.Chrome" and+-- "NanoUI.Sdl.Internal.Dialog".+--+-- * Window, renderer, texture and font handles stay on the display thread,+-- the bound thread 'NanoUI.Sdl.Internal.Window.withSdl' runs the session+-- on, and do not outlive the session. The calls made from other threads+-- are the wake ('pushRefreshEvent') and+-- 'NanoUI.Sdl.Internal.Dialog.cancelFileDialog'.+-- * An import is @unsafe@ unless Haskell can run before it returns. Windows+-- sends the window messages from inside the calls that resize, move,+-- reframe or restyle it, change its hit test, or take the clipboard, and+-- SDL's window procedure then runs the resize watch or the hit test, which+-- are Haskell: a callback into the runtime from inside an unsafe call+-- cannot run and wedges the message pump. Those calls use the @sdl3@+-- bindings' @...Safe@ variants or a @safe@ import. 'pushRefreshEvent' is+-- safe for another reason: SDL_PushEvent waits for the lock SDL holds+-- while the resize watch runs.+-- * A callback made with a @wrapper@ import is freed with+-- 'freeHaskellFunPtr' when it is removed ('watchResizes'); the file+-- dialog's callback is made once per process, so SDL can never call a freed+-- one. The C objects nano-ui creates (render batch, text atlas) are+-- destroyed by the session that created them, and text SDL returns (the+-- clipboard) is freed with @SDL_free@.+module NanoUI.Sdl.Internal.Display+ ( queryWindowPixelDensity+ , scaleMoved+ , queryWindowRefreshHz+ , queryWindowLogicalSize+ , queryMouseWindowPos+ , pointerInWindow+ , queryWindowPosition+ , outPair+ , zoomWindow+ , windowPosCentered+ , ResizeWatches (..)+ , newResizeWatches+ , watchResizes+ , rethrowResizeFailure+ , waylandToplevel+ , sendWaylandSizeLimits+ , refreshEventType+ , initRefreshEvent+ , disableUnusedWindowEvents+ , pushRefreshEvent+ , tryPushRefreshEvent+ , querySystemAppearance+ ) where++import Control.Exception (SomeException, throwIO)+import Control.Exception qualified as E+import Control.Monad (void, when)+import Data.Foldable (traverse_)+import Data.IORef (IORef, newIORef, readIORef, writeIORef)+import Data.Maybe (isNothing)+import Foreign.C.Types (CBool (..), CFloat (..), CInt (..))+import Foreign.Marshal.Alloc (alloca, callocBytes)+import Foreign.Marshal.Utils (with)+import Foreign.Ptr (FunPtr, Ptr, freeHaskellFunPtr, nullPtr)+import Foreign.Storable (Storable, peek, poke, sizeOf)+import Data.Int (Int32)+import Data.Word (Word32)+import NanoUI (Appearance (..), Size (..), V2 (..), ifM, whenM)+import NanoUI.Monad ((<&&>))+import NanoUI.Runner (DrawingLock, newDrawingLock, tryWithDrawingLock)+import NanoUI.Sdl.Internal.Error (sdlFail)+import SDL3.Sys.Bindgen.Events (SDL_Event)+import SDL3.Sys.Bindgen.Stdinc (Uint32 (..))+import SDL3.Sys.Bindgen.Video (SDL_Window)+import SDL3.Sys.Bindgen.Video qualified as Video+import SDL3.Sys.Events (pushEventSafe, registerEvents)+import SDL3.Sys.Mouse (getMouseState)+import SDL3.Sys.Bindgen.Rect (SDL_Rect (..))+import SDL3.Sys.Video (getDisplayForWindow, getDisplayUsableBounds, getSystemTheme, getWindowPixelDensity, getWindowSize, setWindowPositionSafe, setWindowSizeSafe)+import System.IO.Unsafe (unsafePerformIO)++-- | Backbuffer pixels per window coordinate: the factor the retained+-- framebuffer, glyph rasterization and snapping need. This is not+-- @SDL_GetWindowDisplayScale@, which also folds in the desktop's content+-- scale. On Windows window coordinates are already pixels, so at 125%+-- scaling the display scale is 1.25 while the density is 1; sizing the+-- framebuffer by the display scale rendered 1.56x the window's pixels and+-- squeezed them back down on every present.+--+-- SDL works the density out from the width alone, as pixels over window+-- coordinates, so at a fractional scale it wanders with the width: between+-- neighbouring widths under several hundred, by more than 'scaleMoved'+-- tolerates, and each step of a resize would reload the fonts. It is taken+-- to the nearest 120th, the steps Wayland's fractional scales come in.+queryWindowPixelDensity :: Ptr SDL_Window -> IO Float+queryWindowPixelDensity win = (\s -> if s > 0 then fromIntegral (round (s * 120) :: Int) / 120 else 1) <$> getWindowPixelDensity win++-- | Whether a scale or zoom moved by more than float rounding does.+scaleMoved :: Float -> Float -> Bool+scaleMoved a b = abs (a - b) > 0.001++-- | Window size in window (logical) coordinates; 0x0 when SDL cannot say.+-- SDL_GetWindowSize already returns the window-coordinate size, not pixels.+-- Dividing by the display scale would shrink the logical size on DPI-scaled+-- displays, making the retained framebuffer too small.+queryWindowLogicalSize :: Ptr SDL_Window -> IO Size+queryWindowLogicalSize win = do+ (ok, w, h) <- outPair (getWindowSize win)+ pure (if ok then Size (fromIntegral w) (fromIntegral h) else Size 0 0)++-- | Pointer position relative to the window with mouse focus, in window+-- coordinates. Uses @SDL_GetMouseState@ rather than the global pointer ++-- window position: the latter is unreliable on Wayland (window position is not+-- exposed) and breaks hover/wheel targeting.+queryMouseWindowPos :: IO V2+queryMouseWindowPos = do+ (_, x, y) <- outPair getMouseState+ pure (V2 (realToFrac x) (realToFrac y))++-- | Call a native function that answers through two out pointers, and return+-- its result with both answers. The answers are not meaningful when the call+-- reports a failure.+outPair :: (Storable a, Storable b) => (Ptr a -> Ptr b -> IO r) -> IO (r, a, b)+outPair f = alloca $ \pa -> alloca $ \pb -> do+ r <- f pa pb+ (r,,) <$> peek pa <*> peek pb++-- | What the resize watches of a session's windows share.+data ResizeWatches = ResizeWatches+ { rwDrawing :: !DrawingLock+ -- ^ Held by every frame the loop draws, in any window, and by every+ -- watch frame. A watch can run inside an SDL call a frame makes (a window+ -- resized from the view), and the frame it would draw is then skipped.+ , rwFailure :: !(IORef (Maybe SomeException))+ -- ^ The first exception a watch frame threw. It cannot unwind past the C+ -- that called the watch: GHC would end the process there, past every+ -- handler and release. The loop's next pass throws it+ -- ('rethrowResizeFailure'), and no watch draws again.+ }++-- | A free drawing lock and no failure.+newResizeWatches :: IO ResizeWatches+newResizeWatches = ResizeWatches <$> newDrawingLock <*> newIORef Nothing++-- | Install a resize event watch scoped to a window (or any window when null)+-- whose action runs under the drawing lock and keeps its exception for the+-- loop; answer the action that removes it. Windows runs a modal loop while the+-- user drags the border, so the app event loop does not run; SDL still+-- delivers resize events to this watch.+watchResizes :: ResizeWatches -> Ptr SDL_Window -> IO () -> IO (IO ())+watchResizes rws win frame = do+ fp <- mkResizeCb $ whenM (isNothing <$> readIORef (rwFailure rws)) $+ E.handle (\(e :: SomeException) -> writeIORef (rwFailure rws) (Just e)) $+ void (tryWithDrawingLock (rwDrawing rws) frame)+ handle <- installResizeWatchC win fp+ when (handle == nullPtr) $ freeHaskellFunPtr fp >> sdlFail "SDL_AddEventWatch failed"+ pure (removeResizeWatchC handle >> freeHaskellFunPtr fp)++-- | Throw the exception a watch frame threw, if any, on the loop's thread.+rethrowResizeFailure :: ResizeWatches -> IO ()+rethrowResizeFailure rws = readIORef (rwFailure rws) >>= traverse_ throwIO++-- | The event 'pushRefreshEvent' sends, filled in once by 'initRefreshEvent',+-- so a push does not allocate.+{-# NOINLINE refreshEvent #-}+refreshEvent :: Ptr SDL_Event+refreshEvent = unsafePerformIO (callocBytes (sizeOf (undefined :: SDL_Event)))++-- | The user event type that wakes the event loop, registered once per+-- process by 'initRefreshEvent'; 0 until then.+refreshEventType :: IO Word32+refreshEventType = (\(Uint32 ty) -> ty) <$> peek refreshEvent.type'++initRefreshEvent :: IO Bool+initRefreshEvent =+ ifM ((/= 0) <$> refreshEventType) (pure True) $ do+ ty <- registerEvents 1+ poke refreshEvent.type' (Uint32 ty)+ pure (ty /= 0)++-- | Wake the event loop from any thread.+--+-- The push is a safe foreign call. SDL_PushEvent waits for the lock SDL+-- holds while it runs event watches, and the resize watch+-- ('watchResizes') runs Haskell. Pushed from a worker thread as an+-- unsafe call, it would keep the capability that watch is waiting for+-- while it waits for the lock the watch holds, and the program would hang.+pushRefreshEvent :: IO ()+pushRefreshEvent = void tryPushRefreshEvent++-- | 'pushRefreshEvent', answering whether the event was queued: not before+-- 'initRefreshEvent', nor when SDL's queue is full. As the session's wake+-- action it runs once for a run of wakes until the loop takes them, and not+-- for the loop's own dirty marks; a push that fails lets the next wake try+-- again ('NanoUI.Backend.setWakeLoopChecked').+tryPushRefreshEvent :: IO Bool+tryPushRefreshEvent = ((/= 0) <$> refreshEventType) <&&> pushEventSafe refreshEvent++-- | Whether the pointer is over the window (SDL's mouse focus). Once it has+-- left, 'queryMouseWindowPos' still answers the last position inside.+foreign import ccall unsafe "nano_ui_pointer_in_window"+ pointerInWindow :: Ptr SDL_Window -> IO CBool++-- | The window's top-left corner in desktop coordinates, through two out+-- pointers, and whether the desktop reports it: Wayland does not, though+-- SDL answers a position there too.+foreign import ccall unsafe "nano_ui_window_position"+ queryWindowPosition :: Ptr SDL_Window -> Ptr CInt -> Ptr CInt -> IO CBool++-- | Vertical refresh rate of the window's current display mode, in Hz+-- (0 when unavailable), fractions kept: 59.94 Hz is not 59.+foreign import ccall unsafe "nano_ui_window_refresh_rate"+ queryWindowRefreshHz :: Ptr SDL_Window -> IO CFloat++-- | Whether the window is a shown Wayland toplevel SDL made itself (not+-- libdecor's), whose size limits nano-ui sends rather than SDL: SDL would+-- also clamp every configure to them, and a configure it clamps back to the+-- current size is never committed, which stalls a tiling compositor's resize.+-- See @nano_ui_display.c@.+foreign import ccall unsafe "nano_ui_wayland_toplevel"+ waylandToplevel :: Ptr SDL_Window -> IO CBool++-- | Send a 'waylandToplevel' window's minimum and maximum width and height, in+-- window coordinates, zero for none. SDL replaces them with its own on every+-- configure, so they are sent again before each present. A window that cannot+-- be resized, or is fullscreen, keeps SDL's.+foreign import ccall unsafe "nano_ui_wayland_size_limits"+ sendWaylandSizeLimits :: Ptr SDL_Window -> Int32 -> Int32 -> Int32 -> Int32 -> IO ()++foreign import ccall "wrapper"+ mkResizeCb :: IO () -> IO (FunPtr (IO ()))++foreign import ccall safe "nano_ui_install_resize_watch"+ installResizeWatchC :: Ptr SDL_Window -> FunPtr (IO ()) -> IO (Ptr ())++foreign import ccall safe "nano_ui_remove_resize_watch"+ removeResizeWatchC :: Ptr () -> IO ()++-- | Suppress SDL window events that nano-ui does not consume so hover hit+-- testing and window drags do not queue redundant events.+foreign import ccall unsafe "nano_ui_disable_unused_window_events"+ disableUnusedWindowEvents :: IO ()++-- | Grow a window just opened at a logical size by the UI zoom, as far as+-- the usable area of its display allows, and centre it again.+zoomWindow :: Ptr SDL_Window -> Size -> Float -> IO ()+zoomWindow win (Size w h) zoom = do+ display <- getDisplayForWindow win+ -- Left empty, and so not a limit, when SDL cannot say.+ usable <- with (SDL_Rect 0 0 0 0) $ \rp -> getDisplayUsableBounds display rp >> peek rp+ let fit want avail = if avail > 0 then min want (fromIntegral avail) else want+ zw = fit (w * zoom) usable.w+ zh = fit (h * zoom) usable.h+ -- Safe calls: Windows sends the window its size and position messages+ -- from inside both, and SDL's window procedure runs the resize watch.+ void $ setWindowSizeSafe win (round zw) (round zh)+ void $ setWindowPositionSafe win windowPosCentered windowPosCentered++-- | SDL_WINDOWPOS_CENTERED: the centring mask with display 0.+windowPosCentered :: Int32+windowPosCentered = fromIntegral Video.sDL_WINDOWPOS_CENTERED_MASK++-- | The desktop's light or dark setting, or 'Nothing' if SDL cannot tell.+-- Cheap: SDL caches the value from its theme-change event.+querySystemAppearance :: IO (Maybe Appearance)+querySystemAppearance =+ getSystemTheme >>= \case+ Video.SDL_SYSTEM_THEME_LIGHT -> pure (Just AppearanceLight)+ Video.SDL_SYSTEM_THEME_DARK -> pure (Just AppearanceDark)+ _ -> pure Nothing
+ lib/NanoUI/Sdl/Internal/Env.hs view
@@ -0,0 +1,135 @@+-- | The native resources and per-window state of an SDL session+-- ('SdlEnv'), with the records it keeps of the retained frame ('Retain')+-- and of vertical sync ('PresentProbe'). "NanoUI.Sdl.Internal.Window"+-- opens and closes them.+module NanoUI.Sdl.Internal.Env+ ( SdlEnv (..)+ , PresentProbe (..)+ , Retain (..)+ , emptyRetain+ , dropRetainRef+ ) where++import Control.Monad (unless)+import Data.Int (Int32)+import Data.IORef (IORef, readIORef, writeIORef)+import Data.Text (Text)+import Foreign.Ptr (Ptr, nullPtr)+import NanoUI.Internal.Context (Context)+import NanoUI.Internal.Debug (DebugSamplerRef)+import NanoUI.Sdl.Internal.Chrome.Types (ChromeState)+import NanoUI.Sdl.Internal.Cursor (SdlCursors)+import NanoUI.Sdl.Internal.Debug (SdlDebugSnapshot)+import NanoUI.Sdl.Internal.Font (SdlFontCache)+import NanoUI.Sdl.Internal.Image (ImageAtlas)+import NanoUI.Sdl.Internal.Input (TextInputSync)+import NanoUI.Sdl.Internal.NanoUIFont (NanoUIFont)+import NanoUI.Sdl.Internal.Render (RenderBatch)+import SDL3.Sys.Bindgen.Render (SDL_Renderer, SDL_Texture)+import SDL3.Sys.Bindgen.Video (SDL_Window)+import SDL3.Sys.Blendmode (SDL_BlendMode)+import SDL3.Sys.Render (destroyTexture)++-- | Native resources owned by a 'NanoUI.Backend.Sdl.withSdl'+-- callback. Window, renderer, and font handles must stay on the display+-- thread and must not outlive the callback. Use the supplied context, which+-- contains this environment as host data.+data SdlEnv = SdlEnv+ { sdlWindow :: Ptr SDL_Window+ , sdlRenderer :: Ptr SDL_Renderer+ , sdlRendererName :: !Text+ , sdlHasGpu :: !Bool+ -- ^ Whether 'sdlRenderer' is backed by SDL 3.4's @"gpu"@ device.+ , sdlBatch :: RenderBatch+ , sdlFontRequestRef :: !(IORef NanoUIFont)+ , sdlFontAppliedRef :: !(IORef NanoUIFont)+ , sdlForcedScale :: !(Maybe Float)+ -- ^ NANO_FORCE_SCALE override of the pixel density, read at startup.+ , sdlScaleRef :: IORef Float+ -- ^ Backbuffer pixels per layout unit: the pixel density times the zoom.+ , sdlUiScaleRef :: !(IORef Float)+ -- ^ The requested UI scale; see 'NanoUI.Backend.Sdl.sdlAppUiScale'.+ , sdlPointerSeen :: !(IORef Bool)+ -- ^ Whether a pointer event has arrived, so the input's position, which+ -- the events set in layout units, can be trusted over a query.+ , sdlImages :: ImageAtlas+ , sdlCursors :: SdlCursors+ , sdlDebug :: DebugSamplerRef+ , sdlDebugPublished :: IORef (Maybe SdlDebugSnapshot)+ , sdlFrameTrace :: !Bool+ -- ^ Whether @NANO_FRAME_TRACE@ was set when the session opened.+ , sdlRetain :: IORef Retain+ , sdlLastPresented :: IORef Bool+ , sdlVsync :: !Bool+ , sdlRefreshPeriod :: !Double+ -- ^ The refresh period of the window's display when it opened, in+ -- seconds; 'sdlRefreshPeriodRef' follows it to other displays.+ , sdlRefreshPeriodRef :: !(IORef Double)+ -- ^ The refresh period of the window's current display, in seconds, read+ -- again when the window moves to another display or the display's mode+ -- changes ('NanoUI.Sdl.Internal.Pacing.refreshDisplayRate').+ , sdlPresentProbe :: !(IORef PresentProbe)+ -- ^ Whether presents wait for vertical sync as 'sdlVsync' asks+ -- ('NanoUI.Sdl.Internal.Pacing.notePresent').+ , sdlContinuous :: !Bool+ , sdlTransparent :: !(Maybe (SDL_BlendMode, SDL_BlendMode))+ -- ^ For a transparent window, the blend modes for drawing and for+ -- presenting the retained frame; 'Nothing' when opaque. See+ -- 'NanoUI.Sdl.Internal.Window.transparentBlends'.+ , sdlCachedCtx :: !(IORef Context)+ , sdlFontCache :: !SdlFontCache+ , sdlChromeState :: !ChromeState+ -- ^ What a borderless window's own title bar is for; see+ -- "NanoUI.Sdl.Internal.Chrome".+ , sdlTextInput :: !TextInputSync+ -- ^ The focused-field state last sent to SDL's text input; updated each+ -- drawn frame.+ , sdlSizeLimits :: !(Maybe (IORef (Int32, Int32, Int32, Int32)))+ -- ^ On a 'NanoUI.Sdl.Internal.Display.waylandToplevel' window, its+ -- minimum and maximum width and height in window coordinates (zero for+ -- none), which nano-ui sends to the compositor before each present+ -- instead of giving them to SDL. 'Nothing' elsewhere, where SDL keeps+ -- them.+ , sdlSizeLimitsSent :: !(IORef Bool)+ -- ^ Whether the limits last sent from 'sdlSizeLimits' were any, so none+ -- are sent again only to clear them.+ }++-- | What a session with 'sdlVsync' has seen of its presents. A driver can+-- turn vertical sync off whatever the application asks, and then a present+-- returns at once; a loop that trusted it to wait would draw an animation+-- as fast as it can.+data PresentProbe+ = PresentProbe !Double !Int+ -- ^ When the last present returned ('GHC.Clock.getMonotonicTime'), and+ -- how many presents in a row came less than half a refresh after the one+ -- before.+ | VsyncIgnored+ -- ^ 'NanoUI.Sdl.Internal.Pacing.vsyncProbeFrames' presents in a row came+ -- that soon: presents do not wait, and the session paces animation by+ -- time instead.+ deriving (Eq, Show)++-- | The retained framebuffer. The texture is allocated in blocks larger than+-- the window, so a resize drag reuses it instead of creating a render target+-- per pixel of movement; only the top-left used area is drawn and presented.+data Retain = Retain+ { retainTexture :: !(Ptr SDL_Texture)+ , retainCapW :: !Int+ , retainCapH :: !Int+ -- ^ The texture's allocated size in pixels.+ , retainW :: !Int+ , retainH :: !Int+ -- ^ The pixel size the last frame used.+ , retainScale :: !Float+ }++-- | Empty retained framebuffer state before allocation or after teardown.+emptyRetain :: Retain+emptyRetain = Retain nullPtr 0 0 0 0 0++-- | Destroy the retained texture in a reference, if any, and reset it.+dropRetainRef :: IORef Retain -> IO ()+dropRetainRef ref = do+ tex <- retainTexture <$> readIORef ref+ unless (tex == nullPtr) $ writeIORef ref emptyRetain >> destroyTexture tex
+ lib/NanoUI/Sdl/Internal/Error.hs view
@@ -0,0 +1,31 @@+{-# OPTIONS_HADDOCK not-home #-}++-- | SDL failures reported with SDL's own explanation of them.+module NanoUI.Sdl.Internal.Error+ ( sdlErrorText+ , sdlFail+ , withSdlError+ ) where++import Foreign.Ptr (nullPtr)+import GHC.Foreign qualified as GHC+import GHC.IO.Encoding (utf8)+import SDL3.Sys.Bindgen.Runtime.PtrConst qualified as PtrConst+import SDL3.Sys.Error (getError)++-- | The calling thread's last SDL error message (@SDL_GetError@), empty when+-- SDL has set none.+sdlErrorText :: IO String+sdlErrorText = do+ p <- PtrConst.unsafeToPtr <$> getError+ if p == nullPtr then pure "" else GHC.peekCString utf8 p++-- | A message with SDL's last error appended after a colon, or the message+-- alone when SDL has set none.+withSdlError :: String -> IO String+withSdlError what = sdlErrorText >>= \e -> pure (if null e then what else what ++ ": " ++ e)++-- | Throw an 'IOError' for a failed SDL call, naming the call and appending+-- SDL's last error.+sdlFail :: String -> IO a+sdlFail what = ioError . userError =<< withSdlError what
+ lib/NanoUI/Sdl/Internal/Font.hs view
@@ -0,0 +1,164 @@+-- | Desktop SDL_ttf font cache, system fallback discovery, bold-face lookup,+-- and SDL_Renderer glyph atlas integration built over "NanoUI.Ttf.Internal.Font".+module NanoUI.Sdl.Internal.Font+ ( FontSource (..)+ , withTtf+ , fontSourceLabel+ , embeddedFontSource+ , newGlyphAtlas+ , destroyGlyphAtlas+ , dropGlyphTextures+ , glyphAtlasHandle+ , sdlPathEncoding+ , SdlFontCache+ , newSdlFontCache+ , destroySdlFontCache+ , sdlFontCacheSource+ , sdlFontCacheMonoSource+ , withSdlFontCache+ ) where++import Control.Exception (IOException, catch)+import Control.Monad (forM, when)+import Data.ByteString qualified as BS+import Data.ByteString.Short qualified as SBS+import Data.IORef (IORef, modifyIORef', newIORef, readIORef, writeIORef)+import Data.Map.Strict qualified as Map+import Foreign.C.Types (CBool (..), CFloat (..))+import Foreign.Ptr (Ptr, nullPtr)+import GHC.Foreign qualified as GHC+import GHC.IO.Encoding (TextEncoding, getFileSystemEncoding, mkTextEncoding)+import NanoUI.Sdl.Internal.Font.Search (boldFaceCandidates, searchFontFamilies)+import NanoUI.Ttf.Internal.Font+ ( AtlasOps (..)+ , FontHooks (..)+ , FontSource (..)+ , GlyphAtlas (..)+ , SdlFontCache (..)+ , destroyGlyphAtlas+ , destroySdlFontCache+ , embeddedFontSource+ , fontSourceLabel+ , glyphAtlasHandle+ , sdlFontCacheMonoSource+ , sdlFontCacheSource+ , ttfCloseFont+ , ttfIsBoldOf+ , ttfOpenFont+ , withSdlFontCache+ )+import NanoUI.Ttf.Internal.Font qualified as Ttf+import NanoUI.Ttf.Internal.Support (CoveragePool, closeCoveragePool, ensurePoolCoverage, newCoveragePool)+import SDL3.Sys.Bindgen.Render (SDL_Renderer)+import System.IO.Unsafe (unsafePerformIO)+import System.Info (os)++-- | Create a desktop SDL_Renderer-backed glyph atlas.+newGlyphAtlas :: Ptr SDL_Renderer -> IO GlyphAtlas+newGlyphAtlas ren = do+ atlas <- textAtlasCreate ren+ when (atlas == nullPtr) $ fail "nano_ui_text_atlas_create failed (glyph)"+ Ttf.newGlyphAtlas+ AtlasOps+ { aoHandle = atlas+ , aoDestroy = textAtlasDestroy atlas+ , aoReset = textAtlasReset atlas+ , aoInsertSurface = textAtlasInsertSurface atlas+ }++-- | Destroy the glyph pages' textures after a render device reset, scheduling+-- an atlas reset at the next frame start.+dropGlyphTextures :: SdlFontCache -> IO ()+dropGlyphTextures cache = do+ let ga = sfcGlyphAtlas cache+ textAtlasDropTextures (aoHandle (gaOps ga))+ writeIORef (gaFull ga) True++-- | Bracket an action with SDL_ttf initialisation, closing desktop coverage+-- probes before @TTF_Quit@.+withTtf :: IO a -> IO a+withTtf = Ttf.withTtf desktopHooks++-- | Open the base sans and mono fonts at the pixel density with desktop+-- fallback coverage and bold-face discovery enabled.+newSdlFontCache :: FontSource -> FontSource -> GlyphAtlas -> Float -> IORef Float -> IO SdlFontCache+newSdlFontCache sans mono ga basePt scaleRef = do+ boldFacesRef <- newIORef Map.empty+ let hooks = desktopHooks {fhBoldSource = findBoldFace boldFacesRef}+ Ttf.newSdlFontCache hooks sans mono ga basePt scaleRef++desktopHooks :: FontHooks+desktopHooks =+ FontHooks+ { fhEnsureCoverage = ensurePoolCoverage desktopCoveragePool+ , fhBoldSource = \_ _ -> pure Nothing+ , fhPathEncoding = sdlPathEncoding+ , fhOnTtfQuit = closeCoveragePool desktopCoveragePool+ }++-- | The encoding of paths SDL takes and gives: UTF-8 (with roundtrip) on+-- Windows, and the file system encoding elsewhere.+sdlPathEncoding :: IO TextEncoding+sdlPathEncoding+ | os == "mingw32" = mkTextEncoding "UTF-8//ROUNDTRIP"+ | otherwise = getFileSystemEncoding++findBoldFace :: IORef (Map.Map FilePath (Maybe FontSource)) -> FontSource -> IO (Ptr ()) -> IO (Maybe FontSource)+findBoldFace boldFacesRef src getRegular = case src of+ FontFromMemory {} -> pure Nothing+ FontFromPath path ->+ Map.lookup path <$> readIORef boldFacesRef >>= \case+ Just known -> pure known+ Nothing -> do+ regular <- getRegular+ found <- fmap FontFromPath <$> (firstM (isBoldOf regular) =<< boldFaceCandidates path)+ found <$ modifyIORef' boldFacesRef (Map.insert path found)+ where+ isBoldOf regular candidate = do+ face <- Ttf.openFontPath desktopHooks candidate 12+ if face == nullPtr+ then pure False+ else (/= 0) <$> ttfIsBoldOf face regular <* ttfCloseFont face+ firstM _ [] = pure Nothing+ firstM p (x : xs) = p x >>= \ok -> if ok then pure (Just x) else firstM p xs++{-# NOINLINE desktopCoveragePool #-}+desktopCoveragePool :: CoveragePool SBS.ShortByteString+desktopCoveragePool =+ unsafePerformIO $+ newCoveragePool findSources (\path -> SBS.useAsCString path (`ttfOpenFont` 12))+ where+ findSources = do+ files <- searchFontFamilies coverageFamilies `catch` \(_ :: IOException) -> pure []+ enc <- sdlPathEncoding+ forM files $ \path -> GHC.withCStringLen enc path (fmap SBS.toShort . BS.packCStringLen)++coverageFamilies :: [String]+coverageFamilies =+ [ "Noto Sans", "DejaVu Sans"+ , "Noto Sans Arabic", "Noto Sans Hebrew", "Noto Sans Devanagari", "Noto Sans Bengali"+ , "Noto Sans Tamil", "Noto Sans Telugu", "Noto Sans Gujarati", "Noto Sans Gurmukhi"+ , "Noto Sans Kannada", "Noto Sans Malayalam", "Noto Sans Sinhala", "Noto Sans Thai"+ , "Noto Sans Lao", "Noto Sans Khmer", "Noto Sans Myanmar", "Noto Sans Armenian"+ , "Noto Sans Georgian", "Noto Sans Ethiopic", "Noto Sans CJK", "Noto Sans CJK SC", "Noto Sans CJK JP"+ , "Noto Sans Symbols", "Noto Sans Symbols 2", "Noto Sans Math"+ , "Segoe UI", "Segoe UI Symbol", "Nirmala UI", "Leelawadee UI", "Microsoft YaHei"+ , "Yu Gothic", "Malgun Gothic", "Arial Unicode MS"+ , "Geeza Pro", "Kohinoor Devanagari", "Thonburi", "PingFang SC", "Hiragino Sans"+ , "Apple SD Gothic Neo", "Apple Symbols"+ ]++foreign import ccall unsafe "nano_ui_text_atlas_create"+ textAtlasCreate :: Ptr SDL_Renderer -> IO (Ptr ())++foreign import ccall unsafe "nano_ui_text_atlas_destroy"+ textAtlasDestroy :: Ptr () -> IO ()++foreign import ccall unsafe "nano_ui_text_atlas_reset"+ textAtlasReset :: Ptr () -> IO ()++foreign import ccall unsafe "nano_ui_text_atlas_drop_textures"+ textAtlasDropTextures :: Ptr () -> IO ()++foreign import ccall unsafe "nano_ui_text_atlas_insert_surface"+ textAtlasInsertSurface :: Ptr () -> Ptr () -> Ptr CFloat -> IO CBool
+ lib/NanoUI/Sdl/Internal/Font/Search.hs view
@@ -0,0 +1,273 @@+-- | Locate system font files by walking the standard font directories for the+-- current platform, without fontconfig. Each candidate file is matched+-- against the requested family name using a normalised-filename heuristic.+module NanoUI.Sdl.Internal.Font.Search+ ( searchFonts+ , searchFontFamilies+ , listFontFamilies+ , boldFaceCandidates+ , startFontIndex+ , fontFilesUnder+ ) where++import Control.Concurrent (forkIO)+import Control.Concurrent.MVar (MVar, modifyMVar, newEmptyMVar, newMVar, putMVar, readMVar)+import Control.Exception (IOException, SomeException, catch, throwIO, try)+import Control.Monad (filterM, mfilter, void)+import Data.Containers.ListUtils (nubOrd)+import Data.IORef (IORef, modifyIORef', newIORef, readIORef)+import Data.Char (isDigit, isLower, isUpper, toLower)+import Data.List (elemIndex, find, isInfixOf, isPrefixOf, partition, sort, sortOn, stripPrefix, tails)+import Data.Maybe (fromMaybe, listToMaybe, mapMaybe)+import Data.Ord (Down (..))+import qualified Data.Set as Set+import NanoUI.Ttf.Internal.Support (expandGenericFamily, normalizeFamily)+import System.Directory (canonicalizePath, doesDirectoryExist, getHomeDirectory, listDirectory)+import System.Environment (lookupEnv)+import System.FilePath (isAbsolute, splitSearchPath, takeBaseName, takeDirectory, takeExtension, (</>))+import System.Info (os)+import System.IO.Unsafe (unsafePerformIO)++-- | Try each family name in order, returning the first font file that+-- matches. Generic families like @monospace@ are expanded to a list of+-- concrete families first.+searchFonts :: [String] -> IO (Maybe FilePath)+searchFonts names = listToMaybe <$> searchFontFamilies (concatMap families names)+ where+ families name = maybe [name] (concatMap families) (expandGenericFamily (normalizeFamily name))++-- | The file for each family that is installed, in the order asked, reading+-- the font directories once.+searchFontFamilies :: [String] -> IO [FilePath]+searchFontFamilies names = do+ files <- fontStems+ pure (nubOrd (mapMaybe (\name -> bestMatch (normalizeFamily name) files) names))++-- | Files beside a regular face that may be its bold, most likely first: the+-- family's own @-Bold@ file, or Windows' short names, @consolab.ttf@ beside+-- @consola.ttf@ and @courbd.ttf@ beside @cour.ttf@. Names prove nothing, so+-- the caller opens each to check it is the family's bold.+boldFaceCandidates :: FilePath -> IO [FilePath]+boldFaceCandidates regular = do+ siblings <- filter isFontFile <$> listDirectory dir `catch` \(_ :: IOException) -> pure []+ let named = [(normalizeFamily (takeBaseName f), dir </> f) | f <- siblings]+ pure [path | want <- wanted, (stem', path) <- named, stem' == want]+ where+ dir = takeDirectory regular+ stem = normalizeFamily (takeBaseName regular)+ families = stem : [reverse family | t <- regularTails, Just family <- [stripPrefix (reverse t) (reverse stem)], not (null family)]+ wanted = nubOrd (map (<> "bold") families ++ [stem <> "bd", stem <> "b"])++-- | Human-readable names for the installed font files, deduped and sorted.+-- Each is made from a file name, up to its first @-@, so a family whose files+-- are named like @NotoSans-Bold.ttf@ appears once, but one with a short name+-- per style, as on Windows, appears once per style (@arial@, @arialbd@).+-- Each name is a usable 'searchFonts' token: the same normalization is applied+-- to both the requested family and the file stem, so a listed name always+-- resolves back to (at least) the file it came from. Non-text faces (icons,+-- colour emoji) are included; callers that need sans families can filter the+-- result themselves. The font directories are read once per process, so a+-- font installed later is not listed.+listFontFamilies :: IO [String]+listFontFamilies = do+ files <- fontStems+ pure (Set.toAscList (Set.fromList (map (prettyFamily . takeBaseName . snd) files)))++-- | Filename stem -> display family. Everything from the first @-@ is treated+-- as style (\"Regular\", \"Bold Italic\", ...); camel case is split so+-- @NotoSansArabic@ reads as @Noto Sans Arabic@. Kept case-insensitively+-- compatible with 'normalizeFamily'.+prettyFamily :: String -> String+prettyFamily file = concat (zipWith separate (' ' : stem) stem)+ where+ stem = takeWhile (/= '-') file+ separate prev c+ | isUpper c && (isLower prev || isDigit prev) = [' ', c]+ | otherwise = [c]++-- ---------------------------------------------------------------------------+-- Directory traversal++-- | Every font file under every standard font directory for this platform,+-- with its normalised name, normalised once for all the families matched+-- against it. User directories come first so that user-installed fonts win+-- over system ones; missing or unreadable roots are skipped. The directories+-- are walked once per process, on a thread of their own ('startFontIndex');+-- this waits for that walk only while it is still running.+fontStems :: IO [(String, FilePath)]+fontStems = startFontIndex >>= readMVar >>= either throwIO pure++-- | Start walking the font directories on a background thread, unless a walk+-- has started already, and answer where its result goes. A session calls it+-- when it opens, so the first search, or the first character no loaded font+-- has, finds the walk done or under way.+startFontIndex :: IO (MVar (Either SomeException [(String, FilePath)]))+startFontIndex = modifyMVar fontIndexRef $ \case+ Just done -> pure (Just done, done)+ Nothing -> do+ done <- newEmptyMVar+ void $ forkIO $ putMVar done =<< try walk+ pure (Just done, done)+ where+ walk = do+ files <- fontFilesUnder =<< defaultFontDirs+ let stems = map (\path -> (normalizeFamily (takeBaseName path), path)) files+ -- Forced here, so a search that waits finds the work done.+ stems <$ mapM_ (\(stem, _) -> length stem `seq` pure ()) stems++{-# NOINLINE fontIndexRef #-}+fontIndexRef :: MVar (Maybe (MVar (Either SomeException [(String, FilePath)])))+fontIndexRef = unsafePerformIO (newMVar Nothing)++-- | Every font file under each of the directories, in their order, each+-- directory's sorted. A directory reached twice, by a symbolic link or as+-- two of the roots, is walked once.+fontFilesUnder :: [FilePath] -> IO [FilePath]+fontFilesUnder roots = do+ seen <- newIORef Set.empty+ concat <$> mapM (fmap sort . fontFilesBelow seen) roots++-- | Every font file under a directory; returns @[]@ if the directory cannot be+-- read, or was walked already under any name: @seen@ holds the canonical+-- paths walked, so a symbolic link back up the tree ends the walk there and+-- a directory linked from two places is walked once. Only entries that do+-- not match 'isFontFile' are checked with 'doesDirectoryExist' to avoid+-- redundant @stat@ calls in large font directories.+fontFilesBelow :: IORef (Set.Set FilePath) -> FilePath -> IO [FilePath]+fontFilesBelow seen dir = do+ canonical <- canonicalizePath dir `catch` \(_ :: IOException) -> pure dir+ walked <- Set.member canonical <$> readIORef seen+ if walked+ then pure []+ else do+ modifyIORef' seen (Set.insert canonical)+ entries <- map (dir </>) <$> listDirectory dir `catch` \(_ :: IOException) -> pure []+ let (fonts, others) = partition isFontFile entries+ subdirs <- filterM doesDirectoryExist others+ (fonts ++) . concat <$> mapM (fontFilesBelow seen) subdirs++defaultFontDirs :: IO [FilePath]+defaultFontDirs =+ case os of+ "darwin" -> (\home -> [home </> "Library/Fonts", "/Library/Fonts", "/System/Library/Fonts"]) <$> getHomeDirectory+ "mingw32" -> do+ mRoot <- lookupEnv "SystemRoot"+ mLocal <- lookupEnv "LOCALAPPDATA"+ pure $+ [local </> "Microsoft" </> "Windows" </> "Fonts" | Just local <- [mLocal]]+ ++ [fromMaybe "C:\\Windows" mRoot </> "Fonts"]+ -- @fonts@ in the XDG data home and ~/.fonts, then in each XDG data+ -- directory (NixOS keeps its fonts there) and in the system data+ -- directories, which fontconfig reads whatever XDG_DATA_DIRS says. The+ -- XDG spec ignores relative entries, an empty one among them.+ _ -> do+ home <- getHomeDirectory+ let env name = mfilter (not . null) <$> lookupEnv name+ dataHome <- fromMaybe (home </> ".local/share") <$> env "XDG_DATA_HOME"+ dataDirs <- maybe [] (filter isAbsolute . splitSearchPath) <$> env "XDG_DATA_DIRS"+ pure (nubOrd ([dataHome </> "fonts", home </> ".fonts"] ++ map (</> "fonts") (dataDirs ++ ["/usr/local/share", "/usr/share"])))++isFontFile :: FilePath -> Bool+isFontFile path =+ map toLower (takeExtension path) `elem` [".ttf", ".otf", ".ttc", ".otc"]++-- ---------------------------------------------------------------------------+-- Family matching++-- | Pick the highest-scoring file for @norm@ (a normalised family name).+bestMatch :: String -> [(String, FilePath)] -> Maybe FilePath+bestMatch norm files =+ -- The sort is stable, so of equal scores the file found first wins.+ snd <$> listToMaybe (sortOn (Down . fst) scored)+ where+ scored = [(score, path) | (stem, path) <- files, Just score <- [maximum (Nothing : map (`matchScore` stem) candidates)]]+ candidates = norm : familyAliases norm++-- | How well a file stem matches a normalised family name: 'Nothing' unless+-- the stem starts with it. What follows the name is a style (@Regular@,+-- @Bold Italic@, axes in brackets) or the rest of a longer family's name+-- and then a style (@Mono@ in @RobotoMono-Regular@, @Hebrew@ in+-- @OpenSansHebrew-Regular@). Every file of the family itself outranks every+-- file of a longer one, whatever their styles; within each, the style+-- ranks the files.+matchScore :: String -> String -> Maybe Int+matchScore "" _ = Nothing+matchScore norm stem = score <$> stripPrefix norm stem+ where+ score t =+ let style = fromMaybe "" (find isStyleTail (tails t))+ longer = length style < length t+ in styleScore style - (if longer then 200 else 0)+ -- A slanted file ranks just below its upright twin, which by name can+ -- sort after it (@X-Italic[wght]@ before @X[wght]@).+ styleScore t = base t - fromEnum ("italic" `isInfixOf` t || "oblique" `isInfixOf` t)+ base t+ | null t = 100+ | Just i <- elemIndex t regularTails = 90 - i+ | t `elem` otherTails = 70+ | "variable" `isInfixOf` t = 20+ | otherwise = 60++-- | Whether a normalised tail after a family name names only a style: style+-- words, optionally followed by variable-font axes (@[wght]@,+-- @VariableFont_wght@), or one of Windows' one- and two-letter style+-- suffixes (@arialbd@, @consolaz@). @Mono@, @Condensed@ or a script name+-- in it make it the rest of a longer family's name.+isStyleTail :: String -> Bool+isStyleTail t = t `elem` ["", "r", "b", "bd", "i", "bi", "z"] || styleWords (dropVariable (takeWhile (/= '[') t))+ where+ dropVariable "" = ""+ dropVariable s@(c : cs)+ | "variable" `isPrefixOf` s = ""+ | otherwise = c : dropVariable cs+ styleWords "" = True+ styleWords s = any (\w -> maybe False styleWords (stripPrefix w s)) styleVocabulary++-- | Words a style tail is made of.+styleVocabulary :: [String]+styleVocabulary =+ [ "regular", "normal", "book", "roman", "text", "medium", "bold", "italic", "oblique", "light"+ , "thin", "black", "heavy", "semi", "demi", "extra", "ultra"+ ]++-- | Style tails that indicate the regular weight of a family, the likeliest+-- first: of a family's files, the one whose tail comes first wins.+regularTails :: [String]+regularTails = ["regular", "normal", "r", "book", "roman", "text", "medium"]++-- | Style tails for non-regular weights; still worth preferring over an+-- unrelated font, but a regular (or exact) match wins.+otherTails :: [String]+otherTails =+ [ "bold"+ , "italic"+ , "light"+ , "semibold"+ , "semibolditalic"+ , "extrabold"+ , "thin"+ , "black"+ , "regularitalic"+ , "bolditalic"+ , "mediumitalic"+ , "oblique"+ ]++-- | Windows ships @Consolas@ as @consola.ttf@ and @Segoe UI Symbol@ as+-- @seguisym.ttf@, and macOS @PingFang SC@ as @PingFang.ttc@, so those+-- families need filename aliases that prefix-match differently than their+-- family names.+familyAliases :: String -> [String]+familyAliases "consolas" = ["consola"]+familyAliases "couriernew" = ["cour"]+familyAliases "timesnewroman" = ["times"]+familyAliases "segoeuisymbol" = ["seguisym"]+familyAliases "nirmalaui" = ["nirmala"]+familyAliases "leelawadeeui" = ["leelawui"]+familyAliases "microsoftyahei" = ["msyh"]+familyAliases "yugothic" = ["yugothr"]+familyAliases "malgungothic" = ["malgun"]+familyAliases "arialunicodems" = ["arialuni"]+familyAliases "pingfangsc" = ["pingfang"]+familyAliases "kohinoordevanagari" = ["kohinoor"]+familyAliases _ = []
+ lib/NanoUI/Sdl/Internal/Frame.hs view
@@ -0,0 +1,243 @@+{-# LANGUAGE CPP #-}++-- | How much of the desktop's own decoration a window keeps, and the frame+-- and shadow that go under a window that draws its own title bar.+--+-- A borderless window on Windows is a popup with no non-client frame, so the+-- desktop draws no drop shadow under it and provides no outer resize border;+-- without a native frame, a resizable window has to reserve part of its own+-- client area for resize hit testing.+--+-- 'DecorationsFrame' restores both: it keeps the native sizing frame outside+-- the client area (invisible, outside the visible window, and used by the+-- window manager for edge resizing) together with the native drop shadow,+-- expanding the outer window rectangle so the client area keeps its requested+-- size.+--+-- The window procedure the frame needs is in @cbits\/nano_ui_frame.c@ rather+-- than here: Windows calls it from inside @SetWindowPos@, @DefWindowProc@+-- and the modal loop a border drag runs in, and a Haskell callback reached+-- that way re-enters the runtime from a foreign call already running on the+-- thread.+--+-- Elsewhere the compositor decides: the frame and the shadow do nothing, and+-- a window with less than 'DecorationsFull' is a borderless one.+module NanoUI.Sdl.Internal.Frame+ ( WindowDecorations (..)+ , installWin32ResizeHook+ , windowInSizeMove+ , applyDecorations+ , framedWindow+ , applyWindowShadow+ , nativeFrameOutset+ , hasFlag+ ) where++import Control.Monad (void, when)+import Data.Bits (zeroBits, (.&.))+import Foreign.Ptr (Ptr)+import SDL3.Sys.Bindgen.Video (SDL_Window, SDL_WindowFlags)+import SDL3.Sys.Video qualified as SDL++#if defined(mingw32_HOST_OS)+import Data.ByteString qualified as BS+import Data.Int (Int32)+import Data.Word (Word32)+import Foreign.C.Types (CInt (..))+import Foreign.Marshal.Array (withArray)+import Foreign.Marshal.Utils (fromBool, with)+import Foreign.Ptr (castPtr, nullPtr)+import NanoUI.Sdl.Internal.Display (outPair)+import SDL3.Sys.Bindgen.Runtime.PtrConst qualified as PtrConst+import SDL3.Sys.Bindgen.Video (sDL_PROP_WINDOW_WIN32_HWND_POINTER)+import SDL3.Sys.Properties (getPointerProperty)+#endif++-- | How much of the desktop's own decoration a window keeps.+data WindowDecorations+ = DecorationsFull+ -- ^ The desktop's title bar and frame: an ordinary window.+ | DecorationsFrame+ -- ^ The desktop's frame without its title bar, for a view that draws its+ -- own ('NanoUI.Backend.Sdl.windowCaption'). On Windows the frame is never+ -- drawn and takes nothing from the view: it lies outside the window you+ -- can see, it is what the desktop resizes the window by, and it carries+ -- the desktop's drop shadow. The window is made that much larger, so+ -- 'NanoUI.wsSize' is still the size of the view. A+ -- window that cannot be resized, or is fullscreen, has no use for the+ -- edges and is given only the shadow. Elsewhere this is a borderless+ -- window, and the compositor decides about the shadow.+ | DecorationsNone+ -- ^ Nothing of the desktop's: no title bar, no frame and no shadow.+ -- 'NanoUI.Backend.Sdl.setWindowShadow' puts the desktop's shadow under it+ -- on Windows.+ deriving (Eq, Show)++-- | Give a window the decorations asked for, from whatever it had before.+--+-- Safe calls only: turning the border on and off and putting the frame on+-- and off all run the window's procedure before they return.+applyDecorations :: Ptr SDL_Window -> WindowDecorations -> IO ()+applyDecorations win decorations = do+ -- Take off what an earlier call put on, so that any of these can follow+ -- any other.+ applyNativeFrame win False+ applyWindowShadow win False+ void (SDL.setWindowBorderedSafe win (decorations == DecorationsFull))+ when (decorations == DecorationsFrame) $ do+ framed <- framedWindow <$> SDL.getWindowFlags win+ -- When the native sizing frame is enabled it already carries the DWM+ -- shadow, and calling DwmExtendFrameIntoClientArea on top of it would+ -- extend the frame over the top pixel row of the client area.+ if framed then applyNativeFrame win True else applyWindowShadow win True++-- | Whether 'DecorationsFrame' gives a window with these flags the desktop's+-- sizing frame, rather than only its shadow. A non-resizable or fullscreen+-- window should not have an outer sizing frame that intercepts clicks+-- outside the window.+framedWindow :: SDL_WindowFlags -> Bool+framedWindow flags = hasFlag SDL.SDL_WINDOW_RESIZABLE flags && not (hasFlag SDL.SDL_WINDOW_FULLSCREEN flags)++-- | Whether window flags include a flag.+hasFlag :: SDL_WindowFlags -> SDL_WindowFlags -> Bool+hasFlag bit flags = flags .&. bit /= zeroBits++-- | Put the desktop's own frame back under a borderless window, or take it+-- away again.+--+-- The frame stays where the desktop puts it, the same width in on every+-- side, around the outside of the window you can see. Nothing of it is drawn+-- and nothing of the view gives way to it: the window is made that much+-- larger instead, so the view keeps the size it was asked for. What the+-- frame is for is the edges -- the desktop resizes the window by them, from+-- outside the view, the way it does for every window with a title bar of its+-- own.+--+-- It is also what keeps the desktop's rounded corners off the view. The+-- corners the desktop rounds and smooths are the window's, and with the+-- frame between them and the view, the only thing at the view's own corners+-- is the border it draws there itself.+applyNativeFrame :: Ptr SDL_Window -> Bool -> IO ()++-- | Put the desktop's shadow under a window, or take it away again.+applyWindowShadow :: Ptr SDL_Window -> Bool -> IO ()++-- | Install the Win32 subclass that suppresses stale BitBlt copies and+-- background erasure during resize drags and tracks Win32's modal size/move+-- loop. No-op on other platforms.+installWin32ResizeHook :: Ptr SDL_Window -> IO ()++-- | Whether Win32's modal border-drag loop (@WM_ENTERSIZEMOVE@ ..+-- @WM_EXITSIZEMOVE@) is currently active for the window. Always 'False' on+-- other platforms.+windowInSizeMove :: Ptr SDL_Window -> IO Bool++-- | How much larger than its view the desktop's frame makes a window, across+-- and down, in window coordinates: nothing for a window without the frame,+-- or one maximized or fullscreen. SDL sizes a borderless window as though+-- its client area were the whole of it, so a size asked of SDL adds this.+nativeFrameOutset :: Ptr SDL_Window -> IO (Int, Int)++#if defined(mingw32_HOST_OS)+installWin32ResizeHook win = withHwnd win () nanoUiInstallWin32ResizeHook++windowInSizeMove win = withHwnd win False (fmap (/= 0) . nanoUiWindowInSizeMove)++applyNativeFrame win on =+ withHwnd win () $ \hwnd -> do+ nanoUiSetNativeFrame hwnd (fromBool on)+ -- The desktop draws a line of its own around a window that has a frame,+ -- and along the top, where the client area reaches the edge of the+ -- window, it falls on the view's first row. The view draws its own+ -- border there, so the desktop's is taken off.+ setWindowWord hwnd dwmwaBorderColor (if on then dwmwaColorNone else dwmwaColorDefault)+ -- And it rounds the window's corners. Those corners are the frame's, not+ -- the view's -- the view is held a frame's width inside them, so its own+ -- corners are square whatever the desktop does there, and a rounding+ -- that only shapes the shadow leaves the shadow round a window that is+ -- not. Square, the shadow follows the window it belongs to, and the+ -- corners are the view's to draw.+ setWindowWord hwnd dwmwaCornerPreference (if on then dwmwcpDoNotRound else dwmwcpDefault)++applyWindowShadow win on =+ withHwnd win () $ \hwnd -> do+ -- DWM hangs the shadow off the non-client area, which a popup window is+ -- not rendered with unless it is asked for. Off goes back to what the+ -- window's style says rather than to never, which would take the shadow+ -- and border from a window that has a frame of its own.+ setWindowWord hwnd dwmwaNcRenderingPolicy (if on then dwmncrpEnabled else dwmncrpUseWindowStyle)+ -- A frame extended into the client area is what makes DWM treat the+ -- window as one that has a frame at all. One pixel along the top is the+ -- least that does, and the view paints over it.+ withArray (if on then [0, 0, 1, 0] else [0, 0, 0, 0]) (void . dwmExtendFrameIntoClientArea hwnd)++nativeFrameOutset win =+ withHwnd win (0, 0) $ \hwnd -> do+ ((), across, down) <- outPair (nanoUiNativeFrameOutset hwnd)+ pure (fromIntegral across, fromIntegral down)++foreign import ccall safe "nano_ui_install_win32_resize_hook"+ nanoUiInstallWin32ResizeHook :: Ptr () -> IO ()++foreign import ccall unsafe "nano_ui_window_in_sizemove"+ nanoUiWindowInSizeMove :: Ptr () -> IO CInt++-- | Safe, not unsafe: this one puts the window procedure on and takes it off+-- again, and Windows dispatches messages from inside both.+foreign import ccall safe "nano_ui_set_native_frame"+ nanoUiSetNativeFrame :: Ptr () -> CInt -> IO ()++foreign import ccall unsafe "nano_ui_native_frame_outset"+ nanoUiNativeFrameOutset :: Ptr () -> Ptr CInt -> Ptr CInt -> IO ()++-- | Run an action on the window's @HWND@, or answer @none@ for a window that+-- has none.+withHwnd :: Ptr SDL_Window -> a -> (Ptr () -> IO a) -> IO a+withHwnd win none act = do+ props <- SDL.getWindowProperties win+ hwnd <- BS.useAsCString sDL_PROP_WINDOW_WIN32_HWND_POINTER $ \name ->+ getPointerProperty props (PtrConst.unsafeFromPtr name) nullPtr+ if hwnd == nullPtr then pure none else act (castPtr hwnd)++-- | Set a @DWORD@ DWM window attribute. @DWMWA_BORDER_COLOR@ and+-- @DWMWA_WINDOW_CORNER_PREFERENCE@ require Windows 11; older Windows versions+-- ignore the call and return an error code, which is discarded.+setWindowWord :: Ptr () -> Word32 -> Word32 -> IO ()+setWindowWord hwnd attribute value =+ with value $ \p -> void (dwmSetWindowAttribute hwnd attribute (castPtr p) 4)++-- | @DWMWA_BORDER_COLOR@ and the colour that says to draw no border, and+-- @DWMWA_WINDOW_CORNER_PREFERENCE@ and the two roundings used here.+dwmwaBorderColor, dwmwaColorNone, dwmwaColorDefault :: Word32+dwmwaBorderColor = 34+dwmwaColorNone = 0xFFFFFFFE+dwmwaColorDefault = 0xFFFFFFFF++dwmwaCornerPreference, dwmwcpDefault, dwmwcpDoNotRound :: Word32+dwmwaCornerPreference = 33+dwmwcpDefault = 0+dwmwcpDoNotRound = 1++-- | The DWM calls are safe foreign calls: a frame or rendering-policy change+-- sends the window @WM_NCCALCSIZE@ and @WM_DWMNCRENDERINGCHANGED@ from inside+-- the call, and SDL's window procedure can run Haskell callbacks.+foreign import ccall safe "DwmExtendFrameIntoClientArea"+ dwmExtendFrameIntoClientArea :: Ptr () -> Ptr CInt -> IO Int32++foreign import ccall safe "DwmSetWindowAttribute"+ dwmSetWindowAttribute :: Ptr () -> Word32 -> Ptr () -> Word32 -> IO Int32++-- | @DWMWA_NCRENDERING_POLICY@, and the two policies it is set to here.+dwmwaNcRenderingPolicy :: Word32+dwmwaNcRenderingPolicy = 2++dwmncrpUseWindowStyle, dwmncrpEnabled :: Word32+dwmncrpUseWindowStyle = 0+dwmncrpEnabled = 2+#else+installWin32ResizeHook _ = pure ()+windowInSizeMove _ = pure False+applyNativeFrame _ _ = pure ()+applyWindowShadow _ _ = pure ()+nativeFrameOutset _ = pure (0, 0)+#endif
+ lib/NanoUI/Sdl/Internal/Gpu.hs view
@@ -0,0 +1,443 @@+{-# OPTIONS_HADDOCK not-home #-}++-- | SDL 3.4 GPU renderer creation, shader/render-state caching, and live-resize+-- 1:1 swapchain presentation. All SDL 3.4 calls are guarded by the runtime SDL+-- version so SDL 3.2 sessions never pollute @SDL_GetError@.+module NanoUI.Sdl.Internal.Gpu+ ( GpuState+ , newGpuState+ , destroyGpuState+ , gpuHasDevice+ , gpuEnsureWhiteTex+ , gpuBindShader+ , presentGpuRetainImpl+ , createWindowAndGpuRenderer+ , rendererHasGpu+ , rendererHasShaders+ ) where++import Control.Monad (forM_, void, when)+import Data.Bits ((.&.), (.|.))+import Data.ByteString qualified as BS+import Data.ByteString.Unsafe qualified as BSU+import Data.Int (Int32)+import Data.IORef (IORef, modifyIORef', newIORef, readIORef, writeIORef)+import Data.Map.Strict qualified as Map+import Data.Text.Encoding qualified as TE+import Data.Word (Word32, Word64, Word8)+import Foreign.C.String (CString)+import Foreign.C.Types (CInt (..))+import Foreign.Marshal.Alloc (alloca)+import Foreign.Marshal.Utils (with)+import Foreign.Ptr (Ptr, castPtr, nullPtr)+import Foreign.Storable (peek)+import NanoUI (Color, colorA, colorB, colorG, colorR)+import NanoUI.Backend (ShaderProgram (..))+import NanoUI.Sdl.Internal.Display (outPair)+import NanoUI.Sdl.Internal.Error (withSdlError)+import SDL3.Sys.Bindgen.Gpu+ ( SDL_GPUBlitInfo (..)+ , SDL_GPUBlitRegion (..)+ , SDL_GPUDevice+ , SDL_GPUShader+ , SDL_GPUShaderCreateInfo (..)+ )+import SDL3.Sys.Bindgen.Gpu qualified as GpuBind+import SDL3.Sys.Bindgen.Pixels (SDL_FColor (..))+import SDL3.Sys.Bindgen.Pixels qualified as Pixels+import SDL3.Sys.Bindgen.Properties (SDL_PropertiesID (..))+import SDL3.Sys.Bindgen.Rect (SDL_Rect (..))+import SDL3.Sys.Bindgen.Render+ ( SDL_GPURenderState+ , SDL_GPURenderStateCreateInfo (..)+ , SDL_Renderer+ , SDL_Texture+ , sDL_PROP_RENDERER_CREATE_GPU_SHADERS_MSL_BOOLEAN+ , sDL_PROP_RENDERER_CREATE_GPU_SHADERS_SPIRV_BOOLEAN+ , sDL_PROP_RENDERER_CREATE_NAME_STRING+ , sDL_PROP_RENDERER_CREATE_WINDOW_POINTER+ , sDL_PROP_TEXTURE_GPU_TEXTURE_POINTER+ )+import SDL3.Sys.Bindgen.Render qualified as RenderBind+import SDL3.Sys.Bindgen.Runtime.PtrConst qualified as PtrConst+import SDL3.Sys.Bindgen.Surface qualified as SurfaceBind+import SDL3.Sys.Bindgen.Video (SDL_Window, SDL_WindowFlags)+import SDL3.Sys.Blendmode qualified as Blend+import SDL3.Sys.Gpu+ ( acquireGPUCommandBufferSafe+ , blitGPUTexture+ , cancelGPUCommandBuffer+ , createGPUShader+ , getGPUShaderFormats+ , releaseGPUShader+ , setGPUAllowedFramesInFlight+ , submitGPUCommandBufferSafe+ , waitAndAcquireGPUSwapchainTextureSafe+ )+import SDL3.Sys.Gpu qualified as Gpu+import SDL3.Sys.Properties+ ( createProperties+ , destroyProperties+ , getNumberProperty+ , getPointerProperty+ , setBooleanProperty+ , setNumberProperty+ , setPointerProperty+ , setStringProperty+ )+import SDL3.Sys.Render+ ( createGPURenderState+ , createRendererWithPropertiesSafe+ , createTexture+ , destroyGPURenderState+ , destroyTexture+ , getGPURendererDevice+ , getRenderOutputSize+ , getRendererProperties+ , getTextureProperties+ , renderReadPixelsSafe+ , setGPURenderState+ , setGPURenderStateFragmentUniforms+ , setRenderScale+ , setRenderTarget+ , setTextureBlendMode+ , updateTexture+ )+import SDL3.Sys.Surface (destroySurface)+import SDL3.Sys.Version (getVersion)+import SDL3.Sys.Video (createWindowSafe, destroyWindowSafe)+import System.IO (hPutStrLn, stderr)++sdlVersion34, sdlVersion35 :: Int32+sdlVersion34 = 3004000+sdlVersion35 = 3005000++propGpuBbW, propGpuBbH :: BS.ByteString+propGpuBbW = "nano_ui.gpu_bb_w"+propGpuBbH = "nano_ui.gpu_bb_h"++withPropName :: BS.ByteString -> (PtrConst.PtrConst a -> IO b) -> IO b+withPropName bs k = BS.useAsCString bs (k . PtrConst.unsafeFromPtr . castPtr)++logSdlError :: String -> IO ()+logSdlError what = withSdlError ("nano-ui-sdl: " ++ what) >>= hPutStrLn stderr++-- | Cached SDL 3.4 GPU device state, compiled fragment shaders, white fallback+-- texture, and SDL 3.4 backbuffer dimensions.+data GpuState = GpuState+ { gsDevice :: !(Ptr SDL_GPUDevice)+ , gsBbSize :: !(IORef (Int, Int))+ , gsWhiteTex :: !(IORef (Ptr SDL_Texture))+ , gsShaders :: !(IORef (Map.Map Word64 (Maybe (Ptr SDL_GPUShader, Ptr SDL_GPURenderState))))+ }++-- | Create GPU shader cache state for a renderer, recording SDL 3.4's initial+-- GPU backbuffer size when backed by an SDL 3.4 GPU device.+newGpuState :: Ptr SDL_Renderer -> IO GpuState+newGpuState ren = do+ ver <- getVersion+ dev <- if ver >= sdlVersion34 then getGPURendererDevice ren else pure nullPtr+ bb <-+ if dev /= nullPtr+ then do+ rprops <- getRendererProperties ren+ bw <- if rprops /= 0 then fromIntegral <$> withPropName propGpuBbW (\p -> getNumberProperty rprops p 0) else pure 0+ bh <- if rprops /= 0 then fromIntegral <$> withPropName propGpuBbH (\p -> getNumberProperty rprops p 0) else pure 0+ if bw > 0 && bh > 0+ then pure (bw, bh)+ else do+ (ok, ow, oh) <- outPair (getRenderOutputSize ren)+ pure (if ok then (fromIntegral ow, fromIntegral oh) else (0, 0))+ else pure (0, 0)+ GpuState dev <$> newIORef bb <*> newIORef nullPtr <*> newIORef Map.empty++-- | Release all cached GPU render states, GPU shaders, and the white texture.+destroyGpuState :: GpuState -> IO ()+destroyGpuState gs = do+ shaders <- readIORef (gsShaders gs)+ forM_ (Map.elems shaders) $ \case+ Nothing -> pure ()+ Just (sh, st) -> do+ when (st /= nullPtr) (destroyGPURenderState st)+ when (sh /= nullPtr && gsDevice gs /= nullPtr) (releaseGPUShader (gsDevice gs) sh)+ writeIORef (gsShaders gs) Map.empty+ wt <- readIORef (gsWhiteTex gs)+ when (wt /= nullPtr) $ do+ destroyTexture wt+ writeIORef (gsWhiteTex gs) nullPtr++-- | Whether the renderer is backed by an SDL 3.4 GPU device.+{-# INLINE gpuHasDevice #-}+gpuHasDevice :: GpuState -> Bool+gpuHasDevice gs = gsDevice gs /= nullPtr++-- | Return (creating on first use) a 1x1 opaque white texture so SDL's GPU+-- renderer selects its textured vertex pipeline (supplying v_color and v_uv).+gpuEnsureWhiteTex :: Ptr SDL_Renderer -> GpuState -> IO (Ptr SDL_Texture)+gpuEnsureWhiteTex ren gs = do+ cached <- readIORef (gsWhiteTex gs)+ if cached /= nullPtr+ then pure cached+ else do+ tex <- createTexture ren Pixels.SDL_PIXELFORMAT_RGBA32 RenderBind.SDL_TEXTUREACCESS_STATIC 1 1+ if tex == nullPtr+ then pure nullPtr+ else do+ with (0xFFFFFFFF :: Word32) $ \wp ->+ void $ updateTexture tex (PtrConst.unsafeFromPtr nullPtr) (PtrConst.unsafeFromPtr (castPtr wp)) 4+ void $ setTextureBlendMode tex Blend.SDL_BLENDMODE_BLEND+ writeIORef (gsWhiteTex gs) tex+ pure tex++-- | Look up or compile a cached GPU fragment shader, upload its fragment+-- uniform block (if non-empty), and activate its 'SDL_GPURenderState'.+gpuBindShader ::+ Ptr SDL_Renderer ->+ GpuState ->+ ShaderProgram ->+ Word64 ->+ Bool ->+ Ptr Word8 ->+ Int ->+ IO Bool+gpuBindShader ren gs prog hash needsTex uPtr uLen+ | gsDevice gs == nullPtr = pure False+ | otherwise = do+ mEntry <- Map.lookup hash <$> readIORef (gsShaders gs)+ mState <- case mEntry of+ Just res -> pure (snd <$> res)+ Nothing -> do+ created <- compileGpuShader ren (gsDevice gs) prog needsTex+ modifyIORef' (gsShaders gs) (Map.insert hash created)+ pure (snd <$> created)+ case mState of+ Nothing -> pure False+ Just st -> do+ uOk <-+ if uLen > 0 && uPtr /= nullPtr+ then do+ ok <- setGPURenderStateFragmentUniforms st 0 (PtrConst.unsafeFromPtr (castPtr uPtr)) (fromIntegral uLen)+ if ok then pure True else logSdlError "SDL_SetGPURenderStateFragmentUniforms failed" >> pure False+ else pure True+ if not uOk+ then pure False+ else do+ ok <- setGPURenderState ren st+ if ok then pure True else logSdlError "SDL_SetGPURenderState failed" >> pure False++compileGpuShader ::+ Ptr SDL_Renderer ->+ Ptr SDL_GPUDevice ->+ ShaderProgram ->+ Bool ->+ IO (Maybe (Ptr SDL_GPUShader, Ptr SDL_GPURenderState))+compileGpuShader ren dev prog needsTex = do+ fmts <- getGPUShaderFormats dev+ let pick+ | (fmts .&. Gpu.SDL_GPU_SHADERFORMAT_SPIRV) /= 0+ , Just spv <- spSpirv prog+ , not (BS.null spv) =+ Just (Gpu.SDL_GPU_SHADERFORMAT_SPIRV, spv, "main" :: BS.ByteString)+ | (fmts .&. Gpu.SDL_GPU_SHADERFORMAT_MSL) /= 0+ , Just mslText <- spMsl prog+ , let msl = TE.encodeUtf8 mslText+ , not (BS.null msl) =+ Just (Gpu.SDL_GPU_SHADERFORMAT_MSL, msl, "main0" :: BS.ByteString)+ | otherwise = Nothing+ case pick of+ Nothing -> pure Nothing+ Just (fmt, codeBs, entryName) ->+ BSU.unsafeUseAsCStringLen codeBs $ \(codePtr, codeLen) ->+ BS.useAsCString entryName $ \entryPtr -> do+ let sci =+ SDL_GPUShaderCreateInfo+ (fromIntegral codeLen)+ (PtrConst.unsafeFromPtr (castPtr codePtr))+ (PtrConst.unsafeFromPtr entryPtr)+ fmt+ GpuBind.SDL_GPU_SHADERSTAGE_FRAGMENT+ (if needsTex then 1 else 0)+ 0+ 0+ 1+ (SDL_PropertiesID 0)+ shader <- with sci (createGPUShader dev . PtrConst.unsafeFromPtr)+ if shader == nullPtr+ then logSdlError "SDL_CreateGPUShader failed" >> pure Nothing+ else do+ let rsci =+ SDL_GPURenderStateCreateInfo+ shader+ 0+ (PtrConst.unsafeFromPtr nullPtr)+ 0+ (PtrConst.unsafeFromPtr nullPtr)+ 0+ (PtrConst.unsafeFromPtr nullPtr)+ (SDL_PropertiesID 0)+ state <- with rsci (createGPURenderState ren . PtrConst.unsafeFromPtr)+ if state == nullPtr+ then do+ logSdlError "SDL_CreateGPURenderState failed"+ releaseGPUShader dev shader+ pure Nothing+ else pure (Just (shader, state))++-- | On SDL 3.4.x's @"gpu"@ renderer, @GPU_RenderPresent@ blits its internal+-- backbuffer (still at the pre-resize size) linearly stretched onto the new+-- swapchain before recreating the backbuffer. While a live resize is active+-- and the frame size differs from that backbuffer, submit the retained-target+-- draws and blit 1:1 to the swapchain. Once live resize ends, record the new+-- size and return 'False' so one standard present recreates the backbuffer.+presentGpuRetainImpl ::+ Ptr SDL_Renderer ->+ GpuState ->+ IO () ->+ IO () ->+ Ptr SDL_Window ->+ Ptr SDL_Texture ->+ Int ->+ Int ->+ Bool ->+ Color ->+ IO Bool+presentGpuRetainImpl ren gs flushAndLeave resetClip win retain rw rh inResize clear+ | ren == nullPtr || win == nullPtr || retain == nullPtr || rw <= 0 || rh <= 0 || gsDevice gs == nullPtr =+ pure False+ | otherwise = do+ ver <- getVersion+ if ver >= sdlVersion35+ then pure False+ else do+ (bbW, bbH) <- readIORef (gsBbSize gs)+ if rw == bbW && rh == bbH+ then pure False+ else+ if not inResize+ then writeIORef (gsBbSize gs) (rw, rh) >> pure False+ else do+ tprops <- getTextureProperties retain+ srcTex <-+ if tprops /= 0+ then castPtr <$> withPropName sDL_PROP_TEXTURE_GPU_TEXTURE_POINTER (\p -> getPointerProperty tprops p nullPtr)+ else pure nullPtr+ if srcTex == nullPtr+ then pure False+ else do+ let dev = gsDevice gs+ flushAndLeave+ -- Submit SDL_render_gpu's internal command buffer for retain+ -- without touching the window swapchain.+ void $ setRenderTarget ren retain+ syncSurf <- with (SDL_Rect 0 0 1 1) (renderReadPixelsSafe ren . PtrConst.unsafeFromPtr)+ when (syncSurf /= nullPtr) (destroySurface syncSurf)+ cmd <- acquireGPUCommandBufferSafe dev+ if cmd == nullPtr+ then void (setRenderTarget ren nullPtr) >> pure False+ else alloca $ \swapPtr -> alloca $ \swPtr -> alloca $ \shPtr -> do+ ok <- waitAndAcquireGPUSwapchainTextureSafe cmd win swapPtr swPtr shPtr+ if not ok+ then do+ void $ cancelGPUCommandBuffer cmd+ void $ setRenderTarget ren nullPtr+ pure False+ else do+ swapchain <- peek swapPtr+ sw <- peek swPtr+ sh <- peek shPtr+ when (swapchain /= nullPtr && sw > 0 && sh > 0) $ do+ let cw = min (fromIntegral rw) sw+ ch = min (fromIntegral rh) sh+ loadOp = if cw < sw || ch < sh then GpuBind.SDL_GPU_LOADOP_CLEAR else GpuBind.SDL_GPU_LOADOP_DONT_CARE+ clearCol =+ SDL_FColor+ (realToFrac (colorR clear) / 255)+ (realToFrac (colorG clear) / 255)+ (realToFrac (colorB clear) / 255)+ (realToFrac (colorA clear) / 255)+ blit =+ SDL_GPUBlitInfo+ (SDL_GPUBlitRegion srcTex 0 0 0 0 cw ch)+ (SDL_GPUBlitRegion swapchain 0 0 0 0 cw ch)+ loadOp+ clearCol+ SurfaceBind.SDL_FLIP_NONE+ GpuBind.SDL_GPU_FILTER_NEAREST+ 0+ 0+ 0+ 0+ with blit (blitGPUTexture cmd . PtrConst.unsafeFromPtr)+ void $ submitGPUCommandBufferSafe cmd+ void $ setRenderTarget ren nullPtr+ void $ setRenderScale ren 1 1+ resetClip+ pure True++-- | Create a window paired with SDL 3.4's @"gpu"@ renderer supporting SPIR-V+-- and MSL fragment shaders. Returns 'Nothing' on failure or SDL < 3.4 so+-- 'NanoUI.Backend.Sdl.RenderDriverAuto' can fall back cleanly.+createWindowAndGpuRenderer ::+ CString -> Int32 -> Int32 -> SDL_WindowFlags -> IO (Maybe (Ptr SDL_Window, Ptr SDL_Renderer))+createWindowAndGpuRenderer title w h flags = do+ ver <- getVersion+ if ver < sdlVersion34+ then pure Nothing+ else do+ win <- createWindowSafe (PtrConst.unsafeFromPtr title) w h flags+ if win == nullPtr+ then pure Nothing+ else do+ props <- createProperties+ ren <-+ if props == 0+ then pure nullPtr+ else do+ void $ withPropName sDL_PROP_RENDERER_CREATE_WINDOW_POINTER (\p -> setPointerProperty props p (castPtr win))+ void $ BS.useAsCString "gpu" $ \gpuName ->+ withPropName sDL_PROP_RENDERER_CREATE_NAME_STRING (\p -> setStringProperty props p (PtrConst.unsafeFromPtr gpuName))+ void $ withPropName sDL_PROP_RENDERER_CREATE_GPU_SHADERS_SPIRV_BOOLEAN (\p -> setBooleanProperty props p True)+ void $ withPropName sDL_PROP_RENDERER_CREATE_GPU_SHADERS_MSL_BOOLEAN (\p -> setBooleanProperty props p True)+ r <- createRendererWithPropertiesSafe props+ destroyProperties props+ pure r+ if ren == nullPtr+ then destroyWindowSafe win >> pure Nothing+ else do+ -- Limit frames in flight to 1 so live resize drags never queue+ -- stale-size frames behind the current border step.+ dev <- getGPURendererDevice ren+ when (dev /= nullPtr) $ void (setGPUAllowedFramesInFlight dev 1)+ -- Record the initial GPU backbuffer size before zoom/frame refits.+ (ok, bbW, bbH) <- outPair (getRenderOutputSize ren)+ when ok $ do+ rprops <- getRendererProperties ren+ when (rprops /= 0) $ do+ void $ withPropName propGpuBbW (\p -> setNumberProperty rprops p (fromIntegral bbW))+ void $ withPropName propGpuBbH (\p -> setNumberProperty rprops p (fromIntegral bbH))+ pure (Just (win, ren))++-- | Report whether @renderer@ is backed by an SDL 3.4 GPU device.+rendererHasGpu :: Ptr SDL_Renderer -> IO Bool+rendererHasGpu ren+ | ren == nullPtr = pure False+ | otherwise = do+ ver <- getVersion+ if ver < sdlVersion34 then pure False else (/= nullPtr) <$> getGPURendererDevice ren++-- | Report whether @renderer@ can execute @nano-ui-shader@ programs via either+-- SDL 3.4's @"gpu"@ driver (SPIR-V/MSL) or OpenGL 3.2+ (GLSL 150).+rendererHasShaders :: Ptr SDL_Renderer -> IO Bool+rendererHasShaders ren+ | ren == nullPtr = pure False+ | otherwise = do+ ver <- getVersion+ dev <- if ver >= sdlVersion34 then getGPURendererDevice ren else pure nullPtr+ if dev /= nullPtr+ then do+ fmts <- getGPUShaderFormats dev+ pure ((fmts .&. (Gpu.SDL_GPU_SHADERFORMAT_SPIRV .|. Gpu.SDL_GPU_SHADERFORMAT_MSL)) /= 0)+ else (/= 0) <$> c_glProbe ren++foreign import ccall unsafe "nano_ui_gl_probe"+ c_glProbe :: Ptr SDL_Renderer -> IO CInt
+ lib/NanoUI/Sdl/Internal/Image.hs view
@@ -0,0 +1,114 @@+{-# OPTIONS_HADDOCK not-home #-}++-- | Upload the core image atlas to SDL textures and manage their native lifetime.+module NanoUI.Sdl.Internal.Image+ ( ImageAtlas+ , newImageAtlas+ , destroyImageAtlas+ , syncImageAtlas+ , lookupImage+ )+where++import Control.Exception (mask_)+import Control.Monad (void)+import Data.IORef (IORef, atomicModifyIORef', newIORef, readIORef, writeIORef)+import Data.Word (Word8)+import Foreign.ForeignPtr (ForeignPtr, withForeignPtr)+import Foreign.Marshal.Utils (with)+import Foreign.Ptr (Ptr, castPtr, nullPtr, plusPtr)+import NanoUI.Sdl.Internal.Error (withSdlError)+import NanoUI.Backend (AtlasUpload (..), Context, atlasChanges, atlasTextureId)+import SDL3.Sys.Bindgen.Blendmode (sDL_BLENDMODE_BLEND)+import SDL3.Sys.Bindgen.Pixels qualified as Pixels+import SDL3.Sys.Bindgen.Rect (SDL_Rect (..))+import SDL3.Sys.Bindgen.Render (SDL_Renderer, SDL_Texture)+import SDL3.Sys.Bindgen.Render qualified as Render+import SDL3.Sys.Bindgen.Runtime.PtrConst qualified as PtrConst+import SDL3.Sys.Render (createTextureSafe, destroyTexture, setTextureBlendMode, updateTextureSafe)+import System.IO (hPutStrLn, stderr)++-- | The SDL texture of a context's image atlas. A texture and its metadata+-- have one lifetime; publish them together. The second field is the atlas+-- generation whose upload failed (0 for none): that generation is not+-- uploaded again, so a texture SDL will not make is asked for, and+-- reported, once rather than every frame.+data ImageAtlas = ImageAtlas !(IORef (Maybe AtlasTexture)) !(IORef Int)++data AtlasTexture = AtlasTexture+ { atTexture :: !(Ptr SDL_Texture)+ , atGeneration :: !Int+ }++-- | An atlas with no texture yet; the first 'syncImageAtlas' makes one.+newImageAtlas :: IO ImageAtlas+newImageAtlas = ImageAtlas <$> newIORef Nothing <*> newIORef 0++-- | Destroy the texture, if any, and forget a failed upload, so the next+-- 'syncImageAtlas' makes and fills a new texture.+destroyImageAtlas :: ImageAtlas -> IO ()+destroyImageAtlas (ImageAtlas ref failed) = mask_ (publish ref Nothing) >> writeIORef failed 0++-- | Make a texture (or none) the atlas's, and destroy the one it replaces.+publish :: IORef (Maybe AtlasTexture) -> Maybe AtlasTexture -> IO ()+publish ref new = atomicModifyIORef' ref (new,) >>= mapM_ (destroyTexture . atTexture)++-- | Bring the texture up to the context's image atlas. Pixels written in+-- place since the last upload go up as those rects only; a new texture is+-- made and filled when the atlas was resized, or there is none yet. A+-- generation whose upload failed is reported on stderr once and left until+-- the atlas changes again.+syncImageAtlas :: Ptr SDL_Renderer -> ImageAtlas -> Context -> IO ()+syncImageAtlas ren atlas@(ImageAtlas ref failed) ctx = do+ old <- readIORef ref+ changes <- atlasChanges ctx (maybe 0 atGeneration old)+ failedGen <- readIORef failed+ case (changes, old) of+ (Nothing, _) -> pure ()+ (Just (_, _, _, gen, _), _) | gen == failedGen -> pure ()+ (Just (w, h, pixels, gen, AtlasRegions rects), Just at) -> do+ ok <- updateRegions (atTexture at) w pixels rects+ -- A failed update leaves the texture behind, so fill a new one.+ if ok+ then writeIORef ref (Just at {atGeneration = gen})+ else uploadAtlas ren atlas w h pixels gen+ (Just (w, h, pixels, gen, _), _) -> uploadAtlas ren atlas w h pixels gen++-- | Copy the pixel rects @rects@ of an atlas @w@ pixels wide into @tex@.+updateRegions :: Ptr SDL_Texture -> Int -> ForeignPtr Word8 -> [(Int, Int, Int, Int)] -> IO Bool+updateRegions tex w pixels rects =+ withForeignPtr pixels $ \ptr ->+ and <$> mapM (update ptr) rects+ where+ update ptr (x, y, rw, rh) =+ with (SDL_Rect (fromIntegral x) (fromIntegral y) (fromIntegral rw) (fromIntegral rh)) $ \rp ->+ updateTextureSafe+ tex+ (PtrConst.unsafeFromPtr rp)+ (PtrConst.unsafeFromPtr (castPtr (ptr `plusPtr` ((y * w + x) * 4))))+ (fromIntegral (w * 4))++uploadAtlas ::+ Ptr SDL_Renderer -> ImageAtlas -> Int -> Int -> ForeignPtr Word8 -> Int -> IO ()+uploadAtlas ren (ImageAtlas ref failed) w h pixels gen = mask_ $ do+ tex <- createTextureSafe ren Pixels.SDL_PIXELFORMAT_RGBA32 Render.SDL_TEXTUREACCESS_STATIC (fromIntegral w) (fromIntegral h)+ if tex == nullPtr+ then giveUp "SDL_CreateTexture"+ else do+ void $ setTextureBlendMode tex (fromIntegral sDL_BLENDMODE_BLEND)+ uploaded <- updateRegions tex w pixels [(0, 0, w, h)]+ if uploaded+ then publish ref (Just (AtlasTexture tex gen)) >> writeIORef failed 0+ else giveUp "SDL_UpdateTexture" >> destroyTexture tex+ where+ giveUp call = do+ writeIORef failed gen+ msg <- withSdlError ("nano-ui: " ++ call ++ " failed for the " ++ show w ++ "x" ++ show h ++ " image atlas; images will not draw until it changes")+ hPutStrLn stderr msg++-- | The texture for a texture id, or null for one that is not the image+-- atlas's or an atlas not uploaded yet.+lookupImage :: ImageAtlas -> Int -> IO (Ptr SDL_Texture)+lookupImage (ImageAtlas ref _) tid+ | tid == atlasTextureId = maybe nullPtr atTexture <$> readIORef ref+ | otherwise = pure nullPtr
+ lib/NanoUI/Sdl/Internal/Input.hs view
@@ -0,0 +1,442 @@+{-# LANGUAGE OverloadedRecordDot #-}+{-# LANGUAGE NoFieldSelectors #-}+{-# OPTIONS_HADDOCK not-home #-}++-- | SDL3 event polling and waiting, translation of SDL events into+-- 'NanoUI.Input.Input', and syncing SDL's text input with the focused text+-- field.+module NanoUI.Sdl.Internal.Input+ ( SdlEvent (..)+ , pollEvents+ , waitEvent+ , pollWindowEvents+ , waitWindowEvent+ , applyEvent+ , isButtonEdge+ , scaleEventPositions+ , hasPointerEvent+ , sdlKey+ , TextInputSync+ , newTextInputSync+ , syncTextInput+ ) where++import Control.Exception (bracket)+import Control.Monad (mfilter, void, when)+import Data.Bits ((.&.))+import Data.Char (chr, isPrint, toLower)+import Data.IORef (IORef, newIORef, readIORef, writeIORef)+import Data.ByteString qualified as BS+import qualified Data.Text as T+import Data.Text (Text)+import qualified Data.Text.Encoding as TE+import Data.Word (Word32)+import Foreign.C.Types (CChar, CFloat, CUInt)+import Data.Foldable (for_)+import Data.Int (Int32)+import Data.Maybe (fromMaybe, isJust, isNothing)+import Foreign.Marshal.Alloc (alloca)+import Foreign.Marshal.Utils (maybePeek, with)+import Foreign.Ptr (Ptr)+import Foreign.Storable (Storable (..))+import GHC.Records.Compat (getField)+import SDL3.Sys.Bindgen.Runtime.PtrConst qualified as PtrConst+import NanoUI (Rect (..), V2 (..), WidgetId (..), v2Add)+import NanoUI.Backend+import NanoUI.Sdl.Internal.Display (refreshEventType)+import SDL3.Sys.Bindgen.Events (SDL_Event (..), SDL_EventType (..), SDL_KeyboardEvent)+import SDL3.Sys.Bindgen.Events qualified as Events+import SDL3.Sys.Events (pollEventSafe, waitEventSafe, waitEventTimeoutSafe)+import SDL3.Sys.Bindgen.Keycode (SDL_Keycode (..), SDL_Keymod (..))+import SDL3.Sys.Bindgen.Keycode qualified as K+import SDL3.Sys.Bindgen.Rect (SDL_Rect (..))+import SDL3.Sys.Bindgen.Stdinc (Uint32 (..))+import SDL3.Sys.Bindgen.Video (SDL_Window)+import SDL3.Sys.Bindgen.Keyboard (SDL_TextInputType (..), sDL_PROP_TEXTINPUT_TYPE_NUMBER)+import SDL3.Sys.Bindgen.Keyboard qualified as Keyboard+import SDL3.Sys.Keyboard (getModState, setTextInputAreaSafe, startTextInputWithPropertiesSafe, stopTextInputSafe)+import SDL3.Sys.Properties (createPropertiesSafe, destroyPropertiesSafe, setNumberPropertySafe)++-- | Copied SDL event data. Pointer positions use SDL window coordinates until+-- display synchronisation converts them to nano-ui's logical coordinates.+data SdlEvent+ = EvQuit+ | EvWindowChanged+ -- ^ The window's size or pixel density changed; display synchronisation+ -- reads both again.+ | EvSystemThemeChanged+ -- ^ The desktop switched between light and dark; display synchronisation+ -- reads the new setting.+ | EvKey Key Bool Modifiers+ -- ^ A key went down ('True', auto-repeats included) or up.+ | EvModifiers Modifiers+ -- ^ A key with no nano-ui 'Key' (such as a modifier) went down or up.+ -- Only the resulting modifier state is kept.+ | EvText Text+ -- ^ Typed text. It keeps the modifiers of the key event before it: SDL's+ -- text events carry none, and the state when the batch is read may have+ -- a modifier pressed after the key that typed it.+ | EvMouseMotion V2 Modifiers+ -- ^ The pointer moved to a point. The modifiers are SDL's state when the+ -- event was read, which may already count keys queued after it, so+ -- 'applyEvent' keeps those the key events left instead.+ | EvMouseButton MouseButton Bool V2 Modifiers+ -- ^ A button went down ('True') or up at a point, with the modifiers as+ -- for 'EvMouseMotion'.+ | EvMouseLeave+ -- ^ The pointer left the window.+ | EvScroll V2+ | EvDrop DropEvent+ | EvRefresh+ | EvWindowRedraw+ | EvRenderDeviceReset+ -- ^ The render device was reset, which emptied every texture. The session+ -- makes its textures again and repaints the whole window. A host that+ -- polls events itself calls 'NanoUI.Backend.Sdl.resetRenderTextures'+ -- before its next frame.+ | EvEditing Text Int Int+ -- ^ The input method's composition changed: its text, then the start and+ -- length of its caret or selection ('applyComposition'). Empty text ends+ -- the composition.+ | EvFocusLost+ -- ^ The window lost keyboard focus. Held keys are released+ -- ('releaseAllKeys') and the composition ends.+ | EvCloseRequested+ -- ^ The desktop asked to close one window. With one window open SDL asks+ -- to quit as well ('EvQuit'), which is what ends a session; with more, it+ -- is how a window learns it should close.+ | EvDisplayChanged+ -- ^ The window moved to another display, or a display's mode changed:+ -- the session reads the window's refresh rate again.+ deriving (Eq, Show)++-- | Drain every pending event, oldest first.+pollEvents :: IO [SdlEvent]+pollEvents = map snd <$> pollWindowEvents++-- | Wait for one native event, for up to the supplied milliseconds or, when+-- negative, for as long as it takes. 'Nothing' covers a timeout, an SDL+-- failure and an ignored event, so it does not imply a quit request. Call+-- from the display thread.+waitEvent :: Int -> IO (Maybe SdlEvent)+waitEvent ms = fmap snd <$> waitWindowEvent ms++-- | 'pollEvents', each event with the SDL id of the window it is for, or 0+-- for one that is for every window (a wake, a quit, a theme change).+pollWindowEvents :: IO [(Word32, SdlEvent)]+pollWindowEvents =+ alloca $ \(p :: Ptr SDL_Event) -> do+ refreshTy <- refreshEventType+ let drain acc = do+ got <- pollEventSafe p+ if got+ then decodeWindowEvent refreshTy p >>= \ev -> drain (maybe acc (: acc) ev)+ else pure (reverse acc)+ drain []++-- | 'waitEvent' with the event's window id, as 'pollWindowEvents' gives it.+waitWindowEvent :: Int -> IO (Maybe (Word32, SdlEvent))+waitWindowEvent ms =+ alloca $ \p -> do+ got <- if ms < 0 then waitEventSafe p else waitEventTimeoutSafe p (fromIntegral ms)+ if got then refreshEventType >>= \ty -> decodeWindowEvent ty p else pure Nothing++-- | Translate one SDL event with its window id (0 for events addressed to+-- every window); 'Nothing' for events the UI ignores. Every per-window event+-- (window, keyboard, text, mouse, drop and render events) keeps its window id+-- right after the common header, at byte offset 16. A lost render device,+-- which ends the session, throws.+decodeWindowEvent :: Word32 -> Ptr SDL_Event -> IO (Maybe (Word32, SdlEvent))+decodeWindowEvent refreshTy p = do+ Uint32 w <- peek p.type'+ let global ev = pure (Just (0, ev))+ winEv ev = (\wid -> Just (wid, ev)) <$> peekByteOff p 16+ if refreshTy /= 0 && w == refreshTy+ then global EvRefresh+ else case SDL_EventType (fromIntegral w) of+ Events.SDL_EVENT_QUIT -> global EvQuit+ Events.SDL_EVENT_SYSTEM_THEME_CHANGED -> global EvSystemThemeChanged+ -- A display's mode change names the display, not a window: it is for+ -- every window.+ Events.SDL_EVENT_DISPLAY_CURRENT_MODE_CHANGED -> global EvDisplayChanged+ Events.SDL_EVENT_WINDOW_DISPLAY_CHANGED -> winEv EvDisplayChanged+ Events.SDL_EVENT_WINDOW_RESIZED -> winEv EvWindowChanged+ Events.SDL_EVENT_WINDOW_PIXEL_SIZE_CHANGED -> winEv EvWindowChanged+ Events.SDL_EVENT_WINDOW_DISPLAY_SCALE_CHANGED -> winEv EvWindowChanged+ -- The window manager damaged our window surface (occlusion, compositor+ -- effects, restore) or reset render targets. The backbuffer contents are+ -- gone; the next present must be full or stale regions flash.+ Events.SDL_EVENT_WINDOW_EXPOSED -> winEv EvWindowRedraw+ Events.SDL_EVENT_WINDOW_RESTORED -> winEv EvWindowRedraw+ Events.SDL_EVENT_RENDER_TARGETS_RESET -> winEv EvWindowRedraw+ -- Every texture lost its contents, the atlases too (a Direct3D device+ -- removed by a driver update or a remote desktop reconnecting).+ Events.SDL_EVENT_RENDER_DEVICE_RESET -> winEv EvRenderDeviceReset+ Events.SDL_EVENT_RENDER_DEVICE_LOST -> ioError (userError "SDL lost the render device, and with it the renderer")+ Events.SDL_EVENT_KEY_DOWN -> peek p.key >>= winEv . keyEvent True+ Events.SDL_EVENT_KEY_UP -> peek p.key >>= winEv . keyEvent False+ Events.SDL_EVENT_TEXT_INPUT -> textInput p >>= traverse (\ev -> (,ev) <$> peekByteOff p 16)+ Events.SDL_EVENT_TEXT_EDITING -> textEditing p >>= winEv+ -- SDL stops text input while the window is in the background, which+ -- can drop the composition silently. End it here, or a field would+ -- keep showing it and routing keys to it.+ Events.SDL_EVENT_WINDOW_FOCUS_LOST -> winEv EvFocusLost+ Events.SDL_EVENT_WINDOW_CLOSE_REQUESTED -> winEv EvCloseRequested+ Events.SDL_EVENT_MOUSE_MOTION -> do+ me <- peek p.motion+ peekModifiers >>= winEv . EvMouseMotion (v2 (getField @"x" me) (getField @"y" me))+ Events.SDL_EVENT_WINDOW_MOUSE_LEAVE -> winEv EvMouseLeave+ Events.SDL_EVENT_MOUSE_BUTTON_DOWN -> mouseButton p True >>= winEv+ Events.SDL_EVENT_MOUSE_BUTTON_UP -> mouseButton p False >>= winEv+ Events.SDL_EVENT_MOUSE_WHEEL -> do+ we <- peek p.wheel+ winEv (EvScroll (v2 (getField @"x" we) (negate (getField @"y" we))))+ Events.SDL_EVENT_DROP_FILE -> dropEvent p DropFile >>= winEv+ Events.SDL_EVENT_DROP_TEXT -> dropEvent p DropText >>= winEv+ Events.SDL_EVENT_DROP_BEGIN -> dropEvent p DropBegin >>= winEv+ Events.SDL_EVENT_DROP_COMPLETE -> dropEvent p DropComplete >>= winEv+ Events.SDL_EVENT_DROP_POSITION -> dropEvent p DropPosition >>= winEv+ _ -> pure Nothing++v2 :: CFloat -> CFloat -> V2+v2 x y = V2 (realToFrac x) (realToFrac y)++-- | A key going down ('True') or up. Auto-repeats arrive as presses;+-- 'applyKey' tells them apart because the key is already held.+keyEvent :: Bool -> SDL_KeyboardEvent -> SdlEvent+keyEvent down ke = maybe (EvModifiers mods) (\k -> EvKey k down mods) (sdlKey code km)+ where+ code = fromIntegral (getField @"key" ke :: SDL_Keycode)+ km = getField @"mod" ke+ mods = modFromKeymod km++-- | The 'Key' for an SDL keycode and its modifier state. For character keys+-- SDL reports the unmodified character in the current layout (Latin letters+-- on a non-Latin layout), which becomes the 'KeyChar'.+sdlKey :: CUInt -> SDL_Keymod -> Maybe Key+sdlKey code km+ | Just named <- namedKey code = Just named+ | Just typed <- keypadChar code = keypadKey (word32 km .&. word32 K.sDL_KMOD_NUM /= 0) typed+ | code >= K.sDLK_F1 && code <= K.sDLK_F12 = Just (KeyF (fromIntegral (code - K.sDLK_F1) + 1))+ | code >= K.sDLK_F13 && code <= K.sDLK_F24 = Just (KeyF (fromIntegral (code - K.sDLK_F13) + 13))+ | code .&. K.sDLK_SCANCODE_MASK == 0 && code <= 0x10FFFF, isPrint c = Just (KeyChar (toLower c))+ | otherwise = Nothing+ where+ c = chr (fromIntegral code)++namedKey :: CUInt -> Maybe Key+namedKey code+ | code == K.sDLK_ESCAPE = Just KeyEscape+ | code == K.sDLK_RETURN = Just KeyEnter+ | code == K.sDLK_TAB = Just KeyTab+ | code == K.sDLK_BACKSPACE = Just KeyBackspace+ | code == K.sDLK_DELETE = Just KeyDelete+ | code == K.sDLK_LEFT = Just KeyLeft+ | code == K.sDLK_RIGHT = Just KeyRight+ | code == K.sDLK_UP = Just KeyUp+ | code == K.sDLK_DOWN = Just KeyDown+ | code == K.sDLK_HOME = Just KeyHome+ | code == K.sDLK_END = Just KeyEnd+ | code == K.sDLK_PAGEUP = Just KeyPageUp+ | code == K.sDLK_PAGEDOWN = Just KeyPageDown+ | code == K.sDLK_INSERT = Just KeyInsert+ | code == K.sDLK_SPACE = Just KeySpace+ | code == K.sDLK_PRINTSCREEN = Just KeyPrintScreen+ | code == K.sDLK_PAUSE = Just KeyPause+ | code == K.sDLK_CAPSLOCK = Just KeyCapsLock+ | code == K.sDLK_NUMLOCKCLEAR = Just KeyNumLock+ | code == K.sDLK_SCROLLLOCK = Just KeyScrollLock+ | code == K.sDLK_APPLICATION = Just KeyMenu+ | code == K.sDLK_MENU = Just KeyMenu+ | code == K.sDLK_KP_ENTER = Just KeyEnter+ | code == K.sDLK_KP_DIVIDE = Just (KeyChar '/')+ | code == K.sDLK_KP_MULTIPLY = Just (KeyChar '*')+ | code == K.sDLK_KP_MINUS = Just (KeyChar '-')+ | code == K.sDLK_KP_PLUS = Just (KeyChar '+')+ | code == K.sDLK_KP_EQUALS = Just (KeyChar '=')+ | otherwise = Nothing++-- | Keypad digits and decimal point, with the character each types+-- ('keypadKey').+keypadChar :: CUInt -> Maybe Char+keypadChar code+ | code == K.sDLK_KP_0 = Just '0'+ | code == K.sDLK_KP_1 = Just '1'+ | code == K.sDLK_KP_2 = Just '2'+ | code == K.sDLK_KP_3 = Just '3'+ | code == K.sDLK_KP_4 = Just '4'+ | code == K.sDLK_KP_5 = Just '5'+ | code == K.sDLK_KP_6 = Just '6'+ | code == K.sDLK_KP_7 = Just '7'+ | code == K.sDLK_KP_8 = Just '8'+ | code == K.sDLK_KP_9 = Just '9'+ | code == K.sDLK_KP_PERIOD = Just '.'+ | otherwise = Nothing++textInput :: Ptr SDL_Event -> IO (Maybe SdlEvent)+textInput p = do+ te <- peek p.text+ txt <- peekText (getField @"text" te)+ pure (EvText <$> mfilter (not . T.null) txt)++-- | The input method's composition. The session sets+-- @SDL_HINT_IME_IMPLEMENTED_UI@ to @composition@, so SDL sends it to us+-- instead of letting the input method draw it over the window.+textEditing :: Ptr SDL_Event -> IO SdlEvent+textEditing p = do+ ee <- peek p.edit+ txt <- fromMaybe "" <$> peekText (getField @"text" ee)+ let int v = fromIntegral v :: Int+ pure (EvEditing txt (int (getField @"start" ee)) (int (getField @"length" ee)))++-- | A button going down or up. SDL numbers buttons the same way as+-- 'mouseButtonNumber': left, middle, right, X1, X2 from 1, then any extra+-- buttons in order.+mouseButton :: Ptr SDL_Event -> Bool -> IO SdlEvent+mouseButton p down = do+ be <- peek p.button+ let btn = mouseButtonNumber (fromIntegral (getField @"button" be))+ EvMouseButton btn down (v2 (getField @"x" be) (getField @"y" be)) <$> peekModifiers++dropEvent :: Ptr SDL_Event -> DropType -> IO SdlEvent+dropEvent p ty = do+ de <- peek p.drop+ let -- A drag entering or finishing has no position.+ pos+ | ty == DropBegin || ty == DropComplete = Nothing+ | otherwise = Just (v2 (getField @"x" de) (getField @"y" de))+ payload <- fromMaybe "" <$> peekText (getField @"data'" de)+ pure (EvDrop (DropEvent ty pos payload))++-- | Decode an event's UTF-8 string, or 'Nothing' for a null pointer. Bytes+-- that are not UTF-8 (a dropped file named in a legacy encoding) become+-- U+FFFD rather than an exception that would end the session.+peekText :: PtrConst.PtrConst CChar -> IO (Maybe Text)+peekText = maybePeek (fmap TE.decodeUtf8Lenient . BS.packCString) . PtrConst.unsafeToPtr++peekModifiers :: IO Modifiers+peekModifiers = modFromKeymod <$> getModState++modFromKeymod :: SDL_Keymod -> Modifiers+modFromKeymod km =+ modifiersFromBits+ (word32 km)+ (word32 K.sDL_KMOD_SHIFT)+ (word32 K.sDL_KMOD_CTRL)+ (word32 K.sDL_KMOD_ALT)+ (word32 K.sDL_KMOD_GUI)++word32 :: Integral a => a -> Word32+word32 = fromIntegral++-- | Accumulate one event into a frame's input. Window changes and quits need+-- session handling; this does not update size or convert coordinates.+applyEvent :: Input -> SdlEvent -> Input+applyEvent inp ev =+ case ev of+ EvKey k down mods -> (applyKey k down inp) {inputModifiers = mods}+ EvModifiers mods -> inp {inputModifiers = mods}+ EvText txt -> inp {inputChars = inputChars inp <> txt}+ -- SDL's modifiers change only with key events, which carry their own.+ EvMouseMotion pos _ -> inp {inputMousePos = pos}+ EvMouseButton btn down pos _ -> (applyMouseButton btn down inp) {inputMousePos = pos}+ EvMouseLeave -> applyPointerLeave inp+ EvScroll delta -> inp {inputScroll = v2Add (inputScroll inp) delta}+ EvDrop dropEv -> inp {inputDrops = appendDropEvent dropEv (inputDrops inp)}+ EvEditing txt start len -> applyComposition txt start len inp+ EvFocusLost -> releaseAllKeys (applyComposition "" 0 0 inp)+ EvWindowRedraw -> inp {inputWindowRedraw = True}+ EvRenderDeviceReset -> inp {inputWindowRedraw = True}+ -- A wake asks for a frame, not a repaint: the session runs one, and its+ -- damage decides what is presented, if anything.+ EvRefresh -> inp+ EvQuit -> inp+ EvWindowChanged -> inp+ EvSystemThemeChanged -> inp+ EvCloseRequested -> inp+ EvDisplayChanged -> inp++-- | Events with their pointer and drop positions moved from window+-- coordinates into layout units, which a UI zoom divides. Each event keeps+-- its own position: a press the runner gives a frame of its own is hit-tested+-- where it happened, not where the pointer is by the time the batch is read.+scaleEventPositions :: Float -> [SdlEvent] -> [SdlEvent]+scaleEventPositions zoom+ | zoom == 1 || zoom <= 0 = id+ | otherwise = map $ \case+ EvMouseMotion p m -> EvMouseMotion (logical p) m+ EvMouseButton b d p m -> EvMouseButton b d (logical p) m+ EvDrop (DropEvent t p d) -> EvDrop (DropEvent t (logical <$> p) d)+ e -> e+ where+ logical (V2 x y) = V2 (x / zoom) (y / zoom)++-- | Whether a batch moved or pressed the pointer.+hasPointerEvent :: [SdlEvent] -> Bool+hasPointerEvent = any $ \case+ EvMouseMotion {} -> True+ EvMouseButton {} -> True+ _ -> False++-- | Whether an event is a button press or release and should end an input batch.+isButtonEdge :: SdlEvent -> Bool+isButtonEdge = \case+ EvMouseButton {} -> True+ _ -> False++-- | The text input state last sent to SDL: the focused widget, the running+-- purpose ('Nothing' while stopped), and the text input area in window+-- coordinates.+newtype TextInputSync = TextInputSync (IORef (WidgetId, Maybe InputPurpose, Maybe (SDL_Rect, Int32)))++-- | A fresh sync: nothing sent to SDL yet, text input stopped.+newTextInputSync :: IO TextInputSync+newTextInputSync = TextInputSync <$> newIORef (WidgetId 0, Nothing, Nothing)++-- | Update SDL's text input after a frame drawn with @inp@ in window @win@,+-- where one window coordinate is @zoom@ layout units. Call it on every drawn+-- frame. Returns whether text input was started or restarted.+--+-- Text input runs only while a widget takes text ('textInputArea'), with+-- that widget's 'InputPurpose'. Otherwise it is stopped, so no input method+-- composes invisibly and no on-screen keyboard lingers. It restarts when the+-- purpose changes, or when focus moves during a composition, so the+-- composition is dropped instead of carried into the next widget. The input+-- method gets the widget's area so its candidate window sits by the caret.+syncTextInput :: TextInputSync -> Ptr SDL_Window -> Float -> Context -> Input -> IO Bool+syncTextInput (TextInputSync ref) win zoom ctx inp = do+ focus <- getFocusId ctx+ area <- textInputArea ctx+ (lastFocus, running, lastArea) <- readIORef ref+ let purpose = textInputAreaPurpose <$> area+ moved = focus /= lastFocus && isJust (inputComposition inp)+ restart = isJust running && isJust purpose && (moved || purpose /= running)+ started = isJust purpose && (isNothing running || restart)+ native = toWindow <$> area+ when (isJust running && (isNothing purpose || restart)) $ void (stopTextInputSafe win)+ when started $ for_ purpose (startTextInput win)+ for_ native $ \(r, cursor) ->+ when (started || native /= lastArea) $+ -- A safe FFI call: the input method may need a round trip to answer.+ with r $ \rp -> void (setTextInputAreaSafe win (PtrConst.unsafeFromPtr rp) cursor)+ writeIORef ref (focus, purpose, native)+ pure started+ where+ toWindow TextInputArea {textInputAreaRect = Rect x y w h, textInputAreaCursor = cursor} =+ let at :: Integral b => Float -> b+ at v = round (v * zoom)+ in (SDL_Rect (at x) (at y) (max 1 (at w)) (max 1 (at h)), at cursor)++-- | Start text input for a purpose. It picks the on-screen keyboard: a+-- password's input hides what is typed, and a number's keyboard has digits.+startTextInput :: Ptr SDL_Window -> InputPurpose -> IO ()+startTextInput win purpose =+ bracket createPropertiesSafe destroyPropertiesSafe $ \props -> do+ _ <- BS.useAsCString sDL_PROP_TEXTINPUT_TYPE_NUMBER $ \name ->+ setNumberPropertySafe props (PtrConst.unsafeFromPtr name) (fromIntegral textType)+ void (startTextInputWithPropertiesSafe win props)+ where+ SDL_TextInputType textType = case purpose of+ InputNormal -> Keyboard.SDL_TEXTINPUT_TYPE_TEXT+ InputSecure -> Keyboard.SDL_TEXTINPUT_TYPE_TEXT_PASSWORD_HIDDEN+ InputNumeric -> Keyboard.SDL_TEXTINPUT_TYPE_NUMBER
+ lib/NanoUI/Sdl/Internal/NanoUIFont.hs view
@@ -0,0 +1,21 @@+{-# OPTIONS_HADDOCK not-home #-}++-- | Font selection for the SDL backend.+module NanoUI.Sdl.Internal.NanoUIFont+ ( NanoUIFont (..)+ ) where++-- | SDL text font selection.+-- 'DefaultFont' uses the embedded Inter subset.+-- 'FontSearch' tries each family name against the platform font directories+-- (walked recursively at runtime). Names are matched against font file names,+-- ignoring case, spaces, @-@ and @_@, not against the families the fonts+-- declare; @monospace@, @sans-serif@ and @serif@ stand for lists of common+-- families. When nothing matches, the embedded font is used as fallback.+-- 'FontFilePath' loads that file and does not search. A file that will not+-- open is replaced by the embedded font.+data NanoUIFont+ = DefaultFont+ | FontSearch [String]+ | FontFilePath FilePath+ deriving (Eq, Show)
+ lib/NanoUI/Sdl/Internal/Pacing.hs view
@@ -0,0 +1,81 @@+-- | How an SDL session paces animation: whether its presents wait for+-- vertical sync ('notePresent', 'presentPaces'), the refresh period of the+-- window's display, and the event wait between the frames of an animation+-- whose presents do not wait ('sdlPacingMs').+module NanoUI.Sdl.Internal.Pacing+ ( notePresent+ , restartPresentProbe+ , presentPaces+ , refreshDisplayRate+ , refreshPeriodOf+ , sdlPacingMs+ , sdlLivePacingMs+ ) where++import Control.Monad (when)+import Data.IORef (modifyIORef', readIORef, writeIORef)+import Foreign.Ptr (Ptr)+import NanoUI.Runner (pacingMsFor)+import NanoUI.Sdl.Internal.Display (queryWindowRefreshHz)+import NanoUI.Sdl.Internal.Env (PresentProbe (..), SdlEnv (..))+import SDL3.Sys.Bindgen.Video (SDL_Window)++-- | Presents in a row, each less than half a refresh after the last, that+-- show vertical sync is not honoured. A driver may queue two or three+-- frames before a present blocks, so a few fast presents prove nothing.+vsyncProbeFrames :: Int+vsyncProbeFrames = 10++-- | Note a present that returned at time @t@ (a session with 'sdlVsync'+-- only), and give up on vertical sync once 'vsyncProbeFrames' presents in a+-- row returned sooner than half a refresh apart.+notePresent :: SdlEnv -> Double -> IO ()+notePresent env t = when (sdlVsync env) $+ readIORef (sdlPresentProbe env) >>= \case+ VsyncIgnored -> pure ()+ PresentProbe lastT n -> do+ period <- readIORef (sdlRefreshPeriodRef env)+ let n' = if t - lastT < period / 2 then n + 1 else 0+ writeIORef (sdlPresentProbe env) $! if n' >= vsyncProbeFrames then VsyncIgnored else PresentProbe t n'++-- | Start counting presents afresh, after presents that ran with vertical+-- sync off on purpose (the resize watch's). A finding that vertical sync is+-- not honoured stays.+restartPresentProbe :: SdlEnv -> IO ()+restartPresentProbe env = modifyIORef' (sdlPresentProbe env) $ \case+ VsyncIgnored -> VsyncIgnored+ PresentProbe _ _ -> PresentProbe 0 0++-- | Whether the last frame's present waited for the display: it presented,+-- 'sdlVsync' asked for vertical sync, and the presents so far have not+-- shown that the driver ignores it.+presentPaces :: SdlEnv -> IO Bool+presentPaces env+ | sdlVsync env = (&&) <$> readIORef (sdlLastPresented env) <*> ((/= VsyncIgnored) <$> readIORef (sdlPresentProbe env))+ | otherwise = pure False++-- | Read the window's refresh rate again, after it moved to another display+-- or its display changed mode, and start the vertical sync probe afresh:+-- another display's driver may honour it.+refreshDisplayRate :: SdlEnv -> IO ()+refreshDisplayRate env = do+ writeIORef (sdlRefreshPeriodRef env) =<< refreshPeriodOf (sdlWindow env)+ writeIORef (sdlPresentProbe env) (PresentProbe 0 0)++-- | The refresh period of a window's display, in seconds; 60 Hz's when SDL+-- cannot say.+refreshPeriodOf :: Ptr SDL_Window -> IO Double+refreshPeriodOf win = (\hz -> if hz > 0 then 1 / realToFrac hz else 1 / 60) <$> queryWindowRefreshHz win++-- | 'sdlPacingMs' for the window's current display ('sdlRefreshPeriodRef'),+-- whether or not presents wait for vertical sync: the wait for a frame that+-- presents nothing, or whose present does not wait.+sdlLivePacingMs :: SdlEnv -> IO Int+sdlLivePacingMs env = pacingMsFor <$> readIORef (sdlRefreshPeriodRef env)++-- | The event wait while a window animates. With vsync on, presents throttle+-- the loop. With vsync off a live animation would spin at max speed, so wait+-- 'pacingMsFor' the frame period: SDL_WaitEventTimeout overruns by about a+-- millisecond, and the slack keeps the wait from ending past the boundary.+sdlPacingMs :: SdlEnv -> Int+sdlPacingMs env = if sdlVsync env then 16 else pacingMsFor (sdlRefreshPeriod env)
+ lib/NanoUI/Sdl/Internal/Render.hs view
@@ -0,0 +1,634 @@+{-# OPTIONS_HADDOCK not-home #-}++-- | Submit nano-ui draw batches to SDL with texture binding, clip+-- deduplication, range coalescing, and damage clipping.+module NanoUI.Sdl.Internal.Render+ ( RenderBatch+ , newRenderBatch+ , destroyRenderBatch+ , flushRenderBatch+ , discardRenderBatch+ , renderDrawDataPass+ , presentGpuRetain+ , glyphPageTexture+ , snapDamage+ )+where++import Control.Exception (onException)+import Control.Monad (unless, void, when)+import Control.Monad.Primitive (RealWorld)+import Data.ByteString.Unsafe qualified as BSU+import Data.Maybe (isJust)+import Data.Primitive.ByteArray (ByteArray, copyByteArrayToAddr, sizeofByteArray)+import Data.Primitive.PrimArray (MutablePrimArray, newPrimArray, readPrimArray, setPrimArray, writePrimArray)+import Data.Primitive.SmallArray (SmallArray, indexSmallArray, newSmallArray, sizeofSmallArray, smallArrayFromList, unsafeFreezeSmallArray, writeSmallArray)+import Data.Text.Encoding qualified as TE+import Data.Vector.Unboxed qualified as U+import Data.Word (Word64, Word8)+import Foreign.C.Types (CFloat (..), CInt (..))+import Foreign.ForeignPtr (withForeignPtr)+import Foreign.Marshal.Alloc (allocaBytes)+import Foreign.Marshal.Array (allocaArray)+import Foreign.Ptr (Ptr, castPtr, nullPtr, ptrToWordPtr, wordPtrToPtr)+import Foreign.Storable (pokeElemOff)+import NanoUI (Color, Rect (..), colorA, colorB, colorG, colorR)+import NanoUI.Backend+import NanoUI.Sdl.Internal.Gpu+ ( GpuState+ , destroyGpuState+ , gpuBindShader+ , gpuEnsureWhiteTex+ , gpuHasDevice+ , newGpuState+ , presentGpuRetainImpl+ )+import NanoUI.Sdl.Internal.Image (ImageAtlas, lookupImage)+import NanoUI.Sdl.Internal.TargetPool+ ( TargetPool+ , acquireTarget+ , bindTarget+ , destroyTargetPool+ , lookupTarget+ , newTargetPool+ , releaseTarget+ )+import SDL3.Sys.Bindgen.Pixels (SDL_FColor (..))+import SDL3.Sys.Bindgen.Rect (SDL_FPoint (..))+import SDL3.Sys.Bindgen.Render (SDL_Renderer, SDL_Texture, SDL_Vertex (..))+import SDL3.Sys.Bindgen.Render qualified as RenderBind+import SDL3.Sys.Bindgen.Runtime.PtrConst qualified as PtrConst+import SDL3.Sys.Bindgen.Video (SDL_Window)+import SDL3.Sys.Blendmode qualified as Blend+import SDL3.Sys.Render+ ( getRenderTarget+ , renderClearSafe+ , renderGeometry+ , setGPURenderState+ , setRenderDrawColorSafe+ , setRenderTextureAddressMode+ , setTextureBlendMode+ )+import SDL3.Sys.Version (getVersion)++-- Unboxed slot indices inside 'rbState' so per-command clip deduplication and+-- range coalescing perform zero heap allocations.+sHasClip, sClipX, sClipY, sClipW, sClipH :: Int+sHasClip = 0+sClipX = 1+sClipY = 2+sClipW = 3+sClipH = 4++sPendingN, sPendingStart, sPendingVertCount, sPendingVerts, sPendingIndices, sPendingTex :: Int+sPendingN = 5+sPendingStart = 6+sPendingVertCount = 7+sPendingVerts = 8+sPendingIndices = 9+sPendingTex = 10++stateSlots :: Int+stateSlots = 11++{-# INLINE intToWord #-}+intToWord :: Int -> Word+intToWord = fromIntegral++{-# INLINE wordToInt #-}+wordToInt :: Word -> Int+wordToInt = fromIntegral++{-# INLINE ptrToWord #-}+ptrToWord :: Ptr a -> Word+ptrToWord = fromIntegral . ptrToWordPtr++{-# INLINE wordToPtr #-}+wordToPtr :: Word -> Ptr a+wordToPtr = wordPtrToPtr . fromIntegral++-- | Session-owned coalescing state, clip deduplication, GPU shader cache,+-- Tier 2 target pool, and OpenGL 3.2 direct batch handle.+data RenderBatch = RenderBatch+ { rbRenderer :: {-# UNPACK #-} !(Ptr SDL_Renderer)+ , rbGl :: {-# UNPACK #-} !(Ptr ())+ , rbGpu :: !GpuState+ , rbTargets :: !TargetPool+ , rbState :: {-# UNPACK #-} !(MutablePrimArray RealWorld Word)+ }++-- | Create a persistent render batch. Reusing one batch across frames avoids+-- per-frame C/GPU state allocation; flush after each render pass.+newRenderBatch :: Ptr SDL_Renderer -> IO RenderBatch+newRenderBatch ren = do+ gl <- c_glCreate ren+ if gl == nullPtr+ then fail "nano_ui_gl_create failed"+ else do+ -- Every UV the batches submit lies in [0, 1]. Left on AUTO, SDL 3.4 scans+ -- all vertices on every textured call to pick clamp vs wrap.+ ver <- getVersion+ when (ver >= 3004000) $+ void $ setRenderTextureAddressMode ren RenderBind.SDL_TEXTURE_ADDRESS_CLAMP RenderBind.SDL_TEXTURE_ADDRESS_CLAMP+ gpu <- newGpuState ren+ targets <- newTargetPool+ st <- newPrimArray stateSlots+ setPrimArray st 0 stateSlots 0+ pure (RenderBatch ren gl gpu targets st)++-- | Free a render batch and its pooled targets, GPU shaders, and GL buffers.+destroyRenderBatch :: RenderBatch -> IO ()+destroyRenderBatch batch = do+ flushAndLeaveGl batch+ destroyTargetPool (rbTargets batch)+ destroyGpuState (rbGpu batch)+ c_glDestroy (rbGl batch)++{-# INLINE flushAndLeaveGl #-}+flushAndLeaveGl :: RenderBatch -> IO ()+flushAndLeaveGl batch = do+ flushRenderBatch batch+ c_glLeavePass (rbGl batch)++{-# INLINE resetBatchClip #-}+resetBatchClip :: RenderBatch -> IO ()+resetBatchClip batch = do+ writePrimArray (rbState batch) sHasClip 0+ c_glSetClip (rbGl batch) 0 0 0 0 0++{-# INLINE setBatchClip #-}+setBatchClip :: RenderBatch -> Float -> Maybe Rect -> IO ()+setBatchClip batch _ Nothing = do+ let !st = rbState batch+ !was <- readPrimArray st sHasClip+ when (was /= 0) $ do+ flushRenderBatch batch+ writePrimArray st sHasClip 0+ c_glSetClip (rbGl batch) 0 0 0 0 0+setBatchClip batch scale (Just r) = do+ let !(x0, y0, x1, y1) = clipPixelEdges scale r+ !cw = max 1 (x1 - x0)+ !ch = max 1 (y1 - y0)+ !xW = intToWord x0+ !yW = intToWord y0+ !wW = intToWord cw+ !hW = intToWord ch+ !st = rbState batch+ !was <- readPrimArray st sHasClip+ !ox <- readPrimArray st sClipX+ !oy <- readPrimArray st sClipY+ !ow <- readPrimArray st sClipW+ !oh <- readPrimArray st sClipH+ unless (was /= 0 && ox == xW && oy == yW && ow == wW && oh == hW) $ do+ flushRenderBatch batch+ writePrimArray st sHasClip 1+ writePrimArray st sClipX xW+ writePrimArray st sClipY yW+ writePrimArray st sClipW wW+ writePrimArray st sClipH hW+ c_glSetClip (rbGl batch) 1 (fromIntegral x0) (fromIntegral y0) (fromIntegral cw) (fromIntegral ch)++-- | Draw what the batch has queued.+{-# INLINE flushRenderBatch #-}+flushRenderBatch :: RenderBatch -> IO ()+flushRenderBatch batch = do+ let !st = rbState batch+ !n <- wordToInt <$> readPrimArray st sPendingN+ when (n > 0) (flushNonEmpty batch n)++{-# NOINLINE flushNonEmpty #-}+flushNonEmpty :: RenderBatch -> Int -> IO ()+flushNonEmpty batch !n = do+ let !st = rbState batch+ !start <- wordToInt <$> readPrimArray st sPendingStart+ !vc <- wordToInt <$> readPrimArray st sPendingVertCount+ !vpW <- readPrimArray st sPendingVerts+ !ipW <- readPrimArray st sPendingIndices+ !texW <- readPrimArray st sPendingTex+ writePrimArray st sPendingN 0+ writePrimArray st sPendingStart 0+ writePrimArray st sPendingTex 0+ when (n >= 3) $+ c_glDrawPlain+ (rbGl batch)+ (wordToPtr vpW)+ (fromIntegral vc)+ (wordToPtr ipW)+ (fromIntegral start)+ (fromIntegral n)+ (wordToPtr texW)++-- | Drop what the batch has queued without drawing it.+discardRenderBatch :: RenderBatch -> IO ()+discardRenderBatch batch = do+ let !st = rbState batch+ writePrimArray st sPendingN 0+ writePrimArray st sPendingStart 0+ writePrimArray st sPendingTex 0+ c_glLeavePass (rbGl batch)++{-# INLINE rangeIsVisible #-}+rangeIsVisible :: Ptr Word8 -> Int -> Ptr Word8 -> Int -> Int -> Maybe Rect -> IO Bool+rangeIsVisible _ _ _ _ _ Nothing = pure True+rangeIsVisible vp vertCount ip start idxN (Just (Rect dx dy dw dh))+ | dw <= 0 || dh <= 0 = pure True+ | otherwise =+ (/= 0)+ <$> c_rangeVisible+ vp+ (fromIntegral vertCount)+ ip+ (fromIntegral start)+ (fromIntegral idxN)+ (realToFrac dx)+ (realToFrac dy)+ (realToFrac dw)+ (realToFrac dh)++{-# INLINE queueRange #-}+queueRange ::+ RenderBatch ->+ Ptr Word8 -> Int ->+ Ptr Word8 -> Int -> Int ->+ Ptr SDL_Texture ->+ Maybe Rect ->+ IO ()+queueRange batch vp vertCount ip idxStart idxN tex mDmg =+ when (vertCount > 0 && idxN >= 3 && vp /= nullPtr && ip /= nullPtr) $ do+ let !start = max 0 idxStart+ vis <- rangeIsVisible vp vertCount ip start idxN mDmg+ when vis $ do+ let !st = rbState batch+ !vpW = ptrToWord vp+ !ipW = ptrToWord ip+ !texW = ptrToWord tex+ !pendN <- wordToInt <$> readPrimArray st sPendingN+ !pendStart <- wordToInt <$> readPrimArray st sPendingStart+ !pendVp <- readPrimArray st sPendingVerts+ !pendIp <- readPrimArray st sPendingIndices+ !pendTex <- readPrimArray st sPendingTex+ if pendN > 0 && pendVp == vpW && pendIp == ipW && pendTex == texW && pendStart + pendN == start+ then do+ writePrimArray st sPendingN (intToWord (pendN + idxN))+ !pendVc <- wordToInt <$> readPrimArray st sPendingVertCount+ when (vertCount > pendVc) $+ writePrimArray st sPendingVertCount (intToWord vertCount)+ else do+ flushRenderBatch batch+ writePrimArray st sPendingVerts vpW+ writePrimArray st sPendingIndices ipW+ writePrimArray st sPendingTex texW+ writePrimArray st sPendingStart (intToWord start)+ writePrimArray st sPendingN (intToWord idxN)+ writePrimArray st sPendingVertCount (intToWord vertCount)++-- | Shared null-filled page table for passes without a glyph atlas.+emptyGlyphPages :: SmallArray (Ptr SDL_Texture)+emptyGlyphPages = smallArrayFromList (replicate glyphAtlasPages nullPtr)++-- | Flush any dirty glyph atlas pages and snapshot their textures once before+-- a draw pass begins so SDL_UpdateTexture never mutates OpenGL state mid-pass.+resolveGlyphPages :: Ptr () -> IO (SmallArray (Ptr SDL_Texture))+resolveGlyphPages glyphs+ | glyphs == nullPtr = pure emptyGlyphPages+ | otherwise = do+ arr <- newSmallArray glyphAtlasPages nullPtr+ let go !p+ | p >= glyphAtlasPages = unsafeFreezeSmallArray arr+ | otherwise = do+ tex <- glyphPageTexture glyphs p+ writeSmallArray arr p tex+ go (p + 1)+ go 0++-- | Draw every command in layer order, clipped to its own rect and to+-- the damage. A full repaint clears the target to 'drawClear' first.+--+-- The renderer must be at render scale 1: positions are multiplied by the+-- scale here, and clips are whole device pixels. The pass submits+-- everything it queued before it returns, while the draw data's buffers+-- are held; a pass that throws drops what it had queued instead.+renderDrawDataPass ::+ RenderBatch+ -> Ptr SDL_Renderer+ -> Float+ -- ^ Device pixels per layout unit.+ -> DrawData+ -> ImageAtlas+ -> Ptr ()+ -- ^ The glyph atlas, whose pages text draws from ('glyphPageTexture').+ -> Damage+ -> IO ()+renderDrawDataPass batch ren scale drawData images glyphs damage =+ unless (damageIsEmpty damage) $ do+ let !vertCount = drawVertexCount drawData+ !indexCount = fromIntegral (drawIndexCount drawData)+ !st = rbState batch+ !imgTex <- lookupImage images atlasTextureId+ !glyphPages <- resolveGlyphPages glyphs+ writePrimArray st sHasClip 0+ writePrimArray st sPendingN 0+ c_glBeginPass (rbGl batch) (realToFrac scale) indexCount+ mDamage <- case damage of+ DamageFull -> do+ let clear = drawClear drawData+ void $ setRenderDrawColorSafe ren (colorR clear) (colorG clear) (colorB clear) (colorA clear)+ void $ renderClearSafe ren+ pure Nothing+ -- The draw list starts a clip frame with its own page backdrop, so a+ -- clip needs no clear here.+ DamageClip r -> Just r <$ setBatchClip batch scale (Just r)+ let !calls = drawShaderCalls drawData+ !uBytes = drawUniformBytes drawData+ !spans = drawEffectSpans drawData+ !cmds = drawCommands drawData+ !nCmds = U.length cmds+ -- The batch keeps the vertex and index pointers until it flushes, so+ -- the last flush is inside the buffers' scope.+ ( withForeignPtr (drawVertices drawData) $ \vp ->+ withForeignPtr (drawIndices drawData) $ \ip -> do+ if sizeofSmallArray spans == 0+ then+ let go !i = when (i < nCmds) $ do+ let !cmd = U.unsafeIndex cmds i+ !count = fromIntegral (cmdIndexCount cmd)+ !shIdx = fromIntegral (cmdShader cmd) :: Int+ when (count >= 3) $ case cmdEffectiveClip mDamage cmd of+ Nothing -> pure ()+ Just mClip -> do+ setBatchClip batch scale mClip+ let !texId = cmdTextureId cmd+ !page = textureGlyphPage texId+ !tex+ | page >= 0 = indexSmallArray glyphPages page+ | texId == atlasTextureId = imgTex+ | otherwise = nullPtr+ !idxOff = fromIntegral (cmdIndexOffset cmd)+ if shIdx > 0 && shIdx <= sizeofSmallArray calls+ then+ drawShaderCmd+ batch vp vertCount ip idxOff count tex mDamage+ (indexSmallArray calls (shIdx - 1)) uBytes+ else+ queueRange batch vp vertCount ip idxOff count tex mDamage+ go (i + 1)+ in go 0+ else+ renderEffectSpansPass batch ren scale vertCount vp ip imgTex glyphPages calls uBytes spans cmds mDamage+ flushRenderBatch batch+ writePrimArray st sHasClip 0+ c_glEndPass (rbGl batch)+ )+ `onException` discardRenderBatch batch++{-# NOINLINE renderEffectSpansPass #-}+renderEffectSpansPass ::+ RenderBatch ->+ Ptr SDL_Renderer ->+ Float ->+ Int ->+ Ptr Word8 ->+ Ptr Word8 ->+ Ptr SDL_Texture ->+ SmallArray (Ptr SDL_Texture) ->+ SmallArray ShaderCall ->+ ByteArray ->+ SmallArray EffectSpan ->+ U.Vector DrawCmd ->+ Maybe Rect ->+ IO ()+renderEffectSpansPass batch ren scale vertCount vp ip imgTex glyphPages calls uBytes spans cmds mDamage = do+ rootTarget <- getRenderTarget ren+ let drawCmd curDmg !ox !oy cmd = do+ let !count = fromIntegral (cmdIndexCount cmd)+ !shIdx = fromIntegral (cmdShader cmd) :: Int+ when (count >= 3) $ case cmdEffectiveClip curDmg cmd of+ Nothing -> pure ()+ Just mClip -> do+ setBatchClip batch scale (shiftClip (-ox) (-oy) mClip)+ let !texId = cmdTextureId cmd+ !page = textureGlyphPage texId+ !tex+ | page >= 0 = indexSmallArray glyphPages page+ | texId == atlasTextureId = imgTex+ | otherwise = nullPtr+ !idxOff = fromIntegral (cmdIndexOffset cmd)+ if shIdx > 0 && shIdx <= sizeofSmallArray calls+ then+ drawShaderCmd+ batch vp vertCount ip idxOff count tex curDmg+ (indexSmallArray calls (shIdx - 1)) uBytes+ else+ queueRange batch vp vertCount ip idxOff count tex curDmg+ drv =+ EffectDriver+ { edScale = scale+ , edFlipY = False+ , edPreparePasses = \passes ->+ pure $+ if all (\sc -> let p = scProgram sc in isJust (spSpirv p) || isJust (spMsl p) || isJust (spGlsl150 p)) passes+ then Just passes+ else Nothing+ , edAcquireTarget = acquireTarget ren (rbTargets batch) (flushAndLeaveGl batch)+ , edReleaseTarget = releaseTarget (rbTargets batch)+ , edBindTarget = \slot clr ox oy -> do+ ok <- bindTarget ren (rbTargets batch) (flushAndLeaveGl batch) (resetBatchClip batch) slot rootTarget clr+ if not ok+ then pure False+ else do+ c_glSetOrigin (rbGl batch) (realToFrac ox) (realToFrac oy)+ pure True+ , edFlush = flushRenderBatch batch+ , edEmitPlain = \_ _ _ ox oy curDmg from to ->+ let loop !i = when (i < to) (drawCmd curDmg ox oy (U.unsafeIndex cmds i) >> loop (i + 1))+ in loop from+ , edAfterSpanContent = \_ -> pure ()+ , edCompositePass = \_ sc pd _ _ -> do+ unless (epdIntermediate pd) $+ setBatchClip batch scale (epdClip pd)+ compositeEffectPass batch sc uBytes pd+ }+ execEffectSpans drv spans 0 (-1) (0, 0) 0 0 mDamage 0 (U.length cmds)++-- | The texture of a glyph atlas page: null for a page never opened, one past+-- the last, or a null atlas.+glyphPageTexture :: Ptr () -> Int -> IO (Ptr SDL_Texture)+glyphPageTexture atlas = textAtlasTexture atlas . fromIntegral++-- | Present an opaque retained texture directly to the SDL 3.4 GPU swapchain+-- at 1:1 pixels while live-resizing away from SDL 3.4's internal GPU+-- backbuffer size. Returns 'False' when the standard copy-and-present path+-- should run instead (steady frames, SDL 3.5+, or non-GPU renderers).+presentGpuRetain :: RenderBatch -> Ptr SDL_Window -> Ptr SDL_Texture -> Int -> Int -> Bool -> Color -> IO Bool+presentGpuRetain batch =+ presentGpuRetainImpl (rbRenderer batch) (rbGpu batch) (flushAndLeaveGl batch) (resetBatchClip batch)++{-# NOINLINE drawShaderCmd #-}+drawShaderCmd ::+ RenderBatch ->+ Ptr Word8 -> Int ->+ Ptr Word8 -> Int -> Int ->+ Ptr SDL_Texture ->+ Maybe Rect ->+ ShaderCall ->+ ByteArray ->+ IO ()+drawShaderCmd batch vp vertCount ip idxStart idxCount tex mDmg sc uniformBytes =+ when (vertCount > 0 && idxCount >= 3 && vp /= nullPtr && ip /= nullPtr) $ do+ let !start = max 0 idxStart+ vis <- rangeIsVisible vp vertCount ip start idxCount mDmg+ when vis $ do+ flushRenderBatch batch+ let prog = scProgram sc+ !uOff = scUniformOffset sc+ !uLen = min (scUniformLength sc) (max 0 (sizeofByteArray uniformBytes - uOff))+ runWithUniforms uPtr len+ | gpuHasDevice (rbGpu batch) = do+ let ren = rbRenderer batch+ tex' <- if tex /= nullPtr then pure tex else gpuEnsureWhiteTex ren (rbGpu batch)+ if tex' == nullPtr+ then pure False+ else do+ bound <- gpuBindShader ren (rbGpu batch) prog (scHash sc) (spNeedsTex prog) uPtr len+ if not bound+ then pure False+ else do+ ok <-+ c_sdlDrawRaw+ (rbGl batch) tex' vp (fromIntegral vertCount)+ ip (fromIntegral start) (fromIntegral idxCount)+ void $ setGPURenderState ren nullPtr+ pure (ok /= 0)+ | Just glslText <- spGlsl150 prog =+ BSU.unsafeUseAsCStringLen (TE.encodeUtf8 glslText) $ \(glslPtr, glslLen) ->+ (/= 0)+ <$> c_glDrawShader+ (rbGl batch) vp (fromIntegral vertCount)+ ip (fromIntegral start) (fromIntegral idxCount)+ tex (scHash sc)+ (castPtr glslPtr) (fromIntegral glslLen)+ uPtr (fromIntegral len)+ | otherwise = pure False+ drawn <-+ if uLen > 0+ then allocaBytes uLen $ \uPtr -> copyByteArrayToAddr uPtr uniformBytes uOff uLen >> runWithUniforms uPtr uLen+ else runWithUniforms nullPtr 0+ unless drawn $+ queueRange batch vp vertCount ip start idxCount nullPtr Nothing++{-# NOINLINE compositeEffectPass #-}+compositeEffectPass :: RenderBatch -> ShaderCall -> ByteArray -> EffectPassDraw -> IO ()+compositeEffectPass batch sc uniformBytes pd = do+ flushRenderBatch batch+ mSrc <- lookupTarget (rbTargets batch) (epdSrcSlot pd)+ case mSrc of+ Nothing -> pure ()+ Just srcTex ->+ withEffectUniforms sc uniformBytes pd $ \uPtr uLen -> do+ let ren = rbRenderer batch+ prog = scProgram sc+ done <-+ if gpuHasDevice (rbGpu batch)+ then do+ bound <- gpuBindShader ren (rbGpu batch) prog (scHash sc) True uPtr uLen+ if not bound+ then pure False+ else do+ void $ setTextureBlendMode srcTex Blend.SDL_BLENDMODE_BLEND+ void $ renderQuad ren srcTex pd+ void $ setGPURenderState ren nullPtr+ pure True+ else case spGlsl150 prog of+ Just glslText ->+ BSU.unsafeUseAsCStringLen (TE.encodeUtf8 glslText) $ \(glslPtr, glslLen) ->+ (/= 0)+ <$> c_glCompositeEffect+ (rbGl batch) srcTex+ (realToFrac (epdDstX pd)) (realToFrac (epdDstY pd))+ (realToFrac (epdDstW pd)) (realToFrac (epdDstH pd))+ (realToFrac (epdU0 pd)) (realToFrac (epdV0 pd))+ (realToFrac (epdU1 pd)) (realToFrac (epdV1 pd))+ (scHash sc) (castPtr glslPtr) (fromIntegral glslLen)+ uPtr (fromIntegral uLen)+ Nothing -> pure False+ -- Fallback: blit the offscreen premultiplied target unshaded so the+ -- wrapped subtree never disappears on shader compile failure.+ unless done $ do+ c_glLeavePass (rbGl batch)+ void $ setTextureBlendMode srcTex Blend.SDL_BLENDMODE_BLEND_PREMULTIPLIED+ void $ renderQuad ren srcTex pd+ void $ setTextureBlendMode srcTex Blend.SDL_BLENDMODE_BLEND++renderQuad :: Ptr SDL_Renderer -> Ptr SDL_Texture -> EffectPassDraw -> IO Bool+renderQuad ren srcTex pd = do+ let !px = realToFrac (epdDstX pd)+ !py = realToFrac (epdDstY pd)+ !pw = realToFrac (epdDstW pd)+ !ph = realToFrac (epdDstH pd)+ !u0 = realToFrac (epdU0 pd)+ !v0 = realToFrac (epdV0 pd)+ !u1 = realToFrac (epdU1 pd)+ !v1 = realToFrac (epdV1 pd)+ !white = SDL_FColor 1 1 1 1+ allocaArray 4 $ \qPtr -> do+ pokeElemOff qPtr 0 (SDL_Vertex (SDL_FPoint px py) white (SDL_FPoint u0 v0))+ pokeElemOff qPtr 1 (SDL_Vertex (SDL_FPoint (px + pw) py) white (SDL_FPoint u1 v0))+ pokeElemOff qPtr 2 (SDL_Vertex (SDL_FPoint (px + pw) (py + ph)) white (SDL_FPoint u1 v1))+ pokeElemOff qPtr 3 (SDL_Vertex (SDL_FPoint px (py + ph)) white (SDL_FPoint u0 v1))+ allocaArray 6 $ \iPtr -> do+ pokeElemOff iPtr 0 (0 :: CInt)+ pokeElemOff iPtr 1 1+ pokeElemOff iPtr 2 2+ pokeElemOff iPtr 3 0+ pokeElemOff iPtr 4 2+ pokeElemOff iPtr 5 3+ renderGeometry ren srcTex (PtrConst.unsafeFromPtr qPtr) 4 (PtrConst.unsafeFromPtr iPtr) 6++foreign import ccall unsafe "nano_ui_text_atlas_texture"+ textAtlasTexture :: Ptr () -> CInt -> IO (Ptr SDL_Texture)++foreign import ccall unsafe "nano_ui_gl_create"+ c_glCreate :: Ptr SDL_Renderer -> IO (Ptr ())++foreign import ccall unsafe "nano_ui_gl_destroy"+ c_glDestroy :: Ptr () -> IO ()++foreign import ccall unsafe "nano_ui_gl_begin_pass"+ c_glBeginPass :: Ptr () -> CFloat -> CInt -> IO ()++foreign import ccall unsafe "nano_ui_gl_end_pass"+ c_glEndPass :: Ptr () -> IO ()++foreign import ccall unsafe "nano_ui_gl_leave_pass"+ c_glLeavePass :: Ptr () -> IO ()++foreign import ccall unsafe "nano_ui_gl_set_clip"+ c_glSetClip :: Ptr () -> CInt -> CInt -> CInt -> CInt -> CInt -> IO ()++foreign import ccall unsafe "nano_ui_gl_set_origin"+ c_glSetOrigin :: Ptr () -> CFloat -> CFloat -> IO ()++foreign import ccall unsafe "nano_ui_range_visible"+ c_rangeVisible ::+ Ptr Word8 -> CInt -> Ptr Word8 -> CInt -> CInt+ -> CFloat -> CFloat -> CFloat -> CFloat -> IO CInt++foreign import ccall unsafe "nano_ui_sdl_draw_raw"+ c_sdlDrawRaw ::+ Ptr () -> Ptr SDL_Texture -> Ptr Word8 -> CInt -> Ptr Word8 -> CInt -> CInt -> IO CInt++foreign import ccall unsafe "nano_ui_gl_draw_plain"+ c_glDrawPlain ::+ Ptr () -> Ptr Word8 -> CInt -> Ptr Word8 -> CInt -> CInt -> Ptr SDL_Texture -> IO ()++foreign import ccall unsafe "nano_ui_gl_draw_shader"+ c_glDrawShader ::+ Ptr () -> Ptr Word8 -> CInt -> Ptr Word8 -> CInt -> CInt -> Ptr SDL_Texture+ -> Word64 -> Ptr Word8 -> CInt -> Ptr Word8 -> CInt -> IO CInt++foreign import ccall unsafe "nano_ui_gl_composite_effect"+ c_glCompositeEffect ::+ Ptr () -> Ptr SDL_Texture+ -> CFloat -> CFloat -> CFloat -> CFloat+ -> CFloat -> CFloat -> CFloat -> CFloat+ -> Word64 -> Ptr Word8 -> CInt -> Ptr Word8 -> CInt -> IO CInt
+ lib/NanoUI/Sdl/Internal/Runner.hs view
@@ -0,0 +1,386 @@+-- | 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
+ lib/NanoUI/Sdl/Internal/Screenshot.hs view
@@ -0,0 +1,90 @@+-- | Reading an SDL session's frame back: to a BMP file ('saveScreenshot'),+-- as 'NanoUI.Screenshot' pixels ('captureScreenshot'), or from the+-- backbuffer before a present ('captureFrame').+module NanoUI.Sdl.Internal.Screenshot+ ( saveScreenshot+ , captureScreenshot+ , captureFrame+ ) where++import Control.Exception (bracket)+import Control.Monad (void)+import Data.ByteString.Internal qualified as BSI+import Data.IORef (readIORef)+import qualified GHC.Foreign as GHC+import Foreign.Marshal.Utils (with)+import Foreign.Ptr (Ptr, castPtr, nullPtr)+import Foreign.Storable (peek)+import NanoUI (RgbaPixels, Screenshot (..), rgbaPixels)+import NanoUI.Sdl.Internal.Env (Retain (..), SdlEnv (..))+import NanoUI.Sdl.Internal.Font (sdlPathEncoding)+import NanoUI.Sdl.Internal.Target (setRetainTarget)+import SDL3.Sys.Bindgen.Pixels qualified as Pixels+import SDL3.Sys.Bindgen.Rect (SDL_Rect (..))+import SDL3.Sys.Bindgen.Render (SDL_Texture)+import SDL3.Sys.Bindgen.Runtime.PtrConst qualified as PtrConst+import SDL3.Sys.Bindgen.Surface (SDL_Surface)+import SDL3.Sys.Bindgen.Surface qualified as Surface+import SDL3.Sys.Render (renderReadPixels, setRenderTarget)+import SDL3.Sys.Surface (convertPixels, destroySurface, saveBMP)++-- | Write the last presented frame to a BMP file, on the display thread. A+-- retained session reads its retained texture, since SDL leaves the window+-- backbuffer undefined after a present.+--+-- A direct-to-window session ('NanoUI.Backend.Sdl.sdlAppContinuous') has no retained frame and+-- a readable one only between drawing and presenting, so from a view use+-- 'NanoUI.requestScreenshot', which reads it at that point.+saveScreenshot :: SdlEnv -> FilePath -> IO Bool+saveScreenshot env path =+ withSurface (readFrame env . retainTexture =<< readIORef (sdlRetain env)) False $ \surface ->+ sdlPathEncoding >>= \enc -> GHC.withCString enc path (saveBMP surface . PtrConst.unsafeFromPtr)++-- | The last presented frame, as 'NanoUI.requestScreenshot' returns it:+-- window pixels (the backbuffer's size, about the logical size times the+-- pixel density and UI zoom) with the drawn alpha, which is the theme's+-- window colour's alpha where nothing covers it.+-- 'Nothing' when SDL cannot read the frame back. Call on the display thread.+--+-- A direct-to-window session ('NanoUI.Backend.Sdl.sdlAppContinuous') has a readable frame only+-- between drawing and presenting, so from a view use+-- 'NanoUI.requestScreenshot', which reads it at that point.+captureScreenshot :: SdlEnv -> IO (Maybe Screenshot)+captureScreenshot env = do+ scale <- readIORef (sdlScaleRef env)+ fmap (`Screenshot` scale) <$> (captureFrame env . retainTexture =<< readIORef (sdlRetain env))++-- | The frame's pixels from the retained texture, or from the window+-- backbuffer when the target is null (valid only before presenting).+captureFrame :: SdlEnv -> Ptr SDL_Texture -> IO (Maybe RgbaPixels)+captureFrame env target = withSurface (readFrame env target) Nothing $ \surface -> do+ Surface.SDL_Surface _ format sw sh pitch pixels _ _ <- peek surface+ let w = fromIntegral sw+ h = fromIntegral sh+ -- Converted straight into the result, from whatever format was read back;+ -- a failed conversion leaves too few bytes for 'rgbaPixels'.+ bytes <- BSI.createUptoN (w * h * 4) $ \dst -> do+ ok <- convertPixels (fromIntegral w) (fromIntegral h) format (PtrConst.unsafeFromPtr pixels) (fromIntegral pitch) Pixels.SDL_PIXELFORMAT_RGBA32 (castPtr dst) (fromIntegral w * 4)+ pure (if ok then w * h * 4 else 0)+ pure (rgbaPixels w h bytes)++-- | Run an action on a new surface, and free it after; @none@ when there is+-- no surface.+withSurface :: IO (Ptr SDL_Surface) -> a -> (Ptr SDL_Surface -> IO a) -> IO a+withSurface make none act = bracket make destroySurface $ \surface ->+ if surface == nullPtr then pure none else act surface++-- | Read the used area of the retained texture, or the backbuffer for a null+-- target, into a new surface. Null on failure.+readFrame :: SdlEnv -> Ptr SDL_Texture -> IO (Ptr SDL_Surface)+readFrame env tex = do+ r <- readIORef (sdlRetain env)+ let ren = sdlRenderer env+ if tex == nullPtr || retainW r <= 0 || retainH r <= 0+ then renderReadPixels ren (PtrConst.unsafeFromPtr nullPtr)+ else do+ void $ setRetainTarget env tex+ s <- with (SDL_Rect 0 0 (fromIntegral (retainW r)) (fromIntegral (retainH r))) $ \rp ->+ renderReadPixels ren (PtrConst.unsafeFromPtr rp)+ void $ setRenderTarget ren nullPtr+ pure s
+ lib/NanoUI/Sdl/Internal/Session.hs view
@@ -0,0 +1,308 @@+-- | SDL window session loop: event poll, resize sync, frame present.+--+-- 'runSdlSession' opens the window, draws its opening frames+-- ('openingFrames') and runs "NanoUI.Runner"'s loop with 'sessionDriver'.+-- While Windows' modal size loop holds the event loop, the window's resize+-- watch draws with 'resizeFrame' instead. All three read and write the+-- 'Session' record.+module NanoUI.Sdl.Internal.Session+ ( runSdlSession+ ) where++import Control.Exception (bracket, finally)+import Control.Monad (forM_, unless, void, when)+import Data.IORef (IORef, newIORef, readIORef, writeIORef)+import Data.Maybe (fromMaybe, isNothing)+import Foreign.Marshal.Utils (fromBool)+import GHC.Clock (getMonotonicTime)+import NanoUI (Size, WindowSettings (..), whenM)+import NanoUI.Backend (Context, Input (..), clearEphemeral, emptyInput, followSystemThemeIO, newPixelContext, requestWindowClose, setExplainLayout, withTheme)+import NanoUI.Runner+import NanoUI.Runner.Windows (closeWindows)+import NanoUI.Sdl.Internal.Children+import NanoUI.Sdl.Internal.Input+import NanoUI.Sdl.Internal.Display (ResizeWatches (..), newResizeWatches, pushRefreshEvent, rethrowResizeFailure, scaleMoved, watchResizes)+import NanoUI.Sdl.Internal.Window+ (SdlEnv (..), SdlOptions (..), presentPaces, registerAppImages, restartPresentProbe, sdlLivePacingMs, sdlPacingMs, syncDisplay, withSdl)+import SDL3.Sys.Bindgen.Blendmode (sDL_BLENDMODE_BLEND)+import SDL3.Sys.Render (setRenderDrawBlendModeSafe, setRenderVSyncSafe)++-- | Draws a frame and answers whether another is needed; its flags force a+-- full repaint and request a pre-present settle pass (for live resize).+type DrawFn = Context -> SdlEnv -> Input -> Bool -> Bool -> IO Bool++-- | What the session's loop driver, its opening frames and its resize watch+-- share: the window and the state each leaves for the others.+data Session = Session+ { sOptions :: !SdlOptions+ , sEnv :: !SdlEnv+ , sWindows :: !SdlWindows+ -- ^ Windows the view opens beside this one ('NanoUI.nativeWindow').+ , sWatches :: !ResizeWatches+ -- ^ Each window's resize watch draws it while Windows' modal size loop+ -- holds the event loop. They share the loop's drawing lock.+ , sDraw :: DrawFn+ , sPrev :: !(IORef Input)+ -- ^ The input the last pass, opening frame or resize frame synced, which+ -- the next resize frame starts from.+ , sVsyncPaused :: !(IORef Bool)+ -- ^ Whether the resize watch turned vsync off ('pauseVsync').+ , sResizePresented :: !(IORef (Maybe Size))+ -- ^ Window size the resize watch presented since the main loop last+ -- decided whether to draw. That frame already covers the size change and+ -- expose events the loop is about to see.+ , sWatchDrawnAt :: !(IORef Double)+ -- ^ When the watch last drew, or 0 when the loop has drawn since. A watch+ -- frame after another ticks animations by the time between them, not by+ -- the loop's last delta, and the loop's next frame ticks only the time+ -- after the watch's.+ , sWake :: !(IORef Bool)+ -- ^ A wake (a background thread changed what the view reads, a file+ -- dialog finished) that no frame has answered yet. What that frame+ -- presents is up to its damage: a wake that changed nothing on screen+ -- costs the UI pass and no repaint or present. Code may push the wake+ -- event without going through 'NanoUI.Internal.Context.ctxWoken', so this+ -- is not a copy of it.+ , sQuitTaken :: !(IORef Bool)+ -- ^ A close request 'settle' took off the queue during the opening frames.+ -- SDL asks to quit once, so it is kept for the loop.+ , sPassStart :: !(IORef Double)+ -- ^ When the loop's current pass began, for pacing the next by time+ -- ('pacedWait').+ }++-- | Open a window for the options, with their theme and images, and run the+-- event loop until it closes or 'sdlAppShouldQuit' says so. @drawFn@ draws a+-- frame and answers whether another is needed; its flag forces a full+-- repaint.+runSdlSession :: SdlOptions -> DrawFn -> IO ()+runSdlSession options drawFn = do+ base <- newPixelContext+ ctx <- maybe (pure base) (withTheme base) (sdlAppTheme options)+ forM_ (sdlAppThemeFor options) (followSystemThemeIO ctx)+ setExplainLayout ctx (sdlExplainLayout options)+ registerAppImages options ctx+ withSdl options ctx $ \ctx0 env -> do+ watches <- newResizeWatches+ windows <- newSdlWindows options env watches+ -- Every exit closes the further windows, those the opening frames+ -- opened among them, and while SDL is still running.+ flip finally (closeWindows (swWindows windows)) $ do+ void $ setRenderDrawBlendModeSafe (sdlRenderer env) (maybe (fromIntegral sDL_BLENDMODE_BLEND) fst (sdlTransparent env))+ s <-+ Session options env windows watches drawFn+ <$> newIORef emptyInput+ <*> newIORef False+ <*> newIORef Nothing+ <*> newIORef 0+ <*> newIORef False+ <*> newIORef False+ <*> newIORef 0+ (ctx2, inp1) <- openingFrames s ctx0+ -- A close request the opening frames took, which the loop would not see:+ -- it ends the session here, or with exits off the loop's first frame+ -- reports it.+ quit <- readIORef (sQuitTaken s)+ closeNow <- if quit then requestWindowClose ctx2 else pure False+ unless closeNow $+ bracket (watchResizes watches (sdlWindow env) (resizeFrame s)) id $ \_ ->+ runSessionLoop (sessionDriver s) ctx2 inp1++-- | Draw the opening frames, before the loop starts, and answer the context+-- and input the loop starts from.+--+-- SDL draws two or three opening frames where the RGFW and web backends+-- draw one. A window's first present can apply the display's pixel density,+-- so the first frame may be drawn at a scale the window does not keep, with+-- no previous rects to repaint from. A second frame draws at the settled+-- scale; without it a page stays stretched until the first pointer move. A+-- third runs when the size or scale moved again after the second frame, or+-- when events queued meanwhile carry one-shot input (presses, keys, text),+-- which the loop's first pass would clear unseen. RGFW sizes its hidden+-- window at the monitor's scale before showing it and drawing, and the web+-- backend reads the canvas's pixel ratio before its first frame, so their+-- one opening frame has the scale it keeps; both leave every queued event to+-- the loop.+--+-- The frames are drawn outside the loop, so what one asks for beyond itself+-- has to be carried into the loop by hand. A frame answers the wakes that+-- came before it, and leaves the context dirty when it needs another.+openingFrames :: Session -> Context -> IO (Context, Input)+openingFrames s ctx0 = do+ (ctx1, inp0, scale0) <- settleScaled ctx0 emptyInput {inputWindowSize = wsSize (sdlWindowSettings (sOptions s))}+ startupFrame ctx1 inp0+ -- Each frame's one-shot input (presses, keys, text) is only what came+ -- after the frame before.+ (ctx1b, inp0b, scaleSettle) <- settleScaled ctx1 (clearEphemeral inp0)+ startupFrame ctx1b inp0b+ (ctx2, inp1, scale1) <- settleScaled ctx1b (clearEphemeral inp0b)+ -- Once more for a size or scale the second frame did not have, or for+ -- one-shot input it did not see, which the loop's first pass clears.+ when (inputWindowSize inp1 /= inputWindowSize inp0b || scaleMoved scale1 scaleSettle || scaleMoved scaleSettle scale0 || inp1 /= clearEphemeral inp1) $+ startupFrame ctx2 inp1+ writeIORef (sPrev s) inp1+ -- Open the windows the opening frames declared, which the loop would+ -- otherwise leave for its first pass, after waiting for input.+ afterFirstPass (sWindows s) ctx2+ -- The last opening frame may have asked for another: it marked the+ -- context dirty, which the loop sees by itself, or a wake arrived after+ -- it began, which the drains above took off the queue. Queue that wake+ -- again, or the loop would block on a view waiting to be drawn until some+ -- input happened along.+ whenM (readIORef (sWake s)) pushRefreshEvent+ pure (ctx2, inp1)+ where+ startupFrame c inp = do+ writeIORef (sWake s) False+ void (sDraw s c (sEnv s) inp True False)+ settleScaled c inp = do+ (c', inp') <- settle s c inp+ scale <- readIORef (sdlScaleRef (sEnv s))+ pure (c', inp', scale)++-- | Take every queued event into the input, syncing the display after each+-- batch, until none is left. A close request taken here is kept in+-- 'sQuitTaken'.+settle :: Session -> Context -> Input -> IO (Context, Input)+settle s c inp = do+ pending <- pollBatch s+ when (EvQuit `elem` pending) (writeIORef (sQuitTaken s) True)+ (c', inp') <- syncDisplay c (sEnv s) (foldl' applyEvent inp pending)+ if null pending then pure (c', inp') else settle s c' inp'++-- | This window's share of a batch of events, the rest routed to the+-- windows they are for. A wake among them is noted in 'sWake'.+decodeBatch :: Session -> [SdlEvent] -> IO [SdlEvent]+decodeBatch s evs = do+ when (EvRefresh `elem` evs) (writeIORef (sWake s) True)+ decodeForWindow (sEnv s) evs++-- | Take every queued event.+pollBatch :: Session -> IO [SdlEvent]+pollBatch s = pollWindowEvents >>= routeEvents (sWindows s) >>= decodeBatch s++-- | Wait up to @t@ ms for an event (-1 for no limit), then take the rest of+-- the queue with it, so one pass sees a whole burst (a resize queues several+-- window events at once).+waitBatch :: Session -> Int -> IO [SdlEvent]+waitBatch s t =+ waitWindowEvent t >>= maybe (pure []) (\ev -> routeEvents (sWindows s) . (ev :) =<< pollWindowEvents) >>= decodeBatch s++-- | The loop's 'sdPacedWait': the wait between the frames of an animation+-- whose presents do not wait for the display. It follows the display the+-- window is on now ('sdlRefreshPeriodRef') rather than the one it opened on:+-- the wait is that display's, and a wait that times out starts the frame a+-- refresh after the pass began ('sPassStart'). The loop's own alignment+-- ('sdAlignSec') winds onto a fixed period, which cannot follow the window+-- to another display.+pacedWait :: Session -> IO [SdlEvent]+pacedWait s = do+ evs <- waitBatch s =<< sdlLivePacingMs env+ when (null evs) $ do+ period <- readIORef (sdlRefreshPeriodRef env)+ waitUntil . (+ period) =<< readIORef (sPassStart s)+ pure evs+ where+ env = sEnv s++-- | Turn vsync off while the resize watch draws, and on again for the+-- loop's frames. The watch presents with vsync off so Windows' modal size+-- loop does not wait for vblank on each drag step (on OpenGL this is a+-- sub-millisecond swap-interval flip; on Vulkan GPU it avoids blocking+-- swapchain recreation on FIFO vblank).+pauseVsync :: Session -> Bool -> IO ()+pauseVsync s paused =+ when (sdlVsync env) $ whenM ((/= paused) <$> readIORef (sVsyncPaused s)) $ do+ void $ setRenderVSyncSafe (sdlRenderer env) (fromBool (not paused))+ writeIORef (sVsyncPaused s) paused+ where+ env = sEnv s++-- | The resize watch's frame, drawn while Windows' modal size loop holds the+-- event loop, when the window's size or scale moved. 'watchResizes' runs it+-- under the drawing lock. The live context is the session's: 'syncDisplay'+-- answers it.+resizeFrame :: Session -> IO ()+resizeFrame s = do+ liveCtx <- readIORef (sdlCachedCtx env)+ inp <- readIORef (sPrev s)+ scale0 <- readIORef (sdlScaleRef env)+ (ctx', inpSynced) <- syncDisplay liveCtx env (clearEphemeral inp)+ writeIORef (sPrev s) inpSynced+ scale1 <- readIORef (sdlScaleRef env)+ unless (inputWindowSize inpSynced == inputWindowSize inp && scale1 == scale0) $ do+ pauseVsync s True+ now <- getMonotonicTime+ t <- readIORef (sWatchDrawnAt s)+ writeIORef (sWatchDrawnAt s) now+ -- At most the 50 ms the loop ticks a frame by.+ let dt = if t > 0 then min 0.05 (realToFrac (now - t)) else inputDeltaTime inpSynced+ _ <- sDraw s ctx' env inpSynced {inputDeltaTime = dt} True True+ -- Its present ran outside normal frame pacing: it says nothing of whether+ -- the driver honours vsync during steady animation.+ restartPresentProbe env+ writeIORef (sResizePresented s) (Just (inputWindowSize inpSynced))+ where+ env = sEnv s++-- | The loop's view of the session.+sessionDriver :: Session -> SessionDriver SdlEvent+sessionDriver s =+ SessionDriver+ { sdPollEvents = pollBatch s+ , sdWaitEvents = waitBatch s+ , sdPacedWait = Just (\_ -> pacedWait s)+ , sdApplyEvent = applyEvent+ , sdIsButtonEdge = isButtonEdge+ , sdIsSessionQuit = (== EvQuit)+ , sdSyncDisplay = \c inp -> do+ writeIORef (sPassStart s) =<< getMonotonicTime+ rethrowResizeFailure (sWatches s)+ pauseVsync s False+ synced@(_, inp') <- syncDisplay c env inp+ synced <$ writeIORef (sPrev s) inp'+ , sdDebug = sdlDebug env+ , sdContinuous = sdlContinuous env+ , sdVsyncOff = not (sdlVsync env)+ , sdPacingMs = sdlPacingMs env+ -- A frame that skipped (empty damage, e.g. an animation scrolled+ -- out of view) did not wait for vblank, so it must not loop+ -- without waiting; nor may one whose driver turned vsync off+ -- ('NanoUI.Sdl.Internal.Window.notePresent').+ , sdPresentPaces = presentPaces env+ , sdShouldDraw = \c prevInp inpSynced wasAnim refreshDue -> do+ presented <- readIORef (sResizePresented s)+ writeIORef (sResizePresented s) Nothing+ wakeDue <- readIORef (sWake s)+ let keepExpose = sdlHasGpu env+ !(prevInp', inpSynced') = case presented of+ Just size+ | size == inputWindowSize inpSynced ->+ (prevInp {inputWindowSize = size}, if keepExpose then inpSynced else inpSynced {inputWindowRedraw = False})+ _ -> (prevInp, inpSynced)+ shouldRedrawFrame c prevInp' inpSynced' wasAnim (sdlContinuous env) (refreshDue || wakeDue)+ , sdDraw = \c inpSynced forceFull -> do+ writeIORef (sResizePresented s) Nothing+ -- Only a frame that runs answers a wake.+ drawn <- tryWithDrawingLock (rwDrawing (sWatches s)) $ do+ writeIORef (sWake s) False+ t <- readIORef (sWatchDrawnAt s)+ if t > 0+ then do+ now <- getMonotonicTime+ writeIORef (sWatchDrawnAt s) 0+ sDraw s c env inpSynced {inputDeltaTime = min (inputDeltaTime inpSynced) (realToFrac (now - t))} forceFull False+ else sDraw s c env inpSynced forceFull False+ -- A frame the lock turned away leaves its wake's event off+ -- the queue: queue it again for the pass after the lock is+ -- free.+ when (isNothing drawn) $ whenM (readIORef (sWake s)) pushRefreshEvent+ pure (fromMaybe False drawn)+ , sdOnCursor = syncFirstCursor (sWindows s)+ -- Unused: 'sdPacedWait' aligns frames itself.+ , sdAlignSec = 0+ , sdShouldQuit = sdlAppShouldQuit (sOptions s)+ , sdWindows = Just (sdlLoopWindows (sWindows s))+ }+ where+ env = sEnv s
+ lib/NanoUI/Sdl/Internal/Target.hs view
@@ -0,0 +1,36 @@+-- | Making the retained frame's texture the render target, around a fault in+-- SDL's OpenGL ES 2 renderer.+--+-- That renderer changes target without making its GL context current+-- (@GLES2_SetRenderTarget@, SDL 3.2 through 3.4). Destroying a renderer+-- leaves no GL context current, so after a further window closes, the next+-- target change of a remaining window binds its framebuffer with no context,+-- fails, and leaves SDL treating the texture as the target all the same. A+-- target change first runs the commands already queued, and running them+-- makes the context current, so a command queued beforehand avoids the+-- fault.+module NanoUI.Sdl.Internal.Target+ ( setRetainTarget+ ) where++import Control.Monad (void, when)+import Foreign.Ptr (Ptr, nullPtr)+import NanoUI.Sdl.Internal.Env (SdlEnv (..))+import SDL3.Sys.Bindgen.Render (SDL_Texture)+import SDL3.Sys.Bindgen.Video (SDL_GLContext (..))+import SDL3.Sys.Render (getRenderTarget, renderClear, setRenderTarget)+import SDL3.Sys.Video (glGetCurrentContext)++-- | Make @tex@ the render target of the session's renderer. On the OpenGL ES+-- 2 renderer with no GL context current, while the window is the target, a+-- clear of the window is queued first; every retained frame covers the+-- window with its copy, and a screenshot is read after the present, when+-- the window's backbuffer holds nothing to keep.+setRetainTarget :: SdlEnv -> Ptr SDL_Texture -> IO Bool+setRetainTarget env tex = do+ let ren = sdlRenderer env+ when (sdlRendererName env == "opengles2" && tex /= nullPtr) $ do+ SDL_GLContext current <- glGetCurrentContext+ onWindow <- (== nullPtr) <$> getRenderTarget ren+ when (current == nullPtr && onWindow) $ void (renderClear ren)+ setRenderTarget ren tex
+ lib/NanoUI/Sdl/Internal/TargetPool.hs view
@@ -0,0 +1,166 @@+{-# OPTIONS_HADDOCK not-home #-}++-- | Pooled 64px-bucketed RGBA32 offscreen render target textures for Tier 2+-- subtree shader effects, with root draw blend-mode save/restore around+-- offscreen spans.+module NanoUI.Sdl.Internal.TargetPool+ ( TargetPool+ , newTargetPool+ , destroyTargetPool+ , acquireTarget+ , releaseTarget+ , lookupTarget+ , bindTarget+ ) where++import Control.Monad (forM_, void, when)+import Data.Bits (complement, (.&.))+import Data.IntMap.Strict qualified as IM+import Data.IORef (IORef, modifyIORef', newIORef, readIORef, writeIORef)+import Foreign.Marshal.Alloc (alloca)+import Foreign.Ptr (Ptr, nullPtr)+import Foreign.Storable (peek)+import NanoUI.Sdl.Internal.Error (withSdlError)+import SDL3.Sys.Bindgen.Blendmode (SDL_BlendMode)+import SDL3.Sys.Bindgen.Pixels qualified as Pixels+import SDL3.Sys.Bindgen.Render (SDL_Renderer, SDL_Texture)+import SDL3.Sys.Bindgen.Render qualified as RenderBind+import SDL3.Sys.Bindgen.Surface qualified as SurfaceBind+import SDL3.Sys.Blendmode qualified as Blend+import SDL3.Sys.Render+ ( createTexture+ , destroyTexture+ , getRenderDrawBlendMode+ , renderClear+ , setRenderDrawBlendMode+ , setRenderDrawColor+ , setRenderTarget+ , setTextureBlendMode+ , setTextureScaleMode+ )+import System.IO (hPutStrLn, stderr)++data TargetSlot = TargetSlot+ { tsTex :: !(Ptr SDL_Texture)+ , tsCapW :: !Int+ , tsCapH :: !Int+ , tsInUse :: !Bool+ }++-- | Pool of offscreen render targets shared by GPU and OpenGL Tier 2 effects.+data TargetPool = TargetPool+ { tpSlots :: !(IORef (IM.IntMap TargetSlot))+ , tpSavedBlend :: !(IORef (Maybe SDL_BlendMode))+ }++-- | Create an empty offscreen target pool.+newTargetPool :: IO TargetPool+newTargetPool = TargetPool <$> newIORef IM.empty <*> newIORef Nothing++-- | Destroy all pooled offscreen textures.+destroyTargetPool :: TargetPool -> IO ()+destroyTargetPool tp = do+ slots <- readIORef (tpSlots tp)+ forM_ (IM.elems slots) $ \s ->+ when (tsTex s /= nullPtr) (destroyTexture (tsTex s))+ writeIORef (tpSlots tp) IM.empty+ writeIORef (tpSavedBlend tp) Nothing++-- | Acquire a 64px-bucketed RGBA32 offscreen render target, allocating a new+-- texture (after invoking @beforeAlloc@ to leave any active GL pass) when no+-- pooled slot fits within 2x of the needed size.+acquireTarget :: Ptr SDL_Renderer -> TargetPool -> IO () -> Int -> Int -> IO (Int, Int, Int)+acquireTarget ren tp beforeAlloc minW minH+ | ren == nullPtr = pure (-1, 0, 0)+ | otherwise = do+ let needW = if minW > 0 then (minW + 63) .&. complement 63 else 64+ needH = if minH > 0 then (minH + 63) .&. complement 63 else 64+ fits s =+ not (tsInUse s)+ && tsTex s /= nullPtr+ && tsCapW s >= needW+ && tsCapH s >= needH+ && tsCapW s <= needW * 2+ && tsCapH s <= needH * 2+ slots <- readIORef (tpSlots tp)+ case [(k, s) | (k, s) <- IM.toAscList slots, fits s] of+ (slot, s) : _ -> do+ writeIORef (tpSlots tp) (IM.insert slot s {tsInUse = True} slots)+ pure (slot, tsCapW s, tsCapH s)+ [] -> do+ -- SDL_CreateTexture mutates OpenGL texture/FBO state on the "opengl"+ -- renderer; flush any queued geometry and leave the active GL pass first.+ beforeAlloc+ tex <- createTexture ren Pixels.SDL_PIXELFORMAT_RGBA32 RenderBind.SDL_TEXTUREACCESS_TARGET (fromIntegral needW) (fromIntegral needH)+ if tex == nullPtr+ then do+ withSdlError "nano-ui-sdl: offscreen target creation failed" >>= hPutStrLn stderr+ pure (-1, 0, 0)+ else do+ void $ setTextureBlendMode tex Blend.SDL_BLENDMODE_BLEND+ void $ setTextureScaleMode tex SurfaceBind.SDL_SCALEMODE_LINEAR+ let slot = IM.size slots+ entry = TargetSlot tex needW needH True+ writeIORef (tpSlots tp) (IM.insert slot entry slots)+ pure (slot, needW, needH)++-- | Return a pooled target slot for reuse.+releaseTarget :: TargetPool -> Int -> IO ()+releaseTarget tp slot =+ modifyIORef' (tpSlots tp) (IM.adjust (\s -> s {tsInUse = False}) slot)++-- | Look up the texture of a pooled target slot.+lookupTarget :: TargetPool -> Int -> IO (Maybe (Ptr SDL_Texture))+lookupTarget tp slot = do+ m <- IM.lookup slot <$> readIORef (tpSlots tp)+ pure $ case m of+ Just s | tsTex s /= nullPtr -> Just (tsTex s)+ _ -> Nothing++-- | Bind pooled target @slot@ (>= 0) or @fallbackTarget@ when @slot < 0@,+-- saving and restoring the root target's draw blend mode around offscreen+-- effect spans and clearing to transparent black when requested.+bindTarget ::+ Ptr SDL_Renderer ->+ TargetPool ->+ IO () ->+ IO () ->+ Int ->+ Ptr SDL_Texture ->+ Bool ->+ IO Bool+bindTarget ren tp flushAndLeave resetClip slot fallbackTarget clearTransparent+ | ren == nullPtr = pure False+ | otherwise = do+ flushAndLeave+ slots <- readIORef (tpSlots tp)+ let mSlot = IM.lookup slot slots+ target = maybe fallbackTarget tsTex mSlot+ ok <- setRenderTarget ren target+ if not ok+ then pure False+ else do+ -- Offscreen Tier 2 effect targets accumulate premultiplied alpha over+ -- transparent black via SDL_BLENDMODE_BLEND regardless of the root+ -- target's draw blend mode (e.g. transparent windows).+ case mSlot of+ Just _ -> do+ saved <- readIORef (tpSavedBlend tp)+ case saved of+ Nothing -> alloca $ \bmPtr -> do+ got <- getRenderDrawBlendMode ren bmPtr+ when got $ peek bmPtr >>= writeIORef (tpSavedBlend tp) . Just+ Just _ -> pure ()+ void $ setRenderDrawBlendMode ren Blend.SDL_BLENDMODE_BLEND+ Nothing -> do+ saved <- readIORef (tpSavedBlend tp)+ case saved of+ Just bm -> do+ void $ setRenderDrawBlendMode ren bm+ writeIORef (tpSavedBlend tp) Nothing+ Nothing -> pure ()+ resetClip+ when clearTransparent $ do+ void $ setRenderDrawColor ren 0 0 0 0+ void $ renderClear ren+ pure True
+ lib/NanoUI/Sdl/Internal/Url.hs view
@@ -0,0 +1,24 @@+-- | Open a URL with the platform's default handler.+module NanoUI.Sdl.Internal.Url (openUrl) where++import Data.Text (Text)+import Data.Text.Foreign qualified as TextForeign+import SDL3.Sys.Bindgen.Runtime.PtrConst qualified as PtrConst+import SDL3.Sys.Misc qualified as SDL++-- | Open a URL with the platform's default application, such as a browser or+-- mail client. Call from the application's main thread.+--+-- The call is a safe foreign call: on Windows the shell can send messages to+-- this program's windows while it starts the handler, and a window+-- procedure that runs Haskell (the resize watch, the hit test) must not be+-- entered from inside an unsafe call.+--+-- The string goes to the platform unchecked: a @file:@ URL opens a local+-- file, and on Windows a path to a program runs it. Before opening a URL+-- from content the application does not control, such as a link in a+-- Markdown document, check that its scheme is one it means to allow+-- (@http@, @https@, @mailto@).+openUrl :: Text -> IO Bool+openUrl url = TextForeign.withCString url $ \cUrl ->+ SDL.openURLSafe (PtrConst.unsafeFromPtr cUrl)
+ lib/NanoUI/Sdl/Internal/Window.hs view
@@ -0,0 +1,679 @@+{-# LANGUAGE RecordWildCards #-}+{-# LANGUAGE TypeFamilies #-}+{-# OPTIONS_HADDOCK not-home #-}+-- The 'BackendSession' instance for 'Sdl' is an orphan by construction: the+-- core owns the backend kind, and this package owns its session type.+{-# OPTIONS_GHC -Wno-orphans #-}++-- | SDL session resources, window options, and font/display synchronisation.+-- It also re-exports the session record ("NanoUI.Sdl.Internal.Env"), the+-- present probe and pacing helpers ("NanoUI.Sdl.Internal.Pacing") and the+-- screenshots ("NanoUI.Sdl.Internal.Screenshot"), so this exposed module+-- keeps every name it has exported.+module NanoUI.Sdl.Internal.Window+ ( RgbaImage (..)+ , SdlEnv (..)+ , PresentProbe (..)+ , Retain (..)+ , SdlOptions (..)+ , RenderDriver (..)+ , defaultSdlOptions+ , withSdl+ , withSdlBench+ , openChildWindow+ , registerAppImages+ , sdlPacingMs+ , sdlLivePacingMs+ , refreshDisplayRate+ , notePresent+ , restartPresentProbe+ , presentPaces+ , askSdlEnv+ , withSdlEnv+ , syncDisplay+ , windowZoom+ , saveScreenshot+ , captureScreenshot+ , captureFrame+ ) where++import Control.Exception (IOException, catch, finally, onException)+import Control.Monad (forM_, mfilter, unless, void, when)+import Control.Monad.IO.Class (liftIO)+import Data.Acquire (Acquire, mkAcquire)+import Data.Acquire qualified as Acquire+import Data.Acquire (allocateAcquire)+import Control.Monad.Trans.Resource (closeInternalState, createInternalState, runInternalState)+import Data.Bits (zeroBits, (.|.))+import Data.ByteString qualified as BS+import Data.Maybe (fromMaybe, isJust, isNothing)+import Data.IORef (newIORef, readIORef, writeIORef)+import System.Environment (lookupEnv)+import System.Info (os)+import Text.Read (readMaybe)+import Data.Primitive.SmallArray (SmallArray)+import Data.Text qualified as T+import Data.Text.Encoding qualified as TE+import Data.Text.Foreign qualified as TextForeign+import Foreign.Marshal.Utils (fromBool, maybePeek)+import Foreign.Ptr (Ptr, castPtr)+import NanoUI (Appearance, ImageId, Input (..), NanoUI, ShaderCapabilities (..), Size (..), Theme, V2 (..), WindowMode (..), WindowSettings (..), defaultWindowSettings, unlessM)+import NanoUI.Backend+ ( Backend (..), BackendSession, SBackend (..), askBackendSession, setBackendSession, withBackendSession, cancelTasks+ , closeWindowHost, installWindowHost, newPixelContext, registerImage, reportWindowState, setShaderCapabilities, setSystemAppearance+ , inBoundThread, setWakeLoopChecked, withClipboard, withTheme+ )+import NanoUI.Internal.Context (Context (..), followSystemTheme, setDrawSnapScale)+import NanoUI.Sdl.Internal.Display+import NanoUI.Sdl.Internal.Env (PresentProbe (..), Retain (..), SdlEnv (..), dropRetainRef, emptyRetain)+import NanoUI.Sdl.Internal.Pacing+ ( notePresent+ , presentPaces+ , refreshDisplayRate+ , refreshPeriodOf+ , restartPresentProbe+ , sdlLivePacingMs+ , sdlPacingMs+ )+import NanoUI.Sdl.Internal.Screenshot (captureFrame, captureScreenshot, saveScreenshot)+import NanoUI.Sdl.Internal.Error (sdlFail)+import NanoUI.Sdl.Internal.Chrome.Types (clearChromeState, newChromeState)+import NanoUI.Sdl.Internal.Frame (WindowDecorations (..), applyDecorations, framedWindow, installWin32ResizeHook)+import NanoUI.Sdl.Internal.Cursor (destroyCursors, initCursors)+import NanoUI.Sdl.Internal.Font+import NanoUI.Ttf.Internal.Support (syncSdlFontCache)+import NanoUI.Sdl.Internal.Font.Search (searchFonts, startFontIndex)+import NanoUI.Sdl.Internal.Gpu (createWindowAndGpuRenderer, rendererHasGpu, rendererHasShaders)+import NanoUI.Sdl.Internal.NanoUIFont (NanoUIFont (..))+import NanoUI.Internal.Debug (newDebugSampler)+import NanoUI.Sdl.Internal.Image (destroyImageAtlas, newImageAtlas)+import NanoUI.Sdl.Internal.Input (newTextInputSync)+import NanoUI.Sdl.Internal.Render (destroyRenderBatch, newRenderBatch)+import NanoUI.Sdl.Internal.WindowOptions+import SDL3.Sys.Bindgen.Hints+ ( sDL_HINT_ASSERT+ , sDL_HINT_IME_IMPLEMENTED_UI+ , sDL_HINT_RENDER_DRIVER+ , sDL_HINT_RENDER_VSYNC+ , sDL_HINT_VIDEO_DRIVER+ )+import SDL3.Sys.Bindgen.Render (SDL_Renderer)+import SDL3.Sys.Bindgen.Runtime.PtrConst qualified as PtrConst+import SDL3.Sys.Bindgen.Video (SDL_Window, SDL_WindowFlags)+import SDL3.Sys.Bindgen.Init (SDL_InitFlags (..), sDL_INIT_VIDEO)+import SDL3.Sys.Clipboard (getClipboardTextSafe, setClipboardTextSafe)+import SDL3.Sys.Hints (resetHint, setHint)+import SDL3.Sys.Blendmode (SDL_BlendMode, composeCustomBlendMode)+import SDL3.Sys.Blendmode qualified as Blend+import SDL3.Sys.Init (initSafe, quitSafe)+import SDL3.Sys.Keyboard (stopTextInputSafe)+import SDL3.Sys.Render+ ( createWindowAndRendererSafe+ , destroyRendererSafe+ , getRendererName+ , setRenderDrawBlendMode+ , setRenderScale+ , setRenderVSyncSafe+ )+import SDL3.Sys.Stdinc (free)+import SDL3.Sys.Video (destroyWindowSafe, getWindowDisplayScale)+import SDL3.Sys.Video qualified as SDL++-- | An image registered before the first frame ('sdlAppImages') under the id+-- 'NanoUI.image' draws it by. Width and height are positive; pixels are+-- tightly packed RGBA8, top row first.+data RgbaImage = RgbaImage+ { rgbaImageId :: !ImageId+ , rgbaImageWidth :: !Int+ , rgbaImageHeight :: !Int+ , rgbaImagePixels :: !BS.ByteString+ }+ deriving (Eq)++-- | Application-owned SDL settings.+data SdlOptions = SdlOptions+ { sdlWindowSettings :: !WindowSettings+ -- ^ Title, size, position, size limits, icon, mode, transparency,+ -- opacity and close behaviour (default: 'defaultWindowSettings'). Sizes+ -- are layout units converted at the opening zoom; a later+ -- 'NanoUI.Backend.Sdl.setSdlUiScale' does not resize the window. A+ -- 'NanoUI.WindowPositionDefault' window opens where the desktop puts it, or+ -- centred when 'sdlAppUiScale' enlarges it. A transparent window+ -- ('wsTransparent') repaints fully on any change. Where translucent+ -- colours overlap, the resulting alpha depends on the render driver: most+ -- keep the larger alpha, SDL's OpenGL renderer weights the new alpha by+ -- itself, and the software renderer adds them.+ , sdlWindowDecorations :: !WindowDecorations+ -- ^ How much of the desktop's title bar and frame the window keeps+ -- (default: 'DecorationsFull'). 'DecorationsFrame' is for a view that+ -- draws its own title bar ('NanoUI.Backend.Sdl.windowCaption');+ -- 'NanoUI.Backend.Sdl.setWindowDecorations' changes it afterwards.+ , sdlWindowAlwaysOnTop :: !Bool+ -- ^ Keep the window on top of other windows (default: 'False').+ , sdlAppVsync :: !Bool+ -- ^ Enable vertical synchronization (default: 'True').+ , sdlRenderDriver :: !RenderDriver+ -- ^ Which SDL render driver to ask for (default: 'RenderDriverAuto').+ -- An @SDL_RENDER_DRIVER@ in the environment wins over this.+ , sdlAppContinuous :: !Bool+ -- ^ Redraw on every pass without waiting for events, paced by vsync when+ -- 'sdlAppVsync' is on, or by the display's refresh period when the driver+ -- ignores vsync (default: 'False'). With 'sdlAppVsync' off the passes+ -- run without waiting.+ , sdlExplainLayout :: !Bool+ -- ^ Start with the layout overlay on (default: 'False'). A view toggles+ -- it with @explainLayout@.+ , sdlAppFont :: !NanoUIFont+ -- ^ UI font (default: installed sans-serif search, falling back to bundled Inter).+ , sdlAppMonoFont :: !NanoUIFont+ -- ^ Monospace font (default: installed monospace search, falling back to Inter).+ , sdlAppFontSize :: !Float+ -- ^ Base font size in points (default: 16).+ , sdlAppTheme :: !(Maybe Theme)+ -- ^ Initial UI theme override (default: 'Nothing').+ , sdlAppThemeFor :: !(Maybe (Maybe Appearance -> Theme))+ -- ^ Picks the theme from the desktop's light or dark setting and follows+ -- its changes, e.g. @'NanoUI.lightDark' light dark@ (default: 'Nothing').+ -- Overrides 'sdlAppTheme' when set; see 'NanoUI.followSystemTheme'.+ , sdlAppShouldQuit :: !(Input -> Bool)+ -- ^ Predicate on user input to trigger application exit (default: @const False@).+ , sdlAppImages :: !(SmallArray RgbaImage)+ -- ^ Initial RGBA textures registered before the first frame.+ , sdlAppUiScale :: !Float+ -- ^ Zoom of the whole UI, on top of the window's pixel density (default:+ -- 1). Zero or less follows the display's content scale, which on Windows+ -- is the desktop's scaling setting. 'NanoUI.Backend.Sdl.setSdlUiScale'+ -- changes it at runtime.+ }++-- | Resizable 1280x800 window with vsync, 16-point text, UI scale 1, installed+-- font lookup, and bundled-font fallback. Continuous rendering is disabled.+defaultSdlOptions :: SdlOptions+defaultSdlOptions =+ SdlOptions+ { sdlWindowSettings = defaultWindowSettings+ , sdlWindowDecorations = DecorationsFull+ , sdlWindowAlwaysOnTop = False+ , sdlAppVsync = True+ , sdlRenderDriver = RenderDriverAuto+ , sdlAppContinuous = False+ , sdlExplainLayout = False+ , sdlAppFont =+ FontSearch+ [ "Inter"+ , "Montserrat"+ , "Work Sans"+ , "Roboto"+ , "Open Sans"+ , "Helvetica Neue"+ ]+ , sdlAppMonoFont =+ FontSearch+ [ "Consolas"+ , "Courier New"+ , "Liberation Mono"+ , "DejaVu Sans Mono"+ , "monospace"+ ]+ , sdlAppFontSize = 16+ , sdlAppTheme = Nothing+ , sdlAppThemeFor = Nothing+ , sdlAppShouldQuit = const False+ , sdlAppImages = mempty+ , sdlAppUiScale = 1+ }++-- | SDL_WINDOW_HIGH_PIXEL_DENSITY: without it the window's surface+-- gets scale 1.0 even on a 2x / HiDPI output, so the compositor upscales the+-- whole window (blurry "looks upscaled"). With it, SDL_GetWindowPixelDensity+-- returns the real output scale where window coordinates are points (macOS,+-- Wayland), the window keeps its logical size, and the pixel buffer (and+-- therefore the retain texture, glyph atlas, and fonts) rasterizes at the+-- native pixel density. On Windows window coordinates are already pixels, so+-- the density stays 1 whatever the desktop scaling.+windowFlags :: SdlOptions -> SDL_WindowFlags+windowFlags opts =+ SDL.SDL_WINDOW_HIGH_PIXEL_DENSITY+ .|. flag (wsResizable settings) SDL.SDL_WINDOW_RESIZABLE+ .|. flag (wsMode settings == Fullscreen) SDL.SDL_WINDOW_FULLSCREEN+ .|. flag (sdlWindowDecorations opts /= DecorationsFull) SDL.SDL_WINDOW_BORDERLESS+ .|. flag (sdlWindowAlwaysOnTop opts) SDL.SDL_WINDOW_ALWAYS_ON_TOP+ .|. flag (wsMode settings == Hidden) SDL.SDL_WINDOW_HIDDEN+ .|. flag (wsTransparent settings) SDL.SDL_WINDOW_TRANSPARENT+ where+ settings = sdlWindowSettings opts+ flag on bit = if on then bit else zeroBits++-- | The zoom a UI scale setting asks for: the setting itself, or for zero or+-- less the display's content scale beyond the pixel density.+resolveZoom :: Ptr SDL_Window -> Float -> IO Float+resolveZoom win setting+ | setting > 0 = pure setting+ | otherwise = do+ display <- getWindowDisplayScale win+ density <- queryWindowPixelDensity win+ pure (if display > 0 then max 0.25 (display / density) else 1)++-- | Window coordinates per layout unit: the zoom the window is running at,+-- which is what 'sdlAppUiScale' asks for or what the display's content scale+-- works out to. A frame is laid out in window coordinates divided by this.+windowZoom :: SdlEnv -> IO Float+windowZoom env = resolveZoom (sdlWindow env) =<< readIORef (sdlUiScaleRef env)++-- | Synchronise display scale, requested fonts, and logical input coordinates.+-- Call on the display thread before drawing, then use both returned values;+-- font changes may replace the context's metrics and invalidate cached layout.+syncDisplay :: Context -> SdlEnv -> Input -> IO (Context, Input)+syncDisplay ctx env inp = do+ density <- maybe (queryWindowPixelDensity (sdlWindow env)) pure (sdlForcedScale env)+ zoom <- windowZoom env+ let scale = density * zoom+ oldScale <- readIORef (sdlScaleRef env)+ let scaleChanged = scaleMoved scale oldScale+ when scaleChanged $ do+ -- Presents leave the renderer at 1:1 pixels; re-assert it only when the+ -- pixel density moves.+ unlessM (setRenderScale (sdlRenderer env) 1 1) (sdlFail "SDL_SetRenderScale failed")+ writeIORef (sdlScaleRef env) scale+ setDrawSnapScale ctx scale+ -- Runtime font-family switch: the app publishes its requested family through+ -- 'setSdlUiFont'; resolve and apply it here, on the display thread, before+ -- the next frame so the atlas, metrics, and text resolver agree.+ requested <- readIORef (sdlFontRequestRef env)+ applied <- readIORef (sdlFontAppliedRef env)+ let fontChanged = requested /= applied+ when (scaleChanged || fontChanged) $ do+ source <-+ if fontChanged+ then resolveNanoUIFont requested+ else sdlFontCacheSource (sdlFontCache env)+ writeIORef (sdlFontAppliedRef env) requested+ writeIORef (sdlCachedCtx env) =<< syncSdlFontCache (sdlFontCache env) ctx source withSdlClipboard+ -- SDL updates the appearance before queueing the theme event that wakes+ -- us, and the query is free.+ setSystemAppearance ctx =<< querySystemAppearance+ reportWindowState ctx =<< queryWindowState (sdlWindow env) scale+ queried <- queryWindowLogicalSize (sdlWindow env)+ let winSize = case (queried, inputWindowSize inp) of+ (Size 0 0, Size 0 0) -> wsSize defaultWindowSettings+ (Size 0 0, s) -> s+ (Size sw sh, _) -> Size (sw / zoom) (sh / zoom)+ -- The events set the input's position, each its own and already in+ -- layout units, so a press keeps the point it happened at. SDL is asked+ -- only before any pointer event, or when the zoom moved what those units+ -- are. Off the window, SDL keeps the last position inside it: the input's+ -- own, moved off every widget when the pointer left, stays.+ inWindow <- pointerInWindow (sdlWindow env)+ seen <- readIORef (sdlPointerSeen env)+ mouse <-+ if inWindow /= 0 && (not seen || scaleChanged)+ then (\(V2 mx my) -> V2 (mx / zoom) (my / zoom)) <$> queryMouseWindowPos+ else pure (inputMousePos inp)+ ctxMeasured <- readIORef (sdlCachedCtx env)+ pure (ctxMeasured, inp {inputWindowSize = winSize, inputMousePos = mouse})++-- | Open native resources around an action and release them on exit, including+-- exceptions. Supplies an SDL-equipped context. This does not run an event+-- loop or apply the high-level runner's initial theme/image registration.+withSdl :: SdlOptions -> Context -> (Context -> SdlEnv -> IO a) -> IO a+withSdl opts = withSdlWindow hints (windowFlags opts) opts+ where+ hints = do+ setSdlHint sDL_HINT_RENDER_VSYNC (if sdlAppVsync opts then "1" else "0")+ -- Text fields draw IME composition at their caret, so ask SDL for+ -- SDL_EVENT_TEXT_EDITING instead of letting the IME draw it. The+ -- candidate list stays the IME's, placed by SDL_SetTextInputArea.+ setSdlHint sDL_HINT_IME_IMPLEMENTED_UI "composition"+ -- SDL3 only auto-picks Wayland when the compositor has the fifo-v1 /+ -- commit-timing-v1 protocols. Without them (sway, wlroots, many+ -- others) it selects X11/XWayland, giving a scale-1 window on a+ -- scale-2 (or fractional) output that the compositor upscales, so+ -- text looks blurred. Native Wayland with+ -- SDL_WINDOW_HIGH_PIXEL_DENSITY rasterizes at the real output scale.+ -- X11 follows in the list, for an SDL that cannot start Wayland (built+ -- without it, or the compositor out of reach) where XWayland runs: a+ -- driver named alone is the only one SDL tries. An explicit+ -- SDL_VIDEO_DRIVER wins, and pure X11 sessions are left alone.+ wayland <- lookupEnv "WAYLAND_DISPLAY"+ driver <- lookupEnv "SDL_VIDEO_DRIVER"+ when (isJust wayland && isNothing driver) $+ setSdlHint sDL_HINT_VIDEO_DRIVER "wayland,x11"++-- | 'withSdl' for measurements: a hidden 800x600 window, bundled fonts,+-- scale 1, continuous drawing, and no vsync. The window is hidden only: on+-- Windows it must not be resizable as well.+withSdlBench :: Context -> (Context -> SdlEnv -> IO a) -> IO a+withSdlBench =+ withSdlWindow+ (setSdlHint sDL_HINT_ASSERT "always_ignore" >> setSdlHint sDL_HINT_RENDER_VSYNC "0")+ SDL.SDL_WINDOW_HIDDEN+ defaultSdlOptions+ { sdlWindowSettings = defaultWindowSettings {wsTitle = "nano-ui-bench", wsSize = Size 800 600}+ , sdlAppVsync = False+ , sdlAppContinuous = True+ , sdlAppFont = DefaultFont+ , sdlAppMonoFont = DefaultFont+ }++-- | Which SDL render driver a session asks for.+data RenderDriver+ = RenderDriverAuto+ -- ^ nano-ui picks: @"opengl"@ on Windows (avoiding D3D11 flip-model and+ -- Vulkan WSI resize stalls/stretching while still running GLSL 150 custom+ -- shaders), and SDL 3.4's @"gpu"@ driver (Metal or Vulkan) elsewhere when+ -- available, falling back to SDL's own order if creation fails.+ | RenderDriverGpu+ -- ^ Require SDL 3.4's @"gpu"@ renderer with SPIR-V and MSL shaders enabled.+ | RenderDriverSdlDefault+ -- ^ Leave SDL's own preference order alone.+ | RenderDriverNamed !BS.ByteString+ -- ^ An explicit driver name, e.g. @"d3d11"@ or @"opengl"@.+ deriving (Eq, Show)++setSdlHint :: BS.ByteString -> BS.ByteString -> IO ()+setSdlHint name value =+ BS.useAsCString name $ \cname ->+ BS.useAsCString value $ \cvalue ->+ void $ setHint (PtrConst.unsafeFromPtr cname) (PtrConst.unsafeFromPtr cvalue)++-- | Create a non-GPU renderer under the render driver the options ask for,+-- unless @SDL_RENDER_DRIVER@ in the environment names one.+--+-- On Windows, 'RenderDriverAuto' asks for @"opengl"@ rather than D3D11 or+-- SDL 3.4's Vulkan @"gpu"@ driver: Windows' modal size loop hands the app one+-- step at a time, and DXGI/Vulkan swapchain resize stalls and stretches the+-- window during border drags, whereas OpenGL drags smoothly and runs+-- @nano-ui-shader@ GLSL 150 shaders directly. Elsewhere,+-- 'acquireWindowAndRenderer' tries SDL 3.4's @"gpu"@ driver first and falls+-- back here when no GPU device is available.+--+-- If GL context creation fails (remote desktop, basic display adapter VM),+-- the hint is cleared and creation is retried with SDL's default driver. A+-- driver the caller explicitly named is not retried.+withRenderDriver :: RenderDriver -> IO a -> IO a+withRenderDriver driver create = do+ fromEnv <- isJust <$> lookupEnv "SDL_RENDER_DRIVER"+ case driver of+ _ | fromEnv -> create+ RenderDriverNamed name -> setSdlHint sDL_HINT_RENDER_DRIVER name >> create+ RenderDriverAuto | os == "mingw32" -> do+ setSdlHint sDL_HINT_RENDER_DRIVER "opengl"+ create `catch` \(_ :: IOException) -> do+ void $ BS.useAsCString sDL_HINT_RENDER_DRIVER (resetHint . PtrConst.unsafeFromPtr)+ create+ _ -> create++-- | Open a session: set the hints, then open a window with the flags.+withSdlWindow :: IO () -> SDL_WindowFlags -> SdlOptions -> Context -> (Context -> SdlEnv -> IO a) -> IO a+withSdlWindow hints flags opts ctx act =+ -- SDL's GL renderer -- what 'RenderDriverAuto' asks for on Windows --+ -- keeps its context current on the OS thread that created it, and the+ -- same thread pumps the window's messages, so the session runs on one.+ inBoundThread $ withTtf $ do+ -- The font directories are walked on a thread of their own from here,+ -- so the first character no loaded font has does not wait for the walk+ -- inside a frame.+ void startFontIndex+ hints+ fontSource <- resolveNanoUIFont (sdlAppFont opts)+ monoSource <- resolveNanoUIFont (sdlAppMonoFont opts)+ Acquire.with (startSdl >> startSdlWindow opts flags ctx fontSource monoSource Nothing) $ \(ctx', env) ->+ withBackendSession ctx' SSdl env (act ctx' env)++-- | An SDL session stores its 'SdlEnv' on the context so view-side operations+-- can look it up without taking an explicit handle.+type instance BackendSession 'Sdl = SdlEnv++-- | Look up the 'SdlEnv' of the SDL session driving this view, for IO-level+-- SDL operations ('NanoUI.Backend.Sdl.openFileDialog' and similar),+-- which run on the display thread like the view. Returns 'Nothing' when the+-- context is not driven by an SDL session (such as in headless tests).+askSdlEnv :: NanoUI (Maybe SdlEnv)+askSdlEnv = askBackendSession SSdl++-- | Run with the open session's environment, or answer @outside@ when no+-- session is open.+withSdlEnv :: a -> (SdlEnv -> IO a) -> NanoUI a+withSdlEnv outside k = askSdlEnv >>= maybe (pure outside) (liftIO . k)++acquireWindowAndRenderer ::+ SdlOptions -> SDL_WindowFlags -> Acquire (Ptr SDL_Window, Ptr SDL_Renderer)+acquireWindowAndRenderer opts flags =+ mkAcquire+ ( do+ envDriver <- lookupEnv "SDL_RENDER_DRIVER"+ TextForeign.withCString (wsTitle settings) $ \titlePtr -> do+ let (rw, rh) = (round w, round h)+ createStandard =+ withRenderDriver (sdlRenderDriver opts) $ do+ (ok, win, ren) <-+ outPair (createWindowAndRendererSafe (PtrConst.unsafeFromPtr titlePtr) rw rh flags)+ unless ok $ sdlFail "SDL_CreateWindowAndRenderer failed"+ pure (win, ren)+ tryGpu =+ createWindowAndGpuRenderer titlePtr rw rh flags+ case envDriver of+ Just "gpu" ->+ tryGpu >>= maybe (sdlFail "SDL 3.4 GPU renderer creation failed") pure+ Just _ -> createStandard+ Nothing -> case sdlRenderDriver opts of+ RenderDriverGpu ->+ tryGpu >>= maybe (sdlFail "SDL 3.4 GPU renderer creation failed") pure+ RenderDriverAuto+ | os == "mingw32" -> createStandard+ | otherwise -> tryGpu >>= maybe createStandard pure+ _ -> createStandard+ )+ ( \(win, ren) -> do+ void $ setRenderScale ren 1 1+ destroyRendererSafe ren+ destroyWindowSafe win+ )+ where+ settings = sdlWindowSettings opts+ Size w h = wsSize settings++-- | Start SDL's video subsystem and register the wake event, for the+-- session's windows.+startSdl :: Acquire ()+startSdl = do+ mkAcquire+ (unlessM (initSafe (SDL_InitFlags (fromIntegral sDL_INIT_VIDEO))) (sdlFail "SDL_Init(SDL_INIT_VIDEO) failed"))+ (const quitSafe)+ liftIO $ unlessM initRefreshEvent (sdlFail "SDL_RegisterEvents failed for refresh wake")+ liftIO disableUnusedWindowEvents++-- | Open a window, its renderer and what draws into it. A further window+-- shares its session's first window's cursors and its font and UI scale+-- requests, so 'NanoUI.Backend.Sdl.setSdlUiFont' and+-- 'NanoUI.Backend.Sdl.setSdlUiScale' reach every window.+startSdlWindow ::+ SdlOptions -> SDL_WindowFlags -> Context -> FontSource -> FontSource -> Maybe SdlEnv -> Acquire (Context, SdlEnv)+startSdlWindow opts flags ctx fontSource monoSource first = do+ let settings = sdlWindowSettings opts+ -- NANO_FORCE_SCALE: debug override of the pixel density.+ sdlForcedScale <- liftIO $ mfilter (> 0) . (>>= readMaybe) <$> lookupEnv "NANO_FORCE_SCALE"+ -- Before the window, so that it is released after the window is gone: the+ -- window holds the hit test this frees.+ sdlChromeState <- mkAcquire (newChromeState (sdlWindowDecorations opts) (framedWindow flags)) clearChromeState+ (sdlWindow, sdlRenderer) <- acquireWindowAndRenderer opts flags+ -- Install the Win32 resize subclass on every window so size changes never+ -- BitBlt stale client pixels or flash GDI backgrounds during border drags.+ liftIO $ installWin32ResizeHook sdlWindow+ density <- liftIO $ queryWindowPixelDensity sdlWindow+ zoom <- liftIO $ resolveZoom sdlWindow (sdlAppUiScale opts)+ -- The requested size is logical, so the window grows with the zoom.+ liftIO $ when (scaleMoved zoom 1) $ zoomWindow sdlWindow (wsSize settings) zoom+ -- After the zoom: SDL sizes a borderless window as though its view were+ -- the whole of it, so the desktop's frame goes on around a view that is+ -- already the size asked for, and the window grows by the frame.+ liftIO $ when (sdlWindowDecorations opts /= DecorationsFull) (applyDecorations sdlWindow (sdlWindowDecorations opts))+ let+ scale = density * zoom+ liftIO $ setDrawSnapScale ctx scale+ sdlHasGpu <- liftIO $ rendererHasGpu sdlRenderer+ hasShaders <- liftIO $ rendererHasShaders sdlRenderer+ liftIO $ setShaderCapabilities ctx (ShaderCapabilities hasShaders hasShaders)+ sdlRefreshPeriod <- liftIO $ refreshPeriodOf sdlWindow+ sdlRefreshPeriodRef <- liftIO $ newIORef sdlRefreshPeriod+ sdlPresentProbe <- liftIO $ newIORef (PresentProbe 0 0)+ sdlRendererName <-+ liftIO $ fromMaybe "unknown" <$> (maybePeek TextForeign.peekCString . PtrConst.unsafeToPtr =<< getRendererName sdlRenderer)+ sdlScaleRef <- liftIO $ newIORef scale+ sdlUiScaleRef <- liftIO $ maybe (newIORef (sdlAppUiScale opts)) (pure . sdlUiScaleRef) first+ sdlPointerSeen <- liftIO $ newIORef False+ sdlFontRequestRef <- liftIO $ maybe (newIORef (sdlAppFont opts)) (pure . sdlFontRequestRef) first+ sdlFontAppliedRef <- liftIO $ newIORef =<< maybe (pure (sdlAppFont opts)) (readIORef . sdlFontAppliedRef) first+ glyphAtlas <- mkAcquire (newGlyphAtlas sdlRenderer) destroyGlyphAtlas+ sdlImages <- mkAcquire newImageAtlas destroyImageAtlas+ sdlCursors <- maybe (mkAcquire initCursors destroyCursors) (pure . sdlCursors) first+ sdlDebug <- liftIO newDebugSampler+ sdlDebugPublished <- liftIO (newIORef Nothing)+ sdlFrameTrace <- liftIO $ isJust <$> lookupEnv "NANO_FRAME_TRACE"+ sdlRetain <- mkAcquire (newIORef emptyRetain) dropRetainRef+ sdlFontCache <-+ mkAcquire+ (newSdlFontCache fontSource monoSource glyphAtlas (sdlAppFontSize opts) sdlScaleRef)+ destroySdlFontCache+ sdlCachedCtx <-+ liftIO $ newIORef . withSdlClipboard =<< withSdlFontCache sdlFontCache ctx+ let+ sdlVsync = sdlAppVsync opts+ sdlContinuous = sdlAppContinuous opts+ sdlTransparent <-+ liftIO $+ if wsTransparent settings+ then Just <$> transparentBlends sdlRenderer+ else pure Nothing+ liftIO $ unlessM (setRenderScale sdlRenderer 1 1) (sdlFail "SDL_SetRenderScale failed")+ -- Text input runs only while a widget takes text ('syncTextInput'); this+ -- stops it when the session ends.+ mkAcquire+ (void (setRenderVSyncSafe sdlRenderer (fromBool sdlVsync)))+ (const (void (stopTextInputSafe sdlWindow)))+ sdlLastPresented <- liftIO $ newIORef False+ sdlTextInput <- liftIO newTextInputSync+ -- Decided while the window is shown, before the settings apply its limits.+ sdlSizeLimits <- liftIO $ do+ toplevel <- waylandToplevel sdlWindow+ if toplevel /= 0 then Just <$> newIORef (0, 0, 0, 0) else pure Nothing+ sdlSizeLimitsSent <- liftIO $ newIORef False+ sdlBatch <- mkAcquire (newRenderBatch sdlRenderer) destroyRenderBatch+ let+ env = SdlEnv {..}+ ctx' <- liftIO $ readIORef sdlCachedCtx+ -- Before the wake action, so the first frame has the right theme without+ -- a wake.+ liftIO $ setSystemAppearance ctx' =<< querySystemAppearance+ -- Background hook jobs are cancelled with the session, before SDL quits,+ -- including when a host drives frames itself inside 'withSdl'. Ending it+ -- reads the live context: holding this one until then would keep the+ -- opening fonts' caches alive after a reload.+ mkAcquire (setWakeLoopChecked ctx' tryPushRefreshEvent) $ \_ -> do+ live <- readIORef sdlCachedCtx+ closeWindowHost live `finally` cancelTasks live+ -- The remaining settings go through the host, as from a view. This runs+ -- after the decorations (size limits account for the frame) and after the+ -- zoom (which centres the enlarged window).+ liftIO $ installWindowHost ctx' settings (windowHostFor sdlWindow (windowZoom env) sdlSizeLimits)+ liftIO $ reportWindowState ctx' =<< queryWindowState sdlWindow scale+ pure (ctx', env)++-- | Open a further window of a session, for a view's+-- 'NanoUI.nativeWindow': a context of its own with the declaring view's+-- theme and the session's images, and a window with the settings, the full+-- desktop frame, no vsync (the session's first window paces the loop), and+-- the session's fonts and UI scale. Answers the context, the environment,+-- and the action that closes the window, which also cancels the view's+-- background jobs. Call on the display thread.+openChildWindow :: SdlOptions -> SdlEnv -> Context -> WindowSettings -> IO (Context, SdlEnv, IO ())+openChildWindow opts first parent settings = do+ base <- newPixelContext+ themeFor <- readIORef (ctxThemeFor parent)+ ctx <- maybe (withTheme base =<< readIORef (ctxTheme parent)) (\pick -> base <$ followSystemTheme base pick) themeFor+ registerAppImages opts ctx+ fontSource <- sdlFontCacheSource (sdlFontCache first)+ uiScale <- readIORef (sdlUiScaleRef first)+ let childOpts =+ opts+ { sdlWindowSettings = settings+ , sdlWindowDecorations = DecorationsFull+ , sdlWindowAlwaysOnTop = False+ , sdlAppVsync = False+ , sdlAppContinuous = False+ , sdlAppUiScale = uiScale+ }+ monoSource = sdlFontCacheMonoSource (sdlFontCache first)+ -- The window's resources outlive this call: closing the state frees them.+ st <- createInternalState+ (_, (ctx', env)) <-+ runInternalState (allocateAcquire (startSdlWindow childOpts (windowFlags childOpts) ctx fontSource monoSource (Just first))) st+ `onException` closeInternalState st+ setBackendSession ctx' SSdl env+ pure (ctx', env, closeInternalState st)++-- | Register 'sdlAppImages' on a context.+registerAppImages :: SdlOptions -> Context -> IO ()+registerAppImages opts ctx =+ forM_ (sdlAppImages opts) $ \(RgbaImage image w h pixels) ->+ unlessM (registerImage ctx image w h pixels) (fail "registerImage failed")++-- | The blend modes a transparent window draws and presents with.+--+-- A frame can paint the window colour several times (the backdrop, then a+-- page-sized scroller), and ordinary blending accumulates translucent+-- alpha. Here colour blends normally but alpha takes the maximum, so the+-- window colour over itself is unchanged and the retained frame holds+-- straight alpha for screenshots. Presenting premultiplies, as compositors+-- expect.+--+-- SDL's OpenGL renderer uses one operation for colour and alpha, so it+-- cannot take the maximum. It weights the new alpha by itself instead:+-- the window colour over itself is still unchanged, but a translucent pixel+-- over a more opaque one ends slightly more transparent than either. The+-- software renderer supports neither and blends as for an opaque window,+-- so overlapping alpha accumulates.+transparentBlends :: Ptr SDL_Renderer -> IO (SDL_BlendMode, SDL_BlendMode)+transparentBlends ren = do+ let straightColour =+ composeCustomBlendMode Blend.SDL_BLENDFACTOR_SRC_ALPHA Blend.SDL_BLENDFACTOR_ONE_MINUS_SRC_ALPHA Blend.SDL_BLENDOPERATION_ADD+ firstSupported = \case+ [] -> pure Nothing+ mode : rest -> setRenderDrawBlendMode ren mode >>= \ok -> if ok then pure (Just mode) else firstSupported rest+ keepLarger <- straightColour Blend.SDL_BLENDFACTOR_ONE Blend.SDL_BLENDFACTOR_ONE Blend.SDL_BLENDOPERATION_MAXIMUM+ selfWeighted <- straightColour Blend.SDL_BLENDFACTOR_SRC_ALPHA Blend.SDL_BLENDFACTOR_ONE_MINUS_SRC_ALPHA Blend.SDL_BLENDOPERATION_ADD+ present <-+ composeCustomBlendMode+ Blend.SDL_BLENDFACTOR_SRC_ALPHA+ Blend.SDL_BLENDFACTOR_ZERO+ Blend.SDL_BLENDOPERATION_ADD+ Blend.SDL_BLENDFACTOR_ONE+ Blend.SDL_BLENDFACTOR_ZERO+ Blend.SDL_BLENDOPERATION_ADD+ maybe (Blend.SDL_BLENDMODE_BLEND, Blend.SDL_BLENDMODE_NONE) (,present) <$> firstSupported [keepLarger, selfWeighted]++-- | Resolve a font request. A search falls back to bundled Inter when no+-- family matches; an explicit file path is passed through, and loading it can+-- still fail later.+resolveNanoUIFont :: NanoUIFont -> IO FontSource+resolveNanoUIFont = \case+ DefaultFont -> pure embeddedFontSource+ FontFilePath path -> pure (FontFromPath path)+ FontSearch names -> maybe embeddedFontSource FontFromPath <$> searchFonts names++-- | Route the context's clipboard through SDL (UTF-8 text both ways).+withSdlClipboard :: Context -> Context+withSdlClipboard ctx = withClipboard ctx readClipboard writeClipboard+ where+ -- Both are safe calls. Taking the clipboard on Windows sends the window+ -- WM_DESTROYCLIPBOARD and clipboard-update messages, and on X11 SDL pumps+ -- events while the clipboard's owner answers: either can run this+ -- program's resize and hit-test callbacks.+ writeClipboard txt = TextForeign.withCString txt (setClipboardTextSafe . PtrConst.unsafeFromPtr)+ -- Another program's text need not be valid UTF-8.+ readClipboard = do+ ptr <- getClipboardTextSafe+ -- SDL_free takes a null pointer too.+ txt <- maybePeek (fmap TE.decodeUtf8Lenient . BS.packCString) ptr `finally` free (castPtr ptr)+ pure (mfilter (not . T.null) txt)+
+ lib/NanoUI/Sdl/Internal/WindowOptions.hs view
@@ -0,0 +1,116 @@+-- | The context's 'WindowHost' for an SDL window (title, icon, size limits,+-- opacity, mode, position, size, maximize and minimize), and the window state+-- views read ('queryWindowState'). "NanoUI.Sdl.Internal.Window" installs the+-- host when a window opens, applying the settings it did not open with.+module NanoUI.Sdl.Internal.WindowOptions+ ( windowHostFor+ , queryWindowState+ ) where++import Control.Monad (unless, void)+import Data.ByteString.Unsafe qualified as BSU+import Data.Int (Int32)+import Data.IORef (IORef, readIORef, writeIORef)+import Data.Maybe (isNothing)+import Data.Text.Foreign qualified as TextForeign+import Foreign.Ptr (Ptr, castPtr, nullPtr)+import NanoUI (RgbaPixels, Size (..), WindowMode (..), rgbaBytes, rgbaHeight, rgbaWidth)+import NanoUI.Backend (WindowCapabilities (..), WindowHost (..), WindowState (..), allWindowCapabilities, defaultWindowState, sizeLimitAt)+import NanoUI.Sdl.Internal.Display (outPair, queryWindowPosition, sendWaylandSizeLimits, windowPosCentered)+import NanoUI.Sdl.Internal.Frame (hasFlag, nativeFrameOutset)+import SDL3.Sys.Bindgen.Pixels qualified as Pixels+import SDL3.Sys.Bindgen.Runtime.PtrConst qualified as PtrConst+import SDL3.Sys.Bindgen.Video (SDL_Window)+import SDL3.Sys.Surface (createSurfaceFrom, destroySurface)+import SDL3.Sys.Video qualified as SDL++-- Window changes use the safe bindings, as in "NanoUI.Sdl.Internal.Chrome":+-- on Windows each call runs the window procedure before returning, which can+-- call back into the Haskell hit test.++-- | The window host for @win@. @zoom@ gives the window coordinates per layout+-- unit, read at each call. @limits@ holds the size limits of a Wayland+-- toplevel that nano-ui sends itself ('NanoUI.Sdl.Internal.Window.sdlSizeLimits').+windowHostFor :: Ptr SDL_Window -> IO Float -> Maybe (IORef (Int32, Int32, Int32, Int32)) -> WindowHost+windowHostFor win zoom limits =+ WindowHost+ { -- A Wayland toplevel cannot place itself.+ hostCapabilities = allWindowCapabilities {wcMove = isNothing limits}+ , hostSetTitle = \t -> TextForeign.withCString t (void . SDL.setWindowTitleSafe win . PtrConst.unsafeFromPtr)+ , hostSetIcon = setIcon win+ , hostSetMinSize = sizeLimit SDL.setWindowMinimumSizeSafe (\(w, h) (_, _, xw, xh) -> (w, h, raiseMax w xw, raiseMax h xh))+ , hostSetMaxSize = sizeLimit SDL.setWindowMaximumSizeSafe (\(w, h) (nw, nh, _, _) -> (lowerMin nw w, lowerMin nh h, w, h))+ , hostSetOpacity = void . SDL.setWindowOpacitySafe win+ , hostSetMode = \case+ Windowed -> void (SDL.setWindowFullscreenSafe win False) >> void (SDL.showWindowSafe win)+ Fullscreen -> void (SDL.showWindowSafe win) >> void (SDL.setWindowFullscreenSafe win True)+ Hidden -> void (SDL.hideWindowSafe win)+ , hostMove = \x y -> void (SDL.setWindowPositionSafe win (fromIntegral x) (fromIntegral y))+ , hostCenter = void (SDL.setWindowPositionSafe win windowPosCentered windowPosCentered)+ , hostResize = \s -> viewSize (Just s) >>= \(w, h) -> void (SDL.setWindowSizeSafe win w h)+ , hostMinimize = void (SDL.minimizeWindowSafe win)+ , hostMaximize = void (SDL.maximizeWindowSafe win)+ , hostRestore = void (SDL.restoreWindowSafe win)+ }+ where+ -- On a Wayland toplevel the new limit wins over the other one on an axis+ -- where the minimum would pass the maximum: the compositor disconnects a+ -- client that sends such a pair. A zero is no limit.+ raiseMax lo hi = if hi > 0 && lo > hi then lo else hi+ lowerMin lo hi = if hi > 0 && lo > hi then hi else lo+ -- A view size in window coordinates at the current zoom, plus the+ -- desktop frame on a 'NanoUI.Sdl.Internal.Frame.DecorationsFrame' window+ -- (as at open). A zero axis stays zero, meaning no limit ('sizeLimitAt').+ viewSize size = do+ z <- zoom+ outset <- nativeFrameOutset win+ let (w, h) = sizeLimitAt z outset size+ pure (fromIntegral w :: Int32, fromIntegral h)+ -- SDL resizes a window that is already past the limit. A Wayland+ -- toplevel's limits go to the compositor ('sendWaylandSizeLimits') and+ -- not to SDL, which would clamp configures to them, so it is resized here.+ sizeLimit ::+ (Ptr SDL_Window -> Int32 -> Int32 -> IO Bool) ->+ ((Int32, Int32) -> (Int32, Int32, Int32, Int32) -> (Int32, Int32, Int32, Int32)) ->+ Maybe Size ->+ IO ()+ sizeLimit set place limit = do+ (w, h) <- viewSize limit+ case limits of+ Nothing -> void (set win w h)+ Just ref -> do+ new@(nw, nh, xw, xh) <- place (w, h) <$> readIORef ref+ writeIORef ref new+ sendWaylandSizeLimits win nw nh xw xh+ (_, cw, ch) <- outPair (SDL.getWindowSize win)+ let fit v lo hi = (if hi > 0 then min hi else id) (max lo (fromIntegral v))+ (fw, fh) = (fit cw nw xw, fit ch nh xh)+ unless (fw == fromIntegral cw && fh == fromIntegral ch) $+ void (SDL.setWindowSizeSafe win fw fh)++-- | Set the window icon. SDL keeps a copy; video drivers without icons+-- ignore it.+setIcon :: Ptr SDL_Window -> RgbaPixels -> IO ()+setIcon win px =+ BSU.unsafeUseAsCString (rgbaBytes px) $ \p -> do+ surface <- createSurfaceFrom (fromIntegral (rgbaWidth px)) (fromIntegral (rgbaHeight px)) Pixels.SDL_PIXELFORMAT_RGBA32 (castPtr p) (fromIntegral (rgbaWidth px * 4))+ unless (surface == nullPtr) $+ void (SDL.setWindowIconSafe win surface) >> destroySurface surface++-- | The window state for views: the position the desktop last reported+-- (Wayland never does), and focus and mode from the window flags. Two reads+-- of SDL's cached state, cheap enough for every frame.+queryWindowState :: Ptr SDL_Window -> Float -> IO WindowState+queryWindowState win scale = do+ flags <- SDL.getWindowFlags win+ (ok, x, y) <- outPair (queryWindowPosition win)+ let has bit = hasFlag bit flags+ pure+ defaultWindowState+ { winScale = scale+ , winPosition = if ok /= 0 then Just (fromIntegral x, fromIntegral y) else Nothing+ , winFocused = has SDL.SDL_WINDOW_INPUT_FOCUS+ , winMaximized = has SDL.SDL_WINDOW_MAXIMIZED+ , winMinimized = has SDL.SDL_WINDOW_MINIMIZED+ , winFullscreen = has SDL.SDL_WINDOW_FULLSCREEN+ }
− lib/NanoUI/Sdl/NanoUIFont.hs
@@ -1,16 +0,0 @@--- | Font selection for the SDL backend.-module NanoUI.Sdl.NanoUIFont- ( NanoUIFont (..)- ) where---- | SDL text font selection.--- 'DefaultFont' uses the embedded Inter subset.--- 'FontSearch' tries each family name against the platform font directories--- (walked recursively at runtime). When nothing matches, the embedded font--- is used as fallback.--- 'FontFilePath' loads that file and does not search.-data NanoUIFont- = DefaultFont- | FontSearch [String]- | FontFilePath FilePath- deriving (Eq, Show)
− lib/NanoUI/Sdl/Render.hs
@@ -1,243 +0,0 @@-module NanoUI.Sdl.Render- ( RenderBatch- , newRenderBatch- , destroyRenderBatch- , flushRenderBatch- , renderDrawDataPass- , snapDamage- ) where--import NanoUI.Sdl.Image (ImageAtlas, lookupImage)--import Control.Monad (void, when)-import Data.Bits (shiftR, (.&.))-import Data.IORef (IORef, newIORef, readIORef, writeIORef)-import Data.Primitive.PrimArray (indexPrimArray, sizeofPrimArray)-import Data.Word (Word8)-import Foreign.C.Types (CFloat (..), CInt (..))-import Foreign.ForeignPtr (withForeignPtr)-import Foreign.Marshal.Alloc (free, malloc)-import Foreign.Ptr (Ptr, nullPtr)-import Foreign.Storable (poke)-import NanoUI (Color (..), Rect (..), rectIntersect)-import NanoUI.Testing- ( Damage (..)- , DrawCmd (..)- , DrawData (..)- , LayerSlice (..)- , damageIsEmpty- , glyphAtlasTextureId- )-import SDL3.Sys.Bindgen.Rect (SDL_Rect (..))-import SDL3.Sys.Bindgen.Render (SDL_Renderer, SDL_Texture)-import SDL3.Sys.Bindgen.Runtime.PtrConst qualified as PtrConst-import SDL3.Sys.Render- ( renderClearSafe- , setRenderClipRect- , setRenderDrawColorSafe- )--data ClipState- = ClipNone- | ClipKey {-# UNPACK #-} !Int {-# UNPACK #-} !Int {-# UNPACK #-} !Int {-# UNPACK #-} !Int- deriving (Eq)--{-# INLINE snapDamage #-}-snapDamage :: Float -> Damage -> Damage-snapDamage _ DamageFull = DamageFull-snapDamage scale (DamageClip (Rect x y w h)) =- let px = fromIntegral (floor (x * scale) :: Int) / scale- py = fromIntegral (floor (y * scale) :: Int) / scale- pw = fromIntegral (ceiling ((x + w) * scale) :: Int) / scale - px- ph = fromIntegral (ceiling ((y + h) * scale) :: Int) / scale - py- in DamageClip (Rect px py pw ph)--{-# INLINE toClipKey #-}-toClipKey :: Rect -> ClipState-toClipKey (Rect x y w h) =- let px = floor x :: Int- py = floor y :: Int- x1 = ceiling (x + w) :: Int- y1 = ceiling (y + h) :: Int- in ClipKey px py (max 1 (x1 - px)) (max 1 (y1 - py))--applyClipState :: RenderBatch -> IORef ClipState -> Ptr SDL_Renderer -> ClipState -> IO ()-applyClipState batch ref ren next = do- prev <- readIORef ref- when (prev /= next) $ do- flushRenderBatch batch- writeIORef ref next- void $ case next of- ClipNone -> setRenderClipRect ren (PtrConst.unsafeFromPtr nullPtr)- ClipKey px py pw ph -> do- let rect = rbClipRect batch- poke rect (SDL_Rect (fromIntegral px) (fromIntegral py) (fromIntegral pw) (fromIntegral ph))- setRenderClipRect ren (PtrConst.unsafeFromPtr rect)---- | Draw every command in layer-slice order, clipped to its own rect and to--- the damage. A full repaint with a clear colour clears the target first.-renderDrawDataPass :: RenderBatch -> Ptr SDL_Renderer -> Maybe Color -> DrawData -> ImageAtlas -> Ptr SDL_Texture -> Damage -> IO ()-renderDrawDataPass batch ren mClear drawData images glyphTex damage =- when (not (damageIsEmpty damage)) $ do- clipRef <- newIORef ClipNone- void $ setRenderClipRect ren (PtrConst.unsafeFromPtr nullPtr)- case (mClear, damage) of- (Just clearColor, DamageFull) -> do- let (cr, cg, cb, ca) = unpackColor clearColor- void $ setRenderDrawColorSafe ren cr cg cb ca- void $ renderClearSafe ren- (Just _clearColor, DamageClip r) ->- -- The draw list starts a clip frame with its own window backdrop,- -- so the clip needs no clear here.- applyClipState batch clipRef ren (toClipKey r)- (Nothing, DamageClip r) -> applyClipState batch clipRef ren (toClipKey r)- (Nothing, DamageFull) -> pure ()- let clip = case damage of- DamageFull -> Nothing- DamageClip r -> Just r- vc = drawVertexCount drawData- cmds = drawCommands drawData- slices = drawLayerSlices drawData- withForeignPtr (drawVertices drawData) $ \vp ->- withForeignPtr (drawIndices drawData) $ \ip ->- let goLy !li- | li >= sizeofPrimArray slices = pure ()- | otherwise = do- let LayerSlice off cnt = indexPrimArray slices li- goCmd !j- | j >= cnt = pure ()- | otherwise = do- drawCmd batch ren vp vc ip images glyphTex clip clipRef (indexPrimArray cmds (off + j))- goCmd (j + 1)- goCmd 0- goLy (li + 1)- in goLy 0- applyClipState batch clipRef ren ClipNone--{-# INLINE drawCmd #-}-drawCmd ::- RenderBatch ->- Ptr SDL_Renderer ->- Ptr Word8 ->- Int ->- Ptr Word8 ->- ImageAtlas ->- Ptr SDL_Texture ->- Maybe Rect ->- IORef ClipState ->- DrawCmd ->- IO ()-drawCmd batch ren vp vc ip images glyphTex mDamage clipRef cmd = do- let !count = fromIntegral (cmdIndexCount cmd)- !cmdRect = Rect (cmdClipX cmd) (cmdClipY cmd) (cmdClipW cmd) (cmdClipH cmd)- !cmdOpen = cmdClipW cmd >= 1e8 || cmdClipH cmd >= 1e8- live = case (mDamage, cmdOpen) of- (Nothing, _) -> Just cmdRect- (Just dmg, True) -> Just dmg- (Just dmg, False) -> rectIntersect dmg cmdRect- when (count >= 3) $- case live of- Nothing -> pure ()- Just clip -> do- if cmdOpen && mDamage == Nothing- then applyClipState batch clipRef ren ClipNone- else applyClipState batch clipRef ren (toClipKey clip)- let !start = fromIntegral (cmdIndexOffset cmd)- !texId = cmdTextureId cmd- tex <-- if texId == glyphAtlasTextureId- then pure glyphTex- else if texId > 0- then maybe nullPtr id <$> lookupImage images texId- else pure nullPtr- batchDrawRange batch vp vc ip start count tex mDamage--{-# INLINE unpackColor #-}-unpackColor :: Color -> (Word8, Word8, Word8, Word8)-unpackColor (Color w) =- ( fromIntegral ((w `shiftR` 24) .&. 0xFF)- , fromIntegral ((w `shiftR` 16) .&. 0xFF)- , fromIntegral ((w `shiftR` 8) .&. 0xFF)- , fromIntegral (w .&. 0xFF)- )---- | The C batch and a clip rect it passes to SDL, both owned for the session.-data RenderBatch = RenderBatch- { rbBatch :: !(Ptr ())- , rbClipRect :: !(Ptr SDL_Rect)- }---- | Create a persistent render batch. Reusing one batch across frames avoids--- a C calloc/free pair per presented frame; flush after each render pass.-newRenderBatch :: Ptr SDL_Renderer -> IO RenderBatch-newRenderBatch ren = do- p <- batchCreate ren- if p == nullPtr- then fail "nano_ui_batch_create failed"- else RenderBatch p <$> malloc--destroyRenderBatch :: RenderBatch -> IO ()-destroyRenderBatch batch = do- batchDestroy (rbBatch batch)- free (rbClipRect batch)--flushRenderBatch :: RenderBatch -> IO ()-flushRenderBatch batch = batchFlush (rbBatch batch)--batchDrawRange ::- RenderBatch ->- Ptr Word8 ->- Int ->- Ptr Word8 ->- Int ->- Int ->- Ptr SDL_Texture ->- Maybe Rect ->- IO ()-batchDrawRange batch verts vc indices start n tex mDmg =- batchDrawRangeC- (rbBatch batch)- verts- (ci vc)- indices- (ci start)- (ci n)- tex- hasDmg- (cf dx)- (cf dy)- (cf dw)- (cf dh)- where- ci = fromIntegral- (hasDmg, dx, dy, dw, dh) = case mDmg of- Nothing -> (0, 0, 0, 0, 0)- Just (Rect x y w h) -> (1, x, y, w, h)--cf :: Float -> CFloat-cf = realToFrac--foreign import ccall unsafe "nano_ui_batch_create"- batchCreate :: Ptr SDL_Renderer -> IO (Ptr ())--foreign import ccall unsafe "nano_ui_batch_destroy"- batchDestroy :: Ptr () -> IO ()--foreign import ccall unsafe "nano_ui_batch_flush"- batchFlush :: Ptr () -> IO ()--foreign import ccall unsafe "nano_ui_batch_draw_range"- batchDrawRangeC ::- Ptr () ->- Ptr Word8 ->- CInt ->- Ptr Word8 ->- CInt ->- CInt ->- Ptr SDL_Texture ->- CInt ->- CFloat ->- CFloat ->- CFloat ->- CFloat ->- IO ()
− lib/NanoUI/Sdl/Runner.hs
@@ -1,317 +0,0 @@-{-# LANGUAGE DataKinds #-}---- | SDL3 draw path: retained damage updates or direct continuous presentation.-module NanoUI.Sdl.Runner- ( sdlDrawFrame- , drawReduceEff- , askSdlDebug- , setSdlUiFont- , setSdlUiScale- ) where--import Control.Exception (finally, mask_)-import Control.Monad (unless, void, when)-import Data.IORef (IORef, readIORef, writeIORef)-import Data.Typeable (Typeable)-import GHC.Clock (getMonotonicTime)-import NanoUI- ( Input (..)- , NanoUI- , Size (..)- , V2 (..)- , themeWindow- )-import Effectful (Eff, IOE, type (:>))-import NanoUI.Testing- ( Context- , Damage (..)- , DrawData (..)- , Ui- , askHost- , ctxPaintFull- , ctxTheme- , damageFull- , damageIsEmpty- , drawCmdCount- , markDirty- , runEff- , runFrameEff- , runFrameReduceEff- , takeDamage- , uiIO- )-import NanoUI.Debug (CoreDebugSnapshot (..), noteDebugPresent, noteDebugSkip, refreshDebugSnapshot)-import NanoUI.Sdl.Debug- ( SdlDebugSampler (..)- , SdlDebugSnapshot (..)- , emptySdlDebug- , traceFrame- )-import NanoUI.Sdl.Display (pushRefreshEvent, queryMouseWindowPos, queryWindowLogicalSize)-import NanoUI.Sdl.Font- ( fontSourceLabel- , glyphAtlasTexture- , sdlFontCacheSource- , prepareGlyphAtlasForFrame- , takeGlyphAtlasResetFlag- )-import NanoUI.Sdl.NanoUIFont (NanoUIFont)-import NanoUI.Sdl.Render (flushRenderBatch, renderDrawDataPass, snapDamage)-import NanoUI.Sdl.Window (Retain (..), SdlEnv (..))-import Foreign.Marshal.Alloc (alloca)-import Foreign.Marshal.Utils (with)-import Foreign.Ptr (Ptr, nullPtr)-import Foreign.Storable (peek)-import qualified NanoUI.Sdl.Image as SdlImage-import SDL3.Sys.Bindgen.Blendmode (sDL_BLENDMODE_NONE)-import SDL3.Sys.Bindgen.Pixels (data SDL_PIXELFORMAT_RGBA32)-import SDL3.Sys.Bindgen.Rect (SDL_FRect (..))-import SDL3.Sys.Bindgen.Render (SDL_Texture, data SDL_TEXTUREACCESS_TARGET)-import SDL3.Sys.Bindgen.Runtime.PtrConst qualified as PtrConst-import SDL3.Sys.Render- ( createTexture- , destroyTexture- , getRenderOutputSize- , renderPresentSafe- , renderTexture- , setRenderClipRect- , setRenderScale- , setRenderTarget- , setTextureBlendMode- )--sdlDrawFrame :: Context -> NanoUI () -> SdlEnv -> Input -> Bool -> IO (Bool, Input)-sdlDrawFrame ctx ui env inp forceFull =- drawFrameWith ctx env inp forceFull $ do- (_, _, drawData, dirtyAfterUi) <- runFrameEff runEff ctx inp ui- pure (drawData, dirtyAfterUi)---- | Both application styles share atlas maintenance, retain preparation,--- timing, and presentation. Only evaluation of the UI differs.-drawFrameWith :: Context -> SdlEnv -> Input -> Bool -> IO (DrawData, Bool) -> IO (Bool, Input)-drawFrameWith ctx env inp forceFull evaluateUi = do- SdlImage.syncImageAtlas (sdlRenderer env) (sdlImages env) ctx- (tex, presentFull) <- prepareRetain ctx env inp forceFull- t0 <- getMonotonicTime- (drawData, dirtyAfterUi) <- evaluateUi- t1 <- getMonotonicTime- finishDraw ctx env inp tex presentFull t0 t1 drawData dirtyAfterUi---- | Choose the render target and whether to repaint everything. Must run--- before the frame so paint can cull to damage for retained partial updates.-prepareRetain :: Context -> SdlEnv -> Input -> Bool -> IO (Ptr SDL_Texture, Bool)-prepareRetain ctx env inp forceFull = do- -- 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.- prepareGlyphAtlasForFrame (sdlGlyphAtlas env)- scale <- readIORef (sdlScaleRef env)- let Size lw lh = inputWindowSize inp- pw = max 1 (round (lw * scale))- ph = max 1 (round (lh * scale))- -- Continuous sessions repaint every pixel, so retaining and copying a- -- second framebuffer only adds a target switch and a full-window blit.- -- 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.- direct <-- if sdlContinuous env- then- alloca $ \wp ->- alloca $ \hp -> do- ok <- getRenderOutputSize (sdlRenderer env) wp hp- ow <- peek wp- oh <- peek hp- pure (ok && fromIntegral ow == pw && fromIntegral oh == ph)- else pure False- (tex, retainNew) <-- if direct- then pure (nullPtr, False)- else ensureRetain env pw ph scale- let presentFull = forceFull || retainNew || sdlContinuous env || inputWindowRedraw inp- writeIORef (ctxPaintFull ctx) presentFull- pure (tex, presentFull)--drawReduceEff ::- (IOE :> es, Typeable msg, Eq model) =>- (forall x. Eff es x -> IO x) ->- (msg -> model -> model) ->- IORef model ->- (model -> Eff (Ui : es) ()) ->- Context ->- SdlEnv ->- Input ->- Bool ->- IO (Bool, Input)-drawReduceEff unlift update modelRef view ctx env inp forceFull =- drawFrameWith ctx env inp forceFull $ do- m <- readIORef modelRef- (_, m', _, drawData, dirtyAfterUi) <- runFrameReduceEff unlift update ctx inp m view- writeIORef modelRef m'- pure (drawData, dirtyAfterUi)--finishDraw :: Context -> SdlEnv -> Input -> Ptr SDL_Texture -> Bool -> Double -> Double -> DrawData -> Bool -> IO (Bool, Input)-finishDraw ctx env inp tex presentFull t0 t1 drawData dirtyAfterUi = do- let uiMs = (t1 - t0) * 1000- scale <- readIORef (sdlScaleRef env)- dmg0 <- takeDamage ctx- let Size lw lh = inputWindowSize inp- -- 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 =- if presentFull- then DamageFull- else snapDamage scale dmg0- writeIORef (sdlLastPresented env) False- -- A glyph-atlas reset or exhaustion during the UI pass means quads- -- recorded before that point hold stale (or unplaceable) UVs. Drop the- -- frame instead of presenting it: the screen keeps the previous valid- -- frame, 'damageFull' forces a full repaint, and- -- 'prepareGlyphAtlasForFrame' resets the atlas before the next frame- -- records any quads, so text never flickers or vanishes for a frame.- atlasReset <- takeGlyphAtlasResetFlag (sdlGlyphAtlas env)- if atlasReset || damageIsEmpty damage || lw <= 0 || lh <= 0- then do- when atlasReset $ do- damageFull ctx- markDirty ctx- noteDebugSkip (sdsSampler (sdlDebug env))- pure (atlasReset || dirtyAfterUi, inp)- else do- -- A null texture draws full-repaint sessions straight to the window.- okBegin <- setRenderTarget (sdlRenderer env) tex- okScale <- setRenderScale (sdlRenderer env) scale scale- unless (okBegin && okScale) $ fail "SDL_SetRenderTarget/Scale failed"- theme <- readIORef (ctxTheme ctx)- glyphTex <- glyphAtlasTexture (sdlGlyphAtlas env)- -- Persistent batch created once per session (sdlBatch): no C- -- calloc/free pair per presented frame. Flush unconditionally so an- -- aborted pass cannot leak pending geometry into the next frame.- --- -- Full repaints clear the target, including bare backdrop regions.- -- Partial updates preserve the undamaged part of the retained texture.- let batch = sdlBatch env- renderDrawDataPass- batch- (sdlRenderer env)- (if damage == DamageFull then Just (themeWindow theme) else Nothing)- drawData- (sdlImages env)- glyphTex- damage- `finally` flushRenderBatch batch- t2 <- getMonotonicTime- -- Damage limits updates to the retained texture, not the final copy:- -- SDL leaves the window backbuffer undefined after each present.- -- Restore the window's pixel coordinate system before polling events.- -- Retained sessions do this as part of their final texture copy.- okBlit <-- if tex == nullPtr- then setRenderScale (sdlRenderer env) 1 1- else do- okTarget <- setRenderTarget (sdlRenderer env) nullPtr- okClip <- setRenderClipRect (sdlRenderer env) (PtrConst.unsafeFromPtr nullPtr)- void $ setRenderScale (sdlRenderer env) 1 1- -- The texture is larger than the window: copy only the used area.- r <- readIORef (sdlRetain env)- let src = SDL_FRect 0 0 (fromIntegral (retainW r)) (fromIntegral (retainH r))- okCopy <- with src $ \srcP ->- renderTexture (sdlRenderer env) tex (PtrConst.unsafeFromPtr srcP) (PtrConst.unsafeFromPtr nullPtr)- pure (okTarget && okClip && okCopy)- unless okBlit $ fail "SDL window presentation preparation failed"- void $ renderPresentSafe (sdlRenderer env)- t3 <- getMonotonicTime- let renderMs = (t2 - t1) * 1000- presentMs = (t3 - t2) * 1000- frameMs = (t3 - t0) * 1000- noteDebugPresent (sdsSampler (sdlDebug env)) uiMs renderMs presentMs frameMs- (drawVertexCount drawData) (drawIndexCount drawData) (drawCmdCount drawData)- writeIORef (sdlLastPresented env) True- pure (dirtyAfterUi, inp)---- | 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)- let tex = retainTexture r- fits = w <= retainCapW r && h <= retainCapH r- -- Give memory back once the window is well inside the texture, but not- -- for a shrink of a block or so, which a drag back out would undo.- roomy = 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 || abs (retainScale r - scale) > 0.001- 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) SDL_PIXELFORMAT_RGBA32 SDL_TEXTUREACCESS_TARGET (fromIntegral cw) (fromIntegral ch)- when (tex' == nullPtr) $ fail "SDL_CreateTexture(retain) failed"- void $ setTextureBlendMode tex' (fromIntegral sDL_BLENDMODE_NONE)- 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)--askSdlDebug :: Ui :> es => Eff es SdlDebugSnapshot-askSdlDebug = do- menv <- askHost @SdlEnv- case menv of- Nothing -> pure emptySdlDebug- Just env -> uiIO $ do- let sampler = sdlDebug env- -- The display is queried only when the snapshot refreshes.- refreshDebugSnapshot (sdsSampler sampler) (sdsSnapshot sampler) $ \core -> do- scale <- readIORef (sdlScaleRef env)- fontSource <- sdlFontCacheSource (sdlFontCache 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- , dbgRefreshHz = round (1 / sdlRefreshPeriod env)- }- when (sdsTrace sampler) (traceFrame snap)- pure snap---- | Request a UI font family. The SDL display thread resolves and applies it--- before the next frame (see 'NanoUI.Sdl.Window.syncDisplay'), rebuilding the--- glyph atlas and text resolver. A no-op on non-SDL hosts.-setSdlUiFont :: Ui :> es => NanoUIFont -> Eff es ()-setSdlUiFont font = do- menv <- askHost @SdlEnv- case menv of- Nothing -> pure ()- Just env -> uiIO $ do- cur <- readIORef (sdlFontRequestRef env)- when (cur /= font) $ writeIORef (sdlFontRequestRef env) font---- | Set the UI scale (see 'NanoUI.Sdl.Window.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 wakes. A no-op on--- non-SDL hosts.-setSdlUiScale :: Ui :> es => Float -> Eff es ()-setSdlUiScale s = do- menv <- askHost @SdlEnv- case menv of- Nothing -> pure ()- Just env -> uiIO $ do- cur <- readIORef (sdlUiScaleRef env)- when (cur /= s) $ do- writeIORef (sdlUiScaleRef env) s- pushRefreshEvent
− lib/NanoUI/Sdl/Session.hs
@@ -1,187 +0,0 @@-{-# LANGUAGE DataKinds #-}---- | SDL window session loop: event poll, resize sync, frame present.-module NanoUI.Sdl.Session- ( runSdlSession- ) where--import Control.Exception (bracket)-import Control.Monad (void, when)-import Data.IORef (newIORef, readIORef, writeIORef)-import NanoUI (Input (..), emptyInput)-import NanoUI.Sdl.Debug (SdlDebugSampler (..))-import NanoUI.Input (clearEphemeral)-import NanoUI.Runner- ( SessionDriver (..)- , newDrawingLock- , runSessionLoop- , shouldRedrawFrame- , tryWithDrawingLock- )-import NanoUI.Testing- ( Context- , clearDirty- )-import NanoUI.Sdl.Cursor (syncPointerCursor)-import NanoUI.Sdl.Input- ( SdlEvent (..)- , applyEvent- , isButtonEdge- , isHardQuit- , pollEvents- , waitEvent- , waitEventTimeout- )-import NanoUI.Sdl.Display (installResizeWatch)-import NanoUI.Sdl.Window (SdlEnv (..), SdlOptions (..), syncDisplay, withSdl)-import SDL3.Sys.Bindgen.Blendmode (sDL_BLENDMODE_BLEND)-import SDL3.Sys.Render (setRenderDrawBlendModeSafe, setRenderVSync)---runSdlSession ::- SdlOptions ->- Context ->- (SdlEnv -> IO ()) ->- (Input -> Bool) ->- (Context -> SdlEnv -> Input -> Bool -> IO (Bool, Input)) ->- IO ()-runSdlSession options ctx setup shouldQuit drawFn =- withSdl options ctx $ \ctx0 env -> do- setup env- void $ setRenderDrawBlendModeSafe (sdlRenderer env) (fromIntegral sDL_BLENDMODE_BLEND)- ctxRef <- newIORef ctx0- prev <- newIORef emptyInput- drawing <- newDrawingLock- startupDone <- newIORef False- startupCatchup <- newIORef False- -- The resize watch presents with vsync off: Windows' modal size loop- -- cannot take the next drag step while a present waits for vblank. The- -- main loop turns vsync back on before its own frames.- vsyncPaused <- newIORef False- -- Window size the resize watch presented since the main loop last- -- decided whether to draw. That frame already covers the size change and- -- expose events the loop is about to see.- resizePresented <- newIORef Nothing- let onResize = do- void $- tryWithDrawingLock drawing $ do- liveCtx <- readIORef ctxRef- inp <- readIORef prev- scale0 <- readIORef (sdlScaleRef env)- (ctx', inpSynced) <- syncDisplay liveCtx env (clearEphemeral inp)- writeIORef ctxRef ctx'- done <- readIORef startupDone- if not done- then do- writeIORef prev inpSynced- writeIORef startupCatchup True- else do- scale1 <- readIORef (sdlScaleRef env)- if inputWindowSize inpSynced == inputWindowSize inp && scale1 == scale0- then writeIORef prev inpSynced- else do- paused <- readIORef vsyncPaused- when (sdlVsync env && not paused) $ do- void $ setRenderVSync (sdlRenderer env) 0- writeIORef vsyncPaused True- (_, s) <- drawFn ctx' env inpSynced True- writeIORef prev s- writeIORef resizePresented (Just (inputWindowSize s))- -- A refresh wake (a finished file dialog) may postdate the watch's frame,- -- so it voids that frame's cover.- let noteWake evs = do- when (EvRefresh `elem` evs) $ writeIORef resizePresented Nothing- pure evs- let drainUntilQuiet c inp = do- pending <- pollEvents- (c', inp') <- syncDisplay c env (foldl' applyEvent inp pending)- if null pending- then pure (c', inp')- else drainUntilQuiet c' inp'- let inpSeed = emptyInput {inputWindowSize = sdlWindowSize options}- (ctx1, inp0) <- drainUntilQuiet ctx0 inpSeed- writeIORef ctxRef ctx1- scale0 <- readIORef (sdlScaleRef env)- (_, synced0) <- drawFn ctx1 env inp0 True- -- First present can apply DPI. Prev rects are empty on that frame.- -- Draw once more before idle or the Controls page stays stretched- -- until the first mouse move.- (ctx1b, inp0b) <- drainUntilQuiet ctx1 synced0- writeIORef ctxRef ctx1b- scaleSettle <- readIORef (sdlScaleRef env)- let paintedSize = inputWindowSize inp0b- (_, synced0b) <- drawFn ctx1b env inp0b True- clearDirty ctx1b- (ctx2, inp1) <- drainUntilQuiet ctx1b synced0b- writeIORef ctxRef ctx2- scale1 <- readIORef (sdlScaleRef env)- catchup <- readIORef startupCatchup- synced1 <-- if catchup || inputWindowSize inp1 /= paintedSize || abs (scale1 - scaleSettle) > 0.001 || abs (scaleSettle - scale0) > 0.001- then do- (_, s) <- drawFn ctx2 env inp1 True- clearDirty ctx2- pure s- else pure inp1- writeIORef startupCatchup False- writeIORef startupDone True- writeIORef prev synced1- let drv =- SessionDriver- { sdPollEvents = pollEvents >>= noteWake- , sdWaitEvents = \t -> do- -- Take the rest of the queue with the event that ended the- -- wait, so one pass sees a whole burst (a resize queues- -- several window events at once).- woke <- if t < 0 then waitEvent else waitEventTimeout t- case woke of- Nothing -> pure []- Just ev -> noteWake . (ev :) =<< pollEvents- , sdApplyEvent = applyEvent- , sdIsButtonEdge = isButtonEdge- , sdIsHardQuit = isHardQuit- , sdIsSessionQuit = (== EvQuit)- , sdSyncDisplay = \c inp -> do- paused <- readIORef vsyncPaused- when paused $ do- void $ setRenderVSync (sdlRenderer env) 1- writeIORef vsyncPaused False- (c', inp') <- syncDisplay c env inp- writeIORef ctxRef c'- writeIORef prev inp'- pure (c', inp')- , sdDebug = sdsSampler (sdlDebug env)- , sdContinuous = sdlContinuous env- -- With vsync on, presents throttle the loop. With vsync off a- -- live animation would spin at max speed, so wait ~2 ms short- -- of the frame period, leaving the slack for alignFrameStart:- -- SDL_WaitEventTimeout overruns by ~1 ms, and a wait that- -- returns past the boundary makes the frame late.- , sdPacingMs = if sdlVsync env then 16 else max 1 (floor (sdlRefreshPeriod env * 1000) - 2)- -- A frame that skipped (empty damage, e.g. an animation scrolled- -- out of view) did not wait for vblank, so it must not loop- -- without waiting.- , sdPresentPaces = if sdlVsync env then readIORef (sdlLastPresented env) else pure False- , sdShouldDraw = \c prevInp inpSynced wasAnim wantDebug -> do- presented <- readIORef resizePresented- writeIORef resizePresented Nothing- let (prevInp', inpSynced') = case presented of- Just size- | size == inputWindowSize inpSynced ->- (prevInp {inputWindowSize = size}, inpSynced {inputWindowRedraw = False})- _ -> (prevInp, inpSynced)- shouldRedrawFrame c prevInp' inpSynced' wasAnim (sdlContinuous env) wantDebug- , sdDraw = \c inpSynced forceFull -> do- writeIORef resizePresented Nothing- ms <- tryWithDrawingLock drawing (drawFn c env inpSynced (forceFull || sdlContinuous env))- case ms of- Just (dirtyOut, s) -> do- writeIORef prev s- pure (dirtyOut, s)- Nothing -> pure (False, inpSynced)- , sdOnCursor = syncPointerCursor (sdlCursors env)- , sdAlignSec = sdlRefreshPeriod env- , sdShouldQuit = shouldQuit- }- bracket (installResizeWatch onResize) id $ \_ ->- runSessionLoop drv ctx2 synced1
− lib/NanoUI/Sdl/Window.hs
@@ -1,490 +0,0 @@-module NanoUI.Sdl.Window- ( RgbaImage (..)- , SdlEnv (..)- , Retain (..)- , noRetain- , SdlOptions (..)- , defaultSdlOptions- , withSdl- , withSdlBench- , syncDisplay- , saveScreenshot- ) where--import Control.Exception (bracket)-import Control.Monad (unless, void, when)-import Data.Bits ((.|.))-import Data.ByteString (ByteString)-import Data.ByteString qualified as BS-import Data.Maybe (isJust, isNothing)-import Data.IORef (IORef, newIORef, readIORef, writeIORef)-import System.Environment (lookupEnv)-import Text.Read (readMaybe)-import Data.Primitive.SmallArray (SmallArray)-import Data.Text (Text)-import Data.Text.Foreign qualified as TextForeign-import Foreign.C.String (withCString)-import Foreign.Marshal.Alloc (alloca)-import Foreign.Ptr (Ptr, nullPtr)-import Foreign.Storable (peek)-import NanoUI (ImageId, Input (..), Size (..), Theme, V2 (..))-import NanoUI.Context (Context (..), setDrawSnapScale)-import NanoUI.Testing (clearMeasureCache, markDirty, setHost, setWakeLoop)-import NanoUI.Sdl.Display- ( defaultFontSize- , initRefreshEvent- , pushRefreshEvent- , queryMouseWindowPos- , queryWindowPixelDensity- , queryWindowLogicalSize- , queryWindowRefreshHz- , zoomWindow- )-import NanoUI.Sdl.Clipboard (withSdlClipboard)-import NanoUI.Sdl.Cursor (SdlCursors (..), destroyCursors, initCursors)-import NanoUI.Sdl.Font- ( FontSource (..)- , GlyphAtlas- , SdlFontCache- , destroyGlyphAtlas- , destroySdlFontCache- , newGlyphAtlas- , newSdlFontCache- , reloadSdlFontCache- , sdlFontCacheSource- , withSdlFontCache- , withTtf- )-import NanoUI.Sdl.Font.Resolve- ( embeddedFontSource- , resolveNanoUIFont- , defaultFontSearch- , defaultFontSearchMono- )-import NanoUI.Sdl.NanoUIFont (NanoUIFont (..))-import NanoUI.Sdl.Debug (SdlDebugSampler, newSdlDebugSampler)-import NanoUI.Sdl.Dialog.Types (DialogState (..), clearDialogState, newDialogState)-import NanoUI.Sdl.Image (ImageAtlas, destroyImageAtlas, newImageAtlas)-import NanoUI.Sdl.Render (RenderBatch, destroyRenderBatch, newRenderBatch)-import SDL3.Sys.Bindgen.Hints (sDL_HINT_ASSERT, sDL_HINT_RENDER_VSYNC, sDL_HINT_VIDEO_DRIVER)-import SDL3.Sys.Bindgen.Render (SDL_Renderer, SDL_Texture)-import SDL3.Sys.Bindgen.Runtime.PtrConst qualified as PtrConst-import SDL3.Sys.Bindgen.Video (SDL_Window, SDL_WindowFlags (..))-import SDL3.Sys.Bindgen.Init (SDL_InitFlags (..), sDL_INIT_VIDEO)-import SDL3.Sys.Hints (setHint)-import SDL3.Sys.Init (initSafe, quitSafe)-import SDL3.Sys.Keyboard (startTextInputSafe, stopTextInputSafe)-import SDL3.Sys.Render- ( createWindowAndRendererSafe- , destroyRendererSafe- , destroyTexture- , getRendererName- , renderReadPixels- , setRenderScale- , setRenderVSync- )-import SDL3.Sys.Surface (destroySurface, saveBMP)-import SDL3.Sys.Video (destroyWindowSafe, getWindowDisplayScale)---- | Initial RGBA asset uploaded before the first frame.-data RgbaImage = RgbaImage- { rgbaImageId :: !ImageId- , rgbaImageWidth :: !Int- , rgbaImageHeight :: !Int- , rgbaImagePixels :: !ByteString- }---- | Application-owned SDL settings.-data SdlOptions = SdlOptions- { sdlWindowTitle :: !Text- -- ^ Window title (default: @"nano-ui"@).- , sdlWindowSize :: !Size- -- ^ Initial window size in logical units (default: 1280x800).- , sdlWindowResizable :: !Bool- -- ^ Allow the window to be resized (default: 'True').- , sdlWindowFullscreen :: !Bool- -- ^ Open the window in fullscreen mode (default: 'False').- , sdlWindowBorderless :: !Bool- -- ^ Create a borderless window (default: 'False').- , sdlWindowAlwaysOnTop :: !Bool- -- ^ Keep the window on top of other windows (default: 'False').- , sdlWindowHidden :: !Bool- -- ^ Start the window hidden (default: 'False').- , sdlAppVsync :: !Bool- -- ^ Enable vertical synchronization (default: 'True').- , sdlAppContinuous :: !Bool- -- ^ Continuous unthrottled rendering without waiting for events (default: 'False').- , sdlAppFont :: !NanoUIFont- -- ^ UI font (default: embedded Inter).- , sdlAppMonoFont :: !NanoUIFont- -- ^ Monospace font (default: embedded Inter).- , sdlAppFontSize :: !Float- -- ^ Base font size in points (default: 16).- , sdlAppTheme :: !(Maybe Theme)- -- ^ Initial UI theme override (default: 'Nothing').- , sdlAppShouldQuit :: !(Input -> Bool)- -- ^ Predicate on user input to trigger application exit (default: @const False@).\- , sdlAppImages :: !(SmallArray RgbaImage)- -- ^ Initial RGBA textures registered before the first frame.- , sdlAppUiScale :: !Float- -- ^ Zoom of the whole UI, on top of the window's pixel density (default:- -- 1). Zero or less follows the display's content scale, which on Windows- -- is the desktop's scaling setting. 'NanoUI.Backend.Sdl.setSdlUiScale'- -- changes it at runtime.- }--defaultSdlOptions :: SdlOptions-defaultSdlOptions =- SdlOptions- { sdlWindowTitle = "nano-ui"- , sdlWindowSize = defaultWindowSize- , sdlWindowResizable = True- , sdlWindowFullscreen = False- , sdlWindowBorderless = False- , sdlWindowAlwaysOnTop = False- , sdlWindowHidden = False- , sdlAppVsync = True- , sdlAppContinuous = False- , sdlAppFont = defaultFontSearch- , sdlAppMonoFont = defaultFontSearchMono- , sdlAppFontSize = defaultFontSize- , sdlAppTheme = Nothing- , sdlAppShouldQuit = const False- , sdlAppImages = mempty- , sdlAppUiScale = 1- }---- | SDL_WINDOW_HIGH_PIXEL_DENSITY (0x2000): without it the window's surface--- gets scale 1.0 even on a 2x / HiDPI output, so the compositor upscales the--- whole window (blurry "looks upscaled"). With it, SDL_GetWindowPixelDensity--- returns the real output scale where window coordinates are points (macOS,--- Wayland), the window keeps its logical size, and the pixel buffer (and--- therefore the retain texture, glyph atlas, and fonts) rasterizes at the--- native pixel density. On Windows window coordinates are already pixels, so--- the density stays 1 whatever the desktop scaling.-windowFlags :: SdlOptions -> SDL_WindowFlags-windowFlags opts =- SDL_WindowFlags $- 0x0000000000002000- .|. flag sdlWindowResizable 0x0000000000000020- .|. flag sdlWindowFullscreen 0x0000000000000001- .|. flag sdlWindowBorderless 0x0000000000000010- .|. flag sdlWindowAlwaysOnTop 0x0000000000010000- .|. flag sdlWindowHidden 0x0000000000000008- where- flag field bit = if field opts then bit else 0---- Hidden only. Do not combine with resizable for bench windows on Windows.-sdlWindowHiddenFlag :: SDL_WindowFlags-sdlWindowHiddenFlag = SDL_WindowFlags 0x0000000000000008--scaleEpsilon :: Float-scaleEpsilon = 0.001--data SdlEnv = SdlEnv- { sdlWindow :: Ptr SDL_Window- , sdlRenderer :: Ptr SDL_Renderer- , sdlRendererName :: !Text- , sdlBatch :: RenderBatch- , sdlFontRequestRef :: !(IORef NanoUIFont)- , sdlFontAppliedRef :: !(IORef NanoUIFont)- , sdlForcedScale :: !(Maybe Float)- -- ^ NANO_FORCE_SCALE override of the pixel density, read at startup.- , sdlScaleRef :: IORef Float- -- ^ Backbuffer pixels per layout unit: the pixel density times the zoom.- , sdlUiScaleRef :: !(IORef Float)- -- ^ The requested UI scale; see 'sdlAppUiScale'.- , sdlGlyphAtlas :: GlyphAtlas- , sdlImages :: ImageAtlas- , sdlCursors :: SdlCursors- , sdlDebug :: SdlDebugSampler- , sdlRetain :: IORef Retain- , sdlLastPresented :: IORef Bool- , sdlVsync :: !Bool- , sdlRefreshPeriod :: !Double- , sdlContinuous :: !Bool- , sdlCachedCtx :: !(IORef Context)- , sdlFontCache :: !SdlFontCache- , sdlDialogState :: !DialogState- }---- | The retained framebuffer. The texture is allocated in blocks larger than--- the window, so a resize drag reuses it instead of creating a render target--- per pixel of movement; only the top-left used area is drawn and presented.-data Retain = Retain- { retainTexture :: !(Ptr SDL_Texture)- , retainCapW :: !Int- , retainCapH :: !Int- -- ^ The texture's allocated size in pixels.- , retainW :: !Int- , retainH :: !Int- -- ^ The pixel size the last frame used.- , retainScale :: !Float- }--noRetain :: Retain-noRetain = Retain nullPtr 0 0 0 0 0--defaultWindowSize :: Size-defaultWindowSize = Size 1280 800---- | The zoom a UI scale setting asks for: the setting itself, or for zero or--- less the display's content scale beyond the pixel density.-resolveZoom :: Ptr SDL_Window -> Float -> IO Float-resolveZoom win setting- | setting > 0 = pure setting- | otherwise = do- display <- getWindowDisplayScale win- density <- queryWindowPixelDensity win- pure (if display > 0 then max 0.25 (display / density) else 1)---- Layout in logical coordinates (window coordinates over the zoom);--- draw/text rasterize at native pixel density.-syncDisplay :: Context -> SdlEnv -> Input -> IO (Context, Input)-syncDisplay ctx env inp = do- density <- maybe (queryWindowPixelDensity (sdlWindow env)) pure (sdlForcedScale env)- zoom <- resolveZoom (sdlWindow env) =<< readIORef (sdlUiScaleRef env)- let scale = density * zoom- oldScale <- readIORef (sdlScaleRef env)- let scaleChanged = abs (scale - oldScale) > scaleEpsilon- when scaleChanged $ do- -- Presents leave the renderer at 1:1 pixels; re-assert it only when the- -- pixel density moves.- ok <- setRenderScale (sdlRenderer env) 1 1- unless ok $ fail "SDL_SetRenderScale failed"- writeIORef (sdlScaleRef env) scale- setDrawSnapScale ctx scale- -- Runtime font-family switch: the app publishes its requested family through- -- 'setSdlUiFont'; resolve and apply it here, on the display thread, before- -- the next frame so the atlas, metrics, and text resolver agree.- requested <- readIORef (sdlFontRequestRef env)- applied <- readIORef (sdlFontAppliedRef env)- let fontChanged = requested /= applied- when (scaleChanged || fontChanged) $ do- source <-- if fontChanged- then resolveNanoUIFont requested- else sdlFontCacheSource (sdlFontCache env)- writeIORef (sdlFontAppliedRef env) requested- reloadSdlFontCache (sdlFontCache env) source- writeIORef (sdlCachedCtx env) . withSdlClipboard =<< withSdlFontCache (sdlFontCache env) ctx- clearMeasureCache ctx- markDirty ctx- queried <- queryWindowLogicalSize (sdlWindow env)- let unzoom (Size sw sh) = Size (sw / zoom) (sh / zoom)- winSize =- case unzoom queried of- Size 0 0 ->- case inputWindowSize inp of- Size 0 0 -> defaultWindowSize- s -> s- s -> s- V2 mx my <- queryMouseWindowPos- let mouse = V2 (mx / zoom) (my / zoom)- ctxMeasured <- readIORef (sdlCachedCtx env)- pure (ctxMeasured, inp {inputWindowSize = winSize, inputMousePos = mouse})---- | Everything a window session is opened with, besides the context.-data WindowConfig = WindowConfig- { wcTitle :: !Text- , wcSize :: !Size- , wcFlags :: !SDL_WindowFlags- , wcBench :: !Bool- -- ^ Hidden benchmark window: bench hints, no vsync setup or text input.- , wcVsync :: !Bool- , wcContinuous :: !Bool- , wcUiFont :: !NanoUIFont- , wcMonoFont :: !NanoUIFont- , wcFontSize :: !Float- , wcUiScale :: !Float- }--withSdl :: SdlOptions -> Context -> (Context -> SdlEnv -> IO a) -> IO a-withSdl opts ctx =- withSdlWindow- ctx- WindowConfig- { wcTitle = sdlWindowTitle opts- , wcSize = sdlWindowSize opts- , wcFlags = windowFlags opts- , wcBench = False- , wcVsync = sdlAppVsync opts- , wcContinuous = sdlAppContinuous opts- , wcUiFont = sdlAppFont opts- , wcMonoFont = sdlAppMonoFont opts- , wcFontSize = sdlAppFontSize opts- , wcUiScale = sdlAppUiScale opts- }--withSdlBench :: Context -> (Context -> SdlEnv -> IO a) -> IO a-withSdlBench ctx =- withSdlWindow- ctx- WindowConfig- { wcTitle = "nano-ui-bench"- , wcSize = Size 800 600- , wcFlags = sdlWindowHiddenFlag- , wcBench = True- , wcVsync = False- , wcContinuous = True- , wcUiFont = DefaultFont- , wcMonoFont = DefaultFont- , wcFontSize = defaultFontSize- , wcUiScale = 1- }--withSdlWindow :: Context -> WindowConfig -> (Context -> SdlEnv -> IO a) -> IO a-withSdlWindow ctx cfg act =- withTtf $ do- let hint name value =- BS.useAsCString name $ \cname ->- BS.useAsCString value $ \cvalue ->- void $ setHint (PtrConst.unsafeFromPtr cname) (PtrConst.unsafeFromPtr cvalue)- if wcBench cfg- then do- hint sDL_HINT_ASSERT "always_ignore"- hint sDL_HINT_RENDER_VSYNC "0"- else do- hint sDL_HINT_RENDER_VSYNC (if wcVsync cfg then "1" else "0")- -- SDL3 only auto-picks Wayland when the compositor has the fifo-v1 /- -- commit-timing-v1 protocols. Without them (sway, wlroots, many- -- others) it selects X11/XWayland, giving a scale-1 window on a- -- scale-2 (or fractional) output that the compositor upscales, so- -- text looks blurred. Native Wayland with- -- SDL_WINDOW_HIGH_PIXEL_DENSITY rasterizes at the real output scale.- -- An explicit SDL_VIDEO_DRIVER wins, and pure X11 sessions are left- -- alone.- wayland <- lookupEnv "WAYLAND_DISPLAY"- driver <- lookupEnv "SDL_VIDEO_DRIVER"- when (isJust wayland && isNothing driver) $- hint sDL_HINT_VIDEO_DRIVER "wayland"- fontSource <- resolveNanoUIFont (wcUiFont cfg)- monoSource <- resolveNanoUIFont (wcMonoFont cfg)- bracket- (startSdlWindow ctx cfg fontSource monoSource)- (\(_, env) -> stopSdlWindow (wcBench cfg) env)- (uncurry act)--startSdlWindow :: Context -> WindowConfig -> FontSource -> FontSource -> IO (Context, SdlEnv)-startSdlWindow ctx cfg fontSource monoSource = do- videoOk <- initSafe (SDL_InitFlags (fromIntegral sDL_INIT_VIDEO))- unless videoOk $ fail "SDL_Init(SDL_INIT_VIDEO) failed"- refreshOk <- initRefreshEvent- unless refreshOk $ fail "SDL_RegisterEvents failed for refresh wake"- let Size w h = wcSize cfg- bench = wcBench cfg- -- NANO_FORCE_SCALE: debug override of the pixel density.- forcedEnv <- lookupEnv "NANO_FORCE_SCALE"- let forcedScale = case forcedEnv >>= readMaybe of- Just s | s > 0 -> Just s- _ -> Nothing- env <-- TextForeign.withCString (wcTitle cfg) $ \titlePtr ->- alloca $ \winPtr ->- alloca $ \renPtr -> do- ok <-- createWindowAndRendererSafe- (PtrConst.unsafeFromPtr titlePtr)- (round w)- (round h)- (wcFlags cfg)- winPtr- renPtr- unless ok $ fail "SDL_CreateWindowAndRenderer failed"- win <- peek winPtr- ren <- peek renPtr- density <- queryWindowPixelDensity win- zoom <- resolveZoom win (wcUiScale cfg)- -- The requested size is logical, so the window grows with the zoom.- when (abs (zoom - 1) > scaleEpsilon) $- zoomWindow win (wcSize cfg) zoom- let scale = density * zoom- setDrawSnapScale ctx scale- refreshHz <- queryWindowRefreshHz win- rendererName <- getRendererName ren >>= \name ->- if PtrConst.unsafeToPtr name == nullPtr then pure "unknown" else TextForeign.peekCString (PtrConst.unsafeToPtr name)- scaleRef <- newIORef scale- uiScaleRef <- newIORef (wcUiScale cfg)- fontRequestRef <- newIORef (wcUiFont cfg)- fontAppliedRef <- newIORef (wcUiFont cfg)- glyphAtlas <- newGlyphAtlas ren- images <- newImageAtlas- cursors <- initCursors- debug <- newSdlDebugSampler- retain <- newIORef noRetain- fontCache <-- newSdlFontCache- fontSource- embeddedFontSource- monoSource- embeddedFontSource- glyphAtlas- (wcFontSize cfg)- scaleRef- cachedCtx <- newIORef . withSdlClipboard =<< withSdlFontCache fontCache ctx- let refreshPeriod =- if refreshHz > 0- then 1 / fromIntegral refreshHz- else 1 / 60- scaleOk <- setRenderScale ren 1 1- unless scaleOk $ fail "SDL_SetRenderScale failed"- unless bench $ do- void $ setRenderVSync ren (if wcVsync cfg then 1 else 0)- void $ startTextInputSafe win- dialogState <- newDialogState- lastPresented <- newIORef False- batch <- newRenderBatch ren- pure- SdlEnv- { sdlWindow = win- , sdlRenderer = ren- , sdlRendererName = rendererName- , sdlBatch = batch- , sdlFontRequestRef = fontRequestRef- , sdlFontAppliedRef = fontAppliedRef- , sdlForcedScale = forcedScale- , sdlScaleRef = scaleRef- , sdlUiScaleRef = uiScaleRef- , sdlGlyphAtlas = glyphAtlas- , sdlImages = images- , sdlCursors = cursors- , sdlDebug = debug- , sdlRetain = retain- , sdlLastPresented = lastPresented- , sdlVsync = wcVsync cfg- , sdlRefreshPeriod = refreshPeriod- , sdlContinuous = wcContinuous cfg- , sdlCachedCtx = cachedCtx- , sdlFontCache = fontCache- , sdlDialogState = dialogState- }- ctx' <- readIORef (sdlCachedCtx env)- setHost ctx' env- setWakeLoop ctx' pushRefreshEvent- pure (ctx', env)--stopSdlWindow :: Bool -> SdlEnv -> IO ()-stopSdlWindow bench env = do- clearDialogState (sdlDialogState env)- tex <- retainTexture <$> readIORef (sdlRetain env)- unless (tex == nullPtr) $ destroyTexture tex- destroyRenderBatch (sdlBatch env)- destroyCursors (sdlCursors env)- destroyImageAtlas (sdlImages env)- destroySdlFontCache (sdlFontCache env)- destroyGlyphAtlas (sdlGlyphAtlas env)- unless bench $ void $ stopTextInputSafe (sdlWindow env)- void $ setRenderScale (sdlRenderer env) 1 1- destroyRendererSafe (sdlRenderer env)- destroyWindowSafe (sdlWindow env)- quitSafe--saveScreenshot :: SdlEnv -> FilePath -> IO Bool-saveScreenshot env path = do- surface <- renderReadPixels (sdlRenderer env) (PtrConst.unsafeFromPtr nullPtr)- if surface == nullPtr- then pure False- else withCString path $ \cpath -> do- ok <- saveBMP surface (PtrConst.unsafeFromPtr cpath)- destroySurface surface- pure ok
nano-ui-sdl.cabal view
@@ -1,6 +1,6 @@ cabal-version: 3.4 name: nano-ui-sdl-version: 0.1.0.1+version: 0.2.0.0 synopsis: SDL3 window backend for nano-ui description: Runs nano-ui views in an SDL3 window with TrueType text and native file@@ -9,26 +9,28 @@ license-file: LICENSE author: goolord maintainer: zacharyachurchill@gmail.com+homepage: https://github.com/goolord/nano-ui+bug-reports: https://github.com/goolord/nano-ui/issues category: Graphics build-type: Simple+tested-with: GHC ==9.10.3 || ==9.14.1 extra-doc-files: CHANGELOG.md README.md extra-source-files:- data/inter.ttf cbits/*.h +source-repository head+ type: git+ location: https://github.com/goolord/nano-ui.git+ subdir: packages/nano-ui-sdl+ flag sdl description: Build the SDL3 backend. Needs SDL3, SDL3_ttf, and pkg-config. manual: True default: True -flag simd- description: Compile the batch culler with AVX2 (x86-64 only; the binary then requires an AVX2 CPU)- manual: True- default: False- common extensions default-language: GHC2024 default-extensions:@@ -46,94 +48,133 @@ ghc-options: -rtsopts -threaded "-with-rtsopts=-N1 -T" common warnings- ghc-options:- -Wall- -Wextra- -Wcompat- -Widentities- -Wincomplete-record-updates- -Wincomplete-uni-patterns- -Wmissing-export-lists- -Wmissing-home-modules- -Wpartial-fields- -Wredundant-constraints- -Wunused-packages+ ghc-options:+ -Wall+ -Wextra+ -Wcompat+ -Widentities+ -Wincomplete-record-updates+ -Wincomplete-uni-patterns+ -Wmissing-export-lists+ -Wmissing-home-modules+ -Wpartial-fields+ -Wredundant-constraints+ -Wunused-packages library import: extensions import: warnings exposed-modules: NanoUI.Backend.Sdl- NanoUI.Sdl.Input- NanoUI.Sdl.NanoUIFont+ NanoUI.Sdl.Internal.Cursor+ NanoUI.Sdl.Internal.DialogState+ NanoUI.Sdl.Internal.Error+ NanoUI.Sdl.Internal.Image+ NanoUI.Sdl.Internal.Input+ NanoUI.Sdl.Internal.NanoUIFont+ NanoUI.Sdl.Internal.Render+ NanoUI.Sdl.Internal.Window other-modules:- NanoUI.Sdl.Session- NanoUI.Sdl.Runner- NanoUI.Sdl.Clipboard- NanoUI.Sdl.Cursor- NanoUI.Sdl.Debug- NanoUI.Sdl.Dialog- NanoUI.Sdl.Dialog.Types- NanoUI.Sdl.Display- NanoUI.Sdl.Font- NanoUI.Sdl.Font.Inter- NanoUI.Sdl.Font.Resolve- NanoUI.Sdl.Font.Search- NanoUI.Sdl.Image- NanoUI.Sdl.Render- NanoUI.Sdl.Window+ NanoUI.Sdl.Internal.Session+ NanoUI.Sdl.Internal.Children+ NanoUI.Sdl.Internal.Runner+ NanoUI.Sdl.Internal.Debug+ NanoUI.Sdl.Internal.Dialog+ NanoUI.Sdl.Internal.Chrome+ NanoUI.Sdl.Internal.Chrome.Types+ NanoUI.Sdl.Internal.Frame+ NanoUI.Sdl.Internal.Display+ NanoUI.Sdl.Internal.Env+ NanoUI.Sdl.Internal.Gpu+ NanoUI.Sdl.Internal.Pacing+ NanoUI.Sdl.Internal.Screenshot+ NanoUI.Sdl.Internal.Target+ NanoUI.Sdl.Internal.TargetPool+ NanoUI.Sdl.Internal.Font+ NanoUI.Sdl.Internal.Font.Search+ NanoUI.Sdl.Internal.Url+ NanoUI.Sdl.Internal.WindowOptions build-depends:- base ^>=4.22.0.0,+ base >=4.20 && <4.23, bytestring ^>=0.12,- containers ^>=0.8,+ containers >=0.7 && <0.9, directory ^>=1.3,- dir-traverse ^>=0.2.3.0,- effectful-core ^>=2.6, filepath ^>=1.5,- file-embed ^>=0.0.16,- hashable ^>=1.5,- nano-ui ^>=0.1,+ nano-ui ^>=0.2,+ nano-ui-emit ^>=0.2,+ nano-ui-ttf ^>=0.2, primitive ^>=0.9,+ vector ^>=0.13, record-hasfield ^>=1.0,- sdl3-bindgen-sys ^>=0.0.0.2,- text ^>=2.1,- unordered-containers ^>=0.2+ resourcet ^>=1.3,+ sdl3-bindgen-sys >=0.0.1.0 && <0.0.2,+ text >=2.1.2 && <2.2 hs-source-dirs: lib+ -- The frame and drop shadow under a window with no title bar are DWM's;+ -- see "NanoUI.Sdl.Internal.Frame".+ if os(windows)+ extra-libraries: dwmapi, user32 if !flag(sdl) buildable: False if flag(sdl)- c-sources: cbits/nano_ui_ttf.c+ c-sources: cbits/nano_ui_frame.c cbits/nano_ui_display.c- cbits/nano_ui_batch.c+ cbits/nano_ui_render.c cbits/nano_ui_text_atlas.c include-dirs: cbits pkgconfig-depends: sdl3 >= 3.2, sdl3-ttf >= 3.2- -- nano_ui_batch.c falls back to a scalar cull loop without __AVX2__.- if flag(simd) && arch(x86_64)- cc-options: -mavx2 +test-suite nano-ui-render-test+ import: extensions, warnings, rts-options+ type: exitcode-stdio-1.0+ main-is: Rendering.hs+ hs-source-dirs: test+ other-modules: Input, WindowChecks+ if os(windows)+ ghc-options: -optl-mconsole+ build-depends:+ base >=4.20 && <4.23,+ bytestring ^>=0.12,+ nano-ui ^>=0.2,+ nano-ui-emit ^>=0.2,+ nano-ui-sdl,+ nano-ui-shader ^>=0.2,+ primitive ^>=0.9,+ sdl3-bindgen-sys >=0.0.1.0 && <0.0.2,+ vector ^>=0.13+ if !flag(sdl)+ buildable: False+ test-suite nano-ui-font-search-test import: extensions, warnings type: exitcode-stdio-1.0 main-is: FontSearch.hs hs-source-dirs: test, lib- other-modules: NanoUI.Sdl.Font.Search+ other-modules: NanoUI.Sdl.Internal.Font.Search build-depends:- base ^>=4.22.0.0,- containers ^>=0.8,+ base >=4.20 && <4.23,+ containers >=0.7 && <0.9, directory ^>=1.3,- dir-traverse ^>=0.2.3.0,- filepath ^>=1.5+ filepath ^>=1.5,+ nano-ui-ttf ^>=0.2+ if !flag(sdl)+ buildable: False test-suite nano-ui-font-effects-test import: extensions, warnings, rts-options type: exitcode-stdio-1.0 main-is: FontEffects.hs hs-source-dirs: test+ if os(windows)+ ghc-options: -optl-mconsole build-depends:- base ^>=4.22.0.0,- nano-ui,+ base >=4.20 && <4.23,+ bytestring ^>=0.12,+ directory ^>=1.3,+ filepath ^>=1.5,+ nano-ui ^>=0.2, nano-ui-sdl,+ nano-ui-ttf ^>=0.2, primitive ^>=0.9, text ^>=2.1 if !flag(sdl)@@ -145,8 +186,8 @@ import: warnings main-is: SdlAnim.hs build-depends:- base ^>=4.22.0.0,- nano-ui,+ base >=4.20 && <4.23,+ nano-ui ^>=0.2, nano-ui-sdl, text ^>=2.1 hs-source-dirs: examples@@ -155,6 +196,23 @@ if !flag(sdl) buildable: False +executable nano-ui-sdl-idle+ import: extensions+ import: rts-options+ import: warnings+ main-is: SdlIdle.hs+ build-depends:+ base >=4.20 && <4.23,+ nano-ui ^>=0.2,+ nano-ui-sdl,+ sdl3-bindgen-sys >=0.0.1.0 && <0.0.2,+ text ^>=2.1+ hs-source-dirs: examples+ if os(windows)+ ghc-options: -optl-mconsole+ if !flag(sdl)+ buildable: False+ benchmark nano-ui-sdl-bench import: extensions import: bench-rts-options@@ -163,8 +221,8 @@ type: exitcode-stdio-1.0 main-is: SdlBench.hs build-depends:- base ^>=4.22.0.0,- nano-ui,+ base >=4.20 && <4.23,+ nano-ui ^>=0.2, nano-ui-sdl, tasty-bench ^>=0.4 if os(windows)
test/FontEffects.hs view
@@ -1,107 +1,170 @@+-- | The SDL session's fonts: start-up failures release what they took,+-- shaped text measures as SDL draws it, caches and font replacement leave+-- earlier text intact, and font handles outlive neither their font nor the+-- session. module Main (main) where -import Control.Exception (IOException, evaluate, try)-import Control.Monad (forM_, unless, void)+import Control.Exception (IOException, evaluate, finally, try)+import Control.Monad (forM_, void)+import Data.ByteString qualified as BS+import Data.IORef (IORef, writeIORef) import Data.List (isInfixOf)-import Data.IORef (writeIORef)-import qualified Data.Text as T-import Data.Primitive.PrimArray (indexPrimArray, sizeofPrimArray)+import Data.Primitive.PrimArray (indexPrimArray, primArrayToList, sizeofPrimArray)+import Data.Text qualified as T+import Data.Word (Word32) import NanoUI-import NanoUI.Testing (newPixelContext, textIndexAtX)-import NanoUI.Backend.Sdl (NanoUIFont (..), SdlEnv (..), syncDisplay, withSdlBench)-import NanoUI.Context (ctxResolveFont, ctxResolveMeasure)+import NanoUI.Backend+import NanoUI.Backend.Sdl+ ( NanoUIFont (..), SdlDebugSnapshot (..), SdlOptions (..), defaultSdlOptions, sdlDebugSnapshot, syncDisplay+ , withSdl, withSdlBench+ )+import NanoUI.Internal.Context (ctxResolveFont, ctxResolveMeasure)+import NanoUI.Sdl.Internal.Window (sdlFontRequestRef)+import NanoUI.Testing (textIndexAtX)+import NanoUI.Testing.Runner (check, runChecks)+import NanoUI.Ttf.Internal.Inter (fontInterBytes)+import System.Directory (createDirectory, getTemporaryDirectory, removeFile, removePathForcibly) import System.Environment (setEnv)+import System.FilePath ((</>))+import System.IO (hClose, openTempFile) import System.Mem (performGC) +foreign import ccall unsafe "SDL_WasInit" wasInit :: Word32 -> IO Word32++-- | Whether two widths agree.+near :: Float -> Float -> Bool+near a b = abs (a - b) < 0.01++-- | The floats of a run's glyph quads, eight per glyph.+quadFloats :: Maybe ShapedGlyphs -> Int+quadFloats = maybe 0 (\(ShapedGlyphs q) -> sizeofPrimArray q)+ main :: IO () main = do- setEnv "SDL_VIDEODRIVER" "dummy"+ setEnv "SDL_VIDEO_DRIVER" "dummy" setEnv "SDL_RENDER_DRIVER" "software" ctx0 <- newPixelContext- (font, snapshot, width, quad) <- withSdlBench ctx0 $ \ctx env -> do- (fm, _) <- ctxResolveFont ctx 16 WeightNormal FontStyleNormal FontRegular- let text = "AV To fi café λ"+ runChecks [("failed-start", failedStartChecks ctx0), ("session-fonts", sessionFontChecks ctx0)]++-- | Window creation fails after SDL starts: what was acquired is released,+-- and a later session opens normally.+failedStartChecks :: Context -> IORef Int -> IO ()+failedStartChecks ctx0 failed = do+ setEnv "SDL_RENDER_DRIVER" "nano-ui-test-unavailable-renderer"+ let hidden = defaultSdlOptions {sdlWindowSettings = defaultWindowSettings {wsMode = Hidden}}+ failedStart <- try (withSdl hidden ctx0 (\_ _ -> pure ()))+ setEnv "SDL_RENDER_DRIVER" "software"+ check failed "an unavailable renderer fails at creation" $ case failedStart of+ Left (e :: IOException) -> "SDL_CreateWindowAndRenderer failed" `isInfixOf` show e+ Right () -> False+ (== 0) <$> wasInit 0 >>= check failed "a failed start leaves no SDL subsystem initialised"++-- | Shaping, caches, font replacement and handle lifetimes in one session.+sessionFontChecks :: Context -> IORef Int -> IO ()+sessionFontChecks ctx0 failed = do+ -- The bundled Inter twice, as a family's regular and bold files: the+ -- "bold" is at the regular's own weight. The directory is this run's own,+ -- since another run may hold its files open.+ fixtures <- do+ (path, handle) <- (`openTempFile` "nano-ui-font-effects") =<< getTemporaryDirectory+ hClose handle >> removeFile path >> createDirectory path+ pure path+ let regularFile = fixtures </> "NanoFixture-Regular.ttf"+ text = "AV To fi café λ"+ BS.writeFile regularFile fontInterBytes+ BS.writeFile (fixtures </> "NanoFixture-Bold.ttf") fontInterBytes+ (font, snapshot, width, quad) <- (`finally` removePathForcibly fixtures) . withSdlBench ctx0 $ \ctx env -> do+ let resolve c w s = ctxResolveFont c 16 w s FontRegular+ measure c w s = fst <$> ctxResolveMeasure c 16 w s FontRegular text+ (fm, _) <- resolve ctx WeightNormal FontStyleNormal prepared <- prepareFontMetrics fm text- (hostWidth, _) <- ctxResolveMeasure ctx 16 WeightNormal FontStyleNormal FontRegular text measured <- evaluate (lineWidth prepared text)- unless (abs (hostWidth - measured) < 0.01) $- fail ("prepared shaped width differs from SDL measurement: " ++ show (hostWidth, measured))+ hostWidth <- measure ctx WeightNormal FontStyleNormal scaled <- lineWidthIO (scaleFontMetrics 1.5 fm) text- unless (abs (scaled - measured * 1.5) < 0.01) $- fail "effectful font scaling lost its metric scale"+ (italicFm, _) <- resolve ctx WeightNormal FontStyleItalic+ italicWidth <- lineWidthIO italicFm text+ italicHost <- measure ctx WeightNormal FontStyleItalic+ check failed ("prepared shaped width matches SDL's " ++ show (hostWidth, measured)) (near hostWidth measured)+ check failed "font scaling keeps its metric scale" (near scaled (measured * 1.5))+ check failed ("italic shaped width matches SDL's " ++ show (italicHost, italicWidth)) $+ near italicHost italicWidth before <- drawShaped fm text- unless (maybe False (\(ShapedGlyphs q) -> sizeofPrimArray q >= 8 * 10) before) $- fail "shaped drawing returned no glyph quads"- -- Exceed both cache caps through measurement only. This must not fill or- -- reset the atlas, nor alter an already-rasterised run.+ check failed "shaped drawing returns glyph quads" (quadFloats before >= 8 * 10)+ -- Exceeding both cache caps through measurement alone neither fills nor+ -- resets the atlas, nor alters a run already rasterised. forM_ [1 .. 1100 :: Int] $ \n -> do- let labelText = "counter " <> T.pack (show n)- p <- prepareFontMetrics fm labelText- void (evaluate (lineWidth p labelText))+ let counter = "counter " <> T.pack (show n)+ p <- prepareFontMetrics fm counter+ void (evaluate (lineWidth p counter)) after <- drawShaped fm text- unless (before == after) $- fail "metric preparation mutated the atlas or raster cache"+ check failed "metric preparation leaves the atlas and raster cache alone" (before == after) let oversized = T.replicate 1000 "W" large <- prepareFontMetrics fm oversized largeGlyphs <- drawShaped fm oversized- unless (maybe False (\(ShapedGlyphs q) -> sizeofPrimArray q == 8 * 1000) largeGlyphs && lineWidth large oversized > 0) $- fail "text wider than the atlas lost its glyphs"- shapingChecks fm+ check failed "text wider than the atlas keeps its glyphs" $+ quadFloats largeGlyphs == 8 * 1000 && lineWidth large oversized > 0+ shapingChecks failed fm performGC- again <- lineWidthIO fm text- unless (abs (again - measured) < 0.01) $- fail "font metrics changed after cache eviction and GC"- -- Exercise the actual font/atlas replacement path. Old pure snapshots- -- remain valid while old native callbacks must reject their closed font.+ lineWidthIO fm text >>= check failed "font metrics are unchanged after cache eviction and GC" . near measured+ -- Replacing the font and atlas keeps old pure snapshots valid, while+ -- old native callbacks reject their closed font. writeIORef (sdlFontRequestRef env) (FontSearch []) (replacement, _) <- syncDisplay ctx env emptyInput- expectClosed (drawShaped fm text)- (fresh, _) <- ctxResolveFont replacement 16 WeightNormal FontStyleNormal FontRegular+ expectClosed failed "a replaced font rejects drawing" (drawShaped fm text)+ (fresh, _) <- resolve replacement WeightNormal FontStyleNormal freshWidth <- lineWidthIO fresh text freshQuad <- drawShaped fresh text- unless (abs (freshWidth - measured) < 0.01 && freshQuad /= Nothing) $- fail "font/atlas replacement failed to restore shaped text"+ check failed "font and atlas replacement restores shaped text" (near freshWidth measured && freshQuad /= Nothing)+ -- A file named as the font's bold but no heavier is not its bold face:+ -- bold text stays synthetic, and measures as it draws.+ writeIORef (sdlFontRequestRef env) (FontFilePath regularFile)+ (fromFile, _) <- syncDisplay replacement env emptyInput+ (boldFm, native) <- resolve fromFile WeightBold FontStyleNormal+ check failed "a file at the regular weight is not taken for the bold face" (not native)+ boldWidth <- measure fromFile WeightBold FontStyleNormal+ drawnWidth <- lineWidthIO boldFm text+ check failed ("bold text measures as it draws " ++ show (boldWidth, drawnWidth)) (near boldWidth drawnWidth)+ -- A file that will not open draws in bundled Inter, and the debug+ -- readout names the font drawn, not the one asked for.+ let missing = fixtures </> "NanoMissing.ttf"+ writeIORef (sdlFontRequestRef env) (FontFilePath missing)+ _ <- syncDisplay fromFile env emptyInput+ shown <- dbgFontPath <$> sdlDebugSnapshot env+ check failed "the debug readout names the font drawn" (shown /= missing) pure (fresh, prepared, measured, freshQuad)- -- Pure metric and quad values are safe to evaluate after the native font,- -- atlas and SDL session are closed; native effects fail before dereferencing.- afterClose <- evaluate (lineWidth snapshot "AV To fi café λ")- unless (afterClose == width) $ fail "immutable snapshot changed after shutdown"+ -- Pure metric and quad values stay safe after the native font, atlas and+ -- session close; native effects fail before dereferencing.+ afterClose <- evaluate (lineWidth snapshot text)+ check failed "an immutable snapshot is unchanged after shutdown" (afterClose == width) void (evaluate quad)- expectClosed (prepareFontMetrics font "new text")- expectClosed (drawShaped font "AV To fi café λ")- expectClosed (drawGlyph font 'A')- putStrLn "font effects: ok"+ expectClosed failed "a closed font rejects metric preparation" (prepareFontMetrics font "new text")+ expectClosed failed "a closed font rejects drawing" (drawShaped font text) -- | Shaping reorders right-to-left text and gives every character a caret:--- an Arabic word's carets run right to left, a mixed line keeps its Latin--- carets increasing, and a click lands on the nearest caret.-shapingChecks :: FontMetrics -> IO ()-shapingChecks fm = do+-- an Arabic word's carets run right to left (the script sets the direction,+-- whichever font draws it), a mixed line keeps its Latin carets increasing,+-- and a click lands on the nearest caret.+shapingChecks :: IORef Int -> FontMetrics -> IO ()+shapingChecks failed fm = do let arabic = "مرحبا" mixed = "Hi مرحبا 12" pArabic <- prepareFontMetrics fm arabic- case fmShape pArabic arabic of- Nothing -> fail "Arabic text was not shaped"- Just st -> do- let carets = [indexPrimArray (stCarets st) i | i <- [0 .. sizeofPrimArray (stCarets st) - 1]]- unless (length carets == T.length arabic + 1) $ fail "Arabic carets do not cover every character"- -- The script sets the direction, so the word runs right to left- -- whichever font draws it.- unless (and (zipWith (>=) carets (drop 1 carets))) $- fail ("Arabic carets do not decrease: " <> show carets)- unless (textIndexAtX pArabic arabic (maximum carets + 1) == 0) $- fail "a click at the right edge of Arabic text did not land before its first character" pMixed <- prepareFontMetrics fm mixed- case fmShape pMixed mixed of- Nothing -> fail "mixed text was not shaped"- Just st -> do- let caret i = indexPrimArray (stCarets st) i- unless (caret 0 < caret 1 && caret 1 < caret 2) $ fail "Latin carets in a mixed line do not increase"- unless (caret 9 < caret 10 && caret 10 < caret 11) $ fail "digits after right-to-left text do not run left to right"+ case (fmShape pArabic arabic, fmShape pMixed mixed) of+ (Just a, Just m) -> do+ let carets = primArrayToList (stCarets a)+ caret = indexPrimArray (stCarets m)+ check failed "Arabic carets cover every character" (length carets == T.length arabic + 1)+ check failed ("Arabic carets decrease " <> show carets) (and (zipWith (>=) carets (drop 1 carets)))+ check failed "a click right of Arabic text lands before it" $+ textIndexAtX pArabic arabic (maximum carets + 1) == 0+ check failed "Latin carets in a mixed line increase" (caret 0 < caret 1 && caret 1 < caret 2)+ check failed "digits after right-to-left text run left to right" (caret 9 < caret 10 && caret 10 < caret 11)+ _ -> check failed "Arabic and mixed text are shaped" False -expectClosed :: IO a -> IO ()-expectClosed action = do- result <- try (void action) :: IO (Either IOException ())- case result of- Left err | "used after" `isInfixOf` show err -> pure ()- _ -> fail "retained font callback did not reject its closed native handle"+-- | Check that the action fails with the error a closed native handle raises.+expectClosed :: IORef Int -> String -> IO a -> IO ()+expectClosed failed name action =+ try (void action) >>= \case+ Left (err :: IOException) -> check failed name ("used after" `isInfixOf` show err)+ Right () -> check failed name False
test/FontSearch.hs view
@@ -1,69 +1,109 @@+-- | Installed-font discovery over empty fixture files in a fake home+-- directory: discovery reads only file names, so no display or font data. module Main (main) where -import Control.Exception (bracket)+import Control.Exception (IOException, bracket, try) import Control.Monad (unless)-import NanoUI.Sdl.Font.Search (listFontFamilies, searchFonts)+import Data.Maybe (isJust)+import NanoUI.Sdl.Internal.Font.Search (boldFaceCandidates, fontFilesUnder, listFontFamilies, searchFonts) import System.Directory- ( createDirectory- , createDirectoryIfMissing- , getTemporaryDirectory- , removeFile+ ( createDirectory, createDirectoryIfMissing, createDirectoryLink, getTemporaryDirectory, removeFile , removePathForcibly )+import System.Timeout (timeout) import System.Environment (lookupEnv, setEnv, unsetEnv)-import System.FilePath ((</>))+import System.FilePath (takeDirectory, (</>)) import System.IO (hClose, openTempFile) import System.Info (os) --- Discovery only inspects filenames; no native display or valid font data is needed. main :: IO () main = bracket temporaryRoot removePathForcibly $ \root ->- bracket (lookupEnv homeVar) restoreHome $ \_ -> do+ bracket (lookupEnv homeVar) (maybe (unsetEnv homeVar) (setEnv homeVar)) $ \_ -> do setEnv homeVar root- let- fonts =- root </> case os of- "mingw32" -> "Microsoft/Windows/Fonts"- "darwin" -> "Library/Fonts"- _ -> ".local/share/fonts"- regular = fonts </> "NanoSearchFixture-Regular.ttf"- bold = fonts </> "NanoSearchFixture-Bold.ttf"- fallback = fonts </> "NanoFallbackFixture.otf"- boldOnly = fonts </> "NanoBoldOnlyFixture-Bold.ttf"+ let fonts =+ root </> case os of+ "mingw32" -> "Microsoft" </> "Windows" </> "Fonts"+ "darwin" -> "Library" </> "Fonts"+ _ -> ".local" </> "share" </> "fonts"+ font = (fonts </>)+ found = Just . font+ -- Only the Linux search reads the XDG data directories.+ xdg = root </> "xdg" </> "fonts" </> "NanoXdgFixture.ttf"+ searches =+ [ ("regular face", ["Nano Search Fixture"], found "NanoSearchFixture-Regular.ttf")+ , -- Windows' file for a family whose name it does not start with.+ ("family by file name", ["Segoe UI Symbol"], found "seguisym.ttf")+ , ("regular over medium", ["NanoWeightFixture"], found "NanoWeightFixture-Regular.ttf")+ , ("book over bold", ["NanoBookFixture"], found "NanoBookFixture-Book.ttf")+ , ("upright variable font", ["NanoVariableFixture"], found "NanoVariableFixture-VariableFont_wght.ttf")+ , -- The google/fonts names, whose italic sorts first.+ ("upright font named by its axes", ["NanoBracketFixture"], found "NanoBracketFixture[wght].ttf")+ , ("XDG data directory", ["NanoXdgFixture"], if os `elem` ["mingw32", "darwin"] then Nothing else Just xdg)+ , ( "ordered fallback"+ , ["", "NanoMissingFixture", "NanoFallbackFixture", "NanoSearchFixture"]+ , found "NanoFallbackFixture.otf"+ )+ , ("empty request", [], Nothing)+ , ("missing family", ["NanoMissingFixture"], Nothing)+ , ("non-regular fallback", ["NanoBoldOnlyFixture"], found "NanoBoldOnlyFixture-Bold.ttf")+ , -- The family itself over a longer one that starts with its name,+ -- though the longer one's file sorts first.+ ("family over a longer family", ["NanoAxesFixture"], found "NanoAxesFixture[wdth,wght].ttf")+ , ("family italic over a longer family's regular", ["NanoSlantFixture"], found "NanoSlantFixture-Italic.ttf")+ , ("a longer family when it is the only one", ["NanoOnlyLongerFixture"], found "NanoOnlyLongerFixtureSC-Regular.otf")+ ]+ others =+ [ "NanoSearchFixture-Bold.ttf", "NanoBookFixture-Bold.ttf", "NanoBracketFixture-Italic[wght].ttf"+ , "NanoVariableFixture-Italic-VariableFont_wght.ttf", "NanoWeightFixture-Medium.ttf", "times.ttf"+ , "nanoshort.ttf", "nanoshortbd.ttf", "nanoshortb.ttf", "nanoshortz.ttf"+ , "NanoAxesFixtureMono[wght].ttf", "NanoAxesFixture-Italic[wdth,wght].ttf"+ , "NanoSlantFixtureCondensed-Regular.ttf", "NanoSlantFixtureHebrew-Regular.ttf"+ ]+ setEnv "XDG_DATA_DIRS" (root </> "xdg")+ unsetEnv "XDG_DATA_HOME" -- The font directories are walked once per process, so every fixture -- exists before the first search.- createDirectoryIfMissing True fonts- mapM_ (`writeFile` "") [regular, bold, fallback, boldOnly]- expect "regular face" (Just regular) =<< searchFonts ["Nano Search Fixture"]- expect "ordered fallback" (Just fallback)- =<< searchFonts- ["", "NanoMissingFixture", "NanoFallbackFixture", "NanoSearchFixture"]- expect "empty request" Nothing =<< searchFonts []- expect "missing family" Nothing =<< searchFonts ["NanoMissingFixture"]- families <- listFontFamilies- expect- "deduplicated family"- ["Nano Search Fixture"]- (filter (== "Nano Search Fixture") families)- expect "non-regular fallback" (Just boldOnly) =<< searchFonts ["NanoBoldOnlyFixture"]+ mapM_ (createDirectoryIfMissing True) [fonts, takeDirectory xdg]+ mapM_ (`writeFile` "") (xdg : map font others ++ [f | (_, _, Just f) <- searches, f /= xdg])+ mapM_ (\(name, request, want) -> expect name want =<< searchFonts request) searches+ -- An installed Times New Roman named in full may win over the fixture.+ expect "Times New Roman by its short file name" True . isJust =<< searchFonts ["Times New Roman"]+ expect "deduplicated family" ["Nano Search Fixture"] . filter (== "Nano Search Fixture") =<< listFontFamilies+ -- A bold face is looked for beside its regular face by name, the+ -- family's own file first and Windows' short names after.+ mapM_+ (\(name, regular, bolds) -> expect name (map font bolds) =<< boldFaceCandidates (font regular))+ [ ("family bold", "NanoSearchFixture-Regular.ttf", ["NanoSearchFixture-Bold.ttf"])+ , ("short-name bold", "nanoshort.ttf", ["nanoshortbd.ttf", "nanoshortb.ttf"])+ , ("no bold", "NanoFallbackFixture.otf", [])+ ]+ linkChecks root putStrLn "font search: ok" +-- | A symbolic link back up the tree ends the walk there, and a directory+-- linked from another one walked is walked once. Skipped where links cannot+-- be made (Windows without the privilege to make them).+linkChecks :: FilePath -> IO ()+linkChecks root = do+ let walked = root </> "walk"+ shared = root </> "shared"+ mapM_ (createDirectoryIfMissing True) [walked, shared]+ mapM_ (`writeFile` "") [walked </> "a.ttf", shared </> "b.ttf"]+ made <- try (createDirectoryLink walked (walked </> "loop") >> createDirectoryLink shared (walked </> "linked"))+ case made of+ Left (e :: IOException) -> putStrLn ("font search links: skipped (" ++ show e ++ ")")+ Right () -> do+ files <- timeout 10000000 (fontFilesUnder [walked, shared])+ expect "each directory walked once" (Just 2) (length <$> files)+ expect :: (Eq a, Show a) => String -> a -> a -> IO ()-expect label expected actual =- unless (actual == expected) $- fail (label ++ ": expected " ++ show expected ++ ", got " ++ show actual)+expect name want got = unless (got == want) (fail (name ++ ": expected " ++ show want ++ ", got " ++ show got)) homeVar :: String homeVar = if os == "mingw32" then "LOCALAPPDATA" else "HOME" -restoreHome :: Maybe String -> IO ()-restoreHome = maybe (unsetEnv homeVar) (setEnv homeVar)- temporaryRoot :: IO FilePath temporaryRoot = do- tmp <- getTemporaryDirectory- (path, handle) <- openTempFile tmp "nano-ui-font-search"- hClose handle- removeFile path- createDirectory path+ (path, handle) <- (`openTempFile` "nano-ui-font-search") =<< getTemporaryDirectory+ hClose handle >> removeFile path >> createDirectory path pure path
+ test/Input.hs view
@@ -0,0 +1,125 @@+{-# LANGUAGE DisambiguateRecordFields #-}+{-# LANGUAGE PackageImports #-}++-- | SDL input translation: keycodes to 'Key', events folded into 'Input',+-- and native events through SDL's own queue.+module Input (inputChecks, queueChecks) where++import Control.Exception (IOException, try)+import Control.Monad (forM_, unless)+import Data.Foldable (toList)+import Data.Word (Word32)+import Foreign.C.Types (CBool (..))+import Foreign.Marshal.Alloc (alloca)+import Foreign.Ptr (castPtr)+import Foreign.Storable (Storable, poke)+import NanoUI (V2 (..))+import NanoUI.Backend+import NanoUI.Testing.Assert (require)+import SDL3.Sys.Bindgen.Events+ (SDL_MouseButtonEvent (..), SDL_MouseMotionEvent (..), SDL_RenderEvent (..), SDL_WindowEvent (..))+import SDL3.Sys.Bindgen.Events qualified as Events+import SDL3.Sys.Bindgen.Keycode+ ( SDL_Keymod (..), sDLK_1, sDLK_A, sDLK_EQUALS, sDLK_F1, sDLK_F12, sDLK_F13, sDLK_F24, sDLK_KP_4, sDLK_KP_5+ , sDLK_KP_ENTER, sDLK_KP_PLUS, sDLK_LSHIFT, sDLK_PAGEDOWN, sDLK_RETURN, sDLK_SPACE, sDL_KMOD_NONE, sDL_KMOD_NUM+ )+import SDL3.Sys.Bindgen.Mouse (sDL_BUTTON_MIDDLE, sDL_BUTTON_X1, sDL_BUTTON_X2)+import SDL3.Sys.Events (pushEvent)+import "nano-ui-sdl" NanoUI.Sdl.Internal.Input (SdlEvent (..), applyEvent, pollEvents, sdlKey)++checks :: String -> [(String, Bool)] -> IO ()+checks what cs = do+ forM_ cs $ \(name, ok) -> require (what <> ": " <> name) ok+ putStrLn ("SDL " <> what <> ": ok")++-- | Keycodes and folded keyboard and pointer events; no SDL needed.+inputChecks :: IO ()+inputChecks = do+ let keyWith mods code = sdlKey code (SDL_Keymod (fromIntegral mods))+ key = keyWith sDL_KMOD_NONE+ keypad = keyWith sDL_KMOD_NUM+ ctrl = noModifiers {modCtrl = True}+ shift = noModifiers {modShift = True}+ folded = foldl' applyEvent emptyInput+ chord = folded [EvModifiers ctrl, EvKey (KeyChar 's') True ctrl]+ letGo = folded [EvKey (KeyChar 's') True ctrl, EvKey (KeyChar 's') False ctrl, EvModifiers noModifiers]+ blurred = applyEvent chord EvFocusLost+ typed = folded [EvKey (KeyChar 'x') True shift, EvText "X"]+ button b isDown inp = applyEvent inp (EvMouseButton b isDown (V2 5 5) (inputModifiers emptyInput))+ -- A click is read with the modifiers of the whole batch, which may+ -- already have let go of a key released just after it.+ ctrlClick = button MouseLeft True (applyEvent emptyInput (EvModifiers ctrl))+ checks "input translation"+ [ ("a letter is its character key", key sDLK_A == Just (KeyChar 'a'))+ , ("a digit and a symbol are character keys", map key [sDLK_1, sDLK_EQUALS] == map (Just . KeyChar) "1=")+ , ("Space and PageDown are named", key sDLK_SPACE == Just KeySpace && key sDLK_PAGEDOWN == Just KeyPageDown)+ , ("Return is Enter", key sDLK_RETURN == Just KeyEnter)+ , ("F1, F12, F13 and F24", map key [sDLK_F1, sDLK_F12, sDLK_F13, sDLK_F24] == map (Just . KeyF) [1, 12, 13, 24])+ , ("the keypad types with Num Lock", keypad sDLK_KP_4 == Just (KeyChar '4'))+ , ("the keypad navigates without Num Lock", key sDLK_KP_4 == Just KeyLeft && key sDLK_KP_5 == Nothing)+ , ("keypad Enter and plus", key sDLK_KP_ENTER == Just KeyEnter && keypad sDLK_KP_PLUS == Just (KeyChar '+'))+ , ("a modifier key is no key", key sDLK_LSHIFT == Nothing)+ , ( "a chord is a key with its modifiers and types nothing"+ , toList (inputKeys chord) == [KeyChar 's'] && inputModifiers chord == ctrl && inputChars chord == ""+ )+ , ( "a release is reported, and a modifier let go clears it"+ , toList (inputKeysReleased letGo) == [KeyChar 's'] && null (inputKeysHeld letGo)+ && inputModifiers letGo == noModifiers+ )+ , ( "losing the keyboard lets go of the keys and modifiers held"+ , null (inputKeysHeld blurred) && toList (inputKeysReleased blurred) == [KeyChar 's']+ && inputModifiers blurred == noModifiers+ )+ , ( "typed text keeps the modifiers of the key that typed it"+ , inputChars typed == "X" && inputModifiers typed == shift+ )+ , ("a click keeps the modifiers of the keys before it", inputModifiers ctrlClick == ctrl)+ ]++-- | Push a raw SDL event and return what the backend decodes from the queue.+through :: Storable e => e -> IO [SdlEvent]+through ev = alloca $ \p -> do+ poke (castPtr p) ev+ pushEvent p >>= \ok -> unless ok (fail "SDL_PushEvent failed")+ pollEvents++-- | Native pointer, window, render and theme events, decoded from SDL's+-- queue, emptied first. SDL's video subsystem must be running.+queueChecks :: IO ()+queueChecks = do+ _ <- pollEvents+ -- SDL_EVENT_SYSTEM_THEME_CHANGED; only the type field is set.+ theme <- through (0x108 :: Word32)+ buttons <- mapM pushButton cases+ moved <- through (SDL_MouseMotionEvent Events.SDL_EVENT_MOUSE_MOTION 0 0 0 1 0 30 40 1 1)+ left <- through (SDL_WindowEvent Events.SDL_EVENT_WINDOW_MOUSE_LEAVE 0 0 0 0 0)+ targets <- through (SDL_RenderEvent Events.SDL_EVENT_RENDER_TARGETS_RESET 0 0 0)+ device <- through (SDL_RenderEvent Events.SDL_EVENT_RENDER_DEVICE_RESET 0 0 0)+ lost <- try (through (SDL_RenderEvent Events.SDL_EVENT_RENDER_DEVICE_LOST 0 0 0))+ checks "native events" $+ [ (name, case evs of [EvMouseButton b d _ _] -> b == want && d == isDown; _ -> False)+ | ((name, isDown, _, want), evs) <- zip cases buttons+ ]+ ++ [ ("the mouse moves the pointer", case moved of [EvMouseMotion (V2 30 40) _] -> True; _ -> False)+ , ("the pointer leaves the window", left == [EvMouseLeave])+ , ("lost render targets repaint the whole window", targets == [EvWindowRedraw])+ , ("a render device reset is told from lost render targets", device == [EvRenderDeviceReset])+ , ("a lost render device ends the session", either (\(_ :: IOException) -> True) (const False) lost)+ , ("the theme event", theme == [EvSystemThemeChanged])+ ]+ where+ cases =+ [ ("the middle button goes down", True, sDL_BUTTON_MIDDLE, MouseMiddle)+ , ("the middle button comes up", False, sDL_BUTTON_MIDDLE, MouseMiddle)+ , ("X1 is back", True, sDL_BUTTON_X1, MouseBack)+ , ("X2 is forward", True, sDL_BUTTON_X2, MouseForward)+ , ("X2 comes up", False, sDL_BUTTON_X2, MouseForward)+ , ("a sixth button is another", True, 6, MouseOther 6)+ ]+ pushButton (_, isDown, b, _) =+ through+ SDL_MouseButtonEvent+ { type' = if isDown then Events.SDL_EVENT_MOUSE_BUTTON_DOWN else Events.SDL_EVENT_MOUSE_BUTTON_UP+ , reserved = 0, timestamp = 0, windowID = 0, which = 1, button = fromIntegral b+ , down = CBool (if isDown then 1 else 0), clicks = 1, padding = 0, x = 30, y = 40+ }
+ test/Rendering.hs view
@@ -0,0 +1,595 @@+{-# LANGUAGE CApiFFI #-}+{-# LANGUAGE PackageImports #-}++module Main (main) where++import Control.Exception (IOException, SomeException, bracket, catch, displayException, throwIO, try)+import Control.Monad (forM_, replicateM_, unless, void, when)+import Data.ByteString qualified as BS+import Data.Functor ((<&>))+import Data.IORef (readIORef)+import Data.List (isInfixOf, nub)+import Data.Maybe (fromMaybe, isJust, mapMaybe)+import Data.Primitive.PrimArray (primArrayFromList)+import Data.Vector.Unboxed qualified as U+import Data.Word (Word8)+import Foreign.C.Types (CBool (..), CFloat (..), CInt (..), CUInt (..))+import Foreign.ForeignPtr (mallocForeignPtrBytes, withForeignPtr)+import Foreign.Marshal.Alloc (allocaBytes)+import Foreign.Marshal.Array (allocaArray, peekArray, pokeArray)+import Foreign.Ptr (Ptr, castPtr, nullPtr, plusPtr)+import Foreign.Storable (peekByteOff, pokeByteOff)+import GHC.Clock (getMonotonicTimeNSec)+import GHC.Conc (getAllocationCounter)+import Input (inputChecks, queueChecks)+import NanoUI+ ( Color, ImageId (..), Rect (..), ShaderCapabilities (..), ShaderConfig (..), V2 (..), box, canvas, clipBox, colorA, colorBlack+ , colorB, colorG, colorR, colorRGBA, colorWhite, column, columnWith, defaultLightTheme, defaultShaderConfig+ , defaultTheme, drawStrokePathWith, fixedWH, gap, lightDark, padAll, pageColor, respRect+ , shaderBox, shaderConfigured, tight, withShader+ )+import NanoUI.Internal.Shader (CpuFragCtx (..), Shader (..))+import NanoUI.Shader+ ( MeshGradientParams (..), SdfBoxParams (..), TintParams (..), composeColor, gaussianBlur, grayscale+ , groupOpacity, meshGradient4, sdfRoundedBox, tint+ )+import NanoUI.Path qualified as P+import NanoUI.Backend+ ( Appearance (..), cursorFallback, emptyEffectSpans, emptyInput, emptyShaderCalls, emptyUniformBytes+ , followSystemThemeIO, getShaderCapabilities, getSystemAppearance, getThemeIO, setSystemAppearance, setThemeIO, snapDamage+ )+import NanoUI.Internal.Context (lookupImageUv)+import NanoUI.Sdl.Internal.Cursor (SdlCursors (..), destroyCursors, initCursors, sdlSystemCursor, showCursorKind)+import NanoUI.Sdl.Internal.Error (sdlErrorText)+import NanoUI.Sdl.Internal.Image (ImageAtlas, destroyImageAtlas, newImageAtlas, syncImageAtlas)+import NanoUI.Sdl.Internal.Render (destroyRenderBatch, flushRenderBatch, newRenderBatch, renderDrawDataPass)+import NanoUI.Testing+ ( Context, Damage (..), DrawCmd (..), DrawData (..), Layer (..), UiCursorKind (..), atlasTextureId+ , glyphPageTextureId, newPixelContext, registerImage+ )+import NanoUI.Testing.Assert (withInput)+import NanoUI.Testing.Harness (warmupDraw)+import SDL3.Sys.Bindgen.Mouse qualified as M+import SDL3.Sys.Bindgen.Render (SDL_Renderer)+import SDL3.Sys.Bindgen.Runtime.PtrConst qualified as PtrConst+import SDL3.Sys.Bindgen.Video qualified as Video+import SDL3.Sys.Error (clearError)+import SDL3.Sys.Mouse (cursorVisibleSafe)+import SDL3.Sys.Render (renderPresentSafe, renderReadPixels)+import SDL3.Sys.Video (getSystemTheme)+import System.Environment (getArgs, lookupEnv, setEnv)+import System.IO (BufferMode (LineBuffering), hFlush, hPutStrLn, hSetBuffering, stderr, stdout)+import System.Mem (performGC)+import Text.Printf (printf)+import Text.Read (readMaybe)+import WindowChecks (windowChecks)+import "nano-ui-sdl" NanoUI.Backend.Sdl (SdlEnv, syncDisplay, withSdlBench)+import "nano-ui-sdl" NanoUI.Sdl.Internal.Window (sdlRenderer, sdlRendererName)++foreign import ccall unsafe "SDL_ReadSurfacePixel"+ readPixel :: Ptr () -> CInt -> CInt -> Ptr Word8 -> Ptr Word8 -> Ptr Word8 -> Ptr Word8 -> IO CBool+foreign import ccall unsafe "SDL_DestroySurface" freeSurface :: Ptr () -> IO ()+foreign import capi unsafe "SDL3/SDL.h value SDL_PIXELFORMAT_RGBA32" rgba32 :: CUInt+foreign import capi unsafe "SDL3/SDL.h SDL_CreateSurfaceFrom"+ surfaceFrom :: CInt -> CInt -> CUInt -> Ptr Word8 -> CInt -> IO (Ptr ())+foreign import capi unsafe "SDL3/SDL.h SDL_FillSurfaceRect" fillSurface :: Ptr () -> Ptr () -> CUInt -> IO CBool+foreign import ccall unsafe "nano_ui_text_atlas_create" newAtlas :: Ptr SDL_Renderer -> IO (Ptr ())+foreign import ccall unsafe "nano_ui_text_atlas_destroy" freeAtlas :: Ptr () -> IO ()+foreign import ccall unsafe "nano_ui_text_atlas_reset" resetAtlas :: Ptr () -> IO ()+foreign import ccall unsafe "nano_ui_text_atlas_insert_surface"+ insertAtlas :: Ptr () -> Ptr () -> Ptr CFloat -> IO CBool++-- A padded pitch deliberately differs from both the glyph width and atlas pitch.+withGlyphSurface :: (Ptr () -> IO a) -> IO a+withGlyphSurface action = allocaBytes 64 $ \pixels ->+ bracket (surfaceFrom 3 2 rgba32 pixels 32) freeSurface $ \surface -> do+ unless (surface /= nullPtr) (fail "glyph surface creation failed")+ ok <- fillSurface surface nullPtr 0xffffffff+ unless (ok /= 0) (fail "glyph surface fill failed")+ action surface++-- | Insert a surface into the atlas: its page and pixel bounds, read back+-- from the UVs it returns, or 'Nothing' when no page has room.+insertInto :: Ptr () -> Ptr () -> IO (Maybe (CInt, [CFloat]))+insertInto atlas surface =+ allocaArray 4 $ \uv -> do+ ok <- insertAtlas atlas surface uv+ if ok /= 0+ then do+ [u0, v0, u1, v1] <- peekArray 4 uv+ let page = floor u0+ px a = a * 2048+ pure (Just (page, [px (u0 - fromIntegral page), px v0, px (u1 - u0), px (v1 - v0)]))+ else pure Nothing++atlasChecks :: SdlEnv -> (Ptr () -> DrawData -> IO ()) -> IO ()+atlasChecks env draw = withGlyphSurface $ \surface ->+ bracket (newAtlas (sdlRenderer env)) freeAtlas $ \atlas -> do+ unless (atlas /= nullPtr) (fail "atlas creation failed")+ let firstGlyph name =+ insertInto atlas surface >>= \r -> unless (r == Just (0, [5, 1, 3, 2])) (fail (name ++ ": " ++ show r))+ sampleOn page name x y expected = do+ draw atlas =<< texturedTriangle (glyphPageTextureId page) [(24, x / 2048), (28, y / 2048)]+ expectPixel env name expected+ sample = sampleOn 0+ fill = insertInto atlas surface >>= \case+ Just (0, _) -> fill+ other -> pure other+ firstGlyph "unexpected glyph bounds"+ sample "white patch" 0.5 0.5 (255, 0, 0)+ sample "glyph with padded source pitch" 6.5 2.5 (255, 0, 0)+ sample "transparent glyph padding" 8.5 2.5 (0, 0, 0)+ -- A full page opens the next one rather than failing. Draw page 0 then the+ -- still-dirty page 1 in one pass so a mid-pass flush cannot corrupt page 0.+ fill >>= \case+ Just (1, [x, y, _, _]) -> do+ let tri x0 y0 u v =+ [ (x0, y0, u, v), (x0 + 30, y0, u, v), (x0, y0 + 30, u, v) ]+ pts =+ tri 60 10 (0.5 / 2048) (0.5 / 2048)+ ++ tri 10 10 (102.5 / 2048) (2.5 / 2048)+ ++ tri 110 10 ((realToFrac x + 1.5) / 2048) ((realToFrac y + 0.5) / 2048)+ n = length pts+ vertices <- mallocForeignPtrBytes (32 * n)+ indices <- mallocForeignPtrBytes (4 * n)+ withForeignPtr vertices $ \p ->+ pokeArray (castPtr p) [CFloat v | (px, py, u, v') <- pts, v <- [px, py, 1, 0, 0, 1, u, v']]+ withForeignPtr indices $ \p -> pokeArray (castPtr p) [0 .. fromIntegral n - 1 :: CInt]+ let cmds =+ U.fromList+ [ DrawCmd 50 0 50 50 (glyphPageTextureId 0) 0 3 LayerContent 0+ , DrawCmd 0 0 50 50 (glyphPageTextureId 0) 3 3 LayerContent 0+ , DrawCmd 100 0 50 50 (glyphPageTextureId 1) 6 3 LayerContent 0+ ]+ multi = DrawData vertices n indices n cmds (primArrayFromList [0, 0, 3, 3, 3]) colorBlack emptyShaderCalls emptyUniformBytes emptyEffectSpans+ draw atlas multi+ expectPixel env "page 0 before dirty page 1 in same pass" (255, 0, 0)+ pixel env 120 20 >>= \actual -> unless (actual == (255, 0, 0)) (fail ("dirty page 1 in same pass: " ++ show actual))+ next -> fail ("a full page did not open another: " ++ show next)+ resetAtlas atlas+ sample "white patch after reset" 0.5 0.5 (255, 0, 0)+ sample "old glyph cleared by reset" 6.5 2.5 (0, 0, 0)+ firstGlyph "a reset atlas did not start on page 0"++-- | Images reach the atlas texture however they change: rewritten in place,+-- added beside others, or added by growing the atlas. Each is sampled at its+-- centre through white vertices.+imageChecks :: SdlEnv -> Context -> ImageAtlas -> (DrawData -> IO ()) -> IO ()+imageChecks env ctx images draw = do+ let register tid w h px = registerImage ctx (ImageId tid) w h px >>= (`unless` fail "image registration failed")+ solid tid w h (r, g, b) = register tid w h (BS.concat (replicate (w * h) (BS.pack [r, g, b, 255])))+ sample name tid expected = do+ syncImageAtlas (sdlRenderer env) images ctx+ (u0, v0, u1, v1) <- lookupImageUv ctx (ImageId tid) >>= maybe (fail "missing image") pure+ let white = [(o, 1) | o <- [8, 12, 16, 20]]+ draw =<< texturedTriangle atlasTextureId (white ++ [(24, (u0 + u1) / 2), (28, (v0 + v1) / 2)])+ expectPixel env name expected+ solid 1 4 4 (255, 0, 0)+ solid 2 4 4 (0, 255, 0)+ sample "first upload" 1 (255, 0, 0)+ solid 1 4 4 (0, 0, 255)+ sample "written in place" 1 (0, 0, 255)+ sample "neighbour kept" 2 (0, 255, 0)+ solid 3 4 4 (255, 255, 0)+ sample "added beside" 3 (255, 255, 0)+ solid 4 300 2 (0, 255, 255)+ sample "added by growing" 4 (0, 255, 255)+ sample "kept across growth" 1 (0, 0, 255)++-- | An atlas texture SDL will not make (here, for want of a renderer) is+-- asked for once per atlas generation: the second sync makes no SDL call,+-- so SDL's error, cleared between them, stays clear.+imageFailureChecks :: IO ()+imageFailureChecks = do+ ctx <- newPixelContext+ registerImage ctx (ImageId 1) 2 2 (BS.replicate 16 255) >>= (`unless` fail "image registration failed")+ bracket newImageAtlas destroyImageAtlas $ \atlas -> do+ syncImageAtlas nullPtr atlas ctx+ first <- sdlErrorText+ void clearError+ syncImageAtlas nullPtr atlas ctx+ again <- sdlErrorText+ unless (not (null first) && null again) $+ fail ("failed image atlas upload retried: " ++ show (first, again))++-- | At a fractional scale the pass clips to the device pixels the damage+-- was snapped to, and draws geometry at that scale: a red quad over layout+-- units 7 to 13 of damage at scale 1.5 fills device pixels 10 to 19 only.+fractionalScaleChecks :: SdlEnv -> (Float -> DrawData -> Damage -> IO ()) -> IO ()+fractionalScaleChecks env draw = do+ let scale = 1.5+ quad x0 y0 x1 y1 = [(x0, y0), (x1, y0), (x0, y1), (x1, y0), (x1, y1), (x0, y1)]+ row name xs expected = do+ got <- mapM (\x -> pixel env x 15) xs+ unless (got == expected) (fail (name ++ ": " ++ show (zip xs got)))+ red = (255, 0, 0)+ black = (0, 0, 0)+ empty <- geometry []+ draw 1 empty DamageFull+ big <- geometry (quad 0 0 60 60)+ draw scale big (snapDamage scale (DamageClip (Rect 7 7 6 6)))+ row "damage clip at scale 1.5" [9, 10, 19, 20] [black, red, red, black]+ small <- geometry (quad 0 0 20 20)+ draw scale small DamageFull+ row "geometry at scale 1.5" [29, 30] [red, black]++-- | A translucent canvas line as SDL draws it has even alpha across its+-- round caps and join: a cap drawn over the line's end would darken it.+pathChecks :: SdlEnv -> Context -> (DrawData -> IO ()) -> IO ()+pathChecks env ctx draw = do+ (resp, dd) <-+ warmupDraw ctx (withInput 400 300) . column . canvas (fixedWH 200 100) $ \(Rect x y _ _) ->+ drawStrokePathWith+ (P.stroke 20) {P.strokeCap = P.RoundCap, P.strokeJoin = P.RoundJoin}+ (P.polyline [V2 (x + 100) (y + 30), V2 (x + 150) (y + 30), V2 (x + 150) (y + 80)])+ (P.Solid (colorRGBA 255 255 255 128))+ draw dd+ let at dx dy = let Rect x y _ _ = respRect resp in pixel env (floor (x + dx)) (floor (y + dy))+ backdrop <- at 80 5+ line <- mapM (uncurry at) [(125, 30), (103, 30), (93, 30), (152, 28), (156, 24), (150, 88)]+ case nub line of+ [one] | one /= backdrop -> pure ()+ _ -> fail ("translucent line, caps and join: " ++ show line)++atlasBench :: SdlEnv -> IO ()+atlasBench env = withGlyphSurface $ \surface ->+ bracket (newAtlas (sdlRenderer env)) freeAtlas $ \atlas -> allocaArray 4 $ \uv -> do+ unless (atlas /= nullPtr) (fail "atlas creation failed")+ benchmark "atlas-reset-1024-glyphs" 5 100 . (resetAtlas atlas >>) . replicateM_ 1024 $+ insertAtlas atlas surface uv >>= \ok -> unless (ok /= 0) (fail "benchmark atlas insertion failed")++-- | Run an action @warm@ times, then @n@ times, and print the mean time and+-- allocation per run.+benchmark :: String -> Int -> Int -> IO () -> IO ()+benchmark name warm n action = do+ replicateM_ warm action+ performGC+ bytes0 <- getAllocationCounter+ t0 <- getMonotonicTimeNSec+ replicateM_ n action+ t1 <- getMonotonicTimeNSec+ bytes1 <- getAllocationCounter+ let perRun :: Integral a => a -> Double+ perRun x = fromIntegral x / fromIntegral n+ printf "%s: %.6f ms/frame | %.1f B/frame\n" name (perRun (t1 - t0) / 1e6) (perRun (bytes0 - bytes1))++-- | Every cursor kind maps to a system cursor SDL declares (SDL 3.2 does not+-- check), each kind SDL has a cursor for (its own fallback, bar the default+-- and hidden ones) gets a distinct one, and showing every kind twice creates+-- each system cursor once, NULL ones (this driver's) included.+cursorChecks :: IO ()+cursorChecks = do+ let kinds = [minBound .. maxBound] :: [UiCursorKind]+ wanted = mapMaybe sdlSystemCursor kinds+ own = [sdlSystemCursor k | k <- kinds, cursorFallback k == k, k /= UiCursorDefault, k /= UiCursorHidden]+ unless (all (\c -> c >= M.SDL_SYSTEM_CURSOR_DEFAULT && c < M.SDL_SYSTEM_CURSOR_COUNT) wanted) $+ fail ("cursor kinds ask for undeclared SDL cursors: " ++ show wanted)+ unless (all isJust own && length (nub own) == length own) $+ fail ("cursor kinds do not show their own SDL cursors: " ++ show own)+ bracket initCursors destroyCursors $ \cursors -> do+ mapM_ (showCursorKind cursors) (kinds ++ kinds)+ created <- map fst <$> readIORef (scSystem cursors)+ unless (length created == length (nub wanted) && all (`elem` created) wanted) $+ fail ("system cursors created more than once or not at all: " ++ show created)+ -- The hidden kind hides the pointer, and any other shows it again.+ showCursorKind cursors UiCursorHidden+ hidden <- not <$> cursorVisibleSafe+ showCursorKind cursors UiCursorPointer+ shownAgain <- cursorVisibleSafe+ unless (hidden && shownAgain) $+ fail ("the hidden cursor kind does not hide the pointer and show it again: " ++ show (hidden, shownAgain))++-- The public draw format is SDL_Vertex-compatible: xy, rgba, uv floats.+geometry :: [(Float, Float)] -> IO DrawData+geometry points = do+ let n = length points+ vertices <- mallocForeignPtrBytes (32 * n)+ indices <- mallocForeignPtrBytes (4 * n)+ withForeignPtr vertices $ \p -> pokeArray (castPtr p) [CFloat v | (x, y) <- points, v <- [x, y, 1, 0, 0, 1, 0, 0]]+ withForeignPtr indices $ \p -> pokeArray (castPtr p) [0 .. fromIntegral n - 1 :: CInt]+ let cmds = U.singleton (DrawCmd 0 0 800 600 0 0 (fromIntegral n) LayerContent 0)+ pure (DrawData vertices n indices n cmds (primArrayFromList [0, 0, 1, 1, 1]) colorBlack emptyShaderCalls emptyUniformBytes emptyEffectSpans)++-- | A triangle covering pixel (20, 20) that samples @texture@, with floats+-- written at each vertex's byte offsets: colour at 8 to 20, UV at 24 and 28.+texturedTriangle :: Int -> [(Int, Float)] -> IO DrawData+texturedTriangle texture writes = do+ dd <- geometry [(10, 10), (50, 10), (10, 50)]+ withForeignPtr (drawVertices dd) $ \p ->+ forM_ [0 .. 2] $ \i -> forM_ writes $ \(o, v) -> pokeByteOff p (i * 32 + o) (CFloat v)+ pure dd {drawCommands = U.map (\cmd -> cmd {cmdTextureId = texture}) (drawCommands dd)}++pixel :: SdlEnv -> Int -> Int -> IO (Word8, Word8, Word8)+pixel env x y = do+ let readBack = castPtr <$> renderReadPixels (sdlRenderer env) (PtrConst.unsafeFromPtr nullPtr)+ bracket readBack freeSurface $ \surface -> do+ unless (surface /= nullPtr) (fail "SDL readback failed")+ allocaBytes 4 $ \p -> do+ ok <- readPixel surface (fromIntegral x) (fromIntegral y) p (p `plusPtr` 1) (p `plusPtr` 2) (p `plusPtr` 3)+ unless (ok /= 0) (fail "SDL pixel read failed")+ (,,) <$> peekByteOff p 0 <*> peekByteOff p 1 <*> peekByteOff p 2++-- | Fail unless pixel (20, 20) has the expected colour.+expectPixel :: SdlEnv -> String -> (Word8, Word8, Word8) -> IO ()+expectPixel env name expected =+ pixel env 20 20 >>= \actual -> unless (actual == expected) (fail (name ++ ": " ++ show actual))++-- | A display sync passes SDL's appearance to the context, switching the+-- theme of a context that follows the system. The context starts with the+-- other appearance (light when SDL reports none, as the dummy driver does),+-- so a sync that did not report would leave the appearance and theme stale.+systemThemeChecks :: SdlEnv -> Context -> IO ()+systemThemeChecks env ctx = do+ want <-+ getSystemTheme <&> \case+ Video.SDL_SYSTEM_THEME_LIGHT -> Just AppearanceLight+ Video.SDL_SYSTEM_THEME_DARK -> Just AppearanceDark+ _ -> Nothing+ setSystemAppearance ctx (Just (if want == Just AppearanceLight then AppearanceDark else AppearanceLight))+ followSystemThemeIO ctx (lightDark defaultLightTheme defaultTheme)+ (synced, _) <- syncDisplay ctx env emptyInput+ got <- getSystemAppearance synced+ theme <- getThemeIO synced+ unless (got == want) (fail ("system appearance " ++ show got ++ ", SDL reports " ++ show want))+ unless (theme == lightDark defaultLightTheme defaultTheme want) $+ fail "a context following the system kept the stale theme after the sync"++shaderChecks :: SdlEnv -> Context -> (DrawData -> IO ()) -> IO ()+shaderChecks env ctx draw = do+ caps <- getShaderCapabilities ctx+ let mgParams =+ MeshGradientParams+ { mgTopLeft = colorRGBA 240 40 40 255+ , mgTopRight = colorRGBA 40 220 40 255+ , mgBottomLeft = colorRGBA 40 60 240 255+ , mgBottomRight = colorRGBA 240 220 40 255+ }+ fallbackCol = colorRGBA 12 90 180 255+ cfg =+ defaultShaderConfig+ { scLayout = fixedWH 100 80+ , scFallback = fallbackCol+ }+ if not (capSurfaceShaders caps)+ then do+ (_, dd) <- warmupDraw ctx (withInput 800 600) (columnWith tight (shaderConfigured cfg meshGradient4 mgParams))+ draw dd+ (r, g, b) <- pixel env 50 40+ let near c1 c2 = abs (fromIntegral c1 - fromIntegral c2 :: Int) <= 2+ unless (near r (colorR fallbackCol) && near g (colorG fallbackCol) && near b (colorB fallbackCol)) $+ fail ("software shader fallback mismatch: got " ++ show (r, g, b))+ else do+ -- Verify SDL 3.4 GPU SPIR-V/MSL execution matches CPU reference evaluator.+ let evalCpu :: Shader k u -> u -> Float -> Float -> Color+ evalCpu sh u px py = case shaderCpuEval sh of+ Nothing -> error "missing CPU evaluator"+ Just f ->+ f+ u+ CpuFragCtx+ { cfcUv = V2 (px / 100) (py / 80)+ , cfcPos = V2 px py+ , cfcSize = V2 100 80+ , cfcScale = 1.0+ , cfcColor = colorWhite+ , cfcCornerRadius = 0.0+ }+ (const colorBlack)+ near3 (r1, g1, b1) col =+ let a = fromIntegral (colorA col) :: Int+ blend ch = (fromIntegral ch * a + 127) `div` 255+ d x y = abs (fromIntegral x - y)+ in d r1 (blend (colorR col)) <= 4 && d g1 (blend (colorG col)) <= 4 && d b1 (blend (colorB col)) <= 4+ (_, dd1) <- warmupDraw ctx (withInput 800 600) (columnWith tight (shaderBox (fixedWH 100 80) meshGradient4 mgParams))+ draw dd1+ forM_ [(10, 10), (89, 10), (10, 69), (89, 69), (50, 40)] $ \(x, y) -> do+ gpuPx <- pixel env x y+ let cpuPx = evalCpu meshGradient4 mgParams (fromIntegral x + 0.5) (fromIntegral y + 0.5)+ unless (near3 gpuPx cpuPx) $+ fail ("meshGradient4 GPU vs CPU mismatch at " ++ show (x, y) ++ ": gpu=" ++ show gpuPx ++ " cpu=" ++ show (colorR cpuPx, colorG cpuPx, colorB cpuPx))++ let sdfParams =+ SdfBoxParams+ { sbFill = colorRGBA 30 160 220 255+ , sbBorder = colorRGBA 250 180 40 255+ , sbBorderWidth = 4+ , sbRadius = 16+ }+ (_, dd2) <- warmupDraw ctx (withInput 800 600) (columnWith tight (shaderBox (fixedWH 100 80) sdfRoundedBox sdfParams))+ draw dd2+ -- Center is fill, top-center at y=2 is border, corner (1, 1) is outside rounded rect (black clear).+ forM_ [(50, 40), (50, 2), (1, 1)] $ \(x, y) -> do+ gpuPx <- pixel env x y+ let cpuPx = evalCpu sdfRoundedBox sdfParams (fromIntegral x + 0.5) (fromIntegral y + 0.5)+ unless (near3 gpuPx cpuPx) $+ fail ("sdfRoundedBox GPU vs CPU mismatch at " ++ show (x, y) ++ ": gpu=" ++ show gpuPx ++ " cpu=" ++ show (colorR cpuPx, colorG cpuPx, colorB cpuPx))++ -- Tier 2 subtree effects (offscreen targets, fused ColorEffect, 2-pass gaussianBlur, nested effects).+ when (capNodeEffects caps) $ do+ let srcCol = colorRGBA 200 40 20 255+ evalEffectCpu :: Shader k u -> u -> Color+ evalEffectCpu sh u = case shaderCpuEval sh of+ Nothing -> error "missing CPU evaluator"+ Just f ->+ f+ u+ CpuFragCtx+ { cfcUv = V2 0.5 0.5+ , cfcPos = V2 40 30+ , cfcSize = V2 80 60+ , cfcScale = 1.0+ , cfcColor = colorWhite+ , cfcCornerRadius = 0.0+ }+ (const srcCol)++ -- 1. Single-pass ColorEffect (grayscale)+ (_, ddGray) <- warmupDraw ctx (withInput 800 600) $+ columnWith tight (withShader grayscale 1.0 (box (fixedWH 80 60) srcCol))+ draw ddGray+ grayPx <- pixel env 40 30+ let grayCpu = evalEffectCpu grayscale 1.0+ unless (near3 grayPx grayCpu) $+ fail ("Tier 2 grayscale GPU vs CPU mismatch: gpu=" ++ show grayPx ++ " cpu=" ++ show (colorR grayCpu, colorG grayCpu, colorB grayCpu))++ -- 2. Fused 1-pass composeColor grayscale tint+ let fused = composeColor grayscale tint+ fusedU = (1.0, TintParams (colorRGBA 0 80 240 255) 0.5)+ (_, ddFused) <- warmupDraw ctx (withInput 800 600) $+ columnWith tight (withShader fused fusedU (box (fixedWH 80 60) srcCol))+ draw ddFused+ fusedPx <- pixel env 40 30+ let fusedCpu = evalEffectCpu fused fusedU+ unless (near3 fusedPx fusedCpu) $+ fail ("Tier 2 fused composeColor GPU vs CPU mismatch: gpu=" ++ show fusedPx ++ " cpu=" ++ show (colorR fusedCpu, colorG fusedCpu, colorB fusedCpu))++ -- 3. Separable 2-pass gaussianBlur with bleed margin halo outside the box+ (_, ddBlur) <- warmupDraw ctx (withInput 800 600) $+ columnWith (padAll 30 . tight) $+ withShader gaussianBlur 4.0 (box (fixedWH 40 40) (colorRGBA 255 0 0 255))+ draw ddBlur+ (cr, cg, cb) <- pixel env 50 50+ (hr, hg, hb) <- pixel env 27 50+ farPx <- pixel env 5 50+ unless (cr > 200 && cg < 10 && cb < 10) $+ fail ("Tier 2 gaussianBlur center unexpected: " ++ show (cr, cg, cb))+ unless (hr > 15 && hr < 245 && hg < 10 && hb < 10) $+ fail ("Tier 2 gaussianBlur bleed halo missing at (27,50): " ++ show (hr, hg, hb))+ unless (farPx == (0, 0, 0)) $+ fail ("Tier 2 gaussianBlur leaked past margin at (5,50): " ++ show farPx)++ -- 4. Translucent child under Tier 2 effects verifies premultiplied-alpha+ -- offscreen targets do not double-darken on composite.+ let halfCol = colorRGBA 200 100 50 128+ (_, ddAlpha) <- warmupDraw ctx (withInput 800 600) $+ columnWith tight (withShader groupOpacity 1.0 (box (fixedWH 80 60) halfCol))+ draw ddAlpha+ alphaPx <- pixel env 40 30+ unless (near3 alphaPx halfCol) $+ fail ("Tier 2 translucent groupOpacity 1.0 double-darkened: gpu=" ++ show alphaPx ++ " expected=" ++ show halfCol)++ -- 5. Nested subtree effects: groupOpacity 0.5 around grayscale 1.0+ (_, ddNest) <- warmupDraw ctx (withInput 800 600) $+ columnWith tight $+ withShader groupOpacity 0.5 $+ withShader grayscale 1.0 (box (fixedWH 80 60) srcCol)+ draw ddNest+ nestPx <- pixel env 40 30+ let halfGray = colorRGBA (colorR grayCpu) (colorG grayCpu) (colorB grayCpu) 128+ unless (near3 nestPx halfGray) $+ fail ("Tier 2 nested groupOpacity(grayscale) mismatch: gpu=" ++ show nestPx ++ " expected~" ++ show (colorR halfGray `div` 2))++ -- 6. Plain batches before/after fresh offscreen target allocation and+ -- Tier 1 shader draw share one pass without clobbering GL state or EBO.+ -- The clipped first box flushes and activates the GL plain pass before+ -- the second box is queued and before withShader allocates a new target.+ let redCol = colorRGBA 220 30 30 255+ blueCol = colorRGBA 30 60 220 255+ greenCol = colorRGBA 30 200 60 255+ (_, ddMixed) <- warmupDraw ctx (withInput 800 600) $+ columnWith (tight . gap 0) $ do+ clipBox (fixedWH 80 40) (box (fixedWH 80 40) redCol)+ box (fixedWH 80 40) blueCol+ withShader grayscale 1.0 (box (fixedWH 140 140) srcCol)+ shaderBox (fixedWH 80 40) meshGradient4 mgParams+ box (fixedWH 80 40) greenCol+ draw ddMixed+ preRed <- pixel env 40 20+ preBlue <- pixel env 40 60+ midGray <- pixel env 70 150+ postGreen <- pixel env 40 280+ unless (near3 preRed redCol && near3 preBlue blueCol && near3 midGray grayCpu && near3 postGreen greenCol) $+ fail ("Mixed plain + fresh Tier 2 target + Tier 1 shader mismatch: " ++ show (preRed, preBlue, midGray, postGreen))++ putStrLn (" (verified live GPU Tier 1 + Tier 2 shaders on SDL renderer: " ++ show (sdlRendererName env) ++ ")")++main :: IO ()+main = do+ hSetBuffering stdout LineBuffering+ hSetBuffering stderr LineBuffering+ args <- getArgs+ iterations <- max 1 . fromMaybe 500 . (>>= readMaybe) <$> lookupEnv "NANO_RENDER_ITERATIONS"+ let bench = args == ["--bench"] || args == ["--atlas-bench"]+ gpuShadersOnly = args == ["--gpu-shaders"]+ native = args == ["--native"] || gpuShadersOnly+ unless (bench || native) $ do+ setEnv "SDL_VIDEO_DRIVER" "dummy"+ setEnv "SDL_RENDER_DRIVER" "software"+ unless (bench || gpuShadersOnly) inputChecks+ ctx <- newPixelContext+ -- These checks read pixels over a black clear: a black page makes the+ -- frame's clear black.+ getThemeIO ctx >>= setThemeIO ctx . pageColor colorBlack+ withSdlBench ctx $ \_ env -> bracket newImageAtlas destroyImageAtlas $ \images ->+ bracket (newRenderBatch (sdlRenderer env)) destroyRenderBatch $ \batch -> do+ let drawScaled scale glyphs dd dmg =+ renderDrawDataPass batch (sdlRenderer env) scale dd images glyphs dmg >> flushRenderBatch batch+ drawWithGlyph = drawScaled 1+ draw = drawWithGlyph nullPtr+ damage = DamageClip (Rect 15 15 10 10)+ step name act =+ (act >> putStrLn ("SDL " ++ name ++ ": ok")) `catch` \(e :: SomeException) -> do+ hPutStrLn stderr ("SDL " ++ name ++ ": FAIL: " ++ displayException e)+ hFlush stderr+ hFlush stdout+ throwIO e+ case args of+ ["--gpu-shaders"] -> do+ step "glyph upload, padding and reset readback" $+ atlasChecks env (\glyphs dd -> drawWithGlyph glyphs dd DamageFull)+ step "surface shader GPU/fallback readback" (shaderChecks env ctx (`draw` DamageFull))+ ["--atlas-bench"] -> atlasBench env+ ["--bench"] -> do+ let quad x y = [(x, y), (x + 40, y), (x + 40, y + 40), (x + 40, y + 40), (x, y + 40), (x, y)]+ offscreen = concat (replicate 4096 (quad 100 100))+ sparse <- geometry offscreen+ mixed <- geometry (offscreen ++ quad 10 10)+ dense <- geometry (concat (replicate 256 (quad 10 10)))+ forM_+ [ ("sparse-partial", sparse, damage), ("mixed-partial", mixed, damage), ("dense-partial", dense, damage)+ , ("dense-full", dense, DamageFull)+ ]+ $ \(name, dd, dmg) ->+ benchmark name 30 iterations (draw dd dmg >> void (renderPresentSafe (sdlRenderer env)))+ _ -> do+ -- A six-index group can hold independent triangles, and a command can+ -- end in three indices. Neither may be culled as an offscreen quad.+ step "partial-damage triangle readback" $ do+ let visible = [(10, 10), (50, 10), (10, 50)]+ outside = [(100, 100), (120, 100), (100, 120)]+ empty <- geometry []+ forM_ [("independent triangles", [outside]), ("triangle tail", [outside, outside])] $ \(name, before) -> do+ let points = concat before ++ visible+ dd <- geometry points+ draw empty DamageFull+ draw dd damage+ inside <- pixel env 20 20+ untouched <- pixel env 12 12+ unless (inside == (255, 0, 0) && untouched == (0, 0, 0)) $+ fail (name ++ ": clipped geometry lost or escaped damage: " ++ show (inside, untouched))+ step "glyph upload, padding and reset readback" $+ atlasChecks env (\glyphs dd -> drawWithGlyph glyphs dd DamageFull)+ step "image atlas upload readback" (imageChecks env ctx images (`draw` DamageFull))+ step "failed image atlas upload reported once" imageFailureChecks+ step "fractional-scale clip and geometry readback" (fractionalScaleChecks env (\s -> drawScaled s nullPtr))+ step "canvas line caps and joins readback" (pathChecks env ctx (`draw` DamageFull))+ step "surface shader GPU/fallback readback" (shaderChecks env ctx (`draw` DamageFull))+ step "cursor mapping and creation" cursorChecks+ step "native events and the system theme" (queueChecks >> systemThemeChecks env ctx)+ unless (bench || gpuShadersOnly) $ do+ windowChecks (if native then "native drivers" else "dummy video, software renderer") False+ -- With a display, repeat on the GPU renderers, which give a transparent+ -- window custom blend modes: OpenGL blends alpha with the colour's+ -- operation, and OpenGL ES keeps the larger alpha. Missing renderers are+ -- skipped.+ display <- lookupEnv "DISPLAY"+ when (isJust display && not native) $+ forM_ ["opengl", "opengles2"] $ \renderer -> do+ setEnv "SDL_VIDEO_DRIVER" "x11"+ setEnv "SDL_RENDER_DRIVER" renderer+ try (windowChecks ("x11, " ++ renderer) True) >>= \case+ Left (err :: IOException)+ | any (`isInfixOf` show err) ["SDL_Init", "SDL_CreateWindowAndRenderer"] ->+ putStrLn ("SDL window checks on " ++ renderer ++ " skipped: " ++ show err)+ | otherwise -> throwIO err+ Right () -> pure ()
+ test/WindowChecks.hs view
@@ -0,0 +1,486 @@+{-# LANGUAGE PackageImports #-}++-- | Window options as SDL reports them, screenshots from retained and+-- continuous sessions, transparent-window alpha, and the session's opening+-- frames, resize-watch frames and render device resets.+module WindowChecks (windowChecks) where++import Control.Concurrent (forkIO, threadDelay)+import Control.Exception (IOException, onException, try)+import Control.Monad (replicateM_, unless, void, when)+import Data.Bits (zeroBits, (.&.))+import Data.ByteString qualified as BS+import Data.Foldable (for_, traverse_)+import Data.IORef (IORef, atomicModifyIORef', modifyIORef', newIORef, readIORef, writeIORef)+import Data.List (isInfixOf, nub)+import Data.Maybe (fromJust, isNothing)+import Data.Primitive.SmallArray (smallArrayFromList)+import Data.String (fromString)+import Foreign.C.String (peekCString)+import Foreign.C.Types (CBool (..))+import Foreign.Marshal.Alloc (alloca)+import Foreign.Ptr (castPtr)+import Foreign.Storable (Storable, peek, poke)+import GHC.Clock (getMonotonicTime)+import NanoUI+import NanoUI.Backend (colorToWord32, emptyInput, runNanoUI, withTheme)+import NanoUI.Emit (emit)+import NanoUI.Sdl.Internal.DialogState qualified as Dialog+import NanoUI.Testing (Context, isDirty, newPixelContext)+import NanoUI.Testing.Assert (require, requireEq)+import NanoUI.Widgets.Custom (DrawOp (FillRect), drawing, drawingVersioned)+import SDL3.Sys.Blendmode qualified as Blend+import SDL3.Sys.Bindgen.Events+ ( SDL_MouseButtonEvent (SDL_MouseButtonEvent), SDL_QuitEvent (SDL_QuitEvent), SDL_RenderEvent (SDL_RenderEvent)+ , SDL_WindowEvent (SDL_WindowEvent)+ )+import SDL3.Sys.Bindgen.Events qualified as Events+import SDL3.Sys.Bindgen.Mouse (sDL_BUTTON_MIDDLE, sDL_BUTTON_X1)+import SDL3.Sys.Bindgen.Runtime.PtrConst qualified as PtrConst+import SDL3.Sys.Events (pushEventSafe)+import SDL3.Sys.Render (setRenderVSyncSafe)+import SDL3.Sys.Video+ (getWindowFlags, getWindowMaximumSize, getWindowMinimumSize, getWindowOpacity, getWindowSize, getWindowTitle)+import SDL3.Sys.Video qualified as SDL+import System.Environment (lookupEnv)+import System.Timeout (timeout)+import "nano-ui-sdl" NanoUI.Backend.Sdl+import "nano-ui-sdl" NanoUI.Sdl.Internal.Window (sdlRenderer, sdlScaleRef, sdlUiScaleRef, sdlWindow, sdlTransparent)++-- | Run all checks. @gpu@ means a real display with a GPU renderer, which+-- adds checks the dummy driver cannot support: icon, opacity, position, and+-- custom blend modes for transparency.+windowChecks :: String -> Bool -> IO ()+windowChecks drivers gpu = do+ mapM_ (optionChecks gpu) [1, 2]+ mapM_ screenshotChecks [False, True]+ transparencyChecks gpu+ reducerEnvironmentCheck+ openingFramesCheck+ openingCloseCheck+ childWindowCheck+ childScaleCheck+ openingQuitChildCheck+ fakeVsyncCheck+ resizeFailureCheck+ resizeChecks+ uiScaleNaNCheck+ dialogStateChecks+ putStrLn ("SDL window options, screenshots and transparency (" ++ drivers ++ "): ok")++-- | Small hidden window, bundled font, scale 1 (one layout unit per pixel).+options :: SdlOptions+options =+ defaultSdlOptions+ { sdlWindowSettings = defaultWindowSettings {wsMode = Hidden, wsSize = Size 200 100}+ , sdlAppFont = DefaultFont, sdlAppMonoFont = DefaultFont, sdlAppVsync = False, sdlAppUiScale = 1+ }++withWindow :: (WindowSettings -> WindowSettings) -> SdlOptions+withWindow f = options {sdlWindowSettings = f (sdlWindowSettings options)}++-- | A session with page and window colour @backdrop@.+session :: SdlOptions -> Color -> (Context -> SdlEnv -> IO a) -> IO a+session opts backdrop act = do+ ctx <- newPixelContext >>= (`withTheme` pageColor backdrop (windowColor backdrop defaultTheme))+ withSdl opts ctx act++-- | Draw one frame; @full@ forces a full repaint. Returns the view's result.+frame :: Context -> SdlEnv -> Bool -> NanoUI a -> IO a+frame ctx env full ui = do+ (ctx', inp) <- syncDisplay ctx env emptyInput {inputWindowSize = Size 200 100}+ out <- newIORef Nothing+ void (sdlDrawFrame ctx' (ui >>= liftIO . writeIORef out . Just) env inp full)+ maybe (fail "the view did not run") pure =<< readIORef out++-- | Draw a frame that requests a screenshot; fail unless exactly one arrives.+shoot :: String -> Context -> SdlEnv -> Bool -> NanoUI () -> IO Screenshot+shoot name ctx env full ui = do+ shots <- newIORef []+ frame ctx env full (requestScreenshot (\s -> modifyIORef' shots (s :)) >> ui)+ readIORef shots >>= \case+ [Just img] -> pure img+ [Nothing] -> fail (name ++ ": the screenshot could not be read back")+ other -> fail (name ++ ": one screenshot wanted, got " ++ show (length other))+++-- A reducer view reaches its own session without being handed it, on every+-- pass including the follow-up frame after reducing a message. Once the+-- session closes, no view can reach it, and a dialog asked for outside one+-- fails instead of touching a window.+reducerEnvironmentCheck :: IO ()+reducerEnvironmentCheck = do+ observed <- newIORef []+ completed <- timeout 10000000 $+ runSdlAppReduce options (+) (0 :: Int) $ \model -> do+ live <- askSdlEnv+ title <- liftIO (traverse windowTitle live)+ liftIO (modifyIORef' observed ((model, title) :))+ if model == 0 then emit 1 else quit+ require "reducer terminates" (completed == Just ())+ seen <- readIORef observed+ require "reducer sees both models and its session's native title"+ (any ((== 0) . fst) seen && any ((== 1) . fst) seen && all ((== Just "nano-ui") . snd) seen)+ ctx <- newPixelContext+ (closed, dialog) <- runNanoUI ctx emptyInput $+ (,) <$> askSdlEnv <*> (pollFileDialogUi =<< askOpenFileDialog defaultFileDialogOptions)+ require "a closed session is out of reach" (isNothing closed)+ requireEq "a dialog outside a session fails" FileDialogFailed dialog++windowTitle :: SdlEnv -> IO String+windowTitle env = getWindowTitle (sdlWindow env) >>= peekCString . castPtr . PtrConst.unsafeToPtr++-- | Put an event on SDL's queue, as the desktop would.+push :: Storable e => e -> IO ()+push ev = alloca $ \p -> do+ poke (castPtr p) ev+ pushEventSafe p >>= require "SDL takes the event"++-- | A mouse button going down at (30, 40).+pushPress :: Integral b => b -> IO ()+pushPress b =+ push (SDL_MouseButtonEvent Events.SDL_EVENT_MOUSE_BUTTON_DOWN 0 0 0 1 (fromIntegral b) (CBool 1) 1 0 30 40)++-- | Count the view's passes: the first is 1.+countPass :: IORef Int -> NanoUI Int+countPass ref = liftIO (atomicModifyIORef' ref (\n -> (n + 1, n + 1)))++-- | The opening frames are drawn before the loop starts. A press taken while+-- the first draws is seen by one frame, not replayed by the next; one taken+-- while the second draws is seen too, not dropped. After a render device+-- reset, which empties every texture, the next frame repaints in full with+-- the textures made again, text included. A wake a second after each pass+-- draws a frame should the loop wait for input that never comes.+openingFramesCheck :: IO ()+openingFramesCheck = do+ passes <- newIORef 0+ seen <- newIORef []+ shots <- newIORef []+ redrawn <- newIORef False+ runSdlApp options $ do+ wakeAfter 1+ n <- countPass passes+ inp <- askInput+ label "Text after a reset"+ let shot = requestScreenshot (\s -> modifyIORef' shots (s :))+ liftIO $ modifyIORef' seen ([b | b <- [MouseMiddle, MouseBack], pressedIn b inp] ++)+ when (n == 1) $ liftIO (pushPress sDL_BUTTON_MIDDLE)+ when (n == 2) $ do+ shot+ liftIO (pushPress sDL_BUTTON_X1 >> push (SDL_RenderEvent Events.SDL_EVENT_RENDER_DEVICE_RESET 0 0 0))+ when (n == 3) $ shot >> liftIO (writeIORef redrawn (inputWindowRedraw inp)) >> quit+ readIORef seen >>= requireEq "presses during the opening frames, each seen once" [MouseBack, MouseMiddle]+ readIORef redrawn >>= require "a device reset repaints the window"+ readIORef shots >>= \case+ [Just after, Just before] -> do+ require "text before the reset" (length (nub (pixelsOf before)) > 1)+ require "text drawn from the remade textures" (after == before)+ other -> fail ("two screenshots wanted, got " ++ show (length other))++-- | A close request taken during the opening frames closes the window, as+-- one in the loop does.+openingCloseCheck :: IO ()+openingCloseCheck = do+ firstAt <- newIORef Nothing+ lost <- newIORef False+ runSdlApp options $ do+ wakeAfter 1+ now <- liftIO getMonotonicTime+ liftIO (readIORef firstAt) >>= \case+ Nothing -> liftIO $ do+ writeIORef firstAt (Just now)+ push (SDL_QuitEvent Events.SDL_EVENT_QUIT 0 0)+ Just t0 -> when (now > t0 + 0.5) $ liftIO (writeIORef lost True) >> quit+ readIORef lost >>= require "a close request during the opening frames closes the window" . not++-- | A view's 'nativeWindow' opens a window with a view of its own, which+-- keeps getting frames from its timed wakes. A 'Var' it writes reaches the+-- first window's view, and its close request writes 'False', which closes+-- it and shows in the first window at once, though nothing else wakes it (a+-- watchdog wakes it after five seconds, so a regression fails rather than+-- hangs).+childWindowCheck :: IO ()+childWindowCheck = do+ open <- newVar True+ shared <- newVar (0 :: Int)+ passes <- newIORef 0+ childPasses <- newIORef 0+ closedAt <- newIORef Nothing+ noticedAt <- newIORef Nothing+ seen <- newIORef []+ runSdlApp options $ do+ n <- countPass passes+ when (n == 1) $ askWake >>= \wake -> liftIO (void (forkIO (threadDelay 5000000 >> wake)))+ v <- readVar shared+ liftIO (modifyIORef' seen (v :))+ nativeWindow open (sdlWindowSettings options) {wsTitle = "second"} $ do+ wakeAfter 0.02+ m <- countPass childPasses+ when (m == 1) (writeVar shared 7)+ sent <- liftIO (readIORef closedAt)+ when (m >= 4 && isNothing sent) $ askSdlEnv >>= \live -> liftIO $ for_ live $ \env -> do+ getMonotonicTime >>= writeIORef closedAt . Just+ wid <- SDL.getWindowID (sdlWindow env)+ push (SDL_WindowEvent Events.SDL_EVENT_WINDOW_CLOSE_REQUESTED 0 0 wid 0 0)+ stillOpen <- readVar open+ when (n > 1 && not stillOpen) $ liftIO (getMonotonicTime >>= writeIORef noticedAt . Just)+ when (n > 1 && not stillOpen) quit+ readIORef childPasses >>= require "the second window runs its view" . (>= 4)+ readIORef seen >>= require "a Var the second window writes reaches the first" . elem 7+ readVarIO open >>= require "the close request writes False" . not+ lag <- (\a b -> (-) <$> b <*> a) <$> readIORef closedAt <*> readIORef noticedAt+ require "the first window shows the close at once" (maybe False (< 1) lag)++-- | A UI scale set from the second window's view is the session's: the+-- first window, which nothing else wakes, applies it at once (a watchdog+-- wakes it after five seconds, so a regression fails rather than hangs).+childScaleCheck :: IO ()+childScaleCheck = do+ open <- newVar True+ passes <- newIORef 0+ setAt <- newIORef Nothing+ seenAt <- newIORef Nothing+ runSdlApp options $ do+ n <- countPass passes+ when (n == 1) $ askWake >>= \wake -> liftIO (void (forkIO (threadDelay 5000000 >> wake)))+ scale <- askSdlEnv >>= liftIO . traverse (readIORef . sdlScaleRef)+ when (scale == Just 2) $ liftIO (getMonotonicTime >>= writeIORef seenAt . Just) >> quit+ nativeWindow open (sdlWindowSettings options) {wsTitle = "second"} $ do+ sent <- liftIO (readIORef setAt)+ when (isNothing sent) $ liftIO (getMonotonicTime >>= writeIORef setAt . Just) >> setSdlUiScale 2+ lag <- (\a b -> (-) <$> b <*> a) <$> readIORef setAt <*> readIORef seenAt+ require "a UI scale set in the second window reaches the first at once" (maybe False (< 1) lag)++-- | A window the opening frames open closes with the session when those+-- frames also take a close request: its view's background job is+-- cancelled, which closing the window does.+openingQuitChildCheck :: IO ()+openingQuitChildCheck = do+ open <- newVar True+ job <- newTask+ passes <- newIORef 0+ cancelled <- newIORef False+ runSdlApp options $ do+ n <- countPass passes+ when (n == 1) $ liftIO (push (SDL_QuitEvent Events.SDL_EVENT_QUIT 0 0))+ nativeWindow open (sdlWindowSettings options) {wsTitle = "second"} $+ void $ useTask job () (threadDelay 10000000 `onException` writeIORef cancelled True)+ readIORef cancelled >>= require "a window the opening frames opened closes on their close request"++-- | A driver may turn vsync off whatever the session asks, and then a+-- present returns at once (here the test turns it off behind the session's+-- back). After a few such presents the session paces an animation by time:+-- half a second of it draws about 30 frames at the dummy display's 60 Hz,+-- not as many as the loop can.+fakeVsyncCheck :: IO ()+fakeVsyncCheck = do+ passes <- newIORef 0+ started <- newIORef Nothing+ runSdlApp options {sdlAppVsync = True} $ do+ n <- countPass passes+ when (n == 1) $ askSdlEnv >>= liftIO . traverse_ (\env -> setRenderVSyncSafe (sdlRenderer env) 0)+ now <- liftIO getMonotonicTime+ t0 <- liftIO $ readIORef started >>= maybe (now <$ writeIORef started (Just now)) pure+ keepAnimating =<< label' (fromString (show n))+ when (now - t0 > 0.5) quit+ n <- readIORef passes+ require ("an animation whose presents do not wait is paced by time: " ++ show n ++ " frames in half a second") (n < 150)++-- | A frame the resize watch draws (a live resize) that throws ends the+-- session with the exception, as a frame of the loop's own does, rather+-- than the process. The watch runs where SDL sends the event: here a thread+-- of the test's, which only the software renderer may draw from.+resizeFailureCheck :: IO ()+resizeFailureCheck = do+ software <- (== Just "software") <$> lookupEnv "SDL_RENDER_DRIVER"+ when software $ do+ passes <- newIORef 0+ outcome <- try $ runSdlApp options $ do+ wakeAfter 2+ n <- countPass passes+ width <- windowWidth+ when (width < 150) $ liftIO (ioError (userError "too narrow"))+ -- Once the loop waits, double the UI scale behind the session's back+ -- and send the event a resize would.+ live <- askSdlEnv+ when (n == 1) $ liftIO $ for_ live $ \env -> void $ forkIO $ do+ threadDelay 50000+ writeIORef (sdlUiScaleRef env) 2+ push (SDL_WindowEvent Events.SDL_EVENT_WINDOW_PIXEL_SIZE_CHANGED 0 0 0 200 100)+ -- The wake's frame: nothing drew the resize.+ when (n >= 3) quit+ require "the resize frame's exception leaves the session" $+ either (\(e :: IOException) -> "too narrow" `isInfixOf` show e) (const False) outcome++-- | Resizing a retained window renders 1:1 pixels at the new dimensions+-- without clipping or stretching, and toggling 'DecorationsFrame' preserves+-- window sizing under the Win32 subclass.+resizeChecks :: IO ()+resizeChecks =+ session options (colorRGBA 12 34 56 255) $ \ctx env -> do+ let bar = rowWith (tight . fillW) (flex >> solidBox red)+ frame ctx env True bar+ void (SDL.setWindowSizeSafe (sdlWindow env) 300 140)+ void (SDL.syncWindowSafe (sdlWindow env))+ (ctx', inp) <- syncDisplay ctx env emptyInput+ void (sdlDrawFrame ctx' bar env inp True)+ img <- captureScreenshot env >>= maybe (fail "resizeChecks: screenshot missing") pure+ requireEq "resized screenshot dimensions" (300, 140) (rgbaWidth (screenshotPixels img), rgbaHeight (screenshotPixels img))+ requireEq "right-aligned box after resize" [200, 30, 60, 255] (pixelAt img 280 10)+ requireEq "backdrop left of box after resize" [12, 34, 56, 255] (pixelAt img 10 10)+ setWindowDecorations env DecorationsFrame+ setWindowDecorations env DecorationsFull++-- | A UI scale that is not a number follows the display, as zero does, and+-- asking for it again asks for no frame.+uiScaleNaNCheck :: IO ()+uiScaleNaNCheck =+ session options (colorRGBA 0 0 0 255) $ \ctx env -> do+ replicateM_ 3 (frame ctx env True (setSdlUiScale (0 / 0)))+ isDirty ctx >>= require "asking again for a UI scale that is not a number asks for no frame" . not++-- | A file dialog's result: pending until it completes, delivered once,+-- and never revived by a late or abandoned callback.+dialogStateChecks :: IO ()+dialogStateChecks = do+ ref <- newIORef Dialog.FileDialogPending+ let complete = Dialog.completeResult ref+ chosen = Dialog.FileDialogSelected ["chosen.txt"]+ mapM_+ (\(name, act, want) -> act >> Dialog.takeResult ref >>= requireEq name want)+ [ ("a pending poll is repeatable", pure (), Dialog.FileDialogPending)+ , ("a second pending poll", pure (), Dialog.FileDialogPending)+ , ("completion delivered once", complete chosen, chosen)+ , ("completed handle consumed", pure (), Dialog.FileDialogUnknown)+ , ("a late callback cannot revive it", complete Dialog.FileDialogCancelled, Dialog.FileDialogUnknown)+ , ( "an abandoned callback is discarded"+ , writeIORef ref Dialog.FileDialogUnknown >> complete (Dialog.FileDialogSelected ["abandoned.txt"])+ , Dialog.FileDialogUnknown+ )+ ]+++-- | Size limits (in layout units, so doubled in window coordinates at zoom+-- 2) at creation and from a view, title, scale, resize and mode. With @gpu@,+-- also opacity, icon and position.+optionChecks :: Bool -> Int -> IO ()+optionChecks gpu zoom =+ session+ (withWindow limits) {sdlAppUiScale = fromIntegral zoom}+ (colorRGBA 0 0 0 255)+ $ \ctx env -> do+ let after :: (Eq a, Show a) => String -> IO () -> IO a -> a -> IO ()+ after name act get want = act >> get >>= requireEq (name ++ " at zoom " ++ show zoom) want+ ui v = frame ctx env True (v >> label "window")+ pair get = alloca $ \pw -> alloca $ \ph -> do+ get (sdlWindow env) pw ph >>= require "SDL did not report a size of the window"+ (,) <$> (fromIntegral <$> peek pw) <*> (fromIntegral <$> peek ph)+ zoomed (w, h) = (zoom * w, zoom * h)+ minimal name act = after name act (pair getWindowMinimumSize) . zoomed+ maximal name act = after name act (pair getWindowMaximumSize) . zoomed+ flags = getWindowFlags (sdlWindow env)+ hidden = (\f -> f .&. SDL.SDL_WINDOW_HIDDEN /= zeroBits) <$> flags+ title = windowTitle env+ askedWindow = frame ctx env True askWindow+ minimal "minimum size at creation" (pure ()) (150, 80)+ maximal "maximum size at creation" (pure ()) (900, 700)+ minimal "minimum size from a view" (ui (setWindowMinSize (Just (Size 170 90)))) (170, 90)+ minimal "minimum size taken off from a view" (ui (setWindowMinSize Nothing)) (0, 0)+ maximal "maximum width alone from a view" (ui (setWindowMaxSize (Just (Size 600 0)))) (600, 0)+ after "the title from a view" (ui (setWindowTitle "renamed")) title "renamed"+ after "the scale a view reads" (pure ()) (winScale <$> askedWindow) (fromIntegral zoom)+ -- X11 resizes asynchronously; sync before reading the size.+ let size = SDL.syncWindowSafe (sdlWindow env) >> pair getWindowSize+ after "a resize from a view" (ui (resizeWindow (Size 300 150))) size (zoomed (300, 150))+ after "a hidden window" (pure ()) hidden True+ after "shown from a view" (ui (setWindowMode Windowed)) hidden False+ after "hidden from a view" (ui (setWindowMode Hidden)) hidden True+ when gpu $ do+ let opacity = round . (* 100) <$> getWindowOpacity (sdlWindow env) :: IO Int+ moved name act at = after name act (winPosition <$> askedWindow) (Just at)+ after "the opacity at creation" (pure ()) opacity 50+ after "the opacity from a view" (ui (setWindowOpacity 0.75)) opacity 75+ ui (setWindowIcon (fromJust (rgbaPixels 2 2 (BS.pack (concat (replicate 4 [200, 30, 60, 255]))))))+ moved "the position at creation" (pure ()) (30, 20)+ moved "the position from a view" (ui (moveWindow 60 70)) (60, 70)+ where+ limits w =+ w+ { wsMinSize = Just (Size 150 80), wsMaxSize = Just (Size 900 700), wsOpacity = 0.5+ , wsPosition = WindowPositionAt 30 20+ }++red :: Color+red = colorRGBA 200 30 60 255++-- | RGBA bytes of one screenshot pixel.+pixelAt :: Screenshot -> Int -> Int -> [Int]+pixelAt shot x y =+ [fromIntegral (BS.index (rgbaBytes img) ((y * rgbaWidth img + x) * 4 + c)) | c <- [0 .. 3]]+ where+ img = screenshotPixels shot++-- | Every pixel's RGBA bytes, row by row.+pixelsOf :: Screenshot -> [[Int]]+pixelsOf shot = [pixelAt shot x y | y <- [0 .. rgbaHeight img - 1], x <- [0 .. rgbaWidth img - 1]]+ where+ img = screenshotPixels shot++-- | Alphas of all pixels whose RGB matches the colour.+alphasOf :: Color -> Screenshot -> [Int]+alphasOf c shot = [p !! 3 | p <- pixelsOf shot, take 3 p == map fromIntegral [colorR c, colorG c, colorB c]]++-- | A 40x20 box, versioned by its colour so a colour change repaints it.+solidBox :: Color -> NanoUI ()+solidBox c =+ void (drawingVersioned (fromIntegral (colorToWord32 c)) (fixedWH 40 20) (\r -> smallArrayFromList [FillRect r c]))++-- | A screenshot is answered after its frame is drawn (a skipped frame+-- returns what is on screen), and answering requests another frame. In a+-- continuous session the frame is read before it is presented.+screenshotChecks :: Bool -> IO ()+screenshotChecks continuous =+ session options {sdlAppContinuous = continuous} (colorRGBA 12 34 56 255) $ \ctx env -> do+ let name s = (if continuous then "continuous: " else "retained: ") ++ s+ frame ctx env True (solidBox (colorRGBA 0 0 255 255))+ img <- shoot (name "a frame that repaints the box") ctx env False (solidBox red)+ let size = (rgbaWidth (screenshotPixels img), rgbaHeight (screenshotPixels img), screenshotScale img)+ requireEq (name "screenshot size") (200, 100, 1) size+ requireEq (name "the box's pixels") (replicate 800 255) (alphasOf red img)+ requireEq (name "the window's colour") [12, 34, 56, 255] (pixelAt img 199 99)+ isDirty ctx >>= require (name "an answered screenshot asks for another frame")+ unless continuous $ do+ captureScreenshot env >>= require (name "captureScreenshot reads the same frame") . (== Just img)+ skipped <- shoot (name "a skipped frame") ctx env False (solidBox red)+ require (name "a skipped frame's screenshot") (skipped == img)++-- | A transparent window keeps the window colour's alpha, a partial repaint+-- matches a full one, and a GPU renderer keeps the alpha where the window+-- colour is painted over itself.+transparencyChecks :: Bool -> IO ()+transparencyChecks gpu =+ session (withWindow (\w -> w {wsTransparent = True})) backdrop $ \ctx env -> do+ -- The software renderer lacks custom blend modes and draws as if opaque.+ let exact = maybe False ((/= Blend.SDL_BLENDMODE_BLEND) . fst) (sdlTransparent env)+ -- An opaque box, a translucent tinted box, and the window colour+ -- painted twice, as a page scroller paints over the backdrop.+ shot full tint = shoot "transparent" ctx env full . column $ do+ solidBox red+ solidBox tint+ when exact $ void $ drawing (fixedWH 60 20) $ \r -> smallArrayFromList (replicate 2 (FillRect r backdrop))+ keepsAlpha img = all (== 128) (alphasOf backdrop img)+ require "a transparent window has blend modes" (sdlTransparent env /= Nothing)+ when gpu $ require "a GPU renderer draws a transparent window with custom blend modes" exact+ first <- shot True (colorRGBA 0 200 0 100)+ requireEq "transparent: the window's colour" [10, 20, 30, 128] (pixelAt first 199 99)+ require "transparent: the backdrop keeps its alpha" (keepsAlpha first)+ requireEq "transparent: an opaque box stays opaque" (replicate 800 255) (alphasOf red first)+ -- Repainting only the translucent box must not blend over the old box+ -- or old backdrop.+ second <- shot False (colorRGBA 0 0 200 100)+ require "transparent: the change was drawn" (second /= first)+ full <- shot True (colorRGBA 0 0 200 100)+ require "transparent: a change comes out as a full repaint does" (full == second)+ require "transparent: the backdrop keeps its alpha after a change" (keepsAlpha second)+ where+ backdrop = colorRGBA 10 20 30 128