CuraEngineBackend.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594
  1. # Copyright (c) 2015 Ultimaker B.V.
  2. # Cura is released under the terms of the AGPLv3 or higher.
  3. from UM.Backend.Backend import Backend, BackendState
  4. from UM.Application import Application
  5. from UM.Scene.SceneNode import SceneNode
  6. from UM.Preferences import Preferences
  7. from UM.Signal import Signal
  8. from UM.Logger import Logger
  9. from UM.Message import Message
  10. from UM.PluginRegistry import PluginRegistry
  11. from UM.Resources import Resources
  12. from UM.Settings.Validator import ValidatorState #To find if a setting is in an error state. We can't slice then.
  13. from UM.Platform import Platform
  14. from UM.Scene.Iterator.DepthFirstIterator import DepthFirstIterator
  15. from PyQt5.QtCore import QObject, pyqtSlot
  16. from cura.Settings.ExtruderManager import ExtruderManager
  17. from . import ProcessSlicedLayersJob
  18. from . import StartSliceJob
  19. import os
  20. import sys
  21. from time import time
  22. from PyQt5.QtCore import QTimer
  23. import Arcus
  24. from UM.i18n import i18nCatalog
  25. catalog = i18nCatalog("cura")
  26. class CuraEngineBackend(QObject, Backend):
  27. ## Starts the back-end plug-in.
  28. #
  29. # This registers all the signal listeners and prepares for communication
  30. # with the back-end in general.
  31. # CuraEngineBackend is exposed to qml as well.
  32. def __init__(self, parent = None):
  33. super().__init__(parent = parent)
  34. # Find out where the engine is located, and how it is called.
  35. # This depends on how Cura is packaged and which OS we are running on.
  36. executable_name = "CuraEngine"
  37. if Platform.isWindows():
  38. executable_name += ".exe"
  39. default_engine_location = executable_name
  40. if os.path.exists(os.path.join(Application.getInstallPrefix(), "bin", executable_name)):
  41. default_engine_location = os.path.join(Application.getInstallPrefix(), "bin", executable_name)
  42. if hasattr(sys, "frozen"):
  43. default_engine_location = os.path.join(os.path.dirname(os.path.abspath(sys.executable)), executable_name)
  44. if Platform.isLinux() and not default_engine_location:
  45. if not os.getenv("PATH"):
  46. raise OSError("There is something wrong with your Linux installation.")
  47. for pathdir in os.getenv("PATH").split(os.pathsep):
  48. execpath = os.path.join(pathdir, executable_name)
  49. if os.path.exists(execpath):
  50. default_engine_location = execpath
  51. break
  52. if not default_engine_location:
  53. raise EnvironmentError("Could not find CuraEngine")
  54. Logger.log("i", "Found CuraEngine at: %s" %(default_engine_location))
  55. default_engine_location = os.path.abspath(default_engine_location)
  56. Preferences.getInstance().addPreference("backend/location", default_engine_location)
  57. # Workaround to disable layer view processing if layer view is not active.
  58. self._layer_view_active = False
  59. Application.getInstance().getController().activeViewChanged.connect(self._onActiveViewChanged)
  60. self._onActiveViewChanged()
  61. self._stored_layer_data = []
  62. self._stored_optimized_layer_data = []
  63. self._scene = Application.getInstance().getController().getScene()
  64. self._scene.sceneChanged.connect(self._onSceneChanged)
  65. # Triggers for when to (re)start slicing:
  66. self._global_container_stack = None
  67. Application.getInstance().globalContainerStackChanged.connect(self._onGlobalStackChanged)
  68. self._onGlobalStackChanged()
  69. self._active_extruder_stack = None
  70. ExtruderManager.getInstance().activeExtruderChanged.connect(self._onActiveExtruderChanged)
  71. self._onActiveExtruderChanged()
  72. # Listeners for receiving messages from the back-end.
  73. self._message_handlers["cura.proto.Layer"] = self._onLayerMessage
  74. self._message_handlers["cura.proto.LayerOptimized"] = self._onOptimizedLayerMessage
  75. self._message_handlers["cura.proto.Progress"] = self._onProgressMessage
  76. self._message_handlers["cura.proto.GCodeLayer"] = self._onGCodeLayerMessage
  77. self._message_handlers["cura.proto.GCodePrefix"] = self._onGCodePrefixMessage
  78. self._message_handlers["cura.proto.PrintTimeMaterialEstimates"] = self._onPrintTimeMaterialEstimates
  79. self._message_handlers["cura.proto.SlicingFinished"] = self._onSlicingFinishedMessage
  80. self._start_slice_job = None
  81. self._slicing = False # Are we currently slicing?
  82. self._restart = False # Back-end is currently restarting?
  83. self._tool_active = False # If a tool is active, some tasks do not have to do anything
  84. self._always_restart = True # Always restart the engine when starting a new slice. Don't keep the process running. TODO: Fix engine statelessness.
  85. self._process_layers_job = None # The currently active job to process layers, or None if it is not processing layers.
  86. self._need_slicing = False
  87. self._engine_is_fresh = True # Is the newly started engine used before or not?
  88. self._backend_log_max_lines = 20000 # Maximum number of lines to buffer
  89. self._error_message = None # Pop-up message that shows errors.
  90. self.backendQuit.connect(self._onBackendQuit)
  91. self.backendConnected.connect(self._onBackendConnected)
  92. # When a tool operation is in progress, don't slice. So we need to listen for tool operations.
  93. Application.getInstance().getController().toolOperationStarted.connect(self._onToolOperationStarted)
  94. Application.getInstance().getController().toolOperationStopped.connect(self._onToolOperationStopped)
  95. self._slice_start_time = None
  96. Preferences.getInstance().addPreference("general/auto_slice", True)
  97. self._use_timer = False
  98. # When you update a setting and other settings get changed through inheritance, many propertyChanged signals are fired.
  99. # This timer will group them up, and only slice for the last setting changed signal.
  100. # TODO: Properly group propertyChanged signals by whether they are triggered by the same user interaction.
  101. self._change_timer = QTimer()
  102. self._change_timer.setSingleShot(True)
  103. self._change_timer.setInterval(500)
  104. self.determineAutoSlicing()
  105. Preferences.getInstance().preferenceChanged.connect(self._onPreferencesChanged)
  106. ## Terminate the engine process.
  107. #
  108. # This function should terminate the engine process.
  109. # Called when closing the application.
  110. def close(self):
  111. # Terminate CuraEngine if it is still running at this point
  112. self._terminate()
  113. ## Get the command that is used to call the engine.
  114. # This is useful for debugging and used to actually start the engine.
  115. # \return list of commands and args / parameters.
  116. def getEngineCommand(self):
  117. json_path = Resources.getPath(Resources.DefinitionContainers, "fdmprinter.def.json")
  118. return [Preferences.getInstance().getValue("backend/location"), "connect", "127.0.0.1:{0}".format(self._port), "-j", json_path, ""]
  119. ## Emitted when we get a message containing print duration and material amount.
  120. # This also implies the slicing has finished.
  121. # \param time The amount of time the print will take.
  122. # \param material_amount The amount of material the print will use.
  123. printDurationMessage = Signal()
  124. ## Emitted when the slicing process starts.
  125. slicingStarted = Signal()
  126. ## Emitted when the slicing process is aborted forcefully.
  127. slicingCancelled = Signal()
  128. @pyqtSlot()
  129. def stopSlicing(self):
  130. self.backendStateChange.emit(BackendState.NotStarted)
  131. if self._slicing: # We were already slicing. Stop the old job.
  132. self._terminate()
  133. self._createSocket()
  134. if self._process_layers_job: # We were processing layers. Stop that, the layers are going to change soon.
  135. self._process_layers_job.abort()
  136. self._process_layers_job = None
  137. if self._error_message:
  138. self._error_message.hide()
  139. ## Manually triggers a reslice
  140. @pyqtSlot()
  141. def forceSlice(self):
  142. if self._use_timer:
  143. self._change_timer.start()
  144. else:
  145. self.slice()
  146. ## Perform a slice of the scene.
  147. def slice(self):
  148. self._slice_start_time = time()
  149. if not self._need_slicing:
  150. self.processingProgress.emit(1.0)
  151. self.backendStateChange.emit(BackendState.Done)
  152. Logger.log("w", "Slice unnecessary, nothing has changed that needs reslicing.")
  153. return
  154. self.printDurationMessage.emit(0, [0])
  155. self._stored_layer_data = []
  156. self._stored_optimized_layer_data = []
  157. if self._process is None:
  158. self._createSocket()
  159. self.stopSlicing()
  160. self._engine_is_fresh = False # Yes we're going to use the engine
  161. self.processingProgress.emit(0.0)
  162. self.backendStateChange.emit(BackendState.NotStarted)
  163. self._scene.gcode_list = []
  164. self._slicing = True
  165. self.slicingStarted.emit()
  166. slice_message = self._socket.createMessage("cura.proto.Slice")
  167. self._start_slice_job = StartSliceJob.StartSliceJob(slice_message)
  168. self._start_slice_job.start()
  169. self._start_slice_job.finished.connect(self._onStartSliceCompleted)
  170. ## Terminate the engine process.
  171. # Start the engine process by calling _createSocket()
  172. def _terminate(self):
  173. self._slicing = False
  174. self._stored_layer_data = []
  175. self._stored_optimized_layer_data = []
  176. if self._start_slice_job is not None:
  177. self._start_slice_job.cancel()
  178. self.slicingCancelled.emit()
  179. self.processingProgress.emit(0)
  180. Logger.log("d", "Attempting to kill the engine process")
  181. if Application.getInstance().getCommandLineOption("external-backend", False):
  182. return
  183. if self._process is not None:
  184. Logger.log("d", "Killing engine process")
  185. try:
  186. self._process.terminate()
  187. Logger.log("d", "Engine process is killed. Received return code %s", self._process.wait())
  188. self._process = None
  189. except Exception as e: # terminating a process that is already terminating causes an exception, silently ignore this.
  190. Logger.log("d", "Exception occurred while trying to kill the engine %s", str(e))
  191. ## Event handler to call when the job to initiate the slicing process is
  192. # completed.
  193. #
  194. # When the start slice job is successfully completed, it will be happily
  195. # slicing. This function handles any errors that may occur during the
  196. # bootstrapping of a slice job.
  197. #
  198. # \param job The start slice job that was just finished.
  199. def _onStartSliceCompleted(self, job):
  200. if self._error_message:
  201. self._error_message.hide()
  202. # Note that cancelled slice jobs can still call this method.
  203. if self._start_slice_job is job:
  204. self._start_slice_job = None
  205. if job.isCancelled() or job.getError() or job.getResult() == StartSliceJob.StartJobResult.Error:
  206. return
  207. if job.getResult() == StartSliceJob.StartJobResult.MaterialIncompatible:
  208. if Application.getInstance().platformActivity:
  209. self._error_message = Message(catalog.i18nc("@info:status",
  210. "The selected material is incompatible with the selected machine or configuration."))
  211. self._error_message.show()
  212. self.backendStateChange.emit(BackendState.Error)
  213. else:
  214. self.backendStateChange.emit(BackendState.NotStarted)
  215. return
  216. if job.getResult() == StartSliceJob.StartJobResult.SettingError:
  217. if Application.getInstance().platformActivity:
  218. extruders = list(ExtruderManager.getInstance().getMachineExtruders(self._global_container_stack.getId()))
  219. error_keys = []
  220. for extruder in extruders:
  221. error_keys.extend(extruder.getErrorKeys())
  222. if not extruders:
  223. error_keys = self._global_container_stack.getErrorKeys()
  224. error_labels = set()
  225. definition_container = self._global_container_stack.getBottom()
  226. for key in error_keys:
  227. error_labels.add(definition_container.findDefinitions(key = key)[0].label)
  228. error_labels = ", ".join(error_labels)
  229. self._error_message = Message(catalog.i18nc("@info:status", "Unable to slice with the current settings. The following settings have errors: {0}".format(error_labels)))
  230. self._error_message.show()
  231. self.backendStateChange.emit(BackendState.Error)
  232. else:
  233. self.backendStateChange.emit(BackendState.NotStarted)
  234. return
  235. if job.getResult() == StartSliceJob.StartJobResult.BuildPlateError:
  236. if Application.getInstance().platformActivity:
  237. self._error_message = Message(catalog.i18nc("@info:status", "Unable to slice because the prime tower or prime position(s) are invalid."))
  238. self._error_message.show()
  239. self.backendStateChange.emit(BackendState.Error)
  240. else:
  241. self.backendStateChange.emit(BackendState.NotStarted)
  242. if job.getResult() == StartSliceJob.StartJobResult.NothingToSlice:
  243. if Application.getInstance().platformActivity:
  244. self._error_message = Message(catalog.i18nc("@info:status", "Nothing to slice because none of the models fit the build volume. Please scale or rotate models to fit."))
  245. self._error_message.show()
  246. self.backendStateChange.emit(BackendState.Error)
  247. else:
  248. self.backendStateChange.emit(BackendState.NotStarted)
  249. return
  250. # Preparation completed, send it to the backend.
  251. self._socket.sendMessage(job.getSliceMessage())
  252. # Notify the user that it's now up to the backend to do it's job
  253. self.backendStateChange.emit(BackendState.Processing)
  254. Logger.log("d", "Sending slice message took %s seconds", time() - self._slice_start_time )
  255. ## Determine enable or disable auto slicing. Return True for enable timer and False otherwise.
  256. # It disables when
  257. # - preference auto slice is off
  258. # - decorator isBlockSlicing is found (used in g-code reader)
  259. def determineAutoSlicing(self):
  260. enable_timer = True
  261. if not Preferences.getInstance().getValue("general/auto_slice"):
  262. enable_timer = False
  263. for node in DepthFirstIterator(self._scene.getRoot()):
  264. if node.callDecoration("isBlockSlicing"):
  265. enable_timer = False
  266. self.backendStateChange.emit(BackendState.Disabled)
  267. gcode_list = node.callDecoration("getGCodeList")
  268. if gcode_list is not None:
  269. self._scene.gcode_list = gcode_list
  270. if self._use_timer == enable_timer:
  271. return self._use_timer
  272. if enable_timer:
  273. self.backendStateChange.emit(BackendState.NotStarted)
  274. self.enableTimer()
  275. return True
  276. else:
  277. self.disableTimer()
  278. return False
  279. ## Listener for when the scene has changed.
  280. #
  281. # This should start a slice if the scene is now ready to slice.
  282. #
  283. # \param source The scene node that was changed.
  284. def _onSceneChanged(self, source):
  285. if self._tool_active:
  286. return
  287. if type(source) is not SceneNode:
  288. return
  289. if source is self._scene.getRoot():
  290. return
  291. self.determineAutoSlicing()
  292. if source.getMeshData() is None:
  293. return
  294. if source.getMeshData().getVertices() is None:
  295. return
  296. self.needsSlicing()
  297. self.stopSlicing()
  298. self._onChanged()
  299. ## Called when an error occurs in the socket connection towards the engine.
  300. #
  301. # \param error The exception that occurred.
  302. def _onSocketError(self, error):
  303. if Application.getInstance().isShuttingDown():
  304. return
  305. super()._onSocketError(error)
  306. if error.getErrorCode() == Arcus.ErrorCode.Debug:
  307. return
  308. self._terminate()
  309. self._createSocket()
  310. if error.getErrorCode() not in [Arcus.ErrorCode.BindFailedError, Arcus.ErrorCode.ConnectionResetError, Arcus.ErrorCode.Debug]:
  311. Logger.log("w", "A socket error caused the connection to be reset")
  312. ## Remove old layer data (if any)
  313. def _clearLayerData(self):
  314. for node in DepthFirstIterator(self._scene.getRoot()):
  315. if node.callDecoration("getLayerData"):
  316. node.getParent().removeChild(node)
  317. break
  318. ## Convenient function: set need_slicing, emit state and clear layer data
  319. def needsSlicing(self):
  320. self._need_slicing = True
  321. self.processingProgress.emit(0.0)
  322. self.backendStateChange.emit(BackendState.NotStarted)
  323. if not self._use_timer:
  324. # With manually having to slice, we want to clear the old invalid layer data.
  325. self._clearLayerData()
  326. ## A setting has changed, so check if we must reslice.
  327. #
  328. # \param instance The setting instance that has changed.
  329. # \param property The property of the setting instance that has changed.
  330. def _onSettingChanged(self, instance, property):
  331. if property == "value": # Only reslice if the value has changed.
  332. self.needsSlicing()
  333. self._onChanged()
  334. ## Called when a sliced layer data message is received from the engine.
  335. #
  336. # \param message The protobuf message containing sliced layer data.
  337. def _onLayerMessage(self, message):
  338. self._stored_layer_data.append(message)
  339. ## Called when an optimized sliced layer data message is received from the engine.
  340. #
  341. # \param message The protobuf message containing sliced layer data.
  342. def _onOptimizedLayerMessage(self, message):
  343. self._stored_optimized_layer_data.append(message)
  344. ## Called when a progress message is received from the engine.
  345. #
  346. # \param message The protobuf message containing the slicing progress.
  347. def _onProgressMessage(self, message):
  348. self.processingProgress.emit(message.amount)
  349. self.backendStateChange.emit(BackendState.Processing)
  350. ## Called when the engine sends a message that slicing is finished.
  351. #
  352. # \param message The protobuf message signalling that slicing is finished.
  353. def _onSlicingFinishedMessage(self, message):
  354. self.backendStateChange.emit(BackendState.Done)
  355. self.processingProgress.emit(1.0)
  356. self._slicing = False
  357. self._need_slicing = False
  358. Logger.log("d", "Slicing took %s seconds", time() - self._slice_start_time )
  359. if self._layer_view_active and (self._process_layers_job is None or not self._process_layers_job.isRunning()):
  360. self._process_layers_job = ProcessSlicedLayersJob.ProcessSlicedLayersJob(self._stored_optimized_layer_data)
  361. self._process_layers_job.finished.connect(self._onProcessLayersFinished)
  362. self._process_layers_job.start()
  363. self._stored_optimized_layer_data = []
  364. ## Called when a g-code message is received from the engine.
  365. #
  366. # \param message The protobuf message containing g-code, encoded as UTF-8.
  367. def _onGCodeLayerMessage(self, message):
  368. self._scene.gcode_list.append(message.data.decode("utf-8", "replace"))
  369. ## Called when a g-code prefix message is received from the engine.
  370. #
  371. # \param message The protobuf message containing the g-code prefix,
  372. # encoded as UTF-8.
  373. def _onGCodePrefixMessage(self, message):
  374. self._scene.gcode_list.insert(0, message.data.decode("utf-8", "replace"))
  375. ## Called when a print time message is received from the engine.
  376. #
  377. # \param message The protobuff message containing the print time and
  378. # material amount per extruder
  379. def _onPrintTimeMaterialEstimates(self, message):
  380. material_amounts = []
  381. for index in range(message.repeatedMessageCount("materialEstimates")):
  382. material_amounts.append(message.getRepeatedMessage("materialEstimates", index).material_amount)
  383. self.printDurationMessage.emit(message.time, material_amounts)
  384. ## Creates a new socket connection.
  385. def _createSocket(self):
  386. super()._createSocket(os.path.abspath(os.path.join(PluginRegistry.getInstance().getPluginPath(self.getPluginId()), "Cura.proto")))
  387. self._engine_is_fresh = True
  388. ## Called when anything has changed to the stuff that needs to be sliced.
  389. #
  390. # This indicates that we should probably re-slice soon.
  391. def _onChanged(self, *args, **kwargs):
  392. self.needsSlicing()
  393. if self._use_timer:
  394. self._change_timer.start()
  395. ## Called when the back-end connects to the front-end.
  396. def _onBackendConnected(self):
  397. if self._restart:
  398. self._restart = False
  399. self._onChanged()
  400. ## Called when the user starts using some tool.
  401. #
  402. # When the user starts using a tool, we should pause slicing to prevent
  403. # continuously slicing while the user is dragging some tool handle.
  404. #
  405. # \param tool The tool that the user is using.
  406. def _onToolOperationStarted(self, tool):
  407. self._tool_active = True # Do not react on scene change
  408. self.disableTimer()
  409. # Restart engine as soon as possible, we know we want to slice afterwards
  410. if not self._engine_is_fresh:
  411. self._terminate()
  412. self._createSocket()
  413. ## Called when the user stops using some tool.
  414. #
  415. # This indicates that we can safely start slicing again.
  416. #
  417. # \param tool The tool that the user was using.
  418. def _onToolOperationStopped(self, tool):
  419. self._tool_active = False # React on scene change again
  420. self.determineAutoSlicing()
  421. ## Called when the user changes the active view mode.
  422. def _onActiveViewChanged(self):
  423. if Application.getInstance().getController().getActiveView():
  424. view = Application.getInstance().getController().getActiveView()
  425. if view.getPluginId() == "LayerView": # If switching to layer view, we should process the layers if that hasn't been done yet.
  426. self._layer_view_active = True
  427. # There is data and we're not slicing at the moment
  428. # if we are slicing, there is no need to re-calculate the data as it will be invalid in a moment.
  429. if self._stored_optimized_layer_data and not self._slicing:
  430. self._process_layers_job = ProcessSlicedLayersJob.ProcessSlicedLayersJob(self._stored_optimized_layer_data)
  431. self._process_layers_job.finished.connect(self._onProcessLayersFinished)
  432. self._process_layers_job.start()
  433. self._stored_optimized_layer_data = []
  434. else:
  435. self._layer_view_active = False
  436. ## Called when the back-end self-terminates.
  437. #
  438. # We should reset our state and start listening for new connections.
  439. def _onBackendQuit(self):
  440. if not self._restart:
  441. if self._process:
  442. Logger.log("d", "Backend quit with return code %s. Resetting process and socket.", self._process.wait())
  443. self._process = None
  444. ## Called when the global container stack changes
  445. def _onGlobalStackChanged(self):
  446. if self._global_container_stack:
  447. self._global_container_stack.propertyChanged.disconnect(self._onSettingChanged)
  448. self._global_container_stack.containersChanged.disconnect(self._onChanged)
  449. extruders = list(ExtruderManager.getInstance().getMachineExtruders(self._global_container_stack.getId()))
  450. if extruders:
  451. for extruder in extruders:
  452. extruder.propertyChanged.disconnect(self._onSettingChanged)
  453. self._global_container_stack = Application.getInstance().getGlobalContainerStack()
  454. if self._global_container_stack:
  455. self._global_container_stack.propertyChanged.connect(self._onSettingChanged) # Note: Only starts slicing when the value changed.
  456. self._global_container_stack.containersChanged.connect(self._onChanged)
  457. extruders = list(ExtruderManager.getInstance().getMachineExtruders(self._global_container_stack.getId()))
  458. if extruders:
  459. for extruder in extruders:
  460. extruder.propertyChanged.connect(self._onSettingChanged)
  461. self._onActiveExtruderChanged()
  462. self._onChanged()
  463. def _onActiveExtruderChanged(self):
  464. if self._global_container_stack:
  465. # Connect all extruders of the active machine. This might cause a few connects that have already happend,
  466. # but that shouldn't cause issues as only new / unique connections are added.
  467. extruders = list(ExtruderManager.getInstance().getMachineExtruders(self._global_container_stack.getId()))
  468. if extruders:
  469. for extruder in extruders:
  470. extruder.propertyChanged.connect(self._onSettingChanged)
  471. if self._active_extruder_stack:
  472. self._active_extruder_stack.containersChanged.disconnect(self._onChanged)
  473. self._active_extruder_stack = ExtruderManager.getInstance().getActiveExtruderStack()
  474. if self._active_extruder_stack:
  475. self._active_extruder_stack.containersChanged.connect(self._onChanged)
  476. def _onProcessLayersFinished(self, job):
  477. self._process_layers_job = None
  478. ## Connect slice function to timer.
  479. def enableTimer(self):
  480. if not self._use_timer:
  481. self._change_timer.timeout.connect(self.slice)
  482. self._use_timer = True
  483. ## Disconnect slice function from timer.
  484. # This means that slicing will not be triggered automatically
  485. def disableTimer(self):
  486. if self._use_timer:
  487. self._use_timer = False
  488. self._change_timer.timeout.disconnect(self.slice)
  489. def _onPreferencesChanged(self, preference):
  490. if preference != "general/auto_slice":
  491. return
  492. auto_slice = self.determineAutoSlicing()
  493. if auto_slice:
  494. self._change_timer.start()
  495. ## Tickle the backend so in case of auto slicing, it starts the timer.
  496. def tickle(self):
  497. if self._use_timer:
  498. self._change_timer.start()