CuraApplication.py 80 KB

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