CuraApplication.py 78 KB

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