gdk: Just use WIN_GetModulePath().

There's no need to use the "A" version of GetModuleFileName on GDK; it returns
a UTF-8 string directly on this platform, but we can still use the UTF-16 "W"
version and cut down on code duplication.

This code runs once and caches the results, so we can take the one-time string
conversion overhead.
This commit is contained in:
Ryan C. Gordon 2026-05-27 15:22:10 -04:00
parent bb11c6789c
commit 6b780c5ff9
No known key found for this signature in database
GPG key ID: FA148B892AB48044

View file

@ -33,61 +33,34 @@ extern "C" {
#include <SDL3/SDL_filesystem.h>
#include <XGameSaveFiles.h>
char *
SDL_SYS_GetBasePath(void)
char *SDL_SYS_GetBasePath(void)
{
/* NOTE: This function is a UTF8 version of the Win32 SDL_GetBasePath()!
* The GDK actually _recommends_ the 'A' functions over the 'W' functions :o
*
* !!! FIXME: But can we use WIN_GetModulePath anyhow? (or change WIN_GetModulePath to use GetModuleFileNameA when built for GDK?)
*/
DWORD buflen = 128;
CHAR *path = NULL;
DWORD len = 0;
int i;
while (true) {
void *ptr = SDL_realloc(path, buflen * sizeof(CHAR));
if (!ptr) {
SDL_free(path);
return NULL;
}
path = (CHAR *)ptr;
len = GetModuleFileNameA(NULL, path, buflen);
// if it truncated, then len >= buflen - 1
// if there was enough room (or failure), len < buflen - 1
if (len < buflen - 1) {
break;
}
// buffer too small? Try again.
buflen *= 2;
char *path = WIN_GetModulePath(NULL); // look up full path of the current process's EXE file.
if (!path) {
return NULL; // error message was already set.
}
if (len == 0) {
SDL_free(path);
WIN_SetError("Couldn't locate our .exe");
return NULL;
}
char *ptr = SDL_strrchr(path, '\\');
SDL_assert(ptr != NULL); // Should have been an absolute path.
for (i = len - 1; i > 0; i--) {
if (path[i] == '\\') {
break;
}
}
ptr[1] = '\0'; // chop off filename, leave '\\'.
SDL_assert(i > 0); // Should have been an absolute path.
path[i + 1] = '\0'; // chop off filename.
return path;
ptr = (char *) SDL_realloc(path, ((size_t) (ptr - path)) + 2); // try to shrink this allocation down a little.
return ptr ? ptr : path; // return shrunk buffer if shrink worked out, unchanged original buffer if not.
}
char *SDL_SYS_GetExeName(void)
{
SDL_Unsupported(); // !!! FIXME: use WIN_GetModulePath
return NULL;
char *path = WIN_GetModulePath(NULL); // look up full path of the current process's EXE file.
if (!path) {
return NULL; // error message was already set.
}
char *ptr = SDL_strrchr(path, '\\');
const size_t slen = SDL_strlen(ptr); // counts null terminator because we're still sitting on path separator.
SDL_memmove(path, ptr + 1, slen); // move filename string to start of SDL_realloc'd region.
ptr = (char *) SDL_realloc(path, slen); // try to shrink this allocation down a little.
return ptr ? ptr : path; // return shrunk buffer if shrink worked out, unchanged original buffer if not.
}
char *SDL_SYS_GetPrefPath(const char *org, const char *app)