CuraApplication.py 80 KB

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