DWIN_ICO.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  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. return
  74. def _parseHeader(self, infile):
  75. maxEntries = 256
  76. count = 0
  77. validEntries = 0
  78. while count < maxEntries:
  79. rawBytes = infile.read(16)
  80. entry = Entry()
  81. entry.parseRawData(rawBytes)
  82. # check that it is valid: is offset nonzero?
  83. # Special case: treat 39 as valid
  84. if (entry.offset > 0) or (count == 39):
  85. validEntries += 1
  86. self.entries.append(entry)
  87. count += 1
  88. return
  89. def _splitEntryData(self, infile, outDir):
  90. print('Splitting Entry Data...')
  91. if 0 == len(self.entries):
  92. raise RuntimeError('.ico file is not loaded yet')
  93. # check for output dir:
  94. if not os.path.exists(outDir):
  95. os.mkdir(outDir)
  96. # keep a count
  97. count = 0
  98. for entry in self.entries:
  99. # Skip any empty entries. (Special handling of 39.)
  100. if entry.length == 0:
  101. count += 1
  102. continue
  103. # Seek file position, read length bytes, and write to new output file.
  104. print('%02d: offset: 0x%06x len: 0x%04x width: %d height: %d' %
  105. (count, entry.offset, entry.length, entry.width, entry.height))
  106. outfilename = os.path.join(outDir,
  107. '%03d-%s.jpg' % (count, _iconNames[count]))
  108. with open(outfilename, 'wb') as outfile:
  109. infile.seek(entry.offset)
  110. blob = infile.read(entry.length)
  111. outfile.write(blob)
  112. print('Wrote %d bytes to %s' % (entry.length, outfilename))
  113. count += 1
  114. return
  115. def createFile(self, iconDir, filename):
  116. '''Create a new .ico file from the contents of iconDir.
  117. The contents of iconDir are processed to get image
  118. resolution, and a new entry is created for each.
  119. Each filename must have a leading number followed by a
  120. dash, which is the icon index. E.g., "071-ICON_StepX.jpg".
  121. '''
  122. self.entries = [Entry() for i in range(0,256)]
  123. # 1. Scan icon directory and record all valid files
  124. print('Scanning icon directory', iconDir)
  125. count = 0
  126. for dirEntry in os.scandir(iconDir):
  127. if not dirEntry.is_file():
  128. print('...Ignoring', dirEntry.path)
  129. continue
  130. # process each file:
  131. try:
  132. index = int(dirEntry.name[0:3])
  133. if not (0 <= index <= 255):
  134. print('...Ignoring invalid index on', dirEntry.path)
  135. continue
  136. #dirEntry.path is iconDir/name
  137. w,h = getJpegResolution(dirEntry.path)
  138. length = dirEntry.stat().st_size
  139. e = self.entries[index]
  140. e.width = w
  141. e.height = h
  142. e.length = length
  143. e.filename = dirEntry.path
  144. count += 1
  145. except Exception as e:
  146. print('Whoops: ', e)
  147. pass
  148. print('...Scanned %d icon files' % (count))
  149. # 2. Scan over valid header entries and update offsets
  150. self._updateHeaderOffsets()
  151. # 3. Write out header to .ico file, the append each icon file
  152. self._combineAndWriteIcoFile(filename)
  153. print('Scanning done. %d icons included.' % (count))
  154. def _updateHeaderOffsets(self):
  155. """Iterate over all header entries and update their offsets.
  156. """
  157. offset = 256 * 16
  158. for i in range(0,256):
  159. e = self.entries[i]
  160. if e.length == 0:
  161. continue
  162. e.offset = offset
  163. offset += e.length
  164. #print('%03d: (%d x %d) len=%d off=%d' %
  165. # (i, e.width, e.height, e.length, e.offset))
  166. return
  167. def _combineAndWriteIcoFile(self, filename):
  168. """Write out final .ico file.
  169. All header entries are updated, so write out
  170. the final header contents, and concat each icon
  171. file to the .ico.
  172. """
  173. with open(filename, 'wb') as outfile:
  174. # 1. Write header directory
  175. for e in self.entries:
  176. outfile.write( e.serialize() )
  177. if outfile.tell() != 4096:
  178. raise RuntimeError('Header directory write failed. Not 4096 bytes')
  179. # 2. For each entry, concat the icon file data
  180. for e in self.entries:
  181. if 0 == e.length: continue
  182. guts = self._getFileContents(e.filename, e.length)
  183. outfile.write(guts)
  184. return
  185. def _getFileContents(self, filename, length):
  186. """Read contents of filename, and return bytes"""
  187. with open(filename, 'rb') as infile:
  188. contents = infile.read(length)
  189. if len(contents) != length:
  190. raise RuntimeError('Failed to read contents of', filename)
  191. return contents
  192. class Entry():
  193. '''Entry objects record resolution and size information
  194. about each icon stored in an ICO file.
  195. '''
  196. __slots__ = ('width', 'height', 'offset', 'length', 'filename')
  197. def __init__(self, w=0, h=0, length=0, offset=0):
  198. self.width = w
  199. self.height = h
  200. self.offset = offset
  201. self.length = length
  202. self.filename = None
  203. def parseRawData(self, rawEntryBytes):
  204. if len(rawEntryBytes) != 16:
  205. raise RuntimeError('Entry: data must be 16 bytes long')
  206. # Split data into bigendian fields
  207. (w, h, off, len3, len21, b1,b2,b3,b4,b5) = \
  208. struct.unpack('>HHLBHBBBBB', rawEntryBytes)
  209. self.width = w
  210. self.height = h
  211. self.offset = off
  212. self.length = len3 * 65536 + len21
  213. return
  214. def serialize(self):
  215. """Convert this Entry's information into a 16-byte
  216. .ico directory entry record. Return bytes object.
  217. """
  218. len21 = self.length % 65536
  219. len3 = self.length // 65536
  220. rawdata = struct.pack('>HHLBHBBBBB', self.width, self.height,
  221. self.offset, len3, len21,
  222. 0, 0, 0, 0, 0)
  223. return rawdata
  224. _iconNames = {
  225. 0 : 'ICON_LOGO',
  226. 1 : 'ICON_Print_0',
  227. 2 : 'ICON_Print_1',
  228. 3 : 'ICON_Prepare_0',
  229. 4 : 'ICON_Prepare_1',
  230. 5 : 'ICON_Control_0',
  231. 6 : 'ICON_Control_1',
  232. 7 : 'ICON_Leveling_0',
  233. 8 : 'ICON_Leveling_1',
  234. 9 : 'ICON_HotendTemp',
  235. 10 : 'ICON_BedTemp',
  236. 11 : 'ICON_Speed',
  237. 12 : 'ICON_Zoffset',
  238. 13 : 'ICON_Back',
  239. 14 : 'ICON_File',
  240. 15 : 'ICON_PrintTime',
  241. 16 : 'ICON_RemainTime',
  242. 17 : 'ICON_Setup_0',
  243. 18 : 'ICON_Setup_1',
  244. 19 : 'ICON_Pause_0',
  245. 20 : 'ICON_Pause_1',
  246. 21 : 'ICON_Continue_0',
  247. 22 : 'ICON_Continue_1',
  248. 23 : 'ICON_Stop_0',
  249. 24 : 'ICON_Stop_1',
  250. 25 : 'ICON_Bar',
  251. 26 : 'ICON_More',
  252. 27 : 'ICON_Axis',
  253. 28 : 'ICON_CloseMotor',
  254. 29 : 'ICON_Homing',
  255. 30 : 'ICON_SetHome',
  256. 31 : 'ICON_PLAPreheat',
  257. 32 : 'ICON_ABSPreheat',
  258. 33 : 'ICON_Cool',
  259. 34 : 'ICON_Language',
  260. 35 : 'ICON_MoveX',
  261. 36 : 'ICON_MoveY',
  262. 37 : 'ICON_MoveZ',
  263. 38 : 'ICON_Extruder',
  264. # no 39
  265. 40 : 'ICON_Temperature',
  266. 41 : 'ICON_Motion',
  267. 42 : 'ICON_WriteEEPROM',
  268. 43 : 'ICON_ReadEEPROM',
  269. 44 : 'ICON_ResumeEEPROM',
  270. 45 : 'ICON_Info',
  271. 46 : 'ICON_SetEndTemp',
  272. 47 : 'ICON_SetBedTemp',
  273. 48 : 'ICON_FanSpeed',
  274. 49 : 'ICON_SetPLAPreheat',
  275. 50 : 'ICON_SetABSPreheat',
  276. 51 : 'ICON_MaxSpeed',
  277. 52 : 'ICON_MaxAccelerated',
  278. 53 : 'ICON_MaxJerk',
  279. 54 : 'ICON_Step',
  280. 55 : 'ICON_PrintSize',
  281. 56 : 'ICON_Version',
  282. 57 : 'ICON_Contact',
  283. 58 : 'ICON_StockConfiguraton',
  284. 59 : 'ICON_MaxSpeedX',
  285. 60 : 'ICON_MaxSpeedY',
  286. 61 : 'ICON_MaxSpeedZ',
  287. 62 : 'ICON_MaxSpeedE',
  288. 63 : 'ICON_MaxAccX',
  289. 64 : 'ICON_MaxAccY',
  290. 65 : 'ICON_MaxAccZ',
  291. 66 : 'ICON_MaxAccE',
  292. 67 : 'ICON_MaxSpeedJerkX',
  293. 68 : 'ICON_MaxSpeedJerkY',
  294. 69 : 'ICON_MaxSpeedJerkZ',
  295. 70 : 'ICON_MaxSpeedJerkE',
  296. 71 : 'ICON_StepX',
  297. 72 : 'ICON_StepY',
  298. 73 : 'ICON_StepZ',
  299. 74 : 'ICON_StepE',
  300. 75 : 'ICON_Setspeed',
  301. 76 : 'ICON_SetZOffset',
  302. 77 : 'ICON_Rectangle',
  303. 78 : 'ICON_BLTouch',
  304. 79 : 'ICON_TempTooLow',
  305. 80 : 'ICON_AutoLeveling',
  306. 81 : 'ICON_TempTooHigh',
  307. 82 : 'ICON_NoTips_C',
  308. 83 : 'ICON_NoTips_E',
  309. 84 : 'ICON_Continue_C',
  310. 85 : 'ICON_Continue_E',
  311. 86 : 'ICON_Cancel_C',
  312. 87 : 'ICON_Cancel_E',
  313. 88 : 'ICON_Confirm_C',
  314. 89 : 'ICON_Confirm_E',
  315. 90 : 'ICON_Info_0',
  316. 91 : 'ICON_Info_1'
  317. }