ObjectsModel.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  1. # Copyright (c) 2019 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. from UM.Logger import Logger
  4. import re
  5. from typing import Any, Dict, List, Optional, Union
  6. from PyQt5.QtCore import QTimer, Qt
  7. from UM.Application import Application
  8. from UM.Qt.ListModel import ListModel
  9. from UM.Scene.Camera import Camera
  10. from UM.Scene.Iterator.DepthFirstIterator import DepthFirstIterator
  11. from UM.Scene.SceneNode import SceneNode
  12. from UM.Scene.Selection import Selection
  13. from UM.i18n import i18nCatalog
  14. catalog = i18nCatalog("cura")
  15. # Simple convenience class to keep stuff together. Since we're still stuck on python 3.5, we can't use the full
  16. # typed named tuple, so we have to do it like this.
  17. # Once we are at python 3.6, feel free to change this to a named tuple.
  18. class _NodeInfo:
  19. def __init__(self, index_to_node: Optional[Dict[int, SceneNode]] = None, nodes_to_rename: Optional[List[SceneNode]] = None, is_group: bool = False) -> None:
  20. if index_to_node is None:
  21. index_to_node = {}
  22. if nodes_to_rename is None:
  23. nodes_to_rename = []
  24. self.index_to_node = index_to_node # type: Dict[int, SceneNode]
  25. self.nodes_to_rename = nodes_to_rename # type: List[SceneNode]
  26. self.is_group = is_group # type: bool
  27. ## Keep track of all objects in the project
  28. class ObjectsModel(ListModel):
  29. NameRole = Qt.UserRole + 1
  30. SelectedRole = Qt.UserRole + 2
  31. OutsideAreaRole = Qt.UserRole + 3
  32. BuilplateNumberRole = Qt.UserRole + 4
  33. NodeRole = Qt.UserRole + 5
  34. def __init__(self, parent = None) -> None:
  35. super().__init__(parent)
  36. self.addRoleName(self.NameRole, "name")
  37. self.addRoleName(self.SelectedRole, "selected")
  38. self.addRoleName(self.OutsideAreaRole, "outside_build_area")
  39. self.addRoleName(self.BuilplateNumberRole, "buildplate_number")
  40. self.addRoleName(self.NodeRole, "node")
  41. Application.getInstance().getController().getScene().sceneChanged.connect(self._updateSceneDelayed)
  42. Application.getInstance().getPreferences().preferenceChanged.connect(self._updateDelayed)
  43. Selection.selectionChanged.connect(self._updateDelayed)
  44. self._update_timer = QTimer()
  45. self._update_timer.setInterval(200)
  46. self._update_timer.setSingleShot(True)
  47. self._update_timer.timeout.connect(self._update)
  48. self._build_plate_number = -1
  49. self._group_name_template = catalog.i18nc("@label", "Group #{group_nr}")
  50. self._group_name_prefix = self._group_name_template.split("#")[0]
  51. self._naming_regex = re.compile("^(.+)\(([0-9]+)\)$")
  52. def setActiveBuildPlate(self, nr: int) -> None:
  53. if self._build_plate_number != nr:
  54. self._build_plate_number = nr
  55. self._update()
  56. def _updateSceneDelayed(self, source) -> None:
  57. if not isinstance(source, Camera):
  58. self._update_timer.start()
  59. def _updateDelayed(self, *args) -> None:
  60. self._update_timer.start()
  61. def _shouldNodeBeHandled(self, node: SceneNode) -> bool:
  62. is_group = bool(node.callDecoration("isGroup"))
  63. if not node.callDecoration("isSliceable") and not is_group:
  64. return False
  65. parent = node.getParent()
  66. if parent and parent.callDecoration("isGroup"):
  67. return False # Grouped nodes don't need resetting as their parent (the group) is resetted)
  68. node_build_plate_number = node.callDecoration("getBuildPlateNumber")
  69. if Application.getInstance().getPreferences().getValue("view/filter_current_build_plate") and node_build_plate_number != self._build_plate_number:
  70. return False
  71. return True
  72. def _renameNodes(self, node_info_dict: Dict[str, _NodeInfo]) -> List[SceneNode]:
  73. # Go through all names and find out the names for all nodes that need to be renamed.
  74. all_nodes = [] # type: List[SceneNode]
  75. for name, node_info in node_info_dict.items():
  76. # First add the ones that do not need to be renamed.
  77. for node in node_info.index_to_node.values():
  78. all_nodes.append(node)
  79. # Generate new names for the nodes that need to be renamed
  80. current_index = 0
  81. for node in node_info.nodes_to_rename:
  82. current_index += 1
  83. while current_index in node_info.index_to_node:
  84. current_index += 1
  85. if not node_info.is_group:
  86. new_group_name = "{0}({1})".format(name, current_index)
  87. else:
  88. new_group_name = "{0}#{1}".format(name, current_index)
  89. old_name = node.getName()
  90. node.setName(new_group_name)
  91. Logger.log("d", "Node [%s] renamed to [%s]", old_name, new_group_name)
  92. all_nodes.append(node)
  93. return all_nodes
  94. def _update(self, *args) -> None:
  95. nodes = [] # type: List[Dict[str, Union[str, int, bool, SceneNode]]]
  96. name_to_node_info_dict = {} # type: Dict[str, _NodeInfo]
  97. for node in DepthFirstIterator(Application.getInstance().getController().getScene().getRoot()): # type: ignore
  98. if not self._shouldNodeBeHandled(node):
  99. continue
  100. is_group = bool(node.callDecoration("isGroup"))
  101. force_rename = False
  102. if not is_group:
  103. # Handle names for individual nodes
  104. name = node.getName()
  105. name_match = self._naming_regex.fullmatch(name)
  106. if name_match is None:
  107. original_name = name
  108. name_index = 0
  109. else:
  110. original_name = name_match.groups()[0]
  111. name_index = int(name_match.groups()[1])
  112. else:
  113. # Handle names for grouped nodes
  114. original_name = self._group_name_prefix
  115. current_name = node.getName()
  116. if current_name.startswith(self._group_name_prefix):
  117. name_index = int(current_name.split("#")[-1])
  118. else:
  119. # Force rename this group because this node has not been named as a group yet, probably because
  120. # it's a newly created group.
  121. name_index = 0
  122. force_rename = True
  123. if original_name not in name_to_node_info_dict:
  124. # Keep track of 2 things:
  125. # - known indices for nodes which doesn't need to be renamed
  126. # - a list of nodes that need to be renamed. When renaming then, we should avoid using the known indices.
  127. name_to_node_info_dict[original_name] = _NodeInfo(is_group = is_group)
  128. node_info = name_to_node_info_dict[original_name]
  129. if not force_rename and name_index not in node_info.index_to_node:
  130. node_info.index_to_node[name_index] = node
  131. else:
  132. node_info.nodes_to_rename.append(node)
  133. all_nodes = self._renameNodes(name_to_node_info_dict)
  134. for node in all_nodes:
  135. if hasattr(node, "isOutsideBuildArea"):
  136. is_outside_build_area = node.isOutsideBuildArea() # type: ignore
  137. else:
  138. is_outside_build_area = False
  139. node_build_plate_number = node.callDecoration("getBuildPlateNumber")
  140. nodes.append({
  141. "name": node.getName(),
  142. "selected": Selection.isSelected(node),
  143. "outside_build_area": is_outside_build_area,
  144. "buildplate_number": node_build_plate_number,
  145. "node": node
  146. })
  147. nodes = sorted(nodes, key=lambda n: n["name"])
  148. self.setItems(nodes)