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