CuraApplication.py 86 KB

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