CuraEngineBackend.py 53 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139
  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. immediate_success = self._socket.sendMessage(job.getSliceMessage())
  473. if (not CuraApplication.getInstance().getUseExternalBackend()) and (not immediate_success):
  474. if self._last_socket_error is not None and self._last_socket_error.getErrorCode() == Arcus.ErrorCode.MessageTooBigError:
  475. 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.")
  476. else:
  477. error_txt = catalog.i18nc("@info:status", "Unable to send the model data to the engine. Please try again, or contact support.")
  478. self._error_message = Message(error_txt,
  479. title=catalog.i18nc("@info:title", "Unable to slice"),
  480. message_type=Message.MessageType.WARNING)
  481. self._error_message.show()
  482. self.setState(BackendState.Error)
  483. self.backendError.emit(job)
  484. return
  485. # Notify the user that it's now up to the backend to do its job
  486. self.setState(BackendState.Processing)
  487. # Handle time reporting.
  488. self._time_send_message = time()
  489. if self._time_start_process:
  490. Logger.log("d", "Sending slice message took %s seconds", self._time_send_message - self._time_start_process)
  491. def determineAutoSlicing(self) -> bool:
  492. """Determine enable or disable auto slicing. Return True for enable timer and False otherwise.
  493. It disables when:
  494. - preference auto slice is off
  495. - decorator isBlockSlicing is found (used in g-code reader)
  496. """
  497. enable_timer = True
  498. self._is_disabled = False
  499. if not CuraApplication.getInstance().getPreferences().getValue("general/auto_slice"):
  500. enable_timer = False
  501. for node in DepthFirstIterator(self._scene.getRoot()):
  502. if node.callDecoration("isBlockSlicing"):
  503. enable_timer = False
  504. self.setState(BackendState.Disabled)
  505. self._is_disabled = True
  506. gcode_list = node.callDecoration("getGCodeList")
  507. if gcode_list is not None:
  508. self._scene.gcode_dict[node.callDecoration("getBuildPlateNumber")] = gcode_list # type: ignore
  509. # We need to ignore type because we generate this attribute dynamically.
  510. if self._use_timer == enable_timer:
  511. return self._use_timer
  512. if enable_timer:
  513. self.setState(BackendState.NotStarted)
  514. self.enableTimer()
  515. return True
  516. else:
  517. self.disableTimer()
  518. return False
  519. def _numObjectsPerBuildPlate(self) -> Dict[int, int]:
  520. """Return a dict with number of objects per build plate"""
  521. num_objects: Dict[int, int] = defaultdict(int)
  522. for node in DepthFirstIterator(self._scene.getRoot()):
  523. # Only count sliceable objects
  524. if node.callDecoration("isSliceable"):
  525. build_plate_number = node.callDecoration("getBuildPlateNumber")
  526. if build_plate_number is not None:
  527. num_objects[build_plate_number] += 1
  528. return num_objects
  529. def _onSceneChanged(self, source: SceneNode) -> None:
  530. """Listener for when the scene has changed.
  531. This should start a slice if the scene is now ready to slice.
  532. :param source: The scene node that was changed.
  533. """
  534. if not source.callDecoration("isSliceable") and source != self._scene.getRoot():
  535. return
  536. # This case checks if the source node is a node that contains GCode. In this case the
  537. # current layer data is removed so the previous data is not rendered - CURA-4821
  538. if source.callDecoration("isBlockSlicing") and source.callDecoration("getLayerData"):
  539. self._stored_optimized_layer_data = {}
  540. build_plate_changed = set()
  541. source_build_plate_number = source.callDecoration("getBuildPlateNumber")
  542. if source == self._scene.getRoot():
  543. # we got the root node
  544. num_objects = self._numObjectsPerBuildPlate()
  545. for build_plate_number in list(self._last_num_objects.keys()) + list(num_objects.keys()):
  546. if build_plate_number not in self._last_num_objects or num_objects[build_plate_number] != self._last_num_objects[build_plate_number]:
  547. self._last_num_objects[build_plate_number] = num_objects[build_plate_number]
  548. build_plate_changed.add(build_plate_number)
  549. else:
  550. # we got a single scenenode
  551. if not source.callDecoration("isGroup"):
  552. mesh_data = source.getMeshData()
  553. if mesh_data is None or mesh_data.getVertices() is None:
  554. return
  555. # There are some SceneNodes that do not have any build plate associated, then do not add to the list.
  556. if source_build_plate_number is not None:
  557. build_plate_changed.add(source_build_plate_number)
  558. if not build_plate_changed:
  559. return
  560. if self._tool_active:
  561. # do it later, each source only has to be done once
  562. if source not in self._postponed_scene_change_sources:
  563. self._postponed_scene_change_sources.append(source)
  564. return
  565. self.stopSlicing()
  566. for build_plate_number in build_plate_changed:
  567. if build_plate_number not in self._build_plates_to_be_sliced:
  568. self._build_plates_to_be_sliced.append(build_plate_number)
  569. self.printDurationMessage.emit(source_build_plate_number, {}, [])
  570. self.processingProgress.emit(0.0)
  571. self._clearLayerData(build_plate_changed)
  572. self._invokeSlice()
  573. def _onSocketError(self, error: Arcus.Error) -> None:
  574. """Called when an error occurs in the socket connection towards the engine.
  575. :param error: The exception that occurred.
  576. """
  577. if CuraApplication.getInstance().isShuttingDown():
  578. return
  579. super()._onSocketError(error)
  580. if error.getErrorCode() == Arcus.ErrorCode.Debug:
  581. return
  582. self._last_socket_error = error
  583. self._terminate()
  584. self._createSocket()
  585. if error.getErrorCode() not in [Arcus.ErrorCode.BindFailedError,
  586. Arcus.ErrorCode.ConnectionResetError,
  587. Arcus.ErrorCode.Debug]:
  588. Logger.log("w", "A socket error caused the connection to be reset")
  589. # _terminate()' function sets the job status to 'cancel', after reconnecting to another Port the job status
  590. # needs to be updated. Otherwise, backendState is "Unable To Slice"
  591. if error.getErrorCode() == Arcus.ErrorCode.BindFailedError and self._start_slice_job is not None:
  592. self._start_slice_job.setIsCancelled(False)
  593. # Check if there's any slicable object in the scene.
  594. def hasSlicableObject(self) -> bool:
  595. has_slicable = False
  596. for node in DepthFirstIterator(self._scene.getRoot()):
  597. if node.callDecoration("isSliceable"):
  598. has_slicable = True
  599. break
  600. return has_slicable
  601. def _clearLayerData(self, build_plate_numbers: Set = None) -> None:
  602. """Remove old layer data (if any)"""
  603. # Clear out any old gcode
  604. self._scene.gcode_dict = {} # type: ignore
  605. for node in DepthFirstIterator(self._scene.getRoot()):
  606. if node.callDecoration("getLayerData"):
  607. if not build_plate_numbers or node.callDecoration("getBuildPlateNumber") in build_plate_numbers:
  608. # We can assume that all nodes have a parent as we're looping through the scene and filter out root
  609. cast(SceneNode, node.getParent()).removeChild(node)
  610. def markSliceAll(self) -> None:
  611. for build_plate_number in range(CuraApplication.getInstance().getMultiBuildPlateModel().maxBuildPlate + 1):
  612. if build_plate_number not in self._build_plates_to_be_sliced:
  613. self._build_plates_to_be_sliced.append(build_plate_number)
  614. def needsSlicing(self) -> None:
  615. """Convenient function: mark everything to slice, emit state and clear layer data"""
  616. # CURA-6604: If there's no slicable object, do not (try to) trigger slice, which will clear all the current
  617. # gcode. This can break Gcode file loading if it tries to remove it afterwards.
  618. if not self.hasSlicableObject():
  619. return
  620. self.determineAutoSlicing()
  621. self.stopSlicing()
  622. self.markSliceAll()
  623. self.processingProgress.emit(0.0)
  624. if not self._use_timer:
  625. # With manually having to slice, we want to clear the old invalid layer data.
  626. self._clearLayerData()
  627. def _onSettingChanged(self, instance: SettingInstance, property: str) -> None:
  628. """A setting has changed, so check if we must reslice.
  629. :param instance: The setting instance that has changed.
  630. :param property: The property of the setting instance that has changed.
  631. """
  632. if property == "value": # Only re-slice if the value has changed.
  633. self.needsSlicing()
  634. self._onChanged()
  635. elif property == "validationState":
  636. if self._use_timer:
  637. self._change_timer.stop()
  638. def _onStackErrorCheckFinished(self) -> None:
  639. self.determineAutoSlicing()
  640. if self._is_disabled:
  641. return
  642. if not self._slicing and self._build_plates_to_be_sliced:
  643. self.needsSlicing()
  644. self._onChanged()
  645. def _onLayerMessage(self, message: Arcus.PythonMessage) -> None:
  646. """Called when a sliced layer data message is received from the engine.
  647. :param message: The protobuf message containing sliced layer data.
  648. """
  649. self._stored_layer_data.append(message)
  650. def _onOptimizedLayerMessage(self, message: Arcus.PythonMessage) -> None:
  651. """Called when an optimized sliced layer data message is received from the engine.
  652. :param message: The protobuf message containing sliced layer data.
  653. """
  654. if self._start_slice_job_build_plate is not None:
  655. if self._start_slice_job_build_plate not in self._stored_optimized_layer_data:
  656. self._stored_optimized_layer_data[self._start_slice_job_build_plate] = []
  657. self._stored_optimized_layer_data[self._start_slice_job_build_plate].append(message)
  658. def _onProgressMessage(self, message: Arcus.PythonMessage) -> None:
  659. """Called when a progress message is received from the engine.
  660. :param message: The protobuf message containing the slicing progress.
  661. """
  662. self.processingProgress.emit(message.amount)
  663. self.setState(BackendState.Processing)
  664. def _invokeSlice(self) -> None:
  665. if self._use_timer:
  666. # if the error check is scheduled, wait for the error check finish signal to trigger auto-slice,
  667. # otherwise business as usual
  668. if self._machine_error_checker is None:
  669. self._change_timer.stop()
  670. return
  671. if self._machine_error_checker.needToWaitForResult:
  672. self._change_timer.stop()
  673. else:
  674. self._change_timer.start()
  675. def _onSlicingFinishedMessage(self, message: Arcus.PythonMessage) -> None:
  676. """Called when the engine sends a message that slicing is finished.
  677. :param message: The protobuf message signalling that slicing is finished.
  678. """
  679. self.stopPlugins()
  680. self.setState(BackendState.Done)
  681. self.processingProgress.emit(1.0)
  682. self._time_end_slice = time()
  683. try:
  684. gcode_list = self._scene.gcode_dict[self._start_slice_job_build_plate] #type: ignore
  685. # We need to ignore the type because it was generated dynamically.
  686. except KeyError:
  687. # Can occur if the g-code has been cleared while a slice message is still arriving from the other end.
  688. gcode_list = []
  689. application = CuraApplication.getInstance()
  690. for index, line in enumerate(gcode_list):
  691. replaced = line.replace("{print_time}", str(application.getPrintInformation().currentPrintTime.getDisplayString(DurationFormat.Format.ISO8601)))
  692. replaced = replaced.replace("{filament_amount}", str(application.getPrintInformation().materialLengths))
  693. replaced = replaced.replace("{filament_weight}", str(application.getPrintInformation().materialWeights))
  694. replaced = replaced.replace("{filament_cost}", str(application.getPrintInformation().materialCosts))
  695. replaced = replaced.replace("{jobname}", str(application.getPrintInformation().jobName))
  696. gcode_list[index] = replaced
  697. self._slicing = False
  698. if self._time_start_process:
  699. Logger.log("d", "Slicing took %s seconds", time() - self._time_start_process)
  700. Logger.log("d", "Number of models per buildplate: %s", dict(self._numObjectsPerBuildPlate()))
  701. # See if we need to process the sliced layers job.
  702. active_build_plate = application.getMultiBuildPlateModel().activeBuildPlate
  703. if (
  704. self._layer_view_active and
  705. (self._process_layers_job is None or not self._process_layers_job.isRunning()) and
  706. active_build_plate == self._start_slice_job_build_plate and
  707. active_build_plate not in self._build_plates_to_be_sliced):
  708. self._startProcessSlicedLayersJob(active_build_plate)
  709. # self._onActiveViewChanged()
  710. self._start_slice_job_build_plate = None
  711. Logger.log("d", "See if there is more to slice...")
  712. # Somehow this results in an Arcus Error
  713. # self.slice()
  714. # Call slice again using the timer, allowing the backend to restart
  715. if self._build_plates_to_be_sliced:
  716. self.enableTimer() # manually enable timer to be able to invoke slice, also when in manual slice mode
  717. self._invokeSlice()
  718. def _onGCodeLayerMessage(self, message: Arcus.PythonMessage) -> None:
  719. """Called when a g-code message is received from the engine.
  720. :param message: The protobuf message containing g-code, encoded as UTF-8.
  721. """
  722. try:
  723. 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.
  724. except KeyError:
  725. # Can occur if the g-code has been cleared while a slice message is still arriving from the other end.
  726. pass # Throw the message away.
  727. def _onGCodePrefixMessage(self, message: Arcus.PythonMessage) -> None:
  728. """Called when a g-code prefix message is received from the engine.
  729. :param message: The protobuf message containing the g-code prefix,
  730. encoded as UTF-8.
  731. """
  732. try:
  733. 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.
  734. except KeyError:
  735. # Can occur if the g-code has been cleared while a slice message is still arriving from the other end.
  736. pass # Throw the message away.
  737. def _onSliceUUIDMessage(self, message: Arcus.PythonMessage) -> None:
  738. application = CuraApplication.getInstance()
  739. application.getPrintInformation().slice_uuid = message.slice_uuid
  740. def _createSocket(self, protocol_file: str = None) -> None:
  741. """Creates a new socket connection."""
  742. if not protocol_file:
  743. if not self.getPluginId():
  744. Logger.error("Can't create socket before CuraEngineBackend plug-in is registered.")
  745. return
  746. plugin_path = PluginRegistry.getInstance().getPluginPath(self.getPluginId())
  747. if not plugin_path:
  748. Logger.error("Could not get plugin path!", self.getPluginId())
  749. return
  750. protocol_file = os.path.abspath(os.path.join(plugin_path, "Cura.proto"))
  751. super()._createSocket(protocol_file)
  752. self._engine_is_fresh = True
  753. def _onChanged(self, *args: Any, **kwargs: Any) -> None:
  754. """Called when anything has changed to the stuff that needs to be sliced.
  755. This indicates that we should probably re-slice soon.
  756. """
  757. self.needsSlicing()
  758. if self._use_timer:
  759. # if the error check is scheduled, wait for the error check finish signal to trigger auto-slice,
  760. # otherwise business as usual
  761. if self._machine_error_checker is None:
  762. self._change_timer.stop()
  763. return
  764. if self._machine_error_checker.needToWaitForResult:
  765. self._change_timer.stop()
  766. else:
  767. self._change_timer.start()
  768. def _onPrintTimeMaterialEstimates(self, message: Arcus.PythonMessage) -> None:
  769. """Called when a print time message is received from the engine.
  770. :param message: The protobuf message containing the print time per feature and
  771. material amount per extruder
  772. """
  773. material_amounts = []
  774. for index in range(message.repeatedMessageCount("materialEstimates")):
  775. material_amounts.append(message.getRepeatedMessage("materialEstimates", index).material_amount)
  776. times = self._parseMessagePrintTimes(message)
  777. self.printDurationMessage.emit(self._start_slice_job_build_plate, times, material_amounts)
  778. def _parseMessagePrintTimes(self, message: Arcus.PythonMessage) -> Dict[str, float]:
  779. """Called for parsing message to retrieve estimated time per feature
  780. :param message: The protobuf message containing the print time per feature
  781. """
  782. result = {
  783. "inset_0": message.time_inset_0,
  784. "inset_x": message.time_inset_x,
  785. "skin": message.time_skin,
  786. "infill": message.time_infill,
  787. "support_infill": message.time_support_infill,
  788. "support_interface": message.time_support_interface,
  789. "support": message.time_support,
  790. "skirt": message.time_skirt,
  791. "prime_tower": message.time_prime_tower,
  792. "travel": message.time_travel,
  793. "retract": message.time_retract,
  794. "none": message.time_none
  795. }
  796. return result
  797. def _onBackendConnected(self) -> None:
  798. """Called when the back-end connects to the front-end."""
  799. if self._restart:
  800. self._restart = False
  801. self._onChanged()
  802. def _onToolOperationStarted(self, tool: Tool) -> None:
  803. """Called when the user starts using some tool.
  804. When the user starts using a tool, we should pause slicing to prevent
  805. continuously slicing while the user is dragging some tool handle.
  806. :param tool: The tool that the user is using.
  807. """
  808. self._tool_active = True # Do not react on scene change
  809. self.disableTimer()
  810. # Restart engine as soon as possible, we know we want to slice afterwards
  811. if not self._engine_is_fresh:
  812. self._terminate()
  813. self._createSocket()
  814. def _onToolOperationStopped(self, tool: Tool) -> None:
  815. """Called when the user stops using some tool.
  816. This indicates that we can safely start slicing again.
  817. :param tool: The tool that the user was using.
  818. """
  819. self._tool_active = False # React on scene change again
  820. self.determineAutoSlicing() # Switch timer on if appropriate
  821. # Process all the postponed scene changes
  822. while self._postponed_scene_change_sources:
  823. source = self._postponed_scene_change_sources.pop(0)
  824. self._onSceneChanged(source)
  825. def _startProcessSlicedLayersJob(self, build_plate_number: int) -> None:
  826. self._process_layers_job = ProcessSlicedLayersJob(self._stored_optimized_layer_data[build_plate_number])
  827. self._process_layers_job.setBuildPlate(build_plate_number)
  828. self._process_layers_job.finished.connect(self._onProcessLayersFinished)
  829. self._process_layers_job.start()
  830. def _onActiveViewChanged(self) -> None:
  831. """Called when the user changes the active view mode."""
  832. view = CuraApplication.getInstance().getController().getActiveView()
  833. if view:
  834. active_build_plate = CuraApplication.getInstance().getMultiBuildPlateModel().activeBuildPlate
  835. if view.getPluginId() == "SimulationView":
  836. # If switching to layer view, we should process the layers if that hasn't been done yet.
  837. self._layer_view_active = True
  838. # There is data and we're not slicing at the moment
  839. # if we are slicing, there is no need to re-calculate the data as it will be invalid in a moment.
  840. # TODO: what build plate I am slicing
  841. if (active_build_plate in self._stored_optimized_layer_data and
  842. not self._slicing and
  843. not self._process_layers_job and
  844. active_build_plate not in self._build_plates_to_be_sliced):
  845. self._startProcessSlicedLayersJob(active_build_plate)
  846. else:
  847. self._layer_view_active = False
  848. def _onBackendQuit(self) -> None:
  849. """Called when the back-end self-terminates.
  850. We should reset our state and start listening for new connections.
  851. """
  852. if not self._restart:
  853. if self._process: # type: ignore
  854. return_code = self._process.wait()
  855. if return_code != 0:
  856. Logger.log("e", f"Backend exited abnormally with return code {return_code}!")
  857. self._slicing_error_message.show()
  858. self.setState(BackendState.Error)
  859. self.stopSlicing()
  860. else:
  861. Logger.log("d", "Backend finished slicing. Resetting process and socket.")
  862. self.stopPlugins()
  863. self._process = None # type: ignore
  864. def _reportBackendError(self, _message_id: str, _action_id: str) -> None:
  865. """
  866. Triggered when the user wants to report an error in the back-end.
  867. """
  868. QDesktopServices.openUrl(QUrl("https://github.com/Ultimaker/Cura/issues/new/choose"))
  869. def _onGlobalStackChanged(self) -> None:
  870. """Called when the global container stack changes"""
  871. if self._global_container_stack:
  872. self._global_container_stack.propertyChanged.disconnect(self._onSettingChanged)
  873. self._global_container_stack.containersChanged.disconnect(self._onChanged)
  874. for extruder in self._global_container_stack.extruderList:
  875. extruder.propertyChanged.disconnect(self._onSettingChanged)
  876. extruder.containersChanged.disconnect(self._onChanged)
  877. self._global_container_stack = CuraApplication.getInstance().getMachineManager().activeMachine
  878. if self._global_container_stack:
  879. # Note: Only starts slicing when the value changed.
  880. self._global_container_stack.propertyChanged.connect(self._onSettingChanged)
  881. self._global_container_stack.containersChanged.connect(self._onChanged)
  882. for extruder in self._global_container_stack.extruderList:
  883. extruder.propertyChanged.connect(self._onSettingChanged)
  884. extruder.containersChanged.connect(self._onChanged)
  885. self._onChanged()
  886. def _onProcessLayersFinished(self, job: ProcessSlicedLayersJob) -> None:
  887. if job.getBuildPlate() in self._stored_optimized_layer_data:
  888. del self._stored_optimized_layer_data[job.getBuildPlate()]
  889. else:
  890. Logger.log("w", "The optimized layer data was already deleted for buildplate %s", job.getBuildPlate())
  891. self._process_layers_job = None
  892. Logger.log("d", "See if there is more to slice(2)...")
  893. self._invokeSlice()
  894. def enableTimer(self) -> None:
  895. """Connect slice function to timer."""
  896. if not self._use_timer:
  897. self._change_timer.timeout.connect(self.slice)
  898. self._use_timer = True
  899. def disableTimer(self) -> None:
  900. """Disconnect slice function from timer.
  901. This means that slicing will not be triggered automatically
  902. """
  903. if self._use_timer:
  904. self._use_timer = False
  905. self._change_timer.timeout.disconnect(self.slice)
  906. def _onPreferencesChanged(self, preference: str) -> None:
  907. if preference != "general/auto_slice" and preference != "info/send_engine_crash" and preference != "info/anonymous_engine_crash_report":
  908. return
  909. if preference == "general/auto_slice":
  910. auto_slice = self.determineAutoSlicing()
  911. if auto_slice:
  912. self._change_timer.start()
  913. elif preference == "info/send_engine_crash":
  914. os.environ["USE_SENTRY"] = "1" if CuraApplication.getInstance().getPreferences().getValue("info/send_engine_crash") else "0"
  915. def tickle(self) -> None:
  916. """Tickle the backend so in case of auto slicing, it starts the timer."""
  917. if self._use_timer:
  918. self._change_timer.start()
  919. def _extruderChanged(self) -> None:
  920. if not self._multi_build_plate_model:
  921. Logger.log("w", "CuraEngineBackend does not have multi_build_plate_model assigned!")
  922. return
  923. for build_plate_number in range(self._multi_build_plate_model.maxBuildPlate + 1):
  924. if build_plate_number not in self._build_plates_to_be_sliced:
  925. self._build_plates_to_be_sliced.append(build_plate_number)
  926. self._invokeSlice()