xref: /aosp_15_r20/frameworks/base/native/android/system_fonts.cpp (revision d57664e9bc4670b3ecf6748a746a57c557b6bc9e)
1 /*
2  * Copyright (C) 2018 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include <jni.h>
18 
19 #define LOG_TAG "SystemFont"
20 
21 #include <android/font.h>
22 #include <android/font_matcher.h>
23 #include <android/system_fonts.h>
24 #include <errno.h>
25 #include <fcntl.h>
26 #include <hwui/MinikinSkia.h>
27 #include <libxml/parser.h>
28 #include <log/log.h>
29 #include <minikin/FontCollection.h>
30 #include <minikin/LocaleList.h>
31 #include <minikin/SystemFonts.h>
32 #include <sys/stat.h>
33 #include <unistd.h>
34 
35 #include <memory>
36 #include <string>
37 #include <vector>
38 
39 struct XmlCharDeleter {
operator ()XmlCharDeleter40     void operator()(xmlChar* b) { xmlFree(b); }
41 };
42 
43 struct XmlDocDeleter {
operator ()XmlDocDeleter44     void operator()(xmlDoc* d) { xmlFreeDoc(d); }
45 };
46 
47 using XmlCharUniquePtr = std::unique_ptr<xmlChar, XmlCharDeleter>;
48 using XmlDocUniquePtr = std::unique_ptr<xmlDoc, XmlDocDeleter>;
49 
50 struct ParserState {
51     xmlNode* mFontNode = nullptr;
52     XmlCharUniquePtr mLocale;
53 };
54 
55 struct AFont {
56     std::string mFilePath;
57     std::optional<std::string> mLocale;
58     uint16_t mWeight;
59     bool mItalic;
60     uint32_t mCollectionIndex;
61     std::vector<std::pair<uint32_t, float>> mAxes;
62 
operator ==AFont63     bool operator==(const AFont& o) const {
64         return mFilePath == o.mFilePath && mLocale == o.mLocale && mWeight == o.mWeight &&
65                 mItalic == o.mItalic && mCollectionIndex == o.mCollectionIndex && mAxes == o.mAxes;
66     }
67 };
68 
69 struct FontHasher {
operator ()FontHasher70     std::size_t operator()(const AFont& font) const {
71         std::size_t r = std::hash<std::string>{}(font.mFilePath);
72         if (font.mLocale) {
73             r = combine(r, std::hash<std::string>{}(*font.mLocale));
74         }
75         r = combine(r, std::hash<uint16_t>{}(font.mWeight));
76         r = combine(r, std::hash<uint32_t>{}(font.mCollectionIndex));
77         for (const auto& [tag, value] : font.mAxes) {
78             r = combine(r, std::hash<uint32_t>{}(tag));
79             r = combine(r, std::hash<float>{}(value));
80         }
81         return r;
82     }
83 
combineFontHasher84     std::size_t combine(std::size_t l, std::size_t r) const { return l ^ (r << 1); }
85 };
86 
87 struct ASystemFontIterator {
88     std::vector<AFont> fonts;
89     uint32_t index;
90 
91     XmlDocUniquePtr mXmlDoc;
92 
93     ParserState state;
94 
95     // The OEM customization XML.
96     XmlDocUniquePtr mCustomizationXmlDoc;
97 };
98 
99 struct AFontMatcher {
100     minikin::FontStyle mFontStyle;
101     uint32_t mLocaleListId = 0;  // 0 is reserved for empty locale ID.
102     bool mFamilyVariant = AFAMILY_VARIANT_DEFAULT;
103 };
104 
105 static_assert(static_cast<uint32_t>(AFAMILY_VARIANT_DEFAULT) ==
106               static_cast<uint32_t>(minikin::FamilyVariant::DEFAULT));
107 static_assert(static_cast<uint32_t>(AFAMILY_VARIANT_COMPACT) ==
108               static_cast<uint32_t>(minikin::FamilyVariant::COMPACT));
109 static_assert(static_cast<uint32_t>(AFAMILY_VARIANT_ELEGANT) ==
110               static_cast<uint32_t>(minikin::FamilyVariant::ELEGANT));
111 
112 namespace {
113 
xmlTrim(const std::string & in)114 std::string xmlTrim(const std::string& in) {
115     if (in.empty()) {
116         return in;
117     }
118     const char XML_SPACES[] = "\u0020\u000D\u000A\u0009";
119     const size_t start = in.find_first_not_of(XML_SPACES);  // inclusive
120     if (start == std::string::npos) {
121         return "";
122     }
123     const size_t end = in.find_last_not_of(XML_SPACES);     // inclusive
124     if (end == std::string::npos) {
125         return "";
126     }
127     return in.substr(start, end - start + 1 /* +1 since end is inclusive */);
128 }
129 
130 const xmlChar* FAMILY_TAG = BAD_CAST("family");
131 const xmlChar* FONT_TAG = BAD_CAST("font");
132 const xmlChar* LOCALE_ATTR_NAME = BAD_CAST("lang");
133 
firstElement(xmlNode * node,const xmlChar * tag)134 xmlNode* firstElement(xmlNode* node, const xmlChar* tag) {
135     for (xmlNode* child = node->children; child; child = child->next) {
136         if (xmlStrEqual(child->name, tag)) {
137             return child;
138         }
139     }
140     return nullptr;
141 }
142 
nextSibling(xmlNode * node,const xmlChar * tag)143 xmlNode* nextSibling(xmlNode* node, const xmlChar* tag) {
144     while ((node = node->next) != nullptr) {
145         if (xmlStrEqual(node->name, tag)) {
146             return node;
147         }
148     }
149     return nullptr;
150 }
151 
copyFont(const XmlDocUniquePtr & xmlDoc,const ParserState & state,AFont * out,const std::string & pathPrefix)152 void copyFont(const XmlDocUniquePtr& xmlDoc, const ParserState& state, AFont* out,
153               const std::string& pathPrefix) {
154     xmlNode* fontNode = state.mFontNode;
155     XmlCharUniquePtr filePathStr(
156             xmlNodeListGetString(xmlDoc.get(), fontNode->xmlChildrenNode, 1));
157     out->mFilePath = pathPrefix + xmlTrim(
158             std::string(filePathStr.get(), filePathStr.get() + xmlStrlen(filePathStr.get())));
159 
160     const xmlChar* WEIGHT_ATTR_NAME = BAD_CAST("weight");
161     XmlCharUniquePtr weightStr(xmlGetProp(fontNode, WEIGHT_ATTR_NAME));
162     out->mWeight = weightStr ?
163             strtol(reinterpret_cast<const char*>(weightStr.get()), nullptr, 10) : 400;
164 
165     const xmlChar* STYLE_ATTR_NAME = BAD_CAST("style");
166     const xmlChar* ITALIC_ATTR_VALUE = BAD_CAST("italic");
167     XmlCharUniquePtr styleStr(xmlGetProp(fontNode, STYLE_ATTR_NAME));
168     out->mItalic = styleStr ? xmlStrEqual(styleStr.get(), ITALIC_ATTR_VALUE) : false;
169 
170     const xmlChar* INDEX_ATTR_NAME = BAD_CAST("index");
171     XmlCharUniquePtr indexStr(xmlGetProp(fontNode, INDEX_ATTR_NAME));
172     out->mCollectionIndex =  indexStr ?
173             strtol(reinterpret_cast<const char*>(indexStr.get()), nullptr, 10) : 0;
174 
175     if (state.mLocale) {
176         out->mLocale.emplace(reinterpret_cast<const char*>(state.mLocale.get()));
177     }
178 
179     const xmlChar* TAG_ATTR_NAME = BAD_CAST("tag");
180     const xmlChar* STYLEVALUE_ATTR_NAME = BAD_CAST("stylevalue");
181     const xmlChar* AXIS_TAG = BAD_CAST("axis");
182     out->mAxes.clear();
183     for (xmlNode* axis = firstElement(fontNode, AXIS_TAG); axis;
184             axis = nextSibling(axis, AXIS_TAG)) {
185         XmlCharUniquePtr tagStr(xmlGetProp(axis, TAG_ATTR_NAME));
186         if (!tagStr || xmlStrlen(tagStr.get()) != 4) {
187             continue;  // Tag value must be 4 char string
188         }
189 
190         XmlCharUniquePtr styleValueStr(xmlGetProp(axis, STYLEVALUE_ATTR_NAME));
191         if (!styleValueStr) {
192             continue;
193         }
194 
195         uint32_t tag =
196             static_cast<uint32_t>(tagStr.get()[0] << 24) |
197             static_cast<uint32_t>(tagStr.get()[1] << 16) |
198             static_cast<uint32_t>(tagStr.get()[2] << 8) |
199             static_cast<uint32_t>(tagStr.get()[3]);
200         float styleValue = strtod(reinterpret_cast<const char*>(styleValueStr.get()), nullptr);
201         out->mAxes.push_back(std::make_pair(tag, styleValue));
202     }
203 }
204 
isFontFileAvailable(const std::string & filePath)205 bool isFontFileAvailable(const std::string& filePath) {
206     std::string fullPath = filePath;
207     struct stat st = {};
208     if (stat(fullPath.c_str(), &st) != 0) {
209         return false;
210     }
211     return S_ISREG(st.st_mode);
212 }
213 
findFirstFontNode(const XmlDocUniquePtr & doc,ParserState * state)214 bool findFirstFontNode(const XmlDocUniquePtr& doc, ParserState* state) {
215     xmlNode* familySet = xmlDocGetRootElement(doc.get());
216     if (familySet == nullptr) {
217         return false;
218     }
219     xmlNode* family = firstElement(familySet, FAMILY_TAG);
220     if (family == nullptr) {
221         return false;
222     }
223     state->mLocale.reset(xmlGetProp(family, LOCALE_ATTR_NAME));
224 
225     xmlNode* font = firstElement(family, FONT_TAG);
226     while (font == nullptr) {
227         family = nextSibling(family, FAMILY_TAG);
228         if (family == nullptr) {
229             return false;
230         }
231         font = firstElement(family, FONT_TAG);
232     }
233     state->mFontNode = font;
234     return font != nullptr;
235 }
236 
237 }  // namespace
238 
ASystemFontIterator_open()239 ASystemFontIterator* ASystemFontIterator_open() {
240     std::unique_ptr<ASystemFontIterator> ite(new ASystemFontIterator());
241 
242     std::unordered_set<AFont, FontHasher> fonts;
243     minikin::SystemFonts::getFontSet(
244             [&fonts](const std::vector<std::shared_ptr<minikin::Font>>& fontSet) {
245                 for (const auto& font : fontSet) {
246                     std::optional<std::string> locale;
247                     uint32_t localeId = font->getLocaleListId();
248                     if (localeId != minikin::kEmptyLocaleListId) {
249                         locale.emplace(minikin::getLocaleString(localeId));
250                     }
251                     std::vector<std::pair<uint32_t, float>> axes;
252                     for (const auto& [tag, value] : font->baseTypeface()->GetAxes()) {
253                         axes.push_back(std::make_pair(tag, value));
254                     }
255 
256                     fonts.insert({font->baseTypeface()->GetFontPath(), std::move(locale),
257                                   font->style().weight(),
258                                   font->style().slant() == minikin::FontStyle::Slant::ITALIC,
259                                   static_cast<uint32_t>(font->baseTypeface()->GetFontIndex()),
260                                   axes});
261                 }
262             });
263 
264     if (fonts.empty()) {
265         ite->mXmlDoc.reset(xmlReadFile("/system/etc/fonts.xml", nullptr, 0));
266         ite->mCustomizationXmlDoc.reset(
267                 xmlReadFile("/product/etc/fonts_customization.xml", nullptr, 0));
268     } else {
269         ite->index = 0;
270         ite->fonts.assign(fonts.begin(), fonts.end());
271     }
272     return ite.release();
273 }
274 
ASystemFontIterator_close(ASystemFontIterator * ite)275 void ASystemFontIterator_close(ASystemFontIterator* ite) {
276     delete ite;
277 }
278 
AFontMatcher_create()279 AFontMatcher* _Nonnull AFontMatcher_create() {
280     return new AFontMatcher();
281 }
282 
AFontMatcher_destroy(AFontMatcher * matcher)283 void AFontMatcher_destroy(AFontMatcher* matcher) {
284     delete matcher;
285 }
286 
AFontMatcher_setStyle(AFontMatcher * _Nonnull matcher,uint16_t weight,bool italic)287 void AFontMatcher_setStyle(
288         AFontMatcher* _Nonnull matcher,
289         uint16_t weight,
290         bool italic) {
291     matcher->mFontStyle = minikin::FontStyle(
292             weight, static_cast<minikin::FontStyle::Slant>(italic));
293 }
294 
AFontMatcher_setLocales(AFontMatcher * _Nonnull matcher,const char * _Nonnull languageTags)295 void AFontMatcher_setLocales(
296         AFontMatcher* _Nonnull matcher,
297         const char* _Nonnull languageTags) {
298     matcher->mLocaleListId = minikin::registerLocaleList(languageTags);
299 }
300 
AFontMatcher_setFamilyVariant(AFontMatcher * _Nonnull matcher,uint32_t familyVariant)301 void AFontMatcher_setFamilyVariant(AFontMatcher* _Nonnull matcher, uint32_t familyVariant) {
302     matcher->mFamilyVariant = familyVariant;
303 }
304 
AFontMatcher_match(const AFontMatcher * _Nonnull matcher,const char * _Nonnull familyName,const uint16_t * _Nonnull text,const uint32_t textLength,uint32_t * _Nullable runLength)305 AFont* _Nonnull AFontMatcher_match(
306         const AFontMatcher* _Nonnull matcher,
307         const char* _Nonnull familyName,
308         const uint16_t* _Nonnull text,
309         const uint32_t textLength,
310         uint32_t* _Nullable runLength) {
311     std::shared_ptr<minikin::FontCollection> fc =
312             minikin::SystemFonts::findFontCollection(familyName);
313     std::vector<minikin::FontCollection::Run> runs = fc->itemize(
314                 minikin::U16StringPiece(text, textLength),
315                 matcher->mFontStyle,
316                 matcher->mLocaleListId,
317                 static_cast<minikin::FamilyVariant>(matcher->mFamilyVariant),
318                 1  /* maxRun */);
319 
320     const std::shared_ptr<minikin::Font>& font =
321             fc->getBestFont(minikin::U16StringPiece(text, textLength), runs[0], matcher->mFontStyle)
322                     .font;
323     std::unique_ptr<AFont> result = std::make_unique<AFont>();
324     const android::MinikinFontSkia* minikinFontSkia =
325             reinterpret_cast<android::MinikinFontSkia*>(font->baseTypeface().get());
326     result->mFilePath = minikinFontSkia->getFilePath();
327     result->mWeight = font->style().weight();
328     result->mItalic = font->style().slant() == minikin::FontStyle::Slant::ITALIC;
329     result->mCollectionIndex = minikinFontSkia->GetFontIndex();
330     const minikin::VariationSettings& axes = minikinFontSkia->GetAxes();
331     result->mAxes.reserve(axes.size());
332     for (auto axis : axes) {
333         result->mAxes.push_back(std::make_pair(axis.axisTag, axis.value));
334     }
335     if (runLength != nullptr) {
336         *runLength = runs[0].end;
337     }
338     return result.release();
339 }
340 
findNextFontNode(const XmlDocUniquePtr & xmlDoc,ParserState * state)341 bool findNextFontNode(const XmlDocUniquePtr& xmlDoc, ParserState* state) {
342     if (state->mFontNode == nullptr) {
343         if (!xmlDoc) {
344             return false;  // Already at the end.
345         } else {
346             // First time to query font.
347             return findFirstFontNode(xmlDoc, state);
348         }
349     } else {
350         xmlNode* nextNode = nextSibling(state->mFontNode, FONT_TAG);
351         while (nextNode == nullptr) {
352             xmlNode* family = nextSibling(state->mFontNode->parent, FAMILY_TAG);
353             if (family == nullptr) {
354                 break;
355             }
356             state->mLocale.reset(xmlGetProp(family, LOCALE_ATTR_NAME));
357             nextNode = firstElement(family, FONT_TAG);
358         }
359         state->mFontNode = nextNode;
360         return nextNode != nullptr;
361     }
362 }
363 
ASystemFontIterator_next(ASystemFontIterator * ite)364 AFont* ASystemFontIterator_next(ASystemFontIterator* ite) {
365     LOG_ALWAYS_FATAL_IF(ite == nullptr, "nullptr has passed as iterator argument");
366     if (!ite->fonts.empty()) {
367         if (ite->index >= ite->fonts.size()) {
368             return nullptr;
369         }
370         return new AFont(ite->fonts[ite->index++]);
371     }
372 
373     if (ite->mXmlDoc) {
374         if (!findNextFontNode(ite->mXmlDoc, &ite->state)) {
375             // Reached end of the XML file. Continue OEM customization.
376             ite->mXmlDoc.reset();
377         } else {
378             std::unique_ptr<AFont> font = std::make_unique<AFont>();
379             copyFont(ite->mXmlDoc, ite->state, font.get(), "/system/fonts/");
380             if (!isFontFileAvailable(font->mFilePath)) {
381                 return ASystemFontIterator_next(ite);
382             }
383             return font.release();
384         }
385     }
386     if (ite->mCustomizationXmlDoc) {
387         // TODO: Filter only customizationType="new-named-family"
388         if (!findNextFontNode(ite->mCustomizationXmlDoc, &ite->state)) {
389             // Reached end of the XML file. Finishing
390             ite->mCustomizationXmlDoc.reset();
391             return nullptr;
392         } else {
393             std::unique_ptr<AFont> font = std::make_unique<AFont>();
394             copyFont(ite->mCustomizationXmlDoc, ite->state, font.get(), "/product/fonts/");
395             if (!isFontFileAvailable(font->mFilePath)) {
396                 return ASystemFontIterator_next(ite);
397             }
398             return font.release();
399         }
400     }
401     return nullptr;
402 }
403 
AFont_close(AFont * font)404 void AFont_close(AFont* font) {
405     delete font;
406 }
407 
AFont_getFontFilePath(const AFont * font)408 const char* AFont_getFontFilePath(const AFont* font) {
409     LOG_ALWAYS_FATAL_IF(font == nullptr, "nullptr has passed as font argument");
410     return font->mFilePath.c_str();
411 }
412 
AFont_getWeight(const AFont * font)413 uint16_t AFont_getWeight(const AFont* font) {
414     LOG_ALWAYS_FATAL_IF(font == nullptr, "nullptr has passed as font argument");
415     return font->mWeight;
416 }
417 
AFont_isItalic(const AFont * font)418 bool AFont_isItalic(const AFont* font) {
419     LOG_ALWAYS_FATAL_IF(font == nullptr, "nullptr has passed as font argument");
420     return font->mItalic;
421 }
422 
AFont_getLocale(const AFont * font)423 const char* AFont_getLocale(const AFont* font) {
424     LOG_ALWAYS_FATAL_IF(font == nullptr, "nullptr has passed to font argument");
425     return font->mLocale ? font->mLocale->c_str() : nullptr;
426 }
427 
AFont_getCollectionIndex(const AFont * font)428 size_t AFont_getCollectionIndex(const AFont* font) {
429     LOG_ALWAYS_FATAL_IF(font == nullptr, "nullptr has passed to font argument");
430     return font->mCollectionIndex;
431 }
432 
AFont_getAxisCount(const AFont * font)433 size_t AFont_getAxisCount(const AFont* font) {
434     LOG_ALWAYS_FATAL_IF(font == nullptr, "nullptr has passed to font argument");
435     return font->mAxes.size();
436 }
437 
AFont_getAxisTag(const AFont * font,uint32_t axisIndex)438 uint32_t AFont_getAxisTag(const AFont* font, uint32_t axisIndex) {
439     LOG_ALWAYS_FATAL_IF(font == nullptr, "nullptr has passed to font argument");
440     LOG_ALWAYS_FATAL_IF(axisIndex >= font->mAxes.size(),
441                         "given axis index is out of bounds. (< %zd", font->mAxes.size());
442     return font->mAxes[axisIndex].first;
443 }
444 
AFont_getAxisValue(const AFont * font,uint32_t axisIndex)445 float AFont_getAxisValue(const AFont* font, uint32_t axisIndex) {
446     LOG_ALWAYS_FATAL_IF(font == nullptr, "nullptr has passed to font argument");
447     LOG_ALWAYS_FATAL_IF(axisIndex >= font->mAxes.size(),
448                         "given axis index is out of bounds. (< %zd", font->mAxes.size());
449     return font->mAxes[axisIndex].second;
450 }
451