CuraEngineBackend.py 53 KB

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