CuraApplication.py 78 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703
  1. # Copyright (c) 2018 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. import copy
  4. import os
  5. import sys
  6. import time
  7. import numpy
  8. from PyQt5.QtCore import QObject, QTimer, QUrl, pyqtSignal, pyqtProperty, QEvent, Q_ENUMS
  9. from PyQt5.QtGui import QColor, QIcon
  10. from PyQt5.QtWidgets import QMessageBox
  11. from PyQt5.QtQml import qmlRegisterUncreatableType, qmlRegisterSingletonType, qmlRegisterType
  12. from typing import cast, TYPE_CHECKING
  13. from UM.Scene.SceneNode import SceneNode
  14. from UM.Scene.Camera import Camera
  15. from UM.Math.Vector import Vector
  16. from UM.Math.Quaternion import Quaternion
  17. from UM.Math.AxisAlignedBox import AxisAlignedBox
  18. from UM.Math.Matrix import Matrix
  19. from UM.Platform import Platform
  20. from UM.Resources import Resources
  21. from UM.Scene.ToolHandle import ToolHandle
  22. from UM.Scene.Iterator.DepthFirstIterator import DepthFirstIterator
  23. from UM.Mesh.ReadMeshJob import ReadMeshJob
  24. from UM.Logger import Logger
  25. from UM.Preferences import Preferences
  26. from UM.Qt.QtApplication import QtApplication #The class we're inheriting from.
  27. from UM.View.SelectionPass import SelectionPass #For typing.
  28. from UM.Scene.Selection import Selection
  29. from UM.Scene.GroupDecorator import GroupDecorator
  30. from UM.Settings.ContainerStack import ContainerStack
  31. from UM.Settings.InstanceContainer import InstanceContainer
  32. from UM.Settings.Validator import Validator
  33. from UM.Message import Message
  34. from UM.i18n import i18nCatalog
  35. from UM.Workspace.WorkspaceReader import WorkspaceReader
  36. from UM.Decorators import deprecated
  37. from UM.Operations.AddSceneNodeOperation import AddSceneNodeOperation
  38. from UM.Operations.RemoveSceneNodeOperation import RemoveSceneNodeOperation
  39. from UM.Operations.GroupedOperation import GroupedOperation
  40. from UM.Operations.SetTransformOperation import SetTransformOperation
  41. from cura.Arranging.Arrange import Arrange
  42. from cura.Arranging.ArrangeObjectsJob import ArrangeObjectsJob
  43. from cura.Arranging.ArrangeObjectsAllBuildPlatesJob import ArrangeObjectsAllBuildPlatesJob
  44. from cura.Arranging.ShapeArray import ShapeArray
  45. from cura.MultiplyObjectsJob import MultiplyObjectsJob
  46. from cura.Scene.ConvexHullDecorator import ConvexHullDecorator
  47. from cura.Operations.SetParentOperation import SetParentOperation
  48. from cura.Scene.SliceableObjectDecorator import SliceableObjectDecorator
  49. from cura.Scene.BlockSlicingDecorator import BlockSlicingDecorator
  50. from cura.Scene.BuildPlateDecorator import BuildPlateDecorator
  51. from cura.Scene.CuraSceneNode import CuraSceneNode
  52. from cura.Scene.CuraSceneController import CuraSceneController
  53. from UM.Settings.SettingDefinition import SettingDefinition, DefinitionPropertyType
  54. from UM.Settings.ContainerRegistry import ContainerRegistry
  55. from UM.Settings.SettingFunction import SettingFunction
  56. from cura.Settings.MachineNameValidator import MachineNameValidator
  57. from cura.Machines.Models.BuildPlateModel import BuildPlateModel
  58. from cura.Machines.Models.NozzleModel import NozzleModel
  59. from cura.Machines.Models.QualityProfilesDropDownMenuModel import QualityProfilesDropDownMenuModel
  60. from cura.Machines.Models.CustomQualityProfilesDropDownMenuModel import CustomQualityProfilesDropDownMenuModel
  61. from cura.Machines.Models.MultiBuildPlateModel import MultiBuildPlateModel
  62. from cura.Machines.Models.MaterialManagementModel import MaterialManagementModel
  63. from cura.Machines.Models.GenericMaterialsModel import GenericMaterialsModel
  64. from cura.Machines.Models.BrandMaterialsModel import BrandMaterialsModel
  65. from cura.Machines.Models.QualityManagementModel import QualityManagementModel
  66. from cura.Machines.Models.QualitySettingsModel import QualitySettingsModel
  67. from cura.Machines.Models.MachineManagementModel import MachineManagementModel
  68. from cura.Machines.Models.SettingVisibilityPresetsModel import SettingVisibilityPresetsModel
  69. from cura.Machines.MachineErrorChecker import MachineErrorChecker
  70. from cura.Settings.SettingInheritanceManager import SettingInheritanceManager
  71. from cura.Settings.SimpleModeSettingsManager import SimpleModeSettingsManager
  72. from cura.Machines.VariantManager import VariantManager
  73. from .SingleInstance import SingleInstance
  74. from .AutoSave import AutoSave
  75. from . import PlatformPhysics
  76. from . import BuildVolume
  77. from . import CameraAnimation
  78. from . import PrintInformation
  79. from . import CuraActions
  80. from cura.Scene import ZOffsetDecorator
  81. from . import CuraSplashScreen
  82. from . import CameraImageProvider
  83. from . import MachineActionManager
  84. from cura.Settings.MachineManager import MachineManager
  85. from cura.Settings.ExtruderManager import ExtruderManager
  86. from cura.Settings.UserChangesModel import UserChangesModel
  87. from cura.Settings.ExtrudersModel import ExtrudersModel
  88. from cura.Settings.MaterialSettingsVisibilityHandler import MaterialSettingsVisibilityHandler
  89. from cura.Settings.ContainerManager import ContainerManager
  90. from cura.ObjectsModel import ObjectsModel
  91. from UM.FlameProfiler import pyqtSlot
  92. if TYPE_CHECKING:
  93. from plugins.SliceInfoPlugin.SliceInfo import SliceInfo
  94. numpy.seterr(all = "ignore")
  95. try:
  96. from cura.CuraVersion import CuraVersion, CuraBuildType, CuraDebugMode
  97. except ImportError:
  98. CuraVersion = "master" # [CodeStyle: Reflecting imported value]
  99. CuraBuildType = ""
  100. CuraDebugMode = False
  101. class CuraApplication(QtApplication):
  102. # SettingVersion represents the set of settings available in the machine/extruder definitions.
  103. # You need to make sure that this version number needs to be increased if there is any non-backwards-compatible
  104. # changes of the settings.
  105. SettingVersion = 5
  106. Created = False
  107. class ResourceTypes:
  108. QmlFiles = Resources.UserType + 1
  109. Firmware = Resources.UserType + 2
  110. QualityInstanceContainer = Resources.UserType + 3
  111. QualityChangesInstanceContainer = Resources.UserType + 4
  112. MaterialInstanceContainer = Resources.UserType + 5
  113. VariantInstanceContainer = Resources.UserType + 6
  114. UserInstanceContainer = Resources.UserType + 7
  115. MachineStack = Resources.UserType + 8
  116. ExtruderStack = Resources.UserType + 9
  117. DefinitionChangesContainer = Resources.UserType + 10
  118. SettingVisibilityPreset = Resources.UserType + 11
  119. Q_ENUMS(ResourceTypes)
  120. def __init__(self, *args, **kwargs):
  121. super().__init__(name = "cura",
  122. version = CuraVersion,
  123. buildtype = CuraBuildType,
  124. is_debug_mode = CuraDebugMode,
  125. tray_icon_name = "cura-icon-32.png",
  126. **kwargs)
  127. self.default_theme = "cura-light"
  128. self._boot_loading_time = time.time()
  129. # Variables set from CLI
  130. self._files_to_open = []
  131. self._use_single_instance = False
  132. self._trigger_early_crash = False # For debug only
  133. self._single_instance = None
  134. self._cura_package_manager = None
  135. self._machine_action_manager = None
  136. self.empty_container = None
  137. self.empty_definition_changes_container = None
  138. self.empty_variant_container = None
  139. self.empty_material_container = None
  140. self.empty_quality_container = None
  141. self.empty_quality_changes_container = None
  142. self._variant_manager = None
  143. self._material_manager = None
  144. self._quality_manager = None
  145. self._machine_manager = None
  146. self._extruder_manager = None
  147. self._container_manager = None
  148. self._object_manager = None
  149. self._build_plate_model = None
  150. self._multi_build_plate_model = None
  151. self._setting_visibility_presets_model = None
  152. self._setting_inheritance_manager = None
  153. self._simple_mode_settings_manager = None
  154. self._cura_scene_controller = None
  155. self._machine_error_checker = None
  156. self._quality_profile_drop_down_menu_model = None
  157. self._custom_quality_profile_drop_down_menu_model = None
  158. self._physics = None
  159. self._volume = None
  160. self._output_devices = {}
  161. self._print_information = None
  162. self._previous_active_tool = None
  163. self._platform_activity = False
  164. self._scene_bounding_box = AxisAlignedBox.Null
  165. self._center_after_select = False
  166. self._camera_animation = None
  167. self._cura_actions = None
  168. self.started = False
  169. self._message_box_callback = None
  170. self._message_box_callback_arguments = []
  171. self._preferred_mimetype = ""
  172. self._i18n_catalog = None
  173. self._currently_loading_files = []
  174. self._non_sliceable_extensions = []
  175. self._additional_components = {} # Components to add to certain areas in the interface
  176. self._open_file_queue = [] # A list of files to open (after the application has started)
  177. self._update_platform_activity_timer = None
  178. self._need_to_show_user_agreement = True
  179. # Backups
  180. self._auto_save = None
  181. self._save_data_enabled = True
  182. from cura.Settings.CuraContainerRegistry import CuraContainerRegistry
  183. self._container_registry_class = CuraContainerRegistry
  184. from cura.CuraPackageManager import CuraPackageManager
  185. self._package_manager_class = CuraPackageManager
  186. # Adds command line options to the command line parser. This should be called after the application is created and
  187. # before the pre-start.
  188. def addCommandLineOptions(self):
  189. super().addCommandLineOptions()
  190. self._cli_parser.add_argument("--help", "-h",
  191. action = "store_true",
  192. default = False,
  193. help = "Show this help message and exit.")
  194. self._cli_parser.add_argument("--single-instance",
  195. dest = "single_instance",
  196. action = "store_true",
  197. default = False)
  198. # >> For debugging
  199. # Trigger an early crash, i.e. a crash that happens before the application enters its event loop.
  200. self._cli_parser.add_argument("--trigger-early-crash",
  201. dest = "trigger_early_crash",
  202. action = "store_true",
  203. default = False,
  204. help = "FOR TESTING ONLY. Trigger an early crash to show the crash dialog.")
  205. self._cli_parser.add_argument("file", nargs = "*", help = "Files to load after starting the application.")
  206. def parseCliOptions(self):
  207. super().parseCliOptions()
  208. if self._cli_args.help:
  209. self._cli_parser.print_help()
  210. sys.exit(0)
  211. self._use_single_instance = self._cli_args.single_instance
  212. self._trigger_early_crash = self._cli_args.trigger_early_crash
  213. for filename in self._cli_args.file:
  214. self._files_to_open.append(os.path.abspath(filename))
  215. def initialize(self) -> None:
  216. self.__addExpectedResourceDirsAndSearchPaths() # Must be added before init of super
  217. super().initialize()
  218. self.__sendCommandToSingleInstance()
  219. self.__initializeSettingDefinitionsAndFunctions()
  220. self.__addAllResourcesAndContainerResources()
  221. self.__addAllEmptyContainers()
  222. self.__setLatestResouceVersionsForVersionUpgrade()
  223. self._machine_action_manager = MachineActionManager.MachineActionManager(self)
  224. self._machine_action_manager.initialize()
  225. def __sendCommandToSingleInstance(self):
  226. self._single_instance = SingleInstance(self, self._files_to_open)
  227. # If we use single instance, try to connect to the single instance server, send commands, and then exit.
  228. # If we cannot find an existing single instance server, this is the only instance, so just keep going.
  229. if self._use_single_instance:
  230. if self._single_instance.startClient():
  231. Logger.log("i", "Single instance commands were sent, exiting")
  232. sys.exit(0)
  233. # Adds expected directory names and search paths for Resources.
  234. def __addExpectedResourceDirsAndSearchPaths(self):
  235. # this list of dir names will be used by UM to detect an old cura directory
  236. for dir_name in ["extruders", "machine_instances", "materials", "plugins", "quality", "quality_changes", "user", "variants"]:
  237. Resources.addExpectedDirNameInData(dir_name)
  238. Resources.addSearchPath(os.path.join(self._app_install_dir, "share", "cura", "resources"))
  239. if not hasattr(sys, "frozen"):
  240. resource_path = os.path.join(os.path.abspath(os.path.dirname(__file__)), "..", "resources")
  241. Resources.addSearchPath(resource_path)
  242. # Adds custom property types, settings types, and extra operators (functions) that need to be registered in
  243. # SettingDefinition and SettingFunction.
  244. def __initializeSettingDefinitionsAndFunctions(self):
  245. # Need to do this before ContainerRegistry tries to load the machines
  246. SettingDefinition.addSupportedProperty("settable_per_mesh", DefinitionPropertyType.Any, default = True, read_only = True)
  247. SettingDefinition.addSupportedProperty("settable_per_extruder", DefinitionPropertyType.Any, default = True, read_only = True)
  248. # this setting can be changed for each group in one-at-a-time mode
  249. SettingDefinition.addSupportedProperty("settable_per_meshgroup", DefinitionPropertyType.Any, default = True, read_only = True)
  250. SettingDefinition.addSupportedProperty("settable_globally", DefinitionPropertyType.Any, default = True, read_only = True)
  251. # From which stack the setting would inherit if not defined per object (handled in the engine)
  252. # AND for settings which are not settable_per_mesh:
  253. # which extruder is the only extruder this setting is obtained from
  254. SettingDefinition.addSupportedProperty("limit_to_extruder", DefinitionPropertyType.Function, default = "-1", depends_on = "value")
  255. # For settings which are not settable_per_mesh and not settable_per_extruder:
  256. # A function which determines the glabel/meshgroup value by looking at the values of the setting in all (used) extruders
  257. SettingDefinition.addSupportedProperty("resolve", DefinitionPropertyType.Function, default = None, depends_on = "value")
  258. SettingDefinition.addSettingType("extruder", None, str, Validator)
  259. SettingDefinition.addSettingType("optional_extruder", None, str, None)
  260. SettingDefinition.addSettingType("[int]", None, str, None)
  261. SettingFunction.registerOperator("extruderValues", ExtruderManager.getExtruderValues)
  262. SettingFunction.registerOperator("extruderValue", ExtruderManager.getExtruderValue)
  263. SettingFunction.registerOperator("resolveOrValue", ExtruderManager.getResolveOrValue)
  264. SettingFunction.registerOperator("defaultExtruderPosition", ExtruderManager.getDefaultExtruderPosition)
  265. # Adds all resources and container related resources.
  266. def __addAllResourcesAndContainerResources(self) -> None:
  267. Resources.addStorageType(self.ResourceTypes.QualityInstanceContainer, "quality")
  268. Resources.addStorageType(self.ResourceTypes.QualityChangesInstanceContainer, "quality_changes")
  269. Resources.addStorageType(self.ResourceTypes.VariantInstanceContainer, "variants")
  270. Resources.addStorageType(self.ResourceTypes.MaterialInstanceContainer, "materials")
  271. Resources.addStorageType(self.ResourceTypes.UserInstanceContainer, "user")
  272. Resources.addStorageType(self.ResourceTypes.ExtruderStack, "extruders")
  273. Resources.addStorageType(self.ResourceTypes.MachineStack, "machine_instances")
  274. Resources.addStorageType(self.ResourceTypes.DefinitionChangesContainer, "definition_changes")
  275. Resources.addStorageType(self.ResourceTypes.SettingVisibilityPreset, "setting_visibility")
  276. self._container_registry.addResourceType(self.ResourceTypes.QualityInstanceContainer, "quality")
  277. self._container_registry.addResourceType(self.ResourceTypes.QualityChangesInstanceContainer, "quality_changes")
  278. self._container_registry.addResourceType(self.ResourceTypes.VariantInstanceContainer, "variant")
  279. self._container_registry.addResourceType(self.ResourceTypes.MaterialInstanceContainer, "material")
  280. self._container_registry.addResourceType(self.ResourceTypes.UserInstanceContainer, "user")
  281. self._container_registry.addResourceType(self.ResourceTypes.ExtruderStack, "extruder_train")
  282. self._container_registry.addResourceType(self.ResourceTypes.MachineStack, "machine")
  283. self._container_registry.addResourceType(self.ResourceTypes.DefinitionChangesContainer, "definition_changes")
  284. Resources.addType(self.ResourceTypes.QmlFiles, "qml")
  285. Resources.addType(self.ResourceTypes.Firmware, "firmware")
  286. # Adds all empty containers.
  287. def __addAllEmptyContainers(self) -> None:
  288. # Add empty variant, material and quality containers.
  289. # Since they are empty, they should never be serialized and instead just programmatically created.
  290. # We need them to simplify the switching between materials.
  291. empty_container = self._container_registry.getEmptyInstanceContainer()
  292. self.empty_container = empty_container
  293. empty_definition_changes_container = copy.deepcopy(empty_container)
  294. empty_definition_changes_container.setMetaDataEntry("id", "empty_definition_changes")
  295. empty_definition_changes_container.addMetaDataEntry("type", "definition_changes")
  296. self._container_registry.addContainer(empty_definition_changes_container)
  297. self.empty_definition_changes_container = empty_definition_changes_container
  298. empty_variant_container = copy.deepcopy(empty_container)
  299. empty_variant_container.setMetaDataEntry("id", "empty_variant")
  300. empty_variant_container.addMetaDataEntry("type", "variant")
  301. self._container_registry.addContainer(empty_variant_container)
  302. self.empty_variant_container = empty_variant_container
  303. empty_material_container = copy.deepcopy(empty_container)
  304. empty_material_container.setMetaDataEntry("id", "empty_material")
  305. empty_material_container.addMetaDataEntry("type", "material")
  306. self._container_registry.addContainer(empty_material_container)
  307. self.empty_material_container = empty_material_container
  308. empty_quality_container = copy.deepcopy(empty_container)
  309. empty_quality_container.setMetaDataEntry("id", "empty_quality")
  310. empty_quality_container.setName("Not Supported")
  311. empty_quality_container.addMetaDataEntry("quality_type", "not_supported")
  312. empty_quality_container.addMetaDataEntry("type", "quality")
  313. empty_quality_container.addMetaDataEntry("supported", False)
  314. self._container_registry.addContainer(empty_quality_container)
  315. self.empty_quality_container = empty_quality_container
  316. empty_quality_changes_container = copy.deepcopy(empty_container)
  317. empty_quality_changes_container.setMetaDataEntry("id", "empty_quality_changes")
  318. empty_quality_changes_container.addMetaDataEntry("type", "quality_changes")
  319. empty_quality_changes_container.addMetaDataEntry("quality_type", "not_supported")
  320. self._container_registry.addContainer(empty_quality_changes_container)
  321. self.empty_quality_changes_container = empty_quality_changes_container
  322. # Initializes the version upgrade manager with by providing the paths for each resource type and the latest
  323. # versions.
  324. def __setLatestResouceVersionsForVersionUpgrade(self):
  325. self._version_upgrade_manager.setCurrentVersions(
  326. {
  327. ("quality", InstanceContainer.Version * 1000000 + self.SettingVersion): (self.ResourceTypes.QualityInstanceContainer, "application/x-uranium-instancecontainer"),
  328. ("quality_changes", InstanceContainer.Version * 1000000 + self.SettingVersion): (self.ResourceTypes.QualityChangesInstanceContainer, "application/x-uranium-instancecontainer"),
  329. ("machine_stack", ContainerStack.Version * 1000000 + self.SettingVersion): (self.ResourceTypes.MachineStack, "application/x-cura-globalstack"),
  330. ("extruder_train", ContainerStack.Version * 1000000 + self.SettingVersion): (self.ResourceTypes.ExtruderStack, "application/x-cura-extruderstack"),
  331. ("preferences", Preferences.Version * 1000000 + self.SettingVersion): (Resources.Preferences, "application/x-uranium-preferences"),
  332. ("user", InstanceContainer.Version * 1000000 + self.SettingVersion): (self.ResourceTypes.UserInstanceContainer, "application/x-uranium-instancecontainer"),
  333. ("definition_changes", InstanceContainer.Version * 1000000 + self.SettingVersion): (self.ResourceTypes.DefinitionChangesContainer, "application/x-uranium-instancecontainer"),
  334. ("variant", InstanceContainer.Version * 1000000 + self.SettingVersion): (self.ResourceTypes.VariantInstanceContainer, "application/x-uranium-instancecontainer"),
  335. }
  336. )
  337. # Runs preparations that needs to be done before the starting process.
  338. def startSplashWindowPhase(self):
  339. super().startSplashWindowPhase()
  340. self.setWindowIcon(QIcon(Resources.getPath(Resources.Images, "cura-icon.png")))
  341. self.setRequiredPlugins([
  342. # Misc.:
  343. "ConsoleLogger",
  344. "CuraEngineBackend",
  345. "UserAgreement",
  346. "FileLogger",
  347. "XmlMaterialProfile",
  348. "Toolbox",
  349. "PrepareStage",
  350. "MonitorStage",
  351. "LocalFileOutputDevice",
  352. "LocalContainerProvider",
  353. # Views:
  354. "SimpleView",
  355. "SimulationView",
  356. "SolidView",
  357. # Readers & Writers:
  358. "GCodeWriter",
  359. "STLReader",
  360. # Tools:
  361. "CameraTool",
  362. "MirrorTool",
  363. "RotateTool",
  364. "ScaleTool",
  365. "SelectionTool",
  366. "TranslateTool",
  367. ])
  368. self._i18n_catalog = i18nCatalog("cura")
  369. self._update_platform_activity_timer = QTimer()
  370. self._update_platform_activity_timer.setInterval(500)
  371. self._update_platform_activity_timer.setSingleShot(True)
  372. self._update_platform_activity_timer.timeout.connect(self.updatePlatformActivity)
  373. self.getController().getScene().sceneChanged.connect(self.updatePlatformActivityDelayed)
  374. self.getController().toolOperationStopped.connect(self._onToolOperationStopped)
  375. self.getController().contextMenuRequested.connect(self._onContextMenuRequested)
  376. self.getCuraSceneController().activeBuildPlateChanged.connect(self.updatePlatformActivityDelayed)
  377. self.showSplashMessage(self._i18n_catalog.i18nc("@info:progress", "Loading machines..."))
  378. with self._container_registry.lockFile():
  379. self._container_registry.loadAllMetadata()
  380. # set the setting version for Preferences
  381. preferences = self.getPreferences()
  382. preferences.addPreference("metadata/setting_version", 0)
  383. preferences.setValue("metadata/setting_version", self.SettingVersion) #Don't make it equal to the default so that the setting version always gets written to the file.
  384. preferences.addPreference("cura/active_mode", "simple")
  385. preferences.addPreference("cura/categories_expanded", "")
  386. preferences.addPreference("cura/jobname_prefix", True)
  387. preferences.addPreference("cura/select_models_on_load", False)
  388. preferences.addPreference("view/center_on_select", False)
  389. preferences.addPreference("mesh/scale_to_fit", False)
  390. preferences.addPreference("mesh/scale_tiny_meshes", True)
  391. preferences.addPreference("cura/dialog_on_project_save", True)
  392. preferences.addPreference("cura/asked_dialog_on_project_save", False)
  393. preferences.addPreference("cura/choice_on_profile_override", "always_ask")
  394. preferences.addPreference("cura/choice_on_open_project", "always_ask")
  395. preferences.addPreference("cura/use_multi_build_plate", False)
  396. preferences.addPreference("cura/currency", "€")
  397. preferences.addPreference("cura/material_settings", "{}")
  398. preferences.addPreference("view/invert_zoom", False)
  399. preferences.addPreference("view/filter_current_build_plate", False)
  400. preferences.addPreference("cura/sidebar_collapsed", False)
  401. self._need_to_show_user_agreement = not self.getPreferences().getValue("general/accepted_user_agreement")
  402. for key in [
  403. "dialog_load_path", # dialog_save_path is in LocalFileOutputDevicePlugin
  404. "dialog_profile_path",
  405. "dialog_material_path"]:
  406. preferences.addPreference("local_file/%s" % key, os.path.expanduser("~/"))
  407. preferences.setDefault("local_file/last_used_type", "text/x-gcode")
  408. self.applicationShuttingDown.connect(self.saveSettings)
  409. self.engineCreatedSignal.connect(self._onEngineCreated)
  410. self.globalContainerStackChanged.connect(self._onGlobalContainerChanged)
  411. self._onGlobalContainerChanged()
  412. self.getCuraSceneController().setActiveBuildPlate(0) # Initialize
  413. CuraApplication.Created = True
  414. def _onEngineCreated(self):
  415. self._qml_engine.addImageProvider("camera", CameraImageProvider.CameraImageProvider())
  416. @pyqtProperty(bool)
  417. def needToShowUserAgreement(self):
  418. return self._need_to_show_user_agreement
  419. def setNeedToShowUserAgreement(self, set_value = True):
  420. self._need_to_show_user_agreement = set_value
  421. ## The "Quit" button click event handler.
  422. @pyqtSlot()
  423. def closeApplication(self):
  424. Logger.log("i", "Close application")
  425. main_window = self.getMainWindow()
  426. if main_window is not None:
  427. main_window.close()
  428. else:
  429. self.exit(0)
  430. ## Signal to connect preferences action in QML
  431. showPreferencesWindow = pyqtSignal()
  432. ## Show the preferences window
  433. @pyqtSlot()
  434. def showPreferences(self):
  435. self.showPreferencesWindow.emit()
  436. ## A reusable dialogbox
  437. #
  438. showMessageBox = pyqtSignal(str, str, str, str, int, int, arguments = ["title", "text", "informativeText", "detailedText", "buttons", "icon"])
  439. def messageBox(self, title, text, informativeText = "", detailedText = "", buttons = QMessageBox.Ok, icon = QMessageBox.NoIcon, callback = None, callback_arguments = []):
  440. self._message_box_callback = callback
  441. self._message_box_callback_arguments = callback_arguments
  442. self.showMessageBox.emit(title, text, informativeText, detailedText, buttons, icon)
  443. showDiscardOrKeepProfileChanges = pyqtSignal()
  444. def discardOrKeepProfileChanges(self):
  445. has_user_interaction = False
  446. choice = self.getPreferences().getValue("cura/choice_on_profile_override")
  447. if choice == "always_discard":
  448. # don't show dialog and DISCARD the profile
  449. self.discardOrKeepProfileChangesClosed("discard")
  450. elif choice == "always_keep":
  451. # don't show dialog and KEEP the profile
  452. self.discardOrKeepProfileChangesClosed("keep")
  453. elif not self._is_headless:
  454. # ALWAYS ask whether to keep or discard the profile
  455. self.showDiscardOrKeepProfileChanges.emit()
  456. has_user_interaction = True
  457. return has_user_interaction
  458. @pyqtSlot(str)
  459. def discardOrKeepProfileChangesClosed(self, option):
  460. global_stack = self.getGlobalContainerStack()
  461. if option == "discard":
  462. for extruder in global_stack.extruders.values():
  463. extruder.userChanges.clear()
  464. global_stack.userChanges.clear()
  465. # if the user decided to keep settings then the user settings should be re-calculated and validated for errors
  466. # before slicing. To ensure that slicer uses right settings values
  467. elif option == "keep":
  468. for extruder in global_stack.extruders.values():
  469. extruder.userChanges.update()
  470. global_stack.userChanges.update()
  471. @pyqtSlot(int)
  472. def messageBoxClosed(self, button):
  473. if self._message_box_callback:
  474. self._message_box_callback(button, *self._message_box_callback_arguments)
  475. self._message_box_callback = None
  476. self._message_box_callback_arguments = []
  477. showPrintMonitor = pyqtSignal(bool, arguments = ["show"])
  478. def setSaveDataEnabled(self, enabled: bool) -> None:
  479. self._save_data_enabled = enabled
  480. # Cura has multiple locations where instance containers need to be saved, so we need to handle this differently.
  481. def saveSettings(self):
  482. if not self.started or not self._save_data_enabled:
  483. # Do not do saving during application start or when data should not be safed on quit.
  484. return
  485. ContainerRegistry.getInstance().saveDirtyContainers()
  486. self.savePreferences()
  487. def saveStack(self, stack):
  488. ContainerRegistry.getInstance().saveContainer(stack)
  489. @pyqtSlot(str, result = QUrl)
  490. def getDefaultPath(self, key):
  491. default_path = self.getPreferences().getValue("local_file/%s" % key)
  492. return QUrl.fromLocalFile(default_path)
  493. @pyqtSlot(str, str)
  494. def setDefaultPath(self, key, default_path):
  495. self.getPreferences().setValue("local_file/%s" % key, QUrl(default_path).toLocalFile())
  496. ## Handle loading of all plugin types (and the backend explicitly)
  497. # \sa PluginRegistry
  498. def _loadPlugins(self):
  499. self._plugin_registry.addType("profile_reader", self._addProfileReader)
  500. self._plugin_registry.addType("profile_writer", self._addProfileWriter)
  501. if Platform.isLinux():
  502. lib_suffixes = {"", "64", "32", "x32"} #A few common ones on different distributions.
  503. else:
  504. lib_suffixes = {""}
  505. for suffix in lib_suffixes:
  506. self._plugin_registry.addPluginLocation(os.path.join(QtApplication.getInstallPrefix(), "lib" + suffix, "cura"))
  507. if not hasattr(sys, "frozen"):
  508. self._plugin_registry.addPluginLocation(os.path.join(os.path.abspath(os.path.dirname(__file__)), "..", "plugins"))
  509. self._plugin_registry.loadPlugin("ConsoleLogger")
  510. self._plugin_registry.loadPlugin("CuraEngineBackend")
  511. self._plugin_registry.loadPlugins()
  512. if self.getBackend() is None:
  513. raise RuntimeError("Could not load the backend plugin!")
  514. self._plugins_loaded = True
  515. def run(self):
  516. super().run()
  517. container_registry = self._container_registry
  518. Logger.log("i", "Initializing variant manager")
  519. self._variant_manager = VariantManager(container_registry)
  520. self._variant_manager.initialize()
  521. Logger.log("i", "Initializing material manager")
  522. from cura.Machines.MaterialManager import MaterialManager
  523. self._material_manager = MaterialManager(container_registry, parent = self)
  524. self._material_manager.initialize()
  525. Logger.log("i", "Initializing quality manager")
  526. from cura.Machines.QualityManager import QualityManager
  527. self._quality_manager = QualityManager(container_registry, parent = self)
  528. self._quality_manager.initialize()
  529. Logger.log("i", "Initializing machine manager")
  530. self._machine_manager = MachineManager(self)
  531. Logger.log("i", "Initializing container manager")
  532. self._container_manager = ContainerManager(self)
  533. Logger.log("i", "Initializing machine error checker")
  534. self._machine_error_checker = MachineErrorChecker(self)
  535. self._machine_error_checker.initialize()
  536. # Check if we should run as single instance or not. If so, set up a local socket server which listener which
  537. # coordinates multiple Cura instances and accepts commands.
  538. if self._use_single_instance:
  539. self.__setUpSingleInstanceServer()
  540. # Setup scene and build volume
  541. root = self.getController().getScene().getRoot()
  542. self._volume = BuildVolume.BuildVolume(self, root)
  543. Arrange.build_volume = self._volume
  544. # initialize info objects
  545. self._print_information = PrintInformation.PrintInformation(self)
  546. self._cura_actions = CuraActions.CuraActions(self)
  547. # Initialize setting visibility presets model
  548. self._setting_visibility_presets_model = SettingVisibilityPresetsModel(self)
  549. default_visibility_profile = self._setting_visibility_presets_model.getItem(0)
  550. self.getPreferences().setDefault("general/visible_settings", ";".join(default_visibility_profile["settings"]))
  551. # Detect in which mode to run and execute that mode
  552. if self._is_headless:
  553. self.runWithoutGUI()
  554. else:
  555. self.runWithGUI()
  556. self.started = True
  557. self.initializationFinished.emit()
  558. Logger.log("d", "Booting Cura took %s seconds", time.time() - self._boot_loading_time)
  559. # For now use a timer to postpone some things that need to be done after the application and GUI are
  560. # initialized, for example opening files because they may show dialogs which can be closed due to incomplete
  561. # GUI initialization.
  562. self._post_start_timer = QTimer(self)
  563. self._post_start_timer.setInterval(1000)
  564. self._post_start_timer.setSingleShot(True)
  565. self._post_start_timer.timeout.connect(self._onPostStart)
  566. self._post_start_timer.start()
  567. self._auto_save = AutoSave(self)
  568. self._auto_save.initialize()
  569. self.exec_()
  570. def __setUpSingleInstanceServer(self):
  571. if self._use_single_instance:
  572. self._single_instance.startServer()
  573. def _onPostStart(self):
  574. for file_name in self._files_to_open:
  575. self.callLater(self._openFile, file_name)
  576. for file_name in self._open_file_queue: # Open all the files that were queued up while plug-ins were loading.
  577. self.callLater(self._openFile, file_name)
  578. initializationFinished = pyqtSignal()
  579. ## Run Cura without GUI elements and interaction (server mode).
  580. def runWithoutGUI(self):
  581. self.closeSplash()
  582. ## Run Cura with GUI (desktop mode).
  583. def runWithGUI(self):
  584. self.showSplashMessage(self._i18n_catalog.i18nc("@info:progress", "Setting up scene..."))
  585. controller = self.getController()
  586. t = controller.getTool("TranslateTool")
  587. if t:
  588. t.setEnabledAxis([ToolHandle.XAxis, ToolHandle.YAxis, ToolHandle.ZAxis])
  589. Selection.selectionChanged.connect(self.onSelectionChanged)
  590. # Set default background color for scene
  591. self.getRenderer().setBackgroundColor(QColor(245, 245, 245))
  592. # Initialize platform physics
  593. self._physics = PlatformPhysics.PlatformPhysics(controller, self._volume)
  594. # Initialize camera
  595. root = controller.getScene().getRoot()
  596. camera = Camera("3d", root)
  597. camera.setPosition(Vector(-80, 250, 700))
  598. camera.setPerspective(True)
  599. camera.lookAt(Vector(0, 0, 0))
  600. controller.getScene().setActiveCamera("3d")
  601. # Initialize camera tool
  602. camera_tool = controller.getTool("CameraTool")
  603. camera_tool.setOrigin(Vector(0, 100, 0))
  604. camera_tool.setZoomRange(0.1, 2000)
  605. # Initialize camera animations
  606. self._camera_animation = CameraAnimation.CameraAnimation()
  607. self._camera_animation.setCameraTool(self.getController().getTool("CameraTool"))
  608. self.showSplashMessage(self._i18n_catalog.i18nc("@info:progress", "Loading interface..."))
  609. # Initialize QML engine
  610. self.setMainQml(Resources.getPath(self.ResourceTypes.QmlFiles, "Cura.qml"))
  611. self._qml_import_paths.append(Resources.getPath(self.ResourceTypes.QmlFiles))
  612. self.initializeEngine()
  613. # Initialize UI state
  614. controller.setActiveStage("PrepareStage")
  615. controller.setActiveView("SolidView")
  616. controller.setCameraTool("CameraTool")
  617. controller.setSelectionTool("SelectionTool")
  618. # Hide the splash screen
  619. self.closeSplash()
  620. @pyqtSlot(result = QObject)
  621. def getSettingVisibilityPresetsModel(self, *args) -> SettingVisibilityPresetsModel:
  622. return self._setting_visibility_presets_model
  623. def getMachineErrorChecker(self, *args) -> MachineErrorChecker:
  624. return self._machine_error_checker
  625. def getMachineManager(self, *args) -> MachineManager:
  626. if self._machine_manager is None:
  627. self._machine_manager = MachineManager(self)
  628. return self._machine_manager
  629. def getExtruderManager(self, *args):
  630. if self._extruder_manager is None:
  631. self._extruder_manager = ExtruderManager()
  632. return self._extruder_manager
  633. def getVariantManager(self, *args):
  634. return self._variant_manager
  635. @pyqtSlot(result = QObject)
  636. def getMaterialManager(self, *args):
  637. return self._material_manager
  638. @pyqtSlot(result = QObject)
  639. def getQualityManager(self, *args):
  640. return self._quality_manager
  641. def getObjectsModel(self, *args):
  642. if self._object_manager is None:
  643. self._object_manager = ObjectsModel.createObjectsModel()
  644. return self._object_manager
  645. @pyqtSlot(result = QObject)
  646. def getMultiBuildPlateModel(self, *args):
  647. if self._multi_build_plate_model is None:
  648. self._multi_build_plate_model = MultiBuildPlateModel(self)
  649. return self._multi_build_plate_model
  650. @pyqtSlot(result = QObject)
  651. def getBuildPlateModel(self, *args):
  652. if self._build_plate_model is None:
  653. self._build_plate_model = BuildPlateModel(self)
  654. return self._build_plate_model
  655. def getCuraSceneController(self, *args):
  656. if self._cura_scene_controller is None:
  657. self._cura_scene_controller = CuraSceneController.createCuraSceneController()
  658. return self._cura_scene_controller
  659. def getSettingInheritanceManager(self, *args):
  660. if self._setting_inheritance_manager is None:
  661. self._setting_inheritance_manager = SettingInheritanceManager.createSettingInheritanceManager()
  662. return self._setting_inheritance_manager
  663. ## Get the machine action manager
  664. # We ignore any *args given to this, as we also register the machine manager as qml singleton.
  665. # It wants to give this function an engine and script engine, but we don't care about that.
  666. def getMachineActionManager(self, *args):
  667. return self._machine_action_manager
  668. def getSimpleModeSettingsManager(self, *args):
  669. if self._simple_mode_settings_manager is None:
  670. self._simple_mode_settings_manager = SimpleModeSettingsManager()
  671. return self._simple_mode_settings_manager
  672. ## Handle Qt events
  673. def event(self, event):
  674. if event.type() == QEvent.FileOpen:
  675. if self._plugins_loaded:
  676. self._openFile(event.file())
  677. else:
  678. self._open_file_queue.append(event.file())
  679. return super().event(event)
  680. def getAutoSave(self):
  681. return self._auto_save
  682. ## Get print information (duration / material used)
  683. def getPrintInformation(self):
  684. return self._print_information
  685. def getQualityProfilesDropDownMenuModel(self, *args, **kwargs):
  686. if self._quality_profile_drop_down_menu_model is None:
  687. self._quality_profile_drop_down_menu_model = QualityProfilesDropDownMenuModel(self)
  688. return self._quality_profile_drop_down_menu_model
  689. def getCustomQualityProfilesDropDownMenuModel(self, *args, **kwargs):
  690. if self._custom_quality_profile_drop_down_menu_model is None:
  691. self._custom_quality_profile_drop_down_menu_model = CustomQualityProfilesDropDownMenuModel(self)
  692. return self._custom_quality_profile_drop_down_menu_model
  693. ## Registers objects for the QML engine to use.
  694. #
  695. # \param engine The QML engine.
  696. def registerObjects(self, engine):
  697. super().registerObjects(engine)
  698. # global contexts
  699. engine.rootContext().setContextProperty("Printer", self)
  700. engine.rootContext().setContextProperty("CuraApplication", self)
  701. engine.rootContext().setContextProperty("PrintInformation", self._print_information)
  702. engine.rootContext().setContextProperty("CuraActions", self._cura_actions)
  703. qmlRegisterUncreatableType(CuraApplication, "Cura", 1, 0, "ResourceTypes", "Just an Enum type")
  704. qmlRegisterSingletonType(CuraSceneController, "Cura", 1, 0, "SceneController", self.getCuraSceneController)
  705. qmlRegisterSingletonType(ExtruderManager, "Cura", 1, 0, "ExtruderManager", self.getExtruderManager)
  706. qmlRegisterSingletonType(MachineManager, "Cura", 1, 0, "MachineManager", self.getMachineManager)
  707. qmlRegisterSingletonType(SettingInheritanceManager, "Cura", 1, 0, "SettingInheritanceManager", self.getSettingInheritanceManager)
  708. qmlRegisterSingletonType(SimpleModeSettingsManager, "Cura", 1, 0, "SimpleModeSettingsManager", self.getSimpleModeSettingsManager)
  709. qmlRegisterSingletonType(MachineActionManager.MachineActionManager, "Cura", 1, 0, "MachineActionManager", self.getMachineActionManager)
  710. qmlRegisterSingletonType(ObjectsModel, "Cura", 1, 0, "ObjectsModel", self.getObjectsModel)
  711. qmlRegisterType(BuildPlateModel, "Cura", 1, 0, "BuildPlateModel")
  712. qmlRegisterType(MultiBuildPlateModel, "Cura", 1, 0, "MultiBuildPlateModel")
  713. qmlRegisterType(InstanceContainer, "Cura", 1, 0, "InstanceContainer")
  714. qmlRegisterType(ExtrudersModel, "Cura", 1, 0, "ExtrudersModel")
  715. qmlRegisterType(GenericMaterialsModel, "Cura", 1, 0, "GenericMaterialsModel")
  716. qmlRegisterType(BrandMaterialsModel, "Cura", 1, 0, "BrandMaterialsModel")
  717. qmlRegisterType(MaterialManagementModel, "Cura", 1, 0, "MaterialManagementModel")
  718. qmlRegisterType(QualityManagementModel, "Cura", 1, 0, "QualityManagementModel")
  719. qmlRegisterType(MachineManagementModel, "Cura", 1, 0, "MachineManagementModel")
  720. qmlRegisterSingletonType(QualityProfilesDropDownMenuModel, "Cura", 1, 0,
  721. "QualityProfilesDropDownMenuModel", self.getQualityProfilesDropDownMenuModel)
  722. qmlRegisterSingletonType(CustomQualityProfilesDropDownMenuModel, "Cura", 1, 0,
  723. "CustomQualityProfilesDropDownMenuModel", self.getCustomQualityProfilesDropDownMenuModel)
  724. qmlRegisterType(NozzleModel, "Cura", 1, 0, "NozzleModel")
  725. qmlRegisterType(MaterialSettingsVisibilityHandler, "Cura", 1, 0, "MaterialSettingsVisibilityHandler")
  726. qmlRegisterType(SettingVisibilityPresetsModel, "Cura", 1, 0, "SettingVisibilityPresetsModel")
  727. qmlRegisterType(QualitySettingsModel, "Cura", 1, 0, "QualitySettingsModel")
  728. qmlRegisterType(MachineNameValidator, "Cura", 1, 0, "MachineNameValidator")
  729. qmlRegisterType(UserChangesModel, "Cura", 1, 0, "UserChangesModel")
  730. qmlRegisterSingletonType(ContainerManager, "Cura", 1, 0, "ContainerManager", ContainerManager.getInstance)
  731. # As of Qt5.7, it is necessary to get rid of any ".." in the path for the singleton to work.
  732. actions_url = QUrl.fromLocalFile(os.path.abspath(Resources.getPath(CuraApplication.ResourceTypes.QmlFiles, "Actions.qml")))
  733. qmlRegisterSingletonType(actions_url, "Cura", 1, 0, "Actions")
  734. for path in Resources.getAllResourcesOfType(CuraApplication.ResourceTypes.QmlFiles):
  735. type_name = os.path.splitext(os.path.basename(path))[0]
  736. if type_name in ("Cura", "Actions"):
  737. continue
  738. # Ignore anything that is not a QML file.
  739. if not path.endswith(".qml"):
  740. continue
  741. qmlRegisterType(QUrl.fromLocalFile(path), "Cura", 1, 0, type_name)
  742. def onSelectionChanged(self):
  743. if Selection.hasSelection():
  744. if self.getController().getActiveTool():
  745. # If the tool has been disabled by the new selection
  746. if not self.getController().getActiveTool().getEnabled():
  747. # Default
  748. self.getController().setActiveTool("TranslateTool")
  749. else:
  750. if self._previous_active_tool:
  751. self.getController().setActiveTool(self._previous_active_tool)
  752. if not self.getController().getActiveTool().getEnabled():
  753. self.getController().setActiveTool("TranslateTool")
  754. self._previous_active_tool = None
  755. else:
  756. # Default
  757. self.getController().setActiveTool("TranslateTool")
  758. if self.getPreferences().getValue("view/center_on_select"):
  759. self._center_after_select = True
  760. else:
  761. if self.getController().getActiveTool():
  762. self._previous_active_tool = self.getController().getActiveTool().getPluginId()
  763. self.getController().setActiveTool(None)
  764. def _onToolOperationStopped(self, event):
  765. if self._center_after_select and Selection.getSelectedObject(0) is not None:
  766. self._center_after_select = False
  767. self._camera_animation.setStart(self.getController().getTool("CameraTool").getOrigin())
  768. self._camera_animation.setTarget(Selection.getSelectedObject(0).getWorldPosition())
  769. self._camera_animation.start()
  770. def _onGlobalContainerChanged(self):
  771. if self._global_container_stack is not None:
  772. machine_file_formats = [file_type.strip() for file_type in self._global_container_stack.getMetaDataEntry("file_formats").split(";")]
  773. new_preferred_mimetype = ""
  774. if machine_file_formats:
  775. new_preferred_mimetype = machine_file_formats[0]
  776. if new_preferred_mimetype != self._preferred_mimetype:
  777. self._preferred_mimetype = new_preferred_mimetype
  778. self.preferredOutputMimetypeChanged.emit()
  779. requestAddPrinter = pyqtSignal()
  780. activityChanged = pyqtSignal()
  781. sceneBoundingBoxChanged = pyqtSignal()
  782. preferredOutputMimetypeChanged = pyqtSignal()
  783. @pyqtProperty(bool, notify = activityChanged)
  784. def platformActivity(self):
  785. return self._platform_activity
  786. @pyqtProperty(str, notify=preferredOutputMimetypeChanged)
  787. def preferredOutputMimetype(self):
  788. return self._preferred_mimetype
  789. @pyqtProperty(str, notify = sceneBoundingBoxChanged)
  790. def getSceneBoundingBoxString(self):
  791. return self._i18n_catalog.i18nc("@info 'width', 'depth' and 'height' are variable names that must NOT be translated; just translate the format of ##x##x## mm.", "%(width).1f x %(depth).1f x %(height).1f mm") % {'width' : self._scene_bounding_box.width.item(), 'depth': self._scene_bounding_box.depth.item(), 'height' : self._scene_bounding_box.height.item()}
  792. def updatePlatformActivityDelayed(self, node = None):
  793. if node is not None and (node.getMeshData() is not None or node.callDecoration("getLayerData")):
  794. self._update_platform_activity_timer.start()
  795. ## Update scene bounding box for current build plate
  796. def updatePlatformActivity(self, node = None):
  797. count = 0
  798. scene_bounding_box = None
  799. is_block_slicing_node = False
  800. active_build_plate = self.getMultiBuildPlateModel().activeBuildPlate
  801. print_information = self.getPrintInformation()
  802. for node in DepthFirstIterator(self.getController().getScene().getRoot()):
  803. if (
  804. not issubclass(type(node), CuraSceneNode) or
  805. (not node.getMeshData() and not node.callDecoration("getLayerData")) or
  806. (node.callDecoration("getBuildPlateNumber") != active_build_plate)):
  807. continue
  808. if node.callDecoration("isBlockSlicing"):
  809. is_block_slicing_node = True
  810. count += 1
  811. # After clicking the Undo button, if the build plate empty the project name needs to be set
  812. if print_information.baseName == '':
  813. print_information.setBaseName(node.getName())
  814. if not scene_bounding_box:
  815. scene_bounding_box = node.getBoundingBox()
  816. else:
  817. other_bb = node.getBoundingBox()
  818. if other_bb is not None:
  819. scene_bounding_box = scene_bounding_box + node.getBoundingBox()
  820. if print_information:
  821. print_information.setPreSliced(is_block_slicing_node)
  822. if not scene_bounding_box:
  823. scene_bounding_box = AxisAlignedBox.Null
  824. if repr(self._scene_bounding_box) != repr(scene_bounding_box):
  825. self._scene_bounding_box = scene_bounding_box
  826. self.sceneBoundingBoxChanged.emit()
  827. self._platform_activity = True if count > 0 else False
  828. self.activityChanged.emit()
  829. # Remove all selected objects from the scene.
  830. @pyqtSlot()
  831. @deprecated("Moved to CuraActions", "2.6")
  832. def deleteSelection(self):
  833. if not self.getController().getToolsEnabled():
  834. return
  835. removed_group_nodes = []
  836. op = GroupedOperation()
  837. nodes = Selection.getAllSelectedObjects()
  838. for node in nodes:
  839. op.addOperation(RemoveSceneNodeOperation(node))
  840. group_node = node.getParent()
  841. if group_node and group_node.callDecoration("isGroup") and group_node not in removed_group_nodes:
  842. remaining_nodes_in_group = list(set(group_node.getChildren()) - set(nodes))
  843. if len(remaining_nodes_in_group) == 1:
  844. removed_group_nodes.append(group_node)
  845. op.addOperation(SetParentOperation(remaining_nodes_in_group[0], group_node.getParent()))
  846. op.addOperation(RemoveSceneNodeOperation(group_node))
  847. op.push()
  848. ## Remove an object from the scene.
  849. # Note that this only removes an object if it is selected.
  850. @pyqtSlot("quint64")
  851. @deprecated("Use deleteSelection instead", "2.6")
  852. def deleteObject(self, object_id):
  853. if not self.getController().getToolsEnabled():
  854. return
  855. node = self.getController().getScene().findObject(object_id)
  856. if not node and object_id != 0: # Workaround for tool handles overlapping the selected object
  857. node = Selection.getSelectedObject(0)
  858. if node:
  859. op = GroupedOperation()
  860. op.addOperation(RemoveSceneNodeOperation(node))
  861. group_node = node.getParent()
  862. if group_node:
  863. # Note that at this point the node has not yet been deleted
  864. if len(group_node.getChildren()) <= 2 and group_node.callDecoration("isGroup"):
  865. op.addOperation(SetParentOperation(group_node.getChildren()[0], group_node.getParent()))
  866. op.addOperation(RemoveSceneNodeOperation(group_node))
  867. op.push()
  868. ## Create a number of copies of existing object.
  869. # \param object_id
  870. # \param count number of copies
  871. # \param min_offset minimum offset to other objects.
  872. @pyqtSlot("quint64", int)
  873. @deprecated("Use CuraActions::multiplySelection", "2.6")
  874. def multiplyObject(self, object_id, count, min_offset = 8):
  875. node = self.getController().getScene().findObject(object_id)
  876. if not node:
  877. node = Selection.getSelectedObject(0)
  878. while node.getParent() and node.getParent().callDecoration("isGroup"):
  879. node = node.getParent()
  880. job = MultiplyObjectsJob([node], count, min_offset)
  881. job.start()
  882. return
  883. ## Center object on platform.
  884. @pyqtSlot("quint64")
  885. @deprecated("Use CuraActions::centerSelection", "2.6")
  886. def centerObject(self, object_id):
  887. node = self.getController().getScene().findObject(object_id)
  888. if not node and object_id != 0: # Workaround for tool handles overlapping the selected object
  889. node = Selection.getSelectedObject(0)
  890. if not node:
  891. return
  892. if node.getParent() and node.getParent().callDecoration("isGroup"):
  893. node = node.getParent()
  894. if node:
  895. op = SetTransformOperation(node, Vector())
  896. op.push()
  897. ## Select all nodes containing mesh data in the scene.
  898. @pyqtSlot()
  899. def selectAll(self):
  900. if not self.getController().getToolsEnabled():
  901. return
  902. Selection.clear()
  903. for node in DepthFirstIterator(self.getController().getScene().getRoot()):
  904. if not isinstance(node, SceneNode):
  905. continue
  906. if not node.getMeshData() and not node.callDecoration("isGroup"):
  907. continue # Node that doesnt have a mesh and is not a group.
  908. if node.getParent() and node.getParent().callDecoration("isGroup") or node.getParent().callDecoration("isSliceable"):
  909. continue # Grouped nodes don't need resetting as their parent (the group) is resetted)
  910. if not node.isSelectable():
  911. continue # i.e. node with layer data
  912. if not node.callDecoration("isSliceable") and not node.callDecoration("isGroup"):
  913. continue # i.e. node with layer data
  914. Selection.add(node)
  915. ## Reset all translation on nodes with mesh data.
  916. @pyqtSlot()
  917. def resetAllTranslation(self):
  918. Logger.log("i", "Resetting all scene translations")
  919. nodes = []
  920. for node in DepthFirstIterator(self.getController().getScene().getRoot()):
  921. if not isinstance(node, SceneNode):
  922. continue
  923. if not node.getMeshData() and not node.callDecoration("isGroup"):
  924. continue # Node that doesnt have a mesh and is not a group.
  925. if node.getParent() and node.getParent().callDecoration("isGroup"):
  926. continue # Grouped nodes don't need resetting as their parent (the group) is resetted)
  927. if not node.isSelectable():
  928. continue # i.e. node with layer data
  929. nodes.append(node)
  930. if nodes:
  931. op = GroupedOperation()
  932. for node in nodes:
  933. # Ensure that the object is above the build platform
  934. node.removeDecorator(ZOffsetDecorator.ZOffsetDecorator)
  935. if node.getBoundingBox():
  936. center_y = node.getWorldPosition().y - node.getBoundingBox().bottom
  937. else:
  938. center_y = 0
  939. op.addOperation(SetTransformOperation(node, Vector(0, center_y, 0)))
  940. op.push()
  941. ## Reset all transformations on nodes with mesh data.
  942. @pyqtSlot()
  943. def resetAll(self):
  944. Logger.log("i", "Resetting all scene transformations")
  945. nodes = []
  946. for node in DepthFirstIterator(self.getController().getScene().getRoot()):
  947. if not isinstance(node, SceneNode):
  948. continue
  949. if not node.getMeshData() and not node.callDecoration("isGroup"):
  950. continue # Node that doesnt have a mesh and is not a group.
  951. if node.getParent() and node.getParent().callDecoration("isGroup"):
  952. continue # Grouped nodes don't need resetting as their parent (the group) is resetted)
  953. if not node.callDecoration("isSliceable") and not node.callDecoration("isGroup"):
  954. continue # i.e. node with layer data
  955. nodes.append(node)
  956. if nodes:
  957. op = GroupedOperation()
  958. for node in nodes:
  959. # Ensure that the object is above the build platform
  960. node.removeDecorator(ZOffsetDecorator.ZOffsetDecorator)
  961. if node.getBoundingBox():
  962. center_y = node.getWorldPosition().y - node.getBoundingBox().bottom
  963. else:
  964. center_y = 0
  965. op.addOperation(SetTransformOperation(node, Vector(0, center_y, 0), Quaternion(), Vector(1, 1, 1)))
  966. op.push()
  967. ## Arrange all objects.
  968. @pyqtSlot()
  969. def arrangeObjectsToAllBuildPlates(self):
  970. nodes = []
  971. for node in DepthFirstIterator(self.getController().getScene().getRoot()):
  972. if not isinstance(node, SceneNode):
  973. continue
  974. if not node.getMeshData() and not node.callDecoration("isGroup"):
  975. continue # Node that doesnt have a mesh and is not a group.
  976. if node.getParent() and node.getParent().callDecoration("isGroup"):
  977. continue # Grouped nodes don't need resetting as their parent (the group) is resetted)
  978. if not node.callDecoration("isSliceable") and not node.callDecoration("isGroup"):
  979. continue # i.e. node with layer data
  980. # Skip nodes that are too big
  981. if node.getBoundingBox().width < self._volume.getBoundingBox().width or node.getBoundingBox().depth < self._volume.getBoundingBox().depth:
  982. nodes.append(node)
  983. job = ArrangeObjectsAllBuildPlatesJob(nodes)
  984. job.start()
  985. self.getCuraSceneController().setActiveBuildPlate(0) # Select first build plate
  986. # Single build plate
  987. @pyqtSlot()
  988. def arrangeAll(self):
  989. nodes = []
  990. active_build_plate = self.getMultiBuildPlateModel().activeBuildPlate
  991. for node in DepthFirstIterator(self.getController().getScene().getRoot()):
  992. if not isinstance(node, SceneNode):
  993. continue
  994. if not node.getMeshData() and not node.callDecoration("isGroup"):
  995. continue # Node that doesnt have a mesh and is not a group.
  996. if node.getParent() and node.getParent().callDecoration("isGroup"):
  997. continue # Grouped nodes don't need resetting as their parent (the group) is resetted)
  998. if not node.isSelectable():
  999. continue # i.e. node with layer data
  1000. if not node.callDecoration("isSliceable") and not node.callDecoration("isGroup"):
  1001. continue # i.e. node with layer data
  1002. if node.callDecoration("getBuildPlateNumber") == active_build_plate:
  1003. # Skip nodes that are too big
  1004. if node.getBoundingBox().width < self._volume.getBoundingBox().width or node.getBoundingBox().depth < self._volume.getBoundingBox().depth:
  1005. nodes.append(node)
  1006. self.arrange(nodes, fixed_nodes = [])
  1007. ## Arrange a set of nodes given a set of fixed nodes
  1008. # \param nodes nodes that we have to place
  1009. # \param fixed_nodes nodes that are placed in the arranger before finding spots for nodes
  1010. def arrange(self, nodes, fixed_nodes):
  1011. min_offset = self.getBuildVolume().getEdgeDisallowedSize() + 2 # Allow for some rounding errors
  1012. job = ArrangeObjectsJob(nodes, fixed_nodes, min_offset = max(min_offset, 8))
  1013. job.start()
  1014. ## Reload all mesh data on the screen from file.
  1015. @pyqtSlot()
  1016. def reloadAll(self):
  1017. Logger.log("i", "Reloading all loaded mesh data.")
  1018. nodes = []
  1019. has_merged_nodes = False
  1020. for node in DepthFirstIterator(self.getController().getScene().getRoot()):
  1021. if not isinstance(node, CuraSceneNode) or not node.getMeshData() :
  1022. if node.getName() == "MergedMesh":
  1023. has_merged_nodes = True
  1024. continue
  1025. nodes.append(node)
  1026. if not nodes:
  1027. return
  1028. for node in nodes:
  1029. file_name = node.getMeshData().getFileName()
  1030. if file_name:
  1031. job = ReadMeshJob(file_name)
  1032. job._node = node
  1033. job.finished.connect(self._reloadMeshFinished)
  1034. if has_merged_nodes:
  1035. job.finished.connect(self.updateOriginOfMergedMeshes)
  1036. job.start()
  1037. else:
  1038. Logger.log("w", "Unable to reload data because we don't have a filename.")
  1039. ## Get logging data of the backend engine
  1040. # \returns \type{string} Logging data
  1041. @pyqtSlot(result = str)
  1042. def getEngineLog(self):
  1043. log = ""
  1044. for entry in self.getBackend().getLog():
  1045. log += entry.decode()
  1046. return log
  1047. @pyqtSlot("QStringList")
  1048. def setExpandedCategories(self, categories):
  1049. categories = list(set(categories))
  1050. categories.sort()
  1051. joined = ";".join(categories)
  1052. if joined != self.getPreferences().getValue("cura/categories_expanded"):
  1053. self.getPreferences().setValue("cura/categories_expanded", joined)
  1054. self.expandedCategoriesChanged.emit()
  1055. expandedCategoriesChanged = pyqtSignal()
  1056. @pyqtProperty("QStringList", notify = expandedCategoriesChanged)
  1057. def expandedCategories(self):
  1058. return self.getPreferences().getValue("cura/categories_expanded").split(";")
  1059. @pyqtSlot()
  1060. def mergeSelected(self):
  1061. self.groupSelected()
  1062. try:
  1063. group_node = Selection.getAllSelectedObjects()[0]
  1064. except Exception as e:
  1065. Logger.log("e", "mergeSelected: Exception: %s", e)
  1066. return
  1067. meshes = [node.getMeshData() for node in group_node.getAllChildren() if node.getMeshData()]
  1068. # Compute the center of the objects
  1069. object_centers = []
  1070. # Forget about the translation that the original objects have
  1071. zero_translation = Matrix(data=numpy.zeros(3))
  1072. for mesh, node in zip(meshes, group_node.getChildren()):
  1073. transformation = node.getLocalTransformation()
  1074. transformation.setTranslation(zero_translation)
  1075. transformed_mesh = mesh.getTransformed(transformation)
  1076. center = transformed_mesh.getCenterPosition()
  1077. if center is not None:
  1078. object_centers.append(center)
  1079. if object_centers and len(object_centers) > 0:
  1080. middle_x = sum([v.x for v in object_centers]) / len(object_centers)
  1081. middle_y = sum([v.y for v in object_centers]) / len(object_centers)
  1082. middle_z = sum([v.z for v in object_centers]) / len(object_centers)
  1083. offset = Vector(middle_x, middle_y, middle_z)
  1084. else:
  1085. offset = Vector(0, 0, 0)
  1086. # Move each node to the same position.
  1087. for mesh, node in zip(meshes, group_node.getChildren()):
  1088. transformation = node.getLocalTransformation()
  1089. transformation.setTranslation(zero_translation)
  1090. transformed_mesh = mesh.getTransformed(transformation)
  1091. # Align the object around its zero position
  1092. # and also apply the offset to center it inside the group.
  1093. node.setPosition(-transformed_mesh.getZeroPosition() - offset)
  1094. # Use the previously found center of the group bounding box as the new location of the group
  1095. group_node.setPosition(group_node.getBoundingBox().center)
  1096. group_node.setName("MergedMesh") # add a specific name to distinguish this node
  1097. ## Updates origin position of all merged meshes
  1098. # \param jobNode \type{Job} empty object which passed which is required by JobQueue
  1099. def updateOriginOfMergedMeshes(self, jobNode):
  1100. group_nodes = []
  1101. for node in DepthFirstIterator(self.getController().getScene().getRoot()):
  1102. if isinstance(node, CuraSceneNode) and node.getName() == "MergedMesh":
  1103. #checking by name might be not enough, the merged mesh should has "GroupDecorator" decorator
  1104. for decorator in node.getDecorators():
  1105. if isinstance(decorator, GroupDecorator):
  1106. group_nodes.append(node)
  1107. break
  1108. for group_node in group_nodes:
  1109. meshes = [node.getMeshData() for node in group_node.getAllChildren() if node.getMeshData()]
  1110. # Compute the center of the objects
  1111. object_centers = []
  1112. # Forget about the translation that the original objects have
  1113. zero_translation = Matrix(data=numpy.zeros(3))
  1114. for mesh, node in zip(meshes, group_node.getChildren()):
  1115. transformation = node.getLocalTransformation()
  1116. transformation.setTranslation(zero_translation)
  1117. transformed_mesh = mesh.getTransformed(transformation)
  1118. center = transformed_mesh.getCenterPosition()
  1119. if center is not None:
  1120. object_centers.append(center)
  1121. if object_centers and len(object_centers) > 0:
  1122. middle_x = sum([v.x for v in object_centers]) / len(object_centers)
  1123. middle_y = sum([v.y for v in object_centers]) / len(object_centers)
  1124. middle_z = sum([v.z for v in object_centers]) / len(object_centers)
  1125. offset = Vector(middle_x, middle_y, middle_z)
  1126. else:
  1127. offset = Vector(0, 0, 0)
  1128. # Move each node to the same position.
  1129. for mesh, node in zip(meshes, group_node.getChildren()):
  1130. transformation = node.getLocalTransformation()
  1131. transformation.setTranslation(zero_translation)
  1132. transformed_mesh = mesh.getTransformed(transformation)
  1133. # Align the object around its zero position
  1134. # and also apply the offset to center it inside the group.
  1135. node.setPosition(-transformed_mesh.getZeroPosition() - offset)
  1136. # Use the previously found center of the group bounding box as the new location of the group
  1137. group_node.setPosition(group_node.getBoundingBox().center)
  1138. @pyqtSlot()
  1139. def groupSelected(self):
  1140. # Create a group-node
  1141. group_node = CuraSceneNode()
  1142. group_decorator = GroupDecorator()
  1143. group_node.addDecorator(group_decorator)
  1144. group_node.addDecorator(ConvexHullDecorator())
  1145. group_node.addDecorator(BuildPlateDecorator(self.getMultiBuildPlateModel().activeBuildPlate))
  1146. group_node.setParent(self.getController().getScene().getRoot())
  1147. group_node.setSelectable(True)
  1148. center = Selection.getSelectionCenter()
  1149. group_node.setPosition(center)
  1150. group_node.setCenterPosition(center)
  1151. # Remove nodes that are directly parented to another selected node from the selection so they remain parented
  1152. selected_nodes = Selection.getAllSelectedObjects().copy()
  1153. for node in selected_nodes:
  1154. if node.getParent() in selected_nodes and not node.getParent().callDecoration("isGroup"):
  1155. Selection.remove(node)
  1156. # Move selected nodes into the group-node
  1157. Selection.applyOperation(SetParentOperation, group_node)
  1158. # Deselect individual nodes and select the group-node instead
  1159. for node in group_node.getChildren():
  1160. Selection.remove(node)
  1161. Selection.add(group_node)
  1162. @pyqtSlot()
  1163. def ungroupSelected(self):
  1164. selected_objects = Selection.getAllSelectedObjects().copy()
  1165. for node in selected_objects:
  1166. if node.callDecoration("isGroup"):
  1167. op = GroupedOperation()
  1168. group_parent = node.getParent()
  1169. children = node.getChildren().copy()
  1170. for child in children:
  1171. # Ungroup only 1 level deep
  1172. if child.getParent() != node:
  1173. continue
  1174. # Set the parent of the children to the parent of the group-node
  1175. op.addOperation(SetParentOperation(child, group_parent))
  1176. # Add all individual nodes to the selection
  1177. Selection.add(child)
  1178. op.push()
  1179. # Note: The group removes itself from the scene once all its children have left it,
  1180. # see GroupDecorator._onChildrenChanged
  1181. def _createSplashScreen(self):
  1182. if self._is_headless:
  1183. return None
  1184. return CuraSplashScreen.CuraSplashScreen()
  1185. def _onActiveMachineChanged(self):
  1186. pass
  1187. fileLoaded = pyqtSignal(str)
  1188. fileCompleted = pyqtSignal(str)
  1189. def _reloadMeshFinished(self, job):
  1190. # TODO; This needs to be fixed properly. We now make the assumption that we only load a single mesh!
  1191. job_result = job.getResult()
  1192. if len(job_result) == 0:
  1193. Logger.log("e", "Reloading the mesh failed.")
  1194. return
  1195. mesh_data = job_result[0].getMeshData()
  1196. if not mesh_data:
  1197. Logger.log("w", "Could not find a mesh in reloaded node.")
  1198. return
  1199. job._node.setMeshData(mesh_data)
  1200. def _openFile(self, filename):
  1201. self.readLocalFile(QUrl.fromLocalFile(filename))
  1202. def _addProfileReader(self, profile_reader):
  1203. # TODO: Add the profile reader to the list of plug-ins that can be used when importing profiles.
  1204. pass
  1205. def _addProfileWriter(self, profile_writer):
  1206. pass
  1207. @pyqtSlot("QSize")
  1208. def setMinimumWindowSize(self, size):
  1209. main_window = self.getMainWindow()
  1210. if main_window:
  1211. main_window.setMinimumSize(size)
  1212. def getBuildVolume(self):
  1213. return self._volume
  1214. additionalComponentsChanged = pyqtSignal(str, arguments = ["areaId"])
  1215. @pyqtProperty("QVariantMap", notify = additionalComponentsChanged)
  1216. def additionalComponents(self):
  1217. return self._additional_components
  1218. ## Add a component to a list of components to be reparented to another area in the GUI.
  1219. # The actual reparenting is done by the area itself.
  1220. # \param area_id \type{str} Identifying name of the area to which the component should be reparented
  1221. # \param component \type{QQuickComponent} The component that should be reparented
  1222. @pyqtSlot(str, "QVariant")
  1223. def addAdditionalComponent(self, area_id, component):
  1224. if area_id not in self._additional_components:
  1225. self._additional_components[area_id] = []
  1226. self._additional_components[area_id].append(component)
  1227. self.additionalComponentsChanged.emit(area_id)
  1228. @pyqtSlot(str)
  1229. def log(self, msg):
  1230. Logger.log("d", msg)
  1231. openProjectFile = pyqtSignal(QUrl, arguments = ["project_file"]) # Emitted when a project file is about to open.
  1232. @pyqtSlot(QUrl, bool)
  1233. def readLocalFile(self, file, skip_project_file_check = False):
  1234. if not file.isValid():
  1235. return
  1236. scene = self.getController().getScene()
  1237. for node in DepthFirstIterator(scene.getRoot()):
  1238. if node.callDecoration("isBlockSlicing"):
  1239. self.deleteAll()
  1240. break
  1241. if not skip_project_file_check and self.checkIsValidProjectFile(file):
  1242. self.callLater(self.openProjectFile.emit, file)
  1243. return
  1244. if Preferences.getInstance().getValue("cura/select_models_on_load"):
  1245. Selection.clear()
  1246. f = file.toLocalFile()
  1247. extension = os.path.splitext(f)[1]
  1248. extension = extension.lower()
  1249. filename = os.path.basename(f)
  1250. if len(self._currently_loading_files) > 0:
  1251. # If a non-slicable file is already being loaded, we prevent loading of any further non-slicable files
  1252. if extension in self._non_sliceable_extensions:
  1253. message = Message(
  1254. self._i18n_catalog.i18nc("@info:status",
  1255. "Only one G-code file can be loaded at a time. Skipped importing {0}",
  1256. filename), title = self._i18n_catalog.i18nc("@info:title", "Warning"))
  1257. message.show()
  1258. return
  1259. # If file being loaded is non-slicable file, then prevent loading of any other files
  1260. extension = os.path.splitext(self._currently_loading_files[0])[1]
  1261. extension = extension.lower()
  1262. if extension in self._non_sliceable_extensions:
  1263. message = Message(
  1264. self._i18n_catalog.i18nc("@info:status",
  1265. "Can't open any other file if G-code is loading. Skipped importing {0}",
  1266. filename), title = self._i18n_catalog.i18nc("@info:title", "Error"))
  1267. message.show()
  1268. return
  1269. self._currently_loading_files.append(f)
  1270. if extension in self._non_sliceable_extensions:
  1271. self.deleteAll(only_selectable = False)
  1272. job = ReadMeshJob(f)
  1273. job.finished.connect(self._readMeshFinished)
  1274. job.start()
  1275. def _readMeshFinished(self, job):
  1276. nodes = job.getResult()
  1277. filename = job.getFileName()
  1278. self._currently_loading_files.remove(filename)
  1279. self.fileLoaded.emit(filename)
  1280. arrange_objects_on_load = not self.getPreferences().getValue("cura/use_multi_build_plate")
  1281. target_build_plate = self.getMultiBuildPlateModel().activeBuildPlate if arrange_objects_on_load else -1
  1282. root = self.getController().getScene().getRoot()
  1283. fixed_nodes = []
  1284. for node_ in DepthFirstIterator(root):
  1285. if node_.callDecoration("isSliceable") and node_.callDecoration("getBuildPlateNumber") == target_build_plate:
  1286. fixed_nodes.append(node_)
  1287. global_container_stack = self.getGlobalContainerStack()
  1288. machine_width = global_container_stack.getProperty("machine_width", "value")
  1289. machine_depth = global_container_stack.getProperty("machine_depth", "value")
  1290. arranger = Arrange.create(x = machine_width, y = machine_depth, fixed_nodes = fixed_nodes)
  1291. min_offset = 8
  1292. default_extruder_position = self.getMachineManager().defaultExtruderPosition
  1293. default_extruder_id = self._global_container_stack.extruders[default_extruder_position].getId()
  1294. select_models_on_load = Preferences.getInstance().getValue("cura/select_models_on_load")
  1295. for original_node in nodes:
  1296. # Create a CuraSceneNode just if the original node is not that type
  1297. if isinstance(original_node, CuraSceneNode):
  1298. node = original_node
  1299. else:
  1300. node = CuraSceneNode()
  1301. node.setMeshData(original_node.getMeshData())
  1302. #Setting meshdata does not apply scaling.
  1303. if(original_node.getScale() != Vector(1.0, 1.0, 1.0)):
  1304. node.scale(original_node.getScale())
  1305. node.setSelectable(True)
  1306. node.setName(os.path.basename(filename))
  1307. self.getBuildVolume().checkBoundsAndUpdate(node)
  1308. is_non_sliceable = False
  1309. filename_lower = filename.lower()
  1310. for extension in self._non_sliceable_extensions:
  1311. if filename_lower.endswith(extension):
  1312. is_non_sliceable = True
  1313. break
  1314. if is_non_sliceable:
  1315. self.callLater(lambda: self.getController().setActiveView("SimulationView"))
  1316. block_slicing_decorator = BlockSlicingDecorator()
  1317. node.addDecorator(block_slicing_decorator)
  1318. else:
  1319. sliceable_decorator = SliceableObjectDecorator()
  1320. node.addDecorator(sliceable_decorator)
  1321. scene = self.getController().getScene()
  1322. # If there is no convex hull for the node, start calculating it and continue.
  1323. if not node.getDecorator(ConvexHullDecorator):
  1324. node.addDecorator(ConvexHullDecorator())
  1325. for child in node.getAllChildren():
  1326. if not child.getDecorator(ConvexHullDecorator):
  1327. child.addDecorator(ConvexHullDecorator())
  1328. if arrange_objects_on_load:
  1329. if node.callDecoration("isSliceable"):
  1330. # Only check position if it's not already blatantly obvious that it won't fit.
  1331. if node.getBoundingBox() is None or self._volume.getBoundingBox() is None or node.getBoundingBox().width < self._volume.getBoundingBox().width or node.getBoundingBox().depth < self._volume.getBoundingBox().depth:
  1332. # Find node location
  1333. offset_shape_arr, hull_shape_arr = ShapeArray.fromNode(node, min_offset = min_offset)
  1334. # If a model is to small then it will not contain any points
  1335. if offset_shape_arr is None and hull_shape_arr is None:
  1336. Message(self._i18n_catalog.i18nc("@info:status", "The selected model was too small to load."),
  1337. title=self._i18n_catalog.i18nc("@info:title", "Warning")).show()
  1338. return
  1339. # Step is for skipping tests to make it a lot faster. it also makes the outcome somewhat rougher
  1340. arranger.findNodePlacement(node, offset_shape_arr, hull_shape_arr, step = 10)
  1341. # This node is deep copied from some other node which already has a BuildPlateDecorator, but the deepcopy
  1342. # of BuildPlateDecorator produces one that's associated with build plate -1. So, here we need to check if
  1343. # the BuildPlateDecorator exists or not and always set the correct build plate number.
  1344. build_plate_decorator = node.getDecorator(BuildPlateDecorator)
  1345. if build_plate_decorator is None:
  1346. build_plate_decorator = BuildPlateDecorator(target_build_plate)
  1347. node.addDecorator(build_plate_decorator)
  1348. build_plate_decorator.setBuildPlateNumber(target_build_plate)
  1349. op = AddSceneNodeOperation(node, scene.getRoot())
  1350. op.push()
  1351. node.callDecoration("setActiveExtruder", default_extruder_id)
  1352. scene.sceneChanged.emit(node)
  1353. if select_models_on_load:
  1354. Selection.add(node)
  1355. self.fileCompleted.emit(filename)
  1356. def addNonSliceableExtension(self, extension):
  1357. self._non_sliceable_extensions.append(extension)
  1358. @pyqtSlot(str, result=bool)
  1359. def checkIsValidProjectFile(self, file_url):
  1360. """
  1361. Checks if the given file URL is a valid project file.
  1362. """
  1363. file_path = QUrl(file_url).toLocalFile()
  1364. workspace_reader = self.getWorkspaceFileHandler().getReaderForFile(file_path)
  1365. if workspace_reader is None:
  1366. return False # non-project files won't get a reader
  1367. try:
  1368. result = workspace_reader.preRead(file_path, show_dialog=False)
  1369. return result == WorkspaceReader.PreReadResult.accepted
  1370. except Exception as e:
  1371. Logger.logException("e", "Could not check file %s", file_url)
  1372. return False
  1373. def _onContextMenuRequested(self, x: float, y: float) -> None:
  1374. # Ensure we select the object if we request a context menu over an object without having a selection.
  1375. if not Selection.hasSelection():
  1376. node = self.getController().getScene().findObject(cast(SelectionPass, self.getRenderer().getRenderPass("selection")).getIdAtPosition(x, y))
  1377. if node:
  1378. parent = node.getParent()
  1379. while(parent and parent.callDecoration("isGroup")):
  1380. node = parent
  1381. parent = node.getParent()
  1382. Selection.add(node)
  1383. @pyqtSlot()
  1384. def showMoreInformationDialogForAnonymousDataCollection(self):
  1385. cast(SliceInfo, self._plugin_registry.getPluginObject("SliceInfoPlugin")).showMoreInfoDialog()