CuraApplication.py 98 KB

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