Index: /trunk/src/VBox/Devices/Graphics/DevVGA-SVGA.cpp
===================================================================
--- /trunk/src/VBox/Devices/Graphics/DevVGA-SVGA.cpp	(revision 55839)
+++ /trunk/src/VBox/Devices/Graphics/DevVGA-SVGA.cpp	(revision 55840)
@@ -69,5 +69,9 @@
 #ifdef VBOX_WITH_VMSVGA3D
 # include "DevVGA-SVGA3d.h"
+# ifdef RT_OS_DARWIN
+#  include "DevVGA-SVGA3d-cocoa.h"
+# endif
 #endif
+
 
 /*******************************************************************************
@@ -2203,4 +2207,11 @@
     while (pThread->enmState == PDMTHREADSTATE_RUNNING)
     {
+# if defined(RT_OS_DARWIN) && defined(VBOX_WITH_VMSVGA3D)
+        /*
+         * Should service the run loop every so often.
+         */
+        if (pThis->svga.f3DEnabled)
+            vmsvga3dCocoaServiceRunLoop();
+# endif
 
         /*
Index: /trunk/src/VBox/Devices/Graphics/DevVGA-SVGA3d-cocoa.h
===================================================================
--- /trunk/src/VBox/Devices/Graphics/DevVGA-SVGA3d-cocoa.h	(revision 55839)
+++ /trunk/src/VBox/Devices/Graphics/DevVGA-SVGA3d-cocoa.h	(revision 55840)
@@ -20,5 +20,4 @@
 #include <iprt/types.h>
 #include <VBox/VBoxCocoa.h>
-#include <OpenGL/OpenGL.h>
 
 RT_C_DECLS_BEGIN
@@ -29,19 +28,19 @@
 #endif
 
-#ifdef IN_VMSVGA3D
-# define VMSVGA3D_DECL(type)  DECLEXPORT(type)
+#ifdef IN_VMSVGA3DCOCOA
+# define VMSVGA3DCOCOA_DECL(type)  DECLEXPORT(type)
 #else
-# define VMSVGA3D_DECL(type)  DECLIMPORT(type)
+# define VMSVGA3DCOCOA_DECL(type)  DECLIMPORT(type)
 #endif
 
-VMSVGA3D_DECL(void) vmsvga3dCocoaCreateContext(NativeNSOpenGLContextRef *ppCtx, NativeNSOpenGLContextRef pSharedCtx,
-                                               bool fOtherProfile);
-VMSVGA3D_DECL(void) vmsvga3dCocoaDestroyContext(NativeNSOpenGLContextRef pCtx);
-VMSVGA3D_DECL(void) vmsvga3dCocoaCreateView(NativeNSViewRef *ppView, NativeNSViewRef pParentView);
-VMSVGA3D_DECL(void) vmsvga3dCocoaDestroyView(NativeNSViewRef pView);
-VMSVGA3D_DECL(void) vmsvga3dCocoaViewSetPosition(NativeNSViewRef pView, NativeNSViewRef pParentView, int x, int y);
-VMSVGA3D_DECL(void) vmsvga3dCocoaViewSetSize(NativeNSViewRef pView, int w, int h);
-VMSVGA3D_DECL(void) vmsvga3dCocoaViewMakeCurrentContext(NativeNSViewRef pView, NativeNSOpenGLContextRef pCtx);
-VMSVGA3D_DECL(void) vmsvga3dCocoaSwapBuffers(NativeNSViewRef pView, NativeNSOpenGLContextRef pCtx);
+VMSVGA3DCOCOA_DECL(void) vmsvga3dCocoaServiceRunLoop(void);
+VMSVGA3DCOCOA_DECL(bool) vmsvga3dCocoaCreateViewAndContext(NativeNSViewRef *ppView, NativeNSOpenGLContextRef *ppCtx,
+                                                           NativeNSViewRef pParentView, uint32_t cx, uint32_t cy,
+                                                           NativeNSOpenGLContextRef pSharedCtx, bool fOtherProfile);
+VMSVGA3DCOCOA_DECL(void) vmsvga3dCocoaDestroyViewAndContext(NativeNSViewRef pView, NativeNSOpenGLContextRef pCtx);
+VMSVGA3DCOCOA_DECL(void) vmsvga3dCocoaViewSetPosition(NativeNSViewRef pView, NativeNSViewRef pParentView, int x, int y);
+VMSVGA3DCOCOA_DECL(void) vmsvga3dCocoaViewSetSize(NativeNSViewRef pView, int w, int h);
+VMSVGA3DCOCOA_DECL(void) vmsvga3dCocoaViewMakeCurrentContext(NativeNSViewRef pView, NativeNSOpenGLContextRef pCtx);
+VMSVGA3DCOCOA_DECL(void) vmsvga3dCocoaSwapBuffers(NativeNSViewRef pView, NativeNSOpenGLContextRef pCtx);
 
 RT_C_DECLS_END
Index: /trunk/src/VBox/Devices/Graphics/DevVGA-SVGA3d-cocoa.m
===================================================================
--- /trunk/src/VBox/Devices/Graphics/DevVGA-SVGA3d-cocoa.m	(revision 55839)
+++ /trunk/src/VBox/Devices/Graphics/DevVGA-SVGA3d-cocoa.m	(revision 55840)
@@ -18,4 +18,8 @@
  */
 
+/*******************************************************************************
+*   Header Files                                                               *
+*******************************************************************************/
+#define LOG_GROUP LOG_GROUP_DEV_VMSVGA
 #include "DevVGA-SVGA3d-cocoa.h"
 #import <Cocoa/Cocoa.h>
@@ -24,84 +28,63 @@
 #include <iprt/thread.h>
 #include <iprt/assert.h>
-
-/* Debug macros */
-#if 0 /*def DEBUG_VERBOSE*/
-/*# error "should be disabled!"*/
-# define DEBUG_INFO(text) do { \
-        crWarning text ; \
-        Assert(0); \
-    } while (0)
-
-# define DEBUG_MSG(text) \
-    printf text
-
-# define DEBUG_WARN(text) do { \
-        crWarning text ; \
-        Assert(0); \
-    } while (0)
-
-# define DEBUG_MSG_1(text) \
-    DEBUG_MSG(text)
-
-# define DEBUG_FUNC_ENTER() \
-    int cchDebugFuncEnter = printf("==>%s\n", __PRETTY_FUNCTION__)
-
-#define DEBUG_FUNC_LEAVE() do { \
-        DEBUG_MSG(("<==%s\n", __PRETTY_FUNCTION__)); \
-    } while (0)
-
-#define DEBUG_FUNC_RET(valuefmtnl) do { \
-        DEBUG_MSG(("<==%s returns", __PRETTY_FUNCTION__)); \
-        DEBUG_MSG(valuefmtnl); \
-    } while (0)
-
+#include <iprt/string.h>
+#include <VBox/log.h>
+
+
+/*******************************************************************************
+*   Defined Constants And Macros                                               *
+*******************************************************************************/
+/** @def USE_NSOPENGLVIEW
+ * Define this to experiment with using NSOpenGLView instead 
+ * of NSView.  There are transparency issues with the former, 
+ * so for the time being we're using the latter.  */
+#if 0
+#define USE_NSOPENGLVIEW
+#endif
+
+
+/*******************************************************************************
+*   Structures and Typedefs                                                    *
+*******************************************************************************/
+/**
+ * Argument package for doing this on the main thread.
+ */
+@interface VMSVGA3DCreateViewAndContext : NSObject
+{
+@public
+    /* in */
+    NativeNSViewRef             pParentView; 
+    uint32_t                    cx;
+    uint32_t                    cy;
+    NativeNSOpenGLContextRef    pSharedCtx;
+    bool                        fOtherProfile;
+
+    /* out */
+    NativeNSViewRef             pView;
+    NativeNSOpenGLContextRef    pCtx;
+}
+@end
+
+
+/**
+ * The overlay view.
+ */
+@interface VMSVGA3DOverlayView 
+#ifdef USE_NSOPENGLVIEW
+    : NSOpenGLView
 #else
-
-# define DEBUG_INFO(text) do { \
-        crInfo text ; \
-    } while (0)
-
-# define DEBUG_MSG(text) \
-    do {} while (0)
-
-# define DEBUG_WARN(text) do { \
-        crWarning text ; \
-    } while (0)
-
-# define DEBUG_MSG_1(text) \
-    do {} while (0)
-
-# define DEBUG_FUNC_ENTER() int cchDebugFuncEnter = 0
-# define DEBUG_FUNC_LEAVE() NOREF(cchDebugFuncEnter)
-# define DEBUG_FUNC_RET(valuefmtnl) DEBUG_FUNC_LEAVE()
-
-#endif
-
-# define CHECK_GL_ERROR()\
-    do {} while (0)
-
-
-/** Custom OpenGL context class.
- *
- * This implementation doesn't allow to set a view to the
- * context, but save the view for later use. Also it saves a copy of the
- * pixel format used to create that context for later use. */
-@interface VMSVGA3DOpenGLContext: NSOpenGLContext
-{
-@private
-    NSOpenGLPixelFormat *m_pPixelFormat;
-    NSView              *m_pView;
-}
-- (NSOpenGLPixelFormat*)openGLPixelFormat;
-@end
-
-@interface VMSVGA3DOverlayView: NSView
+    : NSView
+#endif
 {
 @private
     NSView          *m_pParentView;
-    NSWindow        *m_pOverlayWin;
-    
-    NSOpenGLContext *m_pGLCtx;
-    
+    /** Set if the buffers needs clearing. */
+    bool            m_fClear;
+
+#ifndef USE_NSOPENGLVIEW
+    /** The OpenGL context associated with this view. */
+    NSOpenGLContext *m_pCtx;
+#endif
+
     /* Position/Size tracking */
     NSPoint          m_Pos;
@@ -110,276 +93,29 @@
     /** This is necessary for clipping on the root window */
     NSRect           m_RootRect;
-    float            m_yInvRootOffset;
-}
-- (id)initWithFrame:(NSRect)frame parentView:(NSView*)pparentView;
-- (void)setGLCtx:(NSOpenGLContext*)pCtx;
-- (NSOpenGLContext*)glCtx;
-- (void)setOverlayWin: (NSWindow*)win;
-- (NSWindow*)overlayWin;
+}
++ (void)createViewAndContext:(VMSVGA3DCreateViewAndContext *)pParams;
+- (id)initWithFrameAndFormat:(NSRect)frame parentView:(NSView*)pparentView pixelFormat:(NSOpenGLPixelFormat *)pFmt;
 - (void)setPos:(NSPoint)pos;
-- (NSPoint)pos;
 - (void)setSize:(NSSize)size;
-- (NSSize) size;
-- (void)updateViewportCS;
-- (void)reshape;
+- (void)vboxReshape;
+- (void)vboxClearBuffers;
+- (NSOpenGLContext *)makeCurrentGLContext;
+- (void)restoreSavedGLContext:(NSOpenGLContext *)pSavedCtx;
+
+#ifndef USE_NSOPENGLVIEW
+/* NSOpenGLView fakes: */
+- (void)setOpenGLContext:(NSOpenGLContext *)pCtx;
+- (NSOpenGLContext *)openGLContext;
+- (void)prepareOpenGL;
+
+#endif
+/* Overridden: */    
+- (void)viewDidMoveToWindow;
+- (void)viewDidMoveToSuperview;
+- (void)resizeWithOldSuperviewSize:(NSSize)oldBoundsSize;
+- (void)drawRect:(NSRect)rect;
+
 @end
 
-/** Helper view.
- *
- * This view is added as a sub view of the parent view to track
- * main window changes. Whenever the main window is changed
- * (which happens on fullscreen/seamless entry/exit) the overlay
- * window is informed & can add them self as a child window
- * again. */
-@class VMSVGA3DOverlayWindow;
-@interface VMSVGA3DOverlayHelperView: NSView
-{
-@private
-    VMSVGA3DOverlayWindow *m_pOverlayWindow;
-}
--(id)initWithOverlayWindow:(VMSVGA3DOverlayWindow*)pOverlayWindow;
-@end
-
-/** Custom window class.
- *
- * This is the overlay window which contains our custom NSView.
- * Its a direct child of the Qt Main window. It marks its background
- * transparent & non opaque to make clipping possible. It also disable mouse
- * events and handle frame change events of the parent view. */
-@interface VMSVGA3DOverlayWindow: NSWindow
-{
-@private
-    NSView                    *m_pParentView;
-    VMSVGA3DOverlayView       *m_pOverlayView;
-    VMSVGA3DOverlayHelperView *m_pOverlayHelperView;
-    NSThread                  *m_Thread;
-}
-- (id)initWithParentView:(NSView*)pParentView overlayView:(VMSVGA3DOverlayView*)pOverlayView;
-- (void)parentWindowFrameChanged:(NSNotification *)note;
-- (void)parentWindowChanged:(NSWindow*)pWindow;
-@end
-
-
-/********************************************************************************
-*
-* VMSVGA3DOpenGLContext class implementation
-*
-********************************************************************************/
-@implementation VMSVGA3DOpenGLContext
-
--(id)initWithFormat:(NSOpenGLPixelFormat*)format shareContext:(NSOpenGLContext*)share
-{
-    DEBUG_FUNC_ENTER();
-
-    m_pPixelFormat = NULL;
-    m_pView = NULL;
-
-    self = [super initWithFormat:format shareContext:share];
-    if (self)
-        m_pPixelFormat = format;
-
-    DEBUG_MSG(("OCTX(%p): init VMSVGA3DOpenGLContext\n", (void*)self));
-    DEBUG_FUNC_RET(("%p\n", (void *)self));
-    return self;
-}
-
-- (void)dealloc
-{
-    DEBUG_FUNC_ENTER();
-    DEBUG_MSG(("OCTX(%p): dealloc VMSVGA3DOpenGLContext\n", (void*)self));
-
-    [m_pPixelFormat release];
-
-m_pPixelFormat = NULL;
-m_pView = NULL;
-
-    [super dealloc];
-    DEBUG_FUNC_LEAVE();
-}
-
--(bool)isDoubleBuffer
-{
-    DEBUG_FUNC_ENTER();
-    GLint val;
-    [m_pPixelFormat getValues:&val forAttribute:NSOpenGLPFADoubleBuffer forVirtualScreen:0];
-    DEBUG_FUNC_RET(("%d\n", val == 1 ? YES : NO));
-    return val == 1 ? YES : NO;
-}
-
--(void)setView:(NSView*)view
-{
-    DEBUG_FUNC_ENTER();
-    DEBUG_MSG(("OCTX(%p): setView: new view: %p\n", (void*)self, (void*)view));
-
-    m_pView = view;
-
-    DEBUG_FUNC_LEAVE();
-}
-
--(NSView*)view
-{
-    DEBUG_FUNC_ENTER();
-    DEBUG_FUNC_RET(("%p\n", (void *)m_pView));
-    return m_pView;
-}
-
--(void)clearDrawable
-{
-    DEBUG_FUNC_ENTER();
-    DEBUG_MSG(("OCTX(%p): clearDrawable\n", (void*)self));
-
-    m_pView = NULL;
-    [super clearDrawable];
-
-    DEBUG_FUNC_LEAVE();
-}
-
--(NSOpenGLPixelFormat*)openGLPixelFormat
-{
-    DEBUG_FUNC_ENTER();
-    DEBUG_FUNC_RET(("%p\n", (void *)m_pPixelFormat));
-    return m_pPixelFormat;
-}
-
-@end
-
-
-
-/********************************************************************************
-*
-* VMSVGA3DOverlayHelperView class implementation
-*
-********************************************************************************/
-@implementation VMSVGA3DOverlayHelperView
-
--(id)initWithOverlayWindow:(VMSVGA3DOverlayWindow*)pOverlayWindow
-{
-    DEBUG_FUNC_ENTER();
-
-    self = [super initWithFrame:NSZeroRect];
-
-    m_pOverlayWindow = pOverlayWindow;
-
-    DEBUG_MSG(("OHVW(%p): init OverlayHelperView\n", (void*)self));
-    DEBUG_FUNC_RET(("%p\n", (void *)self));
-    return self;
-}
-
--(void)viewDidMoveToWindow
-{
-    DEBUG_FUNC_ENTER();
-    DEBUG_MSG(("OHVW(%p): viewDidMoveToWindow: new win: %p\n", (void*)self, (void*)[self window]));
-
-    [m_pOverlayWindow parentWindowChanged:[self window]];
-
-    DEBUG_FUNC_LEAVE();
-}
-
-@end
-
-/********************************************************************************
-*
-* VMSVGA3DOverlayWindow class implementation
-*
-********************************************************************************/
-@implementation VMSVGA3DOverlayWindow
-
-- (id)initWithParentView:(NSView*)pParentView overlayView:(VMSVGA3DOverlayView*)pOverlayView
-{
-    DEBUG_FUNC_ENTER();
-    NSWindow *pParentWin = nil;
-
-    if((self = [super initWithContentRect:NSZeroRect styleMask:NSBorderlessWindowMask backing:NSBackingStoreBuffered defer:NO]))
-    {
-        m_pParentView = pParentView;
-        m_pOverlayView = pOverlayView;
-        m_Thread = [NSThread currentThread];
-
-        [m_pOverlayView setOverlayWin: self];
-
-        m_pOverlayHelperView = [[VMSVGA3DOverlayHelperView alloc] initWithOverlayWindow:self];
-        /* Add the helper view as a child of the parent view to get notifications */
-        [pParentView addSubview:m_pOverlayHelperView];
-
-        /* Make sure this window is transparent */
-#ifdef SHOW_WINDOW_BACKGROUND
-        /* For debugging */
-        [self setBackgroundColor:[NSColor colorWithCalibratedRed:1.0 green:0.0 blue:0.0 alpha:0.7]];
-#else
-        [self setBackgroundColor:[NSColor clearColor]];
-#endif
-        [self setOpaque:NO];
-        [self setAlphaValue:.999];
-        /* Disable mouse events for this window */
-        [self setIgnoresMouseEvents:YES];
-
-        pParentWin = [m_pParentView window];
-
-        /* Initial set the position to the parents view top/left (Compiz fix). */
-        [self setFrameOrigin:
-            [pParentWin convertBaseToScreen:
-                [m_pParentView convertPoint:NSZeroPoint toView:nil]]];
-
-        /* Set the overlay view as our content view */
-        [self setContentView:m_pOverlayView];
-
-        /* Add ourself as a child to the parent views window. Note: this has to
-         * be done last so that everything else is setup in
-         * parentWindowChanged. */
-        [pParentWin addChildWindow:self ordered:NSWindowAbove];
-    }
-    DEBUG_MSG(("OWIN(%p): init OverlayWindow\n", (void*)self));
-    DEBUG_FUNC_RET(("%p\n", (void *)self));
-    return self;
-}
-
-- (void)dealloc
-{
-    DEBUG_FUNC_ENTER();
-    DEBUG_MSG(("OWIN(%p): dealloc OverlayWindow\n", (void*)self));
-
-    [[NSNotificationCenter defaultCenter] removeObserver:self];
-
-    [m_pOverlayHelperView removeFromSuperview];
-    [m_pOverlayHelperView release];
-
-    [super dealloc];
-    DEBUG_FUNC_LEAVE();
-}
-
-- (void)parentWindowFrameChanged:(NSNotification*)pNote
-{
-    DEBUG_FUNC_ENTER();
-    DEBUG_MSG(("OWIN(%p): parentWindowFrameChanged\n", (void*)self));
-
-    [m_pOverlayView reshape];
-
-    DEBUG_FUNC_LEAVE();
-}
-
-- (void)parentWindowChanged:(NSWindow*)pWindow
-{
-    DEBUG_FUNC_ENTER();
-    DEBUG_MSG(("OWIN(%p): parentWindowChanged\n", (void*)self));
-
-    [[NSNotificationCenter defaultCenter] removeObserver:self];
-
-    if(pWindow != nil)
-    {
-        /* Ask to get notifications when our parent window frame changes. */
-        [[NSNotificationCenter defaultCenter]
-            addObserver:self
-            selector:@selector(parentWindowFrameChanged:)
-            name:NSWindowDidResizeNotification
-            object:pWindow];
-        /* Add us self as child window */
-        [pWindow addChildWindow:self ordered:NSWindowAbove];
-        [m_pOverlayView reshape];
-    }
-
-    DEBUG_FUNC_LEAVE();
-}
-
-@end
 
 /********************************************************************************
@@ -390,244 +126,13 @@
 @implementation VMSVGA3DOverlayView
 
-- (id)initWithFrame:(NSRect) frame parentView:(NSView*)pParentView
-{
-    DEBUG_FUNC_ENTER();
-
-    m_pParentView    = pParentView;
-    /* Make some reasonable defaults */
-    m_pGLCtx         = nil;
-    m_Pos            = NSZeroPoint;
-    m_Size           = NSMakeSize(1, 1);
-    m_RootRect       = NSMakeRect(0, 0, m_Size.width, m_Size.height);
-    m_yInvRootOffset = 0;
-    
-    self = [super initWithFrame: frame];
-    
-    DEBUG_MSG(("OVIW(%p): init VMSVGA3DOverlayView\n", (void*)self));
-    DEBUG_FUNC_RET(("%p\n", (void *)self));
-    return self;
-}
-
-- (void)cleanupData
-{
-    DEBUG_FUNC_ENTER();
-
-    /*[self deleteDockTile];*/
-    
-    [self setGLCtx:nil];
-    
-#if 0
-    if (m_pSharedGLCtx)
-    {
-        if ([m_pSharedGLCtx view] == self)
-            [m_pSharedGLCtx clearDrawable];
-
-        [m_pSharedGLCtx release];
-
-        m_pSharedGLCtx = nil;
-        
-        CrBltTerm(m_pBlitter);
-        
-        RTMemFree(m_pBlitter);
-        
-        m_pBlitter = nil;
-    }
-#endif
-
-    /*[self clearVisibleRegions];*/
-    
-    DEBUG_FUNC_LEAVE();
-}
-
-- (void)dealloc
-{
-    DEBUG_FUNC_ENTER();
-    DEBUG_MSG(("OVIW(%p): dealloc OverlayView\n", (void*)self));
-
-    [self cleanupData];
-
-    [super dealloc];
-
-    DEBUG_FUNC_LEAVE();
-}
-
-
-- (void)setGLCtx:(NSOpenGLContext*)pCtx
-{
-    DEBUG_FUNC_ENTER();
-
-    DEBUG_MSG(("OVIW(%p): setGLCtx: new ctx: %p (old: %p)\n", (void*)self, (void*)pCtx, (void *)m_pGLCtx));
-    if (m_pGLCtx == pCtx)
-    {
-        DEBUG_FUNC_LEAVE();
-        return;
-    }
-
-    /* ensure the context drawable is cleared to avoid holding a reference to inexistent view */
-    if (m_pGLCtx)
-    {
-        [m_pGLCtx clearDrawable];
-        [m_pGLCtx release];
-        /*[m_pGLCtx performSelectorOnMainThread:@selector(release) withObject:nil waitUntilDone:NO];*/
-    }
-    m_pGLCtx = pCtx;
-    if (pCtx)
-        [pCtx retain];
-
-    DEBUG_FUNC_LEAVE();
-}
-
-- (NSOpenGLContext*)glCtx
-{
-    DEBUG_FUNC_ENTER();
-    DEBUG_FUNC_RET(("%p\n", (void *)m_pGLCtx));
-    return m_pGLCtx;
-}
-
-- (void)setOverlayWin:(NSWindow*)pWin
-{
-    DEBUG_FUNC_ENTER();
-    DEBUG_MSG(("OVIW(%p): setOverlayWin: new win: %p\n", (void*)self, (void*)pWin));
-    m_pOverlayWin = pWin;
-    DEBUG_FUNC_LEAVE();
-}
-
-- (NSWindow*)overlayWin
-{
-    DEBUG_FUNC_ENTER();
-    DEBUG_FUNC_RET(("%p\n", (void *)m_pOverlayWin));
-    return m_pOverlayWin;
-}
-
-- (void)setPos:(NSPoint)pos
-{
-    DEBUG_FUNC_ENTER();
-
-    m_Pos = pos;
-    [self reshape];
-    DEBUG_FUNC_LEAVE();
-}
-
-- (NSPoint)pos
-{
-    DEBUG_FUNC_ENTER();
-    DEBUG_FUNC_RET(("%f,%f\n", m_Pos.x, m_Pos.y));
-    return m_Pos;
-}
-
-- (void)setSize:(NSSize)size
-{
-    DEBUG_FUNC_ENTER();
-    m_Size = size;
-    [self reshape];
-    DEBUG_FUNC_LEAVE();
-}
-
-- (NSSize)size
-{
-    DEBUG_FUNC_ENTER();
-    DEBUG_FUNC_RET(("%f,%f\n", m_Size.width, m_Size.height));
-    return m_Size;
-}
-
-- (void)updateViewportCS
-{
-    DEBUG_FUNC_ENTER();
-    DEBUG_MSG(("OVIW(%p): updateViewport\n", (void*)self));
-
-    /* Update the viewport for our OpenGL view */
-/*    [m_pSharedGLCtx update]; */
-        
-    /* Clear background to transparent */
-/*    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);*/
-    DEBUG_FUNC_LEAVE();
-}
-
-- (void)reshape
-{
-    DEBUG_FUNC_ENTER();
-    NSRect parentFrame = NSZeroRect;
-    NSPoint parentPos  = NSZeroPoint;
-    NSPoint childPos   = NSZeroPoint;
-    NSRect childFrame  = NSZeroRect;
-    NSRect newFrame    = NSZeroRect;
-
-    DEBUG_MSG(("OVIW(%p): reshape\n", (void*)self));
-
-    /* Getting the right screen coordinates of the parents frame is a little bit
-     * complicated. */
-    parentFrame = [m_pParentView frame];
-    DEBUG_MSG(("FIXED parentFrame [%f:%f], [%f:%f]\n", parentFrame.origin.x, parentFrame.origin.y, parentFrame.size.width, parentFrame.size.height));    
-    parentPos = [[m_pParentView window] convertBaseToScreen:[[m_pParentView superview] convertPointToBase:NSMakePoint(parentFrame.origin.x, parentFrame.origin.y + parentFrame.size.height)]];
-    parentFrame.origin.x = parentPos.x;
-    parentFrame.origin.y = parentPos.y;
-
-    /* Calculate the new screen coordinates of the overlay window. */
-    childPos = NSMakePoint(m_Pos.x, m_Pos.y + m_Size.height);
-    childPos = [[m_pParentView window] convertBaseToScreen:[[m_pParentView superview] convertPointToBase:childPos]];
-    DEBUG_MSG(("FIXED childPos(screen) [%f:%f]\n", childPos.x, childPos.y));
-
-    /* Make a frame out of it. */
-    childFrame = NSMakeRect(childPos.x, childPos.y, m_Size.width, m_Size.height);
-    DEBUG_MSG(("FIXED childFrame [%f:%f], [%f:%f]\n", childFrame.origin.x, childFrame.origin.y, childFrame.size.width, childFrame.size.height));
-
-    /* We have to make sure that the overlay window will not be displayed out
-     * of the parent window. So intersect both frames & use the result as the new
-     * frame for the window. */
-    newFrame = NSIntersectionRect(parentFrame, childFrame);
-
-    DEBUG_MSG(("[%p]: parentFrame pos[%f : %f] size[%f : %f]\n",
-          (void*)self, 
-         parentFrame.origin.x, parentFrame.origin.y,
-         parentFrame.size.width, parentFrame.size.height));
-    DEBUG_MSG(("[%p]: childFrame pos[%f : %f] size[%f : %f]\n",
-          (void*)self, 
-         childFrame.origin.x, childFrame.origin.y,
-         childFrame.size.width, childFrame.size.height));
-         
-    DEBUG_MSG(("[%p]: newFrame pos[%f : %f] size[%f : %f]\n",
-          (void*)self, 
-         newFrame.origin.x, newFrame.origin.y,
-         newFrame.size.width, newFrame.size.height));
-    
-    /* Later we have to correct the texture position in the case the window is
-     * out of the parents window frame. So save the shift values for later use. */ 
-    m_RootRect.origin.x = newFrame.origin.x - childFrame.origin.x;
-    m_RootRect.origin.y =  childFrame.size.height + childFrame.origin.y - (newFrame.size.height + newFrame.origin.y);
-    m_RootRect.size = newFrame.size;
-    m_yInvRootOffset = newFrame.origin.y - childFrame.origin.y;
-    
-    DEBUG_MSG(("[%p]: m_RootRect pos[%f : %f] size[%f : %f]\n",
-         (void*)self, 
-         m_RootRect.origin.x, m_RootRect.origin.y,
-         m_RootRect.size.width, m_RootRect.size.height));
-
-    /* Set the new frame. */
-    [[self window] setFrame:newFrame display:YES];
-
-#if 0
-    /* Make sure the context is updated according */
-    /* [self updateViewport]; */
-    if (m_pSharedGLCtx)
-    {
-        VBOX_CR_RENDER_CTX_INFO CtxInfo; 
-        vboxCtxEnter(m_pSharedGLCtx, &CtxInfo);
-    
-        [self updateViewportCS];
-    
-        vboxCtxLeave(&CtxInfo);
-    }
-#endif
-    DEBUG_FUNC_LEAVE();
-}
-
-@end
-
-
-void vmsvga3dCocoaCreateContext(NativeNSOpenGLContextRef *ppCtx, NativeNSOpenGLContextRef pShareCtx, bool fOtherProfile)
-{
-    DEBUG_FUNC_ENTER();
+
++ (void)createViewAndContext:(VMSVGA3DCreateViewAndContext *)pParams
+{
+    LogFlow(("OvlWin createViewAndContext:\n"));
+
+    /*
+     * Create a pixel format.
+     */
     NSOpenGLPixelFormat *pFmt = nil;
-    NSAutoreleasePool *pPool = [[NSAutoreleasePool alloc] init];
 
     // Consider to remove it and check if it's harmless.
@@ -638,4 +143,5 @@
         NSOpenGLPFAAccelerated,
         NSOpenGLPFADoubleBuffer,
+        NSOpenGLPFABackingStore,
         NSOpenGLPFAColorSize, (NSOpenGLPixelFormatAttribute)24,
         NSOpenGLPFAAlphaSize, (NSOpenGLPixelFormatAttribute)8,
@@ -643,95 +149,412 @@
         0
     };
-    attribs[1] = fOtherProfile ? NSOpenGLProfileVersion3_2Core : NSOpenGLProfileVersionLegacy;
-
-    /* Choose a pixel format */
+    attribs[1] = pParams->fOtherProfile ? NSOpenGLProfileVersion3_2Core : NSOpenGLProfileVersionLegacy;
     pFmt = [[NSOpenGLPixelFormat alloc] initWithAttributes:attribs];
     if (pFmt)
     {
-        *ppCtx = [[VMSVGA3DOpenGLContext alloc] initWithFormat:pFmt shareContext:pShareCtx];
-        DEBUG_MSG(("New context %p\n", (void *)*ppCtx));
+        /*
+         * Create a new view.
+         */
+        NSRect Frame;
+        Frame.origin.x    = 0;
+        Frame.origin.y    = 0;
+        Frame.size.width  = pParams->cx < _1M ? pParams->cx : 0;
+        Frame.size.height = pParams->cy < _1M ? pParams->cy : 0;
+        VMSVGA3DOverlayView *pView = [[VMSVGA3DOverlayView alloc] initWithFrameAndFormat:Frame
+                                                                              parentView:pParams->pParentView
+                                                                             pixelFormat:pFmt];
+        if (pView)
+        {
+            /*
+             * If we have no shared GL context, we use the one that NSOpenGLView create. Otherwise, 
+             * we replace it.  (If we don't call openGLContext, it won't yet have been instantiated, 
+             * so there is no unecessary contexts created here when pSharedCtx != NULL.)
+             */
+            NSOpenGLContext *pCtx;
+#ifdef USE_NSOPENGLVIEW
+            if (!pParams->pSharedCtx)
+                pCtx = [pView openGLContext];
+            else
+#endif
+            {
+                pCtx = [[NSOpenGLContext alloc] initWithFormat:pFmt shareContext: pParams->pSharedCtx];
+                if (pCtx)
+                {
+                    [pView setOpenGLContext:pCtx];
+                    [pCtx setView:pView];
+#ifdef USE_NSOPENGLVIEW
+                    Assert([pCtx view] == pView);
+#endif
+                }
+            }
+            if (pCtx)
+            {
+                /* 
+                 * Attach the view to the parent.
+                 */
+                [pParams->pParentView addSubview:pView];
+
+                /*
+                 * Resize and return.
+                 */
+                //[pView setSize:Frame.size];
+
+                NSOpenGLContext *pSavedCtx = [pView makeCurrentGLContext];
+
+                [pView prepareOpenGL];
+                GLint x;
+                //x = 0; [pCtx setValues:&x forParameter:NSOpenGLCPSwapInterval];
+                //x = 1; [pCtx setValues:&x forParameter:NSOpenGLCPSurfaceOrder];
+                x = 0; [pCtx setValues:&x forParameter:NSOpenGLCPSurfaceOpacity];
+
+                [pView setHidden:NO];
+
+                [pView restoreSavedGLContext:pSavedCtx];
+
+                pParams->pView = pView;
+                pParams->pCtx  = pCtx;
+                [pCtx retain]; //??
+
+                [pFmt release];
+                LogFlow(("OvlWin createViewAndContext: returns successfully\n"));
+                return;
+            }
+            [pView release];
+        }
+        [pFmt release];
     }
     else
-    {
         AssertFailed();
-        *ppCtx = NULL;
+
+    LogFlow(("OvlWin createViewAndContext: returns failure\n"));
+    return;
+}
+
+- (id)initWithFrameAndFormat:(NSRect) frame parentView:(NSView*)pParentView pixelFormat:(NSOpenGLPixelFormat *)pFmt
+{
+    LogFlow(("OvlWin(%p) initWithFrameAndFormat:\n", (void *)self));
+
+    m_pParentView    = pParentView;
+    /* Make some reasonable defaults */
+    m_Pos            = NSZeroPoint;
+    m_Size           = frame.size;
+    m_RootRect       = NSMakeRect(0, 0, m_Size.width, m_Size.height);
+    
+#ifdef USE_NSOPENGLVIEW
+    self = [super initWithFrame:frame pixelFormat:pFmt];
+#else
+    self = [super initWithFrame:frame];
+#endif
+    if (self)
+    {
+        self.autoresizingMask = NSViewMinXMargin | NSViewMaxXMargin | NSViewMinYMargin | NSViewMaxYMargin;
+    }
+    LogFlow(("OvlWin(%p) initWithFrameAndFormat: returns %p\n", (void *)self, (void *)self));
+    return self;
+}
+
+- (void)dealloc
+{
+    LogFlow(("OvlWin(%p) dealloc:\n", (void *)self));
+
+#ifdef USE_NSOPENGLVIEW
+    [[self openGLContext] clearDrawable];
+#else
+    if (m_pCtx)
+    {
+        [m_pCtx clearDrawable];
+        [m_pCtx release];
+        m_pCtx = nil;
+    }
+#endif
+
+    [super dealloc];
+
+    LogFlow(("OvlWin(%p) dealloc: returns\n", (void *)self));
+}
+
+
+- (void)setPos:(NSPoint)pos
+{
+    Log(("OvlWin(%p) setPos: (%d,%d)\n", (void *)self, (int)pos.x, (int)pos.y));
+
+    m_Pos = pos;
+    [self vboxReshape];
+
+    LogFlow(("OvlWin(%p) setPos: returns\n", (void *)self));
+}
+
+
+- (void)setSize:(NSSize)size
+{
+    Log(("OvlWin(%p) setSize: (%d,%d):\n", (void *)self, (int)size.width, (int)size.height));
+    m_Size = size;
+    [self vboxReshape];
+    LogFlow(("OvlWin(%p) setSize: returns\n", (void *)self));
+}
+
+
+- (void)vboxClearBuffers
+{
+#if 1 /* experiment */
+    if ([NSThread isMainThread])
+        Log(("OvlWin(%p) vboxClearBuffers: skip, main thread\n", (void *)self));
+    else
+    {
+        Log(("OvlWin(%p) vboxClearBuffers: clears\n", (void *)self));
+        NSOpenGLContext *pSavedCtx = [self makeCurrentGLContext];
+
+        GLint iOldDrawBuf = GL_BACK;
+        glGetIntegerv(GL_DRAW_BUFFER, &iOldDrawBuf);
+        glDrawBuffer(GL_FRONT_AND_BACK);
+        glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
+        glClear(GL_COLOR_BUFFER_BIT /*|GL_DEPTH_BUFFER_BIT*/ );
+        [[self openGLContext] flushBuffer];
+        glDrawBuffer(iOldDrawBuf);
+
+        [self restoreSavedGLContext:pSavedCtx];
+    }
+#endif
+}
+
+
+- (void)vboxReshape
+{
+    LogFlow(("OvlWin(%p) vboxReshape:\n", (void *)self));
+
+    /*
+     * Not doing any complicate stuff here yet, hoping that we'll get correctly 
+     * resized when the parent view changes...
+     */
+
+    /*
+     * Tell the GL context.
+     */
+    //[[self openGLContext] setView:self];
+    [[self openGLContext] update];
+
+    [self vboxClearBuffers];
+
+    LogFlow(("OvlWin(%p) vboxReshape: returns\n", (void *)self));
+}
+
+
+/** 
+ * Changes to the OpenGL context associated with the view. 
+ * @returns Previous OpenGL context. 
+ */ 
+- (NSOpenGLContext *)makeCurrentGLContext
+{
+    NSOpenGLContext *pSavedCtx = [NSOpenGLContext currentContext];
+
+    /* Always flush before changing. glXMakeCurrent and wglMakeCurrent does this
+       implicitly, seemingly NSOpenGLContext::makeCurrentContext doesn't. */
+    if (pSavedCtx != nil)
+        glFlush();
+
+    [[self openGLContext] makeCurrentContext];
+    return pSavedCtx;
+}
+
+
+/**
+ * Restores the previous OpenGL context after 
+ * makeCurrentGLContext. 
+ *  
+ * @param pSavedCtx     The makeCurrentGLContext return value.
+ */
+- (void)restoreSavedGLContext:(NSOpenGLContext *)pSavedCtx
+{
+    /* Always flush before changing. glXMakeCurrent and wglMakeCurrent does this
+       implicitly, seemingly NSOpenGLContext::makeCurrentContext doesn't. */
+    glFlush();
+
+    if (pSavedCtx)
+        [pSavedCtx makeCurrentContext];
+    else
+        [NSOpenGLContext clearCurrentContext];
+}
+
+#ifndef USE_NSOPENGLVIEW
+/*
+ * Faking NSOpenGLView interface.
+ */
+- (void)setOpenGLContext:(NSOpenGLContext *)pCtx
+{
+    if (pCtx != m_pCtx)
+    {
+        if (pCtx)
+        {
+            [pCtx retain];
+            [pCtx setView:self];
+            /*Assert([pCtx view] == self); - setView fails early on, works later... */
+        }
+
+        if (m_pCtx)
+            [m_pCtx release];
+
+        m_pCtx = pCtx;
+
+        if (pCtx)
+            [pCtx update];
+    }
+}
+
+- (NSOpenGLContext *)openGLContext
+{
+    /* Stupid hack to work around setView failing early. */
+    if (m_pCtx && [m_pCtx view] != self)
+        [m_pCtx setView:self];
+    return m_pCtx;
+}
+
+- (void)prepareOpenGL
+{
+    //[m_pCtx prepareOpenGL];
+}
+#endif /* USE_NSOPENGLVIEW */
+
+/* 
+ * Overridden NSOpenGLView / NSView methods:
+ */
+
+-(void)viewDidMoveToWindow
+{
+    LogFlow(("OvlView(%p) viewDidMoveToWindow: new win: %p\n", (void *)self, (void *)[self window]));
+    [super viewDidMoveToWindow];
+    [self vboxReshape];
+}
+
+-(void)viewDidMoveToSuperview
+{
+    LogFlow(("OvlView(%p) viewDidMoveToSuperview: new view: %p\n", (void *)self, (void *)[self superview]));
+    [super viewDidMoveToSuperview];
+    [self vboxReshape];
+}
+
+-(void)resizeWithOldSuperviewSize:(NSSize)oldBoundsSize
+{
+    LogFlow(("OvlView(%p) resizeWithOldSuperviewSize: %d,%d -> %d,%d\n", (void *)self, 
+             (int)oldBoundsSize.width, (int)oldBoundsSize.height, (int)[self bounds].size.width, (int)[self bounds].size.height));
+    [super resizeWithOldSuperviewSize:oldBoundsSize];
+    [self vboxReshape];
+}
+
+- (void)drawRect:(NSRect)rect
+{
+    if (m_fClear)
+    {
+        m_fClear = false;
+        [self vboxClearBuffers];
+    }
+}
+
+@end /* VMSVGA3DOverlayView */
+
+@implementation VMSVGA3DCreateViewAndContext
+@end
+
+
+VMSVGA3DCOCOA_DECL(void) vmsvga3dCocoaServiceRunLoop(void)
+{
+    NSAutoreleasePool *pPool = [[NSAutoreleasePool alloc] init];
+    NSRunLoop *pRunLoop = [NSRunLoop currentRunLoop];
+
+    if ([NSRunLoop mainRunLoop] != pRunLoop)
+    {
+        [pRunLoop runUntilDate:[NSDate distantPast]];
     }
 
     [pPool release];
-
-    DEBUG_FUNC_LEAVE();
-}
-
-void vmsvga3dCocoaDestroyContext(NativeNSOpenGLContextRef pCtx)
-{
-    DEBUG_FUNC_ENTER();
+}
+
+
+VMSVGA3DCOCOA_DECL(bool) vmsvga3dCocoaCreateViewAndContext(NativeNSViewRef *ppView, NativeNSOpenGLContextRef *ppCtx,
+                                                           NativeNSViewRef pParentView, uint32_t cx, uint32_t cy,
+                                                           NativeNSOpenGLContextRef pSharedCtx, bool fOtherProfile)
+{
+    LogFlow(("vmsvga3dCocoaCreateViewAndContext: pParentView=%d size=%d,%d pSharedCtx=%p fOtherProfile=%RTbool\n", 
+             (void *)pParentView, cx, cy, (void *)pSharedCtx, fOtherProfile));
     NSAutoreleasePool *pPool = [[NSAutoreleasePool alloc] init];
+    vmsvga3dCocoaServiceRunLoop();
+
+
+    VMSVGA3DCreateViewAndContext *pParams = [VMSVGA3DCreateViewAndContext alloc];
+    pParams->pParentView = pParentView;
+    pParams->cx = cx;
+    pParams->cy = cy;
+    pParams->pSharedCtx = pSharedCtx;
+    pParams->fOtherProfile = fOtherProfile;
+    pParams->pView = NULL;
+    pParams->pCtx = NULL;
+
+    [VMSVGA3DOverlayView performSelectorOnMainThread:@selector(createViewAndContext:)
+                                          withObject:pParams
+                                       waitUntilDone:YES];
+
+    vmsvga3dCocoaServiceRunLoop();
+
+    *ppCtx  = pParams->pCtx;
+    *ppView = pParams->pView;
+    bool fRet = *ppCtx != NULL && *ppView != NULL;
+
+    [pParams release];
+
+    [pPool release];
+    LogFlow(("vmsvga3dCocoaDestroyContext: returns %RTbool\n", fRet));
+    return fRet;
+}
+
+
+VMSVGA3DCOCOA_DECL(void) vmsvga3dCocoaDestroyViewAndContext(NativeNSViewRef pView, NativeNSOpenGLContextRef pCtx)
+{
+    LogFlow(("vmsvga3dCocoaDestroyViewAndContext: pView=%p pCtx=%p\n", (void *)pView, (void *)pCtx));
+    NSAutoreleasePool *pPool = [[NSAutoreleasePool alloc] init];
+
+    /* The view */
+    [pView removeFromSuperview];
+    [pView setHidden: YES];
+    Log(("vmsvga3dCocoaDestroyViewAndContext: view %p ref count=%d\n", (void *)pView, [pView retainCount]));
+    [pView release];
+
+    /* The OpenGL context. */
+    Log(("vmsvga3dCocoaDestroyViewAndContext: ctx  %p ref count=%d\n", (void *)pCtx, [pView retainCount]));
     [pCtx release];
+
     [pPool release];
-    DEBUG_FUNC_LEAVE();
-}
-
-void vmsvga3dCocoaCreateView(NativeNSViewRef *ppView, NativeNSViewRef pParentView)
-{
-    DEBUG_FUNC_ENTER();
+    LogFlow(("vmsvga3dCocoaDestroyViewAndContext: returns\n"));
+}
+
+
+VMSVGA3DCOCOA_DECL(void) vmsvga3dCocoaViewSetPosition(NativeNSViewRef pView, NativeNSViewRef pParentView, int x, int y)
+{
+    LogFlow(("vmsvga3dCocoaViewSetPosition: pView=%p pParentView=%p (%d,%d)\n", (void *)pView, (void *)pParentView, x, y));
     NSAutoreleasePool *pPool = [[NSAutoreleasePool alloc] init];
-    
-    /* Create our worker view */
-    VMSVGA3DOverlayView* pView = [[VMSVGA3DOverlayView alloc] initWithFrame:NSZeroRect parentView:pParentView];
-
-    if (pView)
-    {
-        /* We need a real window as container for the view */
-        [[VMSVGA3DOverlayWindow alloc] initWithParentView:pParentView overlayView:pView];
-        /* Return the freshly created overlay view */
-        *ppView = pView;
-    }
-    
+
+    [(VMSVGA3DOverlayView *)pView setPos:NSMakePoint(x, y)];
+
     [pPool release];
-    DEBUG_FUNC_LEAVE();
-}
-
-void vmsvga3dCocoaDestroyView(NativeNSViewRef pView)
-{
-    DEBUG_FUNC_ENTER();
-    NSWindow *pWin = nil;
-    
+    LogFlow(("vmsvga3dCocoaViewSetPosition: returns\n"));
+}
+
+
+VMSVGA3DCOCOA_DECL(void) vmsvga3dCocoaViewSetSize(NativeNSViewRef pView, int cx, int cy)
+{
+    LogFlow(("vmsvga3dCocoaViewSetSize: pView=%p (%d,%d)\n", (void *)pView, cx, cy));
     NSAutoreleasePool *pPool = [[NSAutoreleasePool alloc] init];
-    [pView setHidden: YES];
-    
-    [pWin release];
-    [pView release];
+    VMSVGA3DOverlayView *pOverlayView = (VMSVGA3DOverlayView *)pView;
+
+    [pOverlayView setSize:NSMakeSize(cx, cy)];
 
     [pPool release];
-    DEBUG_FUNC_LEAVE();
-}
-
-void vmsvga3dCocoaViewSetPosition(NativeNSViewRef pView, NativeNSViewRef pParentView, int x, int y)
-{
-    DEBUG_FUNC_ENTER();
+    LogFlow(("vmsvga3dCocoaViewSetSize: returns\n"));
+}
+
+
+void vmsvga3dCocoaViewMakeCurrentContext(NativeNSViewRef pView, NativeNSOpenGLContextRef pCtx)
+{
+    LogFlow(("vmsvga3dCocoaViewSetSize: pView=%p, pCtx=%p\n", (void*)pView, (void*)pCtx));
     NSAutoreleasePool *pPool = [[NSAutoreleasePool alloc] init];
-
-    [(VMSVGA3DOverlayView*)pView setPos:NSMakePoint(x, y)];
-
-    [pPool release];
-}
-
-void vmsvga3dCocoaViewSetSize(NativeNSViewRef pView, int w, int h)
-{
-    DEBUG_FUNC_ENTER();
-    NSAutoreleasePool *pPool = [[NSAutoreleasePool alloc] init];
-
-    [(VMSVGA3DOverlayView*)pView setSize:NSMakeSize(w, h)];
-
-    [pPool release];
-    DEBUG_FUNC_LEAVE();
-}
-
-void vmsvga3dCocoaViewMakeCurrentContext(NativeNSViewRef pView, NativeNSOpenGLContextRef pCtx)
-{
-    DEBUG_FUNC_ENTER();
-    NSAutoreleasePool *pPool = [[NSAutoreleasePool alloc] init];
-
-    DEBUG_MSG(("cocoaViewMakeCurrentContext(%p, %p)\n", (void*)pView, (void*)pCtx));
+    VMSVGA3DOverlayView *pOverlayView = (VMSVGA3DOverlayView *)pView;
 
     /* Always flush before flush. glXMakeCurrent and wglMakeCurrent does this
@@ -740,28 +563,43 @@
         glFlush();
 
-    if (pView)
-    {
-        [(VMSVGA3DOverlayView*)pView setGLCtx:pCtx];
-/*        [(VMSVGA3DOverlayView*)pView makeCurrentFBO];*/
+    if (pOverlayView)
+    {
+        /* This must be a release assertion as we depend on the setView
+           sideeffect of the openGLContext method call. (hack alert!) */
+        AssertRelease([pOverlayView openGLContext] == pCtx);
         [pCtx makeCurrentContext];
     }
     else
-    {
     	[NSOpenGLContext clearCurrentContext];
-    }
 
     [pPool release];
-    DEBUG_FUNC_LEAVE();
-}
+    LogFlow(("vmsvga3dCocoaSwapBuffers: returns\n"));
+}
+
 
 void vmsvga3dCocoaSwapBuffers(NativeNSViewRef pView, NativeNSOpenGLContextRef pCtx)
 {
-    DEBUG_FUNC_ENTER();
+    LogFlow(("vmsvga3dCocoaSwapBuffers: pView=%p, pCtx=%p\n", (void*)pView, (void*)pCtx));
     NSAutoreleasePool *pPool = [[NSAutoreleasePool alloc] init];
-    
+
+#ifndef USE_NSOPENGLVIEW
+    /* Hack alert! setView fails early on so call openGLContext to try again. */
+    VMSVGA3DOverlayView *pMyView = (VMSVGA3DOverlayView *)pView;
+    if ([pCtx view] == NULL)
+        [pMyView openGLContext];
+#elif defined(RT_STRICT)
+    NSOpenGLView *pMyView = (NSOpenGLView *)pView;
+#endif
+
+    Assert(pCtx == [NSOpenGLContext currentContext]);
+    Assert(pCtx == [pMyView openGLContext]);
+    AssertMsg([pCtx view] == pMyView, ("%p != %p\n", (void *)[pCtx view], (void *)pMyView));
+
     [pCtx flushBuffer];
+    //[pView setNeedsDisplay:YES];
+    vmsvga3dCocoaServiceRunLoop();
     
     [pPool release];
-    DEBUG_FUNC_LEAVE();
-}
-
+    LogFlow(("vmsvga3dCocoaSwapBuffers: returns\n"));
+}
+
Index: /trunk/src/VBox/Devices/Graphics/DevVGA-SVGA3d-ogl.cpp
===================================================================
--- /trunk/src/VBox/Devices/Graphics/DevVGA-SVGA3d-ogl.cpp	(revision 55839)
+++ /trunk/src/VBox/Devices/Graphics/DevVGA-SVGA3d-ogl.cpp	(revision 55840)
@@ -3872,11 +3872,4 @@
     PVMSVGA3DCONTEXT    pContext;
     uint32_t            cid;
-    struct
-    {
-        uint32_t        x;
-        uint32_t        y;
-        uint32_t        cx;
-        uint32_t        cy;
-    } srcViewPort;
 
     AssertReturn(pState, VERR_NO_MEMORY);
@@ -3923,12 +3916,16 @@
     VMSVGA3D_CLEAR_GL_ERRORS();
 
-    /* Source surface different size? */
-    if (pSurface->pMipmapLevels[0].size.width  != pThis->svga.uWidth ||
-        pSurface->pMipmapLevels[0].size.height != pThis->svga.uHeight)
+    /*
+     * Source surface different size?
+     */
+    RTRECT2 srcViewPort;
+    if (   pSurface->pMipmapLevels[0].size.width  != pThis->svga.uWidth
+        || pSurface->pMipmapLevels[0].size.height != pThis->svga.uHeight)
     {
         float xMultiplier = (float)pSurface->pMipmapLevels[0].size.width / (float)pThis->svga.uWidth;
         float yMultiplier = (float)pSurface->pMipmapLevels[0].size.height / (float)pThis->svga.uHeight;
 
-        LogFlow(("size (%d vs %d) (%d vs %d) multiplier %d\n", pSurface->pMipmapLevels[0].size.width, pThis->svga.uWidth, pSurface->pMipmapLevels[0].size.height, pThis->svga.uHeight, (int)(xMultiplier * 100.0), (int)(yMultiplier * 100.0)));
+        LogFlow(("size (%d vs %d) (%d vs %d) multiplier (%d,%d)/100\n", pSurface->pMipmapLevels[0].size.width, pThis->svga.uWidth,
+                 pSurface->pMipmapLevels[0].size.height, pThis->svga.uHeight, (int)(xMultiplier * 100.0), (int)(yMultiplier * 100.0)));
 
         srcViewPort.x  = (uint32_t)((float)pThis->svga.viewport.x  * xMultiplier);
@@ -3944,7 +3941,15 @@
         srcViewPort.cy = pThis->svga.viewport.cy;
     }
-
-#if 1
-    /* @note this path is slightly faster than the glBlitFrameBuffer path below. */
+    RTRECT SrcViewPortRect;
+    SrcViewPortRect.xLeft   = srcViewPort.x;
+    SrcViewPortRect.xRight  = srcViewPort.x + srcViewPort.cx;
+    SrcViewPortRect.yBottom = srcViewPort.y;
+    SrcViewPortRect.yTop    = srcViewPort.y + srcViewPort.cy;
+
+
+#ifndef RT_OS_DARWIN /* blit-cube fails in this path... */
+    /*
+     * Note! this path is slightly faster than the glBlitFrameBuffer path below.
+     */
     SVGA3dCopyRect rect;
     uint32_t oldVShader, oldPShader;
@@ -4085,8 +4090,8 @@
     vmsvga3dShaderSet(pThis, pContext, cid, SVGA3D_SHADERTYPE_PS, oldPShader);
 
-    /* Reset the frame buffer association */
-    VMSVGA3D_ASSERT_GL_CALL(pState->ext.glBindFramebuffer(GL_FRAMEBUFFER, pContext->idFramebuffer), pState, pContext);
-
 #else
+    /*
+     * glBlitFramebuffer variant.
+     */
     /* Activate the read and draw framebuffer objects. */
     pState->ext.glBindFramebuffer(GL_READ_FRAMEBUFFER, pContext->idReadFramebuffer);
@@ -4101,4 +4106,5 @@
     /* Blit the surface rectangle(s) to the back buffer. */
     if (cRects == 0)
+
     {
         Log(("view port (%d,%d)(%d,%d)\n", srcViewPort.x, srcViewPort.y, srcViewPort.cx, srcViewPort.cy));
@@ -4119,4 +4125,63 @@
         for (uint32_t i = 0; i < cRects; i++)
         {
+# ifdef RT_OS_DARWIN
+            /* This works better... */
+            RTRECT SrcRect;
+            SrcRect.xLeft   = pRect[i].srcx;
+            SrcRect.xRight  = pRect[i].srcx + pRect[i].w;
+            SrcRect.yBottom = pRect[i].srcy;
+            SrcRect.yTop    = pRect[i].srcy + pRect[i].h;
+            RTRECT DstRect; /* y flipped wrt source */
+            DstRect.xLeft   = pRect[i].x;
+            DstRect.xRight  = pRect[i].x + pRect[i].w;
+            DstRect.yBottom = pRect[i].y + pRect[i].h;
+            DstRect.yTop    = pRect[i].y;
+
+            if (SrcRect.xLeft < SrcViewPortRect.xLeft)
+            {
+                DstRect.xLeft += SrcViewPortRect.xLeft - SrcRect.xLeft;
+                SrcRect.xLeft  = SrcViewPortRect.xLeft;
+            }
+            else if (SrcRect.xLeft >= SrcViewPortRect.xRight)
+                continue;
+
+            if (SrcRect.xRight > SrcViewPortRect.xRight)
+            {
+                DstRect.xRight -= SrcViewPortRect.xRight - SrcRect.xRight;
+                SrcRect.xRight  = SrcViewPortRect.xRight;
+            }
+            else if (SrcRect.xRight <= SrcViewPortRect.xLeft)
+                continue;
+
+            if (SrcRect.xRight <= SrcRect.xLeft)
+                continue;
+
+            if (SrcRect.yBottom < SrcViewPortRect.yBottom)
+            {
+                DstRect.yTop    += SrcViewPortRect.yBottom - SrcRect.yBottom;
+                SrcRect.yBottom  = SrcViewPortRect.yBottom;
+            }
+            else if (SrcRect.yBottom >= SrcViewPortRect.yTop)
+                continue;
+
+            if (SrcRect.yTop > SrcViewPortRect.yTop)
+            {
+                DstRect.yBottom -= SrcViewPortRect.yTop - SrcRect.yTop;
+                SrcRect.yTop     = SrcViewPortRect.yTop;
+            }
+            else if (SrcRect.yTop <= SrcViewPortRect.yBottom)
+                continue;
+
+            if (SrcRect.yTop <= SrcRect.yBottom)
+                continue;
+
+            Log(("SrcRect: (%d,%d)(%d,%d) DstRect: (%d,%d)(%d,%d)\n",
+                 SrcRect.xLeft, SrcRect.yBottom, SrcRect.xRight, SrcRect.yTop,
+                 DstRect.xLeft, DstRect.yBottom, DstRect.xRight, DstRect.yTop));
+            pState->ext.glBlitFramebuffer(SrcRect.xLeft, SrcRect.yBottom, SrcRect.xRight, SrcRect.yTop,
+                                          DstRect.xLeft, DstRect.yBottom, DstRect.xRight, DstRect.yTop,
+                                          GL_COLOR_BUFFER_BIT, GL_LINEAR);
+
+# else
             if (    pRect[i].x + pRect[i].w <= pThis->svga.viewport.x
                 ||  pThis->svga.viewport.x + pThis->svga.viewport.cx <= pRect[i].x
@@ -4127,5 +4192,4 @@
                 continue;
             }
-
             pState->ext.glBlitFramebuffer(RT_MAX(pRect[i].srcx, srcViewPort.x),
                                           pSurface->pMipmapLevels[0].size.width - RT_MAX(pRect[i].srcy, srcViewPort.y),   /* exclusive. (reverse to flip the image) */
@@ -4138,12 +4202,17 @@
                                           GL_COLOR_BUFFER_BIT,
                                           GL_LINEAR);
-        }
-    }
-    /* Reset the frame buffer association */
-    pState->ext.glBindFramebuffer(GL_FRAMEBUFFER, pContext->idFramebuffer);
-    VMSVGA3D_CHECK_LAST_ERROR_WARN(pState, pContext);
-#endif
-
-    /* Flip the front and back buffers. */
+# endif
+        }
+    }
+
+#endif
+#ifndef RT_OS_DARWIN /* darwin: later */
+    /* Reset the frame buffer association - see below.  */
+    VMSVGA3D_ASSERT_GL_CALL(pState->ext.glBindFramebuffer(GL_FRAMEBUFFER, pContext->idFramebuffer), pState, pContext);
+#endif
+
+    /*
+     * Flip the front and back buffers.
+     */
 #ifdef RT_OS_WINDOWS
     BOOL ret = SwapBuffers(pContext->hdc);
@@ -4160,4 +4229,12 @@
     /* now swap the buffers, i.e. display the rendering result */
     glXSwapBuffers(pState->display, pContext->window);
+#endif
+
+#if defined(RT_OS_DARWIN)
+    /*
+     * Now we can reset the frame buffer association.  Doing it earlier means no
+     * output on darwin.
+     */
+    VMSVGA3D_ASSERT_GL_CALL(pState->ext.glBindFramebuffer(GL_FRAMEBUFFER, pContext->idFramebuffer), pState, pContext);
 #endif
     return VINF_SUCCESS;
@@ -4387,8 +4464,9 @@
     pContext->fOtherProfile = RT_BOOL(fFlags & VMSVGA3D_DEF_CTX_F_OTHER_PROFILE);
 
-    NativeNSOpenGLContextRef shareContext = pSharedCtx ? pSharedCtx->cocoaContext : NULL;
-    vmsvga3dCocoaCreateContext(&pContext->cocoaContext, shareContext, pContext->fOtherProfile);
-    NativeNSViewRef pHostView = (NativeNSViewRef)pThis->svga.u64HostWindowId;
-    vmsvga3dCocoaCreateView(&pContext->cocoaView, pHostView);
+    NativeNSOpenGLContextRef pShareContext = pSharedCtx ? pSharedCtx->cocoaContext : NULL;
+    NativeNSViewRef          pHostView    = (NativeNSViewRef)pThis->svga.u64HostWindowId;
+    vmsvga3dCocoaCreateViewAndContext(&pContext->cocoaView, &pContext->cocoaContext,
+                                      pHostView, pThis->svga.uWidth, pThis->svga.uHeight,
+                                      pShareContext, pContext->fOtherProfile);
 
 #else
@@ -4619,6 +4697,5 @@
         AssertRC(rc);
 #elif defined(RT_OS_DARWIN)
-        vmsvga3dCocoaDestroyView(pContext->cocoaView);
-        vmsvga3dCocoaDestroyContext(pContext->cocoaContext);
+        vmsvga3dCocoaDestroyViewAndContext(pContext->cocoaView, pContext->cocoaContext);
 #elif defined(RT_OS_LINUX)
         glXMakeCurrent(pState->display, None, NULL);
Index: /trunk/src/VBox/Devices/Graphics/VBoxSVGA3DObjC.def
===================================================================
--- /trunk/src/VBox/Devices/Graphics/VBoxSVGA3DObjC.def	(revision 55839)
+++ /trunk/src/VBox/Devices/Graphics/VBoxSVGA3DObjC.def	(revision 55840)
@@ -18,8 +18,7 @@
 LIBRARY VBoxSVGA3DObjC
 EXPORTS 
-    vmsvga3dCocoaCreateContext              
-    vmsvga3dCocoaDestroyContext             
-    vmsvga3dCocoaCreateView                 
-    vmsvga3dCocoaDestroyView                
+    vmsvga3dCocoaServiceRunLoop
+    vmsvga3dCocoaCreateViewAndContext
+    vmsvga3dCocoaDestroyViewAndContext             
     vmsvga3dCocoaViewSetPosition            
     vmsvga3dCocoaViewSetSize                
Index: /trunk/src/VBox/Devices/Makefile.kmk
===================================================================
--- /trunk/src/VBox/Devices/Makefile.kmk	(revision 55839)
+++ /trunk/src/VBox/Devices/Makefile.kmk	(revision 55840)
@@ -1489,5 +1489,5 @@
  DLLS.darwin += VBoxSVGA3DObjC
  VBoxSVGA3DObjC_TEMPLATE    = VBoxSVGA3D
- VBoxSVGA3DObjC_DEFS        = $(VBoxSVGA3D_DEFS)
+ VBoxSVGA3DObjC_DEFS        = $(VBoxSVGA3D_DEFS) IN_VMSVGA3DCOCOA
  VBoxSVGA3DObjC_DEFS.x86    = __i386__
  VBoxSVGA3DObjC_DEFS.amd64  = __x86_64__
@@ -1499,5 +1499,5 @@
  	-install_name $(VBOX_DYLD_EXECUTABLE_PATH)/VBoxSVGA3DObjC.dylib \
  	-framework OpenGL
- if 0
+ if 1
  VBoxSVGA3DObjC_SOURCES.darwin += \
  	Graphics/DevVGA-SVGA3d-cocoa.m
Index: /trunk/src/VBox/HostServices/SharedOpenGL/render/renderspu_cocoa_helper.m
===================================================================
--- /trunk/src/VBox/HostServices/SharedOpenGL/render/renderspu_cocoa_helper.m	(revision 55839)
+++ /trunk/src/VBox/HostServices/SharedOpenGL/render/renderspu_cocoa_helper.m	(revision 55840)
@@ -239,4 +239,91 @@
 
 
+/**
+ * Works functions that creates a NSOpenGLPixelFormat instance. 
+ *  
+ * @returns Instance.
+ * @param   fVisParams          Context flags.
+ */
+static NSOpenGLPixelFormat *vboxCreatePixelFormat(GLbitfield fVisParams)
+{
+    NSOpenGLPixelFormatAttribute attribs[24] =
+    {
+#ifdef IN_VMSVGA3D
+        NSOpenGLPFAOpenGLProfile, (NSOpenGLPixelFormatAttribute)0,
+#endif
+        NSOpenGLPFAAccelerated,
+        NSOpenGLPFAColorSize, (NSOpenGLPixelFormatAttribute)24
+    };
+#ifndef IN_VMSVGA3D
+    int i = 3;
+#else
+    int i = 3+2;
+    if (fVisParams & VMSVGA3D_NON_DEFAULT_PROFILE_BIT)
+        attribs[1] = VBOX_VMSVGA3D_DEFAULT_OGL_PROFILE >= 3.2 ? NSOpenGLProfileVersionLegacy :  NSOpenGLProfileVersion3_2Core;
+    else
+        attribs[1] = VBOX_VMSVGA3D_DEFAULT_OGL_PROFILE >= 3.2 ? NSOpenGLProfileVersion3_2Core : NSOpenGLProfileVersionLegacy;
+#endif
+
+    if (fVisParams & CR_ALPHA_BIT)
+    {
+        COCOA_LOG_FLOW(("  CR_ALPHA_BIT requested\n"));
+        attribs[i++] = NSOpenGLPFAAlphaSize;
+        attribs[i++] = 8;
+    }
+    if (fVisParams & CR_DEPTH_BIT)
+    {
+        COCOA_LOG_FLOW(("  CR_DEPTH_BIT requested\n"));
+        attribs[i++] = NSOpenGLPFADepthSize;
+        attribs[i++] = 24;
+    }
+    if (fVisParams & CR_STENCIL_BIT)
+    {
+        COCOA_LOG_FLOW(("  CR_STENCIL_BIT requested\n"));
+        attribs[i++] = NSOpenGLPFAStencilSize;
+        attribs[i++] = 8;
+    }
+    if (fVisParams & CR_ACCUM_BIT)
+    {
+        COCOA_LOG_FLOW(("  CR_ACCUM_BIT requested\n"));
+        attribs[i++] = NSOpenGLPFAAccumSize;
+        if (fVisParams & CR_ALPHA_BIT)
+            attribs[i++] = 32;
+        else
+            attribs[i++] = 24;
+    }
+    if (fVisParams & CR_MULTISAMPLE_BIT)
+    {
+        COCOA_LOG_FLOW(("  CR_MULTISAMPLE_BIT requested\n"));
+        attribs[i++] = NSOpenGLPFASampleBuffers;
+        attribs[i++] = 1;
+        attribs[i++] = NSOpenGLPFASamples;
+        attribs[i++] = 4;
+    }
+    if (fVisParams & CR_DOUBLE_BIT)
+    {
+        COCOA_LOG_FLOW(("  CR_DOUBLE_BIT requested\n"));
+        attribs[i++] = NSOpenGLPFADoubleBuffer;
+    }
+    if (fVisParams & CR_STEREO_BIT)
+    {
+        /* We don't support that.
+        COCOA_LOG_FLOW(("  CR_STEREO_BIT requested\n"));
+        attribs[i++] = NSOpenGLPFAStereo;
+        */
+    }
+
+    if (VBoxOglIsOfflineRenderingAppropriate())
+    {
+        COCOA_LOG_FLOW(("  Offline rendering is enabled\n"));
+        attribs[i++] = NSOpenGLPFAAllowOfflineRenderers;
+    }
+
+    /* Mark the end */
+    attribs[i++] = 0;
+
+    /* Instantiate the pixel format object. */
+    return [[NSOpenGLPixelFormat alloc] initWithAttributes:attribs];
+}
+
 
 static NSOpenGLContext *vboxCtxGetCurrent(void)
@@ -807,5 +894,6 @@
     bool                m_fEverSized;
 }
-- (id)initWithFrame:(NSRect)frame thread:(RTTHREAD)aThread parentView:(NSView *)pParentView winInfo:(WindowInfo *)pWinInfo;
+- (id)initWithFrame:(NSRect)frame thread:(RTTHREAD)aThread parentView:(NSView *)pParentView winInfo:(WindowInfo *)pWinInfo 
+         fVisParams:(GLbitfield) fVisParams;
 - (void)setGLCtx:(NSOpenGLContext*)pCtx;
 - (NSOpenGLContext *)glCtx;
@@ -887,5 +975,5 @@
     OverlayWindow *m_pOverlayWindow;
 }
--(id)initWithOverlayWindow:(OverlayWindow *)pOverlayWindow;
+-(id)initWithOverlayWindow:(NSRect)frame overlayWindow:(OverlayWindow *)pOverlayWindow;
 @end
 
@@ -1172,9 +1260,12 @@
 @implementation OverlayHelperView
 
--(id)initWithOverlayWindow:(OverlayWindow *)pOverlayWindow
+-(id)initWithOverlayWindow:(NSRect)frame overlayWindow:(OverlayWindow *)pOverlayWindow
 {
     DEBUG_FUNC_ENTER();
 
-    self = [super initWithFrame:NSZeroRect];
+    self = [super initWithFrame:frame];
+#ifdef IN_VMSVGA3D
+    self.autoresizingMask = NSViewWidthSizable | NSViewHeightSizable;
+#endif
 
     m_pOverlayWindow = pOverlayWindow;
@@ -1219,5 +1310,13 @@
         [m_pOverlayView setOverlayWin: self];
 
-        m_pOverlayHelperView = [[OverlayHelperView alloc] initWithOverlayWindow:self];
+#ifdef IN_VMSVGA3D                                                                           
+        NSRect frame = [pParentView frame];
+        frame.origin.x = frame.origin.x = 0;
+        m_pOverlayHelperView = [[OverlayHelperView alloc] initWithOverlayWindow:frame
+                                                                  overlayWindow:self];
+#else
+        m_pOverlayHelperView = [[OverlayHelperView alloc] initWithOverlayWindow:NSZeroRect
+                                                                  overlayWindow:self];
+#endif
 
         /* Add the helper view as a child of the parent view to get notifications */
@@ -1348,8 +1447,9 @@
 @implementation OverlayView
 
-- (id)initWithFrame:(NSRect)frame thread:(RTTHREAD)aThread parentView:(NSView *)pParentView winInfo:(WindowInfo *)pWinInfo
-{
-    COCOA_LOG_FLOW(("%s: self=%p aThread=%p pParentView=%p pWinInfo=%p\n", __PRETTY_FUNCTION__, (void *)self, 
-                    (void *)aThread, (void *)pParentView, (void *)pWinInfo));
+- (id)initWithFrame:(NSRect)frame thread:(RTTHREAD)aThread parentView:(NSView *)pParentView winInfo:(WindowInfo *)pWinInfo 
+         fVisParams:(GLbitfield) fVisParams
+{
+    COCOA_LOG_FLOW(("%s: self=%p aThread=%p pParentView=%p pWinInfo=%p fVisParams=%#x\n", __PRETTY_FUNCTION__, (void *)self, 
+                    (void *)aThread, (void *)pParentView, (void *)pWinInfo, fVisParams));
 
     m_pParentView             = pParentView;
@@ -2755,84 +2855,6 @@
     COCOA_LOG_FLOW(("cocoaGLCtxCreate: ppCtx=%p fVisParams=%#x pSharedCtx=%p\n", (void *)ppCtx, fVisParams, (void *)pSharedCtx));
     NSAutoreleasePool *pPool = [[NSAutoreleasePool alloc] init];
-    NSOpenGLPixelFormat *pFmt = nil;
-
-    NSOpenGLPixelFormatAttribute attribs[24] =
-    {
-#ifdef IN_VMSVGA3D
-        NSOpenGLPFAOpenGLProfile, (NSOpenGLPixelFormatAttribute)0,
-#endif
-        NSOpenGLPFAAccelerated,
-        NSOpenGLPFAColorSize, (NSOpenGLPixelFormatAttribute)24
-    };
-
-    int i = 3;
-
-#ifdef IN_VMSVGA3D
-    if (fVisParams & VMSVGA3D_NON_DEFAULT_PROFILE_BIT)
-        attribs[1] = VBOX_VMSVGA3D_DEFAULT_OGL_PROFILE >= 3.2 ? NSOpenGLProfileVersionLegacy :  NSOpenGLProfileVersion3_2Core;
-    else
-        attribs[1] = VBOX_VMSVGA3D_DEFAULT_OGL_PROFILE >= 3.2 ? NSOpenGLProfileVersion3_2Core : NSOpenGLProfileVersionLegacy;
-#endif
-
-    if (fVisParams & CR_ALPHA_BIT)
-    {
-        COCOA_LOG_FLOW(("  CR_ALPHA_BIT requested\n"));
-        attribs[i++] = NSOpenGLPFAAlphaSize;
-        attribs[i++] = 8;
-    }
-    if (fVisParams & CR_DEPTH_BIT)
-    {
-        COCOA_LOG_FLOW(("  CR_DEPTH_BIT requested\n"));
-        attribs[i++] = NSOpenGLPFADepthSize;
-        attribs[i++] = 24;
-    }
-    if (fVisParams & CR_STENCIL_BIT)
-    {
-        COCOA_LOG_FLOW(("  CR_STENCIL_BIT requested\n"));
-        attribs[i++] = NSOpenGLPFAStencilSize;
-        attribs[i++] = 8;
-    }
-    if (fVisParams & CR_ACCUM_BIT)
-    {
-        COCOA_LOG_FLOW(("  CR_ACCUM_BIT requested\n"));
-        attribs[i++] = NSOpenGLPFAAccumSize;
-        if (fVisParams & CR_ALPHA_BIT)
-            attribs[i++] = 32;
-        else
-            attribs[i++] = 24;
-    }
-    if (fVisParams & CR_MULTISAMPLE_BIT)
-    {
-        COCOA_LOG_FLOW(("  CR_MULTISAMPLE_BIT requested\n"));
-        attribs[i++] = NSOpenGLPFASampleBuffers;
-        attribs[i++] = 1;
-        attribs[i++] = NSOpenGLPFASamples;
-        attribs[i++] = 4;
-    }
-    if (fVisParams & CR_DOUBLE_BIT)
-    {
-        COCOA_LOG_FLOW(("  CR_DOUBLE_BIT requested\n"));
-        attribs[i++] = NSOpenGLPFADoubleBuffer;
-    }
-    if (fVisParams & CR_STEREO_BIT)
-    {
-        /* We don't support that.
-        COCOA_LOG_FLOW(("  CR_STEREO_BIT requested\n"));
-        attribs[i++] = NSOpenGLPFAStereo;
-        */
-    }
-
-    if (VBoxOglIsOfflineRenderingAppropriate())
-    {
-        COCOA_LOG_FLOW(("  Offline rendering is enabled\n"));
-        attribs[i++] = NSOpenGLPFAAllowOfflineRenderers;
-    }
-
-    /* Mark the end */
-    attribs[i++] = 0;
-
-    /* Choose a pixel format */
-    pFmt = [[NSOpenGLPixelFormat alloc] initWithAttributes:attribs];
-
+
+    NSOpenGLPixelFormat *pFmt = vboxCreatePixelFormat(fVisParams);
     if (pFmt)
     {
@@ -2875,7 +2897,7 @@
 *
 ********************************************************************************/
-static OverlayView *vboxViewCreate(WindowInfo *pWinInfo, NativeNSViewRef pParentView)
-{
-    COCOA_LOG_FLOW(("vboxViewCreate: pWinInfo=%p pParentView=%p\n", pWinInfo, (void *)pParentView));
+static OverlayView *vboxViewCreate(WindowInfo *pWinInfo, NativeNSViewRef pParentView, GLbitfield fVisParams)
+{
+    COCOA_LOG_FLOW(("vboxViewCreate: pWinInfo=%p pParentView=%p fVisParams=%#x\n", pWinInfo, (void *)pParentView, fVisParams));
 
     /* Create our worker view. */
@@ -2883,5 +2905,6 @@
                                                      thread:RTThreadSelf() 
                                                  parentView:pParentView 
-                                                    winInfo:pWinInfo];
+                                                    winInfo:pWinInfo
+                                                 fVisParams:fVisParams];
 
     if (pView)
@@ -2912,5 +2935,5 @@
 {
     CR_RCD_CREATEVIEW *pCreateView = (CR_RCD_CREATEVIEW *)pvCb;
-    pCreateView->pView = vboxViewCreate(pCreateView->pWinInfo, pCreateView->pParentView);
+    pCreateView->pView = vboxViewCreate(pCreateView->pWinInfo, pCreateView->pParentView, pCreateView->fVisParams);
     COCOA_LOG_FLOW(("vboxRcdCreateView: returns pView=%p\n", (void *)pCreateView->pView));
 }
@@ -2948,5 +2971,5 @@
         dispatch_sync(dispatch_get_main_queue(), ^{
 #endif
-            *ppView = vboxViewCreate(pWinInfo, pParentView);
+            *ppView = vboxViewCreate(pWinInfo, pParentView, fVisParams);
 #if 0
         });
@@ -3033,6 +3056,7 @@
     COCOA_LOG_FLOW(("cocoaViewSetSize: pView=%p cx=%d cy=%d\n", (void *)pView, cx, cy));
     NSAutoreleasePool *pPool = [[NSAutoreleasePool alloc] init];
-
-    [(OverlayView *)pView vboxSetSize:NSMakeSize(cx, cy)];
+    OverlayView *pOverlayView = (OverlayView *)pView;
+
+    [pOverlayView vboxSetSize:NSMakeSize(cx, cy)];
 
     [pPool release];
@@ -3191,37 +3215,47 @@
  */
 
-VMSVGA3D_DECL(void) vmsvga3dCocoaCreateContext(NativeNSOpenGLContextRef *ppCtx, NativeNSOpenGLContextRef pSharedCtx, 
-                                               bool fOtherProfile)
-{
-    cocoaGLCtxCreate(ppCtx, CR_ALPHA_BIT | CR_DEPTH_BIT | CR_DOUBLE_BIT | (fOtherProfile ? VMSVGA3D_NON_DEFAULT_PROFILE_BIT : 0), 
-                     pSharedCtx);
-}
-
-VMSVGA3D_DECL(void) vmsvga3dCocoaDestroyContext(NativeNSOpenGLContextRef pCtx)
+VMSVGA3DCOCOA_DECL(bool) vmsvga3dCocoaCreateViewAndContext(NativeNSViewRef *ppView, NativeNSOpenGLContextRef *ppCtx,
+                                                           NativeNSViewRef pParentView, uint32_t cx, uint32_t cy,
+                                                           NativeNSOpenGLContextRef pSharedCtx, bool fOtherProfile)
+{
+    NSAutoreleasePool *pPool = [[NSAutoreleasePool alloc] init];
+    GLbitfield fVisParams = CR_ALPHA_BIT | CR_DEPTH_BIT | CR_DOUBLE_BIT | (fOtherProfile ? VMSVGA3D_NON_DEFAULT_PROFILE_BIT : 0);
+    bool fRc = false;
+
+    cocoaGLCtxCreate(ppCtx, fVisParams, pSharedCtx);
+    if (*ppCtx)
+    {
+        cocoaViewCreate(ppView, NULL, pParentView, fVisParams);
+        if (*ppView)
+        {
+            cocoaViewSetSize(*ppView, cx, cy);
+            [(OverlayView *)*ppView setGLCtx: *ppCtx];
+            fRc = true;
+        }
+        else
+            [*ppCtx release];
+    }
+
+    [pPool release];
+    return fRc;
+}
+
+VMSVGA3DCOCOA_DECL(void) vmsvga3dCocoaDestroyViewAndContext(NativeNSViewRef pView, NativeNSOpenGLContextRef pCtx)
 {
     cocoaGLCtxDestroy(pCtx);
-}
-
-VMSVGA3D_DECL(void) vmsvga3dCocoaCreateView(NativeNSViewRef *ppView, NativeNSViewRef pParentView)
-{
-    cocoaViewCreate(ppView, NULL, pParentView, 0 /* fVisParams - ignored */);
-}
-
-VMSVGA3D_DECL(void) vmsvga3dCocoaDestroyView(NativeNSViewRef pView)
-{
     cocoaViewDestroy(pView);
 }
 
-VMSVGA3D_DECL(void) vmsvga3dCocoaViewSetPosition(NativeNSViewRef pView, NativeNSViewRef pParentView, int x, int y)
+VMSVGA3DCOCOA_DECL(void) vmsvga3dCocoaViewSetPosition(NativeNSViewRef pView, NativeNSViewRef pParentView, int x, int y)
 {
     cocoaViewSetPosition(pView, pParentView, x, y);
 }
 
-VMSVGA3D_DECL(void) vmsvga3dCocoaViewSetSize(NativeNSViewRef pView, int w, int h)
+VMSVGA3DCOCOA_DECL(void) vmsvga3dCocoaViewSetSize(NativeNSViewRef pView, int w, int h)
 {
     cocoaViewSetSize(pView, w, h);
 }
 
-VMSVGA3D_DECL(void) vmsvga3dCocoaViewMakeCurrentContext(NativeNSViewRef pView, NativeNSOpenGLContextRef pCtx)
+VMSVGA3DCOCOA_DECL(void) vmsvga3dCocoaViewMakeCurrentContext(NativeNSViewRef pView, NativeNSOpenGLContextRef pCtx)
 {
     Assert(!pView || [(OverlayView *)pView glCtx] == pCtx || [(OverlayView *)pView glCtx] == nil);
@@ -3229,12 +3263,16 @@
 }
 
-VMSVGA3D_DECL(void) vmsvga3dCocoaSwapBuffers(NativeNSViewRef pView, NativeNSOpenGLContextRef pCtx)
+VMSVGA3DCOCOA_DECL(void) vmsvga3dCocoaSwapBuffers(NativeNSViewRef pView, NativeNSOpenGLContextRef pCtx)
 {
 # if 1
     Assert([(OverlayView *)pView glCtx] == pCtx);
+    Assert([pCtx view] == pView);
     cocoaViewDisplay(pView);
 # else
     DEBUG_FUNC_ENTER();
     NSAutoreleasePool *pPool = [[NSAutoreleasePool alloc] init];
+    
+    Assert([(OverlayView *)pView glCtx] == pCtx);
+    Assert([pCtx view] == pView);
 
     [pCtx flushBuffer];
