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 "platform/fonts/SimpleFontData.h"
30 #import <AppKit/AppKit.h>
31 #import <ApplicationServices/ApplicationServices.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>
45 @interface NSFont (WebAppKitSecretAPI)
46 - (BOOL)_isFakeFixedPitch;
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
58 // Forward declare Mac SPIs.
60 // Request for public API: rdar://13803586
61 bool CGFontGetGlyphAdvancesForStyle(CGFontRef font, CGAffineTransform* transform, CGFontRenderingMode renderingMode, ATSGlyphRef* glyph, size_t count, CGSize* advance);
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);
67 static CGFontRenderingMode cgFontRenderingModeForNSFont(NSFont* font) {
69 return kCGFontRenderingModeAntialiasedPixelAligned;
71 switch ([font renderingMode]) {
72 case NSFontIntegerAdvancementsRenderingMode: return kCGFontRenderingMode1BitPixelAligned;
73 case NSFontAntialiasedIntegerAdvancementsRenderingMode: return kCGFontRenderingModeAntialiasedPixelAligned;
74 default: return kCGFontRenderingModeAntialiased;
82 static bool fontHasVerticalGlyphs(CTFontRef ctFont)
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)
95 static bool initFontData(SimpleFontData* fontData)
97 if (!fontData->platformData().cgFont())
103 static NSString *webFallbackFontFamily(void)
105 DEFINE_STATIC_LOCAL(RetainPtr<NSString>, webFallbackFontFamily, ([[NSFont systemFontOfSize:16.0f] familyName]));
106 return webFallbackFontFamily.get();
109 const SimpleFontData* SimpleFontData::getCompositeFontReferenceFontData(NSFont *key) const
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));
117 const SimpleFontData* found = static_cast<const SimpleFontData*>(CFDictionaryGetValue(m_derivedFontData->compositeFontReferences.get(), static_cast<const void *>(key)));
121 if (CFMutableDictionaryRef dictionary = m_derivedFontData->compositeFontReferences.get()) {
122 bool isUsingPrinterFont = platformData().isPrinterFont();
123 NSFont *substituteFont = isUsingPrinterFont ? [key printerFont] : [key screenFont];
125 CTFontSymbolicTraits traits = CTFontGetSymbolicTraits(toCTFontRef(substituteFont));
126 bool syntheticBold = platformData().syntheticBold() && !(traits & kCTFontBoldTrait);
127 bool syntheticOblique = platformData().syntheticOblique() && !(traits & kCTFontItalicTrait);
129 FontPlatformData substitutePlatform(substituteFont, platformData().size(), isUsingPrinterFont, syntheticBold, syntheticOblique, platformData().orientation(), platformData().widthVariant());
130 SimpleFontData* value = new SimpleFontData(substitutePlatform, isCustomFont() ? CustomFontData::create(false) : 0);
132 CFDictionaryAddValue(dictionary, key, value);
140 void SimpleFontData::platformInit()
142 m_syntheticBoldOffset = m_platformData.m_syntheticBold ? 1.0f : 0.f;
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.
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";
157 fallbackFontFamily = webFallbackFontFamily();
159 // Try setting up the alternate font.
160 // This is a last ditch effort to use a substitute font when something has gone wrong.
162 RetainPtr<NSFont> initialFont = m_platformData.font();
164 if (m_platformData.font())
165 m_platformData.setFont([[NSFontManager sharedFontManager] convertFont:m_platformData.font() toFamily:fallbackFontFamily]);
167 m_platformData.setFont([NSFont fontWithName:fallbackFontFamily size:m_platformData.size()]);
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());
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());
186 // Report the problem.
187 WTF_LOG_ERROR("Corrupt font detected, using %@ in place of %@.",
188 [m_platformData.font() familyName], [initialFont.get() familyName]);
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.
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());
204 iAscent = CGFontGetAscent(m_platformData.cgFont());
205 // Some fonts erroneously specify a positive descender value. We follow Core Text in assuming that
206 // such fonts meant the same distance, but in the reverse direction.
207 iDescent = -abs(CGFontGetDescent(m_platformData.cgFont()));
208 iLineGap = CGFontGetLeading(m_platformData.cgFont());
209 unitsPerEm = CGFontGetUnitsPerEm(m_platformData.cgFont());
211 float pointSize = m_platformData.m_size;
212 float ascent = scaleEmToUnits(iAscent, unitsPerEm) * pointSize;
213 float descent = -scaleEmToUnits(iDescent, unitsPerEm) * pointSize;
214 float lineGap = scaleEmToUnits(iLineGap, unitsPerEm) * pointSize;
215 float underlineThickness = CTFontGetUnderlineThickness(m_platformData.ctFont());
217 // We need to adjust Times, Helvetica, and Courier to closely match the
218 // vertical metrics of their Microsoft counterparts that are the de facto
219 // web standard. The AppKit adjustment of 20% is too big and is
220 // incorrectly added to line spacing, so we use a 15% adjustment instead
221 // and add it to the ascent.
222 NSString *familyName = [m_platformData.font() familyName];
223 if ([familyName isEqualToString:@"Times"] || [familyName isEqualToString:@"Helvetica"] || [familyName isEqualToString:@"Courier"])
224 ascent += floorf(((ascent + descent) * 0.15f) + 0.5f);
226 // Compute and store line spacing, before the line metrics hacks are applied.
227 m_fontMetrics.setLineSpacing(lroundf(ascent) + lroundf(descent) + lroundf(lineGap));
229 // Hack Hiragino line metrics to allow room for marked text underlines.
230 // <rdar://problem/5386183>
231 if (descent < 3 && lineGap >= 3 && [familyName hasPrefix:@"Hiragino"]) {
232 lineGap -= 3 - descent;
236 if (platformData().orientation() == Vertical && !isTextOrientationFallback())
237 m_hasVerticalGlyphs = fontHasVerticalGlyphs(m_platformData.ctFont());
241 if (platformData().orientation() == Horizontal) {
242 // Measure the actual character "x", since it's possible for it to extend below the baseline, and we need the
243 // reported x-height to only include the portion of the glyph that is above the baseline.
244 GlyphPage* glyphPageZero = GlyphPageTreeNode::getRootChild(this, 0)->page();
245 NSGlyph xGlyph = glyphPageZero ? glyphPageZero->glyphForCharacter('x') : 0;
247 xHeight = -CGRectGetMinY(platformBoundsForGlyph(xGlyph));
249 xHeight = scaleEmToUnits(CGFontGetXHeight(m_platformData.cgFont()), unitsPerEm) * pointSize;
251 xHeight = verticalRightOrientationFontData()->fontMetrics().xHeight();
253 m_fontMetrics.setUnitsPerEm(unitsPerEm);
254 m_fontMetrics.setAscent(ascent);
255 m_fontMetrics.setDescent(descent);
256 m_fontMetrics.setLineGap(lineGap);
257 m_fontMetrics.setXHeight(xHeight);
258 m_fontMetrics.setUnderlineThickness(underlineThickness);
261 static CFDataRef copyFontTableForTag(FontPlatformData& platformData, FourCharCode tableName)
263 return CGFontCopyTableForTag(platformData.cgFont(), tableName);
266 void SimpleFontData::platformCharWidthInit()
271 RetainPtr<CFDataRef> os2Table(AdoptCF, copyFontTableForTag(m_platformData, 'OS/2'));
272 if (os2Table && CFDataGetLength(os2Table.get()) >= 4) {
273 const UInt8* os2 = CFDataGetBytePtr(os2Table.get());
274 SInt16 os2AvgCharWidth = os2[2] * 256 + os2[3];
275 m_avgCharWidth = scaleEmToUnits(os2AvgCharWidth, m_fontMetrics.unitsPerEm()) * m_platformData.m_size;
278 RetainPtr<CFDataRef> headTable(AdoptCF, copyFontTableForTag(m_platformData, 'head'));
279 if (headTable && CFDataGetLength(headTable.get()) >= 42) {
280 const UInt8* head = CFDataGetBytePtr(headTable.get());
281 ushort uxMin = head[36] * 256 + head[37];
282 ushort uxMax = head[40] * 256 + head[41];
283 SInt16 xMin = static_cast<SInt16>(uxMin);
284 SInt16 xMax = static_cast<SInt16>(uxMax);
285 float diff = static_cast<float>(xMax - xMin);
286 m_maxCharWidth = scaleEmToUnits(diff, m_fontMetrics.unitsPerEm()) * m_platformData.m_size;
289 // Fallback to a cross-platform estimate, which will populate these values if they are non-positive.
293 void SimpleFontData::platformDestroy()
295 if (!isCustomFont() && m_derivedFontData) {
296 // These come from the cache.
297 if (m_derivedFontData->smallCaps)
298 FontCache::fontCache()->releaseFontData(m_derivedFontData->smallCaps.get());
300 if (m_derivedFontData->emphasisMark)
301 FontCache::fontCache()->releaseFontData(m_derivedFontData->emphasisMark.get());
305 PassRefPtr<SimpleFontData> SimpleFontData::platformCreateScaledFontData(const FontDescription& fontDescription, float scaleFactor) const
307 if (isCustomFont()) {
308 FontPlatformData scaledFontData(m_platformData);
309 scaledFontData.m_size = scaledFontData.m_size * scaleFactor;
310 return SimpleFontData::create(scaledFontData, CustomFontData::create(false));
313 BEGIN_BLOCK_OBJC_EXCEPTIONS;
314 float size = m_platformData.size() * scaleFactor;
315 FontPlatformData scaledFontData([[NSFontManager sharedFontManager] convertFont:m_platformData.font() toSize:size], size, m_platformData.isPrinterFont(), false, false, m_platformData.orientation());
317 // AppKit resets the type information (screen/printer) when you convert a font to a different size.
318 // We have to fix up the font that we're handed back.
319 scaledFontData.setFont(fontDescription.usePrinterFont() ? [scaledFontData.font() printerFont] : [scaledFontData.font() screenFont]);
321 if (scaledFontData.font()) {
322 NSFontManager *fontManager = [NSFontManager sharedFontManager];
323 NSFontTraitMask fontTraits = [fontManager traitsOfFont:m_platformData.font()];
325 if (m_platformData.m_syntheticBold)
326 fontTraits |= NSBoldFontMask;
327 if (m_platformData.m_syntheticOblique)
328 fontTraits |= NSItalicFontMask;
330 NSFontTraitMask scaledFontTraits = [fontManager traitsOfFont:scaledFontData.font()];
331 scaledFontData.m_syntheticBold = (fontTraits & NSBoldFontMask) && !(scaledFontTraits & NSBoldFontMask);
332 scaledFontData.m_syntheticOblique = (fontTraits & NSItalicFontMask) && !(scaledFontTraits & NSItalicFontMask);
334 // SimpleFontData::platformDestroy() takes care of not deleting the cached font data twice.
335 return FontCache::fontCache()->fontDataFromFontPlatformData(&scaledFontData);
337 END_BLOCK_OBJC_EXCEPTIONS;
342 void SimpleFontData::determinePitch()
344 NSFont* f = m_platformData.font();
345 // Special case Osaka-Mono.
346 // According to <rdar://problem/3999467>, we should treat Osaka-Mono as fixed pitch.
347 // Note that the AppKit does not report Osaka-Mono as fixed pitch.
349 // Special case MS-PGothic.
350 // According to <rdar://problem/4032938>, we should not treat MS-PGothic as fixed pitch.
351 // Note that AppKit does report MS-PGothic as fixed pitch.
353 // Special case MonotypeCorsiva
354 // According to <rdar://problem/5454704>, we should not treat MonotypeCorsiva as fixed pitch.
355 // Note that AppKit does report MonotypeCorsiva as fixed pitch.
357 NSString *name = [f fontName];
358 m_treatAsFixedPitch = ([f isFixedPitch] || [f _isFakeFixedPitch] ||
359 [name caseInsensitiveCompare:@"Osaka-Mono"] == NSOrderedSame) &&
360 [name caseInsensitiveCompare:@"MS-PGothic"] != NSOrderedSame &&
361 [name caseInsensitiveCompare:@"MonotypeCorsiva"] != NSOrderedSame;
364 FloatRect SimpleFontData::platformBoundsForGlyph(Glyph glyph) const
366 FloatRect boundingBox;
367 boundingBox = CTFontGetBoundingRectsForGlyphs(m_platformData.ctFont(), platformData().orientation() == Vertical ? kCTFontVerticalOrientation : kCTFontHorizontalOrientation, &glyph, 0, 1);
368 boundingBox.setY(-boundingBox.maxY());
369 if (m_syntheticBoldOffset)
370 boundingBox.setWidth(boundingBox.width() + m_syntheticBoldOffset);
375 float SimpleFontData::platformWidthForGlyph(Glyph glyph) const
377 CGSize advance = CGSizeZero;
378 if (platformData().orientation() == Horizontal || m_isBrokenIdeographFallback) {
379 NSFont *font = platformData().font();
380 if (font && platformData().isColorBitmapFont())
381 advance = NSSizeToCGSize([font advancementForGlyph:glyph]);
383 float pointSize = platformData().m_size;
384 CGAffineTransform m = CGAffineTransformMakeScale(pointSize, pointSize);
385 if (!CGFontGetGlyphAdvancesForStyle(platformData().cgFont(), &m, cgFontRenderingModeForNSFont(font), &glyph, 1, &advance)) {
386 WTF_LOG_ERROR("Unable to cache glyph widths for %@ %f", [font displayName], pointSize);
391 CTFontGetAdvancesForGlyphs(m_platformData.ctFont(), kCTFontVerticalOrientation, &glyph, &advance, 1);
393 return advance.width + m_syntheticBoldOffset;
396 struct ProviderInfo {
397 const UChar* characters;
399 CFDictionaryRef attributes;
402 static const UniChar* provideStringAndAttributes(CFIndex stringIndex, CFIndex* count, CFDictionaryRef* attributes, void* context)
404 ProviderInfo* info = static_cast<struct ProviderInfo*>(context);
405 if (stringIndex < 0 || static_cast<size_t>(stringIndex) >= info->length)
408 *count = info->length - stringIndex;
409 *attributes = info->attributes;
410 return info->characters + stringIndex;
413 bool SimpleFontData::canRenderCombiningCharacterSequence(const UChar* characters, size_t length) const
415 ASSERT(isMainThread());
417 if (!m_combiningCharacterSequenceSupport)
418 m_combiningCharacterSequenceSupport = adoptPtr(new HashMap<String, bool>);
420 WTF::HashMap<String, bool>::AddResult addResult = m_combiningCharacterSequenceSupport->add(String(characters, length), false);
421 if (!addResult.isNewEntry)
422 return addResult.storedValue->value;
424 RetainPtr<CGFontRef> cgFont(AdoptCF, CTFontCopyGraphicsFont(platformData().ctFont(), 0));
426 ProviderInfo info = { characters, length, getCFStringAttributes(0, platformData().orientation()) };
427 RetainPtr<CTLineRef> line(AdoptCF, CTLineCreateWithUniCharProvider(&provideStringAndAttributes, 0, &info));
429 CFArrayRef runArray = CTLineGetGlyphRuns(line.get());
430 CFIndex runCount = CFArrayGetCount(runArray);
432 for (CFIndex r = 0; r < runCount; r++) {
433 CTRunRef ctRun = static_cast<CTRunRef>(CFArrayGetValueAtIndex(runArray, r));
434 ASSERT(CFGetTypeID(ctRun) == CTRunGetTypeID());
435 CFDictionaryRef runAttributes = CTRunGetAttributes(ctRun);
436 CTFontRef runFont = static_cast<CTFontRef>(CFDictionaryGetValue(runAttributes, kCTFontAttributeName));
437 RetainPtr<CGFontRef> runCGFont(AdoptCF, CTFontCopyGraphicsFont(runFont, 0));
438 if (!CFEqual(runCGFont.get(), cgFont.get()))
442 addResult.storedValue->value = true;
446 } // namespace WebCore