xref: /aosp_15_r20/external/skia/modules/skparagraph/utils/TestFontCollection.cpp (revision c8dee2aa9b3f27cf6c858bd81872bdeb2c07ed17)
1 // Copyright 2019 Google LLC.
2 #include "modules/skparagraph/utils/TestFontCollection.h"
3 
4 #include "include/core/SkStream.h"
5 #include "modules/skparagraph/src/ParagraphImpl.h"
6 #include "src/base/SkUTF.h"
7 #include "src/core/SkOSFile.h"
8 #include "tools/Resources.h"
9 
10 #if defined(SK_TYPEFACE_FACTORY_FREETYPE)
11 #include "src/ports/SkTypeface_FreeType.h"
12 #elif defined(SK_TYPEFACE_FACTORY_CORETEXT)
13 #include "src/ports/SkTypeface_mac_ct.h"
14 #elif defined(SK_TYPEFACE_FACTORY_DIRECTWRITE)
15 #include "src/ports/SkTypeface_win_dw.h"
16 #endif
17 
18 #include <memory>
19 #include <utility>
20 
21 namespace skia {
22 namespace textlayout {
23 
TestFontCollection(const std::string & resourceDir,bool testOnly,bool loadFonts)24 TestFontCollection::TestFontCollection(const std::string& resourceDir, bool testOnly, bool loadFonts)
25   : fResourceDir(resourceDir)
26   , fFontsFound(0) {
27     if (fDirs == resourceDir) {
28       return;
29     }
30 
31     fFontProvider = sk_make_sp<TypefaceFontProvider>();
32 
33     if (loadFonts) {
34         SkOSFile::Iter iter(fResourceDir.c_str());
35         SkString path;
36         while (iter.next(&path)) {
37             addFontFromFile(path.c_str());
38         }
39     }
40 
41     fFontsFound = fFontProvider->countFamilies();
42     if (testOnly) {
43         this->setTestFontManager(fFontProvider);
44     } else {
45         this->setAssetFontManager(fFontProvider);
46     }
47     this->disableFontFallback();
48     fDirs = resourceDir;
49 }
50 
addFontFromFile(const std::string & path,const std::string & familyName)51 bool TestFontCollection::addFontFromFile(const std::string& path, const std::string& familyName) {
52 
53     SkString file_path;
54     file_path.printf("%s/%s", fResourceDir.c_str(), path.c_str());
55 
56     std::unique_ptr<SkStreamAsset> file = SkFILEStream::Make(file_path.c_str());
57     if (!file) {
58         return false;
59     }
60 #if defined(SK_TYPEFACE_FACTORY_FREETYPE)
61     sk_sp<SkTypeface> face =
62             SkTypeface_FreeType::MakeFromStream(std::move(file), SkFontArguments());
63 #elif defined(SK_TYPEFACE_FACTORY_CORETEXT)
64     sk_sp<SkTypeface> face = SkTypeface_Mac::MakeFromStream(std::move(file), SkFontArguments());
65 #elif defined(SK_TYPEFACE_FACTORY_DIRECTWRITE)
66     sk_sp<SkTypeface> face = DWriteFontTypeface::MakeFromStream(std::move(file), SkFontArguments());
67 #else
68     sk_sp<SkTypeface> face = nullptr;
69 #endif
70     if (familyName.empty()) {
71         fFontProvider->registerTypeface(std::move(face));
72     } else {
73         fFontProvider->registerTypeface(std::move(face), SkString(familyName.c_str()));
74     }
75 
76     return true;
77 }
78 }  // namespace textlayout
79 }  // namespace skia
80