questionable patch: merge of a lot of stuff from the svg branch
[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 String rasterizeGlyphs(String text) {
67         StringBuffer path = new StringBuffer(text.length() * 50);
68         for(int i=0; i<text.length(); i++) {
69             final char c = text.charAt(i);
70             Glyph g = glyphs[c];
71             if (g == null) glyphs[c] = g = Platform.createGlyph(this, c);
72             g.render();
73             path.append(g.path);
74         }
75         return path.toString();
76     }
77     public long rasterizeGlyphs(String text, PixelBuffer pb, Affine a, Mesh h, Affine ha, int fg, int bg) {
78         int width = 0, height = 0;
79         if (!latinCharsPreloaded) {       // preload the Latin-1 charset with low priority (we'll probably want it)
80             for(int i=48; i<57; i++) if(glyphs[i]==null) toBeRasterized.append(glyphs[i]=Platform.createGlyph(this, (char)i));
81             for(int i=32; i<47; i++) if(glyphs[i]==null) toBeRasterized.append(glyphs[i]=Platform.createGlyph(this, (char)i));
82             for(int i=57; i<128; i++) if(glyphs[i]==null) toBeRasterized.append(glyphs[i]=Platform.createGlyph(this, (char)i));
83             latinCharsPreloaded = true;
84         }
85         a = a==null ? null : a.copy();
86         for(int i=0; i<text.length(); i++) {
87             final char c = text.charAt(i);
88             Glyph g = glyphs[c];
89             if (g == null) glyphs[c] = g = Platform.createGlyph(this, c);
90             g.render();
91             if (a!=null) a.multiply(Affine.translate(0, g.font.max_ascent - g.baseline));
92             if (ha!=null) ha.multiply(Affine.translate(0, g.font.max_ascent - g.baseline));
93             if (pb != null) {
94                 pb.drawGlyph(g, a, h, fg, bg);
95                 if (h!=null) h.subtract(new Mesh().addRect(0, 0, g.width, g.height), ha);
96             }
97             if (a!=null) a.multiply(Affine.translate(0, -1 * (g.font.max_ascent - g.baseline)));
98             if (ha!=null) ha.multiply(Affine.translate(0, -1 * (g.font.max_ascent - g.baseline)));
99             width += g.advance;
100             if (a!=null) a.multiply(Affine.translate(g.advance, 0));
101             if (ha!=null) ha.multiply(Affine.translate(g.advance, 0));
102             height = java.lang.Math.max(height, max_ascent + max_descent);
103         }
104         return ((((long)width) << 32) | (long)(height & 0xffffffffL));
105     }
106
107     // FEATURE do we really need to be caching sizes?
108     private static Cache sizeCache = new Cache(1000, true);
109     public int textwidth(String s) { return (int)((textsize(s) >>> 32) & 0xffffffff); }
110     public int textheight(String s) { return (int)(textsize(s) & 0xffffffffL); }
111     public long textsize(String s) {
112         Long l = (Long)sizeCache.get(s);
113         if (l != null) return ((Long)l).longValue();
114         long ret = rasterizeGlyphs(s, null, null, null, null, 0, 0);
115         sizeCache.put(s, new Long(ret));
116         return ret;
117     }
118
119     public Glyph getGlyph(char c) {
120         rasterizeGlyphs(c+"", null, null, null, null, 0, 0);
121         Glyph g = glyphs[c];
122         g.render();
123         return g;
124     }
125
126     static { new Thread() { public void run() {
127         while(true) {
128             Glyph g = (Glyph)toBeRasterized.remove(true);
129             if (g == null) continue;
130             Log.debug(Font.class, "glyphRenderingTask rendering " + g.c + " of " + g.font);
131             g.render();
132             Log.debug(Glyph.class, "   done rendering glyph " + g.c);
133         }
134     } }.start(); }
135
136
137     // FreeType Interface //////////////////////////////////////////////////////////////////////////////
138
139     // FEATURE: use streams, not memoryfont's
140     // FEATURE: kerning pairs
141     private static final Runtime rt;
142     private static JS loadedStream;
143     private static int loadedStreamAddr;
144
145     static {
146         try {
147             rt = (Runtime)Class.forName("org.ibex.util.MIPSApps").newInstance();
148         } catch(Exception e) {
149             throw new Error("Error instantiating freetype: " + e);
150         }
151         rt.start(new String[]{"freetype"});
152         rt.execute();
153         rtCheck();
154     }
155     
156     private static void rtCheck() { if(rt.getState() != Runtime.PAUSED) throw new Error("Freetype exited " + rt.exitStatus()); }
157     
158     private static void loadFontByteStream(JS res) {
159         if(loadedStream == res) return;
160         
161         try {
162             Log.info(Font.class, "loading font " + JSU.str(res));
163             InputStream is = JSU.getInputStream(res);
164             byte[] fontstream = InputStreamToByteArray.convert(is);
165             rt.free(loadedStreamAddr);
166             loadedStreamAddr = rt.xmalloc(fontstream.length);
167             rt.copyout(fontstream, loadedStreamAddr, fontstream.length);
168             if(rt.call("load_font", loadedStreamAddr, fontstream.length) != 0)
169                 throw new RuntimeException("load_font failed"); // FEATURE: better error
170             rtCheck();
171             loadedStream = res;
172         } catch (Exception e) {
173             // FEATURE: Better error reporting (thow an exception?)
174             Log.info(Font.class, e);
175         }
176     }
177
178     private static synchronized void renderGlyph(Font.Glyph glyph) throws IOException {
179         try {
180             Log.debug(Font.class, "rasterizing glyph " + glyph.c + " of font " + glyph.font);
181             if (loadedStream != glyph.font.stream) loadFontByteStream(glyph.font.stream);
182             
183             long start = System.currentTimeMillis();
184             
185             rt.call("render",glyph.c,glyph.font.pointsize);
186             rtCheck();
187             
188             glyph.font.max_ascent = rt.getUserInfo(3);
189             glyph.font.max_descent = rt.getUserInfo(4);
190             glyph.baseline = rt.getUserInfo(5);
191             glyph.advance = rt.getUserInfo(6);
192             
193             glyph.width = rt.getUserInfo(1);
194             glyph.height = rt.getUserInfo(2);
195
196             glyph.data = new byte[glyph.width * glyph.height];
197             int addr = rt.getUserInfo(0);
198             rt.copyin(addr, glyph.data, glyph.width * glyph.height);
199             
200             byte[] path = new byte[rt.getUserInfo(8)];
201             rt.copyin(rt.getUserInfo(7), path, rt.getUserInfo(8));
202             glyph.path = new String(path);
203             glyph.path += " m " + (64 * glyph.advance) + " 0 "; 
204
205             glyph.isLoaded = true;
206         } catch (Exception e) {
207             // FEATURE: Better error reporting (thow an exception?)
208             Log.info(Font.class, e);
209         }
210     }
211 }