import jogamp.nativewindow.x11.X11Util;
import org.junit.Assert;
import org.junit.Test;

import javax.media.opengl.GLCapabilities;
import javax.media.opengl.GLCapabilitiesImmutable;
import javax.media.opengl.GLProfile;
import javax.media.opengl.awt.GLCanvas;
import java.awt.Frame;

/**
 * Tests the GLCanvas in JOGL
 */
public class GLCanvasTestJOGL {

  static {
    System.setProperty( "jogamp.gluegen.UseTempJarCache", "false" );
  }

  //This test will fail on JOGL 2.0 RC5 when running it in linux using X11 and nativewindow
  @Test
  public void testX11WindowMemoryLeak() throws Exception {
    try {
      for ( int j = 0; j < 500; j++ ) {
        GLCapabilitiesImmutable caps = new GLCapabilities( GLProfile.getDefault( GLProfile.getDefaultDesktopDevice() ) );
        Frame frame = new Frame( "JOGL AWT memory leak test for X11" );
  
        GLCanvas glCanvas = new GLCanvas( caps );
        frame.add( glCanvas );
        frame.setSize( 128, 128 );
  
        final Frame _frame = frame;
        final GLCanvas _glCanvas = glCanvas;
  
        try {
          javax.swing.SwingUtilities.invokeAndWait( new Runnable() {
            public void run() {
              _frame.setVisible( true );
            }
          } );
        }
        catch ( Throwable t ) {
          t.printStackTrace();
          Assert.fail(t.getMessage());
        }
        glCanvas.display();
        try {
          javax.swing.SwingUtilities.invokeAndWait( new Runnable() {
            public void run() {
              _frame.setVisible( false );
              _frame.remove( _glCanvas );
              _frame.dispose();
            }
          } );
        }
        catch ( Throwable t ) {
          t.printStackTrace();
          Assert.fail(t.getMessage());
        }

        //Note that this is largely to indicate the problem, feel free to comment this line.
        X11Util.dumpOpenDisplayConnections();
      }
    }
    catch ( Exception e ) {
      e.printStackTrace();
      Assert.fail(e.getMessage());
    }
  }

}
