assets.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  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(
  29. "-s", "--source-directory", help="Source directory"
  30. )
  31. self.parser_icons.add_argument(
  32. "-o", "--output-directory", help="Output directory"
  33. )
  34. self.parser_icons.set_defaults(func=self.icons)
  35. # logging
  36. self.logger = logging.getLogger()
  37. def __call__(self):
  38. self.args = self.parser.parse_args()
  39. if "func" not in self.args:
  40. self.parser.error("Choose something to do")
  41. # configure log output
  42. self.log_level = logging.DEBUG if self.args.debug else logging.INFO
  43. self.logger.setLevel(self.log_level)
  44. self.handler = logging.StreamHandler(sys.stdout)
  45. self.handler.setLevel(self.log_level)
  46. self.formatter = logging.Formatter("%(asctime)s [%(levelname)s] %(message)s")
  47. self.handler.setFormatter(self.formatter)
  48. self.logger.addHandler(self.handler)
  49. # execute requested function
  50. self.args.func()
  51. def icons(self):
  52. self.logger.debug(f"Converting icons")
  53. icons_c = open(os.path.join(self.args.output_directory, "assets_icons.c"), "w")
  54. icons_c.write(ICONS_TEMPLATE_C_HEADER)
  55. icons = []
  56. # Traverse icons tree, append image data to source file
  57. for dirpath, dirnames, filenames in os.walk(self.args.source_directory):
  58. self.logger.debug(f"Processing directory {dirpath}")
  59. dirnames.sort()
  60. if not filenames:
  61. continue
  62. if "frame_rate" in filenames:
  63. self.logger.debug(f"Folder contatins animation")
  64. icon_name = "A_" + os.path.split(dirpath)[1].replace("-", "_")
  65. width = height = None
  66. frame_count = 0
  67. frame_rate = 0
  68. frame_names = []
  69. for filename in sorted(filenames):
  70. fullfilename = os.path.join(dirpath, filename)
  71. if filename == "frame_rate":
  72. frame_rate = int(open(fullfilename, "r").read().strip())
  73. continue
  74. elif not self.iconIsSupported(filename):
  75. continue
  76. self.logger.debug(f"Processing animation frame {filename}")
  77. temp_width, temp_height, data = self.icon2header(fullfilename)
  78. if width is None:
  79. width = temp_width
  80. if height is None:
  81. height = temp_height
  82. assert width == temp_width
  83. assert height == temp_height
  84. frame_name = f"_{icon_name}_{frame_count}"
  85. frame_names.append(frame_name)
  86. icons_c.write(
  87. ICONS_TEMPLATE_C_FRAME.format(name=frame_name, data=data)
  88. )
  89. frame_count += 1
  90. assert frame_rate > 0
  91. assert frame_count > 0
  92. icons_c.write(
  93. ICONS_TEMPLATE_C_DATA.format(
  94. name=f"_{icon_name}", data=f'{{{",".join(frame_names)}}}'
  95. )
  96. )
  97. icons_c.write("\n")
  98. icons.append((icon_name, width, height, frame_rate, frame_count))
  99. else:
  100. # process icons
  101. for filename in filenames:
  102. if not self.iconIsSupported(filename):
  103. continue
  104. self.logger.debug(f"Processing icon {filename}")
  105. icon_name = "I_" + "_".join(filename.split(".")[:-1]).replace(
  106. "-", "_"
  107. )
  108. fullfilename = os.path.join(dirpath, filename)
  109. width, height, data = self.icon2header(fullfilename)
  110. frame_name = f"_{icon_name}_0"
  111. icons_c.write(
  112. ICONS_TEMPLATE_C_FRAME.format(name=frame_name, data=data)
  113. )
  114. icons_c.write(
  115. ICONS_TEMPLATE_C_DATA.format(
  116. name=f"_{icon_name}", data=f"{{{frame_name}}}"
  117. )
  118. )
  119. icons_c.write("\n")
  120. icons.append((icon_name, width, height, 0, 1))
  121. # Create array of images:
  122. self.logger.debug(f"Finalizing source file")
  123. for name, width, height, frame_rate, frame_count in icons:
  124. icons_c.write(
  125. ICONS_TEMPLATE_C_ICONS.format(
  126. name=name,
  127. width=width,
  128. height=height,
  129. frame_rate=frame_rate,
  130. frame_count=frame_count,
  131. )
  132. )
  133. icons_c.write("\n")
  134. # Create Public Header
  135. self.logger.debug(f"Creating header")
  136. icons_h = open(os.path.join(self.args.output_directory, "assets_icons.h"), "w")
  137. icons_h.write(ICONS_TEMPLATE_H_HEADER)
  138. for name, width, height, frame_rate, frame_count in icons:
  139. icons_h.write(ICONS_TEMPLATE_H_ICON_NAME.format(name=name))
  140. self.logger.debug(f"Done")
  141. def icon2header(self, file):
  142. output = subprocess.check_output(["convert", file, "xbm:-"])
  143. assert output
  144. f = io.StringIO(output.decode().strip())
  145. width = int(f.readline().strip().split(" ")[2])
  146. height = int(f.readline().strip().split(" ")[2])
  147. data = f.read().strip().replace("\n", "").replace(" ", "").split("=")[1][:-1]
  148. return width, height, data
  149. def iconIsSupported(self, filename):
  150. extension = filename.lower().split(".")[-1]
  151. return extension in ICONS_SUPPORTED_FORMATS
  152. if __name__ == "__main__":
  153. Main()()