initial checkin
[org.ibex.nanogoat.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 org.ibex.js.JSExn;
7
8 // FEATURE: this could be cleaner
9 /** encapsulates a single font (a set of Glyphs) */
10 public class Font {
11
12     private Font(Stream stream, int pointsize) { this.stream = stream; this.pointsize = pointsize; }
13
14     private static boolean glyphRenderingTaskIsScheduled = false;
15
16     public final int pointsize;                 ///< the size of the font
17     public final Stream stream;                 ///< the stream from which this font was loaded
18     public int max_ascent;                      ///< the maximum ascent, in pixels
19     public int max_descent;                     ///< the maximum descent, in pixels
20     boolean latinCharsPreloaded = false;        ///< true if a request to preload ASCII 32-127 has begun
21     Glyph[] glyphs = new Glyph[65535];          ///< the glyphs that comprise this font
22
23     public abstract static class Glyph {
24         protected Glyph(Font font, char c) { this.font = font; this.c = c; }
25         public final Font font;
26         public final char c;
27         public int baseline;                    ///< within the alphamask, this is the y-coordinate of the baseline
28         public int advance;                     ///< amount to increment the x-coordinate
29         public boolean isLoaded = false;        ///< true iff the glyph is loaded
30         public int width = -1;                  ///< the width of the glyph
31         public int height = -1;                 ///< the height of the glyph
32         public byte[] data = null;              ///< the alpha channel samples for this font
33     }
34
35
36     // Statics //////////////////////////////////////////////////////////////////////
37
38     private static final Freetype freetype = new Freetype();
39     static final Queue glyphsToBeRendered = new Queue(255);
40     private static Cache fontCache = new Cache(100);
41     public static Font getFont(Stream stream, int pointsize) {
42         Font ret = (Font)fontCache.get(stream, new Integer(pointsize));
43         if (ret == null) fontCache.put(stream, new Integer(pointsize), ret = new Font(stream, pointsize));
44         return ret;
45     }
46
47
48     // Methods //////////////////////////////////////////////////////////////////////
49
50     /**
51      *  Rasterize the glyphs of <code>text</code>.
52      *
53      *  If all the glyphs of <code>text</code> are not yet loaded,
54      *  spawn a Task to load them and then invoke callback.  If all
55      *  the glyphs <i>are</i> loaded, rasterize them to the
56      *  PixelBuffer (if non-null).
57      *
58      *  @returns <code>(width&lt;&lt;32)|height</code> if all glyphs are loaded; else -1
59      */
60     public long rasterizeGlyphs(final String text, PixelBuffer pb, int textcolor,
61                                 int x, int y, int cx1, int cy1, int cx2, int cy2,
62                                 final Scheduler.Task callback) {
63         boolean encounteredUnrenderedGlyph = false;
64         int width = 0, height = 0;
65         for(int i=0; i<text.length(); i++) {
66             final char c = text.charAt(i);
67             Glyph g = glyphs[c];
68             if (g == null) {
69                 g = Platform.createGlyph(this, c);
70                 glyphs[c] = g;
71             }
72             if (!g.isLoaded) {
73                 //Log.debug(Font.class, "rasterizeGlyphs encountered unrasterized glyph " + g.c + " of font " + this);
74                 //System.out.println("rasterizeGlyphs encountered unrasterized glyph " + g.c + " of font " + this);
75                 glyphsToBeRendered.prepend(g);              // even if it's already in the queue, boost its priority
76                 encounteredUnrenderedGlyph = true;
77             } else if (!encounteredUnrenderedGlyph) {
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         }
83
84         if (!encounteredUnrenderedGlyph) return ((((long)width) << 32) | (long)(height & 0xffffffffL));
85
86         if (callback != null) Scheduler.add(new Scheduler.Task() {
87                 public void perform() throws IOException, JSExn {
88                     // FEATURE this isn't terribly efficient... perhaps the task should go on the last glyph?
89                     for(int i=0; i<text.length(); i++) {
90                         Glyph g = glyphs[text.charAt(i)];
91                         if (g == null || !g.isLoaded) { Scheduler.add(this); return; }
92                     }
93                     callback.perform();
94                 }});
95
96         // preload the Latin-1 charset with low priority (we'll probably want it)
97         if (!latinCharsPreloaded) {
98             for(int i=48; i<57; i++) glyphsToBeRendered.append(glyphs[i] = Platform.createGlyph(this, (char)i));
99             for(int i=32; i<47; i++) glyphsToBeRendered.append(glyphs[i] = Platform.createGlyph(this, (char)i));
100             for(int i=57; i<128; i++) glyphsToBeRendered.append(glyphs[i] = Platform.createGlyph(this, (char)i));
101             latinCharsPreloaded = true;
102         }
103         if (!glyphRenderingTaskIsScheduled) {
104             Scheduler.add(glyphRenderingTask);
105             glyphRenderingTaskIsScheduled = true;
106         }
107         return -1;
108     }
109
110     // FEATURE do we really need to be caching sizes?
111     private static Cache sizeCache = new Cache(1000);
112     public int textwidth(String s) { return (int)((textsize(s) >>> 32) & 0xffffffff); }
113     public int textheight(String s) { return (int)(textsize(s) & 0xffffffffL); }
114     public long textsize(String s) {
115         Long l = (Long)sizeCache.get(s);
116         if (l != null) return ((Long)l).longValue();
117         long ret = rasterizeGlyphs(s, null, 0, 0, 0, 0, 0, 0, 0, null);
118         if (ret != -1) sizeCache.put(s, new Long(ret));
119         return ret == -1 ? 0 : ret;
120     }
121
122     static final Scheduler.Task glyphRenderingTask = new Scheduler.Task() { public void perform() {
123         Glyph g = (Glyph)glyphsToBeRendered.remove(false);
124         if (g == null) { glyphRenderingTaskIsScheduled = false; return; }
125         Log.debug(Font.class, "glyphRenderingTask dequeued glyph " + g.c + " of font " + g.font);
126         if (!g.isLoaded) {
127             Log.debug(Glyph.class, "rendering glyph " + g.c);
128             try { freetype.renderGlyph(g); } catch (IOException e) { Log.info(Freetype.class, e); }
129         }
130         Scheduler.add(this);          // keep ourselves in the queue until there are no glyphs to render
131         glyphRenderingTaskIsScheduled = true;
132     } };
133 }