SDL: Add file dialogs

From 70c2e15615d7e5b9e39d67d02921a7d7c8254c01 Mon Sep 17 00:00:00 2001
From: Semphris <[EMAIL REDACTED]>
Date: Sun, 10 Mar 2024 17:27:42 -0400
Subject: [PATCH] Add file dialogs

---
 CMakeLists.txt                         |  25 +-
 VisualC/SDL/SDL.vcxproj                |   3 +-
 VisualC/SDL/SDL.vcxproj.filters        |   5 +-
 include/SDL3/SDL.h                     |   1 +
 include/SDL3/SDL_dialog.h              | 184 ++++++++++
 src/core/linux/SDL_dbus.c              |   2 +
 src/core/linux/SDL_dbus.h              |   5 +
 src/dialog/cocoa/SDL_cocoadialog.m     | 169 +++++++++
 src/dialog/dummy/SDL_dummydialog.c     |  41 +++
 src/dialog/haiku/SDL_haikudialog.cc    | 233 ++++++++++++
 src/dialog/unix/SDL_portaldialog.c     | 408 +++++++++++++++++++++
 src/dialog/unix/SDL_portaldialog.h     |  29 ++
 src/dialog/unix/SDL_unixdialog.c       |  85 +++++
 src/dialog/unix/SDL_zenitydialog.c     | 488 +++++++++++++++++++++++++
 src/dialog/unix/SDL_zenitydialog.h     |  29 ++
 src/dialog/windows/SDL_windowsdialog.c | 460 +++++++++++++++++++++++
 src/dynapi/SDL_dynapi.sym              |   3 +
 src/dynapi/SDL_dynapi_overrides.h      |   3 +
 src/dynapi/SDL_dynapi_procs.h          |   3 +
 test/CMakeLists.txt                    |   1 +
 test/testdialog.c                      | 161 ++++++++
 21 files changed, 2335 insertions(+), 3 deletions(-)
 create mode 100644 include/SDL3/SDL_dialog.h
 create mode 100644 src/dialog/cocoa/SDL_cocoadialog.m
 create mode 100644 src/dialog/dummy/SDL_dummydialog.c
 create mode 100644 src/dialog/haiku/SDL_haikudialog.cc
 create mode 100644 src/dialog/unix/SDL_portaldialog.c
 create mode 100644 src/dialog/unix/SDL_portaldialog.h
 create mode 100644 src/dialog/unix/SDL_unixdialog.c
 create mode 100644 src/dialog/unix/SDL_zenitydialog.c
 create mode 100644 src/dialog/unix/SDL_zenitydialog.h
 create mode 100644 src/dialog/windows/SDL_windowsdialog.c
 create mode 100644 test/testdialog.c

diff --git a/CMakeLists.txt b/CMakeLists.txt
index 3c09a00db511c..408c6e88dc0c3 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -255,6 +255,7 @@ define_sdl_subsystem(Haptic)
 define_sdl_subsystem(Hidapi)
 define_sdl_subsystem(Power)
 define_sdl_subsystem(Sensor)
+define_sdl_subsystem(Dialog)
 
 cmake_dependent_option(SDL_FRAMEWORK "Build SDL libraries as Apple Framework" OFF "APPLE" OFF)
 if(SDL_FRAMEWORK)
@@ -2411,7 +2412,7 @@ elseif(HAIKU)
   sdl_glob_sources("${SDL3_SOURCE_DIR}/src/core/haiku/*.cc")
 
   CheckPTHREAD()
-  sdl_link_dependency(base LIBS root be media game device textencoding)
+  sdl_link_dependency(base LIBS root be media game device textencoding tracker)
 
 elseif(RISCOS)
   sdl_glob_sources("${SDL3_SOURCE_DIR}/src/misc/riscos/*.c")
@@ -2754,6 +2755,24 @@ elseif(N3DS)
   sdl_glob_sources("${SDL3_SOURCE_DIR}/src/file/n3ds/*.c")
 endif()
 
+if (SDL_DIALOG)
+  if(UNIX AND NOT APPLE AND NOT RISCOS AND NOT HAIKU)
+    sdl_sources(${SDL3_SOURCE_DIR}/src/dialog/unix/SDL_unixdialog.c)
+    sdl_sources(${SDL3_SOURCE_DIR}/src/dialog/unix/SDL_portaldialog.c)
+    sdl_sources(${SDL3_SOURCE_DIR}/src/dialog/unix/SDL_zenitydialog.c)
+    set(HAVE_SDL_DIALOG TRUE)
+  elseif(HAIKU)
+    sdl_sources(${SDL3_SOURCE_DIR}/src/dialog/haiku/SDL_haikudialog.cc)
+    set(HAVE_SDL_DIALOG TRUE)
+  elseif(WINDOWS AND NOT WINDOWS_STORE)
+    sdl_sources(${SDL3_SOURCE_DIR}/src/dialog/windows/SDL_windowsdialog.c)
+    set(HAVE_SDL_DIALOG TRUE)
+  elseif(APPLE)
+    sdl_sources(${SDL3_SOURCE_DIR}/src/dialog/cocoa/SDL_cocoadialog.m)
+    set(HAVE_SDL_DIALOG TRUE)
+  endif()
+endif()
+
 # Platform-independent options
 
 if(SDL_VIDEO)
@@ -2809,6 +2828,10 @@ if(NOT HAVE_SDL_MISC)
   set(SDL_MISC_DUMMY 1)
   sdl_glob_sources("${SDL3_SOURCE_DIR}/src/misc/dummy/*.c")
 endif()
+if(NOT HAVE_SDL_DIALOG)
+  set(SDL_DIALOG_DUMMY 1)
+  sdl_sources(${SDL3_SOURCE_DIR}/src/dialog/dummy/SDL_dummydialog.c)
+endif()
 if(NOT HAVE_CAMERA)
   set(SDL_CAMERA_DRIVER_DUMMY 1)
   sdl_glob_sources("${SDL3_SOURCE_DIR}/src/camera/dummy/*.c")
diff --git a/VisualC/SDL/SDL.vcxproj b/VisualC/SDL/SDL.vcxproj
index f011b1f643f7f..ccc8492e77756 100644
--- a/VisualC/SDL/SDL.vcxproj
+++ b/VisualC/SDL/SDL.vcxproj
@@ -504,6 +504,7 @@
     <ClCompile Include="..\..\src\core\windows\SDL_windows.c" />
     <ClCompile Include="..\..\src\core\windows\SDL_xinput.c" />
     <ClCompile Include="..\..\src\cpuinfo\SDL_cpuinfo.c" />
+    <ClCompile Include="..\..\src\dialog\windows\SDL_windowsdialog.c" />
     <ClCompile Include="..\..\src\dynapi\SDL_dynapi.c">
       <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">NotUsing</PrecompiledHeader>
       <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">NotUsing</PrecompiledHeader>
@@ -693,4 +694,4 @@
   <ImportGroup Label="ExtensionTargets">
     <Import Project="$(VCTargetsPath)\BuildCustomizations\masm.targets" />
   </ImportGroup>
-</Project>
\ No newline at end of file
+</Project>
diff --git a/VisualC/SDL/SDL.vcxproj.filters b/VisualC/SDL/SDL.vcxproj.filters
index 4f292f1bfc8e1..10eb1997ac3b5 100644
--- a/VisualC/SDL/SDL.vcxproj.filters
+++ b/VisualC/SDL/SDL.vcxproj.filters
@@ -937,6 +937,9 @@
     <ClCompile Include="..\..\src\cpuinfo\SDL_cpuinfo.c">
       <Filter>cpuinfo</Filter>
     </ClCompile>
+    <ClCompile Include="..\..\src\dialog\windows\SDL_windowsdialog.c">
+      <Filter>dialog</Filter>
+    </ClCompile>
     <ClCompile Include="..\..\src\dynapi\SDL_dynapi.c">
       <Filter>dynapi</Filter>
     </ClCompile>
@@ -1453,4 +1456,4 @@
   <ItemGroup>
     <MASM Include="..\..\src\stdlib\SDL_mslibc_x64.masm" />
   </ItemGroup>
-</Project>
\ No newline at end of file
+</Project>
diff --git a/include/SDL3/SDL.h b/include/SDL3/SDL.h
index d7716399de059..cb49d7aedcbf7 100644
--- a/include/SDL3/SDL.h
+++ b/include/SDL3/SDL.h
@@ -38,6 +38,7 @@
 #include <SDL3/SDL_camera.h>
 #include <SDL3/SDL_clipboard.h>
 #include <SDL3/SDL_cpuinfo.h>
+#include <SDL3/SDL_dialog.h>
 #include <SDL3/SDL_endian.h>
 #include <SDL3/SDL_error.h>
 #include <SDL3/SDL_events.h>
diff --git a/include/SDL3/SDL_dialog.h b/include/SDL3/SDL_dialog.h
new file mode 100644
index 0000000000000..78225c9e516e2
--- /dev/null
+++ b/include/SDL3/SDL_dialog.h
@@ -0,0 +1,184 @@
+/*
+  Simple DirectMedia Layer
+  Copyright (C) 1997-2024 Sam Lantinga <slouken@libsdl.org>
+
+  This software is provided 'as-is', without any express or implied
+  warranty.  In no event will the authors be held liable for any damages
+  arising from the use of this software.
+
+  Permission is granted to anyone to use this software for any purpose,
+  including commercial applications, and to alter it and redistribute it
+  freely, subject to the following restrictions:
+
+  1. The origin of this software must not be misrepresented; you must not
+     claim that you wrote the original software. If you use this software
+     in a product, an acknowledgment in the product documentation would be
+     appreciated but is not required.
+  2. Altered source versions must be plainly marked as such, and must not be
+     misrepresented as being the original software.
+  3. This notice may not be removed or altered from any source distribution.
+*/
+
+#ifndef SDL_dialog_h_
+#define SDL_dialog_h_
+
+#include <SDL3/SDL_video.h>
+
+#include <SDL3/SDL_begin_code.h>
+/* Set up for C function definitions, even when using C++ */
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * An entry for filters for file dialogs.
+ *
+ * `name` is a user-readable label for the filter (for example, "Office document").
+ *
+ * `pattern` is a semicolon-separated list of file extensions (for example,
+ * "doc;docx").
+ *
+ * \sa SDL_DialogFileCallback
+ * \sa SDL_ShowOpenFileDialog
+ * \sa SDL_ShowSaveFileDialog
+ * \sa SDL_ShowOpenFolderDialog
+ */
+typedef struct
+{
+    const char *name;
+    const char *pattern;
+} SDL_DialogFileFilter;
+
+/**
+ * Callback used by file dialog functions.
+ *
+ * The specific usage is described in each function.
+ *
+ * If filelist is...
+ * - `NULL`, an error occured. Details can be obtained with SDL_GetError().
+ * - A pointer to `NULL`, the user either didn't choose any file or canceled
+ *   the dialog.
+ * - A pointer to non-`NULL`, the user chose one or more files. The argument is
+ *   a null-terminated list of pointers to C strings, each containing a path.
+ *
+ * The filelist argument does not need to be freed; it will automatically be
+ * freed when the callback returns.
+ *
+ * The filter argument is the index of the filter that was selected, or one
+ * more than the size of the list (therefore the index of the terminating NULL
+ * entry) if no filter was selected, or -1 if the platform or method doesn't
+ * support fetching the selected filter or if an error occured.
+ *
+ * \sa SDL_DialogFileFilter
+ * \sa SDL_ShowOpenFileDialog
+ * \sa SDL_ShowSaveFileDialog
+ * \sa SDL_ShowOpenFolderDialog
+ */
+typedef void(SDLCALL *SDL_DialogFileCallback)(void *userdata, const char * const *filelist, int filter);
+
+/**
+ * Displays a dialog that lets the user select a file on their filesystem.
+ *
+ * This function should only be invoked from the main thread.
+ *
+ * This is an asynchronous function; it will return immediately, and the result
+ * will be passed to the callback.
+ *
+ * The callback will be invoked with a null-terminated list of files the user
+ * chose. The list will be empty if the user canceled the dialog, and it will
+ * be NULL if an error occured.
+ *
+ * Note that the callback may be called from a different thread than the one
+ * the function was invoked on.
+ *
+ * Depending on the platform, the user may be allowed to input paths that don't
+ * yet exist.
+ *
+ * \param callback The function to be invoked when the user selects a file and accepts, or the user cancels the dialog, or an error occurs. The first argument is a null-terminated list of C strings, representing the paths chosen by the user. The list will be empty if the user canceled the dialog, and it will be NULL if an error occured. If an error occured, it can be fetched with SDL_GetError(). The second argument is the userdata pointer passed to the function.
+ * \param userdata An optional pointer to pass extra data to the callback when it will be invoked.
+ * \param window The window that the dialog should be modal for. May be NULL. Not all platforms support this option.
+ * \param filters A null-terminated list of SDL_DialogFileFilter's. May be NULL. Not all platforms support this option, and platforms that do support it may allow the user to ignore the filters.
+ * \param default_location The default folder or file to start the dialog at. May be NULL. Not all platforms support this option.
+ * \param allow_many If non-zero, the user will be allowed to select multiple entries. Not all platforms support this option.
+ *
+ * \since This function is available since SDL 3.0.0.
+ *
+ * \sa SDL_DialogFileFilter
+ * \sa SDL_DialogFileCallback
+ * \sa SDL_ShowSaveFileDialog
+ * \sa SDL_ShowOpenFolderDialog
+ */
+extern DECLSPEC void SDLCALL SDL_ShowOpenFileDialog(SDL_DialogFileCallback callback, void *userdata, SDL_Window *window, const SDL_DialogFileFilter *filters, const char *default_location, SDL_bool allow_many);
+
+/**
+ * Displays a dialog that lets the user choose a new or existing file on their filesystem.
+ *
+ * This function should only be invoked from the main thread.
+ *
+ * This is an asynchronous function; it will return immediately, and the result
+ * will be passed to the callback.
+ *
+ * The callback will be invoked with a null-terminated list of files the user
+ * chose. The list will be empty if the user canceled the dialog, and it will
+ * be NULL if an error occured.
+ *
+ * Note that the callback may be called from a different thread than the one
+ * the function was invoked on.
+ *
+ * The chosen file may or may not already exist.
+ *
+ * \param callback The function to be invoked when the user selects a file and accepts, or the user cancels the dialog, or an error occurs. The first argument is a null-terminated list of C strings, representing the paths chosen by the user. The list will be empty if the user canceled the dialog, and it will be NULL if an error occured. If an error occured, it can be fetched with SDL_GetError(). The second argument is the userdata pointer passed to the function.
+ * \param userdata An optional pointer to pass extra data to the callback when it will be invoked.
+ * \param window The window that the dialog should be modal for. May be NULL. Not all platforms support this option.
+ * \param filters A null-terminated list of SDL_DialogFileFilter's. May be NULL. Not all platforms support this option, and platforms that do support it may allow the user to ignore the filters.
+ * \param default_location The default folder or file to start the dialog at. May be NULL. Not all platforms support this option.
+ *
+ * \since This function is available since SDL 3.0.0.
+ *
+ * \sa SDL_DialogFileFilter
+ * \sa SDL_DialogFileCallback
+ * \sa SDL_ShowOpenFileDialog
+ * \sa SDL_ShowOpenFolderDialog
+ */
+extern DECLSPEC void SDLCALL SDL_ShowSaveFileDialog(SDL_DialogFileCallback callback, void *userdata, SDL_Window *window, const SDL_DialogFileFilter *filters, const char *default_location);
+
+/**
+ * Displays a dialog that lets the user select a folder on their filesystem.
+ *
+ * This function should only be invoked from the main thread.
+ *
+ * This is an asynchronous function; it will return immediately, and the result
+ * will be passed to the callback.
+ *
+ * The callback will be invoked with a null-terminated list of files the user
+ * chose. The list will be empty if the user canceled the dialog, and it will
+ * be NULL if an error occured.
+ *
+ * Note that the callback may be called from a different thread than the one
+ * the function was invoked on.
+ *
+ * Depending on the platform, the user may be allowed to input paths that don't
+ * yet exist.
+ *
+ * \param callback The function to be invoked when the user selects a folder and accepts, or the user cancels the dialog, or an error occurs. The first argument is a null-terminated list of C strings, representing the paths chosen by the user. The list will be empty if the user canceled the dialog, and it will be NULL if an error occured. If an error occured, it can be fetched with SDL_GetError(). The second argument is the userdata pointer passed to the function.
+ * \param userdata An optional pointer to pass extra data to the callback when it will be invoked.
+ * \param window The window that the dialog should be modal for. May be NULL. Not all platforms support this option.
+ * \param default_location The default folder or file to start the dialog at. May be NULL. Not all platforms support this option.
+ * \param allow_many If non-zero, the user will be allowed to select multiple entries. Not all platforms support this option.
+ *
+ * \since This function is available since SDL 3.0.0.
+ *
+ * \sa SDL_DialogFileFilter
+ * \sa SDL_DialogFileCallback
+ * \sa SDL_ShowOpenFileDialog
+ * \sa SDL_ShowSaveFileDialog
+ */
+extern DECLSPEC void SDLCALL SDL_ShowOpenFolderDialog(SDL_DialogFileCallback callback, void *userdata, SDL_Window *window, const char *default_location, SDL_bool allow_many);
+
+/* Ends C function definitions when using C++ */
+#ifdef __cplusplus
+}
+#endif
+#include <SDL3/SDL_close_code.h>
+
+#endif /* SDL_joystick_h_ */
diff --git a/src/core/linux/SDL_dbus.c b/src/core/linux/SDL_dbus.c
index 60be16dc47341..9e6a56b65e1d8 100644
--- a/src/core/linux/SDL_dbus.c
+++ b/src/core/linux/SDL_dbus.c
@@ -53,6 +53,7 @@ static int LoadDBUSSyms(void)
     SDL_DBUS_SYM(void (*)(DBusConnection *, dbus_bool_t), connection_set_exit_on_disconnect);
     SDL_DBUS_SYM(dbus_bool_t (*)(DBusConnection *), connection_get_is_connected);
     SDL_DBUS_SYM(dbus_bool_t (*)(DBusConnection *, DBusHandleMessageFunction, void *, DBusFreeFunction), connection_add_filter);
+    SDL_DBUS_SYM(dbus_bool_t (*)(DBusConnection *, DBusHandleMessageFunction, void *), connection_remove_filter);
     SDL_DBUS_SYM(dbus_bool_t (*)(DBusConnection *, const char *, const DBusObjectPathVTable *, void *, DBusError *), connection_try_register_object_path);
     SDL_DBUS_SYM(dbus_bool_t (*)(DBusConnection *, DBusMessage *, dbus_uint32_t *), connection_send);
     SDL_DBUS_SYM(DBusMessage *(*)(DBusConnection *, DBusMessage *, int, DBusError *), connection_send_with_reply_and_block);
@@ -63,6 +64,7 @@ static int LoadDBUSSyms(void)
     SDL_DBUS_SYM(dbus_bool_t (*)(DBusConnection *, int), connection_read_write);
     SDL_DBUS_SYM(DBusDispatchStatus (*)(DBusConnection *), connection_dispatch);
     SDL_DBUS_SYM(dbus_bool_t (*)(DBusMessage *, const char *, const char *), message_is_signal);
+    SDL_DBUS_SYM(dbus_bool_t (*)(DBusMessage *, const char *), message_has_path);
     SDL_DBUS_SYM(DBusMessage *(*)(const char *, const char *, const char *, const char *), message_new_method_call);
     SDL_DBUS_SYM(dbus_bool_t (*)(DBusMessage *, int, ...), message_append_args);
     SDL_DBUS_SYM(dbus_bool_t (*)(DBusMessage *, int, va_list), message_append_args_valist);
diff --git a/src/core/linux/SDL_dbus.h b/src/core/linux/SDL_dbus.h
index c37de56aa18bc..0be866b36059d 100644
--- a/src/core/linux/SDL_dbus.h
+++ b/src/core/linux/SDL_dbus.h
@@ -31,6 +31,9 @@
 #ifndef DBUS_TIMEOUT_USE_DEFAULT
 #define DBUS_TIMEOUT_USE_DEFAULT -1
 #endif
+#ifndef DBUS_TIMEOUT_INFINITE
+#define DBUS_TIMEOUT_INFINITE ((int) 0x7fffffff)
+#endif
 
 typedef struct SDL_DBusContext
 {
@@ -44,6 +47,7 @@ typedef struct SDL_DBusContext
     void (*connection_set_exit_on_disconnect)(DBusConnection *, dbus_bool_t);
     dbus_bool_t (*connection_get_is_connected)(DBusConnection *);
     dbus_bool_t (*connection_add_filter)(DBusConnection *, DBusHandleMessageFunction, void *, DBusFreeFunction);
+    dbus_bool_t (*connection_remove_filter)(DBusConnection *, DBusHandleMessageFunction, void *);
     dbus_bool_t (*connection_try_register_object_path)(DBusConnection *, const char *,
                                                        const DBusObjectPathVTable *, void *, DBusError *);
     dbus_bool_t (*connection_send)(DBusConnection *, DBusMessage *, dbus_uint32_t *);
@@ -55,6 +59,7 @@ typedef struct SDL_DBusContext
     dbus_bool_t (*connection_read_write)(DBusConnection *, int);
     DBusDispatchStatus (*connection_dispatch)(DBusConnection *);
     dbus_bool_t (*message_is_signal)(DBusMessage *, const char *, const char *);
+    dbus_bool_t (*message_has_path)(DBusMessage *, const char *);
     DBusMessage *(*message_new_method_call)(const char *, const char *, const char *, const char *);
     dbus_bool_t (*message_append_args)(DBusMessage *, int, ...);
     dbus_bool_t (*message_append_args_valist)(DBusMessage *, int, va_list);
diff --git a/src/dialog/cocoa/SDL_cocoadialog.m b/src/dialog/cocoa/SDL_cocoadialog.m
new file mode 100644
index 0000000000000..3d4a8a59bcd8e
--- /dev/null
+++ b/src/dialog/cocoa/SDL_cocoadialog.m
@@ -0,0 +1,169 @@
+/*
+  Simple DirectMedia Layer
+  Copyright (C) 1997-2024 Sam Lantinga <slouken@libsdl.org>
+
+  This software is provided 'as-is', without any express or implied
+  warranty.  In no event will the authors be held liable for any damages
+  arising from the use of this software.
+
+  Permission is granted to anyone to use this software for any purpose,
+  including commercial applications, and to alter it and redistribute it
+  freely, subject to the following restrictions:
+
+  1. The origin of this software must not be misrepresented; you must not
+     claim that you wrote the original software. If you use this software
+     in a product, an acknowledgment in the product documentation would be
+     appreciated but is not required.
+  2. Altered source versions must be plainly marked as such, and must not be
+     misrepresented as being the original software.
+  3. This notice may not be removed or altered from any source distribution.
+*/
+#include "SDL_internal.h"
+
+/* TODO: Macro? */
+
+#import <Cocoa/Cocoa.h>
+
+typedef enum
+{
+    FDT_SAVE,
+    FDT_OPEN,
+    FDT_OPENFOLDER
+} cocoa_FileDialogType;
+
+void show_file_dialog(cocoa_FileDialogType type, SDL_DialogFileCallback callback, void* userdata, SDL_Window* window, const SDL_DialogFileFilter *filters, const char* default_location, SDL_bool allow_many)
+{
+    /* NSOpenPanel inherits from NSSavePanel */
+    NSSavePanel *dialog;
+    NSOpenPanel *dialog_as_open;
+
+    switch (type) {
+    case FDT_SAVE:
+        dialog = [NSSavePanel savePanel];
+        break;
+    case FDT_OPEN:
+        dialog_as_open = [NSOpenPanel openPanel];
+        [dialog_as_open setAllowsMultipleSelection:((allow_many == SDL_TRUE) ? YES : NO)];
+        dialog = dialog_as_open;
+        break;
+    case FDT_OPENFOLDER:
+        dialog_as_open = [NSOpenPanel openPanel];
+        [dialog_as_open setCanChooseFiles:NO];
+        [dialog_as_open setCanChooseDirectories:YES];
+        [dialog_as_open setAllowsMultipleSelection:((allow_many == SDL_TRUE) ? YES : NO)];
+        dialog = dialog_as_open;
+        break;
+    };
+
+    int n = -1;
+    while (filters[++n].name && filters[n].pattern);
+    NSMutableArray *types = [[NSMutableArray alloc] initWithCapacity:n ];
+
+    int has_all_files = 0;
+    for (int i = 0; i < n; i++) {
+        char *pattern = SDL_strdup(filters[i].pattern);
+        char *pattern_ptr = pattern;
+
+        if (!pattern_ptr) {
+            SDL_OutOfMemory();
+            callback(userdata, NULL, -1);
+            return;
+        }
+
+        for (char *c = pattern; *c; c++) {
+            if (*c == ';') {
+                *c = '\0';
+                [types addObject: [NSString stringWithFormat: @"%s", pattern_ptr]];
+                pattern_ptr = c + 1;
+            } else if (!((*c >= 'a' && *c <= 'z') || (*c >= 'A' && *c <= 'Z') || (*c >= '0' && *c <= '9') || *c == '.' || *c == '_' || *c == '-' || (*c == '*' && (c[1] == '\0' || c[1] == ';')))) {
+                SDL_SetError("Illegal character in pattern name: %c (Only alphanumeric characters, periods, underscores and hyphens allowed)", *c);
+                callback(userdata, NULL, -1);
+                SDL_free(pattern);
+            } else if (*c == '*') {
+                has_all_files = 1;
+            }
+        }
+        [types addObject: [NSString stringWithFormat: @"%s", pattern_ptr]];
+
+        SDL_free(pattern);
+    }
+
+    if (!has_all_files) {
+        if (@available(macOS 11.0, *)) {
+            [dialog setAllowedContentTypes:types];
+        } else {
+            [dialog setAllowedFileTypes:types];
+        }
+    }
+
+    /* Keep behavior consistent with other platforms */
+    [dialog setAllowsOtherFileTypes:YES];
+
+    if (default_location) {
+        [dialog setDirectoryURL:[NSURL fileURLWithPath:[NSString stringWithUTF8String:default_location]]];
+    }
+
+    NSWindow *w = NULL;
+
+    if (window) {
+        w = (__bridge NSWindow *)SDL_GetProperty(SDL_GetWindowProperties(window), SDL_PROP_WINDOW_COCOA_WINDOW_POINTER, NULL);
+    }
+
+    if (w) {
+        // [dialog beginWithCompletionHandler:^(NSInteger result) {
+        [dialog beginSheetModalForWindow:w completionHandler:^(NSInteger result) {
+            // NSModalResponseOK for >= 10.13
+            if (result == NSFileHandlingPanelOKButton) {
+                if (dialog_as_open) {
+                    NSArray* urls = [dialog_as_open URLs];
+                    const char *files[[urls count] + 1];
+                    for (int i = 0; i < [urls count]; i++) {
+                        files[i] = [[[urls objectAtIndex:i] path] UTF8String];
+                    }
+                    files[[urls count]] = NULL;
+                    callback(userdata, files, -1);
+                } else {
+                    const char *files[2] = { [[[dialog URL] path] UTF8String], NULL };
+                    callback(userdata, files, -1);
+                }
+            } else if (result == NSModalResponseCancel) {
+                const char *files[1] = { NULL };
+                callback(userdata, files, -1);
+            }
+        }];
+    } else {
+        // NSModalResponseOK for >= 10.10
+        if ([dialog runModal] == NSOKButton) {
+            if (dialog_as_open) {
+                NSArray* urls = [dialog_as_open URLs];
+                const char *files[[urls count] + 1];
+                for (int i = 0; i < [urls count]; i++) {
+                    files[i] = [[[urls objectAtIndex:i] path] UTF8String];
+                }
+                files[[urls count]] = NULL;
+                callback(userdata, files, -1);
+            } else {
+                const char *files[2] = { [[[dialog URL] path] UTF8String], NULL };
+                callback(userdata, files, -1);
+            }
+        } else {
+            const char *files[1] = { NULL };
+            callback(userdata, files, -1);
+        }
+    }
+}
+
+void SDL_ShowOpenFileDialog(SDL_DialogFileCallback callback, void* userdata, SDL_Window* window, const SDL_DialogFileFilter *filters, const char* default_location, SDL_bool allow_many)
+{
+    show_file_dialog(FDT_OPEN, callback, userdata, window, filters, default_location, allow_many);
+}
+
+void SDL_ShowSaveFileDialog(SDL_DialogFileCallback callback, void* userdata, SDL_Window* window, const SDL_DialogFileFilter *filters, const char* default_location)
+{
+    show_file_dialog(FDT_SAVE, callback, userdata, window, filters, default_location, 0);
+}
+
+void SDL_ShowOpenFolderDialog(SDL_DialogFileCallback callback, void* userdata, SDL_Window* window, const char* default_location, SDL_bool allow_many)
+{
+    show_file_dialog(FDT_OPENFOLDER, callback, userdata, window, NULL, default_location, allow_many);
+}
diff --git a/src/dialog/dummy/SDL_dummydialog.c b/src/dialog/dummy/SDL_dummydialog.c
new file mode 100644
index 0000000000000..8740f2f2d8ad2
--- /dev/null
+++ b/src/dialog/dummy/SDL_dummydialog.c
@@ -0,0 +1,41 @@
+/*
+  Simple DirectMedia Layer
+  Copyright (C) 1997-2024 Sam Lantinga <slouken@libsdl.org>
+
+  This software is provided 'as-is', without any express or implied
+  warranty.  In no event will the authors be held liable for any damages
+  arising from the use of this software.
+
+  Permission is granted to anyone to use this software for any purpose,
+  including commercial applications, and to alter it and redistribute it
+  freely, subject to the following restrictions:
+
+  1. The origin of this software must not be misrepresented; you must not
+     claim that you wrote the original software. If you use this software
+     in a product, an acknowledgment in the product documentation would be
+     appreciated but is not required.
+  2. Altered source versions must be plainly marked as such, and must not be
+     misrepresented as being the original software.
+  3. This notice may not be removed or altered from any source distribution.
+*/
+#include "SDL_internal.h"
+
+/* TODO: Macro? */
+
+void SDL_ShowOpenFileDialog(SDL_DialogFileCallback callback, void* userdata, SDL_Window* window, const SDL_DialogFileFilter *filters, const char* default_location, SDL_bool allow_many)
+{
+  SDL_Unsupported();
+  callback(userdata, NULL, -1);
+}
+
+void SDL_ShowSaveFileDialog(SDL_DialogFileCallback callback, void* userdata, SDL_Window* window, const SDL_DialogFileFilter *filters, const char* default_location)
+{
+  SDL_Unsupported();
+  callback(userdata, NULL, -1);
+}
+
+void SDL_ShowOpenFolderDialog(SDL_DialogFileCallback callback, void* userdata, SDL_Window* window, const char* default_location, SDL_bool allow_many)
+{
+  SDL_Unsupported();
+  callback(userdata, NULL, -1);
+}
diff --git a/src/dialog/haiku/SDL_haikudialog.cc b/src/dialog/haiku/SDL_haikudialog.cc
new file mode 100644
index 0000000000000..3e63fc807266b
--- /dev/null
+++ b/src/dialog/haiku/SDL_haikudialog.cc
@@ -0,0 +1,233 @@
+/*
+  Simple DirectMedia Layer
+  Copyright (C) 1997-2024 Sam Lantinga <slouken@libsdl.org>
+
+  This software is provided 'as-is', without any express or implied
+  warranty.  In no event will the authors be held liable for any damages
+  arising from the use of this software.
+
+  Permission is granted to anyone to use this software for any purpose,
+  including commercial applications, and to alter it and redistribute it
+  freely, subject to the following restrictions:
+
+  1. The origin of this software must not be misrepresented; you must not
+     claim that you wrote the original software. If you use this software
+     in a product, an acknowledgment in the product documentation would be
+     appreciated but is not required.
+  2. Altered source versions must be plainly marked as such, and must not be
+     misrepresented as being the original software.
+  3. This notice may not be removed or altered from any source distribution.
+*/
+#include "SDL_internal.h"
+#include "../../core/haiku/SDL_BeApp.h"
+
+#include <string>
+#include <vector>
+
+#include <sys/stat.h>
+
+#include <FilePanel.h>
+#include <Entry.h>
+#include <Looper.h>
+#include <Messenger.h>
+#include <Path.h>
+#include <TypeConstants.h>
+
+bool StringEndsWith(const std::string& str, const std::string& end)
+{
+    return str.size() >= end.size() && !str.compare(str.size() - end.size(), end.size(), end);
+}
+
+std::vector<std::string> StringSplit(const std::string& str, const std::string& split)
+{
+    std::vector<std::string> retval;
+    std::string s = str;
+    size_t pos = 0;
+
+    while ((pos = s.find(split)) != std::string::npos) {
+        retval.push_back(s.substr(0, pos));
+        s = s.substr(pos + split.size());
+    }
+
+    retval.push_back(s);
+
+    return retval;
+}
+
+class SDLBRefFilter : public BRefFilter
+{
+public:
+    SDLBRefFilter(const SDL_DialogFileFilter *filters) :
+        BRefFilter(),
+        m_filters(filters)
+    {
+    }
+
+    virtual bool Filter(const entry_ref *ref, BNode *node, struct stat_beos *stat, const char *mimeType) override
+    {
+        BEntry entry(ref);
+        BPath path;
+        entry.GetPath(&path);
+        std::string result = path.Path();
+
+        if (!m_filters)
+            return true;
+
+        struct stat info;
+        node->GetStat(&info);
+        if (S_ISDIR(info.st_mode))
+            return true;
+
+        const auto *filter = m_filters;
+        while (filter->name && filter->pattern) {
+            for (const auto& suffix : StringSplit(filter->pattern, ";")) {
+                if (StringEndsWith(result, std::string(".") + suffix)) {
+                    return true;
+                }
+            }
+            filter++;
+        }
+
+        return false;
+    }
+
+private:
+    const SDL_DialogFileFilter * const m_filters;
+};
+
+class CallbackLooper : public BLooper
+{
+public:
+    CallbackLooper(SDL_DialogFileCallback callback, void *userdata) :
+        m_callback(callback),
+        m_userdata(userdata),
+        m_files(),
+        m_messenger(),
+        m_panel(),
+        m_filter()
+    {
+    }
+
+    ~CallbackLooper()
+    {
+        delete m_messenger;
+        delete m_panel;
+        delete m_filter;
+    }
+
+    void SetToBeFreed(BMessenger *messenger, BFilePanel *panel, SDLBRefFilter *filter)
+    {
+        m_messenger = messenger;
+        m_panel = panel;
+        m_filter = filter;
+    }
+
+    virtual void MessageReceived(BMessage *msg) override
+    {
+        entry_ref file;
+        BPath path;
+        BEntry entry;
+        std::string result;
+        const char *filename;
+        int32 nFiles = 0;
+
+        switch (msg->what)
+        {
+        case B_REFS_RECEIVED: // Open
+            msg->GetInfo("refs", NULL, &nFiles);
+            for (int i = 0; i < nFiles; i++) {
+                msg->FindRef("refs", i, &file);
+   

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