LDViewer.py
changeset 27 dae55dd9ee14
parent 9 b29105e29081
child 28 fc23e1f415d8
--- a/LDViewer.py	Sat Jul 07 11:35:17 2007 +0200
+++ b/LDViewer.py	Mon Jul 09 11:10:14 2007 +0200
@@ -30,6 +30,7 @@
 from graphics.GraphicCommons import *
 from graphics.FBD_Objects import *
 from Viewer import *
+from Dialogs import *
 
 def ExtractNextBlocks(block, block_list):
     current_list = [block]
@@ -53,10 +54,11 @@
                         next_list.append(next)
         current_list = next_list
     
-def CalcBranchSize(elements, stop):
+def CalcBranchSize(elements, stops):
     branch_size = 0
-    stop_list = [stop]
-    ExtractNextBlocks(stop, stop_list)
+    stop_list = stops
+    for stop in stops:
+        ExtractNextBlocks(stop, stop_list)
     element_tree = {}
     for element in elements:
         if element not in element_tree:
@@ -64,13 +66,34 @@
             GenerateTree(element, element_tree, stop_list)
         elif element_tree[element]:
             element_tree[element]["parents"].append("start")
+    remove_stops = {"start":[], "stop":[]}
     for element, values in element_tree.items():
-        if values and values["children"] == ["stop"]:
+        if "stop" in values["children"]:
+            removed = []
+            for child in values["children"]:
+                if child != "stop":
+##                    if child in elements:
+##                        RemoveElement(child, element_tree)
+##                        removed.append(child)
+                    if "start" in element_tree[child]["parents"]:
+                        if element not in remove_stops["stop"]:
+                            remove_stops["stop"].append(element)
+                        if child not in remove_stops["start"]:
+                            remove_stops["start"].append(child)
+            for child in removed:
+                values["children"].remove(child)
+    for element in remove_stops["start"]:
+        element_tree[element]["parents"].remove("start")
+    for element in remove_stops["stop"]:
+        element_tree[element]["children"].remove("stop")
+    for element, values in element_tree.items():
+        if values and "stop" in values["children"]:
             CalcWeight(element, element_tree)
             if values["weight"]:
                 branch_size += values["weight"]
             else:
                 return 1
+    #print branch_size
     return branch_size
 
 def RemoveElement(remove, element_tree):
@@ -78,7 +101,8 @@
         for child in element_tree[remove]["children"]:
             if child != "stop":
                 RemoveElement(child, element_tree)
-        element_tree[remove] = None
+        element_tree.pop(remove)
+##        element_tree[remove] = None
 
 def GenerateTree(element, element_tree, stop_list):
     if element in element_tree:
@@ -95,11 +119,12 @@
             for wire, handle in connector.GetWires():
                 next = wire.EndConnected.GetParentBlock()
                 if isinstance(next, LD_PowerRail) and next.GetType() == LEFTRAIL or next in stop_list:
-                    for remove in element_tree[element]["children"]:
-                        RemoveElement(remove, element_tree)
-                    element_tree[element]["children"] = ["stop"]
-                elif element_tree[element]["children"] == ["stop"]:
-                    element_tree[next] = None
+##                    for remove in element_tree[element]["children"]:
+##                        RemoveElement(remove, element_tree)
+##                    element_tree[element]["children"] = ["stop"]
+                    element_tree[element]["children"].append("stop")
+##                elif element_tree[element]["children"] == ["stop"]:
+##                    element_tree[next] = None
                 elif next not in element_tree or element_tree[next]:
                     element_tree[element]["children"].append(next)
                     if next in element_tree:
@@ -227,6 +252,9 @@
         return None
 
     def FindElement(self, pos):
+        if self.GetDrawingMode() == FREEDRAWING_MODE:
+            return Viewer.FindElement(self, pos)
+        
         elements = []
         for element in self.Elements:
             if element.HitTest(pos) or element.TestHandle(pos) != (0, 0):
@@ -243,6 +271,9 @@
         return None
 
     def SearchElements(self, bbox):
+        if self.GetDrawingMode() == FREEDRAWING_MODE:
+            return Viewer.SearchElements(self, bbox)
+        
         elements = []
         for element in self.Blocks:
             element_bbox = element.GetBoundingBox()
@@ -255,8 +286,11 @@
 #-------------------------------------------------------------------------------
 
     def OnViewerLeftDown(self, event):
-        if self.Mode == MODE_SELECTION:
-            pos = event.GetPosition()
+        if self.GetDrawingMode() == FREEDRAWING_MODE:
+            Viewer.OnViewerLeftDown(self, event)
+        elif self.Mode == MODE_SELECTION:
+            dc = self.GetLogicalDC()
+            pos = event.GetLogicalPosition(dc)
             element = self.FindElement(pos)
             if self.SelectedElement:
                 if self.SelectedElement in self.Elements:
@@ -283,94 +317,106 @@
                 self.Refresh()
             if element:
                 self.SelectedElement = element
-                self.SelectedElement.OnLeftDown(event, self.Scaling)
+                self.SelectedElement.OnLeftDown(event, dc, self.Scaling)
                 self.Refresh()
             else:
                 self.rubberBand.Reset()
-                self.rubberBand.OnLeftDown(event, self.Scaling)
+                self.rubberBand.OnLeftDown(event, dc, self.Scaling)
         event.Skip()
 
     def OnViewerLeftUp(self, event):
-        if self.rubberBand.IsShown():
+        if self.GetDrawingMode() == FREEDRAWING_MODE:
+            Viewer.OnViewerLeftUp(self, event)
+        elif self.rubberBand.IsShown():
             if self.Mode == MODE_SELECTION:
                 elements = self.SearchElements(self.rubberBand.GetCurrentExtent())
-                self.rubberBand.OnLeftUp(event, self.Scaling)
+                self.rubberBand.OnLeftUp(event, self.GetLogicalDC(), self.Scaling)
                 if len(elements) > 0:
                     self.SelectedElement = Graphic_Group(self)
                     self.SelectedElement.SetElements(elements)
                     self.SelectedElement.SetSelected(True)
                     self.Refresh()
         elif self.Mode == MODE_SELECTION and self.SelectedElement:
+            dc = self.GetLogicalDC() 
             if self.SelectedElement in self.Elements:
                 if self.SelectedElement in self.Wires:
-                    result = self.SelectedElement.TestSegment(event.GetPosition(), True)
+                    result = self.SelectedElement.TestSegment(event.GetLogicalPosition(dc), True)
                     if result and result[1] in [EAST, WEST]:
                         self.SelectedElement.SetSelectedSegment(result[0])
                 else:
-                    self.SelectedElement.OnLeftUp(event, self.Scaling)
+                    self.SelectedElement.OnLeftUp(event, dc, self.Scaling)
             else:
                 for element in self.SelectedElement.GetElements():
                     if element in self.Wires:
-                        result = element.TestSegment(event.GetPosition(), True)
+                        result = element.TestSegment(event.GetLogicalPosition(dc), True)
                         if result and result[1] in [EAST, WEST]:
                             element.SetSelectedSegment(result[0])
                     else:
-                        element.OnLeftUp(event, self.Scaling)
+                        element.OnLeftUp(event, dc, self.Scaling)
             wxCallAfter(self.SetCursor, wxNullCursor)
             self.ReleaseMouse()
             self.Refresh()
         event.Skip()
 
     def OnViewerRightUp(self, event):
-        pos = event.GetPosition()
-        element = self.FindElement(pos)
-        if element:
-            if self.SelectedElement and self.SelectedElement != element:
-                self.SelectedElement.SetSelected(False)
-            self.SelectedElement = element
-            if self.SelectedElement in self.Wires:
-                self.SelectedElement.SetSelectedSegment(0)
-            else:
-                self.SelectedElement.SetSelected(True)
-                self.SelectedElement.OnRightUp(event, self.Scaling)
-            wxCallAfter(self.SetCursor, wxNullCursor)
-            self.ReleaseMouse()
+        if self.GetDrawingMode() == FREEDRAWING_MODE:
+            Viewer.OnViewerRightUp(self, event)
+        else:
+            dc = self.GetLogicalDC()
+            pos = event.GetLogicalPosition(dc)
+            element = self.FindElement(pos)
+            if element:
+                if self.SelectedElement and self.SelectedElement != element:
+                    self.SelectedElement.SetSelected(False)
+                self.SelectedElement = element
+                if self.SelectedElement in self.Wires:
+                    self.SelectedElement.SetSelectedSegment(0)
+                else:
+                    self.SelectedElement.SetSelected(True)
+                    self.SelectedElement.OnRightUp(event, dc, self.Scaling)
+                wxCallAfter(self.SetCursor, wxNullCursor)
+                self.ReleaseMouse()
+                self.Refresh()
+        event.Skip()
+
+    def OnViewerLeftDClick(self, event):
+        if self.GetDrawingMode() == FREEDRAWING_MODE:
+            Viewer.OnViewerLeftDClick(self, event)
+        elif self.Mode == MODE_SELECTION and self.SelectedElement:
+            self.SelectedElement.OnLeftDClick(event, self.GetLogicalDC(), self.Scaling)
             self.Refresh()
         event.Skip()
 
-    def OnViewerLeftDClick(self, event):
-        if self.Mode == MODE_SELECTION and self.SelectedElement:
-            self.SelectedElement.OnLeftDClick(event, self.Scaling)
+    def OnViewerMotion(self, event):
+        if self.GetDrawingMode() == FREEDRAWING_MODE:
+            Viewer.OnViewerMotion(self, event)
+        event.Skip()
+
+#-------------------------------------------------------------------------------
+#                          Keyboard event functions
+#-------------------------------------------------------------------------------
+
+    def OnChar(self, event):
+        if self.GetDrawingMode() == FREEDRAWING_MODE:
+            Viewer.OnChar(self, event)
+        else:
+            keycode = event.GetKeyCode()
+            if keycode == WXK_DELETE and self.SelectedElement:
+                if self.SelectedElement in self.Blocks:
+                    self.SelectedElement.Delete()
+                elif self.SelectedElement in self.Wires:
+                    self.DeleteWire(self.SelectedElement)
+                elif self.SelectedElement not in self.Elements:
+                    all_wires = True
+                    for element in self.SelectedElement.GetElements():
+                        all_wires &= element in self.Wires
+                    if all_wires:
+                        self.DeleteWire(self.SelectedElement)
+                    else:
+                        self.SelectedElement.Delete()
             self.Refresh()
         event.Skip()
 
-    def OnViewerMotion(self, event):
-        if self.rubberBand.IsShown():
-            self.rubberBand.OnMotion(event, self.Scaling)
-        event.Skip()
-
-#-------------------------------------------------------------------------------
-#                          Keyboard event functions
-#-------------------------------------------------------------------------------
-
-    def OnChar(self, event):
-        keycode = event.GetKeyCode()
-        if keycode == WXK_DELETE and self.SelectedElement:
-            if self.SelectedElement in self.Blocks:
-                self.SelectedElement.Delete()
-            elif self.SelectedElement in self.Wires:
-                self.DeleteWire(self.SelectedElement)
-            elif self.SelectedElement not in self.Elements:
-                all_wires = True
-                for element in self.SelectedElement.GetElements():
-                    all_wires &= element in self.Wires
-                if all_wires:
-                    self.DeleteWire(self.SelectedElement)
-                else:
-                    self.SelectedElement.Delete()
-        self.Refresh()
-        event.Skip()
-
 #-------------------------------------------------------------------------------
 #                          Adding element functions
 #-------------------------------------------------------------------------------
@@ -669,6 +715,7 @@
                 for element in right_elements:
                     right_powerrail &= isinstance(element.GetParentBlock(), LD_PowerRail)
                 if not left_powerrail or not right_powerrail:
+                    wires = []
                     if left_powerrail:
                         powerrail = left_elements[0].GetParentBlock()
                         index = 0
@@ -679,15 +726,14 @@
                         powerrail.InsertConnector(index + 1)
                         powerrail.RefreshModel()
                         connectors = powerrail.GetConnectors()
+                        right_elements.reverse()
                         for i, right_element in enumerate(right_elements):
                             new_wire = Wire(self)
+                            wires.append(new_wire)
                             right_element.InsertConnect(right_index[i] + 1, (new_wire, 0), False)
                             connectors[index + 1].Connect((new_wire, -1), False)
                             new_wire.ConnectStartPoint(None, right_element)
                             new_wire.ConnectEndPoint(None, connectors[index + 1])
-                            self.Wires.append(new_wire)
-                            self.Elements.append(new_wire)
-                            rung.SelectElement(new_wire)
                         right_elements.reverse()
                     elif right_powerrail:
                         dialog = LDElementDialog(self.Parent, "coil")
@@ -731,23 +777,20 @@
                             wire.ConnectEndPoint(None, coil_connectors["output"])
                             self.Wires.append(wire)
                             self.Elements.append(wire)
-                            rung.SelectElement(wire)                                
+                            rung.SelectElement(wire)
+                            left_elements.reverse()
                             for i, left_element in enumerate(left_elements):
                                 # Create Wire between LeftPowerRail and Coil
                                 new_wire = Wire(self)
+                                wires.append(new_wire)
                                 coil_connectors["input"].Connect((new_wire, 0), False)
                                 left_element.InsertConnect(left_index[i] + 1, (new_wire, -1), False)
                                 new_wire.ConnectStartPoint(None, coil_connectors["input"])
                                 new_wire.ConnectEndPoint(None, left_element)
-                                self.Wires.append(new_wire)
-                                self.Elements.append(new_wire)
-                                rung.SelectElement(new_wire)
-                            left_elements.reverse()
                             self.RefreshPosition(coil)
                     else:
                         left_elements.reverse()
                         right_elements.reverse()
-                        wires = []
                         for i, left_element in enumerate(left_elements):
                             for j, right_element in enumerate(right_elements):
                                 exist = False
@@ -760,12 +803,12 @@
                                     left_element.InsertConnect(left_index[i] + 1, (new_wire, -1), False)
                                     new_wire.ConnectStartPoint(None, right_element)
                                     new_wire.ConnectEndPoint(None, left_element)
-                        wires.reverse()
-                        for wire in wires:
-                            self.Wires.append(wire)
-                            self.Elements.append(wire)
-                            rung.SelectElement(wire)
-                        right_elements.reverse()
+                    wires.reverse()
+                    for wire in wires:
+                        self.Wires.append(wire)
+                        self.Elements.append(wire)
+                        rung.SelectElement(wire)
+                    right_elements.reverse()
                 for block in blocks:
                     self.RefreshPosition(block)
                 for right_element in right_elements:
@@ -784,7 +827,6 @@
             message.ShowModal()
             message.Destroy()
 
-
     def AddBlock(self):
         message = wxMessageDialog(self, "This option isn't available yet!", "Warning", wxOK|wxICON_EXCLAMATION)
         message.ShowModal()
@@ -795,69 +837,72 @@
 #-------------------------------------------------------------------------------
 
     def DeleteContact(self, contact):
-        rungindex = self.FindRung(contact)
-        rung = self.Rungs[rungindex]
-        old_bbox = rung.GetBoundingBox()
-        connectors = contact.GetConnectors()
-        input_wires = [wire for wire, handle in connectors["input"].GetWires()]
-        output_wires = [wire for wire, handle in connectors["output"].GetWires()]
-        left_elements = [(wire.EndConnected, wire.EndConnected.GetWireIndex(wire)) for wire in input_wires]
-        right_elements = [(wire.StartConnected, wire.StartConnected.GetWireIndex(wire)) for wire in output_wires]
-        for wire in input_wires:
-            wire.Clean()
-            rung.SelectElement(wire)
-            self.Wires.remove(wire)
-            self.Elements.remove(wire)
-        for wire in output_wires:
-            wire.Clean()
-            rung.SelectElement(wire)
-            self.Wires.remove(wire)
-            self.Elements.remove(wire)
-        rung.SelectElement(contact)
-        contact.Clean()
-        left_elements.reverse()
-        right_elements.reverse()
-        powerrail = len(left_elements) == 1 and isinstance(left_elements[0][0].GetParentBlock(), LD_PowerRail)
-        for left_element, left_index in left_elements:
+        if self.GetDrawingMode() == FREEDRAWING_MODE:
+            Viewer.DeleteContact(self, contact)
+        else:
+            rungindex = self.FindRung(contact)
+            rung = self.Rungs[rungindex]
+            old_bbox = rung.GetBoundingBox()
+            connectors = contact.GetConnectors()
+            input_wires = [wire for wire, handle in connectors["input"].GetWires()]
+            output_wires = [wire for wire, handle in connectors["output"].GetWires()]
+            left_elements = [(wire.EndConnected, wire.EndConnected.GetWireIndex(wire)) for wire in input_wires]
+            right_elements = [(wire.StartConnected, wire.StartConnected.GetWireIndex(wire)) for wire in output_wires]
+            for wire in input_wires:
+                wire.Clean()
+                rung.SelectElement(wire)
+                self.Wires.remove(wire)
+                self.Elements.remove(wire)
+            for wire in output_wires:
+                wire.Clean()
+                rung.SelectElement(wire)
+                self.Wires.remove(wire)
+                self.Elements.remove(wire)
+            rung.SelectElement(contact)
+            contact.Clean()
+            left_elements.reverse()
+            right_elements.reverse()
+            powerrail = len(left_elements) == 1 and isinstance(left_elements[0][0].GetParentBlock(), LD_PowerRail)
+            for left_element, left_index in left_elements:
+                for right_element, right_index in right_elements:
+                    wire_removed = []
+                    for wire, handle in right_element.GetWires():
+                        if wire.EndConnected == left_element:
+                            wire_removed.append(wire)
+                        elif isinstance(wire.EndConnected.GetParentBlock(), LD_PowerRail) and powerrail:
+                            left_powerrail = wire.EndConnected.GetParentBlock()
+                            index = left_powerrail.GetConnectorIndex(wire.EndConnected)
+                            left_powerrail.DeleteConnector(index)
+                            wire_removed.append(wire)
+                    for wire in wire_removed:
+                        wire.Clean()
+                        self.Wires.remove(wire)
+                        self.Elements.remove(wire)
+                        rung.SelectElement(wire)
+            wires = []
+            for left_element, left_index in left_elements:
+                for right_element, right_index in right_elements:
+                    wire = Wire(self)
+                    wires.append(wire)
+                    right_element.InsertConnect(right_index, (wire, 0), False)
+                    left_element.InsertConnect(left_index, (wire, -1), False)
+                    wire.ConnectStartPoint(None, right_element)
+                    wire.ConnectEndPoint(None, left_element)
+            wires.reverse()
+            for wire in wires:
+                self.Wires.append(wire)
+                self.Elements.append(wire)
+                rung.SelectElement(wire)
+            right_elements.reverse()
             for right_element, right_index in right_elements:
-                wire_removed = []
-                for wire, handle in right_element.GetWires():
-                    if wire.EndConnected == left_element:
-                        wire_removed.append(wire)
-                    elif isinstance(wire.EndConnected.GetParentBlock(), LD_PowerRail) and powerrail:
-                        left_powerrail = wire.EndConnected.GetParentBlock()
-                        index = left_powerrail.GetConnectorIndex(wire.EndConnected)
-                        left_powerrail.DeleteConnector(index)
-                        wire_removed.append(wire)
-                for wire in wire_removed:
-                    wire.Clean()
-                    self.Wires.remove(wire)
-                    self.Elements.remove(wire)
-                    rung.SelectElement(wire)
-        wires = []
-        for left_element, left_index in left_elements:
-            for right_element, right_index in right_elements:
-                wire = Wire(self)
-                wires.append(wire)
-                right_element.InsertConnect(right_index, (wire, 0), False)
-                left_element.InsertConnect(left_index, (wire, -1), False)
-                wire.ConnectStartPoint(None, right_element)
-                wire.ConnectEndPoint(None, left_element)
-        wires.reverse()
-        for wire in wires:
-            self.Wires.append(wire)
-            self.Elements.append(wire)
-            rung.SelectElement(wire)
-        right_elements.reverse()
-        for right_element, right_index in right_elements:
-            self.RefreshPosition(right_element.GetParentBlock())
-        self.Blocks.remove(contact)
-        self.Elements.remove(contact)
-        self.Controler.RemoveCurrentElementEditingInstance(contact.GetId())
-        rung.RefreshBoundingBox()
-        new_bbox = rung.GetBoundingBox()
-        self.RefreshRungs(new_bbox.height - old_bbox.height, rungindex + 1)
-        self.SelectedElement = None
+                self.RefreshPosition(right_element.GetParentBlock())
+            self.Blocks.remove(contact)
+            self.Elements.remove(contact)
+            self.Controler.RemoveCurrentElementEditingInstance(contact.GetId())
+            rung.RefreshBoundingBox()
+            new_bbox = rung.GetBoundingBox()
+            self.RefreshRungs(new_bbox.height - old_bbox.height, rungindex + 1)
+            self.SelectedElement = None
 
     def RecursiveDeletion(self, element, rung):
         connectors = element.GetConnectors()
@@ -881,109 +926,115 @@
                 self.RefreshPosition(block)
 
     def DeleteCoil(self, coil):
-        rungindex = self.FindRung(coil)
-        rung = self.Rungs[rungindex]
-        old_bbox = rung.GetBoundingBox()
-        nbcoils = 0
-        for element in rung.GetElements():
-            if isinstance(element, LD_Coil):
-                nbcoils += 1
-        if nbcoils > 1:
-            connectors = coil.GetConnectors()
-            output_wires = [wire for wire, handle in connectors["output"].GetWires()]
-            right_elements = [wire.StartConnected for wire in output_wires]
-            for wire in output_wires:
-                wire.Clean()
-                self.Wires.remove(wire)
-                self.Elements.remove(wire)
-                rung.SelectElement(wire)
-            for right_element in right_elements:
-                right_block = right_element.GetParentBlock()
-                if isinstance(right_block, LD_PowerRail):
-                    if len(right_element.GetWires()) == 0:
-                        index = right_block.GetConnectorIndex(right_element)
-                        right_block.DeleteConnector(index)
-                        powerrail_connectors = right_block.GetConnectors()
-                        for connector in powerrail_connectors:
-                            for wire, handle in connector.GetWires():
-                                block = wire.EndConnected.GetParentBlock()
-                                endpoint = wire.EndConnected.GetPosition(False)
-                                startpoint = connector.GetPosition(False)
-                                block.Move(0, startpoint.y - endpoint.y)
-                                self.RefreshPosition(block)
-            self.RecursiveDeletion(coil, rung)
+        if self.GetDrawingMode() == FREEDRAWING_MODE:
+            Viewer.DeleteContact(self, coil)
         else:
-            for element in rung.GetElements():
-                if element in self.Wires:
-                    element.Clean()
-                    self.Wires.remove(element)
-                    self.Elements.remove(element)
-            for element in rung.GetElements():
-                if element in self.Blocks:
-                    self.Controler.RemoveCurrentElementEditingInstance(element.GetId())
-                    self.Blocks.remove(element)
-                    self.Elements.remove(element)
-            self.Controler.RemoveCurrentElementEditingInstance(self.Comments[rungindex].GetId())
-            self.Elements.remove(self.Comments[rungindex])
-            self.Comments.pop(rungindex)
-            self.Rungs.pop(rungindex)
-            if rungindex < len(self.Rungs):
-                next_bbox = self.Rungs[rungindex].GetBoundingBox()
-                self.RefreshRungs(old_bbox.y - next_bbox.y, rungindex)
-        self.SelectedElement = None
-
-    def DeleteWire(self, wire):
-        wires = []
-        left_elements = []
-        right_elements = []
-        if wire in self.Wires:
-            wires = [wire]
-        elif wire not in self.Elements:
-            for element in wire.GetElements():
-                if element in self.Wires:
-                    wires.append(element)
-                else:
-                    wires = []
-                    break
-        if len(wires) > 0:
-            rungindex = self.FindRung(wires[0])
+            rungindex = self.FindRung(coil)
             rung = self.Rungs[rungindex]
             old_bbox = rung.GetBoundingBox()
-            for wire in wires:
-                connections = wire.GetSelectedSegmentConnections()
-                left_block = wire.EndConnected.GetParentBlock()
-                if wire.EndConnected not in left_elements:
-                    left_elements.append(wire.EndConnected)
-                if wire.StartConnected not in right_elements:
-                    right_elements.append(wire.StartConnected)
-                if connections == (False, False) or connections == (False, True) and isinstance(left_block, LD_PowerRail):
+            nbcoils = 0
+            for element in rung.GetElements():
+                if isinstance(element, LD_Coil):
+                    nbcoils += 1
+            if nbcoils > 1:
+                connectors = coil.GetConnectors()
+                output_wires = [wire for wire, handle in connectors["output"].GetWires()]
+                right_elements = [wire.StartConnected for wire in output_wires]
+                for wire in output_wires:
                     wire.Clean()
                     self.Wires.remove(wire)
                     self.Elements.remove(wire)
                     rung.SelectElement(wire)
-            for left_element in left_elements:
-                left_block = left_element.GetParentBlock()
-                if isinstance(left_block, LD_PowerRail):
-                    if len(left_element.GetWires()) == 0:
-                        index = left_block.GetConnectorIndex(left_element)
-                        left_block.DeleteConnector(index)
-                else:
-                    connectors = left_block.GetConnectors()
-                    output_connectors = []
-                    if "outputs" in connectors:
-                        output_connectors = connectors["outputs"]
-                    if "output" in connectors:
-                        output_connectors = [connectors["output"]]
-                    for connector in output_connectors:
-                        for wire, handle in connector.GetWires():
-                            self.RefreshPosition(wire.StartConnected.GetParentBlock())
-            for right_element in right_elements:
-                self.RefreshPosition(right_element.GetParentBlock())
-            rung.RefreshBoundingBox()
-            new_bbox = rung.GetBoundingBox()
-            self.RefreshRungs(new_bbox.height - old_bbox.height, rungindex + 1)
+                for right_element in right_elements:
+                    right_block = right_element.GetParentBlock()
+                    if isinstance(right_block, LD_PowerRail):
+                        if len(right_element.GetWires()) == 0:
+                            index = right_block.GetConnectorIndex(right_element)
+                            right_block.DeleteConnector(index)
+                            powerrail_connectors = right_block.GetConnectors()
+                            for connector in powerrail_connectors:
+                                for wire, handle in connector.GetWires():
+                                    block = wire.EndConnected.GetParentBlock()
+                                    endpoint = wire.EndConnected.GetPosition(False)
+                                    startpoint = connector.GetPosition(False)
+                                    block.Move(0, startpoint.y - endpoint.y)
+                                    self.RefreshPosition(block)
+                self.RecursiveDeletion(coil, rung)
+            else:
+                for element in rung.GetElements():
+                    if element in self.Wires:
+                        element.Clean()
+                        self.Wires.remove(element)
+                        self.Elements.remove(element)
+                for element in rung.GetElements():
+                    if element in self.Blocks:
+                        self.Controler.RemoveCurrentElementEditingInstance(element.GetId())
+                        self.Blocks.remove(element)
+                        self.Elements.remove(element)
+                self.Controler.RemoveCurrentElementEditingInstance(self.Comments[rungindex].GetId())
+                self.Elements.remove(self.Comments[rungindex])
+                self.Comments.pop(rungindex)
+                self.Rungs.pop(rungindex)
+                if rungindex < len(self.Rungs):
+                    next_bbox = self.Rungs[rungindex].GetBoundingBox()
+                    self.RefreshRungs(old_bbox.y - next_bbox.y, rungindex)
             self.SelectedElement = None
 
+    def DeleteWire(self, wire):
+        if self.GetDrawingMode() == FREEDRAWING_MODE:
+            Viewer.DeleteWire(self, wire)
+        else:
+            wires = []
+            left_elements = []
+            right_elements = []
+            if wire in self.Wires:
+                wires = [wire]
+            elif wire not in self.Elements:
+                for element in wire.GetElements():
+                    if element in self.Wires:
+                        wires.append(element)
+                    else:
+                        wires = []
+                        break
+            if len(wires) > 0:
+                rungindex = self.FindRung(wires[0])
+                rung = self.Rungs[rungindex]
+                old_bbox = rung.GetBoundingBox()
+                for wire in wires:
+                    connections = wire.GetSelectedSegmentConnections()
+                    left_block = wire.EndConnected.GetParentBlock()
+                    if wire.EndConnected not in left_elements:
+                        left_elements.append(wire.EndConnected)
+                    if wire.StartConnected not in right_elements:
+                        right_elements.append(wire.StartConnected)
+                    if connections == (False, False) or connections == (False, True) and isinstance(left_block, LD_PowerRail):
+                        wire.Clean()
+                        self.Wires.remove(wire)
+                        self.Elements.remove(wire)
+                        rung.SelectElement(wire)
+                for left_element in left_elements:
+                    left_block = left_element.GetParentBlock()
+                    if isinstance(left_block, LD_PowerRail):
+                        if len(left_element.GetWires()) == 0:
+                            index = left_block.GetConnectorIndex(left_element)
+                            left_block.DeleteConnector(index)
+                    else:
+                        connectors = left_block.GetConnectors()
+                        output_connectors = []
+                        if "outputs" in connectors:
+                            output_connectors = connectors["outputs"]
+                        if "output" in connectors:
+                            output_connectors = [connectors["output"]]
+                        for connector in output_connectors:
+                            for wire, handle in connector.GetWires():
+                                self.RefreshPosition(wire.StartConnected.GetParentBlock())
+                for right_element in right_elements:
+                    self.RefreshPosition(right_element.GetParentBlock())
+                rung.RefreshBoundingBox()
+                new_bbox = rung.GetBoundingBox()
+                self.RefreshRungs(new_bbox.height - old_bbox.height, rungindex + 1)
+                self.SelectedElement = None
+
 #-------------------------------------------------------------------------------
 #                        Refresh element position functions
 #-------------------------------------------------------------------------------
@@ -1030,6 +1081,10 @@
         movex = minx + interval - position[0]
         element.Move(movex, 0)
         position = element.GetPosition()
+        blocks = []
+        for i, connector in enumerate(input_connectors):
+            for j, (wire, handle) in enumerate(connector.GetWires()):
+                blocks.append(wire.EndConnected.GetParentBlock())
         for i, connector in enumerate(input_connectors):
             startpoint = connector.GetPosition(False)
             previous_blocks = []
@@ -1050,7 +1105,7 @@
                         start_offset = endpoint.y - startpoint.y
                     offset = start_offset
                 else:
-                    offset = start_offset + LD_LINE_SIZE * CalcBranchSize(previous_blocks, block)
+                    offset = start_offset + LD_LINE_SIZE * CalcBranchSize(previous_blocks, blocks)
                 if block in block_list:
                     wires = wire.EndConnected.GetWires()
                     endmiddlepoint = wires[0][0].StartConnected.GetPosition(False)[0] - LD_WIRE_SIZE
@@ -1087,6 +1142,7 @@
                         points = [startpoint, endpoint]
                 wire.SetPoints(points)
                 previous_blocks.append(block)
+                blocks.remove(block)
                 ExtractNextBlocks(block, block_list)
         element.RefreshModel(False)
         if recursive:
@@ -1147,175 +1203,3 @@
             self.Refresh()
         dialog.Destroy()
 
-#-------------------------------------------------------------------------------
-#                        Edit Ladder Element Properties Dialog
-#-------------------------------------------------------------------------------
-
-[wxID_LDELEMENTDIALOG, wxID_LDELEMENTDIALOGMAINPANEL, 
- wxID_LDELEMENTDIALOGNAME, wxID_LDELEMENTDIALOGRADIOBUTTON1, 
- wxID_LDELEMENTDIALOGRADIOBUTTON2, wxID_LDELEMENTDIALOGRADIOBUTTON3,
- wxID_LDELEMENTDIALOGRADIOBUTTON4, wxID_LDELEMENTDIALOGPREVIEW,
- wxID_LDELEMENTDIALOGSTATICTEXT1, wxID_LDELEMENTDIALOGSTATICTEXT2, 
- wxID_LDELEMENTDIALOGSTATICTEXT3, 
-] = [wx.NewId() for _init_ctrls in range(11)]
-
-class LDElementDialog(wx.Dialog):
-    def _init_coll_flexGridSizer1_Items(self, parent):
-        # generated method, don't edit
-
-        parent.AddWindow(self.MainPanel, 0, border=0, flag=0)
-
-    def _init_sizers(self):
-        # generated method, don't edit
-        self.flexGridSizer1 = wx.FlexGridSizer(cols=1, hgap=0, rows=2, vgap=0)
-
-        self._init_coll_flexGridSizer1_Items(self.flexGridSizer1)
-
-        self.SetSizer(self.flexGridSizer1)
-
-    def _init_ctrls(self, prnt, title, labels):
-        # generated method, don't edit
-        wx.Dialog.__init__(self, id=wxID_LDELEMENTDIALOG,
-              name='VariablePropertiesDialog', parent=prnt, pos=wx.Point(376, 223),
-              size=wx.Size(350, 260), style=wx.DEFAULT_DIALOG_STYLE,
-              title=title)
-        self.SetClientSize(wx.Size(350, 260))
-
-        self.MainPanel = wx.Panel(id=wxID_LDELEMENTDIALOGMAINPANEL,
-              name='MainPanel', parent=self, pos=wx.Point(0, 0),
-              size=wx.Size(340, 200), style=wx.TAB_TRAVERSAL)
-        self.MainPanel.SetAutoLayout(True)
-
-        self.staticText1 = wx.StaticText(id=wxID_LDELEMENTDIALOGSTATICTEXT1,
-              label='Modifier:', name='staticText1', parent=self.MainPanel,
-              pos=wx.Point(24, 24), size=wx.Size(70, 17), style=0)
-
-        self.staticText2 = wx.StaticText(id=wxID_LDELEMENTDIALOGSTATICTEXT2,
-              label='Name:', name='staticText2', parent=self.MainPanel,
-              pos=wx.Point(24, 150), size=wx.Size(70, 17), style=0)
-
-        self.staticText3 = wx.StaticText(id=wxID_LDELEMENTDIALOGSTATICTEXT3,
-              label='Preview:', name='staticText3', parent=self.MainPanel,
-              pos=wx.Point(174, 24), size=wx.Size(100, 17), style=0)
-
-        self.radioButton1 = wx.RadioButton(id=wxID_LDELEMENTDIALOGRADIOBUTTON1,
-              label=labels[0], name='radioButton1', parent=self.MainPanel,
-              pos=wx.Point(24, 48), size=wx.Size(114, 24), style=0)
-        EVT_RADIOBUTTON(self, wxID_LDELEMENTDIALOGRADIOBUTTON1, self.OnTypeChanged)
-        self.radioButton1.SetValue(True)
-
-        self.radioButton2 = wx.RadioButton(id=wxID_LDELEMENTDIALOGRADIOBUTTON2,
-              label=labels[1], name='radioButton2', parent=self.MainPanel, 
-              pos=wx.Point(24, 72), size=wx.Size(128, 24), style=0)
-        EVT_RADIOBUTTON(self, wxID_LDELEMENTDIALOGRADIOBUTTON2, self.OnTypeChanged)
-
-        self.radioButton3 = wx.RadioButton(id=wxID_LDELEMENTDIALOGRADIOBUTTON3,
-              label=labels[2], name='radioButton3', parent=self.MainPanel,
-              pos=wx.Point(24, 96), size=wx.Size(114, 24), style=0)
-        EVT_RADIOBUTTON(self, wxID_LDELEMENTDIALOGRADIOBUTTON3, self.OnTypeChanged)
-
-        self.radioButton4 = wx.RadioButton(id=wxID_LDELEMENTDIALOGRADIOBUTTON4,
-              label=labels[3], name='radioButton4', parent=self.MainPanel, 
-              pos=wx.Point(24, 120), size=wx.Size(128, 24), style=0)
-        EVT_RADIOBUTTON(self, wxID_LDELEMENTDIALOGRADIOBUTTON4, self.OnTypeChanged)
-
-        self.Name = wx.Choice(id=wxID_LDELEMENTDIALOGNAME,
-              name='Name', parent=self.MainPanel, pos=wx.Point(24, 174),
-              size=wx.Size(145, 24), style=0)
-        EVT_CHOICE(self, wxID_LDELEMENTDIALOGNAME, self.OnNameChanged)
-
-        self.Preview = wx.Panel(id=wxID_LDELEMENTDIALOGPREVIEW,
-              name='Preview', parent=self.MainPanel, pos=wx.Point(174, 48),
-              size=wx.Size(150, 150), style=wx.TAB_TRAVERSAL|wx.SIMPLE_BORDER)
-        self.Preview.SetBackgroundColour(wxColour(255,255,255))
-
-        self._init_sizers()
-
-    def __init__(self, parent, type):
-        self.Type = type
-        if type == "contact":
-            self._init_ctrls(parent, "Edit Contact Values", ['Normal','Negate','Rising Edge','Falling Edge'])
-            self.Element = LD_Contact(self.Preview, CONTACT_NORMAL, "")
-        elif type == "coil":
-            self._init_ctrls(parent, "Edit Coil Values", ['Normal','Negate','Set','Reset'])
-            self.Element = LD_Coil(self.Preview, COIL_NORMAL, "")
-        self.Element.SetPosition((150 - LD_ELEMENT_SIZE[0]) / 2, (150 - LD_ELEMENT_SIZE[1]) / 2)
-
-        self.ButtonSizer = self.CreateButtonSizer(wxOK|wxCANCEL|wxCENTRE)
-        self.flexGridSizer1.Add(self.ButtonSizer, 1, wxALIGN_RIGHT)
-
-        EVT_PAINT(self, self.OnPaint)
-
-    def SetVariables(self, vars):
-        self.Name.Clear()
-        for name in vars:
-            self.Name.Append(name)
-        self.Name.Enable(self.Name.GetCount() > 0)
-
-    def SetValues(self, values):
-        for name, value in values.items():
-            if name == "name":
-                self.Element.SetName(value)
-                self.Name.SetStringSelection(value)
-            elif name == "type":
-                self.Element.SetType(value)
-                if self.Type == "contact":
-                    if value == CONTACT_NORMAL:
-                        self.radioButton1.SetValue(True)
-                    elif value == CONTACT_REVERSE:
-                        self.radioButton2.SetValue(True)
-                    elif value == CONTACT_RISING:
-                        self.radioButton3.SetValue(True)
-                    elif value == CONTACT_FALLING:
-                        self.radioButton4.SetValue(True)
-                elif self.Type == "coil":
-                    if value == COIL_NORMAL:
-                        self.radioButton1.SetValue(True)
-                    elif value == COIL_REVERSE:
-                        self.radioButton2.SetValue(True)
-                    elif value == COIL_SET:
-                        self.radioButton3.SetValue(True)
-                    elif value == COIL_RESET:
-                        self.radioButton4.SetValue(True)
-
-    def GetValues(self):
-        values = {}
-        values["name"] = self.Element.GetName()
-        values["type"] = self.Element.GetType()
-        return values
-
-    def OnTypeChanged(self, event):
-        if self.Type == "contact":
-            if self.radioButton1.GetValue():
-                self.Element.SetType(CONTACT_NORMAL)
-            elif self.radioButton2.GetValue():
-                self.Element.SetType(CONTACT_REVERSE)
-            elif self.radioButton3.GetValue():
-                self.Element.SetType(CONTACT_RISING)
-            elif self.radioButton4.GetValue():
-                self.Element.SetType(CONTACT_FALLING)
-        elif self.Type == "coil":
-            if self.radioButton1.GetValue():
-                self.Element.SetType(COIL_NORMAL)
-            elif self.radioButton2.GetValue():
-                self.Element.SetType(COIL_REVERSE)
-            elif self.radioButton3.GetValue():
-                self.Element.SetType(COIL_SET)
-            elif self.radioButton4.GetValue():
-                self.Element.SetType(COIL_RESET)
-        self.RefreshPreview()
-        event.Skip()
-
-    def OnNameChanged(self, event):
-        self.Element.SetName(self.Name.GetStringSelection())
-        self.RefreshPreview()
-        event.Skip()
-
-    def RefreshPreview(self):
-        dc = wxClientDC(self.Preview)
-        dc.Clear()
-        self.Element.Draw(dc)
-
-    def OnPaint(self, event):
-        self.RefreshPreview()
-        event.Skip()