CuraApplication.py 31 KB

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