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