CuraEngineBackend.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611
  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._last_num_objects = 0 # Count number of objects to see if there is something changed
  91. self._postponed_scene_change_sources = [] # scene change is postponed (by a tool)
  92. self.backendQuit.connect(self._onBackendQuit)
  93. self.backendConnected.connect(self._onBackendConnected)
  94. # When a tool operation is in progress, don't slice. So we need to listen for tool operations.
  95. Application.getInstance().getController().toolOperationStarted.connect(self._onToolOperationStarted)
  96. Application.getInstance().getController().toolOperationStopped.connect(self._onToolOperationStopped)
  97. self._slice_start_time = None
  98. Preferences.getInstance().addPreference("general/auto_slice", True)
  99. self._use_timer = False
  100. # When you update a setting and other settings get changed through inheritance, many propertyChanged signals are fired.
  101. # This timer will group them up, and only slice for the last setting changed signal.
  102. # TODO: Properly group propertyChanged signals by whether they are triggered by the same user interaction.
  103. self._change_timer = QTimer()
  104. self._change_timer.setSingleShot(True)
  105. self._change_timer.setInterval(500)
  106. self.determineAutoSlicing()
  107. Preferences.getInstance().preferenceChanged.connect(self._onPreferencesChanged)
  108. ## Terminate the engine process.
  109. #
  110. # This function should terminate the engine process.
  111. # Called when closing the application.
  112. def close(self):
  113. # Terminate CuraEngine if it is still running at this point
  114. self._terminate()
  115. ## Get the command that is used to call the engine.
  116. # This is useful for debugging and used to actually start the engine.
  117. # \return list of commands and args / parameters.
  118. def getEngineCommand(self):
  119. json_path = Resources.getPath(Resources.DefinitionContainers, "fdmprinter.def.json")
  120. return [Preferences.getInstance().getValue("backend/location"), "connect", "127.0.0.1:{0}".format(self._port), "-j", json_path, ""]
  121. ## Emitted when we get a message containing print duration and material amount.
  122. # This also implies the slicing has finished.
  123. # \param time The amount of time the print will take.
  124. # \param material_amount The amount of material the print will use.
  125. printDurationMessage = Signal()
  126. ## Emitted when the slicing process starts.
  127. slicingStarted = Signal()
  128. ## Emitted when the slicing process is aborted forcefully.
  129. slicingCancelled = Signal()
  130. @pyqtSlot()
  131. def stopSlicing(self):
  132. self.backendStateChange.emit(BackendState.NotStarted)
  133. if self._slicing: # We were already slicing. Stop the old job.
  134. self._terminate()
  135. self._createSocket()
  136. if self._process_layers_job: # We were processing layers. Stop that, the layers are going to change soon.
  137. self._process_layers_job.abort()
  138. self._process_layers_job = None
  139. if self._error_message:
  140. self._error_message.hide()
  141. ## Manually triggers a reslice
  142. @pyqtSlot()
  143. def forceSlice(self):
  144. if self._use_timer:
  145. self._change_timer.start()
  146. else:
  147. self.slice()
  148. ## Perform a slice of the scene.
  149. def slice(self):
  150. self._slice_start_time = time()
  151. if not self._need_slicing:
  152. self.processingProgress.emit(1.0)
  153. self.backendStateChange.emit(BackendState.Done)
  154. Logger.log("w", "Slice unnecessary, nothing has changed that needs reslicing.")
  155. return
  156. self.printDurationMessage.emit(0, [0])
  157. self._stored_layer_data = []
  158. self._stored_optimized_layer_data = []
  159. if self._process is None:
  160. self._createSocket()
  161. self.stopSlicing()
  162. self._engine_is_fresh = False # Yes we're going to use the engine
  163. self.processingProgress.emit(0.0)
  164. self.backendStateChange.emit(BackendState.NotStarted)
  165. self._scene.gcode_list = []
  166. self._slicing = True
  167. self.slicingStarted.emit()
  168. slice_message = self._socket.createMessage("cura.proto.Slice")
  169. self._start_slice_job = StartSliceJob.StartSliceJob(slice_message)
  170. self._start_slice_job.start()
  171. self._start_slice_job.finished.connect(self._onStartSliceCompleted)
  172. ## Terminate the engine process.
  173. # Start the engine process by calling _createSocket()
  174. def _terminate(self):
  175. self._slicing = False
  176. self._stored_layer_data = []
  177. self._stored_optimized_layer_data = []
  178. if self._start_slice_job is not None:
  179. self._start_slice_job.cancel()
  180. self.slicingCancelled.emit()
  181. self.processingProgress.emit(0)
  182. Logger.log("d", "Attempting to kill the engine process")
  183. if Application.getInstance().getCommandLineOption("external-backend", False):
  184. return
  185. if self._process is not None:
  186. Logger.log("d", "Killing engine process")
  187. try:
  188. self._process.terminate()
  189. Logger.log("d", "Engine process is killed. Received return code %s", self._process.wait())
  190. self._process = None
  191. except Exception as e: # terminating a process that is already terminating causes an exception, silently ignore this.
  192. Logger.log("d", "Exception occurred while trying to kill the engine %s", str(e))
  193. ## Event handler to call when the job to initiate the slicing process is
  194. # completed.
  195. #
  196. # When the start slice job is successfully completed, it will be happily
  197. # slicing. This function handles any errors that may occur during the
  198. # bootstrapping of a slice job.
  199. #
  200. # \param job The start slice job that was just finished.
  201. def _onStartSliceCompleted(self, job):
  202. if self._error_message:
  203. self._error_message.hide()
  204. # Note that cancelled slice jobs can still call this method.
  205. if self._start_slice_job is job:
  206. self._start_slice_job = None
  207. if job.isCancelled() or job.getError() or job.getResult() == StartSliceJob.StartJobResult.Error:
  208. return
  209. if job.getResult() == StartSliceJob.StartJobResult.MaterialIncompatible:
  210. if Application.getInstance().platformActivity:
  211. self._error_message = Message(catalog.i18nc("@info:status",
  212. "The selected material is incompatible with the selected machine or configuration."))
  213. self._error_message.show()
  214. self.backendStateChange.emit(BackendState.Error)
  215. else:
  216. self.backendStateChange.emit(BackendState.NotStarted)
  217. return
  218. if job.getResult() == StartSliceJob.StartJobResult.SettingError:
  219. if Application.getInstance().platformActivity:
  220. extruders = list(ExtruderManager.getInstance().getMachineExtruders(self._global_container_stack.getId()))
  221. error_keys = []
  222. for extruder in extruders:
  223. error_keys.extend(extruder.getErrorKeys())
  224. if not extruders:
  225. error_keys = self._global_container_stack.getErrorKeys()
  226. error_labels = set()
  227. definition_container = self._global_container_stack.getBottom()
  228. for key in error_keys:
  229. error_labels.add(definition_container.findDefinitions(key = key)[0].label)
  230. error_labels = ", ".join(error_labels)
  231. self._error_message = Message(catalog.i18nc("@info:status", "Unable to slice with the current settings. The following settings have errors: {0}".format(error_labels)))
  232. self._error_message.show()
  233. self.backendStateChange.emit(BackendState.Error)
  234. else:
  235. self.backendStateChange.emit(BackendState.NotStarted)
  236. return
  237. if job.getResult() == StartSliceJob.StartJobResult.BuildPlateError:
  238. if Application.getInstance().platformActivity:
  239. self._error_message = Message(catalog.i18nc("@info:status", "Unable to slice because the prime tower or prime position(s) are invalid."))
  240. self._error_message.show()
  241. self.backendStateChange.emit(BackendState.Error)
  242. else:
  243. self.backendStateChange.emit(BackendState.NotStarted)
  244. if job.getResult() == StartSliceJob.StartJobResult.NothingToSlice:
  245. if Application.getInstance().platformActivity:
  246. 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."))
  247. self._error_message.show()
  248. self.backendStateChange.emit(BackendState.Error)
  249. else:
  250. self.backendStateChange.emit(BackendState.NotStarted)
  251. return
  252. # Preparation completed, send it to the backend.
  253. self._socket.sendMessage(job.getSliceMessage())
  254. # Notify the user that it's now up to the backend to do it's job
  255. self.backendStateChange.emit(BackendState.Processing)
  256. Logger.log("d", "Sending slice message took %s seconds", time() - self._slice_start_time )
  257. ## Determine enable or disable auto slicing. Return True for enable timer and False otherwise.
  258. # It disables when
  259. # - preference auto slice is off
  260. # - decorator isBlockSlicing is found (used in g-code reader)
  261. def determineAutoSlicing(self):
  262. enable_timer = True
  263. if not Preferences.getInstance().getValue("general/auto_slice"):
  264. enable_timer = False
  265. for node in DepthFirstIterator(self._scene.getRoot()):
  266. if node.callDecoration("isBlockSlicing"):
  267. enable_timer = False
  268. self.backendStateChange.emit(BackendState.Disabled)
  269. gcode_list = node.callDecoration("getGCodeList")
  270. if gcode_list is not None:
  271. self._scene.gcode_list = gcode_list
  272. if self._use_timer == enable_timer:
  273. return self._use_timer
  274. if enable_timer:
  275. self.backendStateChange.emit(BackendState.NotStarted)
  276. self.enableTimer()
  277. return True
  278. else:
  279. self.disableTimer()
  280. return False
  281. ## Listener for when the scene has changed.
  282. #
  283. # This should start a slice if the scene is now ready to slice.
  284. #
  285. # \param source The scene node that was changed.
  286. def _onSceneChanged(self, source):
  287. if type(source) is not SceneNode:
  288. return
  289. root_scene_nodes_changed = False
  290. if source == self._scene.getRoot():
  291. num_objects = 0
  292. for node in DepthFirstIterator(self._scene.getRoot()):
  293. # Only count sliceable objects
  294. if node.callDecoration("isSliceable"):
  295. num_objects += 1
  296. if num_objects != self._last_num_objects:
  297. self._last_num_objects = num_objects
  298. root_scene_nodes_changed = True
  299. else:
  300. return
  301. if not source.callDecoration("isGroup") and not root_scene_nodes_changed:
  302. if source.getMeshData() is None:
  303. return
  304. if source.getMeshData().getVertices() is None:
  305. return
  306. if self._tool_active:
  307. # do it later, each source only has to be done once
  308. if source not in self._postponed_scene_change_sources:
  309. self._postponed_scene_change_sources.append(source)
  310. return
  311. self.needsSlicing()
  312. self.stopSlicing()
  313. self._onChanged()
  314. ## Called when an error occurs in the socket connection towards the engine.
  315. #
  316. # \param error The exception that occurred.
  317. def _onSocketError(self, error):
  318. if Application.getInstance().isShuttingDown():
  319. return
  320. super()._onSocketError(error)
  321. if error.getErrorCode() == Arcus.ErrorCode.Debug:
  322. return
  323. self._terminate()
  324. self._createSocket()
  325. if error.getErrorCode() not in [Arcus.ErrorCode.BindFailedError, Arcus.ErrorCode.ConnectionResetError, Arcus.ErrorCode.Debug]:
  326. Logger.log("w", "A socket error caused the connection to be reset")
  327. ## Remove old layer data (if any)
  328. def _clearLayerData(self):
  329. for node in DepthFirstIterator(self._scene.getRoot()):
  330. if node.callDecoration("getLayerData"):
  331. node.getParent().removeChild(node)
  332. break
  333. ## Convenient function: set need_slicing, emit state and clear layer data
  334. def needsSlicing(self):
  335. self._need_slicing = True
  336. self.processingProgress.emit(0.0)
  337. self.backendStateChange.emit(BackendState.NotStarted)
  338. if not self._use_timer:
  339. # With manually having to slice, we want to clear the old invalid layer data.
  340. self._clearLayerData()
  341. ## A setting has changed, so check if we must reslice.
  342. #
  343. # \param instance The setting instance that has changed.
  344. # \param property The property of the setting instance that has changed.
  345. def _onSettingChanged(self, instance, property):
  346. if property == "value": # Only reslice if the value has changed.
  347. self.needsSlicing()
  348. self._onChanged()
  349. ## Called when a sliced layer data message is received from the engine.
  350. #
  351. # \param message The protobuf message containing sliced layer data.
  352. def _onLayerMessage(self, message):
  353. self._stored_layer_data.append(message)
  354. ## Called when an optimized sliced layer data message is received from the engine.
  355. #
  356. # \param message The protobuf message containing sliced layer data.
  357. def _onOptimizedLayerMessage(self, message):
  358. self._stored_optimized_layer_data.append(message)
  359. ## Called when a progress message is received from the engine.
  360. #
  361. # \param message The protobuf message containing the slicing progress.
  362. def _onProgressMessage(self, message):
  363. self.processingProgress.emit(message.amount)
  364. self.backendStateChange.emit(BackendState.Processing)
  365. ## Called when the engine sends a message that slicing is finished.
  366. #
  367. # \param message The protobuf message signalling that slicing is finished.
  368. def _onSlicingFinishedMessage(self, message):
  369. self.backendStateChange.emit(BackendState.Done)
  370. self.processingProgress.emit(1.0)
  371. self._slicing = False
  372. self._need_slicing = False
  373. Logger.log("d", "Slicing took %s seconds", time() - self._slice_start_time )
  374. if self._layer_view_active and (self._process_layers_job is None or not self._process_layers_job.isRunning()):
  375. self._process_layers_job = ProcessSlicedLayersJob.ProcessSlicedLayersJob(self._stored_optimized_layer_data)
  376. self._process_layers_job.finished.connect(self._onProcessLayersFinished)
  377. self._process_layers_job.start()
  378. self._stored_optimized_layer_data = []
  379. ## Called when a g-code message is received from the engine.
  380. #
  381. # \param message The protobuf message containing g-code, encoded as UTF-8.
  382. def _onGCodeLayerMessage(self, message):
  383. self._scene.gcode_list.append(message.data.decode("utf-8", "replace"))
  384. ## Called when a g-code prefix message is received from the engine.
  385. #
  386. # \param message The protobuf message containing the g-code prefix,
  387. # encoded as UTF-8.
  388. def _onGCodePrefixMessage(self, message):
  389. self._scene.gcode_list.insert(0, message.data.decode("utf-8", "replace"))
  390. ## Called when a print time message is received from the engine.
  391. #
  392. # \param message The protobuff message containing the print time and
  393. # material amount per extruder
  394. def _onPrintTimeMaterialEstimates(self, message):
  395. material_amounts = []
  396. for index in range(message.repeatedMessageCount("materialEstimates")):
  397. material_amounts.append(message.getRepeatedMessage("materialEstimates", index).material_amount)
  398. self.printDurationMessage.emit(message.time, material_amounts)
  399. ## Creates a new socket connection.
  400. def _createSocket(self):
  401. super()._createSocket(os.path.abspath(os.path.join(PluginRegistry.getInstance().getPluginPath(self.getPluginId()), "Cura.proto")))
  402. self._engine_is_fresh = True
  403. ## Called when anything has changed to the stuff that needs to be sliced.
  404. #
  405. # This indicates that we should probably re-slice soon.
  406. def _onChanged(self, *args, **kwargs):
  407. self.needsSlicing()
  408. if self._use_timer:
  409. self._change_timer.start()
  410. ## Called when the back-end connects to the front-end.
  411. def _onBackendConnected(self):
  412. if self._restart:
  413. self._restart = False
  414. self._onChanged()
  415. ## Called when the user starts using some tool.
  416. #
  417. # When the user starts using a tool, we should pause slicing to prevent
  418. # continuously slicing while the user is dragging some tool handle.
  419. #
  420. # \param tool The tool that the user is using.
  421. def _onToolOperationStarted(self, tool):
  422. self._tool_active = True # Do not react on scene change
  423. self.disableTimer()
  424. # Restart engine as soon as possible, we know we want to slice afterwards
  425. if not self._engine_is_fresh:
  426. self._terminate()
  427. self._createSocket()
  428. ## Called when the user stops using some tool.
  429. #
  430. # This indicates that we can safely start slicing again.
  431. #
  432. # \param tool The tool that the user was using.
  433. def _onToolOperationStopped(self, tool):
  434. self._tool_active = False # React on scene change again
  435. self.determineAutoSlicing() # Switch timer on if appropriate
  436. # Process all the postponed scene changes
  437. while self._postponed_scene_change_sources:
  438. source = self._postponed_scene_change_sources.pop(0)
  439. self._onSceneChanged(source)
  440. ## Called when the user changes the active view mode.
  441. def _onActiveViewChanged(self):
  442. if Application.getInstance().getController().getActiveView():
  443. view = Application.getInstance().getController().getActiveView()
  444. if view.getPluginId() == "LayerView": # If switching to layer view, we should process the layers if that hasn't been done yet.
  445. self._layer_view_active = True
  446. # There is data and we're not slicing at the moment
  447. # if we are slicing, there is no need to re-calculate the data as it will be invalid in a moment.
  448. if self._stored_optimized_layer_data and not self._slicing:
  449. self._process_layers_job = ProcessSlicedLayersJob.ProcessSlicedLayersJob(self._stored_optimized_layer_data)
  450. self._process_layers_job.finished.connect(self._onProcessLayersFinished)
  451. self._process_layers_job.start()
  452. self._stored_optimized_layer_data = []
  453. else:
  454. self._layer_view_active = False
  455. ## Called when the back-end self-terminates.
  456. #
  457. # We should reset our state and start listening for new connections.
  458. def _onBackendQuit(self):
  459. if not self._restart:
  460. if self._process:
  461. Logger.log("d", "Backend quit with return code %s. Resetting process and socket.", self._process.wait())
  462. self._process = None
  463. ## Called when the global container stack changes
  464. def _onGlobalStackChanged(self):
  465. if self._global_container_stack:
  466. self._global_container_stack.propertyChanged.disconnect(self._onSettingChanged)
  467. self._global_container_stack.containersChanged.disconnect(self._onChanged)
  468. extruders = list(ExtruderManager.getInstance().getMachineExtruders(self._global_container_stack.getId()))
  469. if extruders:
  470. for extruder in extruders:
  471. extruder.propertyChanged.disconnect(self._onSettingChanged)
  472. self._global_container_stack = Application.getInstance().getGlobalContainerStack()
  473. if self._global_container_stack:
  474. self._global_container_stack.propertyChanged.connect(self._onSettingChanged) # Note: Only starts slicing when the value changed.
  475. self._global_container_stack.containersChanged.connect(self._onChanged)
  476. extruders = list(ExtruderManager.getInstance().getMachineExtruders(self._global_container_stack.getId()))
  477. if extruders:
  478. for extruder in extruders:
  479. extruder.propertyChanged.connect(self._onSettingChanged)
  480. self._onActiveExtruderChanged()
  481. self._onChanged()
  482. def _onActiveExtruderChanged(self):
  483. if self._global_container_stack:
  484. # Connect all extruders of the active machine. This might cause a few connects that have already happend,
  485. # but that shouldn't cause issues as only new / unique connections are added.
  486. extruders = list(ExtruderManager.getInstance().getMachineExtruders(self._global_container_stack.getId()))
  487. if extruders:
  488. for extruder in extruders:
  489. extruder.propertyChanged.connect(self._onSettingChanged)
  490. if self._active_extruder_stack:
  491. self._active_extruder_stack.containersChanged.disconnect(self._onChanged)
  492. self._active_extruder_stack = ExtruderManager.getInstance().getActiveExtruderStack()
  493. if self._active_extruder_stack:
  494. self._active_extruder_stack.containersChanged.connect(self._onChanged)
  495. def _onProcessLayersFinished(self, job):
  496. self._process_layers_job = None
  497. ## Connect slice function to timer.
  498. def enableTimer(self):
  499. if not self._use_timer:
  500. self._change_timer.timeout.connect(self.slice)
  501. self._use_timer = True
  502. ## Disconnect slice function from timer.
  503. # This means that slicing will not be triggered automatically
  504. def disableTimer(self):
  505. if self._use_timer:
  506. self._use_timer = False
  507. self._change_timer.timeout.disconnect(self.slice)
  508. def _onPreferencesChanged(self, preference):
  509. if preference != "general/auto_slice":
  510. return
  511. auto_slice = self.determineAutoSlicing()
  512. if auto_slice:
  513. self._change_timer.start()
  514. ## Tickle the backend so in case of auto slicing, it starts the timer.
  515. def tickle(self):
  516. if self._use_timer:
  517. self._change_timer.start()