added missing patches to move to fillTriangle() and Mesh
[org.ibex.core.git] / src / org / ibex / graphics / Font.java
index 451672e..b2c30ca 100644 (file)
@@ -1,26 +1,28 @@
-// Copyright 2004 Adam Megacz, see the COPYING file for licensing [GPL]
-package org.ibex;
-import org.ibex.translators.*;
+// Copyright 2000-2005 the Contributors, as shown in the revision logs.
+// Licensed under the GNU General Public License version 2 ("the License").
+// You may not use this file except in compliance with the License.
+
+package org.ibex.graphics;
 import org.ibex.util.*;
 import java.io.*;
 import java.util.Hashtable;
-
-import org.ibex.js.JSExn;
+import org.ibex.js.*;
+import org.ibex.nestedvm.*;
+import org.ibex.plat.*;
+import org.ibex.nestedvm.Runtime;
 
 // FEATURE: this could be cleaner
 /** encapsulates a single font (a set of Glyphs) */
 public class Font {
 
-    private Font(Stream stream, int pointsize) { this.stream = stream; this.pointsize = pointsize; }
-
-    private static boolean glyphRenderingTaskIsScheduled = false;
+    private Font(JS stream, int pointsize) { this.stream = stream; this.pointsize = pointsize; }
 
     public final int pointsize;                 ///< the size of the font
-    public final Stream stream;                 ///< the stream from which this font was loaded
+    public final JS stream;                 ///< the stream from which this font was loaded
     public int max_ascent;                      ///< the maximum ascent, in pixels
     public int max_descent;                     ///< the maximum descent, in pixels
     boolean latinCharsPreloaded = false;        ///< true if a request to preload ASCII 32-127 has begun
-    Glyph[] glyphs = new Glyph[65535];          ///< the glyphs that comprise this font
+    public Glyph[] glyphs = new Glyph[65535];          ///< the glyphs that comprise this font
 
     public abstract static class Glyph {
         protected Glyph(Font font, char c) { this.font = font; this.c = c; }
@@ -32,8 +34,9 @@ public class Font {
         public int width = -1;                  ///< the width of the glyph
         public int height = -1;                 ///< the height of the glyph
         public byte[] data = null;              ///< the alpha channel samples for this font
+        public String path = null; // FIXME this should be shared across point sizes
         void render() {
-            if (!isLoaded) try { freetype.renderGlyph(this); } catch (IOException e) { Log.info(Freetype.class, e); }
+            if (!isLoaded) try { renderGlyph(this); } catch (IOException e) { Log.info(Font.class, e); }
             isLoaded = true;
         }
     }
@@ -41,13 +44,15 @@ public class Font {
 
     // Statics //////////////////////////////////////////////////////////////////////
 
-    static final Freetype freetype = new Freetype();
-    static final Hashtable glyphsToBeCached = new Hashtable();
-    static final Hashtable glyphsToBeDisplayed = new Hashtable();
-    private static Cache fontCache = new Cache(100);
-    public static Font getFont(Stream stream, int pointsize) {
-        Font ret = (Font)fontCache.get(stream, new Integer(pointsize));
-        if (ret == null) fontCache.put(stream, new Integer(pointsize), ret = new Font(stream, pointsize));
+    static final Queue toBeRasterized = new Queue(300);
+    static final Queue toBeDisplayed = new Queue(300);
+    private static Basket.Map fonts = new Basket.Hash();
+    public static Font getFont(JS stream, int pointsize) {
+        Basket.Map m = (Basket.Map)fonts.get(stream);
+        Font ret = null;
+        if (m != null) ret = (Font)m.get(new Integer(pointsize));
+        else fonts.put(stream, m = new Basket.Hash());
+        if (ret == null) m.put(new Integer(pointsize), ret = new Font(stream, pointsize));
         return ret;
     }
 
@@ -58,53 +63,143 @@ public class Font {
      *  Rasterize the glyphs of <code>text</code>.
      *  @returns <code>(width&lt;&lt;32)|height</code>
      */
-    public long rasterizeGlyphs(String text, PixelBuffer pb, int textcolor, int x, int y, int cx1, int cy1, int cx2, int cy2) {
+    public String rasterizeGlyphs(String text) {
+        StringBuffer path = new StringBuffer(text.length() * 50);
+        for(int i=0; i<text.length(); i++) {
+            final char c = text.charAt(i);
+            Glyph g = glyphs[c];
+            if (g == null) glyphs[c] = g = Platform.createGlyph(this, c);
+            g.render();
+            path.append(g.path);
+        }
+        return path.toString();
+    }
+    public long rasterizeGlyphs(String text, PixelBuffer pb, Affine a, Mesh h, int fg, int bg) {
         int width = 0, height = 0;
         if (!latinCharsPreloaded) {       // preload the Latin-1 charset with low priority (we'll probably want it)
-            for(int i=48; i<57; i++) if (glyphs[i]==null) glyphsToBeCached.put(glyphs[i]=Platform.createGlyph(this, (char)i),"");
-            for(int i=32; i<47; i++) if (glyphs[i]==null) glyphsToBeCached.put(glyphs[i]=Platform.createGlyph(this, (char)i),"");
-            for(int i=57; i<128; i++) if (glyphs[i]==null) glyphsToBeCached.put(glyphs[i]=Platform.createGlyph(this, (char)i),"");
-            if (!glyphRenderingTaskIsScheduled) {
-                Scheduler.add(glyphRenderingTask);
-                glyphRenderingTaskIsScheduled = true;
-            }
+            for(int i=48; i<57; i++) if(glyphs[i]==null) toBeRasterized.append(glyphs[i]=Platform.createGlyph(this, (char)i));
+            for(int i=32; i<47; i++) if(glyphs[i]==null) toBeRasterized.append(glyphs[i]=Platform.createGlyph(this, (char)i));
+            for(int i=57; i<128; i++) if(glyphs[i]==null) toBeRasterized.append(glyphs[i]=Platform.createGlyph(this, (char)i));
             latinCharsPreloaded = true;
         }
+        a = a==null ? null : a.copy();
         for(int i=0; i<text.length(); i++) {
             final char c = text.charAt(i);
             Glyph g = glyphs[c];
             if (g == null) glyphs[c] = g = Platform.createGlyph(this, c);
             g.render();
-            if (pb != null) pb.drawGlyph(g, x + width, y + g.font.max_ascent - g.baseline, cx1, cy1, cx2, cy2, textcolor);
+            if (a!=null) a.premultiply(Affine.translate(0, g.font.max_ascent - g.baseline));
+            if (pb != null) pb.drawGlyph(g, a, h, fg, bg);
+            if (a!=null) a.premultiply(Affine.translate(0, -1 * (g.font.max_ascent - g.baseline)));
             width += g.advance;
+            if (a!=null) a.premultiply(Affine.translate(g.advance, 0));
             height = java.lang.Math.max(height, max_ascent + max_descent);
         }
         return ((((long)width) << 32) | (long)(height & 0xffffffffL));
     }
 
     // FEATURE do we really need to be caching sizes?
-    private static Cache sizeCache = new Cache(1000);
+    private static Cache sizeCache = new Cache(1000, true);
     public int textwidth(String s) { return (int)((textsize(s) >>> 32) & 0xffffffff); }
     public int textheight(String s) { return (int)(textsize(s) & 0xffffffffL); }
     public long textsize(String s) {
         Long l = (Long)sizeCache.get(s);
         if (l != null) return ((Long)l).longValue();
-        long ret = rasterizeGlyphs(s, null, 0, 0, 0, 0, 0, 0, 0);
+        long ret = rasterizeGlyphs(s, null, null, null, 0, 0);
         sizeCache.put(s, new Long(ret));
         return ret;
     }
 
-    static final Scheduler.Task glyphRenderingTask = new Scheduler.Task() { public void perform() {
-        // FIXME: this should be a low-priority task
-        glyphRenderingTaskIsScheduled = false;
-        if (glyphsToBeCached.isEmpty()) return;
-        Glyph g = (Glyph)glyphsToBeCached.keys().nextElement();
-        if (g == null) return;
-        glyphsToBeCached.remove(g);
-        Log.debug(Font.class, "glyphRenderingTask rendering " + g.c + " of " + g.font);
+    public Glyph getGlyph(char c) {
+        rasterizeGlyphs(c+"", null, null, null, 0, 0);
+        Glyph g = glyphs[c];
         g.render();
-        Log.debug(Glyph.class, "   done rendering glyph " + g.c);
-        glyphRenderingTaskIsScheduled = true;
-        Scheduler.add(this);
-    } };
+        return g;
+    }
+
+    static { new Thread() { public void run() {
+        while(true) {
+            Glyph g = (Glyph)toBeRasterized.remove(true);
+            if (g == null) continue;
+            Log.debug(Font.class, "glyphRenderingTask rendering " + g.c + " of " + g.font);
+            g.render();
+            Log.debug(Glyph.class, "   done rendering glyph " + g.c);
+        }
+    } }.start(); }
+
+
+    // FreeType Interface //////////////////////////////////////////////////////////////////////////////
+
+    // FEATURE: use streams, not memoryfont's
+    // FEATURE: kerning pairs
+    private static final Runtime rt;
+    private static JS loadedStream;
+    private static int loadedStreamAddr;
+
+    static {
+        try {
+            rt = (Runtime)Class.forName("org.ibex.util.MIPSApps").newInstance();
+        } catch(Exception e) {
+            throw new Error("Error instantiating freetype: " + e);
+        }
+        rt.start(new String[]{"freetype"});
+        rt.execute();
+        rtCheck();
+    }
+    
+    private static void rtCheck() { if(rt.getState() != Runtime.PAUSED) throw new Error("Freetype exited " + rt.exitStatus()); }
+    
+    private static void loadFontByteStream(JS res) {
+        if(loadedStream == res) return;
+        
+        try {
+            Log.info(Font.class, "loading font " + JSU.str(res));
+            InputStream is = JSU.getInputStream(res);
+            byte[] fontstream = InputStreamToByteArray.convert(is);
+            rt.free(loadedStreamAddr);
+            loadedStreamAddr = rt.xmalloc(fontstream.length);
+            rt.copyout(fontstream, loadedStreamAddr, fontstream.length);
+            if(rt.call("load_font", loadedStreamAddr, fontstream.length) != 0)
+                throw new RuntimeException("load_font failed"); // FEATURE: better error
+            rtCheck();
+            loadedStream = res;
+        } catch (Exception e) {
+            // FEATURE: Better error reporting (thow an exception?)
+            Log.info(Font.class, e);
+        }
+    }
+
+    private static synchronized void renderGlyph(Font.Glyph glyph) throws IOException {
+        try {
+            Log.debug(Font.class, "rasterizing glyph " + glyph.c + " of font " + glyph.font);
+            if (loadedStream != glyph.font.stream) loadFontByteStream(glyph.font.stream);
+            
+            long start = System.currentTimeMillis();
+            
+            rt.call("render",glyph.c,glyph.font.pointsize);
+            rtCheck();
+            
+            glyph.font.max_ascent = rt.getUserInfo(3);
+            glyph.font.max_descent = rt.getUserInfo(4);
+            glyph.baseline = rt.getUserInfo(5);
+            glyph.advance = rt.getUserInfo(6);
+            
+            glyph.width = rt.getUserInfo(1);
+            glyph.height = rt.getUserInfo(2);
+
+            glyph.data = new byte[glyph.width * glyph.height];
+            int addr = rt.getUserInfo(0);
+            rt.copyin(addr, glyph.data, glyph.width * glyph.height);
+            
+            byte[] path = new byte[rt.getUserInfo(8)];
+            rt.copyin(rt.getUserInfo(7), path, rt.getUserInfo(8));
+            glyph.path = new String(path);
+            glyph.path += " m " + (64 * glyph.advance) + " 0 "; 
+
+            glyph.isLoaded = true;
+        } catch (Exception e) {
+            // FEATURE: Better error reporting (thow an exception?)
+            Log.info(Font.class, e);
+        }
+    }
 }