splash.py 22 KB

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