bugfix in url parsing for HTTP.java
[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 import org.xwt.mips.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(Stream 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 Stream 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     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         void render() {
37             if (!isLoaded) try { renderGlyph(this); } catch (IOException e) { Log.info(Font.class, e); }
38             isLoaded = true;
39         }
40     }
41
42
43     // Statics //////////////////////////////////////////////////////////////////////
44
45     static final Hashtable glyphsToBeCached = new Hashtable();
46     static final Hashtable glyphsToBeDisplayed = new Hashtable();
47     private static Cache fontCache = new Cache(100);
48     public static Font getFont(Stream stream, int pointsize) {
49         Font ret = (Font)fontCache.get(stream, new Integer(pointsize));
50         if (ret == null) fontCache.put(stream, new Integer(pointsize), ret = new Font(stream, pointsize));
51         return ret;
52     }
53
54
55     // Methods //////////////////////////////////////////////////////////////////////
56
57     /**
58      *  Rasterize the glyphs of <code>text</code>.
59      *  @returns <code>(width&lt;&lt;32)|height</code>
60      */
61     public long rasterizeGlyphs(String text, PixelBuffer pb, int textcolor, int x, int y, int cx1, int cy1, int cx2, int cy2) {
62         int width = 0, height = 0;
63         if (!latinCharsPreloaded) {       // preload the Latin-1 charset with low priority (we'll probably want it)
64             for(int i=48; i<57; i++) if (glyphs[i]==null) glyphsToBeCached.put(glyphs[i]=Platform.createGlyph(this, (char)i),"");
65             for(int i=32; i<47; i++) if (glyphs[i]==null) glyphsToBeCached.put(glyphs[i]=Platform.createGlyph(this, (char)i),"");
66             for(int i=57; i<128; i++) if (glyphs[i]==null) glyphsToBeCached.put(glyphs[i]=Platform.createGlyph(this, (char)i),"");
67             if (!glyphRenderingTaskIsScheduled) {
68                 Scheduler.add(glyphRenderingTask);
69                 glyphRenderingTaskIsScheduled = true;
70             }
71             latinCharsPreloaded = true;
72         }
73         for(int i=0; i<text.length(); i++) {
74             final char c = text.charAt(i);
75             Glyph g = glyphs[c];
76             if (g == null) glyphs[c] = g = Platform.createGlyph(this, c);
77             g.render();
78             if (pb != null) pb.drawGlyph(g, x + width, y + g.font.max_ascent - g.baseline, cx1, cy1, cx2, cy2, textcolor);
79             width += g.advance;
80             height = java.lang.Math.max(height, max_ascent + max_descent);
81         }
82         return ((((long)width) << 32) | (long)(height & 0xffffffffL));
83     }
84
85     // FEATURE do we really need to be caching sizes?
86     private static Cache sizeCache = new Cache(1000);
87     public int textwidth(String s) { return (int)((textsize(s) >>> 32) & 0xffffffff); }
88     public int textheight(String s) { return (int)(textsize(s) & 0xffffffffL); }
89     public long textsize(String s) {
90         Long l = (Long)sizeCache.get(s);
91         if (l != null) return ((Long)l).longValue();
92         long ret = rasterizeGlyphs(s, null, 0, 0, 0, 0, 0, 0, 0);
93         sizeCache.put(s, new Long(ret));
94         return ret;
95     }
96
97     static final Task glyphRenderingTask = new Task() { public void perform() {
98         // FIXME: this should be a low-priority task
99         glyphRenderingTaskIsScheduled = false;
100         if (glyphsToBeCached.isEmpty()) return;
101         Glyph g = (Glyph)glyphsToBeCached.keys().nextElement();
102         if (g == null) return;
103         glyphsToBeCached.remove(g);
104         Log.debug(Font.class, "glyphRenderingTask rendering " + g.c + " of " + g.font);
105         g.render();
106         Log.debug(Glyph.class, "   done rendering glyph " + g.c);
107         glyphRenderingTaskIsScheduled = true;
108         Scheduler.add(this);
109     } };
110
111
112     // FreeType Interface //////////////////////////////////////////////////////////////////////////////
113
114     // FEATURE: use streams, not memoryfont's
115     // FEATURE: kerning pairs
116     private static final Runtime rt;
117     private static Stream loadedStream;
118     private static int loadedStreamAddr;
119
120     static {
121         try {
122             rt = (Runtime)Class.forName("org.ibex.util.MIPSApps").newInstance();
123         } catch(Exception e) {
124             throw new Error("Error instantiating freetype: " + e);
125         }
126         rt.start(new String[]{"freetype"});
127         rt.execute();
128         rtCheck();
129     }
130     
131     private static void rtCheck() { if(rt.getState() != Runtime.PAUSED) throw new Error("Freetype exited " + rt.exitStatus()); }
132     
133     private static void loadFontByteStream(Stream res) {
134         if(loadedStream == res) return;
135         
136         try {
137             Log.info(Font.class, "loading font " + res);
138             InputStream is = Stream.getInputStream(res);
139             byte[] fontstream = InputStreamToByteArray.convert(is);
140             rt.free(loadedStreamAddr);
141             loadedStreamAddr = rt.xmalloc(fontstream.length);
142             rt.copyout(fontstream, loadedStreamAddr, fontstream.length);
143             if(rt.call("load_font", loadedStreamAddr, fontstream.length) != 0)
144                 throw new RuntimeException("load_font failed"); // FEATURE: better error
145             rtCheck();
146             loadedStream = res;
147         } catch (Exception e) {
148             // FEATURE: Better error reporting (thow an exception?)
149             Log.info(Font.class, e);
150         }
151     }
152
153     private static synchronized void renderGlyph(Font.Glyph glyph) throws IOException {
154         try {
155             Log.debug(Font.class, "rasterizing glyph " + glyph.c + " of font " + glyph.font);
156             if (loadedStream != glyph.font.stream) loadFontByteStream(glyph.font.stream);
157             
158             long start = System.currentTimeMillis();
159             
160             rt.call("render",glyph.c,glyph.font.pointsize);
161             rtCheck();
162             
163             glyph.font.max_ascent = rt.getUserInfo(3);
164             glyph.font.max_descent = rt.getUserInfo(4);
165             glyph.baseline = rt.getUserInfo(5);
166             glyph.advance = rt.getUserInfo(6);
167             
168             glyph.width = rt.getUserInfo(1);
169             glyph.height = rt.getUserInfo(2);
170             
171             glyph.data = new byte[glyph.width * glyph.height];
172             int addr = rt.getUserInfo(0);
173             rt.copyin(addr, glyph.data, glyph.width * glyph.height);
174             
175             glyph.isLoaded = true;
176         } catch (Exception e) {
177             // FEATURE: Better error reporting (thow an exception?)
178             Log.info(Font.class, e);
179         }
180     }
181 }