CuraEngineBackend.py 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120
  1. # Copyright (c) 2022 UltiMaker
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. import argparse #To run the engine in debug mode if the front-end is in debug mode.
  4. from collections import defaultdict
  5. import os
  6. from PyQt6.QtCore import QObject, QTimer, QUrl, pyqtSlot
  7. import sys
  8. from time import time
  9. from typing import Any, cast, Dict, List, Optional, Set, TYPE_CHECKING
  10. from PyQt6.QtGui import QDesktopServices, QImage
  11. from UM.Backend.Backend import Backend, BackendState
  12. from UM.Scene.SceneNode import SceneNode
  13. from UM.Signal import Signal
  14. from UM.Logger import Logger
  15. from UM.Message import Message
  16. from UM.PluginRegistry import PluginRegistry
  17. from UM.Platform import Platform
  18. from UM.Qt.Duration import DurationFormat
  19. from UM.Scene.Iterator.DepthFirstIterator import DepthFirstIterator
  20. from UM.Settings.Interfaces import DefinitionContainerInterface
  21. from UM.Settings.SettingInstance import SettingInstance #For typing.
  22. from UM.Tool import Tool #For typing.
  23. from cura.CuraApplication import CuraApplication
  24. from cura.Settings.ExtruderManager import ExtruderManager
  25. from cura.Snapshot import Snapshot
  26. from cura.Utils.Threading import call_on_qt_thread
  27. from .ProcessSlicedLayersJob import ProcessSlicedLayersJob
  28. from .StartSliceJob import StartSliceJob, StartJobResult
  29. import pyArcus as Arcus
  30. if TYPE_CHECKING:
  31. from cura.Machines.Models.MultiBuildPlateModel import MultiBuildPlateModel
  32. from cura.Machines.MachineErrorChecker import MachineErrorChecker
  33. from UM.Scene.Scene import Scene
  34. from UM.Settings.ContainerStack import ContainerStack
  35. from UM.i18n import i18nCatalog
  36. catalog = i18nCatalog("cura")
  37. class CuraEngineBackend(QObject, Backend):
  38. backendError = Signal()
  39. printDurationMessage = Signal()
  40. """Emitted when we get a message containing print duration and material amount.
  41. This also implies the slicing has finished.
  42. :param time: The amount of time the print will take.
  43. :param material_amount: The amount of material the print will use.
  44. """
  45. slicingStarted = Signal()
  46. """Emitted when the slicing process starts."""
  47. slicingCancelled = Signal()
  48. """Emitted when the slicing process is aborted forcefully."""
  49. def __init__(self) -> None:
  50. """Starts the back-end plug-in.
  51. This registers all the signal listeners and prepares for communication
  52. with the back-end in general.
  53. CuraEngineBackend is exposed to qml as well.
  54. """
  55. super().__init__()
  56. # Find out where the engine is located, and how it is called.
  57. # This depends on how Cura is packaged and which OS we are running on.
  58. executable_name = "CuraEngine"
  59. if Platform.isWindows():
  60. executable_name += ".exe"
  61. self._default_engine_location = executable_name
  62. search_path = [
  63. os.path.abspath(os.path.dirname(sys.executable)),
  64. os.path.abspath(os.path.join(os.path.dirname(sys.executable), "bin")),
  65. os.path.abspath(os.path.join(os.path.dirname(sys.executable), "..")),
  66. os.path.join(CuraApplication.getInstallPrefix(), "bin"),
  67. os.path.dirname(os.path.abspath(sys.executable)),
  68. ]
  69. for path in search_path:
  70. engine_path = os.path.join(path, executable_name)
  71. if os.path.isfile(engine_path):
  72. self._default_engine_location = engine_path
  73. break
  74. if Platform.isLinux() and not self._default_engine_location:
  75. if not os.getenv("PATH"):
  76. raise OSError("There is something wrong with your Linux installation.")
  77. for pathdir in cast(str, os.getenv("PATH")).split(os.pathsep):
  78. execpath = os.path.join(pathdir, executable_name)
  79. if os.path.exists(execpath):
  80. self._default_engine_location = execpath
  81. break
  82. application: CuraApplication = CuraApplication.getInstance()
  83. self._multi_build_plate_model: Optional[MultiBuildPlateModel] = None
  84. self._machine_error_checker: Optional[MachineErrorChecker] = None
  85. if not self._default_engine_location:
  86. raise EnvironmentError("Could not find CuraEngine")
  87. Logger.log("i", "Found CuraEngine at: %s", self._default_engine_location)
  88. self._default_engine_location = os.path.abspath(self._default_engine_location)
  89. application.getPreferences().addPreference("backend/location", self._default_engine_location)
  90. # Workaround to disable layer view processing if layer view is not active.
  91. self._layer_view_active: bool = False
  92. self._onActiveViewChanged()
  93. self._stored_layer_data: List[Arcus.PythonMessage] = []
  94. # key is build plate number, then arrays are stored until they go to the ProcessSlicesLayersJob
  95. self._stored_optimized_layer_data: Dict[int, List[Arcus.PythonMessage]] = {}
  96. self._scene: Scene = application.getController().getScene()
  97. self._scene.sceneChanged.connect(self._onSceneChanged)
  98. # Triggers for auto-slicing. Auto-slicing is triggered as follows:
  99. # - auto-slicing is started with a timer
  100. # - whenever there is a value change, we start the timer
  101. # - sometimes an error check can get scheduled for a value change, in that case, we ONLY want to start the
  102. # auto-slicing timer when that error check is finished
  103. # If there is an error check, stop the auto-slicing timer, and only wait for the error check to be finished
  104. # to start the auto-slicing timer again.
  105. #
  106. self._global_container_stack: Optional[ContainerStack] = None
  107. # Listeners for receiving messages from the back-end.
  108. self._message_handlers["cura.proto.Layer"] = self._onLayerMessage
  109. self._message_handlers["cura.proto.LayerOptimized"] = self._onOptimizedLayerMessage
  110. self._message_handlers["cura.proto.Progress"] = self._onProgressMessage
  111. self._message_handlers["cura.proto.GCodeLayer"] = self._onGCodeLayerMessage
  112. self._message_handlers["cura.proto.GCodePrefix"] = self._onGCodePrefixMessage
  113. self._message_handlers["cura.proto.SliceUUID"] = self._onSliceUUIDMessage
  114. self._message_handlers["cura.proto.PrintTimeMaterialEstimates"] = self._onPrintTimeMaterialEstimates
  115. self._message_handlers["cura.proto.SlicingFinished"] = self._onSlicingFinishedMessage
  116. self._start_slice_job: Optional[StartSliceJob] = None
  117. self._start_slice_job_build_plate: Optional[int] = None
  118. self._slicing: bool = False # Are we currently slicing?
  119. self._restart: bool = False # Back-end is currently restarting?
  120. self._tool_active: bool = False # If a tool is active, some tasks do not have to do anything
  121. self._always_restart: bool = True # Always restart the engine when starting a new slice. Don't keep the process running. TODO: Fix engine statelessness.
  122. self._process_layers_job: Optional[ProcessSlicedLayersJob] = None # The currently active job to process layers, or None if it is not processing layers.
  123. self._build_plates_to_be_sliced: List[int] = [] # what needs slicing?
  124. self._engine_is_fresh: bool = True # Is the newly started engine used before or not?
  125. self._backend_log_max_lines: int = 20000 # Maximum number of lines to buffer
  126. self._error_message: Optional[Message] = None # Pop-up message that shows errors.
  127. # Count number of objects to see if there is something changed
  128. self._last_num_objects: Dict[int, int] = defaultdict(int)
  129. self._postponed_scene_change_sources: List[SceneNode] = [] # scene change is postponed (by a tool)
  130. self._time_start_process: Optional[float] = None
  131. self._is_disabled: bool = False
  132. application.getPreferences().addPreference("general/auto_slice", False)
  133. application.getPreferences().addPreference("info/send_engine_crash", True)
  134. application.getPreferences().addPreference("info/anonymous_engine_crash_report", True)
  135. self._use_timer: bool = False
  136. # When you update a setting and other settings get changed through inheritance, many propertyChanged
  137. # signals are fired. This timer will group them up, and only slice for the last setting changed signal.
  138. # TODO: Properly group propertyChanged signals by whether they are triggered by the same user interaction.
  139. self._change_timer: QTimer = QTimer()
  140. self._change_timer.setSingleShot(True)
  141. self._change_timer.setInterval(500)
  142. self.determineAutoSlicing()
  143. application.getPreferences().preferenceChanged.connect(self._onPreferencesChanged)
  144. self._slicing_error_message = Message(
  145. text = catalog.i18nc("@message", "Slicing failed with an unexpected error. Please consider reporting a bug on our issue tracker."),
  146. title = catalog.i18nc("@message:title", "Slicing failed"),
  147. message_type = Message.MessageType.ERROR
  148. )
  149. self._slicing_error_message.addAction(
  150. action_id = "report_bug",
  151. name = catalog.i18nc("@message:button", "Report a bug"),
  152. description = catalog.i18nc("@message:description", "Report a bug on UltiMaker Cura's issue tracker."),
  153. icon = "[no_icon]"
  154. )
  155. self._slicing_error_message.actionTriggered.connect(self._reportBackendError)
  156. self._resetLastSliceTimeStats()
  157. self._snapshot: Optional[QImage] = None
  158. application.initializationFinished.connect(self.initialize)
  159. # Ensure that the initial value for send_engine_crash is handled correctly.
  160. application.callLater(self._onPreferencesChanged, "info/send_engine_crash")
  161. def startPlugins(self) -> None:
  162. """
  163. Ensure that all backend plugins are started
  164. It assigns unique ports to each plugin to avoid conflicts.
  165. :return:
  166. """
  167. self.stopPlugins()
  168. backend_plugins = CuraApplication.getInstance().getBackendPlugins()
  169. for backend_plugin in backend_plugins:
  170. # Set the port to prevent plugins from using the same one.
  171. if backend_plugin.getPort() < 1:
  172. backend_plugin.setAvailablePort()
  173. backend_plugin.start()
  174. def stopPlugins(self) -> None:
  175. """
  176. Ensure that all backend plugins will be terminated.
  177. """
  178. backend_plugins = CuraApplication.getInstance().getBackendPlugins()
  179. for backend_plugin in backend_plugins:
  180. if backend_plugin.isRunning():
  181. backend_plugin.stop()
  182. def _resetLastSliceTimeStats(self) -> None:
  183. self._time_start_process = None
  184. self._time_send_message = None
  185. self._time_end_slice = None
  186. def resetAndReturnLastSliceTimeStats(self) -> Dict[str, float]:
  187. last_slice_data = {
  188. "time_start_process": self._time_start_process,
  189. "time_send_message": self._time_send_message,
  190. "time_end_slice": self._time_end_slice,
  191. }
  192. self._resetLastSliceTimeStats()
  193. return last_slice_data
  194. def initialize(self) -> None:
  195. application = CuraApplication.getInstance()
  196. self._multi_build_plate_model = application.getMultiBuildPlateModel()
  197. application.getController().activeViewChanged.connect(self._onActiveViewChanged)
  198. if self._multi_build_plate_model:
  199. self._multi_build_plate_model.activeBuildPlateChanged.connect(self._onActiveViewChanged)
  200. application.getMachineManager().globalContainerChanged.connect(self._onGlobalStackChanged)
  201. self._onGlobalStackChanged()
  202. # Extruder enable / disable. Actually wanted to use machine manager here,
  203. # but the initialization order causes it to crash
  204. ExtruderManager.getInstance().extrudersChanged.connect(self._extruderChanged)
  205. self.backendQuit.connect(self._onBackendQuit)
  206. self.backendConnected.connect(self._onBackendConnected)
  207. # When a tool operation is in progress, don't slice. So we need to listen for tool operations.
  208. application.getController().toolOperationStarted.connect(self._onToolOperationStarted)
  209. application.getController().toolOperationStopped.connect(self._onToolOperationStopped)
  210. self._machine_error_checker = application.getMachineErrorChecker()
  211. self._machine_error_checker.errorCheckFinished.connect(self._onStackErrorCheckFinished)
  212. def close(self) -> None:
  213. """Terminate the engine process.
  214. This function should terminate the engine process.
  215. Called when closing the application.
  216. """
  217. # Terminate CuraEngine if it is still running at this point
  218. self._terminate()
  219. def getEngineCommand(self) -> List[str]:
  220. """Get the command that is used to call the engine.
  221. This is useful for debugging and used to actually start the engine.
  222. :return: list of commands and args / parameters.
  223. """
  224. from cura import ApplicationMetadata
  225. if ApplicationMetadata.IsEnterpriseVersion:
  226. command = [self._default_engine_location]
  227. else:
  228. command = [CuraApplication.getInstance().getPreferences().getValue("backend/location")]
  229. command += ["connect", "127.0.0.1:{0}".format(self._port), ""]
  230. parser = argparse.ArgumentParser(prog = "cura", add_help = False)
  231. parser.add_argument("--debug", action = "store_true", default = False,
  232. help = "Turn on the debug mode by setting this option.")
  233. known_args = vars(parser.parse_known_args()[0])
  234. if known_args["debug"]:
  235. command.append("-vvv")
  236. return command
  237. @pyqtSlot()
  238. def stopSlicing(self) -> None:
  239. self.setState(BackendState.NotStarted)
  240. if self._slicing: # We were already slicing. Stop the old job.
  241. self._terminate()
  242. self._createSocket()
  243. if self._process_layers_job is not None:
  244. # We were processing layers. Stop that, the layers are going to change soon.
  245. Logger.log("i", "Aborting process layers job...")
  246. self._process_layers_job.abort()
  247. self._process_layers_job = None
  248. if self._error_message:
  249. self._error_message.hide()
  250. @pyqtSlot()
  251. def forceSlice(self) -> None:
  252. """Manually triggers a reslice"""
  253. self.markSliceAll()
  254. self.slice()
  255. @call_on_qt_thread # Must be called from the main thread because of OpenGL
  256. def _createSnapshot(self) -> None:
  257. self._snapshot = None
  258. if not CuraApplication.getInstance().isVisible:
  259. Logger.log("w", "Can't create snapshot when renderer not initialized.")
  260. return
  261. Logger.log("i", "Creating thumbnail image (just before slice)...")
  262. try:
  263. self._snapshot = Snapshot.snapshot(width = 300, height = 300)
  264. except Exception:
  265. Logger.logException("w", "Failed to create snapshot image")
  266. self._snapshot = None # Failing to create thumbnail should not fail creation of UFP
  267. def getLatestSnapshot(self) -> Optional[QImage]:
  268. return self._snapshot
  269. def slice(self) -> None:
  270. """Perform a slice of the scene."""
  271. self._createSnapshot()
  272. self.startPlugins()
  273. Logger.log("i", "Starting to slice...")
  274. self._time_start_process = time()
  275. if not self._build_plates_to_be_sliced:
  276. self.processingProgress.emit(1.0)
  277. Logger.log("w", "Slice unnecessary, nothing has changed that needs reslicing.")
  278. self.setState(BackendState.Done)
  279. return
  280. if self._process_layers_job:
  281. Logger.log("d", "Process layers job still busy, trying later.")
  282. return
  283. if not hasattr(self._scene, "gcode_dict"):
  284. self._scene.gcode_dict = {} # type: ignore
  285. # We need to ignore type because we are creating the missing attribute here.
  286. # see if we really have to slice
  287. application = CuraApplication.getInstance()
  288. active_build_plate = application.getMultiBuildPlateModel().activeBuildPlate
  289. build_plate_to_be_sliced = self._build_plates_to_be_sliced.pop(0)
  290. Logger.log("d", "Going to slice build plate [%s]!" % build_plate_to_be_sliced)
  291. num_objects = self._numObjectsPerBuildPlate()
  292. self._stored_layer_data = []
  293. if build_plate_to_be_sliced not in num_objects or num_objects[build_plate_to_be_sliced] == 0:
  294. self._scene.gcode_dict[build_plate_to_be_sliced] = [] # type: ignore
  295. # We need to ignore the type because we created this attribute above.
  296. Logger.log("d", "Build plate %s has no objects to be sliced, skipping", build_plate_to_be_sliced)
  297. if self._build_plates_to_be_sliced:
  298. self.slice()
  299. return
  300. self._stored_optimized_layer_data[build_plate_to_be_sliced] = []
  301. if application.getPrintInformation() and build_plate_to_be_sliced == active_build_plate:
  302. application.getPrintInformation().setToZeroPrintInformation(build_plate_to_be_sliced)
  303. if self._process is None: # type: ignore
  304. self._createSocket()
  305. self.stopSlicing()
  306. self._engine_is_fresh = False # Yes we're going to use the engine
  307. self.processingProgress.emit(0.0)
  308. self.backendStateChange.emit(BackendState.NotStarted)
  309. self._scene.gcode_dict[build_plate_to_be_sliced] = [] # type: ignore #[] indexed by build plate number
  310. self._slicing = True
  311. self.slicingStarted.emit()
  312. self.determineAutoSlicing() # Switch timer on or off if appropriate
  313. slice_message = self._socket.createMessage("cura.proto.Slice")
  314. self._start_slice_job = StartSliceJob(slice_message)
  315. self._start_slice_job_build_plate = build_plate_to_be_sliced
  316. self._start_slice_job.setBuildPlate(self._start_slice_job_build_plate)
  317. self._start_slice_job.start()
  318. self._start_slice_job.finished.connect(self._onStartSliceCompleted)
  319. def _terminate(self) -> None:
  320. """Terminate the engine process.
  321. Start the engine process by calling _createSocket()
  322. """
  323. self._slicing = False
  324. self._stored_layer_data = []
  325. if self._start_slice_job_build_plate in self._stored_optimized_layer_data:
  326. del self._stored_optimized_layer_data[self._start_slice_job_build_plate]
  327. if self._start_slice_job is not None:
  328. self._start_slice_job.cancel()
  329. self.stopPlugins()
  330. self.slicingCancelled.emit()
  331. self.processingProgress.emit(0)
  332. Logger.log("d", "Attempting to kill the engine process")
  333. if CuraApplication.getInstance().getUseExternalBackend():
  334. return
  335. if self._process is not None: # type: ignore
  336. Logger.log("d", "Killing engine process")
  337. try:
  338. self._process.terminate() # type: ignore
  339. Logger.log("d", "Engine process is killed. Received return code %s", self._process.wait()) # type: ignore
  340. self._process = None # type: ignore
  341. except Exception as e:
  342. # Terminating a process that is already terminating causes an exception, silently ignore this.
  343. Logger.log("d", "Exception occurred while trying to kill the engine %s", str(e))
  344. def _onStartSliceCompleted(self, job: StartSliceJob) -> None:
  345. """Event handler to call when the job to initiate the slicing process is
  346. completed.
  347. When the start slice job is successfully completed, it will be happily
  348. slicing. This function handles any errors that may occur during the
  349. bootstrapping of a slice job.
  350. :param job: The start slice job that was just finished.
  351. """
  352. if self._error_message:
  353. self._error_message.hide()
  354. # Note that cancelled slice jobs can still call this method.
  355. if self._start_slice_job is job:
  356. self._start_slice_job = None
  357. if job.isCancelled() or job.getError() or job.getResult() == StartJobResult.Error:
  358. self.setState(BackendState.Error)
  359. self.backendError.emit(job)
  360. return
  361. application = CuraApplication.getInstance()
  362. if job.getResult() == StartJobResult.MaterialIncompatible:
  363. if application.platformActivity:
  364. self._error_message = Message(catalog.i18nc("@info:status",
  365. "Unable to slice with the current material as it is incompatible with the selected machine or configuration."),
  366. title = catalog.i18nc("@info:title", "Unable to slice"),
  367. message_type = Message.MessageType.WARNING)
  368. self._error_message.show()
  369. self.setState(BackendState.Error)
  370. self.backendError.emit(job)
  371. else:
  372. self.setState(BackendState.NotStarted)
  373. return
  374. if job.getResult() == StartJobResult.SettingError:
  375. if application.platformActivity:
  376. if not self._global_container_stack:
  377. Logger.log("w", "Global container stack not assigned to CuraEngineBackend!")
  378. return
  379. extruders = ExtruderManager.getInstance().getActiveExtruderStacks()
  380. error_keys: List[str] = []
  381. for extruder in extruders:
  382. error_keys.extend(extruder.getErrorKeys())
  383. if not extruders:
  384. error_keys = self._global_container_stack.getErrorKeys()
  385. error_labels = set()
  386. for key in error_keys:
  387. for stack in [self._global_container_stack] + extruders: #Search all container stacks for the definition of this setting. Some are only in an extruder stack.
  388. definitions = cast(DefinitionContainerInterface, stack.getBottom()).findDefinitions(key = key)
  389. if definitions:
  390. break #Found it! No need to continue search.
  391. else: #No stack has a definition for this setting.
  392. Logger.log("w", "When checking settings for errors, unable to find definition for key: {key}".format(key = key))
  393. continue
  394. error_labels.add(definitions[0].label)
  395. self._error_message = Message(catalog.i18nc("@info:status",
  396. "Unable to slice with the current settings. The following settings have errors: {0}").format(", ".join(error_labels)),
  397. title = catalog.i18nc("@info:title", "Unable to slice"),
  398. message_type = Message.MessageType.WARNING)
  399. Logger.warning(f"Unable to slice with the current settings. The following settings have errors: {', '.join(error_labels)}")
  400. self._error_message.show()
  401. self.setState(BackendState.Error)
  402. self.backendError.emit(job)
  403. else:
  404. self.setState(BackendState.NotStarted)
  405. return
  406. elif job.getResult() == StartJobResult.ObjectSettingError:
  407. errors = {}
  408. for node in DepthFirstIterator(application.getController().getScene().getRoot()):
  409. stack = node.callDecoration("getStack")
  410. if not stack:
  411. continue
  412. for key in stack.getErrorKeys():
  413. if not self._global_container_stack:
  414. Logger.log("e", "CuraEngineBackend does not have global_container_stack assigned.")
  415. continue
  416. definition = cast(DefinitionContainerInterface, self._global_container_stack.getBottom()).findDefinitions(key = key)
  417. if not definition:
  418. Logger.log("e", "When checking settings for errors, unable to find definition for key {key} in per-object stack.".format(key = key))
  419. continue
  420. errors[key] = definition[0].label
  421. self._error_message = Message(catalog.i18nc("@info:status",
  422. "Unable to slice due to some per-model settings. The following settings have errors on one or more models: {error_labels}").format(error_labels = ", ".join(errors.values())),
  423. title = catalog.i18nc("@info:title", "Unable to slice"),
  424. message_type = Message.MessageType.WARNING)
  425. Logger.warning(f"Unable to slice due to per-object settings. The following settings have errors on one or more models: {', '.join(errors.values())}")
  426. self._error_message.show()
  427. self.setState(BackendState.Error)
  428. self.backendError.emit(job)
  429. return
  430. if job.getResult() == StartJobResult.BuildPlateError:
  431. if application.platformActivity:
  432. self._error_message = Message(catalog.i18nc("@info:status",
  433. "Unable to slice because the prime tower or prime position(s) are invalid."),
  434. title = catalog.i18nc("@info:title", "Unable to slice"),
  435. message_type = Message.MessageType.WARNING)
  436. self._error_message.show()
  437. self.setState(BackendState.Error)
  438. self.backendError.emit(job)
  439. return
  440. else:
  441. self.setState(BackendState.NotStarted)
  442. if job.getResult() == StartJobResult.ObjectsWithDisabledExtruder:
  443. self._error_message = Message(catalog.i18nc("@info:status",
  444. "Unable to slice because there are objects associated with disabled Extruder %s.") % job.getMessage(),
  445. title = catalog.i18nc("@info:title", "Unable to slice"),
  446. message_type = Message.MessageType.WARNING)
  447. self._error_message.show()
  448. self.setState(BackendState.Error)
  449. self.backendError.emit(job)
  450. return
  451. if job.getResult() == StartJobResult.NothingToSlice:
  452. if application.platformActivity:
  453. self._error_message = Message(catalog.i18nc("@info:status", "Please review settings and check if your models:"
  454. "\n- Fit within the build volume"
  455. "\n- Are assigned to an enabled extruder"
  456. "\n- Are not all set as modifier meshes"),
  457. title = catalog.i18nc("@info:title", "Unable to slice"),
  458. message_type = Message.MessageType.WARNING)
  459. self._error_message.show()
  460. self.setState(BackendState.Error)
  461. self.backendError.emit(job)
  462. else:
  463. self.setState(BackendState.NotStarted)
  464. self._invokeSlice()
  465. return
  466. # Preparation completed, send it to the backend.
  467. self._socket.sendMessage(job.getSliceMessage())
  468. # Notify the user that it's now up to the backend to do its job
  469. self.setState(BackendState.Processing)
  470. # Handle time reporting.
  471. self._time_send_message = time()
  472. if self._time_start_process:
  473. Logger.log("d", "Sending slice message took %s seconds", self._time_send_message - self._time_start_process)
  474. def determineAutoSlicing(self) -> bool:
  475. """Determine enable or disable auto slicing. Return True for enable timer and False otherwise.
  476. It disables when:
  477. - preference auto slice is off
  478. - decorator isBlockSlicing is found (used in g-code reader)
  479. """
  480. enable_timer = True
  481. self._is_disabled = False
  482. if not CuraApplication.getInstance().getPreferences().getValue("general/auto_slice"):
  483. enable_timer = False
  484. for node in DepthFirstIterator(self._scene.getRoot()):
  485. if node.callDecoration("isBlockSlicing"):
  486. enable_timer = False
  487. self.setState(BackendState.Disabled)
  488. self._is_disabled = True
  489. gcode_list = node.callDecoration("getGCodeList")
  490. if gcode_list is not None:
  491. self._scene.gcode_dict[node.callDecoration("getBuildPlateNumber")] = gcode_list # type: ignore
  492. # We need to ignore type because we generate this attribute dynamically.
  493. if self._use_timer == enable_timer:
  494. return self._use_timer
  495. if enable_timer:
  496. self.setState(BackendState.NotStarted)
  497. self.enableTimer()
  498. return True
  499. else:
  500. self.disableTimer()
  501. return False
  502. def _numObjectsPerBuildPlate(self) -> Dict[int, int]:
  503. """Return a dict with number of objects per build plate"""
  504. num_objects: Dict[int, int] = defaultdict(int)
  505. for node in DepthFirstIterator(self._scene.getRoot()):
  506. # Only count sliceable objects
  507. if node.callDecoration("isSliceable"):
  508. build_plate_number = node.callDecoration("getBuildPlateNumber")
  509. if build_plate_number is not None:
  510. num_objects[build_plate_number] += 1
  511. return num_objects
  512. def _onSceneChanged(self, source: SceneNode) -> None:
  513. """Listener for when the scene has changed.
  514. This should start a slice if the scene is now ready to slice.
  515. :param source: The scene node that was changed.
  516. """
  517. if not source.callDecoration("isSliceable") and source != self._scene.getRoot():
  518. return
  519. # This case checks if the source node is a node that contains GCode. In this case the
  520. # current layer data is removed so the previous data is not rendered - CURA-4821
  521. if source.callDecoration("isBlockSlicing") and source.callDecoration("getLayerData"):
  522. self._stored_optimized_layer_data = {}
  523. build_plate_changed = set()
  524. source_build_plate_number = source.callDecoration("getBuildPlateNumber")
  525. if source == self._scene.getRoot():
  526. # we got the root node
  527. num_objects = self._numObjectsPerBuildPlate()
  528. for build_plate_number in list(self._last_num_objects.keys()) + list(num_objects.keys()):
  529. if build_plate_number not in self._last_num_objects or num_objects[build_plate_number] != self._last_num_objects[build_plate_number]:
  530. self._last_num_objects[build_plate_number] = num_objects[build_plate_number]
  531. build_plate_changed.add(build_plate_number)
  532. else:
  533. # we got a single scenenode
  534. if not source.callDecoration("isGroup"):
  535. mesh_data = source.getMeshData()
  536. if mesh_data is None or mesh_data.getVertices() is None:
  537. return
  538. # There are some SceneNodes that do not have any build plate associated, then do not add to the list.
  539. if source_build_plate_number is not None:
  540. build_plate_changed.add(source_build_plate_number)
  541. if not build_plate_changed:
  542. return
  543. if self._tool_active:
  544. # do it later, each source only has to be done once
  545. if source not in self._postponed_scene_change_sources:
  546. self._postponed_scene_change_sources.append(source)
  547. return
  548. self.stopSlicing()
  549. for build_plate_number in build_plate_changed:
  550. if build_plate_number not in self._build_plates_to_be_sliced:
  551. self._build_plates_to_be_sliced.append(build_plate_number)
  552. self.printDurationMessage.emit(source_build_plate_number, {}, [])
  553. self.processingProgress.emit(0.0)
  554. self._clearLayerData(build_plate_changed)
  555. self._invokeSlice()
  556. def _onSocketError(self, error: Arcus.Error) -> None:
  557. """Called when an error occurs in the socket connection towards the engine.
  558. :param error: The exception that occurred.
  559. """
  560. if CuraApplication.getInstance().isShuttingDown():
  561. return
  562. super()._onSocketError(error)
  563. if error.getErrorCode() == Arcus.ErrorCode.Debug:
  564. return
  565. self._terminate()
  566. self._createSocket()
  567. if error.getErrorCode() not in [Arcus.ErrorCode.BindFailedError,
  568. Arcus.ErrorCode.ConnectionResetError,
  569. Arcus.ErrorCode.Debug]:
  570. Logger.log("w", "A socket error caused the connection to be reset")
  571. # _terminate()' function sets the job status to 'cancel', after reconnecting to another Port the job status
  572. # needs to be updated. Otherwise, backendState is "Unable To Slice"
  573. if error.getErrorCode() == Arcus.ErrorCode.BindFailedError and self._start_slice_job is not None:
  574. self._start_slice_job.setIsCancelled(False)
  575. # Check if there's any slicable object in the scene.
  576. def hasSlicableObject(self) -> bool:
  577. has_slicable = False
  578. for node in DepthFirstIterator(self._scene.getRoot()):
  579. if node.callDecoration("isSliceable"):
  580. has_slicable = True
  581. break
  582. return has_slicable
  583. def _clearLayerData(self, build_plate_numbers: Set = None) -> None:
  584. """Remove old layer data (if any)"""
  585. # Clear out any old gcode
  586. self._scene.gcode_dict = {} # type: ignore
  587. for node in DepthFirstIterator(self._scene.getRoot()):
  588. if node.callDecoration("getLayerData"):
  589. if not build_plate_numbers or node.callDecoration("getBuildPlateNumber") in build_plate_numbers:
  590. # We can assume that all nodes have a parent as we're looping through the scene and filter out root
  591. cast(SceneNode, node.getParent()).removeChild(node)
  592. def markSliceAll(self) -> None:
  593. for build_plate_number in range(CuraApplication.getInstance().getMultiBuildPlateModel().maxBuildPlate + 1):
  594. if build_plate_number not in self._build_plates_to_be_sliced:
  595. self._build_plates_to_be_sliced.append(build_plate_number)
  596. def needsSlicing(self) -> None:
  597. """Convenient function: mark everything to slice, emit state and clear layer data"""
  598. # CURA-6604: If there's no slicable object, do not (try to) trigger slice, which will clear all the current
  599. # gcode. This can break Gcode file loading if it tries to remove it afterwards.
  600. if not self.hasSlicableObject():
  601. return
  602. self.determineAutoSlicing()
  603. self.stopSlicing()
  604. self.markSliceAll()
  605. self.processingProgress.emit(0.0)
  606. if not self._use_timer:
  607. # With manually having to slice, we want to clear the old invalid layer data.
  608. self._clearLayerData()
  609. def _onSettingChanged(self, instance: SettingInstance, property: str) -> None:
  610. """A setting has changed, so check if we must reslice.
  611. :param instance: The setting instance that has changed.
  612. :param property: The property of the setting instance that has changed.
  613. """
  614. if property == "value": # Only re-slice if the value has changed.
  615. self.needsSlicing()
  616. self._onChanged()
  617. elif property == "validationState":
  618. if self._use_timer:
  619. self._change_timer.stop()
  620. def _onStackErrorCheckFinished(self) -> None:
  621. self.determineAutoSlicing()
  622. if self._is_disabled:
  623. return
  624. if not self._slicing and self._build_plates_to_be_sliced:
  625. self.needsSlicing()
  626. self._onChanged()
  627. def _onLayerMessage(self, message: Arcus.PythonMessage) -> None:
  628. """Called when a sliced layer data message is received from the engine.
  629. :param message: The protobuf message containing sliced layer data.
  630. """
  631. self._stored_layer_data.append(message)
  632. def _onOptimizedLayerMessage(self, message: Arcus.PythonMessage) -> None:
  633. """Called when an optimized sliced layer data message is received from the engine.
  634. :param message: The protobuf message containing sliced layer data.
  635. """
  636. if self._start_slice_job_build_plate is not None:
  637. if self._start_slice_job_build_plate not in self._stored_optimized_layer_data:
  638. self._stored_optimized_layer_data[self._start_slice_job_build_plate] = []
  639. self._stored_optimized_layer_data[self._start_slice_job_build_plate].append(message)
  640. def _onProgressMessage(self, message: Arcus.PythonMessage) -> None:
  641. """Called when a progress message is received from the engine.
  642. :param message: The protobuf message containing the slicing progress.
  643. """
  644. self.processingProgress.emit(message.amount)
  645. self.setState(BackendState.Processing)
  646. def _invokeSlice(self) -> None:
  647. if self._use_timer:
  648. # if the error check is scheduled, wait for the error check finish signal to trigger auto-slice,
  649. # otherwise business as usual
  650. if self._machine_error_checker is None:
  651. self._change_timer.stop()
  652. return
  653. if self._machine_error_checker.needToWaitForResult:
  654. self._change_timer.stop()
  655. else:
  656. self._change_timer.start()
  657. def _onSlicingFinishedMessage(self, message: Arcus.PythonMessage) -> None:
  658. """Called when the engine sends a message that slicing is finished.
  659. :param message: The protobuf message signalling that slicing is finished.
  660. """
  661. self.stopPlugins()
  662. self.setState(BackendState.Done)
  663. self.processingProgress.emit(1.0)
  664. self._time_end_slice = time()
  665. try:
  666. gcode_list = self._scene.gcode_dict[self._start_slice_job_build_plate] #type: ignore
  667. # We need to ignore the type because it was generated dynamically.
  668. except KeyError:
  669. # Can occur if the g-code has been cleared while a slice message is still arriving from the other end.
  670. gcode_list = []
  671. application = CuraApplication.getInstance()
  672. for index, line in enumerate(gcode_list):
  673. replaced = line.replace("{print_time}", str(application.getPrintInformation().currentPrintTime.getDisplayString(DurationFormat.Format.ISO8601)))
  674. replaced = replaced.replace("{filament_amount}", str(application.getPrintInformation().materialLengths))
  675. replaced = replaced.replace("{filament_weight}", str(application.getPrintInformation().materialWeights))
  676. replaced = replaced.replace("{filament_cost}", str(application.getPrintInformation().materialCosts))
  677. replaced = replaced.replace("{jobname}", str(application.getPrintInformation().jobName))
  678. gcode_list[index] = replaced
  679. self._slicing = False
  680. if self._time_start_process:
  681. Logger.log("d", "Slicing took %s seconds", time() - self._time_start_process)
  682. Logger.log("d", "Number of models per buildplate: %s", dict(self._numObjectsPerBuildPlate()))
  683. # See if we need to process the sliced layers job.
  684. active_build_plate = application.getMultiBuildPlateModel().activeBuildPlate
  685. if (
  686. self._layer_view_active and
  687. (self._process_layers_job is None or not self._process_layers_job.isRunning()) and
  688. active_build_plate == self._start_slice_job_build_plate and
  689. active_build_plate not in self._build_plates_to_be_sliced):
  690. self._startProcessSlicedLayersJob(active_build_plate)
  691. # self._onActiveViewChanged()
  692. self._start_slice_job_build_plate = None
  693. Logger.log("d", "See if there is more to slice...")
  694. # Somehow this results in an Arcus Error
  695. # self.slice()
  696. # Call slice again using the timer, allowing the backend to restart
  697. if self._build_plates_to_be_sliced:
  698. self.enableTimer() # manually enable timer to be able to invoke slice, also when in manual slice mode
  699. self._invokeSlice()
  700. def _onGCodeLayerMessage(self, message: Arcus.PythonMessage) -> None:
  701. """Called when a g-code message is received from the engine.
  702. :param message: The protobuf message containing g-code, encoded as UTF-8.
  703. """
  704. try:
  705. self._scene.gcode_dict[self._start_slice_job_build_plate].append(message.data.decode("utf-8", "replace")) #type: ignore #Because we generate this attribute dynamically.
  706. except KeyError:
  707. # Can occur if the g-code has been cleared while a slice message is still arriving from the other end.
  708. pass # Throw the message away.
  709. def _onGCodePrefixMessage(self, message: Arcus.PythonMessage) -> None:
  710. """Called when a g-code prefix message is received from the engine.
  711. :param message: The protobuf message containing the g-code prefix,
  712. encoded as UTF-8.
  713. """
  714. try:
  715. self._scene.gcode_dict[self._start_slice_job_build_plate].insert(0, message.data.decode("utf-8", "replace")) #type: ignore #Because we generate this attribute dynamically.
  716. except KeyError:
  717. # Can occur if the g-code has been cleared while a slice message is still arriving from the other end.
  718. pass # Throw the message away.
  719. def _onSliceUUIDMessage(self, message: Arcus.PythonMessage) -> None:
  720. application = CuraApplication.getInstance()
  721. application.getPrintInformation().slice_uuid = message.slice_uuid
  722. def _createSocket(self, protocol_file: str = None) -> None:
  723. """Creates a new socket connection."""
  724. if not protocol_file:
  725. if not self.getPluginId():
  726. Logger.error("Can't create socket before CuraEngineBackend plug-in is registered.")
  727. return
  728. plugin_path = PluginRegistry.getInstance().getPluginPath(self.getPluginId())
  729. if not plugin_path:
  730. Logger.error("Could not get plugin path!", self.getPluginId())
  731. return
  732. protocol_file = os.path.abspath(os.path.join(plugin_path, "Cura.proto"))
  733. super()._createSocket(protocol_file)
  734. self._engine_is_fresh = True
  735. def _onChanged(self, *args: Any, **kwargs: Any) -> None:
  736. """Called when anything has changed to the stuff that needs to be sliced.
  737. This indicates that we should probably re-slice soon.
  738. """
  739. self.needsSlicing()
  740. if self._use_timer:
  741. # if the error check is scheduled, wait for the error check finish signal to trigger auto-slice,
  742. # otherwise business as usual
  743. if self._machine_error_checker is None:
  744. self._change_timer.stop()
  745. return
  746. if self._machine_error_checker.needToWaitForResult:
  747. self._change_timer.stop()
  748. else:
  749. self._change_timer.start()
  750. def _onPrintTimeMaterialEstimates(self, message: Arcus.PythonMessage) -> None:
  751. """Called when a print time message is received from the engine.
  752. :param message: The protobuf message containing the print time per feature and
  753. material amount per extruder
  754. """
  755. material_amounts = []
  756. for index in range(message.repeatedMessageCount("materialEstimates")):
  757. material_amounts.append(message.getRepeatedMessage("materialEstimates", index).material_amount)
  758. times = self._parseMessagePrintTimes(message)
  759. self.printDurationMessage.emit(self._start_slice_job_build_plate, times, material_amounts)
  760. def _parseMessagePrintTimes(self, message: Arcus.PythonMessage) -> Dict[str, float]:
  761. """Called for parsing message to retrieve estimated time per feature
  762. :param message: The protobuf message containing the print time per feature
  763. """
  764. result = {
  765. "inset_0": message.time_inset_0,
  766. "inset_x": message.time_inset_x,
  767. "skin": message.time_skin,
  768. "infill": message.time_infill,
  769. "support_infill": message.time_support_infill,
  770. "support_interface": message.time_support_interface,
  771. "support": message.time_support,
  772. "skirt": message.time_skirt,
  773. "prime_tower": message.time_prime_tower,
  774. "travel": message.time_travel,
  775. "retract": message.time_retract,
  776. "none": message.time_none
  777. }
  778. return result
  779. def _onBackendConnected(self) -> None:
  780. """Called when the back-end connects to the front-end."""
  781. if self._restart:
  782. self._restart = False
  783. self._onChanged()
  784. def _onToolOperationStarted(self, tool: Tool) -> None:
  785. """Called when the user starts using some tool.
  786. When the user starts using a tool, we should pause slicing to prevent
  787. continuously slicing while the user is dragging some tool handle.
  788. :param tool: The tool that the user is using.
  789. """
  790. self._tool_active = True # Do not react on scene change
  791. self.disableTimer()
  792. # Restart engine as soon as possible, we know we want to slice afterwards
  793. if not self._engine_is_fresh:
  794. self._terminate()
  795. self._createSocket()
  796. def _onToolOperationStopped(self, tool: Tool) -> None:
  797. """Called when the user stops using some tool.
  798. This indicates that we can safely start slicing again.
  799. :param tool: The tool that the user was using.
  800. """
  801. self._tool_active = False # React on scene change again
  802. self.determineAutoSlicing() # Switch timer on if appropriate
  803. # Process all the postponed scene changes
  804. while self._postponed_scene_change_sources:
  805. source = self._postponed_scene_change_sources.pop(0)
  806. self._onSceneChanged(source)
  807. def _startProcessSlicedLayersJob(self, build_plate_number: int) -> None:
  808. self._process_layers_job = ProcessSlicedLayersJob(self._stored_optimized_layer_data[build_plate_number])
  809. self._process_layers_job.setBuildPlate(build_plate_number)
  810. self._process_layers_job.finished.connect(self._onProcessLayersFinished)
  811. self._process_layers_job.start()
  812. def _onActiveViewChanged(self) -> None:
  813. """Called when the user changes the active view mode."""
  814. view = CuraApplication.getInstance().getController().getActiveView()
  815. if view:
  816. active_build_plate = CuraApplication.getInstance().getMultiBuildPlateModel().activeBuildPlate
  817. if view.getPluginId() == "SimulationView":
  818. # If switching to layer view, we should process the layers if that hasn't been done yet.
  819. self._layer_view_active = True
  820. # There is data and we're not slicing at the moment
  821. # if we are slicing, there is no need to re-calculate the data as it will be invalid in a moment.
  822. # TODO: what build plate I am slicing
  823. if (active_build_plate in self._stored_optimized_layer_data and
  824. not self._slicing and
  825. not self._process_layers_job and
  826. active_build_plate not in self._build_plates_to_be_sliced):
  827. self._startProcessSlicedLayersJob(active_build_plate)
  828. else:
  829. self._layer_view_active = False
  830. def _onBackendQuit(self) -> None:
  831. """Called when the back-end self-terminates.
  832. We should reset our state and start listening for new connections.
  833. """
  834. if not self._restart:
  835. if self._process: # type: ignore
  836. return_code = self._process.wait()
  837. if return_code != 0:
  838. Logger.log("e", f"Backend exited abnormally with return code {return_code}!")
  839. self._slicing_error_message.show()
  840. self.setState(BackendState.Error)
  841. self.stopSlicing()
  842. else:
  843. Logger.log("d", "Backend finished slicing. Resetting process and socket.")
  844. self.stopPlugins()
  845. self._process = None # type: ignore
  846. def _reportBackendError(self, _message_id: str, _action_id: str) -> None:
  847. """
  848. Triggered when the user wants to report an error in the back-end.
  849. """
  850. QDesktopServices.openUrl(QUrl("https://github.com/Ultimaker/Cura/issues/new/choose"))
  851. def _onGlobalStackChanged(self) -> None:
  852. """Called when the global container stack changes"""
  853. if self._global_container_stack:
  854. self._global_container_stack.propertyChanged.disconnect(self._onSettingChanged)
  855. self._global_container_stack.containersChanged.disconnect(self._onChanged)
  856. for extruder in self._global_container_stack.extruderList:
  857. extruder.propertyChanged.disconnect(self._onSettingChanged)
  858. extruder.containersChanged.disconnect(self._onChanged)
  859. self._global_container_stack = CuraApplication.getInstance().getMachineManager().activeMachine
  860. if self._global_container_stack:
  861. # Note: Only starts slicing when the value changed.
  862. self._global_container_stack.propertyChanged.connect(self._onSettingChanged)
  863. self._global_container_stack.containersChanged.connect(self._onChanged)
  864. for extruder in self._global_container_stack.extruderList:
  865. extruder.propertyChanged.connect(self._onSettingChanged)
  866. extruder.containersChanged.connect(self._onChanged)
  867. self._onChanged()
  868. def _onProcessLayersFinished(self, job: ProcessSlicedLayersJob) -> None:
  869. if job.getBuildPlate() in self._stored_optimized_layer_data:
  870. del self._stored_optimized_layer_data[job.getBuildPlate()]
  871. else:
  872. Logger.log("w", "The optimized layer data was already deleted for buildplate %s", job.getBuildPlate())
  873. self._process_layers_job = None
  874. Logger.log("d", "See if there is more to slice(2)...")
  875. self._invokeSlice()
  876. def enableTimer(self) -> None:
  877. """Connect slice function to timer."""
  878. if not self._use_timer:
  879. self._change_timer.timeout.connect(self.slice)
  880. self._use_timer = True
  881. def disableTimer(self) -> None:
  882. """Disconnect slice function from timer.
  883. This means that slicing will not be triggered automatically
  884. """
  885. if self._use_timer:
  886. self._use_timer = False
  887. self._change_timer.timeout.disconnect(self.slice)
  888. def _onPreferencesChanged(self, preference: str) -> None:
  889. if preference != "general/auto_slice" and preference != "info/send_engine_crash" and preference != "info/anonymous_engine_crash_report":
  890. return
  891. if preference == "general/auto_slice":
  892. auto_slice = self.determineAutoSlicing()
  893. if auto_slice:
  894. self._change_timer.start()
  895. elif preference == "info/send_engine_crash":
  896. os.environ["USE_SENTRY"] = "1" if CuraApplication.getInstance().getPreferences().getValue("info/send_engine_crash") else "0"
  897. def tickle(self) -> None:
  898. """Tickle the backend so in case of auto slicing, it starts the timer."""
  899. if self._use_timer:
  900. self._change_timer.start()
  901. def _extruderChanged(self) -> None:
  902. if not self._multi_build_plate_model:
  903. Logger.log("w", "CuraEngineBackend does not have multi_build_plate_model assigned!")
  904. return
  905. for build_plate_number in range(self._multi_build_plate_model.maxBuildPlate + 1):
  906. if build_plate_number not in self._build_plates_to_be_sliced:
  907. self._build_plates_to_be_sliced.append(build_plate_number)
  908. self._invokeSlice()