from UM.Event import Event
from UM.Tool import Tool
from UM.Application import Application
from UM.Scene.BoxRenderer import BoxRenderer
from UM.Scene.RayRenderer import RayRenderer

from UM.Scene.Iterator.BreadthFirstIterator import BreadthFirstIterator

class SelectionTool(Tool):
    def __init__(self, name):
        super().__init__(name)

        self._scene = Application.getInstance().getController().getScene()
        self._selection = []
        self._bboxes = {}
        self._selectionMask = 1

    def event(self, event):
        if event.type == Event.MousePressEvent:
            root = self._scene.getRoot()

            ray = self._scene.getActiveCamera().getRay(event.x, event.y)

            intersections = []
            for node in BreadthFirstIterator(root):
                if node.getSelectionMask() == self._selectionMask and not node.isLocked():
                    intersection = node.getBoundingBox().intersectsRay(ray)
                    if intersection:
                        intersections.append((node, intersection[0], intersection[1]))

            if intersections:
                intersections.sort(key=lambda k: k[1])

                node = intersections[0][0]
                for i in self._bboxes:
                    self._bboxes[i].setParent(None)

                self._bboxes.clear()
                self._selection.clear()

                box = BoxRenderer(node.getBoundingBox(), root)
                self._bboxes[node] = box
                self._selection.append(node)

@@ -174,16 +174,56 @@
 enderer%0A
+from UM.Scene.Selection import Selection
 %0Afrom UM
@@ -456,37 +456,8 @@
 e()%0A
-        self._selection = %5B%5D%0A
     
@@ -1207,16 +1207,17 @@
 s%5B0%5D%5B0%5D%0A
+%0A
         
@@ -1228,29 +1228,37 @@
     
-for i in self._bboxes
+if Selection.isSelected(node)
 :%0A  
@@ -1279,41 +1279,31 @@
     
-self._bboxes%5Bi%5D.setParent(Non
+Selection.remove(nod
 e)%0A
-%0A
     
@@ -1318,28 +1318,13 @@
     
-s
 el
-f._bboxes.clear()
+se:
 %0A   
@@ -1328,39 +1328,37 @@
                 
-self._s
+    S
 election.clear()
@@ -1354,120 +1354,35 @@
 ion.
-clear()%0A%0A                box = BoxRenderer(node.getBoundingBox(), root)%0A                self._bboxes%5Bnode%5D = box
+add(node)%0A            else:
 %0A   
@@ -1386,39 +1386,33 @@
                 
-self._s
+S
 election.append(
@@ -1408,17 +1408,12 @@
 ion.
-append(node
+clear(
 )%0A

Use the Selection class in SelectionTool