assets.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  1. #!/usr/bin/env python3
  2. import logging
  3. import argparse
  4. import subprocess
  5. import io
  6. import os
  7. import sys
  8. import struct
  9. import datetime
  10. ICONS_SUPPORTED_FORMATS = ["png"]
  11. ICONS_TEMPLATE_H_HEADER = """#pragma once
  12. #include <gui/icon.h>
  13. typedef enum {
  14. """
  15. ICONS_TEMPLATE_H_ICON_NAME = "\t{name},\n"
  16. ICONS_TEMPLATE_H_FOOTER = """} IconName;
  17. Icon * assets_icons_get(IconName name);
  18. """
  19. ICONS_TEMPLATE_H_I = """#pragma once
  20. #include <assets_icons.h>
  21. const IconData * assets_icons_get_data(IconName name);
  22. """
  23. ICONS_TEMPLATE_C_HEADER = """#include \"assets_icons_i.h\"
  24. #include <gui/icon_i.h>
  25. """
  26. ICONS_TEMPLATE_C_FRAME = "const uint8_t {name}[] = {data};\n"
  27. ICONS_TEMPLATE_C_DATA = "const uint8_t *{name}[] = {data};\n"
  28. ICONS_TEMPLATE_C_ICONS_ARRAY_START = "const IconData icons[] = {\n"
  29. ICONS_TEMPLATE_C_ICONS_ITEM = "\t{{ .width={width}, .height={height}, .frame_count={frame_count}, .frame_rate={frame_rate}, .frames=_{name} }},\n"
  30. ICONS_TEMPLATE_C_ICONS_ARRAY_END = "};"
  31. ICONS_TEMPLATE_C_FOOTER = """
  32. const IconData * assets_icons_get_data(IconName name) {
  33. return &icons[name];
  34. }
  35. Icon * assets_icons_get(IconName name) {
  36. return icon_alloc(assets_icons_get_data(name));
  37. }
  38. """
  39. class Assets:
  40. def __init__(self):
  41. # command args
  42. self.parser = argparse.ArgumentParser()
  43. self.parser.add_argument("-d", "--debug", action="store_true", help="Debug")
  44. self.subparsers = self.parser.add_subparsers(help="sub-command help")
  45. self.parser_icons = self.subparsers.add_parser(
  46. "icons", help="Process icons and build icon registry"
  47. )
  48. self.parser_icons.add_argument(
  49. "-s", "--source-directory", help="Source directory"
  50. )
  51. self.parser_icons.add_argument(
  52. "-o", "--output-directory", help="Output directory"
  53. )
  54. self.parser_icons.set_defaults(func=self.icons)
  55. self.parser_otp = self.subparsers.add_parser(
  56. "otp", help="OTP HW version generator"
  57. )
  58. self.parser_otp.add_argument(
  59. "--version", type=int, help="Version", required=True
  60. )
  61. self.parser_otp.add_argument(
  62. "--firmware", type=int, help="Firmware", required=True
  63. )
  64. self.parser_otp.add_argument("--body", type=int, help="Body", required=True)
  65. self.parser_otp.add_argument(
  66. "--connect", type=int, help="Connect", required=True
  67. )
  68. self.parser_otp.add_argument("file", help="Output file")
  69. self.parser_otp.set_defaults(func=self.otp)
  70. # logging
  71. self.logger = logging.getLogger()
  72. def __call__(self):
  73. self.args = self.parser.parse_args()
  74. if "func" not in self.args:
  75. self.parser.error("Choose something to do")
  76. # configure log output
  77. self.log_level = logging.DEBUG if self.args.debug else logging.INFO
  78. self.logger.setLevel(self.log_level)
  79. self.handler = logging.StreamHandler(sys.stdout)
  80. self.handler.setLevel(self.log_level)
  81. self.formatter = logging.Formatter("%(asctime)s [%(levelname)s] %(message)s")
  82. self.handler.setFormatter(self.formatter)
  83. self.logger.addHandler(self.handler)
  84. # execute requested function
  85. self.args.func()
  86. def otp(self):
  87. self.logger.debug(f"Generating OTP")
  88. data = struct.pack(
  89. "<BBBBL",
  90. self.args.version,
  91. self.args.firmware,
  92. self.args.body,
  93. self.args.connect,
  94. int(datetime.datetime.now().timestamp()),
  95. )
  96. open(self.args.file, "wb").write(data)
  97. def icons(self):
  98. self.logger.debug(f"Converting icons")
  99. icons_c = open(os.path.join(self.args.output_directory, "assets_icons.c"), "w")
  100. icons_c.write(ICONS_TEMPLATE_C_HEADER)
  101. icons = []
  102. # Traverse icons tree, append image data to source file
  103. for dirpath, dirnames, filenames in os.walk(self.args.source_directory):
  104. self.logger.debug(f"Processing directory {dirpath}")
  105. if not filenames:
  106. continue
  107. if "frame_rate" in filenames:
  108. self.logger.debug(f"Folder contatins animation")
  109. icon_name = "A_" + os.path.split(dirpath)[1].replace("-", "_")
  110. width = height = None
  111. frame_count = 0
  112. frame_rate = 0
  113. frame_names = []
  114. for filename in sorted(filenames):
  115. fullfilename = os.path.join(dirpath, filename)
  116. if filename == "frame_rate":
  117. frame_rate = int(open(fullfilename, "r").read().strip())
  118. continue
  119. elif not self.iconIsSupported(filename):
  120. continue
  121. self.logger.debug(f"Processing animation frame {filename}")
  122. temp_width, temp_height, data = self.icon2header(fullfilename)
  123. if width is None:
  124. width = temp_width
  125. if height is None:
  126. height = temp_height
  127. assert width == temp_width
  128. assert height == temp_height
  129. frame_name = f"_{icon_name}_{frame_count}"
  130. frame_names.append(frame_name)
  131. icons_c.write(
  132. ICONS_TEMPLATE_C_FRAME.format(name=frame_name, data=data)
  133. )
  134. frame_count += 1
  135. assert frame_rate > 0
  136. assert frame_count > 0
  137. icons_c.write(
  138. ICONS_TEMPLATE_C_DATA.format(
  139. name=f"_{icon_name}", data=f'{{{",".join(frame_names)}}}'
  140. )
  141. )
  142. icons_c.write("\n")
  143. icons.append((icon_name, width, height, frame_rate, frame_count))
  144. else:
  145. # process icons
  146. for filename in filenames:
  147. if not self.iconIsSupported(filename):
  148. continue
  149. self.logger.debug(f"Processing icon {filename}")
  150. icon_name = "I_" + "_".join(filename.split(".")[:-1]).replace(
  151. "-", "_"
  152. )
  153. fullfilename = os.path.join(dirpath, filename)
  154. width, height, data = self.icon2header(fullfilename)
  155. frame_name = f"_{icon_name}_0"
  156. icons_c.write(
  157. ICONS_TEMPLATE_C_FRAME.format(name=frame_name, data=data)
  158. )
  159. icons_c.write(
  160. ICONS_TEMPLATE_C_DATA.format(
  161. name=f"_{icon_name}", data=f"{{{frame_name}}}"
  162. )
  163. )
  164. icons_c.write("\n")
  165. icons.append((icon_name, width, height, 0, 1))
  166. # Create array of images:
  167. self.logger.debug(f"Finalizing source file")
  168. icons_c.write(ICONS_TEMPLATE_C_ICONS_ARRAY_START)
  169. for name, width, height, frame_rate, frame_count in icons:
  170. icons_c.write(
  171. ICONS_TEMPLATE_C_ICONS_ITEM.format(
  172. name=name,
  173. width=width,
  174. height=height,
  175. frame_rate=frame_rate,
  176. frame_count=frame_count,
  177. )
  178. )
  179. icons_c.write(ICONS_TEMPLATE_C_ICONS_ARRAY_END)
  180. icons_c.write(ICONS_TEMPLATE_C_FOOTER)
  181. icons_c.write("\n")
  182. # Create Public Header
  183. self.logger.debug(f"Creating header")
  184. icons_h = open(os.path.join(self.args.output_directory, "assets_icons.h"), "w")
  185. icons_h.write(ICONS_TEMPLATE_H_HEADER)
  186. for name, width, height, frame_rate, frame_count in icons:
  187. icons_h.write(ICONS_TEMPLATE_H_ICON_NAME.format(name=name))
  188. icons_h.write(ICONS_TEMPLATE_H_FOOTER)
  189. # Create Private Header
  190. icons_h_i = open(
  191. os.path.join(self.args.output_directory, "assets_icons_i.h"), "w"
  192. )
  193. icons_h_i.write(ICONS_TEMPLATE_H_I)
  194. self.logger.debug(f"Done")
  195. def icon2header(self, file):
  196. output = subprocess.check_output(["convert", file, "xbm:-"])
  197. assert output
  198. f = io.StringIO(output.decode().strip())
  199. width = int(f.readline().strip().split(" ")[2])
  200. height = int(f.readline().strip().split(" ")[2])
  201. data = f.read().strip().replace("\n", "").replace(" ", "").split("=")[1][:-1]
  202. return width, height, data
  203. def iconIsSupported(self, filename):
  204. extension = filename.lower().split(".")[-1]
  205. return extension in ICONS_SUPPORTED_FORMATS
  206. if __name__ == "__main__":
  207. Assets()()