aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/ports/SkFontConfigParser_android.cpp
blob: 3f0ebbfc6b8f3f2e1547db559d26b778d15d4524 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
/*
 * Copyright 2011 The Android Open Source Project
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "SkFontConfigParser_android.h"
#include "SkFontMgr_android.h"
#include "SkStream.h"
#include "SkTDArray.h"
#include "SkTSearch.h"
#include "SkTypeface.h"

#include <expat.h>
#include <dirent.h>
#include <stdio.h>

#include <limits>
#include <stdlib.h>

// From Android version LMP onwards, all font files collapse into
// /system/etc/fonts.xml. Instead of trying to detect which version
// we're on, try to open fonts.xml; if that fails, fall back to the
// older filename.
#define LMP_SYSTEM_FONTS_FILE "/system/etc/fonts.xml"
#define OLD_SYSTEM_FONTS_FILE "/system/etc/system_fonts.xml"
#define FALLBACK_FONTS_FILE "/system/etc/fallback_fonts.xml"
#define VENDOR_FONTS_FILE "/vendor/etc/fallback_fonts.xml"

#define LOCALE_FALLBACK_FONTS_SYSTEM_DIR "/system/etc"
#define LOCALE_FALLBACK_FONTS_VENDOR_DIR "/vendor/etc"
#define LOCALE_FALLBACK_FONTS_PREFIX "fallback_fonts-"
#define LOCALE_FALLBACK_FONTS_SUFFIX ".xml"

#ifndef SK_FONT_FILE_PREFIX
#    define SK_FONT_FILE_PREFIX "/fonts/"
#endif

/**
 * This file contains TWO parsers: one for JB and earlier (system_fonts.xml /
 * fallback_fonts.xml), one for LMP and later (fonts.xml).
 * We start with the JB parser, and if we detect a <familyset> tag with
 * version 21 or higher we switch to the LMP parser.
 */

/** Used to track which tag is currently populating with data.
 *  Only nameset and fileset are of interest for now.
 */
enum CurrentTag {
    kNo_CurrentTag,
    kNameSet_CurrentTag,
    kFileSet_CurrentTag
};

/**
 * The FamilyData structure is passed around by the parser so that each handler
 * can read these variables that are relevant to the current parsing.
 */
struct FamilyData {
    FamilyData(XML_Parser parser, SkTDArray<FontFamily*>& families,
               const SkString& basePath, bool isFallback, const char* filename)
        : fParser(parser)
        , fFamilies(families)
        , fCurrentFamily(NULL)
        , fCurrentFontInfo(NULL)
        , fCurrentTag(kNo_CurrentTag)
        , fVersion(0)
        , fBasePath(basePath)
        , fIsFallback(isFallback)
        , fFilename(filename)
    { };

    XML_Parser fParser;                       // The expat parser doing the work, owned by caller
    SkTDArray<FontFamily*>& fFamilies;        // The array to append families, owned by caller
    SkAutoTDelete<FontFamily> fCurrentFamily; // The family being created, owned by this
    FontFileInfo* fCurrentFontInfo;           // The fontInfo being created, owned by fCurrentFamily
    CurrentTag fCurrentTag;                   // The kind of tag currently being parsed.
    int fVersion;                             // The version of the file parsed.
    const SkString& fBasePath;                // The current base path.
    const bool fIsFallback;                   // Indicates the file being parsed is a fallback file
    const char* fFilename;                    // The name of the file currently being parsed.
};

/** Parses a null terminated string into an integer type, checking for overflow.
 *  http://www.w3.org/TR/html-markup/datatypes.html#common.data.integer.non-negative-def
 *
 *  If the string cannot be parsed into 'value', returns false and does not change 'value'.
 */
template <typename T> static bool parse_non_negative_integer(const char* s, T* value) {
    SK_COMPILE_ASSERT(std::numeric_limits<T>::is_integer, T_must_be_integer);
    const T nMax = std::numeric_limits<T>::max() / 10;
    const T dMax = std::numeric_limits<T>::max() - (nMax * 10);
    T n = 0;
    for (; *s; ++s) {
        // Check if digit
        if (*s < '0' || '9' < *s) {
            return false;
        }
        int d = *s - '0';
        // Check for overflow
        if (n > nMax || (n == nMax && d > dMax)) {
            return false;
        }
        n = (n * 10) + d;
    }
    *value = n;
    return true;
}

static bool memeq(const char* s1, const char* s2, size_t n1, size_t n2) {
    return n1 == n2 && 0 == memcmp(s1, s2, n1);
}
#define MEMEQ(c, s, n) memeq(c, s, sizeof(c) - 1, n)

#define ATTS_NON_NULL(a, i) (a[i] != NULL && a[i+1] != NULL)

#define SK_FONTCONFIGPARSER_PREFIX "[SkFontConfigParser] "

#define SK_FONTCONFIGPARSER_WARNING(message, ...) SkDebugf( \
    SK_FONTCONFIGPARSER_PREFIX "%s:%d:%d: warning: " message "\n", \
    self->fFilename, \
    XML_GetCurrentLineNumber(self->fParser), \
    XML_GetCurrentColumnNumber(self->fParser), \
    ##__VA_ARGS__);

namespace lmpParser {

static void family_element_handler(FamilyData* self, const char** attributes) {
    // A <family> element without a 'name' (string) attribute is a fallback font.
    // The element may have 'lang' (string) and 'variant' ("elegant", "compact") attributes.
    // The element should contain <font> elements.
    FontFamily* family = new FontFamily(self->fBasePath, true);
    self->fCurrentFamily.reset(family);
    for (size_t i = 0; ATTS_NON_NULL(attributes, i); i += 2) {
        const char* name = attributes[i];
        const char* value = attributes[i+1];
        size_t nameLen = strlen(name);
        size_t valueLen = strlen(value);
        if (MEMEQ("name", name, nameLen)) {
            SkAutoAsciiToLC tolc(value);
            family->fNames.push_back().set(tolc.lc());
            family->fIsFallbackFont = false;
        } else if (MEMEQ("lang", name, nameLen)) {
            family->fLanguage = SkLanguage(value, valueLen);
        } else if (MEMEQ("variant", name, nameLen)) {
            if (MEMEQ("elegant", value, valueLen)) {
                family->fVariant = kElegant_FontVariant;
            } else if (MEMEQ("compact", value, valueLen)) {
                family->fVariant = kCompact_FontVariant;
            }
        }
    }
}

static void XMLCALL font_file_name_handler(void* data, const char* s, int len) {
    FamilyData* self = static_cast<FamilyData*>(data);
    self->fCurrentFontInfo->fFileName.append(s, len);
}

static void font_element_handler(FamilyData* self, const char** attributes) {
    // A <font> element should be contained in a <family> element.
    // The element may have 'weight' (non-negative integer), 'style' ("normal", "italic"),
    // and 'index' (non-negative integer) attributes.
    // The element should contain a filename.
    FontFileInfo& file = self->fCurrentFamily->fFonts.push_back();
    self->fCurrentFontInfo = &file;
    for (size_t i = 0; ATTS_NON_NULL(attributes, i); i += 2) {
        const char* name = attributes[i];
        const char* value = attributes[i+1];
        size_t nameLen = strlen(name);
        if (MEMEQ("weight", name, nameLen)) {
            if (!parse_non_negative_integer(value, &file.fWeight)) {
                SK_FONTCONFIGPARSER_WARNING("'%s' is an invalid weight", value);
            }
        } else if (MEMEQ("style", name, nameLen)) {
            size_t valueLen = strlen(value);
            if (MEMEQ("normal", value, valueLen)) {
                file.fStyle = FontFileInfo::Style::kNormal;
            } else if (MEMEQ("italic", value, valueLen)) {
                file.fStyle = FontFileInfo::Style::kItalic;
            }
        } else if (MEMEQ("index", name, nameLen)) {
            if (!parse_non_negative_integer(value, &file.fIndex)) {
                SK_FONTCONFIGPARSER_WARNING("'%s' is an invalid index", value);
            }
        }
    }
    XML_SetCharacterDataHandler(self->fParser, font_file_name_handler);
}

static FontFamily* find_family(FamilyData* self, const SkString& familyName) {
    for (int i = 0; i < self->fFamilies.count(); i++) {
        FontFamily* candidate = self->fFamilies[i];
        for (int j = 0; j < candidate->fNames.count(); j++) {
            if (candidate->fNames[j] == familyName) {
                return candidate;
            }
        }
    }
    return NULL;
}

static void alias_element_handler(FamilyData* self, const char** attributes) {
    // A <alias> element must have 'name' (string) and 'to' (string) attributes.
    // The element may also have a 'weight' (non-negative integer) attribute.
    // The 'name' introduces a new family name.
    // The 'to' specifies which (previous) <family> to alias.
    // If it *does not* have a weight, 'name' is an alias for the entire 'to' <family>.
    // If it *does* have a weight, 'name' is a new family consisting of the <font>(s) with 'weight'
    // from the 'to' <family>.

    SkString aliasName;
    SkString to;
    int weight = 0;
    for (size_t i = 0; ATTS_NON_NULL(attributes, i); i += 2) {
        const char* name = attributes[i];
        const char* value = attributes[i+1];
        size_t nameLen = strlen(name);
        if (MEMEQ("name", name, nameLen)) {
            SkAutoAsciiToLC tolc(value);
            aliasName.set(tolc.lc());
        } else if (MEMEQ("to", name, nameLen)) {
            to.set(value);
        } else if (MEMEQ("weight", name, nameLen)) {
            if (!parse_non_negative_integer(value, &weight)) {
                SK_FONTCONFIGPARSER_WARNING("'%s' is an invalid weight", value);
            }
        }
    }

    // Assumes that the named family is already declared
    FontFamily* targetFamily = find_family(self, to);
    if (!targetFamily) {
        SK_FONTCONFIGPARSER_WARNING("'%s' alias target not found", to.c_str());
        return;
    }

    if (weight) {
        FontFamily* family = new FontFamily(targetFamily->fBasePath, self->fIsFallback);
        family->fNames.push_back().set(aliasName);

        for (int i = 0; i < targetFamily->fFonts.count(); i++) {
            if (targetFamily->fFonts[i].fWeight == weight) {
                family->fFonts.push_back(targetFamily->fFonts[i]);
            }
        }
        *self->fFamilies.append() = family;
    } else {
        targetFamily->fNames.push_back().set(aliasName);
    }
}

static void XMLCALL start_element_handler(void* data, const char* tag, const char** attributes) {
    FamilyData* self = static_cast<FamilyData*>(data);
    size_t len = strlen(tag);
    if (MEMEQ("family", tag, len)) {
        family_element_handler(self, attributes);
    } else if (MEMEQ("font", tag, len)) {
        font_element_handler(self, attributes);
    } else if (MEMEQ("alias", tag, len)) {
        alias_element_handler(self, attributes);
    }
}

static bool is_whitespace(char c) {
    return c == ' ' || c == '\n'|| c == '\r' || c == '\t';
}

static void trim_string(SkString* s) {
    char* str = s->writable_str();
    const char* start = str;  // start is inclusive
    const char* end = start + s->size();  // end is exclusive
    while (is_whitespace(*start)) { ++start; }
    if (start != end) {
        --end;  // make end inclusive
        while (is_whitespace(*end)) { --end; }
        ++end;  // make end exclusive
    }
    size_t len = end - start;
    memmove(str, start, len);
    s->resize(len);
}

static void XMLCALL end_element_handler(void* data, const char* tag) {
    FamilyData* self = static_cast<FamilyData*>(data);
    size_t len = strlen(tag);
    if (MEMEQ("family", tag, len)) {
        *self->fFamilies.append() = self->fCurrentFamily.detach();
    } else if (MEMEQ("font", tag, len)) {
        XML_SetCharacterDataHandler(self->fParser, NULL);
        trim_string(&self->fCurrentFontInfo->fFileName);
    }
}

} // lmpParser

namespace jbParser {

/**
 * Handler for arbitrary text. This is used to parse the text inside each name
 * or file tag. The resulting strings are put into the fNames or FontFileInfo arrays.
 */
static void XMLCALL text_handler(void* data, const char* s, int len) {
    FamilyData* self = static_cast<FamilyData*>(data);
    // Make sure we're in the right state to store this name information
    if (self->fCurrentFamily.get()) {
        switch (self->fCurrentTag) {
        case kNameSet_CurrentTag: {
            SkAutoAsciiToLC tolc(s, len);
            self->fCurrentFamily->fNames.back().append(tolc.lc(), len);
            break;
        }
        case kFileSet_CurrentTag:
            if (self->fCurrentFontInfo) {
                self->fCurrentFontInfo->fFileName.append(s, len);
            }
            break;
        default:
            // Noop - don't care about any text that's not in the Fonts or Names list
            break;
        }
    }
}

/**
 * Handler for font files. This processes the attributes for language and
 * variants then lets textHandler handle the actual file name
 */
static void font_file_element_handler(FamilyData* self, const char** attributes) {
    FontFamily& currentFamily = *self->fCurrentFamily.get();
    FontFileInfo& newFileInfo = currentFamily.fFonts.push_back();
    if (attributes) {
        for (size_t i = 0; ATTS_NON_NULL(attributes, i); i += 2) {
            const char* name = attributes[i];
            const char* value = attributes[i+1];
            size_t nameLen = strlen(name);
            size_t valueLen = strlen(value);
            if (MEMEQ("variant", name, nameLen)) {
                const FontVariant prevVariant = currentFamily.fVariant;
                if (MEMEQ("elegant", value, valueLen)) {
                    currentFamily.fVariant = kElegant_FontVariant;
                } else if (MEMEQ("compact", value, valueLen)) {
                    currentFamily.fVariant = kCompact_FontVariant;
                }
                if (currentFamily.fFonts.count() > 1 && currentFamily.fVariant != prevVariant) {
                    SK_FONTCONFIGPARSER_WARNING("'%s' unexpected variant found\n"
                        "Note: Every font file within a family must have identical variants.",
                        value);
                }

            } else if (MEMEQ("lang", name, nameLen)) {
                SkLanguage prevLang = currentFamily.fLanguage;
                currentFamily.fLanguage = SkLanguage(value, valueLen);
                if (currentFamily.fFonts.count() > 1 && currentFamily.fLanguage != prevLang) {
                    SK_FONTCONFIGPARSER_WARNING("'%s' unexpected language found\n"
                        "Note: Every font file within a family must have identical languages.",
                        value);
                }

            } else if (MEMEQ("index", name, nameLen)) {
                if (!parse_non_negative_integer(value, &newFileInfo.fIndex)) {
                    SK_FONTCONFIGPARSER_WARNING("'%s' is an invalid index", value);
                }
            }
        }
    }
    self->fCurrentFontInfo = &newFileInfo;
    XML_SetCharacterDataHandler(self->fParser, text_handler);
}

/**
 * Handler for the start of a tag. The only tags we expect are familyset, family,
 * nameset, fileset, name, and file.
 */
static void XMLCALL start_element_handler(void* data, const char* tag, const char** attributes) {
    FamilyData* self = static_cast<FamilyData*>(data);
    size_t len = strlen(tag);
    if (MEMEQ("familyset", tag, len)) {
        // The <familyset> element has an optional 'version' (non-negative integer) attribute.
        for (size_t i = 0; ATTS_NON_NULL(attributes, i); i += 2) {
            size_t nameLen = strlen(attributes[i]);
            if (!MEMEQ("version", attributes[i], nameLen)) continue;
            const char* valueString = attributes[i+1];
            int version;
            if (parse_non_negative_integer(valueString, &version) && (version >= 21)) {
                XML_SetElementHandler(self->fParser,
                                      lmpParser::start_element_handler,
                                      lmpParser::end_element_handler);
                self->fVersion = version;
            }
        }
    } else if (MEMEQ("family", tag, len)) {
        self->fCurrentFamily.reset(new FontFamily(self->fBasePath, self->fIsFallback));
        // The <family> element has an optional 'order' (non-negative integer) attribute.
        // If this attribute does not exist, the default value is -1.
        for (size_t i = 0; ATTS_NON_NULL(attributes, i); i += 2) {
            const char* valueString = attributes[i+1];
            int value;
            if (parse_non_negative_integer(valueString, &value)) {
                self->fCurrentFamily->fOrder = value;
            }
        }
    } else if (MEMEQ("nameset", tag, len)) {
        self->fCurrentTag = kNameSet_CurrentTag;
    } else if (MEMEQ("fileset", tag, len)) {
        self->fCurrentTag = kFileSet_CurrentTag;
    } else if (MEMEQ("name", tag, len) && self->fCurrentTag == kNameSet_CurrentTag) {
        // If it's a Name, parse the text inside
        self->fCurrentFamily->fNames.push_back();
        XML_SetCharacterDataHandler(self->fParser, text_handler);
    } else if (MEMEQ("file", tag, len) && self->fCurrentTag == kFileSet_CurrentTag) {
        // If it's a file, parse the attributes, then parse the text inside
        font_file_element_handler(self, attributes);
    }
}

/**
 * Handler for the end of tags. We only care about family, nameset, fileset,
 * name, and file.
 */
static void XMLCALL end_element_handler(void* data, const char* tag) {
    FamilyData* self = static_cast<FamilyData*>(data);
    size_t len = strlen(tag);
    if (MEMEQ("family", tag, len)) {
        // Done parsing a Family - store the created currentFamily in the families array
        *self->fFamilies.append() = self->fCurrentFamily.detach();
    } else if (MEMEQ("nameset", tag, len)) {
        self->fCurrentTag = kNo_CurrentTag;
    } else if (MEMEQ("fileset", tag, len)) {
        self->fCurrentTag = kNo_CurrentTag;
    } else if ((MEMEQ("name", tag, len) && self->fCurrentTag == kNameSet_CurrentTag) ||
               (MEMEQ("file", tag, len) && self->fCurrentTag == kFileSet_CurrentTag)) {
        // Disable the arbitrary text handler installed to load Name data
        XML_SetCharacterDataHandler(self->fParser, NULL);
    }
}

} // namespace jbParser

static void XMLCALL xml_entity_decl_handler(void *data,
                                            const XML_Char *entityName,
                                            int is_parameter_entity,
                                            const XML_Char *value,
                                            int value_length,
                                            const XML_Char *base,
                                            const XML_Char *systemId,
                                            const XML_Char *publicId,
                                            const XML_Char *notationName)
{
    FamilyData* self = static_cast<FamilyData*>(data);
    SK_FONTCONFIGPARSER_WARNING("'%s' entity declaration found, stopping processing", entityName);
    XML_StopParser(self->fParser, XML_FALSE);
}

static const XML_Memory_Handling_Suite sk_XML_alloc = {
    sk_malloc_throw,
    sk_realloc_throw,
    sk_free
};

template<typename T> struct remove_ptr {typedef T type;};
template<typename T> struct remove_ptr<T*> {typedef T type;};

/**
 * This function parses the given filename and stores the results in the given
 * families array. Returns the version of the file, negative if the file does not exist.
 */
static int parse_config_file(const char* filename, SkTDArray<FontFamily*>& families,
                             const SkString& basePath, bool isFallback)
{
    SkFILEStream file(filename);

    // Some of the files we attempt to parse (in particular, /vendor/etc/fallback_fonts.xml)
    // are optional - failure here is okay because one of these optional files may not exist.
    if (!file.isValid()) {
        SkDebugf(SK_FONTCONFIGPARSER_PREFIX "'%s' could not be opened\n", filename);
        return -1;
    }

    SkAutoTCallVProc<remove_ptr<XML_Parser>::type, XML_ParserFree> parser(
        XML_ParserCreate_MM(NULL, &sk_XML_alloc, NULL));
    if (!parser) {
        SkDebugf(SK_FONTCONFIGPARSER_PREFIX "could not create XML parser\n");
        return -1;
    }

    FamilyData self(parser, families, basePath, isFallback, filename);
    XML_SetUserData(parser, &self);

    // Disable entity processing, to inhibit internal entity expansion. See expat CVE-2013-0340
    XML_SetEntityDeclHandler(parser, xml_entity_decl_handler);

    // Start parsing oldschool; switch these in flight if we detect a newer version of the file.
    XML_SetElementHandler(parser, jbParser::start_element_handler, jbParser::end_element_handler);

    // One would assume it would be faster to have a buffer on the stack and call XML_Parse.
    // But XML_Parse will call XML_GetBuffer anyway and memmove the passed buffer into it.
    // (Unless XML_CONTEXT_BYTES is undefined, but all users define it.)
    // In debug, buffer a small odd number of bytes to detect slicing in XML_CharacterDataHandler.
    static const int bufferSize = 512 SkDEBUGCODE( - 507);
    bool done = false;
    while (!done) {
        void* buffer = XML_GetBuffer(parser, bufferSize);
        if (!buffer) {
            SkDebugf(SK_FONTCONFIGPARSER_PREFIX "could not buffer enough to continue\n");
            return -1;
        }
        size_t len = file.read(buffer, bufferSize);
        done = file.isAtEnd();
        XML_Status status = XML_ParseBuffer(parser, len, done);
        if (XML_STATUS_ERROR == status) {
            XML_Error error = XML_GetErrorCode(parser);
            int line = XML_GetCurrentLineNumber(parser);
            int column = XML_GetCurrentColumnNumber(parser);
            const XML_LChar* errorString = XML_ErrorString(error);
            SkDebugf(SK_FONTCONFIGPARSER_PREFIX "%s:%d:%d error %d: %s.\n",
                     filename, line, column, error, errorString);
            return -1;
        }
    }
    return self.fVersion;
}

/** Returns the version of the system font file actually found, negative if none. */
static int append_system_font_families(SkTDArray<FontFamily*>& fontFamilies,
                                       const SkString& basePath)
{
    int initialCount = fontFamilies.count();
    int version = parse_config_file(LMP_SYSTEM_FONTS_FILE, fontFamilies, basePath, false);
    if (version < 0 || fontFamilies.count() == initialCount) {
        version = parse_config_file(OLD_SYSTEM_FONTS_FILE, fontFamilies, basePath, false);
    }
    return version;
}

/**
 * In some versions of Android prior to Android 4.2 (JellyBean MR1 at API
 * Level 17) the fallback fonts for certain locales were encoded in their own
 * XML files with a suffix that identified the locale.  We search the provided
 * directory for those files,add all of their entries to the fallback chain, and
 * include the locale as part of each entry.
 */
static void append_fallback_font_families_for_locale(SkTDArray<FontFamily*>& fallbackFonts,
                                                     const char* dir,
                                                     const SkString& basePath)
{
#if defined(SK_BUILD_FOR_ANDROID_FRAMEWORK)
    // The framework is beyond Android 4.2 and can therefore skip this function
    return;
#endif

    SkAutoTCallIProc<DIR, closedir> fontDirectory(opendir(dir));
    if (NULL == fontDirectory) {
        return;
    }

    for (struct dirent* dirEntry; (dirEntry = readdir(fontDirectory));) {
        // The size of the prefix and suffix.
        static const size_t fixedLen = sizeof(LOCALE_FALLBACK_FONTS_PREFIX) - 1
                                     + sizeof(LOCALE_FALLBACK_FONTS_SUFFIX) - 1;

        // The size of the prefix, suffix, and a minimum valid language code
        static const size_t minSize = fixedLen + 2;

        SkString fileName(dirEntry->d_name);
        if (fileName.size() < minSize ||
            !fileName.startsWith(LOCALE_FALLBACK_FONTS_PREFIX) ||
            !fileName.endsWith(LOCALE_FALLBACK_FONTS_SUFFIX))
        {
            continue;
        }

        SkString locale(fileName.c_str() + sizeof(LOCALE_FALLBACK_FONTS_PREFIX) - 1,
                        fileName.size() - fixedLen);

        SkString absoluteFilename;
        absoluteFilename.printf("%s/%s", dir, fileName.c_str());

        SkTDArray<FontFamily*> langSpecificFonts;
        parse_config_file(absoluteFilename.c_str(), langSpecificFonts, basePath, true);

        for (int i = 0; i < langSpecificFonts.count(); ++i) {
            FontFamily* family = langSpecificFonts[i];
            family->fLanguage = SkLanguage(locale);
            *fallbackFonts.append() = family;
        }
    }
}

static void append_system_fallback_font_families(SkTDArray<FontFamily*>& fallbackFonts,
                                                 const SkString& basePath)
{
    parse_config_file(FALLBACK_FONTS_FILE, fallbackFonts, basePath, true);
    append_fallback_font_families_for_locale(fallbackFonts,
                                             LOCALE_FALLBACK_FONTS_SYSTEM_DIR,
                                             basePath);
}

static void mixin_vendor_fallback_font_families(SkTDArray<FontFamily*>& fallbackFonts,
                                                const SkString& basePath)
{
    SkTDArray<FontFamily*> vendorFonts;
    parse_config_file(VENDOR_FONTS_FILE, vendorFonts, basePath, true);
    append_fallback_font_families_for_locale(vendorFonts,
                                             LOCALE_FALLBACK_FONTS_VENDOR_DIR,
                                             basePath);

    // This loop inserts the vendor fallback fonts in the correct order in the
    // overall fallbacks list.
    int currentOrder = -1;
    for (int i = 0; i < vendorFonts.count(); ++i) {
        FontFamily* family = vendorFonts[i];
        int order = family->fOrder;
        if (order < 0) {
            if (currentOrder < 0) {
                // Default case - just add it to the end of the fallback list
                *fallbackFonts.append() = family;
            } else {
                // no order specified on this font, but we're incrementing the order
                // based on an earlier order insertion request
                *fallbackFonts.insert(currentOrder++) = family;
            }
        } else {
            // Add the font into the fallback list in the specified order. Set
            // currentOrder for correct placement of other fonts in the vendor list.
            *fallbackFonts.insert(order) = family;
            currentOrder = order + 1;
        }
    }
}

void SkFontConfigParser::GetSystemFontFamilies(SkTDArray<FontFamily*>& fontFamilies) {
    // Version 21 of the system font configuration does not need any fallback configuration files.
    SkString basePath(getenv("ANDROID_ROOT"));
    basePath.append(SK_FONT_FILE_PREFIX, sizeof(SK_FONT_FILE_PREFIX) - 1);

    if (append_system_font_families(fontFamilies, basePath) >= 21) {
        return;
    }

    // Append all the fallback fonts to system fonts
    SkTDArray<FontFamily*> fallbackFonts;
    append_system_fallback_font_families(fallbackFonts, basePath);
    mixin_vendor_fallback_font_families(fallbackFonts, basePath);
    fontFamilies.append(fallbackFonts.count(), fallbackFonts.begin());
}

void SkFontConfigParser::GetCustomFontFamilies(SkTDArray<FontFamily*>& fontFamilies,
                                               const SkString& basePath,
                                               const char* fontsXml,
                                               const char* fallbackFontsXml,
                                               const char* langFallbackFontsDir)
{
    if (fontsXml) {
        parse_config_file(fontsXml, fontFamilies, basePath, false);
    }
    if (fallbackFontsXml) {
        parse_config_file(fallbackFontsXml, fontFamilies, basePath, true);
    }
    if (langFallbackFontsDir) {
        append_fallback_font_families_for_locale(fontFamilies,
                                                 langFallbackFontsDir,
                                                 basePath);
    }
}

SkLanguage SkLanguage::getParent() const {
    SkASSERT(!fTag.isEmpty());
    const char* tag = fTag.c_str();

    // strip off the rightmost "-.*"
    const char* parentTagEnd = strrchr(tag, '-');
    if (parentTagEnd == NULL) {
        return SkLanguage();
    }
    size_t parentTagLen = parentTagEnd - tag;
    return SkLanguage(tag, parentTagLen);
}