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