CuraApplication.py 91 KB

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