Add a vendored copy of SDL

This commit is contained in:
2024-02-24 19:00:12 -08:00
parent 2cb2743283
commit 5c11bfd9c8
1613 changed files with 675493 additions and 0 deletions

View File

@ -0,0 +1,523 @@
cmake_minimum_required(VERSION 3.0...3.5)
project(SDL2_test)
include(CheckCCompilerFlag)
include(CMakeParseArguments)
include(CMakePushCheckState)
set(SDL_TEST_EXECUTABLES)
set(SDL_TESTS_NONINTERACTIVE)
set(SDL_TESTS_NEEDS_RESOURCES)
macro(add_sdl_test_executable TARGET)
cmake_parse_arguments(AST "NONINTERACTIVE;NEEDS_RESOURCES" "" "" ${ARGN})
if(ANDROID)
add_library(${TARGET} SHARED ${AST_UNPARSED_ARGUMENTS})
else()
add_executable(${TARGET} ${AST_UNPARSED_ARGUMENTS})
endif()
list(APPEND SDL_TEST_EXECUTABLES ${TARGET})
if(AST_NONINTERACTIVE)
list(APPEND SDL_TESTS_NONINTERACTIVE ${TARGET})
endif()
if(AST_NEEDS_RESOURCES)
list(APPEND SDL_TESTS_NEEDS_RESOURCES ${TARGET})
endif()
if(HAVE_GCC_WDOCUMENTATION)
target_compile_options(${TARGET} PRIVATE "-Wdocumentation")
if(HAVE_GCC_WERROR_DOCUMENTATION)
target_compile_options(${TARGET} PRIVATE "-Werror=documentation")
endif()
endif()
if(HAVE_GCC_WDOCUMENTATION_UNKNOWN_COMMAND)
if(SDL_WERROR)
if(HAVE_GCC_WERROR_DOCUMENTATION_UNKNOWN_COMMAND)
target_compile_options(${TARGET} PRIVATE "-Werror=documentation-unknown-command")
endif()
endif()
target_compile_options(${TARGET} PRIVATE "-Wdocumentation-unknown-command")
endif()
if(HAVE_GCC_COMMENT_BLOCK_COMMANDS)
target_compile_options(${TARGET} PRIVATE "-fcomment-block-commands=threadsafety")
target_compile_options(${TARGET} PRIVATE "-fcomment-block-commands=deprecated")
else()
if(HAVE_CLANG_COMMENT_BLOCK_COMMANDS)
target_compile_options(${TARGET} PRIVATE "/clang:-fcomment-block-commands=threadsafety")
target_compile_options(${TARGET} PRIVATE "/clang:-fcomment-block-commands=deprecated")
endif()
endif()
if(USE_GCC OR USE_CLANG)
check_c_compiler_flag(-fno-fast-math HAVE_GCC_FNO_FAST_MATH)
if(HAVE_GCC_FNO_FAST_MATH)
target_compile_options(${TARGET} PRIVATE -fno-fast-math)
endif()
endif()
endmacro()
if(NOT TARGET SDL2::SDL2-static)
find_package(SDL2 2.0.23 REQUIRED COMPONENTS SDL2-static SDL2test)
endif()
enable_testing()
if(SDL_INSTALL_TESTS)
include(GNUInstallDirs)
endif()
if(N3DS)
link_libraries(SDL2::SDL2main)
endif()
if(PSP)
link_libraries(
SDL2::SDL2main
SDL2::SDL2test
SDL2::SDL2-static
GL
pspvram
pspvfpu
pspdisplay
pspgu
pspge
pspaudio
pspctrl
psphprm
psppower
)
elseif(PS2)
link_libraries(
SDL2main
SDL2_test
SDL2-static
patches
gskit
dmakit
ps2_drivers
)
else()
link_libraries(SDL2::SDL2test SDL2::SDL2-static)
endif()
if(WINDOWS)
# mingw32 must come before SDL2main to link successfully
if(MINGW OR CYGWIN)
link_libraries(mingw32)
endif()
# CET support was added in VS 16.7
if(MSVC_VERSION GREATER 1926 AND CMAKE_GENERATOR_PLATFORM MATCHES "Win32|x64")
link_libraries(-CETCOMPAT)
endif()
# FIXME: Parent directory CMakeLists.txt only sets these for mingw/cygwin,
# but we need them for VS as well.
link_libraries(SDL2main)
add_definitions(-Dmain=SDL_main)
endif()
# CMake incorrectly detects opengl32.lib being present on MSVC ARM64
if(NOT MSVC OR NOT CMAKE_GENERATOR_PLATFORM STREQUAL "ARM64")
# Prefer GLVND, if present
set(OpenGL_GL_PREFERENCE GLVND)
find_package(OpenGL)
endif()
if (OPENGL_FOUND)
add_definitions(-DHAVE_OPENGL)
endif()
add_sdl_test_executable(checkkeys checkkeys.c)
add_sdl_test_executable(checkkeysthreads checkkeysthreads.c)
add_sdl_test_executable(loopwave NEEDS_RESOURCES loopwave.c testutils.c)
add_sdl_test_executable(loopwavequeue NEEDS_RESOURCES loopwavequeue.c testutils.c)
add_sdl_test_executable(testsurround testsurround.c)
add_sdl_test_executable(testresample NEEDS_RESOURCES testresample.c)
add_sdl_test_executable(testaudioinfo testaudioinfo.c)
file(GLOB TESTAUTOMATION_SOURCE_FILES testautomation*.c)
add_sdl_test_executable(testautomation NONINTERACTIVE NEEDS_RESOURCES ${TESTAUTOMATION_SOURCE_FILES})
add_sdl_test_executable(testmultiaudio NEEDS_RESOURCES testmultiaudio.c testutils.c)
add_sdl_test_executable(testaudiohotplug NEEDS_RESOURCES testaudiohotplug.c testutils.c)
add_sdl_test_executable(testaudiocapture testaudiocapture.c)
add_sdl_test_executable(testatomic NONINTERACTIVE testatomic.c)
add_sdl_test_executable(testintersections testintersections.c)
add_sdl_test_executable(testrelative testrelative.c)
add_sdl_test_executable(testhittesting testhittesting.c)
add_sdl_test_executable(testdraw2 testdraw2.c)
add_sdl_test_executable(testdrawchessboard testdrawchessboard.c)
add_sdl_test_executable(testdropfile testdropfile.c)
add_sdl_test_executable(testerror NONINTERACTIVE testerror.c)
if(LINUX)
add_sdl_test_executable(testevdev NONINTERACTIVE testevdev.c)
endif()
add_sdl_test_executable(testfile testfile.c)
add_sdl_test_executable(testgamecontroller NEEDS_RESOURCES testgamecontroller.c testutils.c)
add_sdl_test_executable(testgeometry testgeometry.c testutils.c)
add_sdl_test_executable(testgesture testgesture.c)
add_sdl_test_executable(testgl2 testgl2.c)
add_sdl_test_executable(testgles testgles.c)
add_sdl_test_executable(testgles2 testgles2.c)
add_sdl_test_executable(testgles2_sdf NEEDS_RESOURCES testgles2_sdf.c testutils.c)
add_sdl_test_executable(testhaptic testhaptic.c)
add_sdl_test_executable(testhotplug testhotplug.c)
add_sdl_test_executable(testrumble testrumble.c)
add_sdl_test_executable(testthread NONINTERACTIVE testthread.c)
add_sdl_test_executable(testiconv NEEDS_RESOURCES testiconv.c testutils.c)
add_sdl_test_executable(testime NEEDS_RESOURCES testime.c testutils.c)
add_sdl_test_executable(testjoystick testjoystick.c)
add_sdl_test_executable(testkeys testkeys.c)
add_sdl_test_executable(testloadso testloadso.c)
add_sdl_test_executable(testlocale NONINTERACTIVE testlocale.c)
add_sdl_test_executable(testlock testlock.c)
add_sdl_test_executable(testmouse testmouse.c)
if(APPLE)
add_sdl_test_executable(testnative NEEDS_RESOURCES
testnative.c
testnativecocoa.m
testnativex11.c
testutils.c
)
cmake_push_check_state(RESET)
check_c_compiler_flag(-Wno-error=deprecated-declarations HAVE_WNO_ERROR_DEPRECATED_DECLARATIONS)
cmake_pop_check_state()
if(HAVE_WNO_ERROR_DEPRECATED_DECLARATIONS)
set_property(SOURCE "testnativecocoa.m" APPEND_STRING PROPERTY COMPILE_FLAGS " -Wno-error=deprecated-declarations")
endif()
elseif(WINDOWS)
add_sdl_test_executable(testnative NEEDS_RESOURCES testnative.c testnativew32.c testutils.c)
elseif(HAVE_X11)
add_sdl_test_executable(testnative NEEDS_RESOURCES testnative.c testnativex11.c testutils.c)
target_link_libraries(testnative X11)
elseif(OS2)
add_sdl_test_executable(testnative NEEDS_RESOURCES testnative.c testnativeos2.c testutils.c)
endif()
add_sdl_test_executable(testoverlay2 NEEDS_RESOURCES testoverlay2.c testyuv_cvt.c testutils.c)
add_sdl_test_executable(testplatform NONINTERACTIVE testplatform.c)
add_sdl_test_executable(testpower NONINTERACTIVE testpower.c)
add_sdl_test_executable(testfilesystem NONINTERACTIVE testfilesystem.c)
if(WIN32 AND CMAKE_SIZEOF_VOID_P EQUAL 4)
add_sdl_test_executable(testfilesystem_pre NONINTERACTIVE testfilesystem_pre.c)
endif()
add_sdl_test_executable(testrendertarget NEEDS_RESOURCES testrendertarget.c testutils.c)
add_sdl_test_executable(testscale NEEDS_RESOURCES testscale.c testutils.c)
add_sdl_test_executable(testsem testsem.c)
add_sdl_test_executable(testsensor testsensor.c)
add_sdl_test_executable(testshader NEEDS_RESOURCES testshader.c)
add_sdl_test_executable(testshape NEEDS_RESOURCES testshape.c)
add_sdl_test_executable(testsprite2 NEEDS_RESOURCES testsprite2.c testutils.c)
add_sdl_test_executable(testspriteminimal NEEDS_RESOURCES testspriteminimal.c testutils.c)
add_sdl_test_executable(teststreaming NEEDS_RESOURCES teststreaming.c testutils.c)
add_sdl_test_executable(testtimer NONINTERACTIVE testtimer.c)
add_sdl_test_executable(testurl testurl.c)
add_sdl_test_executable(testver NONINTERACTIVE testver.c)
add_sdl_test_executable(testviewport NEEDS_RESOURCES testviewport.c testutils.c)
add_sdl_test_executable(testwm2 testwm2.c)
add_sdl_test_executable(testyuv NEEDS_RESOURCES testyuv.c testyuv_cvt.c)
add_sdl_test_executable(torturethread torturethread.c)
add_sdl_test_executable(testrendercopyex NEEDS_RESOURCES testrendercopyex.c testutils.c)
add_sdl_test_executable(testmessage testmessage.c)
add_sdl_test_executable(testdisplayinfo testdisplayinfo.c)
add_sdl_test_executable(testqsort NONINTERACTIVE testqsort.c)
add_sdl_test_executable(testbounds testbounds.c)
add_sdl_test_executable(testcustomcursor testcustomcursor.c)
add_sdl_test_executable(controllermap NEEDS_RESOURCES controllermap.c testutils.c)
add_sdl_test_executable(testvulkan testvulkan.c)
add_sdl_test_executable(testoffscreen testoffscreen.c)
cmake_push_check_state(RESET)
check_c_compiler_flag(-Wformat-overflow HAVE_WFORMAT_OVERFLOW)
if(HAVE_WFORMAT_OVERFLOW)
target_compile_definitions(testautomation PRIVATE HAVE_WFORMAT_OVERFLOW)
endif()
check_c_compiler_flag(-Wformat HAVE_WFORMAT)
if(HAVE_WFORMAT)
target_compile_definitions(testautomation PRIVATE HAVE_WFORMAT)
endif()
check_c_compiler_flag(-Wformat-extra-args HAVE_WFORMAT_EXTRA_ARGS)
if(HAVE_WFORMAT_EXTRA_ARGS)
target_compile_definitions(testautomation PRIVATE HAVE_WFORMAT_EXTRA_ARGS)
endif()
cmake_pop_check_state()
if(SDL_DUMMYAUDIO)
list(APPEND SDL_TESTS_NONINTERACTIVE
testaudioinfo
testsurround
)
endif()
if(SDL_DUMMYVIDEO)
list(APPEND SDL_TESTS_NONINTERACTIVE
testkeys
testbounds
testdisplayinfo
)
endif()
if(OPENGL_FOUND)
if(TARGET OpenGL::GL)
target_link_libraries(testshader OpenGL::GL)
target_link_libraries(testgl2 OpenGL::GL)
else()
if(EMSCRIPTEN AND OPENGL_gl_LIBRARY STREQUAL "nul")
set(OPENGL_gl_LIBRARY GL)
endif()
# emscripten's FindOpenGL.cmake does not create OpenGL::GL
target_link_libraries(testshader ${OPENGL_gl_LIBRARY})
target_link_libraries(testgl2 ${OPENGL_gl_LIBRARY})
endif()
endif()
if(EMSCRIPTEN)
target_link_libraries(testshader -sLEGACY_GL_EMULATION)
endif()
file(GLOB RESOURCE_FILES *.bmp *.wav *.hex moose.dat utf8.txt)
file(COPY ${RESOURCE_FILES} DESTINATION ${CMAKE_CURRENT_BINARY_DIR})
if(PSP)
# Build EBOOT files if building for PSP
set(BUILD_EBOOT
${SDL_TESTS_NEEDS_RESOURCES}
testatomic
testaudiocapture
testaudioinfo
testbounds
testdisplayinfo
testdraw2
testdrawchessboard
testerror
testfile
testfilesystem
testgeometry
testgl2
testhittesting
testiconv
testintersections
testjoystick
testlock
testmessage
testoverlay2
testplatform
testpower
testqsort
testsem
teststreaming
testsurround
testthread
testtimer
testver
testviewport
testwm2
torturethread
)
foreach(APP IN LISTS BUILD_EBOOT)
create_pbp_file(
TARGET ${APP}
TITLE SDL-${APP}
ICON_PATH NULL
BACKGROUND_PATH NULL
PREVIEW_PATH NULL
)
add_custom_command(
TARGET ${APP} POST_BUILD
COMMAND ${CMAKE_COMMAND} -E make_directory
$<TARGET_FILE_DIR:${ARG_TARGET}>/sdl-${APP}
)
add_custom_command(
TARGET ${APP} POST_BUILD
COMMAND ${CMAKE_COMMAND} -E rename
$<TARGET_FILE_DIR:${ARG_TARGET}>/EBOOT.PBP
$<TARGET_FILE_DIR:${ARG_TARGET}>/sdl-${APP}/EBOOT.PBP
)
if(${BUILD_PRX})
add_custom_command(
TARGET ${APP} POST_BUILD
COMMAND ${CMAKE_COMMAND} -E copy
$<TARGET_FILE_DIR:${ARG_TARGET}>/${APP}
$<TARGET_FILE_DIR:${ARG_TARGET}>/sdl-${APP}/${APP}
)
add_custom_command(
TARGET ${APP} POST_BUILD
COMMAND ${CMAKE_COMMAND} -E rename
$<TARGET_FILE_DIR:${ARG_TARGET}>/${APP}.prx
$<TARGET_FILE_DIR:${ARG_TARGET}>/sdl-${APP}/${APP}.prx
)
endif()
add_custom_command(
TARGET ${APP} POST_BUILD
COMMAND ${CMAKE_COMMAND} -E remove
$<TARGET_FILE_DIR:${ARG_TARGET}>/PARAM.SFO
)
endforeach()
endif()
if(N3DS)
set(ROMFS_DIR "${CMAKE_CURRENT_BINARY_DIR}/romfs")
file(COPY ${RESOURCE_FILES} DESTINATION "${ROMFS_DIR}")
foreach(APP IN LISTS SDL_TEST_EXECUTABLES)
get_target_property(TARGET_BINARY_DIR ${APP} BINARY_DIR)
set(SMDH_FILE "${TARGET_BINARY_DIR}/${APP}.smdh")
ctr_generate_smdh("${SMDH_FILE}"
NAME "SDL-${APP}"
DESCRIPTION "SDL2 Test suite"
AUTHOR "SDL2 Contributors"
ICON "${CMAKE_CURRENT_SOURCE_DIR}/n3ds/logo48x48.png"
)
ctr_create_3dsx(
${APP}
ROMFS "${ROMFS_DIR}"
SMDH "${SMDH_FILE}"
)
endforeach()
endif()
if(RISCOS)
set(SDL_TEST_EXECUTABLES_AIF)
foreach(APP IN LISTS SDL_TEST_EXECUTABLES)
target_link_options(${APP} PRIVATE -static)
add_custom_command(
OUTPUT ${APP},ff8
COMMAND elf2aif ${APP} ${APP},ff8
DEPENDS ${APP}
)
add_custom_target(${APP}-aif ALL DEPENDS ${APP},ff8)
list(APPEND SDL_TEST_EXECUTABLES_AIF ${CMAKE_CURRENT_BINARY_DIR}/${APP},ff8)
endforeach()
endif()
if(CMAKE_RUNTIME_OUTPUT_DIRECTORY)
set(test_bin_dir "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}")
if(NOT IS_ABSOLUTE "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}")
set(test_bin_dir "${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_RUNTIME_OUTPUT_DIRECTORY}")
endif()
else()
set(test_bin_dir "${CMAKE_CURRENT_BINARY_DIR}")
endif()
if(NOT CMAKE_VERSION VERSION_LESS 3.20)
get_property(is_multi_config GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG)
set(test_bin_dir "${test_bin_dir}$<$<BOOL:${is_multi_config}>:/$<CONFIG>>")
endif()
set(RESOURCE_FILES_BINDIR)
foreach(resource_file IN LISTS RESOURCE_FILES)
get_filename_component(res_file_name ${resource_file} NAME)
set(resource_file_bindir "${test_bin_dir}/${res_file_name}")
add_custom_command(OUTPUT "${resource_file_bindir}"
COMMAND "${CMAKE_COMMAND}" -E copy "${resource_file}" "${resource_file_bindir}"
DEPENDS "${resource_file}"
)
list(APPEND RESOURCE_FILES_BINDIR "${resource_file_bindir}")
endforeach()
add_custom_target(copy-sdl-test-resources
DEPENDS "${RESOURCE_FILES_BINDIR}"
)
foreach(APP IN LISTS SDL_TESTS_NEEDS_RESOURCES)
if(PSP OR PS2)
foreach(RESOURCE_FILE ${RESOURCE_FILES})
add_custom_command(TARGET ${APP} POST_BUILD COMMAND ${CMAKE_COMMAND} ARGS -E copy_if_different ${RESOURCE_FILE} $<TARGET_FILE_DIR:${APP}>/sdl-${APP})
endforeach()
else()
add_dependencies(${APP} copy-sdl-test-resources)
endif()
if(APPLE)
# Make sure resource files get installed into macOS/iOS .app bundles.
target_sources(${APP} PRIVATE "${RESOURCE_FILES}")
set_target_properties(${APP} PROPERTIES RESOURCE "${RESOURCE_FILES}")
endif()
endforeach()
# Set Apple App ID / Bundle ID. This is needed to launch apps on some Apple
# platforms (iOS, for example).
if(APPLE)
if(${CMAKE_VERSION} VERSION_LESS "3.7.0")
# CMake's 'BUILDSYSTEM_TARGETS' property is only available in
# CMake 3.7 and above.
message(WARNING "Unable to set Bundle ID for Apple .app builds due to old CMake (pre 3.7).")
else()
get_property(TARGETS DIRECTORY ${CMAKE_CURRENT_LIST_DIR} PROPERTY BUILDSYSTEM_TARGETS)
foreach(CURRENT_TARGET IN LISTS TARGETS)
get_property(TARGET_TYPE TARGET ${CURRENT_TARGET} PROPERTY TYPE)
if(TARGET_TYPE STREQUAL "EXECUTABLE")
set_target_properties("${CURRENT_TARGET}" PROPERTIES
MACOSX_BUNDLE_GUI_IDENTIFIER "org.libsdl.${CURRENT_TARGET}"
MACOSX_BUNDLE_BUNDLE_VERSION "${SDL_VERSION}"
MACOSX_BUNDLE_SHORT_VERSION_STRING "${SDL_VERSION}"
)
endif()
endforeach()
endif()
endif()
set(TESTS_ENVIRONMENT
SDL_AUDIODRIVER=dummy
SDL_VIDEODRIVER=dummy
)
foreach(TESTCASE ${SDL_TESTS_NONINTERACTIVE})
add_test(
NAME ${TESTCASE}
COMMAND ${TESTCASE}
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
)
set_tests_properties(${TESTCASE}
PROPERTIES
ENVIRONMENT "${TESTS_ENVIRONMENT}"
TIMEOUT 10
)
if(SDL_INSTALL_TESTS)
set(exe ${TESTCASE})
set(installedtestsdir "${CMAKE_INSTALL_FULL_LIBEXECDIR}/installed-tests/SDL2")
configure_file(template.test.in "${exe}.test" @ONLY)
install(
FILES "${CMAKE_CURRENT_BINARY_DIR}/${exe}.test"
DESTINATION ${CMAKE_INSTALL_DATADIR}/installed-tests/SDL2
)
endif()
endforeach()
set_tests_properties(testautomation PROPERTIES TIMEOUT 120)
set_tests_properties(testthread PROPERTIES TIMEOUT 40)
set_tests_properties(testtimer PROPERTIES TIMEOUT 60)
if(TARGET testfilesystem_pre)
set_property(TEST testfilesystem_pre PROPERTY TIMEOUT 60)
set_property(TEST testfilesystem APPEND PROPERTY DEPENDS testfilesystem_pre)
endif()
if(SDL_INSTALL_TESTS)
if(RISCOS)
install(
FILES ${SDL_TEST_EXECUTABLES_AIF}
DESTINATION ${CMAKE_INSTALL_LIBEXECDIR}/installed-tests/SDL2
)
else()
install(
TARGETS ${SDL_TEST_EXECUTABLES}
DESTINATION ${CMAKE_INSTALL_LIBEXECDIR}/installed-tests/SDL2
)
endif()
if(MSVC)
foreach(test ${SDL_TEST_EXECUTABLES})
SDL_install_pdb(${test} "${CMAKE_INSTALL_LIBEXECDIR}/installed-tests/SDL2")
endforeach()
endif()
install(
FILES ${RESOURCE_FILES}
DESTINATION ${CMAKE_INSTALL_LIBEXECDIR}/installed-tests/SDL2
)
endif()

View File

@ -0,0 +1,8 @@
The test programs in this directory tree are for demonstrating and
testing the functionality of the SDL library, and are placed in the
public domain.
October 28, 1997
--
Sam Lantinga (slouken@libsdl.org)

View File

@ -0,0 +1,448 @@
# Makefile to build the SDL tests
srcdir = @srcdir@
prefix = @prefix@
exec_prefix = @exec_prefix@
bindir = @bindir@
libdir = @libdir@
libexecdir = @libexecdir@
includedir = @includedir@
datarootdir = @datarootdir@
datadir = @datadir@
CC = @CC@
EXE = @EXE@
CFLAGS = @CFLAGS@ -g
LIBS = @LIBS@
TARGETS = \
checkkeys$(EXE) \
checkkeysthreads$(EXE) \
controllermap$(EXE) \
loopwave$(EXE) \
loopwavequeue$(EXE) \
testatomic$(EXE) \
testaudiocapture$(EXE) \
testaudiohotplug$(EXE) \
testaudioinfo$(EXE) \
testautomation$(EXE) \
testbounds$(EXE) \
testcustomcursor$(EXE) \
testdisplayinfo$(EXE) \
testdraw2$(EXE) \
testdrawchessboard$(EXE) \
testdropfile$(EXE) \
testerror$(EXE) \
testevdev$(EXE) \
testfile$(EXE) \
testfilesystem$(EXE) \
testgamecontroller$(EXE) \
testgeometry$(EXE) \
testgesture$(EXE) \
testhaptic$(EXE) \
testhittesting$(EXE) \
testhotplug$(EXE) \
testiconv$(EXE) \
testime$(EXE) \
testintersections$(EXE) \
testjoystick$(EXE) \
testkeys$(EXE) \
testloadso$(EXE) \
testlocale$(EXE) \
testlock$(EXE) \
testmessage$(EXE) \
testmouse$(EXE) \
testmultiaudio$(EXE) \
testnative$(EXE) \
testoverlay2$(EXE) \
testplatform$(EXE) \
testpower$(EXE) \
testqsort$(EXE) \
testrelative$(EXE) \
testrendercopyex$(EXE) \
testrendertarget$(EXE) \
testresample$(EXE) \
testrumble$(EXE) \
testscale$(EXE) \
testsem$(EXE) \
testsensor$(EXE) \
testshape$(EXE) \
testsprite2$(EXE) \
testspriteminimal$(EXE) \
teststreaming$(EXE) \
testsurround$(EXE) \
testthread$(EXE) \
testtimer$(EXE) \
testurl$(EXE) \
testver$(EXE) \
testviewport$(EXE) \
testvulkan$(EXE) \
testwm2$(EXE) \
testyuv$(EXE) \
torturethread$(EXE) \
@OPENGL_TARGETS@ += testgl2$(EXE) testshader$(EXE)
@OPENGLES1_TARGETS@ += testgles$(EXE)
@OPENGLES2_TARGETS@ += testgles2$(EXE)
all: Makefile $(TARGETS) copydatafiles generatetestmeta
installedtestsdir = $(libexecdir)/installed-tests/SDL2
installedtestsmetadir = $(datadir)/installed-tests/SDL2
generatetestmeta:
rm -f *.test
set -e; for exe in $(TESTS); do \
sed \
-e 's#@installedtestsdir@#$(installedtestsdir)#g' \
-e "s#@exe@#$$exe#g" \
< $(srcdir)/template.test.in > $$exe.test; \
done
install: all
install -d $(DESTDIR)$(installedtestsdir)
install $(TARGETS) $(DESTDIR)$(installedtestsdir)
install -m644 $(DATA) $(DESTDIR)$(installedtestsdir)
install -d $(DESTDIR)$(installedtestsmetadir)
install -m644 *.test $(DESTDIR)$(installedtestsmetadir)
Makefile: $(srcdir)/Makefile.in
$(SHELL) config.status $@
checkkeys$(EXE): $(srcdir)/checkkeys.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
checkkeysthreads$(EXE): $(srcdir)/checkkeysthreads.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
loopwave$(EXE): $(srcdir)/loopwave.c $(srcdir)/testutils.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
loopwavequeue$(EXE): $(srcdir)/loopwavequeue.c $(srcdir)/testutils.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
testsurround$(EXE): $(srcdir)/testsurround.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
testresample$(EXE): $(srcdir)/testresample.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
testaudioinfo$(EXE): $(srcdir)/testaudioinfo.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
testautomation$(EXE): $(srcdir)/testautomation.c \
$(srcdir)/testautomation_audio.c \
$(srcdir)/testautomation_clipboard.c \
$(srcdir)/testautomation_events.c \
$(srcdir)/testautomation_guid.c \
$(srcdir)/testautomation_hints.c \
$(srcdir)/testautomation_joystick.c \
$(srcdir)/testautomation_keyboard.c \
$(srcdir)/testautomation_log.c \
$(srcdir)/testautomation_main.c \
$(srcdir)/testautomation_math.c \
$(srcdir)/testautomation_mouse.c \
$(srcdir)/testautomation_pixels.c \
$(srcdir)/testautomation_platform.c \
$(srcdir)/testautomation_rect.c \
$(srcdir)/testautomation_render.c \
$(srcdir)/testautomation_rwops.c \
$(srcdir)/testautomation_sdltest.c \
$(srcdir)/testautomation_stdlib.c \
$(srcdir)/testautomation_subsystems.c \
$(srcdir)/testautomation_surface.c \
$(srcdir)/testautomation_syswm.c \
$(srcdir)/testautomation_timer.c \
$(srcdir)/testautomation_video.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
testmultiaudio$(EXE): $(srcdir)/testmultiaudio.c $(srcdir)/testutils.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
testaudiohotplug$(EXE): $(srcdir)/testaudiohotplug.c $(srcdir)/testutils.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
testaudiocapture$(EXE): $(srcdir)/testaudiocapture.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
testatomic$(EXE): $(srcdir)/testatomic.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
testintersections$(EXE): $(srcdir)/testintersections.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
testrelative$(EXE): $(srcdir)/testrelative.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
testhittesting$(EXE): $(srcdir)/testhittesting.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
testdraw2$(EXE): $(srcdir)/testdraw2.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
testdrawchessboard$(EXE): $(srcdir)/testdrawchessboard.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
testdropfile$(EXE): $(srcdir)/testdropfile.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
testerror$(EXE): $(srcdir)/testerror.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
testevdev$(EXE): $(srcdir)/testevdev.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
testfile$(EXE): $(srcdir)/testfile.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
testgamecontroller$(EXE): $(srcdir)/testgamecontroller.c $(srcdir)/testutils.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
testgeometry$(EXE): $(srcdir)/testgeometry.c $(srcdir)/testutils.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
testgesture$(EXE): $(srcdir)/testgesture.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS) @MATHLIB@
testgl2$(EXE): $(srcdir)/testgl2.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS) @MATHLIB@
testgles$(EXE): $(srcdir)/testgles.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS) @GLESLIB@ @MATHLIB@
testgles2$(EXE): $(srcdir)/testgles2.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS) @MATHLIB@
testgles2_sdf$(EXE): $(srcdir)/testgles2_sdf.c $(srcdir)/testutils.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS) @MATHLIB@
testhaptic$(EXE): $(srcdir)/testhaptic.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
testhotplug$(EXE): $(srcdir)/testhotplug.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
testrumble$(EXE): $(srcdir)/testrumble.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
testthread$(EXE): $(srcdir)/testthread.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
testiconv$(EXE): $(srcdir)/testiconv.c $(srcdir)/testutils.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
testime$(EXE): $(srcdir)/testime.c $(srcdir)/testutils.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS) @SDL_TTF_LIB@
testjoystick$(EXE): $(srcdir)/testjoystick.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
testkeys$(EXE): $(srcdir)/testkeys.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
testloadso$(EXE): $(srcdir)/testloadso.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
testlock$(EXE): $(srcdir)/testlock.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
ifeq (@ISMACOSX@,true)
testnative$(EXE): $(srcdir)/testnative.c \
$(srcdir)/testnativecocoa.m \
$(srcdir)/testutils.c \
$(srcdir)/testnativex11.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS) -framework Cocoa @XLIB@
endif
ifeq (@ISWINDOWS@,true)
testnative$(EXE): $(srcdir)/testnative.c \
$(srcdir)/testutils.c \
$(srcdir)/testnativew32.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
endif
ifeq (@ISUNIX@,true)
testnative$(EXE): $(srcdir)/testnative.c \
$(srcdir)/testutils.c \
$(srcdir)/testnativex11.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS) @XLIB@
endif
ifeq (@ISOS2@,true)
testnative$(EXE): $(srcdir)/testnative.c \
$(srcdir)/testnativeos2.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
endif
#there's probably a better way of doing this
ifeq (@ISMACOSX@,false)
ifeq (@ISWINDOWS@,false)
ifeq (@ISUNIX@,false)
ifeq (@ISOS2@,false)
testnative$(EXE): ;
endif
endif
endif
endif
testoverlay2$(EXE): $(srcdir)/testoverlay2.c $(srcdir)/testyuv_cvt.c $(srcdir)/testutils.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
testplatform$(EXE): $(srcdir)/testplatform.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
testpower$(EXE): $(srcdir)/testpower.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
testfilesystem$(EXE): $(srcdir)/testfilesystem.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
testrendertarget$(EXE): $(srcdir)/testrendertarget.c $(srcdir)/testutils.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
testscale$(EXE): $(srcdir)/testscale.c $(srcdir)/testutils.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
testsem$(EXE): $(srcdir)/testsem.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
testsensor$(EXE): $(srcdir)/testsensor.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
testshader$(EXE): $(srcdir)/testshader.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS) @GLLIB@ @MATHLIB@
testshape$(EXE): $(srcdir)/testshape.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
testsprite2$(EXE): $(srcdir)/testsprite2.c $(srcdir)/testutils.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
testspriteminimal$(EXE): $(srcdir)/testspriteminimal.c $(srcdir)/testutils.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS) @MATHLIB@
teststreaming$(EXE): $(srcdir)/teststreaming.c $(srcdir)/testutils.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS) @MATHLIB@
testtimer$(EXE): $(srcdir)/testtimer.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
testurl$(EXE): $(srcdir)/testurl.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
testver$(EXE): $(srcdir)/testver.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
testviewport$(EXE): $(srcdir)/testviewport.c $(srcdir)/testutils.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
testwm2$(EXE): $(srcdir)/testwm2.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
testyuv$(EXE): $(srcdir)/testyuv.c $(srcdir)/testyuv_cvt.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
torturethread$(EXE): $(srcdir)/torturethread.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
testrendercopyex$(EXE): $(srcdir)/testrendercopyex.c $(srcdir)/testutils.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS) @MATHLIB@
testmessage$(EXE): $(srcdir)/testmessage.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
testdisplayinfo$(EXE): $(srcdir)/testdisplayinfo.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
testqsort$(EXE): $(srcdir)/testqsort.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
testbounds$(EXE): $(srcdir)/testbounds.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
testcustomcursor$(EXE): $(srcdir)/testcustomcursor.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
controllermap$(EXE): $(srcdir)/controllermap.c $(srcdir)/testutils.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
testvulkan$(EXE): $(srcdir)/testvulkan.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
testlocale$(EXE): $(srcdir)/testlocale.c
$(CC) -o $@ $? $(CFLAGS) $(LIBS)
testmouse$(EXE): $(srcdir)/testmouse.c
$(CC) -o $@ $^ $(CFLAGS) $(LIBS)
clean:
rm -f $(TARGETS) *.test
distclean: clean
rm -f Makefile
rm -f config.status config.cache config.log
rm -rf $(srcdir)/autom4te*
TESTS = \
testatomic$(EXE) \
testaudioinfo$(EXE) \
testautomation$(EXE) \
testbounds$(EXE) \
testdisplayinfo$(EXE) \
testerror$(EXE) \
testevdev$(EXE) \
testfilesystem$(EXE) \
testkeys$(EXE) \
testlocale$(EXE) \
testplatform$(EXE) \
testpower$(EXE) \
testqsort$(EXE) \
testsurround$(EXE) \
testthread$(EXE) \
testtimer$(EXE) \
testver$(EXE) \
$(NULL)
check:
@set -e; \
status=0; \
export SDL_AUDIODRIVER=dummy; \
export SDL_VIDEODRIVER=dummy; \
for exe in $(TESTS); do \
echo "$$exe..."; \
if ./"$$exe"; then \
echo "$$exe: OK"; \
else \
echo "$$exe: FAILED: $$?"; \
status=1; \
fi; \
done; \
exit "$$status"
DATA = \
axis.bmp \
button.bmp \
controllermap.bmp \
controllermap_back.bmp \
icon.bmp \
moose.dat \
sample.bmp \
sample.wav \
testgles2_sdf_img_normal.bmp \
testgles2_sdf_img_sdf.bmp \
testyuv.bmp \
unifont-13.0.06.hex \
utf8.txt \
$(NULL)
ifneq ($(srcdir), .)
$(DATA) : %: $(srcdir)/% Makefile
cp $< $@
endif
copydatafiles: $(DATA)
.PHONY : copydatafiles

View File

@ -0,0 +1,19 @@
# Open Watcom makefile to build SDL2 tests for OS/2
# wmake -f Makefile.os2
#
# To error out upon warnings: wmake -f Makefile.os2 ENABLE_WERROR=1
SYSTEM = os2v2
INCPATH = -I"$(%WATCOM)/h/os2" -I"$(%WATCOM)/h"
CFLAGS = -bt=os2 -d0 -q -bm -5s -fp5 -fpi87 -sg -oteanbmier -ei
CFLAGS+= -wx -wcd=303
CFLAGS+= -DHAVE_SIGNAL_H
!ifeq ENABLE_WERROR 1
CFLAGS+= -we
!endif
TNSRCS = testnative.c testnativeos2.c
!include watcom.mif

View File

@ -0,0 +1,21 @@
# Open Watcom makefile to build SDL2 tests for Win32
# wmake -f Makefile.w32
#
# To error out upon warnings: wmake -f Makefile.w32 ENABLE_WERROR=1
SYSTEM = nt
INCPATH = -I"$(%WATCOM)/h/nt" -I"$(%WATCOM)/h" -I"../src/video/khronos"
CFLAGS = -bt=nt -d0 -q -bm -5s -fp5 -fpi87 -sg -oteanbmier -ei
CFLAGS+= -wx -wcd=303
!ifeq ENABLE_WERROR 1
CFLAGS+= -we
!endif
CFLAGS+= -DSDL_MAIN_HANDLED
CFLAGS+= -DHAVE_OPENGL -DHAVE_SIGNAL_H
GLLIBS = opengl32.lib
TNSRCS = testnative.c testnativew32.c
!include watcom.mif

50
vendored/sdl/test/README Normal file
View File

@ -0,0 +1,50 @@
These are test programs for the SDL library:
checkkeys Watch the key events to check the keyboard
loopwave Audio test -- loop playing a WAV file
loopwavequeue Audio test -- loop playing a WAV file with SDL_QueueAudio
testsurround Audio test -- play test tone on each audio channel
testaudioinfo Lists audio device capabilities
testerror Tests multi-threaded error handling
testfile Tests RWops layer
testgl2 A very simple example of using OpenGL with SDL
testiconv Tests international string conversion
testjoystick List joysticks and watch joystick events
testkeys List the available keyboard keys
testloadso Tests the loadable library layer
testlocale Test Locale API
testlock Hacked up test of multi-threading and locking
testmouse Tests mouse coordinates
testmultiaudio Tests using several audio devices
testoverlay2 Tests the overlay flickering/scaling during playback.
testplatform Tests types, endianness and cpu capabilities
testsem Tests SDL's semaphore implementation
testshape Tests shaped windows
testsprite2 Example of fast sprite movement on the screen
testthread Hacked up test of multi-threading
testtimer Test the timer facilities
testver Check the version and dynamic loading and endianness
testwm2 Test window manager -- title, icon, events
torturethread Simple test for thread creation/destruction
controllermap Useful to generate Game Controller API compatible maps
This directory contains sample.wav, which is a sample from Will Provost's
song, The Living Proof:
From the album The Living Proof
Publisher: 5 Guys Named Will
Copyright 1996 Will Provost
You can get a copy of the full song (and album!) from iTunes...
https://itunes.apple.com/us/album/the-living-proof/id4153978
or Amazon...
http://www.amazon.com/The-Living-Proof-Will-Provost/dp/B00004R8RH
Thanks to Will for permitting us to distribute this sample with SDL!

View File

@ -0,0 +1,335 @@
# Configure paths for SDL
# Sam Lantinga 9/21/99
# stolen from Manish Singh
# stolen back from Frank Belew
# stolen from Manish Singh
# Shamelessly stolen from Owen Taylor
dnl AM_PATH_SDL2([MINIMUM-VERSION, [ACTION-IF-FOUND [, ACTION-IF-NOT-FOUND]]])
dnl Test for SDL, and define SDL_CFLAGS and SDL_LIBS
dnl
AC_DEFUN([AM_PATH_SDL2],
[dnl
dnl Get the cflags and libraries from the sdl2-config script
dnl
AC_ARG_WITH(sdl-prefix,[ --with-sdl-prefix=PFX Prefix where SDL is installed (optional)],
sdl_prefix="$withval", sdl_prefix="")
AC_ARG_WITH(sdl-exec-prefix,[ --with-sdl-exec-prefix=PFX Exec prefix where SDL is installed (optional)],
sdl_exec_prefix="$withval", sdl_exec_prefix="")
AC_ARG_ENABLE(sdltest, [ --disable-sdltest Do not try to compile and run a test SDL program],
, enable_sdltest=yes)
min_sdl_version=ifelse([$1], ,2.0.0,$1)
if test "x$sdl_prefix$sdl_exec_prefix" = x ; then
PKG_CHECK_MODULES([SDL], [sdl2 >= $min_sdl_version],
[sdl_pc=yes],
[sdl_pc=no])
else
sdl_pc=no
if test x$sdl_exec_prefix != x ; then
sdl_config_args="$sdl_config_args --exec-prefix=$sdl_exec_prefix"
if test x${SDL2_CONFIG+set} != xset ; then
SDL2_CONFIG=$sdl_exec_prefix/bin/sdl2-config
fi
fi
if test x$sdl_prefix != x ; then
sdl_config_args="$sdl_config_args --prefix=$sdl_prefix"
if test x${SDL2_CONFIG+set} != xset ; then
SDL2_CONFIG=$sdl_prefix/bin/sdl2-config
fi
fi
fi
if test "x$sdl_pc" = xyes ; then
no_sdl=""
SDL2_CONFIG="$PKG_CONFIG sdl2"
else
as_save_PATH="$PATH"
if test "x$prefix" != xNONE && test "$cross_compiling" != yes; then
PATH="$prefix/bin:$prefix/usr/bin:$PATH"
fi
AC_PATH_PROG(SDL2_CONFIG, sdl2-config, no, [$PATH])
PATH="$as_save_PATH"
AC_MSG_CHECKING(for SDL - version >= $min_sdl_version)
no_sdl=""
if test "$SDL2_CONFIG" = "no" ; then
no_sdl=yes
else
SDL_CFLAGS=`$SDL2_CONFIG $sdl_config_args --cflags`
SDL_LIBS=`$SDL2_CONFIG $sdl_config_args --libs`
sdl_major_version=`$SDL2_CONFIG $sdl_config_args --version | \
sed 's/\([[0-9]]*\).\([[0-9]]*\).\([[0-9]]*\)/\1/'`
sdl_minor_version=`$SDL2_CONFIG $sdl_config_args --version | \
sed 's/\([[0-9]]*\).\([[0-9]]*\).\([[0-9]]*\)/\2/'`
sdl_micro_version=`$SDL2_CONFIG $sdl_config_args --version | \
sed 's/\([[0-9]]*\).\([[0-9]]*\).\([[0-9]]*\)/\3/'`
if test "x$enable_sdltest" = "xyes" ; then
ac_save_CFLAGS="$CFLAGS"
ac_save_CXXFLAGS="$CXXFLAGS"
ac_save_LIBS="$LIBS"
CFLAGS="$CFLAGS $SDL_CFLAGS"
CXXFLAGS="$CXXFLAGS $SDL_CFLAGS"
LIBS="$LIBS $SDL_LIBS"
dnl
dnl Now check if the installed SDL is sufficiently new. (Also sanity
dnl checks the results of sdl2-config to some extent
dnl
rm -f conf.sdltest
AC_RUN_IFELSE([AC_LANG_SOURCE([[
#include <stdio.h>
#include <stdlib.h>
#include "SDL.h"
int main (int argc, char *argv[])
{
int major, minor, micro;
FILE *fp = fopen("conf.sdltest", "w");
if (fp) fclose(fp);
if (sscanf("$min_sdl_version", "%d.%d.%d", &major, &minor, &micro) != 3) {
printf("%s, bad version string\n", "$min_sdl_version");
exit(1);
}
if (($sdl_major_version > major) ||
(($sdl_major_version == major) && ($sdl_minor_version > minor)) ||
(($sdl_major_version == major) && ($sdl_minor_version == minor) && ($sdl_micro_version >= micro)))
{
return 0;
}
else
{
printf("\n*** 'sdl2-config --version' returned %d.%d.%d, but the minimum version\n", $sdl_major_version, $sdl_minor_version, $sdl_micro_version);
printf("*** of SDL required is %d.%d.%d. If sdl2-config is correct, then it is\n", major, minor, micro);
printf("*** best to upgrade to the required version.\n");
printf("*** If sdl2-config was wrong, set the environment variable SDL2_CONFIG\n");
printf("*** to point to the correct copy of sdl2-config, and remove the file\n");
printf("*** config.cache before re-running configure\n");
return 1;
}
}
]])], [], [no_sdl=yes], [echo $ac_n "cross compiling; assumed OK... $ac_c"])
CFLAGS="$ac_save_CFLAGS"
CXXFLAGS="$ac_save_CXXFLAGS"
LIBS="$ac_save_LIBS"
fi
fi
if test "x$no_sdl" = x ; then
AC_MSG_RESULT(yes)
else
AC_MSG_RESULT(no)
fi
fi
if test "x$no_sdl" = x ; then
ifelse([$2], , :, [$2])
else
if test "$SDL2_CONFIG" = "no" ; then
echo "*** The sdl2-config script installed by SDL could not be found"
echo "*** If SDL was installed in PREFIX, make sure PREFIX/bin is in"
echo "*** your path, or set the SDL2_CONFIG environment variable to the"
echo "*** full path to sdl2-config."
else
if test -f conf.sdltest ; then
:
else
echo "*** Could not run SDL test program, checking why..."
CFLAGS="$CFLAGS $SDL_CFLAGS"
CXXFLAGS="$CXXFLAGS $SDL_CFLAGS"
LIBS="$LIBS $SDL_LIBS"
AC_LINK_IFELSE([AC_LANG_PROGRAM([[
#include <stdio.h>
#include "SDL.h"
int main(int argc, char *argv[])
{ return 0; }
#undef main
#define main K_and_R_C_main
]], [[ return 0; ]])],
[ echo "*** The test program compiled, but did not run. This usually means"
echo "*** that the run-time linker is not finding SDL or finding the wrong"
echo "*** version of SDL. If it is not finding SDL, you'll need to set your"
echo "*** LD_LIBRARY_PATH environment variable, or edit /etc/ld.so.conf to point"
echo "*** to the installed location Also, make sure you have run ldconfig if that"
echo "*** is required on your system"
echo "***"
echo "*** If you have an old version installed, it is best to remove it, although"
echo "*** you may also be able to get things to work by modifying LD_LIBRARY_PATH"],
[ echo "*** The test program failed to compile or link. See the file config.log for the"
echo "*** exact error that occured. This usually means SDL was incorrectly installed"
echo "*** or that you have moved SDL since it was installed. In the latter case, you"
echo "*** may want to edit the sdl2-config script: $SDL2_CONFIG" ])
CFLAGS="$ac_save_CFLAGS"
CXXFLAGS="$ac_save_CXXFLAGS"
LIBS="$ac_save_LIBS"
fi
fi
SDL_CFLAGS=""
SDL_LIBS=""
ifelse([$3], , :, [$3])
fi
AC_SUBST(SDL_CFLAGS)
AC_SUBST(SDL_LIBS)
rm -f conf.sdltest
])
# pkg.m4 - Macros to locate and utilise pkg-config. -*- Autoconf -*-
# serial 1 (pkg-config-0.24)
#
# Copyright © 2004 Scott James Remnant <scott@netsplit.com>.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
# As a special exception to the GNU General Public License, if you
# distribute this file as part of a program that contains a
# configuration script generated by Autoconf, you may include it under
# the same distribution terms that you use for the rest of that program.
# PKG_PROG_PKG_CONFIG([MIN-VERSION])
# ----------------------------------
AC_DEFUN([PKG_PROG_PKG_CONFIG],
[m4_pattern_forbid([^_?PKG_[A-Z_]+$])
m4_pattern_allow([^PKG_CONFIG(_PATH|_LIBDIR)?$])
AC_ARG_VAR([PKG_CONFIG], [path to pkg-config utility])
AC_ARG_VAR([PKG_CONFIG_PATH], [directories to add to pkg-config's search path])
AC_ARG_VAR([PKG_CONFIG_LIBDIR], [path overriding pkg-config's built-in search path])
if test "x$ac_cv_env_PKG_CONFIG_set" != "xset"; then
AC_PATH_TOOL([PKG_CONFIG], [pkg-config])
fi
if test -n "$PKG_CONFIG"; then
_pkg_min_version=m4_default([$1], [0.9.0])
AC_MSG_CHECKING([pkg-config is at least version $_pkg_min_version])
if $PKG_CONFIG --atleast-pkgconfig-version $_pkg_min_version; then
AC_MSG_RESULT([yes])
else
AC_MSG_RESULT([no])
PKG_CONFIG=""
fi
fi[]dnl
])# PKG_PROG_PKG_CONFIG
# PKG_CHECK_EXISTS(MODULES, [ACTION-IF-FOUND], [ACTION-IF-NOT-FOUND])
#
# Check to see whether a particular set of modules exists. Similar
# to PKG_CHECK_MODULES(), but does not set variables or print errors.
#
# Please remember that m4 expands AC_REQUIRE([PKG_PROG_PKG_CONFIG])
# only at the first occurence in configure.ac, so if the first place
# it's called might be skipped (such as if it is within an "if", you
# have to call PKG_CHECK_EXISTS manually
# --------------------------------------------------------------
AC_DEFUN([PKG_CHECK_EXISTS],
[AC_REQUIRE([PKG_PROG_PKG_CONFIG])dnl
if test -n "$PKG_CONFIG" && \
AC_RUN_LOG([$PKG_CONFIG --exists --print-errors "$1"]); then
m4_default([$2], [:])
m4_ifvaln([$3], [else
$3])dnl
fi])
# _PKG_CONFIG([VARIABLE], [COMMAND], [MODULES])
# ---------------------------------------------
m4_define([_PKG_CONFIG],
[if test -n "$$1"; then
pkg_cv_[]$1="$$1"
elif test -n "$PKG_CONFIG"; then
PKG_CHECK_EXISTS([$3],
[pkg_cv_[]$1=`$PKG_CONFIG --[]$2 "$3" 2>/dev/null`],
[pkg_failed=yes])
else
pkg_failed=untried
fi[]dnl
])# _PKG_CONFIG
# _PKG_SHORT_ERRORS_SUPPORTED
# -----------------------------
AC_DEFUN([_PKG_SHORT_ERRORS_SUPPORTED],
[AC_REQUIRE([PKG_PROG_PKG_CONFIG])
if $PKG_CONFIG --atleast-pkgconfig-version 0.20; then
_pkg_short_errors_supported=yes
else
_pkg_short_errors_supported=no
fi[]dnl
])# _PKG_SHORT_ERRORS_SUPPORTED
# PKG_CHECK_MODULES(VARIABLE-PREFIX, MODULES, [ACTION-IF-FOUND],
# [ACTION-IF-NOT-FOUND])
#
#
# Note that if there is a possibility the first call to
# PKG_CHECK_MODULES might not happen, you should be sure to include an
# explicit call to PKG_PROG_PKG_CONFIG in your configure.ac
#
#
# --------------------------------------------------------------
AC_DEFUN([PKG_CHECK_MODULES],
[AC_REQUIRE([PKG_PROG_PKG_CONFIG])dnl
AC_ARG_VAR([$1][_CFLAGS], [C compiler flags for $1, overriding pkg-config])dnl
AC_ARG_VAR([$1][_LIBS], [linker flags for $1, overriding pkg-config])dnl
pkg_failed=no
AC_MSG_CHECKING([for $2])
_PKG_CONFIG([$1][_CFLAGS], [cflags], [$2])
_PKG_CONFIG([$1][_LIBS], [libs], [$2])
m4_define([_PKG_TEXT], [Alternatively, you may set the environment variables $1[]_CFLAGS
and $1[]_LIBS to avoid the need to call pkg-config.
See the pkg-config man page for more details.])
if test $pkg_failed = yes; then
AC_MSG_RESULT([no])
_PKG_SHORT_ERRORS_SUPPORTED
if test $_pkg_short_errors_supported = yes; then
$1[]_PKG_ERRORS=`$PKG_CONFIG --short-errors --print-errors "$2" 2>&1`
else
$1[]_PKG_ERRORS=`$PKG_CONFIG --print-errors "$2" 2>&1`
fi
# Put the nasty error message in config.log where it belongs
echo "$$1[]_PKG_ERRORS" >&AS_MESSAGE_LOG_FD
m4_default([$4], [AC_MSG_ERROR(
[Package requirements ($2) were not met:
$$1_PKG_ERRORS
Consider adjusting the PKG_CONFIG_PATH environment variable if you
installed software in a non-standard prefix.
_PKG_TEXT])[]dnl
])
elif test $pkg_failed = untried; then
AC_MSG_RESULT([no])
m4_default([$4], [AC_MSG_FAILURE(
[The pkg-config script could not be found or is too old. Make sure it
is in your PATH or set the PKG_CONFIG environment variable to the full
path to pkg-config.
_PKG_TEXT
To get pkg-config, see <http://pkg-config.freedesktop.org/>.])[]dnl
])
else
$1[]_CFLAGS=$pkg_cv_[]$1[]_CFLAGS
$1[]_LIBS=$pkg_cv_[]$1[]_LIBS
AC_MSG_RESULT([yes])
$3
fi[]dnl
])# PKG_CHECK_MODULES

View File

@ -0,0 +1,9 @@
#!/bin/sh
set -e
cp acinclude.m4 aclocal.m4
"${AUTOCONF:-autoconf}"
rm aclocal.m4
rm -rf autom4te.cache

BIN
vendored/sdl/test/axis.bmp Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.7 KiB

View File

@ -0,0 +1,313 @@
/*
Copyright (C) 1997-2024 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely.
*/
/* Simple program: Loop, watching keystrokes
Note that you need to call SDL_PollEvent() or SDL_WaitEvent() to
pump the event loop and catch keystrokes.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef __EMSCRIPTEN__
#include <emscripten/emscripten.h>
#endif
#include "SDL.h"
#include "SDL_test_font.h"
static SDL_Window *window;
static SDL_Renderer *renderer;
static SDLTest_TextWindow *textwin;
static int done;
/* Call this instead of exit(), so we can clean up SDL: atexit() is evil. */
static void
quit(int rc)
{
SDL_Quit();
exit(rc);
}
static void
print_string(char **text, size_t *maxlen, const char *fmt, ...)
{
int len;
va_list ap;
va_start(ap, fmt);
len = SDL_vsnprintf(*text, *maxlen, fmt, ap);
if (len > 0) {
*text += len;
if (((size_t)len) < *maxlen) {
*maxlen -= (size_t)len;
} else {
*maxlen = 0;
}
}
va_end(ap);
}
static void
print_modifiers(char **text, size_t *maxlen)
{
int mod;
print_string(text, maxlen, " modifiers:");
mod = SDL_GetModState();
if (!mod) {
print_string(text, maxlen, " (none)");
return;
}
if (mod & KMOD_LSHIFT) {
print_string(text, maxlen, " LSHIFT");
}
if (mod & KMOD_RSHIFT) {
print_string(text, maxlen, " RSHIFT");
}
if (mod & KMOD_LCTRL) {
print_string(text, maxlen, " LCTRL");
}
if (mod & KMOD_RCTRL) {
print_string(text, maxlen, " RCTRL");
}
if (mod & KMOD_LALT) {
print_string(text, maxlen, " LALT");
}
if (mod & KMOD_RALT) {
print_string(text, maxlen, " RALT");
}
if (mod & KMOD_LGUI) {
print_string(text, maxlen, " LGUI");
}
if (mod & KMOD_RGUI) {
print_string(text, maxlen, " RGUI");
}
if (mod & KMOD_NUM) {
print_string(text, maxlen, " NUM");
}
if (mod & KMOD_CAPS) {
print_string(text, maxlen, " CAPS");
}
if (mod & KMOD_MODE) {
print_string(text, maxlen, " MODE");
}
if (mod & KMOD_SCROLL) {
print_string(text, maxlen, " SCROLL");
}
}
static void
PrintModifierState()
{
char message[512];
char *spot;
size_t left;
spot = message;
left = sizeof(message);
print_modifiers(&spot, &left);
SDL_Log("Initial state:%s\n", message);
}
static void
PrintKey(SDL_Keysym *sym, SDL_bool pressed, SDL_bool repeat)
{
char message[512];
char *spot;
size_t left;
spot = message;
left = sizeof(message);
/* Print the keycode, name and state */
if (sym->sym) {
print_string(&spot, &left,
"Key %s: scancode %d = %s, keycode 0x%08X = %s ",
pressed ? "pressed " : "released",
sym->scancode,
SDL_GetScancodeName(sym->scancode),
sym->sym, SDL_GetKeyName(sym->sym));
} else {
print_string(&spot, &left,
"Unknown Key (scancode %d = %s) %s ",
sym->scancode,
SDL_GetScancodeName(sym->scancode),
pressed ? "pressed " : "released");
}
print_modifiers(&spot, &left);
if (repeat) {
print_string(&spot, &left, " (repeat)");
}
SDL_Log("%s\n", message);
}
static void
PrintText(const char *eventtype, const char *text)
{
const char *spot;
char expanded[1024];
expanded[0] = '\0';
for (spot = text; *spot; ++spot) {
size_t length = SDL_strlen(expanded);
(void)SDL_snprintf(expanded + length, sizeof(expanded) - length, "\\x%.2x", (unsigned char)*spot);
}
SDL_Log("%s Text (%s): \"%s%s\"\n", eventtype, expanded, *text == '"' ? "\\" : "", text);
}
void loop()
{
SDL_Event event;
/* Check for events */
/*SDL_WaitEvent(&event); emscripten does not like waiting*/
while (SDL_PollEvent(&event)) {
switch (event.type) {
case SDL_KEYDOWN:
case SDL_KEYUP:
PrintKey(&event.key.keysym, (event.key.state == SDL_PRESSED) ? SDL_TRUE : SDL_FALSE, (event.key.repeat) ? SDL_TRUE : SDL_FALSE);
if (event.type == SDL_KEYDOWN) {
switch (event.key.keysym.sym) {
case SDLK_BACKSPACE:
SDLTest_TextWindowAddText(textwin, "\b");
break;
case SDLK_RETURN:
SDLTest_TextWindowAddText(textwin, "\n");
break;
default:
break;
}
}
break;
case SDL_TEXTEDITING:
PrintText("EDIT", event.edit.text);
break;
case SDL_TEXTEDITING_EXT:
PrintText("EDIT_EXT", event.editExt.text);
SDL_free(event.editExt.text);
break;
case SDL_TEXTINPUT:
PrintText("INPUT", event.text.text);
SDLTest_TextWindowAddText(textwin, "%s", event.text.text);
break;
case SDL_FINGERDOWN:
if (SDL_IsTextInputActive()) {
SDL_Log("Stopping text input\n");
SDL_StopTextInput();
} else {
SDL_Log("Starting text input\n");
SDL_StartTextInput();
}
break;
case SDL_MOUSEBUTTONDOWN:
/* Left button quits the app, other buttons toggles text input */
if (event.button.button == SDL_BUTTON_LEFT) {
done = 1;
} else {
if (SDL_IsTextInputActive()) {
SDL_Log("Stopping text input\n");
SDL_StopTextInput();
} else {
SDL_Log("Starting text input\n");
SDL_StartTextInput();
}
}
break;
case SDL_QUIT:
done = 1;
break;
default:
break;
}
}
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
SDL_RenderClear(renderer);
SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);
SDLTest_TextWindowDisplay(textwin, renderer);
SDL_RenderPresent(renderer);
/* Slow down framerate */
SDL_Delay(100);
#ifdef __EMSCRIPTEN__
if (done) {
emscripten_cancel_main_loop();
}
#endif
}
int main(int argc, char *argv[])
{
/* Enable standard application logging */
SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);
/* Disable mouse emulation */
SDL_SetHint(SDL_HINT_TOUCH_MOUSE_EVENTS, "0");
/* Enable extended text editing events */
SDL_SetHint(SDL_HINT_IME_SUPPORT_EXTENDED_TEXT, "1");
/* Initialize SDL */
if (SDL_Init(SDL_INIT_VIDEO) < 0) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't initialize SDL: %s\n", SDL_GetError());
return 1;
}
/* Set 640x480 video mode */
window = SDL_CreateWindow("CheckKeys Test",
SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
640, 480, 0);
if (!window) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't create 640x480 window: %s\n",
SDL_GetError());
quit(2);
}
renderer = SDL_CreateRenderer(window, -1, 0);
if (!renderer) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't create renderer: %s\n",
SDL_GetError());
quit(2);
}
textwin = SDLTest_TextWindowCreate(0, 0, 640, 480);
#ifdef __IPHONEOS__
/* Creating the context creates the view, which we need to show keyboard */
SDL_GL_CreateContext(window);
#endif
SDL_StartTextInput();
/* Print initial modifier state */
SDL_PumpEvents();
PrintModifierState();
/* Watch keystrokes */
done = 0;
#ifdef __EMSCRIPTEN__
emscripten_set_main_loop(loop, 0, 1);
#else
while (!done) {
loop();
}
#endif
SDL_Quit();
return 0;
}
/* vi: set ts=4 sw=4 expandtab: */

View File

@ -0,0 +1,298 @@
/*
Copyright (C) 1997-2024 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely.
*/
/* Simple program: Loop, watching keystrokes
Note that you need to call SDL_PollEvent() or SDL_WaitEvent() to
pump the event loop and catch keystrokes.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef __EMSCRIPTEN__
#include <emscripten/emscripten.h>
#endif
#include "SDL.h"
int done;
/* Call this instead of exit(), so we can clean up SDL: atexit() is evil. */
static void
quit(int rc)
{
SDL_Quit();
exit(rc);
}
static void
print_string(char **text, size_t *maxlen, const char *fmt, ...)
{
int len;
va_list ap;
va_start(ap, fmt);
len = SDL_vsnprintf(*text, *maxlen, fmt, ap);
if (len > 0) {
*text += len;
if (((size_t)len) < *maxlen) {
*maxlen -= (size_t)len;
} else {
*maxlen = 0;
}
}
va_end(ap);
}
static void
print_modifiers(char **text, size_t *maxlen)
{
int mod;
print_string(text, maxlen, " modifiers:");
mod = SDL_GetModState();
if (!mod) {
print_string(text, maxlen, " (none)");
return;
}
if (mod & KMOD_LSHIFT) {
print_string(text, maxlen, " LSHIFT");
}
if (mod & KMOD_RSHIFT) {
print_string(text, maxlen, " RSHIFT");
}
if (mod & KMOD_LCTRL) {
print_string(text, maxlen, " LCTRL");
}
if (mod & KMOD_RCTRL) {
print_string(text, maxlen, " RCTRL");
}
if (mod & KMOD_LALT) {
print_string(text, maxlen, " LALT");
}
if (mod & KMOD_RALT) {
print_string(text, maxlen, " RALT");
}
if (mod & KMOD_LGUI) {
print_string(text, maxlen, " LGUI");
}
if (mod & KMOD_RGUI) {
print_string(text, maxlen, " RGUI");
}
if (mod & KMOD_NUM) {
print_string(text, maxlen, " NUM");
}
if (mod & KMOD_CAPS) {
print_string(text, maxlen, " CAPS");
}
if (mod & KMOD_MODE) {
print_string(text, maxlen, " MODE");
}
if (mod & KMOD_SCROLL) {
print_string(text, maxlen, " SCROLL");
}
}
static void
PrintModifierState()
{
char message[512];
char *spot;
size_t left;
spot = message;
left = sizeof(message);
print_modifiers(&spot, &left);
SDL_Log("Initial state:%s\n", message);
}
static void
PrintKey(SDL_Keysym *sym, SDL_bool pressed, SDL_bool repeat)
{
char message[512];
char *spot;
size_t left;
spot = message;
left = sizeof(message);
/* Print the keycode, name and state */
if (sym->sym) {
print_string(&spot, &left,
"Key %s: scancode %d = %s, keycode 0x%08X = %s ",
pressed ? "pressed " : "released",
sym->scancode,
SDL_GetScancodeName(sym->scancode),
sym->sym, SDL_GetKeyName(sym->sym));
} else {
print_string(&spot, &left,
"Unknown Key (scancode %d = %s) %s ",
sym->scancode,
SDL_GetScancodeName(sym->scancode),
pressed ? "pressed " : "released");
}
print_modifiers(&spot, &left);
if (repeat) {
print_string(&spot, &left, " (repeat)");
}
SDL_Log("%s\n", message);
}
static void
PrintText(const char *eventtype, const char *text)
{
const char *spot;
char expanded[1024];
expanded[0] = '\0';
for (spot = text; *spot; ++spot) {
size_t length = SDL_strlen(expanded);
(void)SDL_snprintf(expanded + length, sizeof(expanded) - length, "\\x%.2x", (unsigned char)*spot);
}
SDL_Log("%s Text (%s): \"%s%s\"\n", eventtype, expanded, *text == '"' ? "\\" : "", text);
}
void loop()
{
SDL_Event event;
/* Check for events */
/*SDL_WaitEvent(&event); emscripten does not like waiting*/
(void)fprintf(stderr, "starting loop\n");
(void)fflush(stderr);
// while (SDL_PollEvent(&event)) {
while (!done && SDL_WaitEvent(&event)) {
SDL_Log("Got event type: %" SDL_PRIu32 "\n", event.type);
switch (event.type) {
case SDL_KEYDOWN:
case SDL_KEYUP:
PrintKey(&event.key.keysym, (event.key.state == SDL_PRESSED) ? SDL_TRUE : SDL_FALSE, (event.key.repeat) ? SDL_TRUE : SDL_FALSE);
break;
case SDL_TEXTEDITING:
PrintText("EDIT", event.text.text);
break;
case SDL_TEXTINPUT:
PrintText("INPUT", event.text.text);
break;
case SDL_MOUSEBUTTONDOWN:
/* Left button quits the app, other buttons toggles text input */
(void)fprintf(stderr, "mouse button down button: %d (LEFT=%d)\n", event.button.button, SDL_BUTTON_LEFT);
(void)fflush(stderr);
if (event.button.button == SDL_BUTTON_LEFT) {
done = 1;
} else {
if (SDL_IsTextInputActive()) {
SDL_Log("Stopping text input\n");
SDL_StopTextInput();
} else {
SDL_Log("Starting text input\n");
SDL_StartTextInput();
}
}
break;
case SDL_QUIT:
done = 1;
break;
default:
break;
}
(void)fprintf(stderr, "waiting new event\n");
(void)fflush(stderr);
}
(void)fprintf(stderr, "exiting event loop\n");
(void)fflush(stderr);
#ifdef __EMSCRIPTEN__
if (done) {
emscripten_cancel_main_loop();
}
#endif
}
/* Very simple thread - counts 0 to 9 delaying 50ms between increments */
static int SDLCALL ping_thread(void *ptr)
{
int cnt;
SDL_Event sdlevent;
SDL_memset(&sdlevent, 0, sizeof(SDL_Event));
for (cnt = 0; cnt < 10; ++cnt) {
(void)fprintf(stderr, "sending event (%d/%d) from thread.\n", cnt + 1, 10);
(void)fflush(stderr);
sdlevent.type = SDL_KEYDOWN;
sdlevent.key.keysym.sym = SDLK_1;
SDL_PushEvent(&sdlevent);
SDL_Delay(1000 + rand() % 1000);
}
return cnt;
}
int main(int argc, char *argv[])
{
SDL_Window *window;
SDL_Renderer *renderer;
SDL_Thread *thread;
/* Enable standard application logging */
SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);
/* Initialize SDL */
if (SDL_Init(SDL_INIT_VIDEO) < 0) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't initialize SDL: %s\n", SDL_GetError());
return 1;
}
/* Set 640x480 video mode */
window = SDL_CreateWindow("CheckKeys Test",
SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
640, 480, 0);
if (!window) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't create 640x480 window: %s\n",
SDL_GetError());
quit(2);
}
/* On wayland, no window will actually show until something has
actually been displayed.
*/
renderer = SDL_CreateRenderer(window, -1, 0);
SDL_RenderPresent(renderer);
#ifdef __IPHONEOS__
/* Creating the context creates the view, which we need to show keyboard */
SDL_GL_CreateContext(window);
#endif
SDL_StartTextInput();
/* Print initial modifier state */
SDL_PumpEvents();
PrintModifierState();
/* Watch keystrokes */
done = 0;
thread = SDL_CreateThread(ping_thread, "PingThread", NULL);
#ifdef __EMSCRIPTEN__
emscripten_set_main_loop(loop, 0, 1);
#else
while (!done) {
loop();
}
#endif
SDL_WaitThread(thread, NULL);
SDL_Quit();
return 0;
}
/* vi: set ts=4 sw=4 expandtab: */

6106
vendored/sdl/test/configure vendored Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,289 @@
dnl Process this file with autoconf to produce a configure script.
AC_INIT
AC_CONFIG_SRCDIR([loopwave.c])
dnl Detect the canonical build and host environments
AC_CONFIG_AUX_DIR([../build-scripts])
AC_CANONICAL_HOST
dnl Check for tools
AC_PROG_CC
dnl Check for compiler environment
AC_C_CONST
dnl We only care about this for building testnative at the moment, so these
dnl values shouldn't be considered absolute truth.
dnl (Haiku, for example, sets none of these.)
ISUNIX="false"
ISWINDOWS="false"
ISMACOSX="false"
ISOS2="false"
dnl Figure out which math library to use
case "$host" in
*-*-cygwin* | *-*-mingw*)
ISWINDOWS="true"
EXE=".exe"
MATHLIB=""
SYS_GL_LIBS="-lopengl32"
;;
*-*-haiku*)
EXE=""
MATHLIB=""
SYS_GL_LIBS="-lGL"
;;
*-*-darwin*)
ISMACOSX="true"
EXE=""
MATHLIB=""
SYS_GL_LIBS="-Wl,-framework,OpenGL"
;;
*-*-aix*)
ISUNIX="true"
EXE=""
if test x$ac_cv_c_compiler_gnu = xyes; then
CFLAGS="-mthreads"
fi
SYS_GL_LIBS=""
;;
*-*-mint*)
EXE=""
MATHLIB=""
AC_PATH_PROG(OSMESA_CONFIG, osmesa-config, no)
if test "x$OSMESA_CONFIG" = "xyes"; then
OSMESA_CFLAGS=`$OSMESA_CONFIG --cflags`
OSMESA_LIBS=`$OSMESA_CONFIG --libs`
CFLAGS="$CFLAGS $OSMESA_CFLAGS"
SYS_GL_LIBS="$OSMESA_LIBS"
else
SYS_GL_LIBS="-lOSMesa"
fi
;;
*-*-qnx*)
EXE=""
MATHLIB=""
SYS_GL_LIBS="-lGLES_CM"
;;
*-*-emscripten*)
dnl This should really be .js, but we need to specify extra flags when compiling to js
EXE=".bc"
MATHLIB=""
SYS_GL_LIBS=""
;;
*-*-riscos*)
EXE=",e1f"
MATHLIB=""
SYS_GL_LIBS=""
;;
*-*-os2*)
ISOS2="true"
EXE=".exe"
MATHLIB=""
SYS_GL_LIBS=""
;;
*)
dnl Oh well, call it Unix...
ISUNIX="true"
EXE=""
MATHLIB="-lm"
dnl Use the new libOpenGL if present.
AC_CHECK_LIB(OpenGL, glBegin,
[SYS_GL_LIBS="-lOpenGL"],[SYS_GL_LIBS="-lGL"])
;;
esac
AC_SUBST(EXE)
AC_SUBST(MATHLIB)
AC_SUBST(ISMACOSX)
AC_SUBST(ISWINDOWS)
AC_SUBST(ISUNIX)
AC_SUBST(ISOS2)
dnl Check for SDL
SDL_VERSION=2.0.18
AM_PATH_SDL2($SDL_VERSION,
:,
AC_MSG_ERROR([*** SDL version $SDL_VERSION not found!])
)
CFLAGS="$CFLAGS $SDL_CFLAGS"
LIBS="$LIBS -lSDL2_test $SDL_LIBS"
dnl Check for X11 path, needed for OpenGL on some systems
AC_PATH_X
if test x$have_x = xyes; then
if test x$ac_x_includes = xno || test "x$ac_x_includes" = xNone || test "x$ac_x_includes" = x; then
:
else
CFLAGS="$CFLAGS -I$ac_x_includes"
fi
if test x$ac_x_libraries = xno || test "x$ac_x_libraries" = xNone; then
:
else
if test "x$ac_x_libraries" = x; then
XPATH=""
XLIB="-lX11"
else
XPATH="-L$ac_x_libraries"
XLIB="-L$ac_x_libraries -lX11"
fi
fi
fi
dnl Check for OpenGL
AC_MSG_CHECKING(for OpenGL support)
have_opengl=no
AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[
#include "SDL_opengl.h"
#ifndef SDL_VIDEO_OPENGL
#error SDL_VIDEO_OPENGL
#endif
]],[])], [have_opengl=yes],[])
AC_MSG_RESULT($have_opengl)
dnl Check for OpenGL ES
AC_MSG_CHECKING(for OpenGL ES support)
have_opengles=no
AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[
#include "SDL_opengles.h"
#ifndef SDL_VIDEO_OPENGL_ES
#error SDL_VIDEO_OPENGL_ES
#endif
]],[])] ,[have_opengles=yes],[])
AC_MSG_RESULT($have_opengles)
dnl Check for OpenGL ES2
AC_MSG_CHECKING(for OpenGL ES2 support)
have_opengles2=no
AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[
#include "SDL_opengles2.h"
#ifndef SDL_VIDEO_OPENGL_ES2
#error SDL_VIDEO_OPENGL_ES2
#endif
]],[])], [have_opengles2=yes],[])
AC_MSG_RESULT($have_opengles2)
GLLIB=""
GLESLIB=""
GLES2LIB=""
OPENGLES1_TARGETS="UNUSED"
OPENGLES2_TARGETS="UNUSED"
OPENGL_TARGETS="UNUSED"
if test x$have_opengles = xyes; then
CFLAGS="$CFLAGS -DHAVE_OPENGLES"
GLESLIB="$XPATH -lGLESv1_CM"
OPENGLES1_TARGETS="TARGETS"
fi
if test x$have_opengles2 = xyes; then
CFLAGS="$CFLAGS -DHAVE_OPENGLES2"
#GLES2LIB="$XPATH -lGLESv2"
OPENGLES2_TARGETS="TARGETS"
fi
if test x$have_opengl = xyes; then
CFLAGS="$CFLAGS -DHAVE_OPENGL"
GLLIB="$XPATH $SYS_GL_LIBS"
OPENGL_TARGETS="TARGETS"
fi
AC_MSG_CHECKING(for GCC -Wformat)
have_wformat=no
save_CFLAGS="$CFLAGS"
CFLAGS="$save_CFLAGS -Wformat"
AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[int x = 0;]],[])],
[have_wformat=yes], [])
AC_MSG_RESULT($have_wformat)
CFLAGS="$save_CFLAGS"
if test x$have_wformat = xyes; then
CFLAGS="$CFLAGS -DHAVE_WFORMAT"
fi
AC_MSG_CHECKING(for GCC -Wformat-overflow)
have_wformat_overflow=no
save_CFLAGS="$CFLAGS"
CFLAGS="$save_CFLAGS -Wformat-overflow"
AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[int x = 0;]],[])],
[have_wformat_overflow=yes], [])
AC_MSG_RESULT($have_wformat_overflow)
CFLAGS="$save_CFLAGS"
if test x$have_wformat_overflow = xyes; then
CFLAGS="$CFLAGS -DHAVE_WFORMAT_OVERFLOW"
fi
AC_MSG_CHECKING(for GCC -Wformat-extra-args)
have_wformat_extra_args=no
save_CFLAGS="$CFLAGS"
CFLAGS="$save_CFLAGS -Wformat-extra-args"
AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[int x = 0;]],[])],
[have_wformat_extra_args=yes], [])
AC_MSG_RESULT($have_wformat_extra_args)
CFLAGS="$save_CFLAGS"
if test x$have_wformat_extra_args = xyes; then
CFLAGS="$CFLAGS -DHAVE_WFORMAT_EXTRA_ARGS"
fi
AC_ARG_ENABLE(werror,
[AS_HELP_STRING([--enable-werror], [treat warnings as errors [default=no]])],
enable_werror=$enableval, enable_werror=no)
if test x$enable_werror = xyes; then
AC_MSG_CHECKING(for GCC -Werror option)
have_gcc_werror=no
save_CFLAGS="$CFLAGS"
CFLAGS="$save_CFLAGS -Werror"
AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[int x = 0;]],[])],
[have_gcc_werror=yes], [])
AC_MSG_RESULT($have_gcc_werror)
CFLAGS="$save_CFLAGS"
if test x$have_gcc_werror = xyes; then
CFLAGS="$CFLAGS -Werror"
fi
fi
case "$host" in
*-ios-*|*-*-darwin* )
AC_MSG_CHECKING(for GCC -Wno-error=deprecated-declarations option)
have_gcc_wno_error_deprecated_declarations=no
save_CFLAGS="$CFLAGS"
CFLAGS="$save_CFLAGS -Wno-error=deprecated-declarations"
AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[
int x = 0;
]],[])], [have_gcc_wno_error_deprecated_declarations=yes],[])
AC_MSG_RESULT($have_gcc_werror)
CFLAGS="$save_CFLAGS"
if test x$have_gcc_wno_error_deprecated_declarations = xyes; then
EXTRA_CFLAGS="$EXTRA_CFLAGS -Wno-error=deprecated-declarations"
fi
;;
esac
AC_SUBST(OPENGLES1_TARGETS)
AC_SUBST(OPENGLES2_TARGETS)
AC_SUBST(OPENGL_TARGETS)
AC_SUBST(GLLIB)
AC_SUBST(GLESLIB)
AC_SUBST(GLES2LIB)
AC_SUBST(XLIB)
dnl Check for SDL_ttf
AC_CHECK_LIB(SDL2_ttf, TTF_Init, have_SDL_ttf=yes)
if test x$have_SDL_ttf = xyes; then
CFLAGS="$CFLAGS -DHAVE_SDL_TTF"
SDL_TTF_LIB="-lSDL2_ttf"
fi
AC_SUBST(SDL_TTF_LIB)
dnl Really, SDL2_test should be linking against libunwind (if it found
dnl libunwind.h when configured), but SDL2_test is a static library, so
dnl there's no way for it to link against it. We could make SDL2 depend on
dnl it, but we don't want all SDL2 build to suddenly gain an extra dependency,
dnl so just assume that if it's here now, SDL2_test was probably built with it.
PKG_CHECK_MODULES(LIBUNWIND, libunwind, have_libunwind=yes, have_libunwind=no)
if test x$have_libunwind = xyes ; then
LIBS="$LIBS $LIBUNWIND_LIBS"
fi
dnl Finally create all the generated files
AC_CONFIG_FILES([Makefile])
AC_OUTPUT

Binary file not shown.

After

Width:  |  Height:  |  Size: 160 KiB

View File

@ -0,0 +1,821 @@
/*
Copyright (C) 1997-2024 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely.
*/
/* Game controller mapping generator */
/* Gabriel Jacobo <gabomdq@gmail.com> */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "SDL.h"
#include "testutils.h"
#ifndef SDL_JOYSTICK_DISABLED
/* Define this for verbose output while mapping controllers */
#define DEBUG_CONTROLLERMAP
#define SCREEN_WIDTH 512
#define SCREEN_HEIGHT 320
enum marker_type
{
MARKER_BUTTON,
MARKER_AXIS,
};
enum
{
SDL_CONTROLLER_BINDING_AXIS_LEFTX_NEGATIVE,
SDL_CONTROLLER_BINDING_AXIS_LEFTX_POSITIVE,
SDL_CONTROLLER_BINDING_AXIS_LEFTY_NEGATIVE,
SDL_CONTROLLER_BINDING_AXIS_LEFTY_POSITIVE,
SDL_CONTROLLER_BINDING_AXIS_RIGHTX_NEGATIVE,
SDL_CONTROLLER_BINDING_AXIS_RIGHTX_POSITIVE,
SDL_CONTROLLER_BINDING_AXIS_RIGHTY_NEGATIVE,
SDL_CONTROLLER_BINDING_AXIS_RIGHTY_POSITIVE,
SDL_CONTROLLER_BINDING_AXIS_TRIGGERLEFT,
SDL_CONTROLLER_BINDING_AXIS_TRIGGERRIGHT,
SDL_CONTROLLER_BINDING_AXIS_MAX,
};
#define BINDING_COUNT (SDL_CONTROLLER_BUTTON_MAX + SDL_CONTROLLER_BINDING_AXIS_MAX)
static struct
{
int x, y;
double angle;
enum marker_type marker;
} s_arrBindingDisplay[] = {
{ 387, 167, 0.0, MARKER_BUTTON }, /* SDL_CONTROLLER_BUTTON_A */
{ 431, 132, 0.0, MARKER_BUTTON }, /* SDL_CONTROLLER_BUTTON_B */
{ 342, 132, 0.0, MARKER_BUTTON }, /* SDL_CONTROLLER_BUTTON_X */
{ 389, 101, 0.0, MARKER_BUTTON }, /* SDL_CONTROLLER_BUTTON_Y */
{ 174, 132, 0.0, MARKER_BUTTON }, /* SDL_CONTROLLER_BUTTON_BACK */
{ 232, 128, 0.0, MARKER_BUTTON }, /* SDL_CONTROLLER_BUTTON_GUIDE */
{ 289, 132, 0.0, MARKER_BUTTON }, /* SDL_CONTROLLER_BUTTON_START */
{ 75, 154, 0.0, MARKER_BUTTON }, /* SDL_CONTROLLER_BUTTON_LEFTSTICK */
{ 305, 230, 0.0, MARKER_BUTTON }, /* SDL_CONTROLLER_BUTTON_RIGHTSTICK */
{ 77, 40, 0.0, MARKER_BUTTON }, /* SDL_CONTROLLER_BUTTON_LEFTSHOULDER */
{ 396, 36, 0.0, MARKER_BUTTON }, /* SDL_CONTROLLER_BUTTON_RIGHTSHOULDER */
{ 154, 188, 0.0, MARKER_BUTTON }, /* SDL_CONTROLLER_BUTTON_DPAD_UP */
{ 154, 249, 0.0, MARKER_BUTTON }, /* SDL_CONTROLLER_BUTTON_DPAD_DOWN */
{ 116, 217, 0.0, MARKER_BUTTON }, /* SDL_CONTROLLER_BUTTON_DPAD_LEFT */
{ 186, 217, 0.0, MARKER_BUTTON }, /* SDL_CONTROLLER_BUTTON_DPAD_RIGHT */
{ 232, 174, 0.0, MARKER_BUTTON }, /* SDL_CONTROLLER_BUTTON_MISC1 */
{ 132, 135, 0.0, MARKER_BUTTON }, /* SDL_CONTROLLER_BUTTON_PADDLE1 */
{ 330, 135, 0.0, MARKER_BUTTON }, /* SDL_CONTROLLER_BUTTON_PADDLE2 */
{ 132, 175, 0.0, MARKER_BUTTON }, /* SDL_CONTROLLER_BUTTON_PADDLE3 */
{ 330, 175, 0.0, MARKER_BUTTON }, /* SDL_CONTROLLER_BUTTON_PADDLE4 */
{ 0, 0, 0.0, MARKER_BUTTON }, /* SDL_CONTROLLER_BUTTON_TOUCHPAD */
{ 74, 153, 270.0, MARKER_AXIS }, /* SDL_CONTROLLER_BINDING_AXIS_LEFTX_NEGATIVE */
{ 74, 153, 90.0, MARKER_AXIS }, /* SDL_CONTROLLER_BINDING_AXIS_LEFTX_POSITIVE */
{ 74, 153, 0.0, MARKER_AXIS }, /* SDL_CONTROLLER_BINDING_AXIS_LEFTY_NEGATIVE */
{ 74, 153, 180.0, MARKER_AXIS }, /* SDL_CONTROLLER_BINDING_AXIS_LEFTY_POSITIVE */
{ 306, 231, 270.0, MARKER_AXIS }, /* SDL_CONTROLLER_BINDING_AXIS_RIGHTX_NEGATIVE */
{ 306, 231, 90.0, MARKER_AXIS }, /* SDL_CONTROLLER_BINDING_AXIS_RIGHTX_POSITIVE */
{ 306, 231, 0.0, MARKER_AXIS }, /* SDL_CONTROLLER_BINDING_AXIS_RIGHTY_NEGATIVE */
{ 306, 231, 180.0, MARKER_AXIS }, /* SDL_CONTROLLER_BINDING_AXIS_RIGHTY_POSITIVE */
{ 91, -20, 180.0, MARKER_AXIS }, /* SDL_CONTROLLER_BINDING_AXIS_TRIGGERLEFT */
{ 375, -20, 180.0, MARKER_AXIS }, /* SDL_CONTROLLER_BINDING_AXIS_TRIGGERRIGHT */
};
SDL_COMPILE_TIME_ASSERT(s_arrBindingDisplay, SDL_arraysize(s_arrBindingDisplay) == BINDING_COUNT);
static int s_arrBindingOrder[] = {
SDL_CONTROLLER_BUTTON_A,
SDL_CONTROLLER_BUTTON_B,
SDL_CONTROLLER_BUTTON_Y,
SDL_CONTROLLER_BUTTON_X,
SDL_CONTROLLER_BUTTON_MAX + SDL_CONTROLLER_BINDING_AXIS_LEFTX_NEGATIVE,
SDL_CONTROLLER_BUTTON_MAX + SDL_CONTROLLER_BINDING_AXIS_LEFTX_POSITIVE,
SDL_CONTROLLER_BUTTON_MAX + SDL_CONTROLLER_BINDING_AXIS_LEFTY_NEGATIVE,
SDL_CONTROLLER_BUTTON_MAX + SDL_CONTROLLER_BINDING_AXIS_LEFTY_POSITIVE,
SDL_CONTROLLER_BUTTON_LEFTSTICK,
SDL_CONTROLLER_BUTTON_MAX + SDL_CONTROLLER_BINDING_AXIS_RIGHTX_NEGATIVE,
SDL_CONTROLLER_BUTTON_MAX + SDL_CONTROLLER_BINDING_AXIS_RIGHTX_POSITIVE,
SDL_CONTROLLER_BUTTON_MAX + SDL_CONTROLLER_BINDING_AXIS_RIGHTY_NEGATIVE,
SDL_CONTROLLER_BUTTON_MAX + SDL_CONTROLLER_BINDING_AXIS_RIGHTY_POSITIVE,
SDL_CONTROLLER_BUTTON_RIGHTSTICK,
SDL_CONTROLLER_BUTTON_LEFTSHOULDER,
SDL_CONTROLLER_BUTTON_MAX + SDL_CONTROLLER_BINDING_AXIS_TRIGGERLEFT,
SDL_CONTROLLER_BUTTON_RIGHTSHOULDER,
SDL_CONTROLLER_BUTTON_MAX + SDL_CONTROLLER_BINDING_AXIS_TRIGGERRIGHT,
SDL_CONTROLLER_BUTTON_DPAD_UP,
SDL_CONTROLLER_BUTTON_DPAD_RIGHT,
SDL_CONTROLLER_BUTTON_DPAD_DOWN,
SDL_CONTROLLER_BUTTON_DPAD_LEFT,
SDL_CONTROLLER_BUTTON_BACK,
SDL_CONTROLLER_BUTTON_GUIDE,
SDL_CONTROLLER_BUTTON_START,
SDL_CONTROLLER_BUTTON_MISC1,
SDL_CONTROLLER_BUTTON_PADDLE1,
SDL_CONTROLLER_BUTTON_PADDLE2,
SDL_CONTROLLER_BUTTON_PADDLE3,
SDL_CONTROLLER_BUTTON_PADDLE4,
SDL_CONTROLLER_BUTTON_TOUCHPAD,
};
SDL_COMPILE_TIME_ASSERT(s_arrBindingOrder, SDL_arraysize(s_arrBindingOrder) == BINDING_COUNT);
typedef struct
{
SDL_GameControllerBindType bindType;
union
{
int button;
struct
{
int axis;
int axis_min;
int axis_max;
} axis;
struct
{
int hat;
int hat_mask;
} hat;
} value;
SDL_bool committed;
} SDL_GameControllerExtendedBind;
static SDL_GameControllerExtendedBind s_arrBindings[BINDING_COUNT];
typedef struct
{
SDL_bool m_bMoving;
int m_nLastValue;
int m_nStartingValue;
int m_nFarthestValue;
} AxisState;
static int s_nNumAxes;
static AxisState *s_arrAxisState;
static int s_iCurrentBinding;
static Uint32 s_unPendingAdvanceTime;
static SDL_bool s_bBindingComplete;
static SDL_Window *window;
static SDL_Renderer *screen;
static SDL_bool done = SDL_FALSE;
static SDL_bool bind_touchpad = SDL_FALSE;
static int
StandardizeAxisValue(int nValue)
{
if (nValue > SDL_JOYSTICK_AXIS_MAX / 2) {
return SDL_JOYSTICK_AXIS_MAX;
} else if (nValue < SDL_JOYSTICK_AXIS_MIN / 2) {
return SDL_JOYSTICK_AXIS_MIN;
} else {
return 0;
}
}
static void
SetCurrentBinding(int iBinding)
{
int iIndex;
SDL_GameControllerExtendedBind *pBinding;
if (iBinding < 0) {
return;
}
if (iBinding == BINDING_COUNT) {
s_bBindingComplete = SDL_TRUE;
return;
}
if (s_arrBindingOrder[iBinding] == -1) {
SetCurrentBinding(iBinding + 1);
return;
}
if (s_arrBindingOrder[iBinding] == SDL_CONTROLLER_BUTTON_TOUCHPAD &&
!bind_touchpad) {
SetCurrentBinding(iBinding + 1);
return;
}
s_iCurrentBinding = iBinding;
pBinding = &s_arrBindings[s_arrBindingOrder[s_iCurrentBinding]];
SDL_zerop(pBinding);
for (iIndex = 0; iIndex < s_nNumAxes; ++iIndex) {
s_arrAxisState[iIndex].m_nFarthestValue = s_arrAxisState[iIndex].m_nStartingValue;
}
s_unPendingAdvanceTime = 0;
}
static SDL_bool
BBindingContainsBinding(const SDL_GameControllerExtendedBind *pBindingA, const SDL_GameControllerExtendedBind *pBindingB)
{
if (pBindingA->bindType != pBindingB->bindType) {
return SDL_FALSE;
}
switch (pBindingA->bindType) {
case SDL_CONTROLLER_BINDTYPE_AXIS:
if (pBindingA->value.axis.axis != pBindingB->value.axis.axis) {
return SDL_FALSE;
}
if (!pBindingA->committed) {
return SDL_FALSE;
}
{
int minA = SDL_min(pBindingA->value.axis.axis_min, pBindingA->value.axis.axis_max);
int maxA = SDL_max(pBindingA->value.axis.axis_min, pBindingA->value.axis.axis_max);
int minB = SDL_min(pBindingB->value.axis.axis_min, pBindingB->value.axis.axis_max);
int maxB = SDL_max(pBindingB->value.axis.axis_min, pBindingB->value.axis.axis_max);
return minA <= minB && maxA >= maxB;
}
/* Not reached */
default:
return SDL_memcmp(pBindingA, pBindingB, sizeof(*pBindingA)) == 0;
}
}
static void
ConfigureBinding(const SDL_GameControllerExtendedBind *pBinding)
{
SDL_GameControllerExtendedBind *pCurrent;
int iIndex;
int iCurrentElement = s_arrBindingOrder[s_iCurrentBinding];
/* Do we already have this binding? */
for (iIndex = 0; iIndex < SDL_arraysize(s_arrBindings); ++iIndex) {
pCurrent = &s_arrBindings[iIndex];
if (BBindingContainsBinding(pCurrent, pBinding)) {
if (iIndex == SDL_CONTROLLER_BUTTON_A && iCurrentElement != SDL_CONTROLLER_BUTTON_B) {
/* Skip to the next binding */
SetCurrentBinding(s_iCurrentBinding + 1);
return;
}
if (iIndex == SDL_CONTROLLER_BUTTON_B) {
/* Go back to the previous binding */
SetCurrentBinding(s_iCurrentBinding - 1);
return;
}
/* Already have this binding, ignore it */
return;
}
}
#ifdef DEBUG_CONTROLLERMAP
switch (pBinding->bindType) {
case SDL_CONTROLLER_BINDTYPE_NONE:
break;
case SDL_CONTROLLER_BINDTYPE_BUTTON:
SDL_Log("Configuring button binding for button %d\n", pBinding->value.button);
break;
case SDL_CONTROLLER_BINDTYPE_AXIS:
SDL_Log("Configuring axis binding for axis %d %d/%d committed = %s\n", pBinding->value.axis.axis, pBinding->value.axis.axis_min, pBinding->value.axis.axis_max,
pBinding->committed ? "true" : "false");
break;
case SDL_CONTROLLER_BINDTYPE_HAT:
SDL_Log("Configuring hat binding for hat %d %d\n", pBinding->value.hat.hat, pBinding->value.hat.hat_mask);
break;
}
#endif /* DEBUG_CONTROLLERMAP */
/* Should the new binding override the existing one? */
pCurrent = &s_arrBindings[iCurrentElement];
if (pCurrent->bindType != SDL_CONTROLLER_BINDTYPE_NONE) {
SDL_bool bNativeDPad, bCurrentDPad;
SDL_bool bNativeAxis, bCurrentAxis;
bNativeDPad = (iCurrentElement == SDL_CONTROLLER_BUTTON_DPAD_UP ||
iCurrentElement == SDL_CONTROLLER_BUTTON_DPAD_DOWN ||
iCurrentElement == SDL_CONTROLLER_BUTTON_DPAD_LEFT ||
iCurrentElement == SDL_CONTROLLER_BUTTON_DPAD_RIGHT);
bCurrentDPad = (pCurrent->bindType == SDL_CONTROLLER_BINDTYPE_HAT);
if (bNativeDPad && bCurrentDPad) {
/* We already have a binding of the type we want, ignore the new one */
return;
}
bNativeAxis = (iCurrentElement >= SDL_CONTROLLER_BUTTON_MAX);
bCurrentAxis = (pCurrent->bindType == SDL_CONTROLLER_BINDTYPE_AXIS);
if (bNativeAxis == bCurrentAxis &&
(pBinding->bindType != SDL_CONTROLLER_BINDTYPE_AXIS ||
pBinding->value.axis.axis != pCurrent->value.axis.axis)) {
/* We already have a binding of the type we want, ignore the new one */
return;
}
}
*pCurrent = *pBinding;
if (pBinding->committed) {
s_unPendingAdvanceTime = SDL_GetTicks();
} else {
s_unPendingAdvanceTime = 0;
}
}
static SDL_bool
BMergeAxisBindings(int iIndex)
{
SDL_GameControllerExtendedBind *pBindingA = &s_arrBindings[iIndex];
SDL_GameControllerExtendedBind *pBindingB = &s_arrBindings[iIndex + 1];
if (pBindingA->bindType == SDL_CONTROLLER_BINDTYPE_AXIS &&
pBindingB->bindType == SDL_CONTROLLER_BINDTYPE_AXIS &&
pBindingA->value.axis.axis == pBindingB->value.axis.axis) {
if (pBindingA->value.axis.axis_min == pBindingB->value.axis.axis_min) {
pBindingA->value.axis.axis_min = pBindingA->value.axis.axis_max;
pBindingA->value.axis.axis_max = pBindingB->value.axis.axis_max;
pBindingB->bindType = SDL_CONTROLLER_BINDTYPE_NONE;
return SDL_TRUE;
}
}
return SDL_FALSE;
}
static void
WatchJoystick(SDL_Joystick *joystick)
{
SDL_Texture *background_front, *background_back, *button, *axis, *marker = NULL;
const char *name = NULL;
SDL_Event event;
SDL_Rect dst;
Uint8 alpha = 200, alpha_step = -1;
Uint32 alpha_ticks = 0;
SDL_JoystickID nJoystickID;
background_front = LoadTexture(screen, "controllermap.bmp", SDL_FALSE, NULL, NULL);
background_back = LoadTexture(screen, "controllermap_back.bmp", SDL_FALSE, NULL, NULL);
button = LoadTexture(screen, "button.bmp", SDL_TRUE, NULL, NULL);
axis = LoadTexture(screen, "axis.bmp", SDL_TRUE, NULL, NULL);
SDL_RaiseWindow(window);
/* scale for platforms that don't give you the window size you asked for. */
SDL_RenderSetLogicalSize(screen, SCREEN_WIDTH, SCREEN_HEIGHT);
/* Print info about the joystick we are watching */
name = SDL_JoystickName(joystick);
SDL_Log("Watching joystick %" SDL_PRIs32 ": (%s)\n", SDL_JoystickInstanceID(joystick),
name ? name : "Unknown Joystick");
SDL_Log("Joystick has %d axes, %d hats, %d balls, and %d buttons\n",
SDL_JoystickNumAxes(joystick), SDL_JoystickNumHats(joystick),
SDL_JoystickNumBalls(joystick), SDL_JoystickNumButtons(joystick));
SDL_Log("\n\n\
====================================================================================\n\
Press the buttons on your controller when indicated\n\
(Your controller may look different than the picture)\n\
If you want to correct a mistake, press backspace or the back button on your device\n\
To skip a button, press SPACE or click/touch the screen\n\
To exit, press ESC\n\
====================================================================================\n");
nJoystickID = SDL_JoystickInstanceID(joystick);
s_nNumAxes = SDL_JoystickNumAxes(joystick);
s_arrAxisState = (AxisState *)SDL_calloc(s_nNumAxes, sizeof(*s_arrAxisState));
/* Skip any spurious events at start */
while (SDL_PollEvent(&event) > 0) {
}
/* Loop, getting joystick events! */
while (!done && !s_bBindingComplete) {
int iElement = s_arrBindingOrder[s_iCurrentBinding];
switch (s_arrBindingDisplay[iElement].marker) {
case MARKER_AXIS:
marker = axis;
break;
case MARKER_BUTTON:
marker = button;
break;
}
dst.x = s_arrBindingDisplay[iElement].x;
dst.y = s_arrBindingDisplay[iElement].y;
SDL_QueryTexture(marker, NULL, NULL, &dst.w, &dst.h);
if (SDL_GetTicks() - alpha_ticks > 5) {
alpha_ticks = SDL_GetTicks();
alpha += alpha_step;
if (alpha == 255) {
alpha_step = -1;
}
if (alpha < 128) {
alpha_step = 1;
}
}
SDL_SetRenderDrawColor(screen, 0xFF, 0xFF, 0xFF, SDL_ALPHA_OPAQUE);
SDL_RenderClear(screen);
if (s_arrBindingOrder[s_iCurrentBinding] >= SDL_CONTROLLER_BUTTON_PADDLE1 &&
s_arrBindingOrder[s_iCurrentBinding] <= SDL_CONTROLLER_BUTTON_PADDLE4) {
SDL_RenderCopy(screen, background_back, NULL, NULL);
} else {
SDL_RenderCopy(screen, background_front, NULL, NULL);
}
SDL_SetTextureAlphaMod(marker, alpha);
SDL_SetTextureColorMod(marker, 10, 255, 21);
SDL_RenderCopyEx(screen, marker, NULL, &dst, s_arrBindingDisplay[iElement].angle, NULL, SDL_FLIP_NONE);
SDL_RenderPresent(screen);
while (SDL_PollEvent(&event) > 0) {
switch (event.type) {
case SDL_JOYDEVICEREMOVED:
if (event.jaxis.which == nJoystickID) {
done = SDL_TRUE;
}
break;
case SDL_JOYAXISMOTION:
if (event.jaxis.which == nJoystickID) {
const int MAX_ALLOWED_JITTER = SDL_JOYSTICK_AXIS_MAX / 80; /* ShanWan PS3 controller needed 96 */
AxisState *pAxisState = &s_arrAxisState[event.jaxis.axis];
int nValue = event.jaxis.value;
int nCurrentDistance, nFarthestDistance;
if (!pAxisState->m_bMoving) {
Sint16 nInitialValue;
pAxisState->m_bMoving = SDL_JoystickGetAxisInitialState(joystick, event.jaxis.axis, &nInitialValue);
pAxisState->m_nLastValue = nValue;
pAxisState->m_nStartingValue = nInitialValue;
pAxisState->m_nFarthestValue = nInitialValue;
} else if (SDL_abs(nValue - pAxisState->m_nLastValue) <= MAX_ALLOWED_JITTER) {
break;
} else {
pAxisState->m_nLastValue = nValue;
}
nCurrentDistance = SDL_abs(nValue - pAxisState->m_nStartingValue);
nFarthestDistance = SDL_abs(pAxisState->m_nFarthestValue - pAxisState->m_nStartingValue);
if (nCurrentDistance > nFarthestDistance) {
pAxisState->m_nFarthestValue = nValue;
nFarthestDistance = SDL_abs(pAxisState->m_nFarthestValue - pAxisState->m_nStartingValue);
}
#ifdef DEBUG_CONTROLLERMAP
SDL_Log("AXIS %d nValue %d nCurrentDistance %d nFarthestDistance %d\n", event.jaxis.axis, nValue, nCurrentDistance, nFarthestDistance);
#endif
if (nFarthestDistance >= 16000) {
/* If we've gone out far enough and started to come back, let's bind this axis */
SDL_bool bCommitBinding = (nCurrentDistance <= 10000) ? SDL_TRUE : SDL_FALSE;
SDL_GameControllerExtendedBind binding;
SDL_zero(binding);
binding.bindType = SDL_CONTROLLER_BINDTYPE_AXIS;
binding.value.axis.axis = event.jaxis.axis;
binding.value.axis.axis_min = StandardizeAxisValue(pAxisState->m_nStartingValue);
binding.value.axis.axis_max = StandardizeAxisValue(pAxisState->m_nFarthestValue);
binding.committed = bCommitBinding;
ConfigureBinding(&binding);
}
}
break;
case SDL_JOYHATMOTION:
if (event.jhat.which == nJoystickID) {
if (event.jhat.value != SDL_HAT_CENTERED) {
SDL_GameControllerExtendedBind binding;
#ifdef DEBUG_CONTROLLERMAP
SDL_Log("HAT %d %d\n", event.jhat.hat, event.jhat.value);
#endif
SDL_zero(binding);
binding.bindType = SDL_CONTROLLER_BINDTYPE_HAT;
binding.value.hat.hat = event.jhat.hat;
binding.value.hat.hat_mask = event.jhat.value;
binding.committed = SDL_TRUE;
ConfigureBinding(&binding);
}
}
break;
case SDL_JOYBUTTONUP:
if (event.jbutton.which == nJoystickID) {
SDL_GameControllerExtendedBind binding;
#ifdef DEBUG_CONTROLLERMAP
SDL_Log("BUTTON %d\n", event.jbutton.button);
#endif
SDL_zero(binding);
binding.bindType = SDL_CONTROLLER_BINDTYPE_BUTTON;
binding.value.button = event.jbutton.button;
binding.committed = SDL_TRUE;
ConfigureBinding(&binding);
}
break;
case SDL_FINGERDOWN:
case SDL_MOUSEBUTTONDOWN:
/* Skip this step */
SetCurrentBinding(s_iCurrentBinding + 1);
break;
case SDL_KEYDOWN:
if (event.key.keysym.sym == SDLK_BACKSPACE || event.key.keysym.sym == SDLK_AC_BACK) {
SetCurrentBinding(s_iCurrentBinding - 1);
break;
}
if (event.key.keysym.sym == SDLK_SPACE) {
SetCurrentBinding(s_iCurrentBinding + 1);
break;
}
if (event.key.keysym.sym != SDLK_ESCAPE) {
break;
}
SDL_FALLTHROUGH;
case SDL_QUIT:
done = SDL_TRUE;
break;
default:
break;
}
}
SDL_Delay(15);
/* Wait 30 ms for joystick events to stop coming in,
in case a controller sends multiple events for a single control (e.g. axis and button for trigger)
*/
if (s_unPendingAdvanceTime && SDL_GetTicks() - s_unPendingAdvanceTime >= 30) {
SetCurrentBinding(s_iCurrentBinding + 1);
}
}
if (s_bBindingComplete) {
SDL_JoystickGUID guid;
Uint16 crc;
char mapping[1024];
char trimmed_name[128];
char *spot;
int iIndex;
char pszElement[12];
SDL_strlcpy(trimmed_name, name, SDL_arraysize(trimmed_name));
while (SDL_isspace(trimmed_name[0])) {
SDL_memmove(&trimmed_name[0], &trimmed_name[1], SDL_strlen(trimmed_name));
}
while (trimmed_name[0] && SDL_isspace(trimmed_name[SDL_strlen(trimmed_name) - 1])) {
trimmed_name[SDL_strlen(trimmed_name) - 1] = '\0';
}
while ((spot = SDL_strchr(trimmed_name, ',')) != NULL) {
SDL_memmove(spot, spot + 1, SDL_strlen(spot));
}
/* Initialize mapping with GUID and name */
guid = SDL_JoystickGetGUID(joystick);
SDL_GetJoystickGUIDInfo(guid, NULL, NULL, NULL, &crc);
if (crc) {
/* Clear the CRC from the GUID for the mapping */
guid.data[2] = 0;
guid.data[3] = 0;
}
SDL_JoystickGetGUIDString(guid, mapping, SDL_arraysize(mapping));
SDL_strlcat(mapping, ",", SDL_arraysize(mapping));
SDL_strlcat(mapping, trimmed_name, SDL_arraysize(mapping));
SDL_strlcat(mapping, ",", SDL_arraysize(mapping));
SDL_strlcat(mapping, "platform:", SDL_arraysize(mapping));
SDL_strlcat(mapping, SDL_GetPlatform(), SDL_arraysize(mapping));
SDL_strlcat(mapping, ",", SDL_arraysize(mapping));
if (crc) {
char crc_string[5];
SDL_strlcat(mapping, "crc:", SDL_arraysize(mapping));
(void)SDL_snprintf(crc_string, sizeof(crc_string), "%.4x", crc);
SDL_strlcat(mapping, crc_string, SDL_arraysize(mapping));
SDL_strlcat(mapping, ",", SDL_arraysize(mapping));
}
for (iIndex = 0; iIndex < SDL_arraysize(s_arrBindings); ++iIndex) {
SDL_GameControllerExtendedBind *pBinding = &s_arrBindings[iIndex];
if (pBinding->bindType == SDL_CONTROLLER_BINDTYPE_NONE) {
continue;
}
if (iIndex < SDL_CONTROLLER_BUTTON_MAX) {
SDL_GameControllerButton eButton = (SDL_GameControllerButton)iIndex;
SDL_strlcat(mapping, SDL_GameControllerGetStringForButton(eButton), SDL_arraysize(mapping));
} else {
const char *pszAxisName = NULL;
switch (iIndex - SDL_CONTROLLER_BUTTON_MAX) {
case SDL_CONTROLLER_BINDING_AXIS_LEFTX_NEGATIVE:
if (!BMergeAxisBindings(iIndex)) {
SDL_strlcat(mapping, "-", SDL_arraysize(mapping));
}
pszAxisName = SDL_GameControllerGetStringForAxis(SDL_CONTROLLER_AXIS_LEFTX);
break;
case SDL_CONTROLLER_BINDING_AXIS_LEFTX_POSITIVE:
SDL_strlcat(mapping, "+", SDL_arraysize(mapping));
pszAxisName = SDL_GameControllerGetStringForAxis(SDL_CONTROLLER_AXIS_LEFTX);
break;
case SDL_CONTROLLER_BINDING_AXIS_LEFTY_NEGATIVE:
if (!BMergeAxisBindings(iIndex)) {
SDL_strlcat(mapping, "-", SDL_arraysize(mapping));
}
pszAxisName = SDL_GameControllerGetStringForAxis(SDL_CONTROLLER_AXIS_LEFTY);
break;
case SDL_CONTROLLER_BINDING_AXIS_LEFTY_POSITIVE:
SDL_strlcat(mapping, "+", SDL_arraysize(mapping));
pszAxisName = SDL_GameControllerGetStringForAxis(SDL_CONTROLLER_AXIS_LEFTY);
break;
case SDL_CONTROLLER_BINDING_AXIS_RIGHTX_NEGATIVE:
if (!BMergeAxisBindings(iIndex)) {
SDL_strlcat(mapping, "-", SDL_arraysize(mapping));
}
pszAxisName = SDL_GameControllerGetStringForAxis(SDL_CONTROLLER_AXIS_RIGHTX);
break;
case SDL_CONTROLLER_BINDING_AXIS_RIGHTX_POSITIVE:
SDL_strlcat(mapping, "+", SDL_arraysize(mapping));
pszAxisName = SDL_GameControllerGetStringForAxis(SDL_CONTROLLER_AXIS_RIGHTX);
break;
case SDL_CONTROLLER_BINDING_AXIS_RIGHTY_NEGATIVE:
if (!BMergeAxisBindings(iIndex)) {
SDL_strlcat(mapping, "-", SDL_arraysize(mapping));
}
pszAxisName = SDL_GameControllerGetStringForAxis(SDL_CONTROLLER_AXIS_RIGHTY);
break;
case SDL_CONTROLLER_BINDING_AXIS_RIGHTY_POSITIVE:
SDL_strlcat(mapping, "+", SDL_arraysize(mapping));
pszAxisName = SDL_GameControllerGetStringForAxis(SDL_CONTROLLER_AXIS_RIGHTY);
break;
case SDL_CONTROLLER_BINDING_AXIS_TRIGGERLEFT:
pszAxisName = SDL_GameControllerGetStringForAxis(SDL_CONTROLLER_AXIS_TRIGGERLEFT);
break;
case SDL_CONTROLLER_BINDING_AXIS_TRIGGERRIGHT:
pszAxisName = SDL_GameControllerGetStringForAxis(SDL_CONTROLLER_AXIS_TRIGGERRIGHT);
break;
}
if (pszAxisName) {
SDL_strlcat(mapping, pszAxisName, SDL_arraysize(mapping));
}
}
SDL_strlcat(mapping, ":", SDL_arraysize(mapping));
pszElement[0] = '\0';
switch (pBinding->bindType) {
case SDL_CONTROLLER_BINDTYPE_BUTTON:
(void)SDL_snprintf(pszElement, sizeof(pszElement), "b%d", pBinding->value.button);
break;
case SDL_CONTROLLER_BINDTYPE_AXIS:
if (pBinding->value.axis.axis_min == 0 && pBinding->value.axis.axis_max == SDL_JOYSTICK_AXIS_MIN) {
/* The negative half axis */
(void)SDL_snprintf(pszElement, sizeof(pszElement), "-a%d", pBinding->value.axis.axis);
} else if (pBinding->value.axis.axis_min == 0 && pBinding->value.axis.axis_max == SDL_JOYSTICK_AXIS_MAX) {
/* The positive half axis */
(void)SDL_snprintf(pszElement, sizeof(pszElement), "+a%d", pBinding->value.axis.axis);
} else {
(void)SDL_snprintf(pszElement, sizeof(pszElement), "a%d", pBinding->value.axis.axis);
if (pBinding->value.axis.axis_min > pBinding->value.axis.axis_max) {
/* Invert the axis */
SDL_strlcat(pszElement, "~", SDL_arraysize(pszElement));
}
}
break;
case SDL_CONTROLLER_BINDTYPE_HAT:
(void)SDL_snprintf(pszElement, sizeof(pszElement), "h%d.%d", pBinding->value.hat.hat, pBinding->value.hat.hat_mask);
break;
default:
SDL_assert(!"Unknown bind type");
break;
}
SDL_strlcat(mapping, pszElement, SDL_arraysize(mapping));
SDL_strlcat(mapping, ",", SDL_arraysize(mapping));
}
SDL_Log("Mapping:\n\n%s\n\n", mapping);
/* Print to stdout as well so the user can cat the output somewhere */
printf("%s\n", mapping);
}
SDL_free(s_arrAxisState);
s_arrAxisState = NULL;
SDL_DestroyRenderer(screen);
}
int main(int argc, char *argv[])
{
const char *name;
int i;
int joystick_index;
SDL_Joystick *joystick;
SDL_SetHint(SDL_HINT_ACCELEROMETER_AS_JOYSTICK, "0");
/* Enable standard application logging */
SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);
/* Initialize SDL (Note: video is required to start event loop) */
if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_JOYSTICK) < 0) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't initialize SDL: %s\n", SDL_GetError());
exit(1);
}
if (argv[1] && SDL_strcmp(argv[1], "--bind-touchpad") == 0) {
bind_touchpad = SDL_TRUE;
}
/* Create a window to display joystick axis position */
window = SDL_CreateWindow("Game Controller Map", SDL_WINDOWPOS_CENTERED,
SDL_WINDOWPOS_CENTERED, SCREEN_WIDTH,
SCREEN_HEIGHT, 0);
if (!window) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't create window: %s\n", SDL_GetError());
return 2;
}
screen = SDL_CreateRenderer(window, -1, 0);
if (!screen) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't create renderer: %s\n", SDL_GetError());
return 2;
}
while (!done && SDL_NumJoysticks() == 0) {
SDL_Event event;
while (SDL_PollEvent(&event) > 0) {
switch (event.type) {
case SDL_KEYDOWN:
if (event.key.keysym.sym != SDLK_ESCAPE) {
break;
}
SDL_FALLTHROUGH;
case SDL_QUIT:
done = SDL_TRUE;
break;
default:
break;
}
}
SDL_RenderPresent(screen);
}
/* Print information about the joysticks */
SDL_Log("There are %d joysticks attached\n", SDL_NumJoysticks());
for (i = 0; i < SDL_NumJoysticks(); ++i) {
name = SDL_JoystickNameForIndex(i);
SDL_Log("Joystick %d: %s\n", i, name ? name : "Unknown Joystick");
joystick = SDL_JoystickOpen(i);
if (!joystick) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "SDL_JoystickOpen(%d) failed: %s\n", i,
SDL_GetError());
} else {
char guid[64];
SDL_JoystickGetGUIDString(SDL_JoystickGetGUID(joystick),
guid, sizeof(guid));
SDL_Log(" axes: %d\n", SDL_JoystickNumAxes(joystick));
SDL_Log(" balls: %d\n", SDL_JoystickNumBalls(joystick));
SDL_Log(" hats: %d\n", SDL_JoystickNumHats(joystick));
SDL_Log(" buttons: %d\n", SDL_JoystickNumButtons(joystick));
SDL_Log("instance id: %" SDL_PRIu32 "\n", SDL_JoystickInstanceID(joystick));
SDL_Log(" guid: %s\n", guid);
SDL_Log(" VID/PID: 0x%.4x/0x%.4x\n", SDL_JoystickGetVendor(joystick), SDL_JoystickGetProduct(joystick));
SDL_JoystickClose(joystick);
}
}
joystick_index = 0;
for (i = 1; i < argc; ++i) {
if (argv[i] && *argv[i] != '-') {
joystick_index = SDL_atoi(argv[i]);
break;
}
}
joystick = SDL_JoystickOpen(joystick_index);
if (!joystick) {
SDL_Log("Couldn't open joystick %d: %s\n", joystick_index, SDL_GetError());
} else {
WatchJoystick(joystick);
SDL_JoystickClose(joystick);
}
SDL_DestroyWindow(window);
SDL_QuitSubSystem(SDL_INIT_VIDEO | SDL_INIT_JOYSTICK);
return 0;
}
#else
int
main(int argc, char *argv[])
{
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "SDL compiled without Joystick support.\n");
return 1;
}
#endif
/* vi: set ts=4 sw=4 expandtab: */

Binary file not shown.

After

Width:  |  Height:  |  Size: 476 KiB

View File

@ -0,0 +1,25 @@
Module['arguments'] = ['0'];
//Gamepads don't appear until a button is pressed and the joystick/gamepad tests expect one to be connected
Module['preRun'].push(function()
{
Module['print']("Waiting for gamepad...");
Module['addRunDependency']("gamepad");
window.addEventListener('gamepadconnected', function()
{
//OK, got one
Module['removeRunDependency']("gamepad");
}, false);
//chrome
if(!!navigator.webkitGetGamepads)
{
var timeout = function()
{
if(navigator.webkitGetGamepads()[0] !== undefined)
Module['removeRunDependency']("gamepad");
else
setTimeout(timeout, 100);
}
setTimeout(timeout, 100);
}
});

BIN
vendored/sdl/test/icon.bmp Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 578 B

View File

@ -0,0 +1,182 @@
/*
Copyright (C) 1997-2024 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely.
*/
/* Program to load a wave file and loop playing it using SDL audio */
/* loopwaves.c is much more robust in handling WAVE files --
This is only for simple WAVEs
*/
#include "SDL_config.h"
#include <stdio.h>
#include <stdlib.h>
#ifdef __EMSCRIPTEN__
#include <emscripten/emscripten.h>
#endif
#include "SDL.h"
#include "testutils.h"
static struct
{
SDL_AudioSpec spec;
Uint8 *sound; /* Pointer to wave data */
Uint32 soundlen; /* Length of wave data */
int soundpos; /* Current play position */
} wave;
static SDL_AudioDeviceID device;
/* Call this instead of exit(), so we can clean up SDL: atexit() is evil. */
static void
quit(int rc)
{
SDL_Quit();
exit(rc);
}
static void
close_audio()
{
if (device != 0) {
SDL_CloseAudioDevice(device);
device = 0;
}
}
static void
open_audio()
{
/* Initialize fillerup() variables */
device = SDL_OpenAudioDevice(NULL, SDL_FALSE, &wave.spec, NULL, 0);
if (!device) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't open audio: %s\n", SDL_GetError());
SDL_FreeWAV(wave.sound);
quit(2);
}
/* Let the audio run */
SDL_PauseAudioDevice(device, SDL_FALSE);
}
#ifndef __EMSCRIPTEN__
static void reopen_audio()
{
close_audio();
open_audio();
}
#endif
void SDLCALL
fillerup(void *unused, Uint8 *stream, int len)
{
Uint8 *waveptr;
int waveleft;
/* Set up the pointers */
waveptr = wave.sound + wave.soundpos;
waveleft = wave.soundlen - wave.soundpos;
/* Go! */
while (waveleft <= len) {
SDL_memcpy(stream, waveptr, waveleft);
stream += waveleft;
len -= waveleft;
waveptr = wave.sound;
waveleft = wave.soundlen;
wave.soundpos = 0;
}
SDL_memcpy(stream, waveptr, len);
wave.soundpos += len;
}
static int done = 0;
#ifdef __EMSCRIPTEN__
void loop()
{
if (done || (SDL_GetAudioDeviceStatus(device) != SDL_AUDIO_PLAYING)) {
emscripten_cancel_main_loop();
}
}
#endif
int main(int argc, char *argv[])
{
int i;
char *filename = NULL;
/* Enable standard application logging */
SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);
/* Load the SDL library */
if (SDL_Init(SDL_INIT_AUDIO | SDL_INIT_EVENTS) < 0) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't initialize SDL: %s\n", SDL_GetError());
return 1;
}
filename = GetResourceFilename(argc > 1 ? argv[1] : NULL, "sample.wav");
if (!filename) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "%s\n", SDL_GetError());
quit(1);
}
/* Load the wave file into memory */
if (SDL_LoadWAV(filename, &wave.spec, &wave.sound, &wave.soundlen) == NULL) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't load %s: %s\n", filename, SDL_GetError());
quit(1);
}
wave.spec.callback = fillerup;
/* Show the list of available drivers */
SDL_Log("Available audio drivers:");
for (i = 0; i < SDL_GetNumAudioDrivers(); ++i) {
SDL_Log("%i: %s", i, SDL_GetAudioDriver(i));
}
SDL_Log("Using audio driver: %s\n", SDL_GetCurrentAudioDriver());
open_audio();
SDL_FlushEvents(SDL_AUDIODEVICEADDED, SDL_AUDIODEVICEREMOVED);
#ifdef __EMSCRIPTEN__
emscripten_set_main_loop(loop, 0, 1);
#else
while (!done) {
SDL_Event event;
while (SDL_PollEvent(&event) > 0) {
if (event.type == SDL_QUIT) {
done = 1;
}
if ((event.type == SDL_AUDIODEVICEADDED && !event.adevice.iscapture) ||
(event.type == SDL_AUDIODEVICEREMOVED && !event.adevice.iscapture && event.adevice.which == device)) {
reopen_audio();
}
}
SDL_Delay(100);
}
#endif
/* Clean up on signal */
close_audio();
SDL_FreeWAV(wave.sound);
SDL_free(filename);
SDL_Quit();
return 0;
}
/* vi: set ts=4 sw=4 expandtab: */

View File

@ -0,0 +1,148 @@
/*
Copyright (C) 1997-2024 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely.
*/
/* Program to load a wave file and loop playing it using SDL sound queueing */
#include <stdio.h>
#include <stdlib.h>
#ifdef __EMSCRIPTEN__
#include <emscripten/emscripten.h>
#endif
#include "SDL.h"
#ifdef HAVE_SIGNAL_H
#include <signal.h>
#endif
#include "testutils.h"
static struct
{
SDL_AudioSpec spec;
Uint8 *sound; /* Pointer to wave data */
Uint32 soundlen; /* Length of wave data */
} wave;
/* Call this instead of exit(), so we can clean up SDL: atexit() is evil. */
static void
quit(int rc)
{
SDL_Quit();
exit(rc);
}
static int done = 0;
void poked(int sig)
{
done = 1;
}
void loop()
{
#ifdef __EMSCRIPTEN__
if (done || (SDL_GetAudioStatus() != SDL_AUDIO_PLAYING)) {
emscripten_cancel_main_loop();
} else
#endif
{
/* The device from SDL_OpenAudio() is always device #1. */
const Uint32 queued = SDL_GetQueuedAudioSize(1);
SDL_Log("Device has %u bytes queued.\n", (unsigned int)queued);
if (queued <= 8192) { /* time to requeue the whole thing? */
if (SDL_QueueAudio(1, wave.sound, wave.soundlen) == 0) {
SDL_Log("Device queued %u more bytes.\n", (unsigned int)wave.soundlen);
} else {
SDL_Log("Device FAILED to queue %u more bytes: %s\n", (unsigned int)wave.soundlen, SDL_GetError());
}
}
}
}
int main(int argc, char *argv[])
{
char *filename = NULL;
/* Enable standard application logging */
SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);
/* Load the SDL library */
if (SDL_Init(SDL_INIT_AUDIO) < 0) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't initialize SDL: %s\n", SDL_GetError());
return 1;
}
filename = GetResourceFilename(argc > 1 ? argv[1] : NULL, "sample.wav");
if (!filename) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "%s\n", SDL_GetError());
quit(1);
}
/* Load the wave file into memory */
if (SDL_LoadWAV(filename, &wave.spec, &wave.sound, &wave.soundlen) == NULL) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't load %s: %s\n", filename, SDL_GetError());
quit(1);
}
wave.spec.callback = NULL; /* we'll push audio. */
#ifdef HAVE_SIGNAL_H
/* Set the signals */
#ifdef SIGHUP
(void)signal(SIGHUP, poked);
#endif
(void)signal(SIGINT, poked);
#ifdef SIGQUIT
(void)signal(SIGQUIT, poked);
#endif
(void)signal(SIGTERM, poked);
#endif /* HAVE_SIGNAL_H */
/* Initialize fillerup() variables */
if (SDL_OpenAudio(&wave.spec, NULL) < 0) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't open audio: %s\n", SDL_GetError());
SDL_FreeWAV(wave.sound);
quit(2);
}
/*static x[99999]; SDL_QueueAudio(1, x, sizeof (x));*/
/* Let the audio run */
SDL_PauseAudio(0);
done = 0;
/* Note that we stuff the entire audio buffer into the queue in one
shot. Most apps would want to feed it a little at a time, as it
plays, but we're going for simplicity here. */
#ifdef __EMSCRIPTEN__
emscripten_set_main_loop(loop, 0, 1);
#else
while (!done && (SDL_GetAudioStatus() == SDL_AUDIO_PLAYING)) {
loop();
SDL_Delay(100); /* let it play for awhile. */
}
#endif
/* Clean up on signal */
SDL_CloseAudio();
SDL_FreeWAV(wave.sound);
SDL_free(filename);
SDL_Quit();
return 0;
}
/* vi: set ts=4 sw=4 expandtab: */

BIN
vendored/sdl/test/moose.dat Normal file

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.0 KiB

View File

@ -0,0 +1,63 @@
# Copyright (c) 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# GNU Makefile based on shared rules provided by the Native Client SDK.
# See README.Makefiles for more details.
VALID_TOOLCHAINS := pnacl
# NACL_SDK_ROOT ?= $(abspath $(CURDIR)/../../..)
include $(NACL_SDK_ROOT)/tools/common.mk
TARGET = sdl_app
DEPS = ppapi_simple nacl_io
# ppapi_simple and SDL2 end up being listed twice due to dependency solving issues -- Gabriel
LIBS = SDL2_test SDL2 ppapi_simple SDL2main SDL2 $(DEPS) ppapi_gles2 ppapi_cpp ppapi pthread
CFLAGS := -Wall
SOURCES ?= testgles2.c
# Build rules generated by macros from common.mk:
# Overriden macro from NACL SDK to be able to customize the library search path -- Gabriel
# Specific Link Macro
#
# $1 = Target Name
# $2 = List of inputs
# $3 = List of libs
# $4 = List of deps
# $5 = List of lib dirs
# $6 = Other Linker Args
#
# For debugging, we translate the pre-finalized .bc file.
#
define LINKER_RULE
all: $(1).pexe
$(1)_x86_32.nexe : $(1).bc
$(call LOG,TRANSLATE,$$@,$(PNACL_TRANSLATE) --allow-llvm-bitcode-input -arch x86-32 $$^ -o $$@)
$(1)_x86_64.nexe : $(1).bc
$(call LOG,TRANSLATE,$$@,$(PNACL_TRANSLATE) --allow-llvm-bitcode-input -arch x86-64 $$^ -o $$@)
$(1)_arm.nexe : $(1).bc
$(call LOG,TRANSLATE,$$@,$(PNACL_TRANSLATE) --allow-llvm-bitcode-input -arch arm $$^ -o $$@)
$(1).pexe: $(1).bc
$(call LOG,FINALIZE,$$@,$(PNACL_FINALIZE) -o $$@ $$^)
$(1).bc: $(2) $(foreach dep,$(4),$(STAMPDIR)/$(dep).stamp)
$(call LOG,LINK,$$@,$(PNACL_LINK) -o $$@ $(2) $(PNACL_LDFLAGS) $(foreach path,$(5),-L$(path)/pnacl/$(CONFIG)) -L./lib $(foreach lib,$(3),-l$(lib)) $(6))
endef
$(foreach dep,$(DEPS),$(eval $(call DEPEND_RULE,$(dep))))
$(foreach src,$(SOURCES),$(eval $(call COMPILE_RULE,$(src),$(CFLAGS))))
ifeq ($(CONFIG),Release)
$(eval $(call LINK_RULE,$(TARGET)_unstripped,$(SOURCES),$(LIBS),$(DEPS)))
$(eval $(call STRIP_RULE,$(TARGET),$(TARGET)_unstripped))
else
$(eval $(call LINK_RULE,$(TARGET),$(SOURCES),$(LIBS),$(DEPS)))
endif
$(eval $(call NMF_RULE,$(TARGET),))

View File

@ -0,0 +1,40 @@
// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
function makeURL(toolchain, config) {
return 'index.html?tc=' + toolchain + '&config=' + config;
}
function createWindow(url) {
console.log('loading ' + url);
chrome.app.window.create(url, {
width: 1024,
height: 800,
frame: 'none'
});
}
function onLaunched(launchData) {
// Send and XHR to get the URL to load from a configuration file.
// Normally you won't need to do this; just call:
//
// chrome.app.window.create('<your url>', {...});
//
// In the SDK we want to be able to load different URLs (for different
// toolchain/config combinations) from the commandline, so we to read
// this information from the file "run_package_config".
var xhr = new XMLHttpRequest();
xhr.open('GET', 'run_package_config', true);
xhr.onload = function() {
var toolchain_config = this.responseText.split(' ');
createWindow(makeURL.apply(null, toolchain_config));
};
xhr.onerror = function() {
// Can't find the config file, just load the default.
createWindow('index.html');
};
xhr.send();
}
chrome.app.runtime.onLaunched.addListener(onLaunched);

View File

@ -0,0 +1,474 @@
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Set to true when the Document is loaded IFF "test=true" is in the query
// string.
var isTest = false;
// Set to true when loading a "Release" NaCl module, false when loading a
// "Debug" NaCl module.
var isRelease = true;
// Javascript module pattern:
// see http://en.wikipedia.org/wiki/Unobtrusive_JavaScript#Namespaces
// In essence, we define an anonymous function which is immediately called and
// returns a new object. The new object contains only the exported definitions;
// all other definitions in the anonymous function are inaccessible to external
// code.
var common = (function() {
function isHostToolchain(tool) {
return tool == 'win' || tool == 'linux' || tool == 'mac';
}
/**
* Return the mime type for NaCl plugin.
*
* @param {string} tool The name of the toolchain, e.g. "glibc", "newlib" etc.
* @return {string} The mime-type for the kind of NaCl plugin matching
* the given toolchain.
*/
function mimeTypeForTool(tool) {
// For NaCl modules use application/x-nacl.
var mimetype = 'application/x-nacl';
if (isHostToolchain(tool)) {
// For non-NaCl PPAPI plugins use the x-ppapi-debug/release
// mime type.
if (isRelease)
mimetype = 'application/x-ppapi-release';
else
mimetype = 'application/x-ppapi-debug';
} else if (tool == 'pnacl') {
mimetype = 'application/x-pnacl';
}
return mimetype;
}
/**
* Check if the browser supports NaCl plugins.
*
* @param {string} tool The name of the toolchain, e.g. "glibc", "newlib" etc.
* @return {bool} True if the browser supports the type of NaCl plugin
* produced by the given toolchain.
*/
function browserSupportsNaCl(tool) {
// Assume host toolchains always work with the given browser.
// The below mime-type checking might not work with
// --register-pepper-plugins.
if (isHostToolchain(tool)) {
return true;
}
var mimetype = mimeTypeForTool(tool);
return navigator.mimeTypes[mimetype] !== undefined;
}
/**
* Inject a script into the DOM, and call a callback when it is loaded.
*
* @param {string} url The url of the script to load.
* @param {Function} onload The callback to call when the script is loaded.
* @param {Function} onerror The callback to call if the script fails to load.
*/
function injectScript(url, onload, onerror) {
var scriptEl = document.createElement('script');
scriptEl.type = 'text/javascript';
scriptEl.src = url;
scriptEl.onload = onload;
if (onerror) {
scriptEl.addEventListener('error', onerror, false);
}
document.head.appendChild(scriptEl);
}
/**
* Run all tests for this example.
*
* @param {Object} moduleEl The module DOM element.
*/
function runTests(moduleEl) {
console.log('runTests()');
common.tester = new Tester();
// All NaCl SDK examples are OK if the example exits cleanly; (i.e. the
// NaCl module returns 0 or calls exit(0)).
//
// Without this exception, the browser_tester thinks that the module
// has crashed.
common.tester.exitCleanlyIsOK();
common.tester.addAsyncTest('loaded', function(test) {
test.pass();
});
if (typeof window.addTests !== 'undefined') {
window.addTests();
}
common.tester.waitFor(moduleEl);
common.tester.run();
}
/**
* Create the Native Client <embed> element as a child of the DOM element
* named "listener".
*
* @param {string} name The name of the example.
* @param {string} tool The name of the toolchain, e.g. "glibc", "newlib" etc.
* @param {string} path Directory name where .nmf file can be found.
* @param {number} width The width to create the plugin.
* @param {number} height The height to create the plugin.
* @param {Object} attrs Dictionary of attributes to set on the module.
*/
function createNaClModule(name, tool, path, width, height, attrs) {
var moduleEl = document.createElement('embed');
moduleEl.setAttribute('name', 'nacl_module');
moduleEl.setAttribute('id', 'nacl_module');
moduleEl.setAttribute('width', width);
moduleEl.setAttribute('height', height);
moduleEl.setAttribute('path', path);
moduleEl.setAttribute('src', path + '/' + name + '.nmf');
// Add any optional arguments
if (attrs) {
for (var key in attrs) {
moduleEl.setAttribute(key, attrs[key]);
}
}
var mimetype = mimeTypeForTool(tool);
moduleEl.setAttribute('type', mimetype);
// The <EMBED> element is wrapped inside a <DIV>, which has both a 'load'
// and a 'message' event listener attached. This wrapping method is used
// instead of attaching the event listeners directly to the <EMBED> element
// to ensure that the listeners are active before the NaCl module 'load'
// event fires.
var listenerDiv = document.getElementById('listener');
listenerDiv.appendChild(moduleEl);
// Request the offsetTop property to force a relayout. As of Apr 10, 2014
// this is needed if the module is being loaded on a Chrome App's
// background page (see crbug.com/350445).
moduleEl.offsetTop;
// Host plugins don't send a moduleDidLoad message. We'll fake it here.
var isHost = isHostToolchain(tool);
if (isHost) {
window.setTimeout(function() {
moduleEl.readyState = 1;
moduleEl.dispatchEvent(new CustomEvent('loadstart'));
moduleEl.readyState = 4;
moduleEl.dispatchEvent(new CustomEvent('load'));
moduleEl.dispatchEvent(new CustomEvent('loadend'));
}, 100); // 100 ms
}
// This is code that is only used to test the SDK.
if (isTest) {
var loadNaClTest = function() {
injectScript('nacltest.js', function() {
runTests(moduleEl);
});
};
// Try to load test.js for the example. Whether or not it exists, load
// nacltest.js.
injectScript('test.js', loadNaClTest, loadNaClTest);
}
}
/**
* Add the default "load" and "message" event listeners to the element with
* id "listener".
*
* The "load" event is sent when the module is successfully loaded. The
* "message" event is sent when the naclModule posts a message using
* PPB_Messaging.PostMessage() (in C) or pp::Instance().PostMessage() (in
* C++).
*/
function attachDefaultListeners() {
var listenerDiv = document.getElementById('listener');
listenerDiv.addEventListener('load', moduleDidLoad, true);
listenerDiv.addEventListener('message', handleMessage, true);
listenerDiv.addEventListener('error', handleError, true);
listenerDiv.addEventListener('crash', handleCrash, true);
if (typeof window.attachListeners !== 'undefined') {
window.attachListeners();
}
}
/**
* Called when the NaCl module fails to load.
*
* This event listener is registered in createNaClModule above.
*/
function handleError(event) {
// We can't use common.naclModule yet because the module has not been
// loaded.
var moduleEl = document.getElementById('nacl_module');
updateStatus('ERROR [' + moduleEl.lastError + ']');
}
/**
* Called when the Browser can not communicate with the Module
*
* This event listener is registered in attachDefaultListeners above.
*/
function handleCrash(event) {
if (common.naclModule.exitStatus == -1) {
updateStatus('CRASHED');
} else {
updateStatus('EXITED [' + common.naclModule.exitStatus + ']');
}
if (typeof window.handleCrash !== 'undefined') {
window.handleCrash(common.naclModule.lastError);
}
}
/**
* Called when the NaCl module is loaded.
*
* This event listener is registered in attachDefaultListeners above.
*/
function moduleDidLoad() {
common.naclModule = document.getElementById('nacl_module');
updateStatus('RUNNING');
if (typeof window.moduleDidLoad !== 'undefined') {
window.moduleDidLoad();
}
}
/**
* Hide the NaCl module's embed element.
*
* We don't want to hide by default; if we do, it is harder to determine that
* a plugin failed to load. Instead, call this function inside the example's
* "moduleDidLoad" function.
*
*/
function hideModule() {
// Setting common.naclModule.style.display = "None" doesn't work; the
// module will no longer be able to receive postMessages.
common.naclModule.style.height = '0';
}
/**
* Remove the NaCl module from the page.
*/
function removeModule() {
common.naclModule.parentNode.removeChild(common.naclModule);
common.naclModule = null;
}
/**
* Return true when |s| starts with the string |prefix|.
*
* @param {string} s The string to search.
* @param {string} prefix The prefix to search for in |s|.
*/
function startsWith(s, prefix) {
// indexOf would search the entire string, lastIndexOf(p, 0) only checks at
// the first index. See: http://stackoverflow.com/a/4579228
return s.lastIndexOf(prefix, 0) === 0;
}
/** Maximum length of logMessageArray. */
var kMaxLogMessageLength = 20;
/** An array of messages to display in the element with id "log". */
var logMessageArray = [];
/**
* Add a message to an element with id "log".
*
* This function is used by the default "log:" message handler.
*
* @param {string} message The message to log.
*/
function logMessage(message) {
logMessageArray.push(message);
if (logMessageArray.length > kMaxLogMessageLength)
logMessageArray.shift();
document.getElementById('log').textContent = logMessageArray.join('\n');
console.log(message);
}
/**
*/
var defaultMessageTypes = {
'alert': alert,
'log': logMessage
};
/**
* Called when the NaCl module sends a message to JavaScript (via
* PPB_Messaging.PostMessage())
*
* This event listener is registered in createNaClModule above.
*
* @param {Event} message_event A message event. message_event.data contains
* the data sent from the NaCl module.
*/
function handleMessage(message_event) {
if (typeof message_event.data === 'string') {
for (var type in defaultMessageTypes) {
if (defaultMessageTypes.hasOwnProperty(type)) {
if (startsWith(message_event.data, type + ':')) {
func = defaultMessageTypes[type];
func(message_event.data.slice(type.length + 1));
return;
}
}
}
}
if (typeof window.handleMessage !== 'undefined') {
window.handleMessage(message_event);
return;
}
logMessage('Unhandled message: ' + message_event.data);
}
/**
* Called when the DOM content has loaded; i.e. the page's document is fully
* parsed. At this point, we can safely query any elements in the document via
* document.querySelector, document.getElementById, etc.
*
* @param {string} name The name of the example.
* @param {string} tool The name of the toolchain, e.g. "glibc", "newlib" etc.
* @param {string} path Directory name where .nmf file can be found.
* @param {number} width The width to create the plugin.
* @param {number} height The height to create the plugin.
* @param {Object} attrs Optional dictionary of additional attributes.
*/
function domContentLoaded(name, tool, path, width, height, attrs) {
// If the page loads before the Native Client module loads, then set the
// status message indicating that the module is still loading. Otherwise,
// do not change the status message.
updateStatus('Page loaded.');
if (!browserSupportsNaCl(tool)) {
updateStatus(
'Browser does not support NaCl (' + tool + '), or NaCl is disabled');
} else if (common.naclModule == null) {
updateStatus('Creating embed: ' + tool);
// We use a non-zero sized embed to give Chrome space to place the bad
// plug-in graphic, if there is a problem.
width = typeof width !== 'undefined' ? width : 200;
height = typeof height !== 'undefined' ? height : 200;
attachDefaultListeners();
createNaClModule(name, tool, path, width, height, attrs);
} else {
// It's possible that the Native Client module onload event fired
// before the page's onload event. In this case, the status message
// will reflect 'SUCCESS', but won't be displayed. This call will
// display the current message.
updateStatus('Waiting.');
}
}
/** Saved text to display in the element with id 'statusField'. */
var statusText = 'NO-STATUSES';
/**
* Set the global status message. If the element with id 'statusField'
* exists, then set its HTML to the status message as well.
*
* @param {string} opt_message The message to set. If null or undefined, then
* set element 'statusField' to the message from the last call to
* updateStatus.
*/
function updateStatus(opt_message) {
if (opt_message) {
statusText = opt_message;
}
var statusField = document.getElementById('statusField');
if (statusField) {
statusField.innerHTML = statusText;
}
}
// The symbols to export.
return {
/** A reference to the NaCl module, once it is loaded. */
naclModule: null,
attachDefaultListeners: attachDefaultListeners,
domContentLoaded: domContentLoaded,
createNaClModule: createNaClModule,
hideModule: hideModule,
removeModule: removeModule,
logMessage: logMessage,
updateStatus: updateStatus
};
}());
// Listen for the DOM content to be loaded. This event is fired when parsing of
// the page's document has finished.
document.addEventListener('DOMContentLoaded', function() {
var body = document.body;
// The data-* attributes on the body can be referenced via body.dataset.
if (body.dataset) {
var loadFunction;
if (!body.dataset.customLoad) {
loadFunction = common.domContentLoaded;
} else if (typeof window.domContentLoaded !== 'undefined') {
loadFunction = window.domContentLoaded;
}
// From https://developer.mozilla.org/en-US/docs/DOM/window.location
var searchVars = {};
if (window.location.search.length > 1) {
var pairs = window.location.search.substr(1).split('&');
for (var key_ix = 0; key_ix < pairs.length; key_ix++) {
var keyValue = pairs[key_ix].split('=');
searchVars[unescape(keyValue[0])] =
keyValue.length > 1 ? unescape(keyValue[1]) : '';
}
}
if (loadFunction) {
var toolchains = body.dataset.tools.split(' ');
var configs = body.dataset.configs.split(' ');
var attrs = {};
if (body.dataset.attrs) {
var attr_list = body.dataset.attrs.split(' ');
for (var key in attr_list) {
var attr = attr_list[key].split('=');
var key = attr[0];
var value = attr[1];
attrs[key] = value;
}
}
var tc = toolchains.indexOf(searchVars.tc) !== -1 ?
searchVars.tc : toolchains[0];
// If the config value is included in the search vars, use that.
// Otherwise default to Release if it is valid, or the first value if
// Release is not valid.
if (configs.indexOf(searchVars.config) !== -1)
var config = searchVars.config;
else if (configs.indexOf('Release') !== -1)
var config = 'Release';
else
var config = configs[0];
var pathFormat = body.dataset.path;
var path = pathFormat.replace('{tc}', tc).replace('{config}', config);
isTest = searchVars.test === 'true';
isRelease = path.toLowerCase().indexOf('release') != -1;
loadFunction(body.dataset.name, tc, path, body.dataset.width,
body.dataset.height, attrs);
}
}
});

View File

@ -0,0 +1,21 @@
<!DOCTYPE html>
<html>
<!--
Copyright (c) 2012 The Chromium Authors. All rights reserved.
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file.
-->
<head>
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Expires" content="-1">
<title>SDL NACL Test</title>
<script type="text/javascript" src="common.js"></script>
</head>
<body data-width="640" data-height="640" data-name="sdl_app" data-tools="pnacl" data-configs="Debug Release" data-path="{tc}/{config}">
<h1>SDL NACL Test</h1>
<h2>Status: <code id="statusField">NO-STATUS</code></h2>
<!-- The NaCl plugin will be embedded inside the element with id "listener".
See common.js.-->
<div id="listener"></div>
</body>
</html>

View File

@ -0,0 +1,22 @@
{
"name": "SDL testgles2",
"version": "33.0.1750.117",
"minimum_chrome_version": "33.0.1750.117",
"manifest_version": 2,
"description": "testgles2",
"offline_enabled": true,
"icons": {
"128": "icon128.png"
},
"app": {
"background": {
"scripts": ["background.js"]
}
},
"key": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCMN716Qyu0l2EHNFqIJVqVysFcTR6urqhaGGqW4UK7slBaURz9+Sb1b4Ot5P1uQNE5c+CTU5Vu61wpqmSqMMxqHLWdPPMh8uRlyctsb2cxWwG6XoGSvpX29NsQVUFXd4v2tkJm3G9t+V0X8TYskrvWQmnyOW8OEIDvrBhUEfFxWQIDAQAB",
"oauth2": {
"client_id": "903965034255.apps.googleusercontent.com",
"scopes": ["https://www.googleapis.com/auth/drive"]
},
"permissions": []
}

View File

@ -0,0 +1,14 @@
#define picture_width 32
#define picture_height 32
static char picture_bits[] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x80, 0x01, 0x18,
0x64, 0x6f, 0xf6, 0x26, 0x0a, 0x00, 0x00, 0x50, 0xf2, 0xff, 0xff, 0x4f,
0x14, 0x04, 0x00, 0x28, 0x14, 0x0e, 0x00, 0x28, 0x10, 0x32, 0x00, 0x08,
0x94, 0x03, 0x00, 0x08, 0xf4, 0x04, 0x00, 0x08, 0xb0, 0x08, 0x00, 0x08,
0x34, 0x01, 0x00, 0x28, 0x34, 0x01, 0x00, 0x28, 0x12, 0x00, 0x40, 0x48,
0x12, 0x20, 0xa6, 0x48, 0x14, 0x50, 0x11, 0x29, 0x14, 0x50, 0x48, 0x2a,
0x10, 0x27, 0xac, 0x0e, 0xd4, 0x71, 0xe8, 0x0a, 0x74, 0x20, 0xa8, 0x0a,
0x14, 0x20, 0x00, 0x08, 0x10, 0x50, 0x00, 0x08, 0x14, 0x00, 0x00, 0x28,
0x14, 0x00, 0x00, 0x28, 0xf2, 0xff, 0xff, 0x4f, 0x0a, 0x00, 0x00, 0x50,
0x64, 0x6f, 0xf6, 0x26, 0x18, 0x80, 0x01, 0x18, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};

View File

@ -0,0 +1,58 @@
Relative mode testing
=====================
See test program at the bottom of this file.
Initial tests:
- When in relative mode, the mouse shouldn't be moveable outside of the window.
- When the cursor is outside the window when relative mode is enabled, mouse
clicks should not go to whatever app was under the cursor previously.
- When alt/cmd-tabbing between a relative mode app and another app, clicks when
in the relative mode app should also not go to whatever app was under the
cursor previously.
Code
====
#include <SDL.h>
int PollEvents()
{
SDL_Event event;
while (SDL_PollEvent(&event))
{
switch (event.type)
{
case SDL_QUIT:
return 1;
default:
break;
}
}
return 0;
}
int main(int argc, char *argv[])
{
SDL_Window *win;
SDL_Init(SDL_INIT_VIDEO);
win = SDL_CreateWindow("Test", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 800, 600, 0);
SDL_SetRelativeMouseMode(SDL_TRUE);
while (1)
{
if (PollEvents())
break;
}
SDL_DestroyWindow(win);
SDL_Quit();
return 0;
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 68 KiB

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 401 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 401 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 401 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 50 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 401 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 401 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 401 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 401 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 401 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 401 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 50 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 401 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 401 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 401 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 401 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 401 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 401 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 50 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 401 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 192 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 256 KiB

View File

@ -0,0 +1,3 @@
[Test]
Type=session
Exec=@installedtestsdir@/@exe@

View File

@ -0,0 +1,721 @@
/*
Copyright (C) 1997-2024 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely.
*/
#include <stdio.h>
#include "SDL.h"
/*
Absolutely basic tests just to see if we get the expected value
after calling each function.
*/
static const char *
tf(SDL_bool _tf)
{
static const char *t = "TRUE";
static const char *f = "FALSE";
if (_tf) {
return t;
}
return f;
}
static void RunBasicTest()
{
int value;
SDL_SpinLock lock = 0;
SDL_atomic_t v;
SDL_bool tfret = SDL_FALSE;
SDL_Log("\nspin lock---------------------------------------\n\n");
SDL_AtomicLock(&lock);
SDL_Log("AtomicLock lock=%d\n", lock);
SDL_AtomicUnlock(&lock);
SDL_Log("AtomicUnlock lock=%d\n", lock);
SDL_Log("\natomic -----------------------------------------\n\n");
SDL_AtomicSet(&v, 0);
tfret = SDL_AtomicSet(&v, 10) == 0 ? SDL_TRUE : SDL_FALSE;
SDL_Log("AtomicSet(10) tfret=%s val=%d\n", tf(tfret), SDL_AtomicGet(&v));
tfret = SDL_AtomicAdd(&v, 10) == 10 ? SDL_TRUE : SDL_FALSE;
SDL_Log("AtomicAdd(10) tfret=%s val=%d\n", tf(tfret), SDL_AtomicGet(&v));
SDL_AtomicSet(&v, 0);
SDL_AtomicIncRef(&v);
tfret = (SDL_AtomicGet(&v) == 1) ? SDL_TRUE : SDL_FALSE;
SDL_Log("AtomicIncRef() tfret=%s val=%d\n", tf(tfret), SDL_AtomicGet(&v));
SDL_AtomicIncRef(&v);
tfret = (SDL_AtomicGet(&v) == 2) ? SDL_TRUE : SDL_FALSE;
SDL_Log("AtomicIncRef() tfret=%s val=%d\n", tf(tfret), SDL_AtomicGet(&v));
tfret = (SDL_AtomicDecRef(&v) == SDL_FALSE) ? SDL_TRUE : SDL_FALSE;
SDL_Log("AtomicDecRef() tfret=%s val=%d\n", tf(tfret), SDL_AtomicGet(&v));
tfret = (SDL_AtomicDecRef(&v) == SDL_TRUE) ? SDL_TRUE : SDL_FALSE;
SDL_Log("AtomicDecRef() tfret=%s val=%d\n", tf(tfret), SDL_AtomicGet(&v));
SDL_AtomicSet(&v, 10);
tfret = (SDL_AtomicCAS(&v, 0, 20) == SDL_FALSE) ? SDL_TRUE : SDL_FALSE;
SDL_Log("AtomicCAS() tfret=%s val=%d\n", tf(tfret), SDL_AtomicGet(&v));
value = SDL_AtomicGet(&v);
tfret = (SDL_AtomicCAS(&v, value, 20) == SDL_TRUE) ? SDL_TRUE : SDL_FALSE;
SDL_Log("AtomicCAS() tfret=%s val=%d\n", tf(tfret), SDL_AtomicGet(&v));
}
/**************************************************************************/
/* Atomic operation test
* Adapted with permission from code by Michael Davidsaver at:
* http://bazaar.launchpad.net/~mdavidsaver/epics-base/atomic/revision/12105#src/libCom/test/epicsAtomicTest.c
* Original copyright 2010 Brookhaven Science Associates as operator of Brookhaven National Lab
* http://www.aps.anl.gov/epics/license/open.php
*/
/* Tests semantics of atomic operations. Also a stress test
* to see if they are really atomic.
*
* Several threads adding to the same variable.
* at the end the value is compared with the expected
* and with a non-atomic counter.
*/
/* Number of concurrent incrementers */
#define NThreads 2
#define CountInc 100
#define VALBITS (sizeof(atomicValue) * 8)
#define atomicValue int
#define CountTo ((atomicValue)((unsigned int)(1 << (VALBITS - 1)) - 1))
#define NInter (CountTo / CountInc / NThreads)
#define Expect (CountTo - NInter * CountInc * NThreads)
enum
{
CountTo_GreaterThanZero = CountTo > 0,
};
SDL_COMPILE_TIME_ASSERT(size, CountTo_GreaterThanZero); /* check for rollover */
static SDL_atomic_t good = { 42 };
static atomicValue bad = 42;
static SDL_atomic_t threadsRunning;
static SDL_sem *threadDone;
static int SDLCALL adder(void *junk)
{
unsigned long N = NInter;
SDL_Log("Thread subtracting %d %lu times\n", CountInc, N);
while (N--) {
SDL_AtomicAdd(&good, -CountInc);
bad -= CountInc;
}
SDL_AtomicAdd(&threadsRunning, -1);
SDL_SemPost(threadDone);
return 0;
}
static void runAdder(void)
{
Uint32 start, end;
int T = NThreads;
start = SDL_GetTicks();
threadDone = SDL_CreateSemaphore(0);
SDL_AtomicSet(&threadsRunning, NThreads);
while (T--) {
SDL_CreateThread(adder, "Adder", NULL);
}
while (SDL_AtomicGet(&threadsRunning) > 0) {
SDL_SemWait(threadDone);
}
SDL_DestroySemaphore(threadDone);
end = SDL_GetTicks();
SDL_Log("Finished in %f sec\n", (end - start) / 1000.f);
}
static void RunEpicTest()
{
int b;
atomicValue v;
SDL_Log("\nepic test---------------------------------------\n\n");
SDL_Log("Size asserted to be >= 32-bit\n");
SDL_assert(sizeof(atomicValue) >= 4);
SDL_Log("Check static initializer\n");
v = SDL_AtomicGet(&good);
SDL_assert(v == 42);
SDL_assert(bad == 42);
SDL_Log("Test negative values\n");
SDL_AtomicSet(&good, -5);
v = SDL_AtomicGet(&good);
SDL_assert(v == -5);
SDL_Log("Verify maximum value\n");
SDL_AtomicSet(&good, CountTo);
v = SDL_AtomicGet(&good);
SDL_assert(v == CountTo);
SDL_Log("Test compare and exchange\n");
b = SDL_AtomicCAS(&good, 500, 43);
SDL_assert(!b); /* no swap since CountTo!=500 */
v = SDL_AtomicGet(&good);
SDL_assert(v == CountTo); /* ensure no swap */
b = SDL_AtomicCAS(&good, CountTo, 44);
SDL_assert(!!b); /* will swap */
v = SDL_AtomicGet(&good);
SDL_assert(v == 44);
SDL_Log("Test Add\n");
v = SDL_AtomicAdd(&good, 1);
SDL_assert(v == 44);
v = SDL_AtomicGet(&good);
SDL_assert(v == 45);
v = SDL_AtomicAdd(&good, 10);
SDL_assert(v == 45);
v = SDL_AtomicGet(&good);
SDL_assert(v == 55);
SDL_Log("Test Add (Negative values)\n");
v = SDL_AtomicAdd(&good, -20);
SDL_assert(v == 55);
v = SDL_AtomicGet(&good);
SDL_assert(v == 35);
v = SDL_AtomicAdd(&good, -50); /* crossing zero down */
SDL_assert(v == 35);
v = SDL_AtomicGet(&good);
SDL_assert(v == -15);
v = SDL_AtomicAdd(&good, 30); /* crossing zero up */
SDL_assert(v == -15);
v = SDL_AtomicGet(&good);
SDL_assert(v == 15);
SDL_Log("Reset before count down test\n");
SDL_AtomicSet(&good, CountTo);
v = SDL_AtomicGet(&good);
SDL_assert(v == CountTo);
bad = CountTo;
SDL_assert(bad == CountTo);
SDL_Log("Counting down from %d, Expect %d remaining\n", CountTo, Expect);
runAdder();
v = SDL_AtomicGet(&good);
SDL_Log("Atomic %d Non-Atomic %d\n", v, bad);
SDL_assert(v == Expect);
/* We can't guarantee that bad != Expect, this would happen on a single core system, for example. */
/*SDL_assert(bad != Expect);*/
}
/* End atomic operation test */
/**************************************************************************/
/**************************************************************************/
/* Lock-free FIFO test */
/* This is useful to test the impact of another thread locking the queue
entirely for heavy-weight manipulation.
*/
#define TEST_SPINLOCK_FIFO
#define NUM_READERS 4
#define NUM_WRITERS 4
#define EVENTS_PER_WRITER 1000000
/* The number of entries must be a power of 2 */
#define MAX_ENTRIES 256
#define WRAP_MASK (MAX_ENTRIES - 1)
typedef struct
{
SDL_atomic_t sequence;
SDL_Event event;
} SDL_EventQueueEntry;
typedef struct
{
SDL_EventQueueEntry entries[MAX_ENTRIES];
char cache_pad1[SDL_CACHELINE_SIZE - ((sizeof(SDL_EventQueueEntry) * MAX_ENTRIES) % SDL_CACHELINE_SIZE)];
SDL_atomic_t enqueue_pos;
char cache_pad2[SDL_CACHELINE_SIZE - sizeof(SDL_atomic_t)];
SDL_atomic_t dequeue_pos;
char cache_pad3[SDL_CACHELINE_SIZE - sizeof(SDL_atomic_t)];
#ifdef TEST_SPINLOCK_FIFO
SDL_SpinLock lock;
SDL_atomic_t rwcount;
SDL_atomic_t watcher;
char cache_pad4[SDL_CACHELINE_SIZE - sizeof(SDL_SpinLock) - 2 * sizeof(SDL_atomic_t)];
#endif
SDL_atomic_t active;
/* Only needed for the mutex test */
SDL_mutex *mutex;
} SDL_EventQueue;
static void InitEventQueue(SDL_EventQueue *queue)
{
int i;
for (i = 0; i < MAX_ENTRIES; ++i) {
SDL_AtomicSet(&queue->entries[i].sequence, i);
}
SDL_AtomicSet(&queue->enqueue_pos, 0);
SDL_AtomicSet(&queue->dequeue_pos, 0);
#ifdef TEST_SPINLOCK_FIFO
queue->lock = 0;
SDL_AtomicSet(&queue->rwcount, 0);
SDL_AtomicSet(&queue->watcher, 0);
#endif
SDL_AtomicSet(&queue->active, 1);
}
static SDL_bool EnqueueEvent_LockFree(SDL_EventQueue *queue, const SDL_Event *event)
{
SDL_EventQueueEntry *entry;
unsigned queue_pos;
unsigned entry_seq;
int delta;
SDL_bool status;
#ifdef TEST_SPINLOCK_FIFO
/* This is a gate so an external thread can lock the queue */
SDL_AtomicLock(&queue->lock);
SDL_assert(SDL_AtomicGet(&queue->watcher) == 0);
SDL_AtomicIncRef(&queue->rwcount);
SDL_AtomicUnlock(&queue->lock);
#endif
queue_pos = (unsigned)SDL_AtomicGet(&queue->enqueue_pos);
for (;;) {
entry = &queue->entries[queue_pos & WRAP_MASK];
entry_seq = (unsigned)SDL_AtomicGet(&entry->sequence);
delta = (int)(entry_seq - queue_pos);
if (delta == 0) {
/* The entry and the queue position match, try to increment the queue position */
if (SDL_AtomicCAS(&queue->enqueue_pos, (int)queue_pos, (int)(queue_pos + 1))) {
/* We own the object, fill it! */
entry->event = *event;
SDL_AtomicSet(&entry->sequence, (int)(queue_pos + 1));
status = SDL_TRUE;
break;
}
} else if (delta < 0) {
/* We ran into an old queue entry, which means it still needs to be dequeued */
status = SDL_FALSE;
break;
} else {
/* We ran into a new queue entry, get the new queue position */
queue_pos = (unsigned)SDL_AtomicGet(&queue->enqueue_pos);
}
}
#ifdef TEST_SPINLOCK_FIFO
(void)SDL_AtomicDecRef(&queue->rwcount);
#endif
return status;
}
static SDL_bool DequeueEvent_LockFree(SDL_EventQueue *queue, SDL_Event *event)
{
SDL_EventQueueEntry *entry;
unsigned queue_pos;
unsigned entry_seq;
int delta;
SDL_bool status;
#ifdef TEST_SPINLOCK_FIFO
/* This is a gate so an external thread can lock the queue */
SDL_AtomicLock(&queue->lock);
SDL_assert(SDL_AtomicGet(&queue->watcher) == 0);
SDL_AtomicIncRef(&queue->rwcount);
SDL_AtomicUnlock(&queue->lock);
#endif
queue_pos = (unsigned)SDL_AtomicGet(&queue->dequeue_pos);
for (;;) {
entry = &queue->entries[queue_pos & WRAP_MASK];
entry_seq = (unsigned)SDL_AtomicGet(&entry->sequence);
delta = (int)(entry_seq - (queue_pos + 1));
if (delta == 0) {
/* The entry and the queue position match, try to increment the queue position */
if (SDL_AtomicCAS(&queue->dequeue_pos, (int)queue_pos, (int)(queue_pos + 1))) {
/* We own the object, fill it! */
*event = entry->event;
SDL_AtomicSet(&entry->sequence, (int)(queue_pos + MAX_ENTRIES));
status = SDL_TRUE;
break;
}
} else if (delta < 0) {
/* We ran into an old queue entry, which means we've hit empty */
status = SDL_FALSE;
break;
} else {
/* We ran into a new queue entry, get the new queue position */
queue_pos = (unsigned)SDL_AtomicGet(&queue->dequeue_pos);
}
}
#ifdef TEST_SPINLOCK_FIFO
(void)SDL_AtomicDecRef(&queue->rwcount);
#endif
return status;
}
static SDL_bool EnqueueEvent_Mutex(SDL_EventQueue *queue, const SDL_Event *event)
{
SDL_EventQueueEntry *entry;
unsigned queue_pos;
unsigned entry_seq;
int delta;
SDL_bool status = SDL_FALSE;
SDL_LockMutex(queue->mutex);
queue_pos = (unsigned)queue->enqueue_pos.value;
entry = &queue->entries[queue_pos & WRAP_MASK];
entry_seq = (unsigned)entry->sequence.value;
delta = (int)(entry_seq - queue_pos);
if (delta == 0) {
++queue->enqueue_pos.value;
/* We own the object, fill it! */
entry->event = *event;
entry->sequence.value = (int)(queue_pos + 1);
status = SDL_TRUE;
} else if (delta < 0) {
/* We ran into an old queue entry, which means it still needs to be dequeued */
} else {
SDL_Log("ERROR: mutex failed!\n");
}
SDL_UnlockMutex(queue->mutex);
return status;
}
static SDL_bool DequeueEvent_Mutex(SDL_EventQueue *queue, SDL_Event *event)
{
SDL_EventQueueEntry *entry;
unsigned queue_pos;
unsigned entry_seq;
int delta;
SDL_bool status = SDL_FALSE;
SDL_LockMutex(queue->mutex);
queue_pos = (unsigned)queue->dequeue_pos.value;
entry = &queue->entries[queue_pos & WRAP_MASK];
entry_seq = (unsigned)entry->sequence.value;
delta = (int)(entry_seq - (queue_pos + 1));
if (delta == 0) {
++queue->dequeue_pos.value;
/* We own the object, fill it! */
*event = entry->event;
entry->sequence.value = (int)(queue_pos + MAX_ENTRIES);
status = SDL_TRUE;
} else if (delta < 0) {
/* We ran into an old queue entry, which means we've hit empty */
} else {
SDL_Log("ERROR: mutex failed!\n");
}
SDL_UnlockMutex(queue->mutex);
return status;
}
typedef struct
{
SDL_EventQueue *queue;
int index;
char padding1[SDL_CACHELINE_SIZE - (sizeof(SDL_EventQueue *) + sizeof(int)) % SDL_CACHELINE_SIZE];
int waits;
SDL_bool lock_free;
char padding2[SDL_CACHELINE_SIZE - sizeof(int) - sizeof(SDL_bool)];
SDL_Thread *thread;
} WriterData;
typedef struct
{
SDL_EventQueue *queue;
int counters[NUM_WRITERS];
int waits;
SDL_bool lock_free;
char padding[SDL_CACHELINE_SIZE - (sizeof(SDL_EventQueue *) + sizeof(int) * NUM_WRITERS + sizeof(int) + sizeof(SDL_bool)) % SDL_CACHELINE_SIZE];
SDL_Thread *thread;
} ReaderData;
static int SDLCALL FIFO_Writer(void *_data)
{
WriterData *data = (WriterData *)_data;
SDL_EventQueue *queue = data->queue;
int i;
SDL_Event event;
event.type = SDL_USEREVENT;
event.user.windowID = 0;
event.user.code = 0;
event.user.data1 = data;
event.user.data2 = NULL;
if (data->lock_free) {
for (i = 0; i < EVENTS_PER_WRITER; ++i) {
event.user.code = i;
while (!EnqueueEvent_LockFree(queue, &event)) {
++data->waits;
SDL_Delay(0);
}
}
} else {
for (i = 0; i < EVENTS_PER_WRITER; ++i) {
event.user.code = i;
while (!EnqueueEvent_Mutex(queue, &event)) {
++data->waits;
SDL_Delay(0);
}
}
}
return 0;
}
static int SDLCALL FIFO_Reader(void *_data)
{
ReaderData *data = (ReaderData *)_data;
SDL_EventQueue *queue = data->queue;
SDL_Event event;
if (data->lock_free) {
for (;;) {
if (DequeueEvent_LockFree(queue, &event)) {
WriterData *writer = (WriterData *)event.user.data1;
++data->counters[writer->index];
} else if (SDL_AtomicGet(&queue->active)) {
++data->waits;
SDL_Delay(0);
} else {
/* We drained the queue, we're done! */
break;
}
}
} else {
for (;;) {
if (DequeueEvent_Mutex(queue, &event)) {
WriterData *writer = (WriterData *)event.user.data1;
++data->counters[writer->index];
} else if (SDL_AtomicGet(&queue->active)) {
++data->waits;
SDL_Delay(0);
} else {
/* We drained the queue, we're done! */
break;
}
}
}
return 0;
}
#ifdef TEST_SPINLOCK_FIFO
/* This thread periodically locks the queue for no particular reason */
static int SDLCALL FIFO_Watcher(void *_data)
{
SDL_EventQueue *queue = (SDL_EventQueue *)_data;
while (SDL_AtomicGet(&queue->active)) {
SDL_AtomicLock(&queue->lock);
SDL_AtomicIncRef(&queue->watcher);
while (SDL_AtomicGet(&queue->rwcount) > 0) {
SDL_Delay(0);
}
/* Do queue manipulation here... */
(void)SDL_AtomicDecRef(&queue->watcher);
SDL_AtomicUnlock(&queue->lock);
/* Wait a bit... */
SDL_Delay(1);
}
return 0;
}
#endif /* TEST_SPINLOCK_FIFO */
static void RunFIFOTest(SDL_bool lock_free)
{
SDL_EventQueue queue;
SDL_Thread *fifo_thread = NULL;
WriterData writerData[NUM_WRITERS];
ReaderData readerData[NUM_READERS];
Uint32 start, end;
int i, j;
int grand_total;
char textBuffer[1024];
size_t len;
SDL_Log("\nFIFO test---------------------------------------\n\n");
SDL_Log("Mode: %s\n", lock_free ? "LockFree" : "Mutex");
SDL_memset(&queue, 0xff, sizeof(queue));
InitEventQueue(&queue);
if (!lock_free) {
queue.mutex = SDL_CreateMutex();
}
start = SDL_GetTicks();
#ifdef TEST_SPINLOCK_FIFO
/* Start a monitoring thread */
if (lock_free) {
fifo_thread = SDL_CreateThread(FIFO_Watcher, "FIFOWatcher", &queue);
}
#endif
/* Start the readers first */
SDL_Log("Starting %d readers\n", NUM_READERS);
SDL_zeroa(readerData);
for (i = 0; i < NUM_READERS; ++i) {
char name[64];
(void)SDL_snprintf(name, sizeof(name), "FIFOReader%d", i);
readerData[i].queue = &queue;
readerData[i].lock_free = lock_free;
readerData[i].thread = SDL_CreateThread(FIFO_Reader, name, &readerData[i]);
}
/* Start up the writers */
SDL_Log("Starting %d writers\n", NUM_WRITERS);
SDL_zeroa(writerData);
for (i = 0; i < NUM_WRITERS; ++i) {
char name[64];
(void)SDL_snprintf(name, sizeof(name), "FIFOWriter%d", i);
writerData[i].queue = &queue;
writerData[i].index = i;
writerData[i].lock_free = lock_free;
writerData[i].thread = SDL_CreateThread(FIFO_Writer, name, &writerData[i]);
}
/* Wait for the writers */
for (i = 0; i < NUM_WRITERS; ++i) {
SDL_WaitThread(writerData[i].thread, NULL);
}
/* Shut down the queue so readers exit */
SDL_AtomicSet(&queue.active, 0);
/* Wait for the readers */
for (i = 0; i < NUM_READERS; ++i) {
SDL_WaitThread(readerData[i].thread, NULL);
}
end = SDL_GetTicks();
/* Wait for the FIFO thread */
if (fifo_thread) {
SDL_WaitThread(fifo_thread, NULL);
}
if (!lock_free) {
SDL_DestroyMutex(queue.mutex);
}
SDL_Log("Finished in %f sec\n", (end - start) / 1000.f);
SDL_Log("\n");
for (i = 0; i < NUM_WRITERS; ++i) {
SDL_Log("Writer %d wrote %d events, had %d waits\n", i, EVENTS_PER_WRITER, writerData[i].waits);
}
SDL_Log("Writers wrote %d total events\n", NUM_WRITERS * EVENTS_PER_WRITER);
/* Print a breakdown of which readers read messages from which writer */
SDL_Log("\n");
grand_total = 0;
for (i = 0; i < NUM_READERS; ++i) {
int total = 0;
for (j = 0; j < NUM_WRITERS; ++j) {
total += readerData[i].counters[j];
}
grand_total += total;
SDL_Log("Reader %d read %d events, had %d waits\n", i, total, readerData[i].waits);
(void)SDL_snprintf(textBuffer, sizeof(textBuffer), " { ");
for (j = 0; j < NUM_WRITERS; ++j) {
if (j > 0) {
len = SDL_strlen(textBuffer);
(void)SDL_snprintf(textBuffer + len, sizeof(textBuffer) - len, ", ");
}
len = SDL_strlen(textBuffer);
(void)SDL_snprintf(textBuffer + len, sizeof(textBuffer) - len, "%d", readerData[i].counters[j]);
}
len = SDL_strlen(textBuffer);
(void)SDL_snprintf(textBuffer + len, sizeof(textBuffer) - len, " }\n");
SDL_Log("%s", textBuffer);
}
SDL_Log("Readers read %d total events\n", grand_total);
}
/* End FIFO test */
/**************************************************************************/
int main(int argc, char *argv[])
{
/* Enable standard application logging */
SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);
RunBasicTest();
if (SDL_getenv("SDL_TESTS_QUICK") != NULL) {
SDL_Log("Not running slower tests");
return 0;
}
RunEpicTest();
/* This test is really slow, so don't run it by default */
#if 0
RunFIFOTest(SDL_FALSE);
#endif
RunFIFOTest(SDL_TRUE);
return 0;
}
/* vi: set ts=4 sw=4 expandtab: */

View File

@ -0,0 +1,167 @@
/*
Copyright (C) 1997-2024 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely.
*/
#include "SDL.h"
#include <stdlib.h>
#ifdef __EMSCRIPTEN__
#include <emscripten/emscripten.h>
#endif
static SDL_Window *window = NULL;
static SDL_Renderer *renderer = NULL;
static SDL_AudioSpec spec;
static SDL_AudioDeviceID devid_in = 0;
static SDL_AudioDeviceID devid_out = 0;
static void
loop()
{
SDL_bool please_quit = SDL_FALSE;
SDL_Event e;
while (SDL_PollEvent(&e)) {
if (e.type == SDL_QUIT) {
please_quit = SDL_TRUE;
} else if (e.type == SDL_KEYDOWN) {
if (e.key.keysym.sym == SDLK_ESCAPE) {
please_quit = SDL_TRUE;
}
} else if (e.type == SDL_MOUSEBUTTONDOWN) {
if (e.button.button == 1) {
SDL_PauseAudioDevice(devid_out, SDL_TRUE);
SDL_PauseAudioDevice(devid_in, SDL_FALSE);
}
} else if (e.type == SDL_MOUSEBUTTONUP) {
if (e.button.button == 1) {
SDL_PauseAudioDevice(devid_in, SDL_TRUE);
SDL_PauseAudioDevice(devid_out, SDL_FALSE);
}
}
}
if (SDL_GetAudioDeviceStatus(devid_in) == SDL_AUDIO_PLAYING) {
SDL_SetRenderDrawColor(renderer, 0, 255, 0, 255);
} else {
SDL_SetRenderDrawColor(renderer, 255, 0, 0, 255);
}
SDL_RenderClear(renderer);
SDL_RenderPresent(renderer);
if (please_quit) {
/* stop playing back, quit. */
SDL_Log("Shutting down.\n");
SDL_PauseAudioDevice(devid_in, 1);
SDL_CloseAudioDevice(devid_in);
SDL_PauseAudioDevice(devid_out, 1);
SDL_CloseAudioDevice(devid_out);
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();
#ifdef __EMSCRIPTEN__
emscripten_cancel_main_loop();
#endif
exit(0);
}
/* Note that it would be easier to just have a one-line function that
calls SDL_QueueAudio() as a capture device callback, but we're
trying to test the API, so we use SDL_DequeueAudio() here. */
while (SDL_TRUE) {
Uint8 buf[1024];
const Uint32 br = SDL_DequeueAudio(devid_in, buf, sizeof(buf));
SDL_QueueAudio(devid_out, buf, br);
if (br < sizeof(buf)) {
break;
}
}
}
int main(int argc, char **argv)
{
/* (argv[1] == NULL means "open default device.") */
const char *devname = argv[1];
SDL_AudioSpec wanted;
int devcount;
int i;
/* Enable standard application logging */
SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);
/* Load the SDL library */
if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO) < 0) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't initialize SDL: %s\n", SDL_GetError());
return 1;
}
window = SDL_CreateWindow("testaudiocapture", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 320, 240, 0);
renderer = SDL_CreateRenderer(window, -1, 0);
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
SDL_RenderClear(renderer);
SDL_RenderPresent(renderer);
SDL_Log("Using audio driver: %s\n", SDL_GetCurrentAudioDriver());
devcount = SDL_GetNumAudioDevices(SDL_TRUE);
for (i = 0; i < devcount; i++) {
SDL_Log(" Capture device #%d: '%s'\n", i, SDL_GetAudioDeviceName(i, SDL_TRUE));
}
SDL_zero(wanted);
wanted.freq = 44100;
wanted.format = AUDIO_F32SYS;
wanted.channels = 1;
wanted.samples = 4096;
wanted.callback = NULL;
SDL_zero(spec);
/* DirectSound can fail in some instances if you open the same hardware
for both capture and output and didn't open the output end first,
according to the docs, so if you're doing something like this, always
open your capture devices second in case you land in those bizarre
circumstances. */
SDL_Log("Opening default playback device...\n");
devid_out = SDL_OpenAudioDevice(NULL, SDL_FALSE, &wanted, &spec, SDL_AUDIO_ALLOW_ANY_CHANGE);
if (!devid_out) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't open an audio device for playback: %s!\n", SDL_GetError());
SDL_Quit();
exit(1);
}
SDL_Log("Opening capture device %s%s%s...\n",
devname ? "'" : "",
devname ? devname : "[[default]]",
devname ? "'" : "");
devid_in = SDL_OpenAudioDevice(argv[1], SDL_TRUE, &spec, &spec, 0);
if (!devid_in) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't open an audio device for capture: %s!\n", SDL_GetError());
SDL_Quit();
exit(1);
}
SDL_Log("Ready! Hold down mouse or finger to record!\n");
#ifdef __EMSCRIPTEN__
emscripten_set_main_loop(loop, 0, 1);
#else
while (1) {
loop();
SDL_Delay(16);
}
#endif
return 0;
}

View File

@ -0,0 +1,205 @@
/*
Copyright (C) 1997-2024 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely.
*/
/* Program to test hotplugging of audio devices */
#include "SDL_config.h"
#include <stdio.h>
#include <stdlib.h>
#ifdef HAVE_SIGNAL_H
#include <signal.h>
#endif
#ifdef __EMSCRIPTEN__
#include <emscripten/emscripten.h>
#endif
#include "SDL.h"
#include "testutils.h"
static SDL_AudioSpec spec;
static Uint8 *sound = NULL; /* Pointer to wave data */
static Uint32 soundlen = 0; /* Length of wave data */
static int posindex = 0;
static Uint32 positions[64];
/* Call this instead of exit(), so we can clean up SDL: atexit() is evil. */
static void
quit(int rc)
{
SDL_Quit();
exit(rc);
}
void SDLCALL
fillerup(void *_pos, Uint8 *stream, int len)
{
Uint32 pos = *((Uint32 *)_pos);
Uint8 *waveptr;
int waveleft;
/* Set up the pointers */
waveptr = sound + pos;
waveleft = soundlen - pos;
/* Go! */
while (waveleft <= len) {
SDL_memcpy(stream, waveptr, waveleft);
stream += waveleft;
len -= waveleft;
waveptr = sound;
waveleft = soundlen;
pos = 0;
}
SDL_memcpy(stream, waveptr, len);
pos += len;
*((Uint32 *)_pos) = pos;
}
static int done = 0;
void poked(int sig)
{
done = 1;
}
static const char *
devtypestr(int iscapture)
{
return iscapture ? "capture" : "output";
}
static void
iteration()
{
SDL_Event e;
SDL_AudioDeviceID dev;
while (SDL_PollEvent(&e)) {
if (e.type == SDL_QUIT) {
done = 1;
} else if (e.type == SDL_KEYUP) {
if (e.key.keysym.sym == SDLK_ESCAPE) {
done = 1;
}
} else if (e.type == SDL_AUDIODEVICEADDED) {
int index = e.adevice.which;
int iscapture = e.adevice.iscapture;
const char *name = SDL_GetAudioDeviceName(index, iscapture);
if (name) {
SDL_Log("New %s audio device at index %u: %s\n", devtypestr(iscapture), (unsigned int)index, name);
} else {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Got new %s device at index %u, but failed to get the name: %s\n",
devtypestr(iscapture), (unsigned int)index, SDL_GetError());
continue;
}
if (!iscapture) {
positions[posindex] = 0;
spec.userdata = &positions[posindex++];
spec.callback = fillerup;
dev = SDL_OpenAudioDevice(name, 0, &spec, NULL, 0);
if (!dev) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't open '%s': %s\n", name, SDL_GetError());
} else {
SDL_Log("Opened '%s' as %u\n", name, (unsigned int)dev);
SDL_PauseAudioDevice(dev, 0);
}
}
} else if (e.type == SDL_AUDIODEVICEREMOVED) {
dev = (SDL_AudioDeviceID)e.adevice.which;
SDL_Log("%s device %u removed.\n", devtypestr(e.adevice.iscapture), (unsigned int)dev);
SDL_CloseAudioDevice(dev);
}
}
}
#ifdef __EMSCRIPTEN__
void loop()
{
if (done)
emscripten_cancel_main_loop();
else
iteration();
}
#endif
int main(int argc, char *argv[])
{
int i;
char *filename = NULL;
/* Enable standard application logging */
SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);
/* Load the SDL library */
if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO) < 0) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't initialize SDL: %s\n", SDL_GetError());
return 1;
}
/* Some targets (Mac CoreAudio) need an event queue for audio hotplug, so make and immediately hide a window. */
SDL_MinimizeWindow(SDL_CreateWindow("testaudiohotplug", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 640, 480, 0));
filename = GetResourceFilename(argc > 1 ? argv[1] : NULL, "sample.wav");
if (!filename) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "%s\n", SDL_GetError());
quit(1);
}
/* Load the wave file into memory */
if (SDL_LoadWAV(filename, &spec, &sound, &soundlen) == NULL) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't load %s: %s\n", filename, SDL_GetError());
quit(1);
}
#ifdef HAVE_SIGNAL_H
/* Set the signals */
#ifdef SIGHUP
(void)signal(SIGHUP, poked);
#endif
(void)signal(SIGINT, poked);
#ifdef SIGQUIT
(void)signal(SIGQUIT, poked);
#endif
(void)signal(SIGTERM, poked);
#endif /* HAVE_SIGNAL_H */
/* Show the list of available drivers */
SDL_Log("Available audio drivers:");
for (i = 0; i < SDL_GetNumAudioDrivers(); ++i) {
SDL_Log("%i: %s", i, SDL_GetAudioDriver(i));
}
SDL_Log("Select a driver with the SDL_AUDIODRIVER environment variable.\n");
SDL_Log("Using audio driver: %s\n", SDL_GetCurrentAudioDriver());
#ifdef __EMSCRIPTEN__
emscripten_set_main_loop(loop, 0, 1);
#else
while (!done) {
SDL_Delay(100);
iteration();
}
#endif
/* Clean up on signal */
/* Quit audio first, then free WAV. This prevents access violations in the audio threads. */
SDL_QuitSubSystem(SDL_INIT_AUDIO);
SDL_FreeWAV(sound);
SDL_free(filename);
SDL_Quit();
return 0;
}
/* vi: set ts=4 sw=4 expandtab: */

View File

@ -0,0 +1,103 @@
/*
Copyright (C) 1997-2024 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely.
*/
#include <stdio.h>
#include "SDL.h"
static void
print_devices(int iscapture)
{
SDL_AudioSpec spec;
const char *typestr = ((iscapture) ? "capture" : "output");
int n = SDL_GetNumAudioDevices(iscapture);
SDL_Log("Found %d %s device%s:\n", n, typestr, n != 1 ? "s" : "");
if (n == -1) {
SDL_Log(" Driver can't detect specific %s devices.\n\n", typestr);
} else if (n == 0) {
SDL_Log(" No %s devices found.\n\n", typestr);
} else {
int i;
for (i = 0; i < n; i++) {
const char *name = SDL_GetAudioDeviceName(i, iscapture);
if (name) {
SDL_Log(" %d: %s\n", i, name);
} else {
SDL_Log(" %d Error: %s\n", i, SDL_GetError());
}
if (SDL_GetAudioDeviceSpec(i, iscapture, &spec) == 0) {
SDL_Log(" Sample Rate: %d\n", spec.freq);
SDL_Log(" Channels: %d\n", spec.channels);
SDL_Log(" SDL_AudioFormat: %X\n", spec.format);
}
}
SDL_Log("\n");
}
}
int main(int argc, char **argv)
{
char *deviceName = NULL;
SDL_AudioSpec spec;
int n;
/* Enable standard application logging */
SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);
/* Load the SDL library */
if (SDL_Init(SDL_INIT_AUDIO) < 0) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't initialize SDL: %s\n", SDL_GetError());
return 1;
}
/* Print available audio drivers */
n = SDL_GetNumAudioDrivers();
if (n == 0) {
SDL_Log("No built-in audio drivers\n\n");
} else {
int i;
SDL_Log("Built-in audio drivers:\n");
for (i = 0; i < n; ++i) {
SDL_Log(" %d: %s\n", i, SDL_GetAudioDriver(i));
}
SDL_Log("Select a driver with the SDL_AUDIODRIVER environment variable.\n");
}
SDL_Log("Using audio driver: %s\n\n", SDL_GetCurrentAudioDriver());
print_devices(0);
print_devices(1);
if (SDL_GetDefaultAudioInfo(&deviceName, &spec, 0) < 0) {
SDL_Log("Error when calling SDL_GetDefaultAudioInfo: %s\n", SDL_GetError());
} else {
SDL_Log("Default Output Name: %s\n", deviceName ? deviceName : "unknown");
SDL_free(deviceName);
SDL_Log("Sample Rate: %d\n", spec.freq);
SDL_Log("Channels: %d\n", spec.channels);
SDL_Log("SDL_AudioFormat: %X\n", spec.format);
}
if (SDL_GetDefaultAudioInfo(&deviceName, &spec, 1) < 0) {
SDL_Log("Error when calling SDL_GetDefaultAudioInfo: %s\n", SDL_GetError());
} else {
SDL_Log("Default Capture Name: %s\n", deviceName ? deviceName : "unknown");
SDL_free(deviceName);
SDL_Log("Sample Rate: %d\n", spec.freq);
SDL_Log("Channels: %d\n", spec.channels);
SDL_Log("SDL_AudioFormat: %X\n", spec.format);
}
SDL_Quit();
return 0;
}

View File

@ -0,0 +1,125 @@
/*
Copyright (C) 1997-2024 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely.
*/
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include "SDL.h"
#include "SDL_test.h"
#include "testautomation_suites.h"
static SDLTest_CommonState *state;
/* Call this instead of exit(), so we can clean up SDL: atexit() is evil. */
static void
quit(int rc)
{
SDLTest_CommonQuit(state);
exit(rc);
}
int main(int argc, char *argv[])
{
int result;
int testIterations = 1;
Uint64 userExecKey = 0;
char *userRunSeed = NULL;
char *filter = NULL;
int i, done;
SDL_Event event;
/* Initialize test framework */
state = SDLTest_CommonCreateState(argv, SDL_INIT_VIDEO);
if (!state) {
return 1;
}
/* No need of windows (or update testautomation_mouse.c:mouse_getMouseFocus() */
state->num_windows = 0;
/* Parse commandline */
for (i = 1; i < argc;) {
int consumed;
consumed = SDLTest_CommonArg(state, i);
if (consumed == 0) {
consumed = -1;
if (SDL_strcasecmp(argv[i], "--iterations") == 0) {
if (argv[i + 1]) {
testIterations = SDL_atoi(argv[i + 1]);
if (testIterations < 1) {
testIterations = 1;
}
consumed = 2;
}
} else if (SDL_strcasecmp(argv[i], "--execKey") == 0) {
if (argv[i + 1]) {
(void)SDL_sscanf(argv[i + 1], "%" SDL_PRIu64, &userExecKey);
consumed = 2;
}
} else if (SDL_strcasecmp(argv[i], "--seed") == 0) {
if (argv[i + 1]) {
userRunSeed = SDL_strdup(argv[i + 1]);
consumed = 2;
}
} else if (SDL_strcasecmp(argv[i], "--filter") == 0) {
if (argv[i + 1]) {
filter = SDL_strdup(argv[i + 1]);
consumed = 2;
}
}
}
if (consumed < 0) {
static const char *options[] = { "[--iterations #]", "[--execKey #]", "[--seed string]", "[--filter suite_name|test_name]", NULL };
SDLTest_CommonLogUsage(state, argv[0], options);
quit(1);
}
i += consumed;
}
/* Initialize common state */
if (!SDLTest_CommonInit(state)) {
quit(2);
}
/* Create the windows, initialize the renderers */
for (i = 0; i < state->num_windows; ++i) {
SDL_Renderer *renderer = state->renderers[i];
SDL_SetRenderDrawColor(renderer, 0xFF, 0xFF, 0xFF, 0xFF);
SDL_RenderClear(renderer);
}
/* Call Harness */
result = SDLTest_RunSuites(testSuites, userRunSeed, userExecKey, filter, testIterations);
/* Empty event queue */
done = 0;
for (i = 0; i < 100; i++) {
while (SDL_PollEvent(&event)) {
SDLTest_CommonEvent(state, &event, &done);
}
SDL_Delay(10);
}
/* Clean up */
SDL_free(userRunSeed);
SDL_free(filter);
/* Shutdown everything */
quit(result);
return result;
}
/* vi: set ts=4 sw=4 expandtab: */

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,335 @@
/**
* New/updated tests: aschiffler at ferzkopp dot net
*/
#include <stdio.h>
#include <string.h>
#include "SDL.h"
#include "SDL_test.h"
/* ================= Test Case Implementation ================== */
/* Test case functions */
/**
* \brief Check call to SDL_HasClipboardText
*
* \sa
* http://wiki.libsdl.org/SDL_HasClipboardText
*/
int clipboard_testHasClipboardText(void *arg)
{
SDL_HasClipboardText();
SDLTest_AssertPass("Call to SDL_HasClipboardText succeeded");
return TEST_COMPLETED;
}
/**
* \brief Check call to SDL_HasPrimarySelectionText
*
* \sa
* http://wiki.libsdl.org/SDL_HasPrimarySelectionText
*/
int clipboard_testHasPrimarySelectionText(void *arg)
{
SDL_HasPrimarySelectionText();
SDLTest_AssertPass("Call to SDL_HasPrimarySelectionText succeeded");
return TEST_COMPLETED;
}
/**
* \brief Check call to SDL_GetClipboardText
*
* \sa
* http://wiki.libsdl.org/SDL_GetClipboardText
*/
int clipboard_testGetClipboardText(void *arg)
{
char *charResult;
charResult = SDL_GetClipboardText();
SDLTest_AssertPass("Call to SDL_GetClipboardText succeeded");
SDL_free(charResult);
return TEST_COMPLETED;
}
/**
* \brief Check call to SDL_GetPrimarySelectionText
*
* \sa
* http://wiki.libsdl.org/SDL_GetPrimarySelectionText
*/
int clipboard_testGetPrimarySelectionText(void *arg)
{
char *charResult;
charResult = SDL_GetPrimarySelectionText();
SDLTest_AssertPass("Call to SDL_GetPrimarySelectionText succeeded");
SDL_free(charResult);
return TEST_COMPLETED;
}
/**
* \brief Check call to SDL_SetClipboardText
* \sa
* http://wiki.libsdl.org/SDL_SetClipboardText
*/
int clipboard_testSetClipboardText(void *arg)
{
char *textRef = SDLTest_RandomAsciiString();
char *text = SDL_strdup(textRef);
int result;
result = SDL_SetClipboardText(text);
SDLTest_AssertPass("Call to SDL_SetClipboardText succeeded");
SDLTest_AssertCheck(
result == 0,
"Validate SDL_SetClipboardText result, expected 0, got %i",
result);
SDLTest_AssertCheck(
SDL_strcmp(textRef, text) == 0,
"Verify SDL_SetClipboardText did not modify input string, expected '%s', got '%s'",
textRef, text);
/* Cleanup */
SDL_free(textRef);
SDL_free(text);
return TEST_COMPLETED;
}
/**
* \brief Check call to SDL_SetPrimarySelectionText
* \sa
* http://wiki.libsdl.org/SDL_SetPrimarySelectionText
*/
int clipboard_testSetPrimarySelectionText(void *arg)
{
char *textRef = SDLTest_RandomAsciiString();
char *text = SDL_strdup(textRef);
int result;
result = SDL_SetPrimarySelectionText(text);
SDLTest_AssertPass("Call to SDL_SetPrimarySelectionText succeeded");
SDLTest_AssertCheck(
result == 0,
"Validate SDL_SetPrimarySelectionText result, expected 0, got %i",
result);
SDLTest_AssertCheck(
SDL_strcmp(textRef, text) == 0,
"Verify SDL_SetPrimarySelectionText did not modify input string, expected '%s', got '%s'",
textRef, text);
/* Cleanup */
SDL_free(textRef);
SDL_free(text);
return TEST_COMPLETED;
}
/**
* \brief End-to-end test of SDL_xyzClipboardText functions
* \sa
* http://wiki.libsdl.org/SDL_HasClipboardText
* http://wiki.libsdl.org/SDL_GetClipboardText
* http://wiki.libsdl.org/SDL_SetClipboardText
*/
int clipboard_testClipboardTextFunctions(void *arg)
{
char *textRef = SDLTest_RandomAsciiString();
char *text = SDL_strdup(textRef);
SDL_bool boolResult;
int intResult;
char *charResult;
/* Clear clipboard text state */
boolResult = SDL_HasClipboardText();
SDLTest_AssertPass("Call to SDL_HasClipboardText succeeded");
if (boolResult == SDL_TRUE) {
intResult = SDL_SetClipboardText(NULL);
SDLTest_AssertPass("Call to SDL_SetClipboardText(NULL) succeeded");
SDLTest_AssertCheck(
intResult == 0,
"Verify result from SDL_SetClipboardText(NULL), expected 0, got %i",
intResult);
charResult = SDL_GetClipboardText();
SDLTest_AssertPass("Call to SDL_GetClipboardText succeeded");
SDL_free(charResult);
boolResult = SDL_HasClipboardText();
SDLTest_AssertPass("Call to SDL_HasClipboardText succeeded");
SDLTest_AssertCheck(
boolResult == SDL_FALSE,
"Verify SDL_HasClipboardText returned SDL_FALSE, got %s",
(boolResult) ? "SDL_TRUE" : "SDL_FALSE");
}
/* Empty clipboard */
charResult = SDL_GetClipboardText();
SDLTest_AssertPass("Call to SDL_GetClipboardText succeeded");
SDLTest_Assert(
charResult != NULL,
"Verify SDL_GetClipboardText did not return NULL");
SDLTest_AssertCheck(
charResult[0] == '\0', /* NOLINT(clang-analyzer-core.NullDereference): Checked for NULL above */
"Verify SDL_GetClipboardText returned string with length 0, got length %i",
(int)SDL_strlen(charResult));
intResult = SDL_SetClipboardText(text);
SDLTest_AssertPass("Call to SDL_SetClipboardText succeeded");
SDLTest_AssertCheck(
intResult == 0,
"Verify result from SDL_SetClipboardText(NULL), expected 0, got %i",
intResult);
SDLTest_AssertCheck(
SDL_strcmp(textRef, text) == 0,
"Verify SDL_SetClipboardText did not modify input string, expected '%s', got '%s'",
textRef, text);
boolResult = SDL_HasClipboardText();
SDLTest_AssertPass("Call to SDL_HasClipboardText succeeded");
SDLTest_AssertCheck(
boolResult == SDL_TRUE,
"Verify SDL_HasClipboardText returned SDL_TRUE, got %s",
(boolResult) ? "SDL_TRUE" : "SDL_FALSE");
SDL_free(charResult);
charResult = SDL_GetClipboardText();
SDLTest_AssertPass("Call to SDL_GetClipboardText succeeded");
SDLTest_AssertCheck(
SDL_strcmp(textRef, charResult) == 0,
"Verify SDL_GetClipboardText returned correct string, expected '%s', got '%s'",
textRef, charResult);
/* Cleanup */
SDL_free(textRef);
SDL_free(text);
SDL_free(charResult);
return TEST_COMPLETED;
}
/**
* \brief End-to-end test of SDL_xyzPrimarySelectionText functions
* \sa
* http://wiki.libsdl.org/SDL_HasPrimarySelectionText
* http://wiki.libsdl.org/SDL_GetPrimarySelectionText
* http://wiki.libsdl.org/SDL_SetPrimarySelectionText
*/
int clipboard_testPrimarySelectionTextFunctions(void *arg)
{
char *textRef = SDLTest_RandomAsciiString();
char *text = SDL_strdup(textRef);
SDL_bool boolResult;
int intResult;
char *charResult;
/* Clear primary selection text state */
boolResult = SDL_HasPrimarySelectionText();
SDLTest_AssertPass("Call to SDL_HasPrimarySelectionText succeeded");
if (boolResult == SDL_TRUE) {
intResult = SDL_SetPrimarySelectionText(NULL);
SDLTest_AssertPass("Call to SDL_SetPrimarySelectionText(NULL) succeeded");
SDLTest_AssertCheck(
intResult == 0,
"Verify result from SDL_SetPrimarySelectionText(NULL), expected 0, got %i",
intResult);
charResult = SDL_GetPrimarySelectionText();
SDLTest_AssertPass("Call to SDL_GetPrimarySelectionText succeeded");
SDL_free(charResult);
boolResult = SDL_HasPrimarySelectionText();
SDLTest_AssertPass("Call to SDL_HasPrimarySelectionText succeeded");
SDLTest_AssertCheck(
boolResult == SDL_FALSE,
"Verify SDL_HasPrimarySelectionText returned SDL_FALSE, got %s",
(boolResult) ? "SDL_TRUE" : "SDL_FALSE");
}
/* Empty primary selection */
charResult = SDL_GetPrimarySelectionText();
SDLTest_AssertPass("Call to SDL_GetPrimarySelectionText succeeded");
SDLTest_Assert(
charResult != NULL,
"Verify SDL_GetPrimarySelectionText did not return NULL");
SDLTest_AssertCheck(
charResult[0] == '\0', /* NOLINT(clang-analyzer-core.NullDereference): Checked for NULL above */
"Verify SDL_GetPrimarySelectionText returned string with length 0, got length %i",
(int)SDL_strlen(charResult));
intResult = SDL_SetPrimarySelectionText(text);
SDLTest_AssertPass("Call to SDL_SetPrimarySelectionText succeeded");
SDLTest_AssertCheck(
intResult == 0,
"Verify result from SDL_SetPrimarySelectionText(NULL), expected 0, got %i",
intResult);
SDLTest_AssertCheck(
SDL_strcmp(textRef, text) == 0,
"Verify SDL_SetPrimarySelectionText did not modify input string, expected '%s', got '%s'",
textRef, text);
boolResult = SDL_HasPrimarySelectionText();
SDLTest_AssertPass("Call to SDL_HasPrimarySelectionText succeeded");
SDLTest_AssertCheck(
boolResult == SDL_TRUE,
"Verify SDL_HasPrimarySelectionText returned SDL_TRUE, got %s",
(boolResult) ? "SDL_TRUE" : "SDL_FALSE");
SDL_free(charResult);
charResult = SDL_GetPrimarySelectionText();
SDLTest_AssertPass("Call to SDL_GetPrimarySelectionText succeeded");
SDLTest_AssertCheck(
SDL_strcmp(textRef, charResult) == 0,
"Verify SDL_GetPrimarySelectionText returned correct string, expected '%s', got '%s'",
textRef, charResult);
/* Cleanup */
SDL_free(textRef);
SDL_free(text);
SDL_free(charResult);
return TEST_COMPLETED;
}
/* ================= Test References ================== */
/* Clipboard test cases */
static const SDLTest_TestCaseReference clipboardTest1 = {
(SDLTest_TestCaseFp)clipboard_testHasClipboardText, "clipboard_testHasClipboardText", "Check call to SDL_HasClipboardText", TEST_ENABLED
};
static const SDLTest_TestCaseReference clipboardTest2 = {
(SDLTest_TestCaseFp)clipboard_testHasPrimarySelectionText, "clipboard_testHasPrimarySelectionText", "Check call to SDL_HasPrimarySelectionText", TEST_ENABLED
};
static const SDLTest_TestCaseReference clipboardTest3 = {
(SDLTest_TestCaseFp)clipboard_testGetClipboardText, "clipboard_testGetClipboardText", "Check call to SDL_GetClipboardText", TEST_ENABLED
};
static const SDLTest_TestCaseReference clipboardTest4 = {
(SDLTest_TestCaseFp)clipboard_testGetPrimarySelectionText, "clipboard_testGetPrimarySelectionText", "Check call to SDL_GetPrimarySelectionText", TEST_ENABLED
};
static const SDLTest_TestCaseReference clipboardTest5 = {
(SDLTest_TestCaseFp)clipboard_testSetClipboardText, "clipboard_testSetClipboardText", "Check call to SDL_SetClipboardText", TEST_ENABLED
};
static const SDLTest_TestCaseReference clipboardTest6 = {
(SDLTest_TestCaseFp)clipboard_testSetPrimarySelectionText, "clipboard_testSetPrimarySelectionText", "Check call to SDL_SetPrimarySelectionText", TEST_ENABLED
};
static const SDLTest_TestCaseReference clipboardTest7 = {
(SDLTest_TestCaseFp)clipboard_testClipboardTextFunctions, "clipboard_testClipboardTextFunctions", "End-to-end test of SDL_xyzClipboardText functions", TEST_ENABLED
};
static const SDLTest_TestCaseReference clipboardTest8 = {
(SDLTest_TestCaseFp)clipboard_testPrimarySelectionTextFunctions, "clipboard_testPrimarySelectionTextFunctions", "End-to-end test of SDL_xyzPrimarySelectionText functions", TEST_ENABLED
};
/* Sequence of Clipboard test cases */
static const SDLTest_TestCaseReference *clipboardTests[] = {
&clipboardTest1, &clipboardTest2, &clipboardTest3, &clipboardTest4, &clipboardTest5, &clipboardTest6, &clipboardTest7, &clipboardTest8, NULL
};
/* Clipboard test suite (global) */
SDLTest_TestSuiteReference clipboardTestSuite = {
"Clipboard",
NULL,
clipboardTests,
NULL
};

View File

@ -0,0 +1,203 @@
/**
* Events test suite
*/
#include <stdio.h>
#include "SDL.h"
#include "SDL_test.h"
/* ================= Test Case Implementation ================== */
/* Test case functions */
/* Flag indicating if the userdata should be checked */
int _userdataCheck = 0;
/* Userdata value to check */
int _userdataValue = 0;
/* Flag indicating that the filter was called */
int _eventFilterCalled = 0;
/* Userdata values for event */
int _userdataValue1 = 1;
int _userdataValue2 = 2;
/* Event filter that sets some flags and optionally checks userdata */
int SDLCALL _events_sampleNullEventFilter(void *userdata, SDL_Event *event)
{
_eventFilterCalled = 1;
if (_userdataCheck != 0) {
SDLTest_AssertCheck(userdata != NULL, "Check userdata pointer, expected: non-NULL, got: %s", (userdata != NULL) ? "non-NULL" : "NULL");
if (userdata != NULL) {
SDLTest_AssertCheck(*(int *)userdata == _userdataValue, "Check userdata value, expected: %i, got: %i", _userdataValue, *(int *)userdata);
}
}
return 0;
}
/**
* @brief Test pumping and peeking events.
*
* @sa http://wiki.libsdl.org/SDL_PumpEvents
* @sa http://wiki.libsdl.org/SDL_PollEvent
*/
int events_pushPumpAndPollUserevent(void *arg)
{
SDL_Event event1;
SDL_Event event2;
int result;
/* Create user event */
event1.type = SDL_USEREVENT;
event1.user.code = SDLTest_RandomSint32();
event1.user.data1 = (void *)&_userdataValue1;
event1.user.data2 = (void *)&_userdataValue2;
/* Push a user event onto the queue and force queue update */
SDL_PushEvent(&event1);
SDLTest_AssertPass("Call to SDL_PushEvent()");
SDL_PumpEvents();
SDLTest_AssertPass("Call to SDL_PumpEvents()");
/* Poll for user event */
result = SDL_PollEvent(&event2);
SDLTest_AssertPass("Call to SDL_PollEvent()");
SDLTest_AssertCheck(result == 1, "Check result from SDL_PollEvent, expected: 1, got: %d", result);
/* Need to finish getting all events and sentinel, otherwise other tests that rely on event are in bad state */
while (SDL_PollEvent(&event2)) {
}
return TEST_COMPLETED;
}
/**
* @brief Adds and deletes an event watch function with NULL userdata
*
* @sa http://wiki.libsdl.org/SDL_AddEventWatch
* @sa http://wiki.libsdl.org/SDL_DelEventWatch
*
*/
int events_addDelEventWatch(void *arg)
{
SDL_Event event;
/* Create user event */
event.type = SDL_USEREVENT;
event.user.code = SDLTest_RandomSint32();
event.user.data1 = (void *)&_userdataValue1;
event.user.data2 = (void *)&_userdataValue2;
/* Disable userdata check */
_userdataCheck = 0;
/* Reset event filter call tracker */
_eventFilterCalled = 0;
/* Add watch */
SDL_AddEventWatch(_events_sampleNullEventFilter, NULL);
SDLTest_AssertPass("Call to SDL_AddEventWatch()");
/* Push a user event onto the queue and force queue update */
SDL_PushEvent(&event);
SDLTest_AssertPass("Call to SDL_PushEvent()");
SDL_PumpEvents();
SDLTest_AssertPass("Call to SDL_PumpEvents()");
SDLTest_AssertCheck(_eventFilterCalled == 1, "Check that event filter was called");
/* Delete watch */
SDL_DelEventWatch(_events_sampleNullEventFilter, NULL);
SDLTest_AssertPass("Call to SDL_DelEventWatch()");
/* Push a user event onto the queue and force queue update */
_eventFilterCalled = 0;
SDL_PushEvent(&event);
SDLTest_AssertPass("Call to SDL_PushEvent()");
SDL_PumpEvents();
SDLTest_AssertPass("Call to SDL_PumpEvents()");
SDLTest_AssertCheck(_eventFilterCalled == 0, "Check that event filter was NOT called");
return TEST_COMPLETED;
}
/**
* @brief Adds and deletes an event watch function with userdata
*
* @sa http://wiki.libsdl.org/SDL_AddEventWatch
* @sa http://wiki.libsdl.org/SDL_DelEventWatch
*
*/
int events_addDelEventWatchWithUserdata(void *arg)
{
SDL_Event event;
/* Create user event */
event.type = SDL_USEREVENT;
event.user.code = SDLTest_RandomSint32();
event.user.data1 = (void *)&_userdataValue1;
event.user.data2 = (void *)&_userdataValue2;
/* Enable userdata check and set a value to check */
_userdataCheck = 1;
_userdataValue = SDLTest_RandomIntegerInRange(-1024, 1024);
/* Reset event filter call tracker */
_eventFilterCalled = 0;
/* Add watch */
SDL_AddEventWatch(_events_sampleNullEventFilter, (void *)&_userdataValue);
SDLTest_AssertPass("Call to SDL_AddEventWatch()");
/* Push a user event onto the queue and force queue update */
SDL_PushEvent(&event);
SDLTest_AssertPass("Call to SDL_PushEvent()");
SDL_PumpEvents();
SDLTest_AssertPass("Call to SDL_PumpEvents()");
SDLTest_AssertCheck(_eventFilterCalled == 1, "Check that event filter was called");
/* Delete watch */
SDL_DelEventWatch(_events_sampleNullEventFilter, (void *)&_userdataValue);
SDLTest_AssertPass("Call to SDL_DelEventWatch()");
/* Push a user event onto the queue and force queue update */
_eventFilterCalled = 0;
SDL_PushEvent(&event);
SDLTest_AssertPass("Call to SDL_PushEvent()");
SDL_PumpEvents();
SDLTest_AssertPass("Call to SDL_PumpEvents()");
SDLTest_AssertCheck(_eventFilterCalled == 0, "Check that event filter was NOT called");
return TEST_COMPLETED;
}
/* ================= Test References ================== */
/* Events test cases */
static const SDLTest_TestCaseReference eventsTest1 = {
(SDLTest_TestCaseFp)events_pushPumpAndPollUserevent, "events_pushPumpAndPollUserevent", "Pushes, pumps and polls a user event", TEST_ENABLED
};
static const SDLTest_TestCaseReference eventsTest2 = {
(SDLTest_TestCaseFp)events_addDelEventWatch, "events_addDelEventWatch", "Adds and deletes an event watch function with NULL userdata", TEST_ENABLED
};
static const SDLTest_TestCaseReference eventsTest3 = {
(SDLTest_TestCaseFp)events_addDelEventWatchWithUserdata, "events_addDelEventWatchWithUserdata", "Adds and deletes an event watch function with userdata", TEST_ENABLED
};
/* Sequence of Events test cases */
static const SDLTest_TestCaseReference *eventsTests[] = {
&eventsTest1, &eventsTest2, &eventsTest3, NULL
};
/* Events test suite (global) */
SDLTest_TestSuiteReference eventsTestSuite = {
"Events",
NULL,
eventsTests,
NULL
};

View File

@ -0,0 +1,171 @@
/**
* GUID test suite
*/
#include "SDL.h"
#include "SDL_test.h"
#ifdef HAVE_STDINT_H
#include <stdint.h>
#endif
/* ================= Test Case Implementation ================== */
/* Helper functions */
#define NUM_TEST_GUIDS 5
#ifndef UINT64_C
#ifdef _MSC_VER
#define UINT64_C(x) x##ui64
#elif defined(_LP64)
#define UINT64_C(x) x##UL
#else
#define UINT64_C(x) x##ULL
#endif
#endif
static struct
{
char *str;
Uint64 upper, lower;
} test_guids[NUM_TEST_GUIDS] = {
{ "0000000000000000"
"ffffffffffffffff",
UINT64_C(0x0000000000000000), UINT64_C(0xffffffffffffffff) },
{ "0011223344556677"
"8091a2b3c4d5e6f0",
UINT64_C(0x0011223344556677), UINT64_C(0x8091a2b3c4d5e6f0) },
{ "a011223344556677"
"8091a2b3c4d5e6f0",
UINT64_C(0xa011223344556677), UINT64_C(0x8091a2b3c4d5e6f0) },
{ "a011223344556677"
"8091a2b3c4d5e6f1",
UINT64_C(0xa011223344556677), UINT64_C(0x8091a2b3c4d5e6f1) },
{ "a011223344556677"
"8191a2b3c4d5e6f0",
UINT64_C(0xa011223344556677), UINT64_C(0x8191a2b3c4d5e6f0) },
};
static void
upper_lower_to_bytestring(Uint8 *out, Uint64 upper, Uint64 lower)
{
Uint64 values[2];
int i, k;
values[0] = upper;
values[1] = lower;
for (i = 0; i < 2; ++i) {
Uint64 v = values[i];
for (k = 0; k < 8; ++k) {
*out++ = v >> 56;
v <<= 8;
}
}
}
/* Test case functions */
/**
* @brief Check String-to-GUID conversion
*
* @sa SDL_GUIDFromString
*/
static int
TestGuidFromString(void *arg)
{
int i;
SDLTest_AssertPass("Call to SDL_GUIDFromString");
for (i = 0; i < NUM_TEST_GUIDS; ++i) {
Uint8 expected[16];
SDL_GUID guid;
upper_lower_to_bytestring(expected,
test_guids[i].upper, test_guids[i].lower);
guid = SDL_GUIDFromString(test_guids[i].str);
SDLTest_AssertCheck(SDL_memcmp(expected, guid.data, 16) == 0, "GUID from string, GUID was: '%s'", test_guids[i].str);
}
return TEST_COMPLETED;
}
/**
* @brief Check GUID-to-String conversion
*
* @sa SDL_GUIDToString
*/
static int
TestGuidToString(void *arg)
{
int i;
SDLTest_AssertPass("Call to SDL_GUIDToString");
for (i = 0; i < NUM_TEST_GUIDS; ++i) {
const int guid_str_offset = 4;
char guid_str_buf[64];
char *guid_str = guid_str_buf + guid_str_offset;
SDL_GUID guid;
int size;
upper_lower_to_bytestring(guid.data,
test_guids[i].upper, test_guids[i].lower);
/* Serialise to limited-length buffers */
for (size = 0; size <= 36; ++size) {
const Uint8 fill_char = size + 0xa0;
Uint32 expected_prefix;
Uint32 actual_prefix;
int written_size;
SDL_memset(guid_str_buf, fill_char, sizeof(guid_str_buf));
SDL_GUIDToString(guid, guid_str, size);
/* Check bytes before guid_str_buf */
expected_prefix = fill_char | (fill_char << 8) | (fill_char << 16) | (((Uint32)fill_char) << 24);
SDL_memcpy(&actual_prefix, guid_str_buf, 4);
SDLTest_AssertCheck(expected_prefix == actual_prefix, "String buffer memory before output untouched, expected: %" SDL_PRIu32 ", got: %" SDL_PRIu32 ", at size=%d", expected_prefix, actual_prefix, size);
/* Check that we did not overwrite too much */
written_size = 0;
while ((guid_str[written_size] & 0xff) != fill_char && written_size < 256) {
++written_size;
}
SDLTest_AssertCheck(written_size <= size, "Output length is within expected bounds, with length %d: wrote %d of %d permitted bytes", size, written_size, size);
if (size >= 33) {
SDLTest_AssertCheck(SDL_strcmp(guid_str, test_guids[i].str) == 0, "GUID string equality, from string: %s", test_guids[i].str);
}
}
}
return TEST_COMPLETED;
}
/* ================= Test References ================== */
/* GUID routine test cases */
static const SDLTest_TestCaseReference guidTest1 = {
(SDLTest_TestCaseFp)TestGuidFromString, "TestGuidFromString", "Call to SDL_GUIDFromString", TEST_ENABLED
};
static const SDLTest_TestCaseReference guidTest2 = {
(SDLTest_TestCaseFp)TestGuidToString, "TestGuidToString", "Call to SDL_GUIDToString", TEST_ENABLED
};
/* Sequence of GUID routine test cases */
static const SDLTest_TestCaseReference *guidTests[] = {
&guidTest1,
&guidTest2,
NULL
};
/* GUID routine test suite (global) */
SDLTest_TestSuiteReference guidTestSuite = {
"GUID",
NULL,
guidTests,
NULL
};

View File

@ -0,0 +1,266 @@
/**
* Hints test suite
*/
#include <stdio.h>
#include "SDL.h"
#include "SDL_test.h"
const char *_HintsEnum[] = {
SDL_HINT_ACCELEROMETER_AS_JOYSTICK,
SDL_HINT_FRAMEBUFFER_ACCELERATION,
SDL_HINT_GAMECONTROLLERCONFIG,
SDL_HINT_GRAB_KEYBOARD,
SDL_HINT_IDLE_TIMER_DISABLED,
SDL_HINT_JOYSTICK_ALLOW_BACKGROUND_EVENTS,
SDL_HINT_MAC_CTRL_CLICK_EMULATE_RIGHT_CLICK,
SDL_HINT_MOUSE_RELATIVE_MODE_WARP,
SDL_HINT_ORIENTATIONS,
SDL_HINT_RENDER_DIRECT3D_THREADSAFE,
SDL_HINT_RENDER_DRIVER,
SDL_HINT_RENDER_OPENGL_SHADERS,
SDL_HINT_RENDER_SCALE_QUALITY,
SDL_HINT_RENDER_VSYNC,
SDL_HINT_TIMER_RESOLUTION,
SDL_HINT_VIDEO_ALLOW_SCREENSAVER,
SDL_HINT_VIDEO_HIGHDPI_DISABLED,
SDL_HINT_VIDEO_MAC_FULLSCREEN_SPACES,
SDL_HINT_VIDEO_MINIMIZE_ON_FOCUS_LOSS,
SDL_HINT_VIDEO_WINDOW_SHARE_PIXEL_FORMAT,
SDL_HINT_VIDEO_WIN_D3DCOMPILER,
SDL_HINT_VIDEO_X11_XRANDR,
SDL_HINT_XINPUT_ENABLED,
};
const char *_HintsVerbose[] = {
"SDL_ACCELEROMETER_AS_JOYSTICK",
"SDL_FRAMEBUFFER_ACCELERATION",
"SDL_GAMECONTROLLERCONFIG",
"SDL_GRAB_KEYBOARD",
"SDL_IDLE_TIMER_DISABLED",
"SDL_JOYSTICK_ALLOW_BACKGROUND_EVENTS",
"SDL_MAC_CTRL_CLICK_EMULATE_RIGHT_CLICK",
"SDL_MOUSE_RELATIVE_MODE_WARP",
"SDL_ORIENTATIONS",
"SDL_RENDER_DIRECT3D_THREADSAFE",
"SDL_RENDER_DRIVER",
"SDL_RENDER_OPENGL_SHADERS",
"SDL_RENDER_SCALE_QUALITY",
"SDL_RENDER_VSYNC",
"SDL_TIMER_RESOLUTION",
"SDL_VIDEO_ALLOW_SCREENSAVER",
"SDL_VIDEO_HIGHDPI_DISABLED",
"SDL_VIDEO_MAC_FULLSCREEN_SPACES",
"SDL_VIDEO_MINIMIZE_ON_FOCUS_LOSS",
"SDL_VIDEO_WINDOW_SHARE_PIXEL_FORMAT",
"SDL_VIDEO_WIN_D3DCOMPILER",
"SDL_VIDEO_X11_XRANDR",
"SDL_XINPUT_ENABLED"
};
SDL_COMPILE_TIME_ASSERT(HintsEnum, SDL_arraysize(_HintsEnum) == SDL_arraysize(_HintsVerbose));
const int _numHintsEnum = SDL_arraysize(_HintsEnum);
/* Test case functions */
/**
* @brief Call to SDL_GetHint
*/
int hints_getHint(void *arg)
{
const char *result1;
const char *result2;
int i;
for (i = 0; i < _numHintsEnum; i++) {
result1 = SDL_GetHint(_HintsEnum[i]);
SDLTest_AssertPass("Call to SDL_GetHint(%s) - using define definition", (char *)_HintsEnum[i]);
result2 = SDL_GetHint(_HintsVerbose[i]);
SDLTest_AssertPass("Call to SDL_GetHint(%s) - using string definition", (char *)_HintsVerbose[i]);
SDLTest_AssertCheck(
(result1 == NULL && result2 == NULL) || (SDL_strcmp(result1, result2) == 0),
"Verify returned values are equal; got: result1='%s' result2='%s",
(result1 == NULL) ? "null" : result1,
(result2 == NULL) ? "null" : result2);
}
return TEST_COMPLETED;
}
static void SDLCALL hints_testHintChanged(void *userdata, const char *name, const char *oldValue, const char *hint)
{
*(char **)userdata = hint ? SDL_strdup(hint) : NULL;
}
/**
* @brief Call to SDL_SetHint
*/
int hints_setHint(void *arg)
{
const char *testHint = "SDL_AUTOMATED_TEST_HINT";
const char *originalValue;
char *value;
const char *testValue;
char *callbackValue;
SDL_bool result;
int i, j;
/* Create random values to set */
value = SDLTest_RandomAsciiStringOfSize(10);
for (i = 0; i < _numHintsEnum; i++) {
/* Capture current value */
originalValue = SDL_GetHint(_HintsEnum[i]);
SDLTest_AssertPass("Call to SDL_GetHint(%s)", _HintsEnum[i]);
/* Copy the original value, since it will be freed when we set it again */
originalValue = originalValue ? SDL_strdup(originalValue) : NULL;
/* Set value (twice) */
for (j = 1; j <= 2; j++) {
result = SDL_SetHint(_HintsEnum[i], value);
SDLTest_AssertPass("Call to SDL_SetHint(%s, %s) (iteration %i)", _HintsEnum[i], value, j);
SDLTest_AssertCheck(
result == SDL_TRUE || result == SDL_FALSE,
"Verify valid result was returned, got: %i",
(int)result);
testValue = SDL_GetHint(_HintsEnum[i]);
SDLTest_AssertPass("Call to SDL_GetHint(%s) - using string definition", _HintsVerbose[i]);
SDLTest_AssertCheck(
(SDL_strcmp(value, testValue) == 0),
"Verify returned value equals set value; got: testValue='%s' value='%s",
(testValue == NULL) ? "null" : testValue,
value);
}
/* Reset original value */
result = SDL_SetHint(_HintsEnum[i], originalValue);
SDLTest_AssertPass("Call to SDL_SetHint(%s, originalValue)", _HintsEnum[i]);
SDLTest_AssertCheck(
result == SDL_TRUE || result == SDL_FALSE,
"Verify valid result was returned, got: %i",
(int)result);
SDL_free((void *)originalValue);
}
SDL_free(value);
/* Set default value in environment */
SDL_setenv(testHint, "original", 1);
SDLTest_AssertPass("Call to SDL_GetHint() after saving and restoring hint");
originalValue = SDL_GetHint(testHint);
value = (originalValue == NULL) ? NULL : SDL_strdup(originalValue);
SDL_SetHint(testHint, "temp");
SDL_SetHint(testHint, value);
SDL_free(value);
testValue = SDL_GetHint(testHint);
SDLTest_AssertCheck(
testValue && SDL_strcmp(testValue, "original") == 0,
"testValue = %s, expected \"original\"",
testValue);
SDLTest_AssertPass("Call to SDL_SetHintWithPriority(NULL, SDL_HINT_DEFAULT)");
SDL_SetHintWithPriority(testHint, NULL, SDL_HINT_DEFAULT);
testValue = SDL_GetHint(testHint);
SDLTest_AssertCheck(
testValue && SDL_strcmp(testValue, "original") == 0,
"testValue = %s, expected \"original\"",
testValue);
SDLTest_AssertPass("Call to SDL_SetHintWithPriority(\"temp\", SDL_HINT_OVERRIDE)");
SDL_SetHintWithPriority(testHint, "temp", SDL_HINT_OVERRIDE);
testValue = SDL_GetHint(testHint);
SDLTest_AssertCheck(
testValue && SDL_strcmp(testValue, "temp") == 0,
"testValue = %s, expected \"temp\"",
testValue);
SDLTest_AssertPass("Call to SDL_SetHintWithPriority(NULL, SDL_HINT_OVERRIDE)");
SDL_SetHintWithPriority(testHint, NULL, SDL_HINT_OVERRIDE);
testValue = SDL_GetHint(testHint);
SDLTest_AssertCheck(
testValue == NULL,
"testValue = %s, expected NULL",
testValue);
SDLTest_AssertPass("Call to SDL_ResetHint()");
SDL_ResetHint(testHint);
testValue = SDL_GetHint(testHint);
SDLTest_AssertCheck(
testValue && SDL_strcmp(testValue, "original") == 0,
"testValue = %s, expected \"original\"",
testValue);
/* Make sure callback functionality works past a reset */
SDLTest_AssertPass("Call to SDL_AddHintCallback()");
callbackValue = NULL;
SDL_AddHintCallback(testHint, hints_testHintChanged, &callbackValue);
SDLTest_AssertCheck(
callbackValue && SDL_strcmp(callbackValue, "original") == 0,
"callbackValue = %s, expected \"original\"",
callbackValue);
SDL_free(callbackValue);
SDLTest_AssertPass("Call to SDL_SetHintWithPriority(\"temp\", SDL_HINT_OVERRIDE), using callback");
callbackValue = NULL;
SDL_SetHintWithPriority(testHint, "temp", SDL_HINT_OVERRIDE);
SDLTest_AssertCheck(
callbackValue && SDL_strcmp(callbackValue, "temp") == 0,
"callbackValue = %s, expected \"temp\"",
callbackValue);
SDL_free(callbackValue);
SDLTest_AssertPass("Call to SDL_ResetHint(), using callback");
callbackValue = NULL;
SDL_ResetHint(testHint);
SDLTest_AssertCheck(
callbackValue && SDL_strcmp(callbackValue, "original") == 0,
"callbackValue = %s, expected \"original\"",
callbackValue);
SDLTest_AssertPass("Call to SDL_SetHintWithPriority(\"temp\", SDL_HINT_OVERRIDE), using callback after reset");
callbackValue = NULL;
SDL_SetHintWithPriority(testHint, "temp", SDL_HINT_OVERRIDE);
SDLTest_AssertCheck(
callbackValue && SDL_strcmp(callbackValue, "temp") == 0,
"callbackValue = %s, expected \"temp\"",
callbackValue);
SDL_free(callbackValue);
SDLTest_AssertPass("Call to SDL_ResetHint(), after clearing callback");
callbackValue = NULL;
SDL_DelHintCallback(testHint, hints_testHintChanged, &callbackValue);
SDL_ResetHint(testHint);
SDLTest_AssertCheck(
callbackValue == NULL,
"callbackValue = %s, expected \"(null)\"",
callbackValue);
return TEST_COMPLETED;
}
/* ================= Test References ================== */
/* Hints test cases */
static const SDLTest_TestCaseReference hintsTest1 = {
(SDLTest_TestCaseFp)hints_getHint, "hints_getHint", "Call to SDL_GetHint", TEST_ENABLED
};
static const SDLTest_TestCaseReference hintsTest2 = {
(SDLTest_TestCaseFp)hints_setHint, "hints_setHint", "Call to SDL_SetHint", TEST_ENABLED
};
/* Sequence of Hints test cases */
static const SDLTest_TestCaseReference *hintsTests[] = {
&hintsTest1, &hintsTest2, NULL
};
/* Hints test suite (global) */
SDLTest_TestSuiteReference hintsTestSuite = {
"Hints",
NULL,
hintsTests,
NULL
};

View File

@ -0,0 +1,91 @@
/**
* Joystick test suite
*/
#include "SDL.h"
#include "SDL_test.h"
#include "../src/joystick/usb_ids.h"
/* ================= Test Case Implementation ================== */
/* Test case functions */
/**
* @brief Check virtual joystick creation
*
* @sa SDL_JoystickAttachVirtualEx
*/
static int
TestVirtualJoystick(void *arg)
{
SDL_VirtualJoystickDesc desc;
SDL_Joystick *joystick = NULL;
int device_index;
SDLTest_AssertCheck(SDL_InitSubSystem(SDL_INIT_GAMECONTROLLER) == 0, "SDL_InitSubSystem(SDL_INIT_GAMECONTROLLER)");
SDL_zero(desc);
desc.version = SDL_VIRTUAL_JOYSTICK_DESC_VERSION;
desc.type = SDL_JOYSTICK_TYPE_GAMECONTROLLER;
desc.naxes = SDL_CONTROLLER_AXIS_MAX;
desc.nbuttons = SDL_CONTROLLER_BUTTON_MAX;
desc.vendor_id = USB_VENDOR_NVIDIA;
desc.product_id = USB_PRODUCT_NVIDIA_SHIELD_CONTROLLER_V104;
desc.name = "Virtual NVIDIA SHIELD Controller";
device_index = SDL_JoystickAttachVirtualEx(&desc);
SDLTest_AssertCheck(device_index >= 0, "SDL_JoystickAttachVirtualEx()");
SDLTest_AssertCheck(SDL_JoystickIsVirtual(device_index), "SDL_JoystickIsVirtual()");
if (device_index >= 0) {
joystick = SDL_JoystickOpen(device_index);
SDLTest_AssertCheck(joystick != NULL, "SDL_JoystickOpen()");
if (joystick) {
SDLTest_AssertCheck(SDL_strcmp(SDL_JoystickName(joystick), desc.name) == 0, "SDL_JoystickName()");
SDLTest_AssertCheck(SDL_JoystickGetVendor(joystick) == desc.vendor_id, "SDL_JoystickGetVendor()");
SDLTest_AssertCheck(SDL_JoystickGetProduct(joystick) == desc.product_id, "SDL_JoystickGetProduct()");
SDLTest_AssertCheck(SDL_JoystickGetProductVersion(joystick) == 0, "SDL_JoystickGetProductVersion()");
SDLTest_AssertCheck(SDL_JoystickGetFirmwareVersion(joystick) == 0, "SDL_JoystickGetFirmwareVersion()");
SDLTest_AssertCheck(SDL_JoystickGetSerial(joystick) == NULL, "SDL_JoystickGetSerial()");
SDLTest_AssertCheck(SDL_JoystickGetType(joystick) == desc.type, "SDL_JoystickGetType()");
SDLTest_AssertCheck(SDL_JoystickNumAxes(joystick) == desc.naxes, "SDL_JoystickNumAxes()");
SDLTest_AssertCheck(SDL_JoystickNumBalls(joystick) == 0, "SDL_JoystickNumBalls()");
SDLTest_AssertCheck(SDL_JoystickNumHats(joystick) == desc.nhats, "SDL_JoystickNumHats()");
SDLTest_AssertCheck(SDL_JoystickNumButtons(joystick) == desc.nbuttons, "SDL_JoystickNumButtons()");
SDLTest_AssertCheck(SDL_JoystickSetVirtualButton(joystick, SDL_CONTROLLER_BUTTON_A, SDL_PRESSED) == 0, "SDL_JoystickSetVirtualButton(SDL_CONTROLLER_BUTTON_A, SDL_PRESSED)");
SDL_JoystickUpdate();
SDLTest_AssertCheck(SDL_JoystickGetButton(joystick, SDL_CONTROLLER_BUTTON_A) == SDL_PRESSED, "SDL_JoystickGetButton(SDL_CONTROLLER_BUTTON_A) == SDL_PRESSED");
SDLTest_AssertCheck(SDL_JoystickSetVirtualButton(joystick, SDL_CONTROLLER_BUTTON_A, SDL_RELEASED) == 0, "SDL_JoystickSetVirtualButton(SDL_CONTROLLER_BUTTON_A, SDL_RELEASED)");
SDL_JoystickUpdate();
SDLTest_AssertCheck(SDL_JoystickGetButton(joystick, SDL_CONTROLLER_BUTTON_A) == SDL_RELEASED, "SDL_JoystickGetButton(SDL_CONTROLLER_BUTTON_A) == SDL_RELEASED");
SDL_JoystickClose(joystick);
}
SDLTest_AssertCheck(SDL_JoystickDetachVirtual(device_index) == 0, "SDL_JoystickDetachVirtual()");
}
SDLTest_AssertCheck(!SDL_JoystickIsVirtual(device_index), "!SDL_JoystickIsVirtual()");
SDL_QuitSubSystem(SDL_INIT_GAMECONTROLLER);
return TEST_COMPLETED;
}
/* ================= Test References ================== */
/* Joystick routine test cases */
static const SDLTest_TestCaseReference joystickTest1 = {
(SDLTest_TestCaseFp)TestVirtualJoystick, "TestVirtualJoystick", "Test virtual joystick functionality", TEST_ENABLED
};
/* Sequence of Joystick routine test cases */
static const SDLTest_TestCaseReference *joystickTests[] = {
&joystickTest1,
NULL
};
/* Joystick routine test suite (global) */
SDLTest_TestSuiteReference joystickTestSuite = {
"Joystick",
NULL,
joystickTests,
NULL
};

View File

@ -0,0 +1,708 @@
/**
* Keyboard test suite
*/
#include <stdio.h>
#include <limits.h>
#include "SDL_config.h"
#include "SDL.h"
#include "SDL_test.h"
/* ================= Test Case Implementation ================== */
/* Test case functions */
/**
* @brief Check call to SDL_GetKeyboardState with and without numkeys reference.
*
* @sa http://wiki.libsdl.org/SDL_GetKeyboardState
*/
int keyboard_getKeyboardState(void *arg)
{
int numkeys;
Uint8 *state;
/* Case where numkeys pointer is NULL */
state = (Uint8 *)SDL_GetKeyboardState(NULL);
SDLTest_AssertPass("Call to SDL_GetKeyboardState(NULL)");
SDLTest_AssertCheck(state != NULL, "Validate that return value from SDL_GetKeyboardState is not NULL");
/* Case where numkeys pointer is not NULL */
numkeys = -1;
state = (Uint8 *)SDL_GetKeyboardState(&numkeys);
SDLTest_AssertPass("Call to SDL_GetKeyboardState(&numkeys)");
SDLTest_AssertCheck(state != NULL, "Validate that return value from SDL_GetKeyboardState is not NULL");
SDLTest_AssertCheck(numkeys >= 0, "Validate that value of numkeys is >= 0, got: %i", numkeys);
return TEST_COMPLETED;
}
/**
* @brief Check call to SDL_GetKeyboardFocus
*
* @sa http://wiki.libsdl.org/SDL_GetKeyboardFocus
*/
int keyboard_getKeyboardFocus(void *arg)
{
/* Call, but ignore return value */
SDL_GetKeyboardFocus();
SDLTest_AssertPass("Call to SDL_GetKeyboardFocus()");
return TEST_COMPLETED;
}
/**
* @brief Check call to SDL_GetKeyFromName for known, unknown and invalid name.
*
* @sa http://wiki.libsdl.org/SDL_GetKeyFromName
*/
int keyboard_getKeyFromName(void *arg)
{
SDL_Keycode result;
/* Case where Key is known, 1 character input */
result = SDL_GetKeyFromName("A");
SDLTest_AssertPass("Call to SDL_GetKeyFromName(known/single)");
SDLTest_AssertCheck(result == SDLK_a, "Verify result from call, expected: %i, got: %" SDL_PRIs32, SDLK_a, result);
/* Case where Key is known, 2 character input */
result = SDL_GetKeyFromName("F1");
SDLTest_AssertPass("Call to SDL_GetKeyFromName(known/double)");
SDLTest_AssertCheck(result == SDLK_F1, "Verify result from call, expected: %i, got: %" SDL_PRIs32, SDLK_F1, result);
/* Case where Key is known, 3 character input */
result = SDL_GetKeyFromName("End");
SDLTest_AssertPass("Call to SDL_GetKeyFromName(known/triple)");
SDLTest_AssertCheck(result == SDLK_END, "Verify result from call, expected: %i, got: %" SDL_PRIs32, SDLK_END, result);
/* Case where Key is known, 4 character input */
result = SDL_GetKeyFromName("Find");
SDLTest_AssertPass("Call to SDL_GetKeyFromName(known/quad)");
SDLTest_AssertCheck(result == SDLK_FIND, "Verify result from call, expected: %i, got: %" SDL_PRIs32, SDLK_FIND, result);
/* Case where Key is known, multiple character input */
result = SDL_GetKeyFromName("AudioStop");
SDLTest_AssertPass("Call to SDL_GetKeyFromName(known/multi)");
SDLTest_AssertCheck(result == SDLK_AUDIOSTOP, "Verify result from call, expected: %i, got: %" SDL_PRIs32, SDLK_AUDIOSTOP, result);
/* Case where Key is unknown */
result = SDL_GetKeyFromName("NotThere");
SDLTest_AssertPass("Call to SDL_GetKeyFromName(unknown)");
SDLTest_AssertCheck(result == SDLK_UNKNOWN, "Verify result from call is UNKNOWN, expected: %i, got: %" SDL_PRIs32, SDLK_UNKNOWN, result);
/* Case where input is NULL/invalid */
result = SDL_GetKeyFromName(NULL);
SDLTest_AssertPass("Call to SDL_GetKeyFromName(NULL)");
SDLTest_AssertCheck(result == SDLK_UNKNOWN, "Verify result from call is UNKNOWN, expected: %i, got: %" SDL_PRIs32, SDLK_UNKNOWN, result);
return TEST_COMPLETED;
}
/*
* Local helper to check for the invalid scancode error message
*/
void _checkInvalidScancodeError()
{
const char *expectedError = "Parameter 'scancode' is invalid";
const char *error;
error = SDL_GetError();
SDLTest_AssertPass("Call to SDL_GetError()");
SDLTest_AssertCheck(error != NULL, "Validate that error message was not NULL");
if (error != NULL) {
SDLTest_AssertCheck(SDL_strcmp(error, expectedError) == 0,
"Validate error message, expected: '%s', got: '%s'", expectedError, error);
SDL_ClearError();
SDLTest_AssertPass("Call to SDL_ClearError()");
}
}
/**
* @brief Check call to SDL_GetKeyFromScancode
*
* @sa http://wiki.libsdl.org/SDL_GetKeyFromScancode
*/
int keyboard_getKeyFromScancode(void *arg)
{
SDL_Keycode result;
/* Case where input is valid */
result = SDL_GetKeyFromScancode(SDL_SCANCODE_A);
SDLTest_AssertPass("Call to SDL_GetKeyFromScancode(valid)");
SDLTest_AssertCheck(result == SDLK_a, "Verify result from call, expected: %i, got: %" SDL_PRIs32, SDLK_a, result);
/* Case where input is zero */
result = SDL_GetKeyFromScancode(0);
SDLTest_AssertPass("Call to SDL_GetKeyFromScancode(0)");
SDLTest_AssertCheck(result == SDLK_UNKNOWN, "Verify result from call is UNKNOWN, expected: %i, got: %" SDL_PRIs32, SDLK_UNKNOWN, result);
/* Clear error message */
SDL_ClearError();
SDLTest_AssertPass("Call to SDL_ClearError()");
/* Case where input is invalid (too small) */
result = SDL_GetKeyFromScancode(-999);
SDLTest_AssertPass("Call to SDL_GetKeyFromScancode(-999)");
SDLTest_AssertCheck(result == SDLK_UNKNOWN, "Verify result from call is UNKNOWN, expected: %i, got: %" SDL_PRIs32, SDLK_UNKNOWN, result);
_checkInvalidScancodeError();
/* Case where input is invalid (too big) */
result = SDL_GetKeyFromScancode(999);
SDLTest_AssertPass("Call to SDL_GetKeyFromScancode(999)");
SDLTest_AssertCheck(result == SDLK_UNKNOWN, "Verify result from call is UNKNOWN, expected: %i, got: %" SDL_PRIs32, SDLK_UNKNOWN, result);
_checkInvalidScancodeError();
return TEST_COMPLETED;
}
/**
* @brief Check call to SDL_GetKeyName
*
* @sa http://wiki.libsdl.org/SDL_GetKeyName
*/
int keyboard_getKeyName(void *arg)
{
const char *result;
const char *expected;
/* Case where key has a 1 character name */
expected = "3";
result = (char *)SDL_GetKeyName(SDLK_3);
SDLTest_AssertPass("Call to SDL_GetKeyName()");
SDLTest_AssertCheck(result != NULL, "Verify result from call is not NULL");
SDLTest_AssertCheck(SDL_strcmp(result, expected) == 0, "Verify result from call is valid, expected: %s, got: %s", expected, result);
/* Case where key has a 2 character name */
expected = "F1";
result = (char *)SDL_GetKeyName(SDLK_F1);
SDLTest_AssertPass("Call to SDL_GetKeyName()");
SDLTest_AssertCheck(result != NULL, "Verify result from call is not NULL");
SDLTest_AssertCheck(SDL_strcmp(result, expected) == 0, "Verify result from call is valid, expected: %s, got: %s", expected, result);
/* Case where key has a 3 character name */
expected = "Cut";
result = (char *)SDL_GetKeyName(SDLK_CUT);
SDLTest_AssertPass("Call to SDL_GetKeyName()");
SDLTest_AssertCheck(result != NULL, "Verify result from call is not NULL");
SDLTest_AssertCheck(SDL_strcmp(result, expected) == 0, "Verify result from call is valid, expected: %s, got: %s", expected, result);
/* Case where key has a 4 character name */
expected = "Down";
result = (char *)SDL_GetKeyName(SDLK_DOWN);
SDLTest_AssertPass("Call to SDL_GetKeyName()");
SDLTest_AssertCheck(result != NULL, "Verify result from call is not NULL");
SDLTest_AssertCheck(SDL_strcmp(result, expected) == 0, "Verify result from call is valid, expected: %s, got: %s", expected, result);
/* Case where key has a N character name */
expected = "BrightnessUp";
result = (char *)SDL_GetKeyName(SDLK_BRIGHTNESSUP);
SDLTest_AssertPass("Call to SDL_GetKeyName()");
SDLTest_AssertCheck(result != NULL, "Verify result from call is not NULL");
SDLTest_AssertCheck(SDL_strcmp(result, expected) == 0, "Verify result from call is valid, expected: %s, got: %s", expected, result);
/* Case where key has a N character name with space */
expected = "Keypad MemStore";
result = (char *)SDL_GetKeyName(SDLK_KP_MEMSTORE);
SDLTest_AssertPass("Call to SDL_GetKeyName()");
SDLTest_AssertCheck(result != NULL, "Verify result from call is not NULL");
SDLTest_AssertCheck(SDL_strcmp(result, expected) == 0, "Verify result from call is valid, expected: %s, got: %s", expected, result);
return TEST_COMPLETED;
}
/**
* @brief SDL_GetScancodeName negative cases
*
* @sa http://wiki.libsdl.org/SDL_GetScancodeName
*/
int keyboard_getScancodeNameNegative(void *arg)
{
SDL_Scancode scancode;
const char *result;
const char *expected = "";
/* Clear error message */
SDL_ClearError();
SDLTest_AssertPass("Call to SDL_ClearError()");
/* Out-of-bounds scancode */
scancode = (SDL_Scancode)SDL_NUM_SCANCODES;
result = (char *)SDL_GetScancodeName(scancode);
SDLTest_AssertPass("Call to SDL_GetScancodeName(%d/large)", scancode);
SDLTest_AssertCheck(result != NULL, "Verify result from call is not NULL");
SDLTest_AssertCheck(SDL_strcmp(result, expected) == 0, "Verify result from call is valid, expected: '%s', got: '%s'", expected, result);
_checkInvalidScancodeError();
return TEST_COMPLETED;
}
/**
* @brief SDL_GetKeyName negative cases
*
* @sa http://wiki.libsdl.org/SDL_GetKeyName
*/
int keyboard_getKeyNameNegative(void *arg)
{
SDL_Keycode keycode;
const char *result;
const char *expected = "";
/* Unknown keycode */
keycode = SDLK_UNKNOWN;
result = (char *)SDL_GetKeyName(keycode);
SDLTest_AssertPass("Call to SDL_GetKeyName(%" SDL_PRIs32 "/unknown)", keycode);
SDLTest_AssertCheck(result != NULL, "Verify result from call is not NULL");
SDLTest_AssertCheck(SDL_strcmp(result, expected) == 0, "Verify result from call is valid, expected: '%s', got: '%s'", expected, result);
/* Clear error message */
SDL_ClearError();
SDLTest_AssertPass("Call to SDL_ClearError()");
/* Negative keycode */
keycode = (SDL_Keycode)SDLTest_RandomIntegerInRange(-255, -1);
result = (char *)SDL_GetKeyName(keycode);
SDLTest_AssertPass("Call to SDL_GetKeyName(%" SDL_PRIs32 "/negative)", keycode);
SDLTest_AssertCheck(result != NULL, "Verify result from call is not NULL");
SDLTest_AssertCheck(SDL_strcmp(result, expected) == 0, "Verify result from call is valid, expected: '%s', got: '%s'", expected, result);
_checkInvalidScancodeError();
SDL_ClearError();
SDLTest_AssertPass("Call to SDL_ClearError()");
return TEST_COMPLETED;
}
/**
* @brief Check call to SDL_GetModState and SDL_SetModState
*
* @sa http://wiki.libsdl.org/SDL_GetModState
* @sa http://wiki.libsdl.org/SDL_SetModState
*/
int keyboard_getSetModState(void *arg)
{
SDL_Keymod result;
SDL_Keymod currentState;
SDL_Keymod newState;
SDL_Keymod allStates =
KMOD_NONE |
KMOD_LSHIFT |
KMOD_RSHIFT |
KMOD_LCTRL |
KMOD_RCTRL |
KMOD_LALT |
KMOD_RALT |
KMOD_LGUI |
KMOD_RGUI |
KMOD_NUM |
KMOD_CAPS |
KMOD_MODE |
KMOD_SCROLL;
/* Get state, cache for later reset */
result = SDL_GetModState();
SDLTest_AssertPass("Call to SDL_GetModState()");
SDLTest_AssertCheck(/*result >= 0 &&*/ result <= allStates, "Verify result from call is valid, expected: 0 <= result <= %i, got: %i", allStates, result);
currentState = result;
/* Set random state */
newState = SDLTest_RandomIntegerInRange(0, allStates);
SDL_SetModState(newState);
SDLTest_AssertPass("Call to SDL_SetModState(%i)", newState);
result = SDL_GetModState();
SDLTest_AssertPass("Call to SDL_GetModState()");
SDLTest_AssertCheck(result == newState, "Verify result from call is valid, expected: %i, got: %i", newState, result);
/* Set zero state */
SDL_SetModState(0);
SDLTest_AssertPass("Call to SDL_SetModState(0)");
result = SDL_GetModState();
SDLTest_AssertPass("Call to SDL_GetModState()");
SDLTest_AssertCheck(result == 0, "Verify result from call is valid, expected: 0, got: %i", result);
/* Revert back to cached current state if needed */
if (currentState != 0) {
SDL_SetModState(currentState);
SDLTest_AssertPass("Call to SDL_SetModState(%i)", currentState);
result = SDL_GetModState();
SDLTest_AssertPass("Call to SDL_GetModState()");
SDLTest_AssertCheck(result == currentState, "Verify result from call is valid, expected: %i, got: %i", currentState, result);
}
return TEST_COMPLETED;
}
/**
* @brief Check call to SDL_StartTextInput and SDL_StopTextInput
*
* @sa http://wiki.libsdl.org/SDL_StartTextInput
* @sa http://wiki.libsdl.org/SDL_StopTextInput
*/
int keyboard_startStopTextInput(void *arg)
{
/* Start-Stop */
SDL_StartTextInput();
SDLTest_AssertPass("Call to SDL_StartTextInput()");
SDL_StopTextInput();
SDLTest_AssertPass("Call to SDL_StopTextInput()");
/* Stop-Start */
SDL_StartTextInput();
SDLTest_AssertPass("Call to SDL_StartTextInput()");
/* Start-Start */
SDL_StartTextInput();
SDLTest_AssertPass("Call to SDL_StartTextInput()");
/* Stop-Stop */
SDL_StopTextInput();
SDLTest_AssertPass("Call to SDL_StopTextInput()");
SDL_StopTextInput();
SDLTest_AssertPass("Call to SDL_StopTextInput()");
return TEST_COMPLETED;
}
/* Internal function to test SDL_SetTextInputRect */
void _testSetTextInputRect(SDL_Rect refRect)
{
SDL_Rect testRect;
testRect = refRect;
SDL_SetTextInputRect(&testRect);
SDLTest_AssertPass("Call to SDL_SetTextInputRect with refRect(x:%i,y:%i,w:%i,h:%i)", refRect.x, refRect.y, refRect.w, refRect.h);
SDLTest_AssertCheck(
(refRect.x == testRect.x) && (refRect.y == testRect.y) && (refRect.w == testRect.w) && (refRect.h == testRect.h),
"Check that input data was not modified, expected: x:%i,y:%i,w:%i,h:%i, got: x:%i,y:%i,w:%i,h:%i",
refRect.x, refRect.y, refRect.w, refRect.h,
testRect.x, testRect.y, testRect.w, testRect.h);
}
/**
* @brief Check call to SDL_SetTextInputRect
*
* @sa http://wiki.libsdl.org/SDL_SetTextInputRect
*/
int keyboard_setTextInputRect(void *arg)
{
SDL_Rect refRect;
/* Normal visible refRect, origin inside */
refRect.x = SDLTest_RandomIntegerInRange(1, 50);
refRect.y = SDLTest_RandomIntegerInRange(1, 50);
refRect.w = SDLTest_RandomIntegerInRange(10, 50);
refRect.h = SDLTest_RandomIntegerInRange(10, 50);
_testSetTextInputRect(refRect);
/* Normal visible refRect, origin 0,0 */
refRect.x = 0;
refRect.y = 0;
refRect.w = SDLTest_RandomIntegerInRange(10, 50);
refRect.h = SDLTest_RandomIntegerInRange(10, 50);
_testSetTextInputRect(refRect);
/* 1Pixel refRect */
refRect.x = SDLTest_RandomIntegerInRange(10, 50);
refRect.y = SDLTest_RandomIntegerInRange(10, 50);
refRect.w = 1;
refRect.h = 1;
_testSetTextInputRect(refRect);
/* 0pixel refRect */
refRect.x = 1;
refRect.y = 1;
refRect.w = 1;
refRect.h = 0;
_testSetTextInputRect(refRect);
/* 0pixel refRect */
refRect.x = 1;
refRect.y = 1;
refRect.w = 0;
refRect.h = 1;
_testSetTextInputRect(refRect);
/* 0pixel refRect */
refRect.x = 1;
refRect.y = 1;
refRect.w = 0;
refRect.h = 0;
_testSetTextInputRect(refRect);
/* 0pixel refRect */
refRect.x = 0;
refRect.y = 0;
refRect.w = 0;
refRect.h = 0;
_testSetTextInputRect(refRect);
/* negative refRect */
refRect.x = SDLTest_RandomIntegerInRange(-200, -100);
refRect.y = SDLTest_RandomIntegerInRange(-200, -100);
refRect.w = 50;
refRect.h = 50;
_testSetTextInputRect(refRect);
/* oversized refRect */
refRect.x = SDLTest_RandomIntegerInRange(1, 50);
refRect.y = SDLTest_RandomIntegerInRange(1, 50);
refRect.w = 5000;
refRect.h = 5000;
_testSetTextInputRect(refRect);
/* NULL refRect */
SDL_SetTextInputRect(NULL);
SDLTest_AssertPass("Call to SDL_SetTextInputRect(NULL)");
return TEST_COMPLETED;
}
/**
* @brief Check call to SDL_SetTextInputRect with invalid data
*
* @sa http://wiki.libsdl.org/SDL_SetTextInputRect
*/
int keyboard_setTextInputRectNegative(void *arg)
{
int platform_sets_error_message = SDL_strcmp(SDL_GetCurrentVideoDriver(), "windows") == 0 ||
SDL_strcmp(SDL_GetCurrentVideoDriver(), "android") == 0 ||
SDL_strcmp(SDL_GetCurrentVideoDriver(), "cococa") == 0;
/* Some platforms set also an error message; prepare for checking it */
const char *expectedError = "Parameter 'rect' is invalid";
const char *error;
SDL_ClearError();
SDLTest_AssertPass("Call to SDL_ClearError()");
/* NULL refRect */
SDL_SetTextInputRect(NULL);
SDLTest_AssertPass("Call to SDL_SetTextInputRect(NULL)");
/* Some platforms set also an error message; so check it */
if (platform_sets_error_message) {
error = SDL_GetError();
SDLTest_AssertPass("Call to SDL_GetError()");
SDLTest_AssertCheck(error != NULL, "Validate that error message was not NULL");
if (error != NULL) {
SDLTest_AssertCheck(SDL_strcmp(error, expectedError) == 0,
"Validate error message, expected: '%s', got: '%s'", expectedError, error);
}
}
SDL_ClearError();
SDLTest_AssertPass("Call to SDL_ClearError()");
return TEST_COMPLETED;
}
/**
* @brief Check call to SDL_GetScancodeFromKey
*
* @sa http://wiki.libsdl.org/SDL_GetScancodeFromKey
* @sa http://wiki.libsdl.org/SDL_Keycode
*/
int keyboard_getScancodeFromKey(void *arg)
{
SDL_Scancode scancode;
/* Regular key */
scancode = SDL_GetScancodeFromKey(SDLK_4);
SDLTest_AssertPass("Call to SDL_GetScancodeFromKey(SDLK_4)");
SDLTest_AssertCheck(scancode == SDL_SCANCODE_4, "Validate return value from SDL_GetScancodeFromKey, expected: %i, got: %i", SDL_SCANCODE_4, scancode);
/* Virtual key */
scancode = SDL_GetScancodeFromKey(SDLK_PLUS);
SDLTest_AssertPass("Call to SDL_GetScancodeFromKey(SDLK_PLUS)");
SDLTest_AssertCheck(scancode == 0, "Validate return value from SDL_GetScancodeFromKey, expected: 0, got: %i", scancode);
return TEST_COMPLETED;
}
/**
* @brief Check call to SDL_GetScancodeFromName
*
* @sa http://wiki.libsdl.org/SDL_GetScancodeFromName
* @sa http://wiki.libsdl.org/SDL_Keycode
*/
int keyboard_getScancodeFromName(void *arg)
{
SDL_Scancode scancode;
/* Regular key, 1 character, first name in list */
scancode = SDL_GetScancodeFromName("A");
SDLTest_AssertPass("Call to SDL_GetScancodeFromName('A')");
SDLTest_AssertCheck(scancode == SDL_SCANCODE_A, "Validate return value from SDL_GetScancodeFromName, expected: %i, got: %i", SDL_SCANCODE_A, scancode);
/* Regular key, 1 character */
scancode = SDL_GetScancodeFromName("4");
SDLTest_AssertPass("Call to SDL_GetScancodeFromName('4')");
SDLTest_AssertCheck(scancode == SDL_SCANCODE_4, "Validate return value from SDL_GetScancodeFromName, expected: %i, got: %i", SDL_SCANCODE_4, scancode);
/* Regular key, 2 characters */
scancode = SDL_GetScancodeFromName("F1");
SDLTest_AssertPass("Call to SDL_GetScancodeFromName('F1')");
SDLTest_AssertCheck(scancode == SDL_SCANCODE_F1, "Validate return value from SDL_GetScancodeFromName, expected: %i, got: %i", SDL_SCANCODE_F1, scancode);
/* Regular key, 3 characters */
scancode = SDL_GetScancodeFromName("End");
SDLTest_AssertPass("Call to SDL_GetScancodeFromName('End')");
SDLTest_AssertCheck(scancode == SDL_SCANCODE_END, "Validate return value from SDL_GetScancodeFromName, expected: %i, got: %i", SDL_SCANCODE_END, scancode);
/* Regular key, 4 characters */
scancode = SDL_GetScancodeFromName("Find");
SDLTest_AssertPass("Call to SDL_GetScancodeFromName('Find')");
SDLTest_AssertCheck(scancode == SDL_SCANCODE_FIND, "Validate return value from SDL_GetScancodeFromName, expected: %i, got: %i", SDL_SCANCODE_FIND, scancode);
/* Regular key, several characters */
scancode = SDL_GetScancodeFromName("Backspace");
SDLTest_AssertPass("Call to SDL_GetScancodeFromName('Backspace')");
SDLTest_AssertCheck(scancode == SDL_SCANCODE_BACKSPACE, "Validate return value from SDL_GetScancodeFromName, expected: %i, got: %i", SDL_SCANCODE_BACKSPACE, scancode);
/* Regular key, several characters with space */
scancode = SDL_GetScancodeFromName("Keypad Enter");
SDLTest_AssertPass("Call to SDL_GetScancodeFromName('Keypad Enter')");
SDLTest_AssertCheck(scancode == SDL_SCANCODE_KP_ENTER, "Validate return value from SDL_GetScancodeFromName, expected: %i, got: %i", SDL_SCANCODE_KP_ENTER, scancode);
/* Regular key, last name in list */
scancode = SDL_GetScancodeFromName("Sleep");
SDLTest_AssertPass("Call to SDL_GetScancodeFromName('Sleep')");
SDLTest_AssertCheck(scancode == SDL_SCANCODE_SLEEP, "Validate return value from SDL_GetScancodeFromName, expected: %i, got: %i", SDL_SCANCODE_SLEEP, scancode);
return TEST_COMPLETED;
}
/*
* Local helper to check for the invalid scancode error message
*/
void _checkInvalidNameError()
{
const char *expectedError = "Parameter 'name' is invalid";
const char *error;
error = SDL_GetError();
SDLTest_AssertPass("Call to SDL_GetError()");
SDLTest_AssertCheck(error != NULL, "Validate that error message was not NULL");
if (error != NULL) {
SDLTest_AssertCheck(SDL_strcmp(error, expectedError) == 0,
"Validate error message, expected: '%s', got: '%s'", expectedError, error);
SDL_ClearError();
SDLTest_AssertPass("Call to SDL_ClearError()");
}
}
/**
* @brief Check call to SDL_GetScancodeFromName with invalid data
*
* @sa http://wiki.libsdl.org/SDL_GetScancodeFromName
* @sa http://wiki.libsdl.org/SDL_Keycode
*/
int keyboard_getScancodeFromNameNegative(void *arg)
{
const char *name;
SDL_Scancode scancode;
/* Clear error message */
SDL_ClearError();
SDLTest_AssertPass("Call to SDL_ClearError()");
/* Random string input */
name = SDLTest_RandomAsciiStringOfSize(32);
SDLTest_Assert(name != NULL, "Check that random name is not NULL");
if (name == NULL) {
return TEST_ABORTED;
}
scancode = SDL_GetScancodeFromName(name);
SDLTest_AssertPass("Call to SDL_GetScancodeFromName('%s')", name);
SDL_free((void *)name);
SDLTest_AssertCheck(scancode == SDL_SCANCODE_UNKNOWN, "Validate return value from SDL_GetScancodeFromName, expected: %i, got: %i", SDL_SCANCODE_UNKNOWN, scancode);
_checkInvalidNameError();
/* Zero length string input */
name = "";
scancode = SDL_GetScancodeFromName(name);
SDLTest_AssertPass("Call to SDL_GetScancodeFromName(NULL)");
SDLTest_AssertCheck(scancode == SDL_SCANCODE_UNKNOWN, "Validate return value from SDL_GetScancodeFromName, expected: %i, got: %i", SDL_SCANCODE_UNKNOWN, scancode);
_checkInvalidNameError();
/* NULL input */
name = NULL;
scancode = SDL_GetScancodeFromName(name);
SDLTest_AssertPass("Call to SDL_GetScancodeFromName(NULL)");
SDLTest_AssertCheck(scancode == SDL_SCANCODE_UNKNOWN, "Validate return value from SDL_GetScancodeFromName, expected: %i, got: %i", SDL_SCANCODE_UNKNOWN, scancode);
_checkInvalidNameError();
return TEST_COMPLETED;
}
/* ================= Test References ================== */
/* Keyboard test cases */
static const SDLTest_TestCaseReference keyboardTest1 = {
(SDLTest_TestCaseFp)keyboard_getKeyboardState, "keyboard_getKeyboardState", "Check call to SDL_GetKeyboardState with and without numkeys reference", TEST_ENABLED
};
static const SDLTest_TestCaseReference keyboardTest2 = {
(SDLTest_TestCaseFp)keyboard_getKeyboardFocus, "keyboard_getKeyboardFocus", "Check call to SDL_GetKeyboardFocus", TEST_ENABLED
};
static const SDLTest_TestCaseReference keyboardTest3 = {
(SDLTest_TestCaseFp)keyboard_getKeyFromName, "keyboard_getKeyFromName", "Check call to SDL_GetKeyFromName for known, unknown and invalid name", TEST_ENABLED
};
static const SDLTest_TestCaseReference keyboardTest4 = {
(SDLTest_TestCaseFp)keyboard_getKeyFromScancode, "keyboard_getKeyFromScancode", "Check call to SDL_GetKeyFromScancode", TEST_ENABLED
};
static const SDLTest_TestCaseReference keyboardTest5 = {
(SDLTest_TestCaseFp)keyboard_getKeyName, "keyboard_getKeyName", "Check call to SDL_GetKeyName", TEST_ENABLED
};
static const SDLTest_TestCaseReference keyboardTest6 = {
(SDLTest_TestCaseFp)keyboard_getSetModState, "keyboard_getSetModState", "Check call to SDL_GetModState and SDL_SetModState", TEST_ENABLED
};
static const SDLTest_TestCaseReference keyboardTest7 = {
(SDLTest_TestCaseFp)keyboard_startStopTextInput, "keyboard_startStopTextInput", "Check call to SDL_StartTextInput and SDL_StopTextInput", TEST_ENABLED
};
static const SDLTest_TestCaseReference keyboardTest8 = {
(SDLTest_TestCaseFp)keyboard_setTextInputRect, "keyboard_setTextInputRect", "Check call to SDL_SetTextInputRect", TEST_ENABLED
};
static const SDLTest_TestCaseReference keyboardTest9 = {
(SDLTest_TestCaseFp)keyboard_setTextInputRectNegative, "keyboard_setTextInputRectNegative", "Check call to SDL_SetTextInputRect with invalid data", TEST_ENABLED
};
static const SDLTest_TestCaseReference keyboardTest10 = {
(SDLTest_TestCaseFp)keyboard_getScancodeFromKey, "keyboard_getScancodeFromKey", "Check call to SDL_GetScancodeFromKey", TEST_ENABLED
};
static const SDLTest_TestCaseReference keyboardTest11 = {
(SDLTest_TestCaseFp)keyboard_getScancodeFromName, "keyboard_getScancodeFromName", "Check call to SDL_GetScancodeFromName", TEST_ENABLED
};
static const SDLTest_TestCaseReference keyboardTest12 = {
(SDLTest_TestCaseFp)keyboard_getScancodeFromNameNegative, "keyboard_getScancodeFromNameNegative", "Check call to SDL_GetScancodeFromName with invalid data", TEST_ENABLED
};
static const SDLTest_TestCaseReference keyboardTest13 = {
(SDLTest_TestCaseFp)keyboard_getKeyNameNegative, "keyboard_getKeyNameNegative", "Check call to SDL_GetKeyName with invalid data", TEST_ENABLED
};
static const SDLTest_TestCaseReference keyboardTest14 = {
(SDLTest_TestCaseFp)keyboard_getScancodeNameNegative, "keyboard_getScancodeNameNegative", "Check call to SDL_GetScancodeName with invalid data", TEST_ENABLED
};
/* Sequence of Keyboard test cases */
static const SDLTest_TestCaseReference *keyboardTests[] = {
&keyboardTest1, &keyboardTest2, &keyboardTest3, &keyboardTest4, &keyboardTest5, &keyboardTest6,
&keyboardTest7, &keyboardTest8, &keyboardTest9, &keyboardTest10, &keyboardTest11, &keyboardTest12,
&keyboardTest13, &keyboardTest14, NULL
};
/* Keyboard test suite (global) */
SDLTest_TestSuiteReference keyboardTestSuite = {
"Keyboard",
NULL,
keyboardTests,
NULL
};

View File

@ -0,0 +1,209 @@
/**
* Log test suite
*/
#include "SDL.h"
#include "SDL_test.h"
static SDL_LogOutputFunction original_function;
static void *original_userdata;
static void SDLCALL TestLogOutput(void *userdata, int category, SDL_LogPriority priority, const char *message)
{
int *message_count = (int *)userdata;
++(*message_count);
}
static void EnableTestLog(int *message_count)
{
*message_count = 0;
SDL_LogGetOutputFunction(&original_function, &original_userdata);
SDL_LogSetOutputFunction(TestLogOutput, message_count);
}
static void DisableTestLog()
{
SDL_LogSetOutputFunction(original_function, original_userdata);
}
/* Fixture */
/* Test case functions */
/**
* Check SDL_HINT_LOGGING functionality
*/
static int log_testHint(void *arg)
{
int count;
SDL_SetHint(SDL_HINT_LOGGING, NULL);
SDLTest_AssertPass("SDL_SetHint(SDL_HINT_LOGGING, NULL)");
{
EnableTestLog(&count);
SDL_LogMessage(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO, "test");
DisableTestLog();
SDLTest_AssertPass("SDL_LogMessage(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO, \"test\")");
SDLTest_AssertCheck(count == 1, "Check result value, expected: 1, got: %d", count);
EnableTestLog(&count);
SDL_LogMessage(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_DEBUG, "test");
DisableTestLog();
SDLTest_AssertPass("SDL_LogMessage(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_DEBUG, \"test\")");
SDLTest_AssertCheck(count == 0, "Check result value, expected: 0, got: %d", count);
}
SDL_SetHint(SDL_HINT_LOGGING, "debug");
SDLTest_AssertPass("SDL_SetHint(SDL_HINT_LOGGING, \"debug\")");
{
EnableTestLog(&count);
SDL_LogMessage(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_DEBUG, "test");
DisableTestLog();
SDLTest_AssertPass("SDL_LogMessage(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_DEBUG, \"test\")");
SDLTest_AssertCheck(count == 1, "Check result value, expected: 1, got: %d", count);
EnableTestLog(&count);
SDL_LogMessage(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_VERBOSE, "test");
DisableTestLog();
SDLTest_AssertPass("SDL_LogMessage(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_VERBOSE, \"test\")");
SDLTest_AssertCheck(count == 0, "Check result value, expected: 0, got: %d", count);
}
SDL_SetHint(SDL_HINT_LOGGING, "system=debug");
SDLTest_AssertPass("SDL_SetHint(SDL_HINT_LOGGING, \"system=debug\")");
{
EnableTestLog(&count);
SDL_LogMessage(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_DEBUG, "test");
DisableTestLog();
SDLTest_AssertPass("SDL_LogMessage(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_DEBUG, \"test\")");
SDLTest_AssertCheck(count == 0, "Check result value, expected: 0, got: %d", count);
EnableTestLog(&count);
SDL_LogMessage(SDL_LOG_CATEGORY_SYSTEM, SDL_LOG_PRIORITY_DEBUG, "test");
DisableTestLog();
SDLTest_AssertPass("SDL_LogMessage(SDL_LOG_CATEGORY_SYSTEM, SDL_LOG_PRIORITY_DEBUG, \"test\")");
SDLTest_AssertCheck(count == 1, "Check result value, expected: 1, got: %d", count);
EnableTestLog(&count);
SDL_LogMessage(SDL_LOG_CATEGORY_SYSTEM, SDL_LOG_PRIORITY_VERBOSE, "test");
DisableTestLog();
SDLTest_AssertPass("SDL_LogMessage(SDL_LOG_CATEGORY_SYSTEM, SDL_LOG_PRIORITY_VERBOSE, \"test\")");
SDLTest_AssertCheck(count == 0, "Check result value, expected: 0, got: %d", count);
}
SDL_SetHint(SDL_HINT_LOGGING, "app=warn,system=debug,assert=quiet,*=info");
SDLTest_AssertPass("SDL_SetHint(SDL_HINT_LOGGING, \"app=warn,system=debug,assert=quiet,*=info\")");
{
EnableTestLog(&count);
SDL_LogMessage(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_WARN, "test");
DisableTestLog();
SDLTest_AssertPass("SDL_LogMessage(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_WARN, \"test\")");
SDLTest_AssertCheck(count == 1, "Check result value, expected: 1, got: %d", count);
EnableTestLog(&count);
SDL_LogMessage(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO, "test");
DisableTestLog();
SDLTest_AssertPass("SDL_LogMessage(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO, \"test\")");
SDLTest_AssertCheck(count == 0, "Check result value, expected: 0, got: %d", count);
EnableTestLog(&count);
SDL_LogMessage(SDL_LOG_CATEGORY_SYSTEM, SDL_LOG_PRIORITY_DEBUG, "test");
DisableTestLog();
SDLTest_AssertPass("SDL_LogMessage(SDL_LOG_CATEGORY_SYSTEM, SDL_LOG_PRIORITY_DEBUG, \"test\")");
SDLTest_AssertCheck(count == 1, "Check result value, expected: 1, got: %d", count);
EnableTestLog(&count);
SDL_LogMessage(SDL_LOG_CATEGORY_SYSTEM, SDL_LOG_PRIORITY_VERBOSE, "test");
DisableTestLog();
SDLTest_AssertPass("SDL_LogMessage(SDL_LOG_CATEGORY_SYSTEM, SDL_LOG_PRIORITY_VERBOSE, \"test\")");
SDLTest_AssertCheck(count == 0, "Check result value, expected: 0, got: %d", count);
EnableTestLog(&count);
SDL_LogMessage(SDL_LOG_CATEGORY_ASSERT, SDL_LOG_PRIORITY_CRITICAL, "test");
DisableTestLog();
SDLTest_AssertPass("SDL_LogMessage(SDL_LOG_CATEGORY_ASSERT, SDL_LOG_PRIORITY_CRITICAL, \"test\")");
SDLTest_AssertCheck(count == 0, "Check result value, expected: 0, got: %d", count);
EnableTestLog(&count);
SDL_LogMessage(SDL_LOG_CATEGORY_CUSTOM, SDL_LOG_PRIORITY_INFO, "test");
DisableTestLog();
SDLTest_AssertPass("SDL_LogMessage(SDL_LOG_CATEGORY_CUSTOM, SDL_LOG_PRIORITY_INFO, \"test\")");
SDLTest_AssertCheck(count == 1, "Check result value, expected: 1, got: %d", count);
EnableTestLog(&count);
SDL_LogMessage(SDL_LOG_CATEGORY_CUSTOM, SDL_LOG_PRIORITY_DEBUG, "test");
DisableTestLog();
SDLTest_AssertPass("SDL_LogMessage(SDL_LOG_CATEGORY_CUSTOM, SDL_LOG_PRIORITY_DEBUG, \"test\")");
SDLTest_AssertCheck(count == 0, "Check result value, expected: 0, got: %d", count);
}
SDL_SetHint(SDL_HINT_LOGGING, "0=4,3=2,2=0,*=3");
SDLTest_AssertPass("SDL_SetHint(SDL_HINT_LOGGING, \"0=4,3=2,2=0,*=3\")");
{
EnableTestLog(&count);
SDL_LogMessage(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_WARN, "test");
DisableTestLog();
SDLTest_AssertPass("SDL_LogMessage(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_WARN, \"test\")");
SDLTest_AssertCheck(count == 1, "Check result value, expected: 1, got: %d", count);
EnableTestLog(&count);
SDL_LogMessage(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO, "test");
DisableTestLog();
SDLTest_AssertPass("SDL_LogMessage(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO, \"test\")");
SDLTest_AssertCheck(count == 0, "Check result value, expected: 0, got: %d", count);
EnableTestLog(&count);
SDL_LogMessage(SDL_LOG_CATEGORY_SYSTEM, SDL_LOG_PRIORITY_DEBUG, "test");
DisableTestLog();
SDLTest_AssertPass("SDL_LogMessage(SDL_LOG_CATEGORY_SYSTEM, SDL_LOG_PRIORITY_DEBUG, \"test\")");
SDLTest_AssertCheck(count == 1, "Check result value, expected: 1, got: %d", count);
EnableTestLog(&count);
SDL_LogMessage(SDL_LOG_CATEGORY_SYSTEM, SDL_LOG_PRIORITY_VERBOSE, "test");
DisableTestLog();
SDLTest_AssertPass("SDL_LogMessage(SDL_LOG_CATEGORY_SYSTEM, SDL_LOG_PRIORITY_VERBOSE, \"test\")");
SDLTest_AssertCheck(count == 0, "Check result value, expected: 0, got: %d", count);
EnableTestLog(&count);
SDL_LogMessage(SDL_LOG_CATEGORY_ASSERT, SDL_LOG_PRIORITY_CRITICAL, "test");
DisableTestLog();
SDLTest_AssertPass("SDL_LogMessage(SDL_LOG_CATEGORY_ASSERT, SDL_LOG_PRIORITY_CRITICAL, \"test\")");
SDLTest_AssertCheck(count == 0, "Check result value, expected: 0, got: %d", count);
EnableTestLog(&count);
SDL_LogMessage(SDL_LOG_CATEGORY_CUSTOM, SDL_LOG_PRIORITY_INFO, "test");
DisableTestLog();
SDLTest_AssertPass("SDL_LogMessage(SDL_LOG_CATEGORY_CUSTOM, SDL_LOG_PRIORITY_INFO, \"test\")");
SDLTest_AssertCheck(count == 1, "Check result value, expected: 1, got: %d", count);
EnableTestLog(&count);
SDL_LogMessage(SDL_LOG_CATEGORY_CUSTOM, SDL_LOG_PRIORITY_DEBUG, "test");
DisableTestLog();
SDLTest_AssertPass("SDL_LogMessage(SDL_LOG_CATEGORY_CUSTOM, SDL_LOG_PRIORITY_DEBUG, \"test\")");
SDLTest_AssertCheck(count == 0, "Check result value, expected: 0, got: %d", count);
}
return TEST_COMPLETED;
}
/* ================= Test References ================== */
/* Log test cases */
static const SDLTest_TestCaseReference logTestHint = {
(SDLTest_TestCaseFp)log_testHint, "log_testHint", "Check SDL_HINT_LOGGING functionality", TEST_ENABLED
};
/* Sequence of Log test cases */
static const SDLTest_TestCaseReference *logTests[] = {
&logTestHint, NULL
};
/* Timer test suite (global) */
SDLTest_TestSuiteReference logTestSuite = {
"Log",
NULL,
logTests,
NULL
};

View File

@ -0,0 +1,159 @@
/**
* Automated SDL subsystems management test.
*
* Written by J<>rgen Tjern<72> "jorgenpt"
*
* Released under Public Domain.
*/
#include "SDL.h"
#include "SDL_test.h"
/* !
* \brief Tests SDL_InitSubSystem() and SDL_QuitSubSystem()
* \sa
* http://wiki.libsdl.org/SDL_Init
* http://wiki.libsdl.org/SDL_Quit
*/
static int main_testInitQuitSubSystem(void *arg)
{
#if defined SDL_JOYSTICK_DISABLED || defined SDL_HAPTIC_DISABLED || defined SDL_GAMECONTROLLER_DISABLED
return TEST_SKIPPED;
#else
int i;
int subsystems[] = { SDL_INIT_JOYSTICK, SDL_INIT_HAPTIC, SDL_INIT_GAMECONTROLLER };
for (i = 0; i < SDL_arraysize(subsystems); ++i) {
int initialized_system;
int subsystem = subsystems[i];
SDLTest_AssertCheck((SDL_WasInit(subsystem) & subsystem) == 0, "SDL_WasInit(%x) before init should be false", subsystem);
SDLTest_AssertCheck(SDL_InitSubSystem(subsystem) == 0, "SDL_InitSubSystem(%x)", subsystem);
initialized_system = SDL_WasInit(subsystem);
SDLTest_AssertCheck((initialized_system & subsystem) != 0, "SDL_WasInit(%x) should be true (%x)", subsystem, initialized_system);
SDL_QuitSubSystem(subsystem);
SDLTest_AssertCheck((SDL_WasInit(subsystem) & subsystem) == 0, "SDL_WasInit(%x) after shutdown should be false", subsystem);
}
return TEST_COMPLETED;
#endif
}
const int joy_and_controller = SDL_INIT_JOYSTICK | SDL_INIT_GAMECONTROLLER;
static int main_testImpliedJoystickInit(void *arg)
{
#if defined SDL_JOYSTICK_DISABLED || defined SDL_GAMECONTROLLER_DISABLED
return TEST_SKIPPED;
#else
int initialized_system;
/* First initialize the controller */
SDLTest_AssertCheck((SDL_WasInit(joy_and_controller) & joy_and_controller) == 0, "SDL_WasInit() before init should be false for joystick & controller");
SDLTest_AssertCheck(SDL_InitSubSystem(SDL_INIT_GAMECONTROLLER) == 0, "SDL_InitSubSystem(SDL_INIT_GAMECONTROLLER)");
/* Then make sure this implicitly initialized the joystick subsystem */
initialized_system = SDL_WasInit(joy_and_controller);
SDLTest_AssertCheck((initialized_system & joy_and_controller) == joy_and_controller, "SDL_WasInit() should be true for joystick & controller (%x)", initialized_system);
/* Then quit the controller, and make sure that implicitly also quits the */
/* joystick subsystem */
SDL_QuitSubSystem(SDL_INIT_GAMECONTROLLER);
initialized_system = SDL_WasInit(joy_and_controller);
SDLTest_AssertCheck((initialized_system & joy_and_controller) == 0, "SDL_WasInit() should be false for joystick & controller (%x)", initialized_system);
return TEST_COMPLETED;
#endif
}
static int main_testImpliedJoystickQuit(void *arg)
{
#if defined SDL_JOYSTICK_DISABLED || defined SDL_GAMECONTROLLER_DISABLED
return TEST_SKIPPED;
#else
int initialized_system;
/* First initialize the controller and the joystick (explicitly) */
SDLTest_AssertCheck((SDL_WasInit(joy_and_controller) & joy_and_controller) == 0, "SDL_WasInit() before init should be false for joystick & controller");
SDLTest_AssertCheck(SDL_InitSubSystem(SDL_INIT_JOYSTICK) == 0, "SDL_InitSubSystem(SDL_INIT_JOYSTICK)");
SDLTest_AssertCheck(SDL_InitSubSystem(SDL_INIT_GAMECONTROLLER) == 0, "SDL_InitSubSystem(SDL_INIT_GAMECONTROLLER)");
/* Then make sure they're both initialized properly */
initialized_system = SDL_WasInit(joy_and_controller);
SDLTest_AssertCheck((initialized_system & joy_and_controller) == joy_and_controller, "SDL_WasInit() should be true for joystick & controller (%x)", initialized_system);
/* Then quit the controller, and make sure that it does NOT quit the */
/* explicitly initialized joystick subsystem. */
SDL_QuitSubSystem(SDL_INIT_GAMECONTROLLER);
initialized_system = SDL_WasInit(joy_and_controller);
SDLTest_AssertCheck((initialized_system & joy_and_controller) == SDL_INIT_JOYSTICK, "SDL_WasInit() should be false for joystick & controller (%x)", initialized_system);
SDL_QuitSubSystem(SDL_INIT_JOYSTICK);
return TEST_COMPLETED;
#endif
}
#if defined(__GNUC__) || defined(__clang__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wformat-zero-length"
#endif
static int
main_testSetError(void *arg)
{
size_t i;
char error[1024];
error[0] = '\0';
SDL_SetError("");
SDLTest_AssertCheck(SDL_strcmp(error, SDL_GetError()) == 0, "SDL_SetError(\"\")");
for (i = 0; i < (sizeof(error) - 1); ++i) {
error[i] = 'a' + (i % 26);
}
error[i] = '\0';
SDL_SetError("%s", error);
SDLTest_AssertCheck(SDL_strcmp(error, SDL_GetError()) == 0, "SDL_SetError(\"abc...1023\")");
return TEST_COMPLETED;
}
#if defined(__GNUC__) || defined(__clang__)
#pragma GCC diagnostic pop
#endif
static const SDLTest_TestCaseReference mainTest1 = {
(SDLTest_TestCaseFp)main_testInitQuitSubSystem, "main_testInitQuitSubSystem", "Tests SDL_InitSubSystem/QuitSubSystem", TEST_ENABLED
};
static const SDLTest_TestCaseReference mainTest2 = {
(SDLTest_TestCaseFp)main_testImpliedJoystickInit, "main_testImpliedJoystickInit", "Tests that init for gamecontroller properly implies joystick", TEST_ENABLED
};
static const SDLTest_TestCaseReference mainTest3 = {
(SDLTest_TestCaseFp)main_testImpliedJoystickQuit, "main_testImpliedJoystickQuit", "Tests that quit for gamecontroller doesn't quit joystick if you inited it explicitly", TEST_ENABLED
};
static const SDLTest_TestCaseReference mainTest4 = {
(SDLTest_TestCaseFp)main_testSetError, "main_testSetError", "Tests that SDL_SetError() handles arbitrarily large strings", TEST_ENABLED
};
/* Sequence of Main test cases */
static const SDLTest_TestCaseReference *mainTests[] = {
&mainTest1,
&mainTest2,
&mainTest3,
&mainTest4,
NULL
};
/* Main test suite (global) */
SDLTest_TestSuiteReference mainTestSuite = {
"Main",
NULL,
mainTests,
NULL
};

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,616 @@
/**
* Mouse test suite
*/
#include <stdio.h>
#include <limits.h>
#include "SDL.h"
#include "SDL_test.h"
/* ================= Test Case Implementation ================== */
/* Test case functions */
/* Helper to evaluate state returned from SDL_GetMouseState */
int _mouseStateCheck(Uint32 state)
{
return (state == 0) ||
(state == SDL_BUTTON(SDL_BUTTON_LEFT)) ||
(state == SDL_BUTTON(SDL_BUTTON_MIDDLE)) ||
(state == SDL_BUTTON(SDL_BUTTON_RIGHT)) ||
(state == SDL_BUTTON(SDL_BUTTON_X1)) ||
(state == SDL_BUTTON(SDL_BUTTON_X2));
}
/**
* @brief Check call to SDL_GetMouseState
*
*/
int mouse_getMouseState(void *arg)
{
int x;
int y;
Uint32 state;
/* Pump some events to update mouse state */
SDL_PumpEvents();
SDLTest_AssertPass("Call to SDL_PumpEvents()");
/* Case where x, y pointer is NULL */
state = SDL_GetMouseState(NULL, NULL);
SDLTest_AssertPass("Call to SDL_GetMouseState(NULL, NULL)");
SDLTest_AssertCheck(_mouseStateCheck(state), "Validate state returned from function, got: %" SDL_PRIu32, state);
/* Case where x pointer is not NULL */
x = INT_MIN;
state = SDL_GetMouseState(&x, NULL);
SDLTest_AssertPass("Call to SDL_GetMouseState(&x, NULL)");
SDLTest_AssertCheck(x > INT_MIN, "Validate that value of x is > INT_MIN, got: %i", x);
SDLTest_AssertCheck(_mouseStateCheck(state), "Validate state returned from function, got: %" SDL_PRIu32, state);
/* Case where y pointer is not NULL */
y = INT_MIN;
state = SDL_GetMouseState(NULL, &y);
SDLTest_AssertPass("Call to SDL_GetMouseState(NULL, &y)");
SDLTest_AssertCheck(y > INT_MIN, "Validate that value of y is > INT_MIN, got: %i", y);
SDLTest_AssertCheck(_mouseStateCheck(state), "Validate state returned from function, got: %" SDL_PRIu32, state);
/* Case where x and y pointer is not NULL */
x = INT_MIN;
y = INT_MIN;
state = SDL_GetMouseState(&x, &y);
SDLTest_AssertPass("Call to SDL_GetMouseState(&x, &y)");
SDLTest_AssertCheck(x > INT_MIN, "Validate that value of x is > INT_MIN, got: %i", x);
SDLTest_AssertCheck(y > INT_MIN, "Validate that value of y is > INT_MIN, got: %i", y);
SDLTest_AssertCheck(_mouseStateCheck(state), "Validate state returned from function, got: %" SDL_PRIu32, state);
return TEST_COMPLETED;
}
/**
* @brief Check call to SDL_GetRelativeMouseState
*
*/
int mouse_getRelativeMouseState(void *arg)
{
int x;
int y;
Uint32 state;
/* Pump some events to update mouse state */
SDL_PumpEvents();
SDLTest_AssertPass("Call to SDL_PumpEvents()");
/* Case where x, y pointer is NULL */
state = SDL_GetRelativeMouseState(NULL, NULL);
SDLTest_AssertPass("Call to SDL_GetRelativeMouseState(NULL, NULL)");
SDLTest_AssertCheck(_mouseStateCheck(state), "Validate state returned from function, got: %" SDL_PRIu32, state);
/* Case where x pointer is not NULL */
x = INT_MIN;
state = SDL_GetRelativeMouseState(&x, NULL);
SDLTest_AssertPass("Call to SDL_GetRelativeMouseState(&x, NULL)");
SDLTest_AssertCheck(x > INT_MIN, "Validate that value of x is > INT_MIN, got: %i", x);
SDLTest_AssertCheck(_mouseStateCheck(state), "Validate state returned from function, got: %" SDL_PRIu32, state);
/* Case where y pointer is not NULL */
y = INT_MIN;
state = SDL_GetRelativeMouseState(NULL, &y);
SDLTest_AssertPass("Call to SDL_GetRelativeMouseState(NULL, &y)");
SDLTest_AssertCheck(y > INT_MIN, "Validate that value of y is > INT_MIN, got: %i", y);
SDLTest_AssertCheck(_mouseStateCheck(state), "Validate state returned from function, got: %" SDL_PRIu32, state);
/* Case where x and y pointer is not NULL */
x = INT_MIN;
y = INT_MIN;
state = SDL_GetRelativeMouseState(&x, &y);
SDLTest_AssertPass("Call to SDL_GetRelativeMouseState(&x, &y)");
SDLTest_AssertCheck(x > INT_MIN, "Validate that value of x is > INT_MIN, got: %i", x);
SDLTest_AssertCheck(y > INT_MIN, "Validate that value of y is > INT_MIN, got: %i", y);
SDLTest_AssertCheck(_mouseStateCheck(state), "Validate state returned from function, got: %" SDL_PRIu32, state);
return TEST_COMPLETED;
}
/* XPM definition of mouse Cursor */
static const char *_mouseArrowData[] = {
/* pixels */
"X ",
"XX ",
"X.X ",
"X..X ",
"X...X ",
"X....X ",
"X.....X ",
"X......X ",
"X.......X ",
"X........X ",
"X.....XXXXX ",
"X..X..X ",
"X.X X..X ",
"XX X..X ",
"X X..X ",
" X..X ",
" X..X ",
" X..X ",
" XX ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" "
};
/* Helper that creates a new mouse cursor from an XPM */
static SDL_Cursor *_initArrowCursor(const char *image[])
{
SDL_Cursor *cursor;
int i, row, col;
Uint8 data[4 * 32];
Uint8 mask[4 * 32];
i = -1;
for (row = 0; row < 32; ++row) {
for (col = 0; col < 32; ++col) {
if (col % 8) {
data[i] <<= 1;
mask[i] <<= 1;
} else {
++i;
data[i] = mask[i] = 0;
}
switch (image[row][col]) {
case 'X':
data[i] |= 0x01;
mask[i] |= 0x01;
break;
case '.':
mask[i] |= 0x01;
break;
case ' ':
break;
}
}
}
cursor = SDL_CreateCursor(data, mask, 32, 32, 0, 0);
return cursor;
}
/**
* @brief Check call to SDL_CreateCursor and SDL_FreeCursor
*
* @sa http://wiki.libsdl.org/SDL_CreateCursor
* @sa http://wiki.libsdl.org/SDL_FreeCursor
*/
int mouse_createFreeCursor(void *arg)
{
SDL_Cursor *cursor;
/* Create a cursor */
cursor = _initArrowCursor(_mouseArrowData);
SDLTest_AssertPass("Call to SDL_CreateCursor()");
SDLTest_AssertCheck(cursor != NULL, "Validate result from SDL_CreateCursor() is not NULL");
if (cursor == NULL) {
return TEST_ABORTED;
}
/* Free cursor again */
SDL_FreeCursor(cursor);
SDLTest_AssertPass("Call to SDL_FreeCursor()");
return TEST_COMPLETED;
}
/**
* @brief Check call to SDL_CreateColorCursor and SDL_FreeCursor
*
* @sa http://wiki.libsdl.org/SDL_CreateColorCursor
* @sa http://wiki.libsdl.org/SDL_FreeCursor
*/
int mouse_createFreeColorCursor(void *arg)
{
SDL_Surface *face;
SDL_Cursor *cursor;
/* Get sample surface */
face = SDLTest_ImageFace();
SDLTest_AssertCheck(face != NULL, "Validate sample input image is not NULL");
if (face == NULL) {
return TEST_ABORTED;
}
/* Create a color cursor from surface */
cursor = SDL_CreateColorCursor(face, 0, 0);
SDLTest_AssertPass("Call to SDL_CreateColorCursor()");
SDLTest_AssertCheck(cursor != NULL, "Validate result from SDL_CreateColorCursor() is not NULL");
if (cursor == NULL) {
SDL_FreeSurface(face);
return TEST_ABORTED;
}
/* Free cursor again */
SDL_FreeCursor(cursor);
SDLTest_AssertPass("Call to SDL_FreeCursor()");
/* Clean up */
SDL_FreeSurface(face);
return TEST_COMPLETED;
}
/* Helper that changes cursor visibility */
void _changeCursorVisibility(int state)
{
int oldState;
int newState;
int result;
oldState = SDL_ShowCursor(SDL_QUERY);
SDLTest_AssertPass("Call to SDL_ShowCursor(SDL_QUERY)");
result = SDL_ShowCursor(state);
SDLTest_AssertPass("Call to SDL_ShowCursor(%s)", (state == SDL_ENABLE) ? "SDL_ENABLE" : "SDL_DISABLE");
SDLTest_AssertCheck(result == oldState, "Validate result from SDL_ShowCursor(%s), expected: %i, got: %i",
(state == SDL_ENABLE) ? "SDL_ENABLE" : "SDL_DISABLE", oldState, result);
newState = SDL_ShowCursor(SDL_QUERY);
SDLTest_AssertPass("Call to SDL_ShowCursor(SDL_QUERY)");
SDLTest_AssertCheck(state == newState, "Validate new state, expected: %i, got: %i",
state, newState);
}
/**
* @brief Check call to SDL_ShowCursor
*
* @sa http://wiki.libsdl.org/SDL_ShowCursor
*/
int mouse_showCursor(void *arg)
{
int currentState;
/* Get current state */
currentState = SDL_ShowCursor(SDL_QUERY);
SDLTest_AssertPass("Call to SDL_ShowCursor(SDL_QUERY)");
SDLTest_AssertCheck(currentState == SDL_DISABLE || currentState == SDL_ENABLE,
"Validate result is %i or %i, got: %i", SDL_DISABLE, SDL_ENABLE, currentState);
if (currentState == SDL_DISABLE) {
/* Show the cursor, then hide it again */
_changeCursorVisibility(SDL_ENABLE);
_changeCursorVisibility(SDL_DISABLE);
} else if (currentState == SDL_ENABLE) {
/* Hide the cursor, then show it again */
_changeCursorVisibility(SDL_DISABLE);
_changeCursorVisibility(SDL_ENABLE);
} else {
return TEST_ABORTED;
}
return TEST_COMPLETED;
}
/**
* @brief Check call to SDL_SetCursor
*
* @sa http://wiki.libsdl.org/SDL_SetCursor
*/
int mouse_setCursor(void *arg)
{
SDL_Cursor *cursor;
/* Create a cursor */
cursor = _initArrowCursor(_mouseArrowData);
SDLTest_AssertPass("Call to SDL_CreateCursor()");
SDLTest_AssertCheck(cursor != NULL, "Validate result from SDL_CreateCursor() is not NULL");
if (cursor == NULL) {
return TEST_ABORTED;
}
/* Set the arrow cursor */
SDL_SetCursor(cursor);
SDLTest_AssertPass("Call to SDL_SetCursor(cursor)");
/* Force redraw */
SDL_SetCursor(NULL);
SDLTest_AssertPass("Call to SDL_SetCursor(NULL)");
/* Free cursor again */
SDL_FreeCursor(cursor);
SDLTest_AssertPass("Call to SDL_FreeCursor()");
return TEST_COMPLETED;
}
/**
* @brief Check call to SDL_GetCursor
*
* @sa http://wiki.libsdl.org/SDL_GetCursor
*/
int mouse_getCursor(void *arg)
{
SDL_Cursor *cursor;
/* Get current cursor */
cursor = SDL_GetCursor();
SDLTest_AssertPass("Call to SDL_GetCursor()");
SDLTest_AssertCheck(cursor != NULL, "Validate result from SDL_GetCursor() is not NULL");
return TEST_COMPLETED;
}
/**
* @brief Check call to SDL_GetRelativeMouseMode and SDL_SetRelativeMouseMode
*
* @sa http://wiki.libsdl.org/SDL_GetRelativeMouseMode
* @sa http://wiki.libsdl.org/SDL_SetRelativeMouseMode
*/
int mouse_getSetRelativeMouseMode(void *arg)
{
int result;
int i;
SDL_bool initialState;
SDL_bool currentState;
/* Capture original state so we can revert back to it later */
initialState = SDL_GetRelativeMouseMode();
SDLTest_AssertPass("Call to SDL_GetRelativeMouseMode()");
/* Repeat twice to check D->D transition */
for (i = 0; i < 2; i++) {
/* Disable - should always be supported */
result = SDL_SetRelativeMouseMode(SDL_FALSE);
SDLTest_AssertPass("Call to SDL_SetRelativeMouseMode(FALSE)");
SDLTest_AssertCheck(result == 0, "Validate result value from SDL_SetRelativeMouseMode, expected: 0, got: %i", result);
currentState = SDL_GetRelativeMouseMode();
SDLTest_AssertPass("Call to SDL_GetRelativeMouseMode()");
SDLTest_AssertCheck(currentState == SDL_FALSE, "Validate current state is FALSE, got: %i", currentState);
}
/* Repeat twice to check D->E->E transition */
for (i = 0; i < 2; i++) {
/* Enable - may not be supported */
result = SDL_SetRelativeMouseMode(SDL_TRUE);
SDLTest_AssertPass("Call to SDL_SetRelativeMouseMode(TRUE)");
if (result != -1) {
SDLTest_AssertCheck(result == 0, "Validate result value from SDL_SetRelativeMouseMode, expected: 0, got: %i", result);
currentState = SDL_GetRelativeMouseMode();
SDLTest_AssertPass("Call to SDL_GetRelativeMouseMode()");
SDLTest_AssertCheck(currentState == SDL_TRUE, "Validate current state is TRUE, got: %i", currentState);
}
}
/* Disable to check E->D transition */
result = SDL_SetRelativeMouseMode(SDL_FALSE);
SDLTest_AssertPass("Call to SDL_SetRelativeMouseMode(FALSE)");
SDLTest_AssertCheck(result == 0, "Validate result value from SDL_SetRelativeMouseMode, expected: 0, got: %i", result);
currentState = SDL_GetRelativeMouseMode();
SDLTest_AssertPass("Call to SDL_GetRelativeMouseMode()");
SDLTest_AssertCheck(currentState == SDL_FALSE, "Validate current state is FALSE, got: %i", currentState);
/* Revert to original state - ignore result */
result = SDL_SetRelativeMouseMode(initialState);
return TEST_COMPLETED;
}
#define MOUSE_TESTWINDOW_WIDTH 320
#define MOUSE_TESTWINDOW_HEIGHT 200
/**
* Creates a test window
*/
SDL_Window *_createMouseSuiteTestWindow()
{
int posX = 100, posY = 100, width = MOUSE_TESTWINDOW_WIDTH, height = MOUSE_TESTWINDOW_HEIGHT;
SDL_Window *window;
window = SDL_CreateWindow("mouse_createMouseSuiteTestWindow", posX, posY, width, height, 0);
SDLTest_AssertPass("SDL_CreateWindow()");
SDLTest_AssertCheck(window != NULL, "Check SDL_CreateWindow result");
return window;
}
/*
* Destroy test window
*/
void _destroyMouseSuiteTestWindow(SDL_Window *window)
{
if (window) {
SDL_DestroyWindow(window);
window = NULL;
SDLTest_AssertPass("SDL_DestroyWindow()");
}
}
/**
* @brief Check call to SDL_WarpMouseInWindow
*
* @sa http://wiki.libsdl.org/SDL_WarpMouseInWindow
*/
int mouse_warpMouseInWindow(void *arg)
{
const int w = MOUSE_TESTWINDOW_WIDTH, h = MOUSE_TESTWINDOW_HEIGHT;
int numPositions = 6;
int xPositions[6];
int yPositions[6];
int x, y, i, j;
SDL_Window *window;
xPositions[0] = -1;
xPositions[1] = 0;
xPositions[2] = 1;
xPositions[3] = w - 1;
xPositions[4] = w;
xPositions[5] = w + 1;
yPositions[0] = -1;
yPositions[1] = 0;
yPositions[2] = 1;
yPositions[3] = h - 1;
yPositions[4] = h;
yPositions[5] = h + 1;
/* Create test window */
window = _createMouseSuiteTestWindow();
if (!window) {
return TEST_ABORTED;
}
/* Mouse to random position inside window */
x = SDLTest_RandomIntegerInRange(1, w - 1);
y = SDLTest_RandomIntegerInRange(1, h - 1);
SDL_WarpMouseInWindow(window, x, y);
SDLTest_AssertPass("SDL_WarpMouseInWindow(...,%i,%i)", x, y);
/* Same position again */
SDL_WarpMouseInWindow(window, x, y);
SDLTest_AssertPass("SDL_WarpMouseInWindow(...,%i,%i)", x, y);
/* Mouse to various boundary positions */
for (i = 0; i < numPositions; i++) {
for (j = 0; j < numPositions; j++) {
x = xPositions[i];
y = yPositions[j];
SDL_WarpMouseInWindow(window, x, y);
SDLTest_AssertPass("SDL_WarpMouseInWindow(...,%i,%i)", x, y);
/* TODO: add tracking of events and check that each call generates a mouse motion event */
SDL_PumpEvents();
SDLTest_AssertPass("SDL_PumpEvents()");
}
}
/* Clean up test window */
_destroyMouseSuiteTestWindow(window);
return TEST_COMPLETED;
}
/**
* @brief Check call to SDL_GetMouseFocus
*
* @sa http://wiki.libsdl.org/SDL_GetMouseFocus
*/
int mouse_getMouseFocus(void *arg)
{
const int w = MOUSE_TESTWINDOW_WIDTH, h = MOUSE_TESTWINDOW_HEIGHT;
int x, y;
SDL_Window *window;
SDL_Window *focusWindow;
const SDL_bool video_driver_is_wayland = !SDL_strcmp(SDL_GetCurrentVideoDriver(), "wayland");
/* Get focus - focus non-deterministic */
focusWindow = SDL_GetMouseFocus();
SDLTest_AssertPass("SDL_GetMouseFocus()");
/* Create test window */
window = _createMouseSuiteTestWindow();
if (!window) {
return TEST_ABORTED;
}
/* Wayland explicitly disallows warping the mouse pointer, so this test must be skipped. */
if (!video_driver_is_wayland) {
/* Mouse to random position inside window */
x = SDLTest_RandomIntegerInRange(1, w - 1);
y = SDLTest_RandomIntegerInRange(1, h - 1);
SDL_WarpMouseInWindow(window, x, y);
SDLTest_AssertPass("SDL_WarpMouseInWindow(...,%i,%i)", x, y);
/* Pump events to update focus state */
SDL_Delay(100);
SDL_PumpEvents();
SDLTest_AssertPass("SDL_PumpEvents()");
/* Get focus with explicit window setup - focus deterministic */
focusWindow = SDL_GetMouseFocus();
SDLTest_AssertPass("SDL_GetMouseFocus()");
SDLTest_AssertCheck(focusWindow != NULL, "Check returned window value is not NULL");
SDLTest_AssertCheck(focusWindow == window, "Check returned window value is test window");
/* Mouse to random position outside window */
x = SDLTest_RandomIntegerInRange(-9, -1);
y = SDLTest_RandomIntegerInRange(-9, -1);
SDL_WarpMouseInWindow(window, x, y);
SDLTest_AssertPass("SDL_WarpMouseInWindow(...,%i,%i)", x, y);
} else {
SDLTest_Log("Skipping mouse warp focus tests: Wayland does not support warping the mouse pointer");
}
/* Clean up test window */
_destroyMouseSuiteTestWindow(window);
/* Pump events to update focus state */
SDL_PumpEvents();
SDLTest_AssertPass("SDL_PumpEvents()");
/* Get focus for non-existing window */
focusWindow = SDL_GetMouseFocus();
SDLTest_AssertPass("SDL_GetMouseFocus()");
SDLTest_AssertCheck(focusWindow == NULL, "Check returned window value is NULL");
return TEST_COMPLETED;
}
/* ================= Test References ================== */
/* Mouse test cases */
static const SDLTest_TestCaseReference mouseTest1 = {
(SDLTest_TestCaseFp)mouse_getMouseState, "mouse_getMouseState", "Check call to SDL_GetMouseState", TEST_ENABLED
};
static const SDLTest_TestCaseReference mouseTest2 = {
(SDLTest_TestCaseFp)mouse_getRelativeMouseState, "mouse_getRelativeMouseState", "Check call to SDL_GetRelativeMouseState", TEST_ENABLED
};
static const SDLTest_TestCaseReference mouseTest3 = {
(SDLTest_TestCaseFp)mouse_createFreeCursor, "mouse_createFreeCursor", "Check call to SDL_CreateCursor and SDL_FreeCursor", TEST_ENABLED
};
static const SDLTest_TestCaseReference mouseTest4 = {
(SDLTest_TestCaseFp)mouse_showCursor, "mouse_showCursor", "Check call to SDL_ShowCursor", TEST_ENABLED
};
static const SDLTest_TestCaseReference mouseTest5 = {
(SDLTest_TestCaseFp)mouse_setCursor, "mouse_setCursor", "Check call to SDL_SetCursor", TEST_ENABLED
};
static const SDLTest_TestCaseReference mouseTest6 = {
(SDLTest_TestCaseFp)mouse_getCursor, "mouse_getCursor", "Check call to SDL_GetCursor", TEST_ENABLED
};
static const SDLTest_TestCaseReference mouseTest7 = {
(SDLTest_TestCaseFp)mouse_warpMouseInWindow, "mouse_warpMouseInWindow", "Check call to SDL_WarpMouseInWindow", TEST_ENABLED
};
static const SDLTest_TestCaseReference mouseTest8 = {
(SDLTest_TestCaseFp)mouse_getMouseFocus, "mouse_getMouseFocus", "Check call to SDL_getMouseFocus", TEST_ENABLED
};
static const SDLTest_TestCaseReference mouseTest9 = {
(SDLTest_TestCaseFp)mouse_createFreeColorCursor, "mouse_createFreeColorCursor", "Check call to SDL_CreateColorCursor and SDL_FreeCursor", TEST_ENABLED
};
static const SDLTest_TestCaseReference mouseTest10 = {
(SDLTest_TestCaseFp)mouse_getSetRelativeMouseMode, "mouse_getSetRelativeMouseMode", "Check call to SDL_GetRelativeMouseMode and SDL_SetRelativeMouseMode", TEST_ENABLED
};
/* Sequence of Mouse test cases */
static const SDLTest_TestCaseReference *mouseTests[] = {
&mouseTest1, &mouseTest2, &mouseTest3, &mouseTest4, &mouseTest5, &mouseTest6,
&mouseTest7, &mouseTest8, &mouseTest9, &mouseTest10, NULL
};
/* Mouse test suite (global) */
SDLTest_TestSuiteReference mouseTestSuite = {
"Mouse",
NULL,
mouseTests,
NULL
};

View File

@ -0,0 +1,500 @@
/**
* Pixels test suite
*/
#include <stdio.h>
#include "SDL.h"
#include "SDL_test.h"
/* Test case functions */
/* Definition of all RGB formats used to test pixel conversions */
const int _numRGBPixelFormats = 31;
Uint32 _RGBPixelFormats[] = {
SDL_PIXELFORMAT_INDEX1LSB,
SDL_PIXELFORMAT_INDEX1MSB,
SDL_PIXELFORMAT_INDEX2LSB,
SDL_PIXELFORMAT_INDEX2MSB,
SDL_PIXELFORMAT_INDEX4LSB,
SDL_PIXELFORMAT_INDEX4MSB,
SDL_PIXELFORMAT_INDEX8,
SDL_PIXELFORMAT_RGB332,
SDL_PIXELFORMAT_RGB444,
SDL_PIXELFORMAT_BGR444,
SDL_PIXELFORMAT_RGB555,
SDL_PIXELFORMAT_BGR555,
SDL_PIXELFORMAT_ARGB4444,
SDL_PIXELFORMAT_RGBA4444,
SDL_PIXELFORMAT_ABGR4444,
SDL_PIXELFORMAT_BGRA4444,
SDL_PIXELFORMAT_ARGB1555,
SDL_PIXELFORMAT_RGBA5551,
SDL_PIXELFORMAT_ABGR1555,
SDL_PIXELFORMAT_BGRA5551,
SDL_PIXELFORMAT_RGB565,
SDL_PIXELFORMAT_BGR565,
SDL_PIXELFORMAT_RGB24,
SDL_PIXELFORMAT_BGR24,
SDL_PIXELFORMAT_RGB888,
SDL_PIXELFORMAT_RGBX8888,
SDL_PIXELFORMAT_BGR888,
SDL_PIXELFORMAT_BGRX8888,
SDL_PIXELFORMAT_ARGB8888,
SDL_PIXELFORMAT_RGBA8888,
SDL_PIXELFORMAT_ABGR8888,
SDL_PIXELFORMAT_BGRA8888,
SDL_PIXELFORMAT_ARGB2101010
};
const char *_RGBPixelFormatsVerbose[] = {
"SDL_PIXELFORMAT_INDEX1LSB",
"SDL_PIXELFORMAT_INDEX1MSB",
"SDL_PIXELFORMAT_INDEX2LSB",
"SDL_PIXELFORMAT_INDEX2MSB",
"SDL_PIXELFORMAT_INDEX4LSB",
"SDL_PIXELFORMAT_INDEX4MSB",
"SDL_PIXELFORMAT_INDEX8",
"SDL_PIXELFORMAT_RGB332",
"SDL_PIXELFORMAT_RGB444",
"SDL_PIXELFORMAT_BGR444",
"SDL_PIXELFORMAT_RGB555",
"SDL_PIXELFORMAT_BGR555",
"SDL_PIXELFORMAT_ARGB4444",
"SDL_PIXELFORMAT_RGBA4444",
"SDL_PIXELFORMAT_ABGR4444",
"SDL_PIXELFORMAT_BGRA4444",
"SDL_PIXELFORMAT_ARGB1555",
"SDL_PIXELFORMAT_RGBA5551",
"SDL_PIXELFORMAT_ABGR1555",
"SDL_PIXELFORMAT_BGRA5551",
"SDL_PIXELFORMAT_RGB565",
"SDL_PIXELFORMAT_BGR565",
"SDL_PIXELFORMAT_RGB24",
"SDL_PIXELFORMAT_BGR24",
"SDL_PIXELFORMAT_RGB888",
"SDL_PIXELFORMAT_RGBX8888",
"SDL_PIXELFORMAT_BGR888",
"SDL_PIXELFORMAT_BGRX8888",
"SDL_PIXELFORMAT_ARGB8888",
"SDL_PIXELFORMAT_RGBA8888",
"SDL_PIXELFORMAT_ABGR8888",
"SDL_PIXELFORMAT_BGRA8888",
"SDL_PIXELFORMAT_ARGB2101010"
};
/* Definition of all Non-RGB formats used to test pixel conversions */
const int _numNonRGBPixelFormats = 7;
Uint32 _nonRGBPixelFormats[] = {
SDL_PIXELFORMAT_YV12,
SDL_PIXELFORMAT_IYUV,
SDL_PIXELFORMAT_YUY2,
SDL_PIXELFORMAT_UYVY,
SDL_PIXELFORMAT_YVYU,
SDL_PIXELFORMAT_NV12,
SDL_PIXELFORMAT_NV21
};
const char *_nonRGBPixelFormatsVerbose[] = {
"SDL_PIXELFORMAT_YV12",
"SDL_PIXELFORMAT_IYUV",
"SDL_PIXELFORMAT_YUY2",
"SDL_PIXELFORMAT_UYVY",
"SDL_PIXELFORMAT_YVYU",
"SDL_PIXELFORMAT_NV12",
"SDL_PIXELFORMAT_NV21"
};
/* Definition of some invalid formats for negative tests */
const int _numInvalidPixelFormats = 2;
Uint32 _invalidPixelFormats[] = {
SDL_DEFINE_PIXELFORMAT(SDL_PIXELTYPE_PACKED32, SDL_PACKEDORDER_ABGR, SDL_PACKEDLAYOUT_1010102 + 1, 32, 4),
SDL_DEFINE_PIXELFORMAT(SDL_PIXELTYPE_PACKED32, SDL_PACKEDORDER_ABGR, SDL_PACKEDLAYOUT_1010102 + 2, 32, 4)
};
const char *_invalidPixelFormatsVerbose[] = {
"SDL_PIXELFORMAT_UNKNOWN",
"SDL_PIXELFORMAT_UNKNOWN"
};
/* Test case functions */
/**
* @brief Call to SDL_AllocFormat and SDL_FreeFormat
*
* @sa http://wiki.libsdl.org/SDL_AllocFormat
* @sa http://wiki.libsdl.org/SDL_FreeFormat
*/
int pixels_allocFreeFormat(void *arg)
{
const char *unknownFormat = "SDL_PIXELFORMAT_UNKNOWN";
const char *error;
int i;
Uint32 format;
Uint32 masks;
SDL_PixelFormat *result;
/* Blank/unknown format */
format = 0;
SDLTest_Log("RGB Format: %s (%" SDL_PRIu32 ")", unknownFormat, format);
/* Allocate format */
result = SDL_AllocFormat(format);
SDLTest_AssertPass("Call to SDL_AllocFormat()");
SDLTest_AssertCheck(result != NULL, "Verify result is not NULL");
if (result != NULL) {
SDLTest_AssertCheck(result->format == format, "Verify value of result.format; expected: %" SDL_PRIu32 ", got %" SDL_PRIu32, format, result->format);
SDLTest_AssertCheck(result->BitsPerPixel == 0, "Verify value of result.BitsPerPixel; expected: 0, got %u", result->BitsPerPixel);
SDLTest_AssertCheck(result->BytesPerPixel == 0, "Verify value of result.BytesPerPixel; expected: 0, got %u", result->BytesPerPixel);
masks = result->Rmask | result->Gmask | result->Bmask | result->Amask;
SDLTest_AssertCheck(masks == 0, "Verify value of result.[RGBA]mask combined; expected: 0, got %" SDL_PRIu32, masks);
/* Deallocate again */
SDL_FreeFormat(result);
SDLTest_AssertPass("Call to SDL_FreeFormat()");
}
/* RGB formats */
for (i = 0; i < _numRGBPixelFormats; i++) {
format = _RGBPixelFormats[i];
SDLTest_Log("RGB Format: %s (%" SDL_PRIu32 ")", _RGBPixelFormatsVerbose[i], format);
/* Allocate format */
result = SDL_AllocFormat(format);
SDLTest_AssertPass("Call to SDL_AllocFormat()");
SDLTest_AssertCheck(result != NULL, "Verify result is not NULL");
if (result != NULL) {
SDLTest_AssertCheck(result->format == format, "Verify value of result.format; expected: %" SDL_PRIu32 ", got %" SDL_PRIu32, format, result->format);
SDLTest_AssertCheck(result->BitsPerPixel > 0, "Verify value of result.BitsPerPixel; expected: >0, got %u", result->BitsPerPixel);
SDLTest_AssertCheck(result->BytesPerPixel > 0, "Verify value of result.BytesPerPixel; expected: >0, got %u", result->BytesPerPixel);
if (result->palette != NULL) {
masks = result->Rmask | result->Gmask | result->Bmask | result->Amask;
SDLTest_AssertCheck(masks > 0, "Verify value of result.[RGBA]mask combined; expected: >0, got %" SDL_PRIu32, masks);
}
/* Deallocate again */
SDL_FreeFormat(result);
SDLTest_AssertPass("Call to SDL_FreeFormat()");
}
}
#if 0 /* This succeeds for SDL3, but we don't expect SDL2 applications to call SDL_AllocFormat() for FOURCC formats directly */
/* Non-RGB formats */
for (i = 0; i < _numNonRGBPixelFormats; i++) {
format = _nonRGBPixelFormats[i];
SDLTest_Log("non-RGB Format: %s (%" SDL_PRIu32 ")", _nonRGBPixelFormatsVerbose[i], format);
/* Try to allocate format */
result = SDL_AllocFormat(format);
SDLTest_AssertPass("Call to SDL_AllocFormat()");
SDLTest_AssertCheck(result == NULL, "Verify result is NULL");
}
#endif
/* Negative cases */
/* Invalid Formats */
for (i = 0; i < _numInvalidPixelFormats; i++) {
SDL_ClearError();
SDLTest_AssertPass("Call to SDL_ClearError()");
format = _invalidPixelFormats[i];
result = SDL_AllocFormat(format);
SDLTest_AssertPass("Call to SDL_AllocFormat(%" SDL_PRIu32 ")", format);
SDLTest_AssertCheck(result == NULL, "Verify result is NULL");
error = SDL_GetError();
SDLTest_AssertPass("Call to SDL_GetError()");
SDLTest_AssertCheck(error != NULL, "Validate that error message was not NULL");
}
return TEST_COMPLETED;
}
/**
* @brief Call to SDL_GetPixelFormatName
*
* @sa http://wiki.libsdl.org/SDL_GetPixelFormatName
*/
int pixels_getPixelFormatName(void *arg)
{
const char *unknownFormat = "SDL_PIXELFORMAT_UNKNOWN";
const char *error;
int i;
Uint32 format;
const char *result;
/* Blank/undefined format */
format = 0;
SDLTest_Log("RGB Format: %s (%" SDL_PRIu32 ")", unknownFormat, format);
/* Get name of format */
result = SDL_GetPixelFormatName(format);
SDLTest_AssertPass("Call to SDL_GetPixelFormatName()");
SDLTest_AssertCheck(result != NULL, "Verify result is not NULL");
if (result != NULL) {
SDLTest_AssertCheck(result[0] != '\0', "Verify result is non-empty");
SDLTest_AssertCheck(SDL_strcmp(result, unknownFormat) == 0,
"Verify result text; expected: %s, got %s", unknownFormat, result);
}
/* RGB formats */
for (i = 0; i < _numRGBPixelFormats; i++) {
format = _RGBPixelFormats[i];
SDLTest_Log("RGB Format: %s (%" SDL_PRIu32 ")", _RGBPixelFormatsVerbose[i], format);
/* Get name of format */
result = SDL_GetPixelFormatName(format);
SDLTest_AssertPass("Call to SDL_GetPixelFormatName()");
SDLTest_AssertCheck(result != NULL, "Verify result is not NULL");
if (result != NULL) {
SDLTest_AssertCheck(result[0] != '\0', "Verify result is non-empty");
SDLTest_AssertCheck(SDL_strcmp(result, _RGBPixelFormatsVerbose[i]) == 0,
"Verify result text; expected: %s, got %s", _RGBPixelFormatsVerbose[i], result);
}
}
/* Non-RGB formats */
for (i = 0; i < _numNonRGBPixelFormats; i++) {
format = _nonRGBPixelFormats[i];
SDLTest_Log("non-RGB Format: %s (%" SDL_PRIu32 ")", _nonRGBPixelFormatsVerbose[i], format);
/* Get name of format */
result = SDL_GetPixelFormatName(format);
SDLTest_AssertPass("Call to SDL_GetPixelFormatName()");
SDLTest_AssertCheck(result != NULL, "Verify result is not NULL");
if (result != NULL) {
SDLTest_AssertCheck(result[0] != '\0', "Verify result is non-empty");
SDLTest_AssertCheck(SDL_strcmp(result, _nonRGBPixelFormatsVerbose[i]) == 0,
"Verify result text; expected: %s, got %s", _nonRGBPixelFormatsVerbose[i], result);
}
}
/* Negative cases */
/* Invalid Formats */
SDL_ClearError();
SDLTest_AssertPass("Call to SDL_ClearError()");
for (i = 0; i < _numInvalidPixelFormats; i++) {
format = _invalidPixelFormats[i];
result = SDL_GetPixelFormatName(format);
SDLTest_AssertPass("Call to SDL_GetPixelFormatName(%" SDL_PRIu32 ")", format);
SDLTest_AssertCheck(result != NULL, "Verify result is not NULL");
if (result != NULL) {
SDLTest_AssertCheck(result[0] != '\0',
"Verify result is non-empty; got: %s", result);
SDLTest_AssertCheck(SDL_strcmp(result, _invalidPixelFormatsVerbose[i]) == 0,
"Validate name is UNKNOWN, expected: '%s', got: '%s'", _invalidPixelFormatsVerbose[i], result);
}
error = SDL_GetError();
SDLTest_AssertPass("Call to SDL_GetError()");
SDLTest_AssertCheck(error == NULL || error[0] == '\0', "Validate that error message is empty");
}
return TEST_COMPLETED;
}
/**
* @brief Call to SDL_AllocPalette and SDL_FreePalette
*
* @sa http://wiki.libsdl.org/SDL_AllocPalette
* @sa http://wiki.libsdl.org/SDL_FreePalette
*/
int pixels_allocFreePalette(void *arg)
{
const char *expectedError1 = "Parameter 'ncolors' is invalid";
const char *error;
int variation;
int i;
int ncolors;
SDL_Palette *result;
/* Allocate palette */
for (variation = 1; variation <= 3; variation++) {
switch (variation) {
/* Just one color */
default:
case 1:
ncolors = 1;
break;
/* Two colors */
case 2:
ncolors = 2;
break;
/* More than two colors */
case 3:
ncolors = SDLTest_RandomIntegerInRange(8, 16);
break;
}
result = SDL_AllocPalette(ncolors);
SDLTest_AssertPass("Call to SDL_AllocPalette(%d)", ncolors);
SDLTest_AssertCheck(result != NULL, "Verify result is not NULL");
if (result != NULL) {
SDLTest_AssertCheck(result->ncolors == ncolors, "Verify value of result.ncolors; expected: %u, got %u", ncolors, result->ncolors);
if (result->ncolors > 0) {
SDLTest_AssertCheck(result->colors != NULL, "Verify value of result.colors is not NULL");
if (result->colors != NULL) {
for (i = 0; i < result->ncolors; i++) {
SDLTest_AssertCheck(result->colors[i].r == 255, "Verify value of result.colors[%d].r; expected: 255, got %u", i, result->colors[i].r);
SDLTest_AssertCheck(result->colors[i].g == 255, "Verify value of result.colors[%d].g; expected: 255, got %u", i, result->colors[i].g);
SDLTest_AssertCheck(result->colors[i].b == 255, "Verify value of result.colors[%d].b; expected: 255, got %u", i, result->colors[i].b);
}
}
}
/* Deallocate again */
SDL_FreePalette(result);
SDLTest_AssertPass("Call to SDL_FreePalette()");
}
}
/* Negative cases */
/* Invalid number of colors */
for (ncolors = 0; ncolors > -3; ncolors--) {
SDL_ClearError();
SDLTest_AssertPass("Call to SDL_ClearError()");
result = SDL_AllocPalette(ncolors);
SDLTest_AssertPass("Call to SDL_AllocPalette(%d)", ncolors);
SDLTest_AssertCheck(result == NULL, "Verify result is NULL");
error = SDL_GetError();
SDLTest_AssertPass("Call to SDL_GetError()");
SDLTest_AssertCheck(error != NULL, "Validate that error message was not NULL");
if (error != NULL) {
SDLTest_AssertCheck(SDL_strcmp(error, expectedError1) == 0,
"Validate error message, expected: '%s', got: '%s'", expectedError1, error);
}
}
return TEST_COMPLETED;
}
/**
* @brief Call to SDL_CalculateGammaRamp
*
* @sa http://wiki.libsdl.org/SDL_CalculateGammaRamp
*/
int
pixels_calcGammaRamp(void *arg)
{
const char *expectedError1 = "Parameter 'gamma' is invalid";
const char *expectedError2 = "Parameter 'ramp' is invalid";
const char *error;
float gamma;
Uint16 *ramp;
int variation;
int i;
int changed;
Uint16 magic = 0xbeef;
/* Allocate temp ramp array and fill with some value */
ramp = (Uint16 *)SDL_malloc(256 * sizeof(Uint16));
SDLTest_AssertCheck(ramp != NULL, "Validate temp ramp array could be allocated");
if (ramp == NULL) return TEST_ABORTED;
/* Make call with different gamma values */
for (variation = 0; variation < 4; variation++) {
switch (variation) {
/* gamma = 0 all black */
default:
case 0:
gamma = 0.0f;
break;
/* gamma = 1 identity */
case 1:
gamma = 1.0f;
break;
/* gamma = [0.2,0.8] normal range */
case 2:
gamma = 0.2f + 0.8f * SDLTest_RandomUnitFloat();
break;
/* gamma = >1.1 non-standard range */
case 3:
gamma = 1.1f + SDLTest_RandomUnitFloat();
break;
}
/* Make call and check that values were updated */
for (i = 0; i < 256; i++) ramp[i] = magic;
SDL_CalculateGammaRamp(gamma, ramp);
SDLTest_AssertPass("Call to SDL_CalculateGammaRamp(%f)", gamma);
changed = 0;
for (i = 0; i < 256; i++) if (ramp[i] != magic) changed++;
SDLTest_AssertCheck(changed > 250, "Validate that ramp was calculated; expected: >250 values changed, got: %d values changed", changed);
/* Additional value checks for some cases */
i = SDLTest_RandomIntegerInRange(64,192);
switch (variation) {
case 0:
SDLTest_AssertCheck(ramp[i] == 0, "Validate value at position %d; expected: 0, got: %d", i, ramp[i]);
break;
case 1:
SDLTest_AssertCheck(ramp[i] == ((i << 8) | i), "Validate value at position %d; expected: %d, got: %d", i, (i << 8) | i, ramp[i]);
break;
case 2:
case 3:
SDLTest_AssertCheck(ramp[i] > 0, "Validate value at position %d; expected: >0, got: %d", i, ramp[i]);
break;
}
}
/* Negative cases */
SDL_ClearError();
SDLTest_AssertPass("Call to SDL_ClearError()");
gamma = -1;
for (i=0; i<256; i++) ramp[i] = magic;
SDL_CalculateGammaRamp(gamma, ramp);
SDLTest_AssertPass("Call to SDL_CalculateGammaRamp(%f)", gamma);
error = SDL_GetError();
SDLTest_AssertPass("Call to SDL_GetError()");
SDLTest_AssertCheck(error != NULL, "Validate that error message was not NULL");
if (error != NULL) {
SDLTest_AssertCheck(SDL_strcmp(error, expectedError1) == 0,
"Validate error message, expected: '%s', got: '%s'", expectedError1, error);
}
changed = 0;
for (i = 0; i < 256; i++) if (ramp[i] != magic) changed++;
SDLTest_AssertCheck(changed ==0, "Validate that ramp unchanged; expected: 0 values changed got: %d values changed", changed);
SDL_CalculateGammaRamp(0.5f, NULL);
SDLTest_AssertPass("Call to SDL_CalculateGammaRamp(0.5,NULL)");
error = SDL_GetError();
SDLTest_AssertPass("Call to SDL_GetError()");
SDLTest_AssertCheck(error != NULL, "Validate that error message was not NULL");
if (error != NULL) {
SDLTest_AssertCheck(SDL_strcmp(error, expectedError2) == 0,
"Validate error message, expected: '%s', got: '%s'", expectedError2, error);
}
/* Cleanup */
SDL_free(ramp);
return TEST_COMPLETED;
}
/* ================= Test References ================== */
/* Pixels test cases */
static const SDLTest_TestCaseReference pixelsTest1 = {
(SDLTest_TestCaseFp)pixels_allocFreeFormat, "pixels_allocFreeFormat", "Call to SDL_AllocFormat and SDL_FreeFormat", TEST_ENABLED
};
static const SDLTest_TestCaseReference pixelsTest2 = {
(SDLTest_TestCaseFp)pixels_allocFreePalette, "pixels_allocFreePalette", "Call to SDL_AllocPalette and SDL_FreePalette", TEST_ENABLED
};
static const SDLTest_TestCaseReference pixelsTest3 =
{ (SDLTest_TestCaseFp)pixels_calcGammaRamp, "pixels_calcGammaRamp", "Call to SDL_CalculateGammaRamp", TEST_ENABLED };
static const SDLTest_TestCaseReference pixelsTest4 =
{ (SDLTest_TestCaseFp)pixels_getPixelFormatName, "pixels_getPixelFormatName", "Call to SDL_GetPixelFormatName", TEST_ENABLED };
/* Sequence of Pixels test cases */
static const SDLTest_TestCaseReference *pixelsTests[] = {
&pixelsTest1, &pixelsTest2, &pixelsTest3, &pixelsTest4, NULL
};
/* Pixels test suite (global) */
SDLTest_TestSuiteReference pixelsTestSuite = {
"Pixels",
NULL,
pixelsTests,
NULL
};

View File

@ -0,0 +1,610 @@
/**
* Original code: automated SDL platform test written by Edgar Simo "bobbens"
* Extended and updated by aschiffler at ferzkopp dot net
*/
#include <stdio.h>
#include "SDL.h"
#include "SDL_test.h"
/* ================= Test Case Implementation ================== */
/* Helper functions */
/**
* @brief Compare sizes of types.
*
* @note Watcom C flags these as Warning 201: "Unreachable code" if you just
* compare them directly, so we push it through a function to keep the
* compiler quiet. --ryan.
*/
static int _compareSizeOfType(size_t sizeoftype, size_t hardcodetype)
{
return sizeoftype != hardcodetype;
}
/* Test case functions */
/**
* @brief Tests type sizes.
*/
int platform_testTypes(void *arg)
{
int ret;
ret = _compareSizeOfType(sizeof(Uint8), 1);
SDLTest_AssertCheck(ret == 0, "sizeof(Uint8) = %u, expected 1", (unsigned int)sizeof(Uint8));
ret = _compareSizeOfType(sizeof(Uint16), 2);
SDLTest_AssertCheck(ret == 0, "sizeof(Uint16) = %u, expected 2", (unsigned int)sizeof(Uint16));
ret = _compareSizeOfType(sizeof(Uint32), 4);
SDLTest_AssertCheck(ret == 0, "sizeof(Uint32) = %u, expected 4", (unsigned int)sizeof(Uint32));
ret = _compareSizeOfType(sizeof(Uint64), 8);
SDLTest_AssertCheck(ret == 0, "sizeof(Uint64) = %u, expected 8", (unsigned int)sizeof(Uint64));
return TEST_COMPLETED;
}
/**
* @brief Tests platform endianness and SDL_SwapXY functions.
*/
int platform_testEndianessAndSwap(void *arg)
{
int real_byteorder;
int real_floatwordorder = 0;
Uint16 value = 0x1234;
Uint16 value16 = 0xCDAB;
Uint16 swapped16 = 0xABCD;
Uint32 value32 = 0xEFBEADDE;
Uint32 swapped32 = 0xDEADBEEF;
union
{
double d;
Uint32 ui32[2];
} value_double;
Uint64 value64, swapped64;
value64 = 0xEFBEADDE;
value64 <<= 32;
value64 |= 0xCDAB3412;
swapped64 = 0x1234ABCD;
swapped64 <<= 32;
swapped64 |= 0xDEADBEEF;
value_double.d = 3.141593;
if ((*((char *)&value) >> 4) == 0x1) {
real_byteorder = SDL_BIG_ENDIAN;
} else {
real_byteorder = SDL_LIL_ENDIAN;
}
/* Test endianness. */
SDLTest_AssertCheck(real_byteorder == SDL_BYTEORDER,
"Machine detected as %s endian, appears to be %s endian.",
(SDL_BYTEORDER == SDL_LIL_ENDIAN) ? "little" : "big",
(real_byteorder == SDL_LIL_ENDIAN) ? "little" : "big");
if (value_double.ui32[0] == 0x82c2bd7f && value_double.ui32[1] == 0x400921fb) {
real_floatwordorder = SDL_LIL_ENDIAN;
} else if (value_double.ui32[0] == 0x400921fb && value_double.ui32[1] == 0x82c2bd7f) {
real_floatwordorder = SDL_BIG_ENDIAN;
}
/* Test endianness. */
SDLTest_AssertCheck(real_floatwordorder == SDL_FLOATWORDORDER,
"Machine detected as having %s endian float word order, appears to be %s endian.",
(SDL_FLOATWORDORDER == SDL_LIL_ENDIAN) ? "little" : "big",
(real_floatwordorder == SDL_LIL_ENDIAN) ? "little" : (real_floatwordorder == SDL_BIG_ENDIAN) ? "big"
: "unknown");
/* Test 16 swap. */
SDLTest_AssertCheck(SDL_Swap16(value16) == swapped16,
"SDL_Swap16(): 16 bit swapped: 0x%X => 0x%X",
value16, SDL_Swap16(value16));
/* Test 32 swap. */
SDLTest_AssertCheck(SDL_Swap32(value32) == swapped32,
"SDL_Swap32(): 32 bit swapped: 0x%" SDL_PRIX32 " => 0x%" SDL_PRIX32,
value32, SDL_Swap32(value32));
/* Test 64 swap. */
SDLTest_AssertCheck(SDL_Swap64(value64) == swapped64,
"SDL_Swap64(): 64 bit swapped: 0x%" SDL_PRIX64 " => 0x%" SDL_PRIX64,
value64, SDL_Swap64(value64));
return TEST_COMPLETED;
}
/* !
* \brief Tests SDL_GetXYZ() functions
* \sa
* http://wiki.libsdl.org/SDL_GetPlatform
* http://wiki.libsdl.org/SDL_GetCPUCount
* http://wiki.libsdl.org/SDL_GetCPUCacheLineSize
* http://wiki.libsdl.org/SDL_GetRevision
* http://wiki.libsdl.org/SDL_GetRevisionNumber
*/
int platform_testGetFunctions(void *arg)
{
char *platform;
char *revision;
int ret;
size_t len;
platform = (char *)SDL_GetPlatform();
SDLTest_AssertPass("SDL_GetPlatform()");
SDLTest_AssertCheck(platform != NULL, "SDL_GetPlatform() != NULL");
if (platform != NULL) {
len = SDL_strlen(platform);
SDLTest_AssertCheck(len > 0,
"SDL_GetPlatform(): expected non-empty platform, was platform: '%s', len: %i",
platform,
(int)len);
}
ret = SDL_GetCPUCount();
SDLTest_AssertPass("SDL_GetCPUCount()");
SDLTest_AssertCheck(ret > 0,
"SDL_GetCPUCount(): expected count > 0, was: %i",
ret);
ret = SDL_GetCPUCacheLineSize();
SDLTest_AssertPass("SDL_GetCPUCacheLineSize()");
SDLTest_AssertCheck(ret >= 0,
"SDL_GetCPUCacheLineSize(): expected size >= 0, was: %i",
ret);
revision = (char *)SDL_GetRevision();
SDLTest_AssertPass("SDL_GetRevision()");
SDLTest_AssertCheck(revision != NULL, "SDL_GetRevision() != NULL");
return TEST_COMPLETED;
}
/* !
* \brief Tests SDL_HasXYZ() functions
* \sa
* http://wiki.libsdl.org/SDL_Has3DNow
* http://wiki.libsdl.org/SDL_HasAltiVec
* http://wiki.libsdl.org/SDL_HasMMX
* http://wiki.libsdl.org/SDL_HasRDTSC
* http://wiki.libsdl.org/SDL_HasSSE
* http://wiki.libsdl.org/SDL_HasSSE2
* http://wiki.libsdl.org/SDL_HasSSE3
* http://wiki.libsdl.org/SDL_HasSSE41
* http://wiki.libsdl.org/SDL_HasSSE42
* http://wiki.libsdl.org/SDL_HasAVX
*/
int platform_testHasFunctions(void *arg)
{
/* TODO: independently determine and compare values as well */
SDL_HasRDTSC();
SDLTest_AssertPass("SDL_HasRDTSC()");
SDL_HasAltiVec();
SDLTest_AssertPass("SDL_HasAltiVec()");
SDL_HasMMX();
SDLTest_AssertPass("SDL_HasMMX()");
SDL_Has3DNow();
SDLTest_AssertPass("SDL_Has3DNow()");
SDL_HasSSE();
SDLTest_AssertPass("SDL_HasSSE()");
SDL_HasSSE2();
SDLTest_AssertPass("SDL_HasSSE2()");
SDL_HasSSE3();
SDLTest_AssertPass("SDL_HasSSE3()");
SDL_HasSSE41();
SDLTest_AssertPass("SDL_HasSSE41()");
SDL_HasSSE42();
SDLTest_AssertPass("SDL_HasSSE42()");
SDL_HasAVX();
SDLTest_AssertPass("SDL_HasAVX()");
return TEST_COMPLETED;
}
/* !
* \brief Tests SDL_GetVersion
* \sa
* http://wiki.libsdl.org/SDL_GetVersion
*/
int platform_testGetVersion(void *arg)
{
SDL_version linked;
int major = SDL_MAJOR_VERSION;
int minor = SDL_MINOR_VERSION;
SDL_GetVersion(&linked);
SDLTest_AssertCheck(linked.major >= major,
"SDL_GetVersion(): returned major %i (>= %i)",
linked.major,
major);
SDLTest_AssertCheck(linked.minor >= minor,
"SDL_GetVersion(): returned minor %i (>= %i)",
linked.minor,
minor);
return TEST_COMPLETED;
}
/* !
* \brief Tests SDL_VERSION macro
*/
int platform_testSDLVersion(void *arg)
{
SDL_version compiled;
int major = SDL_MAJOR_VERSION;
int minor = SDL_MINOR_VERSION;
SDL_VERSION(&compiled);
SDLTest_AssertCheck(compiled.major >= major,
"SDL_VERSION() returned major %i (>= %i)",
compiled.major,
major);
SDLTest_AssertCheck(compiled.minor >= minor,
"SDL_VERSION() returned minor %i (>= %i)",
compiled.minor,
minor);
return TEST_COMPLETED;
}
/* !
* \brief Tests default SDL_Init
*/
int platform_testDefaultInit(void *arg)
{
int ret;
int subsystem;
subsystem = SDL_WasInit(SDL_INIT_EVERYTHING);
SDLTest_AssertCheck(subsystem != 0,
"SDL_WasInit(0): returned %i, expected != 0",
subsystem);
ret = SDL_Init(SDL_WasInit(SDL_INIT_EVERYTHING));
SDLTest_AssertCheck(ret == 0,
"SDL_Init(0): returned %i, expected 0, error: %s",
ret,
SDL_GetError());
return TEST_COMPLETED;
}
/* !
* \brief Tests SDL_Get/Set/ClearError
* \sa
* http://wiki.libsdl.org/SDL_GetError
* http://wiki.libsdl.org/SDL_SetError
* http://wiki.libsdl.org/SDL_ClearError
*/
int platform_testGetSetClearError(void *arg)
{
int result;
const char *testError = "Testing";
char *lastError;
size_t len;
SDL_ClearError();
SDLTest_AssertPass("SDL_ClearError()");
lastError = (char *)SDL_GetError();
SDLTest_AssertPass("SDL_GetError()");
SDLTest_AssertCheck(lastError != NULL,
"SDL_GetError() != NULL");
if (lastError != NULL) {
len = SDL_strlen(lastError);
SDLTest_AssertCheck(len == 0,
"SDL_GetError(): no message expected, len: %i", (int)len);
}
result = SDL_SetError("%s", testError);
SDLTest_AssertPass("SDL_SetError()");
SDLTest_AssertCheck(result == -1, "SDL_SetError: expected -1, got: %i", result);
lastError = (char *)SDL_GetError();
SDLTest_AssertCheck(lastError != NULL,
"SDL_GetError() != NULL");
if (lastError != NULL) {
len = SDL_strlen(lastError);
SDLTest_AssertCheck(len == SDL_strlen(testError),
"SDL_GetError(): expected message len %i, was len: %i",
(int)SDL_strlen(testError),
(int)len);
SDLTest_AssertCheck(SDL_strcmp(lastError, testError) == 0,
"SDL_GetError(): expected message %s, was message: %s",
testError,
lastError);
}
/* Clean up */
SDL_ClearError();
SDLTest_AssertPass("SDL_ClearError()");
return TEST_COMPLETED;
}
/* !
* \brief Tests SDL_SetError with empty input
* \sa
* http://wiki.libsdl.org/SDL_SetError
*/
int platform_testSetErrorEmptyInput(void *arg)
{
int result;
const char *testError = "";
char *lastError;
size_t len;
result = SDL_SetError("%s", testError);
SDLTest_AssertPass("SDL_SetError()");
SDLTest_AssertCheck(result == -1, "SDL_SetError: expected -1, got: %i", result);
lastError = (char *)SDL_GetError();
SDLTest_AssertCheck(lastError != NULL,
"SDL_GetError() != NULL");
if (lastError != NULL) {
len = SDL_strlen(lastError);
SDLTest_AssertCheck(len == SDL_strlen(testError),
"SDL_GetError(): expected message len %i, was len: %i",
(int)SDL_strlen(testError),
(int)len);
SDLTest_AssertCheck(SDL_strcmp(lastError, testError) == 0,
"SDL_GetError(): expected message '%s', was message: '%s'",
testError,
lastError);
}
/* Clean up */
SDL_ClearError();
SDLTest_AssertPass("SDL_ClearError()");
return TEST_COMPLETED;
}
#if defined(HAVE_WFORMAT_OVERFLOW)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wformat-overflow"
#endif
/* !
* \brief Tests SDL_SetError with invalid input
* \sa
* http://wiki.libsdl.org/SDL_SetError
*/
int platform_testSetErrorInvalidInput(void *arg)
{
int result;
const char *invalidError = "";
const char *probeError = "Testing";
char *lastError;
size_t len;
/* Reset */
SDL_ClearError();
SDLTest_AssertPass("SDL_ClearError()");
/* Check for no-op */
result = SDL_SetError("%s", invalidError);
SDLTest_AssertPass("SDL_SetError()");
SDLTest_AssertCheck(result == -1, "SDL_SetError: expected -1, got: %i", result);
lastError = (char *)SDL_GetError();
SDLTest_AssertCheck(lastError != NULL,
"SDL_GetError() != NULL");
if (lastError != NULL) {
len = SDL_strlen(lastError);
SDLTest_AssertCheck(len == 0 || SDL_strcmp(lastError, "(null)") == 0,
"SDL_GetError(): expected message len 0, was len: %i",
(int)len);
}
/* Set */
result = SDL_SetError("%s", probeError);
SDLTest_AssertPass("SDL_SetError('%s')", probeError);
SDLTest_AssertCheck(result == -1, "SDL_SetError: expected -1, got: %i", result);
/* Check for no-op */
result = SDL_SetError("%s", invalidError);
SDLTest_AssertPass("SDL_SetError(NULL)");
SDLTest_AssertCheck(result == -1, "SDL_SetError: expected -1, got: %i", result);
lastError = (char *)SDL_GetError();
SDLTest_AssertCheck(lastError != NULL,
"SDL_GetError() != NULL");
if (lastError != NULL) {
len = SDL_strlen(lastError);
SDLTest_AssertCheck(len == 0 || SDL_strcmp(lastError, "(null)") == 0,
"SDL_GetError(): expected message len 0, was len: %i",
(int)len);
}
/* Reset */
SDL_ClearError();
SDLTest_AssertPass("SDL_ClearError()");
/* Set and check */
result = SDL_SetError("%s", probeError);
SDLTest_AssertPass("SDL_SetError()");
SDLTest_AssertCheck(result == -1, "SDL_SetError: expected -1, got: %i", result);
lastError = (char *)SDL_GetError();
SDLTest_AssertCheck(lastError != NULL,
"SDL_GetError() != NULL");
if (lastError != NULL) {
len = SDL_strlen(lastError);
SDLTest_AssertCheck(len == SDL_strlen(probeError),
"SDL_GetError(): expected message len %i, was len: %i",
(int)SDL_strlen(probeError),
(int)len);
SDLTest_AssertCheck(SDL_strcmp(lastError, probeError) == 0,
"SDL_GetError(): expected message '%s', was message: '%s'",
probeError,
lastError);
}
/* Clean up */
SDL_ClearError();
SDLTest_AssertPass("SDL_ClearError()");
return TEST_COMPLETED;
}
#if defined(HAVE_WFORMAT_OVERFLOW)
#pragma GCC diagnostic pop
#endif
/* !
* \brief Tests SDL_GetPowerInfo
* \sa
* http://wiki.libsdl.org/SDL_GetPowerInfo
*/
int platform_testGetPowerInfo(void *arg)
{
SDL_PowerState state;
SDL_PowerState stateAgain;
int secs;
int secsAgain;
int pct;
int pctAgain;
state = SDL_GetPowerInfo(&secs, &pct);
SDLTest_AssertPass("SDL_GetPowerInfo()");
SDLTest_AssertCheck(
state == SDL_POWERSTATE_UNKNOWN ||
state == SDL_POWERSTATE_ON_BATTERY ||
state == SDL_POWERSTATE_NO_BATTERY ||
state == SDL_POWERSTATE_CHARGING ||
state == SDL_POWERSTATE_CHARGED,
"SDL_GetPowerInfo(): state %i is one of the expected values",
(int)state);
if (state == SDL_POWERSTATE_ON_BATTERY) {
SDLTest_AssertCheck(
secs >= 0,
"SDL_GetPowerInfo(): on battery, secs >= 0, was: %i",
secs);
SDLTest_AssertCheck(
(pct >= 0) && (pct <= 100),
"SDL_GetPowerInfo(): on battery, pct=[0,100], was: %i",
pct);
}
if (state == SDL_POWERSTATE_UNKNOWN ||
state == SDL_POWERSTATE_NO_BATTERY) {
SDLTest_AssertCheck(
secs == -1,
"SDL_GetPowerInfo(): no battery, secs == -1, was: %i",
secs);
SDLTest_AssertCheck(
pct == -1,
"SDL_GetPowerInfo(): no battery, pct == -1, was: %i",
pct);
}
/* Partial return value variations */
stateAgain = SDL_GetPowerInfo(&secsAgain, NULL);
SDLTest_AssertCheck(
state == stateAgain,
"State %i returned when only 'secs' requested",
stateAgain);
SDLTest_AssertCheck(
secs == secsAgain,
"Value %i matches when only 'secs' requested",
secsAgain);
stateAgain = SDL_GetPowerInfo(NULL, &pctAgain);
SDLTest_AssertCheck(
state == stateAgain,
"State %i returned when only 'pct' requested",
stateAgain);
SDLTest_AssertCheck(
pct == pctAgain,
"Value %i matches when only 'pct' requested",
pctAgain);
stateAgain = SDL_GetPowerInfo(NULL, NULL);
SDLTest_AssertCheck(
state == stateAgain,
"State %i returned when no value requested",
stateAgain);
return TEST_COMPLETED;
}
/* ================= Test References ================== */
/* Platform test cases */
static const SDLTest_TestCaseReference platformTest1 = {
(SDLTest_TestCaseFp)platform_testTypes, "platform_testTypes", "Tests predefined types", TEST_ENABLED
};
static const SDLTest_TestCaseReference platformTest2 = {
(SDLTest_TestCaseFp)platform_testEndianessAndSwap, "platform_testEndianessAndSwap", "Tests endianness and swap functions", TEST_ENABLED
};
static const SDLTest_TestCaseReference platformTest3 = {
(SDLTest_TestCaseFp)platform_testGetFunctions, "platform_testGetFunctions", "Tests various SDL_GetXYZ functions", TEST_ENABLED
};
static const SDLTest_TestCaseReference platformTest4 = {
(SDLTest_TestCaseFp)platform_testHasFunctions, "platform_testHasFunctions", "Tests various SDL_HasXYZ functions", TEST_ENABLED
};
static const SDLTest_TestCaseReference platformTest5 = {
(SDLTest_TestCaseFp)platform_testGetVersion, "platform_testGetVersion", "Tests SDL_GetVersion function", TEST_ENABLED
};
static const SDLTest_TestCaseReference platformTest6 = {
(SDLTest_TestCaseFp)platform_testSDLVersion, "platform_testSDLVersion", "Tests SDL_VERSION macro", TEST_ENABLED
};
static const SDLTest_TestCaseReference platformTest7 = {
(SDLTest_TestCaseFp)platform_testDefaultInit, "platform_testDefaultInit", "Tests default SDL_Init", TEST_ENABLED
};
static const SDLTest_TestCaseReference platformTest8 = {
(SDLTest_TestCaseFp)platform_testGetSetClearError, "platform_testGetSetClearError", "Tests SDL_Get/Set/ClearError", TEST_ENABLED
};
static const SDLTest_TestCaseReference platformTest9 = {
(SDLTest_TestCaseFp)platform_testSetErrorEmptyInput, "platform_testSetErrorEmptyInput", "Tests SDL_SetError with empty input", TEST_ENABLED
};
static const SDLTest_TestCaseReference platformTest10 = {
(SDLTest_TestCaseFp)platform_testSetErrorInvalidInput, "platform_testSetErrorInvalidInput", "Tests SDL_SetError with invalid input", TEST_ENABLED
};
static const SDLTest_TestCaseReference platformTest11 = {
(SDLTest_TestCaseFp)platform_testGetPowerInfo, "platform_testGetPowerInfo", "Tests SDL_GetPowerInfo function", TEST_ENABLED
};
/* Sequence of Platform test cases */
static const SDLTest_TestCaseReference *platformTests[] = {
&platformTest1,
&platformTest2,
&platformTest3,
&platformTest4,
&platformTest5,
&platformTest6,
&platformTest7,
&platformTest8,
&platformTest9,
&platformTest10,
&platformTest11,
NULL
};
/* Platform test suite (global) */
SDLTest_TestSuiteReference platformTestSuite = {
"Platform",
NULL,
platformTests,
NULL
};

File diff suppressed because it is too large Load Diff

Some files were not shown because too many files have changed in this diff Show More