PostProcessingPlugin.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  1. # Copyright (c) 2018 Jaime van Kessel, Ultimaker B.V.
  2. # The PostProcessingPlugin is released under the terms of the LGPLv3 or higher.
  3. import configparser # The script lists are stored in metadata as serialised config files.
  4. import importlib.util
  5. import io # To allow configparser to write to a string.
  6. import os.path
  7. import pkgutil
  8. import sys
  9. from typing import Dict, Type, TYPE_CHECKING, List, Optional, cast
  10. from PyQt6.QtCore import QObject, pyqtProperty, pyqtSignal, pyqtSlot
  11. from UM.Application import Application
  12. from UM.Extension import Extension
  13. from UM.Logger import Logger
  14. from UM.PluginRegistry import PluginRegistry
  15. from UM.Resources import Resources
  16. from UM.Trust import Trust, TrustBasics
  17. from UM.i18n import i18nCatalog
  18. from cura import ApplicationMetadata
  19. from cura.CuraApplication import CuraApplication
  20. i18n_catalog = i18nCatalog("cura")
  21. if TYPE_CHECKING:
  22. from .Script import Script
  23. class PostProcessingPlugin(QObject, Extension):
  24. """Extension type plugin that enables pre-written scripts to post process g-code files."""
  25. def __init__(self, parent = None) -> None:
  26. QObject.__init__(self, parent)
  27. Extension.__init__(self)
  28. self.setMenuName(i18n_catalog.i18nc("@item:inmenu", "Post Processing"))
  29. self.addMenuItem(i18n_catalog.i18nc("@item:inmenu", "Modify G-Code"), self.showPopup)
  30. self._view = None
  31. # Loaded scripts are all scripts that can be used
  32. self._loaded_scripts = {} # type: Dict[str, Type[Script]]
  33. self._script_labels = {} # type: Dict[str, str]
  34. # Script list contains instances of scripts in loaded_scripts.
  35. # There can be duplicates, which will be executed in sequence.
  36. self._script_list = [] # type: List[Script]
  37. self._selected_script_index = -1
  38. self._global_container_stack = Application.getInstance().getGlobalContainerStack()
  39. if self._global_container_stack:
  40. self._global_container_stack.metaDataChanged.connect(self._restoreScriptInforFromMetadata)
  41. Application.getInstance().getOutputDeviceManager().writeStarted.connect(self.execute)
  42. Application.getInstance().globalContainerStackChanged.connect(self._onGlobalContainerStackChanged) # When the current printer changes, update the list of scripts.
  43. CuraApplication.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.
  44. selectedIndexChanged = pyqtSignal()
  45. @pyqtProperty(str, notify = selectedIndexChanged)
  46. def selectedScriptDefinitionId(self) -> Optional[str]:
  47. try:
  48. return self._script_list[self._selected_script_index].getDefinitionId()
  49. except IndexError:
  50. return ""
  51. @pyqtProperty(str, notify=selectedIndexChanged)
  52. def selectedScriptStackId(self) -> Optional[str]:
  53. try:
  54. return self._script_list[self._selected_script_index].getStackId()
  55. except IndexError:
  56. return ""
  57. def execute(self, output_device) -> None:
  58. """Execute all post-processing scripts on the gcode."""
  59. scene = Application.getInstance().getController().getScene()
  60. # If the scene does not have a gcode, do nothing
  61. if not hasattr(scene, "gcode_dict"):
  62. return
  63. gcode_dict = getattr(scene, "gcode_dict")
  64. if not gcode_dict:
  65. return
  66. # get gcode list for the active build plate
  67. active_build_plate_id = CuraApplication.getInstance().getMultiBuildPlateModel().activeBuildPlate
  68. gcode_list = gcode_dict[active_build_plate_id]
  69. if not gcode_list:
  70. return
  71. if ";POSTPROCESSED" not in gcode_list[0]:
  72. for script in self._script_list:
  73. try:
  74. gcode_list = script.execute(gcode_list)
  75. except Exception:
  76. Logger.logException("e", "Exception in post-processing script.")
  77. if len(self._script_list): # Add comment to g-code if any changes were made.
  78. gcode_list[0] += ";POSTPROCESSED\n"
  79. # Add all the active post processor names to data[0]
  80. pp_name_list = Application.getInstance().getGlobalContainerStack().getMetaDataEntry("post_processing_scripts")
  81. for pp_name in pp_name_list.split("\n"):
  82. pp_name = pp_name.split("]")
  83. gcode_list[0] += "; " + str(pp_name[0]) + "]\n"
  84. gcode_dict[active_build_plate_id] = gcode_list
  85. setattr(scene, "gcode_dict", gcode_dict)
  86. else:
  87. Logger.log("e", "Already post processed")
  88. @pyqtSlot(int)
  89. def setSelectedScriptIndex(self, index: int) -> None:
  90. if self._selected_script_index != index:
  91. self._selected_script_index = index
  92. self.selectedIndexChanged.emit()
  93. @pyqtProperty(int, notify = selectedIndexChanged)
  94. def selectedScriptIndex(self) -> int:
  95. return self._selected_script_index
  96. @pyqtSlot(int, int)
  97. def moveScript(self, index: int, new_index: int) -> None:
  98. if new_index < 0 or new_index > len(self._script_list) - 1:
  99. return # nothing needs to be done
  100. else:
  101. # Magical switch code.
  102. self._script_list[new_index], self._script_list[index] = self._script_list[index], self._script_list[new_index]
  103. self.scriptListChanged.emit()
  104. self.selectedIndexChanged.emit() #Ensure that settings are updated
  105. self._propertyChanged()
  106. @pyqtSlot(int)
  107. def removeScriptByIndex(self, index: int) -> None:
  108. """Remove a script from the active script list by index."""
  109. self._script_list.pop(index)
  110. if len(self._script_list) - 1 < self._selected_script_index:
  111. self._selected_script_index = len(self._script_list) - 1
  112. self.scriptListChanged.emit()
  113. self.selectedIndexChanged.emit() # Ensure that settings are updated
  114. self._propertyChanged()
  115. def loadAllScripts(self) -> None:
  116. """Load all scripts from all paths where scripts can be found.
  117. This should probably only be done on init.
  118. """
  119. if self._loaded_scripts: # Already loaded.
  120. return
  121. # Make sure a "scripts" folder exists in the main configuration folder and the preferences folder.
  122. # On some platforms the resources and preferences folders resolve to the same folder,
  123. # but on Linux they can be different.
  124. for path in set([os.path.join(Resources.getStoragePath(r), "scripts") for r in [Resources.Resources, Resources.Preferences]]):
  125. if not os.path.isdir(path):
  126. try:
  127. os.makedirs(path)
  128. except OSError:
  129. Logger.log("w", "Unable to create a folder for scripts: " + path)
  130. # The PostProcessingPlugin path is for built-in scripts.
  131. # The Resources path is where the user should store custom scripts.
  132. # The Preferences path is legacy, where the user may previously have stored scripts.
  133. resource_folders = [PluginRegistry.getInstance().getPluginPath("PostProcessingPlugin"), Resources.getStoragePath(Resources.Preferences)]
  134. resource_folders.extend(Resources.getAllPathsForType(Resources.Resources))
  135. for root in resource_folders:
  136. if root is None:
  137. continue
  138. path = os.path.join(root, "scripts")
  139. if not os.path.isdir(path):
  140. continue
  141. self.loadScripts(path)
  142. def loadScripts(self, path: str) -> None:
  143. """Load all scripts from provided path.
  144. This should probably only be done on init.
  145. :param path: Path to check for scripts.
  146. """
  147. if ApplicationMetadata.IsEnterpriseVersion:
  148. # Delete all __pycache__ not in installation folder, as it may present a security risk.
  149. # It prevents this very strange scenario (should already be prevented on enterprise because signed-fault):
  150. # - Copy an existing script from the postprocessing-script folder to the appdata scripts folder.
  151. # - Also copy the entire __pycache__ folder from the first to the last location.
  152. # - Leave the __pycache__ as is, but write malicious code just before the class begins.
  153. # - It'll execute, despite that the script has not been signed.
  154. # It's not known if these reproduction steps are minimal, but it does at least happen in this case.
  155. install_prefix = os.path.abspath(CuraApplication.getInstance().getInstallPrefix())
  156. try:
  157. is_in_installation_path = os.path.commonpath([install_prefix, path]).startswith(install_prefix)
  158. except ValueError:
  159. is_in_installation_path = False
  160. if not is_in_installation_path:
  161. TrustBasics.removeCached(path)
  162. scripts = pkgutil.iter_modules(path = [path])
  163. """Load all scripts in the scripts folders"""
  164. for loader, script_name, ispkg in scripts:
  165. # Iterate over all scripts.
  166. if script_name not in sys.modules:
  167. try:
  168. file_path = os.path.join(path, script_name + ".py")
  169. if not self._isScriptAllowed(file_path):
  170. Logger.warning("Skipped loading post-processing script {}: not trusted".format(file_path))
  171. continue
  172. spec = importlib.util.spec_from_file_location(__name__ + "." + script_name,
  173. file_path)
  174. if spec is None:
  175. continue
  176. loaded_script = importlib.util.module_from_spec(spec)
  177. if spec.loader is None:
  178. continue
  179. spec.loader.exec_module(loaded_script) # type: ignore
  180. sys.modules[script_name] = loaded_script #TODO: This could be a security risk. Overwrite any module with a user-provided name?
  181. loaded_class = getattr(loaded_script, script_name)
  182. temp_object = loaded_class()
  183. Logger.log("d", "Begin loading of script: %s", script_name)
  184. try:
  185. setting_data = temp_object.getSettingData()
  186. if "name" in setting_data and "key" in setting_data:
  187. self._script_labels[setting_data["key"]] = setting_data["name"]
  188. self._loaded_scripts[setting_data["key"]] = loaded_class
  189. else:
  190. Logger.log("w", "Script %s.py has no name or key", script_name)
  191. self._script_labels[script_name] = script_name
  192. self._loaded_scripts[script_name] = loaded_class
  193. except AttributeError:
  194. Logger.log("e", "Script %s.py is not a recognised script type. Ensure it inherits Script", script_name)
  195. except NotImplementedError:
  196. Logger.log("e", "Script %s.py has no implemented settings", script_name)
  197. except Exception as e:
  198. Logger.logException("e", "Exception occurred while loading post processing plugin: {error_msg}".format(error_msg = str(e)))
  199. loadedScriptListChanged = pyqtSignal()
  200. @pyqtProperty("QVariantList", notify = loadedScriptListChanged)
  201. def loadedScriptList(self) -> List[str]:
  202. return sorted(list(self._loaded_scripts.keys()))
  203. @pyqtSlot(str, result = str)
  204. def getScriptLabelByKey(self, key: str) -> Optional[str]:
  205. return self._script_labels.get(key)
  206. scriptListChanged = pyqtSignal()
  207. @pyqtProperty("QStringList", notify = scriptListChanged)
  208. def scriptList(self) -> List[str]:
  209. script_list = [script.getSettingData()["key"] for script in self._script_list]
  210. return script_list
  211. @pyqtSlot(str)
  212. def addScriptToList(self, key: str) -> None:
  213. Logger.log("d", "Adding script %s to list.", key)
  214. new_script = self._loaded_scripts[key]()
  215. new_script.initialize()
  216. self._script_list.append(new_script)
  217. self.setSelectedScriptIndex(len(self._script_list) - 1)
  218. self.scriptListChanged.emit()
  219. self._propertyChanged()
  220. def _restoreScriptInforFromMetadata(self):
  221. self.loadAllScripts()
  222. new_stack = self._global_container_stack
  223. if new_stack is None:
  224. return
  225. self._script_list.clear()
  226. if not new_stack.getMetaDataEntry("post_processing_scripts"): # Missing or empty.
  227. self.scriptListChanged.emit() # Even emit this if it didn't change. We want it to write the empty list to the stack's metadata.
  228. self.setSelectedScriptIndex(-1)
  229. return
  230. self._script_list.clear()
  231. scripts_list_strs = new_stack.getMetaDataEntry("post_processing_scripts")
  232. for script_str in scripts_list_strs.split(
  233. "\n"): # Encoded config files should never contain three newlines in a row. At most 2, just before section headers.
  234. if not script_str: # There were no scripts in this one (or a corrupt file caused more than 3 consecutive newlines here).
  235. continue
  236. script_str = script_str.replace(r"\\\n", "\n").replace(r"\\\\", "\\\\") # Unescape escape sequences.
  237. script_parser = configparser.ConfigParser(interpolation=None)
  238. script_parser.optionxform = str # type: ignore # Don't transform the setting keys as they are case-sensitive.
  239. try:
  240. script_parser.read_string(script_str)
  241. except configparser.Error as e:
  242. Logger.error("Stored post-processing scripts have syntax errors: {err}".format(err = str(e)))
  243. continue
  244. 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.
  245. if script_name == "DEFAULT": # ConfigParser always has a DEFAULT section, but we don't fill it. Ignore this one.
  246. continue
  247. if script_name not in self._loaded_scripts: # Don't know this post-processing plug-in.
  248. Logger.log("e",
  249. "Unknown post-processing script {script_name} was encountered in this global stack.".format(
  250. script_name=script_name))
  251. continue
  252. new_script = self._loaded_scripts[script_name]()
  253. new_script.initialize()
  254. for setting_key, setting_value in settings.items(): # Put all setting values into the script.
  255. if new_script._instance is not None:
  256. new_script._instance.setProperty(setting_key, "value", setting_value)
  257. self._script_list.append(new_script)
  258. self.setSelectedScriptIndex(0)
  259. # Ensure that we always force an update (otherwise the fields don't update correctly!)
  260. self.selectedIndexChanged.emit()
  261. self.scriptListChanged.emit()
  262. self._propertyChanged()
  263. def _onGlobalContainerStackChanged(self) -> None:
  264. """When the global container stack is changed, swap out the list of active scripts."""
  265. if self._global_container_stack:
  266. self._global_container_stack.metaDataChanged.disconnect(self._restoreScriptInforFromMetadata)
  267. self._global_container_stack = Application.getInstance().getGlobalContainerStack()
  268. if self._global_container_stack:
  269. self._global_container_stack.metaDataChanged.connect(self._restoreScriptInforFromMetadata)
  270. self._restoreScriptInforFromMetadata()
  271. @pyqtSlot()
  272. def writeScriptsToStack(self) -> None:
  273. script_list_strs = [] # type: List[str]
  274. for script in self._script_list:
  275. 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.
  276. parser.optionxform = str # type: ignore # Don't transform the setting keys as they are case-sensitive.
  277. script_name = script.getSettingData()["key"]
  278. parser.add_section(script_name)
  279. for key in script.getSettingData()["settings"]:
  280. value = script.getSettingValueByKey(key)
  281. parser[script_name][key] = str(value)
  282. serialized = io.StringIO() # ConfigParser can only write to streams. Fine.
  283. parser.write(serialized)
  284. serialized.seek(0)
  285. script_str = serialized.read()
  286. script_str = script_str.replace("\\\\", r"\\\\").replace("\n", r"\\\n") # Escape newlines because configparser sees those as section delimiters.
  287. script_list_strs.append(script_str)
  288. script_list_string = "\n".join(script_list_strs) # ConfigParser should never output three newlines in a row when serialised, so it's a safe delimiter.
  289. if self._global_container_stack is None:
  290. return
  291. # Ensure we don't get triggered by our own write.
  292. self._global_container_stack.metaDataChanged.disconnect(self._restoreScriptInforFromMetadata)
  293. if "post_processing_scripts" not in self._global_container_stack.getMetaData():
  294. self._global_container_stack.setMetaDataEntry("post_processing_scripts", "")
  295. self._global_container_stack.setMetaDataEntry("post_processing_scripts", script_list_string)
  296. # We do want to listen to other events.
  297. self._global_container_stack.metaDataChanged.connect(self._restoreScriptInforFromMetadata)
  298. def _createView(self) -> None:
  299. """Creates the view used by show popup.
  300. The view is saved because of the fairly aggressive garbage collection.
  301. """
  302. Logger.log("d", "Creating post processing plugin view.")
  303. self.loadAllScripts()
  304. # Create the plugin dialog component
  305. path = os.path.join(cast(str, PluginRegistry.getInstance().getPluginPath("PostProcessingPlugin")), "PostProcessingPlugin.qml")
  306. self._view = CuraApplication.getInstance().createQmlComponent(path, {"manager": self})
  307. if self._view is None:
  308. Logger.log("e", "Not creating PostProcessing button near save button because the QML component failed to be created.")
  309. return
  310. Logger.log("d", "Post processing view created.")
  311. # Create the save button component
  312. CuraApplication.getInstance().addAdditionalComponent("saveButton", self._view.findChild(QObject, "postProcessingSaveAreaButton"))
  313. def showPopup(self) -> None:
  314. """Show the (GUI) popup of the post processing plugin."""
  315. if self._view is None:
  316. self._createView()
  317. if self._view is None:
  318. Logger.log("e", "Not creating PostProcessing window since the QML component failed to be created.")
  319. return
  320. self._view.show()
  321. def _propertyChanged(self) -> None:
  322. """Property changed: trigger re-slice
  323. To do this we use the global container stack propertyChanged.
  324. Re-slicing is necessary for setting changes in this plugin, because the changes
  325. are applied only once per "fresh" gcode
  326. """
  327. global_container_stack = Application.getInstance().getGlobalContainerStack()
  328. if global_container_stack is not None:
  329. global_container_stack.propertyChanged.emit("post_processing_plugin", "value")
  330. @staticmethod
  331. def _isScriptAllowed(file_path: str) -> bool:
  332. """Checks whether the given file is allowed to be loaded"""
  333. if not ApplicationMetadata.IsEnterpriseVersion:
  334. # No signature needed
  335. return True
  336. dir_path = os.path.split(file_path)[0] # type: str
  337. plugin_path = PluginRegistry.getInstance().getPluginPath("PostProcessingPlugin")
  338. assert plugin_path is not None # appease mypy
  339. bundled_path = os.path.join(plugin_path, "scripts")
  340. if dir_path == bundled_path:
  341. # Bundled scripts are trusted.
  342. return True
  343. trust_instance = Trust.getInstanceOrNone()
  344. if trust_instance is not None and Trust.signatureFileExistsFor(file_path):
  345. if trust_instance.signedFileCheck(file_path):
  346. return True
  347. return False # Default verdict should be False, being the most secure fallback