qt_loaders.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  1. """
  2. This module contains factory functions that attempt
  3. to return Qt submodules from the various python Qt bindings.
  4. It also protects against double-importing Qt with different
  5. bindings, which is unstable and likely to crash
  6. This is used primarily by qt and qt_for_kernel, and shouldn't
  7. be accessed directly from the outside
  8. """
  9. import importlib.abc
  10. import sys
  11. import os
  12. import types
  13. from functools import partial, lru_cache
  14. import operator
  15. # ### Available APIs.
  16. # Qt6
  17. QT_API_PYQT6 = "pyqt6"
  18. QT_API_PYSIDE6 = "pyside6"
  19. # Qt5
  20. QT_API_PYQT5 = 'pyqt5'
  21. QT_API_PYSIDE2 = 'pyside2'
  22. # Qt4
  23. # NOTE: Here for legacy matplotlib compatibility, but not really supported on the IPython side.
  24. QT_API_PYQT = "pyqt" # Force version 2
  25. QT_API_PYQTv1 = "pyqtv1" # Force version 2
  26. QT_API_PYSIDE = "pyside"
  27. QT_API_PYQT_DEFAULT = "pyqtdefault" # use system default for version 1 vs. 2
  28. api_to_module = {
  29. # Qt6
  30. QT_API_PYQT6: "PyQt6",
  31. QT_API_PYSIDE6: "PySide6",
  32. # Qt5
  33. QT_API_PYQT5: "PyQt5",
  34. QT_API_PYSIDE2: "PySide2",
  35. # Qt4
  36. QT_API_PYSIDE: "PySide",
  37. QT_API_PYQT: "PyQt4",
  38. QT_API_PYQTv1: "PyQt4",
  39. # default
  40. QT_API_PYQT_DEFAULT: "PyQt6",
  41. }
  42. class ImportDenier(importlib.abc.MetaPathFinder):
  43. """Import Hook that will guard against bad Qt imports
  44. once IPython commits to a specific binding
  45. """
  46. def __init__(self):
  47. self.__forbidden = set()
  48. def forbid(self, module_name):
  49. sys.modules.pop(module_name, None)
  50. self.__forbidden.add(module_name)
  51. def find_spec(self, fullname, path, target=None):
  52. if path:
  53. return
  54. if fullname in self.__forbidden:
  55. raise ImportError(
  56. """
  57. Importing %s disabled by IPython, which has
  58. already imported an Incompatible QT Binding: %s
  59. """
  60. % (fullname, loaded_api())
  61. )
  62. ID = ImportDenier()
  63. sys.meta_path.insert(0, ID)
  64. def commit_api(api):
  65. """Commit to a particular API, and trigger ImportErrors on subsequent
  66. dangerous imports"""
  67. modules = set(api_to_module.values())
  68. modules.remove(api_to_module[api])
  69. for mod in modules:
  70. ID.forbid(mod)
  71. def loaded_api():
  72. """Return which API is loaded, if any
  73. If this returns anything besides None,
  74. importing any other Qt binding is unsafe.
  75. Returns
  76. -------
  77. None, 'pyside6', 'pyqt6', 'pyside2', 'pyside', 'pyqt', 'pyqt5', 'pyqtv1'
  78. """
  79. if sys.modules.get("PyQt6.QtCore"):
  80. return QT_API_PYQT6
  81. elif sys.modules.get("PySide6.QtCore"):
  82. return QT_API_PYSIDE6
  83. elif sys.modules.get("PyQt5.QtCore"):
  84. return QT_API_PYQT5
  85. elif sys.modules.get("PySide2.QtCore"):
  86. return QT_API_PYSIDE2
  87. elif sys.modules.get("PyQt4.QtCore"):
  88. if qtapi_version() == 2:
  89. return QT_API_PYQT
  90. else:
  91. return QT_API_PYQTv1
  92. elif sys.modules.get("PySide.QtCore"):
  93. return QT_API_PYSIDE
  94. return None
  95. def has_binding(api):
  96. """Safely check for PyQt4/5, PySide or PySide2, without importing submodules
  97. Parameters
  98. ----------
  99. api : str [ 'pyqtv1' | 'pyqt' | 'pyqt5' | 'pyside' | 'pyside2' | 'pyqtdefault']
  100. Which module to check for
  101. Returns
  102. -------
  103. True if the relevant module appears to be importable
  104. """
  105. module_name = api_to_module[api]
  106. from importlib.util import find_spec
  107. required = ['QtCore', 'QtGui', 'QtSvg']
  108. if api in (QT_API_PYQT5, QT_API_PYSIDE2, QT_API_PYQT6, QT_API_PYSIDE6):
  109. # QT5 requires QtWidgets too
  110. required.append('QtWidgets')
  111. for submod in required:
  112. try:
  113. spec = find_spec('%s.%s' % (module_name, submod))
  114. except ImportError:
  115. # Package (e.g. PyQt5) not found
  116. return False
  117. else:
  118. if spec is None:
  119. # Submodule (e.g. PyQt5.QtCore) not found
  120. return False
  121. if api == QT_API_PYSIDE:
  122. # We can also safely check PySide version
  123. import PySide
  124. return PySide.__version_info__ >= (1, 0, 3)
  125. return True
  126. def qtapi_version():
  127. """Return which QString API has been set, if any
  128. Returns
  129. -------
  130. The QString API version (1 or 2), or None if not set
  131. """
  132. try:
  133. import sip
  134. except ImportError:
  135. # as of PyQt5 5.11, sip is no longer available as a top-level
  136. # module and needs to be imported from the PyQt5 namespace
  137. try:
  138. from PyQt5 import sip
  139. except ImportError:
  140. return
  141. try:
  142. return sip.getapi('QString')
  143. except ValueError:
  144. return
  145. def can_import(api):
  146. """Safely query whether an API is importable, without importing it"""
  147. if not has_binding(api):
  148. return False
  149. current = loaded_api()
  150. if api == QT_API_PYQT_DEFAULT:
  151. return current in [QT_API_PYQT6, None]
  152. else:
  153. return current in [api, None]
  154. def import_pyqt4(version=2):
  155. """
  156. Import PyQt4
  157. Parameters
  158. ----------
  159. version : 1, 2, or None
  160. Which QString/QVariant API to use. Set to None to use the system
  161. default
  162. ImportErrors raised within this function are non-recoverable
  163. """
  164. # The new-style string API (version=2) automatically
  165. # converts QStrings to Unicode Python strings. Also, automatically unpacks
  166. # QVariants to their underlying objects.
  167. import sip
  168. if version is not None:
  169. sip.setapi('QString', version)
  170. sip.setapi('QVariant', version)
  171. from PyQt4 import QtGui, QtCore, QtSvg
  172. if QtCore.PYQT_VERSION < 0x040700:
  173. raise ImportError("IPython requires PyQt4 >= 4.7, found %s" %
  174. QtCore.PYQT_VERSION_STR)
  175. # Alias PyQt-specific functions for PySide compatibility.
  176. QtCore.Signal = QtCore.pyqtSignal
  177. QtCore.Slot = QtCore.pyqtSlot
  178. # query for the API version (in case version == None)
  179. version = sip.getapi('QString')
  180. api = QT_API_PYQTv1 if version == 1 else QT_API_PYQT
  181. return QtCore, QtGui, QtSvg, api
  182. def import_pyqt5():
  183. """
  184. Import PyQt5
  185. ImportErrors raised within this function are non-recoverable
  186. """
  187. from PyQt5 import QtCore, QtSvg, QtWidgets, QtGui
  188. # Alias PyQt-specific functions for PySide compatibility.
  189. QtCore.Signal = QtCore.pyqtSignal
  190. QtCore.Slot = QtCore.pyqtSlot
  191. # Join QtGui and QtWidgets for Qt4 compatibility.
  192. QtGuiCompat = types.ModuleType('QtGuiCompat')
  193. QtGuiCompat.__dict__.update(QtGui.__dict__)
  194. QtGuiCompat.__dict__.update(QtWidgets.__dict__)
  195. api = QT_API_PYQT5
  196. return QtCore, QtGuiCompat, QtSvg, api
  197. def import_pyqt6():
  198. """
  199. Import PyQt6
  200. ImportErrors raised within this function are non-recoverable
  201. """
  202. from PyQt6 import QtCore, QtSvg, QtWidgets, QtGui
  203. # Alias PyQt-specific functions for PySide compatibility.
  204. QtCore.Signal = QtCore.pyqtSignal
  205. QtCore.Slot = QtCore.pyqtSlot
  206. # Join QtGui and QtWidgets for Qt4 compatibility.
  207. QtGuiCompat = types.ModuleType("QtGuiCompat")
  208. QtGuiCompat.__dict__.update(QtGui.__dict__)
  209. QtGuiCompat.__dict__.update(QtWidgets.__dict__)
  210. api = QT_API_PYQT6
  211. return QtCore, QtGuiCompat, QtSvg, api
  212. def import_pyside():
  213. """
  214. Import PySide
  215. ImportErrors raised within this function are non-recoverable
  216. """
  217. from PySide import QtGui, QtCore, QtSvg
  218. return QtCore, QtGui, QtSvg, QT_API_PYSIDE
  219. def import_pyside2():
  220. """
  221. Import PySide2
  222. ImportErrors raised within this function are non-recoverable
  223. """
  224. from PySide2 import QtGui, QtCore, QtSvg, QtWidgets, QtPrintSupport
  225. # Join QtGui and QtWidgets for Qt4 compatibility.
  226. QtGuiCompat = types.ModuleType('QtGuiCompat')
  227. QtGuiCompat.__dict__.update(QtGui.__dict__)
  228. QtGuiCompat.__dict__.update(QtWidgets.__dict__)
  229. QtGuiCompat.__dict__.update(QtPrintSupport.__dict__)
  230. return QtCore, QtGuiCompat, QtSvg, QT_API_PYSIDE2
  231. def import_pyside6():
  232. """
  233. Import PySide6
  234. ImportErrors raised within this function are non-recoverable
  235. """
  236. def get_attrs(module):
  237. return {
  238. name: getattr(module, name)
  239. for name in dir(module)
  240. if not name.startswith("_")
  241. }
  242. from PySide6 import QtGui, QtCore, QtSvg, QtWidgets, QtPrintSupport
  243. # Join QtGui and QtWidgets for Qt4 compatibility.
  244. QtGuiCompat = types.ModuleType("QtGuiCompat")
  245. QtGuiCompat.__dict__.update(QtGui.__dict__)
  246. if QtCore.__version_info__ < (6, 7):
  247. QtGuiCompat.__dict__.update(QtWidgets.__dict__)
  248. QtGuiCompat.__dict__.update(QtPrintSupport.__dict__)
  249. else:
  250. QtGuiCompat.__dict__.update(get_attrs(QtWidgets))
  251. QtGuiCompat.__dict__.update(get_attrs(QtPrintSupport))
  252. return QtCore, QtGuiCompat, QtSvg, QT_API_PYSIDE6
  253. def load_qt(api_options):
  254. """
  255. Attempt to import Qt, given a preference list
  256. of permissible bindings
  257. It is safe to call this function multiple times.
  258. Parameters
  259. ----------
  260. api_options : List of strings
  261. The order of APIs to try. Valid items are 'pyside', 'pyside2',
  262. 'pyqt', 'pyqt5', 'pyqtv1' and 'pyqtdefault'
  263. Returns
  264. -------
  265. A tuple of QtCore, QtGui, QtSvg, QT_API
  266. The first three are the Qt modules. The last is the
  267. string indicating which module was loaded.
  268. Raises
  269. ------
  270. ImportError, if it isn't possible to import any requested
  271. bindings (either because they aren't installed, or because
  272. an incompatible library has already been installed)
  273. """
  274. loaders = {
  275. # Qt6
  276. QT_API_PYQT6: import_pyqt6,
  277. QT_API_PYSIDE6: import_pyside6,
  278. # Qt5
  279. QT_API_PYQT5: import_pyqt5,
  280. QT_API_PYSIDE2: import_pyside2,
  281. # Qt4
  282. QT_API_PYSIDE: import_pyside,
  283. QT_API_PYQT: import_pyqt4,
  284. QT_API_PYQTv1: partial(import_pyqt4, version=1),
  285. # default
  286. QT_API_PYQT_DEFAULT: import_pyqt6,
  287. }
  288. for api in api_options:
  289. if api not in loaders:
  290. raise RuntimeError(
  291. "Invalid Qt API %r, valid values are: %s" %
  292. (api, ", ".join(["%r" % k for k in loaders.keys()])))
  293. if not can_import(api):
  294. continue
  295. #cannot safely recover from an ImportError during this
  296. result = loaders[api]()
  297. api = result[-1] # changed if api = QT_API_PYQT_DEFAULT
  298. commit_api(api)
  299. return result
  300. else:
  301. # Clear the environment variable since it doesn't work.
  302. if "QT_API" in os.environ:
  303. del os.environ["QT_API"]
  304. raise ImportError(
  305. """
  306. Could not load requested Qt binding. Please ensure that
  307. PyQt4 >= 4.7, PyQt5, PyQt6, PySide >= 1.0.3, PySide2, or
  308. PySide6 is available, and only one is imported per session.
  309. Currently-imported Qt library: %r
  310. PyQt5 available (requires QtCore, QtGui, QtSvg, QtWidgets): %s
  311. PyQt6 available (requires QtCore, QtGui, QtSvg, QtWidgets): %s
  312. PySide2 installed: %s
  313. PySide6 installed: %s
  314. Tried to load: %r
  315. """
  316. % (
  317. loaded_api(),
  318. has_binding(QT_API_PYQT5),
  319. has_binding(QT_API_PYQT6),
  320. has_binding(QT_API_PYSIDE2),
  321. has_binding(QT_API_PYSIDE6),
  322. api_options,
  323. )
  324. )
  325. def enum_factory(QT_API, QtCore):
  326. """Construct an enum helper to account for PyQt5 <-> PyQt6 changes."""
  327. @lru_cache(None)
  328. def _enum(name):
  329. # foo.bar.Enum.Entry (PyQt6) <=> foo.bar.Entry (non-PyQt6).
  330. return operator.attrgetter(
  331. name if QT_API == QT_API_PYQT6 else name.rpartition(".")[0]
  332. )(sys.modules[QtCore.__package__])
  333. return _enum