CuraApplication.py 91 KB

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