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.*;
12 * The in-memory representation of a PNG or GIF image. It is
13 * read-only. It is usually passed to PixelBuffer.drawPicture()
15 * Implementations of the Platform class should return objects
16 * supporting this interface from the createPicture() method. These
17 * implementations may choose to implement caching strategies (for
18 * example, using a Pixmap on X11).
20 public class Picture {
22 public Picture() { this.stream = null; }
23 public Picture(JS r) { this.stream = r; }
24 private static Cache cache = new Cache(100, true); ///< Picture, keyed by the Stream that loaded them
26 public JS stream = null; ///< the stream we were loaded from
27 public int width = -1; ///< the width of the image
28 public int height = -1; ///< the height of the image
29 public int[] data = null; ///< argb samples
30 public boolean isLoaded = false; ///< true iff the image is fully loaded
32 public Picture(InputStream is) throws IOException { load(this, is); }
34 public static void load(Picture p, InputStream in) throws IOException {
35 PushbackInputStream pbis = new PushbackInputStream(in);
36 int firstByte = pbis.read();
37 if (firstByte == -1) throw new IOException("empty stream reading image");
38 pbis.unread(firstByte);
39 if ((firstByte & 0xff) == 'G') GIF.load(pbis, p);
40 else if ((firstByte & 0xff) == 137) PNG.load(pbis, p);
41 else if ((firstByte & 0xff) == 0xff) Platform.decodeJPEG(pbis, p);
42 else throw new IOException("couldn't figure out image type from first byte");
46 /** invoked when an image is fully loaded; subclasses can use this to initialize platform-specific constructs */
47 protected void loaded() { isLoaded = true; }
49 /** turns a stream into a Picture.Source and passes it to the callback */
50 public static Picture load(final JS stream, final Callable callback) {
51 if(stream == null) throw new NullPointerException();
52 Picture ret = (Picture)cache.get(stream);
54 ret = Platform.createPicture(stream);
55 if(ret == null) throw new NullPointerException();
56 cache.put(stream, ret);
58 final Picture p = ret;
59 if (!ret.isLoaded && callback != null) {
60 new java.lang.Thread() { public void run() {
61 InputStream in = null;
63 in = JSU.getInputStream(stream);
64 } catch (IOException e) { Log.error(Picture.class, e);
65 //} catch (JSExn e) { Log.error(Picture.class, e);
67 if (in == null) { Log.warn(Picture.class, "couldn't load image for stream " + stream.unclone()); return; }
70 Platform.Scheduler.add(callback);
71 } catch (Exception e) {
72 Log.info(this, "exception while loading image");