package tropo.applet;

import java.awt.*;
import java.util.*;
import java.io.*;
import java.net.*;
import java.awt.image.*;
import java.applet.*;

/**
 * Copyright (c) 1997-1998 Tropo. All Rights Reserved.
 * <p>
 * Buffered, offscreen, flicker-free drawing for an Applet
 *
 * @version 1.0
 */
public abstract class TRBufferedApplet
    extends Applet
{
	/**
	 * No direct newing.
	 */
	protected TRBufferedApplet()
	{
	}
	

	/**
	 *
	 */
	public final void update( Graphics g)
	{
		paint( g);
	}

	/**
	 *
	 */
	public final void paint( Graphics g)
	{
		Dimension d = size();
		int w = d.width;
		int h = d.height;

		// create offscrean image if necessary
		if ( offG == null || (w != iw) || (h != ih))
		{
			if ( offG != null)
				offG.dispose(); // bogus: help out gc
			
			//o.println( "create "+ w + " by " + h);
			iw = w;
			ih = h;
			offImg = createImage( iw, ih);
			offG = offImg.getGraphics();
			offG.setClip( 0, 0, iw, ih); // is this really needed?
		}

		// have derived class do the real work
		draw( offG);

		// blit it out
		g.drawImage( offImg, 0, 0, null);
	}

	/**
	 * Not really needed but in for completeness.
	 */
	public void invalidate()
	{
		super.invalidate();
		if ( offG != null)
			offG.dispose(); // bogus: help out gc
		offG = null;
		offImg = null;
		iw = -1;
		ih = -1;
	}

	/**
	 * Dervied classes must override this and do the real work of
	 * drawing an image.
	 */
	protected abstract void draw( Graphics g);

	
	private Graphics offG;
	private Image offImg;
	private int iw = -1;
	private int ih = -1;

	/**
	 * For debugging.
	 */
	protected static final PrintStream o = System.out;
}
