assets.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  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.set_defaults(func=self.copro)
  42. self.parser_dolphin = self.subparsers.add_parser(
  43. "dolphin", help="Assemble dolphin resources"
  44. )
  45. self.parser_dolphin.add_argument(
  46. "-s",
  47. "--symbol-name",
  48. help="Symbol and file name in dolphin output directory",
  49. default=None,
  50. )
  51. self.parser_dolphin.add_argument(
  52. "input_directory", help="Dolphin source directory"
  53. )
  54. self.parser_dolphin.add_argument(
  55. "output_directory", help="Dolphin output directory"
  56. )
  57. self.parser_dolphin.set_defaults(func=self.dolphin)
  58. def _icon2header(self, file):
  59. output = subprocess.check_output(["convert", file, "xbm:-"])
  60. assert output
  61. f = io.StringIO(output.decode().strip())
  62. width = int(f.readline().strip().split(" ")[2])
  63. height = int(f.readline().strip().split(" ")[2])
  64. data = f.read().strip().replace("\n", "").replace(" ", "").split("=")[1][:-1]
  65. data_bin_str = data[1:-1].replace(",", " ").replace("0x", "")
  66. data_bin = bytearray.fromhex(data_bin_str)
  67. # Encode icon data with LZSS
  68. data_encoded_str = subprocess.check_output(
  69. ["heatshrink", "-e", "-w8", "-l4"], input=data_bin
  70. )
  71. assert data_encoded_str
  72. data_enc = bytearray(data_encoded_str)
  73. data_enc = bytearray([len(data_enc) & 0xFF, len(data_enc) >> 8]) + data_enc
  74. # Use encoded data only if its lenght less than original, including header
  75. if len(data_enc) < len(data_bin) + 1:
  76. data = (
  77. "{0x01,0x00,"
  78. + "".join("0x{:02x},".format(byte) for byte in data_enc)
  79. + "}"
  80. )
  81. else:
  82. data = "{0x00," + data[1:]
  83. return width, height, data
  84. def _iconIsSupported(self, filename):
  85. extension = filename.lower().split(".")[-1]
  86. return extension in ICONS_SUPPORTED_FORMATS
  87. def icons(self):
  88. self.logger.debug(f"Converting icons")
  89. icons_c = open(os.path.join(self.args.output_directory, "assets_icons.c"), "w")
  90. icons_c.write(ICONS_TEMPLATE_C_HEADER)
  91. icons = []
  92. # Traverse icons tree, append image data to source file
  93. for dirpath, dirnames, filenames in os.walk(self.args.input_directory):
  94. self.logger.debug(f"Processing directory {dirpath}")
  95. dirnames.sort()
  96. filenames.sort()
  97. if not filenames:
  98. continue
  99. if "frame_rate" in filenames:
  100. self.logger.debug(f"Folder contatins animation")
  101. icon_name = "A_" + os.path.split(dirpath)[1].replace("-", "_")
  102. width = height = None
  103. frame_count = 0
  104. frame_rate = 0
  105. frame_names = []
  106. for filename in sorted(filenames):
  107. fullfilename = os.path.join(dirpath, filename)
  108. if filename == "frame_rate":
  109. frame_rate = int(open(fullfilename, "r").read().strip())
  110. continue
  111. elif not self._iconIsSupported(filename):
  112. continue
  113. self.logger.debug(f"Processing animation frame {filename}")
  114. temp_width, temp_height, data = self._icon2header(fullfilename)
  115. if width is None:
  116. width = temp_width
  117. if height is None:
  118. height = temp_height
  119. assert width == temp_width
  120. assert height == temp_height
  121. frame_name = f"_{icon_name}_{frame_count}"
  122. frame_names.append(frame_name)
  123. icons_c.write(
  124. ICONS_TEMPLATE_C_FRAME.format(name=frame_name, data=data)
  125. )
  126. frame_count += 1
  127. assert frame_rate > 0
  128. assert frame_count > 0
  129. icons_c.write(
  130. ICONS_TEMPLATE_C_DATA.format(
  131. name=f"_{icon_name}", data=f'{{{",".join(frame_names)}}}'
  132. )
  133. )
  134. icons_c.write("\n")
  135. icons.append((icon_name, width, height, frame_rate, frame_count))
  136. else:
  137. # process icons
  138. for filename in filenames:
  139. if not self._iconIsSupported(filename):
  140. continue
  141. self.logger.debug(f"Processing icon {filename}")
  142. icon_name = "I_" + "_".join(filename.split(".")[:-1]).replace(
  143. "-", "_"
  144. )
  145. fullfilename = os.path.join(dirpath, filename)
  146. width, height, data = self._icon2header(fullfilename)
  147. frame_name = f"_{icon_name}_0"
  148. icons_c.write(
  149. ICONS_TEMPLATE_C_FRAME.format(name=frame_name, data=data)
  150. )
  151. icons_c.write(
  152. ICONS_TEMPLATE_C_DATA.format(
  153. name=f"_{icon_name}", data=f"{{{frame_name}}}"
  154. )
  155. )
  156. icons_c.write("\n")
  157. icons.append((icon_name, width, height, 0, 1))
  158. # Create array of images:
  159. self.logger.debug(f"Finalizing source file")
  160. for name, width, height, frame_rate, frame_count in icons:
  161. icons_c.write(
  162. ICONS_TEMPLATE_C_ICONS.format(
  163. name=name,
  164. width=width,
  165. height=height,
  166. frame_rate=frame_rate,
  167. frame_count=frame_count,
  168. )
  169. )
  170. icons_c.write("\n")
  171. # Create Public Header
  172. self.logger.debug(f"Creating header")
  173. icons_h = open(os.path.join(self.args.output_directory, "assets_icons.h"), "w")
  174. icons_h.write(ICONS_TEMPLATE_H_HEADER)
  175. for name, width, height, frame_rate, frame_count in icons:
  176. icons_h.write(ICONS_TEMPLATE_H_ICON_NAME.format(name=name))
  177. self.logger.debug(f"Done")
  178. return 0
  179. def manifest(self):
  180. from flipper.assets.manifest import Manifest
  181. directory_path = os.path.normpath(self.args.local_path)
  182. if not os.path.isdir(directory_path):
  183. self.logger.error(f'"{directory_path}" is not a directory')
  184. exit(255)
  185. manifest_file = os.path.join(directory_path, "Manifest")
  186. old_manifest = Manifest()
  187. if os.path.exists(manifest_file):
  188. self.logger.info("old manifest is present, loading for compare")
  189. old_manifest.load(manifest_file)
  190. self.logger.info(f'Creating new Manifest for directory "{directory_path}"')
  191. new_manifest = Manifest()
  192. new_manifest.create(directory_path)
  193. self.logger.info(f"Comparing new manifest with old")
  194. only_in_old, changed, only_in_new = Manifest.compare(old_manifest, new_manifest)
  195. for record in only_in_old:
  196. self.logger.info(f"Only in old: {record}")
  197. for record in changed:
  198. self.logger.info(f"Changed: {record}")
  199. for record in only_in_new:
  200. self.logger.info(f"Only in new: {record}")
  201. if any((only_in_old, changed, only_in_new)):
  202. self.logger.warning("Manifests are different, updating")
  203. new_manifest.save(manifest_file)
  204. else:
  205. self.logger.info("Manifest is up-to-date!")
  206. self.logger.info(f"Complete")
  207. return 0
  208. def copro(self):
  209. from flipper.assets.copro import Copro
  210. self.logger.info(f"Bundling coprocessor binaries")
  211. copro = Copro(self.args.mcu)
  212. self.logger.info(f"Loading CUBE info")
  213. copro.loadCubeInfo(self.args.cube_dir)
  214. self.logger.info(f"Bundling")
  215. copro.bundle(self.args.output_dir)
  216. self.logger.info(f"Complete")
  217. return 0
  218. def dolphin(self):
  219. from flipper.assets.dolphin import Dolphin
  220. self.logger.info(f"Processing Dolphin sources")
  221. dolphin = Dolphin()
  222. self.logger.info(f"Loading data")
  223. dolphin.load(self.args.input_directory)
  224. self.logger.info(f"Packing")
  225. dolphin.pack(self.args.output_directory, self.args.symbol_name)
  226. self.logger.info(f"Complete")
  227. return 0
  228. if __name__ == "__main__":
  229. Main()()