#
#   PyGUI - OpenGL View - Macintosh/AGL
#

from GGLViews import GLError

try:
    from OpenGL.GL import glViewport
except ImportError, e:
    raise GLError("OpenGL support is not available (%s)" % e)

from GGLViews import GLView as GGLView
import AGL

class GLView(GGLView):

    def __init__(self, double_buffer = True, alpha = False, depth_buffer = True,
            stencil_buffer = False, accum_buffer = False, multisample = False, **kwds):
        if multisample:
            raise GLError("Multisampling not supported")
        self._agl_context = AGL.Context(
            None,
            double_buffer = double_buffer,
            alpha_size = 8 * (not not alpha),
            depth_size = 32 * (not not depth_buffer),
            stencil_size = 32 * (not not stencil_buffer),
            accum_size = 8 * (not not accum_buffer))
        GGLView.__init__(self, **kwds)
        self.with_context(self.init_context)
    
    def destroy(self):
        self._agl_context = None
        GGLView.destroy(self)

    def _mac_update_viewport(self):
        GGLView._mac_update_viewport(self)
        self._with_focus(self._mac_update_context)
    
    def _mac_update_context(self):
        context = self._agl_context
        if context:
            context.update_port()
            context.with_current(self._mac_update_gl_viewport)
    
    def _mac_update_gl_viewport(self):
        width, height = self.size
        glViewport(0, 0, width, height)
        self.viewport_changed()

    def _mac_draw(self):
        self.with_context(self.render)
        self._agl_context.swap_buffers()
    
    def with_context(self, proc):
        self._agl_context.with_current(proc)
