embed_resources.py 2.5 KB

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