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