icon.py 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. #-----------------------------------------------------------------------------
  2. # Copyright (c) 2013-2021, PyInstaller Development Team.
  3. #
  4. # Distributed under the terms of the GNU General Public License (version 2
  5. # or later) with exception for distributing the bootloader.
  6. #
  7. # The full license is in the file COPYING.txt, distributed with this software.
  8. #
  9. # SPDX-License-Identifier: (GPL-2.0-or-later WITH Bootloader-exception)
  10. #-----------------------------------------------------------------------------
  11. '''
  12. The code in this module supports the --icon parameter in Windows.
  13. (For --icon support under OSX see building/osx.py.)
  14. The only entry point, called from api.py, is CopyIcons(), below.
  15. All the elaborate structure of classes that follows is used to
  16. support the operation of CopyIcons_FromIco(). None of these classes
  17. and globals are referenced outside this module.
  18. '''
  19. import os.path
  20. import struct
  21. from PyInstaller.compat import win32api, pywintypes
  22. from PyInstaller import config
  23. import PyInstaller.log as logging
  24. logger = logging.getLogger(__name__)
  25. RT_ICON = 3
  26. RT_GROUP_ICON = 14
  27. LOAD_LIBRARY_AS_DATAFILE = 2
  28. class Structure:
  29. def __init__(self):
  30. size = self._sizeInBytes = struct.calcsize(self._format_)
  31. self._fields_ = list(struct.unpack(self._format_, b'\000' * size))
  32. indexes = self._indexes_ = {}
  33. for i, nm in enumerate(self._names_):
  34. indexes[nm] = i
  35. def dump(self):
  36. logger.info("DUMP of %s", self)
  37. for name in self._names_:
  38. if not name.startswith('_'):
  39. logger.info("%20s = %s", name, getattr(self, name))
  40. logger.info("")
  41. def __getattr__(self, name):
  42. if name in self._names_:
  43. index = self._indexes_[name]
  44. return self._fields_[index]
  45. try:
  46. return self.__dict__[name]
  47. except KeyError as e:
  48. raise AttributeError(name) from e
  49. def __setattr__(self, name, value):
  50. if name in self._names_:
  51. index = self._indexes_[name]
  52. self._fields_[index] = value
  53. else:
  54. self.__dict__[name] = value
  55. def tostring(self):
  56. return struct.pack(self._format_, *self._fields_)
  57. def fromfile(self, file):
  58. data = file.read(self._sizeInBytes)
  59. self._fields_ = list(struct.unpack(self._format_, data))
  60. class ICONDIRHEADER(Structure):
  61. _names_ = "idReserved", "idType", "idCount"
  62. _format_ = "hhh"
  63. class ICONDIRENTRY(Structure):
  64. _names_ = ("bWidth", "bHeight", "bColorCount", "bReserved", "wPlanes",
  65. "wBitCount", "dwBytesInRes", "dwImageOffset")
  66. _format_ = "bbbbhhii"
  67. class GRPICONDIR(Structure):
  68. _names_ = "idReserved", "idType", "idCount"
  69. _format_ = "hhh"
  70. class GRPICONDIRENTRY(Structure):
  71. _names_ = ("bWidth", "bHeight", "bColorCount", "bReserved", "wPlanes",
  72. "wBitCount", "dwBytesInRes", "nID")
  73. _format_ = "bbbbhhih"
  74. # An IconFile instance is created for each .ico file given.
  75. class IconFile:
  76. def __init__(self, path):
  77. self.path = path
  78. if not os.path.isabs(path):
  79. self.path = os.path.join(config.CONF['specpath'], path)
  80. try:
  81. # The path is from the user parameter, don't trust it.
  82. file = open(self.path, "rb")
  83. except OSError:
  84. # The icon file can't be opened for some reason. Stop the
  85. # program with an informative message.
  86. raise SystemExit(
  87. 'Unable to open icon file {}'.format(path)
  88. )
  89. self.entries = []
  90. self.images = []
  91. header = self.header = ICONDIRHEADER()
  92. header.fromfile(file)
  93. for i in range(header.idCount):
  94. entry = ICONDIRENTRY()
  95. entry.fromfile(file)
  96. self.entries.append(entry)
  97. for e in self.entries:
  98. file.seek(e.dwImageOffset, 0)
  99. self.images.append(file.read(e.dwBytesInRes))
  100. def grp_icon_dir(self):
  101. return self.header.tostring()
  102. def grp_icondir_entries(self, id=1):
  103. data = b''
  104. for entry in self.entries:
  105. e = GRPICONDIRENTRY()
  106. for n in e._names_[:-1]:
  107. setattr(e, n, getattr(entry, n))
  108. e.nID = id
  109. id = id + 1
  110. data = data + e.tostring()
  111. return data
  112. def CopyIcons_FromIco(dstpath, srcpath, id=1):
  113. '''
  114. Use the Win API UpdateResource facility to apply the icon
  115. resource(s) to the .exe file.
  116. :param str dstpath: absolute path of the .exe file being built.
  117. :param str srcpath: list of 1 or more .ico file paths
  118. '''
  119. icons = map(IconFile, srcpath)
  120. logger.info("Copying icons from %s", srcpath)
  121. hdst = win32api.BeginUpdateResource(dstpath, 0)
  122. iconid = 1
  123. # Each step in the following enumerate() will instantiate an IconFile
  124. # object, as a result of deferred execution of the map() above.
  125. for i, f in enumerate(icons):
  126. data = f.grp_icon_dir()
  127. data = data + f.grp_icondir_entries(iconid)
  128. win32api.UpdateResource(hdst, RT_GROUP_ICON, i, data)
  129. logger.info("Writing RT_GROUP_ICON %d resource with %d bytes", i, len(data))
  130. for data in f.images:
  131. win32api.UpdateResource(hdst, RT_ICON, iconid, data)
  132. logger.info("Writing RT_ICON %d resource with %d bytes", iconid, len(data))
  133. iconid = iconid + 1
  134. win32api.EndUpdateResource(hdst, 0)
  135. def CopyIcons(dstpath, srcpath):
  136. '''
  137. Called from building/api.py to handle icons. If the input was by
  138. --icon on the command line, srcpath is a single string. However it
  139. is possible to modify the spec file adding icon=['foo.ico','bar.ico']
  140. to the EXE() statement. In that case, srcpath is a list of strings.
  141. The string format is either path-to-.ico or path-to-.exe,n for n an
  142. integer resource index in the .exe. In either case the path can be
  143. relative or absolute.
  144. '''
  145. if isinstance(srcpath, str):
  146. # just a single string, make it a one-element list
  147. srcpath = [ srcpath ]
  148. def splitter(s):
  149. '''
  150. Convert "pathname" to tuple ("pathname", None)
  151. Convert "pathname,n" to tuple ("pathname", n)
  152. '''
  153. try:
  154. srcpath, index = s.split(',')
  155. return srcpath.strip(), int(index)
  156. except ValueError:
  157. return s, None
  158. # split all the items in the list into tuples as above.
  159. srcpath = list(map(splitter, srcpath))
  160. if len(srcpath) > 1:
  161. # More than one icon source given. We currently handle multiple
  162. # icons by calling CopyIcons_FromIco(), which only allows .ico.
  163. # In principle we could accept a mix of .ico and .exe, but it
  164. # would complicate things. If you need it submit a pull request.
  165. #
  166. # Note that a ",index" on a .ico is just ignored in the single
  167. # or multiple case.
  168. srcs = []
  169. for s in srcpath:
  170. e = os.path.splitext(s[0])[1]
  171. if e.lower() != '.ico':
  172. raise ValueError('Multiple icons supported only from .ico files')
  173. srcs.append(s[0])
  174. return CopyIcons_FromIco(dstpath, srcs)
  175. # Just one source given.
  176. srcpath,index = srcpath[0]
  177. srcext = os.path.splitext(srcpath)[1]
  178. # Handle the simple case of foo.ico, ignoring any ,index.
  179. if srcext.lower() == '.ico':
  180. return CopyIcons_FromIco(dstpath, [srcpath])
  181. # Single source is not .ico, presumably it is .exe (and if not, some
  182. # error will occur). If relative, make it relative to the .spec file.
  183. if not os.path.isabs(srcpath):
  184. srcpath = os.path.join(config.CONF['specpath'], srcpath)
  185. if index is not None:
  186. logger.info("Copying icon from %s, %d", srcpath, index)
  187. else:
  188. logger.info("Copying icons from %s", srcpath)
  189. # Bail out quickly if the input is invalid. Letting images in the wrong
  190. # format be passed to Window's API gives very cryptic error messages as
  191. # it's generally unclear why PyInstaller would treat an image file as an
  192. # executable.
  193. if srcext != ".exe":
  194. raise ValueError(
  195. f"Received icon path '{srcpath}' which exists but is not in the "
  196. f"correct format. On Windows, only '.ico' images or other "
  197. f"'.exe' files may be used as icons. Please convert your "
  198. f"'{srcext}' file to a '.ico' then try again."
  199. )
  200. try:
  201. # Attempt to load the .ico or .exe containing the icon into memory
  202. # using the same mechanism as if it were a DLL. If this fails for
  203. # any reason (for example if the file does not exist or is not a
  204. # .ico/.exe) then LoadLibraryEx returns a null handle and win32api
  205. # raises a unique exception with a win error code and a string.
  206. hsrc = win32api.LoadLibraryEx(srcpath, 0, LOAD_LIBRARY_AS_DATAFILE)
  207. except pywintypes.error as W32E:
  208. # We could continue with no icon (i.e. just return) however it seems
  209. # best to terminate the build with a message.
  210. raise SystemExit(
  211. "Unable to load icon file {}\n {} (Error code {})".format(
  212. srcpath, W32E.strerror, W32E.winerror)
  213. )
  214. hdst = win32api.BeginUpdateResource(dstpath, 0)
  215. if index is None:
  216. grpname = win32api.EnumResourceNames(hsrc, RT_GROUP_ICON)[0]
  217. elif index >= 0:
  218. grpname = win32api.EnumResourceNames(hsrc, RT_GROUP_ICON)[index]
  219. else:
  220. grpname = -index
  221. data = win32api.LoadResource(hsrc, RT_GROUP_ICON, grpname)
  222. win32api.UpdateResource(hdst, RT_GROUP_ICON, grpname, data)
  223. for iconname in win32api.EnumResourceNames(hsrc, RT_ICON):
  224. data = win32api.LoadResource(hsrc, RT_ICON, iconname)
  225. win32api.UpdateResource(hdst, RT_ICON, iconname, data)
  226. win32api.FreeLibrary(hsrc)
  227. win32api.EndUpdateResource(hdst, 0)
  228. if __name__ == "__main__":
  229. import sys
  230. dstpath = sys.argv[1]
  231. srcpath = sys.argv[2:]
  232. CopyIcons(dstpath, srcpath)