DWIN_ICO.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  1. # DWIN_ICO
  2. # - Dissect and create DWIN .ico files for their LCD displays.
  3. #
  4. # Copyright (c) 2020 Brent Burton
  5. #
  6. # This program is free software: you can redistribute it and/or modify
  7. # it under the terms of the GNU General Public License as published by
  8. # the Free Software Foundation, either version 3 of the License, or
  9. # (at your option) any later version.
  10. #
  11. # This program is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License
  17. # along with this program. If not, see <https://www.gnu.org/licenses/>.
  18. #----------------------------------------------------------------
  19. #
  20. # This is not a normal Microsoft .ICO file, but it has a similar
  21. # structure for containing a number of icon images. Each icon is
  22. # a small JPG file.
  23. #
  24. # The file has a directory header containing fixed-length
  25. # records, and each record points to its data at an offset later
  26. # in the file.
  27. #
  28. # The directory entries are 16 bytes each, and the entire
  29. # directory is 4KB (0 - 0x1000). This supports 256 entries.
  30. #
  31. # Multibyte values are in Big Endian format.
  32. #
  33. # Header: (offset 0x0)
  34. # W H offset ?? len ?? ??
  35. # Entry 0: xxxx xxxx 00001000 xx 10a2 00 00000000
  36. # Entry 1: xxxx xxxx 000020a2 xx 0eac 00 00000000
  37. # Entry 2: xxxx xxxx 00002f4e xx 0eaa 00 00000000
  38. # ...
  39. # 0x00001000: ffd8 ffe1 0018 ... jpeg exif and data follow .. ffd9
  40. # 0x000020a2: ffd8 ffe1 ...
  41. # ...rest of ICO entries' data...
  42. #
  43. # Header structure:
  44. # Offset Len What
  45. # 0 2 width
  46. # 2 2 height
  47. # 4 4 file byte position from SEEK_BEG
  48. # 8 3 length of data
  49. # 11 5 ??? all zeroes
  50. #
  51. # Other notes:
  52. # * The index of each icon corresponds to the Icon number in dwin.h
  53. # * One exception is number 39: that header entry is blank, and dwin.h
  54. # does not define a name for 39. This is specially handled to
  55. # prevent reordering stock icons.
  56. import os
  57. import struct
  58. from PIL import Image
  59. def getJpegResolution(jpegFile):
  60. """Returns a 2-tuple containing the jpegFile's (width, height).
  61. """
  62. img = Image.open(jpegFile)
  63. return img.size
  64. class DWIN_ICO_File():
  65. def __init__(self):
  66. self.entries = [] # list of header entries
  67. def splitFile(self, filename, outDir):
  68. if not filename[-4:].lower() == '.ico':
  69. raise RuntimeError('Input file must end in .ico')
  70. with open(filename, 'rb') as infile:
  71. self._parseHeader(infile)
  72. self._splitEntryData(infile, outDir)
  73. def _parseHeader(self, infile):
  74. maxEntries = 256
  75. count = 0
  76. icon_nums = _iconNames.keys()
  77. while count < maxEntries:
  78. rawBytes = infile.read(16)
  79. entry = Entry()
  80. entry.parseRawData(rawBytes)
  81. # check that it is valid: is offset nonzero?
  82. # Special case: treat missing numbers as valid
  83. if (entry.offset > 0) or count not in icon_nums:
  84. self.entries.append(entry)
  85. count += 1
  86. def _splitEntryData(self, infile, outDir):
  87. print('Splitting Entry Data...')
  88. if 0 == len(self.entries):
  89. raise RuntimeError('.ico file is not loaded yet')
  90. # check for output dir:
  91. if not os.path.exists(outDir):
  92. os.mkdir(outDir)
  93. # keep a count
  94. count = 0
  95. for entry in self.entries:
  96. # Skip any empty entries. (Special handling of 39.)
  97. if entry.length == 0:
  98. count += 1
  99. continue
  100. outfilename = os.path.join(outDir, '%03d-ICON_%s.jpg' % (count, _iconNames.get(count, "UNKNOWN")))
  101. with open(outfilename, 'wb') as outfile:
  102. infile.seek(entry.offset)
  103. blob = infile.read(entry.length)
  104. outfile.write(blob)
  105. # Seek file position, read length bytes, and write to new output file.
  106. print('(%3d: width=%3d height=%3d offset=%6d len=%4d) ... %s' %
  107. (count, entry.width, entry.height, entry.offset, entry.length, os.path.basename(outfilename)))
  108. count += 1
  109. def createFile(self, iconDir, filename):
  110. """Create a new .ico file from the contents of iconDir.
  111. The contents of iconDir are processed to get image
  112. resolution, and a new entry is created for each.
  113. Each filename must have a leading number followed by a
  114. dash, which is the icon index. E.g., "071-ICON_StepX.jpg".
  115. """
  116. self.entries = [Entry() for i in range(0,256)]
  117. # 1. Scan icon directory and record all valid files
  118. print('Scanning icon directory', iconDir)
  119. count = 0
  120. for dirEntry in os.scandir(iconDir):
  121. if not dirEntry.is_file():
  122. print('...Ignoring', dirEntry.path)
  123. continue
  124. # process each file:
  125. try:
  126. index = int(dirEntry.name[0:3])
  127. if not (0 <= index <= 255):
  128. print('...Ignoring invalid index on', dirEntry.path)
  129. continue
  130. # dirEntry.path is iconDir/name
  131. w,h = getJpegResolution(dirEntry.path)
  132. length = dirEntry.stat().st_size
  133. e = self.entries[index]
  134. e.width = w
  135. e.height = h
  136. e.length = length
  137. e.filename = dirEntry.path
  138. count += 1
  139. except Exception as e:
  140. print('Whoops: ', e)
  141. pass
  142. print('...Scanned %d icon files' % (count))
  143. # 2. Scan over valid header entries and update offsets
  144. self._updateHeaderOffsets()
  145. # 3. Write out header to .ico file, the append each icon file
  146. self._combineAndWriteIcoFile(filename)
  147. print('Scanning done. %d icons included.' % (count))
  148. def _updateHeaderOffsets(self):
  149. """Iterate over all header entries and update their offsets.
  150. """
  151. offset = 256 * 16
  152. for i in range(0,256):
  153. e = self.entries[i]
  154. if e.length == 0:
  155. continue
  156. e.offset = offset
  157. offset += e.length
  158. # print('%03d: (%d x %d) len=%d off=%d' %
  159. # (i, e.width, e.height, e.length, e.offset))
  160. def _combineAndWriteIcoFile(self, filename):
  161. """Write out final .ico file.
  162. All header entries are updated, so write out
  163. the final header contents, and concat each icon
  164. file to the .ico.
  165. """
  166. with open(filename, 'wb') as outfile:
  167. # 1. Write header directory
  168. for e in self.entries:
  169. outfile.write( e.serialize() )
  170. if outfile.tell() != 4096:
  171. raise RuntimeError('Header directory write failed. Not 4096 bytes')
  172. # 2. For each entry, concat the icon file data
  173. for e in self.entries:
  174. if 0 == e.length: continue
  175. guts = self._getFileContents(e.filename, e.length)
  176. outfile.write(guts)
  177. def _getFileContents(self, filename, length):
  178. """Read contents of filename, and return bytes"""
  179. with open(filename, 'rb') as infile:
  180. contents = infile.read(length)
  181. if len(contents) != length:
  182. raise RuntimeError('Failed to read contents of', filename)
  183. return contents
  184. class Entry():
  185. """Entry objects record resolution and size information
  186. about each icon stored in an ICO file.
  187. """
  188. __slots__ = ('width', 'height', 'offset', 'length', 'filename')
  189. def __init__(self, w=0, h=0, length=0, offset=0, filename=None):
  190. self.width = w
  191. self.height = h
  192. self.offset = offset
  193. self.length = length
  194. self.filename = filename
  195. def parseRawData(self, rawEntryBytes):
  196. if len(rawEntryBytes) != 16:
  197. raise RuntimeError('Entry: data must be 16 bytes long')
  198. # Split data into bigendian fields
  199. (w, h, off, len3, len21, b1,b2,b3,b4,b5) = \
  200. struct.unpack('>HHLBHBBBBB', rawEntryBytes)
  201. self.width = w
  202. self.height = h
  203. self.offset = off
  204. self.length = len3 * 65536 + len21
  205. def serialize(self):
  206. """Convert this Entry's information into a 16-byte
  207. .ico directory entry record. Return bytes object.
  208. """
  209. len21 = self.length % 65536
  210. len3 = self.length // 65536
  211. rawdata = struct.pack('>HHLBHBBBBB', self.width, self.height,
  212. self.offset, len3, len21,
  213. 0, 0, 0, 0, 0)
  214. return rawdata
  215. _iconNames = {
  216. 0 : "LOGO_Creality",
  217. 1 : "Print_0",
  218. 2 : "Print_1",
  219. 3 : "Prepare_0",
  220. 4 : "Prepare_1",
  221. 5 : "Control_0",
  222. 6 : "Control_1",
  223. 7 : "Leveling_0",
  224. 8 : "Leveling_1",
  225. 9 : "HotendTemp",
  226. 10 : "BedTemp",
  227. 11 : "Speed",
  228. 12 : "Zoffset",
  229. 13 : "Back",
  230. 14 : "File",
  231. 15 : "PrintTime",
  232. 16 : "RemainTime",
  233. 17 : "Setup_0",
  234. 18 : "Setup_1",
  235. 19 : "Pause_0",
  236. 20 : "Pause_1",
  237. 21 : "Continue_0",
  238. 22 : "Continue_1",
  239. 23 : "Stop_0",
  240. 24 : "Stop_1",
  241. 25 : "Bar",
  242. 26 : "More",
  243. 27 : "Axis",
  244. 28 : "CloseMotor",
  245. 29 : "Homing",
  246. 30 : "SetHome",
  247. 31 : "PLAPreheat",
  248. 32 : "ABSPreheat",
  249. 33 : "Cool",
  250. 34 : "Language",
  251. 35 : "MoveX",
  252. 36 : "MoveY",
  253. 37 : "MoveZ",
  254. 38 : "Extruder",
  255. # Skip 39
  256. 40 : "Temperature",
  257. 41 : "Motion",
  258. 42 : "WriteEEPROM",
  259. 43 : "ReadEEPROM",
  260. 44 : "ResetEEPROM",
  261. 45 : "Info",
  262. 46 : "SetEndTemp",
  263. 47 : "SetBedTemp",
  264. 48 : "FanSpeed",
  265. 49 : "SetPLAPreheat",
  266. 50 : "SetABSPreheat",
  267. 51 : "MaxSpeed",
  268. 52 : "MaxAccelerated",
  269. 53 : "MaxJerk",
  270. 54 : "Step",
  271. 55 : "PrintSize",
  272. 56 : "Version",
  273. 57 : "Contact",
  274. 58 : "StockConfiguraton",
  275. 59 : "MaxSpeedX",
  276. 60 : "MaxSpeedY",
  277. 61 : "MaxSpeedZ",
  278. 62 : "MaxSpeedE",
  279. 63 : "MaxAccX",
  280. 64 : "MaxAccY",
  281. 65 : "MaxAccZ",
  282. 66 : "MaxAccE",
  283. 67 : "MaxSpeedJerkX",
  284. 68 : "MaxSpeedJerkY",
  285. 69 : "MaxSpeedJerkZ",
  286. 70 : "MaxSpeedJerkE",
  287. 71 : "StepX",
  288. 72 : "StepY",
  289. 73 : "StepZ",
  290. 74 : "StepE",
  291. 75 : "Setspeed",
  292. 76 : "SetZOffset",
  293. 77 : "Rectangle",
  294. 78 : "BLTouch",
  295. 79 : "TempTooLow",
  296. 80 : "AutoLeveling",
  297. 81 : "TempTooHigh",
  298. 82 : "NoTips_C",
  299. 83 : "NoTips_E",
  300. 84 : "Continue_C",
  301. 85 : "Continue_E",
  302. 86 : "Cancel_C",
  303. 87 : "Cancel_E",
  304. 88 : "Confirm_C",
  305. 89 : "Confirm_E",
  306. 90 : "Info_0",
  307. 91 : "Info_1",
  308. 92 : "DegreesC",
  309. 93 : "Printer_0",
  310. 200 : "Checkbox_F",
  311. 201 : "Checkbox_T",
  312. 202 : "Fade",
  313. 203 : "Mesh",
  314. 204 : "Tilt",
  315. 205 : "Brightness",
  316. 206 : "Probe",
  317. 249 : "AxisD",
  318. 250 : "AxisBR",
  319. 251 : "AxisTR",
  320. 252 : "AxisBL",
  321. 253 : "AxisTL",
  322. 254 : "AxisC"
  323. }