From ff6b175a50dd936f4cb1a32eceedc4d63aea1ca7 Mon Sep 17 00:00:00 2001
From: Pierre Rossi <pierre.rossi@digia.com>
Date: Tue, 28 Oct 2014 15:22:05 +0100
Subject: [PATCH] Support Qt::AA_ShareOpenGLContexts

QtWebEngine::initialize happens after QGuiApplication instantiation,
so it is too late to simply set the application attribute.
In that scenario, we don't want to override the shared context and risk
a double free when both QGuiApplication and our cleanup handler try
to delete it.

Change-Id: Id52884abbb0c2380208876d9c00e8ddbfbc21eda
Reviewed-by: Jocelyn Turcotte <jocelyn.turcotte@digia.com>
Reviewed-by: Andras Becsi <andras.becsi@digia.com>
---
 src/webengine/api/qtwebengineglobal.cpp | 17 +++++++++++++----
 1 file changed, 13 insertions(+), 4 deletions(-)

diff --git a/src/webengine/api/qtwebengineglobal.cpp b/src/webengine/api/qtwebengineglobal.cpp
index ea119bba6..b179da2fe 100644
--- a/src/webengine/api/qtwebengineglobal.cpp
+++ b/src/webengine/api/qtwebengineglobal.cpp
@@ -43,6 +43,7 @@
 QT_BEGIN_NAMESPACE
 
 Q_GUI_EXPORT void qt_gl_set_global_share_context(QOpenGLContext *context);
+Q_GUI_EXPORT QOpenGLContext *qt_gl_global_share_context();
 
 namespace QtWebEngine {
 
@@ -54,8 +55,20 @@ static void deleteShareContext()
     shareContext = 0;
 }
 
+// ### Qt 6: unify this logic and Qt::AA_ShareOpenGLContexts.
+// QtWebEngine::initialize was introduced first and meant to be called
+// after the QGuiApplication creation, when AA_ShareOpenGLContexts fills
+// the same need but the flag has to be set earlier.
 void initialize()
 {
+#ifdef Q_OS_WIN32
+    qputenv("QT_D3DCREATE_MULTITHREADED", "1");
+#endif
+
+    // No need to override the shared context if QApplication already set one (e.g with Qt::AA_ShareOpenGLContexts).
+    if (qt_gl_global_share_context())
+        return;
+
     QCoreApplication *app = QCoreApplication::instance();
     if (!app) {
         qFatal("QWebEngine(Widgets)::initialize() must be called after the construction of the application object.");
@@ -69,10 +82,6 @@ void initialize()
     if (shareContext)
         return;
 
-#ifdef Q_OS_WIN32
-    qputenv("QT_D3DCREATE_MULTITHREADED", "1");
-#endif
-
     shareContext = new QOpenGLContext;
     shareContext->create();
     qAddPostRoutine(deleteShareContext);
-- 
GitLab