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