• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#!/usr/bin/python
2
3'''
4Copyright 2015 Google Inc.
5
6Use of this source code is governed by a BSD-style license that can be
7found in the LICENSE file.
8'''
9
10import argparse
11
12
13def bytes_from_file(f, chunksize=8192):
14  while True:
15    chunk = f.read(chunksize)
16    if chunk:
17      for b in chunk:
18        yield ord(b)
19    else:
20      break
21
22
23def main():
24  parser = argparse.ArgumentParser(
25      formatter_class=argparse.RawDescriptionHelpFormatter,
26      description='Convert resource files to embedded read only data.',
27      epilog='''The output (when compiled and linked) can be used as:
28struct SkEmbeddedResource {const uint8_t* data; const size_t size;};
29struct SkEmbeddedHeader {const SkEmbeddedResource* entries; const int count;};
30extern "C" SkEmbeddedHeader const NAME;''')
31  parser.add_argument('--align', default=1, type=int,
32                      help='minimum alignment (in bytes) of resource data')
33  parser.add_argument('--name', default='_resource', type=str,
34                      help='the name of the c identifier to export')
35  parser.add_argument('--input', required=True, type=argparse.FileType('rb'),
36                      nargs='+', help='list of resource files to embed')
37  parser.add_argument('--output', required=True, type=argparse.FileType('w'),
38                      help='the name of the cpp file to output')
39  args = parser.parse_args()
40
41  out = args.output.write;
42  out('#include <stddef.h>\n')
43  out('#include <stdint.h>\n')
44
45  # Write the resources.
46  index = 0
47  for f in args.input:
48    out('alignas({1:d}) static const uint8_t resource{0:d}[] = {{\n'
49        .format(index, args.align))
50    bytes_written = 0
51    bytes_on_line = 0
52    for b in bytes_from_file(f):
53      out(hex(b) + ',')
54      bytes_written += 1
55      bytes_on_line += 1
56      if bytes_on_line >= 32:
57        out('\n')
58        bytes_on_line = 0
59    out('};\n')
60    out('static const size_t resource{0:d}_size = {1:d};\n'
61        .format(index, bytes_written))
62    index += 1
63
64  # Write the resource entries.
65  out('struct SkEmbeddedResource { const uint8_t* d; const size_t s; };\n')
66  out('static const SkEmbeddedResource header[] = {\n')
67  index = 0
68  for f in args.input:
69    out('  {{ resource{0:d}, resource{0:d}_size }},\n'.format(index))
70    index += 1
71  out('};\n')
72  out('static const int header_count = {0:d};\n'.format(index))
73
74  # Export the resource header.
75  out('struct SkEmbeddedHeader {const SkEmbeddedResource* e; const int c;};\n')
76  out('extern "C" const SkEmbeddedHeader {0:s} = {{ header, header_count }};\n'
77      .format(args.name))
78
79
80if __name__ == "__main__":
81  main()
82