assets.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  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_H_I = """#pragma once
  18. #include <assets_icons.h>
  19. const IconData * assets_icons_get_data(IconName name);
  20. """
  21. ICONS_TEMPLATE_C_HEADER = """#include \"assets_icons_i.h\"
  22. #include <gui/icon_i.h>
  23. """
  24. ICONS_TEMPLATE_C_FRAME = "const uint8_t {name}[] = {data};\n"
  25. ICONS_TEMPLATE_C_DATA = "const uint8_t *{name}[] = {data};\n"
  26. ICONS_TEMPLATE_C_ICONS_ARRAY_START = "const IconData icons[] = {\n"
  27. ICONS_TEMPLATE_C_ICONS_ITEM = "\t{{ .width={width}, .height={height}, .frame_count={frame_count}, .frame_rate={frame_rate}, .frames=_{name} }},\n"
  28. ICONS_TEMPLATE_C_ICONS_ARRAY_END = "};"
  29. ICONS_TEMPLATE_C_FOOTER = """
  30. const IconData * assets_icons_get_data(IconName name) {
  31. return &icons[name];
  32. }
  33. Icon * assets_icons_get(IconName name) {
  34. return icon_alloc(assets_icons_get_data(name));
  35. }
  36. """
  37. class Main:
  38. def __init__(self):
  39. # command args
  40. self.parser = argparse.ArgumentParser()
  41. self.parser.add_argument("-d", "--debug", action="store_true", help="Debug")
  42. self.subparsers = self.parser.add_subparsers(help="sub-command help")
  43. self.parser_icons = self.subparsers.add_parser(
  44. "icons", help="Process icons and build icon registry"
  45. )
  46. self.parser_icons.add_argument(
  47. "-s", "--source-directory", help="Source directory"
  48. )
  49. self.parser_icons.add_argument(
  50. "-o", "--output-directory", help="Output directory"
  51. )
  52. self.parser_icons.set_defaults(func=self.icons)
  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. if not filenames:
  78. continue
  79. if "frame_rate" in filenames:
  80. self.logger.debug(f"Folder contatins animation")
  81. icon_name = "A_" + os.path.split(dirpath)[1].replace("-", "_")
  82. width = height = None
  83. frame_count = 0
  84. frame_rate = 0
  85. frame_names = []
  86. for filename in sorted(filenames):
  87. fullfilename = os.path.join(dirpath, filename)
  88. if filename == "frame_rate":
  89. frame_rate = int(open(fullfilename, "r").read().strip())
  90. continue
  91. elif not self.iconIsSupported(filename):
  92. continue
  93. self.logger.debug(f"Processing animation frame {filename}")
  94. temp_width, temp_height, data = self.icon2header(fullfilename)
  95. if width is None:
  96. width = temp_width
  97. if height is None:
  98. height = temp_height
  99. assert width == temp_width
  100. assert height == temp_height
  101. frame_name = f"_{icon_name}_{frame_count}"
  102. frame_names.append(frame_name)
  103. icons_c.write(
  104. ICONS_TEMPLATE_C_FRAME.format(name=frame_name, data=data)
  105. )
  106. frame_count += 1
  107. assert frame_rate > 0
  108. assert frame_count > 0
  109. icons_c.write(
  110. ICONS_TEMPLATE_C_DATA.format(
  111. name=f"_{icon_name}", data=f'{{{",".join(frame_names)}}}'
  112. )
  113. )
  114. icons_c.write("\n")
  115. icons.append((icon_name, width, height, frame_rate, frame_count))
  116. else:
  117. # process icons
  118. for filename in filenames:
  119. if not self.iconIsSupported(filename):
  120. continue
  121. self.logger.debug(f"Processing icon {filename}")
  122. icon_name = "I_" + "_".join(filename.split(".")[:-1]).replace(
  123. "-", "_"
  124. )
  125. fullfilename = os.path.join(dirpath, filename)
  126. width, height, data = self.icon2header(fullfilename)
  127. frame_name = f"_{icon_name}_0"
  128. icons_c.write(
  129. ICONS_TEMPLATE_C_FRAME.format(name=frame_name, data=data)
  130. )
  131. icons_c.write(
  132. ICONS_TEMPLATE_C_DATA.format(
  133. name=f"_{icon_name}", data=f"{{{frame_name}}}"
  134. )
  135. )
  136. icons_c.write("\n")
  137. icons.append((icon_name, width, height, 0, 1))
  138. # Create array of images:
  139. self.logger.debug(f"Finalizing source file")
  140. icons_c.write(ICONS_TEMPLATE_C_ICONS_ARRAY_START)
  141. for name, width, height, frame_rate, frame_count in icons:
  142. icons_c.write(
  143. ICONS_TEMPLATE_C_ICONS_ITEM.format(
  144. name=name,
  145. width=width,
  146. height=height,
  147. frame_rate=frame_rate,
  148. frame_count=frame_count,
  149. )
  150. )
  151. icons_c.write(ICONS_TEMPLATE_C_ICONS_ARRAY_END)
  152. icons_c.write(ICONS_TEMPLATE_C_FOOTER)
  153. icons_c.write("\n")
  154. # Create Public Header
  155. self.logger.debug(f"Creating header")
  156. icons_h = open(os.path.join(self.args.output_directory, "assets_icons.h"), "w")
  157. icons_h.write(ICONS_TEMPLATE_H_HEADER)
  158. for name, width, height, frame_rate, frame_count in icons:
  159. icons_h.write(ICONS_TEMPLATE_H_ICON_NAME.format(name=name))
  160. icons_h.write(ICONS_TEMPLATE_H_FOOTER)
  161. # Create Private Header
  162. icons_h_i = open(
  163. os.path.join(self.args.output_directory, "assets_icons_i.h"), "w"
  164. )
  165. icons_h_i.write(ICONS_TEMPLATE_H_I)
  166. self.logger.debug(f"Done")
  167. def icon2header(self, file):
  168. output = subprocess.check_output(["convert", file, "xbm:-"])
  169. assert output
  170. f = io.StringIO(output.decode().strip())
  171. width = int(f.readline().strip().split(" ")[2])
  172. height = int(f.readline().strip().split(" ")[2])
  173. data = f.read().strip().replace("\n", "").replace(" ", "").split("=")[1][:-1]
  174. return width, height, data
  175. def iconIsSupported(self, filename):
  176. extension = filename.lower().split(".")[-1]
  177. return extension in ICONS_SUPPORTED_FORMATS
  178. if __name__ == "__main__":
  179. Main()()