From ba94e26b8b233456b004084892464ec55b20800c Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Morten=20Johan=20S=C3=B8rvig?=
 <morten.sorvig@theqtcompany.com>
Date: Thu, 20 Aug 2015 15:37:04 +0200
Subject: [PATCH] Cocoa: Clean up context creation.

Make the fallback to creating an unshared context
actually work by using correct [initWithFormat: ]
code.

Warn and return early on context creation failure
instead of continuing and crashing.

Change-Id: Ic88f419eaa717436aefc9c1da36c47e0ccb3e956
Task-number: QTBUG-47825
Reviewed-by: Laszlo Agocs <laszlo.agocs@theqtcompany.com>
---
 src/plugins/platforms/cocoa/qcocoaglcontext.mm | 16 +++++++++++-----
 1 file changed, 11 insertions(+), 5 deletions(-)

diff --git a/src/plugins/platforms/cocoa/qcocoaglcontext.mm b/src/plugins/platforms/cocoa/qcocoaglcontext.mm
index 1d8a1c5e70e..0f9b8b900d0 100644
--- a/src/plugins/platforms/cocoa/qcocoaglcontext.mm
+++ b/src/plugins/platforms/cocoa/qcocoaglcontext.mm
@@ -146,19 +146,25 @@ QCocoaGLContext::QCocoaGLContext(const QSurfaceFormat &format, QPlatformOpenGLCo
 
     QMacAutoReleasePool pool; // For the SG Canvas render thread
 
+    // create native context for the requested pixel format and share
     NSOpenGLPixelFormat *pixelFormat = static_cast <NSOpenGLPixelFormat *>(qcgl_createNSOpenGLPixelFormat(m_format));
     m_shareContext = share ? static_cast<QCocoaGLContext *>(share)->nsOpenGLContext() : nil;
+    m_context = [[NSOpenGLContext alloc] initWithFormat:pixelFormat shareContext:m_shareContext];
 
-    m_context = [NSOpenGLContext alloc];
-    [m_context initWithFormat:pixelFormat shareContext:m_shareContext];
-
+    // retry without sharing on context creation failure.
     if (!m_context && m_shareContext) {
-        // try without shared context
         m_shareContext = nil;
-        [m_context initWithFormat:pixelFormat shareContext:nil];
+        m_context = [[NSOpenGLContext alloc] initWithFormat:pixelFormat shareContext:nil];
+        if (m_context)
+            qWarning("QCocoaGLContext: Falling back to unshared context.");
     }
 
+    // give up if we still did not get a native context
     [pixelFormat release];
+    if (!m_context) {
+        qWarning("QCocoaGLContext: Failed to create context.");
+        return;
+    }
 
     const GLint interval = format.swapInterval() >= 0 ? format.swapInterval() : 1;
     [m_context setValues:&interval forParameter:NSOpenGLCPSwapInterval];
-- 
GitLab