packages feed

nano-ui-rgfw-bindings-0.2.0.0: test/Events.hs

module Main (main) where

import Control.Concurrent (forkIO, threadDelay)
import Control.Monad (replicateM_, unless, void)
import Data.Bits ((.|.))
import Foreign.C.Types (CInt (..), CSize (..))
import Foreign.Ptr (Ptr)
import GHC.Clock (getMonotonicTime, getMonotonicTimeNSec)
import GHC.Conc (getAllocationCounter)
import RGFW
  (Event (..), Window (..), closeWindow, createWindowGL, pollEvent, stopWaitForEvent, waitForEvent, withEventBuffer)
import RGFW.Raw
import System.Environment (getArgs, lookupEnv)
import System.Info (os)
import Text.Printf (printf)

foreign import ccall unsafe "rgfw_test_event_size" nativeSize :: IO CSize

foreign import ccall unsafe "rgfw_test_event"
  writeEvent :: Ptr RGFW_event -> CInt -> IO ()

foreign import ccall unsafe "rgfw_test_win32_drag"
  win32Drag :: Ptr RGFW_window -> CInt -> CInt -> CInt -> IO CInt

foreign import ccall unsafe "rgfw_test_win32_title"
  win32Title :: Ptr RGFW_window -> IO CInt

foreign import ccall unsafe "rgfw_test_enter"
  queueEnter :: Ptr RGFW_window -> CInt -> CInt -> IO ()

check :: (Eq a, Show a) => String -> a -> IO a -> IO ()
check name expected action = action >>= \actual -> unless (actual == expected) (fail (name ++ ": " ++ show actual))

main :: IO ()
main = withEventBuffer $ \event -> do
  size <- c_rgfw_event_size
  expectedSize <- nativeSize
  unless (size == expectedSize) (fail "RGFW event allocation size differs from C")
  -- Each C fixture writes one kind of event through the native types.
  let fixture kind tag = writeEvent event kind >> check "tag" (fromIntegral tag) (c_rgfw_event_type event)
      pair :: (Ptr RGFW_event -> IO a) -> (Ptr RGFW_event -> IO b) -> IO (a, b)
      pair a b = (,) <$> a event <*> b event
  fixture 0 rgfw_keyPressed
  check "key width excludes repeat/mod/state bytes" (fromIntegral rgfw_keyHome) (c_rgfw_event_key_value event)
  check "modifiers" (fromIntegral (rgfw_modControl .|. rgfw_modShift)) (c_rgfw_event_key_mod event)
  check "repeat" 1 (c_rgfw_event_key_repeat event)
  fixture 1 rgfw_keyChar
  check "Unicode character" 0x1f600 (c_rgfw_event_keyChar_value event)
  fixture 2 rgfw_mouseMotion
  check "motion" (-130, 245) (pair c_rgfw_event_mouse_x c_rgfw_event_mouse_y)
  fixture 3 rgfw_mouseScroll
  check "wheel" (1.25, -2.5) (pair c_rgfw_event_delta_x c_rgfw_event_delta_y)
  fixture 4 rgfw_mouseButtonPressed
  check "button" (fromIntegral rgfw_mouseRight) (c_rgfw_event_button_value event)
  fixture 5 rgfw_windowResized
  check "resize" (643, 481) (pair c_rgfw_event_update_w c_rgfw_event_update_h)
  fixture 6 rgfw_scaleUpdated
  check "scale" (1.25, 1.5) (pair c_rgfw_event_scale_x c_rgfw_event_scale_y)
  -- Key ranges that "RGFW.Raw" documents as consecutive.
  check "function keys are consecutive" (23 :: Int) (pure (fromIntegral (rgfw_keyF24 - rgfw_keyF1)))
  check "keypad digits are consecutive" (8 :: Int) (pure (fromIntegral (rgfw_keyPad9 - rgfw_keyPad1)))
  getArgs >>= \case
    ["--bench"] -> do
      writeEvent event 0
      let loop !n !acc
            | n == (0 :: Int) = pure acc
            | otherwise = c_rgfw_event_key_value event >>= \key -> loop (n - 1) (acc + fromIntegral key :: Int)
      before <- getAllocationCounter
      t0 <- getMonotonicTimeNSec
      total <- loop 10000000 0
      t1 <- getMonotonicTimeNSec
      after <- getAllocationCounter
      unless (total == 10000000 * fromIntegral rgfw_keyHome) (fail "event benchmark checksum")
      let perRead x = fromIntegral x / 1e7 :: Double
      printf "event-key: %.6f ns/read | %.3f B/read\n" (perRead (t1 - t0)) (perRead (before - after))
    _ -> do
      putStrLn "RGFW native event ABI: ok"
      titleCheck
      stopWaitCheck event
      enterCheck event
      captureCheck event

-- | A stop from another thread ends a wait, and a stop issued before a wait
-- makes it return at once. Stops that pile up while nothing waits are
-- drained by the next wait, so later waits block again instead of returning
-- immediately forever.
stopWaitCheck :: Ptr RGFW_event -> IO ()
stopWaitCheck event = withTestWindow "stop wait" $ \win -> do
  let -- Seconds a wait of up to @ms@ took, starting with an empty queue.
      timedWait ms = do
        _ <- events win event
        t0 <- getMonotonicTime
        waitForEvent ms
        subtract t0 <$> getMonotonicTime
      endsWithin limit what stop = do
        stop
        took <- timedWait 5000
        unless (took < limit) (fail ("RGFW stop wait: " ++ what ++ " ended the wait after " ++ show took ++ " s"))
  endsWithin 2 "a stop from another thread" (void (forkIO (threadDelay 100000 >> stopWaitForEvent)))
  endsWithin 1 "a stop before the wait" stopWaitForEvent
  endsWithin 1 "piled-up stops" (replicateM_ 100 stopWaitForEvent)
  -- A stray event can end a wait early, so one full wait in three suffices.
  waited <- mapM (const (timedWait 100)) [1 .. 3 :: Int]
  unless (any (>= 0.07) waited) $
    fail ("RGFW stop wait: the waits after the drain returned at once: " ++ show waited)

-- | A title outside ASCII reaches the window as UTF-8, whatever the
-- process locale. Windows only, where the title can be read back.
titleCheck :: IO ()
titleCheck
  | os /= "mingw32" = pure ()
  | otherwise = withTestWindowTitled "title" "nano \x00e9\x4e2d" $ \(Window ptr) ->
      win32Title ptr >>= \ok -> unless (ok == 1) (fail "RGFW title: the window title is not the UTF-8 title asked for")

-- | The pointer entering the window comes as motion to where it entered:
-- until it moves, nothing else reports where it is.
enterCheck :: Ptr RGFW_event -> IO ()
enterCheck event = withTestWindow "enter" $ \win@(Window ptr) -> do
  _ <- events win event
  queueEnter ptr 7 9
  got <- events win event
  unless (EventMouseMotion 7 9 `elem` got) (fail ("RGFW enter: " ++ show got))

-- | On Windows a press captures the mouse until the last button comes up, so
-- a release outside the window still arrives, and the pointer leaves with
-- it. A capture taken away mid-drag releases the button. Windows only.
captureCheck :: Ptr RGFW_event -> IO ()
captureCheck event
  | os /= "mingw32" = pure ()
  | otherwise = withTestWindow "mouse capture" $ \win@(Window ptr) -> do
      let mouse = filter isMouse <$> events win event
          isMouse = \case
            EventMouseButton _ _ -> True
            EventOther t -> t == rgfw_mouseLeave
            _ -> False
          left = EventMouseButton rgfw_mouseLeft
          drag what lose expected = do
            _ <- mouse
            captured <- win32Drag ptr (-20) (-20) lose
            got <- mouse
            unless (captured == 1 && got == expected) $
              fail ("RGFW mouse capture: " ++ what ++ ": " ++ show (captured, got))
      drag "a release outside the window" 0 [left True, left False, EventOther rgfw_mouseLeave]
      drag "a capture taken away" 1 [left True, left False]

-- | Every queued event, oldest first.
events :: Window -> Ptr RGFW_event -> IO [Event]
events win event =
  pollEvent win event >>= \case
    EventNone -> pure []
    ev -> (ev :) <$> events win event

-- | Run @body@ on a hidden 64x64 OpenGL 3.2 window titled @name@, then
-- close it and report "RGFW <name>: ok". Skipped on Linux without an X
-- display, and without such a window.
withTestWindow :: String -> (Window -> IO ()) -> IO ()
withTestWindow name = withTestWindowTitled name name

-- | 'withTestWindow' with a window title other than the check's name.
withTestWindowTitled :: String -> String -> (Window -> IO ()) -> IO ()
withTestWindowTitled name title body = do
  display <- lookupEnv "DISPLAY"
  if os == "linux" && maybe True null display
    then putStrLn ("RGFW " ++ name ++ ": skipped (no X display)")
    else
      createWindowGL title 0 0 64 64 rgfw_windowHide 3 2 >>= \case
        Nothing -> putStrLn ("RGFW " ++ name ++ ": skipped (no OpenGL 3.2 window)")
        Just win -> body win >> closeWindow win >> putStrLn ("RGFW " ++ name ++ ": ok")