no bug - Bumping Firefox l10n changesets r=release a=l10n-bump DONTBUILD CLOSED TREE
[gecko.git] / gfx / thebes / gfxCoreTextShaper.cpp
blobc0a1c83875f9cb2822ebd4850a5cc13a1338e22a
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 "gfxCoreTextShaper.h"
8 #include "gfxMacFont.h"
9 #include "gfxFontUtils.h"
10 #include "gfxTextRun.h"
11 #include "mozilla/gfx/2D.h"
12 #include "mozilla/gfx/ScaledFontMac.h"
13 #include "mozilla/UniquePtrExtensions.h"
15 #include <algorithm>
17 #include <dlfcn.h>
19 using namespace mozilla;
20 using namespace mozilla::gfx;
22 // standard font descriptors that we construct the first time they're needed
23 CTFontDescriptorRef gfxCoreTextShaper::sFeaturesDescriptor[kMaxFontInstances];
25 // Helper to create a CFDictionary with the right attributes for shaping our
26 // text, including imposing the given directionality.
27 CFDictionaryRef gfxCoreTextShaper::CreateAttrDict(bool aRightToLeft) {
28 // Because we always shape unidirectional runs, and may have applied
29 // directional overrides, we want to force a direction rather than
30 // allowing CoreText to do its own unicode-based bidi processing.
31 SInt16 dirOverride = kCTWritingDirectionOverride |
32 (aRightToLeft ? kCTWritingDirectionRightToLeft
33 : kCTWritingDirectionLeftToRight);
34 CFNumberRef dirNumber =
35 ::CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt16Type, &dirOverride);
36 CFArrayRef dirArray = ::CFArrayCreate(
37 kCFAllocatorDefault, (const void**)&dirNumber, 1, &kCFTypeArrayCallBacks);
38 ::CFRelease(dirNumber);
39 CFTypeRef attrs[] = {kCTFontAttributeName, kCTWritingDirectionAttributeName};
40 CFTypeRef values[] = {mCTFont[0], dirArray};
41 CFDictionaryRef attrDict = ::CFDictionaryCreate(
42 kCFAllocatorDefault, attrs, values, ArrayLength(attrs),
43 &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
44 ::CFRelease(dirArray);
45 return attrDict;
48 gfxCoreTextShaper::gfxCoreTextShaper(gfxMacFont* aFont)
49 : gfxFontShaper(aFont),
50 mAttributesDictLTR(nullptr),
51 mAttributesDictRTL(nullptr) {
52 for (size_t i = 0; i < kMaxFontInstances; i++) {
53 mCTFont[i] = nullptr;
55 // Create our default CTFontRef
56 mCTFont[0] = CreateCTFontWithFeatures(
57 aFont->GetAdjustedSize(), GetFeaturesDescriptor(kDefaultFeatures));
60 gfxCoreTextShaper::~gfxCoreTextShaper() {
61 if (mAttributesDictLTR) {
62 ::CFRelease(mAttributesDictLTR);
64 if (mAttributesDictRTL) {
65 ::CFRelease(mAttributesDictRTL);
67 for (size_t i = 0; i < kMaxFontInstances; i++) {
68 if (mCTFont[i]) {
69 ::CFRelease(mCTFont[i]);
74 static bool IsBuggyIndicScript(intl::Script aScript) {
75 return aScript == intl::Script::BENGALI || aScript == intl::Script::KANNADA ||
76 aScript == intl::Script::ORIYA || aScript == intl::Script::KHMER;
79 bool gfxCoreTextShaper::ShapeText(DrawTarget* aDrawTarget,
80 const char16_t* aText, uint32_t aOffset,
81 uint32_t aLength, Script aScript,
82 nsAtom* aLanguage, bool aVertical,
83 RoundingFlags aRounding,
84 gfxShapedText* aShapedText) {
85 // Create a CFAttributedString with text and style info, so we can use
86 // CoreText to lay it out.
87 bool isRightToLeft = aShapedText->IsRightToLeft();
88 const UniChar* text = reinterpret_cast<const UniChar*>(aText);
90 CFStringRef stringObj = ::CFStringCreateWithCharactersNoCopy(
91 kCFAllocatorDefault, text, aLength, kCFAllocatorNull);
93 // Figure out whether we should try to set the AAT small-caps feature:
94 // examine OpenType tags for the requested style, and see if 'smcp' is
95 // among them.
96 const gfxFontStyle* style = mFont->GetStyle();
97 gfxFontEntry* entry = mFont->GetFontEntry();
98 auto handleFeatureTag = [](uint32_t aTag, uint32_t aValue,
99 void* aUserArg) -> void {
100 if (aTag == HB_TAG('s', 'm', 'c', 'p') && aValue) {
101 *static_cast<bool*>(aUserArg) = true;
104 bool addSmallCaps = false;
105 MergeFontFeatures(style, entry->mFeatureSettings, false, entry->FamilyName(),
106 false, handleFeatureTag, &addSmallCaps);
108 // Get an attributes dictionary suitable for shaping text in the
109 // current direction, creating it if necessary.
110 CFDictionaryRef attrObj =
111 isRightToLeft ? mAttributesDictRTL : mAttributesDictLTR;
112 if (!attrObj) {
113 attrObj = CreateAttrDict(isRightToLeft);
114 (isRightToLeft ? mAttributesDictRTL : mAttributesDictLTR) = attrObj;
117 FeatureFlags featureFlags = kDefaultFeatures;
118 if (IsBuggyIndicScript(aScript)) {
119 // To work around buggy Indic AAT fonts shipped with OS X,
120 // we re-enable the Line Initial Smart Swashes feature that is needed
121 // for "split vowels" to work in at least Bengali and Kannada fonts.
122 // Affected fonts include Bangla MN, Bangla Sangam MN, Kannada MN,
123 // Kannada Sangam MN. See bugs 686225, 728557, 953231, 1145515.
124 // Also applies to Oriya and Khmer, see bug 1370927 and bug 1403166.
125 featureFlags |= kIndicFeatures;
127 if (aShapedText->DisableLigatures()) {
128 // For letterspacing (or maybe other situations) we need to make
129 // a copy of the CTFont with the ligature feature disabled.
130 featureFlags |= kDisableLigatures;
132 if (addSmallCaps) {
133 featureFlags |= kAddSmallCaps;
136 // For the disabled-ligature, buggy-indic-font or small-caps case, replace
137 // the default CTFont in the attribute dictionary with a tweaked version.
138 CFMutableDictionaryRef mutableAttr = nullptr;
139 if (featureFlags != 0) {
140 if (!mCTFont[featureFlags]) {
141 mCTFont[featureFlags] = CreateCTFontWithFeatures(
142 mFont->GetAdjustedSize(), GetFeaturesDescriptor(featureFlags));
144 mutableAttr =
145 ::CFDictionaryCreateMutableCopy(kCFAllocatorDefault, 2, attrObj);
146 ::CFDictionaryReplaceValue(mutableAttr, kCTFontAttributeName,
147 mCTFont[featureFlags]);
148 attrObj = mutableAttr;
151 // Now we can create an attributed string
152 CFAttributedStringRef attrStringObj =
153 ::CFAttributedStringCreate(kCFAllocatorDefault, stringObj, attrObj);
154 ::CFRelease(stringObj);
156 // Create the CoreText line from our string, then we're done with it
157 CTLineRef line = ::CTLineCreateWithAttributedString(attrStringObj);
158 ::CFRelease(attrStringObj);
160 // and finally retrieve the glyph data and store into the gfxTextRun
161 CFArrayRef glyphRuns = ::CTLineGetGlyphRuns(line);
162 uint32_t numRuns = ::CFArrayGetCount(glyphRuns);
164 // Iterate through the glyph runs.
165 bool success = true;
166 for (uint32_t runIndex = 0; runIndex < numRuns; runIndex++) {
167 CTRunRef aCTRun = (CTRunRef)::CFArrayGetValueAtIndex(glyphRuns, runIndex);
168 CFRange range = ::CTRunGetStringRange(aCTRun);
169 CFDictionaryRef runAttr = ::CTRunGetAttributes(aCTRun);
170 if (runAttr != attrObj) {
171 // If Core Text manufactured a new dictionary, this may indicate
172 // unexpected font substitution. In that case, we fail (and fall
173 // back to harfbuzz shaping)...
174 const void* font1 = ::CFDictionaryGetValue(attrObj, kCTFontAttributeName);
175 const void* font2 = ::CFDictionaryGetValue(runAttr, kCTFontAttributeName);
176 if (font1 != font2) {
177 // ...except that if the fallback was only for a variation
178 // selector or join control that is otherwise unsupported,
179 // we just ignore it.
180 if (range.length == 1) {
181 char16_t ch = aText[range.location];
182 if (gfxFontUtils::IsJoinControl(ch) ||
183 gfxFontUtils::IsVarSelector(ch)) {
184 continue;
187 NS_WARNING("unexpected font fallback in Core Text");
188 success = false;
189 break;
192 if (SetGlyphsFromRun(aShapedText, aOffset, aLength, aCTRun) != NS_OK) {
193 success = false;
194 break;
198 if (mutableAttr) {
199 ::CFRelease(mutableAttr);
201 ::CFRelease(line);
203 return success;
206 #define SMALL_GLYPH_RUN \
207 128 // preallocated size of our auto arrays for per-glyph data;
208 // some testing indicates that 90%+ of glyph runs will fit
209 // without requiring a separate allocation
211 nsresult gfxCoreTextShaper::SetGlyphsFromRun(gfxShapedText* aShapedText,
212 uint32_t aOffset, uint32_t aLength,
213 CTRunRef aCTRun) {
214 typedef gfxShapedText::CompressedGlyph CompressedGlyph;
216 int32_t direction = aShapedText->IsRightToLeft() ? -1 : 1;
218 int32_t numGlyphs = ::CTRunGetGlyphCount(aCTRun);
219 if (numGlyphs == 0) {
220 return NS_OK;
223 int32_t wordLength = aLength;
225 // character offsets get really confusing here, as we have to keep track of
226 // (a) the text in the actual textRun we're constructing
227 // (c) the string that was handed to CoreText, which contains the text of
228 // the font run
229 // (d) the CTRun currently being processed, which may be a sub-run of the
230 // CoreText line
232 // get the source string range within the CTLine's text
233 CFRange stringRange = ::CTRunGetStringRange(aCTRun);
234 // skip the run if it is entirely outside the actual range of the font run
235 if (stringRange.location + stringRange.length <= 0 ||
236 stringRange.location >= wordLength) {
237 return NS_OK;
240 // retrieve the laid-out glyph data from the CTRun
241 UniquePtr<CGGlyph[]> glyphsArray;
242 UniquePtr<CGPoint[]> positionsArray;
243 UniquePtr<CFIndex[]> glyphToCharArray;
244 const CGGlyph* glyphs = nullptr;
245 const CGPoint* positions = nullptr;
246 const CFIndex* glyphToChar = nullptr;
248 // Testing indicates that CTRunGetGlyphsPtr (almost?) always succeeds,
249 // and so allocating a new array and copying data with CTRunGetGlyphs
250 // will be extremely rare.
251 // If this were not the case, we could use an AutoTArray<> to
252 // try and avoid the heap allocation for small runs.
253 // It's possible that some future change to CoreText will mean that
254 // CTRunGetGlyphsPtr fails more often; if this happens, AutoTArray<>
255 // may become an attractive option.
256 glyphs = ::CTRunGetGlyphsPtr(aCTRun);
257 if (!glyphs) {
258 glyphsArray = MakeUniqueFallible<CGGlyph[]>(numGlyphs);
259 if (!glyphsArray) {
260 return NS_ERROR_OUT_OF_MEMORY;
262 ::CTRunGetGlyphs(aCTRun, ::CFRangeMake(0, 0), glyphsArray.get());
263 glyphs = glyphsArray.get();
266 positions = ::CTRunGetPositionsPtr(aCTRun);
267 if (!positions) {
268 positionsArray = MakeUniqueFallible<CGPoint[]>(numGlyphs);
269 if (!positionsArray) {
270 return NS_ERROR_OUT_OF_MEMORY;
272 ::CTRunGetPositions(aCTRun, ::CFRangeMake(0, 0), positionsArray.get());
273 positions = positionsArray.get();
276 // Remember that the glyphToChar indices relate to the CoreText line,
277 // not to the beginning of the textRun, the font run,
278 // or the stringRange of the glyph run
279 glyphToChar = ::CTRunGetStringIndicesPtr(aCTRun);
280 if (!glyphToChar) {
281 glyphToCharArray = MakeUniqueFallible<CFIndex[]>(numGlyphs);
282 if (!glyphToCharArray) {
283 return NS_ERROR_OUT_OF_MEMORY;
285 ::CTRunGetStringIndices(aCTRun, ::CFRangeMake(0, 0),
286 glyphToCharArray.get());
287 glyphToChar = glyphToCharArray.get();
290 double runWidth = ::CTRunGetTypographicBounds(aCTRun, ::CFRangeMake(0, 0),
291 nullptr, nullptr, nullptr);
293 AutoTArray<gfxShapedText::DetailedGlyph, 1> detailedGlyphs;
294 CompressedGlyph* charGlyphs = aShapedText->GetCharacterGlyphs() + aOffset;
296 // CoreText gives us the glyphindex-to-charindex mapping, which relates each
297 // glyph to a source text character; we also need the charindex-to-glyphindex
298 // mapping to find the glyph for a given char. Note that some chars may not
299 // map to any glyph (ligature continuations), and some may map to several
300 // glyphs (eg Indic split vowels). We set the glyph index to NO_GLYPH for
301 // chars that have no associated glyph, and we record the last glyph index for
302 // cases where the char maps to several glyphs, so that our clumping will
303 // include all the glyph fragments for the character.
305 // The charToGlyph array is indexed by char position within the stringRange of
306 // the glyph run.
308 static const int32_t NO_GLYPH = -1;
309 AutoTArray<int32_t, SMALL_GLYPH_RUN> charToGlyphArray;
310 if (!charToGlyphArray.SetLength(stringRange.length, fallible)) {
311 return NS_ERROR_OUT_OF_MEMORY;
313 int32_t* charToGlyph = charToGlyphArray.Elements();
314 for (int32_t offset = 0; offset < stringRange.length; ++offset) {
315 charToGlyph[offset] = NO_GLYPH;
317 for (int32_t i = 0; i < numGlyphs; ++i) {
318 int32_t loc = glyphToChar[i] - stringRange.location;
319 if (loc >= 0 && loc < stringRange.length) {
320 charToGlyph[loc] = i;
324 // Find character and glyph clumps that correspond, allowing for ligatures,
325 // indic reordering, split glyphs, etc.
327 // The idea is that we'll find a character sequence starting at the first char
328 // of stringRange, and extend it until it includes the character associated
329 // with the first glyph; we also extend it as long as there are "holes" in the
330 // range of glyphs. So we will eventually have a contiguous sequence of
331 // characters, starting at the beginning of the range, that map to a
332 // contiguous sequence of glyphs, starting at the beginning of the glyph
333 // array. That's a clump; then we update the starting positions and repeat.
335 // NB: In the case of RTL layouts, we iterate over the stringRange in reverse.
338 // This may find characters that fall outside the range 0:wordLength,
339 // so we won't necessarily use everything we find here.
341 bool isRightToLeft = aShapedText->IsRightToLeft();
342 int32_t glyphStart =
343 0; // looking for a clump that starts at this glyph index
344 int32_t charStart =
345 isRightToLeft
346 ? stringRange.length - 1
347 : 0; // and this char index (in the stringRange of the glyph run)
349 while (glyphStart <
350 numGlyphs) { // keep finding groups until all glyphs are accounted for
351 bool inOrder = true;
352 int32_t charEnd = glyphToChar[glyphStart] - stringRange.location;
353 NS_WARNING_ASSERTION(charEnd >= 0 && charEnd < stringRange.length,
354 "glyph-to-char mapping points outside string range");
355 // clamp charEnd to the valid range of the string
356 charEnd = std::max(charEnd, 0);
357 charEnd = std::min(charEnd, int32_t(stringRange.length));
359 int32_t glyphEnd = glyphStart;
360 int32_t charLimit = isRightToLeft ? -1 : stringRange.length;
361 do {
362 // This is normally executed once for each iteration of the outer loop,
363 // but in unusual cases where the character/glyph association is complex,
364 // the initial character range might correspond to a non-contiguous
365 // glyph range with "holes" in it. If so, we will repeat this loop to
366 // extend the character range until we have a contiguous glyph sequence.
367 NS_ASSERTION((direction > 0 && charEnd < charLimit) ||
368 (direction < 0 && charEnd > charLimit),
369 "no characters left in range?");
370 charEnd += direction;
371 while (charEnd != charLimit && charToGlyph[charEnd] == NO_GLYPH) {
372 charEnd += direction;
375 // find the maximum glyph index covered by the clump so far
376 if (isRightToLeft) {
377 for (int32_t i = charStart; i > charEnd; --i) {
378 if (charToGlyph[i] != NO_GLYPH) {
379 // update extent of glyph range
380 glyphEnd = std::max(glyphEnd, charToGlyph[i] + 1);
383 } else {
384 for (int32_t i = charStart; i < charEnd; ++i) {
385 if (charToGlyph[i] != NO_GLYPH) {
386 // update extent of glyph range
387 glyphEnd = std::max(glyphEnd, charToGlyph[i] + 1);
392 if (glyphEnd == glyphStart + 1) {
393 // for the common case of a single-glyph clump, we can skip the
394 // following checks
395 break;
398 if (glyphEnd == glyphStart) {
399 // no glyphs, try to extend the clump
400 continue;
403 // check whether all glyphs in the range are associated with the
404 // characters in our clump; if not, we have a discontinuous range, and
405 // should extend it unless we've reached the end of the text
406 bool allGlyphsAreWithinCluster = true;
407 int32_t prevGlyphCharIndex = charStart;
408 for (int32_t i = glyphStart; i < glyphEnd; ++i) {
409 int32_t glyphCharIndex = glyphToChar[i] - stringRange.location;
410 if (isRightToLeft) {
411 if (glyphCharIndex > charStart || glyphCharIndex <= charEnd) {
412 allGlyphsAreWithinCluster = false;
413 break;
415 if (glyphCharIndex > prevGlyphCharIndex) {
416 inOrder = false;
418 prevGlyphCharIndex = glyphCharIndex;
419 } else {
420 if (glyphCharIndex < charStart || glyphCharIndex >= charEnd) {
421 allGlyphsAreWithinCluster = false;
422 break;
424 if (glyphCharIndex < prevGlyphCharIndex) {
425 inOrder = false;
427 prevGlyphCharIndex = glyphCharIndex;
430 if (allGlyphsAreWithinCluster) {
431 break;
433 } while (charEnd != charLimit);
435 NS_WARNING_ASSERTION(glyphStart < glyphEnd,
436 "character/glyph clump contains no glyphs!");
437 if (glyphStart == glyphEnd) {
438 ++glyphStart; // make progress - avoid potential infinite loop
439 charStart = charEnd;
440 continue;
443 NS_WARNING_ASSERTION(charStart != charEnd,
444 "character/glyph clump contains no characters!");
445 if (charStart == charEnd) {
446 glyphStart = glyphEnd; // this is bad - we'll discard the glyph(s),
447 // as there's nowhere to attach them
448 continue;
451 // Now charStart..charEnd is a ligature clump, corresponding to
452 // glyphStart..glyphEnd; Set baseCharIndex to the char we'll actually attach
453 // the glyphs to (1st of ligature), and endCharIndex to the limit (position
454 // beyond the last char), adjusting for the offset of the stringRange
455 // relative to the textRun.
456 int32_t baseCharIndex, endCharIndex;
457 if (isRightToLeft) {
458 while (charEnd >= 0 && charToGlyph[charEnd] == NO_GLYPH) {
459 charEnd--;
461 baseCharIndex = charEnd + stringRange.location + 1;
462 endCharIndex = charStart + stringRange.location + 1;
463 } else {
464 while (charEnd < stringRange.length && charToGlyph[charEnd] == NO_GLYPH) {
465 charEnd++;
467 baseCharIndex = charStart + stringRange.location;
468 endCharIndex = charEnd + stringRange.location;
471 // Then we check if the clump falls outside our actual string range; if so,
472 // just go to the next.
473 if (endCharIndex <= 0 || baseCharIndex >= wordLength) {
474 glyphStart = glyphEnd;
475 charStart = charEnd;
476 continue;
478 // Ensure we won't try to go beyond the valid length of the word's text
479 baseCharIndex = std::max(baseCharIndex, 0);
480 endCharIndex = std::min(endCharIndex, wordLength);
482 // Now we're ready to set the glyph info in the textRun; measure the glyph
483 // width of the first (perhaps only) glyph, to see if it is "Simple"
484 int32_t appUnitsPerDevUnit = aShapedText->GetAppUnitsPerDevUnit();
485 double toNextGlyph;
486 if (glyphStart < numGlyphs - 1) {
487 toNextGlyph = positions[glyphStart + 1].x - positions[glyphStart].x;
488 } else {
489 toNextGlyph = positions[0].x + runWidth - positions[glyphStart].x;
491 int32_t advance = int32_t(toNextGlyph * appUnitsPerDevUnit);
493 // Check if it's a simple one-to-one mapping
494 int32_t glyphsInClump = glyphEnd - glyphStart;
495 if (glyphsInClump == 1 &&
496 gfxTextRun::CompressedGlyph::IsSimpleGlyphID(glyphs[glyphStart]) &&
497 gfxTextRun::CompressedGlyph::IsSimpleAdvance(advance) &&
498 charGlyphs[baseCharIndex].IsClusterStart() &&
499 positions[glyphStart].y == 0.0) {
500 charGlyphs[baseCharIndex].SetSimpleGlyph(advance, glyphs[glyphStart]);
501 } else {
502 // collect all glyphs in a list to be assigned to the first char;
503 // there must be at least one in the clump, and we already measured its
504 // advance, hence the placement of the loop-exit test and the measurement
505 // of the next glyph
506 while (true) {
507 gfxTextRun::DetailedGlyph* details = detailedGlyphs.AppendElement();
508 details->mGlyphID = glyphs[glyphStart];
509 details->mOffset.y = -positions[glyphStart].y * appUnitsPerDevUnit;
510 details->mAdvance = advance;
511 if (++glyphStart >= glyphEnd) {
512 break;
514 if (glyphStart < numGlyphs - 1) {
515 toNextGlyph = positions[glyphStart + 1].x - positions[glyphStart].x;
516 } else {
517 toNextGlyph = positions[0].x + runWidth - positions[glyphStart].x;
519 advance = int32_t(toNextGlyph * appUnitsPerDevUnit);
522 aShapedText->SetDetailedGlyphs(aOffset + baseCharIndex,
523 detailedGlyphs.Length(),
524 detailedGlyphs.Elements());
526 detailedGlyphs.Clear();
529 // the rest of the chars in the group are ligature continuations, no
530 // associated glyphs
531 while (++baseCharIndex != endCharIndex && baseCharIndex < wordLength) {
532 CompressedGlyph& shapedTextGlyph = charGlyphs[baseCharIndex];
533 NS_ASSERTION(!shapedTextGlyph.IsSimpleGlyph(),
534 "overwriting a simple glyph");
535 shapedTextGlyph.SetComplex(inOrder && shapedTextGlyph.IsClusterStart(),
536 false);
539 glyphStart = glyphEnd;
540 charStart = charEnd;
543 return NS_OK;
546 #undef SMALL_GLYPH_RUN
548 // Construct the font attribute descriptor that we'll apply by default when
549 // creating a CTFontRef. This will turn off line-edge swashes by default,
550 // because we don't know the actual line breaks when doing glyph shaping.
552 // We also cache feature descriptors for shaping with disabled ligatures, and
553 // for buggy Indic AAT font workarounds, created on an as-needed basis.
555 #define MAX_FEATURES 5 // max used by any of our Get*Descriptor functions
557 CTFontDescriptorRef gfxCoreTextShaper::CreateFontFeaturesDescriptor(
558 const std::pair<SInt16, SInt16>* aFeatures, size_t aCount) {
559 MOZ_ASSERT(aCount <= MAX_FEATURES);
561 CFDictionaryRef featureSettings[MAX_FEATURES];
563 for (size_t i = 0; i < aCount; i++) {
564 CFNumberRef type = ::CFNumberCreate(
565 kCFAllocatorDefault, kCFNumberSInt16Type, &aFeatures[i].first);
566 CFNumberRef selector = ::CFNumberCreate(
567 kCFAllocatorDefault, kCFNumberSInt16Type, &aFeatures[i].second);
569 CFTypeRef keys[] = {kCTFontFeatureTypeIdentifierKey,
570 kCTFontFeatureSelectorIdentifierKey};
571 CFTypeRef values[] = {type, selector};
572 featureSettings[i] = ::CFDictionaryCreate(
573 kCFAllocatorDefault, (const void**)keys, (const void**)values,
574 ArrayLength(keys), &kCFTypeDictionaryKeyCallBacks,
575 &kCFTypeDictionaryValueCallBacks);
577 ::CFRelease(selector);
578 ::CFRelease(type);
581 CFArrayRef featuresArray =
582 ::CFArrayCreate(kCFAllocatorDefault, (const void**)featureSettings,
583 aCount, // not ArrayLength(featureSettings), as we
584 // may not have used all the allocated slots
585 &kCFTypeArrayCallBacks);
587 for (size_t i = 0; i < aCount; i++) {
588 ::CFRelease(featureSettings[i]);
591 const CFTypeRef attrKeys[] = {kCTFontFeatureSettingsAttribute};
592 const CFTypeRef attrValues[] = {featuresArray};
593 CFDictionaryRef attributesDict = ::CFDictionaryCreate(
594 kCFAllocatorDefault, (const void**)attrKeys, (const void**)attrValues,
595 ArrayLength(attrKeys), &kCFTypeDictionaryKeyCallBacks,
596 &kCFTypeDictionaryValueCallBacks);
597 ::CFRelease(featuresArray);
599 CTFontDescriptorRef descriptor =
600 ::CTFontDescriptorCreateWithAttributes(attributesDict);
601 ::CFRelease(attributesDict);
603 return descriptor;
606 CTFontDescriptorRef gfxCoreTextShaper::GetFeaturesDescriptor(
607 FeatureFlags aFeatureFlags) {
608 MOZ_ASSERT(aFeatureFlags < kMaxFontInstances);
609 if (!sFeaturesDescriptor[aFeatureFlags]) {
610 typedef std::pair<SInt16, SInt16> FeatT;
611 AutoTArray<FeatT, MAX_FEATURES> features;
612 features.AppendElement(
613 FeatT(kSmartSwashType, kLineFinalSwashesOffSelector));
614 if ((aFeatureFlags & kIndicFeatures) == 0) {
615 features.AppendElement(
616 FeatT(kSmartSwashType, kLineInitialSwashesOffSelector));
618 if (aFeatureFlags & kAddSmallCaps) {
619 features.AppendElement(FeatT(kLetterCaseType, kSmallCapsSelector));
620 features.AppendElement(
621 FeatT(kLowerCaseType, kLowerCaseSmallCapsSelector));
623 if (aFeatureFlags & kDisableLigatures) {
624 features.AppendElement(
625 FeatT(kLigaturesType, kCommonLigaturesOffSelector));
627 MOZ_ASSERT(features.Length() <= MAX_FEATURES);
628 sFeaturesDescriptor[aFeatureFlags] =
629 CreateFontFeaturesDescriptor(features.Elements(), features.Length());
631 return sFeaturesDescriptor[aFeatureFlags];
634 CTFontRef gfxCoreTextShaper::CreateCTFontWithFeatures(
635 CGFloat aSize, CTFontDescriptorRef aDescriptor) {
636 const gfxFontEntry* fe = mFont->GetFontEntry();
637 bool isInstalledFont = !fe->IsUserFont() || fe->IsLocalUserFont();
638 CGFontRef cgFont = static_cast<gfxMacFont*>(mFont)->GetCGFontRef();
639 return CreateCTFontFromCGFontWithVariations(cgFont, aSize, isInstalledFont,
640 aDescriptor);
643 void gfxCoreTextShaper::Shutdown() // [static]
645 for (size_t i = 0; i < kMaxFontInstances; i++) {
646 if (sFeaturesDescriptor[i] != nullptr) {
647 ::CFRelease(sFeaturesDescriptor[i]);
648 sFeaturesDescriptor[i] = nullptr;