SDL: Fix OpenFolder dialog behavior on Windows

From fc053fb499645186ca609ab04cd7dca6e712ce87 Mon Sep 17 00:00:00 2001
From: Mykola Rubets <[EMAIL REDACTED]>
Date: Sun, 24 Mar 2024 18:20:28 +0200
Subject: [PATCH] Fix OpenFolder dialog behavior on Windows

---
 src/dialog/windows/SDL_windowsdialog.c | 35 +++++++++++++++++++++++---
 1 file changed, 32 insertions(+), 3 deletions(-)

diff --git a/src/dialog/windows/SDL_windowsdialog.c b/src/dialog/windows/SDL_windowsdialog.c
index 0a58e02ce3f09..57bfe8b63752a 100644
--- a/src/dialog/windows/SDL_windowsdialog.c
+++ b/src/dialog/windows/SDL_windowsdialog.c
@@ -44,6 +44,7 @@ typedef struct
 {
     SDL_Window* parent;
     SDL_DialogFileCallback callback;
+    const char* default_folder;
     void* userdata;
 } winFArgs;
 
@@ -327,6 +328,31 @@ int windows_file_dialog_thread(void* ptr)
     return 0;
 }
 
+int CALLBACK browse_callback_proc(
+				HWND hwnd, 
+				UINT uMsg, 
+				LPARAM lParam, 
+				LPARAM lpData)
+{
+  
+	switch (uMsg)
+	{
+	case BFFM_INITIALIZED :
+		if(lpData)
+        {
+		  SendMessage(hwnd, BFFM_SETSELECTION, TRUE, lpData);
+        }
+		break;
+	case BFFM_SELCHANGED :
+		break;
+	case BFFM_VALIDATEFAILED :
+		break;
+	default:
+		break;
+	}
+	return 0; 
+}
+
 void windows_ShowFolderDialog(void* ptr)
 {
     winFArgs *args = (winFArgs *) ptr;
@@ -349,11 +375,13 @@ void windows_ShowFolderDialog(void* ptr)
     dialog.pszDisplayName = buffer;
     dialog.lpszTitle = NULL;
     dialog.ulFlags = BIF_USENEWUI;
-    dialog.lpfn = NULL;
-    dialog.lParam = 0;
+    dialog.lpfn = browse_callback_proc;
+    dialog.lParam = (LPARAM)args->default_folder;
     dialog.iImage = 0;
 
-    if (SHBrowseForFolderW(&dialog)) {
+    LPITEMIDLIST lpItem = SHBrowseForFolderW(&dialog);
+    if (lpItem != NULL) {
+        SHGetPathFromIDListW(lpItem, buffer);
         char *chosen_file = WIN_StringToUTF8W(buffer);
         const char *files[2] = { chosen_file, NULL };
         callback(userdata, (const char * const*) files, -1);
@@ -447,6 +475,7 @@ void SDL_ShowOpenFolderDialog(SDL_DialogFileCallback callback, void* userdata, S
 
     args->parent = window;
     args->callback = callback;
+    args->default_folder = default_location;
     args->userdata = userdata;
 
     thread = SDL_CreateThreadInternal(windows_folder_dialog_thread, "SDL_ShowOpenFolderDialog", 0, (void *) args);