/*
 * Copyright (c) 1995, 1996 Sun Microsystems, Inc. All Rights Reserved.
 *
 * Permission to use, copy, modify, and distribute this software
 * and its documentation for NON-COMMERCIAL purposes and without
 * fee is hereby granted provided that this copyright notice
 * appears in all copies. Please refer to the file "copyright.html"
 * for further important copyright and licensing information.
 *
 * SUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF
 * THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
 * TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
 * PARTICULAR PURPOSE, OR NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR
 * ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR
 * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
 */
import java.applet.*;
import java.awt.*;
import java.awt.image.ImageObserver;

public class ImageUpdater extends Applet {
    /*
     * Written by Jim Graham.
     * This applet draws a big image scaled to its width and height as
     * specified in the <APPLET> tag, and a small image scaled by the
     * same ratio as the big image and positioned in the center of it.
     */
    Image bigimg, smallimg;
    int smallx, smally, smallw, smallh;
    boolean sizeknown = false;
    boolean errored = false;

    public void init() {
	bigimg = getImage(getDocumentBase(), "bigimg.gif");
	smallimg = getImage(getDocumentBase(), "smallimg.gif");
	positionImages();
    }

    public boolean imageUpdate(Image theimg, int infoflags,
			       int x, int y, int w, int h) {
	if ((infoflags & (ERROR)) != 0) {
	    errored = true;
	}
	if ((infoflags & (WIDTH | HEIGHT)) != 0) {
	    positionImages();
	}
	boolean done = ((infoflags & (ERROR | FRAMEBITS | ALLBITS)) != 0);
	// Repaint immediately if we are done, otherwise batch up
	// repaint requests every 100 milliseconds
	repaint(done ? 0 : 100);
	return !done;
    }

    public synchronized void positionImages() {
	int bigw = bigimg.getWidth(this);
	int bigh = bigimg.getHeight(this);
	int smallw = bigimg.getWidth(this);
	int smallh = bigimg.getHeight(this);
	if (bigw < 0 || bigh < 0 || smallw < 0 || smallh < 0) {
	    return;
	}
	smallw = smallw * bigw / size().width;
	smallh = smallh * bigh / size().height;
	smallx = (bigw - smallw) / 2;
	smally = (bigh - smallh) / 2;
	sizeknown = true;
    }

    public synchronized void paint(Graphics g) {
	int appw = size().width;
	int apph = size().height;
	if (errored) {
	    // The images had a problem - just draw a big red rectangle
	    g.setColor(Color.red);
	    g.fillRect(0, 0, appw, apph);
	    return;
	}
	// Scale the big image to the width and height of the applet
	g.drawImage(bigimg, 0, 0, appw, apph, this);
	if (sizeknown) {
	    // Scale the small image to the central region calculated above.
	    g.drawImage(smallimg, smallx, smally, smallw, smallh, this);
	}
    }
}
