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