1/*
2 * Copyright (C) 2007, 2008, 2009, 2010, 2011 Apple Inc. All rights reserved.
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
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.
12 *
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.
23 */
24
25#include "config.h"
26
27#include "ComplexTextController.h"
28
29#include "Font.h"
30#include "FontCache.h"
31#include "TextRun.h"
32#include "WebCoreSystemInterface.h"
33
34#if PLATFORM(IOS)
35#include <CoreText/CoreText.h>
36#else
37#include <ApplicationServices/ApplicationServices.h>
38#endif
39
40@interface WebCascadeList : NSArray {
41    @private
42    const WebCore::Font* _font;
43    UChar32 _character;
44    NSUInteger _count;
45    Vector<RetainPtr<CTFontDescriptorRef>, 16> _fontDescriptors;
46}
47
48- (id)initWithFont:(const WebCore::Font*)font character:(UChar32)character;
49
50@end
51
52@implementation WebCascadeList
53
54- (id)initWithFont:(const WebCore::Font*)font character:(UChar32)character
55{
56    if (!(self = [super init]))
57        return nil;
58
59    _font = font;
60    _character = character;
61
62    // By the time a WebCascadeList is used, the Font has already been asked to realize all of its
63    // FontData, so this loop does not hit the FontCache.
64    while (_font->fontDataAt(_count))
65        _count++;
66
67    return self;
68}
69
70- (NSUInteger)count
71{
72    return _count;
73}
74
75- (id)objectAtIndex:(NSUInteger)index
76{
77    CTFontDescriptorRef fontDescriptor;
78    if (index < _fontDescriptors.size()) {
79        if ((fontDescriptor = _fontDescriptors[index].get()))
80            return (id)fontDescriptor;
81    } else
82        _fontDescriptors.grow(index + 1);
83
84    const WebCore::SimpleFontData* fontData = _font->fontDataAt(index)->fontDataForCharacter(_character);
85    fontDescriptor = CTFontCopyFontDescriptor(fontData->platformData().ctFont());
86    _fontDescriptors[index] = adoptCF(fontDescriptor);
87    return (id)fontDescriptor;
88}
89
90@end
91
92namespace WebCore {
93
94ComplexTextController::ComplexTextRun::ComplexTextRun(CTRunRef ctRun, const SimpleFontData* fontData, const UChar* characters, unsigned stringLocation, size_t stringLength, CFRange runRange)
95    : m_fontData(fontData)
96    , m_characters(characters)
97    , m_stringLocation(stringLocation)
98    , m_stringLength(stringLength)
99    , m_indexBegin(runRange.location)
100    , m_indexEnd(runRange.location + runRange.length)
101    , m_initialAdvance(wkCTRunGetInitialAdvance(ctRun))
102    , m_isLTR(!(CTRunGetStatus(ctRun) & kCTRunStatusRightToLeft))
103    , m_isMonotonic(true)
104{
105    m_glyphCount = CTRunGetGlyphCount(ctRun);
106    m_coreTextIndices = CTRunGetStringIndicesPtr(ctRun);
107    if (!m_coreTextIndices) {
108        m_coreTextIndicesVector.grow(m_glyphCount);
109        CTRunGetStringIndices(ctRun, CFRangeMake(0, 0), m_coreTextIndicesVector.data());
110        m_coreTextIndices = m_coreTextIndicesVector.data();
111    }
112
113    m_glyphs = CTRunGetGlyphsPtr(ctRun);
114    if (!m_glyphs) {
115        m_glyphsVector.grow(m_glyphCount);
116        CTRunGetGlyphs(ctRun, CFRangeMake(0, 0), m_glyphsVector.data());
117        m_glyphs = m_glyphsVector.data();
118    }
119
120    m_advances = CTRunGetAdvancesPtr(ctRun);
121    if (!m_advances) {
122        m_advancesVector.grow(m_glyphCount);
123        CTRunGetAdvances(ctRun, CFRangeMake(0, 0), m_advancesVector.data());
124        m_advances = m_advancesVector.data();
125    }
126}
127
128// Missing glyphs run constructor. Core Text will not generate a run of missing glyphs, instead falling back on
129// glyphs from LastResort. We want to use the primary font's missing glyph in order to match the fast text code path.
130ComplexTextController::ComplexTextRun::ComplexTextRun(const SimpleFontData* fontData, const UChar* characters, unsigned stringLocation, size_t stringLength, bool ltr)
131    : m_fontData(fontData)
132    , m_characters(characters)
133    , m_stringLocation(stringLocation)
134    , m_stringLength(stringLength)
135    , m_indexBegin(0)
136    , m_indexEnd(stringLength)
137    , m_initialAdvance(CGSizeZero)
138    , m_isLTR(ltr)
139    , m_isMonotonic(true)
140{
141    m_coreTextIndicesVector.reserveInitialCapacity(m_stringLength);
142    unsigned r = 0;
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]));
149            r += 2;
150        } else
151            r++;
152    }
153    m_glyphCount = m_coreTextIndicesVector.size();
154    if (!ltr) {
155        for (unsigned r = 0, end = m_glyphCount - 1; r < m_glyphCount / 2; ++r, --end)
156            std::swap(m_coreTextIndicesVector[r], m_coreTextIndicesVector[end]);
157    }
158    m_coreTextIndices = m_coreTextIndicesVector.data();
159
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();
165}
166
167struct ProviderInfo {
168    const UChar* cp;
169    unsigned length;
170    CFDictionaryRef attributes;
171};
172
173static const UniChar* provideStringAndAttributes(CFIndex stringIndex, CFIndex* charCount, CFDictionaryRef* attributes, void* refCon)
174{
175    ProviderInfo* info = static_cast<struct ProviderInfo*>(refCon);
176    if (stringIndex < 0 || static_cast<unsigned>(stringIndex) >= info->length)
177        return 0;
178
179    *charCount = info->length - stringIndex;
180    *attributes = info->attributes;
181    return info->cp + stringIndex;
182}
183
184void ComplexTextController::collectComplexTextRunsForCharacters(const UChar* cp, unsigned length, unsigned stringLocation, const SimpleFontData* fontData)
185{
186    if (!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()));
189        return;
190    }
191
192    bool isSystemFallback = false;
193
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;
199
200        U16_GET(cp, 0, 0, length, baseCharacter);
201        fontData = m_font.fontDataAt(0)->fontDataForCharacter(baseCharacter);
202
203        RetainPtr<WebCascadeList> cascadeList = adoptNS([[WebCascadeList alloc] initWithFont:&m_font character:baseCharacter]);
204
205        stringAttributes = adoptCF(CFDictionaryCreateMutableCopy(kCFAllocatorDefault, 0, fontData->getCFStringAttributes(m_font.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.pixelSize(), 0, fontDescriptor.get()));
211        CFDictionarySetValue(const_cast<CFMutableDictionaryRef>(stringAttributes.get()), kCTFontAttributeName, fontWithCascadeList.get());
212    } else
213        stringAttributes = fontData->getCFStringAttributes(m_font.typesettingFeatures(), fontData->platformData().orientation());
214
215    RetainPtr<CTLineRef> line;
216
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, &ltrForcedEmbeddingLevelValue) };
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);
225
226        ProviderInfo info = { cp, length, stringAttributes.get() };
227        RetainPtr<CTTypesetterRef> typesetter = adoptCF(wkCreateCTTypesetterWithUniCharProviderAndOptions(&provideStringAndAttributes, 0, &info, m_run.ltr() ? ltrTypesetterOptions : rtlTypesetterOptions));
228
229        line = adoptCF(CTTypesetterCreateLine(typesetter.get(), CFRangeMake(0, 0)));
230    } else {
231        ProviderInfo info = { cp, length, stringAttributes.get() };
232
233        line = adoptCF(wkCreateCTLineWithUniCharProvider(&provideStringAndAttributes, 0, &info));
234    }
235
236    m_coreTextLines.append(line.get());
237
238    CFArrayRef runArray = CTLineGetGlyphRuns(line.get());
239
240    CFIndex runCount = CFArrayGetCount(runArray);
241
242    for (CFIndex r = 0; r < runCount; r++) {
243        CTRunRef ctRun = static_cast<CTRunRef>(CFArrayGetValueAtIndex(runArray, m_run.ltr() ? r : runCount - 1 - r));
244        ASSERT(CFGetTypeID(ctRun) == CTRunGetTypeID());
245        CFRange runRange = CTRunGetStringRange(ctRun);
246        const SimpleFontData* runFontData = fontData;
247        if (isSystemFallback) {
248            CFDictionaryRef runAttributes = CTRunGetAttributes(ctRun);
249            CTFontRef runFont = static_cast<CTFontRef>(CFDictionaryGetValue(runAttributes, kCTFontAttributeName));
250            ASSERT(CFGetTypeID(runFont) == CTFontGetTypeID());
251            if (!CFEqual(runFont, fontData->platformData().ctFont())) {
252                // Begin trying to see if runFont matches any of the fonts in the fallback list.
253                RetainPtr<CGFontRef> runCGFont = adoptCF(CTFontCopyGraphicsFont(runFont, 0));
254                unsigned i = 0;
255                for (const FontData* candidateFontData = m_font.fontDataAt(i); candidateFontData; candidateFontData = m_font.fontDataAt(++i)) {
256                    runFontData = candidateFontData->fontDataForCharacter(baseCharacter);
257                    RetainPtr<CGFontRef> cgFont = adoptCF(CTFontCopyGraphicsFont(runFontData->platformData().ctFont(), 0));
258                    if (CFEqual(cgFont.get(), runCGFont.get()))
259                        break;
260                    runFontData = 0;
261                }
262                // If there is no matching font, look up by name in the font cache.
263                if (!runFontData) {
264                    // Rather than using runFont as an NSFont and wrapping it in a FontPlatformData, go through
265                    // the font cache and ultimately through NSFontManager in order to get an NSFont with the right
266                    // NSFontRenderingMode.
267                    RetainPtr<CFStringRef> fontName = adoptCF(CTFontCopyPostScriptName(runFont));
268                    if (CFEqual(fontName.get(), CFSTR("LastResort"))) {
269                        m_complexTextRuns.append(ComplexTextRun::create(m_font.primaryFont(), cp, stringLocation + runRange.location, runRange.length, m_run.ltr()));
270                        continue;
271                    }
272                    runFontData = fontCache().getCachedFontData(m_font.fontDescription(), fontName.get(), false, FontCache::DoNotRetain).get();
273#if !PLATFORM(IOS)
274                    // Core Text may have used a font that is not known to NSFontManager. In that case, fall back on
275                    // using the font as returned, even though it may not have the best NSFontRenderingMode.
276                    if (!runFontData) {
277                        FontPlatformData runFontPlatformData((NSFont *)runFont, CTFontGetSize(runFont), m_font.fontDescription().usePrinterFont());
278                        runFontData = fontCache().getCachedFontData(&runFontPlatformData, FontCache::DoNotRetain).get();
279                    }
280#else
281                    // FIXME: Just assert for now, until we can devise a better fix that works with iOS.
282                    ASSERT(runFontData);
283#endif
284                }
285                if (m_fallbackFonts && runFontData != m_font.primaryFont())
286                    m_fallbackFonts->add(runFontData);
287            }
288        }
289        if (m_fallbackFonts && runFontData != m_font.primaryFont())
290            m_fallbackFonts->add(fontData);
291
292        m_complexTextRuns.append(ComplexTextRun::create(ctRun, runFontData, cp, stringLocation, length, runRange));
293    }
294}
295
296} // namespace WebCore
297