From: bungeman Date: Mon, 30 Mar 2015 19:53:48 +0000 (-0700) Subject: Add option to embed font data into executable. X-Git-Tag: accepted/tizen/5.0/unified/20181102.025319~2976 X-Git-Url: http://review.tizen.org/git/?a=commitdiff_plain;h=5c9fa2844c4f97b9358d547f947372f680c68dd1;p=platform%2Fupstream%2FlibSkiaSharp.git Add option to embed font data into executable. Some tools would like to be built with all resources embedded. This change makes it possible to build a font manager which uses font data embedded into the executable. Review URL: https://codereview.chromium.org/1015723004 --- diff --git a/gyp/common_variables.gypi b/gyp/common_variables.gypi index 1b9cf33..80ab7c9 100644 --- a/gyp/common_variables.gypi +++ b/gyp/common_variables.gypi @@ -122,6 +122,7 @@ # SkFontHost_fontconfig interface; use the SkFontHost_linux # version instead. 'skia_no_fontconfig%': '0', + 'skia_embedded_fonts%': '0', 'skia_sanitizer%': '', 'skia_scalar%': 'float', @@ -200,6 +201,7 @@ 'skia_freetype_static%': '<(skia_freetype_static)', 'skia_no_fontconfig%': '<(skia_no_fontconfig)', + 'skia_embedded_fonts%': '<(skia_embedded_fonts)', 'skia_sanitizer%': '<(skia_sanitizer)', 'skia_scalar%': '<(skia_scalar)', 'skia_mesa%': '<(skia_mesa)', diff --git a/gyp/ports.gyp b/gyp/ports.gyp index 3cdc734..0f442cd 100644 --- a/gyp/ports.gyp +++ b/gyp/ports.gyp @@ -70,7 +70,43 @@ }], [ 'skia_os in ["linux", "freebsd", "openbsd", "solaris", "chromeos"]', { 'conditions': [ - [ 'skia_no_fontconfig', { + [ 'skia_embedded_fonts', { + 'link_settings': { + 'libraries': [ + '-ldl', + ], + }, + 'variables': { + 'embedded_font_data_identifier': 'sk_fonts', + 'fonts_to_include': [ + '../resources/Funkster.ttf', + ], + }, + 'sources': [ + '../src/ports/SkFontHost_linux.cpp', + ], + 'actions': [{ + 'action_name': 'generate_embedded_font_data', + 'inputs': [ + '../tools/embed_resources.py', + '<@(fonts_to_include)', + ], + 'outputs': [ + '<(SHARED_INTERMEDIATE_DIR)/ports/fonts/fonts.cpp', + ], + 'action': ['python', '../tools/embed_resources.py', + '--align', '4', + '--name', '<(embedded_font_data_identifier)', + '--input', '<@(fonts_to_include)', + '--output', '<@(_outputs)', + ], + 'message': 'Generating <@(_outputs)', + 'process_outputs_as_sources': 1, + }], + 'defines': [ + 'SK_EMBEDDED_FONTS=<(embedded_font_data_identifier)', + ], + }, 'skia_no_fontconfig', { 'link_settings': { 'libraries': [ '-ldl', diff --git a/src/ports/SkFontHost_linux.cpp b/src/ports/SkFontHost_linux.cpp index d96365b..5d62e36 100644 --- a/src/ports/SkFontHost_linux.cpp +++ b/src/ports/SkFontHost_linux.cpp @@ -21,12 +21,6 @@ #include -#ifndef SK_FONT_FILE_PREFIX -# define SK_FONT_FILE_PREFIX "/usr/share/fonts/" -#endif - -/////////////////////////////////////////////////////////////////////////////// - /** The base SkTypeface implementation for the custom font manager. */ class SkTypeface_Custom : public SkTypeface_FreeType { public: @@ -154,6 +148,11 @@ class SkFontStyleSet_Custom : public SkFontStyleSet { public: explicit SkFontStyleSet_Custom(const SkString familyName) : fFamilyName(familyName) { } + /** Should only be called during the inital build phase. */ + void appendTypeface(SkTypeface_Custom* typeface) { + fStyles.push_back().reset(typeface); + } + int count() override { return fStyles.count(); } @@ -206,14 +205,12 @@ public: return SkRef(closest); } + SkString getFamilyName() { return fFamilyName; } + private: SkTArray, true> fStyles; SkString fFamilyName; - void appendTypeface(SkTypeface_Custom* typeface) { - fStyles.push_back().reset(typeface); - } - friend class SkFontMgr_Custom; }; @@ -226,8 +223,38 @@ private: */ class SkFontMgr_Custom : public SkFontMgr { public: - explicit SkFontMgr_Custom(const char* dir) { - this->load_system_fonts(dir); + typedef SkTArray, true> Families; + class SystemFontLoader { + public: + virtual ~SystemFontLoader() { } + virtual void loadSystemFonts(const SkTypeface_FreeType::Scanner&, Families*) const = 0; + }; + explicit SkFontMgr_Custom(const SystemFontLoader& loader) { + loader.loadSystemFonts(fScanner, &fFamilies); + + // Try to pick a default font. + static const char* defaultNames[] = { + "Arial", "Verdana", "Times New Roman", "Droid Sans", NULL + }; + for (size_t i = 0; i < SK_ARRAY_COUNT(defaultNames); ++i) { + SkFontStyleSet_Custom* set = this->onMatchFamily(defaultNames[i]); + if (NULL == set) { + continue; + } + + SkTypeface* tf = set->matchStyle(SkFontStyle(SkFontStyle::kNormal_Weight, + SkFontStyle::kNormal_Width, + SkFontStyle::kUpright_Slant)); + if (NULL == tf) { + continue; + } + + fDefaultFamily = set; + break; + } + if (NULL == fDefaultFamily) { + fDefaultFamily = fFamilies[0]; + } } protected: @@ -237,7 +264,7 @@ protected: void onGetFamilyName(int index, SkString* familyName) const override { SkASSERT(index < fFamilies.count()); - familyName->set(fFamilies[index]->fFamilyName); + familyName->set(fFamilies[index]->getFamilyName()); } SkFontStyleSet_Custom* onCreateStyleSet(int index) const override { @@ -247,29 +274,29 @@ protected: SkFontStyleSet_Custom* onMatchFamily(const char familyName[]) const override { for (int i = 0; i < fFamilies.count(); ++i) { - if (fFamilies[i]->fFamilyName.equals(familyName)) { + if (fFamilies[i]->getFamilyName().equals(familyName)) { return SkRef(fFamilies[i].get()); } } return NULL; } - virtual SkTypeface* onMatchFamilyStyle(const char familyName[], - const SkFontStyle& fontStyle) const override + SkTypeface* onMatchFamilyStyle(const char familyName[], + const SkFontStyle& fontStyle) const override { SkAutoTUnref sset(this->matchFamily(familyName)); return sset->matchStyle(fontStyle); } - virtual SkTypeface* onMatchFamilyStyleCharacter(const char familyName[], const SkFontStyle&, - const char* bcp47[], int bcp47Count, - SkUnichar character) const override + SkTypeface* onMatchFamilyStyleCharacter(const char familyName[], const SkFontStyle&, + const char* bcp47[], int bcp47Count, + SkUnichar character) const override { return NULL; } - virtual SkTypeface* onMatchFaceStyle(const SkTypeface* familyMember, - const SkFontStyle& fontStyle) const override + SkTypeface* onMatchFaceStyle(const SkTypeface* familyMember, + const SkFontStyle& fontStyle) const override { for (int i = 0; i < fFamilies.count(); ++i) { for (int j = 0; j < fFamilies[i]->fStyles.count(); ++j) { @@ -307,9 +334,7 @@ protected: return stream.get() ? this->createFromStream(stream.detach(), ttcIndex) : NULL; } - virtual SkTypeface* onLegacyCreateTypeface(const char familyName[], - unsigned styleBits) const override - { + SkTypeface* onLegacyCreateTypeface(const char familyName[], unsigned styleBits) const override { SkTypeface::Style oldStyle = (SkTypeface::Style)styleBits; SkFontStyle style = SkFontStyle(oldStyle & SkTypeface::kBold ? SkFontStyle::kBold_Weight @@ -325,15 +350,55 @@ protected: } if (NULL == tf) { - tf = gDefaultFamily->matchStyle(style); + tf = fDefaultFamily->matchStyle(style); } return SkSafeRef(tf); } private: + Families fFamilies; + SkFontStyleSet_Custom* fDefaultFamily; + SkTypeface_FreeType::Scanner fScanner; +}; + +/////////////////////////////////////////////////////////////////////////////// + +class DirectorySystemFontLoader : public SkFontMgr_Custom::SystemFontLoader { +public: + DirectorySystemFontLoader(const char* dir) : fBaseDirectory(dir) { } + + void loadSystemFonts(const SkTypeface_FreeType::Scanner& scanner, + SkFontMgr_Custom::Families* families) const override + { + load_directory_fonts(scanner, fBaseDirectory, ".ttf", families); + load_directory_fonts(scanner, fBaseDirectory, ".ttc", families); + load_directory_fonts(scanner, fBaseDirectory, ".otf", families); + load_directory_fonts(scanner, fBaseDirectory, ".pfb", families); + + if (families->empty()) { + SkFontStyleSet_Custom* family = new SkFontStyleSet_Custom(SkString()); + families->push_back().reset(family); + family->appendTypeface(SkNEW(SkTypeface_Empty)); + } + } + +private: + static SkFontStyleSet_Custom* find_family(SkFontMgr_Custom::Families& families, + const char familyName[]) + { + for (int i = 0; i < families.count(); ++i) { + if (families[i]->getFamilyName().equals(familyName)) { + return families[i].get(); + } + } + return NULL; + } - void load_directory_fonts(const SkString& directory, const char* suffix) { + static void load_directory_fonts(const SkTypeface_FreeType::Scanner& scanner, + const SkString& directory, const char* suffix, + SkFontMgr_Custom::Families* families) + { SkOSFile::Iter iter(directory.c_str(), suffix); SkString name; @@ -346,7 +411,7 @@ private: } int numFaces; - if (!fScanner.recognizedFont(stream, &numFaces)) { + if (!scanner.recognizedFont(stream, &numFaces)) { SkDebugf("---- failed to open <%s> as a font\n", filename.c_str()); continue; } @@ -355,7 +420,7 @@ private: bool isFixedPitch; SkString realname; SkFontStyle style = SkFontStyle(); // avoid uninitialized warning - if (!fScanner.scanFont(stream, faceIndex, &realname, &style, &isFixedPitch)) { + if (!scanner.scanFont(stream, faceIndex, &realname, &style, &isFixedPitch)) { SkDebugf("---- failed to open <%s> <%d> as a font\n", filename.c_str(), faceIndex); continue; @@ -366,12 +431,13 @@ private: isFixedPitch, true, // system-font (cannot delete) realname, - filename.c_str(), 0)); + filename.c_str(), + faceIndex)); - SkFontStyleSet_Custom* addTo = this->onMatchFamily(realname.c_str()); + SkFontStyleSet_Custom* addTo = find_family(*families, realname.c_str()); if (NULL == addTo) { addTo = new SkFontStyleSet_Custom(realname); - fFamilies.push_back().reset(addTo); + families->push_back().reset(addTo); } addTo->appendTypeface(tf); } @@ -383,56 +449,102 @@ private: continue; } SkString dirname(SkOSPath::Join(directory.c_str(), name.c_str())); - load_directory_fonts(dirname, suffix); + load_directory_fonts(scanner, dirname, suffix, families); } } - void load_system_fonts(const char* dir) { - SkString baseDirectory(dir); - load_directory_fonts(baseDirectory, ".ttf"); - load_directory_fonts(baseDirectory, ".ttc"); - load_directory_fonts(baseDirectory, ".otf"); - load_directory_fonts(baseDirectory, ".pfb"); + SkString fBaseDirectory; +}; + +struct SkEmbeddedResource { const uint8_t* data; size_t size; }; +struct SkEmbeddedResourceHeader { const SkEmbeddedResource* entries; int count; }; + +class EmbeddedSystemFontLoader : public SkFontMgr_Custom::SystemFontLoader { +public: + EmbeddedSystemFontLoader(const SkEmbeddedResourceHeader* header) : fHeader(header) { } + + void loadSystemFonts(const SkTypeface_FreeType::Scanner& scanner, + SkFontMgr_Custom::Families* families) const override + { + for (int i = 0; i < fHeader->count; ++i) { + const SkEmbeddedResource& fontEntry = fHeader->entries[i]; + load_embedded_font(scanner, fontEntry.data, fontEntry.size, i, families); + } - if (fFamilies.empty()) { + if (families->empty()) { SkFontStyleSet_Custom* family = new SkFontStyleSet_Custom(SkString()); - fFamilies.push_back().reset(family); + families->push_back().reset(family); family->appendTypeface(SkNEW(SkTypeface_Empty)); } + } - // Try to pick a default font. - static const char* gDefaultNames[] = { - "Arial", "Verdana", "Times New Roman", "Droid Sans", NULL - }; - for (size_t i = 0; i < SK_ARRAY_COUNT(gDefaultNames); ++i) { - SkFontStyleSet_Custom* set = this->onMatchFamily(gDefaultNames[i]); - if (NULL == set) { - continue; +private: + static SkFontStyleSet_Custom* find_family(SkFontMgr_Custom::Families& families, + const char familyName[]) + { + for (int i = 0; i < families.count(); ++i) { + if (families[i]->getFamilyName().equals(familyName)) { + return families[i].get(); } + } + return NULL; + } - SkTypeface* tf = set->matchStyle(SkFontStyle(SkFontStyle::kNormal_Weight, - SkFontStyle::kNormal_Width, - SkFontStyle::kUpright_Slant)); - if (NULL == tf) { - continue; - } + static void load_embedded_font(const SkTypeface_FreeType::Scanner& scanner, + const uint8_t* data, size_t size, int index, + SkFontMgr_Custom::Families* families) + { + SkAutoTDelete stream(new SkMemoryStream(data, size, false)); - gDefaultFamily = set; - gDefaultNormal = tf; - break; + int numFaces; + if (!scanner.recognizedFont(stream, &numFaces)) { + SkDebugf("---- failed to open <%d> as a font\n", index); + return; } - if (NULL == gDefaultNormal) { - gDefaultFamily = fFamilies[0]; - gDefaultNormal = gDefaultFamily->fStyles[0]; + + for (int faceIndex = 0; faceIndex < numFaces; ++faceIndex) { + bool isFixedPitch; + SkString realname; + SkFontStyle style = SkFontStyle(); // avoid uninitialized warning + if (!scanner.scanFont(stream, faceIndex, &realname, &style, &isFixedPitch)) { + SkDebugf("---- failed to open <%d> <%d> as a font\n", index, faceIndex); + return; + } + + SkTypeface_Custom* tf = SkNEW_ARGS(SkTypeface_Stream, ( + style, + isFixedPitch, + true, // system-font (cannot delete) + realname, + stream.detach(), + faceIndex)); + + SkFontStyleSet_Custom* addTo = find_family(*families, realname.c_str()); + if (NULL == addTo) { + addTo = new SkFontStyleSet_Custom(realname); + families->push_back().reset(addTo); + } + addTo->appendTypeface(tf); } } - SkTArray, true> fFamilies; - SkFontStyleSet_Custom* gDefaultFamily; - SkTypeface* gDefaultNormal; - SkTypeface_FreeType::Scanner fScanner; + const SkEmbeddedResourceHeader* fHeader; }; +#ifdef SK_EMBEDDED_FONTS + +extern "C" const SkEmbeddedResourceHeader SK_EMBEDDED_FONTS; +SkFontMgr* SkFontMgr::Factory() { + return new SkFontMgr_Custom(EmbeddedSystemFontLoader(&SK_EMBEDDED_FONTS)); +} + +#else + +#ifndef SK_FONT_FILE_PREFIX +# define SK_FONT_FILE_PREFIX "/usr/share/fonts/" +#endif SkFontMgr* SkFontMgr::Factory() { - return new SkFontMgr_Custom(SK_FONT_FILE_PREFIX); + return new SkFontMgr_Custom(DirectorySystemFontLoader(SK_FONT_FILE_PREFIX)); } + +#endif diff --git a/tools/embed_resources.py b/tools/embed_resources.py new file mode 100644 index 0000000..56d5982 --- /dev/null +++ b/tools/embed_resources.py @@ -0,0 +1,80 @@ +#!/usr/bin/python + +''' +Copyright 2015 Google Inc. + +Use of this source code is governed by a BSD-style license that can be +found in the LICENSE file. +''' + +import argparse + + +def bytes_from_file(f, chunksize=8192): + while True: + chunk = f.read(chunksize) + if chunk: + for b in chunk: + yield ord(b) + else: + break + + +def main(): + parser = argparse.ArgumentParser( + formatter_class=argparse.RawDescriptionHelpFormatter, + description='Convert resource files to embedded read only data.', + epilog='''The output (when compiled and linked) can be used as: +struct SkEmbeddedResource {const uint8_t* data; const size_t size;}; +struct SkEmbeddedHeader {const SkEmbeddedResource* entries; const int count;}; +extern "C" SkEmbeddedHeader const NAME;''') + parser.add_argument('--align', default=1, type=int, + help='minimum alignment (in bytes) of resource data') + parser.add_argument('--name', default='_resource', type=str, + help='the name of the c identifier to export') + parser.add_argument('--input', required=True, type=argparse.FileType('rb'), + nargs='+', help='list of resource files to embed') + parser.add_argument('--output', required=True, type=argparse.FileType('w'), + help='the name of the cpp file to output') + args = parser.parse_args() + + out = args.output.write; + out('#include "SkTypes.h"\n') + + # Write the resources. + index = 0 + for f in args.input: + out('static const uint8_t resource{0:d}[] SK_STRUCT_ALIGN({1:d}) = {{\n' + .format(index, args.align)) + bytes_written = 0 + bytes_on_line = 0 + for b in bytes_from_file(f): + out(hex(b) + ',') + bytes_written += 1 + bytes_on_line += 1 + if bytes_on_line >= 32: + out('\n') + bytes_on_line = 0 + out('};\n') + out('static const size_t resource{0:d}_size = {1:d};\n' + .format(index, bytes_written)) + index += 1 + + # Write the resource entries. + out('struct SkEmbeddedResource { const uint8_t* d; const size_t s; };\n') + out('static const SkEmbeddedResource header[] = {\n') + index = 0 + for f in args.input: + out(' {{ resource{0:d}, resource{0:d}_size }},\n'.format(index)) + index += 1 + out('};\n') + out('static const int header_count = {0:d};\n'.format(index)) + + # Export the resource header. + out('struct SkEmbeddedHeader {const SkEmbeddedResource* e; const int c;};\n') + out('extern "C" const SkEmbeddedHeader {0:s} = {{ header, header_count }};\n' + .format(args.name)) + + +if __name__ == "__main__": + main()