PostProcessingPlugin.py 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  1. # Copyright (c) 2015 Jaime van Kessel, Ultimaker B.V.
  2. # The PostProcessingPlugin is released under the terms of the AGPLv3 or higher.
  3. from PyQt5.QtCore import QObject, pyqtProperty, pyqtSignal, pyqtSlot
  4. from UM.PluginRegistry import PluginRegistry
  5. from UM.Resources import Resources
  6. from UM.Application import Application
  7. from UM.Extension import Extension
  8. from UM.Logger import Logger
  9. import os.path
  10. import pkgutil
  11. import sys
  12. import importlib.util
  13. from UM.i18n import i18nCatalog
  14. i18n_catalog = i18nCatalog("cura")
  15. ## The post processing plugin is an Extension type plugin that enables pre-written scripts to post process generated
  16. # g-code files.
  17. class PostProcessingPlugin(QObject, Extension):
  18. def __init__(self, parent = None):
  19. super().__init__(parent)
  20. self.addMenuItem(i18n_catalog.i18n("Modify G-Code"), self.showPopup)
  21. self._view = None
  22. # Loaded scripts are all scripts that can be used
  23. self._loaded_scripts = {}
  24. self._script_labels = {}
  25. # Script list contains instances of scripts in loaded_scripts.
  26. # There can be duplicates, which will be executed in sequence.
  27. self._script_list = []
  28. self._selected_script_index = -1
  29. Application.getInstance().getOutputDeviceManager().writeStarted.connect(self.execute)
  30. selectedIndexChanged = pyqtSignal()
  31. @pyqtProperty("QVariant", notify = selectedIndexChanged)
  32. def selectedScriptDefinitionId(self):
  33. try:
  34. return self._script_list[self._selected_script_index].getDefinitionId()
  35. except:
  36. return ""
  37. @pyqtProperty("QVariant", notify=selectedIndexChanged)
  38. def selectedScriptStackId(self):
  39. try:
  40. return self._script_list[self._selected_script_index].getStackId()
  41. except:
  42. return ""
  43. ## Execute all post-processing scripts on the gcode.
  44. def execute(self, output_device):
  45. scene = Application.getInstance().getController().getScene()
  46. # If the scene does not have a gcode, do nothing
  47. if not hasattr(scene, "gcode_dict"):
  48. return
  49. gcode_dict = getattr(scene, "gcode_dict")
  50. if not gcode_dict:
  51. return
  52. # get gcode list for the active build plate
  53. active_build_plate_id = Application.getInstance().getMultiBuildPlateModel().activeBuildPlate
  54. gcode_list = gcode_dict[active_build_plate_id]
  55. if not gcode_list:
  56. return
  57. if ";POSTPROCESSED" not in gcode_list[0]:
  58. for script in self._script_list:
  59. try:
  60. gcode_list = script.execute(gcode_list)
  61. except Exception:
  62. Logger.logException("e", "Exception in post-processing script.")
  63. if len(self._script_list): # Add comment to g-code if any changes were made.
  64. gcode_list[0] += ";POSTPROCESSED\n"
  65. gcode_dict[active_build_plate_id] = gcode_list
  66. setattr(scene, "gcode_dict", gcode_dict)
  67. else:
  68. Logger.log("e", "Already post processed")
  69. @pyqtSlot(int)
  70. def setSelectedScriptIndex(self, index):
  71. self._selected_script_index = index
  72. self.selectedIndexChanged.emit()
  73. @pyqtProperty(int, notify = selectedIndexChanged)
  74. def selectedScriptIndex(self):
  75. return self._selected_script_index
  76. @pyqtSlot(int, int)
  77. def moveScript(self, index, new_index):
  78. if new_index < 0 or new_index > len(self._script_list) - 1:
  79. return # nothing needs to be done
  80. else:
  81. # Magical switch code.
  82. self._script_list[new_index], self._script_list[index] = self._script_list[index], self._script_list[new_index]
  83. self.scriptListChanged.emit()
  84. self.selectedIndexChanged.emit() #Ensure that settings are updated
  85. self._propertyChanged()
  86. ## Remove a script from the active script list by index.
  87. @pyqtSlot(int)
  88. def removeScriptByIndex(self, index):
  89. self._script_list.pop(index)
  90. if len(self._script_list) - 1 < self._selected_script_index:
  91. self._selected_script_index = len(self._script_list) - 1
  92. self.scriptListChanged.emit()
  93. self.selectedIndexChanged.emit() # Ensure that settings are updated
  94. self._propertyChanged()
  95. ## Load all scripts from provided path.
  96. # This should probably only be done on init.
  97. # \param path Path to check for scripts.
  98. def loadAllScripts(self, path):
  99. scripts = pkgutil.iter_modules(path = [path])
  100. for loader, script_name, ispkg in scripts:
  101. # Iterate over all scripts.
  102. if script_name not in sys.modules:
  103. try:
  104. spec = importlib.util.spec_from_file_location(__name__ + "." + script_name, os.path.join(path, script_name + ".py"))
  105. loaded_script = importlib.util.module_from_spec(spec)
  106. spec.loader.exec_module(loaded_script)
  107. sys.modules[script_name] = loaded_script
  108. loaded_class = getattr(loaded_script, script_name)
  109. temp_object = loaded_class()
  110. Logger.log("d", "Begin loading of script: %s", script_name)
  111. try:
  112. setting_data = temp_object.getSettingData()
  113. if "name" in setting_data and "key" in setting_data:
  114. self._script_labels[setting_data["key"]] = setting_data["name"]
  115. self._loaded_scripts[setting_data["key"]] = loaded_class
  116. else:
  117. Logger.log("w", "Script %s.py has no name or key", script_name)
  118. self._script_labels[script_name] = script_name
  119. self._loaded_scripts[script_name] = loaded_class
  120. except AttributeError:
  121. Logger.log("e", "Script %s.py is not a recognised script type. Ensure it inherits Script", script_name)
  122. except NotImplementedError:
  123. Logger.log("e", "Script %s.py has no implemented settings", script_name)
  124. except Exception as e:
  125. Logger.logException("e", "Exception occurred while loading post processing plugin: {error_msg}".format(error_msg = str(e)))
  126. self.loadedScriptListChanged.emit()
  127. loadedScriptListChanged = pyqtSignal()
  128. @pyqtProperty("QVariantList", notify = loadedScriptListChanged)
  129. def loadedScriptList(self):
  130. return sorted(list(self._loaded_scripts.keys()))
  131. @pyqtSlot(str, result = str)
  132. def getScriptLabelByKey(self, key):
  133. return self._script_labels[key]
  134. scriptListChanged = pyqtSignal()
  135. @pyqtProperty("QVariantList", notify = scriptListChanged)
  136. def scriptList(self):
  137. script_list = [script.getSettingData()["key"] for script in self._script_list]
  138. return script_list
  139. @pyqtSlot(str)
  140. def addScriptToList(self, key):
  141. Logger.log("d", "Adding script %s to list.", key)
  142. new_script = self._loaded_scripts[key]()
  143. self._script_list.append(new_script)
  144. self.setSelectedScriptIndex(len(self._script_list) - 1)
  145. self.scriptListChanged.emit()
  146. self._propertyChanged()
  147. ## Creates the view used by show popup. The view is saved because of the fairly aggressive garbage collection.
  148. def _createView(self):
  149. Logger.log("d", "Creating post processing plugin view.")
  150. ## Load all scripts in the scripts folders
  151. # The PostProcessingPlugin path is for built-in scripts.
  152. # The Resources path is where the user should store custom scripts.
  153. # The Preferences path is legacy, where the user may previously have stored scripts.
  154. for root in [PluginRegistry.getInstance().getPluginPath("PostProcessingPlugin"), Resources.getStoragePath(Resources.Resources), Resources.getStoragePath(Resources.Preferences)]:
  155. path = os.path.join(root, "scripts")
  156. if not os.path.isdir(path):
  157. try:
  158. os.makedirs(path)
  159. except OSError:
  160. Logger.log("w", "Unable to create a folder for scripts: " + path)
  161. continue
  162. self.loadAllScripts(path)
  163. # Create the plugin dialog component
  164. path = os.path.join(PluginRegistry.getInstance().getPluginPath("PostProcessingPlugin"), "PostProcessingPlugin.qml")
  165. self._view = Application.getInstance().createQmlComponent(path, {"manager": self})
  166. Logger.log("d", "Post processing view created.")
  167. # Create the save button component
  168. Application.getInstance().addAdditionalComponent("saveButton", self._view.findChild(QObject, "postProcessingSaveAreaButton"))
  169. ## Show the (GUI) popup of the post processing plugin.
  170. def showPopup(self):
  171. if self._view is None:
  172. self._createView()
  173. self._view.show()
  174. ## Property changed: trigger re-slice
  175. # To do this we use the global container stack propertyChanged.
  176. # Re-slicing is necessary for setting changes in this plugin, because the changes
  177. # are applied only once per "fresh" gcode
  178. def _propertyChanged(self):
  179. global_container_stack = Application.getInstance().getGlobalContainerStack()
  180. global_container_stack.propertyChanged.emit("post_processing_plugin", "value")