CuraApplication.py 76 KB

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