PostProcessingPlugin.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  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 configparser #The script lists are stored in metadata as serialised config files.
  10. import io #To allow configparser to write to a string.
  11. import os.path
  12. import pkgutil
  13. import sys
  14. import importlib.util
  15. from UM.i18n import i18nCatalog
  16. i18n_catalog = i18nCatalog("cura")
  17. ## The post processing plugin is an Extension type plugin that enables pre-written scripts to post process generated
  18. # g-code files.
  19. class PostProcessingPlugin(QObject, Extension):
  20. def __init__(self, parent = None):
  21. super().__init__(parent)
  22. self.addMenuItem(i18n_catalog.i18n("Modify G-Code"), self.showPopup)
  23. self._view = None
  24. # Loaded scripts are all scripts that can be used
  25. self._loaded_scripts = {}
  26. self._script_labels = {}
  27. # Script list contains instances of scripts in loaded_scripts.
  28. # There can be duplicates, which will be executed in sequence.
  29. self._script_list = []
  30. self._selected_script_index = -1
  31. Application.getInstance().getOutputDeviceManager().writeStarted.connect(self.execute)
  32. Application.getInstance().globalContainerStackChanged.connect(self._onGlobalContainerStackChanged) #When the current printer changes, update the list of scripts.
  33. Application.getInstance().mainWindowChanged.connect(self._createView) #When the main window is created, create the view so that we can display the post-processing icon if necessary.
  34. selectedIndexChanged = pyqtSignal()
  35. @pyqtProperty("QVariant", notify = selectedIndexChanged)
  36. def selectedScriptDefinitionId(self):
  37. try:
  38. return self._script_list[self._selected_script_index].getDefinitionId()
  39. except:
  40. return ""
  41. @pyqtProperty("QVariant", notify=selectedIndexChanged)
  42. def selectedScriptStackId(self):
  43. try:
  44. return self._script_list[self._selected_script_index].getStackId()
  45. except:
  46. return ""
  47. ## Execute all post-processing scripts on the gcode.
  48. def execute(self, output_device):
  49. scene = Application.getInstance().getController().getScene()
  50. # If the scene does not have a gcode, do nothing
  51. if not hasattr(scene, "gcode_dict"):
  52. return
  53. gcode_dict = getattr(scene, "gcode_dict")
  54. if not gcode_dict:
  55. return
  56. # get gcode list for the active build plate
  57. active_build_plate_id = Application.getInstance().getMultiBuildPlateModel().activeBuildPlate
  58. gcode_list = gcode_dict[active_build_plate_id]
  59. if not gcode_list:
  60. return
  61. if ";POSTPROCESSED" not in gcode_list[0]:
  62. for script in self._script_list:
  63. try:
  64. gcode_list = script.execute(gcode_list)
  65. except Exception:
  66. Logger.logException("e", "Exception in post-processing script.")
  67. if len(self._script_list): # Add comment to g-code if any changes were made.
  68. gcode_list[0] += ";POSTPROCESSED\n"
  69. gcode_dict[active_build_plate_id] = gcode_list
  70. setattr(scene, "gcode_dict", gcode_dict)
  71. else:
  72. Logger.log("e", "Already post processed")
  73. @pyqtSlot(int)
  74. def setSelectedScriptIndex(self, index):
  75. self._selected_script_index = index
  76. self.selectedIndexChanged.emit()
  77. @pyqtProperty(int, notify = selectedIndexChanged)
  78. def selectedScriptIndex(self):
  79. return self._selected_script_index
  80. @pyqtSlot(int, int)
  81. def moveScript(self, index, new_index):
  82. if new_index < 0 or new_index > len(self._script_list) - 1:
  83. return # nothing needs to be done
  84. else:
  85. # Magical switch code.
  86. self._script_list[new_index], self._script_list[index] = self._script_list[index], self._script_list[new_index]
  87. self.scriptListChanged.emit()
  88. self.selectedIndexChanged.emit() #Ensure that settings are updated
  89. self._propertyChanged()
  90. ## Remove a script from the active script list by index.
  91. @pyqtSlot(int)
  92. def removeScriptByIndex(self, index):
  93. self._script_list.pop(index)
  94. if len(self._script_list) - 1 < self._selected_script_index:
  95. self._selected_script_index = len(self._script_list) - 1
  96. self.scriptListChanged.emit()
  97. self.selectedIndexChanged.emit() # Ensure that settings are updated
  98. self._propertyChanged()
  99. ## Load all scripts from all paths where scripts can be found.
  100. #
  101. # This should probably only be done on init.
  102. def loadAllScripts(self):
  103. if self._loaded_scripts: #Already loaded.
  104. return
  105. #The PostProcessingPlugin path is for built-in scripts.
  106. #The Resources path is where the user should store custom scripts.
  107. #The Preferences path is legacy, where the user may previously have stored scripts.
  108. for root in [PluginRegistry.getInstance().getPluginPath("PostProcessingPlugin"), Resources.getStoragePath(Resources.Resources), Resources.getStoragePath(Resources.Preferences)]:
  109. path = os.path.join(root, "scripts")
  110. if not os.path.isdir(path):
  111. try:
  112. os.makedirs(path)
  113. except OSError:
  114. Logger.log("w", "Unable to create a folder for scripts: " + path)
  115. continue
  116. self.loadScripts(path)
  117. ## Load all scripts from provided path.
  118. # This should probably only be done on init.
  119. # \param path Path to check for scripts.
  120. def loadScripts(self, path):
  121. ## Load all scripts in the scripts folders
  122. scripts = pkgutil.iter_modules(path = [path])
  123. for loader, script_name, ispkg in scripts:
  124. # Iterate over all scripts.
  125. if script_name not in sys.modules:
  126. try:
  127. spec = importlib.util.spec_from_file_location(__name__ + "." + script_name, os.path.join(path, script_name + ".py"))
  128. loaded_script = importlib.util.module_from_spec(spec)
  129. spec.loader.exec_module(loaded_script)
  130. sys.modules[script_name] = loaded_script #TODO: This could be a security risk. Overwrite any module with a user-provided name?
  131. loaded_class = getattr(loaded_script, script_name)
  132. temp_object = loaded_class()
  133. Logger.log("d", "Begin loading of script: %s", script_name)
  134. try:
  135. setting_data = temp_object.getSettingData()
  136. if "name" in setting_data and "key" in setting_data:
  137. self._script_labels[setting_data["key"]] = setting_data["name"]
  138. self._loaded_scripts[setting_data["key"]] = loaded_class
  139. else:
  140. Logger.log("w", "Script %s.py has no name or key", script_name)
  141. self._script_labels[script_name] = script_name
  142. self._loaded_scripts[script_name] = loaded_class
  143. except AttributeError:
  144. Logger.log("e", "Script %s.py is not a recognised script type. Ensure it inherits Script", script_name)
  145. except NotImplementedError:
  146. Logger.log("e", "Script %s.py has no implemented settings", script_name)
  147. except Exception as e:
  148. Logger.logException("e", "Exception occurred while loading post processing plugin: {error_msg}".format(error_msg = str(e)))
  149. loadedScriptListChanged = pyqtSignal()
  150. @pyqtProperty("QVariantList", notify = loadedScriptListChanged)
  151. def loadedScriptList(self):
  152. return sorted(list(self._loaded_scripts.keys()))
  153. @pyqtSlot(str, result = str)
  154. def getScriptLabelByKey(self, key):
  155. return self._script_labels[key]
  156. scriptListChanged = pyqtSignal()
  157. @pyqtProperty("QVariantList", notify = scriptListChanged)
  158. def scriptList(self):
  159. script_list = [script.getSettingData()["key"] for script in self._script_list]
  160. return script_list
  161. @pyqtSlot(str)
  162. def addScriptToList(self, key):
  163. Logger.log("d", "Adding script %s to list.", key)
  164. new_script = self._loaded_scripts[key]()
  165. self._script_list.append(new_script)
  166. self.setSelectedScriptIndex(len(self._script_list) - 1)
  167. self.scriptListChanged.emit()
  168. self._propertyChanged()
  169. ## When the global container stack is changed, swap out the list of active
  170. # scripts.
  171. def _onGlobalContainerStackChanged(self):
  172. self.loadAllScripts()
  173. new_stack = Application.getInstance().getGlobalContainerStack()
  174. self._script_list.clear()
  175. if not new_stack.getMetaDataEntry("post_processing_scripts"): #Missing or empty.
  176. self.scriptListChanged.emit() #Even emit this if it didn't change. We want it to write the empty list to the stack's metadata.
  177. return
  178. self._script_list.clear()
  179. scripts_list_strs = new_stack.getMetaDataEntry("post_processing_scripts")
  180. for script_str in scripts_list_strs.split("\n"): #Encoded config files should never contain three newlines in a row. At most 2, just before section headers.
  181. if not script_str: #There were no scripts in this one (or a corrupt file caused more than 3 consecutive newlines here).
  182. continue
  183. script_str = script_str.replace(r"\\\n", "\n").replace(r"\\\\", "\\\\") #Unescape escape sequences.
  184. script_parser = configparser.ConfigParser(interpolation = None)
  185. script_parser.optionxform = str #Don't transform the setting keys as they are case-sensitive.
  186. script_parser.read_string(script_str)
  187. for script_name, settings in script_parser.items(): #There should only be one, really! Otherwise we can't guarantee the order or allow multiple uses of the same script.
  188. if script_name == "DEFAULT": #ConfigParser always has a DEFAULT section, but we don't fill it. Ignore this one.
  189. continue
  190. if script_name not in self._loaded_scripts: #Don't know this post-processing plug-in.
  191. Logger.log("e", "Unknown post-processing script {script_name} was encountered in this global stack.".format(script_name = script_name))
  192. continue
  193. new_script = self._loaded_scripts[script_name]()
  194. for setting_key, setting_value in settings.items(): #Put all setting values into the script.
  195. new_script._instance.setProperty(setting_key, "value", setting_value)
  196. self._script_list.append(new_script)
  197. self.setSelectedScriptIndex(0)
  198. self.scriptListChanged.emit()
  199. @pyqtSlot()
  200. def writeScriptsToStack(self):
  201. script_list_strs = []
  202. for script in self._script_list:
  203. parser = configparser.ConfigParser(interpolation = None) #We'll encode the script as a config with one section. The section header is the key and its values are the settings.
  204. parser.optionxform = str #Don't transform the setting keys as they are case-sensitive.
  205. script_name = script.getSettingData()["key"]
  206. parser.add_section(script_name)
  207. for key in script.getSettingData()["settings"]:
  208. value = script.getSettingValueByKey(key)
  209. parser[script_name][key] = str(value)
  210. serialized = io.StringIO() #ConfigParser can only write to streams. Fine.
  211. parser.write(serialized)
  212. serialized.seek(0)
  213. script_str = serialized.read()
  214. script_str = script_str.replace("\\\\", r"\\\\").replace("\n", r"\\\n") #Escape newlines because configparser sees those as section delimiters.
  215. script_list_strs.append(script_str)
  216. script_list_strs = "\n".join(script_list_strs) #ConfigParser should never output three newlines in a row when serialised, so it's a safe delimiter.
  217. global_stack = Application.getInstance().getGlobalContainerStack()
  218. if "post_processing_scripts" not in global_stack.getMetaData():
  219. global_stack.addMetaDataEntry("post_processing_scripts", "")
  220. Application.getInstance().getGlobalContainerStack().setMetaDataEntry("post_processing_scripts", script_list_strs)
  221. ## Creates the view used by show popup. The view is saved because of the fairly aggressive garbage collection.
  222. def _createView(self):
  223. Logger.log("d", "Creating post processing plugin view.")
  224. self.loadAllScripts()
  225. # Create the plugin dialog component
  226. path = os.path.join(PluginRegistry.getInstance().getPluginPath("PostProcessingPlugin"), "PostProcessingPlugin.qml")
  227. self._view = Application.getInstance().createQmlComponent(path, {"manager": self})
  228. Logger.log("d", "Post processing view created.")
  229. # Create the save button component
  230. Application.getInstance().addAdditionalComponent("saveButton", self._view.findChild(QObject, "postProcessingSaveAreaButton"))
  231. ## Show the (GUI) popup of the post processing plugin.
  232. def showPopup(self):
  233. if self._view is None:
  234. self._createView()
  235. self._view.show()
  236. ## Property changed: trigger re-slice
  237. # To do this we use the global container stack propertyChanged.
  238. # Re-slicing is necessary for setting changes in this plugin, because the changes
  239. # are applied only once per "fresh" gcode
  240. def _propertyChanged(self):
  241. global_container_stack = Application.getInstance().getGlobalContainerStack()
  242. global_container_stack.propertyChanged.emit("post_processing_plugin", "value")