qobjectcreator.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  1. #############################################################################
  2. ##
  3. ## Copyright (C) 2023 Riverbank Computing Limited.
  4. ## Copyright (C) 2006 Thorsten Marek.
  5. ## All right reserved.
  6. ##
  7. ## This file is part of PyQt.
  8. ##
  9. ## You may use this file under the terms of the GPL v2 or the revised BSD
  10. ## license as follows:
  11. ##
  12. ## "Redistribution and use in source and binary forms, with or without
  13. ## modification, are permitted provided that the following conditions are
  14. ## met:
  15. ## * Redistributions of source code must retain the above copyright
  16. ## notice, this list of conditions and the following disclaimer.
  17. ## * Redistributions in binary form must reproduce the above copyright
  18. ## notice, this list of conditions and the following disclaimer in
  19. ## the documentation and/or other materials provided with the
  20. ## distribution.
  21. ## * Neither the name of the Riverbank Computing Limited nor the names
  22. ## of its contributors may be used to endorse or promote products
  23. ## derived from this software without specific prior written
  24. ## permission.
  25. ##
  26. ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  27. ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  28. ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  29. ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  30. ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  31. ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  32. ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  33. ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  34. ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  35. ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  36. ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
  37. ##
  38. #############################################################################
  39. import logging
  40. import sys
  41. from .as_string import as_string
  42. from .indenter import write_code
  43. from .qtproxies import QtGui, QtWidgets, Literal, strict_getattr
  44. logger = logging.getLogger(__name__)
  45. DEBUG = logger.debug
  46. class _QtWrapper(object):
  47. @classmethod
  48. def search(cls, name):
  49. try:
  50. return strict_getattr(cls.module, name)
  51. except AttributeError:
  52. return None
  53. class _QtGuiWrapper(_QtWrapper):
  54. module = QtGui
  55. class _QtWidgetsWrapper(_QtWrapper):
  56. module = QtWidgets
  57. class _ModuleWrapper(object):
  58. def __init__(self, name, classes):
  59. if "." in name:
  60. idx = name.rfind(".")
  61. self._package = name[:idx]
  62. self._module = name[idx + 1:]
  63. else:
  64. self._package = None
  65. self._module = name
  66. self._classes = classes
  67. self._used = False
  68. def search(self, cls):
  69. if cls in self._classes:
  70. self._used = True
  71. # Remove any C++ scope.
  72. cls = cls.split('.')[-1]
  73. return type(cls, (QtWidgets.QWidget,), {"module": self._module})
  74. else:
  75. return None
  76. def _writeImportCode(self):
  77. if self._used:
  78. if self._package is None:
  79. write_code("import %s" % self._module)
  80. else:
  81. write_code("from %s import %s" % (self._package, self._module))
  82. class _CustomWidgetLoader(object):
  83. def __init__(self):
  84. self._widgets = {}
  85. self._usedWidgets = set()
  86. def addCustomWidget(self, widgetClass, baseClass, module):
  87. assert widgetClass not in self._widgets
  88. self._widgets[widgetClass] = (baseClass, module)
  89. def _resolveBaseclass(self, baseClass):
  90. try:
  91. for x in range(0, 10):
  92. try: return strict_getattr(QtWidgets, baseClass)
  93. except AttributeError: pass
  94. baseClass = self._widgets[baseClass][0]
  95. else:
  96. raise ValueError("baseclass resolve took too long, check custom widgets")
  97. except KeyError:
  98. raise ValueError("unknown baseclass %s" % baseClass)
  99. def search(self, cls):
  100. try:
  101. baseClass = self._resolveBaseclass(self._widgets[cls][0])
  102. DEBUG("resolved baseclass of %s: %s" % (cls, baseClass))
  103. except KeyError:
  104. return None
  105. self._usedWidgets.add(cls)
  106. return type(cls, (baseClass, ), {"module" : ""})
  107. def _writeImportCode(self):
  108. imports = {}
  109. for widget in self._usedWidgets:
  110. _, module = self._widgets[widget]
  111. imports.setdefault(module, []).append(widget)
  112. for module, classes in sorted(imports.items()):
  113. write_code("from %s import %s" % (module, ", ".join(sorted(classes))))
  114. class CompilerCreatorPolicy(object):
  115. def __init__(self):
  116. self._modules = []
  117. def createQtGuiWidgetsWrappers(self):
  118. return [_QtGuiWrapper, _QtWidgetsWrapper]
  119. def createModuleWrapper(self, name, classes):
  120. mw = _ModuleWrapper(name, classes)
  121. self._modules.append(mw)
  122. return mw
  123. def createCustomWidgetLoader(self):
  124. cw = _CustomWidgetLoader()
  125. self._modules.append(cw)
  126. return cw
  127. def instantiate(self, ctor, object_name, ctor_args, ctor_kwargs,
  128. is_attribute, no_instantiation):
  129. return ctor(object_name, ctor_args, ctor_kwargs, is_attribute,
  130. no_instantiation)
  131. def invoke(self, rname, method, args):
  132. return method(rname, *args)
  133. def getSlot(self, object, slotname):
  134. return Literal("%s.%s" % (object, slotname))
  135. def asString(self, s):
  136. return as_string(s)
  137. def _writeOutImports(self):
  138. for module in self._modules:
  139. module._writeImportCode()