CuraApplication.py 86 KB

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