CuraEngineBackend.py 27 KB

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