CuraApplication.py 80 KB

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