SDL: Use the X11 driver if the application uses X11-based graphics frameworks

From bd2f1e9ea635b232d5aa39fb9f0326b1f134b99e Mon Sep 17 00:00:00 2001
From: Sam Lantinga <[EMAIL REDACTED]>
Date: Tue, 9 Jan 2024 11:24:10 -0800
Subject: [PATCH] Use the X11 driver if the application uses X11-based graphics
 frameworks

Fixes https://github.com/libsdl-org/SDL/issues/8812
---
 src/video/SDL_video.c | 23 +++++++++++++++++++++++
 1 file changed, 23 insertions(+)

diff --git a/src/video/SDL_video.c b/src/video/SDL_video.c
index 03e5302ea29b..a1f88acfe980 100644
--- a/src/video/SDL_video.c
+++ b/src/video/SDL_video.c
@@ -61,6 +61,7 @@
 #include <sys/types.h>
 #include <sys/stat.h>
 #include <unistd.h>
+#include <dlfcn.h>
 #endif
 
 /* Available video drivers */
@@ -468,6 +469,28 @@ int SDL_VideoInit(const char *driver_name)
     if (!driver_name) {
         driver_name = SDL_GetHint(SDL_HINT_VIDEODRIVER);
     }
+#ifdef __LINUX__
+    if (!driver_name) {
+        /* See if it looks like we need X11 */
+        SDL_bool force_x11 = SDL_FALSE;
+        void *global_symbols = dlopen(NULL, RTLD_LOCAL|RTLD_NOW);
+
+        /* Use linked libraries to detect what quirks we are likely to need */
+        if (global_symbols != NULL) {
+            if (dlsym(global_symbols, "glxewInit") != NULL) {  /* GLEW (e.g. Frogatto, SLUDGE) */
+                force_x11 = SDL_TRUE;
+            } else if (dlsym(global_symbols, "cgGLEnableProgramProfiles") != NULL) {  /* NVIDIA Cg (e.g. Awesomenauts, Braid) */
+                force_x11 = SDL_TRUE;
+            } else if (dlsym(global_symbols, "_Z7ssgInitv") != NULL) {  /* ::ssgInit(void) in plib (e.g. crrcsim) */
+                force_x11 = SDL_TRUE;
+            }
+            dlclose(global_symbols);
+        }
+        if (force_x11) {
+            driver_name = "x11";
+        }
+    }
+#endif
     if (driver_name && *driver_name != 0) {
         const char *driver_attempt = driver_name;
         while (driver_attempt && *driver_attempt != 0 && !video) {