4d5533eea80e2c21d4d52f908d99193eb260d405
[platform/framework/web/crosswalk.git] / src / third_party / WebKit / Source / platform / fonts / mac / SimpleFontDataMac.mm
1 /*
2  * Copyright (C) 2005, 2006, 2010, 2011 Apple Inc. All rights reserved.
3  * Copyright (C) 2006 Alexey Proskuryakov
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
15  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
16  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
17  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
18  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
19  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
20  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
21  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
22  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
23  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
24  * THE POSSIBILITY OF SUCH DAMAGE.
25  */
26
27 #import "config.h"
28 #import "platform/fonts/SimpleFontData.h"
29
30 #import <AppKit/AppKit.h>
31 #import <ApplicationServices/ApplicationServices.h>
32 #import <float.h>
33 #import <unicode/uchar.h>
34 #import "platform/SharedBuffer.h"
35 #import "platform/fonts/Font.h"
36 #import "platform/fonts/FontCache.h"
37 #import "platform/fonts/FontDescription.h"
38 #import "platform/geometry/FloatRect.h"
39 #import "platform/graphics/Color.h"
40 #import "platform/mac/BlockExceptions.h"
41 #import <wtf/Assertions.h>
42 #import <wtf/RetainPtr.h>
43 #import <wtf/StdLibExtras.h>
44
45 @interface NSFont (WebAppKitSecretAPI)
46 - (BOOL)_isFakeFixedPitch;
47 @end
48
49 // The names of these constants were taken from history
50 // /trunk/WebKit/WebCoreSupport.subproj/WebTextRenderer.m@9311. The values
51 // were derived from the assembly of libWebKitSystemInterfaceLeopard.a.
52 enum CGFontRenderingMode {
53   kCGFontRenderingMode1BitPixelAligned = 0x0,
54   kCGFontRenderingModeAntialiasedPixelAligned = 0x1,
55   kCGFontRenderingModeAntialiased = 0xd
56 };
57
58 // Forward declare Mac SPIs.
59 extern "C" {
60 // Request for public API: rdar://13803586
61 bool CGFontGetGlyphAdvancesForStyle(CGFontRef font, CGAffineTransform* transform, CGFontRenderingMode renderingMode, ATSGlyphRef* glyph, size_t count, CGSize* advance);
62
63 // Request for public API: rdar://13803619
64 CTLineRef CTLineCreateWithUniCharProvider(const UniChar* (*provide)(CFIndex stringIndex, CFIndex* charCount, CFDictionaryRef* attributes, void* context), void (*dispose)(const UniChar* chars, void* context), void* context);
65 }
66
67 static CGFontRenderingMode cgFontRenderingModeForNSFont(NSFont* font) {
68     if (!font)
69         return kCGFontRenderingModeAntialiasedPixelAligned;
70
71     switch ([font renderingMode]) {
72         case NSFontIntegerAdvancementsRenderingMode: return kCGFontRenderingMode1BitPixelAligned;
73         case NSFontAntialiasedIntegerAdvancementsRenderingMode: return kCGFontRenderingModeAntialiasedPixelAligned;
74         default: return kCGFontRenderingModeAntialiased;
75     }
76 }
77
78 using namespace std;
79
80 namespace WebCore {
81
82 static bool fontHasVerticalGlyphs(CTFontRef ctFont)
83 {
84     // The check doesn't look neat but this is what AppKit does for vertical writing...
85     RetainPtr<CFArrayRef> tableTags(AdoptCF, CTFontCopyAvailableTables(ctFont, kCTFontTableOptionNoOptions));
86     CFIndex numTables = CFArrayGetCount(tableTags.get());
87     for (CFIndex index = 0; index < numTables; ++index) {
88         CTFontTableTag tag = (CTFontTableTag)(uintptr_t)CFArrayGetValueAtIndex(tableTags.get(), index);
89         if (tag == kCTFontTableVhea || tag == kCTFontTableVORG)
90             return true;
91     }
92     return false;
93 }
94
95 static bool initFontData(SimpleFontData* fontData)
96 {
97     if (!fontData->platformData().cgFont())
98         return false;
99
100     return true;
101 }
102
103 static NSString *webFallbackFontFamily(void)
104 {
105     DEFINE_STATIC_LOCAL(RetainPtr<NSString>, webFallbackFontFamily, ([[NSFont systemFontOfSize:16.0f] familyName]));
106     return webFallbackFontFamily.get();
107 }
108
109 const SimpleFontData* SimpleFontData::getCompositeFontReferenceFontData(NSFont *key) const
110 {
111     if (key && !CFEqual(RetainPtr<CFStringRef>(AdoptCF, CTFontCopyPostScriptName(CTFontRef(key))).get(), CFSTR("LastResort"))) {
112         if (!m_derivedFontData)
113             m_derivedFontData = DerivedFontData::create(isCustomFont());
114         if (!m_derivedFontData->compositeFontReferences)
115             m_derivedFontData->compositeFontReferences.adoptCF(CFDictionaryCreateMutable(kCFAllocatorDefault, 1, &kCFTypeDictionaryKeyCallBacks, NULL));
116         else {
117             const SimpleFontData* found = static_cast<const SimpleFontData*>(CFDictionaryGetValue(m_derivedFontData->compositeFontReferences.get(), static_cast<const void *>(key)));
118             if (found)
119                 return found;
120         }
121         if (CFMutableDictionaryRef dictionary = m_derivedFontData->compositeFontReferences.get()) {
122             bool isUsingPrinterFont = platformData().isPrinterFont();
123             NSFont *substituteFont = isUsingPrinterFont ? [key printerFont] : [key screenFont];
124
125             CTFontSymbolicTraits traits = CTFontGetSymbolicTraits(toCTFontRef(substituteFont));
126             bool syntheticBold = platformData().syntheticBold() && !(traits & kCTFontBoldTrait);
127             bool syntheticOblique = platformData().syntheticOblique() && !(traits & kCTFontItalicTrait);
128
129             FontPlatformData substitutePlatform(substituteFont, platformData().size(), isUsingPrinterFont, syntheticBold, syntheticOblique, platformData().orientation(), platformData().widthVariant());
130             SimpleFontData* value = new SimpleFontData(substitutePlatform, isCustomFont() ? CustomFontData::create(false) : 0);
131             if (value) {
132                 CFDictionaryAddValue(dictionary, key, value);
133                 return value;
134             }
135         }
136     }
137     return 0;
138 }
139
140 void SimpleFontData::platformInit()
141 {
142     m_syntheticBoldOffset = m_platformData.m_syntheticBold ? 1.0f : 0.f;
143
144     bool failedSetup = false;
145     if (!initFontData(this)) {
146         // Ack! Something very bad happened, like a corrupt font.
147         // Try looking for an alternate 'base' font for this renderer.
148
149         // Special case hack to use "Times New Roman" in place of "Times".
150         // "Times RO" is a common font whose family name is "Times".
151         // It overrides the normal "Times" family font.
152         // It also appears to have a corrupt regular variant.
153         NSString *fallbackFontFamily;
154         if ([[m_platformData.font() familyName] isEqual:@"Times"])
155             fallbackFontFamily = @"Times New Roman";
156         else
157             fallbackFontFamily = webFallbackFontFamily();
158         
159         // Try setting up the alternate font.
160         // This is a last ditch effort to use a substitute font when something has gone wrong.
161 #if !ERROR_DISABLED
162         RetainPtr<NSFont> initialFont = m_platformData.font();
163 #endif
164         if (m_platformData.font())
165             m_platformData.setFont([[NSFontManager sharedFontManager] convertFont:m_platformData.font() toFamily:fallbackFontFamily]);
166         else
167             m_platformData.setFont([NSFont fontWithName:fallbackFontFamily size:m_platformData.size()]);
168
169         if (!initFontData(this)) {
170             if ([fallbackFontFamily isEqual:@"Times New Roman"]) {
171                 // OK, couldn't setup Times New Roman as an alternate to Times, fallback
172                 // on the system font.  If this fails we have no alternative left.
173                 m_platformData.setFont([[NSFontManager sharedFontManager] convertFont:m_platformData.font() toFamily:webFallbackFontFamily()]);
174                 if (!initFontData(this)) {
175                     // We tried, Times, Times New Roman, and the system font. No joy. We have to give up.
176                     WTF_LOG_ERROR("unable to initialize with font %@", initialFont.get());
177                     failedSetup = true;
178                 }
179             } else {
180                 // We tried the requested font and the system font. No joy. We have to give up.
181                 WTF_LOG_ERROR("unable to initialize with font %@", initialFont.get());
182                 failedSetup = true;
183             }
184         }
185
186         // Report the problem.
187         WTF_LOG_ERROR("Corrupt font detected, using %@ in place of %@.",
188             [m_platformData.font() familyName], [initialFont.get() familyName]);
189     }
190
191     // If all else fails, try to set up using the system font.
192     // This is probably because Times and Times New Roman are both unavailable.
193     if (failedSetup) {
194         m_platformData.setFont([NSFont systemFontOfSize:[m_platformData.font() pointSize]]);
195         WTF_LOG_ERROR("failed to set up font, using system font %s", m_platformData.font());
196         initFontData(this);
197     }
198     
199     int iAscent;
200     int iDescent;
201     int iLineGap;
202     unsigned unitsPerEm;
203     iAscent = CGFontGetAscent(m_platformData.cgFont());
204     // Some fonts erroneously specify a positive descender value. We follow Core Text in assuming that
205     // such fonts meant the same distance, but in the reverse direction.
206     iDescent = -abs(CGFontGetDescent(m_platformData.cgFont()));
207     iLineGap = CGFontGetLeading(m_platformData.cgFont());
208     unitsPerEm = CGFontGetUnitsPerEm(m_platformData.cgFont());
209
210     float pointSize = m_platformData.m_size;
211     float ascent = scaleEmToUnits(iAscent, unitsPerEm) * pointSize;
212     float descent = -scaleEmToUnits(iDescent, unitsPerEm) * pointSize;
213     float lineGap = scaleEmToUnits(iLineGap, unitsPerEm) * pointSize;
214
215     // We need to adjust Times, Helvetica, and Courier to closely match the
216     // vertical metrics of their Microsoft counterparts that are the de facto
217     // web standard. The AppKit adjustment of 20% is too big and is
218     // incorrectly added to line spacing, so we use a 15% adjustment instead
219     // and add it to the ascent.
220     NSString *familyName = [m_platformData.font() familyName];
221     if ([familyName isEqualToString:@"Times"] || [familyName isEqualToString:@"Helvetica"] || [familyName isEqualToString:@"Courier"])
222         ascent += floorf(((ascent + descent) * 0.15f) + 0.5f);
223
224     // Compute and store line spacing, before the line metrics hacks are applied.
225     m_fontMetrics.setLineSpacing(lroundf(ascent) + lroundf(descent) + lroundf(lineGap));
226
227     // Hack Hiragino line metrics to allow room for marked text underlines.
228     // <rdar://problem/5386183>
229     if (descent < 3 && lineGap >= 3 && [familyName hasPrefix:@"Hiragino"]) {
230         lineGap -= 3 - descent;
231         descent = 3;
232     }
233     
234     if (platformData().orientation() == Vertical && !isTextOrientationFallback())
235         m_hasVerticalGlyphs = fontHasVerticalGlyphs(m_platformData.ctFont());
236
237     float xHeight;
238
239     if (platformData().orientation() == Horizontal) {
240         // Measure the actual character "x", since it's possible for it to extend below the baseline, and we need the
241         // reported x-height to only include the portion of the glyph that is above the baseline.
242         GlyphPage* glyphPageZero = GlyphPageTreeNode::getRootChild(this, 0)->page();
243         NSGlyph xGlyph = glyphPageZero ? glyphPageZero->glyphForCharacter('x') : 0;
244         if (xGlyph)
245             xHeight = -CGRectGetMinY(platformBoundsForGlyph(xGlyph));
246         else
247             xHeight = scaleEmToUnits(CGFontGetXHeight(m_platformData.cgFont()), unitsPerEm) * pointSize;
248     } else
249         xHeight = verticalRightOrientationFontData()->fontMetrics().xHeight();
250
251     m_fontMetrics.setUnitsPerEm(unitsPerEm);
252     m_fontMetrics.setAscent(ascent);
253     m_fontMetrics.setDescent(descent);
254     m_fontMetrics.setLineGap(lineGap);
255     m_fontMetrics.setXHeight(xHeight);
256 }
257
258 static CFDataRef copyFontTableForTag(FontPlatformData& platformData, FourCharCode tableName)
259 {
260     return CGFontCopyTableForTag(platformData.cgFont(), tableName);
261 }
262
263 void SimpleFontData::platformCharWidthInit()
264 {
265     m_avgCharWidth = 0;
266     m_maxCharWidth = 0;
267     
268     RetainPtr<CFDataRef> os2Table(AdoptCF, copyFontTableForTag(m_platformData, 'OS/2'));
269     if (os2Table && CFDataGetLength(os2Table.get()) >= 4) {
270         const UInt8* os2 = CFDataGetBytePtr(os2Table.get());
271         SInt16 os2AvgCharWidth = os2[2] * 256 + os2[3];
272         m_avgCharWidth = scaleEmToUnits(os2AvgCharWidth, m_fontMetrics.unitsPerEm()) * m_platformData.m_size;
273     }
274
275     RetainPtr<CFDataRef> headTable(AdoptCF, copyFontTableForTag(m_platformData, 'head'));
276     if (headTable && CFDataGetLength(headTable.get()) >= 42) {
277         const UInt8* head = CFDataGetBytePtr(headTable.get());
278         ushort uxMin = head[36] * 256 + head[37];
279         ushort uxMax = head[40] * 256 + head[41];
280         SInt16 xMin = static_cast<SInt16>(uxMin);
281         SInt16 xMax = static_cast<SInt16>(uxMax);
282         float diff = static_cast<float>(xMax - xMin);
283         m_maxCharWidth = scaleEmToUnits(diff, m_fontMetrics.unitsPerEm()) * m_platformData.m_size;
284     }
285
286     // Fallback to a cross-platform estimate, which will populate these values if they are non-positive.
287     initCharWidths();
288 }
289
290 void SimpleFontData::platformDestroy()
291 {
292     if (!isCustomFont() && m_derivedFontData) {
293         // These come from the cache.
294         if (m_derivedFontData->smallCaps)
295             FontCache::fontCache()->releaseFontData(m_derivedFontData->smallCaps.get());
296
297         if (m_derivedFontData->emphasisMark)
298             FontCache::fontCache()->releaseFontData(m_derivedFontData->emphasisMark.get());
299     }
300 }
301
302 PassRefPtr<SimpleFontData> SimpleFontData::platformCreateScaledFontData(const FontDescription& fontDescription, float scaleFactor) const
303 {
304     if (isCustomFont()) {
305         FontPlatformData scaledFontData(m_platformData);
306         scaledFontData.m_size = scaledFontData.m_size * scaleFactor;
307         return SimpleFontData::create(scaledFontData, CustomFontData::create(false));
308     }
309
310     BEGIN_BLOCK_OBJC_EXCEPTIONS;
311     float size = m_platformData.size() * scaleFactor;
312     FontPlatformData scaledFontData([[NSFontManager sharedFontManager] convertFont:m_platformData.font() toSize:size], size, m_platformData.isPrinterFont(), false, false, m_platformData.orientation());
313
314     // AppKit resets the type information (screen/printer) when you convert a font to a different size.
315     // We have to fix up the font that we're handed back.
316     scaledFontData.setFont(fontDescription.usePrinterFont() ? [scaledFontData.font() printerFont] : [scaledFontData.font() screenFont]);
317
318     if (scaledFontData.font()) {
319         NSFontManager *fontManager = [NSFontManager sharedFontManager];
320         NSFontTraitMask fontTraits = [fontManager traitsOfFont:m_platformData.font()];
321
322         if (m_platformData.m_syntheticBold)
323             fontTraits |= NSBoldFontMask;
324         if (m_platformData.m_syntheticOblique)
325             fontTraits |= NSItalicFontMask;
326
327         NSFontTraitMask scaledFontTraits = [fontManager traitsOfFont:scaledFontData.font()];
328         scaledFontData.m_syntheticBold = (fontTraits & NSBoldFontMask) && !(scaledFontTraits & NSBoldFontMask);
329         scaledFontData.m_syntheticOblique = (fontTraits & NSItalicFontMask) && !(scaledFontTraits & NSItalicFontMask);
330
331         // SimpleFontData::platformDestroy() takes care of not deleting the cached font data twice.
332         return FontCache::fontCache()->fontDataFromFontPlatformData(&scaledFontData);
333     }
334     END_BLOCK_OBJC_EXCEPTIONS;
335
336     return 0;
337 }
338
339 bool SimpleFontData::containsCharacters(const UChar* characters, int length) const
340 {
341     NSString *string = [[NSString alloc] initWithCharactersNoCopy:const_cast<unichar*>(characters) length:length freeWhenDone:NO];
342     NSCharacterSet *set = [[m_platformData.font() coveredCharacterSet] invertedSet];
343     bool result = set && [string rangeOfCharacterFromSet:set].location == NSNotFound;
344     [string release];
345     return result;
346 }
347
348 void SimpleFontData::determinePitch()
349 {
350     NSFont* f = m_platformData.font();
351     // Special case Osaka-Mono.
352     // According to <rdar://problem/3999467>, we should treat Osaka-Mono as fixed pitch.
353     // Note that the AppKit does not report Osaka-Mono as fixed pitch.
354
355     // Special case MS-PGothic.
356     // According to <rdar://problem/4032938>, we should not treat MS-PGothic as fixed pitch.
357     // Note that AppKit does report MS-PGothic as fixed pitch.
358
359     // Special case MonotypeCorsiva
360     // According to <rdar://problem/5454704>, we should not treat MonotypeCorsiva as fixed pitch.
361     // Note that AppKit does report MonotypeCorsiva as fixed pitch.
362
363     NSString *name = [f fontName];
364     m_treatAsFixedPitch = ([f isFixedPitch] || [f _isFakeFixedPitch] ||
365            [name caseInsensitiveCompare:@"Osaka-Mono"] == NSOrderedSame) &&
366            [name caseInsensitiveCompare:@"MS-PGothic"] != NSOrderedSame &&
367            [name caseInsensitiveCompare:@"MonotypeCorsiva"] != NSOrderedSame;
368 }
369
370 FloatRect SimpleFontData::platformBoundsForGlyph(Glyph glyph) const
371 {
372     FloatRect boundingBox;
373     boundingBox = CTFontGetBoundingRectsForGlyphs(m_platformData.ctFont(), platformData().orientation() == Vertical ? kCTFontVerticalOrientation : kCTFontHorizontalOrientation, &glyph, 0, 1);
374     boundingBox.setY(-boundingBox.maxY());
375     if (m_syntheticBoldOffset)
376         boundingBox.setWidth(boundingBox.width() + m_syntheticBoldOffset);
377
378     return boundingBox;
379 }
380
381 float SimpleFontData::platformWidthForGlyph(Glyph glyph) const
382 {
383     CGSize advance = CGSizeZero;
384     if (platformData().orientation() == Horizontal || m_isBrokenIdeographFallback) {
385         NSFont *font = platformData().font();
386         if (font && platformData().isColorBitmapFont())
387             advance = NSSizeToCGSize([font advancementForGlyph:glyph]);
388         else {
389             float pointSize = platformData().m_size;
390             CGAffineTransform m = CGAffineTransformMakeScale(pointSize, pointSize);
391             if (!CGFontGetGlyphAdvancesForStyle(platformData().cgFont(), &m, cgFontRenderingModeForNSFont(font), &glyph, 1, &advance)) {
392                 WTF_LOG_ERROR("Unable to cache glyph widths for %@ %f", [font displayName], pointSize);
393                 advance.width = 0;
394             }
395         }
396     } else
397         CTFontGetAdvancesForGlyphs(m_platformData.ctFont(), kCTFontVerticalOrientation, &glyph, &advance, 1);
398
399     return advance.width + m_syntheticBoldOffset;
400 }
401
402 struct ProviderInfo {
403     const UChar* characters;
404     size_t length;
405     CFDictionaryRef attributes;
406 };
407
408 static const UniChar* provideStringAndAttributes(CFIndex stringIndex, CFIndex* count, CFDictionaryRef* attributes, void* context)
409 {
410     ProviderInfo* info = static_cast<struct ProviderInfo*>(context);
411     if (stringIndex < 0 || static_cast<size_t>(stringIndex) >= info->length)
412         return 0;
413
414     *count = info->length - stringIndex;
415     *attributes = info->attributes;
416     return info->characters + stringIndex;
417 }
418
419 bool SimpleFontData::canRenderCombiningCharacterSequence(const UChar* characters, size_t length) const
420 {
421     ASSERT(isMainThread());
422
423     if (!m_combiningCharacterSequenceSupport)
424         m_combiningCharacterSequenceSupport = adoptPtr(new HashMap<String, bool>);
425
426     WTF::HashMap<String, bool>::AddResult addResult = m_combiningCharacterSequenceSupport->add(String(characters, length), false);
427     if (!addResult.isNewEntry)
428         return addResult.iterator->value;
429
430     RetainPtr<CGFontRef> cgFont(AdoptCF, CTFontCopyGraphicsFont(platformData().ctFont(), 0));
431
432     ProviderInfo info = { characters, length, getCFStringAttributes(0, platformData().orientation()) };
433     RetainPtr<CTLineRef> line(AdoptCF, CTLineCreateWithUniCharProvider(&provideStringAndAttributes, 0, &info));
434
435     CFArrayRef runArray = CTLineGetGlyphRuns(line.get());
436     CFIndex runCount = CFArrayGetCount(runArray);
437
438     for (CFIndex r = 0; r < runCount; r++) {
439         CTRunRef ctRun = static_cast<CTRunRef>(CFArrayGetValueAtIndex(runArray, r));
440         ASSERT(CFGetTypeID(ctRun) == CTRunGetTypeID());
441         CFDictionaryRef runAttributes = CTRunGetAttributes(ctRun);
442         CTFontRef runFont = static_cast<CTFontRef>(CFDictionaryGetValue(runAttributes, kCTFontAttributeName));
443         RetainPtr<CGFontRef> runCGFont(AdoptCF, CTFontCopyGraphicsFont(runFont, 0));
444         if (!CFEqual(runCGFont.get(), cgFont.get()))
445             return false;
446     }
447
448     addResult.iterator->value = true;
449     return true;
450 }
451
452 } // namespace WebCore