1 /* -*- Mode: C++; tab-width: 20; indent-tabs-mode: nil; c-basic-offset: 4 -*-
2 * This Source Code Form is subject to the terms of the Mozilla Public
3 * License, v. 2.0. If a copy of the MPL was not distributed with this
4 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
5
6 #include "gfxFT2FontBase.h"
7 #include "gfxFT2Utils.h"
8 #include "mozilla/Likely.h"
9 #include FT_TRUETYPE_TAGS_H
10 #include FT_TRUETYPE_TABLES_H
11 #include <algorithm>
12
13 #ifdef HAVE_FONTCONFIG_FCFREETYPE_H
14 #include <fontconfig/fcfreetype.h>
15 #endif
16
17 #include "prlink.h"
18
19 // aScale is intended for a 16.16 x/y_scale of an FT_Size_Metrics
20 static inline FT_Long
ScaleRoundDesignUnits(FT_Short aDesignMetric,FT_Fixed aScale)21 ScaleRoundDesignUnits(FT_Short aDesignMetric, FT_Fixed aScale)
22 {
23 FT_Long fixed26dot6 = FT_MulFix(aDesignMetric, aScale);
24 return ROUND_26_6_TO_INT(fixed26dot6);
25 }
26
27 // Snap a line to pixels while keeping the center and size of the line as
28 // close to the original position as possible.
29 //
30 // Pango does similar snapping for underline and strikethrough when fonts are
31 // hinted, but nsCSSRendering::GetTextDecorationRectInternal always snaps the
32 // top and size of lines. Optimizing the distance between the line and
33 // baseline is probably good for the gap between text and underline, but
34 // optimizing the center of the line is better for positioning strikethough.
35 static void
SnapLineToPixels(gfxFloat & aOffset,gfxFloat & aSize)36 SnapLineToPixels(gfxFloat& aOffset, gfxFloat& aSize)
37 {
38 gfxFloat snappedSize = std::max(floor(aSize + 0.5), 1.0);
39 // Correct offset for change in size
40 gfxFloat offset = aOffset - 0.5 * (aSize - snappedSize);
41 // Snap offset
42 aOffset = floor(offset + 0.5);
43 aSize = snappedSize;
44 }
45
46 void
GetMetrics(gfxFont::Metrics * aMetrics,uint32_t * aSpaceGlyph)47 gfxFT2LockedFace::GetMetrics(gfxFont::Metrics* aMetrics,
48 uint32_t* aSpaceGlyph)
49 {
50 NS_PRECONDITION(aMetrics != nullptr, "aMetrics must not be NULL");
51 NS_PRECONDITION(aSpaceGlyph != nullptr, "aSpaceGlyph must not be NULL");
52
53 if (MOZ_UNLIKELY(!mFace)) {
54 // No face. This unfortunate situation might happen if the font
55 // file is (re)moved at the wrong time.
56 const gfxFloat emHeight = mGfxFont->GetStyle()->size;
57 aMetrics->emHeight = emHeight;
58 aMetrics->maxAscent = aMetrics->emAscent = 0.8 * emHeight;
59 aMetrics->maxDescent = aMetrics->emDescent = 0.2 * emHeight;
60 aMetrics->maxHeight = emHeight;
61 aMetrics->internalLeading = 0.0;
62 aMetrics->externalLeading = 0.2 * emHeight;
63 const gfxFloat spaceWidth = 0.5 * emHeight;
64 aMetrics->spaceWidth = spaceWidth;
65 aMetrics->maxAdvance = spaceWidth;
66 aMetrics->aveCharWidth = spaceWidth;
67 aMetrics->zeroOrAveCharWidth = spaceWidth;
68 const gfxFloat xHeight = 0.5 * emHeight;
69 aMetrics->xHeight = xHeight;
70 aMetrics->capHeight = aMetrics->maxAscent;
71 const gfxFloat underlineSize = emHeight / 14.0;
72 aMetrics->underlineSize = underlineSize;
73 aMetrics->underlineOffset = -underlineSize;
74 aMetrics->strikeoutOffset = 0.25 * emHeight;
75 aMetrics->strikeoutSize = underlineSize;
76
77 *aSpaceGlyph = 0;
78 return;
79 }
80
81 const FT_Size_Metrics& ftMetrics = mFace->size->metrics;
82
83 gfxFloat emHeight;
84 // Scale for vertical design metric conversion: pixels per design unit.
85 // If this remains at 0.0, we can't use metrics from OS/2 etc.
86 gfxFloat yScale = 0.0;
87 if (FT_IS_SCALABLE(mFace)) {
88 // Prefer FT_Size_Metrics::x_scale to x_ppem as x_ppem does not
89 // have subpixel accuracy.
90 //
91 // FT_Size_Metrics::y_scale is in 16.16 fixed point format. Its
92 // (fractional) value is a factor that converts vertical metrics from
93 // design units to units of 1/64 pixels, so that the result may be
94 // interpreted as pixels in 26.6 fixed point format.
95 yScale = FLOAT_FROM_26_6(FLOAT_FROM_16_16(ftMetrics.y_scale));
96 emHeight = mFace->units_per_EM * yScale;
97 } else { // Not scalable.
98 emHeight = ftMetrics.y_ppem;
99 // FT_Face doc says units_per_EM and a bunch of following fields
100 // are "only relevant to scalable outlines". If it's an sfnt,
101 // we can get units_per_EM from the 'head' table instead; otherwise,
102 // we don't have a unitsPerEm value so we can't compute/use yScale.
103 const TT_Header* head =
104 static_cast<TT_Header*>(FT_Get_Sfnt_Table(mFace, ft_sfnt_head));
105 if (head) {
106 gfxFloat emUnit = head->Units_Per_EM;
107 yScale = emHeight / emUnit;
108 }
109 }
110
111 TT_OS2 *os2 =
112 static_cast<TT_OS2*>(FT_Get_Sfnt_Table(mFace, ft_sfnt_os2));
113
114 aMetrics->maxAscent = FLOAT_FROM_26_6(ftMetrics.ascender);
115 aMetrics->maxDescent = -FLOAT_FROM_26_6(ftMetrics.descender);
116 aMetrics->maxAdvance = FLOAT_FROM_26_6(ftMetrics.max_advance);
117
118 gfxFloat lineHeight;
119 if (os2 && os2->sTypoAscender && yScale > 0.0) {
120 aMetrics->emAscent = os2->sTypoAscender * yScale;
121 aMetrics->emDescent = -os2->sTypoDescender * yScale;
122 FT_Short typoHeight =
123 os2->sTypoAscender - os2->sTypoDescender + os2->sTypoLineGap;
124 lineHeight = typoHeight * yScale;
125
126 // If the OS/2 fsSelection USE_TYPO_METRICS bit is set,
127 // set maxAscent/Descent from the sTypo* fields instead of hhea.
128 const uint16_t kUseTypoMetricsMask = 1 << 7;
129 if (os2->fsSelection & kUseTypoMetricsMask) {
130 aMetrics->maxAscent = NS_round(aMetrics->emAscent);
131 aMetrics->maxDescent = NS_round(aMetrics->emDescent);
132 } else {
133 // maxAscent/maxDescent get used for frame heights, and some fonts
134 // don't have the HHEA table ascent/descent set (bug 279032).
135 // We use NS_round here to parallel the pixel-rounded values that
136 // freetype gives us for ftMetrics.ascender/descender.
137 aMetrics->maxAscent =
138 std::max(aMetrics->maxAscent, NS_round(aMetrics->emAscent));
139 aMetrics->maxDescent =
140 std::max(aMetrics->maxDescent, NS_round(aMetrics->emDescent));
141 }
142 } else {
143 aMetrics->emAscent = aMetrics->maxAscent;
144 aMetrics->emDescent = aMetrics->maxDescent;
145 lineHeight = FLOAT_FROM_26_6(ftMetrics.height);
146 }
147
148 cairo_text_extents_t extents;
149 *aSpaceGlyph = GetCharExtents(' ', &extents);
150 if (*aSpaceGlyph) {
151 aMetrics->spaceWidth = extents.x_advance;
152 } else {
153 aMetrics->spaceWidth = aMetrics->maxAdvance; // guess
154 }
155
156 aMetrics->zeroOrAveCharWidth = 0.0;
157 if (GetCharExtents('0', &extents)) {
158 aMetrics->zeroOrAveCharWidth = extents.x_advance;
159 }
160
161 // Prefering a measured x over sxHeight because sxHeight doesn't consider
162 // hinting, but maybe the x extents are not quite right in some fancy
163 // script fonts. CSS 2.1 suggests possibly using the height of an "o",
164 // which would have a more consistent glyph across fonts.
165 if (GetCharExtents('x', &extents) && extents.y_bearing < 0.0) {
166 aMetrics->xHeight = -extents.y_bearing;
167 aMetrics->aveCharWidth = extents.x_advance;
168 } else {
169 if (os2 && os2->sxHeight && yScale > 0.0) {
170 aMetrics->xHeight = os2->sxHeight * yScale;
171 } else {
172 // CSS 2.1, section 4.3.2 Lengths: "In the cases where it is
173 // impossible or impractical to determine the x-height, a value of
174 // 0.5em should be used."
175 aMetrics->xHeight = 0.5 * emHeight;
176 }
177 aMetrics->aveCharWidth = 0.0; // updated below
178 }
179
180 if (GetCharExtents('H', &extents) && extents.y_bearing < 0.0) {
181 aMetrics->capHeight = -extents.y_bearing;
182 } else {
183 if (os2 && os2->sCapHeight && yScale > 0.0) {
184 aMetrics->capHeight = os2->sCapHeight * yScale;
185 } else {
186 aMetrics->capHeight = aMetrics->maxAscent;
187 }
188 }
189
190 // aveCharWidth is used for the width of text input elements so be
191 // liberal rather than conservative in the estimate.
192 if (os2 && os2->xAvgCharWidth) {
193 // Round to pixels as this is compared with maxAdvance to guess
194 // whether this is a fixed width font.
195 gfxFloat avgCharWidth =
196 ScaleRoundDesignUnits(os2->xAvgCharWidth, ftMetrics.x_scale);
197 aMetrics->aveCharWidth =
198 std::max(aMetrics->aveCharWidth, avgCharWidth);
199 }
200 aMetrics->aveCharWidth =
201 std::max(aMetrics->aveCharWidth, aMetrics->zeroOrAveCharWidth);
202 if (aMetrics->aveCharWidth == 0.0) {
203 aMetrics->aveCharWidth = aMetrics->spaceWidth;
204 }
205 if (aMetrics->zeroOrAveCharWidth == 0.0) {
206 aMetrics->zeroOrAveCharWidth = aMetrics->aveCharWidth;
207 }
208 // Apparently hinting can mean that max_advance is not always accurate.
209 aMetrics->maxAdvance =
210 std::max(aMetrics->maxAdvance, aMetrics->aveCharWidth);
211
212 // gfxFont::Metrics::underlineOffset is the position of the top of the
213 // underline.
214 //
215 // FT_FaceRec documentation describes underline_position as "the
216 // center of the underlining stem". This was the original definition
217 // of the PostScript metric, but in the PostScript table of OpenType
218 // fonts the metric is "the top of the underline"
219 // (http://www.microsoft.com/typography/otspec/post.htm), and FreeType
220 // (up to version 2.3.7) doesn't make any adjustment.
221 //
222 // Therefore get the underline position directly from the table
223 // ourselves when this table exists. Use FreeType's metrics for
224 // other (including older PostScript) fonts.
225 if (mFace->underline_position && mFace->underline_thickness && yScale > 0.0) {
226 aMetrics->underlineSize = mFace->underline_thickness * yScale;
227 TT_Postscript *post = static_cast<TT_Postscript*>
228 (FT_Get_Sfnt_Table(mFace, ft_sfnt_post));
229 if (post && post->underlinePosition) {
230 aMetrics->underlineOffset = post->underlinePosition * yScale;
231 } else {
232 aMetrics->underlineOffset = mFace->underline_position * yScale
233 + 0.5 * aMetrics->underlineSize;
234 }
235 } else { // No underline info.
236 // Imitate Pango.
237 aMetrics->underlineSize = emHeight / 14.0;
238 aMetrics->underlineOffset = -aMetrics->underlineSize;
239 }
240
241 if (os2 && os2->yStrikeoutSize && os2->yStrikeoutPosition && yScale > 0.0) {
242 aMetrics->strikeoutSize = os2->yStrikeoutSize * yScale;
243 aMetrics->strikeoutOffset = os2->yStrikeoutPosition * yScale;
244 } else { // No strikeout info.
245 aMetrics->strikeoutSize = aMetrics->underlineSize;
246 // Use OpenType spec's suggested position for Roman font.
247 aMetrics->strikeoutOffset = emHeight * 409.0 / 2048.0
248 + 0.5 * aMetrics->strikeoutSize;
249 }
250 SnapLineToPixels(aMetrics->strikeoutOffset, aMetrics->strikeoutSize);
251
252 aMetrics->maxHeight = aMetrics->maxAscent + aMetrics->maxDescent;
253
254 // Make the line height an integer number of pixels so that lines will be
255 // equally spaced (rather than just being snapped to pixels, some up and
256 // some down). Layout calculates line height from the emHeight +
257 // internalLeading + externalLeading, but first each of these is rounded
258 // to layout units. To ensure that the result is an integer number of
259 // pixels, round each of the components to pixels.
260 aMetrics->emHeight = floor(emHeight + 0.5);
261
262 // maxHeight will normally be an integer, but round anyway in case
263 // FreeType is configured differently.
264 aMetrics->internalLeading =
265 floor(aMetrics->maxHeight - aMetrics->emHeight + 0.5);
266
267 // Text input boxes currently don't work well with lineHeight
268 // significantly less than maxHeight (with Verdana, for example).
269 lineHeight = floor(std::max(lineHeight, aMetrics->maxHeight) + 0.5);
270 aMetrics->externalLeading =
271 lineHeight - aMetrics->internalLeading - aMetrics->emHeight;
272
273 // Ensure emAscent + emDescent == emHeight
274 gfxFloat sum = aMetrics->emAscent + aMetrics->emDescent;
275 aMetrics->emAscent = sum > 0.0 ?
276 aMetrics->emAscent * aMetrics->emHeight / sum : 0.0;
277 aMetrics->emDescent = aMetrics->emHeight - aMetrics->emAscent;
278 }
279
280 uint32_t
GetGlyph(uint32_t aCharCode)281 gfxFT2LockedFace::GetGlyph(uint32_t aCharCode)
282 {
283 if (MOZ_UNLIKELY(!mFace))
284 return 0;
285
286 #ifdef HAVE_FONTCONFIG_FCFREETYPE_H
287 // FcFreeTypeCharIndex will search starting from the most recently
288 // selected charmap. This can cause non-determistic behavior when more
289 // than one charmap supports a character but with different glyphs, as
290 // with older versions of MS Gothic, for example. Always prefer a Unicode
291 // charmap, if there is one. (FcFreeTypeCharIndex usually does the
292 // appropriate Unicode conversion, but some fonts have non-Roman glyphs
293 // for FT_ENCODING_APPLE_ROMAN characters.)
294 if (!mFace->charmap || mFace->charmap->encoding != FT_ENCODING_UNICODE) {
295 FT_Select_Charmap(mFace, FT_ENCODING_UNICODE);
296 }
297
298 return FcFreeTypeCharIndex(mFace, aCharCode);
299 #else
300 return FT_Get_Char_Index(mFace, aCharCode);
301 #endif
302 }
303
304 typedef FT_UInt (*GetCharVariantFunction)(FT_Face face,
305 FT_ULong charcode,
306 FT_ULong variantSelector);
307
308 uint32_t
GetUVSGlyph(uint32_t aCharCode,uint32_t aVariantSelector)309 gfxFT2LockedFace::GetUVSGlyph(uint32_t aCharCode, uint32_t aVariantSelector)
310 {
311 NS_PRECONDITION(aVariantSelector, "aVariantSelector should not be NULL");
312
313 if (MOZ_UNLIKELY(!mFace))
314 return 0;
315
316 // This function is available from FreeType 2.3.6 (June 2008).
317 static CharVariantFunction sGetCharVariantPtr = FindCharVariantFunction();
318 if (!sGetCharVariantPtr)
319 return 0;
320
321 #ifdef HAVE_FONTCONFIG_FCFREETYPE_H
322 // FcFreeTypeCharIndex may have changed the selected charmap.
323 // FT_Face_GetCharVariantIndex needs a unicode charmap.
324 if (!mFace->charmap || mFace->charmap->encoding != FT_ENCODING_UNICODE) {
325 FT_Select_Charmap(mFace, FT_ENCODING_UNICODE);
326 }
327 #endif
328
329 return (*sGetCharVariantPtr)(mFace, aCharCode, aVariantSelector);
330 }
331
332 uint32_t
GetCharExtents(char aChar,cairo_text_extents_t * aExtents)333 gfxFT2LockedFace::GetCharExtents(char aChar, cairo_text_extents_t* aExtents)
334 {
335 NS_PRECONDITION(aExtents != nullptr, "aExtents must not be NULL");
336
337 if (!mFace)
338 return 0;
339
340 FT_UInt gid = mGfxFont->GetGlyph(aChar);
341 if (gid) {
342 mGfxFont->GetGlyphExtents(gid, aExtents);
343 }
344
345 return gid;
346 }
347
348 gfxFT2LockedFace::CharVariantFunction
FindCharVariantFunction()349 gfxFT2LockedFace::FindCharVariantFunction()
350 {
351 // This function is available from FreeType 2.3.6 (June 2008).
352 PRLibrary *lib = nullptr;
353 CharVariantFunction function =
354 reinterpret_cast<CharVariantFunction>
355 (PR_FindFunctionSymbolAndLibrary("FT_Face_GetCharVariantIndex", &lib));
356 if (!lib) {
357 return nullptr;
358 }
359
360 FT_Int major;
361 FT_Int minor;
362 FT_Int patch;
363 FT_Library_Version(mFace->glyph->library, &major, &minor, &patch);
364
365 // Versions 2.4.0 to 2.4.3 crash if configured with
366 // FT_CONFIG_OPTION_OLD_INTERNALS. Presence of the symbol FT_Alloc
367 // indicates FT_CONFIG_OPTION_OLD_INTERNALS.
368 if (major == 2 && minor == 4 && patch < 4 &&
369 PR_FindFunctionSymbol(lib, "FT_Alloc")) {
370 function = nullptr;
371 }
372
373 // Decrement the reference count incremented in
374 // PR_FindFunctionSymbolAndLibrary.
375 PR_UnloadLibrary(lib);
376
377 return function;
378 }
379