nano-ui-sdl-0.2.0.0: lib/NanoUI/Sdl/Internal/Display.hs
{-# 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