CuraApplication.py 97 KB

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