objcreator.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  1. #############################################################################
  2. ##
  3. ## Copyright (C) 2015 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 os.path
  40. from .exceptions import NoSuchWidgetError, WidgetPluginError
  41. # The list of directories that are searched for widget plugins. This is
  42. # exposed as part of the API.
  43. widgetPluginPath = [os.path.join(os.path.dirname(__file__), 'widget-plugins')]
  44. MATCH = True
  45. NO_MATCH = False
  46. MODULE = 0
  47. CW_FILTER = 1
  48. class QObjectCreator(object):
  49. def __init__(self, creatorPolicy):
  50. self._cpolicy = creatorPolicy
  51. self._cwFilters = []
  52. self._modules = self._cpolicy.createQtGuiWidgetsWrappers()
  53. # Get the optional plugins.
  54. for plugindir in widgetPluginPath:
  55. try:
  56. plugins = os.listdir(plugindir)
  57. except:
  58. plugins = []
  59. for filename in plugins:
  60. if not filename.endswith('.py'):
  61. continue
  62. filename = os.path.join(plugindir, filename)
  63. plugin_globals = {
  64. "MODULE": MODULE,
  65. "CW_FILTER": CW_FILTER,
  66. "MATCH": MATCH,
  67. "NO_MATCH": NO_MATCH}
  68. plugin_locals = {}
  69. if self.load_plugin(filename, plugin_globals, plugin_locals):
  70. pluginType = plugin_locals["pluginType"]
  71. if pluginType == MODULE:
  72. modinfo = plugin_locals["moduleInformation"]()
  73. self._modules.append(self._cpolicy.createModuleWrapper(*modinfo))
  74. elif pluginType == CW_FILTER:
  75. self._cwFilters.append(plugin_locals["getFilter"]())
  76. else:
  77. raise WidgetPluginError("Unknown plugin type of %s" % filename)
  78. self._customWidgets = self._cpolicy.createCustomWidgetLoader()
  79. self._modules.append(self._customWidgets)
  80. def createQtObject(self, ctor_name, object_name, ctor_args=None,
  81. ctor_kwargs=None, is_attribute=True, no_instantiation=False):
  82. # Handle regular and custom widgets.
  83. ctor = self.findQObjectType(ctor_name)
  84. if ctor is None:
  85. # Handle scoped names, typically static factory methods.
  86. parts = ctor_name.split('.')
  87. if len(parts) > 1:
  88. ctor = self.findQObjectType(parts[0])
  89. if ctor is not None:
  90. for part in parts[1:]:
  91. ctor = getattr(ctor, part, None)
  92. if ctor is None:
  93. break
  94. if ctor is None:
  95. raise NoSuchWidgetError(ctor_name)
  96. return self._cpolicy.instantiate(ctor, object_name, ctor_args,
  97. ctor_kwargs, is_attribute, no_instantiation)
  98. def invoke(self, rname, method, args=()):
  99. return self._cpolicy.invoke(rname, method, args)
  100. def findQObjectType(self, classname):
  101. for module in self._modules:
  102. w = module.search(classname)
  103. if w is not None:
  104. return w
  105. return None
  106. def getSlot(self, obj, slotname):
  107. return self._cpolicy.getSlot(obj, slotname)
  108. def asString(self, s):
  109. return self._cpolicy.asString(s)
  110. def addCustomWidget(self, widgetClass, baseClass, module):
  111. for cwFilter in self._cwFilters:
  112. match, result = cwFilter(widgetClass, baseClass, module)
  113. if match:
  114. widgetClass, baseClass, module = result
  115. break
  116. self._customWidgets.addCustomWidget(widgetClass, baseClass, module)
  117. @staticmethod
  118. def load_plugin(filename, plugin_globals, plugin_locals):
  119. """ Load the plugin from the given file. Return True if the plugin was
  120. loaded, or False if it wanted to be ignored. Raise an exception if
  121. there was an error.
  122. """
  123. plugin = open(filename)
  124. try:
  125. exec(plugin.read(), plugin_globals, plugin_locals)
  126. except ImportError:
  127. return False
  128. except Exception as e:
  129. raise WidgetPluginError("%s: %s" % (e.__class__, str(e)))
  130. finally:
  131. plugin.close()
  132. return True