1 /* -*- Mode: C++; tab-width: 20; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
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/. */
6 #include "mozilla/ArrayUtils.h"
7 #include "mozilla/BinarySearch.h"
9 #include "gfxFontUtils.h"
10 #include "gfxFontEntry.h"
11 #include "gfxFontVariations.h"
14 #include "nsServiceManagerUtils.h"
16 #include "mozilla/Preferences.h"
17 #include "mozilla/BinarySearch.h"
18 #include "mozilla/Sprintf.h"
19 #include "mozilla/Unused.h"
22 #include "nsIUUIDGenerator.h"
23 #include "mozilla/Encoding.h"
25 #include "harfbuzz/hb.h"
28 #include "mozilla/Logging.h"
31 # include <CoreFoundation/CoreFoundation.h>
34 #define LOG(log, args) MOZ_LOG(gfxPlatform::GetLog(log), LogLevel::Debug, args)
36 #define UNICODE_BMP_LIMIT 0x10000
38 using namespace mozilla
;
43 AutoSwap_PRUint16 format
;
44 AutoSwap_PRUint16 reserved
;
45 AutoSwap_PRUint32 length
;
46 AutoSwap_PRUint32 language
;
47 AutoSwap_PRUint32 startCharCode
;
48 AutoSwap_PRUint32 numChars
;
52 AutoSwap_PRUint16 format
;
53 AutoSwap_PRUint16 reserved
;
54 AutoSwap_PRUint32 length
;
55 AutoSwap_PRUint32 language
;
56 AutoSwap_PRUint32 numGroups
;
60 AutoSwap_PRUint32 startCharCode
;
61 AutoSwap_PRUint32 endCharCode
;
62 AutoSwap_PRUint32 startGlyphId
;
67 void gfxSparseBitSet::Dump(const char* aPrefix
, eGfxLog aWhichLog
) const {
68 uint32_t numBlocks
= mBlockIndex
.Length();
70 for (uint32_t b
= 0; b
< numBlocks
; b
++) {
71 if (mBlockIndex
[b
] == NO_BLOCK
) {
74 const Block
* block
= &mBlocks
[mBlockIndex
[b
]];
75 const int BUFSIZE
= 256;
78 index
+= snprintf(&outStr
[index
], BUFSIZE
- index
, "%s u+%6.6x [", aPrefix
,
79 (b
* BLOCK_SIZE_BITS
));
80 for (int i
= 0; i
< 32; i
+= 4) {
81 for (int j
= i
; j
< i
+ 4; j
++) {
82 uint8_t bits
= block
->mBits
[j
];
83 uint8_t flip1
= ((bits
& 0xaa) >> 1) | ((bits
& 0x55) << 1);
84 uint8_t flip2
= ((flip1
& 0xcc) >> 2) | ((flip1
& 0x33) << 2);
85 uint8_t flipped
= ((flip2
& 0xf0) >> 4) | ((flip2
& 0x0f) << 4);
87 index
+= snprintf(&outStr
[index
], BUFSIZE
- index
, "%2.2x", flipped
);
89 if (i
+ 4 != 32) index
+= snprintf(&outStr
[index
], BUFSIZE
- index
, " ");
91 Unused
<< snprintf(&outStr
[index
], BUFSIZE
- index
, "]");
92 LOG(aWhichLog
, ("%s", outStr
));
96 nsresult
gfxFontUtils::ReadCMAPTableFormat10(const uint8_t* aBuf
,
98 gfxSparseBitSet
& aCharacterMap
) {
99 // Ensure table is large enough that we can safely read the header
100 NS_ENSURE_TRUE(aLength
>= sizeof(Format10CmapHeader
),
101 NS_ERROR_GFX_CMAP_MALFORMED
);
103 // Sanity-check header fields
104 const Format10CmapHeader
* cmap10
=
105 reinterpret_cast<const Format10CmapHeader
*>(aBuf
);
106 NS_ENSURE_TRUE(uint16_t(cmap10
->format
) == 10, NS_ERROR_GFX_CMAP_MALFORMED
);
107 NS_ENSURE_TRUE(uint16_t(cmap10
->reserved
) == 0, NS_ERROR_GFX_CMAP_MALFORMED
);
109 uint32_t tablelen
= cmap10
->length
;
110 NS_ENSURE_TRUE(tablelen
>= sizeof(Format10CmapHeader
) && tablelen
<= aLength
,
111 NS_ERROR_GFX_CMAP_MALFORMED
);
113 NS_ENSURE_TRUE(cmap10
->language
== 0, NS_ERROR_GFX_CMAP_MALFORMED
);
115 uint32_t numChars
= cmap10
->numChars
;
117 tablelen
== sizeof(Format10CmapHeader
) + numChars
* sizeof(uint16_t),
118 NS_ERROR_GFX_CMAP_MALFORMED
);
120 uint32_t charCode
= cmap10
->startCharCode
;
121 NS_ENSURE_TRUE(charCode
<= CMAP_MAX_CODEPOINT
&&
122 charCode
+ numChars
<= CMAP_MAX_CODEPOINT
,
123 NS_ERROR_GFX_CMAP_MALFORMED
);
125 // glyphs[] array immediately follows the subtable header
126 const AutoSwap_PRUint16
* glyphs
=
127 reinterpret_cast<const AutoSwap_PRUint16
*>(cmap10
+ 1);
129 for (uint32_t i
= 0; i
< numChars
; ++i
) {
130 if (uint16_t(*glyphs
) != 0) {
131 aCharacterMap
.set(charCode
);
137 aCharacterMap
.Compact();
142 nsresult
gfxFontUtils::ReadCMAPTableFormat12or13(
143 const uint8_t* aBuf
, uint32_t aLength
, gfxSparseBitSet
& aCharacterMap
) {
144 // Format 13 has the same structure as format 12, the only difference is
145 // the interpretation of the glyphID field. So we can share the code here
146 // that reads the table and just records character coverage.
148 // Ensure table is large enough that we can safely read the header
149 NS_ENSURE_TRUE(aLength
>= sizeof(Format12CmapHeader
),
150 NS_ERROR_GFX_CMAP_MALFORMED
);
152 // Sanity-check header fields
153 const Format12CmapHeader
* cmap12
=
154 reinterpret_cast<const Format12CmapHeader
*>(aBuf
);
156 uint16_t(cmap12
->format
) == 12 || uint16_t(cmap12
->format
) == 13,
157 NS_ERROR_GFX_CMAP_MALFORMED
);
158 NS_ENSURE_TRUE(uint16_t(cmap12
->reserved
) == 0, NS_ERROR_GFX_CMAP_MALFORMED
);
160 uint32_t tablelen
= cmap12
->length
;
161 NS_ENSURE_TRUE(tablelen
>= sizeof(Format12CmapHeader
) && tablelen
<= aLength
,
162 NS_ERROR_GFX_CMAP_MALFORMED
);
164 NS_ENSURE_TRUE(cmap12
->language
== 0, NS_ERROR_GFX_CMAP_MALFORMED
);
166 // Check that the table is large enough for the group array
167 const uint32_t numGroups
= cmap12
->numGroups
;
169 (tablelen
- sizeof(Format12CmapHeader
)) / sizeof(Format12Group
) >=
171 NS_ERROR_GFX_CMAP_MALFORMED
);
173 // The array of groups immediately follows the subtable header.
174 const Format12Group
* group
=
175 reinterpret_cast<const Format12Group
*>(aBuf
+ sizeof(Format12CmapHeader
));
177 // Check that groups are in correct order and do not overlap,
178 // and record character coverage in aCharacterMap.
179 uint32_t prevEndCharCode
= 0;
180 for (uint32_t i
= 0; i
< numGroups
; i
++, group
++) {
181 uint32_t startCharCode
= group
->startCharCode
;
182 const uint32_t endCharCode
= group
->endCharCode
;
183 NS_ENSURE_TRUE((prevEndCharCode
< startCharCode
|| i
== 0) &&
184 startCharCode
<= endCharCode
&&
185 endCharCode
<= CMAP_MAX_CODEPOINT
,
186 NS_ERROR_GFX_CMAP_MALFORMED
);
187 // don't include a character that maps to glyph ID 0 (.notdef)
188 if (group
->startGlyphId
== 0) {
191 if (startCharCode
<= endCharCode
) {
192 aCharacterMap
.SetRange(startCharCode
, endCharCode
);
194 prevEndCharCode
= endCharCode
;
197 aCharacterMap
.Compact();
202 nsresult
gfxFontUtils::ReadCMAPTableFormat4(const uint8_t* aBuf
,
204 gfxSparseBitSet
& aCharacterMap
) {
212 NS_ENSURE_TRUE(ReadShortAt(aBuf
, OffsetFormat
) == 4,
213 NS_ERROR_GFX_CMAP_MALFORMED
);
214 uint16_t tablelen
= ReadShortAt(aBuf
, OffsetLength
);
215 NS_ENSURE_TRUE(tablelen
<= aLength
, NS_ERROR_GFX_CMAP_MALFORMED
);
216 NS_ENSURE_TRUE(tablelen
> 16, NS_ERROR_GFX_CMAP_MALFORMED
);
218 // This field should normally (except for Mac platform subtables) be zero
219 // according to the OT spec, but some buggy fonts have lang = 1 (which would
220 // be English for MacOS). E.g. Arial Narrow Bold, v. 1.1 (Tiger), Arial
221 // Unicode MS (see bug 530614). So accept either zero or one here; the error
222 // should be harmless.
223 NS_ENSURE_TRUE((ReadShortAt(aBuf
, OffsetLanguage
) & 0xfffe) == 0,
224 NS_ERROR_GFX_CMAP_MALFORMED
);
226 uint16_t segCountX2
= ReadShortAt(aBuf
, OffsetSegCountX2
);
227 NS_ENSURE_TRUE(tablelen
>= 16 + (segCountX2
* 4),
228 NS_ERROR_GFX_CMAP_MALFORMED
);
230 const uint16_t segCount
= segCountX2
/ 2;
232 const uint16_t* endCounts
= reinterpret_cast<const uint16_t*>(aBuf
+ 14);
233 const uint16_t* startCounts
=
234 endCounts
+ 1 /* skip one uint16_t for reservedPad */ + segCount
;
235 const uint16_t* idDeltas
= startCounts
+ segCount
;
236 const uint16_t* idRangeOffsets
= idDeltas
+ segCount
;
237 uint16_t prevEndCount
= 0;
238 for (uint16_t i
= 0; i
< segCount
; i
++) {
239 const uint16_t endCount
= ReadShortAt16(endCounts
, i
);
240 const uint16_t startCount
= ReadShortAt16(startCounts
, i
);
241 const uint16_t idRangeOffset
= ReadShortAt16(idRangeOffsets
, i
);
243 // sanity-check range
244 // This permits ranges to overlap by 1 character, which is strictly
245 // incorrect but occurs in Baskerville on OS X 10.7 (see bug 689087),
246 // and appears to be harmless in practice
247 NS_ENSURE_TRUE(startCount
>= prevEndCount
&& startCount
<= endCount
,
248 NS_ERROR_GFX_CMAP_MALFORMED
);
249 prevEndCount
= endCount
;
251 if (idRangeOffset
== 0) {
252 // figure out if there's a code in the range that would map to
253 // glyph ID 0 (.notdef); if so, we need to skip setting that
254 // character code in the map
255 const uint16_t skipCode
= 65536 - ReadShortAt16(idDeltas
, i
);
256 if (startCount
< skipCode
) {
257 aCharacterMap
.SetRange(startCount
,
258 std::min
<uint16_t>(skipCode
- 1, endCount
));
260 if (skipCode
< endCount
) {
261 aCharacterMap
.SetRange(std::max
<uint16_t>(startCount
, skipCode
+ 1),
265 // Unused: self-documenting.
266 // const uint16_t idDelta = ReadShortAt16(idDeltas, i);
267 for (uint32_t c
= startCount
; c
<= endCount
; ++c
) {
268 if (c
== 0xFFFF) break;
270 const uint16_t* gdata
=
271 (idRangeOffset
/ 2 + (c
- startCount
) + &idRangeOffsets
[i
]);
274 (uint8_t*)gdata
> aBuf
&& (uint8_t*)gdata
< aBuf
+ aLength
,
275 NS_ERROR_GFX_CMAP_MALFORMED
);
277 // make sure we have a glyph
279 // The glyph index at this point is:
280 uint16_t glyph
= ReadShortAt16(idDeltas
, i
) + *gdata
;
282 aCharacterMap
.set(c
);
289 aCharacterMap
.Compact();
294 nsresult
gfxFontUtils::ReadCMAPTableFormat14(const uint8_t* aBuf
,
296 UniquePtr
<uint8_t[]>& aTable
) {
299 OffsetTableLength
= 2,
300 OffsetNumVarSelectorRecords
= 6,
301 OffsetVarSelectorRecords
= 10,
303 SizeOfVarSelectorRecord
= 11,
304 VSRecOffsetVarSelector
= 0,
305 VSRecOffsetDefUVSOffset
= 3,
306 VSRecOffsetNonDefUVSOffset
= 7,
308 SizeOfDefUVSTable
= 4,
309 DefUVSOffsetStartUnicodeValue
= 0,
310 DefUVSOffsetAdditionalCount
= 3,
312 SizeOfNonDefUVSTable
= 5,
313 NonDefUVSOffsetUnicodeValue
= 0,
314 NonDefUVSOffsetGlyphID
= 3
316 NS_ENSURE_TRUE(aLength
>= OffsetVarSelectorRecords
,
317 NS_ERROR_GFX_CMAP_MALFORMED
);
319 NS_ENSURE_TRUE(ReadShortAt(aBuf
, OffsetFormat
) == 14,
320 NS_ERROR_GFX_CMAP_MALFORMED
);
322 uint32_t tablelen
= ReadLongAt(aBuf
, OffsetTableLength
);
323 NS_ENSURE_TRUE(tablelen
<= aLength
, NS_ERROR_GFX_CMAP_MALFORMED
);
324 NS_ENSURE_TRUE(tablelen
>= OffsetVarSelectorRecords
,
325 NS_ERROR_GFX_CMAP_MALFORMED
);
327 const uint32_t numVarSelectorRecords
=
328 ReadLongAt(aBuf
, OffsetNumVarSelectorRecords
);
330 (tablelen
- OffsetVarSelectorRecords
) / SizeOfVarSelectorRecord
>=
331 numVarSelectorRecords
,
332 NS_ERROR_GFX_CMAP_MALFORMED
);
334 const uint8_t* records
= aBuf
+ OffsetVarSelectorRecords
;
335 for (uint32_t i
= 0; i
< numVarSelectorRecords
;
336 i
++, records
+= SizeOfVarSelectorRecord
) {
337 const uint32_t varSelector
= ReadUint24At(records
, VSRecOffsetVarSelector
);
338 const uint32_t defUVSOffset
= ReadLongAt(records
, VSRecOffsetDefUVSOffset
);
339 const uint32_t nonDefUVSOffset
=
340 ReadLongAt(records
, VSRecOffsetNonDefUVSOffset
);
341 NS_ENSURE_TRUE(varSelector
<= CMAP_MAX_CODEPOINT
&&
342 defUVSOffset
<= tablelen
- 4 &&
343 nonDefUVSOffset
<= tablelen
- 4,
344 NS_ERROR_GFX_CMAP_MALFORMED
);
347 const uint32_t numUnicodeValueRanges
= ReadLongAt(aBuf
, defUVSOffset
);
348 NS_ENSURE_TRUE((tablelen
- defUVSOffset
) / SizeOfDefUVSTable
>=
349 numUnicodeValueRanges
,
350 NS_ERROR_GFX_CMAP_MALFORMED
);
351 const uint8_t* tables
= aBuf
+ defUVSOffset
+ 4;
352 uint32_t prevEndUnicode
= 0;
353 for (uint32_t j
= 0; j
< numUnicodeValueRanges
;
354 j
++, tables
+= SizeOfDefUVSTable
) {
355 const uint32_t startUnicode
=
356 ReadUint24At(tables
, DefUVSOffsetStartUnicodeValue
);
357 const uint32_t endUnicode
=
358 startUnicode
+ tables
[DefUVSOffsetAdditionalCount
];
359 NS_ENSURE_TRUE((prevEndUnicode
< startUnicode
|| j
== 0) &&
360 endUnicode
<= CMAP_MAX_CODEPOINT
,
361 NS_ERROR_GFX_CMAP_MALFORMED
);
362 prevEndUnicode
= endUnicode
;
366 if (nonDefUVSOffset
) {
367 const uint32_t numUVSMappings
= ReadLongAt(aBuf
, nonDefUVSOffset
);
369 (tablelen
- nonDefUVSOffset
) / SizeOfNonDefUVSTable
>= numUVSMappings
,
370 NS_ERROR_GFX_CMAP_MALFORMED
);
371 const uint8_t* tables
= aBuf
+ nonDefUVSOffset
+ 4;
372 uint32_t prevUnicode
= 0;
373 for (uint32_t j
= 0; j
< numUVSMappings
;
374 j
++, tables
+= SizeOfNonDefUVSTable
) {
375 const uint32_t unicodeValue
=
376 ReadUint24At(tables
, NonDefUVSOffsetUnicodeValue
);
377 NS_ENSURE_TRUE((prevUnicode
< unicodeValue
|| j
== 0) &&
378 unicodeValue
<= CMAP_MAX_CODEPOINT
,
379 NS_ERROR_GFX_CMAP_MALFORMED
);
380 prevUnicode
= unicodeValue
;
385 aTable
= MakeUnique
<uint8_t[]>(tablelen
);
386 memcpy(aTable
.get(), aBuf
, tablelen
);
391 // For fonts with two format-4 tables, the first one (Unicode platform) is
392 // preferred on the Mac; on other platforms we allow the Microsoft-platform
393 // subtable to replace it.
395 #if defined(XP_MACOSX)
396 # define acceptableFormat4(p, e, k) \
397 (((p) == PLATFORM_ID_MICROSOFT && (e) == EncodingIDMicrosoft && !(k)) || \
398 ((p) == PLATFORM_ID_UNICODE))
400 # define acceptableUCS4Encoding(p, e, k) \
401 (((p) == PLATFORM_ID_MICROSOFT && \
402 (e) == EncodingIDUCS4ForMicrosoftPlatform) && \
404 ((p) == PLATFORM_ID_UNICODE && ((e) != EncodingIDUVSForUnicodePlatform)))
406 # define acceptableFormat4(p, e, k) \
407 (((p) == PLATFORM_ID_MICROSOFT && (e) == EncodingIDMicrosoft) || \
408 ((p) == PLATFORM_ID_UNICODE))
410 # define acceptableUCS4Encoding(p, e, k) \
411 ((p) == PLATFORM_ID_MICROSOFT && (e) == EncodingIDUCS4ForMicrosoftPlatform)
414 #define acceptablePlatform(p) \
415 ((p) == PLATFORM_ID_UNICODE || (p) == PLATFORM_ID_MICROSOFT)
416 #define isSymbol(p, e) ((p) == PLATFORM_ID_MICROSOFT && (e) == EncodingIDSymbol)
417 #define isUVSEncoding(p, e) \
418 ((p) == PLATFORM_ID_UNICODE && (e) == EncodingIDUVSForUnicodePlatform)
420 uint32_t gfxFontUtils::FindPreferredSubtable(const uint8_t* aBuf
,
422 uint32_t* aTableOffset
,
423 uint32_t* aUVSTableOffset
) {
429 TableOffsetPlatformID
= 0,
430 TableOffsetEncodingID
= 2,
431 TableOffsetOffset
= 4,
434 SubtableOffsetFormat
= 0
437 EncodingIDSymbol
= 0,
438 EncodingIDMicrosoft
= 1,
439 EncodingIDDefaultForUnicodePlatform
= 0,
440 EncodingIDUCS4ForUnicodePlatform
= 3,
441 EncodingIDUVSForUnicodePlatform
= 5,
442 EncodingIDUCS4ForMicrosoftPlatform
= 10
445 if (aUVSTableOffset
) {
446 *aUVSTableOffset
= 0;
449 if (!aBuf
|| aBufLength
< SizeOfHeader
) {
450 // cmap table is missing, or too small to contain header fields!
454 // uint16_t version = ReadShortAt(aBuf, OffsetVersion); // Unused:
456 uint16_t numTables
= ReadShortAt(aBuf
, OffsetNumTables
);
457 if (aBufLength
< uint32_t(SizeOfHeader
+ numTables
* SizeOfTable
)) {
461 // save the format we want here
462 uint32_t keepFormat
= 0;
464 const uint8_t* table
= aBuf
+ SizeOfHeader
;
465 for (uint16_t i
= 0; i
< numTables
; ++i
, table
+= SizeOfTable
) {
466 const uint16_t platformID
= ReadShortAt(table
, TableOffsetPlatformID
);
467 if (!acceptablePlatform(platformID
)) continue;
469 const uint16_t encodingID
= ReadShortAt(table
, TableOffsetEncodingID
);
470 const uint32_t offset
= ReadLongAt(table
, TableOffsetOffset
);
471 if (aBufLength
- 2 < offset
) {
472 // this subtable is not valid - beyond end of buffer
476 const uint8_t* subtable
= aBuf
+ offset
;
477 const uint16_t format
= ReadShortAt(subtable
, SubtableOffsetFormat
);
479 if (isSymbol(platformID
, encodingID
)) {
481 *aTableOffset
= offset
;
483 } else if (format
== 4 &&
484 acceptableFormat4(platformID
, encodingID
, keepFormat
)) {
486 *aTableOffset
= offset
;
487 } else if ((format
== 10 || format
== 12 || format
== 13) &&
488 acceptableUCS4Encoding(platformID
, encodingID
, keepFormat
)) {
490 *aTableOffset
= offset
;
491 if (platformID
> PLATFORM_ID_UNICODE
|| !aUVSTableOffset
||
493 break; // we don't want to try anything else when this format is
496 } else if (format
== 14 && isUVSEncoding(platformID
, encodingID
) &&
498 *aUVSTableOffset
= offset
;
499 if (keepFormat
== 10 || keepFormat
== 12) {
508 nsresult
gfxFontUtils::ReadCMAP(const uint8_t* aBuf
, uint32_t aBufLength
,
509 gfxSparseBitSet
& aCharacterMap
,
510 uint32_t& aUVSOffset
) {
513 FindPreferredSubtable(aBuf
, aBufLength
, &offset
, &aUVSOffset
);
517 return ReadCMAPTableFormat4(aBuf
+ offset
, aBufLength
- offset
,
521 return ReadCMAPTableFormat10(aBuf
+ offset
, aBufLength
- offset
,
526 return ReadCMAPTableFormat12or13(aBuf
+ offset
, aBufLength
- offset
,
533 return NS_ERROR_FAILURE
;
539 AutoSwap_PRUint16 format
;
540 AutoSwap_PRUint16 length
;
541 AutoSwap_PRUint16 language
;
542 AutoSwap_PRUint16 segCountX2
;
543 AutoSwap_PRUint16 searchRange
;
544 AutoSwap_PRUint16 entrySelector
;
545 AutoSwap_PRUint16 rangeShift
;
547 AutoSwap_PRUint16 arrays
[1];
550 typedef struct Format14Cmap
{
551 AutoSwap_PRUint16 format
;
552 AutoSwap_PRUint32 length
;
553 AutoSwap_PRUint32 numVarSelectorRecords
;
556 AutoSwap_PRUint24 varSelector
;
557 AutoSwap_PRUint32 defaultUVSOffset
;
558 AutoSwap_PRUint32 nonDefaultUVSOffset
;
561 VarSelectorRecord varSelectorRecords
[1];
564 typedef struct NonDefUVSTable
{
565 AutoSwap_PRUint32 numUVSMappings
;
568 AutoSwap_PRUint24 unicodeValue
;
569 AutoSwap_PRUint16 glyphID
;
572 UVSMapping uvsMappings
[1];
577 uint32_t gfxFontUtils::MapCharToGlyphFormat4(const uint8_t* aBuf
,
578 uint32_t aLength
, char16_t aCh
) {
579 const Format4Cmap
* cmap4
= reinterpret_cast<const Format4Cmap
*>(aBuf
);
581 uint16_t segCount
= (uint16_t)(cmap4
->segCountX2
) / 2;
583 const AutoSwap_PRUint16
* endCodes
= &cmap4
->arrays
[0];
584 const AutoSwap_PRUint16
* startCodes
= &cmap4
->arrays
[segCount
+ 1];
585 const AutoSwap_PRUint16
* idDelta
= &startCodes
[segCount
];
586 const AutoSwap_PRUint16
* idRangeOffset
= &idDelta
[segCount
];
588 // Sanity-check that the fixed-size arrays don't exceed the buffer.
589 const uint8_t* const limit
= aBuf
+ aLength
;
590 if ((const uint8_t*)(&idRangeOffset
[segCount
]) > limit
) {
591 return 0; // broken font, just bail out safely
594 // For most efficient binary search, we want to work on a range of segment
595 // indexes that is a power of 2 so that we can always halve it by shifting.
596 // So we find the largest power of 2 that is <= segCount.
597 // We will offset this range by segOffset so as to reach the end
598 // of the table, provided that doesn't put us beyond the target
599 // value from the outset.
600 uint32_t powerOf2
= mozilla::FindHighestBit(segCount
);
601 uint32_t segOffset
= segCount
- powerOf2
;
604 if (uint16_t(startCodes
[segOffset
]) <= aCh
) {
608 // Repeatedly halve the size of the range until we find the target group
609 while (powerOf2
> 1) {
611 if (uint16_t(startCodes
[idx
+ powerOf2
]) <= aCh
) {
616 if (aCh
>= uint16_t(startCodes
[idx
]) && aCh
<= uint16_t(endCodes
[idx
])) {
618 if (uint16_t(idRangeOffset
[idx
]) == 0) {
621 uint16_t offset
= aCh
- uint16_t(startCodes
[idx
]);
622 const AutoSwap_PRUint16
* glyphIndexTable
=
623 (const AutoSwap_PRUint16
*)((const char*)&idRangeOffset
[idx
] +
624 uint16_t(idRangeOffset
[idx
]));
625 if ((const uint8_t*)(glyphIndexTable
+ offset
+ 1) > limit
) {
626 return 0; // broken font, just bail out safely
628 result
= glyphIndexTable
[offset
];
631 // Note that this is unsigned 16-bit arithmetic, and may wrap around
632 // (which is required behavior per spec)
633 result
+= uint16_t(idDelta
[idx
]);
640 uint32_t gfxFontUtils::MapCharToGlyphFormat10(const uint8_t* aBuf
,
642 const Format10CmapHeader
* cmap10
=
643 reinterpret_cast<const Format10CmapHeader
*>(aBuf
);
645 uint32_t startChar
= cmap10
->startCharCode
;
646 uint32_t numChars
= cmap10
->numChars
;
648 if (aCh
< startChar
|| aCh
>= startChar
+ numChars
) {
652 const AutoSwap_PRUint16
* glyphs
=
653 reinterpret_cast<const AutoSwap_PRUint16
*>(cmap10
+ 1);
655 uint16_t glyph
= glyphs
[aCh
- startChar
];
659 uint32_t gfxFontUtils::MapCharToGlyphFormat12or13(const uint8_t* aBuf
,
661 // The only difference between formats 12 and 13 is the interpretation of
662 // the glyphId field. So the code here uses the same "Format12" structures,
663 // etc., to handle both subtable formats.
665 const Format12CmapHeader
* cmap12
=
666 reinterpret_cast<const Format12CmapHeader
*>(aBuf
);
668 // We know that numGroups is within range for the subtable size
669 // because it was checked by ReadCMAPTableFormat12or13.
670 uint32_t numGroups
= cmap12
->numGroups
;
672 // The array of groups immediately follows the subtable header.
673 const Format12Group
* groups
=
674 reinterpret_cast<const Format12Group
*>(aBuf
+ sizeof(Format12CmapHeader
));
676 // For most efficient binary search, we want to work on a range that
677 // is a power of 2 so that we can always halve it by shifting.
678 // So we find the largest power of 2 that is <= numGroups.
679 // We will offset this range by rangeOffset so as to reach the end
680 // of the table, provided that doesn't put us beyond the target
681 // value from the outset.
682 uint32_t powerOf2
= mozilla::FindHighestBit(numGroups
);
683 uint32_t rangeOffset
= numGroups
- powerOf2
;
685 uint32_t startCharCode
;
687 if (groups
[rangeOffset
].startCharCode
<= aCh
) {
691 // Repeatedly halve the size of the range until we find the target group
692 while (powerOf2
> 1) {
694 if (groups
[range
+ powerOf2
].startCharCode
<= aCh
) {
699 // Check if the character is actually present in the range and return
700 // the corresponding glyph ID. Here is where formats 12 and 13 interpret
701 // the startGlyphId (12) or glyphId (13) field differently
702 startCharCode
= groups
[range
].startCharCode
;
703 if (startCharCode
<= aCh
&& groups
[range
].endCharCode
>= aCh
) {
704 return uint16_t(cmap12
->format
) == 12
705 ? uint16_t(groups
[range
].startGlyphId
) + aCh
- startCharCode
706 : uint16_t(groups
[range
].startGlyphId
);
709 // Else it's not present, so return the .notdef glyph
715 struct Format14CmapWrapper
{
716 const Format14Cmap
& mCmap14
;
717 explicit Format14CmapWrapper(const Format14Cmap
& cmap14
) : mCmap14(cmap14
) {}
718 uint32_t operator[](size_t index
) const {
719 return mCmap14
.varSelectorRecords
[index
].varSelector
;
723 struct NonDefUVSTableWrapper
{
724 const NonDefUVSTable
& mTable
;
725 explicit NonDefUVSTableWrapper(const NonDefUVSTable
& table
) : mTable(table
) {}
726 uint32_t operator[](size_t index
) const {
727 return mTable
.uvsMappings
[index
].unicodeValue
;
733 uint16_t gfxFontUtils::MapUVSToGlyphFormat14(const uint8_t* aBuf
, uint32_t aCh
,
735 using mozilla::BinarySearch
;
736 const Format14Cmap
* cmap14
= reinterpret_cast<const Format14Cmap
*>(aBuf
);
739 if (!BinarySearch(Format14CmapWrapper(*cmap14
), 0,
740 cmap14
->numVarSelectorRecords
, aVS
, &index
)) {
744 const uint32_t nonDefUVSOffset
=
745 cmap14
->varSelectorRecords
[index
].nonDefaultUVSOffset
;
746 if (!nonDefUVSOffset
) {
750 const NonDefUVSTable
* table
=
751 reinterpret_cast<const NonDefUVSTable
*>(aBuf
+ nonDefUVSOffset
);
753 if (BinarySearch(NonDefUVSTableWrapper(*table
), 0, table
->numUVSMappings
, aCh
,
755 return table
->uvsMappings
[index
].glyphID
;
761 uint32_t gfxFontUtils::MapCharToGlyph(const uint8_t* aCmapBuf
,
762 uint32_t aBufLength
, uint32_t aUnicode
,
763 uint32_t aVarSelector
) {
764 uint32_t offset
, uvsOffset
;
766 FindPreferredSubtable(aCmapBuf
, aBufLength
, &offset
, &uvsOffset
);
771 gid
= aUnicode
< UNICODE_BMP_LIMIT
772 ? MapCharToGlyphFormat4(aCmapBuf
+ offset
, aBufLength
- offset
,
777 gid
= MapCharToGlyphFormat10(aCmapBuf
+ offset
, aUnicode
);
781 gid
= MapCharToGlyphFormat12or13(aCmapBuf
+ offset
, aUnicode
);
784 NS_WARNING("unsupported cmap format, glyphs will be missing");
788 if (aVarSelector
&& uvsOffset
&& gid
) {
789 uint32_t varGID
= gfxFontUtils::MapUVSToGlyphFormat14(
790 aCmapBuf
+ uvsOffset
, aUnicode
, aVarSelector
);
792 aUnicode
= gfxFontUtils::GetUVSFallback(aUnicode
, aVarSelector
);
796 if (aUnicode
< UNICODE_BMP_LIMIT
) {
797 varGID
= MapCharToGlyphFormat4(
798 aCmapBuf
+ offset
, aBufLength
- offset
, char16_t(aUnicode
));
802 varGID
= MapCharToGlyphFormat10(aCmapBuf
+ offset
, aUnicode
);
806 varGID
= MapCharToGlyphFormat12or13(aCmapBuf
+ offset
, aUnicode
);
815 // else the variation sequence was not supported, use default mapping
816 // of the character code alone
822 void gfxFontUtils::ParseFontList(const nsACString
& aFamilyList
,
823 nsTArray
<nsCString
>& aFontList
) {
824 const char kComma
= ',';
826 // append each font name to the list
827 nsAutoCString fontname
;
828 const char *p
, *p_end
;
829 aFamilyList
.BeginReading(p
);
830 aFamilyList
.EndReading(p_end
);
833 const char* nameStart
= p
;
834 while (++p
!= p_end
&& *p
!= kComma
) /* nothing */
837 // pull out a single name and clean out leading/trailing whitespace
838 fontname
= Substring(nameStart
, p
);
839 fontname
.CompressWhitespace(true, true);
841 // append it to the list if it's not empty
842 if (!fontname
.IsEmpty()) {
843 aFontList
.AppendElement(fontname
);
849 void gfxFontUtils::AppendPrefsFontList(const char* aPrefName
,
850 nsTArray
<nsCString
>& aFontList
,
852 // get the list of single-face font families
853 nsAutoCString fontlistValue
;
854 nsresult rv
= aLocalized
855 ? Preferences::GetLocalizedCString(aPrefName
, fontlistValue
)
856 : Preferences::GetCString(aPrefName
, fontlistValue
);
861 ParseFontList(fontlistValue
, aFontList
);
864 void gfxFontUtils::GetPrefsFontList(const char* aPrefName
,
865 nsTArray
<nsCString
>& aFontList
,
868 AppendPrefsFontList(aPrefName
, aFontList
, aLocalized
);
871 // produce a unique font name that is (1) a valid Postscript name and (2) less
872 // than 31 characters in length. Using AddFontMemResourceEx on Windows fails
873 // for names longer than 30 characters in length.
875 #define MAX_B64_LEN 32
877 nsresult
gfxFontUtils::MakeUniqueUserFontName(nsAString
& aName
) {
878 nsCOMPtr
<nsIUUIDGenerator
> uuidgen
=
879 do_GetService("@mozilla.org/uuid-generator;1");
880 NS_ENSURE_TRUE(uuidgen
, NS_ERROR_OUT_OF_MEMORY
);
884 NS_ASSERTION(sizeof(guid
) * 2 <= MAX_B64_LEN
, "size of nsID has changed!");
886 nsresult rv
= uuidgen
->GenerateUUIDInPlace(&guid
);
887 NS_ENSURE_SUCCESS(rv
, rv
);
889 char guidB64
[MAX_B64_LEN
] = {0};
891 if (!PL_Base64Encode(reinterpret_cast<char*>(&guid
), sizeof(guid
), guidB64
))
892 return NS_ERROR_FAILURE
;
894 // all b64 characters except for '/' are allowed in Postscript names, so
897 for (p
= guidB64
; *p
; p
++) {
898 if (*p
== '/') *p
= '-';
901 aName
.AssignLiteral(u
"uf");
902 aName
.AppendASCII(guidB64
);
906 // TrueType/OpenType table handling code
908 // need byte aligned structs
911 // name table stores set of name record structures, followed by
912 // large block containing all the strings. name record offset and length
913 // indicates the offset and length within that block.
914 // http://www.microsoft.com/typography/otspec/name.htm
915 struct NameRecordData
{
922 static bool IsValidSFNTVersion(uint32_t version
) {
923 // normally 0x00010000, CFF-style OT fonts == 'OTTO' and Apple TT fonts =
924 // 'true' 'typ1' is also possible for old Type 1 fonts in a SFNT container but
926 return version
== 0x10000 || version
== TRUETYPE_TAG('O', 'T', 'T', 'O') ||
927 version
== TRUETYPE_TAG('t', 'r', 'u', 'e');
930 gfxUserFontType
gfxFontUtils::DetermineFontDataType(const uint8_t* aFontData
,
931 uint32_t aFontDataLength
) {
932 // test for OpenType font data
933 // problem: EOT-Lite with 0x10000 length will look like TrueType!
934 if (aFontDataLength
>= sizeof(SFNTHeader
)) {
935 const SFNTHeader
* sfntHeader
=
936 reinterpret_cast<const SFNTHeader
*>(aFontData
);
937 uint32_t sfntVersion
= sfntHeader
->sfntVersion
;
938 if (IsValidSFNTVersion(sfntVersion
)) {
939 return GFX_USERFONT_OPENTYPE
;
943 // test for WOFF or WOFF2
944 if (aFontDataLength
>= sizeof(AutoSwap_PRUint32
)) {
945 const AutoSwap_PRUint32
* version
=
946 reinterpret_cast<const AutoSwap_PRUint32
*>(aFontData
);
947 if (uint32_t(*version
) == TRUETYPE_TAG('w', 'O', 'F', 'F')) {
948 return GFX_USERFONT_WOFF
;
950 if (uint32_t(*version
) == TRUETYPE_TAG('w', 'O', 'F', '2')) {
951 return GFX_USERFONT_WOFF2
;
955 // tests for other formats here
957 return GFX_USERFONT_UNKNOWN
;
960 static int DirEntryCmp(const void* aKey
, const void* aItem
) {
961 int32_t tag
= *static_cast<const int32_t*>(aKey
);
962 const TableDirEntry
* entry
= static_cast<const TableDirEntry
*>(aItem
);
963 return tag
- int32_t(entry
->tag
);
967 TableDirEntry
* gfxFontUtils::FindTableDirEntry(const void* aFontData
,
968 uint32_t aTableTag
) {
969 const SFNTHeader
* header
= reinterpret_cast<const SFNTHeader
*>(aFontData
);
970 const TableDirEntry
* dir
= reinterpret_cast<const TableDirEntry
*>(header
+ 1);
971 return static_cast<TableDirEntry
*>(
972 bsearch(&aTableTag
, dir
, uint16_t(header
->numTables
),
973 sizeof(TableDirEntry
), DirEntryCmp
));
977 hb_blob_t
* gfxFontUtils::GetTableFromFontData(const void* aFontData
,
978 uint32_t aTableTag
) {
979 const TableDirEntry
* dir
= FindTableDirEntry(aFontData
, aTableTag
);
981 return hb_blob_create(
982 reinterpret_cast<const char*>(aFontData
) + dir
->offset
, dir
->length
,
983 HB_MEMORY_MODE_READONLY
, nullptr, nullptr);
988 nsresult
gfxFontUtils::RenameFont(const nsAString
& aName
,
989 const uint8_t* aFontData
,
990 uint32_t aFontDataLength
,
991 FallibleTArray
<uint8_t>* aNewFont
) {
992 NS_ASSERTION(aNewFont
, "null font data array");
994 uint64_t dataLength(aFontDataLength
);
997 static const uint32_t neededNameIDs
[] = {NAME_ID_FAMILY
, NAME_ID_STYLE
,
998 NAME_ID_UNIQUE
, NAME_ID_FULL
,
1001 // calculate new name table size
1002 uint16_t nameCount
= ArrayLength(neededNameIDs
);
1004 // leave room for null-terminator
1005 uint32_t nameStrLength
= (aName
.Length() + 1) * sizeof(char16_t
);
1006 if (nameStrLength
> 65535) {
1007 // The name length _in bytes_ must fit in an unsigned short field;
1008 // therefore, a name longer than this cannot be used.
1009 return NS_ERROR_FAILURE
;
1012 // round name table size up to 4-byte multiple
1013 uint32_t nameTableSize
=
1014 (sizeof(NameHeader
) + sizeof(NameRecord
) * nameCount
+ nameStrLength
+
1018 if (dataLength
+ nameTableSize
> UINT32_MAX
) return NS_ERROR_FAILURE
;
1020 // bug 505386 - need to handle unpadded font length
1021 uint32_t paddedFontDataSize
= (aFontDataLength
+ 3) & ~3;
1022 uint32_t adjFontDataSize
= paddedFontDataSize
+ nameTableSize
;
1024 // create new buffer: old font data plus new name table
1025 if (!aNewFont
->AppendElements(adjFontDataSize
, fallible
))
1026 return NS_ERROR_OUT_OF_MEMORY
;
1028 // copy the old font data
1029 uint8_t* newFontData
= reinterpret_cast<uint8_t*>(aNewFont
->Elements());
1031 // null the last four bytes in case the font length is not a multiple of 4
1032 memset(newFontData
+ aFontDataLength
, 0,
1033 paddedFontDataSize
- aFontDataLength
);
1036 memcpy(newFontData
, aFontData
, aFontDataLength
);
1038 // null out the last 4 bytes for checksum calculations
1039 memset(newFontData
+ adjFontDataSize
- 4, 0, 4);
1041 NameHeader
* nameHeader
=
1042 reinterpret_cast<NameHeader
*>(newFontData
+ paddedFontDataSize
);
1045 nameHeader
->format
= 0;
1046 nameHeader
->count
= nameCount
;
1047 nameHeader
->stringOffset
=
1048 sizeof(NameHeader
) + nameCount
* sizeof(NameRecord
);
1052 NameRecord
* nameRecord
= reinterpret_cast<NameRecord
*>(nameHeader
+ 1);
1054 for (i
= 0; i
< nameCount
; i
++, nameRecord
++) {
1055 nameRecord
->platformID
= PLATFORM_ID_MICROSOFT
;
1056 nameRecord
->encodingID
= ENCODING_ID_MICROSOFT_UNICODEBMP
;
1057 nameRecord
->languageID
= LANG_ID_MICROSOFT_EN_US
;
1058 nameRecord
->nameID
= neededNameIDs
[i
];
1059 nameRecord
->offset
= 0;
1060 nameRecord
->length
= nameStrLength
;
1063 // -- string data, located after the name records, stored in big-endian form
1064 char16_t
* strData
= reinterpret_cast<char16_t
*>(nameRecord
);
1066 mozilla::NativeEndian::copyAndSwapToBigEndian(strData
, aName
.BeginReading(),
1068 strData
[aName
.Length()] = 0; // add null termination
1070 // adjust name table header to point to the new name table
1071 SFNTHeader
* sfntHeader
= reinterpret_cast<SFNTHeader
*>(newFontData
);
1073 // table directory entries begin immediately following SFNT header
1074 TableDirEntry
* dirEntry
=
1075 FindTableDirEntry(newFontData
, TRUETYPE_TAG('n', 'a', 'm', 'e'));
1076 // function only called if font validates, so this should always be true
1077 MOZ_ASSERT(dirEntry
, "attempt to rename font with no name table");
1079 uint32_t numTables
= sfntHeader
->numTables
;
1081 // note: dirEntry now points to 'name' table record
1083 // recalculate name table checksum
1084 uint32_t checkSum
= 0;
1085 AutoSwap_PRUint32
* nameData
=
1086 reinterpret_cast<AutoSwap_PRUint32
*>(nameHeader
);
1087 AutoSwap_PRUint32
* nameDataEnd
= nameData
+ (nameTableSize
>> 2);
1089 while (nameData
< nameDataEnd
) checkSum
= checkSum
+ *nameData
++;
1091 // adjust name table entry to point to new name table
1092 dirEntry
->offset
= paddedFontDataSize
;
1093 dirEntry
->length
= nameTableSize
;
1094 dirEntry
->checkSum
= checkSum
;
1097 uint32_t checksum
= 0;
1099 // checksum for font = (checksum of header) + (checksum of tables)
1100 uint32_t headerLen
= sizeof(SFNTHeader
) + sizeof(TableDirEntry
) * numTables
;
1101 const AutoSwap_PRUint32
* headerData
=
1102 reinterpret_cast<const AutoSwap_PRUint32
*>(newFontData
);
1104 // header length is in bytes, checksum calculated in longwords
1105 for (i
= 0; i
< (headerLen
>> 2); i
++, headerData
++) {
1106 checksum
+= *headerData
;
1109 uint32_t headOffset
= 0;
1110 dirEntry
= reinterpret_cast<TableDirEntry
*>(newFontData
+ sizeof(SFNTHeader
));
1112 for (i
= 0; i
< numTables
; i
++, dirEntry
++) {
1113 if (dirEntry
->tag
== TRUETYPE_TAG('h', 'e', 'a', 'd')) {
1114 headOffset
= dirEntry
->offset
;
1116 checksum
+= dirEntry
->checkSum
;
1119 NS_ASSERTION(headOffset
!= 0, "no head table for font");
1121 HeadTable
* headData
= reinterpret_cast<HeadTable
*>(newFontData
+ headOffset
);
1123 headData
->checkSumAdjustment
= HeadTable::HEAD_CHECKSUM_CALC_CONST
- checksum
;
1128 // This is only called after the basic validity of the downloaded sfnt
1129 // data has been checked, so it should never fail to find the name table
1130 // (though it might fail to read it, if memory isn't available);
1131 // other checks here are just for extra paranoia.
1132 nsresult
gfxFontUtils::GetFullNameFromSFNT(const uint8_t* aFontData
,
1134 nsACString
& aFullName
) {
1135 aFullName
= "(MISSING NAME)"; // should always get replaced
1137 const TableDirEntry
* dirEntry
=
1138 FindTableDirEntry(aFontData
, TRUETYPE_TAG('n', 'a', 'm', 'e'));
1140 // should never fail, as we're only called after font validation succeeded
1141 NS_ENSURE_TRUE(dirEntry
, NS_ERROR_NOT_AVAILABLE
);
1143 uint32_t len
= dirEntry
->length
;
1144 NS_ENSURE_TRUE(aLength
> len
&& aLength
- len
>= dirEntry
->offset
,
1145 NS_ERROR_UNEXPECTED
);
1147 hb_blob_t
* nameBlob
=
1148 hb_blob_create((const char*)aFontData
+ dirEntry
->offset
, len
,
1149 HB_MEMORY_MODE_READONLY
, nullptr, nullptr);
1150 nsresult rv
= GetFullNameFromTable(nameBlob
, aFullName
);
1151 hb_blob_destroy(nameBlob
);
1156 nsresult
gfxFontUtils::GetFullNameFromTable(hb_blob_t
* aNameTable
,
1157 nsACString
& aFullName
) {
1159 nsresult rv
= gfxFontUtils::ReadCanonicalName(
1160 aNameTable
, gfxFontUtils::NAME_ID_FULL
, name
);
1161 if (NS_SUCCEEDED(rv
) && !name
.IsEmpty()) {
1165 rv
= gfxFontUtils::ReadCanonicalName(aNameTable
, gfxFontUtils::NAME_ID_FAMILY
,
1167 if (NS_SUCCEEDED(rv
) && !name
.IsEmpty()) {
1168 nsAutoCString styleName
;
1169 rv
= gfxFontUtils::ReadCanonicalName(
1170 aNameTable
, gfxFontUtils::NAME_ID_STYLE
, styleName
);
1171 if (NS_SUCCEEDED(rv
) && !styleName
.IsEmpty()) {
1173 name
.Append(styleName
);
1179 return NS_ERROR_NOT_AVAILABLE
;
1182 nsresult
gfxFontUtils::GetFamilyNameFromTable(hb_blob_t
* aNameTable
,
1183 nsACString
& aFamilyName
) {
1185 nsresult rv
= gfxFontUtils::ReadCanonicalName(
1186 aNameTable
, gfxFontUtils::NAME_ID_FAMILY
, name
);
1187 if (NS_SUCCEEDED(rv
) && !name
.IsEmpty()) {
1191 return NS_ERROR_NOT_AVAILABLE
;
1195 #if defined(XP_MACOSX)
1196 CANONICAL_LANG_ID
= gfxFontUtils::LANG_ID_MAC_ENGLISH
,
1197 PLATFORM_ID
= gfxFontUtils::PLATFORM_ID_MAC
1199 CANONICAL_LANG_ID
= gfxFontUtils::LANG_ID_MICROSOFT_EN_US
,
1200 PLATFORM_ID
= gfxFontUtils::PLATFORM_ID_MICROSOFT
1204 nsresult
gfxFontUtils::ReadNames(const char* aNameData
, uint32_t aDataLen
,
1205 uint32_t aNameID
, int32_t aPlatformID
,
1206 nsTArray
<nsCString
>& aNames
) {
1207 return ReadNames(aNameData
, aDataLen
, aNameID
, LANG_ALL
, aPlatformID
, aNames
);
1210 nsresult
gfxFontUtils::ReadCanonicalName(hb_blob_t
* aNameTable
,
1211 uint32_t aNameID
, nsCString
& aName
) {
1212 uint32_t nameTableLen
;
1213 const char* nameTable
= hb_blob_get_data(aNameTable
, &nameTableLen
);
1214 return ReadCanonicalName(nameTable
, nameTableLen
, aNameID
, aName
);
1217 nsresult
gfxFontUtils::ReadCanonicalName(const char* aNameData
,
1218 uint32_t aDataLen
, uint32_t aNameID
,
1222 nsTArray
<nsCString
> names
;
1224 // first, look for the English name (this will succeed 99% of the time)
1225 rv
= ReadNames(aNameData
, aDataLen
, aNameID
, CANONICAL_LANG_ID
, PLATFORM_ID
,
1227 NS_ENSURE_SUCCESS(rv
, rv
);
1229 // otherwise, grab names for all languages
1230 if (names
.Length() == 0) {
1231 rv
= ReadNames(aNameData
, aDataLen
, aNameID
, LANG_ALL
, PLATFORM_ID
, names
);
1232 NS_ENSURE_SUCCESS(rv
, rv
);
1235 #if defined(XP_MACOSX)
1236 // may be dealing with font that only has Microsoft name entries
1237 if (names
.Length() == 0) {
1238 rv
= ReadNames(aNameData
, aDataLen
, aNameID
, LANG_ID_MICROSOFT_EN_US
,
1239 PLATFORM_ID_MICROSOFT
, names
);
1240 NS_ENSURE_SUCCESS(rv
, rv
);
1242 // getting really desperate now, take anything!
1243 if (names
.Length() == 0) {
1244 rv
= ReadNames(aNameData
, aDataLen
, aNameID
, LANG_ALL
,
1245 PLATFORM_ID_MICROSOFT
, names
);
1246 NS_ENSURE_SUCCESS(rv
, rv
);
1251 // return the first name (99.9% of the time names will
1252 // contain a single English name)
1253 if (names
.Length()) {
1254 aName
.Assign(names
[0]);
1258 return NS_ERROR_FAILURE
;
1261 // Charsets to use for decoding Mac platform font names.
1262 // This table is sorted by {encoding, language}, with the wildcard "ANY" being
1263 // greater than any defined values for each field; we use a binary search on
1264 // both fields, and fall back to matching only encoding if necessary
1266 // Some "redundant" entries for specific combinations are included such as
1267 // encoding=roman, lang=english, in order that common entries will be found
1268 // on the first search.
1270 const uint16_t ANY
= 0xffff;
1271 const gfxFontUtils::MacFontNameCharsetMapping
1272 gfxFontUtils::gMacFontNameCharsets
[] = {
1273 {ENCODING_ID_MAC_ROMAN
, LANG_ID_MAC_ENGLISH
, MACINTOSH_ENCODING
},
1274 {ENCODING_ID_MAC_ROMAN
, LANG_ID_MAC_ICELANDIC
, X_USER_DEFINED_ENCODING
},
1275 {ENCODING_ID_MAC_ROMAN
, LANG_ID_MAC_TURKISH
, X_USER_DEFINED_ENCODING
},
1276 {ENCODING_ID_MAC_ROMAN
, LANG_ID_MAC_POLISH
, X_USER_DEFINED_ENCODING
},
1277 {ENCODING_ID_MAC_ROMAN
, LANG_ID_MAC_ROMANIAN
, X_USER_DEFINED_ENCODING
},
1278 {ENCODING_ID_MAC_ROMAN
, LANG_ID_MAC_CZECH
, X_USER_DEFINED_ENCODING
},
1279 {ENCODING_ID_MAC_ROMAN
, LANG_ID_MAC_SLOVAK
, X_USER_DEFINED_ENCODING
},
1280 {ENCODING_ID_MAC_ROMAN
, ANY
, MACINTOSH_ENCODING
},
1281 {ENCODING_ID_MAC_JAPANESE
, LANG_ID_MAC_JAPANESE
, SHIFT_JIS_ENCODING
},
1282 {ENCODING_ID_MAC_JAPANESE
, ANY
, SHIFT_JIS_ENCODING
},
1283 {ENCODING_ID_MAC_TRAD_CHINESE
, LANG_ID_MAC_TRAD_CHINESE
, BIG5_ENCODING
},
1284 {ENCODING_ID_MAC_TRAD_CHINESE
, ANY
, BIG5_ENCODING
},
1285 {ENCODING_ID_MAC_KOREAN
, LANG_ID_MAC_KOREAN
, EUC_KR_ENCODING
},
1286 {ENCODING_ID_MAC_KOREAN
, ANY
, EUC_KR_ENCODING
},
1287 {ENCODING_ID_MAC_ARABIC
, LANG_ID_MAC_ARABIC
, X_USER_DEFINED_ENCODING
},
1288 {ENCODING_ID_MAC_ARABIC
, LANG_ID_MAC_URDU
, X_USER_DEFINED_ENCODING
},
1289 {ENCODING_ID_MAC_ARABIC
, LANG_ID_MAC_FARSI
, X_USER_DEFINED_ENCODING
},
1290 {ENCODING_ID_MAC_ARABIC
, ANY
, X_USER_DEFINED_ENCODING
},
1291 {ENCODING_ID_MAC_HEBREW
, LANG_ID_MAC_HEBREW
, X_USER_DEFINED_ENCODING
},
1292 {ENCODING_ID_MAC_HEBREW
, ANY
, X_USER_DEFINED_ENCODING
},
1293 {ENCODING_ID_MAC_GREEK
, ANY
, X_USER_DEFINED_ENCODING
},
1294 {ENCODING_ID_MAC_CYRILLIC
, ANY
, X_MAC_CYRILLIC_ENCODING
},
1295 {ENCODING_ID_MAC_DEVANAGARI
, ANY
, X_USER_DEFINED_ENCODING
},
1296 {ENCODING_ID_MAC_GURMUKHI
, ANY
, X_USER_DEFINED_ENCODING
},
1297 {ENCODING_ID_MAC_GUJARATI
, ANY
, X_USER_DEFINED_ENCODING
},
1298 {ENCODING_ID_MAC_SIMP_CHINESE
, LANG_ID_MAC_SIMP_CHINESE
,
1300 {ENCODING_ID_MAC_SIMP_CHINESE
, ANY
, GB18030_ENCODING
}};
1302 const Encoding
* gfxFontUtils::gISOFontNameCharsets
[] = {
1303 /* 0 */ WINDOWS_1252_ENCODING
, /* US-ASCII */
1304 /* 1 */ nullptr, /* spec says "ISO 10646" but does not specify encoding
1306 /* 2 */ WINDOWS_1252_ENCODING
/* ISO-8859-1 */
1309 const Encoding
* gfxFontUtils::gMSFontNameCharsets
[] = {
1310 /* [0] ENCODING_ID_MICROSOFT_SYMBOL */ UTF_16BE_ENCODING
,
1311 /* [1] ENCODING_ID_MICROSOFT_UNICODEBMP */ UTF_16BE_ENCODING
,
1312 /* [2] ENCODING_ID_MICROSOFT_SHIFTJIS */ SHIFT_JIS_ENCODING
,
1313 /* [3] ENCODING_ID_MICROSOFT_PRC */ nullptr,
1314 /* [4] ENCODING_ID_MICROSOFT_BIG5 */ BIG5_ENCODING
,
1315 /* [5] ENCODING_ID_MICROSOFT_WANSUNG */ nullptr,
1316 /* [6] ENCODING_ID_MICROSOFT_JOHAB */ nullptr,
1317 /* [7] reserved */ nullptr,
1318 /* [8] reserved */ nullptr,
1319 /* [9] reserved */ nullptr,
1320 /*[10] ENCODING_ID_MICROSOFT_UNICODEFULL */ UTF_16BE_ENCODING
};
1322 struct MacCharsetMappingComparator
{
1323 typedef gfxFontUtils::MacFontNameCharsetMapping MacFontNameCharsetMapping
;
1324 const MacFontNameCharsetMapping
& mSearchValue
;
1325 explicit MacCharsetMappingComparator(
1326 const MacFontNameCharsetMapping
& aSearchValue
)
1327 : mSearchValue(aSearchValue
) {}
1328 int operator()(const MacFontNameCharsetMapping
& aEntry
) const {
1329 if (mSearchValue
< aEntry
) {
1332 if (aEntry
< mSearchValue
) {
1339 // Return the Encoding object we should use to decode a font name
1340 // given the name table attributes.
1341 // Special return values:
1342 // X_USER_DEFINED_ENCODING One of Mac legacy encodings that is not a part
1343 // of Encoding Standard
1344 // nullptr unknown charset, do not attempt conversion
1345 const Encoding
* gfxFontUtils::GetCharsetForFontName(uint16_t aPlatform
,
1347 uint16_t aLanguage
) {
1348 switch (aPlatform
) {
1349 case PLATFORM_ID_UNICODE
:
1350 return UTF_16BE_ENCODING
;
1352 case PLATFORM_ID_MAC
: {
1353 MacFontNameCharsetMapping searchValue
= {aScript
, aLanguage
, nullptr};
1354 for (uint32_t i
= 0; i
< 2; ++i
) {
1356 if (BinarySearchIf(gMacFontNameCharsets
, 0,
1357 ArrayLength(gMacFontNameCharsets
),
1358 MacCharsetMappingComparator(searchValue
), &idx
)) {
1359 return gMacFontNameCharsets
[idx
].mEncoding
;
1362 // no match, so try again finding one in any language
1363 searchValue
.mLanguage
= ANY
;
1367 case PLATFORM_ID_ISO
:
1368 if (aScript
< ArrayLength(gISOFontNameCharsets
)) {
1369 return gISOFontNameCharsets
[aScript
];
1373 case PLATFORM_ID_MICROSOFT
:
1374 if (aScript
< ArrayLength(gMSFontNameCharsets
)) {
1375 return gMSFontNameCharsets
[aScript
];
1384 static bool StartsWith(const nsACString
& string
, const char (&prefix
)[N
]) {
1385 if (N
- 1 > string
.Length()) {
1388 return memcmp(string
.Data(), prefix
, N
- 1) == 0;
1391 // convert a raw name from the name table to an nsString, if possible;
1392 // return value indicates whether conversion succeeded
1393 bool gfxFontUtils::DecodeFontName(const char* aNameData
, int32_t aByteLen
,
1394 uint32_t aPlatformCode
, uint32_t aScriptCode
,
1395 uint32_t aLangCode
, nsACString
& aName
) {
1396 if (aByteLen
<= 0) {
1397 NS_WARNING("empty font name");
1402 auto encoding
= GetCharsetForFontName(aPlatformCode
, aScriptCode
, aLangCode
);
1405 // nullptr -> unknown charset
1408 if (aByteLen
> 64) aByteLen
= 64;
1409 SprintfLiteral(warnBuf
,
1410 "skipping font name, unknown charset %d:%d:%d for <%.*s>",
1411 aPlatformCode
, aScriptCode
, aLangCode
, aByteLen
, aNameData
);
1412 NS_WARNING(warnBuf
);
1417 if (encoding
== X_USER_DEFINED_ENCODING
) {
1419 // Special case for macOS only: support legacy Mac encodings
1420 // that aren't part of the Encoding Standard.
1421 if (aPlatformCode
== PLATFORM_ID_MAC
) {
1423 CFStringCreateWithBytes(kCFAllocatorDefault
, (const UInt8
*)aNameData
,
1424 aByteLen
, aScriptCode
, false);
1426 CFIndex length
= CFStringGetLength(str
);
1427 nsAutoString name16
;
1428 name16
.SetLength(length
);
1429 CFStringGetCharacters(str
, CFRangeMake(0, length
),
1430 (UniChar
*)name16
.BeginWriting());
1432 CopyUTF16toUTF8(name16
, aName
);
1437 NS_WARNING("failed to get the decoder for a font name string");
1441 auto rv
= encoding
->DecodeWithoutBOMHandling(
1442 nsDependentCSubstring(aNameData
, aByteLen
), aName
);
1443 return NS_SUCCEEDED(rv
);
1446 nsresult
gfxFontUtils::ReadNames(const char* aNameData
, uint32_t aDataLen
,
1447 uint32_t aNameID
, int32_t aLangID
,
1448 int32_t aPlatformID
,
1449 nsTArray
<nsCString
>& aNames
) {
1450 NS_ASSERTION(aDataLen
!= 0, "null name table");
1453 return NS_ERROR_FAILURE
;
1456 // -- name table data
1457 const NameHeader
* nameHeader
= reinterpret_cast<const NameHeader
*>(aNameData
);
1459 uint32_t nameCount
= nameHeader
->count
;
1461 // -- sanity check the number of name records
1462 if (uint64_t(nameCount
) * sizeof(NameRecord
) > aDataLen
) {
1463 NS_WARNING("invalid font (name table data)");
1464 return NS_ERROR_FAILURE
;
1467 // -- iterate through name records
1468 const NameRecord
* nameRecord
=
1469 reinterpret_cast<const NameRecord
*>(aNameData
+ sizeof(NameHeader
));
1470 uint64_t nameStringsBase
= uint64_t(nameHeader
->stringOffset
);
1473 for (i
= 0; i
< nameCount
; i
++, nameRecord
++) {
1474 uint32_t platformID
;
1476 // skip over unwanted nameID's
1477 if (uint32_t(nameRecord
->nameID
) != aNameID
) {
1481 // skip over unwanted platform data
1482 platformID
= nameRecord
->platformID
;
1483 if (aPlatformID
!= PLATFORM_ALL
&& platformID
!= uint32_t(aPlatformID
)) {
1487 // skip over unwanted languages
1488 if (aLangID
!= LANG_ALL
&&
1489 uint32_t(nameRecord
->languageID
) != uint32_t(aLangID
)) {
1493 // add name to names array
1495 // -- calculate string location
1496 uint32_t namelen
= nameRecord
->length
;
1498 nameRecord
->offset
; // offset from base of string storage
1500 if (nameStringsBase
+ uint64_t(nameoff
) + uint64_t(namelen
) > aDataLen
) {
1501 NS_WARNING("invalid font (name table strings)");
1502 return NS_ERROR_FAILURE
;
1505 // -- decode if necessary and make nsString
1508 DecodeFontName(aNameData
+ nameStringsBase
+ nameoff
, namelen
, platformID
,
1509 uint32_t(nameRecord
->encodingID
),
1510 uint32_t(nameRecord
->languageID
), name
);
1512 uint32_t k
, numNames
;
1513 bool foundName
= false;
1515 numNames
= aNames
.Length();
1516 for (k
= 0; k
< numNames
; k
++) {
1517 if (name
.Equals(aNames
[k
])) {
1523 if (!foundName
) aNames
.AppendElement(name
);
1531 struct COLRBaseGlyphRecord
{
1532 AutoSwap_PRUint16 glyphId
;
1533 AutoSwap_PRUint16 firstLayerIndex
;
1534 AutoSwap_PRUint16 numLayers
;
1537 struct COLRLayerRecord
{
1538 AutoSwap_PRUint16 glyphId
;
1539 AutoSwap_PRUint16 paletteEntryIndex
;
1543 struct CPALColorRecord
{
1552 bool gfxFontUtils::ValidateColorGlyphs(hb_blob_t
* aCOLR
, hb_blob_t
* aCPAL
) {
1553 unsigned int colrLength
;
1554 const COLRHeader
* colr
=
1555 reinterpret_cast<const COLRHeader
*>(hb_blob_get_data(aCOLR
, &colrLength
));
1556 unsigned int cpalLength
;
1557 const CPALHeaderVersion0
* cpal
= reinterpret_cast<const CPALHeaderVersion0
*>(
1558 hb_blob_get_data(aCPAL
, &cpalLength
));
1560 if (!colr
|| !cpal
|| !colrLength
|| !cpalLength
) {
1564 if (uint16_t(colr
->version
) != 0 || uint16_t(cpal
->version
) != 0) {
1565 // We only support version 0 headers.
1569 const uint32_t offsetBaseGlyphRecord
= colr
->offsetBaseGlyphRecord
;
1570 const uint16_t numBaseGlyphRecord
= colr
->numBaseGlyphRecord
;
1571 const uint32_t offsetLayerRecord
= colr
->offsetLayerRecord
;
1572 const uint16_t numLayerRecords
= colr
->numLayerRecords
;
1574 const uint32_t offsetFirstColorRecord
= cpal
->offsetFirstColorRecord
;
1575 const uint16_t numColorRecords
= cpal
->numColorRecords
;
1576 const uint32_t numPaletteEntries
= cpal
->numPaletteEntries
;
1578 if (offsetBaseGlyphRecord
>= colrLength
) {
1582 if (offsetLayerRecord
>= colrLength
) {
1586 if (offsetFirstColorRecord
>= cpalLength
) {
1590 if (!numPaletteEntries
) {
1594 if (sizeof(COLRBaseGlyphRecord
) * numBaseGlyphRecord
>
1595 colrLength
- offsetBaseGlyphRecord
) {
1596 // COLR base glyph record will be overflow
1600 if (sizeof(COLRLayerRecord
) * numLayerRecords
>
1601 colrLength
- offsetLayerRecord
) {
1602 // COLR layer record will be overflow
1606 if (sizeof(CPALColorRecord
) * numColorRecords
>
1607 cpalLength
- offsetFirstColorRecord
) {
1608 // CPAL color record will be overflow
1612 if (numPaletteEntries
* uint16_t(cpal
->numPalettes
) != numColorRecords
) {
1613 // palette of CPAL color record will be overflow.
1617 uint16_t lastGlyphId
= 0;
1618 const COLRBaseGlyphRecord
* baseGlyph
=
1619 reinterpret_cast<const COLRBaseGlyphRecord
*>(
1620 reinterpret_cast<const uint8_t*>(colr
) + offsetBaseGlyphRecord
);
1622 for (uint16_t i
= 0; i
< numBaseGlyphRecord
; i
++, baseGlyph
++) {
1623 const uint32_t firstLayerIndex
= baseGlyph
->firstLayerIndex
;
1624 const uint16_t numLayers
= baseGlyph
->numLayers
;
1625 const uint16_t glyphId
= baseGlyph
->glyphId
;
1627 if (lastGlyphId
&& lastGlyphId
>= glyphId
) {
1628 // glyphId must be sorted
1631 lastGlyphId
= glyphId
;
1637 if (firstLayerIndex
+ numLayers
> numLayerRecords
) {
1638 // layer length of target glyph is overflow
1643 const COLRLayerRecord
* layer
= reinterpret_cast<const COLRLayerRecord
*>(
1644 reinterpret_cast<const uint8_t*>(colr
) + offsetLayerRecord
);
1646 for (uint16_t i
= 0; i
< numLayerRecords
; i
++, layer
++) {
1647 if (uint16_t(layer
->paletteEntryIndex
) >= numPaletteEntries
&&
1648 uint16_t(layer
->paletteEntryIndex
) != 0xFFFF) {
1649 // CPAL palette entry record is overflow
1657 static int CompareBaseGlyph(const void* key
, const void* data
) {
1658 uint32_t glyphId
= (uint32_t)(uintptr_t)key
;
1659 const COLRBaseGlyphRecord
* baseGlyph
=
1660 reinterpret_cast<const COLRBaseGlyphRecord
*>(data
);
1661 uint32_t baseGlyphId
= uint16_t(baseGlyph
->glyphId
);
1663 if (baseGlyphId
== glyphId
) {
1667 return baseGlyphId
> glyphId
? -1 : 1;
1670 static COLRBaseGlyphRecord
* LookForBaseGlyphRecord(const COLRHeader
* aCOLR
,
1671 uint32_t aGlyphId
) {
1672 const uint8_t* baseGlyphRecords
= reinterpret_cast<const uint8_t*>(aCOLR
) +
1673 uint32_t(aCOLR
->offsetBaseGlyphRecord
);
1674 // BaseGlyphRecord is sorted by glyphId
1675 return reinterpret_cast<COLRBaseGlyphRecord
*>(
1676 bsearch((void*)(uintptr_t)aGlyphId
, baseGlyphRecords
,
1677 uint16_t(aCOLR
->numBaseGlyphRecord
), sizeof(COLRBaseGlyphRecord
),
1681 bool gfxFontUtils::GetColorGlyphLayers(
1682 hb_blob_t
* aCOLR
, hb_blob_t
* aCPAL
, uint32_t aGlyphId
,
1683 const mozilla::gfx::DeviceColor
& aDefaultColor
, nsTArray
<uint16_t>& aGlyphs
,
1684 nsTArray
<mozilla::gfx::DeviceColor
>& aColors
) {
1685 unsigned int blobLength
;
1686 const COLRHeader
* colr
=
1687 reinterpret_cast<const COLRHeader
*>(hb_blob_get_data(aCOLR
, &blobLength
));
1688 MOZ_ASSERT(colr
, "Cannot get COLR raw data");
1689 MOZ_ASSERT(blobLength
, "Found COLR data, but length is 0");
1691 COLRBaseGlyphRecord
* baseGlyph
= LookForBaseGlyphRecord(colr
, aGlyphId
);
1696 const CPALHeaderVersion0
* cpal
= reinterpret_cast<const CPALHeaderVersion0
*>(
1697 hb_blob_get_data(aCPAL
, &blobLength
));
1698 MOZ_ASSERT(cpal
, "Cannot get CPAL raw data");
1699 MOZ_ASSERT(blobLength
, "Found CPAL data, but length is 0");
1701 const COLRLayerRecord
* layer
= reinterpret_cast<const COLRLayerRecord
*>(
1702 reinterpret_cast<const uint8_t*>(colr
) +
1703 uint32_t(colr
->offsetLayerRecord
) +
1704 sizeof(COLRLayerRecord
) * uint16_t(baseGlyph
->firstLayerIndex
));
1705 const uint16_t numLayers
= baseGlyph
->numLayers
;
1706 const uint32_t offsetFirstColorRecord
= cpal
->offsetFirstColorRecord
;
1708 for (uint16_t layerIndex
= 0; layerIndex
< numLayers
; layerIndex
++) {
1709 aGlyphs
.AppendElement(uint16_t(layer
->glyphId
));
1710 if (uint16_t(layer
->paletteEntryIndex
) == 0xFFFF) {
1711 aColors
.AppendElement(aDefaultColor
);
1713 const CPALColorRecord
* color
= reinterpret_cast<const CPALColorRecord
*>(
1714 reinterpret_cast<const uint8_t*>(cpal
) + offsetFirstColorRecord
+
1715 sizeof(CPALColorRecord
) * uint16_t(layer
->paletteEntryIndex
));
1716 aColors
.AppendElement(
1717 mozilla::gfx::ToDeviceColor(mozilla::gfx::sRGBColor::FromU8(
1718 color
->red
, color
->green
, color
->blue
, color
->alpha
)));
1725 bool gfxFontUtils::HasColorLayersForGlyph(hb_blob_t
* aCOLR
, uint32_t aGlyphId
) {
1726 unsigned int blobLength
;
1727 const COLRHeader
* colr
=
1728 reinterpret_cast<const COLRHeader
*>(hb_blob_get_data(aCOLR
, &blobLength
));
1729 MOZ_ASSERT(colr
, "Cannot get COLR raw data");
1730 MOZ_ASSERT(blobLength
, "Found COLR data, but length is 0");
1732 return LookForBaseGlyphRecord(colr
, aGlyphId
);
1735 void gfxFontUtils::GetVariationData(
1736 gfxFontEntry
* aFontEntry
, nsTArray
<gfxFontVariationAxis
>* aAxes
,
1737 nsTArray
<gfxFontVariationInstance
>* aInstances
) {
1738 MOZ_ASSERT(!aAxes
|| aAxes
->IsEmpty());
1739 MOZ_ASSERT(!aInstances
|| aInstances
->IsEmpty());
1741 if (!aFontEntry
->HasVariations()) {
1745 // Some platforms don't offer a simple API to return the list of instances,
1746 // so we have to interpret the 'fvar' table ourselves.
1748 // https://www.microsoft.com/typography/otspec/fvar.htm#fvarHeader
1750 AutoSwap_PRUint16 majorVersion
;
1751 AutoSwap_PRUint16 minorVersion
;
1752 AutoSwap_PRUint16 axesArrayOffset
;
1753 AutoSwap_PRUint16 reserved
;
1754 AutoSwap_PRUint16 axisCount
;
1755 AutoSwap_PRUint16 axisSize
;
1756 AutoSwap_PRUint16 instanceCount
;
1757 AutoSwap_PRUint16 instanceSize
;
1760 // https://www.microsoft.com/typography/otspec/fvar.htm#variationAxisRecord
1762 AutoSwap_PRUint32 axisTag
;
1763 AutoSwap_PRInt32 minValue
;
1764 AutoSwap_PRInt32 defaultValue
;
1765 AutoSwap_PRInt32 maxValue
;
1766 AutoSwap_PRUint16 flags
;
1767 AutoSwap_PRUint16 axisNameID
;
1769 const uint16_t HIDDEN_AXIS
= 0x0001; // AxisRecord flags value
1771 // https://www.microsoft.com/typography/otspec/fvar.htm#instanceRecord
1772 struct InstanceRecord
{
1773 AutoSwap_PRUint16 subfamilyNameID
;
1774 AutoSwap_PRUint16 flags
;
1775 AutoSwap_PRInt32 coordinates
[1]; // variable-size array [axisCount]
1776 // The variable-length 'coordinates' array may be followed by an
1777 // optional extra field 'postScriptNameID'. We can't directly
1778 // represent this in the struct, because its offset varies depending
1779 // on the number of axes present.
1780 // (Not currently used by our code here anyhow.)
1781 // AutoSwap_PRUint16 postScriptNameID;
1784 // Helper to ensure we free a font table when we return.
1787 explicit AutoHBBlob(hb_blob_t
* aBlob
) : mBlob(aBlob
) {}
1789 ~AutoHBBlob() { hb_blob_destroy(mBlob
); }
1791 operator hb_blob_t
*() { return mBlob
; }
1794 hb_blob_t
* const mBlob
;
1797 // Load the two font tables we need as harfbuzz blobs; if either is absent,
1799 AutoHBBlob
fvarTable(
1800 aFontEntry
->GetFontTable(TRUETYPE_TAG('f', 'v', 'a', 'r')));
1801 AutoHBBlob
nameTable(
1802 aFontEntry
->GetFontTable(TRUETYPE_TAG('n', 'a', 'm', 'e')));
1803 if (!fvarTable
|| !nameTable
) {
1807 const char* data
= hb_blob_get_data(fvarTable
, &len
);
1808 if (len
< sizeof(FvarHeader
)) {
1811 // Read the fields of the table header; bail out if it looks broken.
1812 auto fvar
= reinterpret_cast<const FvarHeader
*>(data
);
1813 if (uint16_t(fvar
->majorVersion
) != 1 || uint16_t(fvar
->minorVersion
) != 0 ||
1814 uint16_t(fvar
->reserved
) != 2) {
1817 uint16_t axisCount
= fvar
->axisCount
;
1818 uint16_t axisSize
= fvar
->axisSize
;
1819 uint16_t instanceCount
= fvar
->instanceCount
;
1820 uint16_t instanceSize
= fvar
->instanceSize
;
1823 // https://www.microsoft.com/typography/otspec/fvar.htm#axisSize
1824 axisSize
!= 20 || // required value for current table version
1825 // https://www.microsoft.com/typography/otspec/fvar.htm#instanceSize
1826 (instanceSize
!= axisCount
* sizeof(int32_t) + 4 &&
1827 instanceSize
!= axisCount
* sizeof(int32_t) + 6)) {
1830 // Check that axis array will not exceed table size
1831 uint16_t axesOffset
= fvar
->axesArrayOffset
;
1832 if (axesOffset
+ uint32_t(axisCount
) * axisSize
> len
) {
1835 // Get pointer to the array of axis records
1836 auto axes
= reinterpret_cast<const AxisRecord
*>(data
+ axesOffset
);
1837 // Get address of instance array, and check it doesn't overflow table size.
1838 // https://www.microsoft.com/typography/otspec/fvar.htm#axisAndInstanceArrays
1839 auto instData
= data
+ axesOffset
+ axisCount
* axisSize
;
1840 if (instData
+ uint32_t(instanceCount
) * instanceSize
> data
+ len
) {
1844 aInstances
->SetCapacity(instanceCount
);
1845 for (unsigned i
= 0; i
< instanceCount
; ++i
, instData
+= instanceSize
) {
1846 // Typed pointer to the current instance record, to read its fields.
1847 auto inst
= reinterpret_cast<const InstanceRecord
*>(instData
);
1848 // Pointer to the coordinates array within the instance record.
1849 // This array has axisCount elements, and is included in instanceSize
1850 // (which depends on axisCount, and was validated above) so we know
1851 // access to coords[j] below will not be outside the table bounds.
1852 auto coords
= &inst
->coordinates
[0];
1853 gfxFontVariationInstance instance
;
1854 uint16_t nameID
= inst
->subfamilyNameID
;
1855 nsresult rv
= ReadCanonicalName(nameTable
, nameID
, instance
.mName
);
1856 if (NS_FAILED(rv
)) {
1857 // If no name was available for the instance, ignore it.
1860 instance
.mValues
.SetCapacity(axisCount
);
1861 for (unsigned j
= 0; j
< axisCount
; ++j
) {
1862 gfxFontVariationValue value
= {axes
[j
].axisTag
,
1863 int32_t(coords
[j
]) / 65536.0f
};
1864 instance
.mValues
.AppendElement(value
);
1866 aInstances
->AppendElement(std::move(instance
));
1870 aAxes
->SetCapacity(axisCount
);
1871 for (unsigned i
= 0; i
< axisCount
; ++i
) {
1872 if (uint16_t(axes
[i
].flags
) & HIDDEN_AXIS
) {
1875 gfxFontVariationAxis axis
;
1876 axis
.mTag
= axes
[i
].axisTag
;
1877 uint16_t nameID
= axes
[i
].axisNameID
;
1878 nsresult rv
= ReadCanonicalName(nameTable
, nameID
, axis
.mName
);
1879 if (NS_FAILED(rv
)) {
1880 axis
.mName
.Truncate(0);
1882 // Convert values from 16.16 fixed-point to float
1883 axis
.mMinValue
= int32_t(axes
[i
].minValue
) / 65536.0f
;
1884 axis
.mDefaultValue
= int32_t(axes
[i
].defaultValue
) / 65536.0f
;
1885 axis
.mMaxValue
= int32_t(axes
[i
].maxValue
) / 65536.0f
;
1886 aAxes
->AppendElement(axis
);
1891 void gfxFontUtils::ReadOtherFamilyNamesForFace(
1892 const nsACString
& aFamilyName
, const char* aNameData
, uint32_t aDataLength
,
1893 nsTArray
<nsCString
>& aOtherFamilyNames
, bool useFullName
) {
1894 const NameHeader
* nameHeader
= reinterpret_cast<const NameHeader
*>(aNameData
);
1896 uint32_t nameCount
= nameHeader
->count
;
1897 if (nameCount
* sizeof(NameRecord
) > aDataLength
) {
1898 NS_WARNING("invalid font (name records)");
1902 const NameRecord
* nameRecord
=
1903 reinterpret_cast<const NameRecord
*>(aNameData
+ sizeof(NameHeader
));
1904 uint32_t stringsBase
= uint32_t(nameHeader
->stringOffset
);
1906 for (uint32_t i
= 0; i
< nameCount
; i
++, nameRecord
++) {
1907 uint32_t nameLen
= nameRecord
->length
;
1909 nameRecord
->offset
; // offset from base of string storage
1911 if (stringsBase
+ nameOff
+ nameLen
> aDataLength
) {
1912 NS_WARNING("invalid font (name table strings)");
1916 uint16_t nameID
= nameRecord
->nameID
;
1917 if ((useFullName
&& nameID
== NAME_ID_FULL
) ||
1919 (nameID
== NAME_ID_FAMILY
|| nameID
== NAME_ID_PREFERRED_FAMILY
))) {
1920 nsAutoCString otherFamilyName
;
1921 bool ok
= DecodeFontName(
1922 aNameData
+ stringsBase
+ nameOff
, nameLen
,
1923 uint32_t(nameRecord
->platformID
), uint32_t(nameRecord
->encodingID
),
1924 uint32_t(nameRecord
->languageID
), otherFamilyName
);
1925 // add if not same as canonical family name
1926 if (ok
&& otherFamilyName
!= aFamilyName
&&
1927 !aOtherFamilyNames
.Contains(otherFamilyName
)) {
1928 aOtherFamilyNames
.AppendElement(otherFamilyName
);
1937 bool gfxFontUtils::IsCffFont(const uint8_t* aFontData
) {
1938 // this is only called after aFontData has passed basic validation,
1939 // so we know there is enough data present to allow us to read the version!
1940 const SFNTHeader
* sfntHeader
= reinterpret_cast<const SFNTHeader
*>(aFontData
);
1941 return (sfntHeader
->sfntVersion
== TRUETYPE_TAG('O', 'T', 'T', 'O'));
1946 #undef acceptablePlatform
1948 #undef isUVSEncoding