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
32// FIXME: Remove this define!
33#define LOOSE_PASS_OWN_PTR
34
35#import "SimpleFontData.h"
36
37#import "BlockExceptions.h"
38#import "Color.h"
39#import "FloatRect.h"
40#import "Font.h"
41#import "FontCache.h"
42#import "FontDescription.h"
43#import "SharedBuffer.h"
44#import "WebCoreSystemInterface.h"
45#import <AppKit/AppKit.h>
46#import <ApplicationServices/ApplicationServices.h>
47#import <float.h>
48#import <unicode/uchar.h>
49#import <wtf/Assertions.h>
50#import <wtf/StdLibExtras.h>
51#import <wtf/RetainPtr.h>
52#import <wtf/UnusedParam.h>
53
54@interface NSFont (WebAppKitSecretAPI)
55- (BOOL)_isFakeFixedPitch;
56@end
57
58using namespace std;
59
60namespace WebCore {
61
62const float smallCapsFontSizeMultiplier = 0.7f;
63static inline float scaleEmToUnits(float x, unsigned unitsPerEm) { return x / unitsPerEm; }
64
65static bool initFontData(SimpleFontData* fontData)
66{
67    if (!fontData->platformData().cgFont())
68        return false;
69
70
71    return true;
72}
73
74static NSString *webFallbackFontFamily(void)
75{
76    DEFINE_STATIC_LOCAL(RetainPtr<NSString>, webFallbackFontFamily, ([[NSFont systemFontOfSize:16.0f] familyName]));
77    return webFallbackFontFamily.get();
78}
79
80#if !ERROR_DISABLED
81#if defined(__LP64__) || (!defined(BUILDING_ON_LEOPARD) && !defined(BUILDING_ON_SNOW_LEOPARD))
82static NSString* pathFromFont(NSFont*)
83{
84    // FMGetATSFontRefFromFont is not available. As pathFromFont is only used for debugging purposes,
85    // returning nil is acceptable.
86    return nil;
87}
88#else
89static NSString* pathFromFont(NSFont *font)
90{
91    ATSFontRef atsFont = FMGetATSFontRefFromFont(CTFontGetPlatformFont(toCTFontRef(font), 0));
92    FSRef fileRef;
93
94    OSStatus status = ATSFontGetFileReference(atsFont, &fileRef);
95    if (status != noErr)
96        return nil;
97
98    UInt8 filePathBuffer[PATH_MAX];
99    status = FSRefMakePath(&fileRef, filePathBuffer, PATH_MAX);
100    if (status == noErr)
101        return [NSString stringWithUTF8String:(const char*)filePathBuffer];
102
103    return nil;
104}
105#endif // __LP64__
106#endif // !ERROR_DISABLED
107
108void SimpleFontData::platformInit()
109{
110#if USE(ATSUI)
111    m_ATSUMirrors = false;
112    m_checkedShapesArabic = false;
113    m_shapesArabic = false;
114#endif
115
116    m_syntheticBoldOffset = m_platformData.m_syntheticBold ? 1.0f : 0.f;
117
118    bool failedSetup = false;
119    if (!initFontData(this)) {
120        // Ack! Something very bad happened, like a corrupt font.
121        // Try looking for an alternate 'base' font for this renderer.
122
123        // Special case hack to use "Times New Roman" in place of "Times".
124        // "Times RO" is a common font whose family name is "Times".
125        // It overrides the normal "Times" family font.
126        // It also appears to have a corrupt regular variant.
127        NSString *fallbackFontFamily;
128        if ([[m_platformData.font() familyName] isEqual:@"Times"])
129            fallbackFontFamily = @"Times New Roman";
130        else
131            fallbackFontFamily = webFallbackFontFamily();
132
133        // Try setting up the alternate font.
134        // This is a last ditch effort to use a substitute font when something has gone wrong.
135#if !ERROR_DISABLED
136        RetainPtr<NSFont> initialFont = m_platformData.font();
137#endif
138        if (m_platformData.font())
139            m_platformData.setFont([[NSFontManager sharedFontManager] convertFont:m_platformData.font() toFamily:fallbackFontFamily]);
140        else
141            m_platformData.setFont([NSFont fontWithName:fallbackFontFamily size:m_platformData.size()]);
142#if !ERROR_DISABLED
143        NSString *filePath = pathFromFont(initialFont.get());
144        if (!filePath)
145            filePath = @"not known";
146#endif
147        if (!initFontData(this)) {
148            if ([fallbackFontFamily isEqual:@"Times New Roman"]) {
149                // OK, couldn't setup Times New Roman as an alternate to Times, fallback
150                // on the system font.  If this fails we have no alternative left.
151                m_platformData.setFont([[NSFontManager sharedFontManager] convertFont:m_platformData.font() toFamily:webFallbackFontFamily()]);
152                if (!initFontData(this)) {
153                    // We tried, Times, Times New Roman, and the system font. No joy. We have to give up.
154                    LOG_ERROR("unable to initialize with font %@ at %@", initialFont.get(), filePath);
155                    failedSetup = true;
156                }
157            } else {
158                // We tried the requested font and the system font. No joy. We have to give up.
159                LOG_ERROR("unable to initialize with font %@ at %@", initialFont.get(), filePath);
160                failedSetup = true;
161            }
162        }
163
164        // Report the problem.
165        LOG_ERROR("Corrupt font detected, using %@ in place of %@ located at \"%@\".",
166            [m_platformData.font() familyName], [initialFont.get() familyName], filePath);
167    }
168
169    // If all else fails, try to set up using the system font.
170    // This is probably because Times and Times New Roman are both unavailable.
171    if (failedSetup) {
172        m_platformData.setFont([NSFont systemFontOfSize:[m_platformData.font() pointSize]]);
173        LOG_ERROR("failed to set up font, using system font %s", m_platformData.font());
174        initFontData(this);
175    }
176
177    int iAscent;
178    int iDescent;
179    int iLineGap;
180    unsigned unitsPerEm;
181    iAscent = CGFontGetAscent(m_platformData.cgFont());
182    iDescent = CGFontGetDescent(m_platformData.cgFont());
183    iLineGap = CGFontGetLeading(m_platformData.cgFont());
184    unitsPerEm = CGFontGetUnitsPerEm(m_platformData.cgFont());
185
186    float pointSize = m_platformData.m_size;
187    float ascent = scaleEmToUnits(iAscent, unitsPerEm) * pointSize;
188    float descent = -scaleEmToUnits(iDescent, unitsPerEm) * pointSize;
189    float lineGap = scaleEmToUnits(iLineGap, unitsPerEm) * pointSize;
190
191    // We need to adjust Times, Helvetica, and Courier to closely match the
192    // vertical metrics of their Microsoft counterparts that are the de facto
193    // web standard. The AppKit adjustment of 20% is too big and is
194    // incorrectly added to line spacing, so we use a 15% adjustment instead
195    // and add it to the ascent.
196    NSString *familyName = [m_platformData.font() familyName];
197    if ([familyName isEqualToString:@"Times"] || [familyName isEqualToString:@"Helvetica"] || [familyName isEqualToString:@"Courier"])
198        ascent += floorf(((ascent + descent) * 0.15f) + 0.5f);
199#if defined(BUILDING_ON_LEOPARD)
200    else if ([familyName isEqualToString:@"Geeza Pro"]) {
201        // Geeza Pro has glyphs that draw slightly above the ascent or far below the descent. Adjust
202        // those vertical metrics to better match reality, so that diacritics at the bottom of one line
203        // do not overlap diacritics at the top of the next line.
204        ascent *= 1.08f;
205        descent *= 2.f;
206    }
207#endif
208
209    // Compute and store line spacing, before the line metrics hacks are applied.
210    m_fontMetrics.setLineSpacing(lroundf(ascent) + lroundf(descent) + lroundf(lineGap));
211
212    // Hack Hiragino line metrics to allow room for marked text underlines.
213    // <rdar://problem/5386183>
214    if (descent < 3 && lineGap >= 3 && [familyName hasPrefix:@"Hiragino"]) {
215        lineGap -= 3 - descent;
216        descent = 3;
217    }
218
219    if (platformData().orientation() == Vertical && !isTextOrientationFallback()) {
220        // The check doesn't look neat but this is what AppKit does for vertical writing...
221        RetainPtr<CFArrayRef> tableTags(AdoptCF, CTFontCopyAvailableTables(m_platformData.ctFont(), kCTFontTableOptionExcludeSynthetic));
222        CFIndex numTables = CFArrayGetCount(tableTags.get());
223        for (CFIndex index = 0; index < numTables; ++index) {
224            CTFontTableTag tag = (CTFontTableTag)(uintptr_t)CFArrayGetValueAtIndex(tableTags.get(), index);
225            if (tag == kCTFontTableVhea || tag == kCTFontTableVORG) {
226                m_hasVerticalGlyphs = true;
227                break;
228            }
229        }
230    }
231
232    float xHeight;
233
234    if (platformData().orientation() == Horizontal) {
235        // Measure the actual character "x", since it's possible for it to extend below the baseline, and we need the
236        // reported x-height to only include the portion of the glyph that is above the baseline.
237        GlyphPage* glyphPageZero = GlyphPageTreeNode::getRootChild(this, 0)->page();
238        NSGlyph xGlyph = glyphPageZero ? glyphPageZero->glyphDataForCharacter('x').glyph : 0;
239        if (xGlyph)
240            xHeight = -CGRectGetMinY(platformBoundsForGlyph(xGlyph));
241        else
242            xHeight = scaleEmToUnits(CGFontGetXHeight(m_platformData.cgFont()), unitsPerEm) * pointSize;
243    } else
244        xHeight = verticalRightOrientationFontData()->fontMetrics().xHeight();
245
246    m_fontMetrics.setUnitsPerEm(unitsPerEm);
247    m_fontMetrics.setAscent(ascent);
248    m_fontMetrics.setDescent(descent);
249    m_fontMetrics.setLineGap(lineGap);
250    m_fontMetrics.setXHeight(xHeight);
251}
252
253static CFDataRef copyFontTableForTag(FontPlatformData& platformData, FourCharCode tableName)
254{
255    return CGFontCopyTableForTag(platformData.cgFont(), tableName);
256}
257
258void SimpleFontData::platformCharWidthInit()
259{
260    m_avgCharWidth = 0;
261    m_maxCharWidth = 0;
262
263    RetainPtr<CFDataRef> os2Table(AdoptCF, copyFontTableForTag(m_platformData, 'OS/2'));
264    if (os2Table && CFDataGetLength(os2Table.get()) >= 4) {
265        const UInt8* os2 = CFDataGetBytePtr(os2Table.get());
266        SInt16 os2AvgCharWidth = os2[2] * 256 + os2[3];
267        m_avgCharWidth = scaleEmToUnits(os2AvgCharWidth, m_fontMetrics.unitsPerEm()) * m_platformData.m_size;
268    }
269
270    RetainPtr<CFDataRef> headTable(AdoptCF, copyFontTableForTag(m_platformData, 'head'));
271    if (headTable && CFDataGetLength(headTable.get()) >= 42) {
272        const UInt8* head = CFDataGetBytePtr(headTable.get());
273        ushort uxMin = head[36] * 256 + head[37];
274        ushort uxMax = head[40] * 256 + head[41];
275        SInt16 xMin = static_cast<SInt16>(uxMin);
276        SInt16 xMax = static_cast<SInt16>(uxMax);
277        float diff = static_cast<float>(xMax - xMin);
278        m_maxCharWidth = scaleEmToUnits(diff, m_fontMetrics.unitsPerEm()) * m_platformData.m_size;
279    }
280
281    // Fallback to a cross-platform estimate, which will populate these values if they are non-positive.
282    initCharWidths();
283}
284
285void SimpleFontData::platformDestroy()
286{
287    if (!isCustomFont() && m_derivedFontData) {
288        // These come from the cache.
289        if (m_derivedFontData->smallCaps)
290            fontCache()->releaseFontData(m_derivedFontData->smallCaps.leakPtr());
291
292        if (m_derivedFontData->emphasisMark)
293            fontCache()->releaseFontData(m_derivedFontData->emphasisMark.leakPtr());
294    }
295
296#if USE(ATSUI)
297    HashMap<unsigned, ATSUStyle>::iterator end = m_ATSUStyleMap.end();
298    for (HashMap<unsigned, ATSUStyle>::iterator it = m_ATSUStyleMap.begin(); it != end; ++it)
299        ATSUDisposeStyle(it->second);
300#endif
301}
302
303SimpleFontData* SimpleFontData::scaledFontData(const FontDescription& fontDescription, float scaleFactor) const
304{
305    if (isCustomFont()) {
306        FontPlatformData scaledFontData(m_platformData);
307        scaledFontData.m_size = scaledFontData.m_size * scaleFactor;
308        return new SimpleFontData(scaledFontData, true, false);
309    }
310
311    BEGIN_BLOCK_OBJC_EXCEPTIONS;
312    float size = m_platformData.size() * scaleFactor;
313    FontPlatformData scaledFontData([[NSFontManager sharedFontManager] convertFont:m_platformData.font() toSize:size], size, false, false, m_platformData.orientation());
314
315    // AppKit resets the type information (screen/printer) when you convert a font to a different size.
316    // We have to fix up the font that we're handed back.
317    scaledFontData.setFont(fontDescription.usePrinterFont() ? [scaledFontData.font() printerFont] : [scaledFontData.font() screenFont]);
318
319    if (scaledFontData.font()) {
320        NSFontManager *fontManager = [NSFontManager sharedFontManager];
321        NSFontTraitMask fontTraits = [fontManager traitsOfFont:m_platformData.font()];
322
323        if (m_platformData.m_syntheticBold)
324            fontTraits |= NSBoldFontMask;
325        if (m_platformData.m_syntheticOblique)
326            fontTraits |= NSItalicFontMask;
327
328        NSFontTraitMask scaledFontTraits = [fontManager traitsOfFont:scaledFontData.font()];
329        scaledFontData.m_syntheticBold = (fontTraits & NSBoldFontMask) && !(scaledFontTraits & NSBoldFontMask);
330        scaledFontData.m_syntheticOblique = (fontTraits & NSItalicFontMask) && !(scaledFontTraits & NSItalicFontMask);
331
332        return fontCache()->getCachedFontData(&scaledFontData);
333    }
334    END_BLOCK_OBJC_EXCEPTIONS;
335
336    return 0;
337}
338
339SimpleFontData* SimpleFontData::smallCapsFontData(const FontDescription& fontDescription) const
340{
341    if (!m_derivedFontData)
342        m_derivedFontData = DerivedFontData::create(isCustomFont());
343    if (!m_derivedFontData->smallCaps)
344        m_derivedFontData->smallCaps = scaledFontData(fontDescription, smallCapsFontSizeMultiplier);
345
346    return m_derivedFontData->smallCaps.get();
347}
348
349SimpleFontData* SimpleFontData::emphasisMarkFontData(const FontDescription& fontDescription) const
350{
351    if (!m_derivedFontData)
352        m_derivedFontData = DerivedFontData::create(isCustomFont());
353    if (!m_derivedFontData->emphasisMark)
354        m_derivedFontData->emphasisMark = scaledFontData(fontDescription, .5f);
355
356    return m_derivedFontData->emphasisMark.get();
357}
358
359bool SimpleFontData::containsCharacters(const UChar* characters, int length) const
360{
361    NSString *string = [[NSString alloc] initWithCharactersNoCopy:const_cast<unichar*>(characters) length:length freeWhenDone:NO];
362    NSCharacterSet *set = [[m_platformData.font() coveredCharacterSet] invertedSet];
363    bool result = set && [string rangeOfCharacterFromSet:set].location == NSNotFound;
364    [string release];
365    return result;
366}
367
368void SimpleFontData::determinePitch()
369{
370    NSFont* f = m_platformData.font();
371    // Special case Osaka-Mono.
372    // According to <rdar://problem/3999467>, we should treat Osaka-Mono as fixed pitch.
373    // Note that the AppKit does not report Osaka-Mono as fixed pitch.
374
375    // Special case MS-PGothic.
376    // According to <rdar://problem/4032938>, we should not treat MS-PGothic as fixed pitch.
377    // Note that AppKit does report MS-PGothic as fixed pitch.
378
379    // Special case MonotypeCorsiva
380    // According to <rdar://problem/5454704>, we should not treat MonotypeCorsiva as fixed pitch.
381    // Note that AppKit does report MonotypeCorsiva as fixed pitch.
382
383    NSString *name = [f fontName];
384    m_treatAsFixedPitch = ([f isFixedPitch] || [f _isFakeFixedPitch] ||
385           [name caseInsensitiveCompare:@"Osaka-Mono"] == NSOrderedSame) &&
386           [name caseInsensitiveCompare:@"MS-PGothic"] != NSOrderedSame &&
387           [name caseInsensitiveCompare:@"MonotypeCorsiva"] != NSOrderedSame;
388}
389
390FloatRect SimpleFontData::platformBoundsForGlyph(Glyph glyph) const
391{
392    FloatRect boundingBox;
393    boundingBox = CTFontGetBoundingRectsForGlyphs(m_platformData.ctFont(), platformData().orientation() == Vertical ? kCTFontVerticalOrientation : kCTFontHorizontalOrientation, &glyph, 0, 1);
394    boundingBox.setY(-boundingBox.maxY());
395    if (m_syntheticBoldOffset)
396        boundingBox.setWidth(boundingBox.width() + m_syntheticBoldOffset);
397
398    return boundingBox;
399}
400
401float SimpleFontData::platformWidthForGlyph(Glyph glyph) const
402{
403    CGSize advance;
404    if (platformData().orientation() == Horizontal || m_isBrokenIdeographFallback) {
405        NSFont* font = platformData().font();
406        float pointSize = platformData().m_size;
407        CGAffineTransform m = CGAffineTransformMakeScale(pointSize, pointSize);
408        if (!wkGetGlyphTransformedAdvances(platformData().cgFont(), font, &m, &glyph, &advance)) {
409            LOG_ERROR("Unable to cache glyph widths for %@ %f", [font displayName], pointSize);
410            advance.width = 0;
411        }
412    } else
413        CTFontGetAdvancesForGlyphs(m_platformData.ctFont(), kCTFontVerticalOrientation, &glyph, &advance, 1);
414
415    return advance.width + m_syntheticBoldOffset;
416}
417
418} // namespace WebCore
419