CuraApplication.py 83 KB

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