qt_loaders.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  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 sys
  10. import types
  11. from functools import partial
  12. from IPython.utils.version import check_version
  13. # Available APIs.
  14. QT_API_PYQT = 'pyqt' # Force version 2
  15. QT_API_PYQT5 = 'pyqt5'
  16. QT_API_PYQTv1 = 'pyqtv1' # Force version 2
  17. QT_API_PYQT_DEFAULT = 'pyqtdefault' # use system default for version 1 vs. 2
  18. QT_API_PYSIDE = 'pyside'
  19. QT_API_PYSIDE2 = 'pyside2'
  20. api_to_module = {QT_API_PYSIDE2: 'PySide2',
  21. QT_API_PYSIDE: 'PySide',
  22. QT_API_PYQT: 'PyQt4',
  23. QT_API_PYQTv1: 'PyQt4',
  24. QT_API_PYQT5: 'PyQt5',
  25. QT_API_PYQT_DEFAULT: 'PyQt4',
  26. }
  27. class ImportDenier(object):
  28. """Import Hook that will guard against bad Qt imports
  29. once IPython commits to a specific binding
  30. """
  31. def __init__(self):
  32. self.__forbidden = set()
  33. def forbid(self, module_name):
  34. sys.modules.pop(module_name, None)
  35. self.__forbidden.add(module_name)
  36. def find_module(self, fullname, path=None):
  37. if path:
  38. return
  39. if fullname in self.__forbidden:
  40. return self
  41. def load_module(self, fullname):
  42. raise ImportError("""
  43. Importing %s disabled by IPython, which has
  44. already imported an Incompatible QT Binding: %s
  45. """ % (fullname, loaded_api()))
  46. ID = ImportDenier()
  47. sys.meta_path.insert(0, ID)
  48. def commit_api(api):
  49. """Commit to a particular API, and trigger ImportErrors on subsequent
  50. dangerous imports"""
  51. if api == QT_API_PYSIDE2:
  52. ID.forbid('PySide')
  53. ID.forbid('PyQt4')
  54. ID.forbid('PyQt5')
  55. if api == QT_API_PYSIDE:
  56. ID.forbid('PySide2')
  57. ID.forbid('PyQt4')
  58. ID.forbid('PyQt5')
  59. elif api == QT_API_PYQT5:
  60. ID.forbid('PySide2')
  61. ID.forbid('PySide')
  62. ID.forbid('PyQt4')
  63. else: # There are three other possibilities, all representing PyQt4
  64. ID.forbid('PyQt5')
  65. ID.forbid('PySide2')
  66. ID.forbid('PySide')
  67. def loaded_api():
  68. """Return which API is loaded, if any
  69. If this returns anything besides None,
  70. importing any other Qt binding is unsafe.
  71. Returns
  72. -------
  73. None, 'pyside2', 'pyside', 'pyqt', 'pyqt5', or 'pyqtv1'
  74. """
  75. if 'PyQt4.QtCore' in sys.modules:
  76. if qtapi_version() == 2:
  77. return QT_API_PYQT
  78. else:
  79. return QT_API_PYQTv1
  80. elif 'PySide.QtCore' in sys.modules:
  81. return QT_API_PYSIDE
  82. elif 'PySide2.QtCore' in sys.modules:
  83. return QT_API_PYSIDE2
  84. elif 'PyQt5.QtCore' in sys.modules:
  85. return QT_API_PYQT5
  86. return None
  87. def has_binding(api):
  88. """Safely check for PyQt4/5, PySide or PySide2, without importing submodules
  89. Supports Python <= 3.3
  90. Parameters
  91. ----------
  92. api : str [ 'pyqtv1' | 'pyqt' | 'pyqt5' | 'pyside' | 'pyside2' | 'pyqtdefault']
  93. Which module to check for
  94. Returns
  95. -------
  96. True if the relevant module appears to be importable
  97. """
  98. # we can't import an incomplete pyside and pyqt4
  99. # this will cause a crash in sip (#1431)
  100. # check for complete presence before importing
  101. module_name = api_to_module[api]
  102. import imp
  103. try:
  104. #importing top level PyQt4/PySide module is ok...
  105. mod = __import__(module_name)
  106. #...importing submodules is not
  107. imp.find_module('QtCore', mod.__path__)
  108. imp.find_module('QtGui', mod.__path__)
  109. imp.find_module('QtSvg', mod.__path__)
  110. if api in (QT_API_PYQT5, QT_API_PYSIDE2):
  111. # QT5 requires QtWidgets too
  112. imp.find_module('QtWidgets', mod.__path__)
  113. #we can also safely check PySide version
  114. if api == QT_API_PYSIDE:
  115. return check_version(mod.__version__, '1.0.3')
  116. else:
  117. return True
  118. except ImportError:
  119. return False
  120. def has_binding_new(api):
  121. """Safely check for PyQt4/5, PySide or PySide2, without importing submodules
  122. Supports Python >= 3.4
  123. Parameters
  124. ----------
  125. api : str [ 'pyqtv1' | 'pyqt' | 'pyqt5' | 'pyside' | 'pyside2' | 'pyqtdefault']
  126. Which module to check for
  127. Returns
  128. -------
  129. True if the relevant module appears to be importable
  130. """
  131. module_name = api_to_module[api]
  132. from importlib.util import find_spec
  133. required = ['QtCore', 'QtGui', 'QtSvg']
  134. if api in (QT_API_PYQT5, QT_API_PYSIDE2):
  135. # QT5 requires QtWidgets too
  136. required.append('QtWidgets')
  137. for submod in required:
  138. try:
  139. spec = find_spec('%s.%s' % (module_name, submod))
  140. except ImportError:
  141. # Package (e.g. PyQt5) not found
  142. return False
  143. else:
  144. if spec is None:
  145. # Submodule (e.g. PyQt5.QtCore) not found
  146. return False
  147. if api == QT_API_PYSIDE:
  148. # We can also safely check PySide version
  149. import PySide
  150. return check_version(PySide.__version__, '1.0.3')
  151. return True
  152. if sys.version_info >= (3, 4):
  153. has_binding = has_binding_new
  154. def qtapi_version():
  155. """Return which QString API has been set, if any
  156. Returns
  157. -------
  158. The QString API version (1 or 2), or None if not set
  159. """
  160. try:
  161. import sip
  162. except ImportError:
  163. return
  164. try:
  165. return sip.getapi('QString')
  166. except ValueError:
  167. return
  168. def can_import(api):
  169. """Safely query whether an API is importable, without importing it"""
  170. if not has_binding(api):
  171. return False
  172. current = loaded_api()
  173. if api == QT_API_PYQT_DEFAULT:
  174. return current in [QT_API_PYQT, QT_API_PYQTv1, None]
  175. else:
  176. return current in [api, None]
  177. def import_pyqt4(version=2):
  178. """
  179. Import PyQt4
  180. Parameters
  181. ----------
  182. version : 1, 2, or None
  183. Which QString/QVariant API to use. Set to None to use the system
  184. default
  185. ImportErrors rasied within this function are non-recoverable
  186. """
  187. # The new-style string API (version=2) automatically
  188. # converts QStrings to Unicode Python strings. Also, automatically unpacks
  189. # QVariants to their underlying objects.
  190. import sip
  191. if version is not None:
  192. sip.setapi('QString', version)
  193. sip.setapi('QVariant', version)
  194. from PyQt4 import QtGui, QtCore, QtSvg
  195. if not check_version(QtCore.PYQT_VERSION_STR, '4.7'):
  196. raise ImportError("IPython requires PyQt4 >= 4.7, found %s" %
  197. QtCore.PYQT_VERSION_STR)
  198. # Alias PyQt-specific functions for PySide compatibility.
  199. QtCore.Signal = QtCore.pyqtSignal
  200. QtCore.Slot = QtCore.pyqtSlot
  201. # query for the API version (in case version == None)
  202. version = sip.getapi('QString')
  203. api = QT_API_PYQTv1 if version == 1 else QT_API_PYQT
  204. return QtCore, QtGui, QtSvg, api
  205. def import_pyqt5():
  206. """
  207. Import PyQt5
  208. ImportErrors rasied within this function are non-recoverable
  209. """
  210. import sip
  211. from PyQt5 import QtCore, QtSvg, QtWidgets, QtGui
  212. # Alias PyQt-specific functions for PySide compatibility.
  213. QtCore.Signal = QtCore.pyqtSignal
  214. QtCore.Slot = QtCore.pyqtSlot
  215. # Join QtGui and QtWidgets for Qt4 compatibility.
  216. QtGuiCompat = types.ModuleType('QtGuiCompat')
  217. QtGuiCompat.__dict__.update(QtGui.__dict__)
  218. QtGuiCompat.__dict__.update(QtWidgets.__dict__)
  219. api = QT_API_PYQT5
  220. return QtCore, QtGuiCompat, QtSvg, api
  221. def import_pyside():
  222. """
  223. Import PySide
  224. ImportErrors raised within this function are non-recoverable
  225. """
  226. from PySide import QtGui, QtCore, QtSvg
  227. return QtCore, QtGui, QtSvg, QT_API_PYSIDE
  228. def import_pyside2():
  229. """
  230. Import PySide2
  231. ImportErrors raised within this function are non-recoverable
  232. """
  233. from PySide2 import QtGui, QtCore, QtSvg, QtWidgets, QtPrintSupport
  234. # Join QtGui and QtWidgets for Qt4 compatibility.
  235. QtGuiCompat = types.ModuleType('QtGuiCompat')
  236. QtGuiCompat.__dict__.update(QtGui.__dict__)
  237. QtGuiCompat.__dict__.update(QtWidgets.__dict__)
  238. QtGuiCompat.__dict__.update(QtPrintSupport.__dict__)
  239. return QtCore, QtGuiCompat, QtSvg, QT_API_PYSIDE2
  240. def load_qt(api_options):
  241. """
  242. Attempt to import Qt, given a preference list
  243. of permissible bindings
  244. It is safe to call this function multiple times.
  245. Parameters
  246. ----------
  247. api_options: List of strings
  248. The order of APIs to try. Valid items are 'pyside', 'pyside2',
  249. 'pyqt', 'pyqt5', 'pyqtv1' and 'pyqtdefault'
  250. Returns
  251. -------
  252. A tuple of QtCore, QtGui, QtSvg, QT_API
  253. The first three are the Qt modules. The last is the
  254. string indicating which module was loaded.
  255. Raises
  256. ------
  257. ImportError, if it isn't possible to import any requested
  258. bindings (either becaues they aren't installed, or because
  259. an incompatible library has already been installed)
  260. """
  261. loaders = {
  262. QT_API_PYSIDE2: import_pyside2,
  263. QT_API_PYSIDE: import_pyside,
  264. QT_API_PYQT: import_pyqt4,
  265. QT_API_PYQT5: import_pyqt5,
  266. QT_API_PYQTv1: partial(import_pyqt4, version=1),
  267. QT_API_PYQT_DEFAULT: partial(import_pyqt4, version=None)
  268. }
  269. for api in api_options:
  270. if api not in loaders:
  271. raise RuntimeError(
  272. "Invalid Qt API %r, valid values are: %s" %
  273. (api, ", ".join(["%r" % k for k in loaders.keys()])))
  274. if not can_import(api):
  275. continue
  276. #cannot safely recover from an ImportError during this
  277. result = loaders[api]()
  278. api = result[-1] # changed if api = QT_API_PYQT_DEFAULT
  279. commit_api(api)
  280. return result
  281. else:
  282. raise ImportError("""
  283. Could not load requested Qt binding. Please ensure that
  284. PyQt4 >= 4.7, PyQt5, PySide >= 1.0.3 or PySide2 is available,
  285. and only one is imported per session.
  286. Currently-imported Qt library: %r
  287. PyQt4 available (requires QtCore, QtGui, QtSvg): %s
  288. PyQt5 available (requires QtCore, QtGui, QtSvg, QtWidgets): %s
  289. PySide >= 1.0.3 installed: %s
  290. PySide2 installed: %s
  291. Tried to load: %r
  292. """ % (loaded_api(),
  293. has_binding(QT_API_PYQT),
  294. has_binding(QT_API_PYQT5),
  295. has_binding(QT_API_PYSIDE),
  296. has_binding(QT_API_PYSIDE2),
  297. api_options))