CuraApplication.py 93 KB

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