1 // Copyright 2000-2005 the Contributors, as shown in the revision logs.
2 // Licensed under the GNU General Public License version 2 ("the License").
3 // You may not use this file except in compliance with the License.
5 package org.ibex.graphics;
8 import org.ibex.plat.*;
9 import org.ibex.util.*;
10 import org.ibex.core.*;
13 * The in-memory representation of a PNG or GIF image. It is
14 * read-only. It is usually passed to PixelBuffer.drawPicture()
16 * Implementations of the Platform class should return objects
17 * supporting this interface from the createPicture() method. These
18 * implementations may choose to implement caching strategies (for
19 * example, using a Pixmap on X11).
21 public class Picture {
23 public Picture() { this.stream = null; }
24 public Picture(JS r) { this.stream = r; }
25 private static Cache cache = new Cache(100, true); ///< Picture, keyed by the Stream that loaded them
27 public JS stream = null; ///< the stream we were loaded from
28 public int width = -1; ///< the width of the image
29 public int height = -1; ///< the height of the image
30 public int[] data = null; ///< argb samples
31 public boolean isLoaded = false; ///< true iff the image is fully loaded
33 /** invoked when an image is fully loaded; subclasses can use this to initialize platform-specific constructs */
34 protected void loaded() { isLoaded = true; }
36 /** turns a stream into a Picture.Source and passes it to the callback */
37 public static Picture load(final JS stream, final Callable callback) {
38 if(stream == null) throw new NullPointerException();
39 Picture ret = (Picture)cache.get(stream);
41 ret = Platform.createPicture(stream);
42 if(ret == null) throw new NullPointerException();
43 cache.put(stream, ret);
45 final Picture p = ret;
46 if (!ret.isLoaded && callback != null) {
47 // FEATURE: This is kind of ugly - shouldn't need a blessing
48 final Ibex.Blessing b = Ibex.Blessing.getBlessing(stream);
49 new java.lang.Thread() { public void run() {
50 InputStream in = null;
52 in = b == null ? JSU.getInputStream(stream) : b.getImage();
53 //} catch (IOException e) { Log.error(Picture.class, e);
54 } catch (JSExn e) { Log.error(Picture.class, e);
56 if (in == null) { Log.warn(Picture.class, "couldn't load image for stream " + stream.unclone()); return; }
58 PushbackInputStream pbis = new PushbackInputStream(in);
59 int firstByte = pbis.read();
60 if (firstByte == -1) throw new JSExn("empty stream reading image");
61 pbis.unread(firstByte);
62 if ((firstByte & 0xff) == 'G') GIF.load(pbis, p);
63 else if ((firstByte & 0xff) == 137) PNG.load(pbis, p);
64 else if ((firstByte & 0xff) == 0xff) Platform.decodeJPEG(pbis, p);
65 else throw new JSExn("couldn't figure out image type from first byte");
67 Scheduler.add(callback);
68 } catch (Exception e) {
69 Log.info(this, "exception while loading image");