CuraApplication.py 34 KB

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