CuraApplication.py 99 KB

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