PostProcessingPlugin.py 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  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().getBuildPlateModel().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. spec = importlib.util.spec_from_file_location(__name__ + "." + script_name, os.path.join(path, script_name + ".py"))
  104. loaded_script = importlib.util.module_from_spec(spec)
  105. spec.loader.exec_module(loaded_script)
  106. sys.modules[script_name] = loaded_script
  107. loaded_class = getattr(loaded_script, script_name)
  108. temp_object = loaded_class()
  109. Logger.log("d", "Begin loading of script: %s", script_name)
  110. try:
  111. setting_data = temp_object.getSettingData()
  112. if "name" in setting_data and "key" in setting_data:
  113. self._script_labels[setting_data["key"]] = setting_data["name"]
  114. self._loaded_scripts[setting_data["key"]] = loaded_class
  115. else:
  116. Logger.log("w", "Script %s.py has no name or key", script_name)
  117. self._script_labels[script_name] = script_name
  118. self._loaded_scripts[script_name] = loaded_class
  119. except AttributeError:
  120. Logger.log("e", "Script %s.py is not a recognised script type. Ensure it inherits Script", script_name)
  121. except NotImplementedError:
  122. Logger.log("e", "Script %s.py has no implemented settings", script_name)
  123. self.loadedScriptListChanged.emit()
  124. loadedScriptListChanged = pyqtSignal()
  125. @pyqtProperty("QVariantList", notify = loadedScriptListChanged)
  126. def loadedScriptList(self):
  127. return sorted(list(self._loaded_scripts.keys()))
  128. @pyqtSlot(str, result = str)
  129. def getScriptLabelByKey(self, key):
  130. return self._script_labels[key]
  131. scriptListChanged = pyqtSignal()
  132. @pyqtProperty("QVariantList", notify = scriptListChanged)
  133. def scriptList(self):
  134. script_list = [script.getSettingData()["key"] for script in self._script_list]
  135. return script_list
  136. @pyqtSlot(str)
  137. def addScriptToList(self, key):
  138. Logger.log("d", "Adding script %s to list.", key)
  139. new_script = self._loaded_scripts[key]()
  140. self._script_list.append(new_script)
  141. self.setSelectedScriptIndex(len(self._script_list) - 1)
  142. self.scriptListChanged.emit()
  143. self._propertyChanged()
  144. ## Creates the view used by show popup. The view is saved because of the fairly aggressive garbage collection.
  145. def _createView(self):
  146. Logger.log("d", "Creating post processing plugin view.")
  147. ## Load all scripts in the scripts folders
  148. for root in [PluginRegistry.getInstance().getPluginPath("PostProcessingPlugin"), Resources.getStoragePath(Resources.Preferences)]:
  149. try:
  150. path = os.path.join(root, "scripts")
  151. if not os.path.isdir(path):
  152. try:
  153. os.makedirs(path)
  154. except OSError:
  155. Logger.log("w", "Unable to create a folder for scripts: " + path)
  156. continue
  157. self.loadAllScripts(path)
  158. except Exception as e:
  159. Logger.logException("e", "Exception occurred while loading post processing plugin: {error_msg}".format(error_msg = str(e)))
  160. # Create the plugin dialog component
  161. path = os.path.join(PluginRegistry.getInstance().getPluginPath("PostProcessingPlugin"), "PostProcessingPlugin.qml")
  162. self._view = Application.getInstance().createQmlComponent(path, {"manager": self})
  163. Logger.log("d", "Post processing view created.")
  164. # Create the save button component
  165. Application.getInstance().addAdditionalComponent("saveButton", self._view.findChild(QObject, "postProcessingSaveAreaButton"))
  166. ## Show the (GUI) popup of the post processing plugin.
  167. def showPopup(self):
  168. if self._view is None:
  169. self._createView()
  170. self._view.show()
  171. ## Property changed: trigger re-slice
  172. # To do this we use the global container stack propertyChanged.
  173. # Re-slicing is necessary for setting changes in this plugin, because the changes
  174. # are applied only once per "fresh" gcode
  175. def _propertyChanged(self):
  176. global_container_stack = Application.getInstance().getGlobalContainerStack()
  177. global_container_stack.propertyChanged.emit("post_processing_plugin", "value")