tizen beta release
[profile/ivi/webkit-efl.git] / Source / WebCore / platform / graphics / 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 "SimpleFontData.h"
29
30 #import "BlockExceptions.h"
31 #import "Color.h"
32 #import "FloatRect.h"
33 #import "Font.h"
34 #import "FontCache.h"
35 #import "FontDescription.h"
36 #import "SharedBuffer.h"
37 #import "WebCoreSystemInterface.h"
38 #import <AppKit/AppKit.h>
39 #import <ApplicationServices/ApplicationServices.h>
40 #import <float.h>
41 #import <unicode/uchar.h>
42 #import <wtf/Assertions.h>
43 #import <wtf/StdLibExtras.h>
44 #import <wtf/RetainPtr.h>
45 #import <wtf/UnusedParam.h>
46
47 @interface NSFont (WebAppKitSecretAPI)
48 - (BOOL)_isFakeFixedPitch;
49 @end
50
51 using namespace std;
52
53 namespace WebCore {
54   
55 const float smallCapsFontSizeMultiplier = 0.7f;
56
57 static bool fontHasVerticalGlyphs(CTFontRef ctFont)
58 {
59     // The check doesn't look neat but this is what AppKit does for vertical writing...
60     RetainPtr<CFArrayRef> tableTags(AdoptCF, CTFontCopyAvailableTables(ctFont, kCTFontTableOptionExcludeSynthetic));
61     CFIndex numTables = CFArrayGetCount(tableTags.get());
62     for (CFIndex index = 0; index < numTables; ++index) {
63         CTFontTableTag tag = (CTFontTableTag)(uintptr_t)CFArrayGetValueAtIndex(tableTags.get(), index);
64         if (tag == kCTFontTableVhea || tag == kCTFontTableVORG)
65             return true;
66     }
67     return false;
68 }
69
70 static bool initFontData(SimpleFontData* fontData)
71 {
72     if (!fontData->platformData().cgFont())
73         return false;
74
75
76     return true;
77 }
78
79 static NSString *webFallbackFontFamily(void)
80 {
81     DEFINE_STATIC_LOCAL(RetainPtr<NSString>, webFallbackFontFamily, ([[NSFont systemFontOfSize:16.0f] familyName]));
82     return webFallbackFontFamily.get();
83 }
84
85 #if !ERROR_DISABLED
86 #if defined(__LP64__) || (!defined(BUILDING_ON_LEOPARD) && !defined(BUILDING_ON_SNOW_LEOPARD))
87 static NSString* pathFromFont(NSFont*)
88 {
89     // FMGetATSFontRefFromFont is not available. As pathFromFont is only used for debugging purposes,
90     // returning nil is acceptable.
91     return nil;
92 }
93 #else
94 static NSString* pathFromFont(NSFont *font)
95 {
96     ATSFontRef atsFont = FMGetATSFontRefFromFont(CTFontGetPlatformFont(toCTFontRef(font), 0));
97     FSRef fileRef;
98
99     OSStatus status = ATSFontGetFileReference(atsFont, &fileRef);
100     if (status != noErr)
101         return nil;
102
103     UInt8 filePathBuffer[PATH_MAX];
104     status = FSRefMakePath(&fileRef, filePathBuffer, PATH_MAX);
105     if (status == noErr)
106         return [NSString stringWithUTF8String:(const char*)filePathBuffer];
107
108     return nil;
109 }
110 #endif // __LP64__
111 #endif // !ERROR_DISABLED
112
113 void SimpleFontData::platformInit()
114 {
115 #if USE(ATSUI)
116     m_ATSUMirrors = false;
117     m_checkedShapesArabic = false;
118     m_shapesArabic = false;
119 #endif
120
121     m_syntheticBoldOffset = m_platformData.m_syntheticBold ? 1.0f : 0.f;
122
123     bool failedSetup = false;
124     if (!initFontData(this)) {
125         // Ack! Something very bad happened, like a corrupt font.
126         // Try looking for an alternate 'base' font for this renderer.
127
128         // Special case hack to use "Times New Roman" in place of "Times".
129         // "Times RO" is a common font whose family name is "Times".
130         // It overrides the normal "Times" family font.
131         // It also appears to have a corrupt regular variant.
132         NSString *fallbackFontFamily;
133         if ([[m_platformData.font() familyName] isEqual:@"Times"])
134             fallbackFontFamily = @"Times New Roman";
135         else
136             fallbackFontFamily = webFallbackFontFamily();
137         
138         // Try setting up the alternate font.
139         // This is a last ditch effort to use a substitute font when something has gone wrong.
140 #if !ERROR_DISABLED
141         RetainPtr<NSFont> initialFont = m_platformData.font();
142 #endif
143         if (m_platformData.font())
144             m_platformData.setFont([[NSFontManager sharedFontManager] convertFont:m_platformData.font() toFamily:fallbackFontFamily]);
145         else
146             m_platformData.setFont([NSFont fontWithName:fallbackFontFamily size:m_platformData.size()]);
147 #if !ERROR_DISABLED
148         NSString *filePath = pathFromFont(initialFont.get());
149         if (!filePath)
150             filePath = @"not known";
151 #endif
152         if (!initFontData(this)) {
153             if ([fallbackFontFamily isEqual:@"Times New Roman"]) {
154                 // OK, couldn't setup Times New Roman as an alternate to Times, fallback
155                 // on the system font.  If this fails we have no alternative left.
156                 m_platformData.setFont([[NSFontManager sharedFontManager] convertFont:m_platformData.font() toFamily:webFallbackFontFamily()]);
157                 if (!initFontData(this)) {
158                     // We tried, Times, Times New Roman, and the system font. No joy. We have to give up.
159                     LOG_ERROR("unable to initialize with font %@ at %@", initialFont.get(), filePath);
160                     failedSetup = true;
161                 }
162             } else {
163                 // We tried the requested font and the system font. No joy. We have to give up.
164                 LOG_ERROR("unable to initialize with font %@ at %@", initialFont.get(), filePath);
165                 failedSetup = true;
166             }
167         }
168
169         // Report the problem.
170         LOG_ERROR("Corrupt font detected, using %@ in place of %@ located at \"%@\".",
171             [m_platformData.font() familyName], [initialFont.get() familyName], filePath);
172     }
173
174     // If all else fails, try to set up using the system font.
175     // This is probably because Times and Times New Roman are both unavailable.
176     if (failedSetup) {
177         m_platformData.setFont([NSFont systemFontOfSize:[m_platformData.font() pointSize]]);
178         LOG_ERROR("failed to set up font, using system font %s", m_platformData.font());
179         initFontData(this);
180     }
181     
182     int iAscent;
183     int iDescent;
184     int iLineGap;
185     unsigned unitsPerEm;
186     iAscent = CGFontGetAscent(m_platformData.cgFont());
187     // Some fonts erroneously specify a positive descender value. We follow Core Text in assuming that
188     // such fonts meant the same distance, but in the reverse direction.
189     iDescent = -abs(CGFontGetDescent(m_platformData.cgFont()));
190     iLineGap = CGFontGetLeading(m_platformData.cgFont());
191     unitsPerEm = CGFontGetUnitsPerEm(m_platformData.cgFont());
192
193     float pointSize = m_platformData.m_size;
194     float ascent = scaleEmToUnits(iAscent, unitsPerEm) * pointSize;
195     float descent = -scaleEmToUnits(iDescent, unitsPerEm) * pointSize;
196     float lineGap = scaleEmToUnits(iLineGap, unitsPerEm) * pointSize;
197
198     // We need to adjust Times, Helvetica, and Courier to closely match the
199     // vertical metrics of their Microsoft counterparts that are the de facto
200     // web standard. The AppKit adjustment of 20% is too big and is
201     // incorrectly added to line spacing, so we use a 15% adjustment instead
202     // and add it to the ascent.
203     NSString *familyName = [m_platformData.font() familyName];
204     if ([familyName isEqualToString:@"Times"] || [familyName isEqualToString:@"Helvetica"] || [familyName isEqualToString:@"Courier"])
205         ascent += floorf(((ascent + descent) * 0.15f) + 0.5f);
206 #if defined(BUILDING_ON_LEOPARD)
207     else if ([familyName isEqualToString:@"Geeza Pro"]) {
208         // Geeza Pro has glyphs that draw slightly above the ascent or far below the descent. Adjust
209         // those vertical metrics to better match reality, so that diacritics at the bottom of one line
210         // do not overlap diacritics at the top of the next line.
211         ascent *= 1.08f;
212         descent *= 2.f;
213     }
214 #endif
215
216     // Compute and store line spacing, before the line metrics hacks are applied.
217     m_fontMetrics.setLineSpacing(lroundf(ascent) + lroundf(descent) + lroundf(lineGap));
218
219     // Hack Hiragino line metrics to allow room for marked text underlines.
220     // <rdar://problem/5386183>
221     if (descent < 3 && lineGap >= 3 && [familyName hasPrefix:@"Hiragino"]) {
222         lineGap -= 3 - descent;
223         descent = 3;
224     }
225     
226     if (platformData().orientation() == Vertical && !isTextOrientationFallback())
227         m_hasVerticalGlyphs = fontHasVerticalGlyphs(m_platformData.ctFont());
228
229     float xHeight;
230
231     if (platformData().orientation() == Horizontal) {
232         // Measure the actual character "x", since it's possible for it to extend below the baseline, and we need the
233         // reported x-height to only include the portion of the glyph that is above the baseline.
234         GlyphPage* glyphPageZero = GlyphPageTreeNode::getRootChild(this, 0)->page();
235         NSGlyph xGlyph = glyphPageZero ? glyphPageZero->glyphDataForCharacter('x').glyph : 0;
236         if (xGlyph)
237             xHeight = -CGRectGetMinY(platformBoundsForGlyph(xGlyph));
238         else
239             xHeight = scaleEmToUnits(CGFontGetXHeight(m_platformData.cgFont()), unitsPerEm) * pointSize;
240     } else
241         xHeight = verticalRightOrientationFontData()->fontMetrics().xHeight();
242
243     m_fontMetrics.setUnitsPerEm(unitsPerEm);
244     m_fontMetrics.setAscent(ascent);
245     m_fontMetrics.setDescent(descent);
246     m_fontMetrics.setLineGap(lineGap);
247     m_fontMetrics.setXHeight(xHeight);
248 }
249
250 static CFDataRef copyFontTableForTag(FontPlatformData& platformData, FourCharCode tableName)
251 {
252     return CGFontCopyTableForTag(platformData.cgFont(), tableName);
253 }
254
255 void SimpleFontData::platformCharWidthInit()
256 {
257     m_avgCharWidth = 0;
258     m_maxCharWidth = 0;
259     
260     RetainPtr<CFDataRef> os2Table(AdoptCF, copyFontTableForTag(m_platformData, 'OS/2'));
261     if (os2Table && CFDataGetLength(os2Table.get()) >= 4) {
262         const UInt8* os2 = CFDataGetBytePtr(os2Table.get());
263         SInt16 os2AvgCharWidth = os2[2] * 256 + os2[3];
264         m_avgCharWidth = scaleEmToUnits(os2AvgCharWidth, m_fontMetrics.unitsPerEm()) * m_platformData.m_size;
265     }
266
267     RetainPtr<CFDataRef> headTable(AdoptCF, copyFontTableForTag(m_platformData, 'head'));
268     if (headTable && CFDataGetLength(headTable.get()) >= 42) {
269         const UInt8* head = CFDataGetBytePtr(headTable.get());
270         ushort uxMin = head[36] * 256 + head[37];
271         ushort uxMax = head[40] * 256 + head[41];
272         SInt16 xMin = static_cast<SInt16>(uxMin);
273         SInt16 xMax = static_cast<SInt16>(uxMax);
274         float diff = static_cast<float>(xMax - xMin);
275         m_maxCharWidth = scaleEmToUnits(diff, m_fontMetrics.unitsPerEm()) * m_platformData.m_size;
276     }
277
278     // Fallback to a cross-platform estimate, which will populate these values if they are non-positive.
279     initCharWidths();
280 }
281
282 void SimpleFontData::platformDestroy()
283 {
284     if (!isCustomFont() && m_derivedFontData) {
285         // These come from the cache.
286         if (m_derivedFontData->smallCaps)
287             fontCache()->releaseFontData(m_derivedFontData->smallCaps.leakPtr());
288
289         if (m_derivedFontData->emphasisMark)
290             fontCache()->releaseFontData(m_derivedFontData->emphasisMark.leakPtr());
291     }
292
293 #if USE(ATSUI)
294     HashMap<unsigned, ATSUStyle>::iterator end = m_ATSUStyleMap.end();
295     for (HashMap<unsigned, ATSUStyle>::iterator it = m_ATSUStyleMap.begin(); it != end; ++it)
296         ATSUDisposeStyle(it->second);
297 #endif
298 }
299
300 PassOwnPtr<SimpleFontData> SimpleFontData::createScaledFontData(const FontDescription& fontDescription, float scaleFactor) const
301 {
302     if (isCustomFont()) {
303         FontPlatformData scaledFontData(m_platformData);
304         scaledFontData.m_size = scaledFontData.m_size * scaleFactor;
305         return adoptPtr(new SimpleFontData(scaledFontData, true, false));
306     }
307
308     BEGIN_BLOCK_OBJC_EXCEPTIONS;
309     float size = m_platformData.size() * scaleFactor;
310     FontPlatformData scaledFontData([[NSFontManager sharedFontManager] convertFont:m_platformData.font() toSize:size], size, false, false, m_platformData.orientation());
311
312     // AppKit resets the type information (screen/printer) when you convert a font to a different size.
313     // We have to fix up the font that we're handed back.
314     scaledFontData.setFont(fontDescription.usePrinterFont() ? [scaledFontData.font() printerFont] : [scaledFontData.font() screenFont]);
315
316     if (scaledFontData.font()) {
317         NSFontManager *fontManager = [NSFontManager sharedFontManager];
318         NSFontTraitMask fontTraits = [fontManager traitsOfFont:m_platformData.font()];
319
320         if (m_platformData.m_syntheticBold)
321             fontTraits |= NSBoldFontMask;
322         if (m_platformData.m_syntheticOblique)
323             fontTraits |= NSItalicFontMask;
324
325         NSFontTraitMask scaledFontTraits = [fontManager traitsOfFont:scaledFontData.font()];
326         scaledFontData.m_syntheticBold = (fontTraits & NSBoldFontMask) && !(scaledFontTraits & NSBoldFontMask);
327         scaledFontData.m_syntheticOblique = (fontTraits & NSItalicFontMask) && !(scaledFontTraits & NSItalicFontMask);
328
329         // SimpleFontData::platformDestroy() takes care of not deleting the cached font data twice.
330         return adoptPtr(fontCache()->getCachedFontData(&scaledFontData));
331     }
332     END_BLOCK_OBJC_EXCEPTIONS;
333
334     return nullptr;
335 }
336
337 SimpleFontData* SimpleFontData::smallCapsFontData(const FontDescription& fontDescription) const
338 {
339     if (!m_derivedFontData)
340         m_derivedFontData = DerivedFontData::create(isCustomFont());
341     if (!m_derivedFontData->smallCaps)
342         m_derivedFontData->smallCaps = createScaledFontData(fontDescription, smallCapsFontSizeMultiplier);
343
344     return m_derivedFontData->smallCaps.get();
345 }
346
347 SimpleFontData* SimpleFontData::emphasisMarkFontData(const FontDescription& fontDescription) const
348 {
349     if (!m_derivedFontData)
350         m_derivedFontData = DerivedFontData::create(isCustomFont());
351     if (!m_derivedFontData->emphasisMark)
352         m_derivedFontData->emphasisMark = createScaledFontData(fontDescription, .5f);
353
354     return m_derivedFontData->emphasisMark.get();
355 }
356
357 bool SimpleFontData::containsCharacters(const UChar* characters, int length) const
358 {
359     NSString *string = [[NSString alloc] initWithCharactersNoCopy:const_cast<unichar*>(characters) length:length freeWhenDone:NO];
360     NSCharacterSet *set = [[m_platformData.font() coveredCharacterSet] invertedSet];
361     bool result = set && [string rangeOfCharacterFromSet:set].location == NSNotFound;
362     [string release];
363     return result;
364 }
365
366 void SimpleFontData::determinePitch()
367 {
368     NSFont* f = m_platformData.font();
369     // Special case Osaka-Mono.
370     // According to <rdar://problem/3999467>, we should treat Osaka-Mono as fixed pitch.
371     // Note that the AppKit does not report Osaka-Mono as fixed pitch.
372
373     // Special case MS-PGothic.
374     // According to <rdar://problem/4032938>, we should not treat MS-PGothic as fixed pitch.
375     // Note that AppKit does report MS-PGothic as fixed pitch.
376
377     // Special case MonotypeCorsiva
378     // According to <rdar://problem/5454704>, we should not treat MonotypeCorsiva as fixed pitch.
379     // Note that AppKit does report MonotypeCorsiva as fixed pitch.
380
381     NSString *name = [f fontName];
382     m_treatAsFixedPitch = ([f isFixedPitch] || [f _isFakeFixedPitch] ||
383            [name caseInsensitiveCompare:@"Osaka-Mono"] == NSOrderedSame) &&
384            [name caseInsensitiveCompare:@"MS-PGothic"] != NSOrderedSame &&
385            [name caseInsensitiveCompare:@"MonotypeCorsiva"] != NSOrderedSame;
386 }
387
388 FloatRect SimpleFontData::platformBoundsForGlyph(Glyph glyph) const
389 {
390     FloatRect boundingBox;
391     boundingBox = CTFontGetBoundingRectsForGlyphs(m_platformData.ctFont(), platformData().orientation() == Vertical ? kCTFontVerticalOrientation : kCTFontHorizontalOrientation, &glyph, 0, 1);
392     boundingBox.setY(-boundingBox.maxY());
393     if (m_syntheticBoldOffset)
394         boundingBox.setWidth(boundingBox.width() + m_syntheticBoldOffset);
395
396     return boundingBox;
397 }
398
399 float SimpleFontData::platformWidthForGlyph(Glyph glyph) const
400 {
401     CGSize advance = CGSizeZero;
402     if (platformData().orientation() == Horizontal || m_isBrokenIdeographFallback) {
403         NSFont *font = platformData().font();
404         if (font && platformData().isColorBitmapFont())
405             advance = NSSizeToCGSize([font advancementForGlyph:glyph]);
406         else {
407             float pointSize = platformData().m_size;
408             CGAffineTransform m = CGAffineTransformMakeScale(pointSize, pointSize);
409             if (!wkGetGlyphTransformedAdvances(platformData().cgFont(), font, &m, &glyph, &advance)) {
410                 LOG_ERROR("Unable to cache glyph widths for %@ %f", [font displayName], pointSize);
411                 advance.width = 0;
412             }
413         }
414     } else
415         CTFontGetAdvancesForGlyphs(m_platformData.ctFont(), kCTFontVerticalOrientation, &glyph, &advance, 1);
416
417     return advance.width + m_syntheticBoldOffset;
418 }
419
420 struct ProviderInfo {
421     const UChar* characters;
422     size_t length;
423     CFDictionaryRef attributes;
424 };
425
426 static const UniChar* provideStringAndAttributes(CFIndex stringIndex, CFIndex* count, CFDictionaryRef* attributes, void* context)
427 {
428     ProviderInfo* info = static_cast<struct ProviderInfo*>(context);
429     if (stringIndex < 0 || static_cast<size_t>(stringIndex) >= info->length)
430         return 0;
431
432     *count = info->length - stringIndex;
433     *attributes = info->attributes;
434     return info->characters + stringIndex;
435 }
436
437 bool SimpleFontData::canRenderCombiningCharacterSequence(const UChar* characters, size_t length) const
438 {
439     ASSERT(isMainThread());
440
441     if (!m_combiningCharacterSequenceSupport)
442         m_combiningCharacterSequenceSupport = adoptPtr(new HashMap<String, bool>);
443
444     pair<WTF::HashMap<String, bool>::iterator, bool> addResult = m_combiningCharacterSequenceSupport->add(String(characters, length), false);
445     if (!addResult.second)
446         return addResult.first->second;
447
448     RetainPtr<CGFontRef> cgFont(AdoptCF, CTFontCopyGraphicsFont(platformData().ctFont(), 0));
449
450     ProviderInfo info = { characters, length, getCFStringAttributes(0, platformData().orientation()) };
451     RetainPtr<CTLineRef> line(AdoptCF, wkCreateCTLineWithUniCharProvider(&provideStringAndAttributes, 0, &info));
452
453     CFArrayRef runArray = CTLineGetGlyphRuns(line.get());
454     CFIndex runCount = CFArrayGetCount(runArray);
455
456     for (CFIndex r = 0; r < runCount; r++) {
457         CTRunRef ctRun = static_cast<CTRunRef>(CFArrayGetValueAtIndex(runArray, r));
458         ASSERT(CFGetTypeID(ctRun) == CTRunGetTypeID());
459         CFDictionaryRef runAttributes = CTRunGetAttributes(ctRun);
460         CTFontRef runFont = static_cast<CTFontRef>(CFDictionaryGetValue(runAttributes, kCTFontAttributeName));
461         RetainPtr<CGFontRef> runCGFont(AdoptCF, CTFontCopyGraphicsFont(runFont, 0));
462         if (!CFEqual(runCGFont.get(), cgFont.get()))
463             return false;
464     }
465
466     addResult.first->second = true;
467     return true;
468 }
469
470 } // namespace WebCore