CuraApplication.py 78 KB

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