1 // Copyright 2004 Adam Megacz, see the COPYING file for licensing [GPL]
2 package org.ibex.graphics;
5 import org.ibex.plat.*;
6 import org.ibex.util.*;
7 import org.ibex.core.*;
10 * The in-memory representation of a PNG or GIF image. It is
11 * read-only. It is usually passed to PixelBuffer.drawPicture()
13 * Implementations of the Platform class should return objects
14 * supporting this interface from the createPicture() method. These
15 * implementations may choose to implement caching strategies (for
16 * example, using a Pixmap on X11).
18 public class Picture {
20 public Picture() { this.stream = null; }
21 public Picture(JS r) { this.stream = r; }
22 private static Cache cache = new Cache(100); ///< Picture, keyed by the Stream that loaded them
24 public JS stream = null; ///< the stream we were loaded from
25 public int width = -1; ///< the width of the image
26 public int height = -1; ///< the height of the image
27 public int[] data = null; ///< argb samples
28 public boolean isLoaded = false; ///< true iff the image is fully loaded
30 /** invoked when an image is fully loaded; subclasses can use this to initialize platform-specific constructs */
31 protected void loaded() { isLoaded = true; }
33 /** turns a stream into a Picture.Source and passes it to the callback */
34 public static Picture load(final JS stream, final Task callback) {
35 if(stream == null) throw new NullPointerException();
36 Picture ret = (Picture)cache.get(stream);
38 ret = Platform.createPicture(stream);
39 if(ret == null) throw new NullPointerException();
40 cache.put(stream, ret);
42 final Picture p = ret;
43 if (!ret.isLoaded && callback != null) {
44 // FEATURE: This is kind of ugly - shouldn't need a blessing
45 final Ibex.Blessing b = Ibex.Blessing.getBlessing(stream);
46 new java.lang.Thread() { public void run() {
47 InputStream in = null;
49 in = b == null ? stream.getInputStream() : b.getImage();
50 } catch (IOException e) { Log.error(Picture.class, e);
51 } catch (JSExn e) { Log.error(Picture.class, e);
53 if (in == null) { Log.warn(Picture.class, "couldn't load image for stream " + stream.unclone()); return; }
55 PushbackInputStream pbis = new PushbackInputStream(in);
56 int firstByte = pbis.read();
57 if (firstByte == -1) throw new JSExn("empty stream reading image");
58 pbis.unread(firstByte);
59 if ((firstByte & 0xff) == 'G') GIF.load(pbis, p);
60 else if ((firstByte & 0xff) == 137) PNG.load(pbis, p);
61 else if ((firstByte & 0xff) == 0xff) Platform.decodeJPEG(pbis, p);
62 else throw new JSExn("couldn't figure out image type from first byte");
64 Scheduler.add(callback);
65 } catch (Exception e) {
66 Log.info(this, "exception while loading image");