From cd2a51a66f52767c20e80361033c573651b3a08d Mon Sep 17 00:00:00 2001
From: Andy Nichols <nezticle@gmail.com>
Date: Tue, 7 May 2013 15:36:57 +0200
Subject: [PATCH] Fix Invalid Drawable error for QGLWidget on Mac

You are not supposed to call NSOpenGLContext -setView: for a view that
has not yet called drawRect.  We we attempted to do this, we would get
the invalid drawable error, leading to QGLWidgets just drawing garbage.

Task-number: QTBUG-28175
Change-Id: I47aef07b4676f2db8591f98fc1661f6f447bdef9
Reviewed-by: Gabriel de Dietrich <gabriel.dedietrich@digia.com>
---
 src/plugins/platforms/cocoa/qnsview.h  |  3 +++
 src/plugins/platforms/cocoa/qnsview.mm | 17 ++++++++++++++++-
 2 files changed, 19 insertions(+), 1 deletion(-)

diff --git a/src/plugins/platforms/cocoa/qnsview.h b/src/plugins/platforms/cocoa/qnsview.h
index 67b16b4b329..20e82940bd3 100644
--- a/src/plugins/platforms/cocoa/qnsview.h
+++ b/src/plugins/platforms/cocoa/qnsview.h
@@ -69,6 +69,9 @@ QT_END_NAMESPACE
     bool m_sendUpAsRightButton;
     Qt::KeyboardModifiers currentWheelModifiers;
     bool m_subscribesForGlobalFrameNotifications;
+    QCocoaGLContext *m_glContext;
+    bool m_glContextDirty;
+    bool m_drawRectHasBeenCalled;
 }
 
 - (id)init;
diff --git a/src/plugins/platforms/cocoa/qnsview.mm b/src/plugins/platforms/cocoa/qnsview.mm
index a53d6c4e446..7868d058aee 100644
--- a/src/plugins/platforms/cocoa/qnsview.mm
+++ b/src/plugins/platforms/cocoa/qnsview.mm
@@ -85,6 +85,9 @@ static QTouchDevice *touchDevice = 0;
         m_buttons = Qt::NoButton;
         m_sendKeyEvent = false;
         m_subscribesForGlobalFrameNotifications = false;
+        m_glContext = 0;
+        m_glContextDirty = false;
+        m_drawRectHasBeenCalled = false;
         currentCustomDragTypes = 0;
         m_sendUpAsRightButton = false;
 
@@ -150,7 +153,12 @@ static QTouchDevice *touchDevice = 0;
 
 - (void) setQCocoaGLContext:(QCocoaGLContext *)context
 {
-    [context->nsOpenGLContext() setView:self];
+    m_glContext = context;
+    if (m_drawRectHasBeenCalled) {
+        [m_glContext->nsOpenGLContext() setView:self];
+    } else {
+        m_glContextDirty = true;
+    }
     if (!m_subscribesForGlobalFrameNotifications) {
         // NSOpenGLContext expects us to repaint (or update) the view when
         // it changes position on screen. Since this happens unnoticed for
@@ -344,6 +352,13 @@ static QTouchDevice *touchDevice = 0;
 
 - (void) drawRect:(NSRect)dirtyRect
 {
+    if (m_glContext && m_glContextDirty) {
+        [m_glContext->nsOpenGLContext() setView:self];
+        m_glContextDirty = false;
+    } else {
+        m_drawRectHasBeenCalled = true;
+    }
+
     if (!m_backingStore)
         return;
 
-- 
GitLab