DWIN_ICO.py 11 KB

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