2 * Copyright (C) 2005, 2006, 2010, 2011 Apple Inc. All rights reserved.
3 * Copyright (C) 2006 Alexey Proskuryakov
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
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.
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.
28 #import "SimpleFontData.h"
30 #import "BlockExceptions.h"
35 #import "FontDescription.h"
36 #import "SharedBuffer.h"
37 #import "WebCoreSystemInterface.h"
38 #import <AppKit/AppKit.h>
39 #import <ApplicationServices/ApplicationServices.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>
47 @interface NSFont (WebAppKitSecretAPI)
48 - (BOOL)_isFakeFixedPitch;
55 const float smallCapsFontSizeMultiplier = 0.7f;
57 static bool fontHasVerticalGlyphs(CTFontRef ctFont)
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)
70 static bool initFontData(SimpleFontData* fontData)
72 if (!fontData->platformData().cgFont())
79 static NSString *webFallbackFontFamily(void)
81 DEFINE_STATIC_LOCAL(RetainPtr<NSString>, webFallbackFontFamily, ([[NSFont systemFontOfSize:16.0f] familyName]));
82 return webFallbackFontFamily.get();
86 #if defined(__LP64__) || (!defined(BUILDING_ON_LEOPARD) && !defined(BUILDING_ON_SNOW_LEOPARD))
87 static NSString* pathFromFont(NSFont*)
89 // FMGetATSFontRefFromFont is not available. As pathFromFont is only used for debugging purposes,
90 // returning nil is acceptable.
94 static NSString* pathFromFont(NSFont *font)
96 ATSFontRef atsFont = FMGetATSFontRefFromFont(CTFontGetPlatformFont(toCTFontRef(font), 0));
99 OSStatus status = ATSFontGetFileReference(atsFont, &fileRef);
103 UInt8 filePathBuffer[PATH_MAX];
104 status = FSRefMakePath(&fileRef, filePathBuffer, PATH_MAX);
106 return [NSString stringWithUTF8String:(const char*)filePathBuffer];
111 #endif // !ERROR_DISABLED
113 void SimpleFontData::platformInit()
116 m_ATSUMirrors = false;
117 m_checkedShapesArabic = false;
118 m_shapesArabic = false;
121 m_syntheticBoldOffset = m_platformData.m_syntheticBold ? 1.0f : 0.f;
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.
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";
136 fallbackFontFamily = webFallbackFontFamily();
138 // Try setting up the alternate font.
139 // This is a last ditch effort to use a substitute font when something has gone wrong.
141 RetainPtr<NSFont> initialFont = m_platformData.font();
143 if (m_platformData.font())
144 m_platformData.setFont([[NSFontManager sharedFontManager] convertFont:m_platformData.font() toFamily:fallbackFontFamily]);
146 m_platformData.setFont([NSFont fontWithName:fallbackFontFamily size:m_platformData.size()]);
148 NSString *filePath = pathFromFont(initialFont.get());
150 filePath = @"not known";
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);
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);
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);
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.
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());
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());
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;
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.
216 // Compute and store line spacing, before the line metrics hacks are applied.
217 m_fontMetrics.setLineSpacing(lroundf(ascent) + lroundf(descent) + lroundf(lineGap));
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;
226 if (platformData().orientation() == Vertical && !isTextOrientationFallback())
227 m_hasVerticalGlyphs = fontHasVerticalGlyphs(m_platformData.ctFont());
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;
237 xHeight = -CGRectGetMinY(platformBoundsForGlyph(xGlyph));
239 xHeight = scaleEmToUnits(CGFontGetXHeight(m_platformData.cgFont()), unitsPerEm) * pointSize;
241 xHeight = verticalRightOrientationFontData()->fontMetrics().xHeight();
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);
250 static CFDataRef copyFontTableForTag(FontPlatformData& platformData, FourCharCode tableName)
252 return CGFontCopyTableForTag(platformData.cgFont(), tableName);
255 void SimpleFontData::platformCharWidthInit()
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;
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;
278 // Fallback to a cross-platform estimate, which will populate these values if they are non-positive.
282 void SimpleFontData::platformDestroy()
284 if (!isCustomFont() && m_derivedFontData) {
285 // These come from the cache.
286 if (m_derivedFontData->smallCaps)
287 fontCache()->releaseFontData(m_derivedFontData->smallCaps.leakPtr());
289 if (m_derivedFontData->emphasisMark)
290 fontCache()->releaseFontData(m_derivedFontData->emphasisMark.leakPtr());
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);
300 PassOwnPtr<SimpleFontData> SimpleFontData::createScaledFontData(const FontDescription& fontDescription, float scaleFactor) const
302 if (isCustomFont()) {
303 FontPlatformData scaledFontData(m_platformData);
304 scaledFontData.m_size = scaledFontData.m_size * scaleFactor;
305 return adoptPtr(new SimpleFontData(scaledFontData, true, false));
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());
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]);
316 if (scaledFontData.font()) {
317 NSFontManager *fontManager = [NSFontManager sharedFontManager];
318 NSFontTraitMask fontTraits = [fontManager traitsOfFont:m_platformData.font()];
320 if (m_platformData.m_syntheticBold)
321 fontTraits |= NSBoldFontMask;
322 if (m_platformData.m_syntheticOblique)
323 fontTraits |= NSItalicFontMask;
325 NSFontTraitMask scaledFontTraits = [fontManager traitsOfFont:scaledFontData.font()];
326 scaledFontData.m_syntheticBold = (fontTraits & NSBoldFontMask) && !(scaledFontTraits & NSBoldFontMask);
327 scaledFontData.m_syntheticOblique = (fontTraits & NSItalicFontMask) && !(scaledFontTraits & NSItalicFontMask);
329 // SimpleFontData::platformDestroy() takes care of not deleting the cached font data twice.
330 return adoptPtr(fontCache()->getCachedFontData(&scaledFontData));
332 END_BLOCK_OBJC_EXCEPTIONS;
337 SimpleFontData* SimpleFontData::smallCapsFontData(const FontDescription& fontDescription) const
339 if (!m_derivedFontData)
340 m_derivedFontData = DerivedFontData::create(isCustomFont());
341 if (!m_derivedFontData->smallCaps)
342 m_derivedFontData->smallCaps = createScaledFontData(fontDescription, smallCapsFontSizeMultiplier);
344 return m_derivedFontData->smallCaps.get();
347 SimpleFontData* SimpleFontData::emphasisMarkFontData(const FontDescription& fontDescription) const
349 if (!m_derivedFontData)
350 m_derivedFontData = DerivedFontData::create(isCustomFont());
351 if (!m_derivedFontData->emphasisMark)
352 m_derivedFontData->emphasisMark = createScaledFontData(fontDescription, .5f);
354 return m_derivedFontData->emphasisMark.get();
357 bool SimpleFontData::containsCharacters(const UChar* characters, int length) const
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;
366 void SimpleFontData::determinePitch()
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.
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.
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.
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;
388 FloatRect SimpleFontData::platformBoundsForGlyph(Glyph glyph) const
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);
399 float SimpleFontData::platformWidthForGlyph(Glyph glyph) const
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]);
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);
415 CTFontGetAdvancesForGlyphs(m_platformData.ctFont(), kCTFontVerticalOrientation, &glyph, &advance, 1);
417 return advance.width + m_syntheticBoldOffset;
420 struct ProviderInfo {
421 const UChar* characters;
423 CFDictionaryRef attributes;
426 static const UniChar* provideStringAndAttributes(CFIndex stringIndex, CFIndex* count, CFDictionaryRef* attributes, void* context)
428 ProviderInfo* info = static_cast<struct ProviderInfo*>(context);
429 if (stringIndex < 0 || static_cast<size_t>(stringIndex) >= info->length)
432 *count = info->length - stringIndex;
433 *attributes = info->attributes;
434 return info->characters + stringIndex;
437 bool SimpleFontData::canRenderCombiningCharacterSequence(const UChar* characters, size_t length) const
439 ASSERT(isMainThread());
441 if (!m_combiningCharacterSequenceSupport)
442 m_combiningCharacterSequenceSupport = adoptPtr(new HashMap<String, bool>);
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;
448 RetainPtr<CGFontRef> cgFont(AdoptCF, CTFontCopyGraphicsFont(platformData().ctFont(), 0));
450 ProviderInfo info = { characters, length, getCFStringAttributes(0, platformData().orientation()) };
451 RetainPtr<CTLineRef> line(AdoptCF, wkCreateCTLineWithUniCharProvider(&provideStringAndAttributes, 0, &info));
453 CFArrayRef runArray = CTLineGetGlyphRuns(line.get());
454 CFIndex runCount = CFArrayGetCount(runArray);
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()))
466 addResult.first->second = true;
470 } // namespace WebCore