CuraApplication.py 102 KB

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