assets.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. #!/usr/bin/env python3
  2. from flipper.app import App
  3. import logging
  4. import argparse
  5. import subprocess
  6. import io
  7. import os
  8. import sys
  9. ICONS_SUPPORTED_FORMATS = ["png"]
  10. ICONS_TEMPLATE_H_HEADER = """#pragma once
  11. #include <gui/icon.h>
  12. """
  13. ICONS_TEMPLATE_H_ICON_NAME = "extern const Icon {name};\n"
  14. ICONS_TEMPLATE_C_HEADER = """#include \"assets_icons.h\"
  15. #include <gui/icon_i.h>
  16. """
  17. ICONS_TEMPLATE_C_FRAME = "const uint8_t {name}[] = {data};\n"
  18. ICONS_TEMPLATE_C_DATA = "const uint8_t* const {name}[] = {data};\n"
  19. ICONS_TEMPLATE_C_ICONS = "const Icon {name} = {{.width={width},.height={height},.frame_count={frame_count},.frame_rate={frame_rate},.frames=_{name}}};\n"
  20. class Main(App):
  21. def init(self):
  22. # command args
  23. self.subparsers = self.parser.add_subparsers(help="sub-command help")
  24. self.parser_icons = self.subparsers.add_parser(
  25. "icons", help="Process icons and build icon registry"
  26. )
  27. self.parser_icons.add_argument("input_directory", help="Source directory")
  28. self.parser_icons.add_argument("output_directory", help="Output directory")
  29. self.parser_icons.set_defaults(func=self.icons)
  30. self.parser_manifest = self.subparsers.add_parser(
  31. "manifest", help="Create directory Manifest"
  32. )
  33. self.parser_manifest.add_argument("local_path", help="local_path")
  34. self.parser_manifest.set_defaults(func=self.manifest)
  35. self.parser_copro = self.subparsers.add_parser(
  36. "copro", help="Gather copro binaries for packaging"
  37. )
  38. self.parser_copro.add_argument("cube_dir", help="Path to Cube folder")
  39. self.parser_copro.add_argument("output_dir", help="Path to output folder")
  40. self.parser_copro.add_argument("mcu", help="MCU series as in copro folder")
  41. self.parser_copro.add_argument(
  42. "--cube_ver", dest="cube_ver", help="Cube version", required=True
  43. )
  44. self.parser_copro.add_argument(
  45. "--stack_type", dest="stack_type", help="Stack type", required=True
  46. )
  47. self.parser_copro.add_argument(
  48. "--stack_file",
  49. dest="stack_file",
  50. help="Stack file name in copro folder",
  51. required=True,
  52. )
  53. self.parser_copro.add_argument(
  54. "--stack_addr",
  55. dest="stack_addr",
  56. help="Stack flash address, as per release_notes",
  57. type=lambda x: int(x, 16),
  58. default=0,
  59. required=False,
  60. )
  61. self.parser_copro.set_defaults(func=self.copro)
  62. self.parser_dolphin = self.subparsers.add_parser(
  63. "dolphin", help="Assemble dolphin resources"
  64. )
  65. self.parser_dolphin.add_argument(
  66. "-s",
  67. "--symbol-name",
  68. help="Symbol and file name in dolphin output directory",
  69. default=None,
  70. )
  71. self.parser_dolphin.add_argument(
  72. "input_directory", help="Dolphin source directory"
  73. )
  74. self.parser_dolphin.add_argument(
  75. "output_directory", help="Dolphin output directory"
  76. )
  77. self.parser_dolphin.set_defaults(func=self.dolphin)
  78. def _icon2header(self, file):
  79. output = subprocess.check_output(["convert", file, "xbm:-"])
  80. assert output
  81. f = io.StringIO(output.decode().strip())
  82. width = int(f.readline().strip().split(" ")[2])
  83. height = int(f.readline().strip().split(" ")[2])
  84. data = f.read().strip().replace("\n", "").replace(" ", "").split("=")[1][:-1]
  85. data_bin_str = data[1:-1].replace(",", " ").replace("0x", "")
  86. data_bin = bytearray.fromhex(data_bin_str)
  87. # Encode icon data with LZSS
  88. data_encoded_str = subprocess.check_output(
  89. ["heatshrink", "-e", "-w8", "-l4"], input=data_bin
  90. )
  91. assert data_encoded_str
  92. data_enc = bytearray(data_encoded_str)
  93. data_enc = bytearray([len(data_enc) & 0xFF, len(data_enc) >> 8]) + data_enc
  94. # Use encoded data only if its lenght less than original, including header
  95. if len(data_enc) < len(data_bin) + 1:
  96. data = (
  97. "{0x01,0x00,"
  98. + "".join("0x{:02x},".format(byte) for byte in data_enc)
  99. + "}"
  100. )
  101. else:
  102. data = "{0x00," + data[1:]
  103. return width, height, data
  104. def _iconIsSupported(self, filename):
  105. extension = filename.lower().split(".")[-1]
  106. return extension in ICONS_SUPPORTED_FORMATS
  107. def icons(self):
  108. self.logger.debug(f"Converting icons")
  109. icons_c = open(os.path.join(self.args.output_directory, "assets_icons.c"), "w")
  110. icons_c.write(ICONS_TEMPLATE_C_HEADER)
  111. icons = []
  112. # Traverse icons tree, append image data to source file
  113. for dirpath, dirnames, filenames in os.walk(self.args.input_directory):
  114. self.logger.debug(f"Processing directory {dirpath}")
  115. dirnames.sort()
  116. filenames.sort()
  117. if not filenames:
  118. continue
  119. if "frame_rate" in filenames:
  120. self.logger.debug(f"Folder contatins animation")
  121. icon_name = "A_" + os.path.split(dirpath)[1].replace("-", "_")
  122. width = height = None
  123. frame_count = 0
  124. frame_rate = 0
  125. frame_names = []
  126. for filename in sorted(filenames):
  127. fullfilename = os.path.join(dirpath, filename)
  128. if filename == "frame_rate":
  129. frame_rate = int(open(fullfilename, "r").read().strip())
  130. continue
  131. elif not self._iconIsSupported(filename):
  132. continue
  133. self.logger.debug(f"Processing animation frame {filename}")
  134. temp_width, temp_height, data = self._icon2header(fullfilename)
  135. if width is None:
  136. width = temp_width
  137. if height is None:
  138. height = temp_height
  139. assert width == temp_width
  140. assert height == temp_height
  141. frame_name = f"_{icon_name}_{frame_count}"
  142. frame_names.append(frame_name)
  143. icons_c.write(
  144. ICONS_TEMPLATE_C_FRAME.format(name=frame_name, data=data)
  145. )
  146. frame_count += 1
  147. assert frame_rate > 0
  148. assert frame_count > 0
  149. icons_c.write(
  150. ICONS_TEMPLATE_C_DATA.format(
  151. name=f"_{icon_name}", data=f'{{{",".join(frame_names)}}}'
  152. )
  153. )
  154. icons_c.write("\n")
  155. icons.append((icon_name, width, height, frame_rate, frame_count))
  156. else:
  157. # process icons
  158. for filename in filenames:
  159. if not self._iconIsSupported(filename):
  160. continue
  161. self.logger.debug(f"Processing icon {filename}")
  162. icon_name = "I_" + "_".join(filename.split(".")[:-1]).replace(
  163. "-", "_"
  164. )
  165. fullfilename = os.path.join(dirpath, filename)
  166. width, height, data = self._icon2header(fullfilename)
  167. frame_name = f"_{icon_name}_0"
  168. icons_c.write(
  169. ICONS_TEMPLATE_C_FRAME.format(name=frame_name, data=data)
  170. )
  171. icons_c.write(
  172. ICONS_TEMPLATE_C_DATA.format(
  173. name=f"_{icon_name}", data=f"{{{frame_name}}}"
  174. )
  175. )
  176. icons_c.write("\n")
  177. icons.append((icon_name, width, height, 0, 1))
  178. # Create array of images:
  179. self.logger.debug(f"Finalizing source file")
  180. for name, width, height, frame_rate, frame_count in icons:
  181. icons_c.write(
  182. ICONS_TEMPLATE_C_ICONS.format(
  183. name=name,
  184. width=width,
  185. height=height,
  186. frame_rate=frame_rate,
  187. frame_count=frame_count,
  188. )
  189. )
  190. icons_c.write("\n")
  191. # Create Public Header
  192. self.logger.debug(f"Creating header")
  193. icons_h = open(os.path.join(self.args.output_directory, "assets_icons.h"), "w")
  194. icons_h.write(ICONS_TEMPLATE_H_HEADER)
  195. for name, width, height, frame_rate, frame_count in icons:
  196. icons_h.write(ICONS_TEMPLATE_H_ICON_NAME.format(name=name))
  197. self.logger.debug(f"Done")
  198. return 0
  199. def manifest(self):
  200. from flipper.assets.manifest import Manifest
  201. directory_path = os.path.normpath(self.args.local_path)
  202. if not os.path.isdir(directory_path):
  203. self.logger.error(f'"{directory_path}" is not a directory')
  204. exit(255)
  205. manifest_file = os.path.join(directory_path, "Manifest")
  206. old_manifest = Manifest()
  207. if os.path.exists(manifest_file):
  208. self.logger.info("Manifest is present, loading to compare")
  209. old_manifest.load(manifest_file)
  210. self.logger.info(
  211. f'Creating temporary Manifest for directory "{directory_path}"'
  212. )
  213. new_manifest = Manifest()
  214. new_manifest.create(directory_path)
  215. self.logger.info(f"Comparing new manifest with existing")
  216. only_in_old, changed, only_in_new = Manifest.compare(old_manifest, new_manifest)
  217. for record in only_in_old:
  218. self.logger.info(f"Only in old: {record}")
  219. for record in changed:
  220. self.logger.info(f"Changed: {record}")
  221. for record in only_in_new:
  222. self.logger.info(f"Only in new: {record}")
  223. if any((only_in_old, changed, only_in_new)):
  224. self.logger.warning("Manifests are different, updating")
  225. new_manifest.save(manifest_file)
  226. else:
  227. self.logger.info("Manifest is up-to-date!")
  228. self.logger.info(f"Complete")
  229. return 0
  230. def copro(self):
  231. from flipper.assets.copro import Copro
  232. self.logger.info(f"Bundling coprocessor binaries")
  233. copro = Copro(self.args.mcu)
  234. self.logger.info(f"Loading CUBE info")
  235. copro.loadCubeInfo(self.args.cube_dir, self.args.cube_ver)
  236. self.logger.info(f"Bundling")
  237. copro.bundle(
  238. self.args.output_dir,
  239. self.args.stack_file,
  240. self.args.stack_type,
  241. self.args.stack_addr,
  242. )
  243. self.logger.info(f"Complete")
  244. return 0
  245. def dolphin(self):
  246. from flipper.assets.dolphin import Dolphin
  247. self.logger.info(f"Processing Dolphin sources")
  248. dolphin = Dolphin()
  249. self.logger.info(f"Loading data")
  250. dolphin.load(self.args.input_directory)
  251. self.logger.info(f"Packing")
  252. dolphin.pack(self.args.output_directory, self.args.symbol_name)
  253. self.logger.info(f"Complete")
  254. return 0
  255. if __name__ == "__main__":
  256. Main()()