CuraApplication.py 99 KB

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