splash.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  1. # -----------------------------------------------------------------------------
  2. # Copyright (c) 2005-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. import io
  12. import os
  13. import re
  14. import struct
  15. from PyInstaller import log as logging
  16. from PyInstaller.archive.writers import SplashWriter
  17. from PyInstaller.building import splash_templates
  18. from PyInstaller.building.datastruct import TOC, Target
  19. from PyInstaller.building.utils import _check_guts_eq, _check_guts_toc, misc
  20. from PyInstaller.compat import is_darwin
  21. from PyInstaller.utils.hooks import exec_statement
  22. from PyInstaller.utils.hooks.tcl_tk import (TK_ROOTNAME, collect_tcl_tk_files, find_tcl_tk_shared_libs)
  23. try:
  24. from PIL import Image as PILImage
  25. except ImportError:
  26. PILImage = None
  27. logger = logging.getLogger(__name__)
  28. # These requirement files are checked against the current splash screen script. If you wish to modify the splash screen
  29. # and run into tcl errors/bad behavior, this is a good place to start and add components your implementation of the
  30. # splash screen might use.
  31. splash_requirements = [
  32. # prepended tcl/tk binaries
  33. os.path.join(TK_ROOTNAME, "license.terms"),
  34. os.path.join(TK_ROOTNAME, "text.tcl"),
  35. os.path.join(TK_ROOTNAME, "tk.tcl"),
  36. # Used for customizable font
  37. os.path.join(TK_ROOTNAME, "ttk", "ttk.tcl"),
  38. os.path.join(TK_ROOTNAME, "ttk", "fonts.tcl"),
  39. os.path.join(TK_ROOTNAME, "ttk", "cursors.tcl"),
  40. os.path.join(TK_ROOTNAME, "ttk", "utils.tcl"),
  41. ]
  42. class Splash(Target):
  43. """
  44. Bundles the required resources for the splash screen into a file, which will be included in the CArchive.
  45. A Splash has two outputs, one is itself and one is sored in splash.binaries. Both need to be passed to other
  46. build targets in order to enable the splash screen.
  47. """
  48. typ = 'SPLASH'
  49. def __init__(self, image_file, binaries, datas, **kwargs):
  50. """
  51. :param str image_file:
  52. A path-like object to the image to be used. Only the PNG file format is supported.
  53. .. note:: If a different file format is supplied and PIL (Pillow) is installed, the file will be converted
  54. automatically.
  55. .. note:: *Windows*: Due to the implementation, the color Magenta/ RGB(255, 0, 255) must not be used in the
  56. image or text.
  57. .. note:: If PIL (Pillow) is installed and the image is bigger than max_img_size, the image will be resized
  58. to fit into the specified area.
  59. :param TOC binaries:
  60. The TOC of binaries the Analysis build target found. This TOC includes all extensionmodules and their
  61. dependencies. This is required to figure out, if the users program uses tkinter.
  62. :param TOC datas:
  63. The TOC of data the Analysis build target found. This TOC includes all data-file dependencies of the
  64. modules. This is required to check if all splash screen requirements can be bundled.
  65. :keyword text_pos:
  66. An optional 2x integer tuple that represents the origin of the text on the splash screen image. The
  67. origin of the text is its lower left corner. A unit in the respective coordinate system is a pixel of the
  68. image, its origin lies in the top left corner of the image. This parameter also acts like a switch for
  69. the text feature. If omitted, no text will be displayed on the splash screen. This text will be used to
  70. show textual progress in onefile mode.
  71. :type text_pos: Tuple[int, int]
  72. :keyword text_size:
  73. The desired size of the font. If the size argument is a positive number, it is interpreted as a size in
  74. points. If size is a negative number, its absolute value is interpreted as a size in pixels. Default: ``12``
  75. :type text_size: int
  76. :keyword text_font:
  77. An optional name of a font for the text. This font must be installed on the user system, otherwise the
  78. system default font is used. If this parameter is omitted, the default font is also used.
  79. :keyword text_color:
  80. An optional color for the text. Either RGB HTML notation or color names are supported. Default: black
  81. (Windows: Due to a implementation issue the color magenta/ rgb(255, 0, 255) is forbidden)
  82. :type text_color: str
  83. :keyword text_default:
  84. The default text which will be displayed before the extraction starts. Default: "Initializing"
  85. :type text_default: str
  86. :keyword full_tk:
  87. By default Splash bundles only the necessary files for the splash screen (some tk components). This
  88. options enables adding full tk and making it a requirement, meaning all tk files will be unpacked before
  89. the splash screen can be started. This is useful during development of the splash screen script.
  90. Default: ``False``
  91. :type full_tk: bool
  92. :keyword minify_script:
  93. The splash screen is created by executing an Tcl/Tk script. This option enables minimizing the script,
  94. meaning removing all non essential parts from the script. Default: True
  95. :keyword rundir:
  96. The folder name in which tcl/tk will be extracted at runtime. There should be no matching folder in your
  97. application to avoid conflicts. Default: ``__splash``
  98. :type rundir: str
  99. :keyword name:
  100. An optional alternative filename for the .res file. If not specified, a name is generated.
  101. :type name: str
  102. :keyword script_name:
  103. An optional alternative filename for the Tcl script, that will be generated. If not specified, a name is
  104. generated.
  105. :type script_name: str
  106. :keyword max_img_size:
  107. Maximum size of the splash screen image as a tuple. If the supplied image exceeds this limit, it will be
  108. resized to fit the maximum width (to keep the original aspect ratio). This option can be disabled by
  109. setting it to None. Default: (760, 480)
  110. :type max_img_size: Tuple[int, int]
  111. """
  112. from ..config import CONF
  113. Target.__init__(self)
  114. # Splash screen is not supported on macOS. It operates in a secondary thread and macOS disallows UI operations
  115. # in any thread other than main.
  116. if is_darwin:
  117. raise SystemExit("Splash screen is not supported on macOS.")
  118. # Make image path relative to .spec file
  119. if not os.path.isabs(image_file):
  120. image_file = os.path.join(CONF['specpath'], image_file)
  121. image_file = os.path.normpath(image_file)
  122. if not os.path.exists(image_file):
  123. raise ValueError("Image file '%s' not found" % image_file)
  124. # Copy all arguments
  125. self.image_file = image_file
  126. self.full_tk = kwargs.get("full_tk", False)
  127. self.name = kwargs.get("name", None)
  128. self.script_name = kwargs.get("script_name", None)
  129. self.minify_script = kwargs.get("minify_script", True)
  130. self.rundir = kwargs.get("rundir", None)
  131. self.max_img_size = kwargs.get("max_img_size", (760, 480))
  132. # text options
  133. self.text_pos = kwargs.get("text_pos", None)
  134. self.text_size = kwargs.get("text_size", 12)
  135. self.text_font = kwargs.get("text_font", "TkDefaultFont")
  136. self.text_color = kwargs.get("text_color", "black")
  137. self.text_default = kwargs.get("text_default", "Initializing")
  138. # Save the generated file separately so that it is not necessary to generate the data again and again
  139. root = os.path.splitext(self.tocfilename)[0]
  140. if self.name is None:
  141. self.name = root + '.res'
  142. if self.script_name is None:
  143. self.script_name = root + '_script.tcl'
  144. if self.rundir is None:
  145. self.rundir = self._find_rundir(binaries + datas)
  146. # Internal variables
  147. try:
  148. # Do not import _tkinter at the toplevel, because on some systems _tkinter will fail to load, since it is
  149. # not installed. This would cause a runtime error in PyInstaller, since this module is imported from
  150. # build_main.py, instead we just want to inform the user that the splash screen feature is not supported on
  151. # his platform
  152. import _tkinter
  153. self._tkinter_module = _tkinter
  154. self._tkinter_file = self._tkinter_module.__file__
  155. except ModuleNotFoundError:
  156. raise SystemExit(
  157. "You platform does not support the splash screen feature, since tkinter is not installed. Please "
  158. "install tkinter and try again."
  159. )
  160. # Calculated / analysed values
  161. self.uses_tkinter = self._uses_tkinter(binaries)
  162. self.script = self.generate_script()
  163. self.tcl_lib, self.tk_lib = find_tcl_tk_shared_libs(self._tkinter_file)
  164. if is_darwin:
  165. # Outdated Tcl/Tk 8.5 system framework is not supported. Depending on macOS version, the library path will
  166. # come up empty (hidden system libraries on Big Sur), or will be
  167. # [/System]/Library/Frameworks/Tcl.framework/Tcl
  168. if self.tcl_lib[1] is None or 'Library/Frameworks/Tcl.framework' in self.tcl_lib[1]:
  169. raise SystemExit("The splash screen feature does not support macOS system framework version of Tcl/Tk.")
  170. # Check if tcl/tk was found
  171. assert all(self.tcl_lib)
  172. assert all(self.tk_lib)
  173. logger.debug("Use Tcl Library from %s and Tk From %s" % (self.tcl_lib, self.tk_lib))
  174. self.splash_requirements = set([self.tcl_lib[0], self.tk_lib[0]] + splash_requirements)
  175. logger.info("Collect tcl/tk binaries for the splash screen")
  176. tcltk_tree = collect_tcl_tk_files(self._tkinter_file)
  177. if self.full_tk:
  178. # The user wants a full copy of tk, so make all tk files a requirement.
  179. self.splash_requirements.update(toc[0] for toc in tcltk_tree)
  180. self.binaries = TOC()
  181. if not self.uses_tkinter:
  182. # The user's script does not use tkinter, so we need to provide a TOC of all necessary files add the shared
  183. # libraries to the binaries.
  184. self.binaries.append((self.tcl_lib[0], self.tcl_lib[1], 'BINARY'))
  185. self.binaries.append((self.tk_lib[0], self.tk_lib[1], 'BINARY'))
  186. # Only add the intersection of the required and the collected resources, or add all entries if full_tk is
  187. # true.
  188. self.binaries.extend(toc for toc in tcltk_tree if toc[0] in self.splash_requirements)
  189. # Check if all requirements were found.
  190. fnames = [toc[0] for toc in (binaries + datas + self.binaries)]
  191. def _filter(_item):
  192. if _item not in fnames:
  193. # Item is not bundled, so warn the user about it. This actually may happen on some tkinter installations
  194. # that are missing the license.terms file.
  195. logger.warning(
  196. "The local Tcl/Tk installation is missing the file %s. The behavior of the splash screen is "
  197. "therefore undefined and may be unsupported." % _item
  198. )
  199. return False
  200. return True
  201. # Remove all files which were not found.
  202. self.splash_requirements = set(filter(_filter, self.splash_requirements))
  203. # Test if the tcl/tk version is supported by the bootloader.
  204. self.test_tk_version()
  205. logger.debug("Splash Requirements: %s" % self.splash_requirements)
  206. self.__postinit__()
  207. _GUTS = (
  208. # input parameters
  209. ('image_file', _check_guts_eq),
  210. ('name', _check_guts_eq),
  211. ('script_name', _check_guts_eq),
  212. ('text_pos', _check_guts_eq),
  213. ('text_size', _check_guts_eq),
  214. ('text_font', _check_guts_eq),
  215. ('text_color', _check_guts_eq),
  216. ('text_default', _check_guts_eq),
  217. ('full_tk', _check_guts_eq),
  218. ('minify_script', _check_guts_eq),
  219. ('rundir', _check_guts_eq),
  220. ('max_img_size', _check_guts_eq),
  221. # calculated/analysed values
  222. ('uses_tkinter', _check_guts_eq),
  223. ('script', _check_guts_eq),
  224. ('tcl_lib', _check_guts_eq),
  225. ('tk_lib', _check_guts_eq),
  226. ('splash_requirements', _check_guts_eq),
  227. ('binaries', _check_guts_toc),
  228. # internal value
  229. # Check if the tkinter installation changed. This is theoretically possible if someone uses two different python
  230. # installations of the same version.
  231. ('_tkinter_file', _check_guts_eq),
  232. )
  233. def _check_guts(self, data, last_build):
  234. if Target._check_guts(self, data, last_build):
  235. return True
  236. # Check if the image has been modified.
  237. if misc.mtime(self.image_file) > last_build:
  238. logger.info("Building %s because file %s changed", self.tocbasename, self.image_file)
  239. return True
  240. return False
  241. def assemble(self):
  242. logger.info("Building Splash %s" % self.name)
  243. # Function to resize a given image to fit into the area defined by max_img_size.
  244. def _resize_image(_image, _orig_size):
  245. if PILImage:
  246. _w, _h = _orig_size
  247. _ratio_w = self.max_img_size[0] / _w
  248. if _ratio_w < 1:
  249. # Image width exceeds limit
  250. _h = int(_h * _ratio_w)
  251. _w = self.max_img_size[0]
  252. _ratio_h = self.max_img_size[1] / _h
  253. if _ratio_h < 1:
  254. # Image height exceeds limit
  255. _w = int(_w * _ratio_h)
  256. _h = self.max_img_size[1]
  257. # If a file is given it will be open
  258. if isinstance(_image, PILImage.Image):
  259. _img = _image
  260. else:
  261. _img = PILImage.open(_image)
  262. _img_resized = _img.resize((_w, _h))
  263. # Save image into a stream
  264. _image_stream = io.BytesIO()
  265. _img_resized.save(_image_stream, format='PNG')
  266. _img.close()
  267. _img_resized.close()
  268. _image_data = _image_stream.getvalue()
  269. logger.info(
  270. "Resized image %s from dimensions %s to (%d, %d)" % (self.image_file, str(_orig_size), _w, _h)
  271. )
  272. return _image_data
  273. else:
  274. raise ValueError(
  275. "The splash image dimensions (w: %d, h: %d) exceed max_img_size (w: %d, h:%d), but the image "
  276. "cannot be resized due to missing PIL.Image! Either install the Pillow package, adjust the "
  277. "max_img_size, or use an image of compatible dimensions." %
  278. (_orig_size[0], _orig_size[1], self.max_img_size[0], self.max_img_size[1])
  279. )
  280. # Open image file
  281. image_file = open(self.image_file, 'rb')
  282. # Check header of the file to identify it
  283. if image_file.read(8) == b'\x89PNG\r\n\x1a\n':
  284. # self.image_file is a PNG file
  285. image_file.seek(16)
  286. img_size = (struct.unpack("!I", image_file.read(4))[0], struct.unpack("!I", image_file.read(4))[0])
  287. if img_size > self.max_img_size:
  288. # The image exceeds the maximum image size, so resize it
  289. image = _resize_image(self.image_file, img_size)
  290. else:
  291. image = os.path.abspath(self.image_file)
  292. elif PILImage:
  293. # Pillow is installed, meaning the image can be converted automatically
  294. img = PILImage.open(self.image_file, mode='r')
  295. if img.size > self.max_img_size:
  296. image = _resize_image(img, img.size)
  297. else:
  298. image_data = io.BytesIO()
  299. img.save(image_data, format='PNG')
  300. img.close()
  301. image = image_data.getvalue()
  302. logger.info("Converted image %s to PNG format" % self.image_file)
  303. else:
  304. raise ValueError(
  305. "The image %s needs to be converted to a PNG file, but PIL.Image is not available! Either install the "
  306. "Pillow package, or use a PNG image for you splash screen." % self.image_file
  307. )
  308. image_file.close()
  309. SplashWriter(
  310. self.name,
  311. self.splash_requirements,
  312. self.tcl_lib[0], # tcl86t.dll
  313. self.tk_lib[0], # tk86t.dll
  314. TK_ROOTNAME,
  315. self.rundir,
  316. image,
  317. self.script
  318. )
  319. def test_tk_version(self):
  320. tcl_version = float(self._tkinter_module.TCL_VERSION)
  321. tk_version = float(self._tkinter_module.TK_VERSION)
  322. # Test if tcl/tk version is supported
  323. if tcl_version < 8.6 or tk_version < 8.6:
  324. logger.warning(
  325. "The installed Tcl/Tk (%s/%s) version might not work with the splash screen feature of the bootloader. "
  326. "The bootloader is tested against Tcl/Tk 8.6" %
  327. (self._tkinter_module.TCL_VERSION, self._tkinter_module.TK_VERSION)
  328. )
  329. # This should be impossible, since tcl/tk is released together with the same version number, but just in case
  330. if tcl_version != tk_version:
  331. logger.warning(
  332. "The installed version of Tcl (%s) and Tk (%s) do not match. PyInstaller is tested against matching "
  333. "versions" % (self._tkinter_module.TCL_VERSION, self._tkinter_module.TK_VERSION)
  334. )
  335. # Test if tcl is threaded.
  336. # If the variable tcl_platform(threaded) exist, the tcl interpreter was compiled with thread support.
  337. threaded = bool(exec_statement(
  338. """
  339. from tkinter import Tcl, TclError
  340. try:
  341. print(Tcl().getvar('tcl_platform(threaded)'))
  342. except TclError:
  343. pass
  344. """
  345. )) # yapf: disable
  346. if not threaded:
  347. # This is a feature breaking problem, so exit.
  348. raise SystemExit(
  349. "The installed tcl version is not threaded. PyInstaller only supports the splash screen "
  350. "using threaded tcl."
  351. )
  352. def generate_script(self):
  353. """
  354. Generate the script for the splash screen.
  355. If minify_script is True, all unnecessary parts will be removed.
  356. """
  357. d = {}
  358. if self.text_pos is not None:
  359. logger.debug("Add text support to splash screen")
  360. d.update({
  361. 'pad_x': self.text_pos[0],
  362. 'pad_y': self.text_pos[1],
  363. 'color': self.text_color,
  364. 'font': self.text_font,
  365. 'font_size': self.text_size,
  366. 'default_text': self.text_default,
  367. })
  368. script = splash_templates.build_script(text_options=d)
  369. if self.minify_script:
  370. # Remove any documentation, empty lines and unnecessary spaces
  371. script = '\n'.join(
  372. line for line in map(lambda l: l.strip(), script.splitlines())
  373. if not line.startswith('#') # documentation
  374. and line # empty lines
  375. )
  376. # Remove unnecessary spaces
  377. script = re.sub(' +', ' ', script)
  378. # Write script to disk, so that it is transparent to the user what script is executed.
  379. with open(self.script_name, "w") as script_file:
  380. script_file.write(script)
  381. return script
  382. @staticmethod
  383. def _uses_tkinter(binaries):
  384. # Test for _tkinter instead of tkinter, because a user might use a different wrapping library for tk.
  385. return '_tkinter' in binaries.filenames
  386. @staticmethod
  387. def _find_rundir(structure):
  388. # First try a name the user could understand, if one would find the directory.
  389. rundir = '__splash%s'
  390. candidate = rundir % ""
  391. counter = 0
  392. # Run this loop as long as a folder exist named like rundir. In most cases __splash will be sufficient and this
  393. # loop wont enter.
  394. while any(e[0].startswith(candidate + os.sep) for e in structure):
  395. # just append to rundir a counter
  396. candidate = rundir % str(counter)
  397. counter += 1
  398. # The SPLASH_DATA_HEADER structure limits the name to be 16 bytes at maximum. So if we exceed the limit
  399. # raise an error. This will never happen, since there are 10^8 different possibilities, but just in case.
  400. assert len(candidate) <= 16
  401. return candidate