// Copyright 1996, Marimba Inc. All Rights Reserved.


// @(#)ImageCache.java, 1.9, 11/07/96





package marimba.gui;





import java.net.*;


import java.awt.*;


import java.awt.image.*;


import java.util.*;





import sun.awt.image.URLImageSource;





/**


 * This class fetches and caches images. Unfortunately we can't


 * use ImageRef's because they are in a sun package.


 *


 * @author	Arthur van Hoff


 * @version 	1.9, 11/07/96


 */


public final class ImageCache {


    final static double FAC = 0.75;


    final static Hashtable hash = new Hashtable();


    final static Toolkit tk = Toolkit.getDefaultToolkit();





    Image img;





    /**


     * Create a cached image.


     */


    ImageCache(URL url) {


	this.img = tk.createImage(new URLImageSource(url));


    }





    /**


     * Get an image from the cache.


     */


    static ImageCache getCached(URL url) {


	ImageCache cached = (ImageCache)hash.get(url);


	if (cached == null) {


	    hash.put(url, cached = new ImageCache(url));


	}


	return cached;


    }





    /**


     * Get an image given a url in string form.


     */


    public static Image get(String url) {


	try {


	    return get(new URL(url));


	} catch (MalformedURLException e) {


	}


	return null;


    }





    /**


     * Get an image given a url.


     */


    public synchronized static Image get(URL url) {


	return getCached(url).img;


    }





    /**


     * Check if a URL is the prefix of another URL.


     */


    static boolean prefixURL(URL prefix, URL child) {


	return prefix.getProtocol().equals(child.getProtocol()) &&


	    prefix.getHost().equals(child.getHost()) &&


	    (prefix.getPort() == child.getPort()) &&


	    child.getFile().startsWith(prefix.getFile());


    }





    /**


     * Flush images from the cache. Only images that are


     * relative to the given URL are flushed.


     */


    public synchronized static void flush(URL url) {


	Vector v = null;


	for (Enumeration e = hash.keys() ; e.hasMoreElements() ;) {


	    URL imgUrl = (URL)e.nextElement();


	    if (prefixURL(url, imgUrl)) {


		if (v == null) {


		    v = new Vector();


		}


		//System.out.println("FLUSHING: " + imgUrl.toExternalForm());


		v.addElement(imgUrl);


	    }


	}


	if (v != null) {


	    for (Enumeration e = v.elements() ; e.hasMoreElements() ;) {


		hash.remove(e.nextElement());


	    }


	}


    }


}


