CuraApplication.py 98 KB

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