CuraApplication.py 94 KB

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