import java.applet.*;
import java.awt.*;
import java.awt.image.MemoryImageSource;
import isi.jserver.jserver;

public class image extends Applet
{
	jserver js; boolean showflag;
	Image backImage;
	int WIDTH = 200; int HEIGHT = 200;
	int xpos, ypos, yinc;
	
	public void init()
	{
		resize(WIDTH, HEIGHT);
		js = new jserver();	// create jserver object
		js.start(0);		// start jserver run thread
		js.Log(true);
		js.Do("setdata =: 3 : '(200$i.?40) |.\"0 1|:200 200$<.1600#?32$255^3'");
		js.Do("fixdata =: 3 : '<.(-2^24)+40000$,y.'");
		requestFocus();
	}

	public void destroy(){js.close();}

	public void text(Graphics g, String s)
	{
		g.drawString(s, xpos, ypos);
		ypos += yinc;
	}

	public void paint(Graphics g)
	{
		if(backImage!=null)
			g.drawImage(backImage, 0, 0, this);
		else
		{
			xpos = 10; ypos=10; yinc=20;
			text(g,"Click LEFT mouse button for this help screen.");
			text(g,"Click RIGHT mouse button to paint data from J.");
			text(g,"Press J key to toggle J display.");
			ypos += 20;
			yinc = 12;
			g.drawString("Look at the setdata and fixdata definitions in J.", 10, 90);
			g.drawString("fixdata ensures data is valid 200 by 200 array of colors.", 10, 110);
			g.drawString("setdata returns colors.", 10, 130);
			g.drawString("setdata initially returns shifted vertical bands of random colors.", 10, 150);
			g.drawString("Experiment with changing the definition of setdata.", 10, 170);
			g.drawString("For example, try:", 10, 190);
			g.drawString("setdata =: 3 : '?2^24'", 20, 210);
		}
	}

	public boolean mouseDown(Event ev, int x, int y)
	{
		int imageBits[] = new int[WIDTH*HEIGHT];

		if(ev.metaDown())
		{
			js.Do("data=:fixdata setdata''");
			js.Get("data");
			imageBits = js.getInts();
			MemoryImageSource producer = new MemoryImageSource(WIDTH, HEIGHT, imageBits, 0, WIDTH);
			backImage = createImage(producer);
			repaint();
			requestFocus();
			return true;
		}
		else
		{
			backImage = null;
			repaint();
			return true;
		}
	}

	public boolean keyDown(Event ev, int key)
	{
		if(key != 106) return false;
		js.Show(showflag = ! showflag);
		return true;
	}
}
