splash.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  1. # -----------------------------------------------------------------------------
  2. # Copyright (c) 2005-2022, 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, is_win, is_cygwin
  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. :keyword always_on_top:
  112. Force the splashscreen to be always on top of other windows. If disabled, other windows (e.g., from other
  113. applications) can cover the splash screen by user bringing them to front. This might be useful for
  114. frozen applications with long startup times. Default: True
  115. :type always_on_top: bool
  116. """
  117. from ..config import CONF
  118. Target.__init__(self)
  119. # Splash screen is not supported on macOS. It operates in a secondary thread and macOS disallows UI operations
  120. # in any thread other than main.
  121. if is_darwin:
  122. raise SystemExit("Splash screen is not supported on macOS.")
  123. # Make image path relative to .spec file
  124. if not os.path.isabs(image_file):
  125. image_file = os.path.join(CONF['specpath'], image_file)
  126. image_file = os.path.normpath(image_file)
  127. if not os.path.exists(image_file):
  128. raise ValueError("Image file '%s' not found" % image_file)
  129. # Copy all arguments
  130. self.image_file = image_file
  131. self.full_tk = kwargs.get("full_tk", False)
  132. self.name = kwargs.get("name", None)
  133. self.script_name = kwargs.get("script_name", None)
  134. self.minify_script = kwargs.get("minify_script", True)
  135. self.rundir = kwargs.get("rundir", None)
  136. self.max_img_size = kwargs.get("max_img_size", (760, 480))
  137. # text options
  138. self.text_pos = kwargs.get("text_pos", None)
  139. self.text_size = kwargs.get("text_size", 12)
  140. self.text_font = kwargs.get("text_font", "TkDefaultFont")
  141. self.text_color = kwargs.get("text_color", "black")
  142. self.text_default = kwargs.get("text_default", "Initializing")
  143. # always-on-top behavior
  144. self.always_on_top = kwargs.get("always_on_top", True)
  145. # Save the generated file separately so that it is not necessary to generate the data again and again
  146. root = os.path.splitext(self.tocfilename)[0]
  147. if self.name is None:
  148. self.name = root + '.res'
  149. if self.script_name is None:
  150. self.script_name = root + '_script.tcl'
  151. if self.rundir is None:
  152. self.rundir = self._find_rundir(binaries + datas)
  153. # Internal variables
  154. try:
  155. # Do not import _tkinter at the toplevel, because on some systems _tkinter will fail to load, since it is
  156. # not installed. This would cause a runtime error in PyInstaller, since this module is imported from
  157. # build_main.py, instead we just want to inform the user that the splash screen feature is not supported on
  158. # his platform
  159. import _tkinter
  160. self._tkinter_module = _tkinter
  161. self._tkinter_file = self._tkinter_module.__file__
  162. except ModuleNotFoundError:
  163. raise SystemExit(
  164. "You platform does not support the splash screen feature, since tkinter is not installed. Please "
  165. "install tkinter and try again."
  166. )
  167. # Calculated / analysed values
  168. self.uses_tkinter = self._uses_tkinter(binaries)
  169. self.script = self.generate_script()
  170. self.tcl_lib, self.tk_lib = find_tcl_tk_shared_libs(self._tkinter_file)
  171. if is_darwin:
  172. # Outdated Tcl/Tk 8.5 system framework is not supported. Depending on macOS version, the library path will
  173. # come up empty (hidden system libraries on Big Sur), or will be
  174. # [/System]/Library/Frameworks/Tcl.framework/Tcl
  175. if self.tcl_lib[1] is None or 'Library/Frameworks/Tcl.framework' in self.tcl_lib[1]:
  176. raise SystemExit("The splash screen feature does not support macOS system framework version of Tcl/Tk.")
  177. # Check if tcl/tk was found
  178. assert all(self.tcl_lib)
  179. assert all(self.tk_lib)
  180. logger.debug("Use Tcl Library from %s and Tk From %s" % (self.tcl_lib, self.tk_lib))
  181. self.splash_requirements = set([self.tcl_lib[0], self.tk_lib[0]] + splash_requirements)
  182. logger.info("Collect tcl/tk binaries for the splash screen")
  183. tcltk_tree = collect_tcl_tk_files(self._tkinter_file)
  184. if self.full_tk:
  185. # The user wants a full copy of tk, so make all tk files a requirement.
  186. self.splash_requirements.update(toc[0] for toc in tcltk_tree)
  187. self.binaries = TOC()
  188. if not self.uses_tkinter:
  189. # The user's script does not use tkinter, so we need to provide a TOC of all necessary files add the shared
  190. # libraries to the binaries.
  191. self.binaries.append((self.tcl_lib[0], self.tcl_lib[1], 'BINARY'))
  192. self.binaries.append((self.tk_lib[0], self.tk_lib[1], 'BINARY'))
  193. # Only add the intersection of the required and the collected resources, or add all entries if full_tk is
  194. # true.
  195. self.binaries.extend(toc for toc in tcltk_tree if toc[0] in self.splash_requirements)
  196. # Handle extra requirements of Tcl/Tk shared libraries (e.g., vcruntime140.dll on Windows - see issue #6284).
  197. # These need to be added to splash requirements, so they are extracted into the initial runtime directory in
  198. # order to make onefile builds work.
  199. #
  200. # The really proper way to implement this would be to perform full dependency analysis on self.tcl_lib[0] and
  201. # self.tk_lib[0], and ensure that those dependencies are collected and added to splash requirements. This
  202. # would, for example, ensure that on Linux, dependent X libraries are collected, just as if the frozen app
  203. # itself was using tkinter. On the other hand, collecting all the extra shared libraries on Linux is currently
  204. # futile anyway, because the bootloader's parent process would need to set LD_LIBRARY_PATH to the initial
  205. # runtime directory to actually have them loaded (and that requires process to be restarted to take effect).
  206. #
  207. # So for now, we only deal with this on Windows, in a quick'n'dirty work-around way, by assuming that
  208. # vcruntime140.dll is already collected as dependency of some other shared library (e.g., the python shared
  209. # library).
  210. if is_win or is_cygwin:
  211. EXTRA_REQUIREMENTS = {'vcruntime140.dll'}
  212. self.splash_requirements.update([name for name, *_ in binaries if name.lower() in EXTRA_REQUIREMENTS])
  213. # Check if all requirements were found.
  214. fnames = [toc[0] for toc in (binaries + datas + self.binaries)]
  215. def _filter(_item):
  216. if _item not in fnames:
  217. # Item is not bundled, so warn the user about it. This actually may happen on some tkinter installations
  218. # that are missing the license.terms file.
  219. logger.warning(
  220. "The local Tcl/Tk installation is missing the file %s. The behavior of the splash screen is "
  221. "therefore undefined and may be unsupported." % _item
  222. )
  223. return False
  224. return True
  225. # Remove all files which were not found.
  226. self.splash_requirements = set(filter(_filter, self.splash_requirements))
  227. # Test if the tcl/tk version is supported by the bootloader.
  228. self.test_tk_version()
  229. logger.debug("Splash Requirements: %s" % self.splash_requirements)
  230. self.__postinit__()
  231. _GUTS = (
  232. # input parameters
  233. ('image_file', _check_guts_eq),
  234. ('name', _check_guts_eq),
  235. ('script_name', _check_guts_eq),
  236. ('text_pos', _check_guts_eq),
  237. ('text_size', _check_guts_eq),
  238. ('text_font', _check_guts_eq),
  239. ('text_color', _check_guts_eq),
  240. ('text_default', _check_guts_eq),
  241. ('always_on_top', _check_guts_eq),
  242. ('full_tk', _check_guts_eq),
  243. ('minify_script', _check_guts_eq),
  244. ('rundir', _check_guts_eq),
  245. ('max_img_size', _check_guts_eq),
  246. # calculated/analysed values
  247. ('uses_tkinter', _check_guts_eq),
  248. ('script', _check_guts_eq),
  249. ('tcl_lib', _check_guts_eq),
  250. ('tk_lib', _check_guts_eq),
  251. ('splash_requirements', _check_guts_eq),
  252. ('binaries', _check_guts_toc),
  253. # internal value
  254. # Check if the tkinter installation changed. This is theoretically possible if someone uses two different python
  255. # installations of the same version.
  256. ('_tkinter_file', _check_guts_eq),
  257. )
  258. def _check_guts(self, data, last_build):
  259. if Target._check_guts(self, data, last_build):
  260. return True
  261. # Check if the image has been modified.
  262. if misc.mtime(self.image_file) > last_build:
  263. logger.info("Building %s because file %s changed", self.tocbasename, self.image_file)
  264. return True
  265. return False
  266. def assemble(self):
  267. logger.info("Building Splash %s" % self.name)
  268. # Function to resize a given image to fit into the area defined by max_img_size.
  269. def _resize_image(_image, _orig_size):
  270. if PILImage:
  271. _w, _h = _orig_size
  272. _ratio_w = self.max_img_size[0] / _w
  273. if _ratio_w < 1:
  274. # Image width exceeds limit
  275. _h = int(_h * _ratio_w)
  276. _w = self.max_img_size[0]
  277. _ratio_h = self.max_img_size[1] / _h
  278. if _ratio_h < 1:
  279. # Image height exceeds limit
  280. _w = int(_w * _ratio_h)
  281. _h = self.max_img_size[1]
  282. # If a file is given it will be open
  283. if isinstance(_image, PILImage.Image):
  284. _img = _image
  285. else:
  286. _img = PILImage.open(_image)
  287. _img_resized = _img.resize((_w, _h))
  288. # Save image into a stream
  289. _image_stream = io.BytesIO()
  290. _img_resized.save(_image_stream, format='PNG')
  291. _img.close()
  292. _img_resized.close()
  293. _image_data = _image_stream.getvalue()
  294. logger.info(
  295. "Resized image %s from dimensions %s to (%d, %d)" % (self.image_file, str(_orig_size), _w, _h)
  296. )
  297. return _image_data
  298. else:
  299. raise ValueError(
  300. "The splash image dimensions (w: %d, h: %d) exceed max_img_size (w: %d, h:%d), but the image "
  301. "cannot be resized due to missing PIL.Image! Either install the Pillow package, adjust the "
  302. "max_img_size, or use an image of compatible dimensions." %
  303. (_orig_size[0], _orig_size[1], self.max_img_size[0], self.max_img_size[1])
  304. )
  305. # Open image file
  306. image_file = open(self.image_file, 'rb')
  307. # Check header of the file to identify it
  308. if image_file.read(8) == b'\x89PNG\r\n\x1a\n':
  309. # self.image_file is a PNG file
  310. image_file.seek(16)
  311. img_size = (struct.unpack("!I", image_file.read(4))[0], struct.unpack("!I", image_file.read(4))[0])
  312. if img_size > self.max_img_size:
  313. # The image exceeds the maximum image size, so resize it
  314. image = _resize_image(self.image_file, img_size)
  315. else:
  316. image = os.path.abspath(self.image_file)
  317. elif PILImage:
  318. # Pillow is installed, meaning the image can be converted automatically
  319. img = PILImage.open(self.image_file, mode='r')
  320. if img.size > self.max_img_size:
  321. image = _resize_image(img, img.size)
  322. else:
  323. image_data = io.BytesIO()
  324. img.save(image_data, format='PNG')
  325. img.close()
  326. image = image_data.getvalue()
  327. logger.info("Converted image %s to PNG format" % self.image_file)
  328. else:
  329. raise ValueError(
  330. "The image %s needs to be converted to a PNG file, but PIL.Image is not available! Either install the "
  331. "Pillow package, or use a PNG image for you splash screen." % self.image_file
  332. )
  333. image_file.close()
  334. SplashWriter(
  335. self.name,
  336. self.splash_requirements,
  337. self.tcl_lib[0], # tcl86t.dll
  338. self.tk_lib[0], # tk86t.dll
  339. TK_ROOTNAME,
  340. self.rundir,
  341. image,
  342. self.script
  343. )
  344. def test_tk_version(self):
  345. tcl_version = float(self._tkinter_module.TCL_VERSION)
  346. tk_version = float(self._tkinter_module.TK_VERSION)
  347. # Test if tcl/tk version is supported
  348. if tcl_version < 8.6 or tk_version < 8.6:
  349. logger.warning(
  350. "The installed Tcl/Tk (%s/%s) version might not work with the splash screen feature of the bootloader. "
  351. "The bootloader is tested against Tcl/Tk 8.6" %
  352. (self._tkinter_module.TCL_VERSION, self._tkinter_module.TK_VERSION)
  353. )
  354. # This should be impossible, since tcl/tk is released together with the same version number, but just in case
  355. if tcl_version != tk_version:
  356. logger.warning(
  357. "The installed version of Tcl (%s) and Tk (%s) do not match. PyInstaller is tested against matching "
  358. "versions" % (self._tkinter_module.TCL_VERSION, self._tkinter_module.TK_VERSION)
  359. )
  360. # Test if tcl is threaded.
  361. # If the variable tcl_platform(threaded) exist, the tcl interpreter was compiled with thread support.
  362. threaded = bool(exec_statement(
  363. """
  364. from tkinter import Tcl, TclError
  365. try:
  366. print(Tcl().getvar('tcl_platform(threaded)'))
  367. except TclError:
  368. pass
  369. """
  370. )) # yapf: disable
  371. if not threaded:
  372. # This is a feature breaking problem, so exit.
  373. raise SystemExit(
  374. "The installed tcl version is not threaded. PyInstaller only supports the splash screen "
  375. "using threaded tcl."
  376. )
  377. def generate_script(self):
  378. """
  379. Generate the script for the splash screen.
  380. If minify_script is True, all unnecessary parts will be removed.
  381. """
  382. d = {}
  383. if self.text_pos is not None:
  384. logger.debug("Add text support to splash screen")
  385. d.update({
  386. 'pad_x': self.text_pos[0],
  387. 'pad_y': self.text_pos[1],
  388. 'color': self.text_color,
  389. 'font': self.text_font,
  390. 'font_size': self.text_size,
  391. 'default_text': self.text_default,
  392. })
  393. script = splash_templates.build_script(text_options=d, always_on_top=self.always_on_top)
  394. if self.minify_script:
  395. # Remove any documentation, empty lines and unnecessary spaces
  396. script = '\n'.join(
  397. line for line in map(lambda l: l.strip(), script.splitlines())
  398. if not line.startswith('#') # documentation
  399. and line # empty lines
  400. )
  401. # Remove unnecessary spaces
  402. script = re.sub(' +', ' ', script)
  403. # Write script to disk, so that it is transparent to the user what script is executed.
  404. with open(self.script_name, "w") as script_file:
  405. script_file.write(script)
  406. return script
  407. @staticmethod
  408. def _uses_tkinter(binaries):
  409. # Test for _tkinter instead of tkinter, because a user might use a different wrapping library for tk.
  410. return '_tkinter' in binaries.filenames
  411. @staticmethod
  412. def _find_rundir(structure):
  413. # First try a name the user could understand, if one would find the directory.
  414. rundir = '__splash%s'
  415. candidate = rundir % ""
  416. counter = 0
  417. # Run this loop as long as a folder exist named like rundir. In most cases __splash will be sufficient and this
  418. # loop won't enter.
  419. while any(e[0].startswith(candidate + os.sep) for e in structure):
  420. # just append to rundir a counter
  421. candidate = rundir % str(counter)
  422. counter += 1
  423. # The SPLASH_DATA_HEADER structure limits the name to be 16 bytes at maximum. So if we exceed the limit
  424. # raise an error. This will never happen, since there are 10^8 different possibilities, but just in case.
  425. assert len(candidate) <= 16
  426. return candidate