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());
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());
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;
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);
224 // Compute and store line spacing, before the line metrics hacks are applied.
225 m_fontMetrics.setLineSpacing(lroundf(ascent) + lroundf(descent) + lroundf(lineGap));
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;
234 if (platformData().orientation() == Vertical && !isTextOrientationFallback())
235 m_hasVerticalGlyphs = fontHasVerticalGlyphs(m_platformData.ctFont());
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;
245 xHeight = -CGRectGetMinY(platformBoundsForGlyph(xGlyph));
247 xHeight = scaleEmToUnits(CGFontGetXHeight(m_platformData.cgFont()), unitsPerEm) * pointSize;
249 xHeight = verticalRightOrientationFontData()->fontMetrics().xHeight();
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);
258 static CFDataRef copyFontTableForTag(FontPlatformData& platformData, FourCharCode tableName)
260 return CGFontCopyTableForTag(platformData.cgFont(), tableName);
263 void SimpleFontData::platformCharWidthInit()
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;
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;
286 // Fallback to a cross-platform estimate, which will populate these values if they are non-positive.
290 void SimpleFontData::platformDestroy()
292 if (!isCustomFont() && m_derivedFontData) {
293 // These come from the cache.
294 if (m_derivedFontData->smallCaps)
295 FontCache::fontCache()->releaseFontData(m_derivedFontData->smallCaps.get());
297 if (m_derivedFontData->emphasisMark)
298 FontCache::fontCache()->releaseFontData(m_derivedFontData->emphasisMark.get());
302 PassRefPtr<SimpleFontData> SimpleFontData::platformCreateScaledFontData(const FontDescription& fontDescription, float scaleFactor) const
304 if (isCustomFont()) {
305 FontPlatformData scaledFontData(m_platformData);
306 scaledFontData.m_size = scaledFontData.m_size * scaleFactor;
307 return SimpleFontData::create(scaledFontData, CustomFontData::create(false));
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());
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]);
318 if (scaledFontData.font()) {
319 NSFontManager *fontManager = [NSFontManager sharedFontManager];
320 NSFontTraitMask fontTraits = [fontManager traitsOfFont:m_platformData.font()];
322 if (m_platformData.m_syntheticBold)
323 fontTraits |= NSBoldFontMask;
324 if (m_platformData.m_syntheticOblique)
325 fontTraits |= NSItalicFontMask;
327 NSFontTraitMask scaledFontTraits = [fontManager traitsOfFont:scaledFontData.font()];
328 scaledFontData.m_syntheticBold = (fontTraits & NSBoldFontMask) && !(scaledFontTraits & NSBoldFontMask);
329 scaledFontData.m_syntheticOblique = (fontTraits & NSItalicFontMask) && !(scaledFontTraits & NSItalicFontMask);
331 // SimpleFontData::platformDestroy() takes care of not deleting the cached font data twice.
332 return FontCache::fontCache()->fontDataFromFontPlatformData(&scaledFontData);
334 END_BLOCK_OBJC_EXCEPTIONS;
339 bool SimpleFontData::containsCharacters(const UChar* characters, int length) const
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;
348 void SimpleFontData::determinePitch()
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.
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.
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.
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;
370 FloatRect SimpleFontData::platformBoundsForGlyph(Glyph glyph) const
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);
381 float SimpleFontData::platformWidthForGlyph(Glyph glyph) const
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]);
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);
397 CTFontGetAdvancesForGlyphs(m_platformData.ctFont(), kCTFontVerticalOrientation, &glyph, &advance, 1);
399 return advance.width + m_syntheticBoldOffset;
402 struct ProviderInfo {
403 const UChar* characters;
405 CFDictionaryRef attributes;
408 static const UniChar* provideStringAndAttributes(CFIndex stringIndex, CFIndex* count, CFDictionaryRef* attributes, void* context)
410 ProviderInfo* info = static_cast<struct ProviderInfo*>(context);
411 if (stringIndex < 0 || static_cast<size_t>(stringIndex) >= info->length)
414 *count = info->length - stringIndex;
415 *attributes = info->attributes;
416 return info->characters + stringIndex;
419 bool SimpleFontData::canRenderCombiningCharacterSequence(const UChar* characters, size_t length) const
421 ASSERT(isMainThread());
423 if (!m_combiningCharacterSequenceSupport)
424 m_combiningCharacterSequenceSupport = adoptPtr(new HashMap<String, bool>);
426 WTF::HashMap<String, bool>::AddResult addResult = m_combiningCharacterSequenceSupport->add(String(characters, length), false);
427 if (!addResult.isNewEntry)
428 return addResult.iterator->value;
430 RetainPtr<CGFontRef> cgFont(AdoptCF, CTFontCopyGraphicsFont(platformData().ctFont(), 0));
432 ProviderInfo info = { characters, length, getCFStringAttributes(0, platformData().orientation()) };
433 RetainPtr<CTLineRef> line(AdoptCF, CTLineCreateWithUniCharProvider(&provideStringAndAttributes, 0, &info));
435 CFArrayRef runArray = CTLineGetGlyphRuns(line.get());
436 CFIndex runCount = CFArrayGetCount(runArray);
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()))
448 addResult.iterator->value = true;
452 } // namespace WebCore