SDL: main: Added _optional_ callback entry points.

From 9c664b00623926a0973a8f19cecc55bc7c757d5b Mon Sep 17 00:00:00 2001
From: "Ryan C. Gordon" <[EMAIL REDACTED]>
Date: Wed, 1 Nov 2023 18:40:41 -0400
Subject: [PATCH] main: Added _optional_ callback entry points.

This lets apps optionally have a handful of callbacks for their entry points instead of a single main function. If used, the actual main/SDL_main/whatever entry point will be implemented in the single-header library SDL_main.h and the app will implement four separate functions:

First:

    int SDL_AppInit(int argc, char **argv);

This will be called once before anything else. argc/argv work like they always do. If this returns 0, the app runs. If it returns < 0, the app calls SDL_AppQuit and terminates with an exit code that reports an error to the platform. If it returns > 0, the app calls SDL_AppQuit and terminates with an exit code that reports success to the platform. This function should not go into an infinite mainloop; it should do any one-time startup it requires and then return.

Then:

     int SDL_AppIterate(void);

This is called over and over, possibly at the refresh rate of the display or some other metric that the platform dictates. This is where the heart of your app runs. It should return as quickly as reasonably possible, but it's not a "run one memcpy and that's all the time you have" sort of thing. The app should do any game updates, and render a frame of video. If it returns < 0, SDL will call SDL_AppQuit and terminate the process with an exit code that reports an error to the platform. If it returns > 0, the app calls SDL_AppQuit and terminates with an exit code that reports success to the platform. If it returns 0, then SDL_AppIterate will be called again at some regular frequency. The platform may choose to run this more or less (perhaps less in the background, etc), or it might just call this function in a loop as fast as possible. You do not check the event queue in this function (SDL_AppEvent exists for that).

Next:

    int SDL_AppEvent(const SDL_Event *event);

This will be called once for each event pushed into the SDL queue. This may be called from any thread, and possibly in parallel to SDL_AppIterate. The fields in event do not need to be free'd (as you would normally need to do for SDL_EVENT_DROP_FILE, etc), and your app should not call SDL_PollEvent, SDL_PumpEvent, etc, as SDL will manage this for you. Return values are the same as from SDL_AppIterate(), so you can terminate in response to SDL_EVENT_QUIT, etc.

Finally:

    void SDL_AppQuit(void);

This is called once before terminating the app--assuming the app isn't being forcibly killed or crashed--as a last chance to clean up. After this returns, SDL will call SDL_Quit so the app doesn't have to (but it's safe for the app to call it, too). Process termination proceeds as if the app returned normally from main(), so atexit handles will run, if your platform supports that.

The app does not implement SDL_main if using this. To turn this on, define SDL_MAIN_USE_CALLBACKS before including SDL_main.h. Defines like SDL_MAIN_HANDLED and SDL_MAIN_NOIMPL are also respected for callbacks, if the app wants to do some sort of magic main implementation thing.

In theory, on most platforms these can be implemented in the app itself, but this saves some #ifdefs in the app and lets everyone struggle less against some platforms, and might be more efficient in the long run, too.

On some platforms, it's possible this is the only reasonable way to go, but we haven't actually hit one that 100% requires it yet (but we will, if we want to write a RetroArch backend, for example).

Using the callback entry points works on every platform, because on platforms that don't require them, we can fake them with a simple loop in an internal implementation of the usual SDL_main.

The primary way we expect people to write SDL apps is with SDL_main, and this is not intended to replace it. If the app chooses to use this, it just removes some platform-specific details they might have to otherwise manage, and maybe removes a barrier to entry on some future platform.

Fixes #6785.
Reference PR #8247.
---
 CMakeLists.txt                              |  17 +
 VisualC-GDK/SDL/SDL.vcxproj                 |   3 +
 VisualC-GDK/SDL/SDL.vcxproj.filters         |  15 +
 VisualC-WinRT/SDL-UWP.vcxproj               |   3 +
 VisualC-WinRT/SDL-UWP.vcxproj.filters       |  15 +
 VisualC/SDL/SDL.vcxproj                     |   3 +
 VisualC/SDL/SDL.vcxproj.filters             |  15 +
 Xcode/SDL/SDL.xcodeproj/project.pbxproj     |  27 +
 include/SDL3/SDL_hints.h                    |  16 +
 include/SDL3/SDL_main.h                     | 224 +++++++-
 include/SDL3/SDL_main_impl.h                |  26 +
 include/SDL3/SDL_test_common.h              |  16 +-
 src/dynapi/SDL_dynapi.sym                   |   1 +
 src/dynapi/SDL_dynapi_overrides.h           |   1 +
 src/dynapi/SDL_dynapi_procs.h               |   1 +
 src/main/SDL_main_callbacks.c               | 114 ++++
 src/main/SDL_main_callbacks.h               |  31 ++
 src/main/emscripten/SDL_sysmain_callbacks.c |  47 ++
 src/main/generic/SDL_sysmain_callbacks.c    |  80 +++
 src/main/ios/SDL_sysmain_callbacks.m        |  82 +++
 src/test/SDL_test_common.c                  |  21 +-
 test/CMakeLists.txt                         |  23 +-
 test/loopwave.c                             | 112 ++--
 test/testaudio.c                            | 543 ++++++++++----------
 test/testaudiocapture.c                     | 177 +++----
 test/testsprite.c                           |  63 +--
 26 files changed, 1151 insertions(+), 525 deletions(-)
 create mode 100644 src/main/SDL_main_callbacks.c
 create mode 100644 src/main/SDL_main_callbacks.h
 create mode 100644 src/main/emscripten/SDL_sysmain_callbacks.c
 create mode 100644 src/main/generic/SDL_sysmain_callbacks.c
 create mode 100644 src/main/ios/SDL_sysmain_callbacks.m

diff --git a/CMakeLists.txt b/CMakeLists.txt
index 3bfd22464056..dd24bbfb512f 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -475,6 +475,7 @@ sdl_glob_sources(
   "${SDL3_SOURCE_DIR}/src/hidapi/*.c"
   "${SDL3_SOURCE_DIR}/src/libm/*.c"
   "${SDL3_SOURCE_DIR}/src/locale/*.c"
+  "${SDL3_SOURCE_DIR}/src/main/*.c"
   "${SDL3_SOURCE_DIR}/src/misc/*.c"
   "${SDL3_SOURCE_DIR}/src/power/*.c"
   "${SDL3_SOURCE_DIR}/src/render/*.c"
@@ -1383,6 +1384,9 @@ elseif(EMSCRIPTEN)
   # project. Uncomment at will for verbose cross-compiling -I/../ path info.
   sdl_compile_options(PRIVATE "-Wno-warn-absolute-paths")
 
+  sdl_glob_sources("${SDL3_SOURCE_DIR}/src/main/emscripten/*.c")
+  set(HAVE_SDL_MAIN_CALLBACKS TRUE)
+
   if(SDL_MISC)
     sdl_glob_sources("${SDL3_SOURCE_DIR}/src/misc/emscripten/*.c")
     set(HAVE_SDL_MISC TRUE)
@@ -2033,6 +2037,8 @@ elseif(WINDOWS)
 elseif(APPLE)
   # TODO: rework this all for proper macOS, iOS and Darwin support
 
+  # !!! FIXME: all the `if(IOS OR TVOS OR VISIONOS)` checks should get merged into one variable, so we're ready for the next platform (or just WatchOS).
+
   # We always need these libs on macOS at the moment.
   # !!! FIXME: we need Carbon for some very old API calls in
   # !!! FIXME:  src/video/cocoa/SDL_cocoakeyboard.c, but we should figure out
@@ -2044,6 +2050,12 @@ elseif(APPLE)
   set(SDL_FRAMEWORK_FOUNDATION 1)
   set(SDL_FRAMEWORK_COREVIDEO 1)
 
+  # iOS can use a CADisplayLink for main callbacks. macOS just uses the generic one atm.
+  if(IOS OR TVOS OR VISIONOS)
+    sdl_glob_sources("${SDL3_SOURCE_DIR}/src/main/ios/*.m")
+    set(HAVE_SDL_MAIN_CALLBACKS TRUE)
+  endif()
+
   # Requires the darwin file implementation
   if(SDL_FILE)
     sdl_glob_sources("${SDL3_SOURCE_DIR}/src/file/cocoa/*.m")
@@ -2803,6 +2815,11 @@ if(NOT HAVE_SDL_TIMERS)
   sdl_glob_sources("${SDL3_SOURCE_DIR}/src/timer/dummy/*.c")
 endif()
 
+# Most platforms use this.
+if(NOT HAVE_SDL_MAIN_CALLBACKS)
+  sdl_glob_sources("${SDL3_SOURCE_DIR}/src/main/generic/*.c")
+endif()
+
 # config variables may contain generator expression, so we need to generate SDL_build_config.h in 2 steps:
 # 1. replace all `#cmakedefine`'s and `@abc@`
 configure_file("${SDL3_SOURCE_DIR}/include/build_config/SDL_build_config.h.cmake"
diff --git a/VisualC-GDK/SDL/SDL.vcxproj b/VisualC-GDK/SDL/SDL.vcxproj
index 70b625b37f42..b19bb5fba48e 100644
--- a/VisualC-GDK/SDL/SDL.vcxproj
+++ b/VisualC-GDK/SDL/SDL.vcxproj
@@ -418,6 +418,7 @@
     <ClInclude Include="..\..\src\libm\math_libm.h" />
     <ClInclude Include="..\..\src\libm\math_private.h" />
     <ClInclude Include="..\..\src\locale\SDL_syslocale.h" />
+    <ClInclude Include="..\..\src\main\SDL_main_callbacks.h" />
     <ClInclude Include="..\..\src\misc\SDL_sysurl.h" />
     <ClInclude Include="..\..\src\power\SDL_syspower.h" />
     <ClInclude Include="..\..\src\render\direct3d11\SDL_shaders_d3d11.h" />
@@ -468,6 +469,8 @@
       <PrecompiledHeaderOutputFile Condition="'$(Configuration)|$(Platform)'=='Debug|Gaming.Desktop.x64'">$(IntDir)$(TargetName)_cpp.pch</PrecompiledHeaderOutputFile>
       <PrecompiledHeaderOutputFile Condition="'$(Configuration)|$(Platform)'=='Release|Gaming.Desktop.x64'">$(IntDir)$(TargetName)_cpp.pch</PrecompiledHeaderOutputFile>
     </ClCompile>
+    <ClCompile Include="..\..\src\main\generic\SDL_sysmain_callbacks.c" />
+    <ClCompile Include="..\..\src\main\SDL_main_callbacks.c" />
     <ClCompile Include="..\..\src\SDL_guid.c" />
     <ClInclude Include="..\..\src\SDL_hashtable.h" />
     <ClInclude Include="..\..\src\SDL_hints_c.h" />
diff --git a/VisualC-GDK/SDL/SDL.vcxproj.filters b/VisualC-GDK/SDL/SDL.vcxproj.filters
index a530ef1bfa18..ba454f428fe1 100644
--- a/VisualC-GDK/SDL/SDL.vcxproj.filters
+++ b/VisualC-GDK/SDL/SDL.vcxproj.filters
@@ -175,6 +175,12 @@
     <Filter Include="video\gdk">
       <UniqueIdentifier>{3ad16a8a-0ed8-439c-a771-383af2e2867f}</UniqueIdentifier>
     </Filter>
+    <Filter Include="main">
+      <UniqueIdentifier>{00002ddb6c5ea921181bf32d50e40000}</UniqueIdentifier>
+    </Filter>
+    <Filter Include="main\generic">
+      <UniqueIdentifier>{00000a808f8ba6b489985f82a4e80000}</UniqueIdentifier>
+    </Filter>
   </ItemGroup>
   <ItemGroup>
     <ClInclude Include="..\..\include\SDL3\SDL_begin_code.h">
@@ -399,6 +405,9 @@
     <ClInclude Include="..\..\include\SDL3\SDL_vulkan.h">
       <Filter>API Headers</Filter>
     </ClInclude>
+    <ClInclude Include="..\..\src\main\SDL_main_callbacks.h">
+      <Filter>main</Filter>
+    </ClInclude>
     <ClInclude Include="..\..\src\SDL_error_c.h" />
     <ClInclude Include="..\..\src\SDL_hashtable.h" />
     <ClInclude Include="..\..\src\SDL_list.h" />
@@ -846,6 +855,12 @@
   </ItemGroup>
   <ItemGroup>
     <ClCompile Include="..\..\src\audio\wasapi\SDL_wasapi.c" />
+    <ClCompile Include="..\..\src\main\generic\SDL_sysmain_callbacks.c">
+      <Filter>main\generic</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\src\main\SDL_main_callbacks.c">
+      <Filter>main</Filter>
+    </ClCompile>
     <ClCompile Include="..\..\src\SDL.c" />
     <ClCompile Include="..\..\src\SDL_assert.c" />
     <ClCompile Include="..\..\src\SDL_error.c" />
diff --git a/VisualC-WinRT/SDL-UWP.vcxproj b/VisualC-WinRT/SDL-UWP.vcxproj
index 21c5e7ebba22..0dee306b691f 100644
--- a/VisualC-WinRT/SDL-UWP.vcxproj
+++ b/VisualC-WinRT/SDL-UWP.vcxproj
@@ -133,6 +133,7 @@
     <ClInclude Include="..\src\joystick\windows\SDL_windowsjoystick_c.h" />
     <ClInclude Include="..\src\joystick\windows\SDL_xinputjoystick_c.h" />
     <ClInclude Include="..\src\locale\SDL_syslocale.h" />
+    <ClInclude Include="..\src\main\SDL_main_callbacks.h" />
     <ClInclude Include="..\src\render\direct3d11\SDL_render_winrt.h" />
     <ClInclude Include="..\src\render\direct3d11\SDL_shaders_d3d11.h" />
     <ClInclude Include="..\src\render\opengles2\SDL_gles2funcs.h" />
@@ -337,6 +338,8 @@
     <ClCompile Include="..\src\loadso\windows\SDL_sysloadso.c" />
     <ClCompile Include="..\src\locale\SDL_locale.c" />
     <ClCompile Include="..\src\locale\winrt\SDL_syslocale.c" />
+    <ClCompile Include="..\src\main\generic\SDL_sysmain_callbacks.c" />
+    <ClCompile Include="..\src\main\SDL_main_callbacks.c" />
     <ClCompile Include="..\src\misc\SDL_url.c" />
     <ClCompile Include="..\src\misc\winrt\SDL_sysurl.cpp">
       <CompileAsWinRT>true</CompileAsWinRT>
diff --git a/VisualC-WinRT/SDL-UWP.vcxproj.filters b/VisualC-WinRT/SDL-UWP.vcxproj.filters
index 430babceb123..7d765c13c113 100644
--- a/VisualC-WinRT/SDL-UWP.vcxproj.filters
+++ b/VisualC-WinRT/SDL-UWP.vcxproj.filters
@@ -7,6 +7,12 @@
     <Filter Include="Source Files">
       <UniqueIdentifier>{68e1b30b-19ed-4612-93e4-6260c5a979e5}</UniqueIdentifier>
     </Filter>
+    <Filter Include="main">
+      <UniqueIdentifier>{00004a2523fc69c7128c60648c860000}</UniqueIdentifier>
+    </Filter>
+    <Filter Include="main\generic">
+      <UniqueIdentifier>{0000318d975e0a2867ab1d5727bf0000}</UniqueIdentifier>
+    </Filter>
   </ItemGroup>
   <ItemGroup>
     <ClInclude Include="..\include\SDL3\SDL_begin_code.h">
@@ -270,6 +276,9 @@
     <ClInclude Include="..\src\joystick\windows\SDL_xinputjoystick_c.h">
       <Filter>Source Files</Filter>
     </ClInclude>
+    <ClInclude Include="..\src\main\SDL_main_callbacks.h">
+      <Filter>main</Filter>
+    </ClInclude>
     <ClInclude Include="..\src\render\direct3d11\SDL_render_winrt.h">
       <Filter>Source Files</Filter>
     </ClInclude>
@@ -588,6 +597,12 @@
     <ClCompile Include="..\src\loadso\windows\SDL_sysloadso.c">
       <Filter>Source Files</Filter>
     </ClCompile>
+    <ClCompile Include="..\src\main\generic\SDL_sysmain_callbacks.c">
+      <Filter>main\generic</Filter>
+    </ClCompile>
+    <ClCompile Include="..\src\main\SDL_main_callbacks.c">
+      <Filter>main</Filter>
+    </ClCompile>
     <ClCompile Include="..\src\power\SDL_power.c">
       <Filter>Source Files</Filter>
     </ClCompile>
diff --git a/VisualC/SDL/SDL.vcxproj b/VisualC/SDL/SDL.vcxproj
index 84e774521acc..57eb07e85ca1 100644
--- a/VisualC/SDL/SDL.vcxproj
+++ b/VisualC/SDL/SDL.vcxproj
@@ -368,6 +368,7 @@
     <ClInclude Include="..\..\src\libm\math_libm.h" />
     <ClInclude Include="..\..\src\libm\math_private.h" />
     <ClInclude Include="..\..\src\locale\SDL_syslocale.h" />
+    <ClInclude Include="..\..\src\main\SDL_main_callbacks.h" />
     <ClInclude Include="..\..\src\misc\SDL_sysurl.h" />
     <ClInclude Include="..\..\src\power\SDL_syspower.h" />
     <ClInclude Include="..\..\src\render\direct3d11\SDL_shaders_d3d11.h" />
@@ -397,6 +398,8 @@
       <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">Create</PrecompiledHeader>
       <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|x64'">Create</PrecompiledHeader>
     </ClCompile>
+    <ClCompile Include="..\..\src\main\generic\SDL_sysmain_callbacks.c" />
+    <ClCompile Include="..\..\src\main\SDL_main_callbacks.c" />
     <ClCompile Include="..\..\src\SDL_guid.c" />
     <ClInclude Include="..\..\src\SDL_hashtable.h" />
     <ClInclude Include="..\..\src\SDL_hints_c.h" />
diff --git a/VisualC/SDL/SDL.vcxproj.filters b/VisualC/SDL/SDL.vcxproj.filters
index 23fa7b2e3ffd..cd7b2b2e3e17 100644
--- a/VisualC/SDL/SDL.vcxproj.filters
+++ b/VisualC/SDL/SDL.vcxproj.filters
@@ -169,6 +169,12 @@
     <Filter Include="render\direct3d12">
       <UniqueIdentifier>{f48c2b17-1bee-4fec-a7c8-24cf619abe08}</UniqueIdentifier>
     </Filter>
+    <Filter Include="main">
+      <UniqueIdentifier>{00001967ea2801028a046a722a070000}</UniqueIdentifier>
+    </Filter>
+    <Filter Include="main\generic">
+      <UniqueIdentifier>{0000ddc7911820dbe64274d3654f0000}</UniqueIdentifier>
+    </Filter>
   </ItemGroup>
   <ItemGroup>
     <ClInclude Include="..\..\include\SDL3\SDL_begin_code.h">
@@ -390,6 +396,9 @@
     <ClInclude Include="..\..\include\SDL3\SDL_vulkan.h">
       <Filter>API Headers</Filter>
     </ClInclude>
+    <ClInclude Include="..\..\src\main\SDL_main_callbacks.h">
+      <Filter>main</Filter>
+    </ClInclude>
     <ClInclude Include="..\..\src\SDL_error_c.h" />
     <ClInclude Include="..\..\src\SDL_hashtable.h" />
     <ClInclude Include="..\..\src\SDL_list.h" />
@@ -828,6 +837,12 @@
   </ItemGroup>
   <ItemGroup>
     <ClCompile Include="..\..\src\audio\wasapi\SDL_wasapi.c" />
+    <ClCompile Include="..\..\src\main\generic\SDL_sysmain_callbacks.c">
+      <Filter>main\generic</Filter>
+    </ClCompile>
+    <ClCompile Include="..\..\src\main\SDL_main_callbacks.c">
+      <Filter>main</Filter>
+    </ClCompile>
     <ClCompile Include="..\..\src\SDL.c" />
     <ClCompile Include="..\..\src\SDL_assert.c" />
     <ClCompile Include="..\..\src\SDL_error.c" />
diff --git a/Xcode/SDL/SDL.xcodeproj/project.pbxproj b/Xcode/SDL/SDL.xcodeproj/project.pbxproj
index 279a74856b0f..bd32ee428903 100644
--- a/Xcode/SDL/SDL.xcodeproj/project.pbxproj
+++ b/Xcode/SDL/SDL.xcodeproj/project.pbxproj
@@ -34,6 +34,7 @@
 
 /* Begin PBXBuildFile section */
 		000040E76FDC6AE48CBF0000 /* SDL_hashtable.c in Sources */ = {isa = PBXBuildFile; fileRef = 000078E1881E857EBB6C0000 /* SDL_hashtable.c */; };
+		0000A4DA2F45A31DC4F00000 /* SDL_sysmain_callbacks.m in Sources */ = {isa = PBXBuildFile; fileRef = 0000BB287BA0A0178C1A0000 /* SDL_sysmain_callbacks.m */; platformFilters = (ios, maccatalyst, macos, tvos, watchos, ); };
 		007317A40858DECD00B2BC32 /* Cocoa.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 0073179D0858DECD00B2BC32 /* Cocoa.framework */; platformFilters = (macos, ); };
 		007317A60858DECD00B2BC32 /* IOKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 0073179F0858DECD00B2BC32 /* IOKit.framework */; platformFilters = (ios, maccatalyst, macos, ); };
 		00CFA89D106B4BA100758660 /* ForceFeedback.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 00CFA89C106B4BA100758660 /* ForceFeedback.framework */; platformFilters = (macos, ); };
@@ -476,6 +477,8 @@
 		F3F7D9E12933074E00816151 /* SDL_begin_code.h in Headers */ = {isa = PBXBuildFile; fileRef = F3F7D8E72933074E00816151 /* SDL_begin_code.h */; settings = {ATTRIBUTES = (Public, ); }; };
 		F3F7D9E52933074E00816151 /* SDL_system.h in Headers */ = {isa = PBXBuildFile; fileRef = F3F7D8E82933074E00816151 /* SDL_system.h */; settings = {ATTRIBUTES = (Public, ); }; };
 		FA73671D19A540EF004122E4 /* CoreVideo.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = FA73671C19A540EF004122E4 /* CoreVideo.framework */; platformFilters = (ios, maccatalyst, macos, tvos, watchos, ); };
+		000028F8113A53F4333E0000 /* SDL_main_callbacks.c in Sources */ = {isa = PBXBuildFile; fileRef = 00009366FB9FBBD54C390000 /* SDL_main_callbacks.c */; };
+		0000C3B22D46279F99170000 /* SDL_main_callbacks.h in Headers */ = {isa = PBXBuildFile; fileRef = 00003260407E1002EAC10000 /* SDL_main_callbacks.h */; };
 /* End PBXBuildFile section */
 
 /* Begin PBXContainerItemProxy section */
@@ -504,6 +507,7 @@
 /* Begin PBXFileReference section */
 		000078E1881E857EBB6C0000 /* SDL_hashtable.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = SDL_hashtable.c; sourceTree = "<group>"; };
 		0000B6ADCD88CAD6610F0000 /* SDL_hashtable.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SDL_hashtable.h; sourceTree = "<group>"; };
+		0000BB287BA0A0178C1A0000 /* SDL_sysmain_callbacks.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SDL_sysmain_callbacks.m; sourceTree = "<group>"; };
 		0073179D0858DECD00B2BC32 /* Cocoa.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Cocoa.framework; path = System/Library/Frameworks/Cocoa.framework; sourceTree = SDKROOT; };
 		0073179F0858DECD00B2BC32 /* IOKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = IOKit.framework; path = System/Library/Frameworks/IOKit.framework; sourceTree = SDKROOT; };
 		007317C10858E15000B2BC32 /* Carbon.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Carbon.framework; path = System/Library/Frameworks/Carbon.framework; sourceTree = SDKROOT; };
@@ -977,6 +981,8 @@
 		F59C710600D5CB5801000001 /* SDL.info */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; path = SDL.info; sourceTree = "<group>"; };
 		F5A2EF3900C6A39A01000001 /* BUGS.txt */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; name = BUGS.txt; path = ../../BUGS.txt; sourceTree = SOURCE_ROOT; };
 		FA73671C19A540EF004122E4 /* CoreVideo.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreVideo.framework; path = System/Library/Frameworks/CoreVideo.framework; sourceTree = SDKROOT; };
+		00009366FB9FBBD54C390000 /* SDL_main_callbacks.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; name = SDL_main_callbacks.c; path = SDL_main_callbacks.c; sourceTree = "<group>"; };
+		00003260407E1002EAC10000 /* SDL_main_callbacks.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = SDL_main_callbacks.h; path = SDL_main_callbacks.h; sourceTree = "<group>"; };
 /* End PBXFileReference section */
 
 /* Begin PBXFrameworksBuildPhase section */
@@ -1002,6 +1008,24 @@
 /* End PBXFrameworksBuildPhase section */
 
 /* Begin PBXGroup section */
+		000082EF09C89B62BD840000 /* main */ = {
+			isa = PBXGroup;
+			children = (
+				00008B5A0CB83D2069E80000 /* ios */,
+				00009366FB9FBBD54C390000 /* SDL_main_callbacks.c */,
+				00003260407E1002EAC10000 /* SDL_main_callbacks.h */,
+			);
+			path = main;
+			sourceTree = "<group>";
+		};
+		00008B5A0CB83D2069E80000 /* ios */ = {
+			isa = PBXGroup;
+			children = (
+				0000BB287BA0A0178C1A0000 /* SDL_sysmain_callbacks.m */,
+			);
+			path = ios;
+			sourceTree = "<group>";
+		};
 		0153844A006D81B07F000001 /* Public Headers */ = {
 			isa = PBXGroup;
 			children = (
@@ -1122,6 +1146,7 @@
 				A7D8A91123E2514000DCD162 /* libm */,
 				A7D8A85D23E2513F00DCD162 /* loadso */,
 				566E26CB246274AE00718109 /* locale */,
+				000082EF09C89B62BD840000 /* main */,
 				5616CA47252BB278005D5928 /* misc */,
 				A7D8A7DF23E2513F00DCD162 /* power */,
 				A7D8A8DA23E2514000DCD162 /* render */,
@@ -2614,6 +2639,8 @@
 				A7D8AB6123E2514100DCD162 /* SDL_offscreenwindow.c in Sources */,
 				566E26D8246274CC00718109 /* SDL_locale.c in Sources */,
 				000040E76FDC6AE48CBF0000 /* SDL_hashtable.c in Sources */,
+				0000A4DA2F45A31DC4F00000 /* SDL_sysmain_callbacks.m in Sources */,
+				000028F8113A53F4333E0000 /* SDL_main_callbacks.c in Sources */,
 			);
 			runOnlyForDeploymentPostprocessing = 0;
 		};
diff --git a/include/SDL3/SDL_hints.h b/include/SDL3/SDL_hints.h
index 01193b0cd905..2af3c88fff89 100644
--- a/include/SDL3/SDL_hints.h
+++ b/include/SDL3/SDL_hints.h
@@ -2531,6 +2531,22 @@ extern "C" {
  */
 #define SDL_HINT_AUDIO_DEVICE_SAMPLE_FRAMES "SDL_AUDIO_DEVICE_SAMPLE_FRAMES"
 
+
+/**
+ * Request SDL_AppIterate() be called at a specific rate.
+ *
+ * This number is in Hz, so "60" means try to iterate 60 times per second.
+ *
+ * On some platforms, or if you are using SDL_main instead of SDL_AppIterate,
+ * this hint is ignored. When the hint can be used, it is allowed to be
+ * changed at any time.
+ *
+ * This defaults to 60, and specifying NULL for the hint's value will restore
+ * the default.
+ */
+#define SDL_HINT_MAIN_CALLBACK_RATE "SDL_MAIN_CALLBACK_RATE"
+
+
 /**
  *  \brief  An enumeration of hint priorities
  */
diff --git a/include/SDL3/SDL_main.h b/include/SDL3/SDL_main.h
index 6181c0c01069..1833fa73f2f7 100644
--- a/include/SDL3/SDL_main.h
+++ b/include/SDL3/SDL_main.h
@@ -140,7 +140,7 @@
  *  \endcode
  */
 
-#if defined(SDL_MAIN_NEEDED) || defined(SDL_MAIN_AVAILABLE)
+#if defined(SDL_MAIN_NEEDED) || defined(SDL_MAIN_AVAILABLE) || defined(SDL_MAIN_USE_CALLBACKS)
 #define main    SDL_main
 #endif
 
@@ -149,11 +149,199 @@
 extern "C" {
 #endif
 
+union SDL_Event;
+typedef int (SDLCALL *SDL_AppInit_func)(int argc, char *argv[]);
+typedef int (SDLCALL *SDL_AppIterate_func)(void);
+typedef int (SDLCALL *SDL_AppEvent_func)(const union SDL_Event *event);
+typedef void (SDLCALL *SDL_AppQuit_func)(void);
+
+/**
+ * You can (optionally!) define SDL_MAIN_USE_CALLBACKS before including
+ * SDL_main.h, and then your application will _not_ have a standard
+ * "main" entry point. Instead, it will operate as a collection of
+ * functions that are called as necessary by the system. On some
+ * platforms, this is just a layer where SDL drives your program
+ * instead of your program driving SDL, on other platforms this might
+ * hook into the OS to manage the lifecycle. Programs on most platforms
+ * can use whichever approach they prefer, but the decision boils down
+ * to:
+ *
+ * - Using a standard "main" function: this works like it always has for
+ *   the past 50+ years in C programming, and your app is in control.
+ * - Using the callback functions: this might clean up some code,
+ *   avoid some #ifdef blocks in your program for some platforms, be more
+ *   resource-friendly to the system, and possibly be the primary way to
+ *   access some future platforms (but none require this at the moment).
+ *
+ * This is up to the app; both approaches are considered valid and supported
+ * ways to write SDL apps.
+ *
+ * If using the callbacks, don't define a "main" function. Instead, implement
+ * the functions listed below in your program.
+ */
+#ifdef SDL_MAIN_USE_CALLBACKS
+
+/**
+ * App-implemented initial entry point for SDL_MAIN_USE_CALLBACKS apps.
+ *
+ * Apps implement this function when using SDL_MAIN_USE_CALLBACKS. If
+ * using a standard "main" function, you should not supply this.
+ *
+ * This function is called by SDL once, at startup. The function should
+ * initialize whatever is necessary, possibly create windows and open
+ * audio devices, etc. The `argc` and `argv` parameters work like they would
+ * with a standard "main" function.
+ *
+ * This function should not go into an infinite mainloop; it should do any
+ * one-time setup it requires and then return.
+ *
+ * If this function returns 0, the app will proceed to normal operation,
+ * and will begin receiving repeated calls to SDL_AppIterate and SDL_AppEvent
+ * for the life of the program. If this function returns < 0, SDL will
+ * call SDL_AppQuit and terminate the process with an exit code that reports
+ * an error to the platform. If it returns > 0, the SDL calls SDL_AppQuit
+ * and terminates with an exit code that reports success to the platform.
+ *
+ * \param argc The standard ANSI C main's argc; number of elements in `argv`
+ * \param argv The standard ANSI C main's argv; array of command line arguments.
+ * \returns -1 to terminate with an error, 1 to terminate with success, 0 to continue.
+ *
+ * \threadsafety This function is not thread safe.
+ *
+ * \since This function is available since SDL 3.0.0.
+ *
+ * \sa SDL_AppIterate
+ * \sa SDL_AppEvent
+ * \sa SDL_AppQuit
+ */
+extern SDLMAIN_DECLSPEC int SDLCALL SDL_AppInit(int argc, char *argv[]);
+
+/**
+ * App-implemented iteration entry point for SDL_MAIN_USE_CALLBACKS apps.
+ *
+ * Apps implement this function when using SDL_MAIN_USE_CALLBACKS. If
+ * using a standard "main" function, you should not supply this.
+ *
+ * This function is called repeatedly by SDL after SDL_AppInit returns 0.
+ * The function should operate as a single iteration the program's primary
+ * loop; it should update whatever state it needs and draw a new frame of
+ * video, usually.
+ *
+ * On some platforms, this function will be called at the refresh rate of
+ * the display (which might change during the life of your app!). There are
+ * no promises made about what frequency this function might run at. You
+ * should use SDL's timer functions if you need to see how much time has
+ * passed since the last iteration.
+ *
+ * There is no need to process the SDL event queue during this function;
+ * SDL will send events as they arrive in SDL_AppEvent, and in most cases
+ * the event queue will be empty when this function runs anyhow.
+ *
+ * This function should not go into an infinite mainloop; it should do one
+ * iteration of whatever the program does and return.
+ *
+ * If this function returns 0, the app will continue normal operation,
+ * receiving repeated calls to SDL_AppIterate and SDL_AppEvent for the life
+ * of the program. If this function returns < 0, SDL will call SDL_AppQuit
+ * and terminate the process with an exit code that reports an error to the
+ * platform. If it returns > 0, the SDL calls SDL_AppQuit and terminates with
+ * an exit code that reports success to the platform.
+ *
+ * \returns -1 to terminate with an error, 1 to terminate with success, 0 to continue.
+ *
+ * \threadsafety This function is not thread safe.
+ *
+ * \since This function is available since SDL 3.0.0.
+ *
+ * \sa SDL_AppInit
+ * \sa SDL_AppEvent
+ * \sa SDL_AppQuit
+ */
+extern SDLMAIN_DECLSPEC int SDLCALL SDL_AppIterate(void);
+
+/**
+ * App-implemented event entry point for SDL_MAIN_USE_CALLBACKS apps.
+ *
+ * Apps implement this function when using SDL_MAIN_USE_CALLBACKS. If
+ * using a standard "main" function, you should not supply this.
+ *
+ * This function is called as needed by SDL after SDL_AppInit returns 0;
+ * It is called once for each new event.
+ *
+ * There is (currently) no guarantee about what thread this will be called
+ * from; whatever thread pushes an event onto SDL's queue will trigger this
+ * function. SDL is responsible for pumping the event queue between
+ * each call to SDL_AppIterate, so in normal operation one should only
+ * get events in a serial fashion, but be careful if you have a thread that
+ * explicitly calls SDL_PushEvent.
+ *
+ * Events sent to this function are not owned by the app; if you need to
+ * save the data, you should copy it.
+ *
+ * You do not need to free event data (such as the `file` string in
+ * SDL_EVENT_DROP_FILE), as SDL will free it once this function returns.
+ * Note that this is different than one might expect when using a standard
+ * "main" function!
+ *
+ * This function should not go into an infinite mainloop; it should handle
+ * the provided event appropriately and return.
+ *
+ * If this function returns 0, the app will continue normal operation,
+ * receiving repeated calls to SDL_AppIterate and SDL_AppEvent for the life
+ * of the program. If this function returns < 0, SDL will call SDL_AppQuit
+ * and terminate the process with an exit code that reports an error to the
+ * platform. If it returns > 0, the SDL calls SDL_AppQuit and terminates with
+ * an exit code that reports success to the platform.
+ *
+ * \returns -1 to terminate with an error, 1 to terminate with success, 0 to continue.
+ *
+ * \threadsafety This function is not thread safe.
+ *
+ * \since This function is available since SDL 3.0.0.
+ *
+ * \sa SDL_AppInit
+ * \sa SDL_AppIterate
+ * \sa SDL_AppQuit
+ */
+extern SDLMAIN_DECLSPEC int SDLCALL SDL_AppEvent(const SDL_Event *event);
+
+/**
+ * App-implemented deinit entry point for SDL_MAIN_USE_CALLBACKS apps.
+ *
+ * Apps implement this function when using SDL_MAIN_USE_CALLBACKS. If
+ * using a standard "main" function, you should not supply this.
+ *
+ * This function is called once by SDL before terminating the program.
+ *
+ * This function will be called no matter what, even if SDL_AppInit
+ * requests termination.
+ *
+ * This function should not go into an infinite mainloop; it should
+ * deinitialize any resources necessary, perform whatever shutdown
+ * activities, and return.
+ *
+ * You do not need to call SDL_Quit() in this function, as SDL will call
+ * it after this function returns 

(Patch may be truncated, please check the link at the top of this post.)