Stream->Fountain, move Scheduler to Platform, HashMap->Hash
[org.ibex.core.git] / src / org / ibex / graphics / Font.java
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.
4
5 package org.ibex.graphics;
6 import org.ibex.util.*;
7 import java.io.*;
8 import java.util.Hashtable;
9 import org.ibex.js.*;
10 import org.ibex.nestedvm.*;
11 import org.ibex.plat.*;
12 import org.ibex.nestedvm.Runtime;
13
14 // FEATURE: this could be cleaner
15 /** encapsulates a single font (a set of Glyphs) */
16 public class Font {
17
18     private Font(JS stream, int pointsize) { this.stream = stream; this.pointsize = pointsize; }
19
20     private static boolean glyphRenderingTaskIsScheduled = false;
21
22     public final int pointsize;                 ///< the size of the font
23     public final JS stream;                 ///< the stream from which this font was loaded
24     public int max_ascent;                      ///< the maximum ascent, in pixels
25     public int max_descent;                     ///< the maximum descent, in pixels
26     boolean latinCharsPreloaded = false;        ///< true if a request to preload ASCII 32-127 has begun
27     public Glyph[] glyphs = new Glyph[65535];          ///< the glyphs that comprise this font
28
29     public abstract static class Glyph {
30         protected Glyph(Font font, char c) { this.font = font; this.c = c; }
31         public final Font font;
32         public final char c;
33         public int baseline;                    ///< within the alphamask, this is the y-coordinate of the baseline
34         public int advance;                     ///< amount to increment the x-coordinate
35         public boolean isLoaded = false;        ///< true iff the glyph is loaded
36         public int width = -1;                  ///< the width of the glyph
37         public int height = -1;                 ///< the height of the glyph
38         public byte[] data = null;              ///< the alpha channel samples for this font
39         public String path = null; // FIXME this should be shared across point sizes
40         void render() {
41             if (!isLoaded) try { renderGlyph(this); } catch (IOException e) { Log.info(Font.class, e); }
42             isLoaded = true;
43         }
44     }
45
46
47     // Statics //////////////////////////////////////////////////////////////////////
48
49     static final Hashtable glyphsToBeCached = new Hashtable();
50     static final Hashtable glyphsToBeDisplayed = new Hashtable();
51     // HACK: replace with Cache<JS, int>
52     private static Basket.Map fonts = new Basket.Hash();
53     public static Font getFont(JS stream, int pointsize) {
54         Basket.Map m = (Basket.Map)fonts.get(stream);
55         Font ret = null;
56         if (m != null) ret = (Font)m.get(new Integer(pointsize));
57         else fonts.put(stream, m = new Basket.Hash());
58         if (ret == null) m.put(new Integer(pointsize), ret = new Font(stream, pointsize));
59         return ret;
60     }
61
62
63     // Methods //////////////////////////////////////////////////////////////////////
64
65     /**
66      *  Rasterize the glyphs of <code>text</code>.
67      *  @returns <code>(width&lt;&lt;32)|height</code>
68      */
69     public long rasterizeGlyphs(String text, PixelBuffer pb, int textcolor, int x, int y, int cx1, int cy1, int cx2, int cy2) {
70         return rasterizeGlyphs(text, pb, textcolor, x, y, cx1, cy1, cx2, cy2, 0); }
71     public long rasterizeGlyphs(String text, PixelBuffer pb, int textcolor, int x, int y,
72                                 int cx1, int cy1, int cx2, int cy2, int bg) {
73         int width = 0, height = 0;
74         if (!latinCharsPreloaded) {       // preload the Latin-1 charset with low priority (we'll probably want it)
75             for(int i=48; i<57; i++) if (glyphs[i]==null) glyphsToBeCached.put(glyphs[i]=Platform.createGlyph(this, (char)i),"");
76             for(int i=32; i<47; i++) if (glyphs[i]==null) glyphsToBeCached.put(glyphs[i]=Platform.createGlyph(this, (char)i),"");
77             for(int i=57; i<128; i++) if (glyphs[i]==null) glyphsToBeCached.put(glyphs[i]=Platform.createGlyph(this, (char)i),"");
78             if (!glyphRenderingTaskIsScheduled) {
79                 Platform.Scheduler.add(glyphRenderingTask);
80                 glyphRenderingTaskIsScheduled = true;
81             }
82             latinCharsPreloaded = true;
83         }
84         for(int i=0; i<text.length(); i++) {
85             final char c = text.charAt(i);
86             Glyph g = glyphs[c];
87             if (g == null) glyphs[c] = g = Platform.createGlyph(this, c);
88             g.render();
89             if (pb != null) pb.drawGlyph(g,
90                                          x + width,
91                                          y + g.font.max_ascent - g.baseline,
92                                          x+width,
93                                          cy1,
94                                          x+width+g.advance,
95                                          cy2,
96                                          textcolor, bg);
97             width += g.advance;
98             height = java.lang.Math.max(height, max_ascent + max_descent);
99         }
100         return ((((long)width) << 32) | (long)(height & 0xffffffffL));
101     }
102
103     // FEATURE do we really need to be caching sizes?
104     private static Cache sizeCache = new Cache(1000, true);
105     public int textwidth(String s) { return (int)((textsize(s) >>> 32) & 0xffffffff); }
106     public int textheight(String s) { return (int)(textsize(s) & 0xffffffffL); }
107     public long textsize(String s) {
108         Long l = (Long)sizeCache.get(s);
109         if (l != null) return ((Long)l).longValue();
110         long ret = rasterizeGlyphs(s, null, 0, 0, 0, 0, 0, 0, 0);
111         sizeCache.put(s, new Long(ret));
112         return ret;
113     }
114
115     public Glyph getGlyph(char c) {
116         rasterizeGlyphs(c+"", null, 0, 0, 0, 0, 0, 0, 0);
117         Glyph g = glyphs[c];
118         g.render();
119         return g;
120     }
121
122     static final Callable glyphRenderingTask = new Callable() { public Object run(Object o) {
123         // FIXME: this should be a low-priority task
124         glyphRenderingTaskIsScheduled = false;
125         if (glyphsToBeCached.isEmpty()) return null;
126         Glyph g = (Glyph)glyphsToBeCached.keys().nextElement();
127         if (g == null) return null;
128         glyphsToBeCached.remove(g);
129         Log.debug(Font.class, "glyphRenderingTask rendering " + g.c + " of " + g.font);
130         g.render();
131         Log.debug(Glyph.class, "   done rendering glyph " + g.c);
132         glyphRenderingTaskIsScheduled = true;
133         Platform.Scheduler.add(this);
134         return null;
135     } };
136
137
138     // FreeType Interface //////////////////////////////////////////////////////////////////////////////
139
140     // FEATURE: use streams, not memoryfont's
141     // FEATURE: kerning pairs
142     private static final Runtime rt;
143     private static JS loadedStream;
144     private static int loadedStreamAddr;
145
146     static {
147         try {
148             rt = (Runtime)Class.forName("org.ibex.util.MIPSApps").newInstance();
149         } catch(Exception e) {
150             throw new Error("Error instantiating freetype: " + e);
151         }
152         rt.start(new String[]{"freetype"});
153         rt.execute();
154         rtCheck();
155     }
156     
157     private static void rtCheck() { if(rt.getState() != Runtime.PAUSED) throw new Error("Freetype exited " + rt.exitStatus()); }
158     
159     private static void loadFontByteStream(JS res) {
160         if(loadedStream == res) return;
161         
162         try {
163             Log.info(Font.class, "loading font " + JSU.str(res));
164             InputStream is = JSU.getInputStream(res);
165             byte[] fontstream = InputStreamToByteArray.convert(is);
166             rt.free(loadedStreamAddr);
167             loadedStreamAddr = rt.xmalloc(fontstream.length);
168             rt.copyout(fontstream, loadedStreamAddr, fontstream.length);
169             if(rt.call("load_font", loadedStreamAddr, fontstream.length) != 0)
170                 throw new RuntimeException("load_font failed"); // FEATURE: better error
171             rtCheck();
172             loadedStream = res;
173         } catch (Exception e) {
174             // FEATURE: Better error reporting (thow an exception?)
175             Log.info(Font.class, e);
176         }
177     }
178
179     private static synchronized void renderGlyph(Font.Glyph glyph) throws IOException {
180         try {
181             Log.debug(Font.class, "rasterizing glyph " + glyph.c + " of font " + glyph.font);
182             if (loadedStream != glyph.font.stream) loadFontByteStream(glyph.font.stream);
183             
184             long start = System.currentTimeMillis();
185             
186             rt.call("render",glyph.c,glyph.font.pointsize);
187             rtCheck();
188             
189             glyph.font.max_ascent = rt.getUserInfo(3);
190             glyph.font.max_descent = rt.getUserInfo(4);
191             glyph.baseline = rt.getUserInfo(5);
192             glyph.advance = rt.getUserInfo(6);
193             
194             glyph.width = rt.getUserInfo(1);
195             glyph.height = rt.getUserInfo(2);
196
197             glyph.data = new byte[glyph.width * glyph.height];
198             int addr = rt.getUserInfo(0);
199             rt.copyin(addr, glyph.data, glyph.width * glyph.height);
200             
201             byte[] path = new byte[rt.getUserInfo(8)];
202             rt.copyin(rt.getUserInfo(7), path, rt.getUserInfo(8));
203             glyph.path = new String(path);
204             glyph.path += " m " + (64 * glyph.advance) + " 0 "; 
205
206             glyph.isLoaded = true;
207         } catch (Exception e) {
208             // FEATURE: Better error reporting (thow an exception?)
209             Log.info(Font.class, e);
210         }
211     }
212 }