1
2/*
3 * Copyright 2006 The Android Open Source Project
4 *
5 * Use of this source code is governed by a BSD-style license that can be
6 * found in the LICENSE file.
7 */
8
9
10#ifndef SkFontHost_DEFINED
11#define SkFontHost_DEFINED
12
13#include "SkScalerContext.h"
14#include "SkTypeface.h"
15
16class SkDescriptor;
17class SkStream;
18class SkWStream;
19
20typedef uint32_t SkFontTableTag;
21
22/** \class SkFontHost
23
24    This class is ported to each environment. It is responsible for bridging
25    the gap between the (sort of) abstract class SkTypeface and the
26    platform-specific implementation that provides access to font files.
27
28    One basic task is for each create (subclass of) SkTypeface, the FontHost is
29    resonsible for assigning a uniqueID. The ID should be unique for the
30    underlying font file/data, not unique per typeface instance. Thus it is
31    possible/common to request a typeface for the same font more than once
32    (e.g. asking for the same font by name several times). The FontHost may
33    return seperate typeface instances in that case, or it may choose to use a
34    cache and return the same instance (but calling typeface->ref(), since the
35    caller is always responsible for calling unref() on each instance that is
36    returned). Either way, the fontID for those instance(s) will be the same.
37    In addition, the fontID should never be set to 0. That value is used as a
38    sentinel to indicate no-font-id.
39
40    The major aspects are:
41    1) Given either a name/style, return a subclass of SkTypeface that
42        references the closest matching font available on the host system.
43    2) Given the data for a font (either in a stream or a file name), return
44        a typeface that allows access to that data.
45    3) Each typeface instance carries a 32bit ID for its corresponding font.
46        SkFontHost turns that ID into a stream to access the font's data.
47    4) Given a font ID, return a subclass of SkScalerContext, which connects a
48        font scaler (e.g. freetype or other) to the font's data.
49    5) Utilites to manage the font cache (budgeting) and gamma correction
50*/
51class SK_API SkFontHost {
52public:
53    /** Return a new, closest matching typeface given either an existing family
54        (specified by a typeface in that family) or by a familyName and a
55        requested style, or by a set of Unicode codepoitns to cover in a given
56        style.
57        1) If familyFace is null, use familyName.
58        2) If familyName is null, use data (UTF-16 to cover).
59        3) If all are null, return the default font that best matches style
60     */
61    static SkTypeface* CreateTypeface(const SkTypeface* familyFace,
62                                      const char familyName[],
63                                      const void* data, size_t bytelength,
64                                      SkTypeface::Style style);
65
66    /** Return a new typeface given the data buffer. If the data does not
67        represent a valid font, returns null.
68
69        If a typeface instance is returned, the caller is responsible for
70        calling unref() on the typeface when they are finished with it.
71
72        The returned typeface may or may not have called ref() on the stream
73        parameter. If the typeface has not called ref(), then it may have made
74        a copy of the releveant data. In either case, the caller is still
75        responsible for its refcnt ownership of the stream.
76     */
77    static SkTypeface* CreateTypefaceFromStream(SkStream*);
78
79    /** Return a new typeface from the specified file path. If the file does not
80        represent a valid font, this returns null. If a typeface is returned,
81        the caller is responsible for calling unref() when it is no longer used.
82     */
83    static SkTypeface* CreateTypefaceFromFile(const char path[]);
84
85    ///////////////////////////////////////////////////////////////////////////
86
87    /** Return a new stream to read the font data, or null if the uniqueID does
88        not match an existing typeface. .The caller must call stream->unref()
89        when it is finished reading the data.
90    */
91    static SkStream* OpenStream(SkFontID uniqueID);
92
93    /** Some fonts are stored in files. If that is true for the fontID, then
94        this returns the byte length of the full file path. If path is not null,
95        then the full path is copied into path (allocated by the caller), up to
96        length bytes. If index is not null, then it is set to the truetype
97        collection index for this font, or 0 if the font is not in a collection.
98
99        Note: GetFileName does not assume that path is a null-terminated string,
100        so when it succeeds, it only copies the bytes of the file name and
101        nothing else (i.e. it copies exactly the number of bytes returned by the
102        function. If the caller wants to treat path[] as a C string, it must be
103        sure that it is allocated at least 1 byte larger than the returned size,
104        and it must copy in the terminating 0.
105
106        If the fontID does not correspond to a file, then the function returns
107        0, and the path and index parameters are ignored.
108
109        @param fontID   The font whose file name is being queried
110        @param path     Either NULL, or storage for receiving up to length bytes
111                        of the font's file name. Allocated by the caller.
112        @param length   The maximum space allocated in path (by the caller).
113                        Ignored if path is NULL.
114        @param index    Either NULL, or receives the TTC index for this font.
115                        If the font is not a TTC, then will be set to 0.
116        @return The byte length of th font's file name, or 0 if the font is not
117                baked by a file.
118     */
119    static size_t GetFileName(SkFontID fontID, char path[], size_t length,
120                              int32_t* index);
121
122    ///////////////////////////////////////////////////////////////////////////
123
124    /** Write a unique identifier to the stream, so that the same typeface can
125        be retrieved with Deserialize().
126    */
127    static void Serialize(const SkTypeface*, SkWStream*);
128
129    /** Given a stream created by Serialize(), return a new typeface (like
130        CreateTypeface) or return NULL if no match is found.
131     */
132    static SkTypeface* Deserialize(SkStream*);
133
134    ///////////////////////////////////////////////////////////////////////////
135
136    /** Return a subclass of SkScalarContext
137    */
138    static SkScalerContext* CreateScalerContext(const SkDescriptor* desc);
139
140    /**
141     *  Given a "current" fontID, return the next logical fontID to use
142     *  when searching fonts for a given unicode value. Typically the caller
143     *  will query a given font, and if a unicode value is not supported, they
144     *  will call this, and if 0 is not returned, will search that font, and so
145     *  on. This process must be finite, and when the fonthost sees a
146     *  font with no logical successor, it must return 0.
147     *
148     *  The original fontID is also provided. This is the initial font that was
149     *  stored in the typeface of the caller. It is provided as an aid to choose
150     *  the best next logical font. e.g. If the original font was bold or serif,
151     *  but the 2nd in the logical chain was plain, then a subsequent call to
152     *  get the 3rd can still inspect the original, and try to match its
153     *  stylistic attributes.
154     */
155    static SkFontID NextLogicalFont(SkFontID currFontID, SkFontID origFontID);
156
157#ifdef SK_BUILD_FOR_ANDROID
158    /*
159     * This Android-only version of NextLogicalFont allows us to pass in an
160     * entire Rec structure so that a caller can change fallback behavior
161     */
162    static SkFontID NextLogicalFont(const SkScalerContext::Rec& rec);
163#endif
164
165
166    ///////////////////////////////////////////////////////////////////////////
167
168    /** Given a filled-out rec, the fonthost may decide to modify it to reflect
169        what the host is actually capable of fulfilling. For example, if the
170        rec is requesting a level of hinting that, for this host, maps some
171        other level (e.g. kFull -> kNormal), it should update the rec to reflect
172        what will actually be done. This is an optimization so that the font
173        cache does not contain different recs (i.e. keys) that in reality map to
174        the same output.
175
176        A lazy (but valid) fonthost can do nothing in its FilterRec routine.
177     */
178    static void FilterRec(SkScalerContext::Rec* rec);
179
180    ///////////////////////////////////////////////////////////////////////////
181
182    /** Retrieve detailed typeface metrics.  Used by the PDF backend.
183        @param perGlyphInfo Indicate what glyph specific information (advances,
184                            names, etc.) should be populated.
185        @return The returned object has already been referenced.  NULL is
186                returned if the font is not found.
187        @param glyphIDs  For per-glyph info, specify subset of the font by
188                         giving glyph ids.  Each integer represents a glyph
189                         id.  Passing NULL means all glyphs in the font.
190        @param glyphIDsCount Number of elements in subsetGlyphIds. Ignored if
191                             glyphIDs is NULL.
192     */
193    static SkAdvancedTypefaceMetrics* GetAdvancedTypefaceMetrics(
194            SkFontID fontID,
195            SkAdvancedTypefaceMetrics::PerGlyphInfo perGlyphInfo,
196            const uint32_t* glyphIDs,
197            uint32_t glyphIDsCount);
198
199    /** Return the number of tables in the font
200     */
201    static int CountTables(SkFontID);
202
203    /** Copy into tags[] (allocated by the caller) the list of table tags in
204        the font, and return the number. This will be the same as CountTables()
205        or 0 if an error occured.
206     */
207    static int GetTableTags(SkFontID, SkFontTableTag[]);
208
209    /** Given a table tag, return the size of its contents, or 0 if not present
210     */
211    static size_t GetTableSize(SkFontID, SkFontTableTag);
212
213    /** Copy the contents of a table into data (allocated by the caller). Note
214        that the contents of the table will be in their native endian order
215        (which for most truetype tables is big endian). If the table tag is
216        not found, or there is an error copying the data, then 0 is returned.
217        If this happens, it is possible that some or all of the memory pointed
218        to by data may have been written to, even though an error has occured.
219
220        @param fontID the font to copy the table from
221        @param tag  The table tag whose contents are to be copied
222        @param offset The offset in bytes into the table's contents where the
223                copy should start from.
224        @param length The number of bytes, starting at offset, of table data
225                to copy.
226        @param data storage address where the table contents are copied to
227        @return the number of bytes actually copied into data. If offset+length
228                exceeds the table's size, then only the bytes up to the table's
229                size are actually copied, and this is the value returned. If
230                offset > the table's size, or tag is not a valid table,
231                then 0 is returned.
232     */
233    static size_t GetTableData(SkFontID fontID, SkFontTableTag tag,
234                               size_t offset, size_t length, void* data);
235
236    ///////////////////////////////////////////////////////////////////////////
237
238    /** DEPRECATED -- only called by SkFontHost_FreeType internally
239
240        Return NULL or a pointer to 256 bytes for the black (table[0]) and
241        white (table[1]) gamma tables.
242    */
243    static void GetGammaTables(const uint8_t* tables[2]);
244
245    ///////////////////////////////////////////////////////////////////////////
246
247    /** LCDs either have their color elements arranged horizontally or
248        vertically. When rendering subpixel glyphs we need to know which way
249        round they are.
250
251        Note, if you change this after startup, you'll need to flush the glyph
252        cache because it'll have the wrong type of masks cached.
253    */
254    enum LCDOrientation {
255        kHorizontal_LCDOrientation = 0,    //!< this is the default
256        kVertical_LCDOrientation   = 1,
257    };
258
259    static void SetSubpixelOrientation(LCDOrientation orientation);
260    static LCDOrientation GetSubpixelOrientation();
261
262    /** LCD color elements can vary in order. For subpixel text we need to know
263        the order which the LCDs uses so that the color fringes are in the
264        correct place.
265
266        Note, if you change this after startup, you'll need to flush the glyph
267        cache because it'll have the wrong type of masks cached.
268
269        kNONE_LCDOrder means that the subpixel elements are not spatially
270        separated in any usable fashion.
271     */
272    enum LCDOrder {
273        kRGB_LCDOrder = 0,    //!< this is the default
274        kBGR_LCDOrder = 1,
275        kNONE_LCDOrder = 2,
276    };
277
278    static void SetSubpixelOrder(LCDOrder order);
279    static LCDOrder GetSubpixelOrder();
280
281#ifdef SK_BUILD_FOR_ANDROID
282    ///////////////////////////////////////////////////////////////////////////
283
284    /**
285     * Return the number of font units per em.
286     *
287     * @param fontID the font to query.
288     * @return the number of font units per em or 0 on error.
289     */
290    static uint32_t GetUnitsPerEm(SkFontID fontID);
291#endif
292
293    /** If Skia is running in a constrained environment and the typeface
294        implementation is handle based, the typeface data may become
295        unavailable asynchronously. If a font host or scaler context method is
296        unable to access font data, it may call this function as a request to
297        make the handle contained in the typeface useable.
298    */
299    static void EnsureTypefaceAccessible(const SkTypeface& typeface);
300};
301
302#endif
303