Fix code-style in CuraEngineBackend

This commit is contained in:
Diego Prado Gesto 2018-07-05 08:04:19 +02:00
parent efb9fcb645
commit 7d7a51d772
2 changed files with 46 additions and 33 deletions

View File

@ -3,6 +3,8 @@
from collections import defaultdict from collections import defaultdict
import os import os
from typing import Union
from PyQt5.QtCore import QObject, QTimer, pyqtSlot from PyQt5.QtCore import QObject, QTimer, pyqtSlot
import sys import sys
from time import time from time import time
@ -60,17 +62,16 @@ class CuraEngineBackend(QObject, Backend):
if hasattr(sys, "frozen"): if hasattr(sys, "frozen"):
default_engine_location = os.path.join(os.path.dirname(os.path.abspath(sys.executable)), executable_name) default_engine_location = os.path.join(os.path.dirname(os.path.abspath(sys.executable)), executable_name)
if Platform.isLinux() and not default_engine_location: if Platform.isLinux() and not default_engine_location:
if not os.getenv("PATH"): env_path = os.getenv("PATH")
if not env_path:
raise OSError("There is something wrong with your Linux installation.") raise OSError("There is something wrong with your Linux installation.")
for pathdir in os.getenv("PATH").split(os.pathsep): for pathdir in env_path.split(os.pathsep):
execpath = os.path.join(pathdir, executable_name) execpath = os.path.join(pathdir, executable_name)
if os.path.exists(execpath): if os.path.exists(execpath):
default_engine_location = execpath default_engine_location = execpath
break break
self._application = CuraApplication.getInstance() #type: CuraApplication self._application = CuraApplication.getInstance() #type: CuraApplication
self._multi_build_plate_model = None #type: MultiBuildPlateModel
self._machine_error_checker = None #type: MachineErrorChecker
if not default_engine_location: if not default_engine_location:
raise EnvironmentError("Could not find CuraEngine") raise EnvironmentError("Could not find CuraEngine")
@ -120,11 +121,11 @@ class CuraEngineBackend(QObject, Backend):
self._engine_is_fresh = True #type: bool # Is the newly started engine used before or not? self._engine_is_fresh = True #type: bool # Is the newly started engine used before or not?
self._backend_log_max_lines = 20000 #type: int # Maximum number of lines to buffer self._backend_log_max_lines = 20000 #type: int # Maximum number of lines to buffer
self._error_message = None #type: Message # Pop-up message that shows errors. self._error_message = None #type: Optional[Message] # Pop-up message that shows errors.
self._last_num_objects = defaultdict(int) #type: Dict[int, int] # Count number of objects to see if there is something changed self._last_num_objects = defaultdict(int) #type: Dict[int, int] # Count number of objects to see if there is something changed
self._postponed_scene_change_sources = [] #type: List[SceneNode] # scene change is postponed (by a tool) self._postponed_scene_change_sources = [] #type: List[SceneNode] # scene change is postponed (by a tool)
self._slice_start_time = None #type: Optional[float] self._slice_start_time = time() #type: float
self._is_disabled = False #type: bool self._is_disabled = False #type: bool
self._application.getPreferences().addPreference("general/auto_slice", False) self._application.getPreferences().addPreference("general/auto_slice", False)
@ -142,8 +143,7 @@ class CuraEngineBackend(QObject, Backend):
self._application.initializationFinished.connect(self.initialize) self._application.initializationFinished.connect(self.initialize)
def initialize(self) -> None: def initialize(self) -> None:
self._multi_build_plate_model = self._application.getMultiBuildPlateModel() self._multi_build_plate_model = self._application.getMultiBuildPlateModel() #type: MultiBuildPlateModel
self._application.getController().activeViewChanged.connect(self._onActiveViewChanged) self._application.getController().activeViewChanged.connect(self._onActiveViewChanged)
self._multi_build_plate_model.activeBuildPlateChanged.connect(self._onActiveViewChanged) self._multi_build_plate_model.activeBuildPlateChanged.connect(self._onActiveViewChanged)
@ -160,7 +160,7 @@ class CuraEngineBackend(QObject, Backend):
self._application.getController().toolOperationStarted.connect(self._onToolOperationStarted) self._application.getController().toolOperationStarted.connect(self._onToolOperationStarted)
self._application.getController().toolOperationStopped.connect(self._onToolOperationStopped) self._application.getController().toolOperationStopped.connect(self._onToolOperationStopped)
self._machine_error_checker = self._application.getMachineErrorChecker() self._machine_error_checker = self._application.getMachineErrorChecker() #type: MachineErrorChecker
self._machine_error_checker.errorCheckFinished.connect(self._onStackErrorCheckFinished) self._machine_error_checker.errorCheckFinished.connect(self._onStackErrorCheckFinished)
## Terminate the engine process. ## Terminate the engine process.
@ -310,6 +310,11 @@ class CuraEngineBackend(QObject, Backend):
if self._start_slice_job is job: if self._start_slice_job is job:
self._start_slice_job = None self._start_slice_job = None
if not self._global_container_stack:
self.backendStateChange.emit(BackendState.Error)
self.backendError.emit(job)
return
if job.isCancelled() or job.getError() or job.getResult() == StartJobResult.Error: if job.isCancelled() or job.getError() or job.getResult() == StartJobResult.Error:
self.backendStateChange.emit(BackendState.Error) self.backendStateChange.emit(BackendState.Error)
self.backendError.emit(job) self.backendError.emit(job)
@ -447,7 +452,8 @@ class CuraEngineBackend(QObject, Backend):
# Only count sliceable objects # Only count sliceable objects
if node.callDecoration("isSliceable"): if node.callDecoration("isSliceable"):
build_plate_number = node.callDecoration("getBuildPlateNumber") build_plate_number = node.callDecoration("getBuildPlateNumber")
num_objects[build_plate_number] += 1 if build_plate_number is not None:
num_objects[build_plate_number] += 1
return num_objects return num_objects
## Listener for when the scene has changed. ## Listener for when the scene has changed.
@ -464,7 +470,7 @@ class CuraEngineBackend(QObject, Backend):
if source.callDecoration("isBlockSlicing") and source.callDecoration("getLayerData"): if source.callDecoration("isBlockSlicing") and source.callDecoration("getLayerData"):
self._stored_optimized_layer_data = {} self._stored_optimized_layer_data = {}
build_plate_changed = set() build_plate_changed = set() # type: Set[int]
source_build_plate_number = source.callDecoration("getBuildPlateNumber") source_build_plate_number = source.callDecoration("getBuildPlateNumber")
if source == self._scene.getRoot(): if source == self._scene.getRoot():
# we got the root node # we got the root node
@ -476,14 +482,15 @@ class CuraEngineBackend(QObject, Backend):
else: else:
# we got a single scenenode # we got a single scenenode
if not source.callDecoration("isGroup"): if not source.callDecoration("isGroup"):
if source.getMeshData() is None: mesh_data = source.getMeshData()
if mesh_data is None:
return return
if source.getMeshData().getVertices() is None: elif mesh_data.getVertices() is None:
return return
build_plate_changed.add(source_build_plate_number) if source_build_plate_number is not None:
build_plate_changed.add(source_build_plate_number)
build_plate_changed.discard(None)
build_plate_changed.discard(-1) # object not on build plate build_plate_changed.discard(-1) # object not on build plate
if not build_plate_changed: if not build_plate_changed:
return return
@ -577,9 +584,10 @@ class CuraEngineBackend(QObject, Backend):
# #
# \param message The protobuf message containing sliced layer data. # \param message The protobuf message containing sliced layer data.
def _onOptimizedLayerMessage(self, message: Arcus.PythonMessage) -> None: def _onOptimizedLayerMessage(self, message: Arcus.PythonMessage) -> None:
if self._start_slice_job_build_plate not in self._stored_optimized_layer_data: if self._start_slice_job_build_plate is not None:
self._stored_optimized_layer_data[self._start_slice_job_build_plate] = [] if self._start_slice_job_build_plate not in self._stored_optimized_layer_data:
self._stored_optimized_layer_data[self._start_slice_job_build_plate].append(message) self._stored_optimized_layer_data[self._start_slice_job_build_plate] = []
self._stored_optimized_layer_data[self._start_slice_job_build_plate].append(message)
## Called when a progress message is received from the engine. ## Called when a progress message is received from the engine.
# #
@ -658,7 +666,10 @@ class CuraEngineBackend(QObject, Backend):
## Creates a new socket connection. ## Creates a new socket connection.
def _createSocket(self, protocol_file: str = None) -> None: def _createSocket(self, protocol_file: str = None) -> None:
if not protocol_file: if not protocol_file:
protocol_file = os.path.abspath(os.path.join(PluginRegistry.getInstance().getPluginPath(self.getPluginId()), "Cura.proto")) plugin_path = PluginRegistry.getInstance().getPluginPath(self.getPluginId())
if not plugin_path:
return
protocol_file = os.path.abspath(os.path.join(plugin_path, "Cura.proto"))
super()._createSocket(protocol_file) super()._createSocket(protocol_file)
self._engine_is_fresh = True self._engine_is_fresh = True

View File

@ -114,13 +114,14 @@ class StartSliceJob(Job):
self.setResult(StartJobResult.Error) self.setResult(StartJobResult.Error)
return return
stack = CuraApplication.getInstance().getGlobalContainerStack() global_stack = CuraApplication.getInstance().getGlobalContainerStack()
if not stack: machine_manager = CuraApplication.getInstance().getMachineManager()
if not global_stack:
self.setResult(StartJobResult.Error) self.setResult(StartJobResult.Error)
return return
# Don't slice if there is a setting with an error value. # Don't slice if there is a setting with an error value.
if CuraApplication.getInstance().getMachineManager().stacksHaveErrors: if machine_manager.stacksHaveErrors:
self.setResult(StartJobResult.SettingError) self.setResult(StartJobResult.SettingError)
return return
@ -129,12 +130,12 @@ class StartSliceJob(Job):
return return
# Don't slice if the buildplate or the nozzle type is incompatible with the materials # Don't slice if the buildplate or the nozzle type is incompatible with the materials
if not CuraApplication.getInstance().getMachineManager().variantBuildplateCompatible and \ if not machine_manager.variantBuildplateCompatible and \
not CuraApplication.getInstance().getMachineManager().variantBuildplateUsable: not machine_manager.variantBuildplateUsable:
self.setResult(StartJobResult.MaterialIncompatible) self.setResult(StartJobResult.MaterialIncompatible)
return return
for position, extruder_stack in stack.extruders.items(): for position, extruder_stack in global_stack.extruders.items():
material = extruder_stack.findContainer({"type": "material"}) material = extruder_stack.findContainer({"type": "material"})
if not extruder_stack.isEnabled: if not extruder_stack.isEnabled:
continue continue
@ -162,7 +163,7 @@ class StartSliceJob(Job):
# Get the objects in their groups to print. # Get the objects in their groups to print.
object_groups = [] object_groups = []
if stack.getProperty("print_sequence", "value") == "one_at_a_time": if global_stack.getProperty("print_sequence", "value") == "one_at_a_time":
for node in OneAtATimeIterator(self._scene.getRoot()): #type: ignore #Ignore type error because iter() should get called automatically by Python syntax. for node in OneAtATimeIterator(self._scene.getRoot()): #type: ignore #Ignore type error because iter() should get called automatically by Python syntax.
temp_list = [] temp_list = []
@ -216,12 +217,11 @@ class StartSliceJob(Job):
if temp_list: if temp_list:
object_groups.append(temp_list) object_groups.append(temp_list)
extruders_enabled = {position: stack.isEnabled for position, stack in CuraApplication.getInstance().getGlobalContainerStack().extruders.items()} extruders_enabled = {position: stack.isEnabled for position, stack in global_stack.extruders.items()}
filtered_object_groups = [] filtered_object_groups = []
has_model_with_disabled_extruders = False has_model_with_disabled_extruders = False
associated_disabled_extruders = set() associated_disabled_extruders = set() # type: Set[str]
for group in object_groups: for group in object_groups:
stack = CuraApplication.getInstance().getGlobalContainerStack()
skip_group = False skip_group = False
for node in group: for node in group:
extruder_position = node.callDecoration("getActiveExtruderPosition") extruder_position = node.callDecoration("getActiveExtruderPosition")
@ -234,7 +234,7 @@ class StartSliceJob(Job):
if has_model_with_disabled_extruders: if has_model_with_disabled_extruders:
self.setResult(StartJobResult.ObjectsWithDisabledExtruder) self.setResult(StartJobResult.ObjectsWithDisabledExtruder)
associated_disabled_extruders = [str(c) for c in sorted([int(p) + 1 for p in associated_disabled_extruders])] associated_disabled_extruders = set([str(c) for c in sorted([int(p) + 1 for p in associated_disabled_extruders])])
self.setMessage(", ".join(associated_disabled_extruders)) self.setMessage(", ".join(associated_disabled_extruders))
return return
@ -245,11 +245,11 @@ class StartSliceJob(Job):
self.setResult(StartJobResult.NothingToSlice) self.setResult(StartJobResult.NothingToSlice)
return return
self._buildGlobalSettingsMessage(stack) self._buildGlobalSettingsMessage(global_stack)
self._buildGlobalInheritsStackMessage(stack) self._buildGlobalInheritsStackMessage(global_stack)
# Build messages for extruder stacks # Build messages for extruder stacks
for extruder_stack in ExtruderManager.getInstance().getMachineExtruders(stack.getId()): for extruder_stack in ExtruderManager.getInstance().getMachineExtruders(global_stack.getId()):
self._buildExtruderMessage(extruder_stack) self._buildExtruderMessage(extruder_stack)
for group in filtered_object_groups: for group in filtered_object_groups:
@ -326,6 +326,8 @@ class StartSliceJob(Job):
def _expandGcodeTokens(self, value: str, default_extruder_nr: int = -1) -> str: def _expandGcodeTokens(self, value: str, default_extruder_nr: int = -1) -> str:
if not self._all_extruders_settings: if not self._all_extruders_settings:
global_stack = CuraApplication.getInstance().getGlobalContainerStack() global_stack = CuraApplication.getInstance().getGlobalContainerStack()
if not global_stack:
return str(value)
# NB: keys must be strings for the string formatter # NB: keys must be strings for the string formatter
self._all_extruders_settings = { self._all_extruders_settings = {