CuraApplication.py 95 KB

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