CuraApplication.py 101 KB

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