assets.py 10 KB

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