qt_loaders.py 8.3 KB

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