CuraApplication.py 98 KB

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