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