__init__.py 74 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433
  1. # ----------------------------------------------------------------------------
  2. # Copyright (c) 2005-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. import glob
  12. import os
  13. import pathlib
  14. import re
  15. from PyInstaller import compat
  16. from PyInstaller import isolated
  17. from PyInstaller import log as logging
  18. from PyInstaller.depend import bindepend
  19. from PyInstaller.utils import hooks, misc
  20. from PyInstaller.utils.hooks.qt import _modules_info
  21. logger = logging.getLogger(__name__)
  22. # Qt deployment approach
  23. # ----------------------
  24. # This is the core of PyInstaller's approach to Qt deployment. It is based on:
  25. #
  26. # - Discovering the location of Qt libraries by introspection, using QtLibraryInfo_. This provides compatibility with
  27. # many variants of Qt5/6 (conda, self-compiled, provided by a Linux distro, etc.) and many versions of Qt5/6, all of
  28. # which vary in the location of Qt files.
  29. #
  30. # - Placing all frozen PyQt5/6 or PySide2/6 Qt files in a standard subdirectory layout, which matches the layout of the
  31. # corresponding wheel on PyPI. This is necessary to support Qt installs which are not in a subdirectory of the PyQt5/6
  32. # or PySide2/6 wrappers. See ``hooks/rthooks/pyi_rth_qt5.py`` for the use of environment variables to establish this
  33. # layout.
  34. #
  35. # - Emitting warnings on missing QML and translation files which some installations do not have.
  36. #
  37. # - Determining additional files needed for deployment based on the information in the centralized Qt module information
  38. # list in the ``_modules_info`` module. This includes plugins and translation files associated with each Qt python
  39. # extension module, as well as additional python Qt extension modules.
  40. #
  41. # - Collecting additional files that are specific to each module and are handled separately, for example:
  42. #
  43. # - For dynamic OpenGL applications, the ``libEGL.dll``, ``libGLESv2.dll``, ``d3dcompiler_XX.dll`` (the XX is a
  44. # version number), and ``opengl32sw.dll`` libraries need to be collected on Windows. This is handled by the
  45. # "base" bindings hook, for example ``hook-PyQt5.py``.
  46. #
  47. # - If Qt was configured to use ICU, the ``icudtXX.dll``, ``icuinXX.dll``, and ``icuucXX.dll`` libraries need to
  48. # be collected on Windows. This is handled by the "base" bindings hook, for example ``hook-PyQt5.py``.
  49. #
  50. # - Per the `Deploying QML Applications <http://doc.qt.io/qt-5/qtquick-deployment.html>`_ page, QML-based
  51. # applications need the ``qml/`` directory available. This is handled by ``QtQuick`` hook, for example
  52. # ``hook-PyQt5.QtQuick.py``.
  53. #
  54. # - For ``QtWebEngine``-based applications, we follow the `deployWebEngineCore
  55. # <https://code.woboq.org/qt5/qttools/src/windeployqt/main.cpp.html#_ZL19deployWebEngineCoreRK4QMapI7QStringS0_ERK7OptionsbPS0_>`_
  56. # function copies the following files from ``resources/``, and also copies the web engine process executable.
  57. # - ``icudtl.dat``
  58. # - ``qtwebengine_devtools_resources.pak``
  59. # - ``qtwebengine_resources.pak``
  60. # - ``qtwebengine_resources_100p.pak``
  61. # - ``qtwebengine_resources_200p.pak``
  62. #
  63. # This is handled by the ``QtWebEngineCore`` hook, for example ``hook-PyQt5.QtWebEngineCore.py``.
  64. #
  65. # For details and references, see the `original write-up
  66. # <https://github.com/pyinstaller/pyinstaller/blob/fbf7948be85177dd44b41217e9f039e1d176de6b/PyInstaller/utils/hooks/qt.py#L248-L362>`_
  67. # and the documentation in the ``_modules_info`` module.
  68. # QtModuleInfo
  69. # ------------
  70. # This class contains information about python module (extension), its corresponding Qt module (shared library), and
  71. # associated plugins and translations. It is used within QtLibraryInfo_ to establish name-based mappings for file
  72. # collection.
  73. class QtModuleInfo:
  74. def __init__(self, module, shared_lib=None, translations=None, plugins=None):
  75. # Python module (extension) name without package namespace. For example, `QtCore`.
  76. # Can be None if python bindings do not bind the module, but we still need to establish relationship between
  77. # the Qt module (shared library) and its plugins and translations.
  78. self.module = module
  79. # Associated Qt module (shared library), if any. Used during recursive dependency analysis, where a python
  80. # module (extension) is analyzed for linked Qt modules (shared libraries), and then their corresponding
  81. # python modules (extensions) are added to hidden imports. For example, the Qt module name is `Qt5Core` or
  82. # `Qt6Core`, depending on the Qt version. Can be None for python modules that are not tied to a particular
  83. # Qt shared library (for example, the corresponding Qt module is headers-only) and hence they cannot be
  84. # inferred from recursive link-time dependency analysis.
  85. self.shared_lib = shared_lib
  86. # List of base names of translation files (if any) associated with the Qt module. Multiple base names may be
  87. # associated with a single module.
  88. # For example, `['qt', 'qtbase']` for `QtCore` or `['qtmultimedia']` for `QtMultimedia`.
  89. self.translations = translations or []
  90. # List of plugins associated with the Qt module.
  91. self.plugins = plugins or []
  92. def __repr__(self):
  93. return f"(module={self.module!r}, shared_lib={self.shared_lib!r}, " \
  94. f"translations={self.translations!r}, plugins={self.plugins!r}"
  95. # QtLibraryInfo
  96. # --------------
  97. # This class uses introspection to determine the location of Qt files. This is essential to deal with the many variants
  98. # of the PyQt5/6 and PySide2/6 package, each of which places files in a different location. Therefore, this class
  99. # provides all location-related members of `QLibraryInfo <http://doc.qt.io/qt-5/qlibraryinfo.html>`_.
  100. class QtLibraryInfo:
  101. def __init__(self, namespace):
  102. if namespace not in ['PyQt5', 'PyQt6', 'PySide2', 'PySide6']:
  103. raise Exception('Invalid namespace: {0}'.format(namespace))
  104. self.namespace = namespace
  105. # Distinction between PyQt5/6 and PySide2/6
  106. self.is_pyqt = namespace in {'PyQt5', 'PyQt6'}
  107. # Distinction between Qt5 and Qt6
  108. self.qt_major = 6 if namespace in {'PyQt6', 'PySide6'} else 5
  109. # Determine relative path where Qt libraries and data need to be collected in the frozen application. This
  110. # varies between PyQt5/PyQt6/PySide2/PySide6, their versions, and platforms. NOTE: it is tempting to consider
  111. # deriving this path as simply the value of QLibraryInfo.PrefixPath, taken relative to the package's root
  112. # directory. However, we also need to support non-wheel deployments (e.g., with Qt installed in custom path on
  113. # Windows, or with Qt and PyQt5 installed on linux using native package manager), and in those, the Qt
  114. # PrefixPath does not reflect the required relative target path for the frozen application.
  115. if namespace == 'PyQt5':
  116. if self._use_new_layout("PyQt5", "5.15.4", False):
  117. self.qt_rel_dir = os.path.join('PyQt5', 'Qt5')
  118. else:
  119. self.qt_rel_dir = os.path.join('PyQt5', 'Qt')
  120. elif namespace == 'PyQt6':
  121. if self._use_new_layout("PyQt6", "6.0.3", True):
  122. self.qt_rel_dir = os.path.join('PyQt6', 'Qt6')
  123. else:
  124. self.qt_rel_dir = os.path.join('PyQt6', 'Qt')
  125. elif namespace == 'PySide2':
  126. # PySide2 uses PySide2/Qt on linux and macOS, and PySide2 on Windows
  127. if compat.is_win:
  128. self.qt_rel_dir = 'PySide2'
  129. else:
  130. self.qt_rel_dir = os.path.join('PySide2', 'Qt')
  131. else:
  132. # PySide6 follows the same logic as PySide2
  133. if compat.is_win:
  134. self.qt_rel_dir = 'PySide6'
  135. else:
  136. self.qt_rel_dir = os.path.join('PySide6', 'Qt')
  137. # Process module information list to construct python-module-name -> info and shared-lib-name -> info mappings.
  138. self._load_module_info()
  139. def __repr__(self):
  140. return f"QtLibraryInfo({self.namespace})"
  141. # Delay initialization of the Qt library information until the corresponding attributes are first requested.
  142. def __getattr__(self, name):
  143. if 'version' in self.__dict__:
  144. # Initialization was already done, but requested attribute is not available.
  145. raise AttributeError(name)
  146. # Load Qt library info...
  147. self._load_qt_info()
  148. # ... and return the requested attribute
  149. return getattr(self, name)
  150. # Check whether we must use the new layout (e.g. PyQt5/Qt5, PyQt6/Qt6) instead of the old layout (PyQt5/Qt,
  151. # PyQt6/Qt).
  152. @staticmethod
  153. def _use_new_layout(package_basename: str, version: str, fallback_value: bool) -> bool:
  154. # The PyQt wheels come in both non-commercial and commercial variants. So we need to check if a particular
  155. # variant is installed before testing its version.
  156. if hooks.check_requirement(package_basename):
  157. return hooks.check_requirement(f"{package_basename} >= {version}")
  158. if hooks.check_requirement(f"{package_basename}_commercial"):
  159. return hooks.check_requirement(f"{package_basename}_commercial >= {version}")
  160. return fallback_value
  161. # Load Qt information (called on first access to related fields)
  162. def _load_qt_info(self):
  163. """
  164. Load and process Qt library information. Called on the first access to the related attributes of the class
  165. (e.g., `version` or `location`).
  166. """
  167. # Ensure self.version exists, even if PyQt{5,6}/PySide{2,6} cannot be imported. Hooks and util functions use
  168. # `if .version` to check whether package was imported and other attributes are expected to be available.
  169. # This also serves as a marker that initialization was already done.
  170. self.version = None
  171. # Get library path information from Qt. See QLibraryInfo_.
  172. @isolated.decorate
  173. def _read_qt_library_info(package):
  174. import os
  175. import sys
  176. import importlib
  177. # Import the Qt-based package
  178. # equivalent to: from package.QtCore import QLibraryInfo, QCoreApplication
  179. try:
  180. QtCore = importlib.import_module('.QtCore', package)
  181. except ModuleNotFoundError:
  182. return None # Signal that package is unavailable
  183. QLibraryInfo = QtCore.QLibraryInfo
  184. QCoreApplication = QtCore.QCoreApplication
  185. # QLibraryInfo is not always valid until a QCoreApplication is instantiated.
  186. app = QCoreApplication(sys.argv) # noqa: F841
  187. # Qt6 deprecated QLibraryInfo.location() in favor of QLibraryInfo.path(), and
  188. # QLibraryInfo.LibraryLocation enum was replaced by QLibraryInfo.LibraryPath.
  189. if hasattr(QLibraryInfo, 'path'):
  190. # Qt6; enumerate path enum values directly from the QLibraryInfo.LibraryPath enum.
  191. path_names = [x for x in dir(QLibraryInfo.LibraryPath) if x.endswith('Path')]
  192. location = {x: QLibraryInfo.path(getattr(QLibraryInfo.LibraryPath, x)) for x in path_names}
  193. else:
  194. # Qt5; in recent versions, location enum values can be enumeratd from QLibraryInfo.LibraryLocation.
  195. # However, in older versions of Qt5 and its python bindings, that is unavailable. Hence the
  196. # enumeration of "*Path"-named members of QLibraryInfo.
  197. path_names = [x for x in dir(QLibraryInfo) if x.endswith('Path')]
  198. location = {x: QLibraryInfo.location(getattr(QLibraryInfo, x)) for x in path_names}
  199. # Determine the python-based package location, by looking where the QtCore module is located.
  200. package_location = os.path.dirname(QtCore.__file__)
  201. # Determine Qt version. Works for Qt 5.8 and later, where QLibraryInfo.version() was introduced.
  202. try:
  203. version = QLibraryInfo.version().segments()
  204. except AttributeError:
  205. version = []
  206. return {
  207. 'is_debug_build': QLibraryInfo.isDebugBuild(),
  208. 'version': version,
  209. 'location': location,
  210. 'package_location': package_location,
  211. }
  212. try:
  213. qt_info = _read_qt_library_info(self.namespace)
  214. except Exception as e:
  215. logger.warning("%s: failed to obtain Qt library info: %s", self, e)
  216. return
  217. # If package could not be imported, `_read_qt_library_info` returns None. In such cases, emit a debug message
  218. # instead of a warning, because this initialization might be triggered by a helper function that is trying to
  219. # determine availability of bindings by inspecting the `version` attribute of `QtLibraryInfo` for all bindings.
  220. if qt_info is None:
  221. logger.debug("%s: failed to obtain Qt library info: %s.QtCore could not be imported.", self, self.namespace)
  222. return
  223. for k, v in qt_info.items():
  224. setattr(self, k, v)
  225. # Turn package_location into pathlib.Path(), and fully resolve it.
  226. self.package_location = pathlib.Path(self.package_location).resolve()
  227. # Determine if the Qt is bundled with python package itself; this usually means we are dealing with with PyPI
  228. # wheels.
  229. resolved_qt_prefix_path = pathlib.Path(self.location['PrefixPath']).resolve()
  230. self.qt_inside_package = (
  231. self.package_location == resolved_qt_prefix_path or # PySide2 and PySide6 Windows PyPI wheels
  232. self.package_location in resolved_qt_prefix_path.parents
  233. )
  234. # Determine directory that contains Qt shared libraries. On non-Windows, this is typically location given by
  235. # `LibrariesPath`. On Windows, it is usually `BinariesPath`, except for PySide PyPI wheels, where DLLs are
  236. # placed in top-level `PrefixPath`.
  237. if compat.is_win:
  238. if self.qt_inside_package and not self.is_pyqt:
  239. # Windows PyPI wheel
  240. qt_lib_dir = self.location['PrefixPath']
  241. else:
  242. qt_lib_dir = self.location['BinariesPath']
  243. else:
  244. qt_lib_dir = self.location['LibrariesPath']
  245. self.qt_lib_dir = pathlib.Path(qt_lib_dir).resolve()
  246. # Module information list loading/processing
  247. def _load_module_info(self):
  248. """
  249. Process the Qt modules info definition list and construct two dictionaries:
  250. - dictionary that maps Qt python module names to Qt module info entries
  251. - dictionary that maps shared library names to Qt module info entries
  252. """
  253. self.python_modules = dict()
  254. self.shared_libraries = dict()
  255. for entry in _modules_info.QT_MODULES_INFO:
  256. # If entry specifies applicable bindings, check them
  257. if entry.bindings:
  258. applicable_bindings = _modules_info.process_namespace_strings(entry.bindings)
  259. if self.namespace not in applicable_bindings:
  260. continue
  261. # Create a QtModuleInfo entry
  262. info_entry = QtModuleInfo(
  263. module=entry.module,
  264. shared_lib=f"Qt{self.qt_major}{entry.shared_lib}" if entry.shared_lib else None,
  265. translations=entry.translations,
  266. plugins=entry.plugins
  267. )
  268. # If we have python module (extension) name, create python-module-name -> info mapping.
  269. if info_entry.module is not None:
  270. self.python_modules[info_entry.module] = info_entry
  271. # If we have Qt module (shared library) name, create shared-lib-name -> info mapping.
  272. if info_entry.shared_lib is not None:
  273. self.shared_libraries[info_entry.shared_lib.lower()] = info_entry
  274. def _normalize_shared_library_name(self, filename):
  275. """
  276. Normalize a shared library name into common form that we can use for look-ups and comparisons.
  277. Primarily intended for Qt shared library names.
  278. """
  279. # Take base name, remove suffix, and lower case it.
  280. lib_name = os.path.splitext(os.path.basename(filename))[0].lower()
  281. # Linux libraries sometimes have a dotted version number -- ``libfoo.so.3``. It is now ''libfoo.so``,
  282. # but the ``.so`` must also be removed.
  283. if compat.is_linux and os.path.splitext(lib_name)[1] == '.so':
  284. lib_name = os.path.splitext(lib_name)[0]
  285. # Remove the "lib" prefix (Linux, macOS).
  286. if lib_name.startswith('lib'):
  287. lib_name = lib_name[3:]
  288. # macOS: handle different naming schemes. PyPI wheels ship framework-enabled Qt builds, where shared
  289. # libraries are part of .framework bundles (e.g., ``PyQt5/Qt5/lib/QtCore.framework/Versions/5/QtCore``).
  290. # In Anaconda (Py)Qt installations, the shared libraries are installed in environment's library directory,
  291. # and contain versioned extensions, e.g., ``libQt5Core.5.dylib``.
  292. if compat.is_darwin:
  293. if lib_name.startswith('qt') and not lib_name.startswith('qt' + str(self.qt_major)):
  294. # Qt library from a framework bundle (e.g., ``QtCore``); change prefix from ``qt`` to ``qt5`` or
  295. # ``qt6`` to match names in Windows/Linux.
  296. lib_name = 'qt' + str(self.qt_major) + lib_name[2:]
  297. if lib_name.endswith('.' + str(self.qt_major)):
  298. # Qt library from Anaconda, which originally had versioned extension, e.g., ``libfoo.5.dynlib``.
  299. # The above processing turned it into ``foo.5``, so we need to remove the last two characters.
  300. lib_name = lib_name[:-2]
  301. # Handle cases with QT_LIBINFIX set to '_conda', i.e. conda-forge builds.
  302. if lib_name.endswith('_conda'):
  303. lib_name = lib_name[:-6]
  304. return lib_name
  305. # Collection
  306. def collect_module(self, module_name):
  307. """
  308. Collect all dependencies (hiddenimports, binaries, datas) for the given Qt python module.
  309. This function performs recursive analysis of extension module's link-time dependencies, and uses dictionaries
  310. built by `_load_module_info` to discover associated plugin types, translation file base names, and hidden
  311. imports that need to be collected.
  312. """
  313. # Accumulate all dependencies in a set to avoid duplicates.
  314. hiddenimports = set()
  315. translation_base_names = set()
  316. plugin_types = set()
  317. # Exit if the requested library cannot be imported.
  318. # NOTE: self..version can be empty list on older Qt5 versions (#5381).
  319. if self.version is None:
  320. return [], [], []
  321. logger.debug('%s: processing module %s...', self, module_name)
  322. # Look up the associated Qt module information by python module name.
  323. # This allows us to collect associated module data directly, even if there is no associated shared library
  324. # (e.g., header-only Qt module, or statically-built one).
  325. short_module_name = module_name.split('.', 1)[-1] # PySide2.QtModule -> QtModule
  326. if short_module_name in self.python_modules:
  327. qt_module_info = self.python_modules[short_module_name]
  328. # NOTE: no need to add a hiddenimport here, because this is the module under consideration.
  329. # Add plugins
  330. plugin_types.update(qt_module_info.plugins)
  331. # Add translation base name(s)
  332. translation_base_names.update(qt_module_info.translations)
  333. # Find the actual module extension file.
  334. module_file = hooks.get_module_file_attribute(module_name)
  335. # Additional search path for shared library resolution. This is mostly required for library resolution on
  336. # Windows (Linux and macOS binaries use run paths to find Qt libs).
  337. qtlib_search_paths = [
  338. # For PyQt5 and PyQt6 wheels, shared libraries should be in BinariesPath, while for PySide2 and PySide6,
  339. # they should be in PrefixPath.
  340. self.location['BinariesPath' if self.is_pyqt else 'PrefixPath'],
  341. ]
  342. # Walk through all the link-time dependencies of a dynamically-linked library (``.so``/``.dll``/``.dylib``).
  343. imported_libraries = bindepend.get_imports(module_file, qtlib_search_paths)
  344. while imported_libraries:
  345. imported_lib_name, imported_lib_path = imported_libraries.pop() # (name, fullpath) tuple
  346. # Skip unresolved libraries
  347. if imported_lib_path is None:
  348. logger.debug("%s: ignoring unresolved library import %r", self, imported_lib_name)
  349. continue
  350. # Normalize the shared library name
  351. lib_name = self._normalize_shared_library_name(imported_lib_path)
  352. logger.debug(
  353. '%s: imported library %r, full path %r -> parsed name %r.', self, imported_lib_name, imported_lib_path,
  354. lib_name
  355. )
  356. # PySide2 and PySide6 on linux seem to link all extension modules against libQt5Core, libQt5Network, and
  357. # libQt5Qml (or their libQt6* equivalents). While the first two are reasonable, the libQt5Qml dependency
  358. # pulls in whole QtQml module, along with its data and plugins, which in turn pull in several other Qt
  359. # libraries, greatly inflating the bundle size (see #6447).
  360. #
  361. # Similarly, some extension modules (QtWebChannel, QtWebEngine*) seem to be also linked against libQt5Qml,
  362. # even when the module can be used without having the whole QtQml module collected.
  363. #
  364. # Therefore, we explicitly prevent inclusion of QtQml based on the dynamic library dependency, except for
  365. # QtQml* and QtQuick* modules, whose use directly implies the use of QtQml.
  366. if lib_name in ("qt5qml", "qt6qml"):
  367. if not short_module_name.startswith(('QtQml', 'QtQuick')):
  368. logger.debug('%s: ignoring imported library %r.', self, lib_name)
  369. continue
  370. # Use the parsed library name to look up associated Qt module information.
  371. if lib_name in self.shared_libraries:
  372. logger.debug('%s: collecting Qt module associated with %r.', self, lib_name)
  373. # Look up associated module info
  374. qt_module_info = self.shared_libraries[lib_name]
  375. # If there is a python extension module associated with Qt module, add it to hiddenimports. Since this
  376. # means that we (most likely) have a hook available for that module, we can avoid analyzing the shared
  377. # library itself (i.e., stop the recursive analysis), because this will be done by the corresponding
  378. # hook.
  379. if qt_module_info.module:
  380. if qt_module_info.module == short_module_name:
  381. # The one exception is if we are analyzing shared library associated with the input module; in
  382. # that case, avoid adding a hidden import and analyze the library's link-time dependencies. We
  383. # do not need to worry about plugins and translations for this particular module, because those
  384. # have been handled at the beginning of this function.
  385. imported_libraries.update(bindepend.get_imports(imported_lib_path, qtlib_search_paths))
  386. else:
  387. hiddenimports.add(self.namespace + "." + qt_module_info.module)
  388. continue
  389. # Add plugins
  390. plugin_types.update(qt_module_info.plugins)
  391. # Add translation base name(s)
  392. translation_base_names.update(qt_module_info.translations)
  393. # Analyze the linked shared libraries for its dependencies (recursive analysis).
  394. imported_libraries.update(bindepend.get_imports(imported_lib_path, qtlib_search_paths))
  395. # Collect plugin files.
  396. binaries = []
  397. for plugin_type in plugin_types:
  398. binaries += self.collect_plugins(plugin_type)
  399. # Collect translation files.
  400. datas = []
  401. translation_src = self.location['TranslationsPath']
  402. translation_dst = os.path.join(self.qt_rel_dir, 'translations')
  403. for translation_base_name in translation_base_names:
  404. # Not all PyQt5 installations include translations. See
  405. # https://github.com/pyinstaller/pyinstaller/pull/3229#issuecomment-359479893
  406. # and
  407. # https://github.com/pyinstaller/pyinstaller/issues/2857#issuecomment-368744341.
  408. translation_pattern = os.path.join(translation_src, translation_base_name + '_*.qm')
  409. translation_files = glob.glob(translation_pattern)
  410. if translation_files:
  411. datas += [(translation_file, translation_dst) for translation_file in translation_files]
  412. else:
  413. logger.warning(
  414. '%s: could not find translations with base name %r! These translations will not be collected.',
  415. self, translation_base_name
  416. )
  417. # Convert hiddenimports to a list.
  418. hiddenimports = list(hiddenimports)
  419. logger.debug(
  420. '%s: dependencies for %s:\n'
  421. ' hiddenimports = %r\n'
  422. ' binaries = %r\n'
  423. ' datas = %r', self, module_name, hiddenimports, binaries, datas
  424. )
  425. return hiddenimports, binaries, datas
  426. @staticmethod
  427. def _filter_release_plugins(plugin_files):
  428. """
  429. Filter the provided list of Qt plugin files and remove the debug variants, under the assumption that both the
  430. release version of a plugin (qtplugin.dll) and its debug variant (qtplugind.dll) appear in the list.
  431. """
  432. # All basenames for lookup
  433. plugin_basenames = {os.path.normcase(os.path.basename(f)) for f in plugin_files}
  434. # Process all given filenames
  435. release_plugin_files = []
  436. for plugin_filename in plugin_files:
  437. plugin_basename = os.path.normcase(os.path.basename(plugin_filename))
  438. if plugin_basename.endswith('d.dll'):
  439. # If we can find a variant without trailing 'd' in the plugin list, then the DLL we are dealing with is
  440. # a debug variant and needs to be excluded.
  441. release_name = os.path.splitext(plugin_basename)[0][:-1] + '.dll'
  442. if release_name in plugin_basenames:
  443. continue
  444. release_plugin_files.append(plugin_filename)
  445. return release_plugin_files
  446. def collect_plugins(self, plugin_type):
  447. """
  448. Collect all plugins of the specified type from the Qt plugin directory.
  449. Returns list of (src, dst) tuples.
  450. """
  451. # Ensure plugin directory exists
  452. plugin_src_dir = self.location['PluginsPath']
  453. if not os.path.isdir(plugin_src_dir):
  454. raise Exception(f"Qt plugin directory '{plugin_src_dir}' does not exist!")
  455. # Collect all shared lib files in plugin type (sub)directory
  456. plugin_files = misc.dlls_in_dir(os.path.join(plugin_src_dir, plugin_type))
  457. # Windows:
  458. #
  459. # dlls_in_dir() grabs all files ending with ``*.dll``, ``*.so`` and ``*.dylib`` in a certain directory. On
  460. # Windows this would grab debug copies of Qt plugins, which then causes PyInstaller to add a dependency on the
  461. # Debug CRT *in addition* to the release CRT.
  462. if compat.is_win:
  463. plugin_files = self._filter_release_plugins(plugin_files)
  464. logger.debug("%s: found plugin files for plugin type %r: %r", self, plugin_type, plugin_files)
  465. plugin_dst_dir = os.path.join(self.qt_rel_dir, 'plugins', plugin_type)
  466. # Exclude plugins with invalid Qt dependencies.
  467. binaries = []
  468. for plugin_file in plugin_files:
  469. valid, reason = self._validate_plugin_dependencies(plugin_file)
  470. if valid:
  471. binaries.append((plugin_file, plugin_dst_dir))
  472. else:
  473. logger.debug("%s: excluding plugin %r (%r)! Reason: %s", self, plugin_file, plugin_type, reason)
  474. return binaries
  475. def _validate_plugin_dependencies(self, plugin_file):
  476. """
  477. Validate Qt dependencies of the given Qt plugin file. For the plugin to pass validation, all its Qt dependencies
  478. must be available (resolvable), and must be resolvable from the default Qt shared library directory (to avoid
  479. pulling in libraries from unrelated Qt installations that happen to be in search path).
  480. """
  481. imported_libraries = bindepend.get_imports(plugin_file, search_paths=[self.qt_lib_dir])
  482. for imported_lib_name, imported_lib_path in imported_libraries:
  483. # Parse/normalize the (unresolved) library name, to determine if dependency is a Qt shared library. If not,
  484. # skip the validation.
  485. lib_name = self._normalize_shared_library_name(imported_lib_name)
  486. if not lib_name.startswith(f"qt{self.qt_major}"):
  487. continue
  488. if imported_lib_path is None:
  489. return False, f"Missing Qt dependency {imported_lib_name!r}."
  490. imported_lib_path = pathlib.Path(imported_lib_path).resolve()
  491. if self.qt_lib_dir not in imported_lib_path.parents:
  492. return (
  493. False,
  494. f"Qt dependency {imported_lib_name!r} ({str(imported_lib_path)!r}) has been resolved outside of "
  495. f"the Qt shared library directory ({str(self.qt_lib_dir)!r})."
  496. )
  497. return True, None
  498. def _collect_all_or_none(self, mandatory_dll_patterns, optional_dll_patterns=None):
  499. """
  500. Try to find Qt DLLs from the specified mandatory pattern list. If all mandatory patterns resolve to DLLs,
  501. collect them all, as well as any DLLs from the optional pattern list. If a mandatory pattern fails to resolve
  502. to a DLL, return an empty list.
  503. This allows all-or-none collection of particular groups of Qt DLLs that may or may not be available.
  504. """
  505. optional_dll_patterns = optional_dll_patterns or []
  506. # Package parent path; used to preserve the directory structure when DLLs are collected from the python
  507. # package (e.g., PyPI wheels).
  508. package_parent_path = self.package_location.parent
  509. # On Windows, DLLs are typically placed in `location['BinariesPath']`, except for PySide PyPI wheels, where
  510. # `location['PrefixPath']` is used. This difference is already handled by `qt_lib_dir`, which is also fully
  511. # resolved.
  512. dll_path = self.qt_lib_dir
  513. # Helper for processing single DLL pattern
  514. def _process_dll_pattern(dll_pattern):
  515. discovered_dlls = []
  516. dll_files = dll_path.glob(dll_pattern)
  517. for dll_file in dll_files:
  518. if package_parent_path in dll_file.parents:
  519. # The DLL is located within python package; preserve the layout
  520. dst_dll_dir = dll_file.parent.relative_to(package_parent_path)
  521. else:
  522. # The DLL is not located within python package; collect into top-level directory
  523. dst_dll_dir = '.'
  524. discovered_dlls.append((str(dll_file), str(dst_dll_dir)))
  525. return discovered_dlls
  526. # Process mandatory patterns
  527. collected_dlls = []
  528. for pattern in mandatory_dll_patterns:
  529. discovered_dlls = _process_dll_pattern(pattern)
  530. if not discovered_dlls:
  531. return [] # Mandatory pattern resulted in no DLLs; abort
  532. collected_dlls += discovered_dlls
  533. # Process optional patterns
  534. for pattern in optional_dll_patterns:
  535. collected_dlls += _process_dll_pattern(pattern)
  536. return collected_dlls
  537. # Collect required Qt binaries, but only if all binaries in a group exist.
  538. def collect_extra_binaries(self):
  539. """
  540. Collect extra binaries/DLLs required by Qt. These include ANGLE DLLs, OpenGL software renderer DLL, and ICU
  541. DLLs. Applicable only on Windows (on other OSes, empty list is returned).
  542. """
  543. binaries = []
  544. # Applicable only to Windows.
  545. if not compat.is_win:
  546. return []
  547. # OpenGL: EGL/GLES via ANGLE, software OpenGL renderer.
  548. binaries += self._collect_all_or_none(['libEGL.dll', 'libGLESv2.dll'], ['d3dcompiler_??.dll'])
  549. binaries += self._collect_all_or_none(['opengl32sw.dll'])
  550. # Include ICU files, if they exist.
  551. # See the "Deployment approach" section at the top of this file.
  552. binaries += self._collect_all_or_none(['icudt??.dll', 'icuin??.dll', 'icuuc??.dll'])
  553. return binaries
  554. # Collect additional shared libraries required for SSL support in QtNetwork, if they are available.
  555. # Primarily applicable to Windows (see issue #3520, #4048).
  556. def collect_qtnetwork_files(self):
  557. """
  558. Collect extra binaries/shared libraries required by the QtNetwork module, such as OpenSSL shared libraries.
  559. """
  560. # No-op if requested Qt-based package is not available.
  561. if self.version is None:
  562. return []
  563. # Check if QtNetwork supports SSL and has OpenSSL backend available (Qt >= 6.1).
  564. # Also query the run-time OpenSSL version, so we know what dynamic libraries we need to search for.
  565. @isolated.decorate
  566. def _check_if_openssl_enabled(package):
  567. import sys
  568. import importlib
  569. # Import the Qt-based package
  570. # equivalent to: from package.QtCore import QCoreApplication
  571. QtCore = importlib.import_module('.QtCore', package)
  572. QCoreApplication = QtCore.QCoreApplication
  573. QLibraryInfo = QtCore.QLibraryInfo
  574. # equivalent to: from package.QtNetwork import QSslSocket
  575. QtNetwork = importlib.import_module('.QtNetwork', package)
  576. QSslSocket = QtNetwork.QSslSocket
  577. # Instantiate QCoreApplication to suppress warnings
  578. app = QCoreApplication(sys.argv) # noqa: F841
  579. if not QSslSocket.supportsSsl():
  580. return False, None
  581. # Query the run-time OpenSSL version
  582. openssl_version = QSslSocket.sslLibraryVersionNumber()
  583. # For Qt >= 6.1, check if `openssl` TLS backend is available
  584. try:
  585. qt_version = QLibraryInfo.version().segments()
  586. except AttributeError:
  587. qt_version = [] # Qt <= 5.8
  588. if qt_version < [6, 1]:
  589. return True, openssl_version # TLS backends not implemented yet
  590. return ('openssl' in QSslSocket.availableBackends(), openssl_version)
  591. openssl_enabled, openssl_version = _check_if_openssl_enabled(self.namespace)
  592. if not openssl_enabled or openssl_version == 0:
  593. logger.debug("%s: QtNetwork: does not support SSL or does not use OpenSSL.", self)
  594. return []
  595. # The actual search is handled in OS-specific ways.
  596. if compat.is_win:
  597. return self._collect_qtnetwork_openssl_windows(openssl_version)
  598. elif compat.is_darwin:
  599. return self._collect_qtnetwork_openssl_macos(openssl_version)
  600. elif compat.is_linux:
  601. return self._collect_qtnetwork_openssl_linux(openssl_version)
  602. else:
  603. logger.warning("%s: QtNetwork: collection of OpenSSL not implemented for this platform!", self)
  604. return []
  605. def _collect_qtnetwork_openssl_windows(self, openssl_version):
  606. """
  607. Windows-specific collection of OpenSSL DLLs required by QtNetwork module.
  608. """
  609. # Package parent path; used to preserve the directory structure when DLLs are collected from the python
  610. # package (e.g., PyPI wheels).
  611. package_parent_path = self.package_location.parent
  612. # The OpenSSL DLLs might be shipped with PyPI wheel (PyQt5), might be available in the environment (msys2,
  613. # anaconda), or might be expected to be available in the environment (PySide2, PySide6, PyQt6 PyPI wheels).
  614. #
  615. # The OpenSSL DLL naming scheme depends on the version:
  616. # - OpenSSL 1.0.x: libeay32.dll, ssleay32.dll
  617. # - OpenSSL 1.1.x 32-bit: libssl-1_1.dll, libcrypto-1_1.dll
  618. # - OpenSSL 1.1.x 64-bit: libssl-1_1-x64.dll, libcrypto-1_1-x64.dll
  619. # - OpenSSL 3.0.x 32-bit: libssl-1.dll, libcrypto-3.dll
  620. # - OpenSSL 3.0.x 64-bit: libssl-3-x64.dll, libcrypto-3-x64.dll
  621. #
  622. # The official Qt builds (which are used by PySide and PyQt PyPI wheels) seem to be build against:
  623. # - OpenSSL 1.1.x starting with Qt5 5.14.2:
  624. # https://www.qt.io/blog/2019/06/17/qt-5-12-4-released-support-openssl-1-1-1
  625. # - OpenSSL 3.x starting with Qt6 6.5.0:
  626. # https://www.qt.io/blog/moving-to-openssl-3-in-binary-builds-starting-from-qt-6.5-beta-2
  627. #
  628. # However, a package can build Qt against OpenSSL version of their own choice. For example, at the time of
  629. # writing, both mingw-w64-x86_64-qt5-base 5.15.11+kde+r138-1 and mingw-w64-x86_64-qt6-base 6.6.0-2 packages
  630. # depend on mingw-w64-x86_64-openssl 3.1.4-1 (so OpenSSL 3).
  631. #
  632. # Luckily, we can query the run-time version of OpenSSL by calling `QSslSocket.sslLibraryVersionNumber()`,
  633. # and narrow down the search for specific version.
  634. if openssl_version >= 0x10000000 and openssl_version < 0x10100000:
  635. # OpenSSL 1.0.x - used by old Qt5 builds
  636. dll_names = (
  637. 'libeay32.dll',
  638. 'ssleay32.dll',
  639. )
  640. logger.debug("%s: QtNetwork: looking for OpenSSL 1.0.x DLLs: %r", self, dll_names)
  641. elif openssl_version >= 0x10100000 and openssl_version < 0x30000000:
  642. # OpenSSL 1.1.x
  643. dll_names = (
  644. 'libssl-1_1-x64.dll' if compat.is_64bits else 'libssl-1_1.dll',
  645. 'libcrypto-1_1-x64.dll' if compat.is_64bits else 'libcrypto-1_1.dll',
  646. )
  647. logger.debug("%s: QtNetwork: looking for OpenSSL 1.1.x DLLs: %r", self, dll_names)
  648. elif openssl_version >= 0x30000000 and openssl_version < 0x40000000:
  649. # OpenSSL 3.0.x
  650. dll_names = (
  651. 'libssl-3-x64.dll' if compat.is_64bits else 'libssl-3.dll',
  652. 'libcrypto-3-x64.dll' if compat.is_64bits else 'libcrypto-3.dll',
  653. )
  654. logger.debug("%s: QtNetwork: looking for OpenSSL 3.0.x DLLs: %r", self, dll_names)
  655. else:
  656. dll_names = [] # Nothing to search for
  657. logger.warning("%s: QtNetwork: unsupported OpenSSL version: %X", self, openssl_version)
  658. binaries = []
  659. found_in_package = False
  660. for dll in dll_names:
  661. # Attempt to resolve the DLL path
  662. dll_file_path = bindepend.resolve_library_path(dll, search_paths=[self.qt_lib_dir])
  663. if dll_file_path is None:
  664. continue
  665. dll_file_path = pathlib.Path(dll_file_path).resolve()
  666. if package_parent_path in dll_file_path.parents:
  667. # The DLL is located within python package; preserve the layout
  668. dst_dll_path = dll_file_path.parent.relative_to(package_parent_path)
  669. found_in_package = True
  670. else:
  671. # The DLL is not located within python package; collect into top-level directory
  672. dst_dll_path = '.'
  673. binaries.append((str(dll_file_path), str(dst_dll_path)))
  674. # If we found at least one OpenSSL DLL in the bindings' python package directory, discard all external
  675. # OpenSSL DLLs.
  676. if found_in_package:
  677. binaries = [(dll_src_path, dll_dest_path) for dll_src_path, dll_dest_path in binaries
  678. if package_parent_path in pathlib.Path(dll_src_path).parents]
  679. return binaries
  680. def _collect_qtnetwork_openssl_macos(self, openssl_version):
  681. """
  682. macOS-specific collection of OpenSSL dylibs required by QtNetwork module.
  683. """
  684. # The official Qt5 builds on macOS (shipped by PyPI wheels) appear to be built with Apple's SecureTransport API
  685. # instead of OpenSSL; for example, `QSslSocket.sslLibraryVersionNumber` returns 0, while
  686. # `sslLibraryVersionString()` returns "Secure Transport, macOS 12.6". So with PySide2 and PyQt5, we do not need
  687. # to worry about collection of OpenSSL shared libraries.
  688. #
  689. # Support for OpenSSL was introduced in Qt 6.1 with `openssl` TLS backend; the official Qt6 builds prior to 6.5
  690. # seem to be built with OpenSSL 1.1.x, and later versions with 3.0.x. However, PySide6 and PyQt6 PyPI wheels do
  691. # not ship OpenSSL dynamic libraries at all , so whether `openssl` TLS backend is used or not depends on the
  692. # presence of externally provided OpenSSL dynamic libraries (for example, provided by Homebrew). It is worth
  693. # noting that python.org python installers *do* provide OpenSSL shared libraries (1.1.x for python <= 3.10,
  694. # 3.0.x for python >= 3.12, and both for python 3.11) for its `_ssl` extension - however, these are NOT visible
  695. # to Qt and its QtNetwork module.
  696. #
  697. # When the frozen application is built and we collect python's `_ssl` extension, we also collect the OpenSSL
  698. # shared libraries shipped by python. So at least in theory, those should be available to QtNetwork module as
  699. # well (assuming they are of compatible version). However, this is not exactly the case - QtNetwork looks for
  700. # the libraries in locations given by `DYLD_LIBRARY_PATH` environment variable and in .app/Contents/Frameworks
  701. # (if the program is an .app bundle):
  702. #
  703. # https://github.com/qt/qtbase/blob/6.6.0/src/plugins/tls/openssl/qsslsocket_openssl_symbols.cpp#L590-L599
  704. #
  705. # So it works out-of-the box for our .app bundles, because starting with PyInstaller 6.0, `sys._MEIPASS` is in
  706. # .app/Contents/Frameworks. But it does not with POSIX builds, because bootloader does not modify the
  707. # `DYLD_LIBRARY_PATH` environment variable to include `sys._MEIPASS` (since we usually do not need that;
  708. # regular linked library resolution in our macOS builds is done via path rewriting and rpaths). So either we
  709. # need a run-time hook to add `sys._MEIPASS` to `DYLD_LIBRARY_PATH`, or modify the bootloader to always do that.
  710. #
  711. # Collecting the OpenSSL library and making it discoverable by adding `sys._MEIPASS` to `DYLD_LIBRARY_PATH`
  712. # should also prevent QtNetwork from "accidentally" pulling in Homebrew version at run-time (if Homebrew is
  713. # installed on the target system and provides compatible OpenSSL version).
  714. #
  715. # Therefore, try to resolve OpenSSL library via the version indicated by `QSslSocket.sslLibraryVersionNumber`;
  716. # however, we first explicitly search only {sys.base_prefix}/lib (which is where python.org builds put their
  717. # dynamic libs), and only if that fails, perform regular dylib path resolution. This way we ensure that if the
  718. # OpenSSL dylibs are provided by python itself, we always prefer those over the Homebrew version (since we are
  719. # very likely going to collect them for python's `_ssl` extension anyway).
  720. # As per above text, we need to worry only about Qt6, and thus OpenSSL 1.1.x or 3.0.x
  721. if openssl_version >= 0x10100000 and openssl_version < 0x30000000:
  722. # OpenSSL 1.1.x
  723. dylib_names = (
  724. 'libcrypto.1.1.dylib',
  725. 'libssl.1.1.dylib',
  726. )
  727. logger.debug("%s: QtNetwork: looking for OpenSSL 1.1.x dylibs: %r", self, dylib_names)
  728. elif openssl_version >= 0x30000000 and openssl_version < 0x40000000:
  729. # OpenSSL 3.0.x
  730. dylib_names = (
  731. 'libcrypto.3.dylib',
  732. 'libssl.3.dylib',
  733. )
  734. logger.debug("%s: QtNetwork: looking for OpenSSL 3.0.x dylibs: %r", self, dylib_names)
  735. else:
  736. dylib_names = [] # Nothing to search for
  737. logger.warning("%s: QtNetwork: unsupported OpenSSL version: %X", self, openssl_version)
  738. # Compared to Windows, we do not have to worry about dylib's path preservation, as these are never part of
  739. # the package, and are therefore always collected to the top-level application directory.
  740. binaries = []
  741. base_prefix_lib_dir = os.path.join(compat.base_prefix, 'lib')
  742. for dylib in dylib_names:
  743. # First, attempt to resolve using only {sys.base_prefix}/lib - `bindepend.resolve_library_path` uses
  744. # standard dyld search semantics and uses the given search paths as fallback (and would therefore
  745. # favor Homebrew-provided version of the library).
  746. dylib_path = bindepend._resolve_library_path_in_search_paths(dylib, search_paths=[base_prefix_lib_dir])
  747. if dylib_path is None:
  748. dylib_path = bindepend.resolve_library_path(dylib, search_paths=[base_prefix_lib_dir, self.qt_lib_dir])
  749. if dylib_path is None:
  750. continue
  751. binaries.append((str(dylib_path), '.'))
  752. return binaries
  753. def _collect_qtnetwork_openssl_linux(self, openssl_version):
  754. """
  755. Linux-specific collection of OpenSSL dylibs required by QtNetwork module.
  756. """
  757. # Out of the supported OSes, Linux is by far the most straight-forward, because OpenSSL shared libraries are
  758. # expected to be provided by the system. So we can just use standard library path resolution with library names
  759. # inferred from the run-time OpenSSL version. At run-time, QtNetwork searches paths from `LD_LIBRARY_PATH`, and
  760. # on Linux, our bootloader already adds `sys._MEIPASS` to that environment variable.
  761. if openssl_version >= 0x10000000 and openssl_version < 0x10100000:
  762. # OpenSSL 1.0.x - used by old Qt5 builds
  763. shlib_names = (
  764. 'libcrypto.so.10',
  765. 'libssl.so.10',
  766. )
  767. logger.debug("%s: QtNetwork: looking for OpenSSL 1.0.x shared libraries: %r", self, shlib_names)
  768. elif openssl_version >= 0x10100000 and openssl_version < 0x30000000:
  769. # OpenSSL 1.1.x
  770. shlib_names = (
  771. 'libcrypto.so.1.1',
  772. 'libssl.so.1.1',
  773. )
  774. logger.debug("%s: QtNetwork: looking for OpenSSL 1.1.x shared libraries: %r", self, shlib_names)
  775. elif openssl_version >= 0x30000000 and openssl_version < 0x40000000:
  776. # OpenSSL 3.0.x
  777. shlib_names = (
  778. 'libcrypto.so.3',
  779. 'libssl.so.3',
  780. )
  781. logger.debug("%s: QtNetwork: looking for OpenSSL 3.0.x shared libraries: %r", self, shlib_names)
  782. else:
  783. shlib_names = [] # Nothing to search for
  784. logger.warning("%s: QtNetwork: unsupported OpenSSL version: %X", self, openssl_version)
  785. binaries = []
  786. for shlib in shlib_names:
  787. shlib_path = bindepend.resolve_library_path(shlib)
  788. if shlib_path is None:
  789. continue
  790. binaries.append((str(shlib_path), '.'))
  791. return binaries
  792. def collect_qtqml_files(self):
  793. """
  794. Collect additional binaries and data for QtQml module.
  795. """
  796. # No-op if requested Qt-based package is not available.
  797. if self.version is None:
  798. return [], []
  799. # Not all PyQt5/PySide2 installs have QML files. In this case, location['Qml2ImportsPath'] is empty.
  800. # Furthermore, even if location path is provided, the directory itself may not exist.
  801. #
  802. # https://github.com/pyinstaller/pyinstaller/pull/3229#issuecomment-359735031
  803. # https://github.com/pyinstaller/pyinstaller/issues/3864
  804. #
  805. # In Qt 6, Qml2ImportsPath was deprecated in favor of QmlImportsPath. The former is not available in PySide6
  806. # 6.4.0 anymore (but is in PyQt6 6.4.0). Use the new QmlImportsPath if available.
  807. if 'QmlImportsPath' in self.location:
  808. qml_src_dir = self.location['QmlImportsPath']
  809. else:
  810. qml_src_dir = self.location['Qml2ImportsPath']
  811. if not qml_src_dir or not os.path.isdir(qml_src_dir):
  812. logger.warning('%s: QML directory %r does not exist. QML files not packaged.', self, qml_src_dir)
  813. return [], []
  814. qml_src_path = pathlib.Path(qml_src_dir).resolve()
  815. qml_dest_path = pathlib.PurePath(self.qt_rel_dir) / 'qml'
  816. binaries = []
  817. datas = []
  818. # Helper that computes the destination directory for the given file or directory from a QML plugin directory.
  819. def _compute_dest_dir(src_filename):
  820. if src_filename.is_dir():
  821. rel_path = src_filename.relative_to(qml_src_path)
  822. else:
  823. rel_path = src_filename.relative_to(qml_src_path).parent
  824. return qml_dest_path / rel_path
  825. # Discover all QML plugin sub-directories by searching for `qmldir` files.
  826. qmldir_files = qml_src_path.rglob('**/qmldir')
  827. for qmldir_file in sorted(qmldir_files):
  828. plugin_dir = qmldir_file.parent
  829. logger.debug("%s: processing QML plugin directory %s", self, plugin_dir)
  830. try:
  831. # Obtain lists of source files (separated into binaries and data files).
  832. plugin_binaries, plugin_datas = self._process_qml_plugin(qmldir_file)
  833. # Convert into (src, dest) tuples.
  834. binaries += [(str(src_file), str(_compute_dest_dir(src_file))) for src_file in plugin_binaries]
  835. datas += [(str(src_file), str(_compute_dest_dir(src_file))) for src_file in plugin_datas]
  836. except Exception:
  837. logger.warning("%s: failed to process QML plugin directory %s", self, plugin_dir, exc_info=True)
  838. return binaries, datas
  839. # https://doc.qt.io/qt-6/qtqml-modules-qmldir.html#plugin-declaration
  840. # [optional] plugin <name> [<path]>
  841. _qml_plugin_def = re.compile(r"^(?:(?:optional)\s+)?(?:plugin)\s+(?P<name>\w+)(?:\s+(?P<path>\.+))?$")
  842. def _process_qml_plugin(self, qmldir_file):
  843. """
  844. Processes the QML directory corresponding to the given `qmldir` file.
  845. Returns lists of binaries and data files, but only the source file names. It is up to caller to turn these into
  846. lists of (src, dest) tuples.
  847. """
  848. plugin_dir = qmldir_file.parent
  849. plugin_binaries = set()
  850. # Read the `qmldir` file to determine the names of plugin binaries, if any.
  851. contents = qmldir_file.read_text(encoding="utf-8")
  852. for line in contents.splitlines():
  853. m = self._qml_plugin_def.match(line)
  854. if m is None:
  855. continue
  856. plugin_name = m.group("name")
  857. plugin_path = m.group("path")
  858. # We currently do not support custom plugin path - neither relative nor absolute (the latter will never
  859. # be supported, because to make it relocatable, we would need to modify the `qmpldir file`).
  860. if plugin_path is not None:
  861. raise Exception(f"Non-empty plugin path ({plugin_path!r} is not supported yet!")
  862. # Turn the plugin base name into actual shared lib name.
  863. if compat.is_linux:
  864. plugin_file = plugin_dir / f"lib{plugin_name}.so"
  865. elif compat.is_win:
  866. plugin_file = plugin_dir / f"{plugin_name}.dll"
  867. elif compat.is_darwin:
  868. plugin_file = plugin_dir / f"lib{plugin_name}.dylib"
  869. else:
  870. continue # This implicitly disables subsequent validation on unhandled platforms.
  871. # Warn if plugin file does not exist
  872. if not plugin_file.is_file():
  873. logger.warning("%s: QML plugin binary %r does not exist!", self, str(plugin_file))
  874. continue
  875. plugin_binaries.add(plugin_file)
  876. # Exclude plugins with invalid Qt dependencies.
  877. invalid_binaries = False
  878. for plugin_binary in plugin_binaries:
  879. valid, reason = self._validate_plugin_dependencies(plugin_binary)
  880. if not valid:
  881. logger.debug("%s: excluding QML plugin binary %r! Reason: %s", self, str(plugin_binary), reason)
  882. invalid_binaries = True
  883. # If there was an invalid binary, discard the plugin.
  884. if invalid_binaries:
  885. logger.debug("%s: excluding QML plugin directory %r due to invalid plugin binaries!", self, str(plugin_dir))
  886. return [], []
  887. # Generate binaries list.
  888. binaries = sorted(plugin_binaries)
  889. # Generate list of data files - all content of this directory, except for the plugin binaries. Sub-directories
  890. # are included if they do not contain a `qmldir` file (we do not recurse into the directory, but instead pass
  891. # only its name, leaving the recursion to PyInstaller's built-in expansion of paths returned by hooks).
  892. datas = []
  893. for entry in plugin_dir.iterdir():
  894. if entry.is_file():
  895. if entry in plugin_binaries:
  896. continue
  897. else:
  898. if (entry / "qmldir").is_file():
  899. continue
  900. # Sometimes, QML plugin directories end up containing sub-directories with left-over object files, which
  901. # should not have been distributed with the wheel (for example, `qml/Qt/labs/assetdownloader` in PySide6
  902. # 6.11.1 wheels). We should not be collecting these files; least of all because they end up failing
  903. # PyInstaller's strict codesigning check (enabled on macOS CI)...
  904. if entry.name in {'objects-Debug', 'objects-RelWithDebInfo'} and entry.is_dir():
  905. continue
  906. datas.append(entry)
  907. return binaries, datas
  908. def collect_qtwebengine_files(self):
  909. """
  910. Collect QtWebEngine helper process executable, translations, and resources.
  911. """
  912. binaries = []
  913. datas = []
  914. # Output directory (varies between PyQt and PySide and among OSes; the difference is abstracted by
  915. # QtLibraryInfo.qt_rel_dir)
  916. rel_data_path = self.qt_rel_dir
  917. is_macos_framework = False
  918. if compat.is_darwin:
  919. # Determine if we are dealing with a framework-based Qt build (e.g., PyPI wheels) or a dylib-based one
  920. # (e.g., Anaconda). The former requires special handling, while the latter is handled in the same way as
  921. # Windows and Linux builds.
  922. is_macos_framework = os.path.exists(
  923. os.path.join(self.location['LibrariesPath'], 'QtWebEngineCore.framework')
  924. )
  925. if is_macos_framework:
  926. # macOS .framework bundle
  927. src_framework_path = os.path.join(self.location['LibrariesPath'], 'QtWebEngineCore.framework')
  928. # If Qt libraries are bundled with the package, collect the .framework bundle into corresponding package's
  929. # subdirectory, because binary dependency analysis will also try to preserve the directory structure.
  930. # However, if we are collecting from system-wide Qt installation (e.g., Homebrew-installed Qt), the binary
  931. # depndency analysis will attempt to re-create .framework bundle in top-level directory, so we need to
  932. # collect the extra files there.
  933. bundled_qt_libs = pathlib.Path(self.package_location) in pathlib.Path(src_framework_path).parents
  934. if bundled_qt_libs:
  935. dst_framework_path = os.path.join(rel_data_path, 'lib/QtWebEngineCore.framework')
  936. else:
  937. dst_framework_path = 'QtWebEngineCore.framework' # In top-level directory
  938. # Determine the version directory - for now, we assume we are dealing with single-version framework;
  939. # i.e., the Versions directory contains only a single <version> directory, and Current symlink to it.
  940. versions = sorted([
  941. version for version in os.listdir(os.path.join(src_framework_path, 'Versions')) if version != 'Current'
  942. ])
  943. if len(versions) == 0:
  944. raise RuntimeError("Could not determine version of the QtWebEngineCore.framework!")
  945. elif len(versions) > 1:
  946. logger.warning(
  947. "Found multiple versions in QtWebEngineCore.framework (%r) - using the last one!", versions
  948. )
  949. version = versions[-1]
  950. # Collect the Helpers directory. In well-formed .framework bundles (such as the ones provided by Homebrew),
  951. # the Helpers directory is located in the versioned directory, and symlinked to the top-level directory.
  952. src_helpers_path = os.path.join(src_framework_path, 'Versions', version, 'Helpers')
  953. dst_helpers_path = os.path.join(dst_framework_path, 'Versions', version, 'Helpers')
  954. if not os.path.exists(src_helpers_path):
  955. # Alas, the .framework bundles shipped with contemporary PyPI PyQt/PySide wheels are not well-formed
  956. # (presumably because .whl cannot preserve symlinks?). The Helpers in the top-level directory is in fact
  957. # the hard copy, and there is either no Helpers in versioned directory, or there is a duplicate.
  958. # So fall back to collecting from the top-level, but collect into versioned directory in order to
  959. # be compliant with codesign's expectations.
  960. src_helpers_path = os.path.join(src_framework_path, 'Helpers')
  961. helper_datas = hooks.collect_system_data_files(src_helpers_path, dst_helpers_path)
  962. # Filter out the actual helper executable from datas, and add it to binaries instead. This ensures that it
  963. # undergoes additional binary processing that rewrites the paths to linked libraries.
  964. HELPER_EXE = 'QtWebEngineProcess.app/Contents/MacOS/QtWebEngineProcess'
  965. for src_name, dest_name in helper_datas:
  966. if src_name.endswith(HELPER_EXE):
  967. binaries.append((src_name, dest_name))
  968. else:
  969. datas.append((src_name, dest_name))
  970. # Collect the Resources directory; same logic is used as with Helpers directory.
  971. src_resources_path = os.path.join(src_framework_path, 'Versions', version, 'Resources')
  972. dst_resources_path = os.path.join(dst_framework_path, 'Versions', version, 'Resources')
  973. if not os.path.exists(src_resources_path):
  974. src_resources_path = os.path.join(src_framework_path, 'Resources')
  975. datas += hooks.collect_system_data_files(src_resources_path, dst_resources_path)
  976. # NOTE: the QtWebEngineProcess helper is actually sought within the `QtWebEngineCore.framework/Helpers`,
  977. # which ought to be a symlink to `QtWebEngineCore.framework/Versions/Current/Helpers`, where `Current`
  978. # is also a symlink to the actual version directory, `A`.
  979. #
  980. # These symlinks are created automatically when the TOC list of collected resources is post-processed
  981. # using `PyInstaller.utils.osx.collect_files_from_framework_bundles` helper, so we do not have to
  982. # worry about them here...
  983. else:
  984. # Windows and linux (or Anaconda on macOS)
  985. locales = 'qtwebengine_locales'
  986. resources = 'resources'
  987. # Translations
  988. datas.append((
  989. os.path.join(self.location['TranslationsPath'], locales),
  990. os.path.join(rel_data_path, 'translations', locales),
  991. ))
  992. # Resources; ``DataPath`` is the base directory for ``resources``, as per the
  993. # `docs <https://doc.qt.io/qt-5.10/qtwebengine-deploying.html#deploying-resources>`_.
  994. datas.append((os.path.join(self.location['DataPath'], resources), os.path.join(rel_data_path, resources)),)
  995. # Helper process executable (QtWebEngineProcess), located in ``LibraryExecutablesPath``.
  996. # The target directory is determined as `LibraryExecutablesPath` relative to `PrefixPath`. On Windows,
  997. # this should handle the differences between PySide2/PySide6 and PyQt5/PyQt6 PyPI wheel layout.
  998. rel_helper_path = os.path.relpath(self.location['LibraryExecutablesPath'], self.location['PrefixPath'])
  999. # However, on Linux, we need to account for distribution-packaged Qt, where `LibraryExecutablesPath` might
  1000. # be nested deeper under `PrefixPath` than anticipated (w.r.t. PyPI wheel layout). For example, in Fedora,
  1001. # the helper is located under `/usr/lib64/qt5/libexec/QtWebEngineProcess`, with `PrefixPath` being `/usr`
  1002. # and `LibraryExecutablesPath` being `/usr/lib64/qt5/libexec/`, so the relative path ends up being
  1003. # `lib64/qt5/libexec` instead of just `libexec`. So on linux, we explicitly force the PyPI-compliant
  1004. # layout, by overriding relative helper path to just `libexec`.
  1005. if compat.is_linux and rel_helper_path != "libexec":
  1006. logger.info(
  1007. "%s: overriding relative destination path of QtWebEngineProcess helper from %r to %r!", self,
  1008. rel_helper_path, "libexec"
  1009. )
  1010. rel_helper_path = "libexec"
  1011. # Similarly, force the relative helper path for PySide2/PySide6 on Windows to `.`. This is already the case
  1012. # with PyPI PySide Windows wheels. But it is not the case with conda-installed PySide2, where the Qt's
  1013. # `PrefixPath` is for example `C:/Users/<user>/miniconda3/envs/<env-name>/Library`, while the corresponding
  1014. # `LibraryExecutablesPath` is `C:/Users/<user>/miniconda3/envs/<env-name>/Library/bin`.
  1015. if compat.is_win and not self.is_pyqt and rel_helper_path != ".":
  1016. logger.info(
  1017. "%s: overriding relative destination path of QtWebEngineProcess helper from %r to %r!", self,
  1018. rel_helper_path, "."
  1019. )
  1020. rel_helper_path = "."
  1021. dest = os.path.normpath(os.path.join(rel_data_path, rel_helper_path))
  1022. binaries.append((os.path.join(self.location['LibraryExecutablesPath'], 'QtWebEngineProcess*'), dest))
  1023. # The helper QtWebEngineProcess executable should have an accompanying qt.conf file that helps it locate the
  1024. # Qt shared libraries. Try collecting it as well
  1025. qt_conf_file = os.path.join(self.location['LibraryExecutablesPath'], 'qt.conf')
  1026. if not os.path.isfile(qt_conf_file):
  1027. # The file seems to have been dropped from Qt 6.3 (and corresponding PySide6 and PyQt6) due to
  1028. # redundancy; however, we still need it in the frozen application - so generate our own.
  1029. from PyInstaller.config import CONF # workpath
  1030. # Relative path to root prefix of bundled Qt - this corresponds to the "inverse" of `rel_helper_path`
  1031. # variable that we computed earlier.
  1032. if rel_helper_path == '.':
  1033. rel_prefix = '.'
  1034. else:
  1035. # Replace each directory component in `rel_helper_path` with `..`.
  1036. rel_prefix = os.path.join(*['..' for _ in range(len(rel_helper_path.split(os.pathsep)))])
  1037. # We expect the relative path to be either . or .. depending on PySide/PyQt layout; if that is not the
  1038. # case, warn about irregular path.
  1039. if rel_prefix not in ('.', '..'):
  1040. logger.warning(
  1041. "%s: unexpected relative Qt prefix path for QtWebEngineProcess qt.conf: %s", self, rel_prefix
  1042. )
  1043. # The Qt docs on qt.conf (https://doc.qt.io/qt-5/qt-conf.html) recommend using forward slashes on
  1044. # Windows as well, due to backslash having to be escaped. This should not matter as we expect the
  1045. # relative path to be . or .., but you never know...
  1046. if os.sep == '\\':
  1047. rel_prefix = rel_prefix.replace(os.sep, '/')
  1048. # Create temporary file in workpath
  1049. qt_conf_file = os.path.join(CONF['workpath'], "qt.conf")
  1050. with open(qt_conf_file, 'w', encoding='utf-8') as fp:
  1051. print("[Paths]", file=fp)
  1052. print("Prefix = {}".format(rel_prefix), file=fp)
  1053. datas.append((qt_conf_file, dest))
  1054. # Add Linux-specific libraries.
  1055. if compat.is_linux:
  1056. # The automatic library detection fails for `NSS <https://packages.ubuntu.com/search?keywords=libnss3>`_,
  1057. # which is used by QtWebEngine. In some distributions, the ``libnss`` supporting libraries are stored in a
  1058. # subdirectory ``nss``. Since ``libnss`` is not linked against them but loads them dynamically at run-time,
  1059. # we need to search for and add them.
  1060. #
  1061. # Specifically, the files we are looking for are
  1062. # - libfreebl3.so
  1063. # - libfreeblpriv3.so
  1064. # - libnssckbi.so
  1065. # - libnssdbm3.so
  1066. # - libsoftokn3.so
  1067. # and they might be in the same directory as ``libnss3.so`` (instead of ``nss`` subdirectory); this is
  1068. # the case even with contemporary Debian releases. See
  1069. # https://packages.debian.org/bullseye/amd64/libnss3/filelist
  1070. # vs.
  1071. # https://packages.debian.org/bookworm/amd64/libnss3/filelist
  1072. # Analyze imports of ``QtWebEngineCore`` extension module, and look for ``libnss3.so`` to determine its
  1073. # parent directory.
  1074. libnss_dir = None
  1075. module_file = hooks.get_module_file_attribute(self.namespace + '.QtWebEngineCore')
  1076. for lib_name, lib_path in bindepend.get_imports(module_file): # (name, fullpath) tuples
  1077. if lib_path is None:
  1078. continue # Skip unresolved libraries
  1079. # Look for ``libnss3.so``.
  1080. if os.path.basename(lib_path).startswith('libnss3.so'):
  1081. libnss_dir = os.path.dirname(lib_path)
  1082. break
  1083. # Search for NSS libraries
  1084. logger.debug("%s: QtWebEngineCore is linked against libnss3.so; collecting NSS libraries...", self)
  1085. if libnss_dir is not None:
  1086. # Libraries to search for
  1087. NSS_LIBS = [
  1088. 'libfreebl3.so',
  1089. 'libfreeblpriv3.so',
  1090. 'libnssckbi.so',
  1091. 'libnssdbm3.so',
  1092. 'libsoftokn3.so',
  1093. ]
  1094. # Directories (relative to `libnss_dir`) to search in. Also serve as relative destination paths.
  1095. NSS_LIB_SUBDIRS = [
  1096. 'nss',
  1097. '.',
  1098. ]
  1099. for subdir in NSS_LIB_SUBDIRS:
  1100. for lib_name in NSS_LIBS:
  1101. lib_file = os.path.normpath(os.path.join(libnss_dir, subdir, lib_name))
  1102. if os.path.isfile(lib_file):
  1103. logger.debug("%s: collecting NSS library: %r", self, lib_file)
  1104. binaries.append((lib_file, subdir))
  1105. return binaries, datas
  1106. # Provide single instances of this class to avoid each hook constructing its own.
  1107. pyqt5_library_info = QtLibraryInfo('PyQt5')
  1108. pyqt6_library_info = QtLibraryInfo('PyQt6')
  1109. pyside2_library_info = QtLibraryInfo('PySide2')
  1110. pyside6_library_info = QtLibraryInfo('PySide6')
  1111. def get_qt_library_info(namespace):
  1112. """
  1113. Return QtLibraryInfo instance for the given namespace.
  1114. """
  1115. if namespace == 'PyQt5':
  1116. return pyqt5_library_info
  1117. if namespace == 'PyQt6':
  1118. return pyqt6_library_info
  1119. elif namespace == 'PySide2':
  1120. return pyside2_library_info
  1121. elif namespace == 'PySide6':
  1122. return pyside6_library_info
  1123. raise ValueError(f'Invalid namespace: {namespace}!')
  1124. # add_qt_dependencies
  1125. # --------------------
  1126. # Generic implemnentation that finds the Qt 5/6 dependencies based on the hook name of a PyQt5/PyQt6/PySide2/PySide6
  1127. # hook. Returns (hiddenimports, binaries, datas). Typical usage:
  1128. # ``hiddenimports, binaries, datas = add_qt5_dependencies(__file__)``.
  1129. def add_qt_dependencies(hook_file):
  1130. # Find the module underlying this Qt hook: change ``/path/to/hook-PyQt5.blah.py`` to ``PyQt5.blah``.
  1131. hook_name, hook_ext = os.path.splitext(os.path.basename(hook_file))
  1132. assert hook_ext.startswith('.py')
  1133. assert hook_name.startswith('hook-')
  1134. module_name = hook_name[5:]
  1135. namespace = module_name.split('.')[0]
  1136. # Retrieve Qt library info structure....
  1137. qt_info = get_qt_library_info(namespace)
  1138. # ... and use it to collect module dependencies
  1139. return qt_info.collect_module(module_name)
  1140. # add_qt5_dependencies
  1141. # --------------------
  1142. # Find the Qt5 dependencies based on the hook name of a PySide2/PyQt5 hook. Returns (hiddenimports, binaries, datas).
  1143. # Typical usage: ``hiddenimports, binaries, datas = add_qt5_dependencies(__file__)``.
  1144. add_qt5_dependencies = add_qt_dependencies # Use generic implementation
  1145. # add_qt6_dependencies
  1146. # --------------------
  1147. # Find the Qt6 dependencies based on the hook name of a PySide6/PyQt6 hook. Returns (hiddenimports, binaries, datas).
  1148. # Typical usage: ``hiddenimports, binaries, datas = add_qt6_dependencies(__file__)``.
  1149. add_qt6_dependencies = add_qt_dependencies # Use generic implementation
  1150. # A helper for ensuring that only one Qt bindings package is collected into frozen application. Intended to be called
  1151. # from hooks for top-level bindings packages.
  1152. def ensure_single_qt_bindings_package(qt_bindings):
  1153. # For the lack of better alternative, use CONF structure. Note that this enforces single bindings for the whole
  1154. # spec file instead of individual Analysis instances!
  1155. from PyInstaller.config import CONF
  1156. seen_qt_bindings = CONF.get("_seen_qt_bindings")
  1157. if seen_qt_bindings is None:
  1158. CONF["_seen_qt_bindings"] = qt_bindings
  1159. elif qt_bindings != seen_qt_bindings:
  1160. # Raise SystemExit to abort build process
  1161. raise SystemExit(
  1162. "ERROR: Aborting build process due to attempt to collect multiple Qt bindings packages: attempting to run "
  1163. f"hook for {qt_bindings!r}, while hook for {seen_qt_bindings!r} has already been run! PyInstaller does not "
  1164. "support multiple Qt bindings packages in a frozen application - either ensure that the build environment "
  1165. "has only one Qt bindings package installed, or exclude the extraneous bindings packages via the module "
  1166. "exclusion mechanism (--exclude command-line option, or excludes list in the spec file)."
  1167. )
  1168. # A helper for generating exclude rules for extraneous Qt bindings. Intended for use in hooks for packages that pull in
  1169. # multiple Qt bindings packages due to conditional imports (for example, `matplotlib.backends.qt_compat`, `qtpy`).
  1170. def exclude_extraneous_qt_bindings(hook_name, qt_bindings_order=None):
  1171. _QT_BINDINGS = ['PyQt5', 'PySide2', 'PyQt6', 'PySide6'] # Known bindings, and also their preferred order
  1172. _QT_API_ENV = 'QT_API'
  1173. def _create_excludes(selected_bindings):
  1174. return [bindings for bindings in _QT_BINDINGS if bindings != selected_bindings]
  1175. logger.debug("%s: selecting Qt bindings package...", hook_name)
  1176. if not qt_bindings_order:
  1177. qt_bindings_order = _QT_BINDINGS # Use default preference order
  1178. env_qt_bindings = os.environ.get(_QT_API_ENV)
  1179. if env_qt_bindings is not None:
  1180. # Case-normalize the value into capitalized name from _QT_BINDINGS for further processing.
  1181. normalized_name = {name.lower(): name for name in _QT_BINDINGS}.get(env_qt_bindings.lower())
  1182. if normalized_name is None:
  1183. logger.warning(
  1184. "%s: ignoring unsupported Qt bindings name %r in %s environment variable (supported values: %r)!",
  1185. hook_name, env_qt_bindings, _QT_API_ENV, _QT_BINDINGS
  1186. )
  1187. env_qt_bindings = normalized_name
  1188. # First choice: see if a hook for top-level Qt bindings package has already been run; if it has, use that bindings
  1189. # package. Due to check in the `ensure_single_qt_bindings_package` that these hooks use, only one such hook could
  1190. # have been run. This should cover cases when the entry-point script explicitly imports one of Qt bindings before
  1191. # importing a package that supports multiple bindings.
  1192. from PyInstaller.config import CONF
  1193. seen_qt_bindings = CONF.get("_seen_qt_bindings")
  1194. if seen_qt_bindings is not None:
  1195. # If bindings are also specified via environment variable and they differ, display a warning.
  1196. if env_qt_bindings is not None and env_qt_bindings != seen_qt_bindings:
  1197. logger.warning(
  1198. "%s: ignoring %s environment variable (%r) because hook for %r has been run!", hook_name, _QT_API_ENV,
  1199. env_qt_bindings, seen_qt_bindings
  1200. )
  1201. logger.info(
  1202. "%s: selected %r as Qt bindings because hook for %r has been run before.", hook_name, seen_qt_bindings,
  1203. seen_qt_bindings
  1204. )
  1205. return _create_excludes(seen_qt_bindings)
  1206. # Second choice: honor the QT_API environment variable, if it specified a valid Qt bindings package.
  1207. if env_qt_bindings is not None:
  1208. logger.info(
  1209. "%s: selected %r as Qt bindings as specified by the %s environment variable.", hook_name, env_qt_bindings,
  1210. _QT_API_ENV
  1211. )
  1212. return _create_excludes(env_qt_bindings)
  1213. # Third choice: select first available bindings (sorted by the given preference order), and display a warning if
  1214. # multiple bindings are available.
  1215. available_qt_bindings = []
  1216. for bindings_name in qt_bindings_order:
  1217. # Check if bindings are available
  1218. info = get_qt_library_info(bindings_name)
  1219. if info.version is None:
  1220. continue
  1221. available_qt_bindings.append(bindings_name)
  1222. if not available_qt_bindings:
  1223. logger.warning("%s: no Qt bindings are available!", hook_name)
  1224. return [] # No need to generate any excludes...
  1225. selected_qt_bindings = available_qt_bindings[0]
  1226. if len(available_qt_bindings) == 1:
  1227. logger.info("%s: selected %r as the only available Qt bindings.", hook_name, selected_qt_bindings)
  1228. else:
  1229. # Warn on multiple bindings, and tell user to use QT_API environment variable
  1230. logger.warning(
  1231. "%s: selected %r as Qt bindings, but multiple bindings are available: %r. Use the %s environment variable "
  1232. "to select different bindings and suppress this warning.", hook_name, selected_qt_bindings,
  1233. available_qt_bindings, _QT_API_ENV
  1234. )
  1235. return _create_excludes(selected_qt_bindings)