CuraApplication.py 81 KB

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