CuraApplication.py 100 KB

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