CuraApplication.py 33 KB

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