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