CuraActions.py 11 KB

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