CuraApplication.py 102 KB

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