FontDataMac.mm 13.3 KB
Newer Older
1
/*
darin's avatar
darin committed
2
 * Copyright (C) 2005, 2006 Apple Computer, Inc.  All rights reserved.
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
 * Copyright (C) 2006 Alexey Proskuryakov
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1.  Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer. 
 * 2.  Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution. 
 * 3.  Neither the name of Apple Computer, Inc. ("Apple") nor the names of
 *     its contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission. 
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#import "config.h"
#import "FontData.h"

sullivan's avatar
sullivan committed
33
#import "BlockExceptions.h"
darin's avatar
darin committed
34
#import "Color.h"
35
#import "FloatRect.h"
darin's avatar
darin committed
36 37
#import "Font.h"
#import "FontCache.h"
38
#import "FontDescription.h"
39
#import "SharedBuffer.h"
darin's avatar
darin committed
40 41
#import "WebCoreSystemInterface.h"
#import <ApplicationServices/ApplicationServices.h>
42 43
#import <float.h>
#import <unicode/uchar.h>
darin's avatar
darin committed
44
#import <wtf/Assertions.h>
45
#import <wtf/RetainPtr.h>
46 47 48 49 50

@interface NSFont (WebAppKitSecretAPI)
- (BOOL)_isFakeFixedPitch;
@end

darin's avatar
darin committed
51 52 53 54 55
namespace WebCore {
  
const float smallCapsFontSizeMultiplier = 0.7f;
const float contextDPI = 72.0f;
static inline float scaleEmToUnits(float x, unsigned unitsPerEm) { return x * (contextDPI / (contextDPI * unitsPerEm)); }
56 57 58

bool initFontData(FontData* fontData)
{
59 60 61
    if (!fontData->m_font.m_cgFont)
        return false;

62 63 64 65
    ATSUStyle fontStyle;
    if (ATSUCreateStyle(&fontStyle) != noErr)
        return false;
    
66
    ATSUFontID fontId = fontData->m_font.m_atsuFontID;
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
    if (!fontId) {
        ATSUDisposeStyle(fontStyle);
        return false;
    }

    ATSUAttributeTag tag = kATSUFontTag;
    ByteCount size = sizeof(ATSUFontID);
    ATSUFontID *valueArray[1] = {&fontId};
    OSStatus status = ATSUSetAttributes(fontStyle, 1, &tag, &size, (void* const*)valueArray);
    if (status != noErr) {
        ATSUDisposeStyle(fontStyle);
        return false;
    }

    if (wkGetATSStyleGroup(fontStyle, &fontData->m_styleGroup) != noErr) {
        ATSUDisposeStyle(fontStyle);
        return false;
    }

    ATSUDisposeStyle(fontStyle);

    return true;
}

static NSString *webFallbackFontFamily(void)
{
93
    static RetainPtr<NSString> webFallbackFontFamily = nil;
94
    if (!webFallbackFontFamily)
weinig's avatar
weinig committed
95
        webFallbackFontFamily = [[NSFont systemFontOfSize:16.0f] familyName];
96
    return webFallbackFontFamily.get();
97 98 99 100 101 102 103
}

void FontData::platformInit()
{
    m_styleGroup = 0;
    m_ATSUStyleInitialized = false;
    m_ATSUMirrors = false;
ap's avatar
ap committed
104 105
    m_checkedShapesArabic = false;
    m_shapesArabic = false;
106 107

    m_syntheticBoldOffset = m_font.m_syntheticBold ? 1.0f : 0.f;
108 109 110 111 112 113 114 115 116 117 118
    
    bool failedSetup = false;
    if (!initFontData(this)) {
        // Ack! Something very bad happened, like a corrupt font.
        // Try looking for an alternate 'base' font for this renderer.

        // Special case hack to use "Times New Roman" in place of "Times".
        // "Times RO" is a common font whose family name is "Times".
        // It overrides the normal "Times" family font.
        // It also appears to have a corrupt regular variant.
        NSString *fallbackFontFamily;
oliver's avatar
oliver committed
119
        if ([[m_font.font() familyName] isEqual:@"Times"])
120 121 122 123 124 125 126
            fallbackFontFamily = @"Times New Roman";
        else
            fallbackFontFamily = webFallbackFontFamily();
        
        // Try setting up the alternate font.
        // This is a last ditch effort to use a substitute font when something has gone wrong.
#if !ERROR_DISABLED
oliver's avatar
oliver committed
127
        RetainPtr<NSFont> initialFont = m_font.font();
128
#endif
oliver's avatar
oliver committed
129
        m_font.setFont([[NSFontManager sharedFontManager] convertFont:m_font.font() toFamily:fallbackFontFamily]);
130
#if !ERROR_DISABLED
oliver's avatar
oliver committed
131
        NSString *filePath = wkPathFromFont(initialFont.get());
132 133 134 135 136 137 138
        if (!filePath)
            filePath = @"not known";
#endif
        if (!initFontData(this)) {
            if ([fallbackFontFamily isEqual:@"Times New Roman"]) {
                // OK, couldn't setup Times New Roman as an alternate to Times, fallback
                // on the system font.  If this fails we have no alternative left.
oliver's avatar
oliver committed
139
                m_font.setFont([[NSFontManager sharedFontManager] convertFont:m_font.font() toFamily:webFallbackFontFamily()]);
140 141
                if (!initFontData(this)) {
                    // We tried, Times, Times New Roman, and the system font. No joy. We have to give up.
oliver's avatar
oliver committed
142
                    LOG_ERROR("unable to initialize with font %@ at %@", initialFont.get(), filePath);
143 144 145 146
                    failedSetup = true;
                }
            } else {
                // We tried the requested font and the system font. No joy. We have to give up.
oliver's avatar
oliver committed
147
                LOG_ERROR("unable to initialize with font %@ at %@", initialFont.get(), filePath);
148 149 150 151 152 153
                failedSetup = true;
            }
        }

        // Report the problem.
        LOG_ERROR("Corrupt font detected, using %@ in place of %@ located at \"%@\".",
oliver's avatar
oliver committed
154
            [m_font.font() familyName], [initialFont.get() familyName], filePath);
155 156 157 158 159
    }

    // If all else fails, try to set up using the system font.
    // This is probably because Times and Times New Roman are both unavailable.
    if (failedSetup) {
oliver's avatar
oliver committed
160 161
        m_font.setFont([NSFont systemFontOfSize:[m_font.font() pointSize]]);
        LOG_ERROR("failed to set up font, using system font %s", m_font.font());
162 163 164 165 166 167
        initFontData(this);
    }
    
    int iAscent;
    int iDescent;
    int iLineGap;
168 169
    wkGetFontMetrics(m_font.m_cgFont, &iAscent, &iDescent, &iLineGap, &m_unitsPerEm); 
    float pointSize = m_font.m_size;
oliver's avatar
oliver committed
170 171 172
    float fAscent = scaleEmToUnits(iAscent, m_unitsPerEm) * pointSize;
    float fDescent = -scaleEmToUnits(iDescent, m_unitsPerEm) * pointSize;
    float fLineGap = scaleEmToUnits(iLineGap, m_unitsPerEm) * pointSize;
173 174 175 176 177 178

    // We need to adjust Times, Helvetica, and Courier to closely match the
    // vertical metrics of their Microsoft counterparts that are the de facto
    // web standard. The AppKit adjustment of 20% is too big and is
    // incorrectly added to line spacing, so we use a 15% adjustment instead
    // and add it to the ascent.
oliver's avatar
oliver committed
179
    NSString *familyName = [m_font.font() familyName];
180 181 182 183 184 185 186 187
    if ([familyName isEqualToString:@"Times"] || [familyName isEqualToString:@"Helvetica"] || [familyName isEqualToString:@"Courier"])
        fAscent += floorf(((fAscent + fDescent) * 0.15f) + 0.5f);

    m_ascent = lroundf(fAscent);
    m_descent = lroundf(fDescent);
    m_lineGap = lroundf(fLineGap);
    m_lineSpacing = m_ascent + m_descent + m_lineGap;
    
oliver's avatar
oliver committed
188 189
    // Hack Hiragino line metrics to allow room for marked text underlines.
    // <rdar://problem/5386183>
oliver's avatar
oliver committed
190
    if (m_descent < 3 && m_lineGap >= 3 && [familyName hasPrefix:@"Hiragino"]) {
oliver's avatar
oliver committed
191 192 193 194
        m_lineGap -= 3 - m_descent;
        m_descent = 3;
    }
    
195 196
    // Measure the actual character "x", because AppKit synthesizes X height rather than getting it from the font.
    // Unfortunately, NSFont will round this for us so we don't quite get the right value.
antti's avatar
antti committed
197 198
    GlyphPage* glyphPageZero = GlyphPageTreeNode::getRootChild(this, 0)->page();
    NSGlyph xGlyph = glyphPageZero ? glyphPageZero->glyphDataForCharacter('x').glyph : 0;
199
    if (xGlyph) {
oliver's avatar
oliver committed
200
        NSRect xBox = [m_font.font() boundingRectForGlyph:xGlyph];
201 202 203 204 205 206
        // Use the maximum of either width or height because "x" is nearly square
        // and web pages that foolishly use this metric for width will be laid out
        // poorly if we return an accurate height. Classic case is Times 13 point,
        // which has an "x" that is 7x6 pixels.
        m_xHeight = MAX(NSMaxX(xBox), NSMaxY(xBox));
    } else
oliver's avatar
oliver committed
207
        m_xHeight = [m_font.font() xHeight];
208 209 210 211 212 213 214 215 216 217 218 219 220 221
}

void FontData::platformDestroy()
{
    if (m_styleGroup)
        wkReleaseStyleGroup(m_styleGroup);

    if (m_ATSUStyleInitialized)
        ATSUDisposeStyle(m_ATSUStyle);
}

FontData* FontData::smallCapsFontData(const FontDescription& fontDescription) const
{
    if (!m_smallCapsFontData) {
222 223 224 225 226
        if (isCustomFont()) {
            FontPlatformData smallCapsFontData(m_font);
            smallCapsFontData.m_size = smallCapsFontData.m_size * smallCapsFontSizeMultiplier;
            m_smallCapsFontData = new FontData(smallCapsFontData, true, false);
        } else {
sullivan's avatar
sullivan committed
227
            BEGIN_BLOCK_OBJC_EXCEPTIONS;
oliver's avatar
oliver committed
228 229
            float size = [m_font.font() pointSize] * smallCapsFontSizeMultiplier;
            FontPlatformData smallCapsFont([[NSFontManager sharedFontManager] convertFont:m_font.font() toSize:size]);
230 231 232
            
            // AppKit resets the type information (screen/printer) when you convert a font to a different size.
            // We have to fix up the font that we're handed back.
oliver's avatar
oliver committed
233
            smallCapsFont.setFont(fontDescription.usePrinterFont() ? [smallCapsFont.font() printerFont] : [smallCapsFont.font() screenFont]);
234

oliver's avatar
oliver committed
235
            if (smallCapsFont.font()) {
236
                NSFontManager *fontManager = [NSFontManager sharedFontManager];
oliver's avatar
oliver committed
237
                NSFontTraitMask fontTraits = [fontManager traitsOfFont:m_font.font()];
238

239
                if (m_font.m_syntheticBold)
240
                    fontTraits |= NSBoldFontMask;
241
                if (m_font.m_syntheticOblique)
242 243
                    fontTraits |= NSItalicFontMask;

oliver's avatar
oliver committed
244
                NSFontTraitMask smallCapsFontTraits = [fontManager traitsOfFont:smallCapsFont.font()];
245 246
                smallCapsFont.m_syntheticBold = (fontTraits & NSBoldFontMask) && !(smallCapsFontTraits & NSBoldFontMask);
                smallCapsFont.m_syntheticOblique = (fontTraits & NSItalicFontMask) && !(smallCapsFontTraits & NSItalicFontMask);
247 248 249

                m_smallCapsFontData = FontCache::getCachedFontData(&smallCapsFont);
            }
sullivan's avatar
sullivan committed
250
            END_BLOCK_OBJC_EXCEPTIONS;
251
        }
252 253 254 255 256 257 258
    }
    return m_smallCapsFontData;
}

bool FontData::containsCharacters(const UChar* characters, int length) const
{
    NSString *string = [[NSString alloc] initWithCharactersNoCopy:(UniChar*)characters length:length freeWhenDone:NO];
oliver's avatar
oliver committed
259
    NSCharacterSet *set = [[m_font.font() coveredCharacterSet] invertedSet];
260 261 262 263 264 265 266
    bool result = set && [string rangeOfCharacterFromSet:set].location == NSNotFound;
    [string release];
    return result;
}

void FontData::determinePitch()
{
oliver's avatar
oliver committed
267
    NSFont* f = m_font.font();
268 269 270 271 272
    // Special case Osaka-Mono.
    // According to <rdar://problem/3999467>, we should treat Osaka-Mono as fixed pitch.
    // Note that the AppKit does not report Osaka-Mono as fixed pitch.

    // Special case MS-PGothic.
bdash's avatar
bdash committed
273
    // According to <rdar://problem/4032938>, we should not treat MS-PGothic as fixed pitch.
274 275
    // Note that AppKit does report MS-PGothic as fixed pitch.

bdash's avatar
bdash committed
276 277 278 279
    // Special case MonotypeCorsiva
    // According to <rdar://problem/5454704>, we should not treat MonotypeCorsiva as fixed pitch.
    // Note that AppKit does report MonotypeCorsiva as fixed pitch.

280
    NSString *name = [f fontName];
bdash's avatar
bdash committed
281 282 283 284
    m_treatAsFixedPitch = ([f isFixedPitch] || [f _isFakeFixedPitch] ||
           [name caseInsensitiveCompare:@"Osaka-Mono"] == NSOrderedSame) &&
           [name caseInsensitiveCompare:@"MS-PGothic"] != NSOrderedSame &&
           [name caseInsensitiveCompare:@"MonotypeCorsiva"] != NSOrderedSame;
285 286
}

287
float FontData::platformWidthForGlyph(Glyph glyph) const
288
{
289 290
    NSFont* font = m_font.font();
    float pointSize = m_font.m_size;
291 292
    CGAffineTransform m = CGAffineTransformMakeScale(pointSize, pointSize);
    CGSize advance;
293
    if (!wkGetGlyphTransformedAdvances(m_font.m_cgFont, font, &m, &glyph, &advance)) {
294 295 296 297 298 299
        LOG_ERROR("Unable to cache glyph widths for %@ %f", [font displayName], pointSize);
        advance.width = 0;
    }
    return advance.width + m_syntheticBoldOffset;
}

ap's avatar
ap committed
300 301 302 303 304 305
void FontData::checkShapesArabic() const
{
    ASSERT(!m_checkedShapesArabic);

    m_checkedShapesArabic = true;
    
306
    ATSUFontID fontID = m_font.m_atsuFontID;
ap's avatar
ap committed
307
    if (!fontID) {
oliver's avatar
oliver committed
308
        LOG_ERROR("unable to get ATSUFontID for %@", m_font.font());
ap's avatar
ap committed
309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328
        return;
    }

    // This function is called only on fonts that contain Arabic glyphs. Our
    // heuristic is that if such a font has a glyph metamorphosis table, then
    // it includes shaping information for Arabic.
    FourCharCode tables[] = { 'morx', 'mort' };
    for (unsigned i = 0; i < sizeof(tables) / sizeof(tables[0]); ++i) {
        ByteCount tableSize;
        OSStatus status = ATSFontGetTable(fontID, tables[i], 0, 0, 0, &tableSize);
        if (status == noErr) {
            m_shapesArabic = true;
            return;
        }

        if (status != kATSInvalidFontTableAccess)
            LOG_ERROR("ATSFontGetTable failed (%d)", status);
    }
}

329
}