CuraEngineBackend.py 30 KB

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