CuraApplication.py 79 KB

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