CuraEngineBackend.py 30 KB

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