1/*
2 * Copyright (C) 2005, 2006 Apple Computer, 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 *
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.
17 *
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.
28 */
29
30#import "config.h"
31#import "SimpleFontData.h"
32
33#import "BlockExceptions.h"
34#import "Color.h"
35#import "FloatRect.h"
36#import "Font.h"
37#import "FontCache.h"
38#import "FontDescription.h"
39#import "SharedBuffer.h"
40#import "WebCoreSystemInterface.h"
41#import <AppKit/AppKit.h>
42#import <ApplicationServices/ApplicationServices.h>
43#import <float.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>
49
50@interface NSFont (WebAppKitSecretAPI)
51- (BOOL)_isFakeFixedPitch;
52@end
53
54using namespace std;
55
56namespace WebCore {
57
58const float smallCapsFontSizeMultiplier = 0.7f;
59static inline float scaleEmToUnits(float x, unsigned unitsPerEm) { return x / unitsPerEm; }
60
61static bool initFontData(SimpleFontData* fontData)
62{
63    if (!fontData->platformData().cgFont())
64        return false;
65
66#ifdef BUILDING_ON_TIGER
67    ATSUStyle fontStyle;
68    if (ATSUCreateStyle(&fontStyle) != noErr)
69        return false;
70
71    ATSUFontID fontId = fontData->platformData().m_atsuFontID;
72    if (!fontId) {
73        ATSUDisposeStyle(fontStyle);
74        return false;
75    }
76
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);
83        return false;
84    }
85
86    if (wkGetATSStyleGroup(fontStyle, &fontData->m_styleGroup) != noErr) {
87        ATSUDisposeStyle(fontStyle);
88        return false;
89    }
90
91    ATSUDisposeStyle(fontStyle);
92#endif
93
94    return true;
95}
96
97static NSString *webFallbackFontFamily(void)
98{
99    DEFINE_STATIC_LOCAL(RetainPtr<NSString>, webFallbackFontFamily, ([[NSFont systemFontOfSize:16.0f] familyName]));
100    return webFallbackFontFamily.get();
101}
102
103#if !ERROR_DISABLED
104#if defined(__LP64__) || (!defined(BUILDING_ON_TIGER) && !defined(BUILDING_ON_LEOPARD) && !defined(BUILDING_ON_SNOW_LEOPARD))
105static NSString* pathFromFont(NSFont*)
106{
107    // FMGetATSFontRefFromFont is not available. As pathFromFont is only used for debugging purposes,
108    // returning nil is acceptable.
109    return nil;
110}
111#else
112static NSString* pathFromFont(NSFont *font)
113{
114#ifndef BUILDING_ON_TIGER
115    ATSFontRef atsFont = FMGetATSFontRefFromFont(CTFontGetPlatformFont(toCTFontRef(font), 0));
116#else
117    ATSFontRef atsFont = FMGetATSFontRefFromFont(wkGetNSFontATSUFontId(font));
118#endif
119    FSRef fileRef;
120
121#ifndef BUILDING_ON_TIGER
122    OSStatus status = ATSFontGetFileReference(atsFont, &fileRef);
123    if (status != noErr)
124        return nil;
125#else
126    FSSpec oFile;
127    OSStatus status = ATSFontGetFileSpecification(atsFont, &oFile);
128    if (status != noErr)
129        return nil;
130
131    status = FSpMakeFSRef(&oFile, &fileRef);
132    if (status != noErr)
133        return nil;
134#endif
135
136    UInt8 filePathBuffer[PATH_MAX];
137    status = FSRefMakePath(&fileRef, filePathBuffer, PATH_MAX);
138    if (status == noErr)
139        return [NSString stringWithUTF8String:(const char*)filePathBuffer];
140
141    return nil;
142}
143#endif // __LP64__
144#endif // !ERROR_DISABLED
145
146void SimpleFontData::platformInit()
147{
148#ifdef BUILDING_ON_TIGER
149    m_styleGroup = 0;
150#endif
151#if USE(ATSUI)
152    m_ATSUMirrors = false;
153    m_checkedShapesArabic = false;
154    m_shapesArabic = false;
155#endif
156
157    m_syntheticBoldOffset = m_platformData.m_syntheticBold ? 1.0f : 0.f;
158
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.
163
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";
171        else
172            fallbackFontFamily = webFallbackFontFamily();
173
174        // Try setting up the alternate font.
175        // This is a last ditch effort to use a substitute font when something has gone wrong.
176#if !ERROR_DISABLED
177        RetainPtr<NSFont> initialFont = m_platformData.font();
178#endif
179        if (m_platformData.font())
180            m_platformData.setFont([[NSFontManager sharedFontManager] convertFont:m_platformData.font() toFamily:fallbackFontFamily]);
181        else
182            m_platformData.setFont([NSFont fontWithName:fallbackFontFamily size:m_platformData.size()]);
183#if !ERROR_DISABLED
184        NSString *filePath = pathFromFont(initialFont.get());
185        if (!filePath)
186            filePath = @"not known";
187#endif
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);
196                    failedSetup = true;
197                }
198            } else {
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);
201                failedSetup = true;
202            }
203        }
204
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);
208    }
209
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.
212    if (failedSetup) {
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());
215        initFontData(this);
216    }
217
218    int iAscent;
219    int iDescent;
220    int iLineGap;
221    unsigned unitsPerEm;
222#ifdef BUILDING_ON_TIGER
223    wkGetFontMetrics(m_platformData.cgFont(), &iAscent, &iDescent, &iLineGap, &unitsPerEm);
224#else
225    iAscent = CGFontGetAscent(m_platformData.cgFont());
226    iDescent = CGFontGetDescent(m_platformData.cgFont());
227    iLineGap = CGFontGetLeading(m_platformData.cgFont());
228    unitsPerEm = CGFontGetUnitsPerEm(m_platformData.cgFont());
229#endif
230
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;
235
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.
249        ascent *= 1.08f;
250        descent *= 2.f;
251    }
252#endif
253
254    // Compute and store line spacing, before the line metrics hacks are applied.
255    m_fontMetrics.setLineSpacing(lroundf(ascent) + lroundf(descent) + lroundf(lineGap));
256
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;
261        descent = 3;
262    }
263
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;
272                break;
273            }
274        }
275    }
276
277    float xHeight;
278
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;
284        if (xGlyph)
285            xHeight = -CGRectGetMinY(platformBoundsForGlyph(xGlyph));
286        else
287            xHeight = scaleEmToUnits(CGFontGetXHeight(m_platformData.cgFont()), unitsPerEm) * pointSize;
288    } else
289        xHeight = verticalRightOrientationFontData()->fontMetrics().xHeight();
290
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);
296}
297
298static CFDataRef copyFontTableForTag(FontPlatformData& platformData, FourCharCode tableName)
299{
300#ifdef BUILDING_ON_TIGER
301    ATSFontRef atsFont = FMGetATSFontRefFromFont(platformData.m_atsuFontID);
302
303    ByteCount tableSize;
304    if (ATSFontGetTable(atsFont, tableName, 0, 0, NULL, &tableSize) != noErr)
305        return 0;
306
307    CFMutableDataRef data = CFDataCreateMutable(kCFAllocatorDefault, tableSize);
308    if (!data)
309        return 0;
310
311    CFDataIncreaseLength(data, tableSize);
312    if (ATSFontGetTable(atsFont, tableName, 0, tableSize, CFDataGetMutableBytePtr(data), &tableSize) != noErr) {
313        CFRelease(data);
314        return 0;
315    }
316
317    return data;
318#else
319    return CGFontCopyTableForTag(platformData.cgFont(), tableName);
320#endif
321}
322
323void SimpleFontData::platformCharWidthInit()
324{
325    m_avgCharWidth = 0;
326    m_maxCharWidth = 0;
327
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;
333    }
334
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;
344    }
345
346    // Fallback to a cross-platform estimate, which will populate these values if they are non-positive.
347    initCharWidths();
348}
349
350void SimpleFontData::platformDestroy()
351{
352    if (!isCustomFont() && m_derivedFontData) {
353        // These come from the cache.
354        if (m_derivedFontData->smallCaps)
355            fontCache()->releaseFontData(m_derivedFontData->smallCaps.leakPtr());
356
357        if (m_derivedFontData->emphasisMark)
358            fontCache()->releaseFontData(m_derivedFontData->emphasisMark.leakPtr());
359    }
360
361#ifdef BUILDING_ON_TIGER
362    if (m_styleGroup)
363        wkReleaseStyleGroup(m_styleGroup);
364#endif
365#if USE(ATSUI)
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);
369#endif
370}
371
372SimpleFontData* SimpleFontData::scaledFontData(const FontDescription& fontDescription, float scaleFactor) const
373{
374    if (isCustomFont()) {
375        FontPlatformData scaledFontData(m_platformData);
376        scaledFontData.m_size = scaledFontData.m_size * scaleFactor;
377        return new SimpleFontData(scaledFontData, true, false);
378    }
379
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());
383
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]);
387
388    if (scaledFontData.font()) {
389        NSFontManager *fontManager = [NSFontManager sharedFontManager];
390        NSFontTraitMask fontTraits = [fontManager traitsOfFont:m_platformData.font()];
391
392        if (m_platformData.m_syntheticBold)
393            fontTraits |= NSBoldFontMask;
394        if (m_platformData.m_syntheticOblique)
395            fontTraits |= NSItalicFontMask;
396
397        NSFontTraitMask scaledFontTraits = [fontManager traitsOfFont:scaledFontData.font()];
398        scaledFontData.m_syntheticBold = (fontTraits & NSBoldFontMask) && !(scaledFontTraits & NSBoldFontMask);
399        scaledFontData.m_syntheticOblique = (fontTraits & NSItalicFontMask) && !(scaledFontTraits & NSItalicFontMask);
400
401        return fontCache()->getCachedFontData(&scaledFontData);
402    }
403    END_BLOCK_OBJC_EXCEPTIONS;
404
405    return 0;
406}
407
408SimpleFontData* SimpleFontData::smallCapsFontData(const FontDescription& fontDescription) const
409{
410    if (!m_derivedFontData)
411        m_derivedFontData = DerivedFontData::create(isCustomFont());
412    if (!m_derivedFontData->smallCaps)
413        m_derivedFontData->smallCaps = scaledFontData(fontDescription, smallCapsFontSizeMultiplier);
414
415    return m_derivedFontData->smallCaps.get();
416}
417
418SimpleFontData* SimpleFontData::emphasisMarkFontData(const FontDescription& fontDescription) const
419{
420    if (!m_derivedFontData)
421        m_derivedFontData = DerivedFontData::create(isCustomFont());
422    if (!m_derivedFontData->emphasisMark)
423        m_derivedFontData->emphasisMark = scaledFontData(fontDescription, .5f);
424
425    return m_derivedFontData->emphasisMark.get();
426}
427
428bool SimpleFontData::containsCharacters(const UChar* characters, int length) const
429{
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;
433    [string release];
434    return result;
435}
436
437void SimpleFontData::determinePitch()
438{
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.
443
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.
447
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.
451
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;
457}
458
459FloatRect SimpleFontData::platformBoundsForGlyph(Glyph glyph) const
460{
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);
466
467    return boundingBox;
468}
469
470float SimpleFontData::platformWidthForGlyph(Glyph glyph) const
471{
472    CGSize advance;
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);
479            advance.width = 0;
480        }
481    } else
482        CTFontGetAdvancesForGlyphs(m_platformData.ctFont(), kCTFontVerticalOrientation, &glyph, &advance, 1);
483
484    return advance.width + m_syntheticBoldOffset;
485}
486
487} // namespace WebCore
488