
"Utility class for GLX context creation."

import ctypes

import OpenGL.GL as gl
import OpenGL.GLX as glx
from OpenGL.raw._GLX import Display

def array(t, xs):
    # Thanks, ctypes.
    return (t * len(xs))(*xs)

class GLXContext(object):
    """Utility class for GLX context creation.

    This class represents a GLX rendering context attached to the root window.
    """

    def __init__(self):
        # Me, unportable?
        xlib = ctypes.cdll.LoadLibrary('libX11.so')
        display = xlib.XOpenDisplay(None)
        # XXX: We should probably create a separate window.
        self.window = xlib.XRootWindow(display, 0)
        self.display_ = Display.from_address(display)
        visual = glx.glXChooseVisual(self.display_, 0, array(ctypes.c_int,
            [glx.GLX_RGBA, glx.GLX_DEPTH_SIZE, 24]))
        self.context = glx.glXCreateContext(
            self.display_, visual, None, gl.GL_TRUE)

    def __enter__(self):
        assert glx.glXMakeCurrent(
            self.display_, self.window, self.context) != 0

    def __exit__(self, type, value, traceback):
        # Not that we're going to be doing any X drawing, but may as well.
        glx.glXWaitGL()

