1/*
2 * Copyright (c) 2007, 2014, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.  Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
25
26package sun.font;
27
28import java.awt.geom.GeneralPath;
29import java.awt.geom.Point2D;
30import java.awt.geom.Rectangle2D;
31import java.lang.ref.WeakReference;
32import java.lang.reflect.Constructor;
33
34import sun.java2d.Disposer;
35import sun.java2d.DisposerRecord;
36
37/* FontScaler is "internal interface" to font rasterizer library.
38 *
39 * Access to native rasterizers without going through this interface is
40 * strongly discouraged. In particular, this is important because native
41 * data could be disposed due to runtime font processing error at any time.
42 *
43 * FontScaler represents combination of particular rasterizer implementation
44 * and particular font. It does not include rasterization attributes such as
45 * transform. These attributes are part of native scalerContext object.
46 * This approach allows to share same scaler for different requests related
47 * to the same font file.
48 *
49 * Note that scaler may throw FontScalerException on any operation.
50 * Generally this means that runtime error had happened and scaler is not
51 * usable.  Subsequent calls to this scaler should not cause crash but will
52 * likely cause exceptions to be thrown again.
53 *
54 * It is recommended that callee should replace its reference to the scaler
55 * with something else. For instance it could be FontManager.getNullScaler().
56 * Note that NullScaler is trivial and will not actually rasterize anything.
57 *
58 * Alternatively, callee can use more sophisticated error recovery strategies
59 * and for instance try to substitute failed scaler with new scaler instance
60 * using another font.
61 *
62 * Note that in case of error there is no need to call dispose(). Moreover,
63 * dispose() generally is called by Disposer thread and explicit calls to
64 * dispose might have unexpected sideeffects because scaler can be shared.
65 *
66 * Current disposing logic is the following:
67 *   - scaler is registered in the Disposer by the FontManager (on creation)
68 *   - scalers are disposed when associated Font2D object (e.g. TruetypeFont)
69 *     is garbage collected. That's why this object implements DisposerRecord
70 *     interface directly (as it is not used as indicator when it is safe
71 *     to release native state) and that's why we have to use WeakReference
72 *     to Font internally.
73 *   - Majority of Font2D objects are linked from various mapping arrays
74 *     (e.g. FontManager.localeFullNamesToFont). So, they are not collected.
75 *     This logic only works for fonts created with Font.createFont()
76 *
77 *  Notes:
78 *   - Eventually we may consider releasing some of the scaler resources if
79 *     it was not used for a while but we do not want to be too aggressive on
80 *     this (and this is probably more important for Type1 fonts).
81 */
82public abstract class FontScaler implements DisposerRecord {
83
84    private static FontScaler nullScaler = null;
85    private static Constructor<? extends FontScaler> scalerConstructor = null;
86
87    //Find preferred font scaler
88    //
89    //NB: we can allow property based preferences
90    //   (theoretically logic can be font type specific)
91    static {
92        Class<? extends FontScaler> scalerClass = null;
93        Class<?>[] arglst = new Class<?>[] {Font2D.class, int.class,
94        boolean.class, int.class};
95
96        try {
97            @SuppressWarnings("unchecked")
98            Class<? extends FontScaler> tmp = (Class<? extends FontScaler>)
99                (FontUtilities.isOpenJDK ?
100                 Class.forName("sun.font.FreetypeFontScaler") :
101                 Class.forName("sun.font.T2KFontScaler"));
102            scalerClass = tmp;
103        } catch (ClassNotFoundException e) {
104                scalerClass = NullFontScaler.class;
105        }
106
107        //NB: rewrite using factory? constructor is ugly way
108        try {
109            scalerConstructor = scalerClass.getConstructor(arglst);
110        } catch (NoSuchMethodException e) {
111            //should not happen
112        }
113    }
114
115    /* This is the only place to instantiate new FontScaler.
116     * Therefore this is very convinient place to register
117     * scaler with Disposer as well as trigger deregistring bad font
118     * in case when scaler reports this.
119     */
120    public static FontScaler getScaler(Font2D font,
121                                int indexInCollection,
122                                boolean supportsCJK,
123                                int filesize) {
124        FontScaler scaler = null;
125
126        try {
127            Object args[] = new Object[] {font, indexInCollection,
128                                          supportsCJK, filesize};
129            scaler = scalerConstructor.newInstance(args);
130            Disposer.addObjectRecord(font, scaler);
131        } catch (Throwable e) {
132            scaler = nullScaler;
133
134            //if we can not instantiate scaler assume bad font
135            //NB: technically it could be also because of internal scaler
136            //    error but here we are assuming scaler is ok.
137            FontManager fm = FontManagerFactory.getInstance();
138            fm.deRegisterBadFont(font);
139        }
140        return scaler;
141    }
142
143    /*
144     * At the moment it is harmless to create 2 null scalers so, technically,
145     * syncronized keyword is not needed.
146     *
147     * But it is safer to keep it to avoid subtle problems if we will be adding
148     * checks like whether scaler is null scaler.
149     */
150    public static synchronized FontScaler getNullScaler() {
151        if (nullScaler == null) {
152            nullScaler = new NullFontScaler();
153        }
154        return nullScaler;
155    }
156
157    protected WeakReference<Font2D> font = null;
158    protected long nativeScaler = 0; //used by decendants
159                                     //that have native state
160    protected boolean disposed = false;
161
162    abstract StrikeMetrics getFontMetrics(long pScalerContext)
163                throws FontScalerException;
164
165    abstract float getGlyphAdvance(long pScalerContext, int glyphCode)
166                throws FontScalerException;
167
168    abstract void getGlyphMetrics(long pScalerContext, int glyphCode,
169                                  Point2D.Float metrics)
170                throws FontScalerException;
171
172    /*
173     *  Returns pointer to native GlyphInfo object.
174     *  Callee is responsible for freeing this memory.
175     *
176     *  Note:
177     *   currently this method has to return not 0L but pointer to valid
178     *   GlyphInfo object. Because Strike and drawing releated logic does
179     *   expect that.
180     *   In the future we may want to rework this to allow 0L here.
181     */
182    abstract long getGlyphImage(long pScalerContext, int glyphCode)
183                throws FontScalerException;
184
185    abstract Rectangle2D.Float getGlyphOutlineBounds(long pContext,
186                                                     int glyphCode)
187                throws FontScalerException;
188
189    abstract GeneralPath getGlyphOutline(long pScalerContext, int glyphCode,
190                                         float x, float y)
191                throws FontScalerException;
192
193    abstract GeneralPath getGlyphVectorOutline(long pScalerContext, int[] glyphs,
194                                               int numGlyphs, float x, float y)
195                throws FontScalerException;
196
197    /* Used by Java2D disposer to ensure native resources are released.
198       Note: this method does not release any of created
199             scaler context objects! */
200    public void dispose() {}
201
202    /* At the moment these 3 methods are needed for Type1 fonts only.
203     * For Truetype fonts we extract required info outside of scaler
204     * on java layer.
205     */
206    abstract int getNumGlyphs() throws FontScalerException;
207    abstract int getMissingGlyphCode() throws FontScalerException;
208    abstract int getGlyphCode(char charCode) throws FontScalerException;
209
210    /* This method returns table cache used by native layout engine.
211     * This cache is essentially just small collection of
212     * pointers to various truetype tables. See definition of TTLayoutTableCache
213     * in the fontscalerdefs.h for more details.
214     *
215     * Note that tables themselves have same format as defined in the truetype
216     * specification, i.e. font scaler do not need to perform any preprocessing.
217     *
218     * Probably it is better to have API to request pointers to each table
219     * separately instead of requesting pointer to some native structure.
220     * (then there is not need to share its definition by different
221     * implementations of scaler).
222     * However, this means multiple JNI calls and potential impact on performance.
223     *
224     * Note: return value 0 is legal.
225     *   This means tables are not available (e.g. type1 font).
226     */
227    abstract long getLayoutTableCache() throws FontScalerException;
228
229    /* Used by the OpenType engine for mark positioning. */
230    abstract Point2D.Float getGlyphPoint(long pScalerContext,
231                                int glyphCode, int ptNumber)
232        throws FontScalerException;
233
234    abstract long getUnitsPerEm();
235
236    /* Returns pointer to native structure describing rasterization attributes.
237       Format of this structure is scaler-specific.
238
239       Callee is responsible for freeing scaler context (using free()).
240
241       Note:
242         Context is tightly associated with strike and it is actually
243        freed when corresponding strike is being released.
244     */
245    abstract long createScalerContext(double[] matrix,
246                                      int aa, int fm,
247                                      float boldness, float italic,
248                                      boolean disableHinting);
249
250    /* Marks context as invalid because native scaler is invalid.
251       Notes:
252         - pointer itself is still valid and has to be released
253         - if pointer to native scaler was cached it
254           should not be neither disposed nor used.
255           it is very likely it is already disposed by this moment. */
256    abstract void invalidateScalerContext(long ppScalerContext);
257}
258