2 * Copyright (C) 2005 Apple Computer, Inc. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * 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.
13 * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
14 * its contributors may be used to endorse or promote products derived
15 * from this software without specific prior written permission.
17 * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
18 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
19 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
20 * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
21 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
22 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
23 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
24 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 #import <WebKit/WebAssertions.h>
30 #import <WebKit/WebBridge.h>
31 #import <WebKit/WebKitLogging.h>
32 #import <WebKit/WebKitSystemBits.h>
33 #import <WebKit/WebPreferences.h>
34 #import <WebKit/WebTextRendererFactory.h>
35 #import <WebKit/WebTextRenderer.h>
36 #import <WebKitSystemInterface.h>
38 #import <mach-o/dyld.h>
40 #define IMPORTANT_FONT_TRAITS (0 \
42 | NSCompressedFontMask \
43 | NSCondensedFontMask \
44 | NSExpandedFontMask \
48 | NSSmallCapsFontMask \
51 #define DESIRED_WEIGHT 5
53 @interface NSFont (WebPrivate)
54 - (ATSUFontID)_atsFontID;
57 @interface NSFont (WebAppKitSecretAPI)
58 - (BOOL)_isFakeFixedPitch;
61 @implementation WebTextRendererFactory
63 - (BOOL)coalesceTextDrawing
65 return [viewStack objectAtIndex: [viewStack count]-1] == [NSView focusView] ? YES : NO;
68 - (void)startCoalesceTextDrawing
71 viewStack = [[NSMutableArray alloc] init];
73 viewBuffers = [[NSMutableDictionary alloc] init];
74 [viewStack addObject: [NSView focusView]];
77 - (void)endCoalesceTextDrawing
79 ASSERT([self coalesceTextDrawing]);
81 NSView *targetView = [viewStack objectAtIndex: [viewStack count]-1];
82 [viewStack removeLastObject];
83 NSValue *viewKey = [NSValue valueWithNonretainedObject: targetView];
84 NSMutableSet *glyphBuffers = [viewBuffers objectForKey:viewKey];
86 [glyphBuffers makeObjectsPerformSelector: @selector(drawInView:) withObject: targetView];
87 [glyphBuffers makeObjectsPerformSelector: @selector(reset)];
88 [viewBuffers removeObjectForKey: viewKey];
91 - (WebGlyphBuffer *)glyphBufferForFont: (NSFont *)font andColor: (NSColor *)color
93 ASSERT([self coalesceTextDrawing]);
95 NSMutableSet *glyphBuffers;
96 WebGlyphBuffer *glyphBuffer = nil;
97 NSValue *viewKey = [NSValue valueWithNonretainedObject: [NSView focusView]];
99 glyphBuffers = [viewBuffers objectForKey:viewKey];
100 if (glyphBuffers == nil){
101 glyphBuffers = [[NSMutableSet alloc] init];
102 [viewBuffers setObject: glyphBuffers forKey: viewKey];
103 [glyphBuffers release];
106 NSEnumerator *enumerator = [glyphBuffers objectEnumerator];
109 // Could use a dictionary w/ font/color key for faster lookup.
110 while ((value = [enumerator nextObject])) {
111 if ([value font] == font && [[value color] isEqual: color])
114 if (glyphBuffer == nil){
115 glyphBuffer = [[WebGlyphBuffer alloc] initWithFont: font color: color];
116 [glyphBuffers addObject: glyphBuffer];
117 [glyphBuffer release];
124 getAppDefaultValue(CFStringRef key, int *v)
126 CFPropertyListRef value;
128 value = CFPreferencesCopyValue(key, kCFPreferencesCurrentApplication,
129 kCFPreferencesAnyUser,
130 kCFPreferencesAnyHost);
132 value = CFPreferencesCopyValue(key, kCFPreferencesCurrentApplication,
133 kCFPreferencesCurrentUser,
134 kCFPreferencesAnyHost);
139 if (CFGetTypeID(value) == CFNumberGetTypeID()) {
141 CFNumberGetValue(value, kCFNumberIntType, v);
142 } else if (CFGetTypeID(value) == CFStringGetTypeID()) {
144 *v = CFStringGetIntValue(value);
155 getUserDefaultValue(CFStringRef key, int *v)
157 CFPropertyListRef value;
159 value = CFPreferencesCopyValue(key, kCFPreferencesAnyApplication,
160 kCFPreferencesCurrentUser,
161 kCFPreferencesCurrentHost);
165 if (CFGetTypeID(value) == CFNumberGetTypeID()) {
167 CFNumberGetValue(value, kCFNumberIntType, v);
168 } else if (CFGetTypeID(value) == CFStringGetTypeID()) {
170 *v = CFStringGetIntValue(value);
180 static int getLCDScaleParameters(void)
185 key = CFSTR("AppleFontSmoothing");
186 if (!getAppDefaultValue(key, &mode)) {
187 if (!getUserDefaultValue(key, &mode))
191 if (WKFontSmoothingModeIsLCD(mode))
197 static CFMutableDictionaryRef fontCache;
198 static CFMutableDictionaryRef fixedPitchFonts;
202 [cacheForScreen release];
203 [cacheForPrinter release];
205 cacheForScreen = [[NSMutableDictionary alloc] init];
206 cacheForPrinter = [[NSMutableDictionary alloc] init];
209 CFRelease(fontCache);
212 if (fixedPitchFonts) {
213 CFRelease (fixedPitchFonts);
221 fontsChanged( ATSFontNotificationInfoRef info, void *_factory)
223 WebTextRendererFactory *factory = (WebTextRendererFactory *)_factory;
225 LOG (FontCache, "clearing font caches");
229 [factory clearCaches];
232 #define MINIMUM_GLYPH_CACHE_SIZE 1536 * 1024
234 + (void)createSharedFactory
236 if (![self sharedFactory]) {
237 [[[self alloc] init] release];
240 if (WebSystemMainMemory() > 128 * 1024 * 1024)
241 s = MINIMUM_GLYPH_CACHE_SIZE*getLCDScaleParameters();
243 s = MINIMUM_GLYPH_CACHE_SIZE;
245 LOG (CacheSizes, "Glyph cache size set to %d bytes.", s);
249 // Ignore errors returned from ATSFontNotificationSubscribe. If we can't subscribe then we
250 // won't be told about changes to fonts.
251 ATSFontNotificationSubscribe( fontsChanged, kATSFontNotifyOptionDefault, (void *)[super sharedFactory], nil );
253 ASSERT([[self sharedFactory] isKindOfClass:self]);
256 + (WebTextRendererFactory *)sharedFactory;
258 return (WebTextRendererFactory *)[super sharedFactory];
261 - (BOOL)isFontFixedPitch: (NSFont *)font
265 if (!fixedPitchFonts) {
266 fixedPitchFonts = CFDictionaryCreateMutable (0, 0, &kCFTypeDictionaryKeyCallBacks, 0);
269 CFBooleanRef val = CFDictionaryGetValue (fixedPitchFonts, font);
271 ret = (val == kCFBooleanTrue);
274 // Special case Osaka-Mono. According to <rdar://problem/3999467>, we should treat Osaka-Mono
275 // as fixed pitch. Note that the AppKit does not report MS-PGothic as fixed pitch.
277 // Special case MS PGothic. According to <rdar://problem/4032938, we should not treat MS-PGothic
278 // as fixed pitch. Note that AppKit does report MS-PGothic as fixed pitch.
279 if (([font isFixedPitch] || [font _isFakeFixedPitch] || [[font fontName] caseInsensitiveCompare:@"Osaka-Mono"] == NSOrderedSame) &&
280 ![[font fontName] caseInsensitiveCompare:@"MS-PGothic"] == NSOrderedSame) {
281 CFDictionarySetValue (fixedPitchFonts, font, kCFBooleanTrue);
285 CFDictionarySetValue (fixedPitchFonts, font, kCFBooleanFalse);
296 cacheForScreen = [[NSMutableDictionary alloc] init];
297 cacheForPrinter = [[NSMutableDictionary alloc] init];
304 [cacheForScreen release];
305 [cacheForPrinter release];
306 [viewBuffers release];
312 - (WebTextRenderer *)rendererWithFont:(NSFont *)font usingPrinterFont:(BOOL)usingPrinterFont
314 NSMutableDictionary *cache = usingPrinterFont ? cacheForPrinter : cacheForScreen;
315 WebTextRenderer *renderer = [cache objectForKey:font];
316 if (renderer == nil) {
317 renderer = [[WebTextRenderer alloc] initWithFont:font usingPrinterFont:usingPrinterFont];
318 [cache setObject:renderer forKey:font];
324 - (NSFont *)fallbackFontWithTraits:(NSFontTraitMask)traits size:(float)size
326 NSFont *font = [self cachedFontFromFamily:@"Helvetica" traits:traits size:size];
328 // The Helvetica fallback will almost always work, since that's a basic
329 // font that we ship with all systems. But in the highly unusual case where
330 // the user removed Helvetica, we fall back on Lucida Grande because that's
331 // guaranteed to be there, according to Nathan Taylor. This is good enough
332 // to avoid a crash, at least. To reduce the possibility of failure even further,
333 // we don't even bother with traits.
334 font = [self cachedFontFromFamily:@"Lucida Grande" traits:0 size:size];
341 - (NSFont *)fontWithFamilies:(NSString **)families traits:(NSFontTraitMask)traits size:(float)size
347 while (families && families[i] != 0 && font == nil){
348 family = families[i++];
349 if ([family length] != 0)
350 font = [self cachedFontFromFamily: family traits:traits size:size];
353 // We didn't find a font. Use a fallback font.
354 static int matchCount = 3;
355 static NSString *matchWords[] = { @"Arabic", @"Pashto", @"Urdu" };
356 static NSString *matchFamilies[] = { @"Geeza Pro", @"Geeza Pro", @"Geeza Pro" };
358 // First we'll attempt to find an appropriate font using a match based on
359 // the presence of keywords in the the requested names. For example, we'll
360 // match any name that contains "Arabic" to Geeza Pro.
363 while (families && families[i] != 0 && font == nil) {
364 family = families[i++];
365 if ([family length] != 0) {
367 while (j < matchCount && font == nil) {
368 if ([family rangeOfString:matchWords[j] options:NSCaseInsensitiveSearch].location != NSNotFound) {
369 font = [self cachedFontFromFamily:matchFamilies[j] traits:traits size:size];
376 // Still nothing found, use the final fallback.
378 font = [self fallbackFontWithTraits:traits size:size];
385 static BOOL acceptableChoice(NSFontTraitMask desiredTraits, int desiredWeight,
386 NSFontTraitMask candidateTraits, int candidateWeight)
388 return (candidateTraits & desiredTraits) == desiredTraits;
391 static BOOL betterChoice(NSFontTraitMask desiredTraits, int desiredWeight,
392 NSFontTraitMask chosenTraits, int chosenWeight,
393 NSFontTraitMask candidateTraits, int candidateWeight)
395 if (!acceptableChoice(desiredTraits, desiredWeight, candidateTraits, candidateWeight)) {
399 // A list of the traits we care about.
400 // The top item in the list is the worst trait to mismatch; if a font has this
401 // and we didn't ask for it, we'd prefer any other font in the family.
402 const NSFontTraitMask masks[] = {
406 NSCompressedFontMask,
413 NSFontTraitMask mask;
414 while ((mask = masks[i++])) {
415 if ((desiredTraits & mask) != 0) {
416 ASSERT((chosenTraits & mask) != 0);
417 ASSERT((candidateTraits & mask) != 0);
420 BOOL chosenHasUnwantedTrait = (chosenTraits & mask) != 0;
421 BOOL candidateHasUnwantedTrait = (candidateTraits & mask) != 0;
422 if (!candidateHasUnwantedTrait && chosenHasUnwantedTrait) {
425 if (!chosenHasUnwantedTrait && candidateHasUnwantedTrait) {
430 int chosenWeightDelta = chosenWeight - desiredWeight;
431 int candidateWeightDelta = candidateWeight - desiredWeight;
433 int chosenWeightDeltaMagnitude = ABS(chosenWeightDelta);
434 int candidateWeightDeltaMagnitude = ABS(candidateWeightDelta);
436 // Smaller magnitude wins.
437 // If both have same magnitude, tie breaker is that the smaller weight wins.
438 // Otherwise, first font in the array wins (should almost never happen).
439 if (candidateWeightDeltaMagnitude < chosenWeightDeltaMagnitude) {
442 if (candidateWeightDeltaMagnitude == chosenWeightDeltaMagnitude && candidateWeight < chosenWeight) {
449 // Family name is somewhat of a misnomer here. We first attempt to find an exact match
450 // comparing the desiredFamily to the PostScript name of the installed fonts. If that fails
451 // we then do a search based on the family names of the installed fonts.
452 - (NSFont *)fontWithFamily:(NSString *)desiredFamily traits:(NSFontTraitMask)desiredTraits size:(float)size
454 NSFontManager *fontManager = [NSFontManager sharedFontManager];
457 LOG (FontSelection, "looking for %@ with traits %x\n", desiredFamily, desiredTraits);
459 // Look for an exact match first.
460 NSEnumerator *availableFonts = [[fontManager availableFonts] objectEnumerator];
461 NSString *availableFont;
462 while ((availableFont = [availableFonts nextObject])) {
463 if ([desiredFamily caseInsensitiveCompare:availableFont] == NSOrderedSame) {
464 NSFont *nameMatchedFont = [NSFont fontWithName:availableFont size:size];
466 // Special case Osaka-Mono. According to <rdar://problem/3999467>, we need to
467 // treat Osaka-Mono as fixed pitch.
468 if ([desiredFamily caseInsensitiveCompare:@"Osaka-Mono"] == NSOrderedSame && desiredTraits == 0) {
469 LOG (FontSelection, "found exact match for Osaka-Mono\n");
470 return nameMatchedFont;
473 NSFontTraitMask traits = [fontManager traitsOfFont:nameMatchedFont];
475 if ((traits & desiredTraits) == desiredTraits){
476 font = [fontManager convertFont:nameMatchedFont toHaveTrait:desiredTraits];
477 LOG (FontSelection, "returning exact match (%@)\n\n", [[[font fontDescriptor] fontAttributes] objectForKey: NSFontNameAttribute]);
480 LOG (FontSelection, "found exact match, but not desired traits, available traits %x\n", traits);
485 // Do a simple case insensitive search for a matching font family.
486 // NSFontManager requires exact name matches.
487 // This addresses the problem of matching arial to Arial, etc., but perhaps not all the issues.
488 NSEnumerator *e = [[fontManager availableFontFamilies] objectEnumerator];
489 NSString *availableFamily;
490 while ((availableFamily = [e nextObject])) {
491 if ([desiredFamily caseInsensitiveCompare:availableFamily] == NSOrderedSame) {
496 // Found a family, now figure out what weight and traits to use.
497 BOOL choseFont = false;
498 int chosenWeight = 0;
499 NSFontTraitMask chosenTraits = 0;
501 NSArray *fonts = [fontManager availableMembersOfFontFamily:availableFamily];
502 unsigned n = [fonts count];
504 for (i = 0; i < n; i++) {
505 NSArray *fontInfo = [fonts objectAtIndex:i];
507 // Array indices must be hard coded because of lame AppKit API.
508 int fontWeight = [[fontInfo objectAtIndex:2] intValue];
509 NSFontTraitMask fontTraits = [[fontInfo objectAtIndex:3] unsignedIntValue];
514 newWinner = acceptableChoice(desiredTraits, DESIRED_WEIGHT, fontTraits, fontWeight);
516 newWinner = betterChoice(desiredTraits, DESIRED_WEIGHT,
517 chosenTraits, chosenWeight, fontTraits, fontWeight);
522 chosenWeight = fontWeight;
523 chosenTraits = fontTraits;
525 if (chosenWeight == DESIRED_WEIGHT
526 && (chosenTraits & IMPORTANT_FONT_TRAITS) == (desiredTraits & IMPORTANT_FONT_TRAITS)) {
533 LOG (FontSelection, "nothing appropriate to return\n\n");
537 font = [fontManager fontWithFamily:availableFamily traits:chosenTraits weight:chosenWeight size:size];
538 LOG (FontSelection, "returning font family %@ (%@) traits %x, fontID = %x\n\n",
539 availableFamily, [[[font fontDescriptor] fontAttributes] objectForKey: NSFontNameAttribute], chosenTraits, (unsigned int)[font _atsFontID]);
546 NSFontTraitMask traits;
550 static const void *FontCacheKeyCopy(CFAllocatorRef allocator, const void *value)
552 const FontCacheKey *key = (const FontCacheKey *)value;
553 FontCacheKey *result = malloc(sizeof(FontCacheKey));
554 result->family = [key->family copy];
555 result->traits = key->traits;
556 result->size = key->size;
560 static void FontCacheKeyFree(CFAllocatorRef allocator, const void *value)
562 const FontCacheKey *key = (const FontCacheKey *)value;
563 [key->family release];
567 static Boolean FontCacheKeyEqual(const void *value1, const void *value2)
569 const FontCacheKey *key1 = (const FontCacheKey *)value1;
570 const FontCacheKey *key2 = (const FontCacheKey *)value2;
571 return key1->size == key2->size && key1->traits == key2->traits && [key1->family isEqualToString:key2->family];
574 static CFHashCode FontCacheKeyHash(const void *value)
576 const FontCacheKey *key = (const FontCacheKey *)value;
577 return [key->family hash] ^ key->traits ^ (int)key->size;
580 static const void *FontCacheValueRetain(CFAllocatorRef allocator, const void *value)
588 static void FontCacheValueRelease(CFAllocatorRef allocator, const void *value)
595 - (NSFont *)cachedFontFromFamily:(NSString *)family traits:(NSFontTraitMask)traits size:(float)size
600 static const CFDictionaryKeyCallBacks fontCacheKeyCallBacks = { 0, FontCacheKeyCopy, FontCacheKeyFree, NULL, FontCacheKeyEqual, FontCacheKeyHash };
601 static const CFDictionaryValueCallBacks fontCacheValueCallBacks = { 0, FontCacheValueRetain, FontCacheValueRelease, NULL, NULL };
602 fontCache = CFDictionaryCreateMutable(NULL, 0, &fontCacheKeyCallBacks, &fontCacheValueCallBacks);
605 const FontCacheKey fontKey = { family, traits, size };
608 if (CFDictionaryGetValueIfPresent(fontCache, &fontKey, &value)) {
609 font = (NSFont *)value;
611 if ([family length] == 0) {
614 font = [self fontWithFamily:family traits:traits size:size];
615 CFDictionaryAddValue(fontCache, &fontKey, font);
618 #ifdef DEBUG_MISSING_FONT
619 static int unableToFindFontCount = 0;
621 unableToFindFontCount++;
622 NSLog(@"unableToFindFontCount %@, traits 0x%08x, size %f, %d\n", family, traits, size, unableToFindFontCount);