icon.py 9.6 KB

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