CuraApplication.py 82 KB

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