CuraApplication.py 100 KB

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