minimise move events
[org.ibex.core.git] / src / org / ibex / Font.java
1 // Copyright 2004 Adam Megacz, see the COPYING file for licensing [GPL]
2 package org.ibex;
3 import org.ibex.translators.*;
4 import org.ibex.util.*;
5 import java.io.*;
6 import java.util.Hashtable;
7
8 import org.ibex.js.JSExn;
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     }
36
37
38     // Statics //////////////////////////////////////////////////////////////////////
39
40     private static final Freetype freetype = new Freetype();
41     static final Hashtable glyphsToBeCached = new Hashtable();
42     static final Hashtable glyphsToBeDisplayed = new Hashtable();
43     private static Cache fontCache = new Cache(100);
44     public static Font getFont(Stream stream, int pointsize) {
45         Font ret = (Font)fontCache.get(stream, new Integer(pointsize));
46         if (ret == null) fontCache.put(stream, new Integer(pointsize), ret = new Font(stream, pointsize));
47         return ret;
48     }
49
50
51     // Methods //////////////////////////////////////////////////////////////////////
52
53     /**
54      *  Rasterize the glyphs of <code>text</code>.
55      *
56      *  If all the glyphs of <code>text</code> are not yet loaded,
57      *  spawn a Task to load them and then invoke callback.  If all
58      *  the glyphs <i>are</i> loaded, rasterize them to the
59      *  PixelBuffer (if non-null).
60      *
61      *  @returns <code>(width&lt;&lt;32)|height</code> if all glyphs are loaded; else -1
62      */
63     public long rasterizeGlyphs(final String text, PixelBuffer pb, int textcolor,
64                                 int x, int y, int cx1, int cy1, int cx2, int cy2,
65                                 final Scheduler.Task callback) {
66         boolean encounteredUnrenderedGlyph = false;
67         int width = 0, height = 0;
68         
69         // preload the Latin-1 charset with low priority (we'll probably want it)
70         if (!latinCharsPreloaded) {
71             for(int i=48; i<57; i++) glyphsToBeCached.put(glyphs[i] = Platform.createGlyph(this, (char)i),"");
72             for(int i=32; i<47; i++) glyphsToBeCached.put(glyphs[i] = Platform.createGlyph(this, (char)i),"");
73             for(int i=57; i<128; i++) glyphsToBeCached.put(glyphs[i] = Platform.createGlyph(this, (char)i),"");            
74             }
75         latinCharsPreloaded = true;
76         
77         if (!glyphRenderingTaskIsScheduled) {
78             Scheduler.add(glyphRenderingTask);
79             glyphRenderingTaskIsScheduled = true;
80         }
81         
82         for(int i=0; i<text.length(); i++) {
83                 final char c = text.charAt(i);
84                 Glyph g = glyphs[c];
85                 if (g == null) {
86                         g = Platform.createGlyph(this, c);
87                         glyphs[c] = g;
88                 }
89                 if (!g.isLoaded) {
90                         if (!glyphsToBeDisplayed.contains(g)) {
91                                 glyphsToBeDisplayed.put(g, "");              // move glyph to the display hash
92                                 glyphsToBeCached.remove(g);
93                                 encounteredUnrenderedGlyph = true;
94                         }
95                 } else if (!encounteredUnrenderedGlyph) {
96                         if (pb != null) pb.drawGlyph(g, x + width, y + g.font.max_ascent - g.baseline, cx1, cy1, cx2, cy2, textcolor);
97                         width += g.advance;
98                         height = java.lang.Math.max(height, max_ascent + max_descent);
99                 }
100         }
101         
102         if (!encounteredUnrenderedGlyph) return ((((long)width) << 32) | (long)(height & 0xffffffffL));
103         
104         if (callback != null) Scheduler.add(new Scheduler.Task() {
105                 public void perform() throws IOException, JSExn {
106                         // FEATURE this isn't terribly efficient... perhaps the task should go on the last glyph?
107                         for(int i=0; i<text.length(); i++) {
108                                 Glyph g = glyphs[text.charAt(i)];
109                                 if (g == null || !g.isLoaded) { Scheduler.add(this); return; }
110                         }
111                         callback.perform();
112                 }});
113         return -1;
114     }
115
116     // FEATURE do we really need to be caching sizes?
117     private static Cache sizeCache = new Cache(1000);
118     public int textwidth(String s) { return (int)((textsize(s) >>> 32) & 0xffffffff); }
119     public int textheight(String s) { return (int)(textsize(s) & 0xffffffffL); }
120     public long textsize(String s) {
121         Long l = (Long)sizeCache.get(s);
122         if (l != null) return ((Long)l).longValue();
123         long ret = rasterizeGlyphs(s, null, 0, 0, 0, 0, 0, 0, 0, null);
124         if (ret != -1) sizeCache.put(s, new Long(ret));
125         return ret == -1 ? 0 : ret;
126     }
127
128     static final Scheduler.Task glyphRenderingTask = new Scheduler.Task() { public void perform() {
129         Glyph g = null;
130         if (!glyphsToBeDisplayed.isEmpty()) {
131             g = (Glyph)glyphsToBeDisplayed.keys().nextElement();
132             glyphsToBeDisplayed.remove(g);
133             Log.debug(Font.class, "glyphRenderingTask removed glyph " + g.c + " of font " /*+ g.font*/ + " from glyphsToBeDisplayed");
134         }
135         else if (!glyphsToBeCached.isEmpty()) {
136             g = (Glyph)glyphsToBeCached.keys().nextElement();
137             glyphsToBeCached.remove(g);
138             Log.debug(Font.class, "glyphRenderingTask removed glyph " + g.c + " of font " /*+ g.font*/ + " from glyphsToBeCached");
139         }
140         if (g != null) {
141             Log.debug(Glyph.class, "rendering glyph " + g);
142             try { freetype.renderGlyph(g); } catch (IOException e) { Log.info(Freetype.class, e); }
143             Scheduler.add(this);          // keep ourselves in the queue until there are no glyphs to render
144             glyphRenderingTaskIsScheduled = true;
145         }
146         else {
147             glyphRenderingTaskIsScheduled = false;
148             return;
149         }
150     } };
151 }