// FC_POSTSCRIPT_NAME was added with b561ff20 which ended up in 2.10.92 // Ubuntu 14.04 is on 2.11.0 // Debian 8 and 9 are on 2.11 // OpenSUSE Leap 42.1 is on 2.11.0 (42.3 is on 2.11.1) // Fedora 24 is on 2.11.94 #ifndef FC_POSTSCRIPT_NAME # define FC_POSTSCRIPT_NAME "postscriptname" #endif
/** Since FontConfig is poorly documented, this gives a high level overview: * * FcConfig is a handle to a FontConfig configuration instance. Each 'configuration' is independent * from any others which may exist. There exists a default global configuration which is created * and destroyed by FcInit and FcFini, but this default should not normally be used. * Instead, one should use FcConfigCreate and FcInit* to have a named local state. * * FcPatterns are {objectName -> [element]} (maps from object names to a list of elements). * Each element is some internal data plus an FcValue which is a variant (a union with a type tag). * Lists of elements are not typed, except by convention. Any collection of FcValues must be * assumed to be heterogeneous by the code, but the code need not do anything particularly * interesting if the values go against convention. * * Somewhat like DirectWrite, FontConfig supports synthetics through FC_EMBOLDEN and FC_MATRIX. * Like all synthetic information, such information must be passed with the font data.
*/
namespace {
// FontConfig was thread antagonistic until 2.10.91 with known thread safety issues until 2.13.93. // Before that, lock with a global mutex. // See https://bug.skia.org/1497 and cl/339089311 for background. static SkMutex& f_c_mutex() { static SkMutex& mutex = *(new SkMutex); return mutex;
}
class FCLocker { inlinestatic constexpr int FontConfigThreadSafeVersion = 21393;
// Assume FcGetVersion() has always been thread safe. staticvoid lock() SK_NO_THREAD_SAFETY_ANALYSIS { if (FcGetVersion() < FontConfigThreadSafeVersion) {
f_c_mutex().acquire();
}
} staticvoid unlock() SK_NO_THREAD_SAFETY_ANALYSIS {
AssertHeld(); if (FcGetVersion() < FontConfigThreadSafeVersion) {
f_c_mutex().release();
}
}
enum SkWeakReturn {
kIsWeak_WeakReturn,
kIsStrong_WeakReturn,
kNoId_WeakReturn
}; /** Ideally there would exist a call like * FcResult FcPatternIsWeak(pattern, object, id, FcBool* isWeak); * Sometime after 2.12.4 FcPatternGetWithBinding was added which can retrieve the binding. * * However, there is no such call and as of Fc 2.11.0 even FcPatternEquals ignores the weak bit. * Currently, the only reliable way of finding the weak bit is by its effect on matching. * The weak bit only affects the matching of FC_FAMILY and FC_POSTSCRIPT_NAME object values. * A element with the weak bit is scored after FC_LANG, without the weak bit is scored before. * Note that the weak bit is stored on the element, not on the value it holds.
*/ static SkWeakReturn is_weak(FcPattern* pattern, constchar object[], int id) {
FCLocker::AssertHeld();
FcResult result;
// Create a copy of the pattern with only the value 'pattern'['object'['id']] in it. // Internally, FontConfig pattern objects are linked lists, so faster to remove from head.
SkAutoFcObjectSet requestedObjectOnly(FcObjectSetBuild(object, nullptr));
SkAutoFcPattern minimal(FcPatternFilter(pattern, requestedObjectOnly));
FcBool hasId = true; for (int i = 0; hasId && i < id; ++i) {
hasId = FcPatternRemove(minimal, object, 0);
} if (!hasId) { return kNoId_WeakReturn;
}
FcValue value;
result = FcPatternGet(minimal, object, 0, &value); if (result != FcResultMatch) { return kNoId_WeakReturn;
} while (hasId) {
hasId = FcPatternRemove(minimal, object, 1);
}
// Create a font set with two patterns. // 1. the same 'object' as minimal and a lang object with only 'nomatchlang'. // 2. a different 'object' from minimal and a lang object with only 'matchlang'.
SkAutoFcFontSet fontSet;
// Add 'matchlang' to the copy of the pattern.
FcPatternAddLangSet(minimal, FC_LANG, weakLangSet);
// Run a match against the copy of the pattern. // If the 'id' was weak, then we should match the pattern with 'matchlang'. // If the 'id' was strong, then we should match the pattern with 'nomatchlang'.
// Note that this config is only used for FcFontRenderPrepare, which we don't even want. // However, there appears to be no way to match/sort without it.
SkAutoFcConfig config;
FcFontSet* fontSets[1] = { fontSet };
SkAutoFcPattern match(FcFontSetMatch(config, fontSets, std::size(fontSets),
minimal, &result));
/** Removes weak elements from either FC_FAMILY or FC_POSTSCRIPT_NAME objects in the property. * This can be quite expensive, and should not be used more than once per font lookup. * This removes all of the weak elements after the last strong element.
*/ staticvoid remove_weak(FcPattern* pattern, constchar object[]) {
FCLocker::AssertHeld();
int lastStrongId = -1; int numIds;
SkWeakReturn result; for (int id = 0; ; ++id) {
result = is_weak(minimal, object, 0); if (kNoId_WeakReturn == result) {
numIds = id; break;
} if (kIsStrong_WeakReturn == result) {
lastStrongId = id;
}
SkAssertResult(FcPatternRemove(minimal, object, 0));
}
// If they were all weak, then leave the pattern alone. if (lastStrongId < 0) { return;
}
// Remove everything after the last strong. for (int id = lastStrongId + 1; id < numIds; ++id) {
SkAssertResult(FcPatternRemove(pattern, object, lastStrongId + 1));
}
}
static SkScalar map_ranges(SkScalar val, MapRanges const ranges[], int rangesCount) { // -Inf to [0] if (val < ranges[0].old_val) { return ranges[0].new_val;
}
// Linear from [i] to [i+1] for (int i = 0; i < rangesCount - 1; ++i) { if (val < ranges[i+1].old_val) { return map_range(val, ranges[i].old_val, ranges[i+1].old_val,
ranges[i].new_val, ranges[i+1].new_val);
}
}
// From [n] to +Inf // if (fcweight < Inf) return ranges[rangesCount-1].new_val;
}
class SkScalerContext_fontconfig; class SkTypeface_fontconfig : public SkTypeface { public: static sk_sp<SkTypeface_fontconfig> Make(SkAutoFcPattern pattern,
SkString sysroot,
SkFontScanner* scanner) { return sk_sp<SkTypeface_fontconfig>( new SkTypeface_fontconfig(std::move(pattern), std::move(sysroot), scanner));
} mutable SkAutoFcPattern fPattern; // Mutable for passing to FontConfig API. const SkString fSysroot;
void onGetFamilyName(SkString* familyName) const override {
*familyName = get_string(fPattern, FC_FAMILY);
} void onGetFontDescriptor(SkFontDescriptor* desc, bool* serialize) const override { // TODO: need to serialize FC_MATRIX and FC_EMBOLDEN
FCLocker lock;
fProxy->onGetFontDescriptor(desc, serialize);
desc->setFamilyName(get_string(fPattern, FC_FAMILY));
desc->setFullName(get_string(fPattern, FC_FULLNAME));
desc->setPostscriptName(get_string(fPattern, FC_POSTSCRIPT_NAME));
desc->setStyle(this->fontStyle());
*serialize = false;
}
std::unique_ptr<SkStreamAsset> onOpenStream(int* ttcIndex) const override { return fProxy->onOpenStream(ttcIndex);
} void onFilterRec(SkScalerContextRec* rec) const override { // FontConfig provides 10-scale-bitmap-fonts.conf which applies an inverse "pixelsize" // matrix. It is not known if this .conf is active or not, so it is not clear if // "pixelsize" should be applied before this matrix. Since using a matrix with a bitmap // font isn't a great idea, only apply the matrix to outline fonts. const FcMatrix* fcMatrix = get_matrix(fPattern, FC_MATRIX); bool fcOutline = get_bool(fPattern, FC_OUTLINE, true); if (fcOutline && fcMatrix) { // fPost2x2 is column-major, left handed (y down). // FcMatrix is column-major, right handed (y up).
SkMatrix fm;
fm.setAll(fcMatrix->xx,-fcMatrix->xy, 0,
-fcMatrix->yx, fcMatrix->yy, 0,
0 , 0 , 1);
fProxy->filterRec(rec);
}
std::unique_ptr<SkAdvancedTypefaceMetrics> onGetAdvancedMetrics() const override {
std::unique_ptr<SkAdvancedTypefaceMetrics> info = fProxy->onGetAdvancedMetrics(); // Simulated fonts shouldn't be considered to be of the type of their data. if (get_matrix(fPattern, FC_MATRIX) || get_bool(fPattern, FC_EMBOLDEN)) {
info->fType = SkAdvancedTypefaceMetrics::kOther_Font;
} return info;
}
sk_sp<SkTypeface> onMakeClone(const SkFontArguments& args) const override { // TODO: need to clone FC_MATRIX and FC_EMBOLDEN by wrapping this return fProxy->onMakeClone(args);
}
class SkFontMgr_fontconfig : public SkFontMgr { mutable SkAutoFcConfig fFC; // Only mutable to avoid const cast when passed to FontConfig API. const SkString fSysroot; const sk_sp<SkDataTable> fFamilyNames;
std::unique_ptr<SkFontScanner> fScanner;
class StyleSet : public SkFontStyleSet { public:
StyleSet(sk_sp<SkFontMgr_fontconfig> parent, SkAutoFcFontSet fontSet)
: fFontMgr(std::move(parent))
, fFontSet(std::move(fontSet))
{ }
~StyleSet() override { // Hold the lock while unrefing the font set.
FCLocker lock;
fFontSet.reset();
}
mutable SkMutex fTFCacheMutex; mutable SkTypefaceCache fTFCache; /** Creates a typeface using a typeface cache. * @param pattern a complete pattern from FcFontRenderPrepare.
*/
sk_sp<SkTypeface> createTypefaceFromFcPattern(SkAutoFcPattern pattern) const { if (!pattern) { return nullptr;
} // Cannot hold FCLocker when calling fTFCache.add; an evicted typeface may need to lock. // Must hold fTFCacheMutex when interacting with fTFCache.
SkAutoMutexExclusive ama(fTFCacheMutex);
sk_sp<SkTypeface> face = [&]() {
FCLocker lock;
sk_sp<SkTypeface> face = fTFCache.findByProcAndRef(FindByFcPattern, pattern); if (face) {
pattern.reset();
} return face;
}(); if (!face) {
face = SkTypeface_fontconfig::Make(std::move(pattern), fSysroot, fScanner.get()); if (face) { // Cannot hold FCLocker in fTFCache.add; evicted typefaces may need to lock.
fTFCache.add(face);
}
} return face;
}
public: /** Takes control of the reference to 'config'. */
SkFontMgr_fontconfig(FcConfig* config, std::unique_ptr<SkFontScanner> scanner)
: fFC(config ? config : FcInitLoadConfigAndFonts())
, fSysroot(reinterpret_cast<constchar*>(FcConfigGetSysRoot(fFC)))
, fFamilyNames(GetFamilyNames(fFC))
, fScanner(std::move(scanner)) { }
~SkFontMgr_fontconfig() override { // Hold the lock while unrefing the config.
FCLocker lock;
fFC.reset();
}
protected: int onCountFamilies() const override { return fFamilyNames->count();
}
/** True if any string object value in the font is the same * as a string object value in the pattern.
*/ staticbool AnyStringMatching(FcPattern* font, FcPattern* pattern, constchar* object) { auto getStrings = [](FcPattern* p, constchar* object, STArray<32, FcChar8*>& strings) { // Set an arbitrary (but high) limit on the number of pattern object values to consider. static constexpr constint maxId = 65536; for (int patternId = 0; patternId < maxId; ++patternId) {
FcChar8* patternString;
FcResult result = FcPatternGetString(p, object, patternId, &patternString); if (result == FcResultNoId) { break;
} if (result == FcResultMatch) {
strings.push_back(patternString);
}
}
}; auto compareStrings = [](FcChar8* a, FcChar8* b) -> bool { return FcStrCmpIgnoreCase(a, b) < 0;
};
bool FontAccessible(FcPattern* font) const { // FontConfig can return fonts which are unreadable. constchar* filename = get_string(font, FC_FILE, nullptr); if (nullptr == filename) { returnfalse;
}
// When sysroot was implemented in e96d7760886a3781a46b3271c76af99e15cb0146 (before 2.11.0) // it was broken; mostly fixed in d17f556153fbaf8fe57fdb4fc1f0efa4313f0ecf (after 2.11.1). // This leaves Debian 8 and 9 with broken support for this feature. // As a result, this feature should not be used until at least 2.11.91. // The broken support is mostly around not making all paths relative to the sysroot. // However, even at 2.13.1 it is possible to get a mix of sysroot and non-sysroot paths, // as any added file path not lexically starting with the sysroot will be unchanged. // To allow users to add local app files outside the sysroot, // prefer the sysroot but also look without the sysroot. if (!fSysroot.isEmpty()) {
SkString resolvedFilename;
resolvedFilename = fSysroot;
resolvedFilename += filename; if (sk_exists(resolvedFilename.c_str(), kRead_SkFILE_Flag)) { returntrue;
}
} return sk_exists(filename, kRead_SkFILE_Flag);
}
SkAutoFcFontSet matches; // TODO: Some families have 'duplicates' due to symbolic links. // The patterns are exactly the same except for the FC_FILE. // It should be possible to collapse these patterns by normalizing. staticconst FcSetName fcNameSet[] = { FcSetSystem, FcSetApplication }; for (int setIndex = 0; setIndex < (int)std::size(fcNameSet); ++setIndex) { // Return value of FcConfigGetFonts must not be destroyed.
FcFontSet* allFonts(FcConfigGetFonts(fFC, fcNameSet[setIndex])); if (nullptr == allFonts) { continue;
}
for (int fontIndex = 0; fontIndex < allFonts->nfont; ++fontIndex) {
FcPattern* font = allFonts->fonts[fontIndex]; if (FontAccessible(font) && FontFamilyNameMatches(font, matchPattern)) {
FcFontSetAdd(matches, FcFontRenderPrepare(fFC, pattern, font));
}
}
}
// We really want to match strong (preferred) and same (acceptable) only here. // If a family name was specified, assume that any weak matches after the last strong // match are weak (default) and ignore them. // After substitution the pattern for 'sans-serif' looks like "wwwwwwwwwwwwwwswww" where // there are many weak but preferred names, followed by defaults. // So it is possible to have weakly matching but preferred names. // In aliases, bindings are weak by default, so this is easy and common. // If no family name was specified, we'll probably only get weak matches, but that's ok.
FcPattern* matchPattern;
SkAutoFcPattern strongPattern(nullptr); if (familyName) {
strongPattern.reset(FcPatternDuplicate(pattern));
remove_weak(strongPattern, FC_FAMILY);
matchPattern = strongPattern;
} else {
matchPattern = pattern;
}
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.