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