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