CuraApplication.py 76 KB

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