icon.py 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. #-----------------------------------------------------------------------------
  2. # Copyright (c) 2013-2023, 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 macOS, 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
  19. import os.path
  20. import struct
  21. import PyInstaller.log as logging
  22. from PyInstaller import config
  23. from PyInstaller.compat import pywintypes, win32api
  24. from PyInstaller.building.icon import normalize_icon_type
  25. logger = logging.getLogger(__name__)
  26. RT_ICON = 3
  27. RT_GROUP_ICON = 14
  28. LOAD_LIBRARY_AS_DATAFILE = 2
  29. class Structure:
  30. def __init__(self):
  31. size = self._sizeInBytes = struct.calcsize(self._format_)
  32. self._fields_ = list(struct.unpack(self._format_, b'\000' * size))
  33. indexes = self._indexes_ = {}
  34. for i, nm in enumerate(self._names_):
  35. indexes[nm] = i
  36. def dump(self):
  37. logger.info("DUMP of %s", self)
  38. for name in self._names_:
  39. if not name.startswith('_'):
  40. logger.info("%20s = %s", name, getattr(self, name))
  41. logger.info("")
  42. def __getattr__(self, name):
  43. if name in self._names_:
  44. index = self._indexes_[name]
  45. return self._fields_[index]
  46. try:
  47. return self.__dict__[name]
  48. except KeyError as e:
  49. raise AttributeError(name) from e
  50. def __setattr__(self, name, value):
  51. if name in self._names_:
  52. index = self._indexes_[name]
  53. self._fields_[index] = value
  54. else:
  55. self.__dict__[name] = value
  56. def tostring(self):
  57. return struct.pack(self._format_, *self._fields_)
  58. def fromfile(self, file):
  59. data = file.read(self._sizeInBytes)
  60. self._fields_ = list(struct.unpack(self._format_, data))
  61. class ICONDIRHEADER(Structure):
  62. _names_ = "idReserved", "idType", "idCount"
  63. _format_ = "hhh"
  64. class ICONDIRENTRY(Structure):
  65. _names_ = ("bWidth", "bHeight", "bColorCount", "bReserved", "wPlanes", "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", "wBitCount", "dwBytesInRes", "nID")
  72. _format_ = "bbbbhhih"
  73. # An IconFile instance is created for each .ico file given.
  74. class IconFile:
  75. def __init__(self, path):
  76. self.path = 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(f'ERROR: Unable to open icon file {self.path}!')
  84. with file:
  85. self.entries = []
  86. self.images = []
  87. header = self.header = ICONDIRHEADER()
  88. header.fromfile(file)
  89. for i in range(header.idCount):
  90. entry = ICONDIRENTRY()
  91. entry.fromfile(file)
  92. self.entries.append(entry)
  93. for e in self.entries:
  94. file.seek(e.dwImageOffset, 0)
  95. self.images.append(file.read(e.dwBytesInRes))
  96. def grp_icon_dir(self):
  97. return self.header.tostring()
  98. def grp_icondir_entries(self, id=1):
  99. data = b''
  100. for entry in self.entries:
  101. e = GRPICONDIRENTRY()
  102. for n in e._names_[:-1]:
  103. setattr(e, n, getattr(entry, n))
  104. e.nID = id
  105. id = id + 1
  106. data = data + e.tostring()
  107. return data
  108. def CopyIcons_FromIco(dstpath, srcpath, id=1):
  109. """
  110. Use the Win API UpdateResource facility to apply the icon resource(s) to the .exe file.
  111. :param str dstpath: absolute path of the .exe file being built.
  112. :param str srcpath: list of 1 or more .ico file paths
  113. """
  114. icons = map(IconFile, srcpath)
  115. logger.debug("Copying icons from %s", srcpath)
  116. hdst = win32api.BeginUpdateResource(dstpath, 0)
  117. iconid = 1
  118. # Each step in the following enumerate() will instantiate an IconFile object, as a result of deferred execution
  119. # of the map() above.
  120. for i, f in enumerate(icons):
  121. data = f.grp_icon_dir()
  122. data = data + f.grp_icondir_entries(iconid)
  123. win32api.UpdateResource(hdst, RT_GROUP_ICON, i + 1, data)
  124. logger.debug("Writing RT_GROUP_ICON %d resource with %d bytes", i + 1, len(data))
  125. for data in f.images:
  126. win32api.UpdateResource(hdst, RT_ICON, iconid, data)
  127. logger.debug("Writing RT_ICON %d resource with %d bytes", iconid, len(data))
  128. iconid = iconid + 1
  129. win32api.EndUpdateResource(hdst, 0)
  130. def CopyIcons(dstpath, srcpath):
  131. """
  132. Called from building/api.py to handle icons. If the input was by --icon on the command line, srcpath is a single
  133. string. However, it is possible to modify the spec file adding icon=['foo.ico','bar.ico'] to the EXE() statement.
  134. In that case, srcpath is a list of strings.
  135. The string format is either path-to-.ico or path-to-.exe,n for n an integer resource index in the .exe. In either
  136. case, the path can be relative or absolute.
  137. """
  138. if isinstance(srcpath, (str, os.PathLike)):
  139. # Just a single string, make it a one-element list.
  140. srcpath = [srcpath]
  141. # Convert possible PathLike elements to strings to allow the splitter function to work.
  142. srcpath = [str(path) for path in srcpath]
  143. def splitter(s):
  144. """
  145. Convert "pathname" to tuple ("pathname", None)
  146. Convert "pathname,n" to tuple ("pathname", n)
  147. """
  148. try:
  149. srcpath, index = s.split(',')
  150. return srcpath.strip(), int(index)
  151. except ValueError:
  152. return s, None
  153. # split all the items in the list into tuples as above.
  154. srcpath = list(map(splitter, srcpath))
  155. if len(srcpath) > 1:
  156. # More than one icon source given. We currently handle multiple icons by calling CopyIcons_FromIco(), which only
  157. # allows .ico, but will convert to that format if needed.
  158. #
  159. # Note that a ",index" on a .ico is just ignored in the single or multiple case.
  160. srcs = []
  161. for s in srcpath:
  162. srcs.append(normalize_icon_type(s[0], ("ico",), "ico", config.CONF["workpath"]))
  163. return CopyIcons_FromIco(dstpath, srcs)
  164. # Just one source given.
  165. srcpath, index = srcpath[0]
  166. # Makes sure the icon exists and attempts to convert to the proper format if applicable
  167. srcpath = normalize_icon_type(srcpath, ("exe", "ico"), "ico", config.CONF["workpath"])
  168. srcext = os.path.splitext(srcpath)[1]
  169. # Handle the simple case of foo.ico, ignoring any index.
  170. if srcext.lower() == '.ico':
  171. return CopyIcons_FromIco(dstpath, [srcpath])
  172. # Single source is not .ico, presumably it is .exe (and if not, some error will occur).
  173. if index is not None:
  174. logger.debug("Copying icon from %s, %d", srcpath, index)
  175. else:
  176. logger.debug("Copying icons from %s", srcpath)
  177. try:
  178. # Attempt to load the .ico or .exe containing the icon into memory using the same mechanism as if it were a DLL.
  179. # If this fails for any reason (for example if the file does not exist or is not a .ico/.exe) then LoadLibraryEx
  180. # returns a null handle and win32api raises a unique exception with a win error code and a string.
  181. hsrc = win32api.LoadLibraryEx(srcpath, 0, LOAD_LIBRARY_AS_DATAFILE)
  182. except pywintypes.error as W32E:
  183. # We could continue with no icon (i.e., just return), but it seems best to terminate the build with a message.
  184. raise SystemExit(
  185. "ERROR: Unable to load icon file {}\n {} (Error code {})".format(srcpath, W32E.strerror, W32E.winerror)
  186. )
  187. hdst = win32api.BeginUpdateResource(dstpath, 0)
  188. if index is None:
  189. grpname = win32api.EnumResourceNames(hsrc, RT_GROUP_ICON)[0]
  190. elif index >= 0:
  191. grpname = win32api.EnumResourceNames(hsrc, RT_GROUP_ICON)[index]
  192. else:
  193. grpname = -index
  194. data = win32api.LoadResource(hsrc, RT_GROUP_ICON, grpname)
  195. win32api.UpdateResource(hdst, RT_GROUP_ICON, grpname, data)
  196. for iconname in win32api.EnumResourceNames(hsrc, RT_ICON):
  197. data = win32api.LoadResource(hsrc, RT_ICON, iconname)
  198. win32api.UpdateResource(hdst, RT_ICON, iconname, data)
  199. win32api.FreeLibrary(hsrc)
  200. win32api.EndUpdateResource(hdst, 0)
  201. if __name__ == "__main__":
  202. import sys
  203. dstpath = sys.argv[1]
  204. srcpath = sys.argv[2:]
  205. CopyIcons(dstpath, srcpath)