CuraActions.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. # Copyright (c) 2023 UltiMaker
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. from typing import List, cast
  4. from PyQt6.QtCore import QObject, QUrl, QMimeData
  5. from PyQt6.QtGui import QDesktopServices
  6. from PyQt6.QtWidgets import QApplication
  7. from UM.Event import CallFunctionEvent
  8. from UM.FlameProfiler import pyqtSlot
  9. from UM.Math.Vector import Vector
  10. from UM.Scene.Selection import Selection
  11. from UM.Scene.Iterator.BreadthFirstIterator import BreadthFirstIterator
  12. from UM.Scene.Iterator.DepthFirstIterator import DepthFirstIterator
  13. from UM.Operations.GroupedOperation import GroupedOperation
  14. from UM.Operations.RemoveSceneNodeOperation import RemoveSceneNodeOperation
  15. from UM.Operations.TranslateOperation import TranslateOperation
  16. import cura.CuraApplication
  17. from cura.Operations.SetParentOperation import SetParentOperation
  18. from cura.MultiplyObjectsJob import MultiplyObjectsJob
  19. from cura.Settings.SetObjectExtruderOperation import SetObjectExtruderOperation
  20. from cura.Settings.ExtruderManager import ExtruderManager
  21. from cura.Arranging.Nest2DArrange import createGroupOperationForArrange
  22. from cura.Operations.SetBuildPlateNumberOperation import SetBuildPlateNumberOperation
  23. from UM.Logger import Logger
  24. from UM.Scene.SceneNode import SceneNode
  25. class CuraActions(QObject):
  26. def __init__(self, parent: QObject = None) -> None:
  27. super().__init__(parent)
  28. @pyqtSlot()
  29. def openDocumentation(self) -> None:
  30. # Starting a web browser from a signal handler connected to a menu will crash on windows.
  31. # So instead, defer the call to the next run of the event loop, since that does work.
  32. # Note that weirdly enough, only signal handlers that open a web browser fail like that.
  33. event = CallFunctionEvent(self._openUrl, [QUrl("https://ultimaker.com/en/resources/manuals/software?utm_source=cura&utm_medium=software&utm_campaign=dropdown-documentation")], {})
  34. cura.CuraApplication.CuraApplication.getInstance().functionEvent(event)
  35. @pyqtSlot()
  36. def openBugReportPage(self) -> None:
  37. event = CallFunctionEvent(self._openUrl, [QUrl("https://github.com/Ultimaker/Cura/issues/new/choose")], {})
  38. cura.CuraApplication.CuraApplication.getInstance().functionEvent(event)
  39. @pyqtSlot()
  40. def homeCamera(self) -> None:
  41. """Reset camera position and direction to default"""
  42. scene = cura.CuraApplication.CuraApplication.getInstance().getController().getScene()
  43. camera = scene.getActiveCamera()
  44. if camera:
  45. diagonal_size = cura.CuraApplication.CuraApplication.getInstance().getBuildVolume().getDiagonalSize()
  46. camera.setPosition(Vector(-80, 250, 700) * diagonal_size / 375)
  47. camera.setPerspective(True)
  48. camera.lookAt(Vector(0, 0, 0))
  49. @pyqtSlot()
  50. def centerSelection(self) -> None:
  51. """Center all objects in the selection"""
  52. operation = GroupedOperation()
  53. for node in Selection.getAllSelectedObjects():
  54. current_node = node
  55. parent_node = current_node.getParent()
  56. while parent_node and parent_node.callDecoration("isGroup"):
  57. current_node = parent_node
  58. parent_node = current_node.getParent()
  59. # Find out where the bottom of the object is
  60. bbox = current_node.getBoundingBox()
  61. if bbox:
  62. center_y = current_node.getWorldPosition().y - bbox.bottom
  63. else:
  64. center_y = 0
  65. # Move the object so that it's bottom is on to of the buildplate
  66. center_operation = TranslateOperation(current_node, Vector(0, center_y, 0), set_position = True)
  67. operation.addOperation(center_operation)
  68. operation.push()
  69. @pyqtSlot(int)
  70. def multiplySelection(self, count: int) -> None:
  71. """Multiply all objects in the selection
  72. :param count: The number of times to multiply the selection.
  73. """
  74. min_offset = cura.CuraApplication.CuraApplication.getInstance().getBuildVolume().getEdgeDisallowedSize() + 2 # Allow for some rounding errors
  75. job = MultiplyObjectsJob(Selection.getAllSelectedObjects(), count, min_offset = max(min_offset, 8))
  76. job.start()
  77. @pyqtSlot()
  78. def deleteSelection(self) -> None:
  79. """Delete all selected objects."""
  80. if not cura.CuraApplication.CuraApplication.getInstance().getController().getToolsEnabled():
  81. return
  82. removed_group_nodes = [] #type: List[SceneNode]
  83. op = GroupedOperation()
  84. nodes = Selection.getAllSelectedObjects()
  85. for node in nodes:
  86. op.addOperation(RemoveSceneNodeOperation(node))
  87. group_node = node.getParent()
  88. if group_node and group_node.callDecoration("isGroup") and group_node not in removed_group_nodes:
  89. remaining_nodes_in_group = list(set(group_node.getChildren()) - set(nodes))
  90. if len(remaining_nodes_in_group) == 1:
  91. removed_group_nodes.append(group_node)
  92. op.addOperation(SetParentOperation(remaining_nodes_in_group[0], group_node.getParent()))
  93. op.addOperation(RemoveSceneNodeOperation(group_node))
  94. # Reset the print information
  95. cura.CuraApplication.CuraApplication.getInstance().getController().getScene().sceneChanged.emit(node)
  96. op.push()
  97. @pyqtSlot(str)
  98. def setExtruderForSelection(self, extruder_id: str) -> None:
  99. """Set the extruder that should be used to print the selection.
  100. :param extruder_id: The ID of the extruder stack to use for the selected objects.
  101. """
  102. operation = GroupedOperation()
  103. nodes_to_change = []
  104. for node in Selection.getAllSelectedObjects():
  105. # If the node is a group, apply the active extruder to all children of the group.
  106. if node.callDecoration("isGroup"):
  107. for grouped_node in BreadthFirstIterator(node): #type: ignore #Ignore type error because iter() should get called automatically by Python syntax.
  108. if grouped_node.callDecoration("getActiveExtruder") == extruder_id:
  109. continue
  110. if grouped_node.callDecoration("isGroup"):
  111. continue
  112. nodes_to_change.append(grouped_node)
  113. continue
  114. # Do not change any nodes that already have the right extruder set.
  115. if node.callDecoration("getActiveExtruder") == extruder_id:
  116. continue
  117. nodes_to_change.append(node)
  118. if not nodes_to_change:
  119. # If there are no changes to make, we still need to reset the selected extruders.
  120. # This is a workaround for checked menu items being deselected while still being
  121. # selected.
  122. ExtruderManager.getInstance().resetSelectedObjectExtruders()
  123. return
  124. for node in nodes_to_change:
  125. operation.addOperation(SetObjectExtruderOperation(node, extruder_id))
  126. operation.push()
  127. @pyqtSlot(int)
  128. def setBuildPlateForSelection(self, build_plate_nr: int) -> None:
  129. Logger.log("d", "Setting build plate number... %d" % build_plate_nr)
  130. operation = GroupedOperation()
  131. root = cura.CuraApplication.CuraApplication.getInstance().getController().getScene().getRoot()
  132. nodes_to_change = [] # type: List[SceneNode]
  133. for node in Selection.getAllSelectedObjects():
  134. parent_node = node # Find the parent node to change instead
  135. while parent_node.getParent() != root:
  136. parent_node = cast(SceneNode, parent_node.getParent())
  137. for single_node in BreadthFirstIterator(parent_node): # type: ignore #Ignore type error because iter() should get called automatically by Python syntax.
  138. nodes_to_change.append(single_node)
  139. if not nodes_to_change:
  140. Logger.log("d", "Nothing to change.")
  141. return
  142. for node in nodes_to_change:
  143. operation.addOperation(SetBuildPlateNumberOperation(node, build_plate_nr))
  144. operation.push()
  145. Selection.clear()
  146. @pyqtSlot()
  147. def cut(self) -> None:
  148. self.copy()
  149. self.deleteSelection()
  150. @pyqtSlot()
  151. def copy(self) -> None:
  152. mesh_writer = cura.CuraApplication.CuraApplication.getInstance().getMeshFileHandler().getWriter("3MFWriter")
  153. if not mesh_writer:
  154. Logger.log("e", "No 3MF writer found, unable to copy.")
  155. return
  156. # Get the selected nodes
  157. selected_objects = Selection.getAllSelectedObjects()
  158. # Serialize the nodes to a string
  159. scene_string = mesh_writer.sceneNodesToString(selected_objects)
  160. # Put the string on the clipboard
  161. QApplication.clipboard().setText(scene_string)
  162. @pyqtSlot()
  163. def paste(self) -> None:
  164. application = cura.CuraApplication.CuraApplication.getInstance()
  165. mesh_reader = application.getMeshFileHandler().getReaderForFile(".3mf")
  166. if not mesh_reader:
  167. Logger.log("e", "No 3MF reader found, unable to paste.")
  168. return
  169. # Parse the scene from the clipboard
  170. scene_string = QApplication.clipboard().text()
  171. nodes = mesh_reader.stringToSceneNodes(scene_string)
  172. if not nodes:
  173. # Nothing to paste
  174. return
  175. # Find all fixed nodes, these are the nodes that should be avoided when arranging
  176. fixed_nodes = []
  177. root = application.getController().getScene().getRoot()
  178. for node in DepthFirstIterator(root):
  179. # Only count sliceable objects
  180. if node.callDecoration("isSliceable"):
  181. fixed_nodes.append(node)
  182. # Add the new nodes to the scene, and arrange them
  183. group_operation, not_fit_count = createGroupOperationForArrange(nodes, application.getBuildVolume(),
  184. fixed_nodes, factor=10000,
  185. add_new_nodes_in_scene=True)
  186. group_operation.push()
  187. # deselect currently selected nodes, and select the new nodes
  188. for node in Selection.getAllSelectedObjects():
  189. Selection.remove(node)
  190. for node in nodes:
  191. Selection.add(node)
  192. def _openUrl(self, url: QUrl) -> None:
  193. QDesktopServices.openUrl(url)