CuraApplication.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827
  1. # Copyright (c) 2015 Ultimaker B.V.
  2. # Cura is released under the terms of the AGPLv3 or higher.
  3. from UM.Qt.QtApplication import QtApplication
  4. from UM.Scene.SceneNode import SceneNode
  5. from UM.Scene.Camera import Camera
  6. from UM.Scene.Platform import Platform as Scene_Platform
  7. from UM.Math.Vector import Vector
  8. from UM.Math.Quaternion import Quaternion
  9. from UM.Math.AxisAlignedBox import AxisAlignedBox
  10. from UM.Resources import Resources
  11. from UM.Scene.ToolHandle import ToolHandle
  12. from UM.Scene.Iterator.DepthFirstIterator import DepthFirstIterator
  13. from UM.Mesh.ReadMeshJob import ReadMeshJob
  14. from UM.Logger import Logger
  15. from UM.Preferences import Preferences
  16. from UM.Platform import Platform
  17. from UM.JobQueue import JobQueue
  18. from UM.SaveFile import SaveFile
  19. from UM.Scene.Selection import Selection
  20. from UM.Scene.GroupDecorator import GroupDecorator
  21. from UM.Settings.Validator import Validator
  22. from UM.Operations.AddSceneNodeOperation import AddSceneNodeOperation
  23. from UM.Operations.RemoveSceneNodeOperation import RemoveSceneNodeOperation
  24. from UM.Operations.GroupedOperation import GroupedOperation
  25. from UM.Operations.SetTransformOperation import SetTransformOperation
  26. from cura.SetParentOperation import SetParentOperation
  27. from UM.Settings.SettingDefinition import SettingDefinition, DefinitionPropertyType
  28. from UM.Settings.ContainerRegistry import ContainerRegistry
  29. from UM.i18n import i18nCatalog
  30. from . import ExtruderManager
  31. from . import ExtrudersModel
  32. from . import PlatformPhysics
  33. from . import BuildVolume
  34. from . import CameraAnimation
  35. from . import PrintInformation
  36. from . import CuraActions
  37. from . import MultiMaterialDecorator
  38. from . import ZOffsetDecorator
  39. from . import CuraSplashScreen
  40. from . import MachineManagerModel
  41. from . import ContainerSettingsModel
  42. from . import CameraImageProvider
  43. from . import MachineActionManager
  44. from PyQt5.QtCore import pyqtSlot, QUrl, pyqtSignal, pyqtProperty, QEvent, Q_ENUMS
  45. from PyQt5.QtGui import QColor, QIcon
  46. from PyQt5.QtQml import qmlRegisterUncreatableType, qmlRegisterSingletonType, qmlRegisterType
  47. import platform
  48. import sys
  49. import os.path
  50. import numpy
  51. import copy
  52. import urllib
  53. numpy.seterr(all="ignore")
  54. #WORKAROUND: GITHUB-88 GITHUB-385 GITHUB-612
  55. if Platform.isLinux(): # Needed for platform.linux_distribution, which is not available on Windows and OSX
  56. # For Ubuntu: https://bugs.launchpad.net/ubuntu/+source/python-qt4/+bug/941826
  57. if platform.linux_distribution()[0] in ("Ubuntu", ): # TODO: Needs a "if X11_GFX == 'nvidia'" here. The workaround is only needed on Ubuntu+NVidia drivers. Other drivers are not affected, but fine with this fix.
  58. import ctypes
  59. from ctypes.util import find_library
  60. ctypes.CDLL(find_library('GL'), ctypes.RTLD_GLOBAL)
  61. try:
  62. from cura.CuraVersion import CuraVersion, CuraBuildType
  63. except ImportError:
  64. CuraVersion = "master" # [CodeStyle: Reflecting imported value]
  65. CuraBuildType = ""
  66. class CuraApplication(QtApplication):
  67. class ResourceTypes:
  68. QmlFiles = Resources.UserType + 1
  69. Firmware = Resources.UserType + 2
  70. QualityInstanceContainer = Resources.UserType + 3
  71. MaterialInstanceContainer = Resources.UserType + 4
  72. VariantInstanceContainer = Resources.UserType + 5
  73. UserInstanceContainer = Resources.UserType + 6
  74. MachineStack = Resources.UserType + 7
  75. ExtruderStack = Resources.UserType + 8
  76. Q_ENUMS(ResourceTypes)
  77. def __init__(self):
  78. Resources.addSearchPath(os.path.join(QtApplication.getInstallPrefix(), "share", "cura", "resources"))
  79. if not hasattr(sys, "frozen"):
  80. Resources.addSearchPath(os.path.join(os.path.abspath(os.path.dirname(__file__)), "..", "resources"))
  81. self._open_file_queue = [] # Files to open when plug-ins are loaded.
  82. # Need to do this before ContainerRegistry tries to load the machines
  83. SettingDefinition.addSupportedProperty("settable_per_mesh", DefinitionPropertyType.Any, default = True)
  84. SettingDefinition.addSupportedProperty("settable_per_extruder", DefinitionPropertyType.Any, default = True)
  85. SettingDefinition.addSupportedProperty("settable_per_meshgroup", DefinitionPropertyType.Any, default = True)
  86. SettingDefinition.addSupportedProperty("settable_globally", DefinitionPropertyType.Any, default = True)
  87. SettingDefinition.addSettingType("extruder", int, str, Validator)
  88. ## Add the 4 types of profiles to storage.
  89. Resources.addStorageType(self.ResourceTypes.QualityInstanceContainer, "quality")
  90. Resources.addStorageType(self.ResourceTypes.VariantInstanceContainer, "variants")
  91. Resources.addStorageType(self.ResourceTypes.MaterialInstanceContainer, "materials")
  92. Resources.addStorageType(self.ResourceTypes.UserInstanceContainer, "user")
  93. Resources.addStorageType(self.ResourceTypes.ExtruderStack, "extruders")
  94. Resources.addStorageType(self.ResourceTypes.MachineStack, "machine_instances")
  95. ContainerRegistry.getInstance().addResourceType(self.ResourceTypes.QualityInstanceContainer)
  96. ContainerRegistry.getInstance().addResourceType(self.ResourceTypes.VariantInstanceContainer)
  97. ContainerRegistry.getInstance().addResourceType(self.ResourceTypes.MaterialInstanceContainer)
  98. ContainerRegistry.getInstance().addResourceType(self.ResourceTypes.UserInstanceContainer)
  99. ContainerRegistry.getInstance().addResourceType(self.ResourceTypes.ExtruderStack)
  100. ContainerRegistry.getInstance().addResourceType(self.ResourceTypes.MachineStack)
  101. ## Initialise the version upgrade manager with Cura's storage paths.
  102. import UM.VersionUpgradeManager #Needs to be here to prevent circular dependencies.
  103. self._version_upgrade_manager = UM.VersionUpgradeManager.VersionUpgradeManager(
  104. {
  105. ("quality", UM.Settings.InstanceContainer.Version): (self.ResourceTypes.QualityInstanceContainer, "application/x-uranium-instancecontainer"),
  106. ("machine_stack", UM.Settings.ContainerStack.Version): (self.ResourceTypes.MachineStack, "application/x-uranium-containerstack"),
  107. ("preferences", UM.Preferences.Version): (Resources.Preferences, "application/x-uranium-preferences")
  108. }
  109. )
  110. self._machine_action_manager = MachineActionManager.MachineActionManager()
  111. super().__init__(name = "cura", version = CuraVersion, buildtype = CuraBuildType)
  112. self.setWindowIcon(QIcon(Resources.getPath(Resources.Images, "cura-icon.png")))
  113. self.setRequiredPlugins([
  114. "CuraEngineBackend",
  115. "MeshView",
  116. "LayerView",
  117. "STLReader",
  118. "SelectionTool",
  119. "CameraTool",
  120. "GCodeWriter",
  121. "LocalFileOutputDevice"
  122. ])
  123. self._physics = None
  124. self._volume = None
  125. self._platform = None
  126. self._output_devices = {}
  127. self._print_information = None
  128. self._previous_active_tool = None
  129. self._platform_activity = False
  130. self._scene_bounding_box = AxisAlignedBox.Null
  131. self._job_name = None
  132. self._center_after_select = False
  133. self._camera_animation = None
  134. self._cura_actions = None
  135. self._started = False
  136. self._i18n_catalog = i18nCatalog("cura")
  137. self.getController().getScene().sceneChanged.connect(self.updatePlatformActivity)
  138. self.getController().toolOperationStopped.connect(self._onToolOperationStopped)
  139. Resources.addType(self.ResourceTypes.QmlFiles, "qml")
  140. Resources.addType(self.ResourceTypes.Firmware, "firmware")
  141. self.showSplashMessage(self._i18n_catalog.i18nc("@info:progress", "Loading machines..."))
  142. # Add empty variant, material and quality containers.
  143. # Since they are empty, they should never be serialized and instead just programmatically created.
  144. # We need them to simplify the switching between materials.
  145. empty_container = ContainerRegistry.getInstance().getEmptyInstanceContainer()
  146. empty_variant_container = copy.deepcopy(empty_container)
  147. empty_variant_container._id = "empty_variant"
  148. empty_variant_container.addMetaDataEntry("type", "variant")
  149. ContainerRegistry.getInstance().addContainer(empty_variant_container)
  150. empty_material_container = copy.deepcopy(empty_container)
  151. empty_material_container._id = "empty_material"
  152. empty_material_container.addMetaDataEntry("type", "material")
  153. ContainerRegistry.getInstance().addContainer(empty_material_container)
  154. empty_quality_container = copy.deepcopy(empty_container)
  155. empty_quality_container._id = "empty_quality"
  156. empty_quality_container.addMetaDataEntry("type", "quality")
  157. ContainerRegistry.getInstance().addContainer(empty_quality_container)
  158. ContainerRegistry.getInstance().load()
  159. Preferences.getInstance().addPreference("cura/active_mode", "simple")
  160. Preferences.getInstance().addPreference("cura/recent_files", "")
  161. Preferences.getInstance().addPreference("cura/categories_expanded", "")
  162. Preferences.getInstance().addPreference("cura/jobname_prefix", True)
  163. Preferences.getInstance().addPreference("view/center_on_select", True)
  164. Preferences.getInstance().addPreference("mesh/scale_to_fit", True)
  165. Preferences.getInstance().addPreference("mesh/scale_tiny_meshes", True)
  166. Preferences.getInstance().setDefault("local_file/last_used_type", "text/x-gcode")
  167. Preferences.getInstance().setDefault("general/visible_settings", """
  168. machine_settings
  169. resolution
  170. layer_height
  171. shell
  172. wall_thickness
  173. top_bottom_thickness
  174. infill
  175. infill_sparse_density
  176. material
  177. material_print_temperature
  178. material_bed_temperature
  179. material_diameter
  180. material_flow
  181. retraction_enable
  182. speed
  183. speed_print
  184. speed_travel
  185. acceleration_print
  186. acceleration_travel
  187. jerk_print
  188. jerk_travel
  189. travel
  190. cooling
  191. cool_fan_enabled
  192. support
  193. support_enable
  194. support_type
  195. support_roof_density
  196. platform_adhesion
  197. adhesion_type
  198. brim_width
  199. raft_airgap
  200. layer_0_z_overlap
  201. raft_surface_layers
  202. meshfix
  203. blackmagic
  204. print_sequence
  205. dual
  206. experimental
  207. """.replace("\n", ";").replace(" ", ""))
  208. JobQueue.getInstance().jobFinished.connect(self._onJobFinished)
  209. self.applicationShuttingDown.connect(self.saveSettings)
  210. self.engineCreatedSignal.connect(self._onEngineCreated)
  211. self._recent_files = []
  212. files = Preferences.getInstance().getValue("cura/recent_files").split(";")
  213. for f in files:
  214. if not os.path.isfile(f):
  215. continue
  216. self._recent_files.append(QUrl.fromLocalFile(f))
  217. def _onEngineCreated(self):
  218. self._engine.addImageProvider("camera", CameraImageProvider.CameraImageProvider())
  219. showPrintMonitor = pyqtSignal(bool, arguments = ["show"])
  220. ## Cura has multiple locations where instance containers need to be saved, so we need to handle this differently.
  221. #
  222. # Note that the AutoSave plugin also calls this method.
  223. def saveSettings(self):
  224. if not self._started: # Do not do saving during application start
  225. return
  226. for instance in ContainerRegistry.getInstance().findInstanceContainers():
  227. if not instance.isDirty():
  228. continue
  229. try:
  230. data = instance.serialize()
  231. except NotImplementedError:
  232. continue
  233. except Exception:
  234. Logger.logException("e", "An exception occurred when serializing container %s", instance.getId())
  235. continue
  236. file_name = urllib.parse.quote_plus(instance.getId()) + ".inst.cfg"
  237. instance_type = instance.getMetaDataEntry("type")
  238. path = None
  239. if instance_type == "material":
  240. path = Resources.getStoragePath(self.ResourceTypes.MaterialInstanceContainer, file_name)
  241. elif instance_type == "quality":
  242. path = Resources.getStoragePath(self.ResourceTypes.QualityInstanceContainer, file_name)
  243. elif instance_type == "user":
  244. path = Resources.getStoragePath(self.ResourceTypes.UserInstanceContainer, file_name)
  245. elif instance_type == "variant":
  246. path = Resources.getStoragePath(self.ResourceTypes.VariantInstanceContainer, file_name)
  247. if path:
  248. with SaveFile(path, "wt", -1, "utf-8") as f:
  249. f.write(data)
  250. for stack in ContainerRegistry.getInstance().findContainerStacks():
  251. if not stack.isDirty():
  252. continue
  253. try:
  254. data = stack.serialize()
  255. except NotImplementedError:
  256. continue
  257. except Exception:
  258. Logger.logException("e", "An exception occurred when serializing container %s", instance.getId())
  259. continue
  260. file_name = urllib.parse.quote_plus(stack.getId()) + ".stack.cfg"
  261. stack_type = stack.getMetaDataEntry("type", None)
  262. path = None
  263. if not stack_type or stack_type == "machine":
  264. path = Resources.getStoragePath(self.ResourceTypes.MachineStack, file_name)
  265. elif stack_type == "extruder_train":
  266. path = Resources.getStoragePath(self.ResourceTypes.ExtruderStack, file_name)
  267. if path:
  268. with SaveFile(path, "wt", -1, "utf-8") as f:
  269. f.write(data)
  270. @pyqtSlot(result = QUrl)
  271. def getDefaultPath(self):
  272. return QUrl.fromLocalFile(os.path.expanduser("~/"))
  273. ## Handle loading of all plugin types (and the backend explicitly)
  274. # \sa PluginRegistery
  275. def _loadPlugins(self):
  276. self._plugin_registry.addType("profile_reader", self._addProfileReader)
  277. self._plugin_registry.addType("profile_writer", self._addProfileWriter)
  278. self._plugin_registry.addPluginLocation(os.path.join(QtApplication.getInstallPrefix(), "lib", "cura"))
  279. if not hasattr(sys, "frozen"):
  280. self._plugin_registry.addPluginLocation(os.path.join(os.path.abspath(os.path.dirname(__file__)), "..", "plugins"))
  281. self._plugin_registry.loadPlugin("ConsoleLogger")
  282. self._plugin_registry.loadPlugin("CuraEngineBackend")
  283. self._plugin_registry.loadPlugins()
  284. if self.getBackend() == None:
  285. raise RuntimeError("Could not load the backend plugin!")
  286. self._plugins_loaded = True
  287. def addCommandLineOptions(self, parser):
  288. super().addCommandLineOptions(parser)
  289. parser.add_argument("file", nargs="*", help="Files to load after starting the application.")
  290. parser.add_argument("--debug", dest="debug-mode", action="store_true", default=False, help="Enable detailed crash reports.")
  291. def run(self):
  292. self.showSplashMessage(self._i18n_catalog.i18nc("@info:progress", "Setting up scene..."))
  293. controller = self.getController()
  294. controller.setActiveView("SolidView")
  295. controller.setCameraTool("CameraTool")
  296. controller.setSelectionTool("SelectionTool")
  297. t = controller.getTool("TranslateTool")
  298. if t:
  299. t.setEnabledAxis([ToolHandle.XAxis, ToolHandle.YAxis,ToolHandle.ZAxis])
  300. Selection.selectionChanged.connect(self.onSelectionChanged)
  301. root = controller.getScene().getRoot()
  302. self._platform = Scene_Platform(root)
  303. self._volume = BuildVolume.BuildVolume(root)
  304. self.getRenderer().setBackgroundColor(QColor(245, 245, 245))
  305. self._physics = PlatformPhysics.PlatformPhysics(controller, self._volume)
  306. camera = Camera("3d", root)
  307. camera.setPosition(Vector(-80, 250, 700))
  308. camera.setPerspective(True)
  309. camera.lookAt(Vector(0, 0, 0))
  310. controller.getScene().setActiveCamera("3d")
  311. self.getController().getTool("CameraTool").setOrigin(Vector(0, 100, 0))
  312. self._camera_animation = CameraAnimation.CameraAnimation()
  313. self._camera_animation.setCameraTool(self.getController().getTool("CameraTool"))
  314. self.showSplashMessage(self._i18n_catalog.i18nc("@info:progress", "Loading interface..."))
  315. # Initialise extruder so as to listen to global container stack changes before the first global container stack is set.
  316. ExtruderManager.ExtruderManager.getInstance()
  317. qmlRegisterSingletonType(MachineManagerModel.MachineManagerModel, "Cura", 1, 0, "MachineManager",
  318. MachineManagerModel.createMachineManagerModel)
  319. qmlRegisterSingletonType(MachineActionManager.MachineActionManager, "Cura", 1, 0, "MachineActionManager", self.getMachineActionManager)
  320. self.setMainQml(Resources.getPath(self.ResourceTypes.QmlFiles, "Cura.qml"))
  321. self._qml_import_paths.append(Resources.getPath(self.ResourceTypes.QmlFiles))
  322. self.initializeEngine()
  323. if self._engine.rootObjects:
  324. self.closeSplash()
  325. for file in self.getCommandLineOption("file", []):
  326. self._openFile(file)
  327. for file_name in self._open_file_queue: #Open all the files that were queued up while plug-ins were loading.
  328. self._openFile(file_name)
  329. self._started = True
  330. self.exec_()
  331. ## Get the machine action manager
  332. # We ignore any *args given to this, as we also register the machine manager as qml singleton.
  333. # It wants to give this function an engine and script engine, but we don't care about that.
  334. def getMachineActionManager(self, *args):
  335. return self._machine_action_manager
  336. ## Handle Qt events
  337. def event(self, event):
  338. if event.type() == QEvent.FileOpen:
  339. if self._plugins_loaded:
  340. self._openFile(event.file())
  341. else:
  342. self._open_file_queue.append(event.file())
  343. return super().event(event)
  344. ## Get print information (duration / material used)
  345. def getPrintInformation(self):
  346. return self._print_information
  347. ## Registers objects for the QML engine to use.
  348. #
  349. # \param engine The QML engine.
  350. def registerObjects(self, engine):
  351. engine.rootContext().setContextProperty("Printer", self)
  352. self._print_information = PrintInformation.PrintInformation()
  353. engine.rootContext().setContextProperty("PrintInformation", self._print_information)
  354. self._cura_actions = CuraActions.CuraActions(self)
  355. engine.rootContext().setContextProperty("CuraActions", self._cura_actions)
  356. qmlRegisterUncreatableType(CuraApplication, "Cura", 1, 0, "ResourceTypes", "Just an Enum type")
  357. qmlRegisterType(ExtrudersModel.ExtrudersModel, "Cura", 1, 0, "ExtrudersModel")
  358. qmlRegisterType(ContainerSettingsModel.ContainerSettingsModel, "Cura", 1, 0, "ContainerSettingsModel")
  359. qmlRegisterSingletonType(QUrl.fromLocalFile(Resources.getPath(CuraApplication.ResourceTypes.QmlFiles, "Actions.qml")), "Cura", 1, 0, "Actions")
  360. engine.rootContext().setContextProperty("ExtruderManager", ExtruderManager.ExtruderManager.getInstance())
  361. for path in Resources.getAllResourcesOfType(CuraApplication.ResourceTypes.QmlFiles):
  362. type_name = os.path.splitext(os.path.basename(path))[0]
  363. if type_name in ("Cura", "Actions"):
  364. continue
  365. qmlRegisterType(QUrl.fromLocalFile(path), "Cura", 1, 0, type_name)
  366. def onSelectionChanged(self):
  367. if Selection.hasSelection():
  368. if not self.getController().getActiveTool():
  369. if self._previous_active_tool:
  370. self.getController().setActiveTool(self._previous_active_tool)
  371. self._previous_active_tool = None
  372. else:
  373. self.getController().setActiveTool("TranslateTool")
  374. if Preferences.getInstance().getValue("view/center_on_select"):
  375. self._center_after_select = True
  376. else:
  377. if self.getController().getActiveTool():
  378. self._previous_active_tool = self.getController().getActiveTool().getPluginId()
  379. self.getController().setActiveTool(None)
  380. else:
  381. self._previous_active_tool = None
  382. def _onToolOperationStopped(self, event):
  383. if self._center_after_select:
  384. self._center_after_select = False
  385. self._camera_animation.setStart(self.getController().getTool("CameraTool").getOrigin())
  386. self._camera_animation.setTarget(Selection.getSelectedObject(0).getWorldPosition())
  387. self._camera_animation.start()
  388. requestAddPrinter = pyqtSignal()
  389. activityChanged = pyqtSignal()
  390. sceneBoundingBoxChanged = pyqtSignal()
  391. @pyqtProperty(bool, notify = activityChanged)
  392. def getPlatformActivity(self):
  393. return self._platform_activity
  394. @pyqtProperty(str, notify = sceneBoundingBoxChanged)
  395. def getSceneBoundingBoxString(self):
  396. return self._i18n_catalog.i18nc("@info", "%(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()}
  397. def updatePlatformActivity(self, node = None):
  398. count = 0
  399. scene_bounding_box = None
  400. for node in DepthFirstIterator(self.getController().getScene().getRoot()):
  401. if type(node) is not SceneNode or not node.getMeshData():
  402. continue
  403. count += 1
  404. if not scene_bounding_box:
  405. scene_bounding_box = node.getBoundingBox()
  406. else:
  407. other_bb = node.getBoundingBox()
  408. if other_bb is not None:
  409. scene_bounding_box = scene_bounding_box + node.getBoundingBox()
  410. if not scene_bounding_box:
  411. scene_bounding_box = AxisAlignedBox.Null
  412. if repr(self._scene_bounding_box) != repr(scene_bounding_box):
  413. self._scene_bounding_box = scene_bounding_box
  414. self.sceneBoundingBoxChanged.emit()
  415. self._platform_activity = True if count > 0 else False
  416. self.activityChanged.emit()
  417. # Remove all selected objects from the scene.
  418. @pyqtSlot()
  419. def deleteSelection(self):
  420. if not self.getController().getToolsEnabled():
  421. return
  422. op = GroupedOperation()
  423. nodes = Selection.getAllSelectedObjects()
  424. for node in nodes:
  425. op.addOperation(RemoveSceneNodeOperation(node))
  426. op.push()
  427. pass
  428. ## Remove an object from the scene.
  429. # Note that this only removes an object if it is selected.
  430. @pyqtSlot("quint64")
  431. def deleteObject(self, object_id):
  432. if not self.getController().getToolsEnabled():
  433. return
  434. node = self.getController().getScene().findObject(object_id)
  435. if not node and object_id != 0: # Workaround for tool handles overlapping the selected object
  436. node = Selection.getSelectedObject(0)
  437. if node:
  438. if node.getParent():
  439. group_node = node.getParent()
  440. if not group_node.callDecoration("isGroup"):
  441. op = RemoveSceneNodeOperation(node)
  442. else:
  443. while group_node.getParent().callDecoration("isGroup"):
  444. group_node = group_node.getParent()
  445. op = RemoveSceneNodeOperation(group_node)
  446. op.push()
  447. ## Create a number of copies of existing object.
  448. @pyqtSlot("quint64", int)
  449. def multiplyObject(self, object_id, count):
  450. node = self.getController().getScene().findObject(object_id)
  451. if not node and object_id != 0: # Workaround for tool handles overlapping the selected object
  452. node = Selection.getSelectedObject(0)
  453. if node:
  454. op = GroupedOperation()
  455. for _ in range(count):
  456. if node.getParent() and node.getParent().callDecoration("isGroup"):
  457. new_node = copy.deepcopy(node.getParent()) #Copy the group node.
  458. new_node.callDecoration("recomputeConvexHull")
  459. op.addOperation(AddSceneNodeOperation(new_node,node.getParent().getParent()))
  460. else:
  461. new_node = copy.deepcopy(node)
  462. new_node.callDecoration("recomputeConvexHull")
  463. op.addOperation(AddSceneNodeOperation(new_node, node.getParent()))
  464. op.push()
  465. ## Center object on platform.
  466. @pyqtSlot("quint64")
  467. def centerObject(self, object_id):
  468. node = self.getController().getScene().findObject(object_id)
  469. if not node and object_id != 0: # Workaround for tool handles overlapping the selected object
  470. node = Selection.getSelectedObject(0)
  471. if not node:
  472. return
  473. if node.getParent() and node.getParent().callDecoration("isGroup"):
  474. node = node.getParent()
  475. if node:
  476. op = SetTransformOperation(node, Vector())
  477. op.push()
  478. ## Delete all nodes containing mesh data in the scene.
  479. @pyqtSlot()
  480. def deleteAll(self):
  481. if not self.getController().getToolsEnabled():
  482. return
  483. nodes = []
  484. for node in DepthFirstIterator(self.getController().getScene().getRoot()):
  485. if type(node) is not SceneNode:
  486. continue
  487. if not node.getMeshData() and not node.callDecoration("isGroup"):
  488. continue # Node that doesnt have a mesh and is not a group.
  489. if node.getParent() and node.getParent().callDecoration("isGroup"):
  490. continue # Grouped nodes don't need resetting as their parent (the group) is resetted)
  491. nodes.append(node)
  492. if nodes:
  493. op = GroupedOperation()
  494. for node in nodes:
  495. op.addOperation(RemoveSceneNodeOperation(node))
  496. op.push()
  497. ## Reset all translation on nodes with mesh data.
  498. @pyqtSlot()
  499. def resetAllTranslation(self):
  500. nodes = []
  501. for node in DepthFirstIterator(self.getController().getScene().getRoot()):
  502. if type(node) is not SceneNode:
  503. continue
  504. if not node.getMeshData() and not node.callDecoration("isGroup"):
  505. continue # Node that doesnt have a mesh and is not a group.
  506. if node.getParent() and node.getParent().callDecoration("isGroup"):
  507. continue # Grouped nodes don't need resetting as their parent (the group) is resetted)
  508. nodes.append(node)
  509. if nodes:
  510. op = GroupedOperation()
  511. for node in nodes:
  512. node.removeDecorator(ZOffsetDecorator.ZOffsetDecorator)
  513. op.addOperation(SetTransformOperation(node, Vector(0,0,0)))
  514. op.push()
  515. ## Reset all transformations on nodes with mesh data.
  516. @pyqtSlot()
  517. def resetAll(self):
  518. nodes = []
  519. for node in DepthFirstIterator(self.getController().getScene().getRoot()):
  520. if type(node) is not SceneNode:
  521. continue
  522. if not node.getMeshData() and not node.callDecoration("isGroup"):
  523. continue # Node that doesnt have a mesh and is not a group.
  524. if node.getParent() and node.getParent().callDecoration("isGroup"):
  525. continue # Grouped nodes don't need resetting as their parent (the group) is resetted)
  526. nodes.append(node)
  527. if nodes:
  528. op = GroupedOperation()
  529. for node in nodes:
  530. # Ensure that the object is above the build platform
  531. node.removeDecorator(ZOffsetDecorator.ZOffsetDecorator)
  532. op.addOperation(SetTransformOperation(node, Vector(0,0,0), Quaternion(), Vector(1, 1, 1)))
  533. op.push()
  534. ## Reload all mesh data on the screen from file.
  535. @pyqtSlot()
  536. def reloadAll(self):
  537. nodes = []
  538. for node in DepthFirstIterator(self.getController().getScene().getRoot()):
  539. if type(node) is not SceneNode or not node.getMeshData():
  540. continue
  541. nodes.append(node)
  542. if not nodes:
  543. return
  544. for node in nodes:
  545. if not node.getMeshData():
  546. continue
  547. file_name = node.getMeshData().getFileName()
  548. if file_name:
  549. job = ReadMeshJob(file_name)
  550. job._node = node
  551. job.finished.connect(self._reloadMeshFinished)
  552. job.start()
  553. ## Get logging data of the backend engine
  554. # \returns \type{string} Logging data
  555. @pyqtSlot(result = str)
  556. def getEngineLog(self):
  557. log = ""
  558. for entry in self.getBackend().getLog():
  559. log += entry.decode()
  560. return log
  561. recentFilesChanged = pyqtSignal()
  562. @pyqtProperty("QVariantList", notify = recentFilesChanged)
  563. def recentFiles(self):
  564. return self._recent_files
  565. @pyqtSlot("QStringList")
  566. def setExpandedCategories(self, categories):
  567. categories = list(set(categories))
  568. categories.sort()
  569. joined = ";".join(categories)
  570. if joined != Preferences.getInstance().getValue("cura/categories_expanded"):
  571. Preferences.getInstance().setValue("cura/categories_expanded", joined)
  572. self.expandedCategoriesChanged.emit()
  573. expandedCategoriesChanged = pyqtSignal()
  574. @pyqtProperty("QStringList", notify = expandedCategoriesChanged)
  575. def expandedCategories(self):
  576. return Preferences.getInstance().getValue("cura/categories_expanded").split(";")
  577. @pyqtSlot()
  578. def mergeSelected(self):
  579. self.groupSelected()
  580. try:
  581. group_node = Selection.getAllSelectedObjects()[0]
  582. except Exception as e:
  583. Logger.log("d", "mergeSelected: Exception:", e)
  584. return
  585. multi_material_decorator = MultiMaterialDecorator.MultiMaterialDecorator()
  586. group_node.addDecorator(multi_material_decorator)
  587. # Reset the position of each node
  588. for node in group_node.getChildren():
  589. new_position = node.getMeshData().getCenterPosition()
  590. new_position = new_position.scale(node.getScale())
  591. node.setPosition(new_position)
  592. # Use the previously found center of the group bounding box as the new location of the group
  593. group_node.setPosition(group_node.getBoundingBox().center)
  594. @pyqtSlot()
  595. def groupSelected(self):
  596. # Create a group-node
  597. group_node = SceneNode()
  598. group_decorator = GroupDecorator()
  599. group_node.addDecorator(group_decorator)
  600. group_node.setParent(self.getController().getScene().getRoot())
  601. group_node.setSelectable(True)
  602. center = Selection.getSelectionCenter()
  603. group_node.setPosition(center)
  604. group_node.setCenterPosition(center)
  605. # Move selected nodes into the group-node
  606. Selection.applyOperation(SetParentOperation, group_node)
  607. # Deselect individual nodes and select the group-node instead
  608. for node in group_node.getChildren():
  609. Selection.remove(node)
  610. Selection.add(group_node)
  611. @pyqtSlot()
  612. def ungroupSelected(self):
  613. selected_objects = Selection.getAllSelectedObjects().copy()
  614. for node in selected_objects:
  615. if node.callDecoration("isGroup"):
  616. op = GroupedOperation()
  617. group_parent = node.getParent()
  618. children = node.getChildren().copy()
  619. for child in children:
  620. # Set the parent of the children to the parent of the group-node
  621. op.addOperation(SetParentOperation(child, group_parent))
  622. # Add all individual nodes to the selection
  623. Selection.add(child)
  624. op.push()
  625. # Note: The group removes itself from the scene once all its children have left it,
  626. # see GroupDecorator._onChildrenChanged
  627. def _createSplashScreen(self):
  628. return CuraSplashScreen.CuraSplashScreen()
  629. def _onActiveMachineChanged(self):
  630. pass
  631. fileLoaded = pyqtSignal(str)
  632. def _onFileLoaded(self, job):
  633. node = job.getResult()
  634. if node != None:
  635. self.fileLoaded.emit(job.getFileName())
  636. node.setSelectable(True)
  637. node.setName(os.path.basename(job.getFileName()))
  638. op = AddSceneNodeOperation(node, self.getController().getScene().getRoot())
  639. op.push()
  640. self.getController().getScene().sceneChanged.emit(node) #Force scene change.
  641. def _onJobFinished(self, job):
  642. if type(job) is not ReadMeshJob or not job.getResult():
  643. return
  644. f = QUrl.fromLocalFile(job.getFileName())
  645. if f in self._recent_files:
  646. self._recent_files.remove(f)
  647. self._recent_files.insert(0, f)
  648. if len(self._recent_files) > 10:
  649. del self._recent_files[10]
  650. pref = ""
  651. for path in self._recent_files:
  652. pref += path.toLocalFile() + ";"
  653. Preferences.getInstance().setValue("cura/recent_files", pref)
  654. self.recentFilesChanged.emit()
  655. def _reloadMeshFinished(self, job):
  656. # TODO; This needs to be fixed properly. We now make the assumption that we only load a single mesh!
  657. job._node.setMeshData(job.getResult().getMeshData())
  658. def _openFile(self, file):
  659. job = ReadMeshJob(os.path.abspath(file))
  660. job.finished.connect(self._onFileLoaded)
  661. job.start()
  662. def _addProfileReader(self, profile_reader):
  663. # TODO: Add the profile reader to the list of plug-ins that can be used when importing profiles.
  664. pass
  665. def _addProfileWriter(self, profile_writer):
  666. pass
  667. @pyqtSlot("QSize")
  668. def setMinimumWindowSize(self, size):
  669. self.getMainWindow().setMinimumSize(size)