tizen beta release
[profile/ivi/webkit-efl.git] / Source / WebCore / platform / graphics / mac / ComplexTextControllerCoreText.mm
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 #if USE(CORE_TEXT)
28
29 #include "ComplexTextController.h"
30
31 #include "Font.h"
32 #include "FontCache.h"
33 #include "TextRun.h"
34 #include "WebCoreSystemInterface.h"
35
36 #if PLATFORM(WX)
37 #include <ApplicationServices/ApplicationServices.h>
38 #else
39 #include <CoreText/CoreText.h>
40 #endif
41
42 #if defined(BUILDING_ON_LEOPARD)
43 // The following symbols are SPI in 10.5.
44 extern "C" {
45 void CTRunGetAdvances(CTRunRef run, CFRange range, CGSize buffer[]);
46 const CGSize* CTRunGetAdvancesPtr(CTRunRef run);
47 extern const CFStringRef kCTTypesetterOptionForcedEmbeddingLevel;
48 }
49 #endif
50
51 @interface WebCascadeList : NSArray {
52     @private
53     const WebCore::Font* _font;
54     UChar32 _character;
55     NSUInteger _count;
56     Vector<RetainPtr<CTFontDescriptorRef>, 16> _fontDescriptors;
57 }
58
59 - (id)initWithFont:(const WebCore::Font*)font character:(UChar32)character;
60
61 @end
62
63 @implementation WebCascadeList
64
65 - (id)initWithFont:(const WebCore::Font*)font character:(UChar32)character
66 {
67     if (!(self = [super init]))
68         return nil;
69
70     _font = font;
71     _character = character;
72
73     // By the time a WebCascadeList is used, the Font has already been asked to realize all of its
74     // FontData, so this loop does not hit the FontCache.
75     while (_font->fontDataAt(_count))
76         _count++;
77
78     return self;
79 }
80
81 - (NSUInteger)count
82 {
83     return _count;
84 }
85
86 - (id)objectAtIndex:(NSUInteger)index
87 {
88     CTFontDescriptorRef fontDescriptor;
89     if (index < _fontDescriptors.size()) {
90         if ((fontDescriptor = _fontDescriptors[index].get()))
91             return (id)fontDescriptor;
92     } else
93         _fontDescriptors.grow(index + 1);
94
95     const WebCore::SimpleFontData* fontData = _font->fontDataAt(index)->fontDataForCharacter(_character);
96     fontDescriptor = CTFontCopyFontDescriptor(fontData->platformData().ctFont());
97     _fontDescriptors[index] = RetainPtr<CTFontDescriptorRef>(AdoptCF, fontDescriptor);
98     return (id)fontDescriptor;
99 }
100
101 @end
102
103 namespace WebCore {
104
105 ComplexTextController::ComplexTextRun::ComplexTextRun(CTRunRef ctRun, const SimpleFontData* fontData, const UChar* characters, unsigned stringLocation, size_t stringLength, CFRange runRange)
106     : m_fontData(fontData)
107     , m_characters(characters)
108     , m_stringLocation(stringLocation)
109     , m_stringLength(stringLength)
110     , m_indexEnd(runRange.location + runRange.length)
111     , m_isMonotonic(true)
112 {
113     m_glyphCount = CTRunGetGlyphCount(ctRun);
114     m_coreTextIndices = CTRunGetStringIndicesPtr(ctRun);
115     if (!m_coreTextIndices) {
116         m_coreTextIndicesVector.grow(m_glyphCount);
117         CTRunGetStringIndices(ctRun, CFRangeMake(0, 0), m_coreTextIndicesVector.data());
118         m_coreTextIndices = m_coreTextIndicesVector.data();
119     }
120
121     m_glyphs = CTRunGetGlyphsPtr(ctRun);
122     if (!m_glyphs) {
123         m_glyphsVector.grow(m_glyphCount);
124         CTRunGetGlyphs(ctRun, CFRangeMake(0, 0), m_glyphsVector.data());
125         m_glyphs = m_glyphsVector.data();
126     }
127
128     m_advances = CTRunGetAdvancesPtr(ctRun);
129     if (!m_advances) {
130         m_advancesVector.grow(m_glyphCount);
131         CTRunGetAdvances(ctRun, CFRangeMake(0, 0), m_advancesVector.data());
132         m_advances = m_advancesVector.data();
133     }
134 }
135
136 // Missing glyphs run constructor. Core Text will not generate a run of missing glyphs, instead falling back on
137 // glyphs from LastResort. We want to use the primary font's missing glyph in order to match the fast text code path.
138 void ComplexTextController::ComplexTextRun::createTextRunFromFontDataCoreText(bool ltr)
139 {
140     m_coreTextIndicesVector.reserveInitialCapacity(m_stringLength);
141     unsigned r = 0;
142     while (r < m_stringLength) {
143         m_coreTextIndicesVector.uncheckedAppend(r);
144         if (U_IS_SURROGATE(m_characters[r])) {
145             ASSERT(r + 1 < m_stringLength);
146             ASSERT(U_IS_SURROGATE_LEAD(m_characters[r]));
147             ASSERT(U_IS_TRAIL(m_characters[r + 1]));
148             r += 2;
149         } else
150             r++;
151     }
152     m_glyphCount = m_coreTextIndicesVector.size();
153     if (!ltr) {
154         for (unsigned r = 0, end = m_glyphCount - 1; r < m_glyphCount / 2; ++r, --end)
155             std::swap(m_coreTextIndicesVector[r], m_coreTextIndicesVector[end]);
156     }
157     m_coreTextIndices = m_coreTextIndicesVector.data();
158
159     // Synthesize a run of missing glyphs.
160     m_glyphsVector.fill(0, m_glyphCount);
161     m_glyphs = m_glyphsVector.data();
162     m_advancesVector.fill(CGSizeMake(m_fontData->widthForGlyph(0), 0), m_glyphCount);
163     m_advances = m_advancesVector.data();
164 }
165
166 struct ProviderInfo {
167     const UChar* cp;
168     unsigned length;
169     CFDictionaryRef attributes;
170 };
171
172 static const UniChar* provideStringAndAttributes(CFIndex stringIndex, CFIndex* charCount, CFDictionaryRef* attributes, void* refCon)
173 {
174     ProviderInfo* info = static_cast<struct ProviderInfo*>(refCon);
175     if (stringIndex < 0 || static_cast<unsigned>(stringIndex) >= info->length)
176         return 0;
177
178     *charCount = info->length - stringIndex;
179     *attributes = info->attributes;
180     return info->cp + stringIndex;
181 }
182
183 void ComplexTextController::collectComplexTextRunsForCharactersCoreText(const UChar* cp, unsigned length, unsigned stringLocation, const SimpleFontData* fontData)
184 {
185     ASSERT_ARG(fontData, fontData);
186
187     bool isSystemFallback = false;
188
189     UChar32 baseCharacter = 0;
190     RetainPtr<CFDictionaryRef> stringAttributes;
191     if (fontData == systemFallbackFontData()) {
192         // FIXME: This code path does not support small caps.
193         isSystemFallback = true;
194
195         U16_GET(cp, 0, 0, length, baseCharacter);
196         fontData = m_font.fontDataAt(0)->fontDataForCharacter(baseCharacter);
197
198         RetainPtr<WebCascadeList> cascadeList(AdoptNS, [[WebCascadeList alloc] initWithFont:&m_font character:baseCharacter]);
199
200         stringAttributes.adoptCF(CFDictionaryCreateMutableCopy(kCFAllocatorDefault, 0, fontData->getCFStringAttributes(m_font.typesettingFeatures(), fontData->platformData().orientation())));
201         static const void* attributeKeys[] = { kCTFontCascadeListAttribute };
202         const void* values[] = { cascadeList.get() };
203         RetainPtr<CFDictionaryRef> attributes(AdoptCF, CFDictionaryCreate(kCFAllocatorDefault, attributeKeys, values, sizeof(attributeKeys) / sizeof(*attributeKeys), &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks));
204         RetainPtr<CTFontDescriptorRef> fontDescriptor(AdoptCF, CTFontDescriptorCreateWithAttributes(attributes.get()));
205         RetainPtr<CTFontRef> fontWithCascadeList(AdoptCF, CTFontCreateCopyWithAttributes(fontData->platformData().ctFont(), m_font.pixelSize(), 0, fontDescriptor.get()));
206         CFDictionarySetValue(const_cast<CFMutableDictionaryRef>(stringAttributes.get()), kCTFontAttributeName, fontWithCascadeList.get());
207     } else
208         stringAttributes = fontData->getCFStringAttributes(m_font.typesettingFeatures(), fontData->platformData().orientation());
209
210     RetainPtr<CTLineRef> line;
211
212     if (!m_mayUseNaturalWritingDirection || m_run.directionalOverride()) {
213         static const void* optionKeys[] = { kCTTypesetterOptionForcedEmbeddingLevel };
214         const short ltrForcedEmbeddingLevelValue = 0;
215         const short rtlForcedEmbeddingLevelValue = 1;
216         static const void* ltrOptionValues[] = { CFNumberCreate(kCFAllocatorDefault, kCFNumberShortType, &ltrForcedEmbeddingLevelValue) };
217         static const void* rtlOptionValues[] = { CFNumberCreate(kCFAllocatorDefault, kCFNumberShortType, &rtlForcedEmbeddingLevelValue) };
218         static CFDictionaryRef ltrTypesetterOptions = CFDictionaryCreate(kCFAllocatorDefault, optionKeys, ltrOptionValues, WTF_ARRAY_LENGTH(optionKeys), &kCFCopyStringDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
219         static CFDictionaryRef rtlTypesetterOptions = CFDictionaryCreate(kCFAllocatorDefault, optionKeys, rtlOptionValues, WTF_ARRAY_LENGTH(optionKeys), &kCFCopyStringDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
220
221 #if !defined(BUILDING_ON_LEOPARD) && !defined(BUILDING_ON_SNOW_LEOPARD)
222         ProviderInfo info = { cp, length, stringAttributes.get() };
223         RetainPtr<CTTypesetterRef> typesetter(AdoptCF, wkCreateCTTypesetterWithUniCharProviderAndOptions(&provideStringAndAttributes, 0, &info, m_run.ltr() ? ltrTypesetterOptions : rtlTypesetterOptions));
224 #else
225         RetainPtr<CFStringRef> string(AdoptCF, CFStringCreateWithCharactersNoCopy(kCFAllocatorDefault, cp, length, kCFAllocatorNull));
226         RetainPtr<CFAttributedStringRef> attributedString(AdoptCF, CFAttributedStringCreate(kCFAllocatorDefault, string.get(), stringAttributes.get()));
227         RetainPtr<CTTypesetterRef> typesetter(AdoptCF, CTTypesetterCreateWithAttributedStringAndOptions(attributedString.get(), m_run.ltr() ? ltrTypesetterOptions : rtlTypesetterOptions));
228 #endif
229
230         line.adoptCF(CTTypesetterCreateLine(typesetter.get(), CFRangeMake(0, 0)));
231     } else {
232         ProviderInfo info = { cp, length, stringAttributes.get() };
233
234         line.adoptCF(wkCreateCTLineWithUniCharProvider(&provideStringAndAttributes, 0, &info));
235     }
236
237     m_coreTextLines.append(line.get());
238
239     CFArrayRef runArray = CTLineGetGlyphRuns(line.get());
240
241     CFIndex runCount = CFArrayGetCount(runArray);
242
243     for (CFIndex r = 0; r < runCount; r++) {
244         CTRunRef ctRun = static_cast<CTRunRef>(CFArrayGetValueAtIndex(runArray, m_run.ltr() ? r : runCount - 1 - r));
245         ASSERT(CFGetTypeID(ctRun) == CTRunGetTypeID());
246         CFRange runRange = CTRunGetStringRange(ctRun);
247         const SimpleFontData* runFontData = fontData;
248         if (isSystemFallback) {
249             CFDictionaryRef runAttributes = CTRunGetAttributes(ctRun);
250             CTFontRef runFont = static_cast<CTFontRef>(CFDictionaryGetValue(runAttributes, kCTFontAttributeName));
251             ASSERT(CFGetTypeID(runFont) == CTFontGetTypeID());
252             if (!CFEqual(runFont, fontData->platformData().ctFont())) {
253                 // Begin trying to see if runFont matches any of the fonts in the fallback list.
254                 RetainPtr<CGFontRef> runCGFont(AdoptCF, CTFontCopyGraphicsFont(runFont, 0));
255                 unsigned i = 0;
256                 for (const FontData* candidateFontData = m_font.fontDataAt(i); candidateFontData; candidateFontData = m_font.fontDataAt(++i)) {
257                     runFontData = candidateFontData->fontDataForCharacter(baseCharacter);
258                     RetainPtr<CGFontRef> cgFont(AdoptCF, CTFontCopyGraphicsFont(runFontData->platformData().ctFont(), 0));
259                     if (CFEqual(cgFont.get(), runCGFont.get()))
260                         break;
261                     runFontData = 0;
262                 }
263                 // If there is no matching font, look up by name in the font cache.
264                 if (!runFontData) {
265                     // Rather than using runFont as an NSFont and wrapping it in a FontPlatformData, go through
266                     // the font cache and ultimately through NSFontManager in order to get an NSFont with the right
267                     // NSFontRenderingMode.
268                     RetainPtr<CFStringRef> fontName(AdoptCF, CTFontCopyPostScriptName(runFont));
269                     if (CFEqual(fontName.get(), CFSTR("LastResort"))) {
270                         m_complexTextRuns.append(ComplexTextRun::create(m_font.primaryFont(), cp, stringLocation + runRange.location, runRange.length, m_run.ltr()));
271                         continue;
272                     }
273                     runFontData = fontCache()->getCachedFontData(m_font.fontDescription(), fontName.get(), false, FontCache::DoNotRetain);
274                 }
275                 ASSERT(runFontData);
276                 if (m_fallbackFonts && runFontData != m_font.primaryFont())
277                     m_fallbackFonts->add(runFontData);
278             }
279         }
280         if (m_fallbackFonts && runFontData != m_font.primaryFont())
281             m_fallbackFonts->add(fontData);
282
283         m_complexTextRuns.append(ComplexTextRun::create(ctRun, runFontData, cp, stringLocation, length, runRange));
284     }
285 }
286
287 } // namespace WebCore
288
289 #endif // USE(CORE_TEXT)