Source code

Revision control

Other Tools

/* -*- Mode: C++; tab-width: 20; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "gfxFont.h"
#include "mozilla/BinarySearch.h"
#include "mozilla/DebugOnly.h"
#include "mozilla/FontPropertyTypes.h"
#include "mozilla/gfx/2D.h"
#include "mozilla/IntegerRange.h"
#include "mozilla/MathAlgorithms.h"
#include "mozilla/StaticPrefs_gfx.h"
#include "mozilla/SVGContextPaint.h"
#include "mozilla/Logging.h"
#include "nsITimer.h"
#include "gfxGlyphExtents.h"
#include "gfxPlatform.h"
#include "gfxTextRun.h"
#include "nsGkAtoms.h"
#include "gfxTypes.h"
#include "gfxContext.h"
#include "gfxFontMissingGlyphs.h"
#include "gfxGraphiteShaper.h"
#include "gfxHarfBuzzShaper.h"
#include "gfxUserFontSet.h"
#include "nsCRT.h"
#include "nsSpecialCasingData.h"
#include "nsTextRunTransformations.h"
#include "nsUGenCategory.h"
#include "nsUnicodeProperties.h"
#include "nsStyleConsts.h"
#include "mozilla/AppUnits.h"
#include "mozilla/Likely.h"
#include "mozilla/MemoryReporting.h"
#include "mozilla/Preferences.h"
#include "mozilla/Services.h"
#include "mozilla/Telemetry.h"
#include "gfxMathTable.h"
#include "gfxSVGGlyphs.h"
#include "gfx2DGlue.h"
#include "TextDrawTarget.h"
#include "ThebesRLBox.h"
#include "GreekCasing.h"
#include "cairo.h"
#ifdef XP_WIN
# include "cairo-win32.h"
# include "gfxWindowsPlatform.h"
#endif
#include "harfbuzz/hb.h"
#include "harfbuzz/hb-ot.h"
#include <algorithm>
#include <limits>
#include <cmath>
using namespace mozilla;
using namespace mozilla::gfx;
using namespace mozilla::unicode;
using mozilla::services::GetObserverService;
gfxFontCache* gfxFontCache::gGlobalCache = nullptr;
#ifdef DEBUG_roc
# define DEBUG_TEXT_RUN_STORAGE_METRICS
#endif
#ifdef DEBUG_TEXT_RUN_STORAGE_METRICS
uint32_t gTextRunStorageHighWaterMark = 0;
uint32_t gTextRunStorage = 0;
uint32_t gFontCount = 0;
uint32_t gGlyphExtentsCount = 0;
uint32_t gGlyphExtentsWidthsTotalSize = 0;
uint32_t gGlyphExtentsSetupEagerSimple = 0;
uint32_t gGlyphExtentsSetupEagerTight = 0;
uint32_t gGlyphExtentsSetupLazyTight = 0;
uint32_t gGlyphExtentsSetupFallBackToTight = 0;
#endif
#define LOG_FONTINIT(args) \
MOZ_LOG(gfxPlatform::GetLog(eGfxLog_fontinit), LogLevel::Debug, args)
#define LOG_FONTINIT_ENABLED() \
MOZ_LOG_TEST(gfxPlatform::GetLog(eGfxLog_fontinit), LogLevel::Debug)
/*
* gfxFontCache - global cache of gfxFont instances.
* Expires unused fonts after a short interval;
* notifies fonts to age their cached shaped-word records;
* observes memory-pressure notification and tells fonts to clear their
* shaped-word caches to free up memory.
*/
MOZ_DEFINE_MALLOC_SIZE_OF(FontCacheMallocSizeOf)
NS_IMPL_ISUPPORTS(gfxFontCache::MemoryReporter, nsIMemoryReporter)
/*virtual*/
gfxTextRunFactory::~gfxTextRunFactory() {
// Should not be dropped by stylo
MOZ_ASSERT(NS_IsMainThread());
}
NS_IMETHODIMP
gfxFontCache::MemoryReporter::CollectReports(
nsIHandleReportCallback* aHandleReport, nsISupports* aData,
bool aAnonymize) {
FontCacheSizes sizes;
gfxFontCache::GetCache()->AddSizeOfIncludingThis(&FontCacheMallocSizeOf,
&sizes);
MOZ_COLLECT_REPORT("explicit/gfx/font-cache", KIND_HEAP, UNITS_BYTES,
sizes.mFontInstances,
"Memory used for active font instances.");
MOZ_COLLECT_REPORT("explicit/gfx/font-shaped-words", KIND_HEAP, UNITS_BYTES,
sizes.mShapedWords,
"Memory used to cache shaped glyph data.");
return NS_OK;
}
NS_IMPL_ISUPPORTS(gfxFontCache::Observer, nsIObserver)
NS_IMETHODIMP
gfxFontCache::Observer::Observe(nsISupports* aSubject, const char* aTopic,
const char16_t* someData) {
if (!nsCRT::strcmp(aTopic, "memory-pressure")) {
gfxFontCache* fontCache = gfxFontCache::GetCache();
if (fontCache) {
fontCache->FlushShapedWordCaches();
}
} else {
MOZ_ASSERT_UNREACHABLE("unexpected notification topic");
}
return NS_OK;
}
nsresult gfxFontCache::Init() {
NS_ASSERTION(!gGlobalCache, "Where did this come from?");
gGlobalCache = new gfxFontCache(GetMainThreadSerialEventTarget());
if (!gGlobalCache) {
return NS_ERROR_OUT_OF_MEMORY;
}
RegisterStrongMemoryReporter(new MemoryReporter());
return NS_OK;
}
void gfxFontCache::Shutdown() {
delete gGlobalCache;
gGlobalCache = nullptr;
#ifdef DEBUG_TEXT_RUN_STORAGE_METRICS
printf("Textrun storage high water mark=%d\n", gTextRunStorageHighWaterMark);
printf("Total number of fonts=%d\n", gFontCount);
printf("Total glyph extents allocated=%d (size %d)\n", gGlyphExtentsCount,
int(gGlyphExtentsCount * sizeof(gfxGlyphExtents)));
printf("Total glyph extents width-storage size allocated=%d\n",
gGlyphExtentsWidthsTotalSize);
printf("Number of simple glyph extents eagerly requested=%d\n",
gGlyphExtentsSetupEagerSimple);
printf("Number of tight glyph extents eagerly requested=%d\n",
gGlyphExtentsSetupEagerTight);
printf("Number of tight glyph extents lazily requested=%d\n",
gGlyphExtentsSetupLazyTight);
printf("Number of simple glyph extent setups that fell back to tight=%d\n",
gGlyphExtentsSetupFallBackToTight);
#endif
}
gfxFontCache::gfxFontCache(nsIEventTarget* aEventTarget)
: gfxFontCacheExpirationTracker(aEventTarget) {
nsCOMPtr<nsIObserverService> obs = GetObserverService();
if (obs) {
obs->AddObserver(new Observer, "memory-pressure", false);
}
nsIEventTarget* target = nullptr;
if (XRE_IsContentProcess() && NS_IsMainThread()) {
target = aEventTarget;
}
NS_NewTimerWithFuncCallback(getter_AddRefs(mWordCacheExpirationTimer),
WordCacheExpirationTimerCallback, this,
SHAPED_WORD_TIMEOUT_SECONDS * 1000,
nsITimer::TYPE_REPEATING_SLACK,
"gfxFontCache::gfxFontCache", target);
}
gfxFontCache::~gfxFontCache() {
// Ensure the user font cache releases its references to font entries,
// so they aren't kept alive after the font instances and font-list
// have been shut down.
gfxUserFontSet::UserFontCache::Shutdown();
if (mWordCacheExpirationTimer) {
mWordCacheExpirationTimer->Cancel();
mWordCacheExpirationTimer = nullptr;
}
// Expire everything that has a zero refcount, so we don't leak them.
AgeAllGenerations();
// All fonts should be gone.
NS_WARNING_ASSERTION(mFonts.Count() == 0,
"Fonts still alive while shutting down gfxFontCache");
// Note that we have to delete everything through the expiration
// tracker, since there might be fonts not in the hashtable but in
// the tracker.
}
bool gfxFontCache::HashEntry::KeyEquals(const KeyTypePointer aKey) const {
const gfxCharacterMap* fontUnicodeRangeMap = mFont->GetUnicodeRangeMap();
return aKey->mFontEntry == mFont->GetFontEntry() &&
aKey->mStyle->Equals(*mFont->GetStyle()) &&
((!aKey->mUnicodeRangeMap && !fontUnicodeRangeMap) ||
(aKey->mUnicodeRangeMap && fontUnicodeRangeMap &&
aKey->mUnicodeRangeMap->Equals(fontUnicodeRangeMap)));
}
gfxFont* gfxFontCache::Lookup(const gfxFontEntry* aFontEntry,
const gfxFontStyle* aStyle,
const gfxCharacterMap* aUnicodeRangeMap) {
Key key(aFontEntry, aStyle, aUnicodeRangeMap);
HashEntry* entry = mFonts.GetEntry(key);
Telemetry::Accumulate(Telemetry::FONT_CACHE_HIT, entry != nullptr);
if (!entry) return nullptr;
return entry->mFont;
}
void gfxFontCache::AddNew(gfxFont* aFont) {
Key key(aFont->GetFontEntry(), aFont->GetStyle(),
aFont->GetUnicodeRangeMap());
HashEntry* entry = mFonts.PutEntry(key);
if (!entry) return;
gfxFont* oldFont = entry->mFont;
entry->mFont = aFont;
// Assert that we can find the entry we just put in (this fails if the key
// has a NaN float value in it, e.g. 'sizeAdjust').
MOZ_ASSERT(entry == mFonts.GetEntry(key));
// If someone's asked us to replace an existing font entry, then that's a
// bit weird, but let it happen, and expire the old font if it's not used.
if (oldFont && oldFont->GetExpirationState()->IsTracked()) {
// if oldFont == aFont, recount should be > 0,
// so we shouldn't be here.
NS_ASSERTION(aFont != oldFont, "new font is tracked for expiry!");
NotifyExpired(oldFont);
}
}
void gfxFontCache::NotifyReleased(gfxFont* aFont) {
nsresult rv = AddObject(aFont);
if (NS_FAILED(rv)) {
// We couldn't track it for some reason. Kill it now.
DestroyFont(aFont);
}
// Note that we might have fonts that aren't in the hashtable, perhaps because
// of OOM adding to the hashtable or because someone did an AddNew where
// we already had a font. These fonts are added to the expiration tracker
// anyway, even though Lookup can't resurrect them. Eventually they will
// expire and be deleted.
}
void gfxFontCache::NotifyExpired(gfxFont* aFont) {
aFont->ClearCachedWords();
RemoveObject(aFont);
DestroyFont(aFont);
}
void gfxFontCache::DestroyFont(gfxFont* aFont) {
Key key(aFont->GetFontEntry(), aFont->GetStyle(),
aFont->GetUnicodeRangeMap());
HashEntry* entry = mFonts.GetEntry(key);
if (entry && entry->mFont == aFont) {
mFonts.RemoveEntry(entry);
}
NS_ASSERTION(aFont->GetRefCount() == 0,
"Destroying with non-zero ref count!");
delete aFont;
}
/*static*/
void gfxFontCache::WordCacheExpirationTimerCallback(nsITimer* aTimer,
void* aCache) {
gfxFontCache* cache = static_cast<gfxFontCache*>(aCache);
for (auto it = cache->mFonts.Iter(); !it.Done(); it.Next()) {
it.Get()->mFont->AgeCachedWords();
}
}
void gfxFontCache::FlushShapedWordCaches() {
for (auto it = mFonts.Iter(); !it.Done(); it.Next()) {
it.Get()->mFont->ClearCachedWords();
}
}
void gfxFontCache::NotifyGlyphsChanged() {
for (auto it = mFonts.Iter(); !it.Done(); it.Next()) {
it.Get()->mFont->NotifyGlyphsChanged();
}
}
void gfxFontCache::AddSizeOfExcludingThis(MallocSizeOf aMallocSizeOf,
FontCacheSizes* aSizes) const {
// TODO: add the overhead of the expiration tracker (generation arrays)
aSizes->mFontInstances += mFonts.ShallowSizeOfExcludingThis(aMallocSizeOf);
for (auto iter = mFonts.ConstIter(); !iter.Done(); iter.Next()) {
iter.Get()->mFont->AddSizeOfExcludingThis(aMallocSizeOf, aSizes);
}
}
void gfxFontCache::AddSizeOfIncludingThis(MallocSizeOf aMallocSizeOf,
FontCacheSizes* aSizes) const {
aSizes->mFontInstances += aMallocSizeOf(this);
AddSizeOfExcludingThis(aMallocSizeOf, aSizes);
}
#define MAX_SSXX_VALUE 99
#define MAX_CVXX_VALUE 99
static void LookupAlternateValues(const gfxFontFeatureValueSet& aFeatureLookup,
const nsACString& aFamily,
const StyleVariantAlternates& aAlternates,
nsTArray<gfxFontFeature>& aFontFeatures) {
using Tag = StyleVariantAlternates::Tag;
// historical-forms gets handled in nsFont::AddFontFeaturesToStyle.
if (aAlternates.IsHistoricalForms()) {
return;
}
gfxFontFeature feature;
if (aAlternates.IsCharacterVariant()) {
for (auto& ident : aAlternates.AsCharacterVariant().AsSpan()) {
Span<const uint32_t> values = aFeatureLookup.GetFontFeatureValuesFor(
aFamily, NS_FONT_VARIANT_ALTERNATES_CHARACTER_VARIANT,
ident.AsAtom());
// nothing defined, skip
if (values.IsEmpty()) {
continue;
}
NS_ASSERTION(values.Length() <= 2,
"too many values allowed for character-variant");
// character-variant(12 3) ==> 'cv12' = 3
uint32_t nn = values[0];
// ignore values greater than 99
if (nn == 0 || nn > MAX_CVXX_VALUE) {
continue;
}
feature.mValue = values.Length() > 1 ? values[1] : 1;
feature.mTag = HB_TAG('c', 'v', ('0' + nn / 10), ('0' + nn % 10));
aFontFeatures.AppendElement(feature);
}
return;
}
if (aAlternates.IsStyleset()) {
for (auto& ident : aAlternates.AsStyleset().AsSpan()) {
Span<const uint32_t> values = aFeatureLookup.GetFontFeatureValuesFor(
aFamily, NS_FONT_VARIANT_ALTERNATES_STYLESET, ident.AsAtom());
// styleset(1 2 7) ==> 'ss01' = 1, 'ss02' = 1, 'ss07' = 1
feature.mValue = 1;
for (uint32_t nn : values) {
if (nn == 0 || nn > MAX_SSXX_VALUE) {
continue;
}
feature.mTag = HB_TAG('s', 's', ('0' + nn / 10), ('0' + nn % 10));
aFontFeatures.AppendElement(feature);
}
}
return;
}
uint32_t constant = 0;
nsAtom* name = nullptr;
switch (aAlternates.tag) {
case Tag::Swash:
constant = NS_FONT_VARIANT_ALTERNATES_SWASH;
name = aAlternates.AsSwash().AsAtom();
break;
case Tag::Stylistic:
constant = NS_FONT_VARIANT_ALTERNATES_STYLISTIC;
name = aAlternates.AsStylistic().AsAtom();
break;
case Tag::Ornaments:
constant = NS_FONT_VARIANT_ALTERNATES_ORNAMENTS;
name = aAlternates.AsOrnaments().AsAtom();
break;
case Tag::Annotation:
constant = NS_FONT_VARIANT_ALTERNATES_ANNOTATION;
name = aAlternates.AsAnnotation().AsAtom();
break;
default:
MOZ_ASSERT_UNREACHABLE("Unknown font-variant-alternates value!");
return;
}
Span<const uint32_t> values =
aFeatureLookup.GetFontFeatureValuesFor(aFamily, constant, name);
if (values.IsEmpty()) {
return;
}
MOZ_ASSERT(values.Length() == 1,
"too many values for font-specific font-variant-alternates");
feature.mValue = values[0];
switch (aAlternates.tag) {
case Tag::Swash: // swsh, cswh
feature.mTag = HB_TAG('s', 'w', 's', 'h');
aFontFeatures.AppendElement(feature);
feature.mTag = HB_TAG('c', 's', 'w', 'h');
break;
case Tag::Stylistic: // salt
feature.mTag = HB_TAG('s', 'a', 'l', 't');
break;
case Tag::Ornaments: // ornm
feature.mTag = HB_TAG('o', 'r', 'n', 'm');
break;
case Tag::Annotation: // nalt
feature.mTag = HB_TAG('n', 'a', 'l', 't');
break;
default:
MOZ_ASSERT_UNREACHABLE("how?");
return;
}
aFontFeatures.AppendElement(feature);
}
/* static */
void gfxFontShaper::MergeFontFeatures(
const gfxFontStyle* aStyle, const nsTArray<gfxFontFeature>& aFontFeatures,
bool aDisableLigatures, const nsACString& aFamilyName, bool aAddSmallCaps,
void (*aHandleFeature)(const uint32_t&, uint32_t&, void*),
void* aHandleFeatureData) {
const nsTArray<gfxFontFeature>& styleRuleFeatures = aStyle->featureSettings;
// Bail immediately if nothing to do, which is the common case.
if (styleRuleFeatures.IsEmpty() && aFontFeatures.IsEmpty() &&
!aDisableLigatures &&
aStyle->variantCaps == NS_FONT_VARIANT_CAPS_NORMAL &&
aStyle->variantSubSuper == NS_FONT_VARIANT_POSITION_NORMAL &&
aStyle->variantAlternates.IsEmpty()) {
return;
}
nsDataHashtable<nsUint32HashKey, uint32_t> mergedFeatures;
// add feature values from font
for (const gfxFontFeature& feature : aFontFeatures) {
mergedFeatures.Put(feature.mTag, feature.mValue);
}
// font-variant-caps - handled here due to the need for fallback handling
// petite caps cases can fallback to appropriate smallcaps
uint32_t variantCaps = aStyle->variantCaps;
switch (variantCaps) {
case NS_FONT_VARIANT_CAPS_NORMAL:
break;
case NS_FONT_VARIANT_CAPS_ALLSMALL:
mergedFeatures.Put(HB_TAG('c', '2', 's', 'c'), 1);
// fall through to the small-caps case
[[fallthrough]];
case NS_FONT_VARIANT_CAPS_SMALLCAPS:
mergedFeatures.Put(HB_TAG('s', 'm', 'c', 'p'), 1);
break;
case NS_FONT_VARIANT_CAPS_ALLPETITE:
mergedFeatures.Put(aAddSmallCaps ? HB_TAG('c', '2', 's', 'c')
: HB_TAG('c', '2', 'p', 'c'),
1);
// fall through to the petite-caps case
[[fallthrough]];
case NS_FONT_VARIANT_CAPS_PETITECAPS:
mergedFeatures.Put(aAddSmallCaps ? HB_TAG('s', 'm', 'c', 'p')
: HB_TAG('p', 'c', 'a', 'p'),
1);
break;
case NS_FONT_VARIANT_CAPS_TITLING:
mergedFeatures.Put(HB_TAG('t', 'i', 't', 'l'), 1);
break;
case NS_FONT_VARIANT_CAPS_UNICASE:
mergedFeatures.Put(HB_TAG('u', 'n', 'i', 'c'), 1);
break;
default:
MOZ_ASSERT_UNREACHABLE("Unexpected variantCaps");
break;
}
// font-variant-position - handled here due to the need for fallback
switch (aStyle->variantSubSuper) {
case NS_FONT_VARIANT_POSITION_NORMAL:
break;
case NS_FONT_VARIANT_POSITION_SUPER:
mergedFeatures.Put(HB_TAG('s', 'u', 'p', 's'), 1);
break;
case NS_FONT_VARIANT_POSITION_SUB:
mergedFeatures.Put(HB_TAG('s', 'u', 'b', 's'), 1);
break;
default:
MOZ_ASSERT_UNREACHABLE("Unexpected variantSubSuper");
break;
}
// add font-specific feature values from style rules
if (aStyle->featureValueLookup && !aStyle->variantAlternates.IsEmpty()) {
AutoTArray<gfxFontFeature, 4> featureList;
// insert list of alternate feature settings
for (auto& alternate : aStyle->variantAlternates.AsSpan()) {
LookupAlternateValues(*aStyle->featureValueLookup, aFamilyName, alternate,
featureList);
}
for (const gfxFontFeature& feature : featureList) {
mergedFeatures.Put(feature.mTag, feature.mValue);
}
}
// Add features that are already resolved to tags & values in the style.
if (styleRuleFeatures.IsEmpty()) {
// Disable common ligatures if non-zero letter-spacing is in effect.
if (aDisableLigatures) {
mergedFeatures.Put(HB_TAG('l', 'i', 'g', 'a'), 0);
mergedFeatures.Put(HB_TAG('c', 'l', 'i', 'g'), 0);
}
} else {
for (const gfxFontFeature& feature : styleRuleFeatures) {
// A dummy feature (0,0) is used as a sentinel to separate features
// originating from font-variant-* or other high-level properties from
// those directly specified as font-feature-settings. The high-level
// features may be overridden by aDisableLigatures, while low-level
// features specified directly as tags will come last and therefore
// take precedence over everything else.
if (feature.mTag) {
mergedFeatures.Put(feature.mTag, feature.mValue);
} else if (aDisableLigatures) {
// Handle ligature-disabling setting at the boundary between high-
// and low-level features.
mergedFeatures.Put(HB_TAG('l', 'i', 'g', 'a'), 0);
mergedFeatures.Put(HB_TAG('c', 'l', 'i', 'g'), 0);
}
}
}
if (mergedFeatures.Count() != 0) {
for (auto iter = mergedFeatures.Iter(); !iter.Done(); iter.Next()) {
aHandleFeature(iter.Key(), iter.Data(), aHandleFeatureData);
}
}
}
void gfxShapedText::SetupClusterBoundaries(uint32_t aOffset,
const char16_t* aString,
uint32_t aLength) {
CompressedGlyph* glyphs = GetCharacterGlyphs() + aOffset;
CompressedGlyph extendCluster = CompressedGlyph::MakeComplex(false, true);
ClusterIterator iter(aString, aLength);
// the ClusterIterator won't be able to tell us if the string
// _begins_ with a cluster-extender, so we handle that here
if (aLength) {
uint32_t ch = *aString;
if (aLength > 1 && NS_IS_SURROGATE_PAIR(ch, aString[1])) {
ch = SURROGATE_TO_UCS4(ch, aString[1]);
}
if (IsClusterExtender(ch)) {
*glyphs = extendCluster;
}
}
while (!iter.AtEnd()) {
if (*iter == char16_t(' ')) {
glyphs->SetIsSpace();
}
// advance iter to the next cluster-start (or end of text)
iter.Next();
// step past the first char of the cluster
aString++;
glyphs++;
// mark all the rest as cluster-continuations
while (aString < iter) {
*glyphs = extendCluster;
glyphs++;
aString++;
}
}
}
void gfxShapedText::SetupClusterBoundaries(uint32_t aOffset,
const uint8_t* aString,
uint32_t aLength) {
CompressedGlyph* glyphs = GetCharacterGlyphs() + aOffset;
const uint8_t* limit = aString + aLength;
while (aString < limit) {
if (*aString == uint8_t(' ')) {
glyphs->SetIsSpace();
}
aString++;
glyphs++;
}
}
gfxShapedText::DetailedGlyph* gfxShapedText::AllocateDetailedGlyphs(
uint32_t aIndex, uint32_t aCount) {
NS_ASSERTION(aIndex < GetLength(), "Index out of range");
if (!mDetailedGlyphs) {
mDetailedGlyphs = MakeUnique<DetailedGlyphStore>();
}
return mDetailedGlyphs->Allocate(aIndex, aCount);
}
void gfxShapedText::SetDetailedGlyphs(uint32_t aIndex, uint32_t aGlyphCount,
const DetailedGlyph* aGlyphs) {
CompressedGlyph& g = GetCharacterGlyphs()[aIndex];
MOZ_ASSERT(aIndex > 0 || g.IsLigatureGroupStart(),
"First character can't be a ligature continuation!");
if (aGlyphCount > 0) {
DetailedGlyph* details = AllocateDetailedGlyphs(aIndex, aGlyphCount);
memcpy(details, aGlyphs, sizeof(DetailedGlyph) * aGlyphCount);
}
g.SetGlyphCount(aGlyphCount);
}
#define ZWNJ 0x200C
#define ZWJ 0x200D
static inline bool IsIgnorable(uint32_t aChar) {
return (IsDefaultIgnorable(aChar)) || aChar == ZWNJ || aChar == ZWJ;
}
void gfxShapedText::SetMissingGlyph(uint32_t aIndex, uint32_t aChar,
gfxFont* aFont) {
CompressedGlyph& g = GetCharacterGlyphs()[aIndex];
uint8_t category = GetGeneralCategory(aChar);
if (category >= HB_UNICODE_GENERAL_CATEGORY_SPACING_MARK &&
category <= HB_UNICODE_GENERAL_CATEGORY_NON_SPACING_MARK) {
g.SetComplex(false, true);
}
// Leaving advance as zero will prevent drawing the hexbox for ignorables.
int32_t advance = 0;
if (!IsIgnorable(aChar)) {
gfxFloat width =
std::max(aFont->GetMetrics(nsFontMetrics::eHorizontal).aveCharWidth,
gfxFloat(gfxFontMissingGlyphs::GetDesiredMinWidth(
aChar, mAppUnitsPerDevUnit)));
advance = int32_t(width * mAppUnitsPerDevUnit);
}
DetailedGlyph detail = {aChar, advance, gfx::Point()};
SetDetailedGlyphs(aIndex, 1, &detail);
g.SetMissing();
}
bool gfxShapedText::FilterIfIgnorable(uint32_t aIndex, uint32_t aCh) {
if (IsIgnorable(aCh)) {
// There are a few default-ignorables of Letter category (currently,
// just the Hangul filler characters) that we'd better not discard
// if they're followed by additional characters in the same cluster.
// Some fonts use them to carry the width of a whole cluster of
// combining jamos; see bug 1238243.
auto* charGlyphs = GetCharacterGlyphs();
if (GetGenCategory(aCh) == nsUGenCategory::kLetter &&
aIndex + 1 < GetLength() && !charGlyphs[aIndex + 1].IsClusterStart()) {
return false;
}
// A compressedGlyph that is set to MISSING but has no DetailedGlyphs list
// will be zero-width/invisible, which is what we want here.
CompressedGlyph& g = charGlyphs[aIndex];
g.SetComplex(g.IsClusterStart(), g.IsLigatureGroupStart()).SetMissing();
return true;
}
return false;
}
void gfxShapedText::AdjustAdvancesForSyntheticBold(float aSynBoldOffset,
uint32_t aOffset,
uint32_t aLength) {
uint32_t synAppUnitOffset = aSynBoldOffset * mAppUnitsPerDevUnit;
CompressedGlyph* charGlyphs = GetCharacterGlyphs();
for (uint32_t i = aOffset; i < aOffset + aLength; ++i) {
CompressedGlyph* glyphData = charGlyphs + i;
if (glyphData->IsSimpleGlyph()) {
// simple glyphs ==> just add the advance
int32_t advance = glyphData->GetSimpleAdvance();
if (advance > 0) {
advance += synAppUnitOffset;
if (CompressedGlyph::IsSimpleAdvance(advance)) {
glyphData->SetSimpleGlyph(advance, glyphData->GetSimpleGlyph());
} else {
// rare case, tested by making this the default
uint32_t glyphIndex = glyphData->GetSimpleGlyph();
// convert the simple CompressedGlyph to an empty complex record
glyphData->SetComplex(true, true);
// then set its details (glyph ID with its new advance)
DetailedGlyph detail = {glyphIndex, advance, gfx::Point()};
SetDetailedGlyphs(i, 1, &detail);
}
}
} else {
// complex glyphs ==> add offset at cluster/ligature boundaries
uint32_t detailedLength = glyphData->GetGlyphCount();
if (detailedLength) {
DetailedGlyph* details = GetDetailedGlyphs(i);
if (!details) {
continue;
}
if (IsRightToLeft()) {
if (details[0].mAdvance > 0) {
details[0].mAdvance += synAppUnitOffset;
}
} else {
if (details[detailedLength - 1].mAdvance > 0) {
details[detailedLength - 1].mAdvance += synAppUnitOffset;
}
}
}
}
}
}
float gfxFont::AngleForSyntheticOblique() const {
// If the style doesn't call for italic/oblique, or if the face already
// provides it, no synthetic style should be added.
if (mStyle.style == FontSlantStyle::Normal() || !mStyle.allowSyntheticStyle ||
!mFontEntry->IsUpright()) {
return 0.0f;
}
// If style calls for italic, and face doesn't support it, use default
// oblique angle as a simulation.
if (mStyle.style.IsItalic()) {
return mFontEntry->SupportsItalic() ? 0.0f : FontSlantStyle::kDefaultAngle;
}
// Default or custom oblique angle
return mStyle.style.ObliqueAngle();
}
float gfxFont::SkewForSyntheticOblique() const {
// Precomputed value of tan(kDefaultAngle), the default italic/oblique slant;
// avoids calling tan() at runtime except for custom oblique values.
static const float kTanDefaultAngle =
tan(FontSlantStyle::kDefaultAngle * (M_PI / 180.0));
float angle = AngleForSyntheticOblique();
if (angle == 0.0f) {
return 0.0f;
} else if (angle == FontSlantStyle::kDefaultAngle) {
return kTanDefaultAngle;
} else {
return tan(angle * (M_PI / 180.0));
}
}
void gfxFont::RunMetrics::CombineWith(const RunMetrics& aOther,
bool aOtherIsOnLeft) {
mAscent = std::max(mAscent, aOther.mAscent);
mDescent = std::max(mDescent, aOther.mDescent);
if (aOtherIsOnLeft) {
mBoundingBox = (mBoundingBox + gfxPoint(aOther.mAdvanceWidth, 0))
.Union(aOther.mBoundingBox);
} else {
mBoundingBox =
mBoundingBox.Union(aOther.mBoundingBox + gfxPoint(mAdvanceWidth, 0));
}
mAdvanceWidth += aOther.mAdvanceWidth;
}
gfxFont::gfxFont(const RefPtr<UnscaledFont>& aUnscaledFont,
gfxFontEntry* aFontEntry, const gfxFontStyle* aFontStyle,
AntialiasOption anAAOption)
: mFontEntry(aFontEntry),
mUnscaledFont(aUnscaledFont),
mStyle(*aFontStyle),
mAdjustedSize(0.0),
mFUnitsConvFactor(-1.0f), // negative to indicate "not yet initialized"
mAntialiasOption(anAAOption),
mIsValid(true),
mApplySyntheticBold(false),
mKerningEnabled(false),
mMathInitialized(false) {
#ifdef DEBUG_TEXT_RUN_STORAGE_METRICS
++gFontCount;
#endif
if (MOZ_UNLIKELY(StaticPrefs::gfx_text_disable_aa_AtStartup())) {
mAntialiasOption = kAntialiasNone;
}
// Turn off AA for Ahem for testing purposes when requested.
if (MOZ_UNLIKELY(StaticPrefs::gfx_font_rendering_ahem_antialias_none() &&
mFontEntry->FamilyName().EqualsLiteral("Ahem"))) {
mAntialiasOption = kAntialiasNone;
}
mKerningSet = HasFeatureSet(HB_TAG('k', 'e', 'r', 'n'), mKerningEnabled);
}
gfxFont::~gfxFont() {
mFontEntry->NotifyFontDestroyed(this);
if (mGlyphChangeObservers) {
for (auto it = mGlyphChangeObservers->Iter(); !it.Done(); it.Next()) {
it.Get()->GetKey()->ForgetFont();
}
}
}
// Work out whether cairo will snap inter-glyph spacing to pixels.
//
// Layout does not align text to pixel boundaries, so, with font drawing
// backends that snap glyph positions to pixels, it is important that
// inter-glyph spacing within words is always an integer number of pixels.
// This ensures that the drawing backend snaps all of the word's glyphs in the
// same direction and so inter-glyph spacing remains the same.
//
gfxFont::RoundingFlags gfxFont::GetRoundOffsetsToPixels(
DrawTarget* aDrawTarget) {
// Could do something fancy here for ScaleFactors of
// AxisAlignedTransforms, but we leave things simple.
// Not much point rounding if a matrix will mess things up anyway.
// Also check if the font already knows hint metrics is off...
if (aDrawTarget->GetTransform().HasNonTranslation() || !ShouldHintMetrics()) {
return RoundingFlags(0);
}
cairo_t* cr = static_cast<cairo_t*>(
aDrawTarget->GetNativeSurface(NativeSurfaceType::CAIRO_CONTEXT));
if (cr) {
cairo_surface_t* target = cairo_get_target(cr);
// Check whether the cairo surface's font options hint metrics.
cairo_font_options_t* fontOptions = cairo_font_options_create();
cairo_surface_get_font_options(target, fontOptions);
cairo_hint_metrics_t hintMetrics =
cairo_font_options_get_hint_metrics(fontOptions);
cairo_font_options_destroy(fontOptions);
switch (hintMetrics) {
case CAIRO_HINT_METRICS_OFF:
return RoundingFlags(0);
case CAIRO_HINT_METRICS_ON:
return RoundingFlags::kRoundX | RoundingFlags::kRoundY;
default:
break;
}
}
if (ShouldRoundXOffset(cr)) {
return RoundingFlags::kRoundX | RoundingFlags::kRoundY;
} else {
return RoundingFlags::kRoundY;
}
}
gfxFloat gfxFont::GetGlyphHAdvance(DrawTarget* aDrawTarget, uint16_t aGID) {
if (ProvidesGlyphWidths()) {
return GetGlyphWidth(aGID) / 65536.0;
}
if (mFUnitsConvFactor < 0.0f) {
GetMetrics(nsFontMetrics::eHorizontal);
}
NS_ASSERTION(mFUnitsConvFactor >= 0.0f,
"missing font unit conversion factor");
if (!mHarfBuzzShaper) {
mHarfBuzzShaper = MakeUnique<gfxHarfBuzzShaper>(this);
}
gfxHarfBuzzShaper* shaper =
static_cast<gfxHarfBuzzShaper*>(mHarfBuzzShaper.get());
if (!shaper->Initialize()) {
return 0;
}
return shaper->GetGlyphHAdvance(aGID) / 65536.0;
}
static void CollectLookupsByFeature(hb_face_t* aFace, hb_tag_t aTableTag,
uint32_t aFeatureIndex,
hb_set_t* aLookups) {
uint32_t lookups[32];
uint32_t i, len, offset;
offset = 0;
do {
len = ArrayLength(lookups);
hb_ot_layout_feature_get_lookups(aFace, aTableTag, aFeatureIndex, offset,
&len, lookups);
for (i = 0; i < len; i++) {
hb_set_add(aLookups, lookups[i]);
}
offset += len;
} while (len == ArrayLength(lookups));
}
static void CollectLookupsByLanguage(
hb_face_t* aFace, hb_tag_t aTableTag,
const nsTHashtable<nsUint32HashKey>& aSpecificFeatures,
hb_set_t* aOtherLookups, hb_set_t* aSpecificFeatureLookups,
uint32_t aScriptIndex, uint32_t aLangIndex) {
uint32_t reqFeatureIndex;
if (hb_ot_layout_language_get_required_feature_index(
aFace, aTableTag, aScriptIndex, aLangIndex, &reqFeatureIndex)) {
CollectLookupsByFeature(aFace, aTableTag, reqFeatureIndex, aOtherLookups);
}
uint32_t featureIndexes[32];
uint32_t i, len, offset;
offset = 0;
do {
len = ArrayLength(featureIndexes);
hb_ot_layout_language_get_feature_indexes(aFace, aTableTag, aScriptIndex,
aLangIndex, offset, &len,
featureIndexes);
for (i = 0; i < len; i++) {
uint32_t featureIndex = featureIndexes[i];
// get the feature tag
hb_tag_t featureTag;
uint32_t tagLen = 1;
hb_ot_layout_language_get_feature_tags(aFace, aTableTag, aScriptIndex,
aLangIndex, offset + i, &tagLen,
&featureTag);
// collect lookups
hb_set_t* lookups = aSpecificFeatures.GetEntry(featureTag)
? aSpecificFeatureLookups
: aOtherLookups;
CollectLookupsByFeature(aFace, aTableTag, featureIndex, lookups);
}
offset += len;
} while (len == ArrayLength(featureIndexes));
}
static bool HasLookupRuleWithGlyphByScript(
hb_face_t* aFace, hb_tag_t aTableTag, hb_tag_t aScriptTag,
uint32_t aScriptIndex, uint16_t aGlyph,
const nsTHashtable<nsUint32HashKey>& aDefaultFeatures,
bool& aHasDefaultFeatureWithGlyph) {
uint32_t numLangs, lang;
hb_set_t* defaultFeatureLookups = hb_set_create();
hb_set_t* nonDefaultFeatureLookups = hb_set_create();
// default lang
CollectLookupsByLanguage(aFace, aTableTag, aDefaultFeatures,
nonDefaultFeatureLookups, defaultFeatureLookups,
aScriptIndex, HB_OT_LAYOUT_DEFAULT_LANGUAGE_INDEX);
// iterate over langs
numLangs = hb_ot_layout_script_get_language_tags(
aFace, aTableTag, aScriptIndex, 0, nullptr, nullptr);
for (lang = 0; lang < numLangs; lang++) {
CollectLookupsByLanguage(aFace, aTableTag, aDefaultFeatures,
nonDefaultFeatureLookups, defaultFeatureLookups,
aScriptIndex, lang);
}
// look for the glyph among default feature lookups
aHasDefaultFeatureWithGlyph = false;
hb_set_t* glyphs = hb_set_create();
hb_codepoint_t index = -1;
while (hb_set_next(defaultFeatureLookups, &index)) {
hb_ot_layout_lookup_collect_glyphs(aFace, aTableTag, index, glyphs, glyphs,
glyphs, nullptr);
if (hb_set_has(glyphs, aGlyph)) {
aHasDefaultFeatureWithGlyph = true;
break;
}
}
// look for the glyph among non-default feature lookups
// if no default feature lookups contained spaces
bool hasNonDefaultFeatureWithGlyph = false;
if (!aHasDefaultFeatureWithGlyph) {
hb_set_clear(glyphs);
index = -1;
while (hb_set_next(nonDefaultFeatureLookups, &index)) {
hb_ot_layout_lookup_collect_glyphs(aFace, aTableTag, index, glyphs,
glyphs, glyphs, nullptr);
if (hb_set_has(glyphs, aGlyph)) {
hasNonDefaultFeatureWithGlyph = true;
break;
}
}
}
hb_set_destroy(glyphs);
hb_set_destroy(defaultFeatureLookups);
hb_set_destroy(nonDefaultFeatureLookups);
return aHasDefaultFeatureWithGlyph || hasNonDefaultFeatureWithGlyph;
}
static void HasLookupRuleWithGlyph(hb_face_t* aFace, hb_tag_t aTableTag,
bool& aHasGlyph, hb_tag_t aSpecificFeature,
bool& aHasGlyphSpecific, uint16_t aGlyph) {
// iterate over the scripts in the font
uint32_t numScripts, numLangs, script, lang;
hb_set_t* otherLookups = hb_set_create();
hb_set_t* specificFeatureLookups = hb_set_create();
nsTHashtable<nsUint32HashKey> specificFeature;
specificFeature.PutEntry(aSpecificFeature);
numScripts =
hb_ot_layout_table_get_script_tags(aFace, aTableTag, 0, nullptr, nullptr);
for (script = 0; script < numScripts; script++) {
// default lang
CollectLookupsByLanguage(aFace, aTableTag, specificFeature, otherLookups,
specificFeatureLookups, script,
HB_OT_LAYOUT_DEFAULT_LANGUAGE_INDEX);
// iterate over langs
numLangs = hb_ot_layout_script_get_language_tags(
aFace, HB_OT_TAG_GPOS, script, 0, nullptr, nullptr);
for (lang = 0; lang < numLangs; lang++) {
CollectLookupsByLanguage(aFace, aTableTag, specificFeature, otherLookups,
specificFeatureLookups, script, lang);
}
}
// look for the glyph among non-specific feature lookups
hb_set_t* glyphs = hb_set_create();
hb_codepoint_t index = -1;
while (hb_set_next(otherLookups, &index)) {
hb_ot_layout_lookup_collect_glyphs(aFace, aTableTag, index, glyphs, glyphs,
glyphs, nullptr);
if (hb_set_has(glyphs, aGlyph)) {
aHasGlyph = true;
break;
}
}
// look for the glyph among specific feature lookups
hb_set_clear(glyphs);
index = -1;
while (hb_set_next(specificFeatureLookups, &index)) {
hb_ot_layout_lookup_collect_glyphs(aFace, aTableTag, index, glyphs, glyphs,
glyphs, nullptr);
if (hb_set_has(glyphs, aGlyph)) {
aHasGlyphSpecific = true;
break;
}
}
hb_set_destroy(glyphs);
hb_set_destroy(specificFeatureLookups);
hb_set_destroy(otherLookups);
}
nsDataHashtable<nsUint32HashKey, Script>* gfxFont::sScriptTagToCode = nullptr;
nsTHashtable<nsUint32HashKey>* gfxFont::sDefaultFeatures = nullptr;
static inline bool HasSubstitution(uint32_t* aBitVector, Script aScript) {
return (aBitVector[static_cast<uint32_t>(aScript) >> 5] &
(1 << (static_cast<uint32_t>(aScript) & 0x1f))) != 0;
}
// union of all default substitution features across scripts
static const hb_tag_t defaultFeatures[] = {
HB_TAG('a', 'b', 'v', 'f'), HB_TAG('a', 'b', 'v', 's'),
HB_TAG('a', 'k', 'h', 'n'), HB_TAG('b', 'l', 'w', 'f'),
HB_TAG('b', 'l', 'w', 's'), HB_TAG('c', 'a', 'l', 't'),
HB_TAG('c', 'c', 'm', 'p'), HB_TAG('c', 'f', 'a', 'r'),
HB_TAG('c', 'j', 'c', 't'), HB_TAG('c', 'l', 'i', 'g'),
HB_TAG('f', 'i', 'n', '2'), HB_TAG('f', 'i', 'n', '3'),
HB_TAG('f', 'i', 'n', 'a'), HB_TAG('h', 'a', 'l', 'f'),
HB_TAG('h', 'a', 'l', 'n'), HB_TAG('i', 'n', 'i', 't'),
HB_TAG('i', 's', 'o', 'l'), HB_TAG('l', 'i', 'g', 'a'),
HB_TAG('l', 'j', 'm', 'o'), HB_TAG('l', 'o', 'c', 'l'),
HB_TAG('l', 't', 'r', 'a'), HB_TAG('l', 't', 'r', 'm'),
HB_TAG('m', 'e', 'd', '2'), HB_TAG('m', 'e', 'd', 'i'),
HB_TAG('m', 's', 'e', 't'), HB_TAG('n', 'u', 'k', 't'),
HB_TAG('p', 'r', 'e', 'f'), HB_TAG('p', 'r', 'e', 's'),
HB_TAG('p', 's', 't', 'f'), HB_TAG('p', 's', 't', 's'),
HB_TAG('r', 'c', 'l', 't'), HB_TAG('r', 'l', 'i', 'g'),
HB_TAG('r', 'k', 'r', 'f'), HB_TAG('r', 'p', 'h', 'f'),
HB_TAG('r', 't', 'l', 'a'), HB_TAG('r', 't', 'l', 'm'),
HB_TAG('t', 'j', 'm', 'o'), HB_TAG('v', 'a', 't', 'u'),
HB_TAG('v', 'e', 'r', 't'), HB_TAG('v', 'j', 'm', 'o')};
void gfxFont::CheckForFeaturesInvolvingSpace() {
mFontEntry->mHasSpaceFeaturesInitialized = true;
bool log = LOG_FONTINIT_ENABLED();
TimeStamp start;
if (MOZ_UNLIKELY(log)) {
start = TimeStamp::Now();
}
bool result = false;
uint32_t spaceGlyph = GetSpaceGlyph();
if (!spaceGlyph) {
return;
}
hb_face_t* face = GetFontEntry()->GetHBFace();
// GSUB lookups - examine per script
if (hb_ot_layout_has_substitution(face)) {
// set up the script ==> code hashtable if needed
if (!sScriptTagToCode) {
sScriptTagToCode = new nsDataHashtable<nsUint32HashKey, Script>(
size_t(Script::NUM_SCRIPT_CODES));
sScriptTagToCode->Put(HB_TAG('D', 'F', 'L', 'T'), Script::COMMON);
// Ensure that we don't try to look at script codes beyond what the
// current version of ICU (at runtime -- in case of system ICU)
// knows about.
Script scriptCount =
Script(std::min<int>(u_getIntPropertyMaxValue(UCHAR_SCRIPT) + 1,
int(Script::NUM_SCRIPT_CODES)));
for (Script s = Script::ARABIC; s < scriptCount;
s = Script(static_cast<int>(s) + 1)) {
hb_script_t script = hb_script_t(GetScriptTagForCode(s));
unsigned int scriptCount = 4;
hb_tag_t scriptTags[4];
hb_ot_tags_from_script_and_language(script, HB_LANGUAGE_INVALID,
&scriptCount, scriptTags, nullptr,
nullptr);
for (unsigned int i = 0; i < scriptCount; i++) {
sScriptTagToCode->Put(scriptTags[i], s);
}
}
uint32_t numDefaultFeatures = ArrayLength(defaultFeatures);
sDefaultFeatures = new nsTHashtable<nsUint32HashKey>(numDefaultFeatures);
for (uint32_t i = 0; i < numDefaultFeatures; i++) {
sDefaultFeatures->PutEntry(defaultFeatures[i]);
}
}
// iterate over the scripts in the font
hb_tag_t scriptTags[8];
uint32_t len, offset = 0;
do {
len = ArrayLength(scriptTags);
hb_ot_layout_table_get_script_tags(face, HB_OT_TAG_GSUB, offset, &len,
scriptTags);
for (uint32_t i = 0; i < len; i++) {
bool isDefaultFeature = false;
Script s;
if (!HasLookupRuleWithGlyphByScript(
face, HB_OT_TAG_GSUB, scriptTags[i], offset + i, spaceGlyph,
*sDefaultFeatures, isDefaultFeature) ||
!sScriptTagToCode->Get(scriptTags[i], &s)) {
continue;
}
result = true;
uint32_t index = static_cast<uint32_t>(s) >> 5;
uint32_t bit = static_cast<uint32_t>(s) & 0x1f;
if (isDefaultFeature) {
mFontEntry->mDefaultSubSpaceFeatures[index] |= (1 << bit);
} else {
mFontEntry->mNonDefaultSubSpaceFeatures[index] |= (1 << bit);
}
}
offset += len;
} while (len == ArrayLength(scriptTags));
}
// spaces in default features of default script?
// ==> can't use word cache, skip GPOS analysis
bool canUseWordCache = true;
if (HasSubstitution(mFontEntry->mDefaultSubSpaceFeatures, Script::COMMON)) {
canUseWordCache = false;
}
// GPOS lookups - distinguish kerning from non-kerning features
mFontEntry->mHasSpaceFeaturesKerning = false;
mFontEntry->mHasSpaceFeaturesNonKerning = false;
if (canUseWordCache && hb_ot_layout_has_positioning(face)) {
bool hasKerning = false, hasNonKerning = false;
HasLookupRuleWithGlyph(face, HB_OT_TAG_GPOS, hasNonKerning,
HB_TAG('k', 'e', 'r', 'n'), hasKerning, spaceGlyph);
if (hasKerning || hasNonKerning) {
result = true;
}
mFontEntry->mHasSpaceFeaturesKerning = hasKerning;
mFontEntry->mHasSpaceFeaturesNonKerning = hasNonKerning;
}
hb_face_destroy(face);
mFontEntry->mHasSpaceFeatures = result;
if (MOZ_UNLIKELY(log)) {
TimeDuration elapsed = TimeStamp::Now() - start;
LOG_FONTINIT(
("(fontinit-spacelookups) font: %s - "
"subst default: %8.8x %8.8x %8.8x %8.8x "
"subst non-default: %8.8x %8.8x %8.8x %8.8x "
"kerning: %s non-kerning: %s time: %6.3f\n",
mFontEntry->Name().get(), mFontEntry->mDefaultSubSpaceFeatures[3],
mFontEntry->mDefaultSubSpaceFeatures[2],
mFontEntry->mDefaultSubSpaceFeatures[1],
mFontEntry->mDefaultSubSpaceFeatures[0],
mFontEntry->mNonDefaultSubSpaceFeatures[3],
mFontEntry->mNonDefaultSubSpaceFeatures[2],
mFontEntry->mNonDefaultSubSpaceFeatures[1],
mFontEntry->mNonDefaultSubSpaceFeatures[0],
(mFontEntry->mHasSpaceFeaturesKerning ? "true" : "false"),
(mFontEntry->mHasSpaceFeaturesNonKerning ? "true" : "false"),
elapsed.ToMilliseconds()));
}
}
bool gfxFont::HasSubstitutionRulesWithSpaceLookups(Script aRunScript) {
NS_ASSERTION(GetFontEntry()->mHasSpaceFeaturesInitialized,
"need to initialize space lookup flags");
NS_ASSERTION(aRunScript < Script::NUM_SCRIPT_CODES, "weird script code");
if (aRunScript == Script::INVALID || aRunScript >= Script::NUM_SCRIPT_CODES) {
return false;
}
// default features have space lookups ==> true
if (HasSubstitution(mFontEntry->mDefaultSubSpaceFeatures, Script::COMMON) ||
HasSubstitution(mFontEntry->mDefaultSubSpaceFeatures, aRunScript)) {
return true;
}
// non-default features have space lookups and some type of
// font feature, in font or style is specified ==> true
if ((HasSubstitution(mFontEntry->mNonDefaultSubSpaceFeatures,
Script::COMMON) ||
HasSubstitution(mFontEntry->mNonDefaultSubSpaceFeatures, aRunScript)) &&
(!mStyle.featureSettings.IsEmpty() ||
!mFontEntry->mFeatureSettings.IsEmpty())) {
return true;
}
return false;
}
tainted_boolean_hint gfxFont::SpaceMayParticipateInShaping(Script aRunScript) {
// avoid checking fonts known not to include default space-dependent features
if (MOZ_UNLIKELY(mFontEntry->mSkipDefaultFeatureSpaceCheck)) {
if (!mKerningSet && mStyle.featureSettings.IsEmpty() &&
mFontEntry->mFeatureSettings.IsEmpty()) {
return false;
}
}
if (FontCanSupportGraphite()) {
if (gfxPlatform::GetPlatform()->UseGraphiteShaping()) {
return mFontEntry->HasGraphiteSpaceContextuals();
}
}
// We record the presence of space-dependent features in the font entry
// so that subsequent instantiations for the same font face won't
// require us to re-check the tables; however, the actual check is done
// by gfxFont because not all font entry subclasses know how to create
// a harfbuzz face for introspection.
if (!mFontEntry->mHasSpaceFeaturesInitialized) {
CheckForFeaturesInvolvingSpace();
}
if (!mFontEntry->mHasSpaceFeatures) {
return false;
}
// if font has substitution rules or non-kerning positioning rules
// that involve spaces, bypass
if (HasSubstitutionRulesWithSpaceLookups(aRunScript) ||
mFontEntry->mHasSpaceFeaturesNonKerning) {
return true;
}
// if kerning explicitly enabled/disabled via font-feature-settings or
// font-kerning and kerning rules use spaces, only bypass when enabled
if (mKerningSet && mFontEntry->mHasSpaceFeaturesKerning) {
return mKerningEnabled;
}
return false;
}
bool gfxFont::SupportsFeature(Script aScript, uint32_t aFeatureTag) {
if (mGraphiteShaper && gfxPlatform::GetPlatform()->UseGraphiteShaping()) {
return GetFontEntry()->SupportsGraphiteFeature(aFeatureTag);
}
return GetFontEntry()->SupportsOpenTypeFeature(aScript, aFeatureTag);
}
bool gfxFont::SupportsVariantCaps(Script aScript, uint32_t aVariantCaps,
bool& aFallbackToSmallCaps,
bool& aSyntheticLowerToSmallCaps,
bool& aSyntheticUpperToSmallCaps) {
bool ok = true; // cases without fallback are fine
aFallbackToSmallCaps = false;
aSyntheticLowerToSmallCaps = false;
aSyntheticUpperToSmallCaps = false;
switch (aVariantCaps) {
case NS_FONT_VARIANT_CAPS_SMALLCAPS:
ok = SupportsFeature(aScript, HB_TAG('s', 'm', 'c', 'p'));
if (!ok) {
aSyntheticLowerToSmallCaps = true;
}
break;
case NS_FONT_VARIANT_CAPS_ALLSMALL:
ok = SupportsFeature(aScript, HB_TAG('s', 'm', 'c', 'p')) &&
SupportsFeature(aScript, HB_TAG('c', '2', 's', 'c'));
if (!ok) {
aSyntheticLowerToSmallCaps = true;
aSyntheticUpperToSmallCaps = true;
}
break;
case NS_FONT_VARIANT_CAPS_PETITECAPS:
ok = SupportsFeature(aScript, HB_TAG('p', 'c', 'a', 'p'));
if (!ok) {
ok = SupportsFeature(aScript, HB_TAG('s', 'm', 'c', 'p'));
aFallbackToSmallCaps = ok;
}
if (!ok) {
aSyntheticLowerToSmallCaps = true;
}
break;
case NS_FONT_VARIANT_CAPS_ALLPETITE:
ok = SupportsFeature(aScript, HB_TAG('p', 'c', 'a', 'p')) &&
SupportsFeature(aScript, HB_TAG('c', '2', 'p', 'c'));
if (!ok) {
ok = SupportsFeature(aScript, HB_TAG('s', 'm', 'c', 'p')) &&
SupportsFeature(aScript, HB_TAG('c', '2', 's', 'c'));
aFallbackToSmallCaps = ok;
}
if (!ok) {
aSyntheticLowerToSmallCaps = true;
aSyntheticUpperToSmallCaps = true;
}
break;
default:
break;
}
NS_ASSERTION(
!(ok && (aSyntheticLowerToSmallCaps || aSyntheticUpperToSmallCaps)),
"shouldn't use synthetic features if we found real ones");
NS_ASSERTION(!(!ok && aFallbackToSmallCaps),
"if we found a usable fallback, that counts as ok");
return ok;
}
bool gfxFont::SupportsSubSuperscript(uint32_t aSubSuperscript,
const uint8_t* aString, uint32_t aLength,
Script aRunScript) {
NS_ConvertASCIItoUTF16 unicodeString(reinterpret_cast<const char*>(aString),
aLength);
return SupportsSubSuperscript(aSubSuperscript, unicodeString.get(), aLength,
aRunScript);
}
bool gfxFont::SupportsSubSuperscript(uint32_t aSubSuperscript,
const char16_t* aString, uint32_t aLength,
Script aRunScript) {
NS_ASSERTION(aSubSuperscript == NS_FONT_VARIANT_POSITION_SUPER ||
aSubSuperscript == NS_FONT_VARIANT_POSITION_SUB,
"unknown value of font-variant-position");
uint32_t feature = aSubSuperscript == NS_FONT_VARIANT_POSITION_SUPER
? HB_TAG('s', 'u', 'p', 's')
: HB_TAG('s', 'u', 'b', 's');
if (!SupportsFeature(aRunScript, feature)) {
return false;
}
// xxx - for graphite, don't really know how to sniff lookups so bail
if (mGraphiteShaper && gfxPlatform::GetPlatform()->UseGraphiteShaping()) {
return true;
}
if (!mHarfBuzzShaper) {
mHarfBuzzShaper = MakeUnique<gfxHarfBuzzShaper>(this);
}
gfxHarfBuzzShaper* shaper =
static_cast<gfxHarfBuzzShaper*>(mHarfBuzzShaper.get());
if (!shaper->Initialize()) {
return false;
}
// get the hbset containing input glyphs for the feature
const hb_set_t* inputGlyphs =
mFontEntry->InputsForOpenTypeFeature(aRunScript, feature);
// create an hbset containing default glyphs for the script run
hb_set_t* defaultGlyphsInRun = hb_set_create();
// for each character, get the glyph id
for (uint32_t i = 0; i < aLength; i++) {
uint32_t ch = aString[i];
if (i + 1 < aLength && NS_IS_SURROGATE_PAIR(ch, aString[i + 1])) {
i++;
ch = SURROGATE_TO_UCS4(ch, aString[i]);
}
if (ch == 0xa0) {
ch = ' ';
}
hb_codepoint_t gid = shaper->GetNominalGlyph(ch);
hb_set_add(defaultGlyphsInRun, gid);
}
// intersect with input glyphs, if size is not the same ==> fallback
uint32_t origSize = hb_set_get_population(defaultGlyphsInRun);
hb_set_intersect(defaultGlyphsInRun, inputGlyphs);
uint32_t intersectionSize = hb_set_get_population(defaultGlyphsInRun);
hb_set_destroy(defaultGlyphsInRun);
return origSize == intersectionSize;
}
bool gfxFont::FeatureWillHandleChar(Script aRunScript, uint32_t aFeature,
uint32_t aUnicode) {
if (!SupportsFeature(aRunScript, aFeature)) {
return false;
}
// xxx - for graphite, don't really know how to sniff lookups so bail
if (mGraphiteShaper && gfxPlatform::GetPlatform()->UseGraphiteShaping()) {
return true;
}
if (!mHarfBuzzShaper) {
mHarfBuzzShaper = MakeUnique<gfxHarfBuzzShaper>(this);
}
gfxHarfBuzzShaper* shaper =
static_cast<gfxHarfBuzzShaper*>(mHarfBuzzShaper.get());
if (!shaper->Initialize()) {
return false;
}
// get the hbset containing input glyphs for the feature
const hb_set_t* inputGlyphs =
mFontEntry->InputsForOpenTypeFeature(aRunScript, aFeature);
if (aUnicode == 0xa0) {
aUnicode = ' ';
}
hb_codepoint_t gid = shaper->GetNominalGlyph(aUnicode);
return hb_set_has(inputGlyphs, gid);
}
bool gfxFont::HasFeatureSet(uint32_t aFeature, bool& aFeatureOn) {
aFeatureOn = false;
if (mStyle.featureSettings.IsEmpty() &&
GetFontEntry()->mFeatureSettings.IsEmpty()) {
return false;
}
// add feature values from font
bool featureSet = <