2003/09/25 10:10:52
[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     /** Pictures, cached by Res */
24     private static Cache cache = new Cache();
25
26     private static GIF gif = new GIF();
27     private static PNG png = new PNG();
28     
29     /** turns a resource into a Picture.Source */
30     public static Picture fromRes(Res r) {
31         // FIXME: put self in background thread if needed
32         Picture ret = (Picture)cache.get(r);
33         if (ret == null) {
34             try {
35                 PushbackInputStream pbis = new PushbackInputStream(r.getInputStream());
36                 int c = pbis.read();
37                 pbis.unread(c);
38                 if (c == 'G') ret = gif.fromInputStream(pbis, r.getDescriptiveName());
39                 else if (c == 137) ret = png.fromInputStream(pbis, r.getDescriptiveName());
40                 else if (c == 0xff) ret = Platform.decodeJPEG(pbis, r.getDescriptiveName());
41                 else throw new JS.Exn("couldn't figure out image type from first byte");
42                 cache.put(r, ret);
43             } catch (IOException e) {
44                 Log.logJS(Picture.class, e);
45                 return null;
46             }
47         }
48         return ret;
49     }
50
51     /** the height of the picture */
52     public abstract int getHeight();
53     
54     /** the width of the picture */
55     public abstract int getWidth();
56
57 }