2 * Copyright (C) 2007, 2008, 2009, 2010, 2011 Apple Inc. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
7 * 1. Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * 2. Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
13 * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY
14 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
15 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
16 * DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY
17 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
18 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
19 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
20 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
21 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
22 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 #include "platform/fonts/mac/ComplexTextController.h"
29 #include "platform/fonts/Font.h"
30 #include "platform/fonts/FontCache.h"
31 #include "platform/text/TextRun.h"
33 #include <ApplicationServices/ApplicationServices.h>
34 #import <AvailabilityMacros.h>
36 // Forward declare Mac SPIs.
38 // Request for public API: rdar://13803619
39 CTLineRef CTLineCreateWithUniCharProvider(const UniChar* (*provide)(CFIndex stringIndex, CFIndex* charCount, CFDictionaryRef* attributes, void* context), void (*dispose)(const UniChar* chars, void* context), void* context);
42 @interface WebCascadeList : NSArray {
44 const blink::Font* _font;
47 Vector<RetainPtr<CTFontDescriptorRef>, 16> _fontDescriptors;
50 - (id)initWithFont:(const blink::Font*)font character:(UChar32)character;
54 @implementation WebCascadeList
56 - (id)initWithFont:(const blink::Font*)font character:(UChar32)character
58 if (!(self = [super init]))
62 _character = character;
64 // By the time a WebCascadeList is used, the Font has already been asked to realize all of its
65 // FontData, so this loop does not hit the FontCache.
66 while (_font->fontDataAt(_count))
77 - (id)objectAtIndex:(NSUInteger)index
79 CTFontDescriptorRef fontDescriptor;
80 if (index < _fontDescriptors.size()) {
81 if ((fontDescriptor = _fontDescriptors[index].get()))
82 return (id)fontDescriptor;
84 _fontDescriptors.grow(index + 1);
86 const blink::SimpleFontData* fontData = _font->fontDataAt(index)->fontDataForCharacter(_character);
87 fontDescriptor = CTFontCopyFontDescriptor(fontData->platformData().ctFont());
88 _fontDescriptors[index] = RetainPtr<CTFontDescriptorRef>(AdoptCF, fontDescriptor);
89 return (id)fontDescriptor;
96 ComplexTextController::ComplexTextRun::ComplexTextRun(CTRunRef ctRun, const SimpleFontData* fontData, const UChar* characters, unsigned stringLocation, size_t stringLength, CFRange runRange)
97 : m_fontData(fontData)
98 , m_characters(characters)
99 , m_stringLocation(stringLocation)
100 , m_stringLength(stringLength)
101 , m_indexBegin(runRange.location)
102 , m_indexEnd(runRange.location + runRange.length)
103 , m_isLTR(!(CTRunGetStatus(ctRun) & kCTRunStatusRightToLeft))
104 , m_isMonotonic(true)
106 m_glyphCount = CTRunGetGlyphCount(ctRun);
107 m_coreTextIndices = CTRunGetStringIndicesPtr(ctRun);
108 if (!m_coreTextIndices) {
109 m_coreTextIndicesVector.grow(m_glyphCount);
110 CTRunGetStringIndices(ctRun, CFRangeMake(0, 0), m_coreTextIndicesVector.data());
111 m_coreTextIndices = m_coreTextIndicesVector.data();
114 m_glyphs = CTRunGetGlyphsPtr(ctRun);
116 m_glyphsVector.grow(m_glyphCount);
117 CTRunGetGlyphs(ctRun, CFRangeMake(0, 0), m_glyphsVector.data());
118 m_glyphs = m_glyphsVector.data();
121 m_advances = CTRunGetAdvancesPtr(ctRun);
123 m_advancesVector.grow(m_glyphCount);
124 CTRunGetAdvances(ctRun, CFRangeMake(0, 0), m_advancesVector.data());
125 m_advances = m_advancesVector.data();
129 // Missing glyphs run constructor. Core Text will not generate a run of missing glyphs, instead falling back on
130 // glyphs from LastResort. We want to use the primary font's missing glyph in order to match the fast text code path.
131 ComplexTextController::ComplexTextRun::ComplexTextRun(const SimpleFontData* fontData, const UChar* characters, unsigned stringLocation, size_t stringLength, bool ltr)
132 : m_fontData(fontData)
133 , m_characters(characters)
134 , m_stringLocation(stringLocation)
135 , m_stringLength(stringLength)
137 , m_indexEnd(stringLength)
139 , m_isMonotonic(true)
141 m_coreTextIndicesVector.reserveInitialCapacity(m_stringLength);
143 while (r < m_stringLength) {
144 m_coreTextIndicesVector.uncheckedAppend(r);
145 if (U_IS_SURROGATE(m_characters[r])) {
146 ASSERT(r + 1 < m_stringLength);
147 ASSERT(U_IS_SURROGATE_LEAD(m_characters[r]));
148 ASSERT(U_IS_TRAIL(m_characters[r + 1]));
153 m_glyphCount = m_coreTextIndicesVector.size();
155 for (unsigned r = 0, end = m_glyphCount - 1; r < m_glyphCount / 2; ++r, --end)
156 std::swap(m_coreTextIndicesVector[r], m_coreTextIndicesVector[end]);
158 m_coreTextIndices = m_coreTextIndicesVector.data();
160 // Synthesize a run of missing glyphs.
161 m_glyphsVector.fill(0, m_glyphCount);
162 m_glyphs = m_glyphsVector.data();
163 m_advancesVector.fill(CGSizeMake(m_fontData->widthForGlyph(0), 0), m_glyphCount);
164 m_advances = m_advancesVector.data();
167 struct ProviderInfo {
170 CFDictionaryRef attributes;
173 static const UniChar* provideStringAndAttributes(CFIndex stringIndex, CFIndex* charCount, CFDictionaryRef* attributes, void* refCon)
175 ProviderInfo* info = static_cast<struct ProviderInfo*>(refCon);
176 if (stringIndex < 0 || static_cast<unsigned>(stringIndex) >= info->length)
179 *charCount = info->length - stringIndex;
180 *attributes = info->attributes;
181 return info->cp + stringIndex;
184 void ComplexTextController::collectComplexTextRunsForCharacters(const UChar* cp, unsigned length, unsigned stringLocation, const SimpleFontData* fontData)
187 // Create a run of missing glyphs from the primary font.
188 m_complexTextRuns.append(ComplexTextRun::create(m_font.primaryFont(), cp, stringLocation, length, m_run.ltr()));
192 bool isSystemFallback = false;
194 UChar32 baseCharacter = 0;
195 RetainPtr<CFDictionaryRef> stringAttributes;
196 if (fontData == SimpleFontData::systemFallback()) {
197 // FIXME: This code path does not support small caps.
198 isSystemFallback = true;
200 U16_GET(cp, 0, 0, length, baseCharacter);
201 fontData = m_font.fontDataAt(0)->fontDataForCharacter(baseCharacter);
203 RetainPtr<WebCascadeList> cascadeList(AdoptNS, [[WebCascadeList alloc] initWithFont:&m_font character:baseCharacter]);
205 stringAttributes.adoptCF(CFDictionaryCreateMutableCopy(kCFAllocatorDefault, 0, fontData->getCFStringAttributes(m_font.fontDescription().typesettingFeatures(), fontData->platformData().orientation())));
206 static const void* attributeKeys[] = { kCTFontCascadeListAttribute };
207 const void* values[] = { cascadeList.get() };
208 RetainPtr<CFDictionaryRef> attributes(AdoptCF, CFDictionaryCreate(kCFAllocatorDefault, attributeKeys, values, sizeof(attributeKeys) / sizeof(*attributeKeys), &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks));
209 RetainPtr<CTFontDescriptorRef> fontDescriptor(AdoptCF, CTFontDescriptorCreateWithAttributes(attributes.get()));
210 RetainPtr<CTFontRef> fontWithCascadeList(AdoptCF, CTFontCreateCopyWithAttributes(fontData->platformData().ctFont(), m_font.fontDescription().computedPixelSize(), 0, fontDescriptor.get()));
211 CFDictionarySetValue(const_cast<CFMutableDictionaryRef>(stringAttributes.get()), kCTFontAttributeName, fontWithCascadeList.get());
213 stringAttributes = fontData->getCFStringAttributes(m_font.fontDescription().typesettingFeatures(), fontData->platformData().orientation());
215 RetainPtr<CTLineRef> line;
217 if (!m_mayUseNaturalWritingDirection || m_run.directionalOverride()) {
218 static const void* optionKeys[] = { kCTTypesetterOptionForcedEmbeddingLevel };
219 const short ltrForcedEmbeddingLevelValue = 0;
220 const short rtlForcedEmbeddingLevelValue = 1;
221 static const void* ltrOptionValues[] = { CFNumberCreate(kCFAllocatorDefault, kCFNumberShortType, <rForcedEmbeddingLevelValue) };
222 static const void* rtlOptionValues[] = { CFNumberCreate(kCFAllocatorDefault, kCFNumberShortType, &rtlForcedEmbeddingLevelValue) };
223 static CFDictionaryRef ltrTypesetterOptions = CFDictionaryCreate(kCFAllocatorDefault, optionKeys, ltrOptionValues, WTF_ARRAY_LENGTH(optionKeys), &kCFCopyStringDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
224 static CFDictionaryRef rtlTypesetterOptions = CFDictionaryCreate(kCFAllocatorDefault, optionKeys, rtlOptionValues, WTF_ARRAY_LENGTH(optionKeys), &kCFCopyStringDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
226 #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
227 ProviderInfo info = { cp, length, stringAttributes.get() };
228 RetainPtr<CTTypesetterRef> typesetter(AdoptCF, WKCreateCTTypesetterWithUniCharProviderAndOptions(&provideStringAndAttributes, 0, &info, m_run.ltr() ? ltrTypesetterOptions : rtlTypesetterOptions));
230 RetainPtr<CFStringRef> string(AdoptCF, CFStringCreateWithCharactersNoCopy(kCFAllocatorDefault, cp, length, kCFAllocatorNull));
231 RetainPtr<CFAttributedStringRef> attributedString(AdoptCF, CFAttributedStringCreate(kCFAllocatorDefault, string.get(), stringAttributes.get()));
232 RetainPtr<CTTypesetterRef> typesetter(AdoptCF, CTTypesetterCreateWithAttributedStringAndOptions(attributedString.get(), m_run.ltr() ? ltrTypesetterOptions : rtlTypesetterOptions));
235 line.adoptCF(CTTypesetterCreateLine(typesetter.get(), CFRangeMake(0, 0)));
237 ProviderInfo info = { cp, length, stringAttributes.get() };
239 line.adoptCF(CTLineCreateWithUniCharProvider(&provideStringAndAttributes, 0, &info));
242 m_coreTextLines.append(line.get());
244 CFArrayRef runArray = CTLineGetGlyphRuns(line.get());
246 CFIndex runCount = CFArrayGetCount(runArray);
248 for (CFIndex r = 0; r < runCount; r++) {
249 CTRunRef ctRun = static_cast<CTRunRef>(CFArrayGetValueAtIndex(runArray, m_run.ltr() ? r : runCount - 1 - r));
250 ASSERT(CFGetTypeID(ctRun) == CTRunGetTypeID());
251 CFRange runRange = CTRunGetStringRange(ctRun);
252 const SimpleFontData* runFontData = fontData;
253 if (isSystemFallback) {
254 CFDictionaryRef runAttributes = CTRunGetAttributes(ctRun);
255 CTFontRef runFont = static_cast<CTFontRef>(CFDictionaryGetValue(runAttributes, kCTFontAttributeName));
256 ASSERT(CFGetTypeID(runFont) == CTFontGetTypeID());
257 if (!CFEqual(runFont, fontData->platformData().ctFont())) {
258 // Begin trying to see if runFont matches any of the fonts in the fallback list.
259 RetainPtr<CGFontRef> runCGFont(AdoptCF, CTFontCopyGraphicsFont(runFont, 0));
261 for (const FontData* candidateFontData = m_font.fontDataAt(i); candidateFontData; candidateFontData = m_font.fontDataAt(++i)) {
262 runFontData = candidateFontData->fontDataForCharacter(baseCharacter);
263 RetainPtr<CGFontRef> cgFont(AdoptCF, CTFontCopyGraphicsFont(runFontData->platformData().ctFont(), 0));
264 if (CFEqual(cgFont.get(), runCGFont.get()))
268 // If there is no matching font, look up by name in the font cache.
270 // Rather than using runFont as an NSFont and wrapping it in a FontPlatformData, go through
271 // the font cache and ultimately through NSFontManager in order to get an NSFont with the right
272 // NSFontRenderingMode.
273 RetainPtr<CFStringRef> fontName(AdoptCF, CTFontCopyPostScriptName(runFont));
274 if (CFEqual(fontName.get(), CFSTR("LastResort"))) {
275 m_complexTextRuns.append(ComplexTextRun::create(m_font.primaryFont(), cp, stringLocation + runRange.location, runRange.length, m_run.ltr()));
278 runFontData = FontCache::fontCache()->getFontData(m_font.fontDescription(), fontName.get(), false, DoNotRetain).get();
279 // Core Text may have used a font that is not known to NSFontManager. In that case, fall back on
280 // using the font as returned, even though it may not have the best NSFontRenderingMode.
282 FontPlatformData runFontPlatformData((NSFont *)runFont, CTFontGetSize(runFont));
283 runFontData = FontCache::fontCache()->fontDataFromFontPlatformData(&runFontPlatformData, DoNotRetain).get();
286 if (m_fallbackFonts && runFontData != m_font.primaryFont())
287 m_fallbackFonts->add(runFontData);
290 if (m_fallbackFonts && runFontData != m_font.primaryFont())
291 m_fallbackFonts->add(fontData);
293 m_complexTextRuns.append(ComplexTextRun::create(ctRun, runFontData, cp, stringLocation, length, runRange));