assets.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  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. typedef enum {
  12. """
  13. ICONS_TEMPLATE_H_ICON_NAME = "\t{name},\n"
  14. ICONS_TEMPLATE_H_FOOTER = """} IconName;
  15. Icon * assets_icons_get(IconName name);
  16. """
  17. ICONS_TEMPLATE_C_HEADER = """#include \"assets_icons.h\"
  18. #include <gui/icon_i.h>
  19. """
  20. ICONS_TEMPLATE_C_FRAME = "const uint8_t {name}[] = {data};\n"
  21. ICONS_TEMPLATE_C_DATA = "const uint8_t *{name}[] = {data};\n"
  22. ICONS_TEMPLATE_C_ICONS_ARRAY_START = "const IconData icons[] = {\n"
  23. ICONS_TEMPLATE_C_ICONS_ITEM = "\t{{ .width={width}, .height={height}, .frame_count={frame_count}, .frame_rate={frame_rate}, .frames=_{name} }},\n"
  24. ICONS_TEMPLATE_C_ICONS_ARRAY_END = "};"
  25. ICONS_TEMPLATE_C_FOOTER = """
  26. Icon * assets_icons_get(IconName name) {
  27. return icon_alloc(&icons[name]);
  28. }
  29. """
  30. class Assets:
  31. def __init__(self):
  32. # command args
  33. self.parser = argparse.ArgumentParser()
  34. self.parser.add_argument("-d", "--debug", action="store_true", help="Debug")
  35. self.subparsers = self.parser.add_subparsers(help="sub-command help")
  36. self.parser_icons = self.subparsers.add_parser(
  37. "icons", help="Process icons and build icon registry"
  38. )
  39. self.parser_icons.add_argument(
  40. "-s", "--source-directory", help="Source directory"
  41. )
  42. self.parser_icons.add_argument(
  43. "-o", "--output-directory", help="Output directory"
  44. )
  45. self.parser_icons.set_defaults(func=self.icons)
  46. # logging
  47. self.logger = logging.getLogger()
  48. def __call__(self):
  49. self.args = self.parser.parse_args()
  50. if "func" not in self.args:
  51. self.parser.error("Choose something to do")
  52. # configure log output
  53. self.log_level = logging.DEBUG if self.args.debug else logging.INFO
  54. self.logger.setLevel(self.log_level)
  55. self.handler = logging.StreamHandler(sys.stdout)
  56. self.handler.setLevel(self.log_level)
  57. self.formatter = logging.Formatter("%(asctime)s [%(levelname)s] %(message)s")
  58. self.handler.setFormatter(self.formatter)
  59. self.logger.addHandler(self.handler)
  60. # execute requested function
  61. self.args.func()
  62. def icons(self):
  63. self.logger.debug(f"Converting icons")
  64. icons_c = open(os.path.join(self.args.output_directory, "assets_icons.c"), "w")
  65. icons_c.write(ICONS_TEMPLATE_C_HEADER)
  66. icons = []
  67. # Traverse icons tree, append image data to source file
  68. for dirpath, dirnames, filenames in os.walk(self.args.source_directory):
  69. self.logger.debug(f"Processing directory {dirpath}")
  70. if not filenames:
  71. continue
  72. if "frame_rate" in filenames:
  73. self.logger.debug(f"Folder contatins animation")
  74. icon_name = "A_" + os.path.split(dirpath)[1].replace("-", "_")
  75. width = height = None
  76. frame_count = 0
  77. frame_rate = 0
  78. frame_names = []
  79. for filename in sorted(filenames):
  80. fullfilename = os.path.join(dirpath, filename)
  81. if filename == "frame_rate":
  82. frame_rate = int(open(fullfilename, "r").read().strip())
  83. continue
  84. elif not self.iconIsSupported(filename):
  85. continue
  86. self.logger.debug(f"Processing animation frame {filename}")
  87. temp_width, temp_height, data = self.icon2header(fullfilename)
  88. if width is None:
  89. width = temp_width
  90. if height is None:
  91. height = temp_height
  92. assert width == temp_width
  93. assert height == temp_height
  94. frame_name = f"_{icon_name}_{frame_count}"
  95. frame_names.append(frame_name)
  96. icons_c.write(
  97. ICONS_TEMPLATE_C_FRAME.format(name=frame_name, data=data)
  98. )
  99. frame_count += 1
  100. assert frame_rate > 0
  101. assert frame_count > 0
  102. icons_c.write(
  103. ICONS_TEMPLATE_C_DATA.format(
  104. name=f"_{icon_name}", data=f'{{{",".join(frame_names)}}}'
  105. )
  106. )
  107. icons_c.write("\n")
  108. icons.append((icon_name, width, height, frame_rate, frame_count))
  109. else:
  110. # process icons
  111. for filename in filenames:
  112. if not self.iconIsSupported(filename):
  113. continue
  114. self.logger.debug(f"Processing icon {filename}")
  115. icon_name = "I_" + "_".join(filename.split(".")[:-1]).replace(
  116. "-", "_"
  117. )
  118. fullfilename = os.path.join(dirpath, filename)
  119. width, height, data = self.icon2header(fullfilename)
  120. frame_name = f"_{icon_name}_0"
  121. icons_c.write(
  122. ICONS_TEMPLATE_C_FRAME.format(name=frame_name, data=data)
  123. )
  124. icons_c.write(
  125. ICONS_TEMPLATE_C_DATA.format(
  126. name=f"_{icon_name}", data=f"{{{frame_name}}}"
  127. )
  128. )
  129. icons_c.write("\n")
  130. icons.append((icon_name, width, height, 0, 1))
  131. # Create array of images:
  132. self.logger.debug(f"Finalizing source file")
  133. icons_c.write(ICONS_TEMPLATE_C_ICONS_ARRAY_START)
  134. for name, width, height, frame_rate, frame_count in icons:
  135. icons_c.write(
  136. ICONS_TEMPLATE_C_ICONS_ITEM.format(
  137. name=name,
  138. width=width,
  139. height=height,
  140. frame_rate=frame_rate,
  141. frame_count=frame_count,
  142. )
  143. )
  144. icons_c.write(ICONS_TEMPLATE_C_ICONS_ARRAY_END)
  145. icons_c.write(ICONS_TEMPLATE_C_FOOTER)
  146. icons_c.write("\n")
  147. # Create Header
  148. self.logger.debug(f"Creating header")
  149. icons_h = open(os.path.join(self.args.output_directory, "assets_icons.h"), "w")
  150. icons_h.write(ICONS_TEMPLATE_H_HEADER)
  151. for name, width, height, frame_rate, frame_count in icons:
  152. icons_h.write(ICONS_TEMPLATE_H_ICON_NAME.format(name=name))
  153. icons_h.write(ICONS_TEMPLATE_H_FOOTER)
  154. self.logger.debug(f"Done")
  155. def icon2header(self, file):
  156. output = subprocess.check_output(["convert", file, "xbm:-"])
  157. assert output
  158. f = io.StringIO(output.decode().strip())
  159. width = int(f.readline().strip().split(" ")[2])
  160. height = int(f.readline().strip().split(" ")[2])
  161. data = f.read().strip().replace("\n", "").replace(" ", "").split("=")[1][:-1]
  162. return width, height, data
  163. def iconIsSupported(self, filename):
  164. extension = filename.lower().split(".")[-1]
  165. return extension in ICONS_SUPPORTED_FORMATS
  166. if __name__ == "__main__":
  167. Assets()()