Browse Source

Updated SDL2 to the latest code from Mercurial.

Alex Szpakowski 10 years ago
parent
commit
8d85741390
51 changed files with 820 additions and 286 deletions
  1. 1 1
      CMakeLists.txt
  2. 2 2
      libs/SDL2/.hg_archival.txt
  3. 74 29
      libs/SDL2/Android.mk
  4. 2 2
      libs/SDL2/Makefile.wiz
  5. 23 0
      libs/SDL2/VisualC-WinRT/SDL2-WinRT.nuspec
  6. 39 0
      libs/SDL2/VisualC-WinRT/SDL2-WinRT.targets
  7. 22 0
      libs/SDL2/VisualC-WinRT/SDL2main-WinRT-NonXAML.nuspec
  8. 10 0
      libs/SDL2/VisualC-WinRT/SDL2main-WinRT-NonXAML.targets
  9. 70 16
      libs/SDL2/VisualC/clean.sh
  10. 15 0
      libs/SDL2/configure
  11. 15 0
      libs/SDL2/configure.in
  12. 5 0
      libs/SDL2/debian/rules
  13. 0 1
      libs/SDL2/include/SDL_config_wiz.h
  14. 1 1
      libs/SDL2/premake/Cygwin/build-scripts/clean_premake.bat
  15. 4 7
      libs/SDL2/src/audio/sdlgenaudiocvt.pl
  16. 36 4
      libs/SDL2/src/core/winrt/SDL_winrtapp_direct3d.cpp
  17. 3 1
      libs/SDL2/src/core/winrt/SDL_winrtapp_direct3d.h
  18. 1 1
      libs/SDL2/src/cpuinfo/SDL_cpuinfo.c
  19. 13 0
      libs/SDL2/src/dynapi/gendynapi.pl
  20. 3 0
      libs/SDL2/src/events/SDL_keyboard_c.h
  21. 2 0
      libs/SDL2/src/events/SDL_windowevents.c
  22. 105 63
      libs/SDL2/src/joystick/SDL_gamecontroller.c
  23. 0 2
      libs/SDL2/src/joystick/SDL_gamecontrollerdb.h
  24. 46 2
      libs/SDL2/src/joystick/bsd/SDL_sysjoystick.c
  25. 2 0
      libs/SDL2/src/joystick/darwin/SDL_sysjoystick.c
  26. 78 43
      libs/SDL2/src/joystick/iphoneos/SDL_sysjoystick.m
  27. 2 1
      libs/SDL2/src/joystick/sort_controllers.py
  28. 2 2
      libs/SDL2/src/render/opengl/SDL_render_gl.c
  29. 2 2
      libs/SDL2/src/render/opengles/SDL_render_gles.c
  30. 2 2
      libs/SDL2/src/render/opengles2/SDL_render_gles2.c
  31. 4 0
      libs/SDL2/src/thread/pthread/SDL_systhread.c
  32. 11 10
      libs/SDL2/src/video/SDL_video.c
  33. 49 25
      libs/SDL2/src/video/cocoa/SDL_cocoakeyboard.m
  34. 15 1
      libs/SDL2/src/video/cocoa/SDL_cocoawindow.m
  35. 7 0
      libs/SDL2/src/video/sdlgenblit.pl
  36. 3 0
      libs/SDL2/src/video/windows/SDL_windowsframebuffer.c
  37. 4 0
      libs/SDL2/src/video/windows/SDL_windowskeyboard.c
  38. 20 20
      libs/SDL2/src/video/windows/SDL_windowsopengl.c
  39. 18 0
      libs/SDL2/src/video/windows/SDL_windowswindow.c
  40. 2 0
      libs/SDL2/src/video/windows/SDL_windowswindow.h
  41. 93 14
      libs/SDL2/src/video/winrt/SDL_winrtvideo.cpp
  42. 3 20
      libs/SDL2/src/video/x11/SDL_x11events.c
  43. 4 5
      libs/SDL2/src/video/x11/SDL_x11modes.c
  44. 1 3
      libs/SDL2/test/README
  45. 1 1
      libs/SDL2/test/autogen.sh
  46. 1 1
      libs/SDL2/test/gcc-fat.sh
  47. 1 1
      libs/SDL2/test/testfilesystem.c
  48. 1 1
      libs/SDL2/test/testgl2.c
  49. 1 1
      libs/SDL2/test/testgles2.c
  50. 1 1
      libs/SDL2/test/testspriteminimal.c
  51. 0 0
      libs/SDL2/visualtest/COPYING.txt

+ 1 - 1
CMakeLists.txt

@@ -137,7 +137,7 @@ set(MEGA_LIBVORBIS_VER "1.3.5")
 set(MEGA_LIBTHEORA_VER "1.1")
 set(MEGA_MPG123_VER "1.15.3")
 set(MEGA_FREETYPE_VER "2.6.2")
-set(MEGA_SDL2_VER "2.0.3-6ccf11a01cb5")
+set(MEGA_SDL2_VER "2.0.3-e05d46c27ce3")
 set(MEGA_OPENAL_VER "1.17.0")
 set(MEGA_MODPLUG_VER "0.8.8.4")
 

+ 2 - 2
libs/SDL2/.hg_archival.txt

@@ -1,5 +1,5 @@
 repo: 74212992fb0868a6929180cd74dd67e38507340a
-node: 6ccf11a01cb585eacf1a039a477a18ec82188f81
+node: e05d46c27ce3d91d427f74ae0ca8d900d83cbcad
 branch: default
 latesttag: release-2.0.3
-latesttagdistance: 1181
+latesttagdistance: 1235

+ 74 - 29
libs/SDL2/Android.mk

@@ -296,8 +296,8 @@ set_option(VIDEO_VIVANTE       "Use Vivante EGL video driver" ${UNIX_SYS})
 
 # TODO: We should (should we?) respect cmake's ${BUILD_SHARED_LIBS} flag here
 # The options below are for compatibility to configure's default behaviour.
-set(SDL_SHARED ON CACHE BOOL "Build a shared version of the library")
-set(SDL_STATIC OFF CACHE BOOL "Build a static version of the library")
+set(SDL_SHARED ${SDL_SHARED_ENABLED_BY_DEFAULT} CACHE BOOL "Build a shared version of the library")
+set(SDL_STATIC ON CACHE BOOL "Build a static version of the library")
 
 # General source files
 file(GLOB SOURCE_FILES
@@ -389,7 +389,7 @@ if(USE_GCC OR USE_CLANG)
 
   set(CMAKE_REQUIRED_FLAGS "-Wl,--no-undefined")
   check_c_compiler_flag("" HAVE_NO_UNDEFINED)
-  set(CMAKE_REQUIRED_FLAGS)
+  set(CMAKE_REQUIRED_FLAGS ${ORIG_CMAKE_REQUIRED_FLAGS})
   if(HAVE_NO_UNDEFINED)
     list(APPEND EXTRA_LDFLAGS "-Wl,--no-undefined")
   endif()
@@ -695,6 +695,52 @@ if(SDL_VIDEO)
   endif()
 endif()
 
+if(ANDROID)
+  file(GLOB ANDROID_CORE_SOURCES ${SDL2_SOURCE_DIR}/src/core/android/*.c)
+  set(SOURCE_FILES ${SOURCE_FILES} ${ANDROID_CORE_SOURCES})
+  file(GLOB ANDROID_MAIN_SOURCES ${SDL2_SOURCE_DIR}/src/main/android/*.c)
+  set(SOURCE_FILES ${SOURCE_FILES} ${ANDROID_MAIN_SOURCES})
+  if(SDL_AUDIO)
+    set(SDL_AUDIO_DRIVER_ANDROID 1)
+    file(GLOB ANDROID_AUDIO_SOURCES ${SDL2_SOURCE_DIR}/src/audio/android/*.c)
+    set(SOURCE_FILES ${SOURCE_FILES} ${ANDROID_AUDIO_SOURCES})
+    set(HAVE_SDL_AUDIO TRUE)
+  endif()
+  if(SDL_FILESYSTEM)
+    set(SDL_FILESYSTEM_ANDROID 1)
+    file(GLOB ANDROID_FILESYSTEM_SOURCES ${SDL2_SOURCE_DIR}/src/filesystem/android/*.c)
+    set(SOURCE_FILES ${SOURCE_FILES} ${ANDROID_FILESYSTEM_SOURCES})
+    set(HAVE_SDL_FILESYSTEM TRUE)
+  endif()
+  if(SDL_JOYSTICK)
+    set(SDL_JOYSTICK_ANDROID 1)
+    file(GLOB ANDROID_JOYSTICK_SOURCES ${SDL2_SOURCE_DIR}/src/joystick/android/*.c)
+    set(SOURCE_FILES ${SOURCE_FILES} ${ANDROID_JOYSTICK_SOURCES})
+    set(HAVE_SDL_JOYSTICK TRUE)
+  endif()
+  if(SDL_POWER)
+    set(SDL_POWER_ANDROID 1)
+    file(GLOB ANDROID_POWER_SOURCES ${SDL2_SOURCE_DIR}/src/power/android/*.c)
+    set(SOURCE_FILES ${SOURCE_FILES} ${ANDROID_POWER_SOURCES})
+    set(HAVE_SDL_POWER TRUE)
+  endif()
+  if(SDL_VIDEO)
+    set(SDL_VIDEO_DRIVER_ANDROID 1)
+    file(GLOB ANDROID_VIDEO_SOURCES ${SDL2_SOURCE_DIR}/src/video/android/*.c)
+    set(SOURCE_FILES ${SOURCE_FILES} ${ANDROID_VIDEO_SOURCES})
+    set(HAVE_SDL_VIDEO TRUE)
+
+    #enable gles
+    if(VIDEO_OPENGLES)
+      set(SDL_VIDEO_OPENGL_EGL 1)
+      set(HAVE_VIDEO_OPENGLES TRUE)
+      set(SDL_VIDEO_OPENGL_ES2 1)
+      set(SDL_VIDEO_RENDER_OGL_ES2 1)
+    endif()
+  endif()
+  list(APPEND EXTRA_LDFLAGS "-Wl,--undefined=Java_org_libsdl_app_SDLActivity_nativeInit")
+endif()
+
 # Platform-specific options and settings
 if(EMSCRIPTEN)
   # Hide noisy warnings that intend to aid mostly during initial stages of porting a new
@@ -833,7 +879,7 @@ elseif(UNIX AND NOT APPLE)
 
   if(SDL_JOYSTICK)
     CheckUSBHID()   # seems to be BSD specific - limit the test to BSD only?
-    if(LINUX)
+    if(LINUX AND NOT ANDROID)
       set(SDL_JOYSTICK_LINUX 1)
       file(GLOB JOYSTICK_SOURCES ${SDL2_SOURCE_DIR}/src/joystick/linux/*.c)
       set(SOURCE_FILES ${SOURCE_FILES} ${JOYSTICK_SOURCES})
@@ -905,9 +951,20 @@ elseif(WINDOWS)
   file(GLOB CORE_SOURCES ${SDL2_SOURCE_DIR}/src/core/windows/*.c)
   set(SOURCE_FILES ${SOURCE_FILES} ${CORE_SOURCES})
 
+  if(MSVC)
+    # Prevent codegen that would use the VC runtime libraries.
+    add_definitions(/GS-)
+    if(CMAKE_SIZEOF_VOID_P EQUAL 4)
+      add_definitions(/arch:SSE)
+    endif()
+  endif()
+
   # Check for DirectX
   if(DIRECTX)
-    if(NOT CMAKE_COMPILER_IS_MINGW)
+    if(DEFINED MSVC_VERSION AND NOT ${MSVC_VERSION} LESS 1700)
+        set(USE_WINSDK_DIRECTX TRUE)
+    endif()
+    if(NOT CMAKE_COMPILER_IS_MINGW AND NOT USE_WINSDK_DIRECTX)
       if("$ENV{DXSDK_DIR}" STREQUAL "")
         message_error("DIRECTX requires the \$DXSDK_DIR environment variable to be set")
       endif()
@@ -933,11 +990,9 @@ elseif(WINDOWS)
     check_include_file(dxgi.h HAVE_DXGI_H)
     if(HAVE_D3D_H OR HAVE_D3D11_H OR HAVE_DDRAW_H OR HAVE_DSOUND_H OR HAVE_DINPUT_H OR HAVE_XAUDIO2_H)
       set(HAVE_DIRECTX TRUE)
-      if(NOT CMAKE_COMPILER_IS_MINGW)
+      if(NOT CMAKE_COMPILER_IS_MINGW AND NOT USE_WINSDK_DIRECTX)
       # TODO: change $ENV{DXSDL_DIR} to get the path from the include checks
-        set(SDL_LINK_DIR $ENV{DXSDK_DIR}\\lib\\${PROCESSOR_ARCH})
-        set(SDL_LINK_DIR ${SDL_LINK_DIR} PARENT_SCOPE)
-        link_directories(${SDL_LINK_DIR})
+        link_directories($ENV{DXSDK_DIR}\\lib\\${PROCESSOR_ARCH})
         include_directories($ENV{DXSDK_DIR}\\Include)
       endif()
     endif()
@@ -1053,7 +1108,7 @@ elseif(WINDOWS)
       list(APPEND EXTRA_LIBS dinput8 dxguid)
       if(CMAKE_COMPILER_IS_MINGW)
         list(APPEND EXTRA_LIBS dxerr8)
-      else()
+      elseif (NOT USE_WINSDK_DIRECTX)
         list(APPEND EXTRA_LIBS dxerr)
       endif()
     endif()
@@ -1090,16 +1145,13 @@ elseif(WINDOWS)
     list(APPEND EXTRA_LDFLAGS "-mwindows")
     set(SDL_CFLAGS "${SDL_CFLAGS} -Dmain=SDL_main")
     list(APPEND SDL_LIBS "-lmingw32" "-lSDL2main" "-mwindows")
-  elseif(MSVC)
-    # Avoids linker errors, since we don't link with the CRT
-    add_definitions(/arch:SSE /GS-)
   endif()
 elseif(APPLE)
   # TODO: rework this for proper MacOS X, iOS and Darwin support
 
   # Requires the darwin file implementation
   if(SDL_FILE)
-    file(GLOB EXTRA_SOURCES ${PROJECT_SOURCE_DIR}/src/file/cocoa/*.m)
+    file(GLOB EXTRA_SOURCES ${SDL2_SOURCE_DIR}/src/file/cocoa/*.m)
     set(SOURCE_FILES ${EXTRA_SOURCES} ${SOURCE_FILES})
     set_source_files_properties(${EXTRA_SOURCES} PROPERTIES LANGUAGE C)
     set(HAVE_SDL_FILE TRUE)
@@ -1404,7 +1456,6 @@ set(_INSTALL_LIBS "SDL2main")
 
 if(SDL_SHARED)
   add_library(SDL2 SHARED ${SOURCE_FILES})
-  install(TARGETS SDL2 RUNTIME DESTINATION . LIBRARY DESTINATION .)
   if(UNIX)
     set_target_properties(SDL2 PROPERTIES
       VERSION ${LT_VERSION}
@@ -1415,15 +1466,15 @@ if(SDL_SHARED)
       VERSION ${SDL_VERSION}
       SOVERSION ${LT_REVISION}
       OUTPUT_NAME "SDL2")
-    if(MSVC)
-      set_target_properties(SDL2 PROPERTIES LINK_FLAGS_RELEASE "/NODEFAULTLIB")
-      set_target_properties(SDL2 PROPERTIES LINK_FLAGS_DEBUG "/NODEFAULTLIB")
-      set_target_properties(SDL2 PROPERTIES STATIC_LIBRARY_FLAGS "/NODEFAULTLIB")
-    endif()
   endif()
- set(_INSTALL_LIBS "SDL2" ${_INSTALL_LIBS})
- target_link_libraries(SDL2 ${EXTRA_LIBS} ${EXTRA_LDFLAGS})
- target_include_directories(SDL2 PUBLIC include)
+  if(MSVC)
+    # Don't try to link with the default set of libraries.
+    set_target_properties(SDL2 PROPERTIES LINK_FLAGS_RELEASE "/NODEFAULTLIB")
+    set_target_properties(SDL2 PROPERTIES LINK_FLAGS_DEBUG "/NODEFAULTLIB")
+    set_target_properties(SDL2 PROPERTIES STATIC_LIBRARY_FLAGS "/NODEFAULTLIB")
+  endif()
+  set(_INSTALL_LIBS "SDL2" ${_INSTALL_LIBS})
+  target_link_libraries(SDL2 ${EXTRA_LIBS} ${EXTRA_LDFLAGS})
 endif()
 
 if(SDL_STATIC)
@@ -1442,12 +1493,6 @@ if(SDL_STATIC)
 endif()
 
 ##### Installation targets #####
-
-if(MEGA)
-  return()
-endif()
-
-
 install(TARGETS ${_INSTALL_LIBS}
   LIBRARY DESTINATION "lib${LIB_SUFFIX}"
   ARCHIVE DESTINATION "lib${LIB_SUFFIX}"

+ 2 - 2
libs/SDL2/Makefile.wiz

@@ -12,13 +12,13 @@ CFLAGS  = -Wall -fPIC -I./include -I$(WIZSDK)/include -DWIZ_GLES_LITE
 TARGET_STATIC  = libSDL13.a
 TARGET_SHARED  = libSDL13.so
 
-SOURCES = ./src/*.c ./src/audio/*.c ./src/cdrom/*.c ./src/cpuinfo/*.c ./src/events/*.c \
+SOURCES = ./src/*.c ./src/audio/*.c ./src/cpuinfo/*.c ./src/events/*.c \
 	./src/file/*.c ./src/stdlib/*.c ./src/thread/*.c ./src/timer/*.c ./src/video/*.c \
 	./src/joystick/*.c ./src/haptic/*.c ./src/video/dummy/*.c ./src/audio/disk/*.c \
 	./src/audio/dummy/*.c ./src/loadso/dlopen/*.c ./src/audio/dsp/*.c \
 	./src/thread/pthread/SDL_systhread.c ./src/thread/pthread/SDL_syssem.c \
 	./src/thread/pthread/SDL_sysmutex.c ./src/thread/pthread/SDL_syscond.c \
-	./src/joystick/linux/*.c ./src/haptic/linux/*.c ./src/timer/unix/*.c ./src/cdrom/dummy/*.c \
+	./src/joystick/linux/*.c ./src/haptic/linux/*.c ./src/timer/unix/*.c \
 	./src/video/pandora/SDL_pandora.o ./src/video/pandora/SDL_pandora_events.o
 	
 

+ 23 - 0
libs/SDL2/VisualC-WinRT/SDL2-WinRT.nuspec

@@ -0,0 +1,23 @@
+<?xml version="1.0"?>
+<package >
+  <metadata>
+    <id>SDL2-WinRT</id>
+    <version>2.0.4-Unofficial</version>
+    <authors>Sam Lantinga</authors>
+    <owners>David Ludwig</owners>
+    <licenseUrl>http://libsdl.org/license.php</licenseUrl>
+    <projectUrl>http://libsdl.org</projectUrl>
+    <requireLicenseAcceptance>false</requireLicenseAcceptance>
+    <description>Unofficial pre-release of LibSDL2, built for WinRT platforms</description>
+    <copyright>Copyright 2015</copyright>
+    <tags>SDL2 SDL LibSDL OpenGL C C++ nativepackage</tags>
+  </metadata>
+  <files>
+    <file src="lib\**\*.dll" target="bin"/>
+    <file src="lib\**\*.lib" target="bin"/>
+    <file src="lib\**\*.pdb" target="bin"/>
+    <file src="..\include\**\*.*" target="include"/>
+    <file src="..\src\**\*.*" target="src"/>
+    <file src="SDL2-WinRT.targets" target="build\native"/>
+  </files>
+</package>

+ 39 - 0
libs/SDL2/VisualC-WinRT/SDL2-WinRT.targets

@@ -0,0 +1,39 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+
+  <PropertyGroup>
+    <LibSDL2-DeviceType Condition="'$(TargetPlatformIdentifier)' == 'Windows' and '$(TargetPlatformVersion)' == '8.0'">WinRT80</LibSDL2-DeviceType>
+    <LibSDL2-DeviceType Condition="'$(TargetPlatformIdentifier)' == 'Windows' and '$(TargetPlatformVersion)' == '8.1'">WinRT81</LibSDL2-DeviceType>
+    <LibSDL2-DeviceType Condition="'$(TargetPlatformIdentifier)' == 'Windows Phone' and '$(TargetPlatformVersion)' == '8.0'">WinPhone80</LibSDL2-DeviceType>
+    <LibSDL2-DeviceType Condition="'$(TargetPlatformIdentifier)' == 'WindowsPhoneApp' and '$(TargetPlatformVersion)' == '8.1'">WinPhone81</LibSDL2-DeviceType>
+    <LibSDL2-DeviceType Condition="'$(TargetPlatformIdentifier)' == 'UAP'">UWP</LibSDL2-DeviceType>
+
+  	<LibSDL2-BinPath>$(MSBuildThisFileDirectory)..\..\bin\$(LibSDL2-DeviceType)\$(Platform)</LibSDL2-BinPath>
+  </PropertyGroup>
+
+  <Target Name="LibSDL2-DeviceType-Check" BeforeTargets="ResolveAssemblyReferences">
+      <Error Condition="'$(LibSDL2-DeviceType)' == ''" Text="Unable to determine which version of Windows is being built-for" />
+  </Target>
+
+  <ItemDefinitionGroup>
+    <Link>
+      <AdditionalLibraryDirectories>$(LibSDL2-BinPath);%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
+      <AdditionalDependencies>SDL2.lib;%(AdditionalDependencies)</AdditionalDependencies>
+    </Link>
+  </ItemDefinitionGroup>
+
+  <ItemDefinitionGroup>
+    <ClCompile>
+      <AdditionalIncludeDirectories>$(MSBuildThisFileDirectory)..\..\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+    </ClCompile>
+  </ItemDefinitionGroup>
+
+  <ItemGroup Label="LibSDL2">
+    <PackagingOutputs Include="$(LibSDL2-BinPath)\SDL2.dll">
+        <OutputGroup>LibSDL2Binaries</OutputGroup>
+        <ProjectName>$(ProjectName)</ProjectName>
+        <TargetPath>%(Filename)%(Extension)</TargetPath>
+    </PackagingOutputs>
+  </ItemGroup>
+
+</Project>

+ 22 - 0
libs/SDL2/VisualC-WinRT/SDL2main-WinRT-NonXAML.nuspec

@@ -0,0 +1,22 @@
+<?xml version="1.0"?>
+<package >
+  <metadata>
+    <id>SDL2main-WinRT-NonXAML</id>
+    <version>2.0.4-Unofficial</version>
+    <authors>Sam Lantinga</authors>
+    <owners>David Ludwig</owners>
+    <licenseUrl>http://libsdl.org/license.php</licenseUrl>
+    <projectUrl>http://libsdl.org</projectUrl>
+    <requireLicenseAcceptance>false</requireLicenseAcceptance>
+    <description>WinMain() function for SDL2 + WinRT + CoreWindow (non-XAML) apps</description>
+    <copyright>Copyright 2015</copyright>
+    <tags>SDL2 SDL LibSDL OpenGL C C++ nativepackage</tags>
+    <dependencies>
+      <dependency id="SDL2-WinRT" version="2.0.4"/>
+    </dependencies>
+  </metadata>
+  <files>
+    <file src="..\src\main\winrt\SDL_winrt_main_NonXAML.cpp" target="src\main\winrt"/>
+    <file src="SDL2main-WinRT-NonXAML.targets" target="build\native"/>
+  </files>
+</package>

+ 10 - 0
libs/SDL2/VisualC-WinRT/SDL2main-WinRT-NonXAML.targets

@@ -0,0 +1,10 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+
+  <ItemGroup Label="LibSDL2">
+    <ClCompile Include="$(MSBuildThisFileDirectory)..\..\src\main\winrt\SDL_winrt_main_NonXAML.cpp">
+      <CompileAsWinRT>true</CompileAsWinRT>
+    </ClCompile>
+  </ItemGroup>
+
+</Project>

+ 70 - 16
libs/SDL2/VisualC/clean.sh

@@ -38,6 +38,8 @@
 #     "ARM", or "x64" (for 64-bit x86).
 #
 
+# Base version of SDL, used for packaging purposes
+$SDLVersion = "2.0.4"
 
 # Gets the .bat file that sets up an MSBuild environment, given one of
 # Visual Studio's, "PlatformToolset"s.
@@ -165,7 +167,7 @@ function Build-SDL-WinRT-Variant
     $VSProjectName = Get-VS-ProjectName $VSProjectPath
 
     # Where to place output binaries (.dll, .lib, and .pdb files):
-    $OutDir = "$PSScriptRoot\..\VisualC-WinRT\lib\$PlatformToolset\$Platform"
+    $OutDir = "$PSScriptRoot\..\VisualC-WinRT\lib\$(Get-SDL-WinRT-Variant-Name $PlatformToolset)\$Platform"
 
     # Where to place intermediate build files:
     $IntermediateDir = "$PSScriptRoot\..\VisualC-WinRT\obj\$SDLProjectName-$(Get-SDL-WinRT-Variant-Name $PlatformToolset)\$Platform"
@@ -206,35 +208,87 @@ function Build-SDL-WinRT-Variant
 #
 # Build each variant, with corresponding .dll, .lib, and .pdb files:
 #
-$DidAnyFail = $false
+$DidAnyDLLBuildFail = $false
+$DidAnyNugetBuildFail = $false
 
 # Build for Windows Phone 8.0, via VC++ 2012:
-if ( ! (Build-SDL-WinRT-Variant "SDL" "v110_wp80" "ARM"))   { $DidAnyFail = $true }
-if ( ! (Build-SDL-WinRT-Variant "SDL" "v110_wp80" "Win32")) { $DidAnyFail = $true }
+if ( ! (Build-SDL-WinRT-Variant "SDL" "v110_wp80" "ARM"))   { $DidAnyDLLBuildFail = $true }
+if ( ! (Build-SDL-WinRT-Variant "SDL" "v110_wp80" "Win32")) { $DidAnyDLLBuildFail = $true }
 
 # Build for Windows Phone 8.1, via VC++ 2013:
-if ( ! (Build-SDL-WinRT-Variant "SDL" "v120_wp81" "ARM"))   { $DidAnyFail = $true }
-if ( ! (Build-SDL-WinRT-Variant "SDL" "v120_wp81" "Win32")) { $DidAnyFail = $true }
+if ( ! (Build-SDL-WinRT-Variant "SDL" "v120_wp81" "ARM"))   { $DidAnyDLLBuildFail = $true }
+if ( ! (Build-SDL-WinRT-Variant "SDL" "v120_wp81" "Win32")) { $DidAnyDLLBuildFail = $true }
 
 # Build for Windows 8.0 and Windows RT 8.0, via VC++ 2012:
-if ( ! (Build-SDL-WinRT-Variant "SDL" "v110" "ARM"))        { $DidAnyFail = $true }
-if ( ! (Build-SDL-WinRT-Variant "SDL" "v110" "Win32"))      { $DidAnyFail = $true }
-if ( ! (Build-SDL-WinRT-Variant "SDL" "v110" "x64"))        { $DidAnyFail = $true }
+if ( ! (Build-SDL-WinRT-Variant "SDL" "v110" "ARM"))        { $DidAnyDLLBuildFail = $true }
+if ( ! (Build-SDL-WinRT-Variant "SDL" "v110" "Win32"))      { $DidAnyDLLBuildFail = $true }
+if ( ! (Build-SDL-WinRT-Variant "SDL" "v110" "x64"))        { $DidAnyDLLBuildFail = $true }
 
 # Build for Windows 8.1 and Windows RT 8.1, via VC++ 2013:
-if ( ! (Build-SDL-WinRT-Variant "SDL" "v120" "ARM"))        { $DidAnyFail = $true }
-if ( ! (Build-SDL-WinRT-Variant "SDL" "v120" "Win32"))      { $DidAnyFail = $true }
-if ( ! (Build-SDL-WinRT-Variant "SDL" "v120" "x64"))        { $DidAnyFail = $true }
+if ( ! (Build-SDL-WinRT-Variant "SDL" "v120" "ARM"))        { $DidAnyDLLBuildFail = $true }
+if ( ! (Build-SDL-WinRT-Variant "SDL" "v120" "Win32"))      { $DidAnyDLLBuildFail = $true }
+if ( ! (Build-SDL-WinRT-Variant "SDL" "v120" "x64"))        { $DidAnyDLLBuildFail = $true }
 
 # Build for Windows 10, via VC++ 2015
-if ( ! (Build-SDL-WinRT-Variant "SDL" "v140" "ARM"))        { $DidAnyFail = $true }
-if ( ! (Build-SDL-WinRT-Variant "SDL" "v140" "Win32"))      { $DidAnyFail = $true }
-if ( ! (Build-SDL-WinRT-Variant "SDL" "v140" "x64"))        { $DidAnyFail = $true }
+if ( ! (Build-SDL-WinRT-Variant "SDL" "v140" "ARM"))        { $DidAnyDLLBuildFail = $true }
+if ( ! (Build-SDL-WinRT-Variant "SDL" "v140" "Win32"))      { $DidAnyDLLBuildFail = $true }
+if ( ! (Build-SDL-WinRT-Variant "SDL" "v140" "x64"))        { $DidAnyDLLBuildFail = $true }
+
+# Build NuGet packages, if possible
+if ($DidAnyDLLBuildFail -eq $true) {
+    Write-Warning -Message "Unable to build all variants.  NuGet packages will not be built."
+    $DidAnyNugetBuildFail = $true
+} else {
+    $NugetPath = (Get-Command -CommandType Application nuget.exe | %{$_.Path}) 2> $null
+    if ("$NugetPath" -eq "") {
+        Write-Warning -Message "Unable to find nuget.exe.  NuGet packages will not be built."
+        $DidAnyNugetBuildFail = $true
+    } else {
+        Write-Host -ForegroundColor Cyan "Building SDL2 NuGet packages..."
+        Write-Host -ForegroundColor Cyan "... via NuGet install: $NugetPath"
+        $NugetOutputDir = "$PSScriptRoot\..\VisualC-WinRT\lib\nuget"
+        Write-Host -ForegroundColor Cyan "...  output directory: $NugetOutputDir"
+        $SDLHGRevision = $($(hg log -l 1 --repository "$PSScriptRoot\.." | select-string "changeset") -Replace "changeset:\W*(\d+).*",'$1') 2>$null
+        Write-Host -ForegroundColor Cyan "...       HG Revision: $SDLHGRevision"
+
+        # Base options to nuget.exe
+        $NugetOptions = @("pack", "PACKAGE_NAME_WILL_GO_HERE", "-Output", "$NugetOutputDir")
+
+        # Try attaching hg revision to NuGet package:
+        $NugetOptions += "-Version"
+        if ("$SDLHGRevision" -eq "") {
+            Write-Warning -Message "Unable to find the Mercurial revision (maybe hg.exe can't be found?).  NuGet packages will not have this attached to their name."
+            $NugetOptions += "$SDLVersion-Unofficial"
+        } else {
+            $NugetOptions += "$SDLVersion.$SDLHGRevision-Unofficial"
+        }
+
+        # Create NuGet output dir, if not yet created:
+        if ($(Test-Path "$NugetOutputDir") -eq $false) {
+            New-Item "$NugetOutputDir" -type directory
+        }
+
+        # Package SDL2:
+        $NugetOptions[1] = "$PSScriptRoot\..\VisualC-WinRT\SDL2-WinRT.nuspec"
+        &"$NugetPath" $NugetOptions -Symbols
+        if ( ! $? ) { $DidAnyNugetBuildFail = $true }
+
+        # Package SDL2main:
+        $NugetOptions[1] = "$PSScriptRoot\..\VisualC-WinRT\SDL2main-WinRT-NonXAML.nuspec"
+        &"$NugetPath" $NugetOptions
+        if ( ! $? ) { $DidAnyNugetBuildFail = $true }
+    }
+}
+
 
 # Let the script's caller know whether or not any errors occurred.
 # Exit codes compatible with Buildbot are used (1 for error, 0 for success).
-if ($DidAnyFail -eq $true) {
+if ($DidAnyDLLBuildFail -eq $true) {
+    Write-Error -Message "Unable to build all known variants of SDL2 for WinRT"
     exit 1
+} elseif ($DidAnyNugetBuildFail -eq $true) {
+    Write-Warning -Message "Unable to build NuGet packages"
+    exit 0  # Should NuGet package build failure lead to a non-failing result code instead?
 } else {
     exit 0
 }

+ 15 - 0
libs/SDL2/configure

@@ -22938,6 +22938,21 @@ case "$host" in
             *-*-bsdi*)          ARCH=bsdi ;;
             *-*-freebsd*)       ARCH=freebsd ;;
             *-*-dragonfly*)     ARCH=freebsd ;;
+            *-raspberry-netbsd*)
+                # Raspberry Pi
+                ARCH=netbsd
+                RPI_CFLAGS="-I/usr/pkg/include -I/usr/pkg/include/interface/vcos/pthreads -I/usr/pkg/include/interface/vmcs_host/linux"
+                CFLAGS="$CFLAGS $RPI_CFLAGS"
+                SDL_CFLAGS="$SDL_CFLAGS $RPI_CFLAGS"
+                EXTRA_CFLAGS="$EXTRA_CFLAGS $RPI_CFLAGS"
+                EXTRA_LDFLAGS="$EXTRA_LDFLAGS -Wl,-R/usr/pkg/lib -L/usr/pkg/lib -lbcm_host -ldl"
+
+                if test x$enable_video = xyes; then
+                    SOURCES="$SOURCES $srcdir/src/video/raspberry/*.c"
+                    $as_echo "#define SDL_VIDEO_DRIVER_RPI 1" >>confdefs.h
+                    SUMMARY_video="${SUMMARY_video} raspberry"
+                fi
+                ;;
             *-*-netbsd*)        ARCH=netbsd ;;
             *-*-openbsd*)       ARCH=openbsd ;;
             *-*-sysv5*)         ARCH=sysv5 ;;

+ 15 - 0
libs/SDL2/configure.in

@@ -2846,6 +2846,21 @@ case "$host" in
             *-*-bsdi*)          ARCH=bsdi ;;
             *-*-freebsd*)       ARCH=freebsd ;;
             *-*-dragonfly*)     ARCH=freebsd ;;
+            *-raspberry-netbsd*)
+                # Raspberry Pi
+                ARCH=netbsd
+                RPI_CFLAGS="-I/usr/pkg/include -I/usr/pkg/include/interface/vcos/pthreads -I/usr/pkg/include/interface/vmcs_host/linux"
+                CFLAGS="$CFLAGS $RPI_CFLAGS"
+                SDL_CFLAGS="$SDL_CFLAGS $RPI_CFLAGS"
+                EXTRA_CFLAGS="$EXTRA_CFLAGS $RPI_CFLAGS"
+                EXTRA_LDFLAGS="$EXTRA_LDFLAGS -Wl,-R/usr/pkg/lib -L/usr/pkg/lib -lbcm_host -ldl"
+
+                if test x$enable_video = xyes; then
+                    SOURCES="$SOURCES $srcdir/src/video/raspberry/*.c"
+                    $as_echo "#define SDL_VIDEO_DRIVER_RPI 1" >>confdefs.h
+                    SUMMARY_video="${SUMMARY_video} raspberry"
+                fi
+                ;;
             *-*-netbsd*)        ARCH=netbsd ;;
             *-*-openbsd*)       ARCH=openbsd ;;
             *-*-sysv5*)         ARCH=sysv5 ;;

+ 5 - 0
libs/SDL2/debian/rules

@@ -197,6 +197,7 @@
 #cmakedefine SDL_FILESYSTEM_DISABLED @SDL_FILESYSTEM_DISABLED@
 
 /* Enable various audio drivers */
+#cmakedefine SDL_AUDIO_DRIVER_ANDROID @SDL_AUDIO_DRIVER_ANDROID@
 #cmakedefine SDL_AUDIO_DRIVER_ALSA @SDL_AUDIO_DRIVER_ALSA@
 #cmakedefine SDL_AUDIO_DRIVER_ALSA_DYNAMIC @SDL_AUDIO_DRIVER_ALSA_DYNAMIC@
 #cmakedefine SDL_AUDIO_DRIVER_ARTS @SDL_AUDIO_DRIVER_ARTS@
@@ -230,6 +231,7 @@
 #cmakedefine SDL_INPUT_LINUXEV @SDL_INPUT_LINUXEV@
 #cmakedefine SDL_INPUT_LINUXKD @SDL_INPUT_LINUXKD@
 #cmakedefine SDL_INPUT_TSLIB @SDL_INPUT_TSLIB@
+#cmakedefine SDL_JOYSTICK_ANDROID @SDL_JOYSTICK_ANDROID@
 #cmakedefine SDL_JOYSTICK_HAIKU @SDL_JOYSTICK_HAIKU@
 #cmakedefine SDL_JOYSTICK_DINPUT @SDL_JOYSTICK_DINPUT@
 #cmakedefine SDL_JOYSTICK_XINPUT @SDL_JOYSTICK_XINPUT@
@@ -268,6 +270,7 @@
 #cmakedefine SDL_TIMER_WINCE @SDL_TIMER_WINCE@
 
 /* Enable various video drivers */
+#cmakedefine SDL_VIDEO_DRIVER_ANDROID @SDL_VIDEO_DRIVER_ANDROID@
 #cmakedefine SDL_VIDEO_DRIVER_HAIKU @SDL_VIDEO_DRIVER_HAIKU@
 #cmakedefine SDL_VIDEO_DRIVER_COCOA @SDL_VIDEO_DRIVER_COCOA@
 #cmakedefine SDL_VIDEO_DRIVER_DIRECTFB @SDL_VIDEO_DRIVER_DIRECTFB@
@@ -331,6 +334,7 @@
 #cmakedefine SDL_VIDEO_OPENGL_OSMESA_DYNAMIC @SDL_VIDEO_OPENGL_OSMESA_DYNAMIC@
 
 /* Enable system power support */
+#cmakedefine SDL_POWER_ANDROID @SDL_POWER_ANDROID@
 #cmakedefine SDL_POWER_LINUX @SDL_POWER_LINUX@
 #cmakedefine SDL_POWER_WINDOWS @SDL_POWER_WINDOWS@
 #cmakedefine SDL_POWER_MACOSX @SDL_POWER_MACOSX@
@@ -339,6 +343,7 @@
 #cmakedefine SDL_POWER_HARDWIRED @SDL_POWER_HARDWIRED@
 
 /* Enable system filesystem support */
+#cmakedefine SDL_FILESYSTEM_ANDROID @SDL_FILESYSTEM_ANDROID@
 #cmakedefine SDL_FILESYSTEM_HAIKU @SDL_FILESYSTEM_HAIKU@
 #cmakedefine SDL_FILESYSTEM_COCOA @SDL_FILESYSTEM_COCOA@
 #cmakedefine SDL_FILESYSTEM_DUMMY @SDL_FILESYSTEM_DUMMY@

+ 0 - 1
libs/SDL2/include/SDL_config_wiz.h

@@ -97,7 +97,6 @@
 #define HAVE_NANOSLEEP 1
 #define HAVE_POW 1
 
-#define SDL_CDROM_DISABLED 1
 #define SDL_AUDIO_DRIVER_DUMMY 1
 #define SDL_AUDIO_DRIVER_OSS 1
 

+ 1 - 1
libs/SDL2/premake/Cygwin/build-scripts/clean_premake.bat

@@ -2,7 +2,7 @@
 
 set(prefix "@prefix@") 
 set(exec_prefix "@exec_prefix@")
-set(libdir "@libdir")
+set(libdir "@libdir@")
 set(SDL2_PREFIX "@prefix@")
 set(SDL2_EXEC_PREFIX "@prefix@")
 set(SDL2_LIBDIR "@libdir@")

+ 4 - 7
libs/SDL2/src/audio/sdlgenaudiocvt.pl

@@ -66,14 +66,11 @@
                                in the Windows SDK, v.10.0.10240.0 (Win 10's initial SDK)
                              */
 #else
-/* XAudio2 exists as of the March 2008 DirectX SDK 
-   The XAudio2 implementation available in the Windows 8 SDK targets Windows 8 and newer.
-   If you want to build SDL with XAudio2 support you should install the DirectX SDK.
+/* XAudio2 exists in the last DirectX SDK as well as the latest Windows SDK.
+   To enable XAudio2 support, you will need to add the location of your DirectX SDK headers to
+   the SDL projects additional include directories and then set SDL_XAUDIO2_HAS_SDK=1 as a
+   preprocessor define
  */
-/* Disable compiling in the XAudio2 support pending fixes to dynamically load the XAudio2
-   entry points so we can be robust to user configuration. Also needs to be fixed to build
-   with the Windows 10 SDK.
-*/
 #if 0 /* See comment above */
 #include <dxsdkver.h>
 #if (!defined(_DXSDK_BUILD_MAJOR) || (_DXSDK_BUILD_MAJOR < 1284))

+ 36 - 4
libs/SDL2/src/core/winrt/SDL_winrtapp_direct3d.cpp

@@ -218,7 +218,14 @@ WINRT_ProcessWindowSizeChange() // TODO: Pass an SDL_Window-identifying thing in
             }
 #endif
 
-            WINRT_UpdateWindowFlags(window, SDL_WINDOW_MAXIMIZED | SDL_WINDOW_FULLSCREEN_DESKTOP);
+            const Uint32 latestFlags = WINRT_DetectWindowFlags(window);
+            if (latestFlags & SDL_WINDOW_MAXIMIZED) {
+                SDL_SendWindowEvent(window, SDL_WINDOWEVENT_MAXIMIZED, 0, 0);
+            } else {
+                SDL_SendWindowEvent(window, SDL_WINDOWEVENT_RESTORED, 0, 0);
+            }
+
+            WINRT_UpdateWindowFlags(window, SDL_WINDOW_FULLSCREEN_DESKTOP);
 
             /* The window can move during a resize event, such as when maximizing
                or resizing from a corner */
@@ -364,7 +371,10 @@ void SDL_WinRTApp::SetWindow(CoreWindow^ window)
     window->CharacterReceived +=
         ref new TypedEventHandler<CoreWindow^, CharacterReceivedEventArgs^>(this, &SDL_WinRTApp::OnCharacterReceived);
 
-#if WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP
+#if NTDDI_VERSION >= NTDDI_WIN10
+    Windows::UI::Core::SystemNavigationManager::GetForCurrentView()->BackRequested +=
+        ref new EventHandler<BackRequestedEventArgs^>(this, &SDL_WinRTApp::OnBackButtonPressed);
+#elif WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP
     HardwareButtons::BackPressed +=
         ref new EventHandler<BackPressedEventArgs^>(this, &SDL_WinRTApp::OnBackButtonPressed);
 #endif
@@ -618,6 +628,15 @@ void SDL_WinRTApp::OnWindowActivated(CoreWindow^ sender, WindowActivatedEventArg
             // * FIXME: Update keyboard state
             // */
             //WIN_CheckClipboardUpdate(data->videodata);
+
+            // HACK: Resetting the mouse-cursor here seems to fix
+            // https://bugzilla.libsdl.org/show_bug.cgi?id=3217, whereby a
+            // WinRT app's mouse cursor may switch to Windows' 'wait' cursor,
+            // after a user alt-tabs back into a full-screened SDL app.
+            // This bug does not appear to reproduce 100% of the time.
+            // It may be a bug in Windows itself (v.10.0.586.36, as tested,
+            // and the most-recent as of this writing).
+            SDL_SetCursor(NULL);
         } else {
             if (SDL_GetKeyboardFocus() == window) {
                 SDL_SetKeyboardFocus(NULL);
@@ -785,8 +804,8 @@ void SDL_WinRTApp::OnCharacterReceived(Windows::UI::Core::CoreWindow^ sender, Wi
     WINRT_ProcessCharacterReceivedEvent(args);
 }
 
-#if WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP
-void SDL_WinRTApp::OnBackButtonPressed(Platform::Object^ sender, Windows::Phone::UI::Input::BackPressedEventArgs^ args)
+template <typename BackButtonEventArgs>
+static void WINRT_OnBackButtonPressed(BackButtonEventArgs ^ args)
 {
     SDL_SendKeyboardKey(SDL_PRESSED, SDL_SCANCODE_AC_BACK);
     SDL_SendKeyboardKey(SDL_RELEASED, SDL_SCANCODE_AC_BACK);
@@ -798,5 +817,18 @@ void SDL_WinRTApp::OnBackButtonPressed(Platform::Object^ sender, Windows::Phone:
         }
     }
 }
+
+#if NTDDI_VERSION == NTDDI_WIN10
+void SDL_WinRTApp::OnBackButtonPressed(Platform::Object^ sender, Windows::UI::Core::BackRequestedEventArgs^ args)
+
+{
+    WINRT_OnBackButtonPressed(args);
+}
+#elif WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP
+void SDL_WinRTApp::OnBackButtonPressed(Platform::Object^ sender, Windows::Phone::UI::Input::BackPressedEventArgs^ args)
+
+{
+    WINRT_OnBackButtonPressed(args);
+}
 #endif
 

+ 3 - 1
libs/SDL2/src/core/winrt/SDL_winrtapp_direct3d.h

@@ -74,7 +74,9 @@ protected:
     void OnKeyUp(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::KeyEventArgs^ args);
     void OnCharacterReceived(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::CharacterReceivedEventArgs^ args);
 
-#if WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP
+#if NTDDI_VERSION >= NTDDI_WIN10
+    void OnBackButtonPressed(Platform::Object^ sender, Windows::UI::Core::BackRequestedEventArgs^ args);
+#elif WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP
     void OnBackButtonPressed(Platform::Object^ sender, Windows::Phone::UI::Input::BackPressedEventArgs^ args);
 #endif
 

+ 1 - 1
libs/SDL2/src/cpuinfo/SDL_cpuinfo.c

@@ -735,7 +735,7 @@ SDL_GetSystemRAM(void)
 #endif
 #ifdef HAVE_SYSCTLBYNAME
         if (SDL_SystemRAM <= 0) {
-#if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
+#if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__NetBSD__)
 #ifdef HW_REALMEM
             int mib[2] = {CTL_HW, HW_REALMEM};
 #else

+ 13 - 0
libs/SDL2/src/dynapi/gendynapi.pl

@@ -845,6 +845,19 @@ SDL_SetModState(SDL_Keymod modstate)
     keyboard->modstate = modstate;
 }
 
+/* Note that SDL_ToggleModState() is not a public API. SDL_SetModState() is. */
+void
+SDL_ToggleModState(const SDL_Keymod modstate, const SDL_bool toggle)
+{
+    SDL_Keyboard *keyboard = &SDL_keyboard;
+    if (toggle) {
+        keyboard->modstate |= modstate;
+    } else {
+        keyboard->modstate &= ~modstate;
+    }
+}
+
+
 SDL_Keycode
 SDL_GetKeyFromScancode(SDL_Scancode scancode)
 {

+ 3 - 0
libs/SDL2/src/events/SDL_keyboard_c.h

@@ -62,6 +62,9 @@ extern void SDL_KeyboardQuit(void);
 /* Convert to UTF-8 */
 extern char *SDL_UCS4ToUTF8(Uint32 ch, char *dst);
 
+/* Toggle on or off pieces of the keyboard mod state. */
+extern void SDL_ToggleModState(const SDL_Keymod modstate, const SDL_bool toggle);
+
 #endif /* _SDL_keyboard_c_h */
 
 /* vi: set ts=4 sw=4 expandtab: */

+ 2 - 0
libs/SDL2/src/events/SDL_windowevents.c

@@ -127,6 +127,7 @@ SDL_SendWindowEvent(SDL_Window * window, Uint8 windowevent, int data1,
         if (window->flags & SDL_WINDOW_MINIMIZED) {
             return 0;
         }
+        window->flags &= ~SDL_WINDOW_MAXIMIZED;
         window->flags |= SDL_WINDOW_MINIMIZED;
         SDL_OnWindowMinimized(window);
         break;
@@ -134,6 +135,7 @@ SDL_SendWindowEvent(SDL_Window * window, Uint8 windowevent, int data1,
         if (window->flags & SDL_WINDOW_MAXIMIZED) {
             return 0;
         }
+        window->flags &= ~SDL_WINDOW_MINIMIZED;
         window->flags |= SDL_WINDOW_MAXIMIZED;
         break;
     case SDL_WINDOWEVENT_RESTORED:

+ 105 - 63
libs/SDL2/src/joystick/SDL_gamecontroller.c

@@ -254,36 +254,6 @@ ControllerMapping_t *SDL_PrivateGetControllerMappingForGUID(SDL_JoystickGUID *gu
     return NULL;
 }
 
-/*
- * Helper function to determine pre-calculated offset to certain joystick mappings
- */
-ControllerMapping_t *SDL_PrivateGetControllerMapping(int device_index)
-{
-    SDL_JoystickGUID jGUID = SDL_JoystickGetDeviceGUID(device_index);
-    ControllerMapping_t *mapping;
-
-    mapping = SDL_PrivateGetControllerMappingForGUID(&jGUID);
-#if SDL_JOYSTICK_XINPUT
-    if (!mapping && SDL_SYS_IsXInputGamepad_DeviceIndex(device_index)) {
-        mapping = s_pXInputMapping;
-    }
-#endif
-#if defined(SDL_JOYSTICK_EMSCRIPTEN)
-    if (!mapping && s_pEmscriptenMapping) {
-        mapping = s_pEmscriptenMapping;
-    }
-#endif
-    if (!mapping) {
-        const char *name = SDL_JoystickNameForIndex(device_index);
-        if (name) {
-            if (SDL_strstr(name, "Xbox") || SDL_strstr(name, "X-Box")) {
-                mapping = s_pXInputMapping;
-            }
-        }
-    }
-    return mapping;
-}
-
 static const char* map_StringForControllerAxis[] = {
     "leftx",
     "lefty",
@@ -581,6 +551,9 @@ char *SDL_PrivateGetControllerMappingFromMappingString(const char *pMapping)
     return SDL_strdup(pSecondComma + 1); /* mapping is everything after the 3rd comma */
 }
 
+/*
+ * Helper function to refresh a mapping
+ */
 void SDL_PrivateGameControllerRefreshMapping(ControllerMapping_t *pControllerMapping)
 {
     SDL_GameController *gamecontrollerlist = SDL_gamecontrollers;
@@ -599,6 +572,102 @@ void SDL_PrivateGameControllerRefreshMapping(ControllerMapping_t *pControllerMap
     }
 }
 
+/*
+ * Helper function to add a mapping for a guid
+ */
+static ControllerMapping_t *
+SDL_PrivateAddMappingForGUID(SDL_JoystickGUID jGUID, const char *mappingString, SDL_bool *existing)
+{
+    char *pchName;
+    char *pchMapping;
+    ControllerMapping_t *pControllerMapping;
+
+    pchName = SDL_PrivateGetControllerNameFromMappingString(mappingString);
+    if (!pchName) {
+        SDL_SetError("Couldn't parse name from %s", mappingString);
+        return NULL;
+    }
+
+    pchMapping = SDL_PrivateGetControllerMappingFromMappingString(mappingString);
+    if (!pchMapping) {
+        SDL_free(pchName);
+        SDL_SetError("Couldn't parse %s", mappingString);
+        return NULL;
+    }
+
+    pControllerMapping = SDL_PrivateGetControllerMappingForGUID(&jGUID);
+    if (pControllerMapping) {
+        /* Update existing mapping */
+        SDL_free(pControllerMapping->name);
+        pControllerMapping->name = pchName;
+        SDL_free(pControllerMapping->mapping);
+        pControllerMapping->mapping = pchMapping;
+        /* refresh open controllers */
+        SDL_PrivateGameControllerRefreshMapping(pControllerMapping);
+        *existing = SDL_TRUE;
+    } else {
+        pControllerMapping = SDL_malloc(sizeof(*pControllerMapping));
+        if (!pControllerMapping) {
+            SDL_free(pchName);
+            SDL_free(pchMapping);
+            SDL_OutOfMemory();
+            return NULL;
+        }
+        pControllerMapping->guid = jGUID;
+        pControllerMapping->name = pchName;
+        pControllerMapping->mapping = pchMapping;
+        pControllerMapping->next = s_pSupportedControllers;
+        s_pSupportedControllers = pControllerMapping;
+        *existing = SDL_FALSE;
+    }
+    return pControllerMapping;
+}
+
+/*
+ * Helper function to determine pre-calculated offset to certain joystick mappings
+ */
+ControllerMapping_t *SDL_PrivateGetControllerMapping(int device_index)
+{
+    SDL_JoystickGUID jGUID = SDL_JoystickGetDeviceGUID(device_index);
+    ControllerMapping_t *mapping;
+
+    mapping = SDL_PrivateGetControllerMappingForGUID(&jGUID);
+#if SDL_JOYSTICK_XINPUT
+    if (!mapping && SDL_SYS_IsXInputGamepad_DeviceIndex(device_index)) {
+        mapping = s_pXInputMapping;
+    }
+#endif
+#if defined(SDL_JOYSTICK_EMSCRIPTEN)
+    if (!mapping && s_pEmscriptenMapping) {
+        mapping = s_pEmscriptenMapping;
+    }
+#endif
+#ifdef __LINUX__
+    if (!mapping) {
+        const char *name = SDL_JoystickNameForIndex(device_index);
+        if (name) {
+            if (SDL_strstr(name, "Xbox 360 Wireless Receiver")) {
+                /* The Linux driver xpad.c maps the wireless dpad to buttons */
+                SDL_bool existing;
+                mapping = SDL_PrivateAddMappingForGUID(jGUID,
+"none,X360 Wireless Controller,a:b0,b:b1,back:b6,dpdown:b14,dpleft:b11,dpright:b12,dpup:b13,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,",
+                              &existing);
+            }
+        }
+    }
+#endif /* __LINUX__ */
+
+    if (!mapping) {
+        const char *name = SDL_JoystickNameForIndex(device_index);
+        if (name) {
+            if (SDL_strstr(name, "Xbox") || SDL_strstr(name, "X-Box")) {
+                mapping = s_pXInputMapping;
+            }
+        }
+    }
+    return mapping;
+}
+
 /*
  * Add or update an entry into the Mappings Database
  */
@@ -677,12 +746,11 @@ int
 SDL_GameControllerAddMapping(const char *mappingString)
 {
     char *pchGUID;
-    char *pchName;
-    char *pchMapping;
     SDL_JoystickGUID jGUID;
-    ControllerMapping_t *pControllerMapping;
     SDL_bool is_xinput_mapping = SDL_FALSE;
     SDL_bool is_emscripten_mapping = SDL_FALSE;
+    SDL_bool existing = SDL_FALSE;
+    ControllerMapping_t *pControllerMapping;
 
     if (!mappingString) {
         return SDL_InvalidParamError("mappingString");
@@ -701,46 +769,20 @@ SDL_GameControllerAddMapping(const char *mappingString)
     jGUID = SDL_JoystickGetGUIDFromString(pchGUID);
     SDL_free(pchGUID);
 
-    pchName = SDL_PrivateGetControllerNameFromMappingString(mappingString);
-    if (!pchName) {
-        return SDL_SetError("Couldn't parse name from %s", mappingString);
-    }
-
-    pchMapping = SDL_PrivateGetControllerMappingFromMappingString(mappingString);
-    if (!pchMapping) {
-        SDL_free(pchName);
-        return SDL_SetError("Couldn't parse %s", mappingString);
+    pControllerMapping = SDL_PrivateAddMappingForGUID(jGUID, mappingString, &existing);
+    if (!pControllerMapping) {
+        return -1;
     }
 
-    pControllerMapping = SDL_PrivateGetControllerMappingForGUID(&jGUID);
-
-    if (pControllerMapping) {
-        /* Update existing mapping */
-        SDL_free(pControllerMapping->name);
-        pControllerMapping->name = pchName;
-        SDL_free(pControllerMapping->mapping);
-        pControllerMapping->mapping = pchMapping;
-        /* refresh open controllers */
-        SDL_PrivateGameControllerRefreshMapping(pControllerMapping);
+    if (existing) {
         return 0;
     } else {
-        pControllerMapping = SDL_malloc(sizeof(*pControllerMapping));
-        if (!pControllerMapping) {
-            SDL_free(pchName);
-            SDL_free(pchMapping);
-            return SDL_OutOfMemory();
-        }
         if (is_xinput_mapping) {
             s_pXInputMapping = pControllerMapping;
         }
         if (is_emscripten_mapping) {
             s_pEmscriptenMapping = pControllerMapping;
         }
-        pControllerMapping->guid = jGUID;
-        pControllerMapping->name = pchName;
-        pControllerMapping->mapping = pchMapping;
-        pControllerMapping->next = s_pSupportedControllers;
-        s_pSupportedControllers = pControllerMapping;
         return 1;
     }
 }

+ 0 - 2
libs/SDL2/src/joystick/SDL_gamecontrollerdb.h

@@ -83,8 +83,6 @@ static const char *s_ControllerMappings [] =
     "050000003215000000090000163a0000,Razer Serval,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a5,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a4,rightx:a2,righty:a3,start:b7,x:b2,y:b3,",
     "03000000de280000fc11000001000000,Steam Controller,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,",
     "03000000de280000ff11000001000000,Valve Streaming Gamepad,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,",
-    "030000005e0400001907000000010000,X360 Wireless Controller,a:b0,b:b1,back:b6,dpdown:b14,dpleft:b11,dpright:b12,dpup:b13,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,",
-    "030000005e0400009102000007010000,X360 Wireless Controller,a:b0,b:b1,back:b6,dpdown:b14,dpleft:b11,dpright:b12,dpup:b13,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,",
     "xinput,XInput Controller,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,",
     "030000005e040000d102000001010000,Xbox One Wireless Controller,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,",
 #endif

+ 46 - 2
libs/SDL2/src/joystick/bsd/SDL_sysjoystick.c

@@ -76,7 +76,7 @@
 #include "../SDL_sysjoystick.h"
 #include "../SDL_joystick_c.h"
 
-#define MAX_UHID_JOYS   16
+#define MAX_UHID_JOYS   64
 #define MAX_JOY_JOYS    2
 #define MAX_JOYS    (MAX_UHID_JOYS + MAX_JOY_JOYS)
 
@@ -286,7 +286,7 @@ SDL_SYS_JoystickOpen(SDL_Joystick * joy, int device_index)
     struct joystick_hwdata *hw;
     struct hid_item hitem;
     struct hid_data *hdata;
-    struct report *rep;
+    struct report *rep = NULL;
     int fd;
     int i;
 
@@ -337,6 +337,38 @@ SDL_SYS_JoystickOpen(SDL_Joystick * joy, int device_index)
 #endif
         rep->rid = -1;          /* XXX */
     }
+#if defined(__NetBSD__)
+    usb_device_descriptor_t udd;
+    struct usb_string_desc usd;
+    if (ioctl(fd, USB_GET_DEVICE_DESC, &udd) == -1)
+        goto desc_failed;
+
+    /* Get default language */
+    usd.usd_string_index = USB_LANGUAGE_TABLE;
+    usd.usd_language_id = 0;
+    if (ioctl(fd, USB_GET_STRING_DESC, &usd) == -1 || usd.usd_desc.bLength < 4) {
+        usd.usd_language_id = 0;
+    } else {
+        usd.usd_language_id = UGETW(usd.usd_desc.bString[0]);
+    }
+
+    usd.usd_string_index = udd.iProduct;
+    if (ioctl(fd, USB_GET_STRING_DESC, &usd) == 0) {
+        char str[128];
+        char *new_name = NULL;
+        int i;
+        for (i = 0; i < (usd.usd_desc.bLength >> 1) - 1 && i < sizeof(str) - 1; i++) {
+            str[i] = UGETW(usd.usd_desc.bString[i]);
+        }
+        str[i] = '\0';
+        asprintf(&new_name, "%s @ %s", str, path);
+        if (new_name != NULL) {
+            free(joydevnames[SDL_SYS_numjoysticks]);
+            joydevnames[SDL_SYS_numjoysticks] = new_name;
+        }
+    }
+desc_failed:
+#endif
     if (report_alloc(rep, hw->repdesc, REPORT_INPUT) < 0) {
         goto usberr;
     }
@@ -409,9 +441,21 @@ SDL_SYS_JoystickOpen(SDL_Joystick * joy, int device_index)
         if (hw->axis_map[i] > 0)
             hw->axis_map[i] = joy->naxes++;
 
+    if (joy->naxes == 0 && joy->nbuttons == 0 && joy->nhats == 0 && joy->nballs == 0) {
+        SDL_SetError("%s: Not a joystick, ignoring", hw->path);
+        goto usberr;
+    }
+
   usbend:
     /* The poll blocks the event thread. */
     fcntl(fd, F_SETFL, O_NONBLOCK);
+#ifdef __NetBSD__
+    /* Flush pending events */
+    if (rep) {
+        while (read(joy->hwdata->fd, REP_BUF_DATA(rep), rep->size) == rep->size)
+            ;
+    }
+#endif
 
     return (0);
   usberr:

+ 2 - 0
libs/SDL2/src/joystick/darwin/SDL_sysjoystick.c

@@ -247,6 +247,8 @@ AddHIDElement(const void *value, void *parameter)
                             case kHIDUsage_GD_DPadDown:
                             case kHIDUsage_GD_DPadRight:
                             case kHIDUsage_GD_DPadLeft:
+                            case kHIDUsage_GD_Start:
+                            case kHIDUsage_GD_Select:
                                 if (!ElementAlreadyAdded(cookie, pDevice->firstButton)) {
                                     element = (recElement *) SDL_calloc(1, sizeof (recElement));
                                     if (element) {

+ 78 - 43
libs/SDL2/src/joystick/iphoneos/SDL_sysjoystick.m

@@ -116,6 +116,10 @@ SDL_SYS_AddMFIJoystickDevice(SDL_JoystickDeviceItem *device, GCController *contr
         device->nbuttons = 7; /* ABXY, shoulder buttons, pause button */
     }
     /* TODO: Handle micro profiles on tvOS. */
+
+    /* This will be set when the first button press of the controller is
+     * detected. */
+    controller.playerIndex = -1;
 #endif
 }
 
@@ -361,26 +365,7 @@ SDL_SYS_JoystickOpen(SDL_Joystick * joystick, int device_index)
         } else {
 #ifdef SDL_JOYSTICK_MFI
             GCController *controller = device->controller;
-            BOOL usedPlayerIndexSlots[4] = {NO, NO, NO, NO};
-
-            /* Find the player index of all other connected controllers. */
-            for (GCController *c in [GCController controllers]) {
-                if (c != controller && c.playerIndex >= 0) {
-                    usedPlayerIndexSlots[c.playerIndex] = YES;
-                }
-            }
-
-            /* Set this controller's player index to the first unused index.
-             * FIXME: This logic isn't great... but SDL doesn't expose this
-             * concept in its external API, so we don't have much to go on. */
-            for (int i = 0; i < 4; i++) {
-                if (!usedPlayerIndexSlots[i]) {
-                    controller.playerIndex = i;
-                    break;
-                }
-            }
-
-            controller.controllerPausedHandler = ^(GCController *controller) {
+            controller.controllerPausedHandler = ^(GCController *c) {
                 if (joystick->hwdata) {
                     ++joystick->hwdata->num_pause_presses;
                 }
@@ -475,53 +460,102 @@ SDL_SYS_MFIJoystickUpdate(SDL_Joystick * joystick)
         GCController *controller = joystick->hwdata->controller;
         Uint8 hatstate = SDL_HAT_CENTERED;
         int i;
+        int updateplayerindex = 0;
 
         if (controller.extendedGamepad) {
             GCExtendedGamepad *gamepad = controller.extendedGamepad;
 
             /* Axis order matches the XInput Windows mappings. */
-            SDL_PrivateJoystickAxis(joystick, 0, (Sint16) (gamepad.leftThumbstick.xAxis.value * 32767));
-            SDL_PrivateJoystickAxis(joystick, 1, (Sint16) (gamepad.leftThumbstick.yAxis.value * -32767));
-            SDL_PrivateJoystickAxis(joystick, 2, (Sint16) ((gamepad.leftTrigger.value * 65535) - 32768));
-            SDL_PrivateJoystickAxis(joystick, 3, (Sint16) (gamepad.rightThumbstick.xAxis.value * 32767));
-            SDL_PrivateJoystickAxis(joystick, 4, (Sint16) (gamepad.rightThumbstick.yAxis.value * -32767));
-            SDL_PrivateJoystickAxis(joystick, 5, (Sint16) ((gamepad.rightTrigger.value * 65535) - 32768));
+            Sint16 axes[] = {
+                (Sint16) (gamepad.leftThumbstick.xAxis.value * 32767),
+                (Sint16) (gamepad.leftThumbstick.yAxis.value * -32767),
+                (Sint16) ((gamepad.leftTrigger.value * 65535) - 32768),
+                (Sint16) (gamepad.rightThumbstick.xAxis.value * 32767),
+                (Sint16) (gamepad.rightThumbstick.yAxis.value * -32767),
+                (Sint16) ((gamepad.rightTrigger.value * 65535) - 32768),
+            };
+
+            /* Button order matches the XInput Windows mappings. */
+            Uint8 buttons[] = {
+                gamepad.buttonA.isPressed, gamepad.buttonB.isPressed,
+                gamepad.buttonX.isPressed, gamepad.buttonY.isPressed,
+                gamepad.leftShoulder.isPressed,
+                gamepad.rightShoulder.isPressed,
+            };
 
             hatstate = SDL_SYS_MFIJoystickHatStateForDPad(gamepad.dpad);
 
-            /* Button order matches the XInput Windows mappings. */
-            SDL_PrivateJoystickButton(joystick, 0, gamepad.buttonA.isPressed);
-            SDL_PrivateJoystickButton(joystick, 1, gamepad.buttonB.isPressed);
-            SDL_PrivateJoystickButton(joystick, 2, gamepad.buttonX.isPressed);
-            SDL_PrivateJoystickButton(joystick, 3, gamepad.buttonY.isPressed);
-            SDL_PrivateJoystickButton(joystick, 4, gamepad.leftShoulder.isPressed);
-            SDL_PrivateJoystickButton(joystick, 5, gamepad.rightShoulder.isPressed);
+            for (i = 0; i < SDL_arraysize(axes); i++) {
+                /* The triggers (axes 2 and 5) are resting at -32768 but SDL
+                 * initializes its values to 0. We only want to make sure the
+                 * player index is up to date if the user actually moves an axis. */
+                if ((i != 2 && i != 5) || axes[i] != -32768) {
+                    updateplayerindex |= (joystick->axes[i] != axes[i]);
+                }
+                SDL_PrivateJoystickAxis(joystick, i, axes[i]);
+            }
+
+            for (i = 0; i < SDL_arraysize(buttons); i++) {
+                updateplayerindex |= (joystick->buttons[i] != buttons[i]);
+                SDL_PrivateJoystickButton(joystick, i, buttons[i]);
+            }
         } else if (controller.gamepad) {
             GCGamepad *gamepad = controller.gamepad;
 
+            /* Button order matches the XInput Windows mappings. */
+            Uint8 buttons[] = {
+                gamepad.buttonA.isPressed, gamepad.buttonB.isPressed,
+                gamepad.buttonX.isPressed, gamepad.buttonY.isPressed,
+                gamepad.leftShoulder.isPressed,
+                gamepad.rightShoulder.isPressed,
+            };
+
             hatstate = SDL_SYS_MFIJoystickHatStateForDPad(gamepad.dpad);
 
-            /* Button order matches the XInput Windows mappings. */
-            SDL_PrivateJoystickButton(joystick, 0, gamepad.buttonA.isPressed);
-            SDL_PrivateJoystickButton(joystick, 1, gamepad.buttonB.isPressed);
-            SDL_PrivateJoystickButton(joystick, 2, gamepad.buttonX.isPressed);
-            SDL_PrivateJoystickButton(joystick, 3, gamepad.buttonY.isPressed);
-            SDL_PrivateJoystickButton(joystick, 4, gamepad.leftShoulder.isPressed);
-            SDL_PrivateJoystickButton(joystick, 5, gamepad.rightShoulder.isPressed);
+            for (i = 0; i < SDL_arraysize(buttons); i++) {
+                updateplayerindex |= (joystick->buttons[i] != buttons[i]);
+                SDL_PrivateJoystickButton(joystick, i, buttons[i]);
+            }
         }
         /* TODO: Handle micro profiles on tvOS. */
 
-        SDL_PrivateJoystickHat(joystick, 0, hatstate);
+        if (joystick->nhats > 0) {
+            updateplayerindex |= (joystick->hats[0] != hatstate);
+            SDL_PrivateJoystickHat(joystick, 0, hatstate);
+        }
 
         for (i = 0; i < joystick->hwdata->num_pause_presses; i++) {
             /* The pause button is always last. */
             Uint8 pausebutton = joystick->nbuttons - 1;
 
-            SDL_PrivateJoystickButton(joystick, pausebutton, 1);
-            SDL_PrivateJoystickButton(joystick, pausebutton, 0);
+            SDL_PrivateJoystickButton(joystick, pausebutton, SDL_PRESSED);
+            SDL_PrivateJoystickButton(joystick, pausebutton, SDL_RELEASED);
+
+            updateplayerindex = YES;
         }
 
         joystick->hwdata->num_pause_presses = 0;
+
+        if (updateplayerindex && controller.playerIndex == -1) {
+            BOOL usedPlayerIndexSlots[4] = {NO, NO, NO, NO};
+
+            /* Find the player index of all other connected controllers. */
+            for (GCController *c in [GCController controllers]) {
+                if (c != controller && c.playerIndex >= 0) {
+                    usedPlayerIndexSlots[c.playerIndex] = YES;
+                }
+            }
+
+            /* Set this controller's player index to the first unused index.
+             * FIXME: This logic isn't great... but SDL doesn't expose this
+             * concept in its external API, so we don't have much to go on. */
+            for (i = 0; i < SDL_arraysize(usedPlayerIndexSlots); i++) {
+                if (!usedPlayerIndexSlots[i]) {
+                    controller.playerIndex = i;
+                    break;
+                }
+            }
+        }
     }
 #endif
 }
@@ -566,6 +600,7 @@ SDL_SYS_JoystickClose(SDL_Joystick * joystick)
 #ifdef SDL_JOYSTICK_MFI
             GCController *controller = device->controller;
             controller.controllerPausedHandler = nil;
+            controller.playerIndex = -1;
 #endif
         }
     }

+ 2 - 1
libs/SDL2/src/joystick/sort_controllers.py

@@ -158,7 +158,8 @@ SDL_RendererEventWatch(void *userdata, SDL_Event *event)
                 }
             } else if (event->window.event == SDL_WINDOWEVENT_MINIMIZED) {
                 renderer->hidden = SDL_TRUE;
-            } else if (event->window.event == SDL_WINDOWEVENT_RESTORED) {
+            } else if (event->window.event == SDL_WINDOWEVENT_RESTORED || 
+                       event->window.event == SDL_WINDOWEVENT_MAXIMIZED) {
                 if (!(SDL_GetWindowFlags(window) & SDL_WINDOW_HIDDEN)) {
                     renderer->hidden = SDL_FALSE;
                 }

+ 2 - 2
libs/SDL2/src/render/opengl/SDL_render_gl.c

@@ -393,7 +393,7 @@ GL_CreateRenderer(SDL_Window * window, Uint32 flags)
     const char *hint;
     GLint value;
     Uint32 window_flags;
-    int profile_mask, major, minor;
+    int profile_mask = 0, major = 0, minor = 0;
     SDL_bool changed_window = SDL_FALSE;
 
     SDL_GL_GetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, &profile_mask);
@@ -1052,7 +1052,7 @@ GL_UpdateClipRect(SDL_Renderer * renderer)
             int w, h;
 
             SDL_GetRendererOutputSize(renderer, &w, &h);
-            data->glScissor(renderer->viewport.x + rect->x, (h - renderer->viewport.y - renderer->viewport.h) + rect->y, rect->w, rect->h);
+            data->glScissor(renderer->viewport.x + rect->x, h - renderer->viewport.y - rect->y - rect->h, rect->w, rect->h);
         }
     } else {
         data->glDisable(GL_SCISSOR_TEST);

+ 2 - 2
libs/SDL2/src/render/opengles/SDL_render_gles.c

@@ -285,7 +285,7 @@ GLES_CreateRenderer(SDL_Window * window, Uint32 flags)
     GLES_RenderData *data;
     GLint value;
     Uint32 window_flags;
-    int profile_mask, major, minor;
+    int profile_mask = 0, major = 0, minor = 0;
     SDL_bool changed_window = SDL_FALSE;
 
     SDL_GL_GetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, &profile_mask);
@@ -721,7 +721,7 @@ GLES_UpdateClipRect(SDL_Renderer * renderer)
             int w, h;
 
             SDL_GetRendererOutputSize(renderer, &w, &h);
-            data->glScissor(renderer->viewport.x + rect->x, (h - renderer->viewport.y - renderer->viewport.h) + rect->y, rect->w, rect->h);
+            data->glScissor(renderer->viewport.x + rect->x, h - renderer->viewport.y - rect->y - rect->h, rect->w, rect->h);
         }
     } else {
         data->glDisable(GL_SCISSOR_TEST);

+ 2 - 2
libs/SDL2/src/render/opengles2/SDL_render_gles2.c

@@ -418,7 +418,7 @@ GLES2_UpdateClipRect(SDL_Renderer * renderer)
             int w, h;
 
             SDL_GetRendererOutputSize(renderer, &w, &h);
-            data->glScissor(renderer->viewport.x + rect->x, (h - renderer->viewport.y - renderer->viewport.h) + rect->y, rect->w, rect->h);
+            data->glScissor(renderer->viewport.x + rect->x, h - renderer->viewport.y - rect->y - rect->h, rect->w, rect->h);
         }
     } else {
         data->glDisable(GL_SCISSOR_TEST);
@@ -1956,7 +1956,7 @@ GLES2_CreateRenderer(SDL_Window *window, Uint32 flags)
     Uint32 window_flags;
     GLint window_framebuffer;
     GLint value;
-    int profile_mask, major, minor;
+    int profile_mask = 0, major = 0, minor = 0;
     SDL_bool changed_window = SDL_FALSE;
 
     SDL_GL_GetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, &profile_mask);

+ 4 - 0
libs/SDL2/src/thread/pthread/SDL_systhread.c

@@ -143,7 +143,11 @@ SDL_SYS_SetupThread(const char *name)
             #endif
         }
         #elif HAVE_PTHREAD_SETNAME_NP
+            #if defined(__NETBSD__)
+            pthread_setname_np(pthread_self(), "%s", name);
+            #else
             pthread_setname_np(pthread_self(), name);
+            #endif
         #elif HAVE_PTHREAD_SET_NAME_NP
             pthread_set_name_np(pthread_self(), name);
         #elif defined(__HAIKU__)

+ 11 - 10
libs/SDL2/src/video/SDL_video.c

@@ -1488,6 +1488,7 @@ SDL_RecreateWindow(SDL_Window * window, Uint32 flags)
     if (window->surface) {
         window->surface->flags &= ~SDL_DONTFREE;
         SDL_FreeSurface(window->surface);
+        window->surface = NULL;
     }
     if (_this->DestroyWindowFramebuffer) {
         _this->DestroyWindowFramebuffer(_this, window);
@@ -2913,18 +2914,8 @@ SDL_GL_GetAttribute(SDL_GLattr attr, int *value)
     void (APIENTRY *glGetFramebufferAttachmentParameterivFunc) (GLenum target, GLenum attachment, GLenum pname, GLint* params);
     GLenum attachment = GL_BACK_LEFT;
     GLenum attachmentattrib = 0;
-
-    glGetStringFunc = SDL_GL_GetProcAddress("glGetString");
-    if (!glGetStringFunc) {
-        return SDL_SetError("Failed getting OpenGL glGetString entry point");
-    }
 #endif
 
-    glGetErrorFunc = SDL_GL_GetProcAddress("glGetError");
-    if (!glGetErrorFunc) {
-        return SDL_SetError("Failed getting OpenGL glGetError entry point");
-    }
-
     /* Clear value in any case */
     *value = 0;
 
@@ -3095,6 +3086,11 @@ SDL_GL_GetAttribute(SDL_GLattr attr, int *value)
     }
 
 #if SDL_VIDEO_OPENGL
+    glGetStringFunc = SDL_GL_GetProcAddress("glGetString");
+    if (!glGetStringFunc) {
+        return SDL_SetError("Failed getting OpenGL glGetString entry point");
+    }
+
     if (attachmentattrib && isAtLeastGL3((const char *) glGetStringFunc(GL_VERSION))) {
         glGetFramebufferAttachmentParameterivFunc = SDL_GL_GetProcAddress("glGetFramebufferAttachmentParameteriv");
 
@@ -3115,6 +3111,11 @@ SDL_GL_GetAttribute(SDL_GLattr attr, int *value)
         }
     }
 
+    glGetErrorFunc = SDL_GL_GetProcAddress("glGetError");
+    if (!glGetErrorFunc) {
+        return SDL_SetError("Failed getting OpenGL glGetError entry point");
+    }
+
     error = glGetErrorFunc();
     if (error != GL_NO_ERROR) {
         if (error == GL_INVALID_ENUM) {

+ 49 - 25
libs/SDL2/src/video/cocoa/SDL_cocoakeyboard.m

@@ -33,25 +33,27 @@
 /*#define DEBUG_IME NSLog */
 #define DEBUG_IME(...)
 
-@interface SDLTranslatorResponder : NSView <NSTextInput> {
+@interface SDLTranslatorResponder : NSView <NSTextInputClient> {
     NSString *_markedText;
     NSRange   _markedRange;
     NSRange   _selectedRange;
     SDL_Rect  _inputRect;
 }
-- (void) doCommandBySelector:(SEL)myselector;
-- (void) setInputRect:(SDL_Rect *) rect;
+- (void)doCommandBySelector:(SEL)myselector;
+- (void)setInputRect:(SDL_Rect *)rect;
 @end
 
 @implementation SDLTranslatorResponder
 
-- (void) setInputRect:(SDL_Rect *) rect
+- (void)setInputRect:(SDL_Rect *)rect
 {
     _inputRect = *rect;
 }
 
-- (void) insertText:(id) aString
+- (void)insertText:(id)aString replacementRange:(NSRange)replacementRange
 {
+    /* TODO: Make use of replacementRange? */
+
     const char *str;
 
     DEBUG_IME(@"insertText: %@", aString);
@@ -67,7 +69,15 @@
     SDL_SendKeyboardText(str);
 }
 
-- (void) doCommandBySelector:(SEL) myselector
+- (void)insertText:(id)insertString
+{
+    /* This method is part of NSTextInput and not NSTextInputClient, but
+     * apparently it still might be called in OS X 10.5 and can cause beeps if
+     * the implementation is missing: http://crbug.com/47890 */
+    [self insertText:insertString replacementRange:NSMakeRange(0, 0)];
+}
+
+- (void)doCommandBySelector:(SEL)myselector
 {
     /* No need to do anything since we are not using Cocoa
        selectors to handle special keys, instead we use SDL
@@ -75,23 +85,22 @@
     */
 }
 
-- (BOOL) hasMarkedText
+- (BOOL)hasMarkedText
 {
     return _markedText != nil;
 }
 
-- (NSRange) markedRange
+- (NSRange)markedRange
 {
     return _markedRange;
 }
 
-- (NSRange) selectedRange
+- (NSRange)selectedRange
 {
     return _selectedRange;
 }
 
-- (void) setMarkedText:(id) aString
-         selectedRange:(NSRange) selRange
+- (void)setMarkedText:(id)aString selectedRange:(NSRange)selectedRange replacementRange:(NSRange)replacementRange;
 {
     if ([aString isKindOfClass: [NSAttributedString class]]) {
         aString = [aString string];
@@ -107,17 +116,17 @@
         _markedText = [aString retain];
     }
 
-    _selectedRange = selRange;
+    _selectedRange = selectedRange;
     _markedRange = NSMakeRange(0, [aString length]);
 
     SDL_SendEditingText([aString UTF8String],
-                        selRange.location, selRange.length);
+                        selectedRange.location, selectedRange.length);
 
     DEBUG_IME(@"setMarkedText: %@, (%d, %d)", _markedText,
           selRange.location, selRange.length);
 }
 
-- (void) unmarkText
+- (void)unmarkText
 {
     [_markedText release];
     _markedText = nil;
@@ -125,29 +134,38 @@
     SDL_SendEditingText("", 0, 0);
 }
 
-- (NSRect) firstRectForCharacterRange: (NSRange) theRange
+- (NSRect)firstRectForCharacterRange:(NSRange)aRange actualRange:(NSRangePointer)actualRange;
 {
     NSWindow *window = [self window];
-    NSRect contentRect = [window contentRectForFrameRect: [window frame]];
+    NSRect contentRect = [window contentRectForFrameRect:[window frame]];
     float windowHeight = contentRect.size.height;
     NSRect rect = NSMakeRect(_inputRect.x, windowHeight - _inputRect.y - _inputRect.h,
                              _inputRect.w, _inputRect.h);
 
+    if (actualRange) {
+        *actualRange = aRange;
+    }
+
     DEBUG_IME(@"firstRectForCharacterRange: (%d, %d): windowHeight = %g, rect = %@",
-            theRange.location, theRange.length, windowHeight,
+            aRange.location, aRange.length, windowHeight,
             NSStringFromRect(rect));
-    rect.origin = [[self window] convertBaseToScreen: rect.origin];
+
+    if ([[self window] respondsToSelector:@selector(convertRectToScreen:)]) {
+        rect = [[self window] convertRectToScreen:rect];
+    } else {
+        rect.origin = [[self window] convertBaseToScreen:rect.origin];
+    }
 
     return rect;
 }
 
-- (NSAttributedString *) attributedSubstringFromRange: (NSRange) theRange
+- (NSAttributedString *)attributedSubstringForProposedRange:(NSRange)aRange actualRange:(NSRangePointer)actualRange;
 {
-    DEBUG_IME(@"attributedSubstringFromRange: (%d, %d)", theRange.location, theRange.length);
+    DEBUG_IME(@"attributedSubstringFromRange: (%d, %d)", aRange.location, aRange.length);
     return nil;
 }
 
-- (NSInteger) conversationIdentifier
+- (NSInteger)conversationIdentifier
 {
     return (NSInteger) self;
 }
@@ -155,7 +173,7 @@
 /* This method returns the index for character that is
  * nearest to thePoint.  thPoint is in screen coordinate system.
  */
-- (NSUInteger) characterIndexForPoint:(NSPoint) thePoint
+- (NSUInteger)characterIndexForPoint:(NSPoint)thePoint
 {
     DEBUG_IME(@"characterIndexForPoint: (%g, %g)", thePoint.x, thePoint.y);
     return 0;
@@ -166,7 +184,7 @@
  * NSInputServer examines the return value of this
  * method & constructs appropriate attributed string.
  */
-- (NSArray *) validAttributesForMarkedText
+- (NSArray *)validAttributesForMarkedText
 {
     return [NSArray array];
 }
@@ -479,6 +497,12 @@ Cocoa_InitKeyboard(_THIS)
     SDL_SetScancodeName(SDL_SCANCODE_LGUI, "Left Command");
     SDL_SetScancodeName(SDL_SCANCODE_RALT, "Right Option");
     SDL_SetScancodeName(SDL_SCANCODE_RGUI, "Right Command");
+
+    /* On pre-10.6, you might have the initial capslock key state wrong. */
+    if (floor(NSAppKitVersionNumber) >= NSAppKitVersionNumber10_6) {
+        data->modifierFlags = [NSEvent modifierFlags];
+        SDL_ToggleModState(KMOD_CAPS, (data->modifierFlags & NSAlphaShiftKeyMask) != 0);
+    }
 }
 
 void
@@ -504,7 +528,7 @@ Cocoa_StartTextInput(_THIS)
             [[SDLTranslatorResponder alloc] initWithFrame: NSMakeRect(0.0, 0.0, 0.0, 0.0)];
     }
 
-    if (![[data->fieldEdit superview] isEqual: parentView]) {
+    if (![[data->fieldEdit superview] isEqual:parentView]) {
         /* DEBUG_IME(@"add fieldEdit to window contentView"); */
         [data->fieldEdit removeFromSuperview];
         [parentView addSubview: data->fieldEdit];
@@ -535,7 +559,7 @@ Cocoa_SetTextInputRect(_THIS, SDL_Rect *rect)
         return;
     }
 
-    [data->fieldEdit setInputRect: rect];
+    [data->fieldEdit setInputRect:rect];
 }
 
 void

+ 15 - 1
libs/SDL2/src/video/cocoa/SDL_cocoawindow.m

@@ -588,6 +588,13 @@ SetWindowStyle(SDL_Window * window, unsigned int style)
     if ((isFullscreenSpace) && ((window->flags & SDL_WINDOW_FULLSCREEN_DESKTOP) == SDL_WINDOW_FULLSCREEN_DESKTOP)) {
         [NSMenu setMenuBarVisible:NO];
     }
+
+    /* On pre-10.6, you might have the capslock key state wrong now because we can't check here. */
+    if (floor(NSAppKitVersionNumber) >= NSAppKitVersionNumber10_6) {
+        const unsigned int newflags = [NSEvent modifierFlags] & NSAlphaShiftKeyMask;
+        _data->videodata->modifierFlags = (_data->videodata->modifierFlags & ~NSAlphaShiftKeyMask) | newflags;
+        SDL_ToggleModState(KMOD_CAPS, newflags != 0);
+    }
 }
 
 - (void)windowDidResignKey:(NSNotification *)aNotification
@@ -816,7 +823,14 @@ SetWindowStyle(SDL_Window * window, unsigned int style)
 
     /* Ignore events that aren't inside the client area (i.e. title bar.) */
     if ([theEvent window]) {
-        const NSRect windowRect = [[[theEvent window] contentView] frame];
+        NSRect windowRect = [[[theEvent window] contentView] frame];
+
+        /* add one to size, since NSPointInRect is exclusive of the bottom
+           edges, which mean it misses the top of the window by one pixel
+           (as the origin is the bottom left). */
+        windowRect.size.width += 1;
+        windowRect.size.height += 1;
+
         if (!NSPointInRect([theEvent locationInWindow], windowRect)) {
             return;
         }

+ 7 - 0
libs/SDL2/src/video/sdlgenblit.pl

@@ -415,12 +415,19 @@ WIN_WindowProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
                  * FIXME: Update keyboard state
                  */
                 WIN_CheckClipboardUpdate(data->videodata);
+
+                SDL_ToggleModState(KMOD_CAPS, (GetKeyState(VK_CAPITAL) & 0x0001) != 0);
+                SDL_ToggleModState(KMOD_NUM, (GetKeyState(VK_NUMLOCK) & 0x0001) != 0);
             } else {
+                data->in_window_deactivation = SDL_TRUE;
+
                 if (SDL_GetKeyboardFocus() == data->window) {
                     SDL_SetKeyboardFocus(NULL);
                 }
 
                 ClipCursor(NULL);
+
+                data->in_window_deactivation = SDL_FALSE;
             }
         }
         returnCode = 0;

+ 3 - 0
libs/SDL2/src/video/windows/SDL_windowsframebuffer.c

@@ -42,6 +42,9 @@ int WIN_CreateWindowFramebuffer(_THIS, SDL_Window * window, Uint32 * format, voi
     /* Find out the format of the screen */
     size = sizeof(BITMAPINFOHEADER) + 256 * sizeof (RGBQUAD);
     info = (LPBITMAPINFO)SDL_stack_alloc(Uint8, size);
+    if (!info) {
+        return SDL_OutOfMemory();
+    }
 
     SDL_memset(info, 0, size);
     info->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);

+ 4 - 0
libs/SDL2/src/video/windows/SDL_windowskeyboard.c

@@ -102,6 +102,10 @@ WIN_InitKeyboard(_THIS)
     SDL_SetScancodeName(SDL_SCANCODE_APPLICATION, "Menu");
     SDL_SetScancodeName(SDL_SCANCODE_LGUI, "Left Windows");
     SDL_SetScancodeName(SDL_SCANCODE_RGUI, "Right Windows");
+
+    /* Are system caps/num/scroll lock active? Set our state to match. */
+    SDL_ToggleModState(KMOD_CAPS, (GetKeyState(VK_CAPITAL) & 0x0001) != 0);
+    SDL_ToggleModState(KMOD_NUM, (GetKeyState(VK_NUMLOCK) & 0x0001) != 0);
 }
 
 void

+ 20 - 20
libs/SDL2/src/video/windows/SDL_windowsopengl.c

@@ -666,29 +666,29 @@ WIN_GL_CreateContext(_THIS, SDL_Window * window)
                 WGL_CONTEXT_MINOR_VERSION_ARB, _this->gl_config.minor_version,
                 0
             };
-        int iattr = 4;
-
-        /* SDL profile bits match WGL profile bits */
-        if( _this->gl_config.profile_mask != 0 ) {
-            attribs[iattr++] = WGL_CONTEXT_PROFILE_MASK_ARB;
-        attribs[iattr++] = _this->gl_config.profile_mask;
-        }
-
-        /* SDL flags match WGL flags */
-        if( _this->gl_config.flags != 0 ) {
-            attribs[iattr++] = WGL_CONTEXT_FLAGS_ARB;
-        attribs[iattr++] = _this->gl_config.flags;
-        }
-
-        /* only set if wgl extension is available */
-        if( _this->gl_data->HAS_WGL_ARB_context_flush_control ) {
-            attribs[iattr++] = WGL_CONTEXT_RELEASE_BEHAVIOR_ARB;
-            attribs[iattr++] = _this->gl_config.release_behavior ?
+            int iattr = 4;
+
+            /* SDL profile bits match WGL profile bits */
+            if (_this->gl_config.profile_mask != 0) {
+                attribs[iattr++] = WGL_CONTEXT_PROFILE_MASK_ARB;
+                attribs[iattr++] = _this->gl_config.profile_mask;
+            }
+
+            /* SDL flags match WGL flags */
+            if (_this->gl_config.flags != 0) {
+                attribs[iattr++] = WGL_CONTEXT_FLAGS_ARB;
+                attribs[iattr++] = _this->gl_config.flags;
+            }
+
+            /* only set if wgl extension is available */
+            if (_this->gl_data->HAS_WGL_ARB_context_flush_control) {
+                attribs[iattr++] = WGL_CONTEXT_RELEASE_BEHAVIOR_ARB;
+                attribs[iattr++] = _this->gl_config.release_behavior ?
                                     WGL_CONTEXT_RELEASE_BEHAVIOR_FLUSH_ARB :
                                     WGL_CONTEXT_RELEASE_BEHAVIOR_NONE_ARB;
-        }
+            }
 
-        attribs[iattr++] = 0;
+            attribs[iattr++] = 0;
 
             /* Create the GL 3.x context */
             context = wglCreateContextAttribsARB(hdc, share_context, attribs);

+ 18 - 0
libs/SDL2/src/video/windows/SDL_windowswindow.c

@@ -559,7 +559,25 @@ WIN_SetWindowFullscreen(_THIS, SDL_Window * window, SDL_VideoDisplay * display,
         y = bounds.y;
         w = bounds.w;
         h = bounds.h;
+
+        /* Unset the maximized flag.  This fixes
+           https://bugzilla.libsdl.org/show_bug.cgi?id=3215
+        */
+        if (style & WS_MAXIMIZE) {
+            data->windowed_mode_was_maximized = SDL_TRUE;
+            style &= ~WS_MAXIMIZE;
+        }
     } else {
+        /* Restore window-maximization state, as applicable.
+           Special care is taken to *not* do this if and when we're
+           alt-tab'ing away (to some other window; as indicated by
+           in_window_deactivation), otherwise
+           https://bugzilla.libsdl.org/show_bug.cgi?id=3215 can reproduce!
+        */
+        if (data->windowed_mode_was_maximized && !data->in_window_deactivation) {
+            style |= WS_MAXIMIZE;
+            data->windowed_mode_was_maximized = SDL_FALSE;
+        }
         rect.left = 0;
         rect.top = 0;
         rect.right = window->windowed.w;

+ 2 - 0
libs/SDL2/src/video/windows/SDL_windowswindow.h

@@ -42,6 +42,8 @@ typedef struct
     SDL_bool in_border_change;
     SDL_bool in_title_click;
     SDL_bool focus_click_pending;
+    SDL_bool windowed_mode_was_maximized;
+    SDL_bool in_window_deactivation;
     struct SDL_VideoData *videodata;
 #if SDL_VIDEO_OPENGL_EGL  
     EGLSurface egl_surface;

+ 93 - 14
libs/SDL2/src/video/winrt/SDL_winrtvideo.cpp

@@ -315,6 +315,61 @@ WINRT_AddDisplaysForAdapter (_THIS, IDXGIFactory2 * dxgiFactory2, int adapterInd
 
     for (int outputIndex = 0; ; ++outputIndex) {
         if (WINRT_AddDisplaysForOutput(_this, dxgiAdapter1, outputIndex) < 0) {
+            /* HACK: The Windows App Certification Kit 10.0 can fail, when
+               running the Store Apps' test, "Direct3D Feature Test".  The
+               certification kit's error is:
+
+               "Application App was not running at the end of the test. It likely crashed or was terminated for having become unresponsive."
+
+               This was caused by SDL/WinRT's DXGI failing to report any
+               outputs.  Attempts to get the 1st display-output from the
+               1st display-adapter can fail, with IDXGIAdapter::EnumOutputs
+               returning DXGI_ERROR_NOT_FOUND.  This could be a bug in Windows,
+               the Windows App Certification Kit, or possibly in SDL/WinRT's
+               display detection code.  Either way, try to detect when this
+               happens, and use a hackish means to create a reasonable-as-possible
+               'display mode'.  -- DavidL
+            */
+            if (adapterIndex == 0 && outputIndex == 0) {
+                SDL_VideoDisplay display;
+                SDL_DisplayMode mode;
+#if SDL_WINRT_USE_APPLICATIONVIEW
+                ApplicationView ^ appView = ApplicationView::GetForCurrentView();
+#endif
+                CoreWindow ^ coreWin = CoreWindow::GetForCurrentThread();
+                SDL_zero(display);
+                SDL_zero(mode);
+                display.name = "DXGI Display-detection Workaround";
+
+                /* HACK: ApplicationView's VisibleBounds property, appeared, via testing, to
+                   give a better approximation of display-size, than did CoreWindow's
+                   Bounds property, insofar that ApplicationView::VisibleBounds seems like
+                   it will, at least some of the time, give the full display size (during the
+                   failing test), whereas CoreWindow might not.  -- DavidL
+                */
+
+#if (NTDDI_VERSION >= NTDDI_WIN10) || (SDL_WINRT_USE_APPLICATIONVIEW && WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP)
+                mode.w = WINRT_DIPS_TO_PHYSICAL_PIXELS(appView->VisibleBounds.Width);
+                mode.h = WINRT_DIPS_TO_PHYSICAL_PIXELS(appView->VisibleBounds.Height);
+#else
+                /* On platform(s) that do not support VisibleBounds, such as Windows 8.1,
+                   fall back to CoreWindow's Bounds property.
+                */
+                mode.w = WINRT_DIPS_TO_PHYSICAL_PIXELS(coreWin->Bounds.Width);
+                mode.h = WINRT_DIPS_TO_PHYSICAL_PIXELS(coreWin->Bounds.Height);
+#endif
+
+                mode.format = DXGI_FORMAT_B8G8R8A8_UNORM;
+                mode.refresh_rate = 0;  /* Display mode is unknown, so just fill in zero, as specified by SDL's header files */
+                display.desktop_mode = mode;
+                display.current_mode = mode;
+                if ((SDL_AddDisplayMode(&display, &mode) < 0) ||
+                    (SDL_AddVideoDisplay(&display) < 0))
+                {
+                    return SDL_SetError("Failed to apply DXGI Display-detection workaround");
+                }
+            }
+
             break;
         }
     }
@@ -341,7 +396,6 @@ WINRT_InitModes(_THIS)
         return -1;
     }
 
-    int adapterIndex = 0;
     for (int adapterIndex = 0; ; ++adapterIndex) {
         if (WINRT_AddDisplaysForAdapter(_this, dxgiFactory2, adapterIndex) < 0) {
             break;
@@ -438,6 +492,7 @@ WINRT_DetectWindowFlags(SDL_Window * window)
     return latestFlags;
 }
 
+// TODO, WinRT: consider removing WINRT_UpdateWindowFlags, and just calling WINRT_DetectWindowFlags as-appropriate (with appropriate calls to SDL_SendWindowEvent)
 void
 WINRT_UpdateWindowFlags(SDL_Window * window, Uint32 mask)
 {
@@ -451,6 +506,32 @@ WINRT_UpdateWindowFlags(SDL_Window * window, Uint32 mask)
     }
 }
 
+static bool
+WINRT_IsCoreWindowActive(CoreWindow ^ coreWindow)
+{
+    /* WinRT does not appear to offer API(s) to determine window-activation state,
+       at least not that I am aware of in Win8 - Win10.  As such, SDL tracks this
+       itself, via window-activation events.
+       
+       If there *is* an API to track this, it should probably get used instead
+       of the following hack (that uses "SDLHelperWindowActivationState").
+         -- DavidL.
+    */
+    if (coreWindow->CustomProperties->HasKey("SDLHelperWindowActivationState")) {
+        CoreWindowActivationState activationState = \
+            safe_cast<CoreWindowActivationState>(coreWindow->CustomProperties->Lookup("SDLHelperWindowActivationState"));
+        return (activationState != CoreWindowActivationState::Deactivated);
+    }
+
+    /* Assume that non-SDL tracked windows are active, although this should
+       probably be avoided, if possible.
+       
+       This might not even be possible, in normal SDL use, at least as of
+       this writing (Dec 22, 2015; via latest hg.libsdl.org/SDL clone)  -- DavidL
+    */
+    return true;
+}
+
 int
 WINRT_CreateWindow(_THIS, SDL_Window * window)
 {
@@ -591,12 +672,7 @@ WINRT_CreateWindow(_THIS, SDL_Window * window)
         );
 
         /* Try detecting if the window is active */
-        bool isWindowActive = true;     /* Presume the window is active, unless we've been told otherwise */
-        if (data->coreWindow->CustomProperties->HasKey("SDLHelperWindowActivationState")) {
-            CoreWindowActivationState activationState = \
-                safe_cast<CoreWindowActivationState>(data->coreWindow->CustomProperties->Lookup("SDLHelperWindowActivationState"));
-            isWindowActive = (activationState != CoreWindowActivationState::Deactivated);
-        }
+        bool isWindowActive = WINRT_IsCoreWindowActive(data->coreWindow.Get());
         if (isWindowActive) {
             SDL_SetKeyboardFocus(window);
         }
@@ -627,13 +703,16 @@ WINRT_SetWindowFullscreen(_THIS, SDL_Window * window, SDL_VideoDisplay * display
 {
 #if NTDDI_VERSION >= NTDDI_WIN10
     SDL_WindowData * data = (SDL_WindowData *)window->driverdata;
-    if (fullscreen) {
-        if (!data->appView->IsFullScreenMode) {
-            data->appView->TryEnterFullScreenMode();    // TODO, WinRT: return failure (to caller?) from TryEnterFullScreenMode()
-        }
-    } else {
-        if (data->appView->IsFullScreenMode) {
-            data->appView->ExitFullScreenMode();
+    bool isWindowActive = WINRT_IsCoreWindowActive(data->coreWindow.Get());
+    if (isWindowActive) {
+        if (fullscreen) {
+            if (!data->appView->IsFullScreenMode) {
+                data->appView->TryEnterFullScreenMode();    // TODO, WinRT: return failure (to caller?) from TryEnterFullScreenMode()
+            }
+        } else {
+            if (data->appView->IsFullScreenMode) {
+                data->appView->ExitFullScreenMode();
+            }
         }
     }
 #endif

+ 3 - 20
libs/SDL2/src/video/x11/SDL_x11events.c

@@ -348,27 +348,10 @@ X11_ReconcileKeyboardState(_THIS)
 
     X11_XQueryKeymap(display, keys);
 
-    /* Get the keyboard modifier state */
+    /* Sync up the keyboard modifier state */
     if (X11_XQueryPointer(display, DefaultRootWindow(display), &junk_window, &junk_window, &x, &y, &x, &y, &mask)) {
-        unsigned num_mask = X11_GetNumLockModifierMask(_this);
-        const Uint8 *keystate = SDL_GetKeyboardState(NULL);
-        Uint8 capslockState = keystate[SDL_SCANCODE_CAPSLOCK];
-        Uint8 numlockState = keystate[SDL_SCANCODE_NUMLOCKCLEAR];
-
-        /* Toggle key mod state if needed */
-        if (!!(mask & LockMask) != !!(SDL_GetModState() & KMOD_CAPS)) {
-            SDL_SendKeyboardKey(SDL_PRESSED, SDL_SCANCODE_CAPSLOCK);
-            if (capslockState == SDL_RELEASED) {
-                SDL_SendKeyboardKey(SDL_RELEASED, SDL_SCANCODE_CAPSLOCK);
-            }
-        }
-
-        if (!!(mask & num_mask) != !!(SDL_GetModState() & KMOD_NUM)) {
-            SDL_SendKeyboardKey(SDL_PRESSED, SDL_SCANCODE_NUMLOCKCLEAR);
-            if (numlockState == SDL_RELEASED) {
-                SDL_SendKeyboardKey(SDL_RELEASED, SDL_SCANCODE_NUMLOCKCLEAR);
-            }
-        }
+        SDL_ToggleModState(KMOD_CAPS, (mask & LockMask) != 0);
+        SDL_ToggleModState(KMOD_NUM, (mask & X11_GetNumLockModifierMask(_this)) != 0);
     }
 
     for (keycode = 0; keycode < 256; ++keycode) {

+ 4 - 5
libs/SDL2/src/video/x11/SDL_x11modes.c

@@ -376,8 +376,7 @@ X11_InitModes_XRandR(_THIS)
         for (screen = 0; screen < screencount; screen++) {
 
             /* we want the primary output first, and then skipped later. */
-            if ((looking_for_primary && (screen != default_screen)) ||
-                (!looking_for_primary && (screen == default_screen))) {
+            if (looking_for_primary && (screen != default_screen)) {
                 continue;
             }
 
@@ -421,7 +420,7 @@ X11_InitModes_XRandR(_THIS)
                 XRRCrtcInfo *crtc;
 
                 /* The primary output _should_ always be sorted first, but just in case... */
-                if ((looking_for_primary && ((screen != default_screen) || (res->outputs[output] != primary))) ||
+                if ((looking_for_primary && (res->outputs[output] != primary)) ||
                     (!looking_for_primary && (screen == default_screen) && (res->outputs[output] == primary))) {
                     continue;
                 }
@@ -491,11 +490,11 @@ X11_InitModes_XRandR(_THIS)
                 display.driverdata = displaydata;
                 SDL_AddVideoDisplay(&display);
             }
+
+            X11_XRRFreeScreenResources(res);
         }
     }
 
-    X11_XRRFreeScreenResources(res);
-
     if (_this->num_displays == 0) {
         return SDL_SetError("No available displays");
     }

+ 1 - 3
libs/SDL2/test/README

@@ -5,11 +5,9 @@ These are test programs for the SDL library:
 	loopwave	Audio test -- loop playing a WAV file
 	loopwavequeue	Audio test -- loop playing a WAV file with SDL_QueueAudio
 	testaudioinfo	Lists audio device capabilities
-	testcdrom	Sample audio CD control program
 	testerror	Tests multi-threaded error handling
 	testfile	Tests RWops layer
 	testgl2		A very simple example of using OpenGL with SDL
-	testhread	Hacked up test of multi-threading
 	testiconv	Tests international string conversion
 	testjoystick	List joysticks and watch joystick events
 	testkeys	List the available keyboard keys
@@ -17,11 +15,11 @@ These are test programs for the SDL library:
 	testlock	Hacked up test of multi-threading and locking
 	testmultiaudio	Tests using several audio devices
 	testoverlay2	Tests the overlay flickering/scaling during playback.
-	testpalette	Tests palette color cycling
 	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

+ 1 - 1
libs/SDL2/test/autogen.sh

@@ -232,7 +232,7 @@ WatchJoystick(SDL_Joystick * joystick)
             if (SDL_PollEvent(&event)) {
                 switch (event.type) {
                 case SDL_JOYAXISMOTION:
-                    if (event.jaxis.value > 20000 || event.jaxis.value < -20000) {
+                    if ((event.jaxis.value > 20000 || event.jaxis.value < -20000) && event.jaxis.value != -32768) {
                         for (_s = 0; _s < s; _s++) {
                             if (steps[_s].axis == event.jaxis.axis) {
                                 break;

+ 1 - 1
libs/SDL2/test/gcc-fat.sh

@@ -10,7 +10,7 @@
   freely.
 */
 
-/* Program to load a wave file and loop playing it using SDL sound */
+/* 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

+ 1 - 1
libs/SDL2/test/testfilesystem.c

@@ -9,7 +9,7 @@
   including commercial applications, and to alter it and redistribute it
   freely.
 */
-/* Simple test of power subsystem. */
+/* Simple test of filesystem functions. */
 
 #include <stdio.h>
 #include "SDL.h"

+ 1 - 1
libs/SDL2/test/testgl2.c

@@ -59,7 +59,7 @@ static int LoadContext(GL_Context * data)
             return SDL_SetError("Couldn't load GL function %s: %s\n", #func, SDL_GetError()); \
         } \
     } while ( 0 );
-#endif /* _SDL_NOGETPROCADDR_ */
+#endif /* __SDL_NOGETPROCADDR__ */
 
 #include "../src/render/opengl/SDL_glfuncs.h"
 #undef SDL_PROC

+ 1 - 1
libs/SDL2/test/testgles2.c

@@ -61,7 +61,7 @@ static int LoadContext(GLES2_Context * data)
             return SDL_SetError("Couldn't load GLES2 function %s: %s\n", #func, SDL_GetError()); \
         } \
     } while ( 0 );
-#endif /* _SDL_NOGETPROCADDR_ */
+#endif /* __SDL_NOGETPROCADDR__ */
 
 #include "../src/render/opengles2/SDL_gles2funcs.h"
 #undef SDL_PROC

+ 1 - 1
libs/SDL2/test/testspriteminimal.c

@@ -184,7 +184,7 @@ main(int argc, char *argv[])
 #else
     while (!done) {
         loop();
-        }
+    }
 #endif
     quit(0);
 

+ 0 - 0
libs/SDL2/visualtest/COPYING.txt