summaryrefslogtreecommitdiff
path: root/src/main/java/org/cristalise/gui/ImageLoader.java
blob: 9af6fedcbd6b8a9cfbcfb5b6e31d460590482e6a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package org.cristalise.gui;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Hashtable;

import javax.swing.ImageIcon;

import org.cristalise.kernel.common.ObjectNotFoundException;
import org.cristalise.kernel.process.Gateway;
import org.cristalise.kernel.utils.Logger;


public class ImageLoader {

    static private Hashtable<String, ImageIcon> imgCache = new Hashtable<String, ImageIcon>();
    static public final ImageIcon nullImg = new ImageIcon(new byte[] { 0 });
    static private final ArrayList<String> reportedMissingIcons = new ArrayList<String>();

    /**
     * Gets an image from the resource directories
     *
     * @param resName - filename after resources/images
     * @return
     */
    static public ImageIcon findImage(String resName) {
        try {
        	for (String ns : Gateway.getResource().getModuleBaseURLs().keySet()) {
        		try {
        			return getImage(ns, resName);
        		} catch (ObjectNotFoundException ex) { }
			}
            return getImage(null, resName);
        } catch (ObjectNotFoundException ex) {
        	if (!reportedMissingIcons.contains(resName)) {
        		Logger.warning("Image '"+resName+"' not found. Using null icon");
        		reportedMissingIcons.add(resName);
        	}
            return nullImg;
        }
    }

    static public ImageIcon getImage(String ns, String resName) throws ObjectNotFoundException {
        if (resName == null)
            return nullImg;

        if (imgCache.containsKey(ns+'/'+resName)) {
            return imgCache.get(ns+'/'+resName);
        }

        URL imgLocation = null;
        if (ns == null) 
        	try {
        		imgLocation = Gateway.getResource().getKernelResourceURL("images/"+resName);
        	} catch (MalformedURLException ex) { }
        else
        	try {
        		imgLocation = Gateway.getResource().getModuleResourceURL(ns, "images/"+resName);
        	} catch (MalformedURLException ex) { }
        
        if (imgLocation!= null) {
        	ImageIcon newImg = new ImageIcon(imgLocation);

        	if (newImg.getIconHeight() > -1) {
        		imgCache.put(ns+'/'+resName, newImg);
                Logger.msg(3, "Loaded "+resName+" "+newImg.getIconWidth()+"x"+newImg.getIconHeight());
                return newImg;
        	}
        }
        throw new ObjectNotFoundException();
    }

}