2003/10/31 09:50:08
[org.ibex.core.git] / src / org / xwt / Picture.java
1 // Copyright 2003 Adam Megacz, see the COPYING file for licensing [GPL]
2 package org.xwt;
3 import java.io.*;
4 import org.xwt.js.*;
5 import org.xwt.util.*;
6 import org.xwt.translators.*;
7
8 /** 
9  *    <p>
10  *    The in-memory representation of a PNG or GIF image. It is
11  *    read-only. It is usually passed to PixelBuffer.drawPicture()
12  *    </p>
13  *
14  *    <p>
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).
19  *    </p>
20  */
21 public abstract class Picture {
22
23     /** the resource that created this Picture */
24     public Res res = null;
25
26     /** the height of the picture */
27     public abstract int getHeight();
28     
29     /** the width of the picture */
30     public abstract int getWidth();
31
32     /** Pictures, cache keyed by Res instance */
33     private static Cache cache = new Cache();
34     private static GIF gif = new GIF();
35     
36     /** turns a resource into a Picture.Source and passes it to the callback */
37     public static void fromRes(final Res r, final Callback callback) {
38         Picture ret = (Picture)cache.get(r);
39         if (ret != null) {
40             callback.call(ret);
41             return;
42         }
43
44         try {
45             // FIXME: put self in background
46             PushbackInputStream pbis = new PushbackInputStream(r.getInputStream());
47             int c = pbis.read();
48             pbis.unread(c);
49             if (c == 'G') ret = gif.fromInputStream(pbis, r.getDescriptiveName());
50             else if (c == 137) ret = new PNG().fromInputStream(pbis, r.getDescriptiveName());
51             else if (c == 0xff) ret = Platform.decodeJPEG(pbis, r.getDescriptiveName());
52             else throw new JS.Exn("couldn't figure out image type from first byte");
53             cache.put(r, ret);
54             ret.res = r;
55             callback.call(ret);
56         } catch (Exception e) {
57             Log.log(Picture.class, e);
58         }
59     }
60 }