SDL: [KMSDRM] Unload GL/EGL libs and destroy GBM only when we are destroying the last window.

From 82ff6045fa0aa7ff2f861f20512e30688c7b51c3 Mon Sep 17 00:00:00 2001
From: vanfanel <[EMAIL REDACTED]>
Date: Thu, 18 Mar 2021 12:02:54 +0100
Subject: [PATCH] [KMSDRM] Unload GL/EGL libs and destroy GBM only when we are
 destroying the last window.

---
 src/video/kmsdrm/SDL_kmsdrmvideo.c | 20 ++++++++++++--------
 1 file changed, 12 insertions(+), 8 deletions(-)

diff --git a/src/video/kmsdrm/SDL_kmsdrmvideo.c b/src/video/kmsdrm/SDL_kmsdrmvideo.c
index ef3568a10..703b8768a 100644
--- a/src/video/kmsdrm/SDL_kmsdrmvideo.c
+++ b/src/video/kmsdrm/SDL_kmsdrmvideo.c
@@ -1079,7 +1079,7 @@ KMSDRM_DestroyWindow(_THIS, SDL_Window *window)
         return;
     }
 
-    if ( !is_vulkan && viddata->gbm_init ) {
+    if ( !is_vulkan && viddata->gbm_init) {
 
         /* Destroy the window display's cursor GBM BO. */
         KMSDRM_DestroyCursorBO(_this, SDL_GetDisplayForWindow(window));
@@ -1087,14 +1087,18 @@ KMSDRM_DestroyWindow(_THIS, SDL_Window *window)
         /* Destroy GBM surface and buffers. */
         KMSDRM_DestroySurfaces(_this, window);
 
-        /* Unload EGL/GL library and free egl_data.  */
-        if (_this->egl_data) {
-            SDL_EGL_UnloadLibrary(_this);
-            _this->gl_config.driver_loaded = 0;
-        }
+        /* Unload library and deinit GBM, but only if this is the last remaining window.*/
+        if (viddata->num_windows < 2) {
+
+	    /* Unload EGL/GL library and free egl_data.  */
+	    if (_this->egl_data) {
+		SDL_EGL_UnloadLibrary(_this);
+		_this->gl_config.driver_loaded = 0;
+	    }
 
-        /* Free display plane, and destroy GBM device. */
-        KMSDRM_GBMDeinit(_this, dispdata);
+	    /* Free display plane, and destroy GBM device. */
+	    KMSDRM_GBMDeinit(_this, dispdata);
+	}
 
     } else {