2 * Copyright (C) 2005, 2006 Apple Computer, 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
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
15 * its contributors may be used to endorse or promote products derived
16 * from this software without specific prior written permission.
18 * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
19 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
20 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21 * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
22 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
23 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
24 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
25 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
27 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31 #import "SimpleFontData.h"
33 #import "BlockExceptions.h"
38 #import "FontDescription.h"
39 #import "SharedBuffer.h"
40 #import "WebCoreSystemInterface.h"
41 #import <AppKit/AppKit.h>
42 #import <ApplicationServices/ApplicationServices.h>
44 #import <unicode/uchar.h>
45 #import <wtf/Assertions.h>
46 #import <wtf/StdLibExtras.h>
47 #import <wtf/RetainPtr.h>
48 #import <wtf/UnusedParam.h>
50 @interface NSFont (WebAppKitSecretAPI)
51 - (BOOL)_isFakeFixedPitch;
58 const float smallCapsFontSizeMultiplier = 0.7f;
59 static inline float scaleEmToUnits(float x, unsigned unitsPerEm) { return x / unitsPerEm; }
61 static bool initFontData(SimpleFontData* fontData)
63 if (!fontData->platformData().cgFont())
66 #ifdef BUILDING_ON_TIGER
68 if (ATSUCreateStyle(&fontStyle) != noErr)
71 ATSUFontID fontId = fontData->platformData().m_atsuFontID;
73 ATSUDisposeStyle(fontStyle);
77 ATSUAttributeTag tag = kATSUFontTag;
78 ByteCount size = sizeof(ATSUFontID);
79 ATSUFontID *valueArray[1] = {&fontId};
80 OSStatus status = ATSUSetAttributes(fontStyle, 1, &tag, &size, (void* const*)valueArray);
81 if (status != noErr) {
82 ATSUDisposeStyle(fontStyle);
86 if (wkGetATSStyleGroup(fontStyle, &fontData->m_styleGroup) != noErr) {
87 ATSUDisposeStyle(fontStyle);
91 ATSUDisposeStyle(fontStyle);
97 static NSString *webFallbackFontFamily(void)
99 DEFINE_STATIC_LOCAL(RetainPtr<NSString>, webFallbackFontFamily, ([[NSFont systemFontOfSize:16.0f] familyName]));
100 return webFallbackFontFamily.get();
104 #if defined(__LP64__) || (!defined(BUILDING_ON_TIGER) && !defined(BUILDING_ON_LEOPARD) && !defined(BUILDING_ON_SNOW_LEOPARD))
105 static NSString* pathFromFont(NSFont*)
107 // FMGetATSFontRefFromFont is not available. As pathFromFont is only used for debugging purposes,
108 // returning nil is acceptable.
112 static NSString* pathFromFont(NSFont *font)
114 #ifndef BUILDING_ON_TIGER
115 ATSFontRef atsFont = FMGetATSFontRefFromFont(CTFontGetPlatformFont(toCTFontRef(font), 0));
117 ATSFontRef atsFont = FMGetATSFontRefFromFont(wkGetNSFontATSUFontId(font));
121 #ifndef BUILDING_ON_TIGER
122 OSStatus status = ATSFontGetFileReference(atsFont, &fileRef);
127 OSStatus status = ATSFontGetFileSpecification(atsFont, &oFile);
131 status = FSpMakeFSRef(&oFile, &fileRef);
136 UInt8 filePathBuffer[PATH_MAX];
137 status = FSRefMakePath(&fileRef, filePathBuffer, PATH_MAX);
139 return [NSString stringWithUTF8String:(const char*)filePathBuffer];
144 #endif // !ERROR_DISABLED
146 void SimpleFontData::platformInit()
148 #ifdef BUILDING_ON_TIGER
152 m_ATSUMirrors = false;
153 m_checkedShapesArabic = false;
154 m_shapesArabic = false;
157 m_syntheticBoldOffset = m_platformData.m_syntheticBold ? 1.0f : 0.f;
159 bool failedSetup = false;
160 if (!initFontData(this)) {
161 // Ack! Something very bad happened, like a corrupt font.
162 // Try looking for an alternate 'base' font for this renderer.
164 // Special case hack to use "Times New Roman" in place of "Times".
165 // "Times RO" is a common font whose family name is "Times".
166 // It overrides the normal "Times" family font.
167 // It also appears to have a corrupt regular variant.
168 NSString *fallbackFontFamily;
169 if ([[m_platformData.font() familyName] isEqual:@"Times"])
170 fallbackFontFamily = @"Times New Roman";
172 fallbackFontFamily = webFallbackFontFamily();
174 // Try setting up the alternate font.
175 // This is a last ditch effort to use a substitute font when something has gone wrong.
177 RetainPtr<NSFont> initialFont = m_platformData.font();
179 if (m_platformData.font())
180 m_platformData.setFont([[NSFontManager sharedFontManager] convertFont:m_platformData.font() toFamily:fallbackFontFamily]);
182 m_platformData.setFont([NSFont fontWithName:fallbackFontFamily size:m_platformData.size()]);
184 NSString *filePath = pathFromFont(initialFont.get());
186 filePath = @"not known";
188 if (!initFontData(this)) {
189 if ([fallbackFontFamily isEqual:@"Times New Roman"]) {
190 // OK, couldn't setup Times New Roman as an alternate to Times, fallback
191 // on the system font. If this fails we have no alternative left.
192 m_platformData.setFont([[NSFontManager sharedFontManager] convertFont:m_platformData.font() toFamily:webFallbackFontFamily()]);
193 if (!initFontData(this)) {
194 // We tried, Times, Times New Roman, and the system font. No joy. We have to give up.
195 LOG_ERROR("unable to initialize with font %@ at %@", initialFont.get(), filePath);
199 // We tried the requested font and the system font. No joy. We have to give up.
200 LOG_ERROR("unable to initialize with font %@ at %@", initialFont.get(), filePath);
205 // Report the problem.
206 LOG_ERROR("Corrupt font detected, using %@ in place of %@ located at \"%@\".",
207 [m_platformData.font() familyName], [initialFont.get() familyName], filePath);
210 // If all else fails, try to set up using the system font.
211 // This is probably because Times and Times New Roman are both unavailable.
213 m_platformData.setFont([NSFont systemFontOfSize:[m_platformData.font() pointSize]]);
214 LOG_ERROR("failed to set up font, using system font %s", m_platformData.font());
222 #ifdef BUILDING_ON_TIGER
223 wkGetFontMetrics(m_platformData.cgFont(), &iAscent, &iDescent, &iLineGap, &unitsPerEm);
225 iAscent = CGFontGetAscent(m_platformData.cgFont());
226 iDescent = CGFontGetDescent(m_platformData.cgFont());
227 iLineGap = CGFontGetLeading(m_platformData.cgFont());
228 unitsPerEm = CGFontGetUnitsPerEm(m_platformData.cgFont());
231 float pointSize = m_platformData.m_size;
232 float ascent = scaleEmToUnits(iAscent, unitsPerEm) * pointSize;
233 float descent = -scaleEmToUnits(iDescent, unitsPerEm) * pointSize;
234 float lineGap = scaleEmToUnits(iLineGap, unitsPerEm) * pointSize;
236 // We need to adjust Times, Helvetica, and Courier to closely match the
237 // vertical metrics of their Microsoft counterparts that are the de facto
238 // web standard. The AppKit adjustment of 20% is too big and is
239 // incorrectly added to line spacing, so we use a 15% adjustment instead
240 // and add it to the ascent.
241 NSString *familyName = [m_platformData.font() familyName];
242 if ([familyName isEqualToString:@"Times"] || [familyName isEqualToString:@"Helvetica"] || [familyName isEqualToString:@"Courier"])
243 ascent += floorf(((ascent + descent) * 0.15f) + 0.5f);
244 #if defined(BUILDING_ON_LEOPARD)
245 else if ([familyName isEqualToString:@"Geeza Pro"]) {
246 // Geeza Pro has glyphs that draw slightly above the ascent or far below the descent. Adjust
247 // those vertical metrics to better match reality, so that diacritics at the bottom of one line
248 // do not overlap diacritics at the top of the next line.
254 // Compute and store line spacing, before the line metrics hacks are applied.
255 m_fontMetrics.setLineSpacing(lroundf(ascent) + lroundf(descent) + lroundf(lineGap));
257 // Hack Hiragino line metrics to allow room for marked text underlines.
258 // <rdar://problem/5386183>
259 if (descent < 3 && lineGap >= 3 && [familyName hasPrefix:@"Hiragino"]) {
260 lineGap -= 3 - descent;
264 if (platformData().orientation() == Vertical && !isTextOrientationFallback()) {
265 // The check doesn't look neat but this is what AppKit does for vertical writing...
266 RetainPtr<CFArrayRef> tableTags(AdoptCF, CTFontCopyAvailableTables(m_platformData.ctFont(), kCTFontTableOptionExcludeSynthetic));
267 CFIndex numTables = CFArrayGetCount(tableTags.get());
268 for (CFIndex index = 0; index < numTables; ++index) {
269 CTFontTableTag tag = (CTFontTableTag)(uintptr_t)CFArrayGetValueAtIndex(tableTags.get(), index);
270 if (tag == kCTFontTableVhea || tag == kCTFontTableVORG) {
271 m_hasVerticalGlyphs = true;
279 if (platformData().orientation() == Horizontal) {
280 // Measure the actual character "x", since it's possible for it to extend below the baseline, and we need the
281 // reported x-height to only include the portion of the glyph that is above the baseline.
282 GlyphPage* glyphPageZero = GlyphPageTreeNode::getRootChild(this, 0)->page();
283 NSGlyph xGlyph = glyphPageZero ? glyphPageZero->glyphDataForCharacter('x').glyph : 0;
285 xHeight = -CGRectGetMinY(platformBoundsForGlyph(xGlyph));
287 xHeight = scaleEmToUnits(CGFontGetXHeight(m_platformData.cgFont()), unitsPerEm) * pointSize;
289 xHeight = verticalRightOrientationFontData()->fontMetrics().xHeight();
291 m_fontMetrics.setUnitsPerEm(unitsPerEm);
292 m_fontMetrics.setAscent(ascent);
293 m_fontMetrics.setDescent(descent);
294 m_fontMetrics.setLineGap(lineGap);
295 m_fontMetrics.setXHeight(xHeight);
298 static CFDataRef copyFontTableForTag(FontPlatformData& platformData, FourCharCode tableName)
300 #ifdef BUILDING_ON_TIGER
301 ATSFontRef atsFont = FMGetATSFontRefFromFont(platformData.m_atsuFontID);
304 if (ATSFontGetTable(atsFont, tableName, 0, 0, NULL, &tableSize) != noErr)
307 CFMutableDataRef data = CFDataCreateMutable(kCFAllocatorDefault, tableSize);
311 CFDataIncreaseLength(data, tableSize);
312 if (ATSFontGetTable(atsFont, tableName, 0, tableSize, CFDataGetMutableBytePtr(data), &tableSize) != noErr) {
319 return CGFontCopyTableForTag(platformData.cgFont(), tableName);
323 void SimpleFontData::platformCharWidthInit()
328 RetainPtr<CFDataRef> os2Table(AdoptCF, copyFontTableForTag(m_platformData, 'OS/2'));
329 if (os2Table && CFDataGetLength(os2Table.get()) >= 4) {
330 const UInt8* os2 = CFDataGetBytePtr(os2Table.get());
331 SInt16 os2AvgCharWidth = os2[2] * 256 + os2[3];
332 m_avgCharWidth = scaleEmToUnits(os2AvgCharWidth, m_fontMetrics.unitsPerEm()) * m_platformData.m_size;
335 RetainPtr<CFDataRef> headTable(AdoptCF, copyFontTableForTag(m_platformData, 'head'));
336 if (headTable && CFDataGetLength(headTable.get()) >= 42) {
337 const UInt8* head = CFDataGetBytePtr(headTable.get());
338 ushort uxMin = head[36] * 256 + head[37];
339 ushort uxMax = head[40] * 256 + head[41];
340 SInt16 xMin = static_cast<SInt16>(uxMin);
341 SInt16 xMax = static_cast<SInt16>(uxMax);
342 float diff = static_cast<float>(xMax - xMin);
343 m_maxCharWidth = scaleEmToUnits(diff, m_fontMetrics.unitsPerEm()) * m_platformData.m_size;
346 // Fallback to a cross-platform estimate, which will populate these values if they are non-positive.
350 void SimpleFontData::platformDestroy()
352 if (!isCustomFont() && m_derivedFontData) {
353 // These come from the cache.
354 if (m_derivedFontData->smallCaps)
355 fontCache()->releaseFontData(m_derivedFontData->smallCaps.leakPtr());
357 if (m_derivedFontData->emphasisMark)
358 fontCache()->releaseFontData(m_derivedFontData->emphasisMark.leakPtr());
361 #ifdef BUILDING_ON_TIGER
363 wkReleaseStyleGroup(m_styleGroup);
366 HashMap<unsigned, ATSUStyle>::iterator end = m_ATSUStyleMap.end();
367 for (HashMap<unsigned, ATSUStyle>::iterator it = m_ATSUStyleMap.begin(); it != end; ++it)
368 ATSUDisposeStyle(it->second);
372 SimpleFontData* SimpleFontData::scaledFontData(const FontDescription& fontDescription, float scaleFactor) const
374 if (isCustomFont()) {
375 FontPlatformData scaledFontData(m_platformData);
376 scaledFontData.m_size = scaledFontData.m_size * scaleFactor;
377 return new SimpleFontData(scaledFontData, true, false);
380 BEGIN_BLOCK_OBJC_EXCEPTIONS;
381 float size = m_platformData.size() * scaleFactor;
382 FontPlatformData scaledFontData([[NSFontManager sharedFontManager] convertFont:m_platformData.font() toSize:size], size, false, false, m_platformData.orientation());
384 // AppKit resets the type information (screen/printer) when you convert a font to a different size.
385 // We have to fix up the font that we're handed back.
386 scaledFontData.setFont(fontDescription.usePrinterFont() ? [scaledFontData.font() printerFont] : [scaledFontData.font() screenFont]);
388 if (scaledFontData.font()) {
389 NSFontManager *fontManager = [NSFontManager sharedFontManager];
390 NSFontTraitMask fontTraits = [fontManager traitsOfFont:m_platformData.font()];
392 if (m_platformData.m_syntheticBold)
393 fontTraits |= NSBoldFontMask;
394 if (m_platformData.m_syntheticOblique)
395 fontTraits |= NSItalicFontMask;
397 NSFontTraitMask scaledFontTraits = [fontManager traitsOfFont:scaledFontData.font()];
398 scaledFontData.m_syntheticBold = (fontTraits & NSBoldFontMask) && !(scaledFontTraits & NSBoldFontMask);
399 scaledFontData.m_syntheticOblique = (fontTraits & NSItalicFontMask) && !(scaledFontTraits & NSItalicFontMask);
401 return fontCache()->getCachedFontData(&scaledFontData);
403 END_BLOCK_OBJC_EXCEPTIONS;
408 SimpleFontData* SimpleFontData::smallCapsFontData(const FontDescription& fontDescription) const
410 if (!m_derivedFontData)
411 m_derivedFontData = DerivedFontData::create(isCustomFont());
412 if (!m_derivedFontData->smallCaps)
413 m_derivedFontData->smallCaps = scaledFontData(fontDescription, smallCapsFontSizeMultiplier);
415 return m_derivedFontData->smallCaps.get();
418 SimpleFontData* SimpleFontData::emphasisMarkFontData(const FontDescription& fontDescription) const
420 if (!m_derivedFontData)
421 m_derivedFontData = DerivedFontData::create(isCustomFont());
422 if (!m_derivedFontData->emphasisMark)
423 m_derivedFontData->emphasisMark = scaledFontData(fontDescription, .5f);
425 return m_derivedFontData->emphasisMark.get();
428 bool SimpleFontData::containsCharacters(const UChar* characters, int length) const
430 NSString *string = [[NSString alloc] initWithCharactersNoCopy:const_cast<unichar*>(characters) length:length freeWhenDone:NO];
431 NSCharacterSet *set = [[m_platformData.font() coveredCharacterSet] invertedSet];
432 bool result = set && [string rangeOfCharacterFromSet:set].location == NSNotFound;
437 void SimpleFontData::determinePitch()
439 NSFont* f = m_platformData.font();
440 // Special case Osaka-Mono.
441 // According to <rdar://problem/3999467>, we should treat Osaka-Mono as fixed pitch.
442 // Note that the AppKit does not report Osaka-Mono as fixed pitch.
444 // Special case MS-PGothic.
445 // According to <rdar://problem/4032938>, we should not treat MS-PGothic as fixed pitch.
446 // Note that AppKit does report MS-PGothic as fixed pitch.
448 // Special case MonotypeCorsiva
449 // According to <rdar://problem/5454704>, we should not treat MonotypeCorsiva as fixed pitch.
450 // Note that AppKit does report MonotypeCorsiva as fixed pitch.
452 NSString *name = [f fontName];
453 m_treatAsFixedPitch = ([f isFixedPitch] || [f _isFakeFixedPitch] ||
454 [name caseInsensitiveCompare:@"Osaka-Mono"] == NSOrderedSame) &&
455 [name caseInsensitiveCompare:@"MS-PGothic"] != NSOrderedSame &&
456 [name caseInsensitiveCompare:@"MonotypeCorsiva"] != NSOrderedSame;
459 FloatRect SimpleFontData::platformBoundsForGlyph(Glyph glyph) const
461 FloatRect boundingBox;
462 boundingBox = CTFontGetBoundingRectsForGlyphs(m_platformData.ctFont(), platformData().orientation() == Vertical ? kCTFontVerticalOrientation : kCTFontHorizontalOrientation, &glyph, 0, 1);
463 boundingBox.setY(-boundingBox.maxY());
464 if (m_syntheticBoldOffset)
465 boundingBox.setWidth(boundingBox.width() + m_syntheticBoldOffset);
470 float SimpleFontData::platformWidthForGlyph(Glyph glyph) const
473 if (platformData().orientation() == Horizontal || m_isBrokenIdeographFallback) {
474 NSFont* font = platformData().font();
475 float pointSize = platformData().m_size;
476 CGAffineTransform m = CGAffineTransformMakeScale(pointSize, pointSize);
477 if (!wkGetGlyphTransformedAdvances(platformData().cgFont(), font, &m, &glyph, &advance)) {
478 LOG_ERROR("Unable to cache glyph widths for %@ %f", [font displayName], pointSize);
482 CTFontGetAdvancesForGlyphs(m_platformData.ctFont(), kCTFontVerticalOrientation, &glyph, &advance, 1);
484 return advance.width + m_syntheticBoldOffset;
487 } // namespace WebCore